Exemplo n.º 1
0
    def test_compose_schemas_cache_deserialize(self, mock_caches):
        attr1, attr2 = Attribute.objects.bulk_create(Attribute(
            id=i,
            schema_id=self.schema.id,
            name='testattr%s' % i,
            long_name='Test attribute%s' % i,
            index=i,
            attr_type_id=self.attr_type.id,
            required=bool(i % 2),
            default=i**i if not bool(i % 2) else '') for i in range(1, 3)
        )
        cache_value = (
            OrderedDict([
                ('testattr1', attr1.to_dict()),
                ('testattr2', attr2.to_dict())
            ]),
            {'testattr1'},
            {'testattr2'}
        )
        mock_cache = MagicMock(get=MagicMock(return_value=cache_value))
        mock_caches.__getitem__.return_value = mock_cache

        assert compose_schemas(self.schema) == (
            OrderedDict([
                ('testattr1', attr1),
                ('testattr2', attr2)
            ]),
            {'testattr1'},
            {'testattr2'}
        )
        assert not mock_cache.set.called
Exemplo n.º 2
0
 def create_model_fields(self, model, field_prefix, selectors, new_item=False):
     content_type = ContentType.objects.get_for_model(model)
     schemas = Schema.objects.lookup(content_type=content_type, selectors=selectors)
     attrs, _, _ = compose_schemas(*schemas)
     for name, attr in attrs.items():
         fieldname = field_prefix + "::" + name
         atype = attr.attr_type
         initial = self.data.get(fieldname, "")
         args = {"label": attr.long_name, "required": False, "initial": initial}
         field = form_field_from_name(atype.form_field)
         # if atype.form_field == 'CharField':
         #     args['max_length'] = 32
         if atype.form_field == "ChoiceField" or atype.form_field == "MultipleChoiceField":
             if attr.choice_labels is not None and attr.choice_labels != []:
                 chs = list(zip(attr.choices, attr.choice_labels))
             else:
                 chs = list(map(lambda c: (c, c), attr.choices))
             args["choices"] = chs
         if atype.form_field == "BooleanField":
             args["required"] = False
             if len(attr.default) > 0:
                 args["initial"] = attr.default != "False"
         else:
             if attr.required and new_item:
                 args["required"] = True
             if len(attr.default) > 0 and len(initial) == 0:
                 args["initial"] = attr.default
         self.fields[fieldname] = field(**args)
Exemplo n.º 3
0
 def create_model_fields(self,
                         model,
                         field_prefix,
                         selectors,
                         new_item=False):
     content_type = ContentType.objects.get_for_model(model)
     schemas = Schema.objects.lookup(content_type=content_type,
                                     selectors=selectors)
     attrs, _, _ = compose_schemas(*schemas)
     for name, attr in attrs.items():
         fieldname = field_prefix + '::' + name
         atype = attr.attr_type
         initial = self.data.get(fieldname, '')
         args = {
             'label': attr.long_name,
             'required': False,
             'initial': initial
         }
         field = form_field_from_name(atype.form_field)
         # if atype.form_field == 'CharField':
         #     args['max_length'] = 32
         if (atype.form_field == 'ChoiceField'
                 or atype.form_field == 'MultipleChoiceField'):
             args['choices'] = list(map(lambda c: (c, c), attr.choices))
         if atype.form_field == 'BooleanField':
             args['required'] = False
             if len(attr.default) > 0:
                 args['initial'] = (attr.default != 'False')
         else:
             if attr.required and new_item:
                 args['required'] = True
             if len(attr.default) > 0 and len(initial) == 0:
                 args['initial'] = attr.default
         self.fields[fieldname] = field(**args)
Exemplo n.º 4
0
    def get_attributes(self, project):
        content_type_to_selectors = self._get_content_types_to_selectors()

        attributes_for_models = {}
        for content_type, selector_fields in content_type_to_selectors.items():
            label = '{}.{}'.format(content_type.app_label, content_type.model)
            model = content_type.model_class()
            choices = []
            selectors = OrderedDict({})
            attributes_for_models[label] = OrderedDict({})

            for selector_field in selector_fields:
                field = model._meta.get_field(selector_field.partition('.')[0])
                if field.choices:
                    choices = [choice[0] for choice in field.choices]
                else:
                    selector = project
                    sf = selector_field.partition('.')[-1]
                    sf = sf.replace('.pk', '_id')
                    selector = getattr(selector, sf, None)
                    if selector:
                        selectors[sf] = selector

            if selectors and not choices:
                defaults = list(selectors.values())
                schemas = Schema.objects.lookup(content_type=content_type,
                                                selectors=defaults)
                if schemas:
                    attributes, _, _ = compose_schemas(*schemas)
                    attributes_for_models[label]['DEFAULT'] = attributes

            if selectors and choices:
                for choice in choices:
                    conditionals = list(selectors.values()) + [choice]
                    schemas = Schema.objects.lookup(content_type=content_type,
                                                    selectors=conditionals)
                    if schemas:
                        attributes, _, _ = compose_schemas(*schemas)
                        attributes_for_models[label][choice] = attributes

        return attributes_for_models
Exemplo n.º 5
0
    def get_attributes(self, project):
        content_type_to_selectors = self._get_content_types_to_selectors()
        attributes_for_models = {}
        for content_type, selector_fields in content_type_to_selectors.items():
            label = '{}.{}'.format(content_type.app_label, content_type.model)
            model = content_type.model_class()
            choices = []
            selectors = OrderedDict({})
            attributes_for_models[label] = OrderedDict({})

            for selector_field in selector_fields:
                field = model._meta.get_field(selector_field.partition('.')[0])
                if field.choices:
                    choices = [choice[0] for choice in field.choices]
                else:
                    selector = project
                    sf = selector_field.partition('.')[-1]
                    sf = sf.replace('.pk', '_id')
                    selector = getattr(selector, sf, None)
                    if selector:
                        selectors[sf] = selector

            if selectors and not choices:
                defaults = list(selectors.values())
                schemas = Schema.objects.lookup(
                    content_type=content_type, selectors=defaults)
                if schemas:
                    attributes, _, _ = compose_schemas(*schemas)
                    attributes_for_models[label]['DEFAULT'] = attributes

            if selectors and choices:
                for choice in choices:
                    conditionals = list(selectors.values()) + [choice]
                    schemas = Schema.objects.lookup(
                        content_type=content_type,
                        selectors=conditionals)
                    if schemas:
                        attributes, _, _ = compose_schemas(*schemas)
                        attributes_for_models[label][choice] = attributes

        return attributes_for_models
Exemplo n.º 6
0
    def test_compose_schemas_cache_deserialize(self, mock_caches):
        attr1, attr2 = Attribute.objects.bulk_create(
            Attribute(id=i,
                      schema_id=self.schema.id,
                      name='testattr%s' % i,
                      long_name='Test attribute%s' % i,
                      index=i,
                      attr_type_id=self.attr_type.id,
                      required=bool(i % 2),
                      default=i**i if not bool(i % 2) else '')
            for i in range(1, 3))
        cache_value = (OrderedDict([('testattr1', attr1.to_dict()),
                                    ('testattr2', attr2.to_dict())]),
                       {'testattr1'}, {'testattr2'})
        mock_cache = MagicMock(get=MagicMock(return_value=cache_value))
        mock_caches.__getitem__.return_value = mock_cache

        assert compose_schemas(self.schema) == (OrderedDict([
            ('testattr1', attr1), ('testattr2', attr2)
        ]), {'testattr1'}, {'testattr2'})
        assert not mock_cache.set.called
Exemplo n.º 7
0
    def test_compose_schemas_cache_serialize(self, mock_caches):
        mock_cache = MagicMock(get=MagicMock(return_value=None))
        mock_caches.__getitem__.return_value = mock_cache

        attr1, attr2 = Attribute.objects.bulk_create(
            Attribute(id=i,
                      schema_id=self.schema.id,
                      name='testattr%s' % i,
                      long_name='Test attribute%s' % i,
                      index=i,
                      attr_type_id=self.attr_type.id,
                      required=bool(i % 2),
                      default=i**i if not bool(i % 2) else '')
            for i in range(1, 3))
        attr1.refresh_from_db()
        attr2.refresh_from_db()

        assert compose_schemas(self.schema) == (OrderedDict([
            ('testattr1', attr1), ('testattr2', attr2)
        ]), {'testattr1'}, {'testattr2'})
        mock_cache.set.assert_called_once_with(
            'jsonattrs:compose:{}'.format(self.schema.id), (OrderedDict([
                ('testattr1', attr1.to_dict()), ('testattr2', attr2.to_dict())
            ]), {'testattr1'}, {'testattr2'}))
Exemplo n.º 8
0
    def test_compose_schemas_cache_serialize(self, mock_caches):
        mock_cache = MagicMock(get=MagicMock(return_value=None))
        mock_caches.__getitem__.return_value = mock_cache

        attr1, attr2 = Attribute.objects.bulk_create(Attribute(
            id=i,
            schema_id=self.schema.id,
            name='testattr%s' % i,
            long_name='Test attribute%s' % i,
            index=i,
            attr_type_id=self.attr_type.id,
            required=bool(i % 2),
            default=i**i if not bool(i % 2) else '') for i in range(1, 3)
        )
        attr1.refresh_from_db()
        attr2.refresh_from_db()

        assert compose_schemas(self.schema) == (
            OrderedDict([
                ('testattr1', attr1),
                ('testattr2', attr2)
            ]),
            {'testattr1'},
            {'testattr2'}
        )
        mock_cache.set.assert_called_once_with(
            'jsonattrs:compose:{}'.format(self.schema.id),
            (
                OrderedDict([
                    ('testattr1', attr1.to_dict()),
                    ('testattr2', attr2.to_dict())
                ]),
                {'testattr1'},
                {'testattr2'}
            )
        )