All files / src/plugins/validation/2and3/semantic-validators items-required-for-array-objects.js

100% Statements 15/15
100% Branches 14/14
100% Functions 2/2
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                    29x 29x 29x   29x 99x   99x     5211x 5211x   5211x             1051x 4x                 5211x 4x 1x                 99x    
// Assertation 1:
// The items property for Schema Objects, or schema-like objects (non-body parameters), is required when type is set to array
 
// Assertation 2:
// The required properties for a Schema Object must be defined in the object or one of its ancestors.
 
// Assertation 3
// (For Swagger 2 specs. In the OAS 3 spec, headers do not have types. Their schemas will be checked by Assertation 1):
// Headers with 'array' type require an 'items' property
 
const { walk } = require('../../../utils');
const MessageCarrier = require('../../../utils/messageCarrier');
const isPlainObject = require('lodash/isPlainObject');
 
module.exports.validate = function({ jsSpec }) {
  const messages = new MessageCarrier();
 
  walk(jsSpec, [], function(obj, path) {
    // `definitions` for Swagger 2, `schemas` for OAS 3
    // `properties` applies to both
    const modelLocations = ['definitions', 'schemas', 'properties'];
    const current = path[path.length - 1];
 
    if (
      current === 'schema' ||
      modelLocations.indexOf(path[path.length - 2]) > -1
    ) {
      // if parent is 'schema', or we're in a model definition
 
      // Assertation 1
      if (obj.type === 'array' && !isPlainObject(obj.items)) {
        messages.addMessage(
          path.join('.'),
          "Schema objects with 'array' type require an 'items' property",
          'error'
        );
      }
    }
 
    // this only applies to Swagger 2
    if (path[path.length - 2] === 'headers') {
      if (obj.type === 'array' && !isPlainObject(obj.items)) {
        messages.addMessage(
          path,
          "Headers with 'array' type require an 'items' property",
          'error'
        );
      }
    }
  });
 
  return messages;
};