Assert that mapping.keys() == FIELDS.

        The programmer is not supposed to pass extra/less number of fields
179222
def __assert_field_mapping(self, mapping):
        
        passed_keys = set(mapping.keys())
        class_fields = set(self.FIELDS)

        if passed_keys != class_fields:
            raise ValueError('\n'.join([
                "{0} got different fields from expected".format(
                    self.__class__),
                "  got     : {0}".format(list(sorted(passed_keys))),
                "  expected: {0}".format(list(sorted(class_fields)))]))
278797
function checkUnknown(json, schemaKeys) {
    var jsonKeys = [];
    for (var k in json) {
      if (schemaKeys.indexOf(k) === -1) {
        throw new ValidationException(
          "The key: " +
            k +
            " is not declared in the schema. Declare it or allow unknown keys."
        );
      }
    }
  }
940813
def _check(self):
        
        for k,ix in six.iteritems(self._indices):
            assert k is not None, 'null key'
            assert ix, 'Key does not map to any indices'
            assert ix == sorted(ix), "Key's indices are not in order"
            for i in ix:
                assert i in self._lines, 'Key index does not map to line'
                assert self._lines[i].key is not None, 'Key maps to comment'
                assert self._lines[i].key == k, 'Key does not map to itself'
                assert self._lines[i].value is not None, 'Key has null value'
        prev = None
        for i, line in six.iteritems(self._lines):
            assert prev is None or prev < i, 'Line indices out of order'
            prev = i
            if line.key is None:
                assert line.value is None, 'Comment/blank has value'
                assert line.source is not None, 'Comment source not stored'
                assert loads(line.source) == {}, 'Comment source is not comment'
            else:
                assert line.value is not None, 'Key has null value'
                if line.source is not None:
                    assert loads(line.source) == {line.key: line.value}, \
                        'Key source does not deserialize to itself'
                assert line.key in self._indices, 'Key is missing from map'
                assert i in self._indices[line.key], \
                    'Key does not map to itself'
1338446
def _compile_mapping(self, schema):
        
        assert not self.matcher, 'Mappings cannot be matchers'

        # This stuff is tricky, but thankfully, I like comments :)

        # Set default Marker on all keys.
        # This makes sure that all keys will still become markers, and hence have the correct default behavior
        schema = {self.default_keys(k) if self.get_schema_type(k) != const.COMPILED_TYPE.MARKER else k: v
                  for k, v in schema.items()}

        # Add `Extra`
        # Every Schema implicitly has an `Extra` that defaults to `extra_keys`.
        # Note that this is the only place in the code where Marker behavior is hardcoded :)
        schema.setdefault(markers.Extra, self.extra_keys)

        # Compile both keys & values as schemas.
        # Key schemas are compiled as "Matchers" for performance.
        compiled = {self.sub_compile(key, matcher=True): self.sub_compile(value)
                    for key, value in schema.items()}

        # Notify Markers that they were compiled.
        # _compile_marker() has already done part of the job: it only specified `key_schema`.
        # Here we let the Marker know its `value_schema` as well.
        for key_schema, value_schema in compiled.items():
            if key_schema.compiled_type == const.COMPILED_TYPE.MARKER:
                key_schema.compiled.on_compiled(value_schema=value_schema, as_mapping_key=True)

        # Sort key schemas for matching.

        # Since various schema types have different priority, we need to sort these accordingly.
        # Then, literals match before types, and Markers can define execution order using `priority`.
        # For instance, Remove() should be called first (before any validation takes place),
        # while Extra() should be checked last so it catches all extra keys that did not match other key schemas.

        # In addition, since mapping keys are mostly literals, we want direct matching instead of the costly function calls.
        # Hence, remember which of them are literals or 'catch-all' markers.
        is_literal  = lambda key_schema: key_schema.compiled.key_schema.compiled_type == const.COMPILED_TYPE.LITERAL
        is_identity = lambda identity: key_schema.compiled.key_schema is Identity

        compiled = [ (key_schema, compiled[key_schema], is_literal(key_schema), is_identity(key_schema))
                     for key_schema in self.sort_schemas(compiled.keys())]
        ''' :var  compiled: Sorted list of CompiledSchemas: (key-schema, value-schema, is-literal),
            :type compiled: list[CompiledSchema, CompiledSchema, bool]
        '''

        # Prepare self
        self.compiled_type = const.COMPILED_TYPE.MAPPING
        self.name = _(u'{mapping_cls}[{mapping_keys}]').format(
            mapping_cls=get_type_name(type(schema)),
            mapping_keys=_(u',').join(key_schema.name for key_schema, value_schema, is_literal, is_identity in compiled)
        )

        # Error partials
        schema_type = type(schema)
        err_type = self.Invalid(_(u'Wrong value type'), get_type_name(schema_type))

        # Validator
        def validate_mapping(d):
            # Type check
            if not isinstance(d, schema_type):
                # expected=<type>, provided=<type>
                raise err_type(provided=get_type_name(type(d)))

            # For each schema key, pick matching input key-value pairs.
            # Since we always have Extra which is a catch-all -- this will always result into a full input coverage.
            # Also, key schemas are sorted according to the priority, we're handling each set of matching keys in order.

            errors = []  # Collect errors on the fly
            d_keys = set(d.keys())  # Make a copy of dict keys for destructive iteration

            for key_schema, value_schema, is_literal, is_identity in compiled:
                # First, collect matching (key, value) pairs for the `key_schema`.
                # Note that `key_schema` can change the value (e.g. `Coerce(int)`), so for every key
                # we store both the initial value (`input-key`) and the sanitized value (`sanitized-key`).
                # This results into a list of triples: [(input-key, sanitized-key, input-value), ...].

                matches = []

                if is_literal:  # (short-circuit for literals)
                    # Since mapping keys are mostly literals --
                    # save some iterations & function calls in favor of direct matching,
                    # which introduces a HUGE performance improvement
                    k = key_schema.schema.key  # get the literal from the marker
                    if k in d_keys:
                        # (See comments below)
                        matches.append(( k, k, d[k] ))
                        d_keys.remove(k)
                elif is_identity:  # (short-circuit for Marker(Identity))
                    # When this value is an identity function -- we plainly add all keys to it.
                    # This is to short-circuit catch-all markers like `Extra`, which, being executed last,
                    # just gets all remaining keys.
                    matches.extend((k, k, d[k]) for k in d_keys)
                    d_keys = None  # empty it since we've processed everything
                elif d_keys:
                    # For non-literal schemas we have to walk all input keys
                    # and detect those that match the current `key_schema`.
                    # In contrast to literals, such keys may have multiple matches (e.g. `{ int: 1 }`).

                    # Note that this condition branch includes the logic from the short-circuited logic implemented above,
                    # but is less performant.

                    for k in tuple(d_keys):
                        # Exec key schema on the input key.
                        # Since all key schemas are compiled as matchers -- we get a tuple (key-matched, sanitized-key)

                        okay, sanitized_k = key_schema(k)

                        # If this key has matched -- append it to the list of matches for the current `key_schema`.
                        # Also, remove the key from the original input so it does not match any other key schemas
                        # with lower priorities.
                        if okay:
                            matches.append(( k, sanitized_k, d[k] ))
                            d_keys.remove(k)

                # Now, having a `key_schema` and a list of matches for it, do validation.
                # If the key is a marker -- execute the marker first so it has a chance to modify the input,
                # and then proceed with value validation.

                # Execute Marker first.
                if key_schema.compiled_type == const.COMPILED_TYPE.MARKER:
                    # Note that Markers can raise errors as well.
                    # Since they're compiled - all marker errors are raised as `Invalid`.
                    try:
                        matches = key_schema.compiled.execute(d, matches)
                    except Invalid as e:
                        # Add marker errors to the list of Invalid reports for this schema.
                        # Using enrich(), we're also setting `path` prefix, and other info known at this step.
                        errors.append(e.enrich(
                            # Markers are responsible to set `expected`, `provided`, `validator`
                            expected=key_schema.name,
                            provided=None,  # Marker's required to set that
                            path=self.path,
                            validator=key_schema.compiled
                        ))
                        # If a marker raised an error -- the (key, value) pair is already Invalid, and no
                        # further validation is required.
                        continue

                # Proceed with validation.
                # Now, we validate values for every (key, value) pairs in the current list of matches,
                # and rebuild the mapping.
                for k, sanitized_k, v in matches:
                    try:
                        # Execute the value schema and store it into the rebuilt mapping
                        # using the sanitized key, which might be different from the original key.
                        d[sanitized_k] = value_schema(v)

                        # Remove the original key in case `key_schema` has transformed it.
                        if k != sanitized_k:
                            del d[k]
                    except signals.RemoveValue:
                        # `value_schema` commanded to drop this value
                        del d[k]
                    except Invalid as e:
                        # Any value validation errors are appended to the list of Invalid reports for the schema
                        # enrich() adds more info on the collected errors.
                        errors.append(e.enrich(
                            expected=value_schema.name,
                            provided=get_literal_name(v),
                            path=self.path + [k],
                            validator=value_schema
                        ))

            assert not d_keys, 'Keys must be empty after destructive iteration. Remainder: {!r}'.format(d_keys)

            # Errors?
            if errors:
                # Note that we did not care about whether a sub-schema raised a single Invalid or MultipleInvalid,
                # since MultipleInvalid will flatten the list for us.
                raise MultipleInvalid.if_multiple(errors)

            # Finish
            return d

        return validate_mapping
423036
def simple?
      return false if keys.size > SimpleQueryMaxSize
      key_set = keys.to_set
      key_set == SimpleIdQueryKeys || key_set == SimpleIdAndTypeQueryKeys
    end
434083
function(mapping, keys) {
  assert(keys instanceof Array, 'keys must be an array');
  assert(keys.length > 0, 'CompositeKey needs at least one key');

  // Set keys
  this.keys = keys;

  // Set key types
  this.types = [];
  for (var i = 0; i < keys.length; i++) {
    assert(mapping[keys[i]], 'key \'' + keys[i] + '\' is not defined in mapping');
    this.types[i] = mapping[keys[i]];
  }

  // Set covers
  this.covers = keys;
}
601640
function hexists(key, field, req) {
  var val = this.getKey(key, req);
  if(!val) return 0;
  return val.keyExists(field);
}
540718
private boolean isValidKey(Object key) {
        if (key == null)
            return false;

        // Cheaper than instanceof Enum followed by getDeclaringClass
        Class<?> keyClass = key.getClass();
        return keyClass == keyType || keyClass.getSuperclass() == keyType;
    }
1230127
private static boolean writeIfNotEmpty(OutputAccessor out, boolean hasFields, String field, Object value) {

        if (value == null) {
            return hasFields;
        }

        if (value instanceof String) {

            if (GelfMessage.isEmpty((String) value)) {
                return hasFields;
            }

            if (hasFields) {
                writeKeyValueSeparator(out);
            }

            writeMapEntry(out, field, value);

            return true;
        }

        if (hasFields) {
            writeKeyValueSeparator(out);
        }

        writeMapEntry(out, field, value);

        return true;
    }
179473
function validateKey(key, flags, version) {
  assert(Buffer.isBuffer(key));
  assert(typeof flags === 'number');
  assert(typeof version === 'number');

  if (flags & Script.flags.VERIFY_STRICTENC) {
    if (!common.isKeyEncoding(key))
      throw new ScriptError('PUBKEYTYPE');
  }

  if (version === 1) {
    if (flags & Script.flags.VERIFY_WITNESS_PUBKEYTYPE) {
      if (!common.isCompressedEncoding(key))
        throw new ScriptError('WITNESS_PUBKEYTYPE');
    }
  }

  return true;
}
820743
private void assertPropertyIsIndexed(final PropertyKey key) {

		if (key != null && !key.isIndexed() && key instanceof AbstractPrimitiveProperty) {

			final Class declaringClass = key.getDeclaringClass();
			String className           = "";

			if (declaringClass != null) {

				className = declaringClass.getSimpleName() + ".";
			}

			logger.warn("Non-indexed property key {}{} is used in query. This can lead to performance problems in large databases.", className, key.jsonName());
		}
	}
303046
public static <T> T withFields(Class<T> clazz, Object... keysAndValues) {
        return Mockito.mock(clazz, new FakerAnswer(keysAndValues));
    }
861617
protected static void validateParamsPresence(Map params, String... keys) {
        for (String name : keys) {
            if (!params.containsKey(name)) {
                throw new IllegalArgumentException("parameter: '" + name + "' is missing");
            }
        }
    }
1159665
public static boolean serializeField(String keyName, Field field, Method getter) {
        log.trace("serializeField - keyName: {} field: {} method: {}", new Object[] { keyName, field, getter });
        // if "field" is a class or is transient, skip it
        if ("class".equals(keyName)) {
            return false;
        }
        if (field != null) {
            if (Modifier.isTransient(field.getModifiers())) {
                log.trace("Skipping {} because its transient", keyName);
                return false;
            } else if (field.isAnnotationPresent(DontSerialize.class)) {
                log.trace("Skipping {} because its marked with @DontSerialize", keyName);
                return false;
            }
        }
        if (getter != null && getter.isAnnotationPresent(DontSerialize.class)) {
            log.trace("Skipping {} because its marked with @DontSerialize", keyName);
            return false;
        }
        log.trace("Serialize field: {}", field);
        return true;
    }
1111087
function validate(key, values) {
  if(this.arity > 0 && values.length !== this.arity) {
    throw new TypeDefError(
      util.format('bad arity for \'%s\', expected %s got %s',
        key, this.arity, values.length));
  }
  var types = Array.isArray(this.type) ? this.type : [this.type]
    , i
    , type
    , val
    , num
    , coerced = []
    , enumerable = false;

  for(i = 0;i < types.length;i++) {
    type = types[i];
    val = values[i];
    enumerable = Array.isArray(type);
    if(enumerable) {
      if(!~type.indexOf(val)) {
        throw new TypeDefError(
          util.format('enum error on key \'%s\', got \'%s\' expected one of %s',
            key, val, type.join(', ')));
      }
    }
    switch(type) {
      case ByteSize:
        val = ByteSize.parse(val);
        break;
      case Boolean:
        if(val !== YES && val !== NO) {
          throw new Error(
            util.format('argument must be \'%s\' or \'%s\'', YES, NO));
        }
        val = val === YES ? true : false;
        break;
      case String:
        // strings can be quoted
        val = val.replace(/^"/, '').replace(/"$/, '');
        break;
      case Number:
        num = parseInt(val);
        if(isNaN(num) || !/^-?[0-9]+$/.test(val)) {
          throw new TypeDefError(
            util.format('number expected for \'%s\', got %s', key, val));
        }
        val = num;
        break;
    }

    coerced[i] = val;
  }
  if(this.arity === 1 && !this.repeats) return coerced[0];
  return Array.isArray(this.type) ? coerced : coerced[0];
}
1191248
void validateFields(Iterable<Field> fields, List<Reserved> reserveds) {
    Multimap<Integer, Field> tagToField = LinkedHashMultimap.create();
    Multimap<String, Field> nameToField = LinkedHashMultimap.create();
    for (Field field : fields) {
      int tag = field.tag();
      if (!Util.isValidTag(tag)) {
        withContext(field).addError("tag is out of range: %s", tag);
      }

      for (Reserved reserved : reserveds) {
        if (reserved.matchesTag(tag)) {
          withContext(field).addError("tag %s is reserved (%s)", tag, reserved.getLocation());
        }
        if (reserved.matchesName(field.name())) {
          withContext(field).addError("name '%s' is reserved (%s)", field.name(),
              reserved.getLocation());
        }
      }

      tagToField.put(tag, field);
      nameToField.put(field.qualifiedName(), field);
    }

    for (Map.Entry<Integer, Collection<Field>> entry : tagToField.asMap().entrySet()) {
      if (entry.getValue().size() > 1) {
        StringBuilder error = new StringBuilder();
        error.append(String.format("multiple fields share tag %s:", entry.getKey()));
        int index = 1;
        for (Field field : entry.getValue()) {
          error.append(String.format("\n  %s. %s (%s)",
              index++, field.name(), field.location()));
        }
        addError("%s", error);
      }
    }

    for (Collection<Field> collidingFields : nameToField.asMap().values()) {
      if (collidingFields.size() > 1) {
        Field first = collidingFields.iterator().next();
        StringBuilder error = new StringBuilder();
        error.append(String.format("multiple fields share name %s:", first.name()));
        int index = 1;
        for (Field field : collidingFields) {
          error.append(String.format("\n  %s. %s (%s)",
              index++, field.name(), field.location()));
        }
        addError("%s", error);
      }
    }
  }
1025718
public static void validateAllNotEmpty(Props props, String... keys) {
    for (String key : keys) {
      props.getString(key);
    }
  }