def test_get_choices(self): """Test the get choices queryset method""" crowdsource = CrowdsourceFactory() data = CrowdsourceDataFactory.create_batch( 3, crowdsource=crowdsource, ) user = crowdsource.user limit = 2 # all data should be valid choices eq_( set(crowdsource.data.get_choices(limit, user)), set(data), ) # if I respond to one, it is no longer a choice for me CrowdsourceResponseFactory( crowdsource=crowdsource, user=crowdsource.user, data=data[0], ) eq_( set(crowdsource.data.get_choices(limit, user)), set(data[1:]), ) # if one has at least `limit` responses, it is no longer a valid choice CrowdsourceResponseFactory.create_batch( 2, crowdsource=crowdsource, data=data[1], ) eq_( set(crowdsource.data.get_choices(limit, user)), set(data[2:]), ) # multiple responses from the same user only count once new_user = UserFactory() CrowdsourceResponseFactory.create_batch( 2, crowdsource=crowdsource, data=data[2], user=new_user, ) eq_( set(crowdsource.data.get_choices(limit, user)), set(data[2:]), )
def test_tags(self): """Test bulk add tags""" user = UserFactory() foia = FOIARequestFactory(composer__user=user) MyRequestList()._tags( FOIARequest.objects.filter(pk=foia.pk), user, QueryDict("tags=red&tags=blue"), ) foia.refresh_from_db() tags = [t.name for t in foia.tags.all()] assert_in("red", tags) assert_in("blue", tags)
def test_promote_viewer(self): """Editors should be able to promote viewers to editors.""" user = UserFactory() self.foia.add_viewer(user) assert_true(self.foia.has_viewer(user)) data = {'action': 'promote', 'user': user.pk} request = self.factory.post(self.foia.get_absolute_url(), data) request = mock_middleware(request) request.user = self.editor response = Detail.as_view()(request, jurisdiction=self.foia.jurisdiction.slug, jidx=self.foia.jurisdiction.id, slug=self.foia.slug, idx=self.foia.id) eq_(response.status_code, 302) assert_false(self.foia.has_viewer(user)) assert_true(self.foia.has_editor(user))
def test_add_contributors(self, mock_notify): """When adding contributors, each new contributor should get an email notification.""" new_contributor = UserFactory() data = { "title": self.project.title, "contributors": [self.contributor.pk, new_contributor.pk], "tags": "", } form = forms.ProjectUpdateForm(data, instance=self.project) ok_(form.is_valid(), "The form should validate. %s" % form.errors) http_post_response(self.url, self.view, data, self.contributor, **self.kwargs) self.project.refresh_from_db() ok_(self.project.has_contributor(new_contributor)) ok_(self.project.has_contributor(self.contributor)) mock_notify.assert_called_once_with( new_contributor.pk, self.project.pk, self.contributor.pk )
def test_revoke_view_access(self): """Editors should be able to revoke access from a viewer.""" a_viewer = UserFactory() self.foia.add_viewer(a_viewer) data = {'action': 'revoke_access', 'user': a_viewer.pk} request = self.factory.post(self.foia.get_absolute_url(), data) request = mock_middleware(request) request.user = self.editor response = Detail.as_view()( request, jurisdiction=self.foia.jurisdiction.slug, jidx=self.foia.jurisdiction.id, slug=self.foia.slug, idx=self.foia.id ) eq_(response.status_code, 302) assert_false(self.foia.has_viewer(a_viewer))
def test_unfollow(self): """Test bulk unfollowing""" follow_foia = FOIARequestFactory() unfollow_foia = FOIARequestFactory() user = UserFactory() follow(user, follow_foia, actor_only=False) RequestList()._unfollow( FOIARequest.objects.filter( pk__in=[follow_foia.pk, unfollow_foia.pk]), user, {}, ) assert_false(is_following(user, follow_foia)) assert_false(is_following(user, unfollow_foia))
def test_extend_embargo(self): """Test bulk embargo extending""" tomorrow = date.today() + timedelta(1) next_month = date.today() + timedelta(30) user = UserFactory(profile__acct_type='pro') other_foia = FOIARequestFactory() public_foia = FOIARequestFactory( composer__user=user, embargo=False, status='ack', ) embargo_foia = FOIARequestFactory( composer__user=user, embargo=True, status='ack', ) embargo_done_foia = FOIARequestFactory( composer__user=user, embargo=True, status='done', date_embargo=tomorrow, ) MyRequestList()._extend_embargo( FOIARequest.objects.filter(pk__in=[ other_foia.pk, public_foia.pk, embargo_foia.pk, embargo_done_foia.pk, ]), user, {}, ) other_foia.refresh_from_db() public_foia.refresh_from_db() embargo_foia.refresh_from_db() embargo_done_foia.refresh_from_db() assert_false(other_foia.embargo) ok_(public_foia.embargo) assert_is_none(public_foia.date_embargo) ok_(embargo_foia.embargo) assert_is_none(embargo_foia.date_embargo) ok_(embargo_done_foia.embargo) eq_(embargo_done_foia.date_embargo, next_month)
def test_tags(self): """Test bulk add tags""" user = UserFactory() foia = FOIARequestFactory(composer__user=user) MyRequestList()._tags( FOIARequest.objects.filter(pk=foia.pk), user, {'tags': 'red, blue'}, ) foia.refresh_from_db() tags = [t.name for t in foia.tags.all()] assert_in('red', tags) assert_in('blue', tags)
def test_digest_user_questions(self): """Digests should include information on questions I asked.""" # generate an action on a question the user asked question = QuestionFactory(user=self.user) other_user = UserFactory() AnswerFactory(user=other_user, question=question) # creating an answer _should_ have created a notification # so let's generate the email and see what happened email = self.digest(user=self.user, interval=self.interval) eq_( email.activity["count"], 1, "There should be activity that is not user initiated.", ) eq_(email.activity["questions"]["mine"].first().action.actor, other_user) eq_(email.activity["questions"]["mine"].first().action.verb, "answered") eq_(email.send(), 1, "The email should send.")
def test_project_admin_can_view(self): """Project admin can view a crowdsource's details""" project = ProjectFactory() crowdsource = CrowdsourceFactory(project_admin=True, project=project) url = reverse('crowdsource-detail', kwargs={ 'slug': crowdsource.slug, 'idx': crowdsource.pk }) request = self.request_factory.get(url) request = mock_middleware(request) request.user = UserFactory() project.contributors.add(request.user) response = self.view(request, slug=crowdsource.slug, idx=crowdsource.pk) eq_(response.status_code, 200)
def test_revoke_edit_access(self): """Editors should be able to revoke access from an editor.""" an_editor = UserFactory() self.foia.add_editor(an_editor) data = {"action": "revoke_access", "user": an_editor.pk} request = self.factory.post(self.foia.get_absolute_url(), data) request = mock_middleware(request) request.user = self.editor response = Detail.as_view()( request, jurisdiction=self.foia.jurisdiction.slug, jidx=self.foia.jurisdiction.id, slug=self.foia.slug, idx=self.foia.id, ) eq_(response.status_code, 302) assert_false(self.foia.has_editor(an_editor))
def test_autofollowup_off(self): """Test bulk autofollowup disabling""" user = UserFactory() on_foia = FOIARequestFactory(composer__user=user, disable_autofollowups=False) off_foia = FOIARequestFactory(composer__user=user, disable_autofollowups=True) MyRequestList()._autofollowup_off( FOIARequest.objects.filter(pk__in=[on_foia.pk, off_foia.pk]), user, {}) on_foia.refresh_from_db() off_foia.refresh_from_db() ok_(on_foia.disable_autofollowups) ok_(off_foia.disable_autofollowups)
def test_report_spam(self): """Test reporting spam""" answer = AnswerFactory() url = reverse('question-spam', kwargs={ 'model': 'answer', 'model_pk': answer.pk, }) request = RequestFactory().get(url) request = mock_middleware(request) request.user = UserFactory() nose.tools.ok_(answer.user.is_active) report_spam(request, 'answer', answer.pk) answer.refresh_from_db() nose.tools.ok_(answer.user.is_active) nose.tools.eq_(len(mail.outbox), 1)
def test_boilerplate(self): """Test the boilerplate ajax view""" agencies = AgencyFactory.create_batch(2) request = RequestFactory().get( reverse('agency-boilerplate'), { 'agencies': [a.pk for a in agencies], }, ) request = mock_middleware(request) request.user = UserFactory(first_name='John', last_name='Doe') response = boilerplate(request) eq_(response.status_code, 200) data = json.loads(response.content) assert_in('{ law name }', data['intro']) assert_in('{ days }', data['outro']) assert_in('John Doe', data['outro'])
def test_perm_embargo(self): """Test bulk permanent embargo""" tomorrow = date.today() + timedelta(1) user = UserFactory(profile__acct_type='admin') other_foia = FOIARequestFactory() public_foia = FOIARequestFactory( composer__user=user, embargo=False, status='ack', ) embargo_foia = FOIARequestFactory( composer__user=user, embargo=True, status='ack', ) embargo_done_foia = FOIARequestFactory( composer__user=user, embargo=True, status='done', date_embargo=tomorrow, ) MyRequestList()._perm_embargo( FOIARequest.objects.filter(pk__in=[ other_foia.pk, public_foia.pk, embargo_foia.pk, embargo_done_foia.pk, ]), user, {}, ) other_foia.refresh_from_db() public_foia.refresh_from_db() embargo_foia.refresh_from_db() embargo_done_foia.refresh_from_db() assert_false(other_foia.embargo) ok_(public_foia.embargo) assert_false(public_foia.permanent_embargo) ok_(embargo_foia.embargo) assert_false(embargo_foia.permanent_embargo) ok_(embargo_done_foia.embargo) ok_(embargo_done_foia.permanent_embargo)
def test_flagged_object(self): """A flagged task should be able to return its object.""" text = 'Lorem ipsum' user = UserFactory() foia = FOIARequestFactory() agency = AgencyFactory() jurisdiction = StateJurisdictionFactory() flagged_foia_task = self.task.objects.create(user=user, foia=foia, text=text) flagged_agency_task = self.task.objects.create(user=user, agency=agency, text=text) flagged_jurisdiction_task = self.task.objects.create( user=user, jurisdiction=jurisdiction, text=text) eq_(flagged_foia_task.flagged_object(), foia) eq_(flagged_agency_task.flagged_object(), agency) eq_(flagged_jurisdiction_task.flagged_object(), jurisdiction)
def test_block_user(self): """Test blocking a user""" question = QuestionFactory() url = reverse('question-block', kwargs={ 'model': 'question', 'model_pk': question.pk, }) request = RequestFactory().get(url) request = mock_middleware(request) request.user = UserFactory(is_staff=True) nose.tools.ok_(question.user.is_active) block_user(request, 'question', question.pk) question.user.refresh_from_db() print 'question user', question.user.pk, question.user.username nose.tools.assert_false(question.user.is_active) nose.tools.eq_(len(mail.outbox), 1)
def test_unauthorized_appeal(self): """Appealing a request without permission should not do anything.""" unauth_user = UserFactory() comm_count = self.foia.communications.count() previous_status = self.foia.status data = {'action': 'appeal', 'text': 'Lorem ipsum'} http_post_response( self.url, self.view, data, unauth_user, **self.kwargs ) self.foia.refresh_from_db() eq_( self.foia.status, previous_status, 'The status of the request should not be changed.' ) eq_( self.foia.communications.count(), comm_count, 'No communication should be added to the request.' )
def test_get_question(self): """Try getting the detail page for a Question with an unread notification.""" question = QuestionFactory() view = QuestionDetail.as_view() # Create a notification for the question action = new_action(UserFactory(), 'answered', target=question) notification = notify(self.user, action)[0] ok_(not notification.read, 'The notification should be unread.') # Try getting the view as the user response = http_get_response(question.get_absolute_url(), view, self.user, pk=question.pk, slug=question.slug) eq_(response.status_code, 200, 'The view should respond 200 OK.') # Check that the notification has been read. notification.refresh_from_db() ok_(notification.read, 'The notification should be marked as read.')
def test_composer_detail_private(self): """Composer is private if no viewable foias""" foia = FOIARequestFactory( embargo=True, date_embargo=date.today() + timedelta(1), composer__status="filed", ) composer = foia.composer request = self.request_factory.get( reverse( "foia-composer-detail", kwargs={ "slug": composer.slug, "idx": composer.pk }, )) request.user = UserFactory() request = mock_middleware(request) ComposerDetail.as_view()(request, slug=composer.slug, idx=composer.pk)
def test_news_archive_author(self): """Should return all articles for the given author""" author = UserFactory() ArticleFactory.create_batch( 3, publish=True, authors=[author], pub_date=timezone.now() - timedelta(1), ) response = get_allowed( self.client, reverse('news-author', kwargs={ 'username': author.username }) ) eq_( len(response.context['object_list']), Article.objects.filter(authors=author).count() )
def test_following_request_list(self): """Test to make sure following request list shows correct requests""" user = UserFactory() factory = RequestFactory() request = factory.get(reverse('foia-list-following')) request.user = user foias = FOIARequestFactory.create_batch(7) for foia in foias[::2]: follow(user, foia) response = FollowingRequestList.as_view()(request) eq_(len(response.context_data['object_list']), 4) for foia in foias[::2]: nose.tools.assert_in(foia, response.context_data['object_list']) unfollow(user, foias[2]) response = FollowingRequestList.as_view()(request) eq_(len(response.context_data['object_list']), 3) for foia in (foias[0], foias[4], foias[6]): nose.tools.assert_in(foia, response.context_data['object_list'])
def test_composer_detail_draft_bad(self): """Composer detail view redirects to update page if draft""" composer = FOIAComposerFactory(status='started') request = self.request_factory.get( reverse( 'foia-composer-detail', kwargs={ 'slug': composer.slug, 'idx': composer.pk } ) ) request.user = UserFactory() request = mock_middleware(request) ComposerDetail.as_view()( request, slug=composer.slug, idx=composer.pk, )
def test_action_views(self): """Test action views""" UserFactory(username='******', password='******') self.client.login(username='******', password='******') foia = FOIARequestFactory(status='payment') get_allowed( self.client, reverse( 'foia-pay', kwargs={ 'jurisdiction': foia.jurisdiction.slug, 'jidx': foia.jurisdiction.pk, 'idx': foia.pk, 'slug': foia.slug } ) )
def test_composer_detail_single(self): """Composer redirects to foia page if only a single request""" foia = FOIARequestFactory(composer__status='filed') composer = foia.composer request = self.request_factory.get( reverse('foia-composer-detail', kwargs={ 'slug': composer.slug, 'idx': composer.pk })) request.user = UserFactory() request = mock_middleware(request) response = ComposerDetail.as_view()( request, slug=composer.slug, idx=composer.pk, ) eq_(response.status_code, 302) eq_(response.url, foia.get_absolute_url())
def test_post(self): """Posting data for a crowdfund should create it.""" user = UserFactory(is_staff=True) name = "Project Crowdfund" description = "A crowdfund" payment_required = 100 payment_capped = True date_due = date.today() + timedelta(20) data = { "name": name, "description": description, "payment_required": payment_required, "payment_capped": payment_capped, "date_due": date_due, } request = self.request_factory.post(self.url, data) request.user = user request = mock_middleware(request) response = self.view(request, slug=self.project.slug, pk=self.project.pk) self.project.refresh_from_db() eq_( self.project.crowdfunds.count(), 1, "A crowdfund should be created and added to the project.", ) crowdfund = self.project.crowdfunds.first() eq_(crowdfund.name, name) eq_(crowdfund.description, description) expected_payment_required = ( Decimal(payment_required + payment_required * 0.15) / 100 ) eq_( crowdfund.payment_required, expected_payment_required, "Expected payment of %(expected).2f, actually %(actual).2f" % { "expected": expected_payment_required, "actual": crowdfund.payment_required, }, ) eq_(crowdfund.payment_capped, payment_capped) eq_(crowdfund.date_due, date_due) eq_(response.status_code, 302)
def test_suggest_requests(self): """ Projects should recommend requests to be added to them. They should recommend requests that intersect both the project's set of contributors and the project's set of tags. But projects should not recommend requests that they already contain. """ # set up data tags = u'a' user = UserFactory() self.project.contributors.add(user) self.project.tags.add(tags) test_request = FOIARequestFactory(composer__user=user) test_request.tags.add(tags) # since they have the same user and tags, the project should suggest the request ok_(test_request in self.project.suggest_requests()) # add the request to the project, then try again. it should not be suggested self.project.requests.add(test_request) ok_(test_request not in self.project.suggest_requests())
def test_get_choices(self): """Test the get choices queryset method""" crowdsource = CrowdsourceFactory() data = CrowdsourceDataFactory.create_batch(4, crowdsource=crowdsource) user = crowdsource.user ip_address = "127.0.0.1" limit = 2 # all data should be valid choices eq_(set(crowdsource.data.get_choices(limit, user, None)), set(data)) # if I respond to one, it is no longer a choice for me CrowdsourceResponseFactory(crowdsource=crowdsource, user=crowdsource.user, data=data[0]) eq_(set(crowdsource.data.get_choices(limit, user, None)), set(data[1:])) # if one has at least `limit` responses, it is no longer a valid choice CrowdsourceResponseFactory.create_batch(2, crowdsource=crowdsource, data=data[1]) eq_(set(crowdsource.data.get_choices(limit, user, None)), set(data[2:])) # multiple responses from the same user only count once new_user = UserFactory() CrowdsourceResponseFactory(crowdsource=crowdsource, user=new_user, data=data[2], number=1) CrowdsourceResponseFactory(crowdsource=crowdsource, user=new_user, data=data[2], number=2) eq_(set(crowdsource.data.get_choices(limit, user, None)), set(data[2:])) # if I anonymously to one, it is no longer a choice for me CrowdsourceResponseFactory(crowdsource=crowdsource, ip_address=ip_address, data=data[3]) eq_( set(crowdsource.data.get_choices(limit, None, ip_address)), set([data[0], data[2]]), )
def test_post(self): """Posting a valid ProjectForm should create the project.""" form = forms.ProjectCreateForm({ 'title': 'Cool Project', 'summary': 'Yo my project is cooler than LIFE!', 'image': test_image, 'tags': 'dogs, cats', 'private': True, 'featured': True }) ok_(form.is_valid(), 'The form should validate.') staff_user = UserFactory(is_staff=True) response = http_post_response(self.url, self.view, form.data, staff_user) project = models.Project.objects.last() eq_(response.status_code, 302, 'The response should redirect to the project when it is created.') ok_( staff_user in project.contributors.all(), 'The current user should automatically be added as a contributor.')
def test_suggest_articles(self): """ Projects should recommend articles to be added to them. They should recommend articles that intersect both the project's set of contributors and the project's set of tags. But projects should not recommend articles that they already contain. """ # set up data tags = u'a' user = UserFactory() self.project.contributors.add(user) self.project.tags.add(tags) test_article = ArticleFactory() test_article.authors.add(user) test_article.tags.add(tags) # since they have the same user and tags, the project should suggest the article. ok_(test_article in self.project.suggest_articles()) # add the article to the project, then try again. it should not be suggested self.project.articles.add(test_article) ok_(test_article not in self.project.suggest_articles())