class TestResultUnassignedUITargetsMidlineEndline(test.TestCase):
    """
    A result is unassigned because its "date collected" falls outside of the program period AND
    targets are midline/endline or event

    When a result is unassigned AND targets are Midline/Endline or Event, the following are true:

    1. The result is displayed in the table.
    2. Under the table, we display error message: This record is not associated with a target.
       Open the data record and select an option from the "Measure against target" menu.
    """

    def setUp(self):
        self.program = ProgramFactory(
            reporting_period_start=datetime.date(2018, 1, 1),
            reporting_period_end=datetime.date(2019, 1, 1),
        )
        self.indicator = IndicatorFactory(
            program=self.program,
            target_frequency=Indicator.MID_END,
        )
        PeriodicTargetFactory(
            indicator=self.indicator,
            start_date=datetime.date(2018, 1, 1),
            end_date=datetime.date(2018, 12, 31),
        )
        self.result = ResultFactory(
            indicator=self.indicator,
            date_collected=datetime.date(2017, 1, 1),
            achieved=42,
            record_name='My Test Record',
            evidence_url='http://my_evidence_url',
        )
        self.count = 1
        self.count += str(self.indicator.pk).count('42') * 2
        self.count += str(self.indicator.name).count('42')
        self.count += str(self.result.pk).count('42')
        self.user = UserFactory(first_name="FN", last_name="LN", username="******", is_superuser=True)
        self.user.set_password('password')
        self.user.save()
        self.tola_user = TolaUserFactory(user=self.user)
        self.client.login(username='******', password='******')

    def test_result_table_html(self):
        url = reverse_lazy('result_view', args=[self.indicator.id,])
        response = self.client.get(url)
        # result is displayed
        self.assertContains(
            response,
            'Jan 1, 2017',
        )
        self.assertContains(
            response, '42', count=self.count, msg_prefix=response.content.decode('utf-8')
        )
        # expected warning message
        self.assertContains(
            response,
            "This record is not associated with a target. Open the data record and select "\
            "an option from the “Measure against target” menu."
        )
class TestProjectUserAccess(test.TestCase):
    def setUp(self):
        super(TestProjectUserAccess, self).setUp()

        # create and login user
        self.user = UserFactory(first_name="FN",
                                last_name="LN",
                                username="******")
        self.user.set_password('password')
        self.user.save()

        self.tola_user = TolaUserFactory(user=self.user)

        self.client.login(username="******", password='******')

        self.afghanistan = CountryFactory(country='Afghanistan', code='AF')

    def test_can_access_projects_countries(self):
        self.assertEquals(self.tola_user.allow_projects_access, False)

        self.tola_user.countries.add(self.afghanistan)

        self.assertEquals(self.tola_user.allow_projects_access, True)

    def test_can_access_projects_country(self):
        self.assertEquals(self.tola_user.allow_projects_access, False)

        # Tola user defaults to US for country in factory
        self.tola_user.country = self.afghanistan
        self.tola_user.save()

        self.assertEquals(self.tola_user.allow_projects_access, True)
Example #3
0
class TestProfileUpdates(test.TestCase):
    def setUp(self):
        super(TestProfileUpdates, self).setUp()

        self.afghanistan = CountryFactory(country='Afghanistan', code='AF')
        self.myanmar = CountryFactory(country='Myanmar', code='MM')
        self.usa = CountryFactory(country='United States', code='US')

        self.user = UserFactory(first_name="FN",
                                last_name="LN",
                                username="******")
        self.user.set_password('password')
        self.user.save()
        self.tola_user = TolaUserFactory(user=self.user, country=self.usa)
        self.af_access = CountryAccessFactory(country=self.afghanistan,
                                              tolauser=self.tola_user)
        self.us_access = CountryAccessFactory(country=self.usa,
                                              tolauser=self.tola_user)
        self.tola_user.countryaccess_set.add(self.af_access, self.us_access)
        self.tola_user.save()

        self.countries_assigned = {self.afghanistan.id, self.usa.id}

    def test_superuser_can_save(self):
        self.user.is_superuser = True
        self.user.is_staff = True
        self.user.save()

        client = test.Client()
        client.login(username="******", password='******')

        response = client.post(reverse('profile'),
                               data={
                                   'language': 'fr',
                                   'submit': 'Save + changes'
                               })
        self.tola_user.refresh_from_db()

        self.assertEquals(response.status_code, 302)
        self.assertEquals(self.tola_user.language, 'fr')

    def test_user_can_save(self):
        self.user.is_superuser = False
        self.user.is_staff = False
        self.user.save()

        client = test.Client()
        client.login(username="******", password='******')

        response = client.post(reverse('profile'),
                               data={
                                   'language': 'fr',
                                   'submit': 'Save + changes'
                               })
        self.tola_user.refresh_from_db()

        self.assertEquals(response.status_code, 302)
        self.assertEquals(self.tola_user.language, 'fr')
Example #4
0
class TestIPTTTargetPeriodsReportResponseBase(test.TestCase):
    indicator_frequency = Indicator.LOP

    def setUp(self):

        self.user = UserFactory(first_name="FN",
                                last_name="LN",
                                username="******",
                                is_superuser=True)
        self.user.set_password('password')
        self.user.save()

        self.tola_user = TolaUserFactory(user=self.user)
        self.tola_user.save()

        self.client = test.Client(enforce_csrf_checks=False)
        self.client.login(username='******', password='******')
        self.response = None
        startdate = datetime.strptime('2017-02-04', '%Y-%m-%d')
        enddate = datetime.strptime('2019-10-01', '%Y-%m-%d')
        self.program = ProgramFactory(reporting_period_start=startdate,
                                      reporting_period_end=enddate)

    def tearDown(self):
        Indicator.objects.all().delete()
        self.response = None

    def get_indicator_for_program(self, **kwargs):
        make_kwargs = {'program': self.program}
        make_kwargs.update(kwargs)
        indicator = IndicatorFactory(**make_kwargs)
        return indicator

    def get_indicator_by_frequency(self, frequency, **kwargs):
        kwargs['target_frequency'] = frequency
        return self.get_indicator_for_program(**kwargs)

    def get_response(self,
                     target_frequency=None,
                     reporttype=IPTT_Mixin.REPORT_TYPE_TARGETPERIODS):
        target_frequency = self.indicator_frequency if target_frequency is None else target_frequency
        response = self.client.post(
            '/indicators/iptt_report/{program}/{reporttype}/'.format(
                program=self.program.id, reporttype=reporttype), {
                    'targetperiods': target_frequency,
                    'csrfmiddlewaretoken': 'asfd',
                    'program': self.program.id
                },
            follow=True)
        self.assertEqual(
            response.status_code, 200,
            "response gave status code {0} instead of 200".format(
                response.status_code))
        self.response = IPTTResponse(response.content)
        return self.response

    def format_assert_message(self, msg):
        return "{0}:\n{1}".format(self.response, msg)
Example #5
0
class CrudTest(TestCase):
    def setUp(self):
        self.c = Client()
        self.u = UserFactory(is_staff=True)
        self.u.set_password("test")
        self.u.save()
        # need to make the user have at least one group
        g = Group.objects.create(name=self.u.username)
        g.user_set.add(self.u)
        g.save()
        self.c.login(username=self.u.username, password="******")

    def test_category_crud(self):
        r = self.c.get("/")
        self.assertFalse("test category" in r.content)
        r = self.c.post("/category/add/", {'name': 'test category'})
        self.assertEqual(r.status_code, 302)
        r = self.c.get("/")
        self.assertTrue("test category" in r.content)
        category = Category.objects.get(name="test category")
        r = self.c.post("/category/%d/delete/" % category.id, dict())
        self.assertEqual(r.status_code, 302)
        r = self.c.get("/")
        self.assertFalse("test category" in r.content)

    def test_application_crud(self):
        c = CategoryFactory()
        r = self.c.get(c.get_absolute_url())
        self.assertFalse("test application" in r.content)
        r = self.c.post(c.get_absolute_url() + "add_application/",
                        {'name': 'test application'})
        self.assertEqual(r.status_code, 302)
        r = self.c.get(c.get_absolute_url())
        self.assertTrue("test application" in r.content)

    def test_deployment_crud(self):
        a = ApplicationFactory()
        r = self.c.get(a.get_absolute_url())
        self.assertFalse("test deployment" in r.content)
        r = self.c.post(a.get_absolute_url() + "add_deployment/",
                        {'name': 'test deployment'})
        self.assertEqual(r.status_code, 302)
        r = self.c.get(a.get_absolute_url())
        self.assertTrue("test deployment" in r.content)

    def test_setting_crud(self):
        d = DeploymentFactory()
        d.add_editor(self.u)
        r = self.c.get(d.get_absolute_url())
        self.assertFalse("test setting" in r.content)
        r = self.c.post(d.get_absolute_url() + "add_setting/", {
            'name': 'test setting',
            'value': 'test value'
        })
        self.assertEqual(r.status_code, 302)
        r = self.c.get(d.get_absolute_url())
        self.assertTrue("test setting" in r.content)
Example #6
0
class LoginTest(TestCase):
    def test_root(self):
        self.c = Client()
        self.u = UserFactory()
        self.u.set_password("test")
        self.u.save()

        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/")
        self.assertEquals(response.status_code, 200)
Example #7
0
class LoginTest(TestCase):
    def test_root(self):
        self.c = Client()
        self.u = UserFactory()
        self.u.set_password("test")
        self.u.save()

        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/")
        self.assertEquals(response.status_code, 200)
Example #8
0
 def test_delete_if_correct_user(self):
   new_user = UserFactory()
   new_user.set_password('asdf')
   new_user.save()
   total_users = User.objects.count()
   self.client.login(username=new_user.username, password='******')
   response = self.client.post(reverse('users:destroy', kwargs={'pk': new_user.pk}), {'_method': 'delete'})
   
   self.assertRedirects(response, reverse('home'))
   self.assertEqual(User.objects.count(), total_users - 1)
Example #9
0
class CrudTest(TestCase):
    def setUp(self):
        self.c = Client()
        self.u = UserFactory(is_staff=True)
        self.u.set_password("test")
        self.u.save()
        # need to make the user have at least one group
        g = Group.objects.create(name=self.u.username)
        g.user_set.add(self.u)
        g.save()
        self.c.login(username=self.u.username, password="******")

    def test_category_crud(self):
        r = self.c.get("/")
        self.assertFalse("test category" in r.content)
        r = self.c.post("/category/add/", {'name': 'test category'})
        self.assertEqual(r.status_code, 302)
        r = self.c.get("/")
        self.assertTrue("test category" in r.content)
        category = Category.objects.get(name="test category")
        r = self.c.post("/category/%d/delete/" % category.id, dict())
        self.assertEqual(r.status_code, 302)
        r = self.c.get("/")
        self.assertFalse("test category" in r.content)

    def test_application_crud(self):
        c = CategoryFactory()
        r = self.c.get(c.get_absolute_url())
        self.assertFalse("test application" in r.content)
        r = self.c.post(c.get_absolute_url() + "add_application/",
                        {'name': 'test application'})
        self.assertEqual(r.status_code, 302)
        r = self.c.get(c.get_absolute_url())
        self.assertTrue("test application" in r.content)

    def test_deployment_crud(self):
        a = ApplicationFactory()
        r = self.c.get(a.get_absolute_url())
        self.assertFalse("test deployment" in r.content)
        r = self.c.post(a.get_absolute_url() + "add_deployment/",
                        {'name': 'test deployment'})
        self.assertEqual(r.status_code, 302)
        r = self.c.get(a.get_absolute_url())
        self.assertTrue("test deployment" in r.content)

    def test_setting_crud(self):
        d = DeploymentFactory()
        d.add_editor(self.u)
        r = self.c.get(d.get_absolute_url())
        self.assertFalse("test setting" in r.content)
        r = self.c.post(d.get_absolute_url() + "add_setting/",
                        {'name': 'test setting', 'value': 'test value'})
        self.assertEqual(r.status_code, 302)
        r = self.c.get(d.get_absolute_url())
        self.assertTrue("test setting" in r.content)
class TestResultUnassignedUITargetsNotSetup(test.TestCase):
    """
    When a result is unassigned because no targets are set up, the following are true:

    1. The result is displayed in the table.
    2. Under the table, we display error message: Targets are not set up for this indicator.
    """
    def setUp(self):
        self.program = ProgramFactory(
            reporting_period_start=datetime.date(2018, 1, 1),
            reporting_period_end=datetime.date(2019, 1, 1),
        )
        self.indicator = IndicatorFactory(
            program=self.program,
            target_frequency=Indicator.MID_END,
        )
        self.result = ResultFactory(
            indicator=self.indicator,
            date_collected=datetime.date(2017, 1, 1),
            achieved=42,
            record_name='My Test Record',
            evidence_url='http://my_evidence_url',
        )
        self.count = 1
        self.count += str(self.indicator.pk).count('42') * 3
        self.count += str(self.indicator.name).count('42')
        self.count += str(self.result.pk).count('42')
        self.user = UserFactory(first_name="FN",
                                last_name="LN",
                                username="******",
                                is_superuser=True)
        self.user.set_password('password')
        self.user.save()
        self.tola_user = TolaUserFactory(user=self.user)
        self.client.login(username='******', password='******')

    def test_result_table_html(self):
        url = reverse_lazy('result_view', args=[
            self.indicator.id,
        ])
        response = self.client.get(url)
        # result is displayed
        self.assertContains(
            response,
            'Jan 1, 2017',
        )
        self.assertContains(response,
                            '42',
                            count=self.count,
                            msg_prefix=response.content.decode('utf-8'))
        # expected warning message
        self.assertContains(response,
                            'Targets are not set up for this indicator.')
Example #11
0
class TestSurelink(TestCase):
    def setUp(self):
        self.u = UserFactory()
        self.u.set_password("bar")
        self.u.save()
        self.c = Client()
        self.c.login(username=self.u.username, password="******")

    def test_surelink_form(self):
        response = self.c.get("/surelink/")
        self.assertEquals(response.status_code, 200)

    def test_surelink_with_files(self):
        response = self.c.get("/surelink/", dict(files="foo.mp4"))
        self.assertEquals(response.status_code, 200)

    def test_file_surelink_form(self):
        f = FileFactory()
        response = self.c.get("/file/%d/" % f.id)
        self.assertEquals(response.status_code, 200)

        response = self.c.get("/file/%d/surelink/" % f.id)
        self.assertEquals(response.status_code, 200)

    def test_file_surelink_public_stream(self):
        """ regression test for PMT #87084 """
        public_file = FileFactory(
            filename=("/media/h264/ccnmtl/public/"
                      "courses/56d27944-4131-11e1-8164-0017f20ea192"
                      "-Mediathread_video_uploaded_by_mlp55.mp4"))
        response = self.c.get("/file/%d/" % public_file.id)
        self.assertEquals(response.status_code, 200)

        response = self.c.get(
            "/file/%d/surelink/" % public_file.id,
            {'file': public_file.filename,
             'captions': '',
             'poster': ('http://wardenclyffe.ccnmtl.columbia.edu/'
                        'uploads/images/11213/00000238.jpg'),
             'width': public_file.guess_width(),
             'height': public_file.guess_height(),
             'protection': 'mp4_public_stream',
             'authtype': '',
             'player': 'v4',
             })
        self.assertEquals(response.status_code, 200)
        assert "<iframe" in response.content
        assert "file=/media/h264/ccnmtl/" not in response.content
        assert "file=/course" in response.content
class TestIPTTTimePeriodReportsI18N(iptt_utility.TestIPTTTimePeriodsReportResponseBase):
    """
    Check all time periods against in all languages
    """
    test_time_periods = [
        Indicator.ANNUAL,
        Indicator.SEMI_ANNUAL,
        Indicator.TRI_ANNUAL,
        Indicator.QUARTERLY,
        Indicator.MONTHLY,
    ]

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

        self.set_dates('2016-06-01', '2018-05-30')

        # create indicators w/ collected data
        self.add_indicator_with_data(Indicator.MONTHLY, [100]*24)

        # create and login user (defaulted to 'en' language)
        self.user = UserFactory(first_name="FN", last_name="LN", username="******")
        self.user.set_password('password')
        self.user.save()

        self.tola_user = TolaUserFactory(user=self.user)

        self.client.login(username="******", password='******')

    def _set_user_language(self, language):
        self.tola_user.language = language
        self.tola_user.save()

    def test_iptt_report_requests_in_all_languages(self):
        for language in TEST_LANGUAGES:
            self._set_user_language(language)

            for time_period in self.test_time_periods:
                self.request_params['timeperiods'] = time_period

                url = reverse('iptt_report', args=[self.program.id, IPTT_Mixin.REPORT_TYPE_TIMEPERIODS])

                # lack of exception is a win!
                response = self.client.post(url,
                                            self.request_params,
                                            follow=True)
                self.assertEqual(response.status_code, 200,
                                 "response gave status code {0} instead of 200".format(response.status_code))
Example #13
0
 def test_if_not_correct_user(self):
   wrong_user = UserFactory()
   wrong_user.set_password('asdf')
   wrong_user.save()
   self.client.login(username=wrong_user.username, password='******')
   detail_response = self.client.get(reverse('users:show', kwargs={'pk': self.user.pk}))
   data = {
     'first_name': 'Attempted change',
     'last_name': ':):)',
     'email': '*****@*****.**',
     '_method': 'put',
   }
   update_response = self.client.post(reverse('users:update', kwargs={'pk': self.user.pk}), data)
   delete_response = self.client.post(reverse('users:destroy', kwargs={'pk': self.user.pk}), {'_method': 'delete'})
   
   self.assertEqual(update_response.status_code, 403)
   self.assertEqual(delete_response.status_code, 403)
Example #14
0
class ApiTest(TestCase):
    def setUp(self):
        self.c = Client()
        self.u = UserFactory()
        self.u.set_password("test")
        self.u.save()
        self.c.login(username=self.u.username, password="******")

    def test_plain_getkey(self):
        response = self.c.get("/api/1.0/get_key/")
        assert "<h2>Get API Key</h2>" in response.content

        # no ip specified, so there should be a form
        assert ("Alternatively, you can enter an IP address "
                "here and get a key") in response.content

    def test_key_for_other_ip(self):
        response = self.c.get("/api/1.0/get_key/?ip=128.59.1.1")
        assert ("This key is for the specified IP "
                "Address (128.59.1.1)") in response.content
Example #15
0
class ApiTest(TestCase):
    def setUp(self):
        self.c = Client()
        self.u = UserFactory()
        self.u.set_password("test")
        self.u.save()
        self.c.login(username=self.u.username, password="******")

    def test_plain_getkey(self):
        response = self.c.get("/api/1.0/get_key/")
        assert "<h2>Get API Key</h2>" in response.content

        # no ip specified, so there should be a form
        assert ("Alternatively, you can enter an IP address "
                "here and get a key") in response.content

    def test_key_for_other_ip(self):
        response = self.c.get("/api/1.0/get_key/?ip=128.59.1.1")
        assert ("This key is for the specified IP "
                "Address (128.59.1.1)") in response.content
Example #16
0
class TestIPTTTimePeriodsReportResponseBase(test.TestCase):
    timeperiods = Indicator.ANNUAL

    def setUp(self):
        self.user = UserFactory(first_name="FN",
                                last_name="LN",
                                username="******",
                                is_superuser=True)
        self.user.set_password('password')
        self.user.save()

        self.tola_user = TolaUserFactory(user=self.user)
        self.tola_user.save()

        self.client = test.Client(enforce_csrf_checks=False)
        self.client.login(username='******', password='******')
        self.response = None
        startdate = datetime.strptime('2017-02-04', '%Y-%m-%d')
        enddate = datetime.strptime('2019-10-01', '%Y-%m-%d')
        self.program = ProgramFactory(reporting_period_start=startdate,
                                      reporting_period_end=enddate)
        self.request_params = {
            'csrfmiddlewaretoken': 'asdf',
            'program': self.program.id
        }

    def tearDown(self):
        Indicator.objects.all().delete()
        self.response = None

    def set_dates(self, start, end):
        self.program.reporting_period_start = datetime.strptime(
            start, '%Y-%m-%d')
        self.program.reporting_period_end = datetime.strptime(end, '%Y-%m-%d')
        self.program.save()

    def get_indicator_for_program(self, **kwargs):
        make_kwargs = {'program': self.program}
        make_kwargs.update(kwargs)
        indicator = IndicatorFactory(**make_kwargs)
        return indicator

    def add_indicator(self, frequency=Indicator.ANNUAL, **kwargs):
        kwargs['target_frequency'] = frequency
        return self.get_indicator_for_program(**kwargs)

    def add_indicator_with_data(self, frequency, values):
        indicator = self.add_indicator(frequency=frequency)
        collect_date = self.program.reporting_period_start + timedelta(days=1)
        for value in values:
            _ = ResultFactory(indicator=indicator,
                              date_collected=collect_date,
                              achieved=value)
            if frequency == Indicator.ANNUAL:
                collect_date = datetime(collect_date.year + 1,
                                        collect_date.month, collect_date.day)
            elif frequency == Indicator.SEMI_ANNUAL:
                collect_date = datetime(
                    collect_date.year if collect_date.month < 7 else
                    collect_date.year + 1, collect_date.month +
                    6 if collect_date.month < 7 else collect_date.month - 6,
                    collect_date.day)
            elif frequency == Indicator.TRI_ANNUAL:
                collect_date = datetime(
                    collect_date.year if collect_date.month < 9 else
                    collect_date.year + 1, collect_date.month +
                    4 if collect_date.month < 9 else collect_date.month - 8,
                    collect_date.day)
            elif frequency == Indicator.QUARTERLY:
                collect_date = datetime(
                    collect_date.year if collect_date.month < 10 else
                    collect_date.year + 1, collect_date.month +
                    3 if collect_date.month < 10 else collect_date.month - 9,
                    collect_date.day)
            elif frequency == Indicator.MONTHLY:
                collect_date = datetime(
                    collect_date.year if collect_date.month < 12 else
                    collect_date.year + 1, collect_date.month +
                    1 if collect_date.month < 12 else collect_date.month - 11,
                    collect_date.day)

    def get_showall_response(self):
        self.request_params['timeframe'] = 1
        self.request_params['numrecentperiods'] = None
        return self.get_response()

    def get_recent_periods(self, numrecent):
        self.request_params['timeframe'] = 2
        self.request_params['numrecentperiods'] = numrecent
        return self.get_response()

    def get_date_range_periods(self, start, end):
        self.request_params['start_period'] = start.strftime(
            '%Y-%m-%d') if isinstance(start, datetime) else start
        self.request_params['end_period'] = end.strftime(
            '%Y-%m-%d') if isinstance(end, datetime) else end
        return self.get_response()

    def get_response(self, reporttype=IPTT_Mixin.REPORT_TYPE_TIMEPERIODS):
        self.request_params['timeperiods'] = self.timeperiods
        response = self.client.post(
            '/indicators/iptt_report/{program}/{reporttype}/'.format(
                program=self.program.id, reporttype=reporttype),
            self.request_params,
            follow=True)
        self.assertEqual(
            response.status_code, 200,
            "response gave status code {0} instead of 200".format(
                response.status_code))
        self.response = IPTTResponse(response.content, timeperiods=True)
        return self.response

    def get_indicator_results(self, response, indicator_row=0):
        indicator = response.indicators[indicator_row]['ranges']
        return indicator[0], indicator[1:]

    def format_assert_message(self, msg):
        return "{0}:\n{1} timeperiods, {2}".format(self.response, {
            k: v
            for k, v in Indicator.TARGET_FREQUENCIES
        }[self.timeperiods], msg)

    def number_of_ranges_test(self, start, end, expected_ranges):
        self.set_dates(start, end)
        self.add_indicator()
        response = self.get_showall_response()
        ranges = response.indicators[0]['ranges'][1:]
        self.assertEqual(
            len(ranges), expected_ranges,
            self.format_assert_message(
                "expected {0} ranges for {1} to {2}, got {3}".format(
                    expected_ranges, start, end, len(ranges))))
class TestIPTTTargetReportsI18N(test.TestCase):
    """
    My original thought was to test all target periods in all languages

    I found out the PeriodicTarget.period field is a char field that is actually used as part of the DB
    annotations/query, and needs to line up with the target period your are reporting on. This is
    kind of a nightmare from a testing perspective.

    The bug this is regression testing against was that a PeriodicTarget.period containing unicode
    would throw an encoding exception on view, so just test for that case and call it a day
    """
    test_target_periods = [
        # Indicator.LOP,
        # Indicator.MID_END,
        Indicator.ANNUAL,
        # Indicator.MONTHLY,
        # Indicator.SEMI_ANNUAL,
        # Indicator.TRI_ANNUAL,
        # Indicator.QUARTERLY,
    ]

    def setUp(self):
        startdate = datetime.strptime('2017-02-04', '%Y-%m-%d')
        enddate = datetime.strptime('2019-10-01', '%Y-%m-%d')
        self.program = ProgramFactory(reporting_period_start=startdate,
                                      reporting_period_end=enddate)

        # setting up an indicator of each target type should allow the view to load w/ that target period (I think...)
        for indicator_frequency in self.test_target_periods:
            indicator = IndicatorFactory(target_frequency=indicator_frequency, program=self.program)

            # make periodic target w/ unicode in the period names - this was causing an exception!
            PeriodicTargetFactory(period='Año unicode name', indicator=indicator, start_date=startdate, end_date=enddate)

        # create and login user (defaulted to 'en' language)
        self.user = UserFactory(first_name="FN", last_name="LN", username="******")
        self.user.set_password('password')
        self.user.save()

        self.tola_user = TolaUserFactory(user=self.user)

        self.client.login(username="******", password='******')

    def _set_user_language(self, language):
        self.tola_user.language = language
        self.tola_user.save()

    def test_iptt_report_requests_in_all_languages(self):
        for language in TEST_LANGUAGES:
            self._set_user_language(language)

            for target_period in self.test_target_periods:
                url = reverse('iptt_report', args=[self.program.id, IPTT_Mixin.REPORT_TYPE_TARGETPERIODS])

                # lack of exception is a win!
                response = self.client.post(url,
                                            {
                                                'program': self.program.id,
                                                'targetperiods': target_period,
                                                'timeframe': 1,  # show all
                                                'csrfmiddlewaretoken': 'lol',
                                            },
                                            follow=True)
                self.assertEqual(response.status_code, 200,
                                 "response gave status code {0} instead of 200".format(response.status_code))
Example #18
0
class UserPages(TestCase):
  def setUp(self):
    self.user = UserFactory()
    self.user.set_password('asdf')
    self.user.save()
    self.superuser = SuperUserFactory()
    self.superuser.set_password('asdf')
    self.superuser.save()
    
  def test_new_page(self):
    response = self.client.get(reverse('users:new'))
    
    self.assertContains(response, '<h1>New User</h1>', html=True)
  
  def test_edit_page(self):
    self.assertTrue(self.client.login(username=self.user.username, password='******'))
    response = self.client.get(reverse('users:edit', kwargs={'pk': self.user.pk}), follow=True)

    self.assertContains(response, '<h1>Edit %s</h1>' % self.user.username, html=True)
  
  def test_if_superuser(self):  
    self.client.login(username=self.superuser.username, password='******')
    response = self.client.get(reverse('users:index'))
    
    self.assertContains(response, self.user.username)
    self.assertContains(response, reverse('users:show', kwargs={'pk': self.user.pk}))
  
  def test_create_a_user(self):
    total_users = User.objects.count()
    data = {
      'username': '******',
      'first_name': 'Test',
      'last_name': 'User',
      'email': '*****@*****.**',
      'password1': 'asdf',
      'password2': 'asdf',
    }
    response = self.client.post(reverse('users:create'), data)
    
    self.assertEqual(User.objects.count(), total_users + 1)

  def test_detail_if_correct_user(self):
    response = self.client.get(reverse('users:show', kwargs={'pk': self.user.pk}))
    
    self.assertContains(response, self.user.first_name)
  
  def test_update_if_correct_user(self):
    data = {
      'first_name': 'Attempted change',
      'last_name': self.user.last_name,
      'email': self.user.email,
      '_method': 'put',
    }
    self.client.login(username=self.user.username, password='******')
    response = self.client.post(reverse('users:update', kwargs={'pk': self.user.pk}), data)
    
    self.assertRedirects(response, reverse('users:show', kwargs={'pk': self.user.pk}))
    self.assertEqual(self.user.first_name, 'Attempted change')
    
  def test_delete_if_correct_user(self):
    new_user = UserFactory()
    new_user.set_password('asdf')
    new_user.save()
    total_users = User.objects.count()
    self.client.login(username=new_user.username, password='******')
    response = self.client.post(reverse('users:destroy', kwargs={'pk': new_user.pk}), {'_method': 'delete'})
    
    self.assertRedirects(response, reverse('home'))
    self.assertEqual(User.objects.count(), total_users - 1)
  
  def test_if_not_logged_in(self):
    response = self.client.get(reverse('users:index'))
    
    self.assertRedirects(response, '%s?next=/users/' % reverse('login'))
  
  def test_if_not_superuser(self):
    self.client.login(username=self.user.username, password='******')
    index_response = self.client.get(reverse('users:index'))
    
    self.assertEqual(index_response.status_code, 403)
  
  def test_if_not_correct_user(self):
    wrong_user = UserFactory()
    wrong_user.set_password('asdf')
    wrong_user.save()
    self.client.login(username=wrong_user.username, password='******')
    detail_response = self.client.get(reverse('users:show', kwargs={'pk': self.user.pk}))
    data = {
      'first_name': 'Attempted change',
      'last_name': ':):)',
      'email': '*****@*****.**',
      '_method': 'put',
    }
    update_response = self.client.post(reverse('users:update', kwargs={'pk': self.user.pk}), data)
    delete_response = self.client.post(reverse('users:destroy', kwargs={'pk': self.user.pk}), {'_method': 'delete'})
    
    self.assertEqual(update_response.status_code, 403)
    self.assertEqual(delete_response.status_code, 403)
class TestResultUnassignedUIDateFallsOutsideProgramPeriod(test.TestCase):
    """
    A result is unassigned because its "date collected" falls outside of the program period AND targets are time-aware

    When a result is unassigned because its "date collected" falls outside of the program period AND
    targets are time-aware, the following are true:

    1. The result is displayed in the table underneath the target period rows.
    2. Under the table, we display error message: This date falls outside the range of your target periods.
       Please select a date between [localized program start date] and [localized program end date].
    """

    def setUp(self):
        self.program = ProgramFactory(
            reporting_period_start=datetime.date(2018, 1, 1),
            reporting_period_end=datetime.date(2019, 1, 1),
        )
        self.indicator = IndicatorFactory(
            program=self.program,
            target_frequency=Indicator.ANNUAL,
        )
        PeriodicTargetFactory(
            indicator=self.indicator,
            start_date=datetime.date(2018, 1, 1),
            end_date=datetime.date(2018, 12, 31),
        )
        self.result = ResultFactory(
            indicator=self.indicator,
            date_collected=datetime.date(2017, 1, 1),
            achieved=42,
            record_name='My Test Record',
            evidence_url='http://my_evidence_url',
        )
        self.count = 1
        self.count += str(self.indicator.pk).count('42') * 2
        self.count += str(self.indicator.name).count('42')
        self.count += str(self.result.pk).count('42')
        self.user = UserFactory(first_name="FN", last_name="LN", username="******", is_superuser=True)
        self.user.set_password('password')
        self.user.save()
        self.tola_user = TolaUserFactory(user=self.user)
        self.client.login(username='******', password='******')

    def test_result_table_html(self):
        url = reverse_lazy('result_view', args=[self.indicator.id,])
        response = self.client.get(url)
        # result is displayed
        self.assertContains(
            response,
            'Jan 1, 2017',
        )
        # only 1 expected now as no longer displaying the value for unassigned indicators
        self.assertContains(
            response, '42', count=self.count, msg_prefix=response.content.decode('utf-8')
        )
        # expected warning message
        self.assertContains(
            response,
            "This date falls outside the range of your target periods."\
            " Please select a date between Jan 1, 2018 and Jan 1, 2019."
        )
Example #20
0
class TestStaff(TestCase):
    def setUp(self):
        self.u = UserFactory()
        self.u.set_password("bar")
        self.u.save()
        self.c = Client()
        self.c.login(username=self.u.username, password="******")

    def test_most_recent_operation(self):
        o = OperationFactory()
        r = self.c.get("/most_recent_operation/")
        self.assertEqual(r.status_code, 200)
        self.assertTrue(str(o.modified.year) in r.content)

    def test_most_recent_operation_empty(self):
        r = self.c.get("/most_recent_operation/")
        self.assertEqual(r.status_code, 200)

    def test_servers_empty(self):
        r = self.c.get("/server/")
        self.assertEqual(r.status_code, 200)

    def test_servers(self):
        s = ServerFactory()
        r = self.c.get("/server/")
        self.assertEqual(r.status_code, 200)
        self.assertTrue(s.name in r.content)
        self.assertTrue(s.hostname in r.content)

    def test_server(self):
        s = ServerFactory()
        r = self.c.get(s.get_absolute_url())
        self.assertEqual(r.status_code, 200)
        self.assertTrue(s.name in r.content)
        self.assertTrue(s.hostname in r.content)

    def test_edit_server(self):
        s = ServerFactory()
        r = self.c.get(s.get_absolute_url() + "edit/")
        self.assertEqual(r.status_code, 200)
        self.assertTrue(s.name in r.content)
        self.assertTrue(s.hostname in r.content)
        self.assertTrue("<form " in r.content)

    def test_delete_server(self):
        s = ServerFactory()
        # make sure it appears in the list
        r = self.c.get("/server/")
        self.assertEqual(r.status_code, 200)
        self.assertTrue(s.name in r.content)
        self.assertTrue(s.hostname in r.content)
        # delete it
        r = self.c.post("/server/%d/delete/" % s.id, {})
        self.assertEqual(r.status_code, 302)
        # now it should be gone
        r = self.c.get("/server/")
        self.assertEqual(r.status_code, 200)
        self.assertFalse(s.name in r.content)
        self.assertFalse(s.hostname in r.content)

    def test_delete_server_get(self):
        """ GET request should just be confirm form, not actually delete """
        s = ServerFactory()
        # make sure it appears in the list
        r = self.c.get("/server/")
        self.assertEqual(r.status_code, 200)
        self.assertTrue(s.name in r.content)
        self.assertTrue(s.hostname in r.content)

        r = self.c.get("/server/%d/delete/" % s.id)
        self.assertEqual(r.status_code, 200)
        # it should not be gone
        r = self.c.get("/server/")
        self.assertEqual(r.status_code, 200)
        self.assertTrue(s.name in r.content)
        self.assertTrue(s.hostname in r.content)

    def test_tags(self):
        r = self.c.get("/tag/")
        self.assertEqual(r.status_code, 200)

    def test_video(self):
        v = VideoFactory()
        r = self.c.get(v.get_absolute_url())
        self.assertEqual(r.status_code, 200)

    def test_delete_collection(self):
        c = CollectionFactory()
        r = self.c.get(c.get_absolute_url() + "delete/")
        self.assertEqual(r.status_code, 200)
        r = self.c.post(c.get_absolute_url() + "delete/")
        self.assertEqual(r.status_code, 302)

    def test_video_select_poster(self):
        i = ImageFactory()
        v = i.video
        r = self.c.get("/video/%d/select_poster/%d/" % (v.id, i.id))
        self.assertEqual(r.status_code, 302)

    def test_edit_collection(self):
        c = CollectionFactory()
        r = self.c.get(c.get_absolute_url() + "edit/")
        self.assertEqual(r.status_code, 200)
        r = self.c.post(c.get_absolute_url() + "edit/",
                        data=dict(title="updated title"))
        self.assertEqual(r.status_code, 302)

    def test_collection_toggle_active(self):
        c = CollectionFactory(active=True)
        r = self.c.post(c.get_absolute_url() + "toggle_active/")
        c = Collection.objects.get(id=c.id)
        self.assertEqual(r.status_code, 302)
        self.assertFalse(c.active)
        r = self.c.post(c.get_absolute_url() + "toggle_active/")
        self.assertEqual(r.status_code, 302)
        c = Collection.objects.get(id=c.id)
        self.assertTrue(c.active)

    def test_edit_collection_workflows_form(self):
        c = CollectionFactory()
        r = self.c.get(c.get_absolute_url() + "workflows/")
        self.assertEqual(r.status_code, 200)

    def test_edit_collection_workflows(self):
        c = CollectionFactory()
        r = self.c.post(c.get_absolute_url() + "workflows/")
        self.assertEqual(r.status_code, 302)

    def test_add_server_form(self):
        r = self.c.get("/server/add/")
        self.assertEqual(r.status_code, 200)

    def test_add_server(self):
        r = self.c.post(
            "/server/add/",
            dict(name="foo", hostname="foo", credentials="foo",
                 description="foo", base_dir="/",
                 base_url="something", server_type="sftp"))
        self.assertEqual(r.status_code, 302)

    def test_add_server_invalid(self):
        r = self.c.post("/server/add/")
        self.assertEqual(r.status_code, 200)

    def test_edit_video_form(self):
        v = VideoFactory()
        r = self.c.get(v.get_absolute_url() + "edit/")
        self.assertEqual(r.status_code, 200)

    def test_remove_tag_from_collection(self):
        c = CollectionFactory()
        r = self.c.get(c.get_absolute_url() + "remove_tag/foo/")
        self.assertEqual(r.status_code, 200)
        r = self.c.get(c.get_absolute_url() + "remove_tag/foo/?ajax=1")
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.content, "ok")

    def test_remove_tag_from_video(self):
        c = VideoFactory()
        r = self.c.get(c.get_absolute_url() + "remove_tag/foo/")
        self.assertEqual(r.status_code, 200)
        r = self.c.get(c.get_absolute_url() + "remove_tag/foo/?ajax=1")
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.content, "ok")

    def test_tag(self):
        r = self.c.get("/tag/foo/")
        self.assertEqual(r.status_code, 200)

    def test_add_collection_form(self):
        r = self.c.get("/add_collection/")
        self.assertEqual(r.status_code, 200)

    def test_add_collection(self):
        r = self.c.post("/add_collection/", dict(title="new collection",
                                                 active="on"))
        self.assertEqual(r.status_code, 302)

    def test_operation(self):
        o = OperationFactory()
        response = self.c.get("/operation/%s/" % o.uuid)
        self.assertEqual(response.status_code, 200)

    def test_delete_file_form(self):
        f = FileFactory()
        response = self.c.get("/file/%d/delete/" % f.id)
        self.assertEqual(response.status_code, 200)

    def test_delete_file(self):
        f = FileFactory()
        response = self.c.post("/file/%d/delete/" % f.id)
        self.assertEqual(response.status_code, 302)

    def test_delete_video_form(self):
        f = VideoFactory()
        response = self.c.get("/video/%d/delete/" % f.id)
        self.assertEqual(response.status_code, 200)

    def test_delete_video(self):
        f = VideoFactory()
        response = self.c.post("/video/%d/delete/" % f.id)
        self.assertEqual(response.status_code, 302)

    def test_delete_operation_form(self):
        f = OperationFactory()
        response = self.c.get("/operation/%d/delete/" % f.id)
        self.assertEqual(response.status_code, 200)

    def test_delete_operation(self):
        f = OperationFactory()
        response = self.c.post("/operation/%d/delete/" % f.id)
        self.assertEqual(response.status_code, 302)

    def test_video_pcp_submit_form(self):
        v = VideoFactory()
        response = self.c.get("/video/%d/pcp_submit/" % v.id)
        self.assertEqual(response.status_code, 200)

    def test_video_pcp_submit(self):
        v = VideoFactory()
        response = self.c.post("/video/%d/pcp_submit/" % v.id)
        self.assertEqual(response.status_code, 302)

    def test_file_pcp_submit_form(self):
        v = FileFactory()
        response = self.c.get("/file/%d/submit_to_workflow/" % v.id)
        self.assertEqual(response.status_code, 200)

    def test_file_pcp_submit(self):
        v = FileFactory()
        response = self.c.post("/file/%d/submit_to_workflow/" % v.id)
        self.assertEqual(response.status_code, 302)

    def test_bulk_file_operation_form(self):
        response = self.c.get("/bulk_file_operation/")
        self.assertEqual(response.status_code, 200)

    def test_bulk_file_operation(self):
        response = self.c.post("/bulk_file_operation/")
        self.assertEqual(response.status_code, 302)

    def test_video_add_file_form(self):
        v = VideoFactory()
        response = self.c.get("/video/%d/add_file/" % v.id)
        self.assertEqual(response.status_code, 200)

    def test_list_workflows(self):
        response = self.c.get("/list_workflows/")
        self.assertEqual(response.status_code, 200)
Example #21
0
class SimpleTest(TestCase):
    """ most of these tests are just about getting
    the absolute bare minimum of test coverage in place,
    hitting pages and just making sure they return the
    appropriate 200/302 status instead of generating a
    server error. *Real* tests can come later.
    """
    def setUp(self):
        self.u = UserFactory()
        self.u.set_password("bar")
        self.u.save()
        self.c = Client()

    def tearDown(self):
        self.u.delete()

    def test_index(self):
        response = self.c.get('/')
        self.assertEquals(response.status_code, 302)

        self.c.login(username=self.u.username, password="******")
        response = self.c.get('/')
        self.assertEquals(response.status_code, 200)

    def test_smoke(self):
        response = self.c.get('/smoketest/')
        self.assertEquals(response.status_code, 200)

    def test_dashboard(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/dashboard/")
        self.assertEquals(response.status_code, 200)

    def test_received_invalid(self):
        response = self.c.post("/received/")
        assert response.content == "expecting a title"

    def test_received(self):
        response = self.c.post("/received/",
                               {'title': 'some title. not a uuid'})
        assert response.content == "ok"

    def test_received_with_operation(self):
        o = OperationFactory()
        response = self.c.post("/received/",
                               {'title': str(o.uuid)})
        assert response.content == "ok"

    def test_recent_operations(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/recent_operations/")
        self.assertEquals(response.status_code, 200)

    def test_upload_form(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/upload/")
        self.assertEquals(response.status_code, 200)

        response = self.c.get("/scan_directory/")
        self.assertEquals(response.status_code, 200)

    def test_upload_form_for_collection(self):
        c = CollectionFactory()
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/upload/")
        self.assertEquals(response.status_code, 200)
        response = self.c.get("/upload/?collection=%d" % c.id)
        self.assertEquals(response.status_code, 200)

        response = self.c.get("/scan_directory/")
        self.assertEquals(response.status_code, 200)
        response = self.c.get("/scan_directory/?collection=%d" % c.id)
        self.assertEquals(response.status_code, 200)

    def test_upload_errors(self):
        # if we try to post without logging in, should get redirected
        response = self.c.post("/upload/post/")
        self.assertEquals(response.status_code, 302)

        self.c.login(username=self.u.username, password="******")
        # GET should not work
        response = self.c.get("/upload/post/")
        self.assertEquals(response.status_code, 302)

        # invalid form
        response = self.c.post("/upload/post/")
        self.assertEquals(response.status_code, 302)

    def test_subject_autocomplete(self):
        response = self.c.get("/api/subjectautocomplete/", dict(q="test"))
        self.assertEquals(response.status_code, 200)

    def test_uuid_search(self):
        f = FileFactory()
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/uuid_search/", dict(uuid=f.video.uuid))
        self.assertEquals(response.status_code, 200)

    def test_uuid_search_empty(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/uuid_search/", dict(uuid=""))
        self.assertEquals(response.status_code, 200)

    def test_search(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/search/", dict(q="test"))
        self.assertEquals(response.status_code, 200)

    def test_search_empty(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/search/", dict(q=""))
        self.assertEquals(response.status_code, 200)

    def test_file_filter(self):
        f = FileFactory()
        self.c.login(username=self.u.username, password="******")
        response = self.c.get(
            "/file/filter/",
            dict(
                include_collection=f.video.collection.id,
            ))
        self.assertEquals(response.status_code, 200)

    def test_video_index(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/video/")
        self.assertEquals(response.status_code, 200)

    def test_video_index_nan(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/video/?page=foo")
        self.assertEquals(response.status_code, 200)

    def test_video_index_offtheend(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/video/?page=200")
        self.assertEquals(response.status_code, 200)

    def test_video_index_with_params(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/video/?creator=c&description=d&"
                              "language=l&subject=s&licence=l")
        self.assertEquals(response.status_code, 200)

    def test_file_index(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/file/")
        self.assertEquals(response.status_code, 200)

    def test_file_index_nan(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/file/?page=foo")
        self.assertEquals(response.status_code, 200)

    def test_file_index_offtheend(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/file/?page=200")
        self.assertEquals(response.status_code, 200)

    def test_file_index_with_params(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/file/?foo=bar")
        self.assertEquals(response.status_code, 200)

    def test_user_page(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/user/%s/" % self.u.username)
        self.assertEquals(response.status_code, 200)

    def test_collection_videos(self):
        f = FileFactory()
        self.c.login(username=self.u.username, password="******")
        response = self.c.get(
            "/collection/%d/videos/" % f.video.collection.id)
        self.assertEquals(response.status_code, 200)

    def test_collection_videos_pagination_nan(self):
        f = FileFactory()
        self.c.login(username=self.u.username, password="******")
        response = self.c.get(
            "/collection/%d/videos/?page=foo" % f.video.collection.id)
        self.assertEquals(response.status_code, 200)

    def test_collection_videos_pagination_offtheend(self):
        f = FileFactory()
        self.c.login(username=self.u.username, password="******")
        response = self.c.get(
            "/collection/%d/videos/?page=200" % f.video.collection.id)
        self.assertEquals(response.status_code, 200)

    def test_collection_operations(self):
        f = FileFactory()
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/collection/%d/operations/"
                              % f.video.collection.id)
        self.assertEquals(response.status_code, 200)

    def test_collection_page(self):
        f = FileFactory()
        self.c.login(username=self.u.username, password="******")
        response = self.c.get(
            "/collection/%d/" % f.video.collection.id)
        self.assertEquals(response.status_code, 200)

    def test_slow_operations(self):
        self.c.login(username=self.u.username, password="******")
        response = self.c.get("/slow_operations/")
        self.assertEquals(response.status_code, 200)

    def test_tagautocomplete(self):
        response = self.c.get("/api/tagautocomplete/?q=foo")
        self.assertEquals(response.status_code, 200)

    def test_subjectautocomplete(self):
        VideoFactory(title="thread")
        response = self.c.get("/api/subjectautocomplete/?q=thread")
        self.assertEquals(response.status_code, 200)

    def test_operation_info(self):
        o = OperationFactory()
        response = self.c.get("/operation/%s/info/" % o.uuid)
        self.assertEqual(response.status_code, 200)

    def test_posterdone(self):
        o = OperationFactory()
        response = self.c.post("/posterdone/", dict(title=str(o.uuid)))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, "ok")

    def test_posterdone_empty(self):
        response = self.c.post("/posterdone/")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, "expecting a title")

    def test_posterdone_nonexistant(self):
        response = self.c.post("/posterdone/", dict(title="some-bad-uuid"))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, "ok")

    def test_done(self):
        o = OperationFactory()
        response = self.c.post("/done/", dict(title=str(o.uuid)))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, "ok")

    def test_done_no_title(self):
        response = self.c.post("/done/")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, "expecting a title")

    def test_done_nonexistant(self):
        response = self.c.post("/done/", dict(title="some-bad-uuid"))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content,
                         "could not find an operation with that UUID")