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)
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)
Exemple #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')
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))
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))