Ejemplo n.º 1
0
    def test_update_user_endpoint_with_invalid_role_fails(self):
        create_user_role("update_user", "admin")
        role = RoleFactory()

        user = UserFactory()
        user.save()
        UserRoleFactory(user_id=user.id, role=role)
        user_data = dict(
            first_name="Andela",
            last_name="Eats",
            role_id=100,
            gender="male",
            date_of_birth="2020-10-01",
            employment_date="2020-10-01",
        )

        response = self.client().patch(
            self.make_url(f"/users/{user.id}"),
            headers=self.headers(),
            data=self.encode_to_json_string(user_data),
        )

        response_json = self.decode_from_json_string(response.data.decode("utf-8"))

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response_json["msg"], "Role with id 100 doesnot exist")
Ejemplo n.º 2
0
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)
Ejemplo n.º 4
0
 def test_roles(self):
     """Add a role to a user."""
     role = Role(name="admin")
     role.save()
     user = UserFactory()
     user.roles.append(role)
     user.save()
     assert role in user.roles
Ejemplo n.º 5
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)
Ejemplo n.º 6
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)
Ejemplo n.º 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)
Ejemplo n.º 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)
Ejemplo n.º 9
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)
Ejemplo n.º 10
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.')
Ejemplo n.º 12
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
Ejemplo n.º 13
0
    def test_update_user_endpoint_with_invalid_role_fails(self):
        create_user_role('update_user')
        role = RoleFactory()
        user_role = UserRoleFactory(role=role)
        user = UserFactory(user_type=user_role)
        user.save()
        user_data = dict(firstName="Andela", lastName="Eats", roleId=100)

        response = self.client().patch(self.make_url(f'/users/{user.id}'), headers=self.headers(),
                                       data=self.encode_to_json_string(user_data))

        response_json = self.decode_from_json_string(response.data.decode('utf-8'))

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response_json['msg'], 'Role with id 100 doesnot exist')
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))
Ejemplo n.º 15
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)
Ejemplo n.º 16
0
    def test_create_user_endpoint_succeeds2(self):
        location = LocationFactory.create()
        headers = self.headers()
        headers.update({"X-Location": location.id})

        create_user_role("view_users", "admin")
        user = UserFactory()
        user.save()
        response = self.client().get(
            self.make_url(f"/users/user_profile/{user.id}"), headers=headers
        )

        response_json = self.decode_from_json_string(response.data.decode("utf-8"))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response_json["msg"], "OK")
        self.assertEqual(
            response_json["payload"]["user"]["first_name"], user.first_name
        )
        self.assertEqual(response_json["payload"]["user"]["last_name"], user.last_name)
Ejemplo n.º 17
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
Ejemplo n.º 18
0
    def test_create_user_endpoint_succeeds2(self):
        location = LocationFactory.create()
        headers = self.headers()
        headers.update({'X-Location': location.id})

        create_user_role('view_users')
        user = UserFactory(slack_id="-LXTuXlk2W4Gskt8KTte")
        user.save()

        response = self.client().get(
            self.make_url(f'/users/{user.slack_id}/'),
            headers=headers
        )

        response_json = self.decode_from_json_string(response.data.decode('utf-8'))

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response_json['msg'], 'OK')
        self.assertEqual(response_json['payload']['user']['firstName'], user.first_name)
        self.assertEqual(response_json['payload']['user']['lastName'], user.last_name)
Ejemplo n.º 19
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
Ejemplo n.º 20
0
    def test_update_user_endpoint_succeeds(self):

        create_user_role('update_user')
        role = RoleFactory()
        user_role = UserRoleFactory(role=role)
        user_role.save()
        user = UserFactory(user_type=user_role)
        user.save()
        user_data = dict(firstName="Andela", lastName="Eats", roleId=role.id)

        response = self.client().patch(
            self.make_url(f'/users/{user.id}'),
            headers=self.headers(),
            data=self.encode_to_json_string(user_data)
        )

        response_json = self.decode_from_json_string(response.data.decode('utf-8'))

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response_json['msg'], 'OK')
        self.assertEqual(response_json['payload']['user']['firstName'], user.first_name)
        self.assertEqual(response_json['payload']['user']['lastName'], user.last_name)
Ejemplo n.º 21
0
        def test_top_chefs_page_should_display_top_rated_chefs(
                self, api_client):
            for i in range(10):
                new_user = UserFactory()
                new_user.stars = 5
                new_user.save()

            for i in range(10):
                new_user = UserFactory()
                new_user.stars = 4
                new_user.save()

            top_rated_chefs = UserAccount.objects.all().filter(stars=5)
            bottom_rated_chefs = UserAccount.objects.all().filter(stars=4)

            response = api_client.get(top_rated_accounts_url)

            for chef in top_rated_chefs:
                assert f'{chef}' in f'{response.content}'

            for chef in bottom_rated_chefs:
                assert f'{chef}' not in f'{response.content}'
Ejemplo n.º 22
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')
Ejemplo n.º 23
0
class QueuesAPITestCase(TestCase):
    def setUp(self):
        self.user = UserFactory(username='******')
        self.admin = UserFactory(username='******', super_user=True)
        self.norm = UserFactory(username='******')
        self.collab = UserFactory(username='******')
        self.created_queue = self.mock_create_queue(owner=self.user, name='TestUserQueue')
        self.created_queue.organizers.add(self.collab)

    def _get_test_update_data(self, return_id=True):
        data = {
            'name': 'A BRAND NEW NAME',
            'owner': self.user.id,
            'is_public': False,
        }
        if return_id:
            data['id'] = self.created_queue.id
        return data

    def mock_create_queue(self, **kwargs):
        # Prevent queue creation
        with mock.patch('queues.models.rabbit.create_queue') as rabbit_create_queue:
            rabbit_create_queue.return_value = uuid.uuid4()
            return QueueFactory(**kwargs)

    def queue_api_request_with_mock(self, http_method, url_name, url_kwargs=None, data=None):
        # So we can make API requests without triggering rabbitmq actual queue creation
        with mock.patch('queues.models.rabbit.create_queue') as rabbit_create_queue:
            url_kwargs = url_kwargs if url_kwargs is not None else {}
            data = data if data is not None else {}
            rabbit_create_queue.return_value = uuid.uuid4()
            response = getattr(self.client, http_method.lower())(
                reverse(url_name, kwargs=url_kwargs),
                data=data,
                content_type='application/json'
            )
            return response, rabbit_create_queue.called

    def test_create_queue_through_api(self):
        self.client.login(username='******', password='******')
        assert Queue.objects.count() == 1
        data = {
            'name': 'A brand new queue',
            'owner': self.user.id,
            'is_public': False,
        }
        response, rabbit_create_queue_called = self.queue_api_request_with_mock('post', 'queues-list', {}, data)
        assert rabbit_create_queue_called
        assert Queue.objects.count() == 2
        assert response.status_code == 201

    # --------- Permission tests ---------

    def test_organizer_can_perform_all_operations(self):
        self.client.login(username='******', password='******')
        assert Queue.objects.get(pk=self.created_queue.id).name == 'TestUserQueue'
        response, rabbit_create_queue_called = self.queue_api_request_with_mock(
            'put',
            'queues-detail',
            {'pk': self.created_queue.id},
            self._get_test_update_data()
        )
        assert not rabbit_create_queue_called
        assert response.status_code == 200
        assert Queue.objects.get(pk=self.created_queue.id).name == 'A BRAND NEW NAME'

        response, rabbit_create_queue_called = self.queue_api_request_with_mock(
            'delete',
            'queues-detail',
            {'pk': self.created_queue.id},
        )
        assert response.status_code == 204
        assert not Queue.objects.filter(pk=self.created_queue.id).exists()

    def test_other_user_cannot_delete_or_edit_queue(self):
        self.client.login(username='******', password='******')
        response, rabbit_create_queue_called = self.queue_api_request_with_mock(
            'put',
            'queues-detail',
            {'pk': self.created_queue.id},
            self._get_test_update_data()
        )
        assert not rabbit_create_queue_called
        assert response.status_code == 404
        assert Queue.objects.get(pk=self.created_queue.id).name != 'A BRAND NEW NAME'

        response, rabbit_create_queue_called = self.queue_api_request_with_mock(
            'delete',
            'queues-detail',
            {'pk': self.created_queue.id},
        )

        assert response.status_code == 404
        assert Queue.objects.filter(pk=self.created_queue.id).exists()

    def test_collab_cannot_delete_or_edit_queue(self):
        self.client.login(username='******', password='******')
        response, rabbit_create_queue_called = self.queue_api_request_with_mock(
            'put',
            'queues-detail',
            {'pk': self.created_queue.id},
            self._get_test_update_data()
        )
        assert not rabbit_create_queue_called
        assert response.status_code == 403
        assert Queue.objects.get(pk=self.created_queue.id).name != 'A BRAND NEW NAME'

        response, rabbit_create_queue_called = self.queue_api_request_with_mock(
            'delete',
            'queues-detail',
            {'pk': self.created_queue.id},
        )

        assert response.status_code == 403
        assert Queue.objects.filter(pk=self.created_queue.id).exists()

    # --------- Queue Limit Tests ---------

    # Test user queue limits
    def test_queue_limits_for_regular_users(self):
        self.client.login(username='******', password='******')
        self.user.rabbitmq_queue_limit = 2
        self.user.save()
        # Ensure we can still create a queue to reaach our limit
        response, rabbit_create_queue_called = self.queue_api_request_with_mock(
            'post',
            'queues-list',
            data=self._get_test_update_data(return_id=False)
        )
        assert rabbit_create_queue_called
        assert response.status_code == 201
        assert self.user.rabbitmq_queue_limit == self.user.queues.count()
        response, rabbit_create_queue_called = self.queue_api_request_with_mock(
            'post',
            'queues-list',
            data=self._get_test_update_data(return_id=False)
        )
        assert not rabbit_create_queue_called
        assert response.status_code == 403
        assert self.user.rabbitmq_queue_limit == self.user.queues.count()

    # Test super user queue limits
    def test_super_users_has_no_queue_limit(self):
        # Set user rabbit queue limit
        self.admin.rabbitmq_queue_limit = 1
        self.admin.save()

        # Reach our limit
        self.mock_create_queue(owner=self.admin)
        assert self.admin.queues.count() == self.admin.rabbitmq_queue_limit

        self.client.login(username='******', password='******')
        response, rabbit_create_queue_called = self.queue_api_request_with_mock(
            'post',
            'queues-list',
            data=self._get_test_update_data(return_id=False)
        )
        assert rabbit_create_queue_called
        assert response.status_code == 201

    # --------- Filter Test ---------
    def test_public_filter_does_not_exclude_own_users_public_queues_and_search_works(self):
        # Create a public queue we want to show in our results by search/public=True
        self.mock_create_queue(owner=self.norm, name='TestPublicQueue', is_public=True)

        # Create another queue we do not want to show up that is not public, and should not return in results
        self.mock_create_queue(owner=self.norm)

        # Create yet another queue that IS public, that we want filtered out by search
        self.mock_create_queue(owner=self.norm, is_public=True)

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

        response = self.client.get(f"{reverse('queues-list')}?search=test&public=True")
        assert response.status_code == 200
        assert len(response.data['results']) == 2
        assert response.data['results'][0]['name'] == 'TestPublicQueue'
        assert response.data['results'][0]['is_public']
        assert response.data['results'][1]['name'] == 'TestUserQueue'
        assert not response.data['results'][1]['is_public']
Ejemplo n.º 24
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))
Ejemplo n.º 26
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)
Ejemplo n.º 27
0
class CourseModelTests(TestCase):
    """Test the models used to represent courses and constituent lessons etc"""
    def setUp(self):
        # Prepare two users for each test, Bertie and Hank
        self.user1 = UserFactory(username='******',
                                 email='*****@*****.**',
                                 password='******')
        self.user1.save()
        self.user1.profile.user_tz = "Europe/Rome"  # vary from factory default
        self.user1.profile.save()

        self.user2 = UserFactory(username='******',
                                 email='*****@*****.**',
                                 password='******')
        self.user2.save()
        self.user2.profile.signature_line = 'Tieing knots'
        self.user2.profile.user_tz = 'Atlantic/St_Helena'
        self.user2.profile.save()

        # Prepare some courses
        self.course1 = CourseFactory(
            code=u'EDU02',
            name=u'A Course of Leeches',
            abstract=u'Learn practical benefits of leeches',
            organiser=self.user1,
            instructor=self.user2,
        )

        self.course2 = CourseFactory(
            code=u'FBR9',
            name=u'Basic Knitting',
            abstract=u'Casting on',
            organiser=self.user1,
            instructor=self.user2,
        )

        self.course3 = CourseFactory(
            name=u'Public Speaking',
            abstract=u'Talking in public',
            organiser=self.user1,
            instructor=self.user2,
        )

    def test___unicode__(self):
        uni_name = self.course1.__unicode__()
        self.assertEqual(uni_name, u'A Course of Leeches')

    def test_course_create(self):
        """A course can be created and saved"""
        self.assertEqual(self.course1.pk, 1)

    def test_cannot_create_invalid_course(self):
        with self.assertRaises(IntegrityError):
            invalid_course = Course()
            invalid_course.save()

    def test_model_has_meta_permissions(self):
        perms = Course._meta.permissions
        self.assertTrue('study_course' in (perm[0] for perm in perms))

    def test_can_create_a_course_without_course_code(self):
        """ Course code is optional """
        new_course = Course.objects.create(
            name="Test Course",
            abstract="This course has no code. Should be fine",
            organiser=self.user1,
            instructor=self.user1,
        )
        new_course.save()

    def test_course_get_absolute_url(self):
        """Course returns correct get_absolute_url"""

        url = self.course1.get_absolute_url()
        target = u"/courses/%s/" % self.course1.pk
        self.assertEqual(target, url, "course URL error")

    def test_new_course_is_unpublished_by_default(self):
        new_course = CourseFactory(code=u'TEST1',
                                   name=u'test course',
                                   abstract=u'see unpublished by default',
                                   organiser=self.user1,
                                   instructor=self.user1)
        new_course.save()
        self.assertFalse(new_course.published)

    def test_new_course_has_PricedItem_created(self):
        new_course = CourseFactory(
            code=u'TEST1',
            name=u'test course',
            abstract=u'see the PricedItem instance is created',
            organiser=self.user1,
            instructor=self.user1)
        pitem = PricedItem.objects.get(object_id=new_course.id)
Ejemplo n.º 28
0
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."
        )
Ejemplo n.º 29
0
class CourseModelTests(TestCase):
    """Test the models used to represent courses and constituent lessons etc"""

    def setUp(self):
        # Prepare two users for each test, Bertie and Hank
        self.user1 = UserFactory(
            username = '******',
            email = '*****@*****.**',
            password = '******'
        )
        self.user1.save()
        self.user1.profile.user_tz = "Europe/Rome" # vary from factory default
        self.user1.profile.save()

        self.user2 = UserFactory(
            username = '******',
            email = '*****@*****.**', 
            password = '******'
        )
        self.user2.save()
        self.user2.profile.signature_line = 'Tieing knots'
        self.user2.profile.user_tz = 'Atlantic/St_Helena'
        self.user2.profile.save()

        # Prepare some courses
        self.course1 = CourseFactory(
            code = u'EDU02',
            name = u'A Course of Leeches',
            abstract = u'Learn practical benefits of leeches',
            organiser = self.user1,
            instructor = self.user2,
        )
    
        self.course2 = CourseFactory(
            code = u'FBR9',
            name = u'Basic Knitting',
            abstract = u'Casting on',
            organiser = self.user1,
            instructor = self.user2,
        )

        self.course3 = CourseFactory(
            name = u'Public Speaking',
            abstract = u'Talking in public',
            organiser = self.user1,
            instructor = self.user2,
        )

    def test___unicode__(self):
        uni_name = self.course1.__unicode__()
        self.assertEqual(uni_name, u'A Course of Leeches')
 
    def test_course_create(self):
        """A course can be created and saved"""
        self.assertEqual(self.course1.pk, 1)
 
    def test_cannot_create_invalid_course(self):
        with self.assertRaises(IntegrityError):
            invalid_course = Course()
            invalid_course.save()
        
    def test_model_has_meta_permissions(self):
        perms = Course._meta.permissions
        self.assertTrue('study_course' in (perm[0] for perm in perms))

    def test_can_create_a_course_without_course_code(self):
        """ Course code is optional """
        new_course = Course.objects.create(
            name = "Test Course",
            abstract = "This course has no code. Should be fine",
            organiser = self.user1,
            instructor = self.user1,
        )
        new_course.save()
        
    def test_course_get_absolute_url(self):
        """Course returns correct get_absolute_url"""
        
        url = self.course1.get_absolute_url()
        target = u"/courses/%s/" % self.course1.pk
        self.assertEqual(target, url, "course URL error")
   
    def test_new_course_is_unpublished_by_default(self):
        new_course = CourseFactory(
            code = u'TEST1',
            name = u'test course',
            abstract = u'see unpublished by default',
            organiser = self.user1,
            instructor = self.user1
        )
        new_course.save()
        self.assertFalse(new_course.published)

    def test_new_course_has_PricedItem_created(self):
        new_course = CourseFactory(
            code = u'TEST1',
            name = u'test course',
            abstract = u'see the PricedItem instance is created',
            organiser = self.user1,
            instructor = self.user1
        )
        pitem = PricedItem.objects.get(object_id = new_course.id)
Ejemplo n.º 30
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)
Ejemplo n.º 31
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")