Example #1
0
def test_random():
    for i in xrange(1000):
        random_doc = doc.random_doc()
        pattern_sets = []
        for p, v in doc.doc_iter(random_doc):
            max_level = len(p)
            nr_sets = len(pattern_sets)
            level_diff = max_level - nr_sets + 1
            if max_level >= nr_sets:
                pattern_sets += [set() for _ in xrange(level_diff)]
            for level, segment in enumerate(p):
                pattern_sets[level].add(p[level])

        matched = doc.doc_match_levels(random_doc,
                                       pattern_sets,
                                       expand_pattern_levels=())
        matched_doc = {}
        for p in matched:
            doc.doc_set(matched_doc, p[:-1], p[-1])

        assert random_doc == matched_doc

        matched = doc.doc_match(random_doc,
                                random_doc,
                                callables,
                                expand_levels=(),
                                automerge=True)

        assert random_doc == matched_doc
Example #2
0
    def partial_validate(self, data, raise_exception=True, schema=None):
        """
        Validates data that are going to be sent for a partial update of a
        resource.

        Construct a cerberus schema validator by taking into consideration
        only the fields that are included in the request.

        :param raise_exception: True if an exception should be raised when
        validation fails.
        """
        schema = schema or self.validation_schema
        cerberus_paths = to_cerberus_paths(data)
        validated_subdocs = self._validate_subdata(data, schema,
                                                   raise_exception)
        partial_schema_paths = {
            path: doc.doc_get(schema, path.split('/'))
            for path in cerberus_paths
        }
        partial_schema = doc.doc_from_ns(partial_schema_paths)
        validator = ApimasValidator(partial_schema)
        is_valid = validator.validate(data)
        if raise_exception and not is_valid:
            raise ex.ApimasClientException(validator.errors)
        for k, v in validated_subdocs.iteritems():
            doc.doc_set(validator.document, k, v)
        return validator.document
Example #3
0
    def get_permissions(self, collection, top_spec):
        """
        It constructs permissions rules for every collection.

        Typically, permission rules are provided at a global scope. Then,
        this method, actually matches all permissions rules which are applied
        to a specific collection and then it returns all permissions that
        are compatible and apply on the collection.
        """
        permission_path = ('.endpoint', 'permissions')
        nu_columns = 6
        permission_doc = {}
        permissions = doc.doc_get(top_spec, permission_path) or []
        permissions = [[doc.parse_pattern(segment) for segment in row]
                       for row in permissions]
        for rule in permissions:
            doc.doc_set(permission_doc, rule[:-1], rule[-1])
        patterns = [[collection], [doc.ANY], [doc.ANY], [doc.ANY],
                    [doc.ANY]]
        matches = list(doc.doc_match_levels(
            permission_doc, patterns,
            expand_pattern_levels=range(nu_columns)))
        if not matches:
            return None
        return map((lambda x: x[1:]), matches)
Example #4
0
 def construct_identity_field(self, instance, spec, loc, context,
                              predicate_type):
     """ Construct an `.identity` field. """
     collection_name = loc[1]
     drf_field = self.SERILIZERS_TYPE_MAPPING[predicate_type[1:]](
         view_name='%s-detail' % (collection_name))
     doc.doc_set(instance, (self.ADAPTER_CONF, 'field'), drf_field)
     return instance
Example #5
0
    def __init__(self, column_names, rules=()):
        self.column_names = tuple(column_names)
        self.Row = namedtuple('TabmatchRow', self.column_names)
        self.rules_set = set(rules)
        self.rules_doc = {}
        for rule in rules:
            doc_set(self.rules_doc, rule[:-1], rule[-1])

        self.name_levels = {
            name: x
            for x, name in enumerate(self.column_names)
        }
Example #6
0
    def default_field_constructor(self, instance, spec, loc, context,
                                  predicate_type):
        """
        A common constructor for the drf fields.

        There are two cases:
        * If the field is a model field, then it does not initialize a
          `serializers.Field` object, but it stores all its properties in
          dictionary in order to be initialized later from the serializer.
        * If the field is a non-model field or its type is either `.struct`
          or `.structarry`, then the corresponding `serializers.Field` is
          contructed.

        Moreover, this method checks if the field conforms to the model
        configuations before being constructed.
        """
        model, automated = self.validate_model_configuration(
            instance, spec, loc, context, predicate_type)
        path = (self.ADAPTER_CONF,)
        instance_source = spec.pop('instance_source', None)
        onmodel = spec.get('onmodel', True)
        if instance_source and onmodel:
            raise utils.DRFAdapterException(
                'You don\'t have to specify `instance_source` if'
                ' `onmodel` is set')
        field_kwargs = {k: v for k, v in spec.iteritems() if k != 'onmodel'}
        field_kwargs.update(doc.doc_get(instance, path) or {})
        if predicate_type == '.ref':
            field_kwargs.update(self._get_ref_params(
                instance, loc, context.get('top_spec'), onmodel and automated,
                field_kwargs))
        doc.doc_set(instance, (self.ADAPTER_CONF, 'source'), instance_source)
        drf_field = self._generate_field(
            instance, context.get('parent_name'), predicate_type, model,
            automated and onmodel, **field_kwargs)
        doc.doc_set(instance, (self.ADAPTER_CONF, 'field'), drf_field)
        return instance
Example #7
0
def ns_to_doc_patterns(ns):
    docout = {}
    for key, value in ns.iteritems():
        doc.doc_set(docout, key, value)
    return docout
Example #8
0
 def update(self, rows):
     for row in rows:
         self._check_row_type(row)
         self.rules_set.add(row)
         doc_set(self.rules_doc, row[:-1], row[-1])