Beispiel #1
0
class TestPreprintDeleteView(AdminTestCase):
    def setUp(self):
        super(TestPreprintDeleteView, self).setUp()
        self.user = AuthUserFactory()
        self.preprint = PreprintFactory(creator=self.user)
        self.request = RequestFactory().post('/fake_path')
        self.plain_view = views.PreprintDeleteView
        self.view = setup_log_view(self.plain_view(), self.request,
                                   guid=self.preprint._id)

        self.url = reverse('preprints:remove', kwargs={'guid': self.preprint._id})

    def test_get_object(self):
        obj = self.view.get_object()
        assert isinstance(obj, Preprint)

    def test_get_context(self):
        res = self.view.get_context_data(object=self.preprint)
        assert 'guid' in res
        assert res.get('guid') == self.preprint._id

    def test_remove_preprint(self):
        count = AdminLogEntry.objects.count()
        self.view.delete(self.request)
        self.preprint.refresh_from_db()
        assert self.preprint.deleted is not None
        assert AdminLogEntry.objects.count() == count + 1

    def test_restore_preprint(self):
        self.view.delete(self.request)
        self.preprint.refresh_from_db()
        assert self.preprint.deleted is not None
        count = AdminLogEntry.objects.count()
        self.view.delete(self.request)
        self.preprint.reload()
        assert self.preprint.deleted is None
        assert AdminLogEntry.objects.count() == count + 1

    def test_no_user_permissions_raises_error(self):
        guid = self.preprint._id
        request = RequestFactory().get(self.url)
        request.user = self.user

        with pytest.raises(PermissionDenied):
            self.plain_view.as_view()(request, guid=guid, user_id=self.user)

    def test_correct_view_permissions(self):
        user = AuthUserFactory()
        guid = self.preprint._id
        change_permission = Permission.objects.get(codename='delete_preprint')
        view_permission = Permission.objects.get(codename='view_preprint')
        user.user_permissions.add(change_permission)
        user.user_permissions.add(view_permission)
        user.save()

        request = RequestFactory().get(self.url)
        request.user = user

        response = self.plain_view.as_view()(request, guid=guid)
        assert response.status_code == 200
Beispiel #2
0
class TestPreprintDeleteView(AdminTestCase):
    def setUp(self):
        super(TestPreprintDeleteView, self).setUp()
        self.user = AuthUserFactory()
        self.preprint = PreprintFactory(creator=self.user)
        self.request = RequestFactory().post('/fake_path')
        self.plain_view = views.PreprintDeleteView
        self.view = setup_log_view(self.plain_view(),
                                   self.request,
                                   guid=self.preprint._id)

        self.url = reverse('preprints:remove',
                           kwargs={'guid': self.preprint._id})

    def test_remove_preprint(self):
        count = AdminLogEntry.objects.count()
        self.view.post(self.request)
        self.preprint.refresh_from_db()
        assert self.preprint.deleted is not None
        assert AdminLogEntry.objects.count() == count + 1

    def test_restore_preprint(self):
        self.view.post(self.request)
        self.preprint.refresh_from_db()
        assert self.preprint.deleted is not None
        count = AdminLogEntry.objects.count()
        self.view.post(self.request)
        self.preprint.reload()
        assert self.preprint.deleted is None
        assert AdminLogEntry.objects.count() == count + 1
Beispiel #3
0
    def test_claim_user_registered_preprint_with_correct_password(self):
        preprint = PreprintFactory(creator=self.referrer)
        name, email = fake.name(), fake_email()
        unreg_user = preprint.add_unregistered_contributor(
            fullname=name,
            email=email,
            auth=Auth(user=self.referrer)
        )
        reg_user = AuthUserFactory()  # NOTE: AuthUserFactory sets password as 'queenfan86'
        url = unreg_user.get_claim_url(preprint._id)
        # Follow to password re-enter page
        res = self.app.get(url, auth=reg_user.auth).follow(auth=reg_user.auth)

        # verify that the "Claim Account" form is returned
        assert_in('Claim Contributor', res.body)

        form = res.forms['claimContributorForm']
        form['password'] = '******'
        res = form.submit(auth=reg_user.auth)

        preprint.reload()
        unreg_user.reload()
        # user is now a contributor to the project
        assert_in(reg_user, preprint.contributors)

        # the unregistered user (unreg_user) is removed as a contributor, and their
        assert_not_in(unreg_user, preprint.contributors)

        # unclaimed record for the project has been deleted
        assert_not_in(preprint, unreg_user.unclaimed_records)
class TestPreprintDeleteView(AdminTestCase):
    def setUp(self):
        super(TestPreprintDeleteView, self).setUp()
        self.user = AuthUserFactory()
        self.preprint = PreprintFactory(creator=self.user)
        self.request = RequestFactory().post('/fake_path')
        self.plain_view = views.PreprintDeleteView
        self.view = setup_log_view(self.plain_view(), self.request,
                                   guid=self.preprint._id)

        self.url = reverse('preprints:remove', kwargs={'guid': self.preprint._id})

    def test_get_object(self):
        obj = self.view.get_object()
        assert isinstance(obj, Preprint)

    def test_get_context(self):
        res = self.view.get_context_data(object=self.preprint)
        assert 'guid' in res
        assert res.get('guid') == self.preprint._id

    def test_remove_preprint(self):
        count = AdminLogEntry.objects.count()
        self.view.delete(self.request)
        self.preprint.refresh_from_db()
        assert self.preprint.deleted is not None
        assert AdminLogEntry.objects.count() == count + 1

    def test_restore_preprint(self):
        self.view.delete(self.request)
        self.preprint.refresh_from_db()
        assert self.preprint.deleted is not None
        count = AdminLogEntry.objects.count()
        self.view.delete(self.request)
        self.preprint.reload()
        assert self.preprint.deleted is None
        assert AdminLogEntry.objects.count() == count + 1

    def test_no_user_permissions_raises_error(self):
        guid = self.preprint._id
        request = RequestFactory().get(self.url)
        request.user = self.user

        with pytest.raises(PermissionDenied):
            self.plain_view.as_view()(request, guid=guid, user_id=self.user)

    def test_correct_view_permissions(self):
        user = AuthUserFactory()
        guid = self.preprint._id
        change_permission = Permission.objects.get(codename='delete_preprint')
        view_permission = Permission.objects.get(codename='view_preprint')
        user.user_permissions.add(change_permission)
        user.user_permissions.add(view_permission)
        user.save()

        request = RequestFactory().get(self.url)
        request.user = user

        response = self.plain_view.as_view()(request, guid=guid)
        assert response.status_code == 200
Beispiel #5
0
 def test_update_published(self, app, user):
     unpublished = PreprintFactory(creator=user, is_published=False)
     url = '/{}preprints/{}/'.format(API_BASE, unpublished._id)
     payload = build_preprint_update_payload(unpublished._id, attributes={'is_published': True})
     res = app.patch_json_api(url, payload, auth=user.auth)
     unpublished.reload()
     assert unpublished.is_published
 def test_update_published(self):
     unpublished = PreprintFactory(creator=self.user, is_published=False)
     url = '/{}preprints/{}/'.format(API_BASE, unpublished._id)
     payload = build_preprint_update_payload(
         unpublished._id, attributes={'is_published': True})
     res = self.app.patch_json_api(url, payload, auth=self.user.auth)
     unpublished.reload()
     assert_true(unpublished.is_published)
 def test_update_published(self, mock_get_identifiers, app, user):
     unpublished = PreprintFactory(creator=user, is_published=False)
     url = '/{}preprints/{}/'.format(API_BASE, unpublished._id)
     payload = build_preprint_update_payload(unpublished._id, attributes={'is_published': True})
     res = app.patch_json_api(url, payload, auth=user.auth)
     unpublished.reload()
     assert unpublished.is_published
     assert mock_get_identifiers.called
Beispiel #8
0
class TestPreprintSpam(OsfTestCase):

    def setUp(self):
        super(TestPreprintSpam, self).setUp()

        self.user = AuthUserFactory()
        self.auth = Auth(user=self.user)
        self.node = ProjectFactory(creator=self.user, is_public=True)
        self.preprint_one = PreprintFactory(creator=self.user, project=self.node)
        self.preprint_two = PreprintFactory(creator=self.user, project=self.node, filename='preprint_file_two.txt')

    @mock.patch.object(settings, 'SPAM_CHECK_ENABLED', True)
    def test_preprints_get_marked_as_spammy_if_node_is_spammy(self):
        with mock.patch('osf.models.node.Node._get_spam_content', mock.Mock(return_value='some content!')):
            with mock.patch('osf.models.node.Node.do_check_spam', mock.Mock(return_value=True)):
                self.node.check_spam(self.user, None, None)
        self.preprint_one.reload()
        self.preprint_two.reload()
        assert_true(self.preprint_one.is_spammy)
        assert_true(self.preprint_two.is_spammy)
Beispiel #9
0
class TestPreprintSpam(OsfTestCase):

    def setUp(self):
        super(TestPreprintSpam, self).setUp()

        self.user = AuthUserFactory()
        self.auth = Auth(user=self.user)
        self.node = ProjectFactory(creator=self.user, is_public=True)
        self.preprint_one = PreprintFactory(creator=self.user, project=self.node)
        self.preprint_two = PreprintFactory(creator=self.user, project=self.node, filename='preprint_file_two.txt')

    @mock.patch.object(settings, 'SPAM_CHECK_ENABLED', True)
    def test_preprints_get_marked_as_spammy_if_node_is_spammy(self):
        with mock.patch('osf.models.node.Node._get_spam_content', mock.Mock(return_value='some content!')):
            with mock.patch('osf.models.node.Node.do_check_spam', mock.Mock(return_value=True)):
                self.node.check_spam(self.user, None, None)
        self.preprint_one.reload()
        self.preprint_two.reload()
        assert_true(self.preprint_one.is_spammy)
        assert_true(self.preprint_two.is_spammy)
Beispiel #10
0
class TestPreprintProviders(OsfTestCase):
    def setUp(self):
        super(TestPreprintProviders, self).setUp()
        self.preprint = PreprintFactory(provider=None, is_published=False)
        self.provider = PreprintProviderFactory(name='WWEArxiv')

    def test_add_provider(self):
        assert_not_equal(self.preprint.provider, self.provider)

        self.preprint.provider = self.provider
        self.preprint.save()
        self.preprint.reload()

        assert_equal(self.preprint.provider, self.provider)

    def test_remove_provider(self):
        self.preprint.provider = None
        self.preprint.save()
        self.preprint.reload()

        assert_equal(self.preprint.provider, None)

    def test_find_provider(self):
        self.preprint.provider = self.provider
        self.preprint.save()
        self.preprint.reload()

        assert ('branded', 'WWEArxiv') == find_preprint_provider(self.preprint.node)
Beispiel #11
0
class TestPreprintProvider(OsfTestCase):
    def setUp(self):
        super(TestPreprintProvider, self).setUp()
        self.preprint = PreprintFactory(provider=None, is_published=False)
        self.provider = PreprintProviderFactory(name='WWEArxiv')

    def test_add_provider(self):
        assert_not_equal(self.preprint.provider, self.provider)

        self.preprint.provider = self.provider
        self.preprint.save()
        self.preprint.reload()

        assert_equal(self.preprint.provider, self.provider)

    def test_remove_provider(self):
        self.preprint.provider = None
        self.preprint.save()
        self.preprint.reload()

        assert_equal(self.preprint.provider, None)

    def test_find_provider(self):
        self.preprint.provider = self.provider
        self.preprint.save()
        self.preprint.reload()

        assert ('branded',
                self.provider) == find_preprint_provider(self.preprint.node)

    def test_top_level_subjects(self):
        subj_a = SubjectFactory(provider=self.provider, text='A')
        subj_b = SubjectFactory(provider=self.provider, text='B')
        subj_aa = SubjectFactory(provider=self.provider,
                                 text='AA',
                                 parent=subj_a)
        subj_ab = SubjectFactory(provider=self.provider,
                                 text='AB',
                                 parent=subj_a)
        subj_ba = SubjectFactory(provider=self.provider,
                                 text='BA',
                                 parent=subj_b)
        subj_bb = SubjectFactory(provider=self.provider,
                                 text='BB',
                                 parent=subj_b)
        subj_aaa = SubjectFactory(provider=self.provider,
                                  text='AAA',
                                  parent=subj_aa)

        some_other_provider = PreprintProviderFactory(name='asdfArxiv')
        subj_asdf = SubjectFactory(provider=some_other_provider)

        assert set(self.provider.top_level_subjects) == set([subj_a, subj_b])

    def test_all_subjects(self):
        subj_a = SubjectFactory(provider=self.provider, text='A')
        subj_b = SubjectFactory(provider=self.provider, text='B')
        subj_aa = SubjectFactory(provider=self.provider,
                                 text='AA',
                                 parent=subj_a)
        subj_ab = SubjectFactory(provider=self.provider,
                                 text='AB',
                                 parent=subj_a)
        subj_ba = SubjectFactory(provider=self.provider,
                                 text='BA',
                                 parent=subj_b)
        subj_bb = SubjectFactory(provider=self.provider,
                                 text='BB',
                                 parent=subj_b)
        subj_aaa = SubjectFactory(provider=self.provider,
                                  text='AAA',
                                  parent=subj_aa)

        some_other_provider = PreprintProviderFactory(name='asdfArxiv')
        subj_asdf = SubjectFactory(provider=some_other_provider)

        assert set(self.provider.all_subjects) == set(
            [subj_a, subj_b, subj_aa, subj_ab, subj_ba, subj_bb, subj_aaa])

    def test_highlighted_subjects(self):
        subj_a = SubjectFactory(provider=self.provider, text='A')
        subj_b = SubjectFactory(provider=self.provider, text='B')
        subj_aa = SubjectFactory(provider=self.provider,
                                 text='AA',
                                 parent=subj_a)
        subj_ab = SubjectFactory(provider=self.provider,
                                 text='AB',
                                 parent=subj_a)
        subj_ba = SubjectFactory(provider=self.provider,
                                 text='BA',
                                 parent=subj_b)
        subj_bb = SubjectFactory(provider=self.provider,
                                 text='BB',
                                 parent=subj_b)
        subj_aaa = SubjectFactory(provider=self.provider,
                                  text='AAA',
                                  parent=subj_aa)

        assert self.provider.has_highlighted_subjects is False
        assert set(self.provider.highlighted_subjects) == set([subj_a, subj_b])
        subj_aaa.highlighted = True
        subj_aaa.save()
        assert self.provider.has_highlighted_subjects is True
        assert set(self.provider.highlighted_subjects) == set([subj_aaa])
Beispiel #12
0
class TestPreprintServicePermissions(OsfTestCase):
    def setUp(self):
        super(TestPreprintServicePermissions, self).setUp()
        self.user = AuthUserFactory()
        self.write_contrib = AuthUserFactory()
        self.project = ProjectFactory(creator=self.user)
        self.project.add_contributor(self.write_contrib,
                                     permissions=[permissions.WRITE])

        self.preprint = PreprintFactory(project=self.project,
                                        is_published=False)

    def test_nonadmin_cannot_set_subjects(self):
        initial_subjects = list(self.preprint.subjects.all())
        with assert_raises(PermissionsError):
            self.preprint.set_subjects([[SubjectFactory()._id]],
                                       auth=Auth(self.write_contrib))

        self.preprint.reload()
        assert_equal(initial_subjects, list(self.preprint.subjects.all()))

    def test_nonadmin_cannot_set_file(self):
        initial_file = self.preprint.primary_file
        file = OsfStorageFile.create(node=self.project,
                                     path='/panda.txt',
                                     name='panda.txt',
                                     materialized_path='/panda.txt')
        file.save()

        with assert_raises(PermissionsError):
            self.preprint.set_primary_file(file,
                                           auth=Auth(self.write_contrib),
                                           save=True)

        self.preprint.reload()
        self.preprint.node.reload()
        assert_equal(initial_file._id, self.preprint.primary_file._id)

    def test_nonadmin_cannot_publish(self):
        assert_false(self.preprint.is_published)

        with assert_raises(PermissionsError):
            self.preprint.set_published(True,
                                        auth=Auth(self.write_contrib),
                                        save=True)

        assert_false(self.preprint.is_published)

    def test_admin_can_set_subjects(self):
        initial_subjects = list(self.preprint.subjects.all())
        self.preprint.set_subjects([[SubjectFactory()._id]],
                                   auth=Auth(self.user))

        self.preprint.reload()
        assert_not_equal(initial_subjects, list(self.preprint.subjects.all()))

    def test_admin_can_set_file(self):
        initial_file = self.preprint.primary_file
        file = OsfStorageFile.create(node=self.project,
                                     path='/panda.txt',
                                     name='panda.txt',
                                     materialized_path='/panda.txt')
        file.save()

        self.preprint.set_primary_file(file, auth=Auth(self.user), save=True)

        self.preprint.reload()
        self.preprint.node.reload()
        assert_not_equal(initial_file._id, self.preprint.primary_file._id)
        assert_equal(file._id, self.preprint.primary_file._id)

    def test_admin_can_publish(self):
        assert_false(self.preprint.is_published)

        self.preprint.set_published(True, auth=Auth(self.user), save=True)

        assert_true(self.preprint.is_published)

    def test_admin_cannot_unpublish(self):
        assert_false(self.preprint.is_published)

        self.preprint.set_published(True, auth=Auth(self.user), save=True)

        assert_true(self.preprint.is_published)

        with assert_raises(ValueError) as e:
            self.preprint.set_published(False, auth=Auth(self.user), save=True)

        assert_in('Cannot unpublish', e.exception.message)
Beispiel #13
0
class TestPreprintProvider(OsfTestCase):
    def setUp(self):
        super(TestPreprintProvider, self).setUp()
        self.preprint = PreprintFactory(provider=None, is_published=False)
        self.provider = PreprintProviderFactory(name='WWEArxiv')

    def test_add_provider(self):
        assert_not_equal(self.preprint.provider, self.provider)

        self.preprint.provider = self.provider
        self.preprint.save()
        self.preprint.reload()

        assert_equal(self.preprint.provider, self.provider)

    def test_remove_provider(self):
        self.preprint.provider = None
        self.preprint.save()
        self.preprint.reload()

        assert_equal(self.preprint.provider, None)

    def test_find_provider(self):
        self.preprint.provider = self.provider
        self.preprint.save()
        self.preprint.reload()

        assert ('branded', self.provider) == find_preprint_provider(self.preprint.node)

    def test_top_level_subjects(self):
        subj_a = SubjectFactory(provider=self.provider, text='A')
        subj_b = SubjectFactory(provider=self.provider, text='B')
        subj_aa = SubjectFactory(provider=self.provider, text='AA', parent=subj_a)
        subj_ab = SubjectFactory(provider=self.provider, text='AB', parent=subj_a)
        subj_ba = SubjectFactory(provider=self.provider, text='BA', parent=subj_b)
        subj_bb = SubjectFactory(provider=self.provider, text='BB', parent=subj_b)
        subj_aaa = SubjectFactory(provider=self.provider, text='AAA', parent=subj_aa)

        some_other_provider = PreprintProviderFactory(name='asdfArxiv')
        subj_asdf = SubjectFactory(provider=some_other_provider)

        assert set(self.provider.top_level_subjects) == set([subj_a, subj_b])

    def test_all_subjects(self):
        subj_a = SubjectFactory(provider=self.provider, text='A')
        subj_b = SubjectFactory(provider=self.provider, text='B')
        subj_aa = SubjectFactory(provider=self.provider, text='AA', parent=subj_a)
        subj_ab = SubjectFactory(provider=self.provider, text='AB', parent=subj_a)
        subj_ba = SubjectFactory(provider=self.provider, text='BA', parent=subj_b)
        subj_bb = SubjectFactory(provider=self.provider, text='BB', parent=subj_b)
        subj_aaa = SubjectFactory(provider=self.provider, text='AAA', parent=subj_aa)

        some_other_provider = PreprintProviderFactory(name='asdfArxiv')
        subj_asdf = SubjectFactory(provider=some_other_provider)


        assert set(self.provider.all_subjects) == set([subj_a, subj_b, subj_aa, subj_ab, subj_ba, subj_bb, subj_aaa])

    def test_highlighted_subjects(self):
        subj_a = SubjectFactory(provider=self.provider, text='A')
        subj_b = SubjectFactory(provider=self.provider, text='B')
        subj_aa = SubjectFactory(provider=self.provider, text='AA', parent=subj_a)
        subj_ab = SubjectFactory(provider=self.provider, text='AB', parent=subj_a)
        subj_ba = SubjectFactory(provider=self.provider, text='BA', parent=subj_b)
        subj_bb = SubjectFactory(provider=self.provider, text='BB', parent=subj_b)
        subj_aaa = SubjectFactory(provider=self.provider, text='AAA', parent=subj_aa)

        assert set(self.provider.highlighted_subjects) == set([subj_a, subj_b])
        subj_aaa.highlighted = True
        subj_aaa.save()
        assert set(self.provider.highlighted_subjects) == set([subj_aaa])
Beispiel #14
0
class TestPreprintServicePermissions(OsfTestCase):
    def setUp(self):
        super(TestPreprintServicePermissions, self).setUp()
        self.user = AuthUserFactory()
        self.write_contrib = AuthUserFactory()
        self.project = ProjectFactory(creator=self.user)
        self.project.add_contributor(self.write_contrib, permissions=[permissions.WRITE])

        self.preprint = PreprintFactory(project=self.project, is_published=False)


    def test_nonadmin_cannot_set_subjects(self):
        initial_subjects = list(self.preprint.subjects.all())
        with assert_raises(PermissionsError):
            self.preprint.set_subjects([[SubjectFactory()._id]], auth=Auth(self.write_contrib), save=True)

        self.preprint.reload()
        assert_equal(initial_subjects, list(self.preprint.subjects.all()))

    def test_nonadmin_cannot_set_file(self):
        initial_file = self.preprint.primary_file
        file = OsfStorageFile.create(
            node=self.project,
            path='/panda.txt',
            name='panda.txt',
            materialized_path='/panda.txt')
        file.save()

        with assert_raises(PermissionsError):
            self.preprint.set_primary_file(file, auth=Auth(self.write_contrib), save=True)

        self.preprint.reload()
        self.preprint.node.reload()
        assert_equal(initial_file._id, self.preprint.primary_file._id)

    def test_nonadmin_cannot_publish(self):
        assert_false(self.preprint.is_published)

        with assert_raises(PermissionsError):
            self.preprint.set_published(True, auth=Auth(self.write_contrib), save=True)

        assert_false(self.preprint.is_published)

    def test_admin_can_set_subjects(self):
        initial_subjects = list(self.preprint.subjects.all())
        self.preprint.set_subjects([[SubjectFactory()._id]], auth=Auth(self.user), save=True)

        self.preprint.reload()
        assert_not_equal(initial_subjects, list(self.preprint.subjects.all()))

    def test_admin_can_set_file(self):
        initial_file = self.preprint.primary_file
        file = OsfStorageFile.create(
            node=self.project,
            path='/panda.txt',
            name='panda.txt',
            materialized_path='/panda.txt')
        file.save()

        self.preprint.set_primary_file(file, auth=Auth(self.user), save=True)

        self.preprint.reload()
        self.preprint.node.reload()
        assert_not_equal(initial_file._id, self.preprint.primary_file._id)
        assert_equal(file._id, self.preprint.primary_file._id)

    def test_admin_can_publish(self):
        assert_false(self.preprint.is_published)

        self.preprint.set_published(True, auth=Auth(self.user), save=True)

        assert_true(self.preprint.is_published)

    def test_admin_cannot_unpublish(self):
        assert_false(self.preprint.is_published)

        self.preprint.set_published(True, auth=Auth(self.user), save=True)

        assert_true(self.preprint.is_published)

        with assert_raises(ValueError) as e:
            self.preprint.set_published(False, auth=Auth(self.user), save=True)

        assert_in('Cannot unpublish', e.exception.message)
class TestRemoveContributor(AdminTestCase):
    def setUp(self):
        super(TestRemoveContributor, self).setUp()
        self.user = AuthUserFactory()
        self.preprint = PreprintFactory(creator=self.user)
        self.user_2 = AuthUserFactory()
        self.preprint.add_contributor(self.user_2)
        self.preprint.save()
        self.view = views.PreprintRemoveContributorView
        self.request = RequestFactory().post('/fake_path')
        self.url = reverse('preprints:remove_user', kwargs={'guid': self.preprint._id, 'user_id': self.user._id})

    def test_get_object(self):
        view = setup_log_view(self.view(), self.request, guid=self.preprint._id,
                              user_id=self.user._id)
        preprint, user = view.get_object()
        assert isinstance(preprint, Preprint)
        assert isinstance(user, OSFUser)

    @mock.patch('admin.preprints.views.Preprint.remove_contributor')
    def test_remove_contributor(self, mock_remove_contributor):
        user_id = self.user_2._id
        preprint_id = self.preprint._id
        view = setup_log_view(self.view(), self.request, guid=preprint_id,
                              user_id=user_id)
        view.delete(self.request)
        mock_remove_contributor.assert_called_with(self.user_2, None, log=False)

    def test_integration_remove_contributor(self):
        assert self.user_2 in self.preprint.contributors
        view = setup_log_view(self.view(), self.request, guid=self.preprint._id,
                              user_id=self.user_2._id)
        count = AdminLogEntry.objects.count()
        view.delete(self.request)
        assert self.user_2 not in self.preprint.contributors
        assert AdminLogEntry.objects.count() == count + 1

    def test_do_not_remove_last_admin(self):
        assert len(list(self.preprint.get_admin_contributors(self.preprint.contributors))) == 1
        view = setup_log_view(self.view(), self.request, guid=self.preprint._id,
                              user_id=self.user._id)
        count = AdminLogEntry.objects.count()
        view.delete(self.request)
        self.preprint.reload()  # Reloads instance to show that nothing was removed
        assert len(list(self.preprint.contributors)) == 2
        assert len(list(self.preprint.get_admin_contributors(self.preprint.contributors))) == 1
        assert AdminLogEntry.objects.count() == count

    def test_no_log(self):
        view = setup_log_view(self.view(), self.request, guid=self.preprint._id,
                              user_id=self.user_2._id)
        view.delete(self.request)
        assert self.preprint.logs.latest().action != PreprintLog.CONTRIB_REMOVED

    def test_no_user_permissions_raises_error(self):
        request = RequestFactory().get(self.url)
        request.user = self.user

        with pytest.raises(PermissionDenied):
            self.view.as_view()(request, guid=self.preprint._id, user_id=self.user)

    def test_correct_view_permissions(self):
        change_permission = Permission.objects.get(codename='change_preprint')
        view_permission = Permission.objects.get(codename='view_preprint')
        self.user.user_permissions.add(change_permission)
        self.user.user_permissions.add(view_permission)
        self.user.save()

        request = RequestFactory().get(self.url)
        request.user = self.user

        response = self.view.as_view()(request, guid=self.preprint._id, user_id=self.user._id)
        assert response.status_code == 200
class TestPreprintUpdate(ApiTestCase):
    def setUp(self):
        super(TestPreprintUpdate, self).setUp()
        self.user = AuthUserFactory()

        self.preprint = PreprintFactory(creator=self.user)
        self.url = '/{}preprints/{}/'.format(API_BASE, self.preprint._id)

        self.subject = SubjectFactory()

    def test_update_preprint_permission_denied(self):
        update_doi_payload = build_preprint_update_payload(
            self.preprint._id, attributes={'article_doi': '10.123/456/789'})

        noncontrib = AuthUserFactory()

        res = self.app.patch_json_api(self.url,
                                      update_doi_payload,
                                      auth=noncontrib.auth,
                                      expect_errors=True)
        assert_equal(res.status_code, 403)

        res = self.app.patch_json_api(self.url,
                                      update_doi_payload,
                                      expect_errors=True)
        assert_equal(res.status_code, 401)

    def test_update_subjects(self):
        assert_not_equal(self.preprint.subjects[0], [self.subject._id])
        update_subjects_payload = build_preprint_update_payload(
            self.preprint._id, attributes={"subjects": [[self.subject._id]]})

        res = self.app.patch_json_api(self.url,
                                      update_subjects_payload,
                                      auth=self.user.auth)
        assert_equal(res.status_code, 200)

        self.preprint.reload()
        assert_equal(self.preprint.subjects[0], [self.subject._id])

    def test_update_invalid_subjects(self):
        subjects = self.preprint.subjects
        update_subjects_payload = build_preprint_update_payload(
            self.preprint._id, attributes={"subjects": [['wwe']]})

        res = self.app.patch_json_api(self.url,
                                      update_subjects_payload,
                                      auth=self.user.auth,
                                      expect_errors=True)
        assert_equal(res.status_code, 400)

        self.preprint.reload()
        assert_equal(self.preprint.subjects, subjects)

    def test_update_primary_file(self):
        new_file = test_utils.create_test_file(self.preprint.node,
                                               self.user,
                                               filename='openupthatwindow.pdf')
        relationships = {
            "primary_file": {
                "data": {
                    "type": "file",
                    "id": new_file._id
                }
            }
        }
        assert_not_equal(self.preprint.primary_file, new_file)
        update_file_payload = build_preprint_update_payload(
            self.preprint._id, relationships=relationships)

        res = self.app.patch_json_api(self.url,
                                      update_file_payload,
                                      auth=self.user.auth)
        assert_equal(res.status_code, 200)

        self.preprint.node.reload()
        assert_equal(self.preprint.primary_file.wrapped(), new_file)

        # check logs
        log = self.preprint.node.logs.latest()
        assert_equal(log.action, 'preprint_file_updated')
        assert_equal(log.params.get('preprint'), self.preprint._id)

    def test_new_primary_not_in_node(self):
        project = ProjectFactory()
        file_for_project = test_utils.create_test_file(
            project, self.user, filename='letoutthatantidote.pdf')

        relationships = {
            "primary_file": {
                "data": {
                    "type": "file",
                    "id": file_for_project._id
                }
            }
        }

        update_file_payload = build_preprint_update_payload(
            self.preprint._id, relationships=relationships)

        res = self.app.patch_json_api(self.url,
                                      update_file_payload,
                                      auth=self.user.auth,
                                      expect_errors=True)
        assert_equal(res.status_code, 400)

        self.preprint.reload()
        assert_not_equal(self.preprint.primary_file.wrapped(),
                         file_for_project)

    def test_update_doi(self):
        new_doi = '10.1234/ASDFASDF'
        assert_not_equal(self.preprint.article_doi, new_doi)
        update_subjects_payload = build_preprint_update_payload(
            self.preprint._id, attributes={"doi": new_doi})

        res = self.app.patch_json_api(self.url,
                                      update_subjects_payload,
                                      auth=self.user.auth)
        assert_equal(res.status_code, 200)

        self.preprint.node.reload()
        assert_equal(self.preprint.article_doi, new_doi)

        preprint_detail = self.app.get(self.url,
                                       auth=self.user.auth).json['data']
        assert_equal(preprint_detail['links']['doi'],
                     'https://dx.doi.org/{}'.format(new_doi))

    def test_write_contrib_cannot_set_primary_file(self):
        user_two = AuthUserFactory()
        self.preprint.node.add_contributor(user_two,
                                           permissions=['read', 'write'],
                                           auth=Auth(self.user),
                                           save=True)
        new_file = test_utils.create_test_file(self.preprint.node,
                                               self.user,
                                               filename='openupthatwindow.pdf')

        data = {
            'data': {
                'type': 'primary_file',
                'id': self.preprint._id,
                'attributes': {},
                'relationships': {
                    'primary_file': {
                        'data': {
                            'type': 'file',
                            'id': new_file._id
                        }
                    }
                }
            }
        }

        res = self.app.patch_json_api(self.url,
                                      data,
                                      auth=user_two.auth,
                                      expect_errors=True)
        assert_equal(res.status_code, 403)

    def test_noncontrib_cannot_set_primary_file(self):
        user_two = AuthUserFactory()
        new_file = test_utils.create_test_file(self.preprint.node,
                                               self.user,
                                               filename='openupthatwindow.pdf')

        data = {
            'data': {
                'type': 'primary_file',
                'id': self.preprint._id,
                'attributes': {},
                'relationships': {
                    'primary_file': {
                        'data': {
                            'type': 'file',
                            'id': new_file._id
                        }
                    }
                }
            }
        }

        res = self.app.patch_json_api(self.url,
                                      data,
                                      auth=user_two.auth,
                                      expect_errors=True)
        assert_equal(res.status_code, 403)

    def test_write_contrib_cannot_set_subjects(self):
        user_two = AuthUserFactory()
        self.preprint.node.add_contributor(user_two,
                                           permissions=['read', 'write'],
                                           auth=Auth(self.user),
                                           save=True)

        assert_not_equal(self.preprint.subjects[0][0], self.subject._id)
        update_subjects_payload = build_preprint_update_payload(
            self.preprint._id, attributes={"subjects": [[self.subject._id]]})

        res = self.app.patch_json_api(self.url,
                                      update_subjects_payload,
                                      auth=user_two.auth,
                                      expect_errors=True)
        assert_equal(res.status_code, 403)

        assert_not_equal(self.preprint.subjects[0], self.subject._id)

    def test_noncontrib_cannot_set_subjects(self):
        user_two = AuthUserFactory()
        self.preprint.node.add_contributor(user_two,
                                           permissions=['read', 'write'],
                                           auth=Auth(self.user),
                                           save=True)

        assert_not_equal(self.preprint.subjects[0][0], self.subject._id)

        update_subjects_payload = build_preprint_update_payload(
            self.preprint._id, attributes={"subjects": [[self.subject._id]]})

        res = self.app.patch_json_api(self.url,
                                      update_subjects_payload,
                                      auth=user_two.auth,
                                      expect_errors=True)
        assert_equal(res.status_code, 403)

        assert_not_equal(self.preprint.subjects[0], self.subject._id)

    def test_update_published(self):
        unpublished = PreprintFactory(creator=self.user, is_published=False)
        url = '/{}preprints/{}/'.format(API_BASE, unpublished._id)
        payload = build_preprint_update_payload(
            unpublished._id, attributes={'is_published': True})
        res = self.app.patch_json_api(url, payload, auth=self.user.auth)
        unpublished.reload()
        assert_true(unpublished.is_published)

    # Regression test for https://openscience.atlassian.net/browse/OSF-7630
    def test_update_published_does_not_send_contributor_added_for_inactive_users(
            self):
        unpublished = PreprintFactory(creator=self.user, is_published=False)
        unpublished.node.add_unregistered_contributor(fullname=fake.name(),
                                                      email=fake.email(),
                                                      auth=Auth(self.user),
                                                      save=True)
        url = '/{}preprints/{}/'.format(API_BASE, unpublished._id)
        payload = build_preprint_update_payload(
            unpublished._id, attributes={'is_published': True})
        with capture_signals() as captured:
            res = self.app.patch_json_api(url, payload, auth=self.user.auth)
            # Signal not sent, because contributor is not registered
            assert_false(captured[contributor_added])
class TestPreprintUpdateLicense(ApiTestCase):
    def setUp(self):
        super(TestPreprintUpdateLicense, self).setUp()

        ensure_licenses()

        self.admin_contributor = AuthUserFactory()
        self.rw_contributor = AuthUserFactory()
        self.read_contributor = AuthUserFactory()
        self.non_contributor = AuthUserFactory()

        self.preprint_provider = PreprintProviderFactory()
        self.preprint = PreprintFactory(creator=self.admin_contributor,
                                        provider=self.preprint_provider)

        self.preprint.node.add_contributor(self.rw_contributor,
                                           auth=Auth(self.admin_contributor))
        self.preprint.node.add_contributor(self.read_contributor,
                                           auth=Auth(self.admin_contributor),
                                           permissions=['read'])
        self.preprint.node.save()

        self.cc0_license = NodeLicense.find_one(
            Q('name', 'eq', 'CC0 1.0 Universal'))
        self.mit_license = NodeLicense.find_one(Q('name', 'eq', 'MIT License'))
        self.no_license = NodeLicense.find_one(Q('name', 'eq', 'No license'))

        self.preprint_provider.licenses_acceptable = [
            self.cc0_license, self.no_license
        ]
        self.preprint_provider.save()

        self.url = '/{}preprints/{}/'.format(API_BASE, self.preprint._id)

    def make_payload(self,
                     node_id,
                     license_id=None,
                     license_year=None,
                     copyright_holders=None):
        attributes = {}

        if license_year and copyright_holders:
            attributes = {
                'license_record': {
                    'year': license_year,
                    'copyright_holders': copyright_holders
                }
            }
        elif license_year:
            attributes = {'license_record': {'year': license_year}}
        elif copyright_holders:
            attributes = {
                'license_record': {
                    'copyright_holders': copyright_holders
                }
            }

        return {
            'data': {
                'id': node_id,
                'attributes': attributes,
                'relationships': {
                    'license': {
                        'data': {
                            'type': 'licenses',
                            'id': license_id
                        }
                    }
                }
            }
        } if license_id else {
            'data': {
                'id': node_id,
                'attributes': attributes
            }
        }

    def make_request(self, url, data, auth=None, expect_errors=False):
        return self.app.patch_json_api(url,
                                       data,
                                       auth=auth,
                                       expect_errors=expect_errors)

    def test_admin_update_license_with_invalid_id(self):
        data = self.make_payload(node_id=self.preprint._id,
                                 license_id='thisisafakelicenseid')

        assert_equal(self.preprint.license, None)

        res = self.make_request(self.url,
                                data,
                                auth=self.admin_contributor.auth,
                                expect_errors=True)
        assert_equal(res.status_code, 404)
        assert_equal(res.json['errors'][0]['detail'],
                     'Unable to find specified license.')

        self.preprint.reload()
        assert_equal(self.preprint.license, None)

    def test_admin_can_update_license(self):
        data = self.make_payload(node_id=self.preprint._id,
                                 license_id=self.cc0_license._id)

        assert_equal(self.preprint.license, None)

        res = self.make_request(self.url,
                                data,
                                auth=self.admin_contributor.auth)
        assert_equal(res.status_code, 200)
        self.preprint.reload()

        assert_equal(self.preprint.license.node_license, self.cc0_license)
        assert_equal(self.preprint.license.year, None)
        assert_equal(self.preprint.license.copyright_holders, [])

        # check logs
        log = self.preprint.node.logs.latest()
        assert_equal(log.action, 'preprint_license_updated')
        assert_equal(log.params.get('preprint'), self.preprint._id)

    def test_admin_can_update_license_record(self):
        data = self.make_payload(
            node_id=self.preprint._id,
            license_id=self.no_license._id,
            license_year='2015',
            copyright_holders=['Bojack Horseman, Princess Carolyn'])

        assert_equal(self.preprint.license, None)

        res = self.make_request(self.url,
                                data,
                                auth=self.admin_contributor.auth)
        assert_equal(res.status_code, 200)
        self.preprint.reload()

        assert_equal(self.preprint.license.node_license, self.no_license)
        assert_equal(self.preprint.license.year, '2015')
        assert_equal(self.preprint.license.copyright_holders,
                     ['Bojack Horseman, Princess Carolyn'])

    def test_rw_contributor_cannot_update_license(self):
        data = self.make_payload(node_id=self.preprint._id,
                                 license_id=self.cc0_license._id)

        res = self.make_request(self.url,
                                data,
                                auth=self.rw_contributor.auth,
                                expect_errors=True)
        assert_equal(res.status_code, 403)
        assert_equal(res.json['errors'][0]['detail'],
                     'User must be an admin to update a preprint.')

    def test_read_contributor_cannot_update_license(self):
        data = self.make_payload(node_id=self.preprint._id,
                                 license_id=self.cc0_license._id)

        res = self.make_request(self.url,
                                data,
                                auth=self.read_contributor.auth,
                                expect_errors=True)
        assert_equal(res.status_code, 403)
        assert_equal(res.json['errors'][0]['detail'],
                     'You do not have permission to perform this action.')

    def test_non_contributor_cannot_update_license(self):
        data = self.make_payload(node_id=self.preprint._id,
                                 license_id=self.cc0_license._id)

        res = self.make_request(self.url,
                                data,
                                auth=self.non_contributor.auth,
                                expect_errors=True)
        assert_equal(res.status_code, 403)
        assert_equal(res.json['errors'][0]['detail'],
                     'You do not have permission to perform this action.')

    def test_unauthenticated_user_cannot_update_license(self):
        data = self.make_payload(node_id=self.preprint._id,
                                 license_id=self.cc0_license._id)

        res = self.make_request(self.url, data, expect_errors=True)
        assert_equal(res.status_code, 401)
        assert_equal(res.json['errors'][0]['detail'],
                     'Authentication credentials were not provided.')

    def test_update_preprint_with_invalid_license_for_provider(self):
        data = self.make_payload(node_id=self.preprint._id,
                                 license_id=self.mit_license._id)

        assert_equal(self.preprint.license, None)

        res = self.make_request(self.url,
                                data,
                                auth=self.admin_contributor.auth,
                                expect_errors=True)
        assert_equal(res.status_code, 403)
        assert_equal(
            res.json['errors'][0]['detail'],
            'Invalid license chosen for {}'.format(
                self.preprint_provider.name))

    def test_update_preprint_with_existing_license_year_attribute_only(self):
        self.preprint.set_preprint_license(
            {
                'id': self.no_license.license_id,
                'year': '2014',
                'copyrightHolders': ['Diane', 'Mr. Peanut Butter']
            },
            Auth(self.admin_contributor),
        )
        self.preprint.save()

        assert_equal(self.preprint.license.node_license, self.no_license)
        assert_equal(self.preprint.license.year, '2014')
        assert_equal(self.preprint.license.copyright_holders,
                     ['Diane', 'Mr. Peanut Butter'])

        data = self.make_payload(node_id=self.preprint._id,
                                 license_year='2015')

        res = self.make_request(self.url,
                                data,
                                auth=self.admin_contributor.auth)
        assert_equal(res.status_code, 200)
        self.preprint.license.reload()

        assert_equal(self.preprint.license.node_license, self.no_license)
        assert_equal(self.preprint.license.year, '2015')
        assert_equal(self.preprint.license.copyright_holders,
                     ['Diane', 'Mr. Peanut Butter'])

    def test_update_preprint_with_existing_license_copyright_holders_attribute_only(
            self):
        self.preprint.set_preprint_license(
            {
                'id': self.no_license.license_id,
                'year': '2014',
                'copyrightHolders': ['Diane', 'Mr. Peanut Butter']
            },
            Auth(self.admin_contributor),
        )
        self.preprint.save()

        assert_equal(self.preprint.license.node_license, self.no_license)
        assert_equal(self.preprint.license.year, '2014')
        assert_equal(self.preprint.license.copyright_holders,
                     ['Diane', 'Mr. Peanut Butter'])

        data = self.make_payload(
            node_id=self.preprint._id,
            copyright_holders=['Bojack Horseman', 'Princess Carolyn'])

        res = self.make_request(self.url,
                                data,
                                auth=self.admin_contributor.auth)
        assert_equal(res.status_code, 200)
        self.preprint.license.reload()

        assert_equal(self.preprint.license.node_license, self.no_license)
        assert_equal(self.preprint.license.year, '2014')
        assert_equal(self.preprint.license.copyright_holders,
                     ['Bojack Horseman', 'Princess Carolyn'])

    def test_update_preprint_with_existing_license_relationship_only(self):
        self.preprint.set_preprint_license(
            {
                'id': self.no_license.license_id,
                'year': '2014',
                'copyrightHolders': ['Diane', 'Mr. Peanut Butter']
            },
            Auth(self.admin_contributor),
        )
        self.preprint.save()

        assert_equal(self.preprint.license.node_license, self.no_license)
        assert_equal(self.preprint.license.year, '2014')
        assert_equal(self.preprint.license.copyright_holders,
                     ['Diane', 'Mr. Peanut Butter'])

        data = self.make_payload(node_id=self.preprint._id,
                                 license_id=self.cc0_license._id)

        res = self.make_request(self.url,
                                data,
                                auth=self.admin_contributor.auth)
        assert_equal(res.status_code, 200)
        self.preprint.license.reload()

        assert_equal(self.preprint.license.node_license, self.cc0_license)
        assert_equal(self.preprint.license.year, '2014')
        assert_equal(self.preprint.license.copyright_holders,
                     ['Diane', 'Mr. Peanut Butter'])

    def test_update_preprint_with_existing_license_relationship_and_attributes(
            self):
        self.preprint.set_preprint_license(
            {
                'id': self.no_license.license_id,
                'year': '2014',
                'copyrightHolders': ['Diane', 'Mr. Peanut Butter']
            },
            Auth(self.admin_contributor),
            save=True)

        assert_equal(self.preprint.license.node_license, self.no_license)
        assert_equal(self.preprint.license.year, '2014')
        assert_equal(self.preprint.license.copyright_holders,
                     ['Diane', 'Mr. Peanut Butter'])

        data = self.make_payload(
            node_id=self.preprint._id,
            license_id=self.cc0_license._id,
            license_year='2015',
            copyright_holders=['Bojack Horseman', 'Princess Carolyn'])

        res = self.make_request(self.url,
                                data,
                                auth=self.admin_contributor.auth)
        assert_equal(res.status_code, 200)
        self.preprint.license.reload()

        assert_equal(self.preprint.license.node_license, self.cc0_license)
        assert_equal(self.preprint.license.year, '2015')
        assert_equal(self.preprint.license.copyright_holders,
                     ['Bojack Horseman', 'Princess Carolyn'])

    def test_update_preprint_license_without_required_year_in_payload(self):
        data = self.make_payload(node_id=self.preprint._id,
                                 license_id=self.no_license._id,
                                 copyright_holders=['Rick', 'Morty'])

        res = self.make_request(self.url,
                                data,
                                auth=self.admin_contributor.auth,
                                expect_errors=True)
        assert_equal(res.status_code, 400)
        assert_equal(res.json['errors'][0]['detail'],
                     'year must be specified for this license')

    def test_update_preprint_license_without_required_copyright_holders_in_payload_(
            self):
        data = self.make_payload(node_id=self.preprint._id,
                                 license_id=self.no_license._id,
                                 license_year='1994')

        res = self.make_request(self.url,
                                data,
                                auth=self.admin_contributor.auth,
                                expect_errors=True)
        assert_equal(res.status_code, 400)
        assert_equal(res.json['errors'][0]['detail'],
                     'copyrightHolders must be specified for this license')

    def test_update_preprint_license_does_not_change_project_license(self):
        self.preprint.node.set_node_license(
            {
                'id': self.no_license.license_id,
                'year': '2015',
                'copyrightHolders': ['Simba', 'Mufasa']
            },
            auth=Auth(self.admin_contributor))
        self.preprint.node.save()
        assert_equal(self.preprint.node.node_license.node_license,
                     self.no_license)

        data = self.make_payload(node_id=self.preprint._id,
                                 license_id=self.cc0_license._id)

        res = self.make_request(self.url,
                                data,
                                auth=self.admin_contributor.auth)
        assert_equal(res.status_code, 200)
        self.preprint.reload()

        assert_equal(self.preprint.license.node_license, self.cc0_license)
        assert_equal(self.preprint.node.node_license.node_license,
                     self.no_license)

    def test_update_preprint_license_without_change_does_not_add_log(self):
        self.preprint.set_preprint_license(
            {
                'id': self.no_license.license_id,
                'year': '2015',
                'copyrightHolders': ['Kim', 'Kanye']
            },
            auth=Auth(self.admin_contributor),
            save=True)

        before_num_logs = self.preprint.node.logs.count()
        before_update_log = self.preprint.node.logs.latest()

        data = self.make_payload(node_id=self.preprint._id,
                                 license_id=self.no_license._id,
                                 license_year='2015',
                                 copyright_holders=['Kanye', 'Kim'])
        res = self.make_request(self.url,
                                data,
                                auth=self.admin_contributor.auth)
        self.preprint.node.reload()

        after_num_logs = self.preprint.node.logs.count()
        after_update_log = self.preprint.node.logs.latest()

        assert_equal(res.status_code, 200)
        assert_equal(before_num_logs, after_num_logs)
        assert_equal(before_update_log._id, after_update_log._id)
Beispiel #18
0
class TestRemoveContributor(AdminTestCase):
    def setUp(self):
        super(TestRemoveContributor, self).setUp()
        self.user = AuthUserFactory()
        self.preprint = PreprintFactory(creator=self.user)
        self.user_2 = AuthUserFactory()
        self.preprint.add_contributor(self.user_2)
        self.preprint.save()
        self.view = views.PreprintRemoveContributorView
        self.request = RequestFactory().post('/fake_path')
        self.url = reverse('preprints:remove-user',
                           kwargs={
                               'guid': self.preprint._id,
                               'user_id': self.user._id
                           })

    def test_remove_contributor(self):
        user_id = self.user_2.id
        preprint_id = self.preprint._id
        view = setup_log_view(self.view(),
                              self.request,
                              guid=preprint_id,
                              user_id=user_id)
        view.post(self.request)
        assert not self.preprint.contributors.filter(id=user_id)

    def test_integration_remove_contributor(self):
        assert self.user_2 in self.preprint.contributors
        view = setup_log_view(self.view(),
                              self.request,
                              guid=self.preprint._id,
                              user_id=self.user_2.id)
        count = AdminLogEntry.objects.count()
        view.post(self.request)
        assert self.user_2 not in self.preprint.contributors
        assert AdminLogEntry.objects.count() == count + 1

    def test_do_not_remove_last_admin(self):
        assert len(
            list(
                self.preprint.get_admin_contributors(
                    self.preprint.contributors))) == 1
        view = setup_log_view(self.view(),
                              self.request,
                              guid=self.preprint._id,
                              user_id=self.user.id)
        count = AdminLogEntry.objects.count()
        patch_messages(self.request)
        view.post(self.request)
        self.preprint.reload(
        )  # Reloads instance to show that nothing was removed
        assert len(list(self.preprint.contributors)) == 2
        assert len(
            list(
                self.preprint.get_admin_contributors(
                    self.preprint.contributors))) == 1
        assert AdminLogEntry.objects.count() == count

    def test_no_log(self):
        view = setup_log_view(self.view(),
                              self.request,
                              guid=self.preprint._id,
                              user_id=self.user_2.id)
        view.post(self.request)
        assert self.preprint.logs.latest(
        ).action != PreprintLog.CONTRIB_REMOVED
Beispiel #19
0
class TestRemoveContributor(AdminTestCase):
    def setUp(self):
        super(TestRemoveContributor, self).setUp()
        self.user = AuthUserFactory()
        self.preprint = PreprintFactory(creator=self.user)
        self.user_2 = AuthUserFactory()
        self.preprint.add_contributor(self.user_2)
        self.preprint.save()
        self.view = views.PreprintRemoveContributorView
        self.request = RequestFactory().post('/fake_path')
        self.url = reverse('preprints:remove_user', kwargs={'guid': self.preprint._id, 'user_id': self.user._id})

    def test_get_object(self):
        view = setup_log_view(self.view(), self.request, guid=self.preprint._id,
                              user_id=self.user._id)
        preprint, user = view.get_object()
        assert isinstance(preprint, Preprint)
        assert isinstance(user, OSFUser)

    @mock.patch('admin.preprints.views.Preprint.remove_contributor')
    def test_remove_contributor(self, mock_remove_contributor):
        user_id = self.user_2._id
        preprint_id = self.preprint._id
        view = setup_log_view(self.view(), self.request, guid=preprint_id,
                              user_id=user_id)
        view.delete(self.request)
        mock_remove_contributor.assert_called_with(self.user_2, None, log=False)

    def test_integration_remove_contributor(self):
        assert self.user_2 in self.preprint.contributors
        view = setup_log_view(self.view(), self.request, guid=self.preprint._id,
                              user_id=self.user_2._id)
        count = AdminLogEntry.objects.count()
        view.delete(self.request)
        assert self.user_2 not in self.preprint.contributors
        assert AdminLogEntry.objects.count() == count + 1

    def test_do_not_remove_last_admin(self):
        assert len(list(self.preprint.get_admin_contributors(self.preprint.contributors))) == 1
        view = setup_log_view(self.view(), self.request, guid=self.preprint._id,
                              user_id=self.user._id)
        count = AdminLogEntry.objects.count()
        view.delete(self.request)
        self.preprint.reload()  # Reloads instance to show that nothing was removed
        assert len(list(self.preprint.contributors)) == 2
        assert len(list(self.preprint.get_admin_contributors(self.preprint.contributors))) == 1
        assert AdminLogEntry.objects.count() == count

    def test_no_log(self):
        view = setup_log_view(self.view(), self.request, guid=self.preprint._id,
                              user_id=self.user_2._id)
        view.delete(self.request)
        assert self.preprint.logs.latest().action != PreprintLog.CONTRIB_REMOVED

    def test_no_user_permissions_raises_error(self):
        request = RequestFactory().get(self.url)
        request.user = self.user

        with pytest.raises(PermissionDenied):
            self.view.as_view()(request, guid=self.preprint._id, user_id=self.user)

    def test_correct_view_permissions(self):
        change_permission = Permission.objects.get(codename='change_preprint')
        view_permission = Permission.objects.get(codename='view_preprint')
        self.user.user_permissions.add(change_permission)
        self.user.user_permissions.add(view_permission)
        self.user.save()

        request = RequestFactory().get(self.url)
        request.user = self.user

        response = self.view.as_view()(request, guid=self.preprint._id, user_id=self.user._id)
        assert response.status_code == 200