def test_file_serializer(self, file_one):
        date_created = file_one.versions.first().date_created
        date_modified = file_one.versions.last().date_created
        date_created_tz_aware = date_created.replace(tzinfo=utc)
        date_modified_tz_aware = date_modified.replace(tzinfo=utc)
        new_format = '%Y-%m-%dT%H:%M:%S.%fZ'

        # test_date_modified_formats_to_old_format
        req = make_drf_request_with_version(version='2.0')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert date_modified_tz_aware == data['attributes']['date_modified']

        # test_date_modified_formats_to_new_format
        req = make_drf_request_with_version(version='2.2')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert datetime.strftime(date_modified, new_format) == data['attributes']['date_modified']

        # test_date_created_formats_to_old_format
        req = make_drf_request_with_version(version='2.0')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert date_created_tz_aware == data['attributes']['date_created']

        # test_date_created_formats_to_new_format
        req = make_drf_request_with_version(version='2.2')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert datetime.strftime(date_created, new_format) == data['attributes']['date_created']
Exemple #2
0
    def test_serialize_preprint_file(self, preprint, primary_file):
        req = make_drf_request_with_version(version='2.2')
        data = FileSerializer(primary_file, context={
            'request': req
        }).data['data']
        mfr_url = get_mfr_url(preprint, 'osfstorage')

        # Check render file link with path
        download_link = data['links']['download']
        assert data['links']['render'] == build_expected_render_link(
            mfr_url, download_link, with_version=False)

        # Check render file link with guid
        primary_file.get_guid(create=True)._id
        req = make_drf_request_with_version()
        data = FileSerializer(primary_file, context={
            'request': req
        }).data['data']
        download_link = data['links']['download']
        assert data['links']['render'] == build_expected_render_link(
            mfr_url, download_link, with_version=False)

        # Check html link
        assert data['links']['html'] == '{}{}/files/osfstorage/{}'.format(
            settings.DOMAIN, preprint._id, primary_file._id)
    def test_file_serializer(self, file_one):
        date_created = file_one.versions.first().date_created
        date_modified = file_one.versions.last().date_created
        date_created_tz_aware = date_created.replace(tzinfo=utc)
        date_modified_tz_aware = date_modified.replace(tzinfo=utc)
        new_format = '%Y-%m-%dT%H:%M:%S.%fZ'

        # test_date_modified_formats_to_old_format
        req = make_drf_request_with_version(version='2.0')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert date_modified_tz_aware == data['attributes']['date_modified']

        # test_date_modified_formats_to_new_format
        req = make_drf_request_with_version(version='2.2')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert datetime.strftime(
            date_modified, new_format) == data['attributes']['date_modified']

        # test_date_created_formats_to_old_format
        req = make_drf_request_with_version(version='2.0')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert date_created_tz_aware == data['attributes']['date_created']

        # test_date_created_formats_to_new_format
        req = make_drf_request_with_version(version='2.2')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert datetime.strftime(
            date_created, new_format) == data['attributes']['date_created']
Exemple #4
0
    def test_node_serializer(self, user):

    #   test_node_serialization
        parent = ProjectFactory(creator=user)
        node = NodeFactory(creator=user, parent=parent)
        req = make_drf_request_with_version(version='2.0')
        result = NodeSerializer(node, context={'request': req}).data
        data = result['data']
        assert data['id'] == node._id
        assert data['type'] == 'nodes'

        # Attributes
        attributes = data['attributes']
        assert attributes['title'] == node.title
        assert attributes['description'] == node.description
        assert attributes['public'] == node.is_public
        assert attributes['tags'] == [str(each.name) for each in node.tags.all()]
        assert attributes['current_user_can_comment'] == False
        assert attributes['category'] == node.category
        assert attributes['registration'] == node.is_registration
        assert attributes['fork'] == node.is_fork
        assert attributes['collection'] == node.is_collection

        # Relationships
        relationships = data['relationships']
        assert 'children' in relationships
        assert 'contributors' in relationships
        assert 'files' in relationships
        assert 'parent' in relationships
        assert 'affiliated_institutions' in relationships
        assert 'registrations' in relationships
        # Not a fork, so forked_from is removed entirely
        assert 'forked_from' not in relationships
        parent_link = relationships['parent']['links']['related']['href']
        assert urlparse(parent_link).path == '/{}nodes/{}/'.format(API_BASE, parent._id)

    #   test_fork_serialization
        node = NodeFactory(creator=user)
        fork = node.fork_node(auth=Auth(user))
        req = make_drf_request_with_version(version='2.0')
        result = NodeSerializer(fork, context={'request': req}).data
        data = result['data']

        # Relationships
        relationships = data['relationships']
        forked_from = relationships['forked_from']['links']['related']['href']
        assert urlparse(forked_from).path == '/{}nodes/{}/'.format(API_BASE, node._id)

    #   test_template_serialization
        node = NodeFactory(creator=user)
        fork = node.use_as_template(auth=Auth(user))
        req = make_drf_request_with_version(version='2.0')
        result = NodeSerializer(fork, context={'request': req}).data
        data = result['data']

        # Relationships
        relationships = data['relationships']
        templated_from = relationships['template_node']['links']['related']['href']
        assert urlparse(templated_from).path == '/{}nodes/{}/'.format(API_BASE, node._id)
    def test_no_node_relationship_after_version_2_7(self, file_one):
        req_2_7 = make_drf_request_with_version(version='2.7')
        data_2_7 = FileSerializer(file_one, context={'request': req_2_7}).data['data']
        assert 'node' in data_2_7['relationships'].keys()

        req_2_8 = make_drf_request_with_version(version='2.8')
        data_2_8 = FileSerializer(file_one, context={'request': req_2_8}).data['data']
        assert 'node' not in data_2_8['relationships'].keys()
Exemple #6
0
    def test_no_node_relationship_after_version_2_7(self, file_one):
        req_2_7 = make_drf_request_with_version(version='2.7')
        data_2_7 = FileSerializer(file_one, context={
            'request': req_2_7
        }).data['data']
        assert 'node' in data_2_7['relationships'].keys()

        req_2_8 = make_drf_request_with_version(version='2.8')
        data_2_8 = FileSerializer(file_one, context={
            'request': req_2_8
        }).data['data']
        assert 'node' not in data_2_8['relationships'].keys()
 def test_node_links_allowed_version_registration_serializer(self):
     req = make_drf_request_with_version(version='2.0')
     data = RegistrationSerializer(self.registration,
                                   context={
                                       'request': req
                                   }).data['data']
     assert_in('node_links', data['attributes'])
    def test_null_links_are_omitted(self):
        req = make_drf_request_with_version(version='2.0')
        rep = FakeSerializer(FakeModel, context={'request': req}).data['data']

        assert_not_in('null_field', rep['links'])
        assert_in('valued_field', rep['links'])
        assert_not_in('null_link_field', rep['relationships'])
 def test_node_links_bad_version_registration_serializer(self):
     req = make_drf_request_with_version(version='2.1')
     data = RegistrationSerializer(self.registration,
                                   context={
                                       'request': req
                                   }).data['data']
     assert_not_in('node_links', data['relationships'])
    def test_node_links_withdrawn_registration(self):
        factories.WithdrawnRegistrationFactory(registration=self.registration)

        req = make_drf_request_with_version(version='2.0')
        data = RegistrationSerializer(self.registration,
                                      context={
                                          'request': req
                                      }).data['data']
        assert_not_in('node_links', data['relationships'])

        req = make_drf_request_with_version(version='2.1')
        data = RegistrationSerializer(self.registration,
                                      context={
                                          'request': req
                                      }).data['data']
        assert_not_in('node_links', data['relationships'])
Exemple #11
0
    def test_collection_serialization(self):
        collection = CollectionFactory(creator=self.user)
        req = make_drf_request_with_version()
        if req.version >= '2.2':
            created_format = '%Y-%m-%dT%H:%M:%S.%fZ'
            modified_format = '%Y-%m-%dT%H:%M:%S.%fZ'
        else:
            created_format = '%Y-%m-%dT%H:%M:%S.%f' if collection.date_created.microsecond else '%Y-%m-%dT%H:%M:%S'
            modified_format = '%Y-%m-%dT%H:%M:%S.%f' if collection.date_modified.microsecond else '%Y-%m-%dT%H:%M:%S'

        result = CollectionSerializer(collection, context={
            'request': req
        }).data
        data = result['data']
        assert_equal(data['id'], collection._id)
        assert_equal(data['type'], 'collections')
        # Attributes
        attributes = data['attributes']
        assert_equal(attributes['title'], collection.title)
        assert_equal(attributes['date_created'],
                     collection.date_created.strftime(created_format))
        assert_equal(attributes['date_modified'],
                     collection.date_modified.strftime(modified_format))
        assert_equal(attributes['bookmarks'],
                     collection.is_bookmark_collection)

        # Relationships
        relationships = data['relationships']
        assert_in('node_links', relationships)
        # Bunch of stuff in Nodes that should not be in Collections
        assert_not_in('contributors', relationships)
        assert_not_in('files', relationships)
        assert_not_in('parent', relationships)
        assert_not_in('registrations', relationships)
        assert_not_in('forked_from', relationships)
    def test_collection_serialization(self):
        user = UserFactory()
        collection = CollectionFactory(creator=user)
        req = make_drf_request_with_version()
        if req.version >= '2.2':
            created_format = '%Y-%m-%dT%H:%M:%S.%fZ'
            modified_format = '%Y-%m-%dT%H:%M:%S.%fZ'
        else:
            created_format = '%Y-%m-%dT%H:%M:%S.%f' if collection.created.microsecond else '%Y-%m-%dT%H:%M:%S'
            modified_format = '%Y-%m-%dT%H:%M:%S.%f' if collection.modified.microsecond else '%Y-%m-%dT%H:%M:%S'

        result = CollectionSerializer(collection, context={
            'request': req
        }).data
        data = result['data']
        assert data['id'] == collection._id
        assert data['type'] == 'collections'
        # Attributes
        attributes = data['attributes']
        assert attributes['title'] == collection.title
        assert attributes['date_created'] == collection.created.strftime(
            created_format)
        assert attributes['date_modified'] == collection.modified.strftime(
            modified_format)
        assert attributes['bookmarks'] == collection.is_bookmark_collection

        # Relationships
        relationships = data['relationships']
        assert 'node_links' in relationships
        # Bunch of stuff in Nodes that should not be in Collections
        assert 'contributors' not in relationships
        assert 'files' not in relationships
        assert 'parent' not in relationships
        assert 'registrations' not in relationships
        assert 'forked_from' not in relationships
Exemple #13
0
    def test_preprint_provider_serialization_v25(self):
        req = make_drf_request_with_version(version='2.5')
        result = PreprintProviderSerializer(
            self.preprint_provider,
            context={'request': req}
        ).data

        data = result['data']
        attributes = data['attributes']

        assert_equal(data['id'], self.preprint_provider._id)
        assert_equal(data['type'], 'preprint_providers')

        assert_not_in('banner_path', attributes)
        assert_not_in('logo_path', attributes)
        assert_not_in('header_text', attributes)
        assert_not_in('email_contact', attributes)
        assert_not_in('social_facebook', attributes)
        assert_not_in('social_instagram', attributes)
        assert_not_in('social_twitter', attributes)
        assert_not_in('subjects_acceptable', attributes)

        assert_in('name', attributes)
        assert_in('description', attributes)
        assert_in('advisory_board', attributes)
        assert_in('example', attributes)
        assert_in('domain', attributes)
        assert_in('domain_redirect_enabled', attributes)
        assert_in('footer_links', attributes)
        assert_in('share_source', attributes)
        assert_in('share_publish_type', attributes)
        assert_in('email_support', attributes)
        assert_in('preprint_word', attributes)
        assert_in('allow_submissions', attributes)
        assert_in('additional_providers', attributes)
 def test_node_links_allowed_version_registration_serializer(self):
     req = make_drf_request_with_version(version='2.0')
     data = RegistrationSerializer(
         self.registration,
         context={'request': req}
     ).data['data']
     assert_in('node_links', data['relationships'])
Exemple #15
0
 def test_node_links_bad_version_registration_serializer(self):
     req = make_drf_request_with_version(version='2.1')
     data = RegistrationSerializer(
         self.registration,
         context={'request': req}
     ).data['data']
     assert_not_in('node_links', data['attributes'])
Exemple #16
0
 def test_field_with_two_kwargs(self):
     req = make_drf_request_with_version(version='2.0')
     project = factories.ProjectFactory()
     node = factories.NodeFactory(parent=project)
     data = self.BasicNodeSerializer(node, context={'request': req}).data['data']
     field = data['relationships']['two_url_kwargs']['links']
     assert_in('/v2/nodes/{}/node_links/{}/'.format(node._id, node._id), field['related']['href'])
 def test_field_with_non_attribute(self):
     req = make_drf_request_with_version(version='2.0')
     project = factories.ProjectFactory()
     node = factories.NodeFactory(parent=project)
     data = self.BasicNodeSerializer(node, context={'request': req}).data['data']
     field = data['relationships']['not_attribute_on_target']['links']
     assert_in('/v2/nodes/{}/children/'.format('12345'), field['related']['href'])
Exemple #18
0
    def test_serializing_log_with_legacy_non_registered_contributor_data(
            self, fake):
        # Old logs store unregistered contributors in params as dictionaries of the form:
        # {
        #     'nr_email': <email>,
        #     'nr_name': <name>,
        # }
        # This test ensures that the NodeLogSerializer can handle this legacy data.
        project = ProjectFactory()
        user = UserFactory()
        request = make_drf_request_with_version()
        nr_data = {'nr_email': fake.email(), 'nr_name': fake.name()}
        log = project.add_log(action=NodeLog.CONTRIB_ADDED,
                              auth=Auth(project.creator),
                              params={
                                  'project': project._id,
                                  'node': project._id,
                                  'contributors': [user._id, nr_data],
                              })
        serialized = NodeLogSerializer(log, context={'request': request}).data
        contributor_data = serialized['data']['attributes']['params'][
            'contributors']
        # contributor_data will have two dicts:
        # the first will be the registered contrib, 2nd will be non-reg contrib
        reg_contributor_data, unreg_contributor_data = contributor_data
        assert reg_contributor_data['id'] == user._id
        assert reg_contributor_data['full_name'] == user.fullname

        assert unreg_contributor_data['id'] is None
        assert unreg_contributor_data['full_name'] == nr_data['nr_name']
Exemple #19
0
 def test_field_with_non_attribute(self):
     req = make_drf_request_with_version(version="2.0")
     project = factories.ProjectFactory()
     node = factories.NodeFactory(parent=project)
     data = self.BasicNodeSerializer(node, context={"request": req}).data["data"]
     field = data["relationships"]["not_attribute_on_target"]["links"]
     assert_in("/v2/nodes/{}/children/".format("12345"), field["related"]["href"])
Exemple #20
0
 def test_field_with_non_attribute(self):
     req = make_drf_request_with_version(version='2.0')
     project = factories.ProjectFactory()
     node = factories.NodeFactory(parent=project)
     data = self.BasicNodeSerializer(node, context={'request': req}).data['data']
     field = data['relationships']['not_attribute_on_target']['links']
     assert_in('/v2/nodes/{}/children/'.format('12345'), field['related']['href'])
    def test_serializing_log_with_legacy_non_registered_contributor_data(self, fake):
        # Old logs store unregistered contributors in params as dictionaries of the form:
        # {
        #     'nr_email': <email>,
        #     'nr_name': <name>,
        # }
        # This test ensures that the NodeLogSerializer can handle this legacy data.
        project = ProjectFactory()
        user = UserFactory()
        request = make_drf_request_with_version()
        nr_data = {'nr_email': fake.email(), 'nr_name': fake.name()}
        log = project.add_log(
            action=NodeLog.CONTRIB_ADDED,
            auth=Auth(project.creator),
            params={
                'project': project._id,
                'node': project._id,
                'contributors': [user._id, nr_data],
            }
        )
        serialized = NodeLogSerializer(log, context={'request': request}).data
        contributor_data = serialized['data']['attributes']['params']['contributors']
        # contributor_data will have two dicts:
        # the first will be the registered contrib, 2nd will be non-reg contrib
        reg_contributor_data, unreg_contributor_data = contributor_data
        assert reg_contributor_data['id'] == user._id
        assert reg_contributor_data['full_name'] == user.fullname

        assert unreg_contributor_data['id'] is None
        assert unreg_contributor_data['full_name'] == nr_data['nr_name']
Exemple #22
0
 def test_field_with_two_kwargs(self):
     req = make_drf_request_with_version(version="2.0")
     project = factories.ProjectFactory()
     node = factories.NodeFactory(parent=project)
     data = self.BasicNodeSerializer(node, context={"request": req}).data["data"]
     field = data["relationships"]["two_url_kwargs"]["links"]
     assert_in("/v2/nodes/{}/node_links/{}/".format(node._id, node._id), field["related"]["href"])
 def get_related_count(self, user, related_field, auth):
     req = make_drf_request_with_version(version='2.0')
     req.query_params['related_counts'] = True
     if auth:
         req.user = auth
     result = UserSerializer(user, context={'request': req}).data
     return result['data']['relationships'][related_field]['links']['related']['meta']['count']
Exemple #24
0
    def test_field_with_callable_related_attrs(self):
        req = make_drf_request_with_version(version='2.0')
        project = factories.ProjectFactory()
        node = factories.NodeFactory(parent=project)
        data = self.BasicNodeSerializer(node, context={
            'request': req
        }).data['data']
        assert_not_in('registered_from', data['relationships'])

        registration = factories.RegistrationFactory(project=node)
        data = self.BasicNodeSerializer(registration, context={
            'request': req
        }).data['data']
        field = data['relationships']['registered_from']['links']
        assert_in('/v2/nodes/{}/'.format(node._id), field['related']['href'])

        registration_registration = factories.RegistrationFactory(
            project=registration)
        data = self.BasicNodeSerializer(registration_registration,
                                        context={
                                            'request': req
                                        }).data['data']
        field = data['relationships']['registered_from']['links']
        assert_in('/v2/registrations/{}/'.format(registration._id),
                  field['related']['href'])
    def test_search_serializer_mixed_model(self):

        user = AuthUserFactory()
        project = ProjectFactory(creator=user, is_public=True)
        component = NodeFactory(parent=project, creator=user, is_public=True)
        file_component = utils.create_test_file(component, user)
        context = {'request': make_drf_request_with_version(version='2.0')}
        schema = RegistrationSchema.objects.filter(
            name='Replication Recipe (Brandt et al., 2013): Post-Completion',
            schema_version=LATEST_SCHEMA_VERSION).first()

        # test_search_serializer_mixed_model_project
        result = SearchSerializer(project, context=context).data
        assert result['data']['type'] == 'nodes'

        # test_search_serializer_mixed_model_component
        result = SearchSerializer(component, context=context).data
        assert result['data']['type'] == 'nodes'

        # test_search_serializer_mixed_model_registration
        with mock_archive(project, autocomplete=True, autoapprove=True, schema=schema) as registration:
            result = SearchSerializer(registration, context=context).data
            assert result['data']['type'] == 'registrations'

        # test_search_serializer_mixed_model_file
        result = SearchSerializer(file_component, context=context).data
        assert result['data']['type'] == 'files'

        # test_search_serializer_mixed_model_user
        result = SearchSerializer(user, context=context).data
        assert result['data']['type'] == 'users'
Exemple #26
0
    def test_search_serializer_mixed_model(self):

        user = AuthUserFactory()
        project = ProjectFactory(creator=user, is_public=True)
        component = NodeFactory(parent=project, creator=user, is_public=True)
        file_component = utils.create_test_file(component, user)
        context = {'request': make_drf_request_with_version(version='2.0')}
        schema = MetaSchema.objects.filter(
            name='Replication Recipe (Brandt et al., 2013): Post-Completion',
            schema_version=LATEST_SCHEMA_VERSION).first()

        # test_search_serializer_mixed_model_project
        result = SearchSerializer(project, context=context).data
        assert result['data']['type'] == 'nodes'

        # test_search_serializer_mixed_model_component
        result = SearchSerializer(component, context=context).data
        assert result['data']['type'] == 'nodes'

        # test_search_serializer_mixed_model_registration
        with mock_archive(project,
                          autocomplete=True,
                          autoapprove=True,
                          schema=schema) as registration:
            result = SearchSerializer(registration, context=context).data
            assert result['data']['type'] == 'registrations'

        # test_search_serializer_mixed_model_file
        result = SearchSerializer(file_component, context=context).data
        assert result['data']['type'] == 'files'

        # test_search_serializer_mixed_model_user
        result = SearchSerializer(user, context=context).data
        assert result['data']['type'] == 'users'
Exemple #27
0
    def test_preprint_provider_serialization_v25(self):
        req = make_drf_request_with_version(version='2.5')
        result = PreprintProviderSerializer(self.preprint_provider,
                                            context={
                                                'request': req
                                            }).data

        data = result['data']
        attributes = data['attributes']

        assert_equal(data['id'], self.preprint_provider._id)
        assert_equal(data['type'], 'preprint_providers')

        assert_not_in('banner_path', attributes)
        assert_not_in('logo_path', attributes)
        assert_not_in('header_text', attributes)
        assert_not_in('email_contact', attributes)
        assert_not_in('social_facebook', attributes)
        assert_not_in('social_instagram', attributes)
        assert_not_in('social_twitter', attributes)
        assert_not_in('subjects_acceptable', attributes)

        assert_in('name', attributes)
        assert_in('description', attributes)
        assert_in('advisory_board', attributes)
        assert_in('example', attributes)
        assert_in('domain', attributes)
        assert_in('domain_redirect_enabled', attributes)
        assert_in('footer_links', attributes)
        assert_in('share_source', attributes)
        assert_in('share_publish_type', attributes)
        assert_in('email_support', attributes)
        assert_in('preprint_word', attributes)
        assert_in('allow_submissions', attributes)
        assert_in('additional_providers', attributes)
 def test_field_with_two_kwargs(self):
     req = make_drf_request_with_version(version='2.0')
     project = factories.ProjectFactory()
     node = factories.NodeFactory(parent=project)
     data = self.BasicNodeSerializer(node, context={'request': req}).data['data']
     field = data['relationships']['two_url_kwargs']['links']
     assert_in('/v2/nodes/{}/node_links/{}/'.format(node._id, node._id), field['related']['href'])
Exemple #29
0
    def test_collection_serialization(self):
        collection = CollectionFactory(creator=self.user)
        req = make_drf_request_with_version()
        result = CollectionSerializer(collection, context={
            'request': req
        }).data
        data = result['data']
        assert_equal(data['id'], collection._id)
        assert_equal(data['type'], 'collections')

        # Attributes
        attributes = data['attributes']
        assert_equal(attributes['title'], collection.title)
        assert_equal(attributes['date_created'],
                     collection.date_created.isoformat())
        assert_equal(attributes['date_modified'],
                     collection.date_modified.isoformat())
        assert_equal(attributes['bookmarks'],
                     collection.is_bookmark_collection)

        # Relationships
        relationships = data['relationships']
        assert_in('node_links', relationships)
        # Bunch of stuff in Nodes that should not be in Collections
        assert_not_in('contributors', relationships)
        assert_not_in('files', relationships)
        assert_not_in('parent', relationships)
        assert_not_in('registrations', relationships)
        assert_not_in('forked_from', relationships)
Exemple #30
0
    def test_null_links_are_omitted(self):
        req = make_drf_request_with_version(version='2.0')
        rep = FakeSerializer(FakeModel, context={'request': req}).data['data']

        assert_not_in('null_field', rep['links'])
        assert_in('valued_field', rep['links'])
        assert_not_in('null_link_field', rep['relationships'])
Exemple #31
0
    def test_collection_serialization(self):
        collection = CollectionFactory(creator=self.user)
        req = make_drf_request_with_version()
        if req.version >= '2.2':
            created_format = '%Y-%m-%dT%H:%M:%S.%fZ'
            modified_format = '%Y-%m-%dT%H:%M:%S.%fZ'
        else:
            created_format = '%Y-%m-%dT%H:%M:%S.%f' if collection.date_created.microsecond else '%Y-%m-%dT%H:%M:%S'
            modified_format = '%Y-%m-%dT%H:%M:%S.%f' if collection.date_modified.microsecond else '%Y-%m-%dT%H:%M:%S'

        result = CollectionSerializer(collection, context={'request': req}).data
        data = result['data']
        assert_equal(data['id'], collection._id)
        assert_equal(data['type'], 'collections')
        # Attributes
        attributes = data['attributes']
        assert_equal(attributes['title'], collection.title)
        assert_equal(attributes['date_created'], collection.date_created.strftime(created_format))
        assert_equal(attributes['date_modified'], collection.date_modified.strftime(modified_format))
        assert_equal(attributes['bookmarks'], collection.is_bookmark_collection)

        # Relationships
        relationships = data['relationships']
        assert_in('node_links', relationships)
        # Bunch of stuff in Nodes that should not be in Collections
        assert_not_in('contributors', relationships)
        assert_not_in('files', relationships)
        assert_not_in('parent', relationships)
        assert_not_in('registrations', relationships)
        assert_not_in('forked_from', relationships)
    def test_collection_serialization(self):
        user = UserFactory()
        collection = CollectionFactory(creator=user)
        req = make_drf_request_with_version()
        if req.version >= '2.2':
            created_format = '%Y-%m-%dT%H:%M:%S.%fZ'
            modified_format = '%Y-%m-%dT%H:%M:%S.%fZ'
        else:
            created_format = '%Y-%m-%dT%H:%M:%S.%f' if collection.created.microsecond else '%Y-%m-%dT%H:%M:%S'
            modified_format = '%Y-%m-%dT%H:%M:%S.%f' if collection.modified.microsecond else '%Y-%m-%dT%H:%M:%S'

        result = CollectionSerializer(
            collection, context={'request': req}
        ).data
        data = result['data']
        assert data['id'] == collection._id
        assert data['type'] == 'collections'
        # Attributes
        attributes = data['attributes']
        assert attributes['title'] == collection.title
        assert attributes['date_created'] == collection.created.strftime(
            created_format)
        assert attributes['date_modified'] == collection.modified.strftime(
            modified_format)
        assert attributes['bookmarks'] == collection.is_bookmark_collection

        # Relationships
        relationships = data['relationships']
        assert 'node_links' in relationships
        # Bunch of stuff in Nodes that should not be in Collections
        assert 'contributors' not in relationships
        assert 'files' not in relationships
        assert 'parent' not in relationships
        assert 'registrations' not in relationships
        assert 'forked_from' not in relationships
Exemple #33
0
 def test_draft_node_relationships(self, draft_node, draft_node_folder):
     # Ensure that the files relationship link is pointing to the correct root endpoint
     req = make_drf_request_with_version()
     data = FileSerializer(draft_node_folder, context={
         'request': req
     }).data['data']
     assert 'draft_nodes' in data['relationships']['files']['links'][
         'related']['href']
    def test_node_links_withdrawn_registration(self):
        factories.WithdrawnRegistrationFactory(
            registration=self.registration)

        req = make_drf_request_with_version(version='2.0')
        data = RegistrationSerializer(
            self.registration,
            context={'request': req}
        ).data['data']
        assert_not_in('node_links', data['relationships'])

        req = make_drf_request_with_version(version='2.1')
        data = RegistrationSerializer(
            self.registration,
            context={'request': req}
        ).data['data']
        assert_not_in('node_links', data['relationships'])
Exemple #35
0
 def test_new_date_without_microseconds_formats_to_old_format(self):
     req = make_drf_request_with_version(version='2.0')
     setattr(self.node, 'date_modified', self.new_date_without_microseconds)
     data = NodeSerializer(self.node, context={'request': req}).data['data']
     assert_equal(
         datetime.strftime(self.new_date_without_microseconds, self.old_format_without_microseconds),
         data['attributes']['date_modified']
     )
Exemple #36
0
 def test_old_date_formats_to_old_format(self):
     req = make_drf_request_with_version(version='2.0')
     setattr(self.node, 'last_logged', self.old_date)
     data = NodeSerializer(self.node, context={'request': req}).data['data']
     assert_equal(
         datetime.strftime(self.old_date,self.old_format),
         data['attributes']['date_modified']
     )
Exemple #37
0
 def test_field_with_two_filters(self):
     req = make_drf_request_with_version(version='2.0')
     project = factories.ProjectFactory()
     node = factories.NodeFactory(parent=project)
     data = self.BasicNodeSerializer(node, context={'request': req}).data['data']
     field = data['relationships']['field_with_filters']['links']
     assert_in(urllib.quote('filter[target]=hello', safe='?='), field['related']['href'])
     assert_in(urllib.quote('filter[woop]=yea', safe='?='), field['related']['href'])
Exemple #38
0
 def test_new_date_formats_to_new_format(self):
     req = make_drf_request_with_version(version='2.2')
     setattr(self.node, 'last_logged', self.new_date)
     data = NodeSerializer(self.node, context={'request': req}).data['data']
     assert_equal(
         datetime.strftime(self.new_date, self.new_format),
         data['attributes']['date_modified']
     )
Exemple #39
0
 def get_related_count(self, user, related_field, auth):
     req = make_drf_request_with_version(version='2.0')
     req.query_params['related_counts'] = True
     if auth:
         req.user = auth
     result = UserSerializer(user, context={'request': req}).data
     return result['data']['relationships'][related_field]['links'][
         'related']['meta']['count']
 def test_new_date_without_microseconds_formats_to_new_format(self):
     req = make_drf_request_with_version(version='2.2')
     setattr(self.node, 'last_logged', self.new_date_without_microseconds)
     data = NodeSerializer(self.node, context={'request': req}).data['data']
     assert_equal(
         datetime.strftime(self.new_date_without_microseconds,
                           self.new_format),
         data['attributes']['date_modified'])
 def test_field_with_two_filters(self):
     req = make_drf_request_with_version(version='2.0')
     project = factories.ProjectFactory()
     node = factories.NodeFactory(parent=project)
     data = self.BasicNodeSerializer(node, context={'request': req}).data['data']
     field = data['relationships']['field_with_filters']['links']
     assert_in(urllib.quote('filter[target]=hello', safe='?='), field['related']['href'])
     assert_in(urllib.quote('filter[woop]=yea', safe='?='), field['related']['href'])
Exemple #42
0
    def test_null_links_are_omitted(self):
        req = make_drf_request_with_version(version="2.0")
        rep = FakeSerializer(FakeModel, context={"request": req}).data["data"]

        assert_not_in("null_field", rep["links"])
        assert_in("valued_field", rep["links"])
        assert_not_in("null_link_field", rep["relationships"])
        assert_in("valued_link_field", rep["relationships"])
Exemple #43
0
    def test_self_and_related_fields(self):
        req = make_drf_request_with_version(version="2.0")
        project = factories.ProjectFactory()
        node = factories.NodeFactory(parent=project)
        data = self.BasicNodeSerializer(node, context={"request": req}).data["data"]

        relationship_field = data["relationships"]["self_and_related_field"]["links"]
        assert_in("/v2/nodes/{}/contributors/".format(node._id), relationship_field["self"]["href"])
        assert_in("/v2/nodes/{}/".format(node._id), relationship_field["related"]["href"])
    def test_self_and_related_fields(self):
        req = make_drf_request_with_version(version='2.0')
        project = factories.ProjectFactory()
        node = factories.NodeFactory(parent=project)
        data = self.BasicNodeSerializer(node, context={'request': req}).data['data']

        relationship_field = data['relationships']['self_and_related_field']['links']
        assert_in('/v2/nodes/{}/contributors/'.format(node._id), relationship_field['self']['href'])
        assert_in('/v2/nodes/{}/'.format(node._id), relationship_field['related']['href'])
    def test_serializing_empty_to_one(self):
        req = make_drf_request_with_version(version='2.2')
        node = factories.NodeFactory()
        data = self.BasicNodeSerializer(node, context={
            'request': req
        }).data['data']
        # This node is not registered_from another node hence it is an empty-to-one.
        assert 'registered_from' not in data['relationships']

        # In 2.9, API returns null for empty relationships
        # https://openscience.atlassian.net/browse/PLAT-840
        req = make_drf_request_with_version(version='2.9')
        node = factories.NodeFactory()
        data = self.BasicNodeSerializer(node, context={
            'request': req
        }).data['data']

        assert data['relationships']['registered_from']['data'] is None
    def get_view_count(self, user, related_field, auth):
        req = make_drf_request_with_version(version='2.0')
        if auth:
            req.user = auth
        view_name = UserSerializer().fields[related_field].field.view_name
        resolve_match = resolve(reverse(view_name, kwargs={'version': 'v2', 'user_id': user._id}))
        view = resolve_match.func.view_class(request=req, kwargs={'version': 'v2', 'user_id': user._id})

        return view.get_queryset().count()
Exemple #47
0
    def test_self_and_related_fields(self):
        req = make_drf_request_with_version(version='2.0')
        project = factories.ProjectFactory()
        node = factories.NodeFactory(parent=project)
        data = self.BasicNodeSerializer(node, context={'request': req}).data['data']

        relationship_field = data['relationships']['self_and_related_field']['links']
        assert_in('/v2/nodes/{}/contributors/'.format(node._id), relationship_field['self']['href'])
        assert_in('/v2/nodes/{}/'.format(node._id), relationship_field['related']['href'])
Exemple #48
0
    def test_serializing_empty_to_one(self):
        req = make_drf_request_with_version(version='2.2')
        node = factories.NodeFactory()
        data = self.BasicNodeSerializer(
            node, context={'request': req}
        ).data['data']
        # This node is not registered_from another node hence it is an empty-to-one.
        assert 'registered_from' not in data['relationships']

        # In 2.9, API returns null for empty relationships
        # https://openscience.atlassian.net/browse/PLAT-840
        req = make_drf_request_with_version(version='2.9')
        node = factories.NodeFactory()
        data = self.BasicNodeSerializer(
            node, context={'request': req}
        ).data['data']

        assert data['relationships']['registered_from']['data'] is None
Exemple #49
0
    def test_serialization(self):
        user = UserFactory()
        versioned_request = make_drf_request_with_version(version='2.2')
        registration = RegistrationFactory(creator=user)
        result = RegistrationSerializer(registration,
                                        context={
                                            'request': versioned_request
                                        }).data
        data = result['data']
        assert data['id'] == registration._id
        assert data['type'] == 'registrations'
        should_not_relate_to_registrations = [
            'registered_from',
            'registered_by',
            'registration_schema',
            'region',
            'provider',
            'storage',
            'groups',
            'original_response',
            'latest_response',
        ]

        # Attributes
        attributes = data['attributes']
        assert_datetime_equal(parse_date(attributes['date_registered']),
                              registration.registered_date)
        assert attributes['withdrawn'] == registration.is_retracted

        # Relationships
        relationships = data['relationships']

        # Relationships with data
        relationship_urls = {
            k: v['links']['related']['href']
            for k, v in relationships.items()
        }

        assert 'registered_by' in relationships
        registered_by = relationships['registered_by']['links']['related'][
            'href']
        assert urlparse(registered_by).path == '/{}users/{}/'.format(
            API_BASE, user._id)
        assert 'registered_from' in relationships
        registered_from = relationships['registered_from']['links']['related'][
            'href']
        assert urlparse(registered_from).path == '/{}nodes/{}/'.format(
            API_BASE, registration.registered_from._id)
        api_registrations_url = '/{}registrations/'.format(API_BASE)
        for relationship in relationship_urls:
            if relationship in should_not_relate_to_registrations:
                assert api_registrations_url not in relationship_urls[
                    relationship]
            else:
                assert api_registrations_url in relationship_urls[
                    relationship], 'For key {}'.format(relationship)
Exemple #50
0
    def test_serializing_meta(self):
        req = make_drf_request_with_version(version="2.0")
        project = factories.ProjectFactory()
        node = factories.NodeFactory(parent=project)
        data = self.BasicNodeSerializer(node, context={"request": req}).data["data"]

        meta = data["relationships"]["parent_with_meta"]["links"]["related"]["meta"]
        assert_not_in("count", meta)
        assert_in("extra", meta)
        assert_equal(meta["extra"], "foo")
    def test_serializing_meta(self):
        req = make_drf_request_with_version(version='2.0')
        project = factories.ProjectFactory()
        node = factories.NodeFactory(parent=project)
        data = self.BasicNodeSerializer(node, context={'request': req}).data['data']

        meta = data['relationships']['parent_with_meta']['links']['related']['meta']
        assert_not_in('count', meta)
        assert_in('extra', meta)
        assert_equal(meta['extra'], 'foo')
Exemple #52
0
    def test_serializing_meta(self):
        req = make_drf_request_with_version(version='2.0')
        project = factories.ProjectFactory()
        node = factories.NodeFactory(parent=project)
        data = self.BasicNodeSerializer(node, context={'request': req}).data['data']

        meta = data['relationships']['parent_with_meta']['links']['related']['meta']
        assert_not_in('count', meta)
        assert_in('extra', meta)
        assert_equal(meta['extra'], 'foo')
    def test_file_serializer(self, file_one):
        created = file_one.versions.last().created
        modified = file_one.versions.first().created
        created_tz_aware = created.replace(tzinfo=utc)
        modified_tz_aware = modified.replace(tzinfo=utc)
        new_format = '%Y-%m-%dT%H:%M:%S.%fZ'

        download_base = '/download/{}'
        path = file_one._id

        # test_date_modified_formats_to_old_format
        req = make_drf_request_with_version(version='2.0')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert modified_tz_aware == data['attributes']['date_modified']

        # test_date_modified_formats_to_new_format
        req = make_drf_request_with_version(version='2.2')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert datetime.strftime(
            modified, new_format
        ) == data['attributes']['date_modified']

        # test_date_created_formats_to_old_format
        req = make_drf_request_with_version(version='2.0')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert created_tz_aware == data['attributes']['date_created']

        # test_date_created_formats_to_new_format
        req = make_drf_request_with_version(version='2.2')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert datetime.strftime(
            created, new_format
        ) == data['attributes']['date_created']

        # check download file link with path
        assert download_base.format(path) in data['links']['download']

        # check download file link with guid
        guid = file_one.get_guid(create=True)._id
        req = make_drf_request_with_version()
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert download_base.format(guid) in data['links']['download']
Exemple #54
0
    def test_field_with_callable_related_attrs(self):
        req = make_drf_request_with_version(version='2.0')
        project = factories.ProjectFactory()
        node = factories.NodeFactory(parent=project)
        data = self.BasicNodeSerializer(node, context={'request': req}).data['data']
        assert_not_in('registered_from', data['relationships'])

        registration = factories.RegistrationFactory(project=node)
        data = self.BasicNodeSerializer(registration, context={'request': req}).data['data']
        field = data['relationships']['registered_from']['links']
        assert_in('/v2/nodes/{}/'.format(node._id), field['related']['href'])
    def test_file_serializer(self, file_one):
        created = file_one.versions.last().created
        modified = file_one.versions.first().created
        created_tz_aware = created.replace(tzinfo=utc)
        modified_tz_aware = modified.replace(tzinfo=utc)
        new_format = '%Y-%m-%dT%H:%M:%S.%fZ'

        download_base = '/download/{}'
        path = file_one._id

        # test_date_modified_formats_to_old_format
        req = make_drf_request_with_version(version='2.0')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert modified_tz_aware == data['attributes']['date_modified']

        # test_date_modified_formats_to_new_format
        req = make_drf_request_with_version(version='2.2')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert datetime.strftime(
            modified, new_format) == data['attributes']['date_modified']

        # test_date_created_formats_to_old_format
        req = make_drf_request_with_version(version='2.0')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert created_tz_aware == data['attributes']['date_created']

        # test_date_created_formats_to_new_format
        req = make_drf_request_with_version(version='2.2')
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert datetime.strftime(
            created, new_format) == data['attributes']['date_created']

        # check download file link with path
        assert download_base.format(path) in data['links']['download']

        # check download file link with guid
        guid = file_one.get_guid(create=True)._id
        req = make_drf_request_with_version()
        data = FileSerializer(file_one, context={'request': req}).data['data']
        assert download_base.format(guid) in data['links']['download']
    def test_fork_serialization(self):
        node = NodeFactory(creator=self.user)
        fork = node.fork_node(auth=Auth(user=node.creator))
        req = make_drf_request_with_version(version='2.0')
        result = NodeSerializer(fork, context={'request': req}).data
        data = result['data']

        # Relationships
        relationships = data['relationships']
        forked_from = relationships['forked_from']['links']['related']['href']
        assert_equal(
            urlparse(forked_from).path,
            '/{}nodes/{}/'.format(API_BASE, node._id))
    def test_template_serialization(self):
        node = NodeFactory(creator=self.user)
        fork = node.use_as_template(auth=Auth(user=node.creator))
        req = make_drf_request_with_version(version='2.0')
        result = NodeSerializer(fork, context={'request': req}).data
        data = result['data']

        # Relationships
        relationships = data['relationships']
        templated_from = relationships['template_node']['links']['related']['href']
        assert_equal(
            urlparse(templated_from).path,
            '/{}nodes/{}/'.format(API_BASE, node._id)
        )
Exemple #58
0
    def get_view_count(self, user, related_field, auth):
        req = make_drf_request_with_version(version='2.0')
        if auth:
            req.user = auth
        view_name = UserSerializer().fields[related_field].field.view_name
        resolve_match = resolve(
            reverse(view_name, kwargs={
                'version': 'v2',
                'user_id': user._id
            }))
        view = resolve_match.func.view_class(request=req,
                                             kwargs={
                                                 'version': 'v2',
                                                 'user_id': user._id
                                             })

        return view.get_queryset().count()
Exemple #59
0
    def test_serialization(self):
        user = UserFactory()
        req = make_drf_request_with_version(version='2.0')
        reg = RegistrationFactory(creator=user)
        result = RegistrationSerializer(reg, context={'request': req}).data
        data = result['data']
        assert_equal(data['id'], reg._id)
        assert_equal(data['type'], 'registrations')
        should_not_relate_to_registrations = [
            'registered_from',
            'registered_by',
            'registration_schema'
        ]

        # Attributes
        attributes = data['attributes']
        assert_datetime_equal(
            parse_date(attributes['date_registered']),
            reg.registered_date
        )
        assert_equal(attributes['withdrawn'], reg.is_retracted)

        # Relationships
        relationships = data['relationships']
        relationship_urls = {}
        for relationship in relationships:
            relationship_urls[relationship]=relationships[relationship]['links']['related']['href']
        assert_in('registered_by', relationships)
        registered_by = relationships['registered_by']['links']['related']['href']
        assert_equal(
            urlparse(registered_by).path,
            '/{}users/{}/'.format(API_BASE, user._id)
        )
        assert_in('registered_from', relationships)
        registered_from = relationships['registered_from']['links']['related']['href']
        assert_equal(
            urlparse(registered_from).path,
            '/{}nodes/{}/'.format(API_BASE, reg.registered_from._id)
        )
        for relationship in relationship_urls:
            if relationship in should_not_relate_to_registrations:
                assert_not_in('/{}registrations/'.format(API_BASE), relationship_urls[relationship])
            else:
                assert_in('/{}registrations/'.format(API_BASE), relationship_urls[relationship],
                          'For key {}'.format(relationship))
Exemple #60
0
    def test_sparse_node_serializer(self, user):

        #   test_node_serialization
        parent = ProjectFactory(creator=user)
        node = NodeFactory(creator=user, parent=parent)
        req = make_drf_request_with_version(version='2.15')
        result = SparseNodeSerializer(node, context={'request': req}).data
        data = result['data']
        assert data['id'] == node._id
        assert data['type'] == 'sparse-nodes'

        # Attributes
        attributes = data['attributes']
        assert attributes['title'] == node.title
        assert attributes['description'] == node.description
        assert attributes['public'] == node.is_public
        assert set(attributes['tags']) == set(
            node.tags.values_list('name', flat=True))
        assert 'current_user_can_comment' not in attributes
        assert 'license' not in attributes
        assert attributes['category'] == node.category
        assert 'registration' not in attributes
        assert attributes['fork'] == node.is_fork

        # Relationships
        relationships = data['relationships']
        assert 'region' not in relationships
        assert 'children' in relationships
        assert 'detail' in relationships
        assert 'contributors' in relationships
        assert 'files' not in relationships
        assert 'parent' in relationships
        assert 'affiliated_institutions' not in relationships
        assert 'registrations' not in relationships
        assert 'forked_from' not in relationships
        parent_link = relationships['parent']['links']['related']['href']
        assert urlparse(parent_link).path == '/{}sparse/nodes/{}/'.format(
            API_BASE, parent._id)
        assert 'sparse' not in relationships['detail']['links']['related'][
            'href']
        sparse_children_path = urlparse(
            relationships['children']['links']['related']['href']).path
        assert sparse_children_path == '/{}sparse/nodes/{}/children/'.format(
            API_BASE, node._id)