Ejemplo n.º 1
0
 def test_composer_detail_multi_submitted(self):
     """Composer shows its own page if multiple foias"""
     foia = FOIARequestFactory(
         composer__status='submitted',
         composer__datetime_submitted=timezone.now(),
     )
     FOIARequestFactory(composer=foia.composer)
     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, 200)
     eq_(response.template_name, ['foia/foiacomposer_detail.html'])
Ejemplo n.º 2
0
    def test_normal(self):
        """Test a normal succesful response"""

        foia = FOIARequestFactory(status="ack")
        from_name = "Smith, Bob"
        from_email = "*****@*****.**"
        from_ = '"%s" <%s>' % (from_name, from_email)
        to_ = '%s, "Doe, John" <*****@*****.**>' % foia.get_request_email()
        subject = "Test subject"
        text = "Test normal."
        signature = "-Charlie Jones"

        self.mailgun_route(from_, to_, subject, text, signature)
        foia.refresh_from_db()

        last_comm = foia.communications.last()
        nose.tools.eq_(last_comm.communication, "%s\n%s" % (text, signature))
        nose.tools.eq_(last_comm.subject, subject)
        nose.tools.eq_(last_comm.from_user, foia.agency.get_user())
        nose.tools.eq_(last_comm.to_user, foia.user)
        nose.tools.eq_(last_comm.response, True)
        nose.tools.eq_(last_comm.full_html, False)
        nose.tools.ok_(last_comm.get_raw_email())
        nose.tools.eq_(last_comm.responsetask_set.count(), 1)
        nose.tools.eq_(foia.email, EmailAddress.objects.fetch(from_email))
        nose.tools.eq_(
            set(foia.cc_emails.all()),
            set(EmailAddress.objects.fetch_many("*****@*****.**")),
        )
        nose.tools.eq_(foia.status, "processed")
Ejemplo n.º 3
0
 def test_clone_multi(self, mock_upload):
     """Should duplicate the communication to each request in the list."""
     first_foia = FOIARequestFactory()
     second_foia = FOIARequestFactory()
     third_foia = FOIARequestFactory()
     comm_count = FOIACommunication.objects.count()
     clones = self.comm.clone(
         [first_foia, second_foia, third_foia],
         self.user,
     )
     # + 3 communications
     eq_(
         FOIACommunication.objects.count(), comm_count + 3,
         'Should clone the request twice.'
     )
     ok_(
         clones[0].pk is not clones[1].pk is not clones[2].pk,
         'The returned list should contain unique communcation objects.'
     )
     # a move log should be generated for each cloned request
     for clone in clones:
         ok_(
             CommunicationMoveLog.objects.filter(
                 communication=clone,
                 foia=self.comm.foia,
                 user=self.user,
             ).exists()
         )
     mock_upload.assert_called()
Ejemplo n.º 4
0
 def test_foia_followup_estimated(self):
     """If request has an estimated date, returns number of days until the estimated date"""
     # pylint: disable=protected-access
     num_days = 365
     foia = FOIARequestFactory(date_estimate=date.today() +
                               timedelta(num_days))
     nose.tools.eq_(foia._followup_days(), num_days)
Ejemplo n.º 5
0
 def test_composer_detail_single_submitted(self):
     """Composer redirects to foia page if only a single request even
     if it hasn't been filed yet"""
     foia = FOIARequestFactory(
         composer__status='submitted',
         composer__datetime_submitted=timezone.now(),
     )
     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())
Ejemplo n.º 6
0
    def test_foia_list_user(self):
        """Test the foia-list-user view"""

        users = UserFactory.create_batch(2)
        FOIARequestFactory.create_batch(4, composer__user=users[0])
        FOIARequestFactory.create_batch(3, composer__user=users[1])

        for user in users:
            response = get_allowed(
                self.client,
                reverse('foia-list-user', kwargs={
                    'user_pk': user.pk,
                })
            )
            nose.tools.eq_(
                set(response.context['object_list']),
                set(
                    FOIARequest.objects.get_viewable(AnonymousUser())
                    .filter(composer__user=user)
                )
            )
            nose.tools.ok_(
                all(
                    foia.user == user
                    for foia in response.context['object_list']
                )
            )
Ejemplo n.º 7
0
    def test_bad_verify(self):
        """Test an improperly signed message"""

        foia = FOIARequestFactory(block_incoming=True)
        to_ = foia.get_request_email()
        response = self.mailgun_route(to_=to_, sign=False)
        nose.tools.eq_(response.status_code, 403)
Ejemplo n.º 8
0
    def setUp(self):
        """Set up tests"""

        mail.outbox = []

        self.foia = FOIARequestFactory(status='submitted', title='Test 1')
        UserFactory(username='******')
Ejemplo n.º 9
0
 def setUp(self):
     self.foia1 = FOIARequestFactory()
     self.foia2 = FOIARequestFactory()
     self.comm = FOIACommunicationFactory(foia=self.foia1)
     self.file = FOIAFileFactory(comm=self.comm)
     eq_(self.comm.files.count(), 1)
     self.user = UserFactory()
Ejemplo n.º 10
0
    def setUp(self):
        """Set up tests"""

        mail.outbox = []

        self.foia = FOIARequestFactory(status="submitted", title="Test 1")
        UserFactory(username="******")
Ejemplo n.º 11
0
 def setUp(self):
     agency = AgencyFactory()
     self.owner = UserFactory()
     self.follower = UserFactory()
     self.request = FOIARequestFactory(composer__user=self.owner,
                                       agency=agency)
     follow(self.follower, self.request)
     self.action = new_action(agency, "completed", target=self.request)
Ejemplo n.º 12
0
 def setUp(self):
     self.foia = FOIARequestFactory(status='payment')
     self.url = reverse('foia-crowdfund',
                        args=(self.foia.jurisdiction.slug,
                              self.foia.jurisdiction.id, self.foia.slug,
                              self.foia.id))
     self.request_factory = RequestFactory()
     self.view = crowdfund_request
Ejemplo n.º 13
0
    def test_foia_viewable(self):
        """Test all the viewable and embargo functions"""

        user1 = UserFactory()
        user2 = UserFactory()

        foias = [
            FOIARequestFactory(
                composer__user=user1,
                status='done',
                embargo=False,
            ),
            FOIARequestFactory(
                composer__user=user1,
                status='done',
                embargo=True,
            ),
            FOIARequestFactory(
                composer__user=user1,
                status='done',
                embargo=True,
            ),
        ]
        foias[2].add_viewer(user2)

        # check manager get_viewable against view permission
        viewable_foias = FOIARequest.objects.get_viewable(user1)
        for foia in FOIARequest.objects.all():
            if foia in viewable_foias:
                nose.tools.assert_true(foia.has_perm(user1, 'view'))
            else:
                nose.tools.assert_false(foia.has_perm(user1, 'view'))

        viewable_foias = FOIARequest.objects.get_viewable(user2)
        for foia in FOIARequest.objects.all():
            if foia in viewable_foias:
                nose.tools.assert_true(foia.has_perm(user2, 'view'))
            else:
                nose.tools.assert_false(foia.has_perm(user2, 'view'))

        viewable_foias = FOIARequest.objects.get_public()
        for foia in FOIARequest.objects.all():
            if foia in viewable_foias:
                nose.tools.assert_true(foia.has_perm(AnonymousUser(), 'view'))
            else:
                nose.tools.assert_false(foia.has_perm(AnonymousUser(), 'view'))

        nose.tools.assert_true(foias[0].has_perm(user1, 'view'))
        nose.tools.assert_true(foias[1].has_perm(user1, 'view'))
        nose.tools.assert_true(foias[2].has_perm(user1, 'view'))

        nose.tools.assert_true(foias[0].has_perm(user2, 'view'))
        nose.tools.assert_false(foias[1].has_perm(user2, 'view'))
        nose.tools.assert_true(foias[2].has_perm(user2, 'view'))

        nose.tools.assert_true(foias[0].has_perm(AnonymousUser(), 'view'))
        nose.tools.assert_false(foias[1].has_perm(AnonymousUser(), 'view'))
        nose.tools.assert_false(foias[2].has_perm(AnonymousUser(), 'view'))
Ejemplo n.º 14
0
class TestCommunication(test.TestCase):
    """Tests communication methods"""

    def setUp(self):
        self.foia = FOIARequestFactory()
        self.comm = FOIACommunicationFactory(
            foia=self.foia,
            email__from_email=EmailAddress.objects.
            fetch(u'Test Email <*****@*****.**>'),
        )
        self.file = FOIAFileFactory(comm=self.comm)
        eq_(self.comm.files.count(), 1)

    def test_primary_contact(self):
        """Makes the primary email of the FOIA to the email the communication was sent from."""
        self.comm.make_sender_primary_contact()
        self.foia.refresh_from_db()
        eq_(self.foia.email, self.comm.emails.first().from_email)

    def test_attach_file_with_file(self):
        """Test attaching a file with an actual file"""
        comm = FOIACommunicationFactory()
        file_ = open('tmp.txt', 'w')
        file_.write('The file contents')
        file_.close()
        file_ = open('tmp.txt', 'r')
        comm.attach_file(file_=file_)
        file_.close()
        os.remove('tmp.txt')
        eq_(comm.files.count(), 1)
        foia_file = comm.files.first()
        eq_(foia_file.title, 'tmp')
        eq_(foia_file.ffile.file.name, 'tmp.txt')
        eq_(foia_file.ffile.read(), 'The file contents')

    def test_attach_file_with_content(self):
        """Test attaching a file with n memory content"""
        comm = FOIACommunicationFactory()
        comm.attach_file(content='More contents', name='doc.pdf')
        eq_(comm.files.count(), 1)
        foia_file = comm.files.first()
        eq_(foia_file.title, 'doc')
        eq_(foia_file.ffile.file.name, 'doc.pdf')
        eq_(foia_file.ffile.read(), 'More contents')

    @raises(ValueError)
    def test_orphan_error(self):
        """Orphans should raise an error"""
        self.comm.foia = None
        self.comm.make_sender_primary_contact()

    @raises(ValueError)
    def test_bad_sender_error(self):
        """Comms with bad sender email should raise an error"""
        email = self.comm.emails.first()
        email.from_email = None
        email.save()
        self.comm.make_sender_primary_contact()
Ejemplo n.º 15
0
    def test_get_viewable_edit_collaborator(self):
        """Test get viewable for an edit collaborator"""

        foia = FOIARequestFactory(composer__status="filed", embargo=True)
        foia.add_editor(self.user)

        assert_true(FOIAComposer.objects.get_viewable(self.staff).exists())
        assert_true(FOIAComposer.objects.get_viewable(self.user).exists())
        assert_false(FOIAComposer.objects.get_viewable(self.anon).exists())
Ejemplo n.º 16
0
    def test_get_viewable_partial_embargoed(self):
        """Test get viewable for a partially embargoed composer"""

        foia = FOIARequestFactory(composer__status="filed", embargo=True)
        FOIARequestFactory(composer=foia.composer, embargo=False)

        assert_true(FOIAComposer.objects.get_viewable(self.staff).exists())
        assert_true(FOIAComposer.objects.get_viewable(self.user).exists())
        assert_true(FOIAComposer.objects.get_viewable(self.anon).exists())
Ejemplo n.º 17
0
 def setUp(self):
     self.foia = FOIARequestFactory()
     self.comm = FOIACommunicationFactory(
         foia=self.foia,
         email__from_email=EmailAddress.objects.
         fetch(u'Test Email <*****@*****.**>'),
     )
     self.file = FOIAFileFactory(comm=self.comm)
     eq_(self.comm.files.count(), 1)
Ejemplo n.º 18
0
 def test_fee_rate(self):
     """
     Jurisdictions should report the rate at which requests have fees.
     State jurisdictions should include fee rates of local jurisdictions.
     """
     FOIARequestFactory(agency__jurisdiction=self.state, status="ack", price=0)
     FOIARequestFactory(agency__jurisdiction=self.local, status="ack", price=1.00)
     eq_(self.state.fee_rate(), 50.0)
     eq_(self.local.fee_rate(), 100.0)
Ejemplo n.º 19
0
 def test_requests(self):
     """Projects should keep a list of relevant FOIA requests."""
     request1 = FOIARequestFactory()
     request2 = FOIARequestFactory()
     self.project.requests.add(request1, request2)
     ok_(request1 in self.project.requests.all())
     ok_(request2 in self.project.requests.all())
     self.project.articles.clear()
     eq_(len(self.project.articles.all()), 0)
Ejemplo n.º 20
0
 def test_multi_clone(self):
     """Test cloning a multirequest"""
     foia = FOIARequestFactory(composer__status="filed", embargo=False)
     FOIARequestFactory(composer=foia.composer)
     form = BaseComposerForm(
         {"action": "save", "parent": foia.composer.pk, "tags": ""},
         user=foia.composer.user,
         request=None,
     )
     ok_(form.is_valid())
Ejemplo n.º 21
0
    def test_soft_delete(self):
        """Test the soft delete method"""
        foia = FOIARequestFactory(status="processed")
        FOIAFileFactory.create_batch(size=3, comm__foia=foia)
        user = UserFactory(is_superuser=True)

        nose.tools.eq_(foia.get_files().count(), 3)
        nose.tools.eq_(
            RawEmail.objects.filter(email__communication__foia=foia).count(),
            3)

        foia.soft_delete(user, "final message", "note")
        foia.refresh_from_db()
        self.run_commit_hooks()

        # final communication we send out is not cleared
        for comm in list(foia.communications.all())[:-1]:
            nose.tools.eq_(comm.communication, "")
        nose.tools.eq_(foia.get_files().count(), 0)
        # one raw email left on the final outgoing message
        nose.tools.eq_(
            RawEmail.objects.filter(email__communication__foia=foia).count(),
            1)
        nose.tools.eq_(foia.last_request().communication, "final message")
        nose.tools.eq_(foia.notes.first().note, "note")

        nose.tools.ok_(foia.deleted)
        nose.tools.ok_(foia.embargo)
        nose.tools.ok_(foia.permanent_embargo)
        nose.tools.eq_(foia.status, "abandoned")
Ejemplo n.º 22
0
    def test_bad_strip(self):
        """Test an improperly stripped message"""

        foia = FOIARequestFactory()
        to_ = foia.get_request_email()
        text = ""
        body = "Here is the full body."
        self.mailgun_route(to_=to_, text=text, body=body)

        last_comm = foia.communications.last()
        nose.tools.eq_(last_comm.communication, body)
Ejemplo n.º 23
0
 def test_success_rate(self):
     """
     Jurisdictions should report their success rate: completed/filed.
     State jurisdictions should include success rates of local jurisdictions.
     """
     FOIARequestFactory(
         agency__jurisdiction=self.state, status="done", datetime_done=timezone.now()
     )
     FOIARequestFactory(agency__jurisdiction=self.local, status="ack")
     eq_(self.state.success_rate(), 50.0)
     eq_(self.local.success_rate(), 0.0)
Ejemplo n.º 24
0
 def test_move(self):
     """Should move the communication to the listed requests and create a
     ResponseTask for each new communication.
     """
     foia1 = FOIARequestFactory()
     foia2 = FOIARequestFactory()
     foia3 = FOIARequestFactory()
     count_response_tasks = ResponseTask.objects.count()
     self.task.move([foia1.pk, foia2.pk, foia3.pk], self.user)
     eq_(ResponseTask.objects.count(), count_response_tasks + 3,
         'Reponse tasks should be created for each communication moved.')
Ejemplo n.º 25
0
 def test_reject(self):
     replacement = AgencyFactory()
     existing_foia = FOIARequestFactory(agency=self.agency)
     self.task.reject(replacement)
     existing_foia.refresh_from_db()
     eq_(self.task.agency.status, 'rejected',
         'Rejecting a new agency should leave it unapproved.')
     eq_(
         existing_foia.agency, replacement,
         'The replacement agency should receive the rejected agency\'s requests.'
     )
 def test_access_key(self):
     """Editors should be able to generate a secure access key to view an embargoed request."""
     embargoed_foia = FOIARequestFactory(embargo=True)
     access_key = embargoed_foia.generate_access_key()
     nose.tools.assert_true(
         access_key == embargoed_foia.access_key,
         'The key in the URL should match the key saved to the request.')
     embargoed_foia.generate_access_key()
     nose.tools.assert_false(
         access_key == embargoed_foia.access_key,
         'After regenerating the link, the key should no longer match.')
Ejemplo n.º 27
0
    def test_get_viewable_read_collaborator(self):
        """Test get viewable for a read collaborator"""

        foia = FOIARequestFactory(
            composer__status='filed',
            embargo=True,
        )
        foia.add_viewer(self.user)

        assert_true(FOIAComposer.objects.get_viewable(self.staff).exists())
        assert_true(FOIAComposer.objects.get_viewable(self.user).exists())
        assert_false(FOIAComposer.objects.get_viewable(self.anon).exists())
Ejemplo n.º 28
0
 def setUp(self):
     self.factory = RequestFactory()
     self.foia = FOIARequestFactory()
     self.creator = self.foia.user
     self.editor = UserFactory()
     self.viewer = UserFactory()
     self.staff = UserFactory(is_staff=True)
     self.normie = UserFactory()
     self.foia.add_editor(self.editor)
     self.foia.add_viewer(self.viewer)
     self.foia.save()
     UserFactory(username='******')
Ejemplo n.º 29
0
 def setUp(self):
     agency = AgencyFactory(appeal_agency=AppealAgencyFactory())
     self.foia = FOIARequestFactory(agency=agency)
     self.view = Detail.as_view()
     self.url = self.foia.get_absolute_url()
     self.kwargs = {
         'jurisdiction': self.foia.jurisdiction.slug,
         'jidx': self.foia.jurisdiction.id,
         'slug': self.foia.slug,
         'idx': self.foia.id
     }
     UserFactory(username='******')
Ejemplo n.º 30
0
 def setUp(self):
     agency = AgencyFactory(appeal_agency=AppealAgencyFactory())
     self.foia = FOIARequestFactory(agency=agency)
     self.view = Detail.as_view()
     self.url = self.foia.get_absolute_url()
     self.kwargs = {
         "jurisdiction": self.foia.jurisdiction.slug,
         "jidx": self.foia.jurisdiction.id,
         "slug": self.foia.slug,
         "idx": self.foia.id,
     }
     UserFactory(username="******")