Esempio n. 1
0
 class Meta:
     model = Cart
     total = Field(source='total')
     total_cart_products = Field(source='total_cart_products')
     fields = [
         'id', 'user', 'products', 'used', 'total', 'total_cart_products'
     ]
    def setUp(self):
        self.required_field = Field()
        self.required_field.label = uuid4().hex
        self.required_field.required = True

        self.optional_field = Field()
        self.optional_field.label = uuid4().hex
        self.optional_field.required = False
Esempio n. 3
0
    def setUp(self):
        self.required_field = Field()
        self.required_field.label = uuid4().hex
        self.required_field.required = True

        self.optional_field = Field()
        self.optional_field.label = uuid4().hex
        self.optional_field.required = False
Esempio n. 4
0
class InvoiceSerializer(HyperlinkedModelSerializer):
	grand_total = Field(source='_get_grand_total')
	taxable_total = Field(source='_get_taxable_total')
	total_tax = Field(source='_get_total_tax')
	sub_total = Field(source='_get_sub_total')
	lineitems = HyperlinkedRelatedField(read_only=True, many=True, view_name='lineitem-detail')

	class Meta:
		model = Invoice
		read_only_fields = ('first_name','last_name','street1','street2','state','zip_code','phone','email')
Esempio n. 5
0
class LocationSerializer(serializers.HyperlinkedModelSerializer):
    latLng = Field(source='get_as_latLng')
    name = Field(source='title')
    id = serializers.Field()

    class Meta:
        model = Location
        fields = (
            'id',
            'name',
            'latLng',
        )
Esempio n. 6
0
class TopicSerializer(RelatedTopicSerializerMixin, ProjectSpecificItemMixin,
                      serializers.ModelSerializer):
    topic_node_id = Field(source='topic_node.id')
    type = Field(source='topic_node.type')
    alternate_names = AlternateNameField(slug_field='name', many=True)
    url = URLField(lookup_arg_attrs=('project.slug', 'topic_node_id'))
    project = ProjectSlugField()
    related_topics = TopicAssignmentField()
    citations = CitationSerializer(source='summary_cites',
                                   many=True,
                                   read_only=True)

    class Meta:
        model = Topic
        fields = ('id', 'topic_node_id', 'preferred_name', 'type', 'url',
                  'alternate_names', 'related_topics', 'project',
                  'last_updated', 'summary', 'citations')

    def save_object(self, obj, **kwargs):
        if not obj.id:
            topic_node_id = self.context.get('topic_node_id', None)
            if topic_node_id is None and 'view' in self.context:
                topic_node_id = self.context['view'].kwargs.get(
                    'topic_node_id', None)
            if topic_node_id is None:
                topic_node = TopicNode.objects.create(
                    _preferred_name=obj.preferred_name,
                    creator_id=obj.creator_id,
                    last_updater_id=obj.creator_id)
                topic_node_id = topic_node.id
            obj.topic_node_id = topic_node_id
        alternate_names = obj._related_data.pop('alternate_names')
        super(TopicSerializer, self).save_object(obj, **kwargs)
        self.save_alternate_names(obj, alternate_names)

    def save_alternate_names(self, obj, alternate_names):
        to_create = set(alternate_names)
        to_delete = []

        queryset = self.fields['alternate_names'].queryset or []
        for alternate_name_obj in queryset:
            name = alternate_name_obj.name
            if name in alternate_names:
                to_create.remove(name)
            else:
                to_delete.append(alternate_name_obj)

        for alternate_name_obj in to_delete:
            alternate_name_obj.delete()

        user = self.context['request'].user
        for name in to_create:
            obj.alternate_names.create(name=name, creator_id=user.id)
Esempio n. 7
0
 class Meta:
     model = Cart
     get_total = Field(source="get_total")
     get_tax_total = Field(source="get_tax_total")
     get_cart_total = Field(source="get_cart_total")
     fields = [
         "id",
         "user",
         "products",
         "get_total",
         "get_tax_total",
         "get_cart_total",
     ]
Esempio n. 8
0
 class Meta:
     model = Order
     get_cart_total = Field(source="get_cart_total")
     get_tax_total = Field(source="get_tax_total")
     get_total = Field(source="get_total")
     fields = [
         "id",
         "create_date",
         "shipping",
         "get_cart_total",
         "get_tax_total",
         "get_total",
     ]
class MessageSerializer(UUIDFieldSerializerMixin, serializers.ModelSerializer):
    chat__uuid = Field(source='chat.uuid')
    user_from__username = Field(source='user_from.username')

    class Meta:
        model = Message
        fields = (
            'uuid',
            'timestamp',
            'chat__uuid',
            'user_from__username',
            'message_body',
        )
Esempio n. 10
0
 def __new__(
     cls, wrapped: Field, schema_type: typing.Union[Field, typing.Type[Field]] = None,
 ) -> Field:
     if isinstance(schema_type, type):
         schema_type = schema_type()
     wrapped.schema_type = schema_type
     return wrapped
def test_get_field_description_success_case(settings):
    settings.API_STRICT_SCHEMA_VALIDATION = True
    schema = RestDoctorSchema()

    result = schema.get_field_description(Field(help_text='help_text'))

    assert result == 'help_text'
Esempio n. 12
0
class UserChatStatusSerializer(UUIDFieldSerializerMixin,
                               serializers.ModelSerializer):
    user = UserSerializer()
    unread_messages = Field(source='unread_messages')

    class Meta:
        model = UserChatStatus
        fields = ('user', 'status', 'joined', 'unread_messages')
Esempio n. 13
0
class ArticleSerializer(serializers.HyperlinkedModelSerializer):
    link = Field(source='get_absolute_url')

    class Meta:
        model = Article
        fields = (
            'title',
            'link',
        )
class FieldMetadata(TestCase):
    def setUp(self):
        self.required_field = Field()
        self.required_field.label = uuid4().hex
        self.required_field.required = True

        self.optional_field = Field()
        self.optional_field.label = uuid4().hex
        self.optional_field.required = False

    def test_required(self):
        self.assertEqual(self.required_field.metadata()['required'], True)

    def test_optional(self):
        self.assertEqual(self.optional_field.metadata()['required'], False)

    def test_label(self):
        for field in (self.required_field, self.optional_field):
            self.assertEqual(field.metadata()['label'], field.label)
Esempio n. 15
0
class HalPaginationSerializer(BasePaginationSerializer):
    count = Field(source='paginator.count')
    page_size = Field(source='paginator.per_page')
    results_field = '_embedded'

    def __init__(self, *args, **kwargs):
        super(HalPaginationSerializer, self).__init__(*args, **kwargs)

        class NestedLinksSerializer(Serializer):
            class NestedSelfLinkField(Field):
                def to_native(self, value):
                    request = self.context.get('request')
                    return request and request.build_absolute_uri() or ''

            self = NestedSelfLinkField(source='*')
            next = NextPageField(source='*')
            previous = PreviousPageField(source='*')

        self.fields.insert(0, '_links', NestedLinksSerializer(source="*"))
Esempio n. 16
0
class FieldMetadata(TestCase):
    def setUp(self):
        self.required_field = Field()
        self.required_field.label = uuid4().hex
        self.required_field.required = True

        self.optional_field = Field()
        self.optional_field.label = uuid4().hex
        self.optional_field.required = False

    def test_required(self):
        self.assertEqual(self.required_field.metadata()['required'], True)

    def test_optional(self):
        self.assertEqual(self.optional_field.metadata()['required'], False)

    def test_label(self):
        for field in (self.required_field, self.optional_field):
            self.assertEqual(field.metadata()['label'], field.label)
Esempio n. 17
0
class ProjectSerializer(MySerializer):
    has_data = Field()

    def get_default_fields(self):
        fields = super(ProjectSerializer, self).get_default_fields()
        if 'request' in self.context and self.context['request'].POST:
            pass
        else:
            fields['relationships'] = RelationshipSerializer(
                source="active_rels", )
        return fields
Esempio n. 18
0
 class Meta:
     model = Comment
     get_reply_count = Field(source="get_reply_count")
     fields = [
         "id",
         "user",
         "product",
         "content",
         "reply",
         "get_reply_count",
         "create_date",
     ]
Esempio n. 19
0
class LocationArticleSerializer(serializers.HyperlinkedModelSerializer):
    articles = ArticleSerializer(source='get_articles')
    topics = ArticleSerializer(source='get_topics')
    link = Field(source='get_absolute_url')

    class Meta:
        model = Location
        fields = (
            'articles',
            'topics',
            'title',
            'description',
            'link',
        )
Esempio n. 20
0
class DataRequestSerializer(MySerializer):
    as_python = Field()

    def validate_option(self, attrs, field):
        if not attrs.get('webservice', None):
            return attrs

        webservice = attrs['webservice']
        opts = webservice.default_options[field]
        if not attrs.get(field, None) and opts['required']:
            raise ValidationError(
                "This field is required for this webservice.")
        return attrs

    def validate_start_date(self, attrs, source):
        return self.validate_option(attrs, source)

    def validate_end_date(self, attrs, source):
        return self.validate_option(attrs, source)

    def from_native(self, data, files):
        # Create project on the fly
        project_name = data.get('project-name', None)
        if project_name:
            project, is_new = Project.objects.get_or_create_by_natural_key(
                project_name)
            if not is_new:
                project_name += " " + get_random_string(5)
                project = Project.objects.find(project_name)
            project_id = project.primary_identifier.slug
            user = self.context['request'].user
            project.name = project_name
            project.user_id = user.pk
            project.save()
            reltype = RelationshipType.objects.get(from_type__name='project')
            data = data.copy()
            data['inverserelationship-%s-item_id' % reltype.pk] = project_id

        return super(DataRequestSerializer, self).from_native(data, files)

    def save(self, *args, **kwargs):
        result = super(DataRequestSerializer, self).save(*args, **kwargs)
        if getattr(self, 'object', None) and self.object.project:
            self.object.public = self.object.project.public
            self.object.save()
        return result

    class Meta:
        exclude = ("relationships", )
Esempio n. 21
0
 def test_call_on_default_returns_field_age_group(self, monkeypatch):
     profile = UserProfileFactory.build()
     m_context = mock.MagicMock()
     m_context["request"].user = profile.user
     m_field_age_group = mock.Mock()
     field = Field()
     field.root._context = m_context
     monkeypatch.setattr(
         FieldOfStudyOfAgeGroupManager,
         "get_default_by_profile",
         mock.Mock(return_value=m_field_age_group),
     )
     default = FieldAgeGroupDefault()
     assert default.requires_context
     assert default(field) == m_field_age_group
Esempio n. 22
0
class TopicNodeSerializer(serializers.ModelSerializer):
    name = Field(source='_preferred_name')
    url = URLField('api:api-topic-nodes-detail', ('id', ))
    alternate_forms = serializers.SerializerMethodField('get_alternate_forms')
    project_topics = serializers.SerializerMethodField('get_project_value')

    class Meta:
        model = TopicNode
        fields = (
            'id',
            'name',
            'url',
            'alternate_forms',
            'type',
            'project_topics',
        )

    def get_alternate_forms(self, obj):
        topics = obj.project_topics.select_related('alternate_names')
        alternate_forms = set()
        alternate_forms.update(topic.preferred_name for topic in topics)
        alternate_forms.update(
            alternate_name.name for topic in topics
            for alternate_name in topic.alternate_names.all())
        alternate_forms.remove(obj._preferred_name)
        return list(alternate_forms)

    def get_project_value(self, obj):
        return [
            OrderedDict((('project_name', topic.project.name),
                         ('project_url',
                          reverse('api:api-project-detail',
                                  args=(topic.project.slug, ),
                                  request=self.context['request'])),
                         ('preferred_name', topic.preferred_name),
                         ('url',
                          reverse('api:api-topics-detail',
                                  args=(topic.project.slug, obj.id),
                                  request=self.context['request']))))
            for topic in obj.project_topics.select_related('project')
        ]
Esempio n. 23
0
class DataRequestSerializer(MySerializer):
    as_python = Field()

    def validate_option(self, attrs, field):
        if not attrs.get('webservice', None):
            return attrs

        webservice = attrs['webservice']
        opts = webservice.default_options[field]
        if not attrs.get(field, None) and opts['required']:
            raise ValidationError(
                "This field is required for this webservice."
            )
        return attrs

    def validate_start_date(self, attrs, source):
        return self.validate_option(attrs, source)

    def validate_end_date(self, attrs, source):
        return self.validate_option(attrs, source)

    class Meta:
        exclude = ("relationships",)
Esempio n. 24
0
class ChatSessionSerializer(serializers.ModelSerializer):
    username = Field(source='user.username')

    class Meta:
        model = ChatSession
        fields = ('username', 'status')
Esempio n. 25
0
    SlugField,
    TimeField,
    URLField,
    UUIDField,
)
from rest_framework_gis.fields import GeometryField

from restdoctor.rest_framework.schema import RestDoctorSchema

url_pattern = URLValidator.regex.pattern.replace('\\Z', '\\z')


@pytest.mark.parametrize(
    ('field', 'expected_schema'),
    [
        (Field(), {
            'type': 'string'
        }),
        (ReadOnlyField(), {
            'readOnly': True,
            'type': 'string'
        }),
        (Field(write_only=True), {
            'writeOnly': True,
            'type': 'string'
        }),
        (Field(allow_null=True), {
            'nullable': True,
            'type': 'string'
        }),
        (Field(default='default'), {
Esempio n. 26
0
class ProjectSerializer(MySerializer):
    has_data = Field()
def test_get_field_description_strict_fail_case(settings):
    settings.API_STRICT_SCHEMA_VALIDATION = True
    schema = RestDoctorSchema()

    with pytest.raises(ImproperlyConfigured):
        schema.get_field_description(Field())
from __future__ import annotations

import pytest
from django.core.exceptions import ImproperlyConfigured
from rest_framework.fields import Field
from rest_framework.routers import SimpleRouter

from restdoctor.rest_framework.schema import RestDoctorSchema
from restdoctor.rest_framework.schema.generators import RefsSchemaGenerator30
from tests.stubs.serializers import MyModelWithoutHelpTextsSerializer, WithMethodFieldSerializer
from tests.test_unit.test_schema.conftest import UrlConf
from tests.test_unit.test_schema.stubs import DefaultViewSet, DefaultViewSetWithOperationId


@pytest.mark.parametrize(('field', 'expected_help_text'),
                         [(Field(), None),
                          (Field(help_text='help_text'), 'help_text')])
def test_get_field_description_not_raises_success_case(field,
                                                       expected_help_text):
    schema = RestDoctorSchema()

    result = schema.get_field_description(field)

    assert result == expected_help_text


def test_get_field_description_strict_fail_case(settings):
    settings.API_STRICT_SCHEMA_VALIDATION = True
    schema = RestDoctorSchema()

    with pytest.raises(ImproperlyConfigured):
Esempio n. 29
0
class UserExtendSimpleSerializer(serializers.ModelSerializer):
    exists = Field(source='user_exists')

    class Meta:
        model = UserExtend
        fields = ('exists', )
Esempio n. 30
0
 class SerializerWithoutResourceName(serializers.Serializer):
     something = Field()
Esempio n. 31
0
class WebserviceSerializer(ModelSerializer):
    opts = Field("default_options")
    extra_opts = Field("extra_options")
    source_url = Field()
Esempio n. 32
0
class LineItemSerializer(serializers.HyperlinkedModelSerializer):
    total = Field(source='_get_total')

    class Meta:
        model = LineItem