Validate DjangoQL AST tree vs. current schema
167101
def validate(self, node):
        
        assert isinstance(node, Node)
        if isinstance(node.operator, Logical):
            self.validate(node.left)
            self.validate(node.right)
            return
        assert isinstance(node.left, Name)
        assert isinstance(node.operator, Comparison)
        assert isinstance(node.right, (Const, List))

        # Check that field and value types are compatible
        field = self.resolve_name(node.left)
        value = node.right.value
        if field is None:
            if value is not None:
                raise DjangoQLSchemaError(
                    'Related model %s can be compared to None only, but not to '
                    '%s' % (node.left.value, type(value).__name__)
                )
        else:
            values = value if isinstance(node.right, List) else [value]
            for v in values:
                field.validate(v)
1373024
def validate(data, schema, defined_keys=False):
    
    if isinstance(data, dict):
        validator = Validator(data, schema, defined_keys=defined_keys)
        validator.validate()
    else:
        raise TypeError('expected data to be of type dict, but got: %s' % type(data))
653669
def graphql_impl(
    schema,
    source,
    root_value,
    context_value,
    variable_values,
    operation_name,
    field_resolver,
    type_resolver,
    middleware,
    execution_context_class,
) -> AwaitableOrValue[ExecutionResult]:
    """"""
    # Validate Schema
    schema_validation_errors = validate_schema(schema)
    if schema_validation_errors:
        return ExecutionResult(data=None, errors=schema_validation_errors)

    # Parse
    try:
        document = parse(source)
    except GraphQLError as error:
        return ExecutionResult(data=None, errors=[error])
    except Exception as error:
        error = GraphQLError(str(error), original_error=error)
        return ExecutionResult(data=None, errors=[error])

    # Validate
    from .validation import validate

    validation_errors = validate(schema, document)
    if validation_errors:
        return ExecutionResult(data=None, errors=validation_errors)

    # Execute
    return execute(
        schema,
        document,
        root_value,
        context_value,
        variable_values,
        operation_name,
        field_resolver,
        type_resolver,
        middleware,
        execution_context_class,
    )
940378
def apply_search(queryset, search, schema=None):
    
    ast = DjangoQLParser().parse(search)
    schema = schema or DjangoQLSchema
    schema_instance = schema(queryset.model)
    schema_instance.validate(ast)
    return queryset.filter(build_filter(ast, schema_instance))
305692
def _validate(data_type, parent_path):
    """"""
    if isinstance(data_type, _CLASS_TYPES):
        raise TypeError(
            "The data type is expected to be an instance object, but got the "
            "type '%s' instead." % (_format_type(data_type),))

    base = _find_base_type(data_type)
    if not base:
        raise TypeError(
            "Objects of type '%s' aren't supported as data types. Use any "
            "type from %s instead."
            % (_format_type(type(data_type)), _join_types(_ALL, "or ")))

    name = getattr(data_type, 'name', None)
    if not name:
        name = type(data_type).__name__

    full_path = '%s.%s' % (parent_path, name) if parent_path else name

    # Generic checks for each attribute.
    for check in _TYPE_ATTR_CHECKS[base]:
        attribute = getattr(data_type, check.name)
        if attribute is None:
            if check.allow_none:
                continue
            else:
                raise TypeError("The attribute '%s.%s' cannot be 'None'."
                                % (full_path, check.name))

        if isinstance(check, _FieldInstanceCheck):
            check_function = isinstance
        elif isinstance(check, _FieldSubclassCheck):
            if not isinstance(attribute, _CLASS_TYPES):
                raise TypeError(
                    "The attribute '%s.%s' is expected to be a type "
                    "object%s." % (full_path, check.name,
                                   " or 'None'" if check.allow_none else ''))

            check_function = issubclass

        if not check_function(attribute, check.type):
            if isinstance(check, _FieldInstanceCheck):
                glue_1 = "an instance object of type"
                glue_2 = "not"
                glue_3 = ""
                type_name = _format_type(type(attribute))
            elif isinstance(check, _FieldSubclassCheck):
                glue_1 = "a subclass of"
                glue_2 = "but got"
                glue_3 = " instead"
                type_name = _format_type(attribute)

            raise TypeError(
                "The attribute '%s.%s' is expected to be %s %s, %s '%s'%s."
                % (full_path, check.name, glue_1,
                   _join_types(check.type, "or "), glue_2, type_name, glue_3))

    # Additional and/or recursive checks for specific attributes.
    if isinstance(data_type, Array):
        _validate(data_type.element_type, full_path)
    elif isinstance(data_type, Structure):
        for field in data_type.fields:
            if not isinstance(field, _SEQUENCE_TYPES):
                raise TypeError(
                    "Each field from the attribute '%s.fields' is expected "
                    "to be an instance object of type %s, not '%s'."
                    % (full_path,
                       _join_types(_SEQUENCE_TYPES + (Field,), "or "),
                       _format_type(type(field))))

            if len(field) not in _FIELD_REQUIRED_ARG_RANGE:
                raise TypeError(
                    "Each field from the attribute '%s.fields' is expected "
                    "to be an instance object of type %s, and compatible with "
                    "the '%s' structure, but got %r instead."
                    % (full_path,
                       _join_types(_SEQUENCE_TYPES + (Field,), "or "),
                       _format_type(Field), field))

            field = Field(*field)
            if not isinstance(field.name, _STRING_TYPES):
                raise TypeError(
                    "The first element of each field from the attribute "
                    "'%s.fields', that is the 'name' attribute, is expected "
                    "to be an instance object of type %s, not '%s'."
                    % (full_path, _join_types(_STRING_TYPES, "or "),
                       _format_type(type(field.name))))

            if not isinstance(field.type, _ALL):
                raise TypeError(
                    "The second element of each field from the attribute "
                    "'%s.fields', that is the 'type' attribute, is expected "
                    "to be an instance object of type %s, not '%s'."
                    % (full_path, _join_types(_ALL, "or "),
                       _format_type(type(field.type))))

            if not isinstance(field.read_only, bool):
                raise TypeError(
                    "The third element of each field from the attribute "
                    "'%s.fields', that is the 'read_only' attribute, is "
                    "expected to be an instance object of type 'bool', "
                    "not '%s'." % (full_path,
                                   _format_type(type(field.read_only))))

            field_path = '%s.%s' % (full_path, field.name)
            _validate(field.type, field_path)

        fields = [field[_FIELD_NAME_IDX] for field in data_type.fields]
        duplicates = _find_duplicates(fields)
        if duplicates:
            if len(duplicates) > 1:
                raise ValueError(
                    "The structure fields %s, were provided multiple times."
                    % (_join_sequence(duplicates, "and ")),)
            else:
                raise ValueError(
                    "The structure field '%s' was provided multiple times."
                    % (duplicates[0]),)

    return True
969359
def validate(cls, data):
        """"""
        try:
            jsonschema.validate(
                data, cls.SCHEMA,
                # See: https://github.com/Julian/jsonschema/issues/148
                types={'array': (list, tuple)})
        except jsonschema.ValidationError as e:
            raise InvalidFormat("Failure data not of the"
                                " expected format: %s" % (e.message))
        else:
            # Ensure that all 'exc_type_names' originate from one of
            # base exceptions, because those are the root exceptions that
            # python mandates/provides and anything else is invalid...
            causes = collections.deque([data])
            while causes:
                cause = causes.popleft()
                try:
                    generated_on = cause['generated_on']
                    ok_bases = cls.BASE_EXCEPTIONS[generated_on[0]]
                except (KeyError, IndexError):
                    ok_bases = []
                root_exc_type = cause['exc_type_names'][-1]
                if root_exc_type not in ok_bases:
                    raise InvalidFormat(
                        "Failure data 'exc_type_names' must"
                        " have an initial exception type that is one"
                        " of %s types: '%s' is not one of those"
                        " types" % (ok_bases, root_exc_type))
                sub_cause = cause.get('cause')
                if sub_cause is not None:
                    causes.append(sub_cause)
355311
def is_valid(self, instance):
        ''''''
        dbdata = instance.dbdata
        data = dbdata['cleaned_data'] = {}
        errors = dbdata['errors'] = {}
        #Loop over scalar fields first
        for field, value in instance.fieldvalue_pairs():
            name = field.attname
            try:
                svalue = field.set_get_value(instance, value)
            except Exception as e:
                errors[name] = str(e)
            else:
                if (svalue is None or svalue is '') and field.required:
                    errors[name] = ("Field '{0}' is required for '{1}'."
                                    .format(name, self))
                else:
                    if isinstance(svalue, dict):
                        data.update(svalue)
                    elif svalue is not None:
                        data[name] = svalue
        return len(errors) == 0
653169
def validate(schema, data, owner=None):
    
    schema._validate(data=data, owner=owner)
1208981
def validate_sdl(
    document_ast: DocumentNode,
    schema_to_extend: GraphQLSchema = None,
    rules: Sequence[RuleType] = None,
) -> List[GraphQLError]:
    """"""
    context = SDLValidationContext(document_ast, schema_to_extend)
    if rules is None:
        rules = specified_sdl_rules
    visitors = [rule(context) for rule in rules]
    visit(document_ast, ParallelVisitor(visitors))
    return context.errors
569873
def validate_schema(sconf):
    

    # verify session_name
    if 'session_name' not in sconf:
        raise exc.ConfigError('config requires "session_name"')

    if 'windows' not in sconf:
        raise exc.ConfigError('config requires list of "windows"')

    for window in sconf['windows']:
        if 'window_name' not in window:
            raise exc.ConfigError('config window is missing "window_name"')

        if 'panes' not in window:
            raise exc.ConfigError(
                'config window %s requires list of panes' % window['window_name']
            )

    return True
1214725
function validateSchema(schema, throwOrLogError) {
  var $schema = schema.$schema;
  if ($schema !== undefined && typeof $schema != 'string')
    throw new Error('$schema must be a string');
  $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
  if (!$schema) {
    this.logger.warn('meta-schema not available');
    this.errors = null;
    return true;
  }
  var valid = this.validate($schema, schema);
  if (!valid && throwOrLogError) {
    var message = 'schema is invalid: ' + this.errorsText();
    if (this._opts.validateSchema == 'log') this.logger.error(message);
    else throw new Error(message);
  }
  return valid;
}
1248400
def _try_validate(cnf, schema, **options):
    
    valid = True
    if schema:
        (valid, msg) = validate(cnf, schema, **options)
        if msg:
            LOGGER.warning(msg)

    if valid:
        return cnf

    return None
867922
def validate(request: Union[Dict, List], schema: dict) -> Union[Dict, List]:
    
    jsonschema_validate(request, schema)
    return request
109591
def validate(self, schema_str, xml_valid):
        
        # TODO: be able to get doc for error given an xsd.
        # Changed path to allow have xsd that are imported by others xsd in the
        # same library, and not call to SAT page each time that is generated
        # a new XML.
        with change_path():
            path = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'templates')
            os.chdir(path)
            schema_root = etree.parse(StringIO(schema_str))
            schema = etree.XMLSchema(schema_root)
        try:
            tree = etree.parse(StringIO(xml_valid.encode('UTF-8')))
            schema.assertValid(tree)
        except etree.DocumentInvalid as ups:
            self.ups = ups
        finally:
            if self.ups:
                self.valid = False
            else:
                self.valid = True
            return self.valid
1155105
def get_field_schema_validations(field: Field) -> Dict[str, Any]:
    
    f_schema: Dict[str, Any] = {}
    if lenient_issubclass(field.type_, (str, bytes)):
        for attr_name, t, keyword in _str_types_attrs:
            attr = getattr(field.schema, attr_name, None)
            if isinstance(attr, t):
                f_schema[keyword] = attr
    if lenient_issubclass(field.type_, numeric_types) and not issubclass(field.type_, bool):
        for attr_name, t, keyword in _numeric_types_attrs:
            attr = getattr(field.schema, attr_name, None)
            if isinstance(attr, t):
                f_schema[keyword] = attr
    schema = cast('Schema', field.schema)
    if schema.extra:
        f_schema.update(schema.extra)
    return f_schema
1254939
def valid(self, instance, schema):
        """"""
        try:
            jsonschema.validate(instance, schema)
        except jsonschema.exceptions.ValidationError as ex:
            self.stderr.write("    VALIDATION ERROR: {}".format(instance['name'] if 'name' in instance else ''))
            self.stderr.write("        path:       {}".format(ex.path))
            self.stderr.write("        message:    {}".format(ex.message))
            self.stderr.write("        validator:  {}".format(ex.validator))
            self.stderr.write("        val. value: {}".format(ex.validator_value))
            return False

        try:
            # Check that default values fit field schema.
            for field in ['input', 'output', 'schema']:
                for schema, _, path in iterate_schema({}, instance.get(field, {})):
                    if 'default' in schema:
                        validate_schema({schema['name']: schema['default']}, [schema])
        except ValidationError:
            self.stderr.write("    VALIDATION ERROR: {}".format(instance['name']))
            self.stderr.write("        Default value of field '{}' is not valid.". format(path))
            return False

        return True
150117
def _validate(self, inst: "InstanceNode", scope: ValidationScope,
                  ctype: ContentType) -> None:
        """"""
        if scope.value & ValidationScope.syntax.value:   # schema
            self._check_schema_pattern(inst, ctype)
        for m in inst:
            inst._member(m).validate(scope, ctype)
        super()._validate(inst, scope, ctype)