Ejemplo n.º 1
0
    def test_compare_view(self):
        """
        the compare view is intended to do various visual comparison
        of two age specific rate functions

        supported styles:
          overlay
          scatter
          stack
          parallel
        """
        c = Client()
        c.login(username='******', password='******')

        response = c.get('/age_specific_rate_function/compare/1000_1001')
        self.assertTemplateUsed(response, 'age_specific_rate_function/compare.html')

        response = c.get('/age_specific_rate_function/compare/1000_1001_compare.png')
        self.assertPng(response)

        response = c.get('/age_specific_rate_function/compare/1000_1001_compare.png', {'style': 'scatter'})
        self.assertPng(response)

        response = c.get('/age_specific_rate_function/compare/1000_1001_compare.png', {'style': 'stack'})
        self.assertPng(response)

        response = c.get('/age_specific_rate_function/compare/1000_1001_compare.png', {'style': 'parallel'})
        self.assertPng(response)
Ejemplo n.º 2
0
class TestLoginRequiredMixin1(TestCase):
    # テスト用のURLパターンを使用します。
    urls = 'myapp.test_urls'

    def setUp(self):
        super().setUp()
        self.client = Client()
        # テスト用URL(test/sample1/login_required_mixin1/)を取得します。
        self.path = reverse('test_sample1_login_required_mixin1')

    def test_logged_in(self):
        """ログイン済みのテストです。"""
        # ユーザを作成し、ログインします。
        username = '******'
        password = '******'
        User.objects.create_user(username=username, password=password)
        self.client.login(username=username, password=password)

        # テスト対象を実行します。
        res = self.client.get(self.path)

        # テスト結果を確認します。
        self.assertEqual(res.status_code, 200)

    def test_not_logged_in(self):
        """ログインしていない場合のテストです。"""
        # テスト対象を実行します。
        res = self.client.get(self.path)

        # テスト結果を確認します。
        self.assertEqual(res.status_code, 302)
Ejemplo n.º 3
0
class AuthTests(TestCase):
    def setUp(self):
        self.c = Client()
        self.password = User.objects.make_random_password()
        self.username = "******"
        self.email = "*****@*****.**"
        u = User.objects.create_user(self.username, self.email, self.password)
        u.is_staff = True
        u.save()

    def tearDown(self):
        User.objects.get(username=self.username).delete()
    
    def testAddUser(self):
        testcase_username = '******'
        testcase_password = User.objects.make_random_password()
        
        self.c.login(username=self.username, password=self.password)
        self.c.post('http://uwcs.co.uk/admin/auth/user/add/', {
            'username':testcase_username, 
            'password1':testcase_password, 
            'password2':testcase_password
        })
        #User.objects.get(username=testcase_username).delete()


    def testLogin(self):
       self.assertContains(self.c.post('/login/', {"username": self.username, "password": self.password, "next":""}, follow=True), "Logged in as")
Ejemplo n.º 4
0
class ConfigWeightTest(TestCase):

    def setUp(self):
        # Setup the permission
        ct = ContentType.objects.get(app_label='config', model='configstore')
        perm = Permission.objects.get(content_type=ct, codename='can_manage')

        # Setup two users
        self.manager = User.objects.create(username='******')
        self.manager.reset_password('default')
        self.manager.user_permissions.add(perm)

        # Login
        self.client_manager = Client()
        self.client_manager.login(username='******', password='******')

    def test_order_of_config_pages_abstract(self):
        config_page_dict = {}
        for receiver, config_page in config_signal.send(sender=self):
            config_page_dict[receiver.__name__] = config_page
        self.assertGreater(config_page_dict['set_grouped_config_page'].weight, config_page_dict['set_simple_config_page'].weight)

    def test_order_of_config_pages_on_view(self):
        response = self.client_manager.get('/config/testgroupedpage1/')
        import re
        m1 = re.search('<a href="/config/testgroupedpage1/" class="btn btn-mini active">Config vars for testing 1</a>', response.content)
        m2 = re.search('<a href="/config/testsimplepage1/" class="btn btn-mini ">Config vars for testing 2</a>', response.content)
        self.assertGreater(m1.start(), m2.start())
class TestComprehensiveTheming(ModuleStoreTestCase):
    """Tests for comprehensive theming of wiki pages."""

    def setUp(self):
        """Test setup."""
        super(TestComprehensiveTheming, self).setUp()

        self.wiki = get_or_create_root()

        self.course_math101 = CourseFactory.create(org='edx', number='math101', display_name='2014',
                                                   metadata={'use_unique_wiki_id': 'false'})
        self.course_math101_instructor = InstructorFactory(course_key=self.course_math101.id, username='******',
                                                           password='******')
        self.wiki_math101 = URLPath.create_article(self.wiki, 'math101', title='math101')

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

    @skip("Fails when run immediately after lms.djangoapps.course_wiki.tests.test_middleware")
    @with_comprehensive_theme('red-theme')
    def test_themed_footer(self):
        """
        Tests that theme footer is used rather than standard
        footer when comprehensive theme is enabled.
        """
        response = self.client.get('/courses/edx/math101/2014/wiki/math101/')
        self.assertEqual(response.status_code, 200)
        # This string comes from themes/red-theme/lms/templates/footer.html
        self.assertContains(response, "super-ugly")
Ejemplo n.º 6
0
 def test_downloadable_resource_for_organization_ms_full_members(self):
     """
     Verifies that a resource with an MS Commons license can be downloaded by
     a user of an organization which has the META-SHARE full member
     permission.
     """
     client = Client()
     client.login(username='******', password='******')
     # make sure the license page is shown:
     response = client.get(
         reverse(views.download,
                 args=(self.ms_commons_resource.storage_object.identifier,)),
         follow = True)
     self.assertTemplateUsed(response, 'repository/licence_agreement.html',
                             "license agreement page expected")
     self.assertContains(response,
         'licences/META-SHARE_COMMONS_BYNCSA_v1.0.htm', msg_prefix="the " \
             "correct license appears to not be shown in an iframe")
     # make sure the download is started after accepting the license:
     response = client.post(
         reverse(views.download,
                 args=(self.ms_commons_resource.storage_object.identifier,)),
         { 'in_licence_agree_form': 'True', 'licence_agree': 'True',
           'licence': 'MSCommons-BY-NC-SA' },
         follow = True)
     self.assertTemplateNotUsed(response,
         'repository/licence_agreement.html',
         msg_prefix="a download should have been started")
     self.assertTemplateNotUsed(response,
         'repository/licence_selection.html',
         msg_prefix="a download should have been started")
     self.assertTemplateNotUsed(response,
         'repository/lr_not_downloadable.html',
         msg_prefix="a download should have been started")
Ejemplo n.º 7
0
 def test_non_downloadable_resource_for_normal_organization_members(self):
     """
     Verifies that a resource with an MS Commons license cannot be downloaded
     by a user of an organization which does not have the META-SHARE full
     member permission.
     """
     test_passwd = 'secret'
     test_user = test_utils.create_organization_member(
         'organization_member_non_ms', '*****@*****.**', test_passwd,
         (Organization.objects.create(name='test_organization_non_ms'),))
     client = Client()
     client.login(username=test_user.username, password=test_passwd)
     # make sure the license page is shown:
     response = client.get(reverse(views.download,
                 args=(self.ms_commons_resource.storage_object.identifier,)),
         follow = True)
     self.assertTemplateUsed(response, 'repository/licence_agreement.html',
                             "license agreement page expected")
     self.assertContains(response,
         'licences/META-SHARE_COMMONS_BYNCSA_v1.0.htm', msg_prefix="the " \
             "correct license appears to not be shown in an iframe")
     # make sure the download cannot be started:
     response = client.post(
         reverse(views.download,
                 args=(self.ms_commons_resource.storage_object.identifier,)),
         { 'in_licence_agree_form': 'True', 'licence_agree': 'True',
           'licence': 'MSCommons-BY-NC-SA' },
         follow = True)
     self.assertTemplateUsed(response, 'repository/licence_agreement.html',
         msg_prefix="a download should not have been started")
Ejemplo n.º 8
0
class GroupCreateTests(TestCase):
    def setUp(self):
        self.c = Client()
        self.user = User.objects.create_user('dummy', '*****@*****.**', 'dummy')
        self.user.save()

        self.user2 = User.objects.create_user('adummy', '*****@*****.**', 'adummy')
        self.user2.save()

        self.user3 = User.objects.create_user('fdummy', '*****@*****.**', 'fdummy')
        self.user3.save()

        self.grupo_a = Group.objects.create(id=1, name="abcd", is_public=0, owner=self.user)
        self.grupo_a.save()

        acesso_a = Group_Access.objects.create(group=self.grupo_a, user=self.user3)
        acesso_a.save()


    def teste_usuario_anonimo_retorna_302(self):
        response = self.c.get(reverse("group_create"))
        self.assertEqual(response.status_code, 302)

    def teste_usuario_logado_retorna_200(self):
        self.c.login(username='******', password='******')
        response = self.c.get(reverse("group_create"))
        self.assertEqual(response.status_code, 200)
Ejemplo n.º 9
0
    def test_teacher_attendance(self):
        """ Tests to ensure that we can take attendance. This test covers
                the submission_percentage dashlet and teacher_submission view. """
        self.setup()

        user = User.objects.get(username='******')
        user.set_password('aa') # Why is this needed?
        user.save()

        c = Client()

        c.login(username='******', password='******')

        response = c.get('/admin/')
        self.assertEqual(response.status_code, 200)

        course_section = CourseSection.objects.get(name="Homeroom FX 2011")

        response = c.get('/attendance/teacher_attendance/' + str(course_section.id), follow=True)
        self.assertEqual(response.status_code, 200)

        AttendanceLog(user=user, course_section=self.course_section1).save()
        AttendanceLog(user=user, course_section=self.course_section2).save()

        homerooms = CourseSection.objects.filter(course__homeroom=True)
        for homeroom in homerooms:
            log = AttendanceLog.objects.filter(course_section=homeroom)
            assert log.count() > 0
Ejemplo n.º 10
0
class PremioTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.user = UserFactory()
        self.post_data = {'text': 'Esta pelicula es genial'}
        self.movie = MovieFactory()
        self.movie.save()
        self.client.login(username=self.user.username, password='******')

    def test_premio(self):
        from django.utils import simplejson
        m = mocker.Mocker()
        obj = m.replace('random')
        obj.randint(1, 200)
        m.result(22)
        k = {'movie_id': self.movie.id}
        m.replay()

        response = self.client.post(reverse('add_review', kwargs=k), self.post_data)

        self.assertEquals(response.status_code, 201)
        self.assertEquals(self.movie.moviereview_set.count(), 1)
        d = simplejson.loads(response.content)

        self.assertTrue(d.has_key('premio'))
Ejemplo n.º 11
0
Archivo: tests.py Proyecto: sheimi/oedu
class scheduleCRUDTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        self.client.login(username="******", password="******")
        
    def test_rent_detail(self):
        put = { 'content'   :   "test",
                'starttime' : '2009-1-1',
                'endtime': '2010-1-1',
               }
        
        response = self.client.put("/schedule/crud/", json.dumps(put), "text")
        schedule = Schedule.objects.get(pk=int(response.content))
        self.assertEqual(schedule.content, "test")
        
        post = {'content' : "test2"}
        response = self.client.post("/schedule/crud/%d" % schedule.pk, json.dumps(post), "text")
        schedule = Schedule.objects.get(pk=schedule.pk)
        self.assertEqual(response.content, '"success"')
        self.assertEqual(schedule.content, "test2")
        
        
        response = self.client.get("/schedule/crud/%d" % schedule.pk)
        a = json.loads(response.content)[0]
        self.assertEqual("test2", a["fields"]["content"])
        
        i = schedule.pk
        response = self.client.delete("/schedule/crud/%d" % i)
        rents = Schedule.objects.filter(pk=i)
        self.assertEqual(response.content, '"success"')
        self.assertEqual(0, len(rents))
    def test_POST_delete_logo(self):
        """
        If the 'delete_logo' POST argument is present, the logo should be
        deleted.
        """
        self.profile.logo = File(self._data_file('logo.png'))
        self.profile.save()
        self.assertTrue(self.profile.logo)

        data = {
            'username': self.user.username,
            'name': self.user.get_full_name(),
            'email': self.user.email,
            'delete_logo': 'yes'
            }

        c = Client()
        c.login(username='******', password='******')
        response = c.post(self.url, data)
        self.assertStatusCodeEquals(response, 302)
        self.assertEqual(response['Location'],
                          'http://%s%s' % (
                self.site_settings.site.domain,
                self.url))

        user = User.objects.get(pk=self.user.pk)
        profile = user.get_profile()
        self.assertFalse(profile.logo)
Ejemplo n.º 13
0
class AdminTest(TestCase):
    fixtures = ['l10n-data.yaml', 'sample-store-data.yaml', 'products.yaml', 'initial_data.yaml']

    def setUp(self):
        self.client = Client()
        user = User.objects.create_user('fredsu', '*****@*****.**', 'passwd')
        user.is_staff = True
        user.is_superuser = True
        user.save()
        self.client.login(username='******', password='******')

    def tearDown(self):
        cache_delete()

    def test_index(self):
        response = self.client.get('/admin/')
        self.assertContains(response, "contact/contact/", status_code=200)

    #def test_product(self):
        response = self.client.get('/admin/product/product/1/')
        self.assertContains(response, "Django Rocks shirt", status_code=200)

    #def test_configurableproduct(self):
        response = self.client.get('/admin/configurable/configurableproduct/1/')
        self.assertContains(response, "Small, Black", status_code=200)
Ejemplo n.º 14
0
Archivo: tests.py Proyecto: jjdu/gbd
    def test_get_covariate_types(self):
        c = Client()

        url = reverse('gbd.covariate_data_server.views.get_covariate_types')
        response = c.get(url)
        self.assertRedirects(response, '/accounts/login/?next=%s'%url)
        # then login and do functional tests
        c.login(username='******', password='******')

        response = c.get(url)
        #import pdb;pdb.set_trace()
        resp_json = json.loads(response.content)['cov']
        
        self.assertEqual(resp_json[0]['slug'], 'GDP')
        self.assertEqual(resp_json[0]['uploader'], 'red')
        self.assertEqual(resp_json[0]['source'], 'web')
        self.assertEqual(resp_json[0]['notes'], 'notes')
        self.assertEqual(resp_json[0]['year range'], '1950-2010')
        self.assertEqual(resp_json[0]['region only'], 'False')
        self.assertEqual(resp_json[0]['mean'], 0.130)
        self.assertEqual(resp_json[0]['variance'], 0.004817)
        self.assertEqual(resp_json[1]['slug'], 'ABC')
        self.assertEqual(resp_json[1]['uploader'], 'red')
        self.assertEqual(resp_json[1]['source'], 'web')
        self.assertEqual(resp_json[1]['notes'], 'notes')
        self.assertEqual(resp_json[1]['year range'], '1950-2010')
        self.assertEqual(resp_json[1]['region only'], 'True')
        self.assertEqual(resp_json[1]['mean'], 0.095)
        self.assertEqual(resp_json[1]['variance'], 0.002692)
    def test_POST_success(self):
        """
        Filling the ProfileForm with data should cause the Profile to be
        updated.
        """
        data = {
            'username': '******',
            'name': 'First Last',
            'email': '*****@*****.**',
            'description': 'New Description',
            'location': 'Where I am',
            'website': 'http://www.google.com'
            }
        c = Client()
        c.login(username='******', password='******')
        response = c.post(self.url, data)
        self.assertStatusCodeEquals(response, 302)
        self.assertEqual(response['Location'],
                          'http://%s%s' % (
                self.site_settings.site.domain,
                self.url))

        user = User.objects.get(pk=self.user.pk)
        self.assertEqual(user.username, 'newusername')
        self.assertEqual(user.first_name, 'First')
        self.assertEqual(user.last_name, 'Last')
        self.assertEqual(user.email, '*****@*****.**')
        self.assertEqual(user.get_profile().description,
                          'New Description')
        self.assertEqual(user.get_profile().location, 'Where I am')
        self.assertEqual(user.get_profile().website,
                          'http://www.google.com/')
Ejemplo n.º 16
0
    def test_translated_competition_entry_stored_against_the_main_lang(self):
        client = Client()
        client.login(username='******', password='******')

        en_comp = YourWordsCompetition(
            title='Test Competition',
            description='This is the description',
            slug='test-competition')
        self.competition_index.add_child(instance=en_comp)
        en_comp.save_revision().publish()

        self.client.post(reverse(
            'add_translation', args=[en_comp.id, 'fr']))
        fr_comp = YourWordsCompetition.objects.get(
            slug='french-translation-of-test-competition')
        fr_comp.save_revision().publish()

        client.post(
            reverse('molo.yourwords:competition_entry', args=[fr_comp.slug]), {
                'story_name': 'this is a french story',
                'story_text': 'The text',
                'terms_or_conditions_approved': 'true'})

        entry = YourWordsCompetitionEntry.objects.all().first()
        self.assertEqual(entry.story_name, 'this is a french story')
        self.assertEqual(entry.competition.id, en_comp.id)
Ejemplo n.º 17
0
Archivo: tests.py Proyecto: jjdu/gbd
    def test_upload(self):
        c = Client()

        url = reverse('gbd.covariate_data_server.views.covariate_upload')
        response = c.get(url)
        self.assertRedirects(response, '/accounts/login/?next=%s'%url)
        # then login and do functional tests
        c.login(username='******', password='******')

        response = c.get(url)
        self.assertTemplateUsed(response, 'covariate_upload.html')

        response = c.post(url, {})
        self.assertTemplateUsed(response, 'covariate_upload.html')

        # now do it right, and make sure that data and datasets are added
        from StringIO import StringIO
        f = StringIO(',iso3,year,LDI_id,LDI_usd\n1,ABW,1950,1533.743774,1105.747437\n1,ABW,1951,1533.843774,1105.87437\n')
        f.name = 'LDI.csv'
        response = c.post(url, {'file':f, 'type': 'LDI_id', 'source': 'web', 'notes': 'description', 'uploader': 'red', 'yearStart': 1950, 'yearEnd': 2010})
        self.assertRedirects(response, reverse('gbd.covariate_data_server.views.covariate_type_list_show'))
        self.assertEqual(CovariateType.objects.filter(slug='LDI_id').count(), 1)
        self.assertEqual(Covariate.objects.filter(type__slug='LDI_id', sex='male').count(), 2)
        self.assertEqual(Covariate.objects.filter(type__slug='LDI_id', sex='female').count(), 2)
        self.assertEqual(Covariate.objects.filter(type__slug='LDI_id', sex='total').count(), 2)
Ejemplo n.º 18
0
    def test_footprint_viewset(self):
        csrf_client = Client(enforce_csrf_checks=True)

        grp = GroupFactory(permissions=ADD_CHANGE_PERMISSIONS)
        contributor = UserFactory(group=grp)

        csrf_client.login(username=contributor.username, password="******")

        # get a csrf token
        url = reverse('create-footprint-view')
        response = csrf_client.get(url)

        footprint = FootprintFactory()
        data = {'pk': footprint.id, 'title': 'abcdefg'}
        content = encode_multipart('BoUnDaRyStRiNg', data)
        content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'

        url = '/api/footprint/%s/' % footprint.id

        csrf_header = response.cookies['csrftoken'].value
        response = csrf_client.patch(url, content,
                                     content_type=content_type,
                                     HTTP_X_CSRFTOKEN=csrf_header)
        self.assertEquals(response.status_code, 200)

        footprint.refresh_from_db()
        self.assertEquals(footprint.title, 'abcdefg')
Ejemplo n.º 19
0
class CampaignsAppTestcase(TestCase):

    def setUp(self):
        self.c = Client()
        self.user = User.objects.create_user(
            username="******", email="*****@*****.**", password="******")
        # self.publisher = Publisher.objects.create(
        #     name='bsp', slug='bsp', address='address')
        # self.book = Book.objects.create(publisher=self.publisher,
        #                                 image='/home/agiliq/Desktop/screenshots/gradmale_avatar.png',
        # title='title', slug='slug', author='author', cost='40.0')

    def test_CampaignsListView(self):
        response = self.c.get(reverse("campaigns:list_of_campaigns"))
        self.assertEqual(302, response.status_code)
        self.c.login(username="******", password="******")
        response = self.c.get(reverse("campaigns:list_of_campaigns"))
        self.assertEqual(200, response.status_code)

    def test_MycampaignsView(self):
        response = self.c.get(
            reverse("campaigns:my_campaigns", args=[self.user.id]))
        self.assertEqual(302, response.status_code)
        self.c.login(username="******", password="******")
        response = self.c.get(
            reverse("campaigns:my_campaigns", args=[self.user.id]))
        self.assertEqual(200, response.status_code)
Ejemplo n.º 20
0
 def test_01_add_page(self):
     """Test that the add admin page could be displayed via the
     admin"""
     c = Client()
     c.login(username= '******', password='******')
     response = c.get('/admin/pages/page/add/')
     self.assertEqual(response.status_code, 200)
Ejemplo n.º 21
0
    def test_25_page_admin_view(self):
        """Test page admin view"""
        c = Client()
        c.login(username= '******', password='******')
        page_data = self.get_new_page_data()
        page_data['slug'] = 'page-1'
        response = c.post('/admin/pages/page/add/', page_data)
        page = Content.objects.get_content_slug_by_slug('page-1').page
        self.assertEqual(page.status, 1)
        response = c.post('/admin/pages/page/%d/change-status/' %
            page.id, {'status':Page.DRAFT})
        page = Content.objects.get_content_slug_by_slug('page-1').page
        self.assertEqual(page.status, Page.DRAFT)

        url = '/admin/pages/page/%d/modify-content/title/en-us/' % page.id
        response = c.post(url, {'content': 'test content'})
        self.assertEqual(page.title(), 'test content')

        # TODO: realy test these methods
        url = '/admin/pages/page/%d/traduction/en-us/' % page.id
        response = c.get(url)
        self.assertEqual(response.status_code, 200)
        
        url = '/admin/pages/page/%d/sub-menu/' % page.id
        response = c.get(url)
        self.assertEqual(response.status_code, 200)

        url = '/admin/pages/page/%d/get-content/1/' % page.id
        response = c.get(url)
        self.assertEqual(response.status_code, 200)
Ejemplo n.º 22
0
    def test_access_time_change_list(self):
        """ """
        # Issue #y (client vs browser.get)
        t_info("Opening browser to get to room access log page......", 3)
        self.browser.get(self.live_server_url +
            '/lockadmin/rfid_lock_management/accesstime/')
        self.browser.maximize_window()

        t_info("logging in as staff user....", 3)
        client = Client()
        client.login(username='******', password='******')
        response = client.get("/lockadmin/rfid_lock_management/accesstime/")

        t_info("Are we on the change list for access times? Check "
               "template and title.", 4)
        self.assertTemplateUsed(response,
            'admin/rfid_lock_management/change_list.html')
        title = self.browser.find_element_by_tag_name('title')
        self.assertEqual(title.text,
            'Room access log | RFID Lock Administration')

        t_info("Does user see listed the doors they are allowed to manage in "
               "top navigation bar?", 4)
        # in pk order
        navbar_doors = "Doors you manage: Community Theater, Seminar Room"
        base_page_body = self.browser.find_element_by_tag_name('body')
        self.assertIn(navbar_doors, base_page_body.text)
Ejemplo n.º 23
0
    def testExportTokens(self):
        c = Client()
        c.login(**{'username': '******', 'password': '******'})
        # no data = 404
        resp = get_export_response(c)
        self.assertEqual(404, resp.status_code)

        # data = data
        _submit_form()

        # now that this is time based we have to sleep first. this is annoying
        time.sleep(1)
        resp = get_export_response(c)
        self.assertEqual(200, resp.status_code)
        self.assertTrue(_content(resp) is not None)
        self.assertTrue("X-CommCareHQ-Export-Token" in resp)
        prev_token = resp["X-CommCareHQ-Export-Token"]

        # data but no new data = 404
        resp = get_export_response(c, prev_token)
        self.assertEqual(404, resp.status_code)

        _submit_form()
        time.sleep(1)
        resp = get_export_response(c, prev_token)
        self.assertEqual(200, resp.status_code)
        self.assertTrue(_content(resp) is not None)
        self.assertTrue("X-CommCareHQ-Export-Token" in resp)
Ejemplo n.º 24
0
class TestBulkCoordBased(TestCase):
    fixtures = ['test_data',]

    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user(
            'featuretest', '*****@*****.**', password='******')
        self.ds = DataSheet.objects.get(pk=19) # northwest straights
        d = os.path.dirname(__file__)
        testdir = os.path.abspath(os.path.join(d, 'fixtures', 'testdata'))

        self.fpath = os.path.join(testdir, 'test_bulk_derelict.csv')
     
    def test_derelict_post(self):
        self.client.login(username='******', password='******')
        url = '/datasheet/bulk_import/'
        num_events = Event.objects.all().count()
        num_sites = Site.objects.all().count()
        with open(self.fpath) as f:
            response = self.client.post(url, {
                'organization': 'Northwest Straights', 
                'project_id': 1, 
                'datasheet_id': self.ds.pk,
                'csvfile': f
                }
            )
        d = pq(response.content)
        el = d("ul.errorlist li")
        self.assertEqual(response.status_code, 200, response.content)
        self.assertEqual(len(el), 0)
        # should have 3 new events at 2 new sites
        self.assertEqual(Event.objects.all().count(), num_events+3)
        self.assertEqual(Site.objects.all().count(), num_sites+2)
Ejemplo n.º 25
0
    def testExportFilter(self):
        c = Client()
        c.login(**{'username': '******', 'password': '******'})

        # initially nothing
        self.assertEqual(404, get_export_response(c).status_code)

        # submit, assert something
        f = get_form()
        _submit_form(f)
        resp = get_export_response(c)
        self.assertEqual(200, resp.status_code)
        initial_content = _content(resp)
        
        # resubmit, assert same since it's a dupe
        _submit_form(f)
        resp = get_export_response(c)
        self.assertEqual(200, resp.status_code)
        # hack: check for the number of rows to ensure the new one 
        # didn't get added. They aren't exactly the same because the
        # duplicate adds to the schema.
        content = _content(resp)
        self.assertEqual(initial_content.count("<tr>"), 
                         content.count("<tr>"))
        
        # unless we explicitly include errors
        resp = get_export_response(c, include_errors=True)
        self.assertEqual(200, resp.status_code)
        self.assertTrue(len(_content(resp)) > len(initial_content))
Ejemplo n.º 26
0
 def test_view_edit_profile_page(self):
     """Get edit profile page."""
     c = Client()
     c.login(username='******', password='******')
     response = c.get(reverse('profiles_edit',
                              kwargs={'display_name': 'koki'}))
     self.assertTemplateUsed(response, 'profiles_edit.html')
Ejemplo n.º 27
0
 def test_view_delete_profile_page(self):
     """Get delete profile page."""
     c = Client()
     c.login(username='******', password='******')
     response = c.get(reverse('profiles_delete',
                              kwargs={'display_name': 'koki'}), follow=True)
     self.assertTemplateUsed(response, 'main.html')
Ejemplo n.º 28
0
class BuilderTest(TestCase):
    fixtures = [
            "presets/fixtures/profile_fixtures.json",
            "presets/fixtures/test_fixtures.json",
            "ocrmodels/fixtures/test_fixtures.json"
            "projects/fixtures/test_fixtures.json",
            "batch/fixtures/test_batch.json",
            "ocrtasks/fixtures/test_task.json"]

    def setUp(self):
        """
            Setup OCR tests.  Creates a test user.
        """
        self.testuser = User.objects.create_user("test_user", "*****@*****.**", "testpass")
        self.client = Client()
        self.client.login(username="******", password="******")

    def tearDown(self):
        """
        Revert any changes.
        """
        self.testuser.delete()

    def test_builder(self):
        r = self.client.get("/presets/builder/")
        self.assertEqual(r.status_code, 200)
Ejemplo n.º 29
0
    def test_view_incomplete_profile_page(self):
        """Test permission to view incomplete profile pages.

        Only users with profiles.can_edit_profiles permission can view
        profiles of users with incomplete profiles.

        """
        c = Client()

        # Test as anonymous.
        url = reverse('profiles_view_profile',
                      kwargs={'display_name': 'rep2'})

        response = c.get(url, follow=True)
        self.assertTemplateUsed(response, '404.html',
                                'Anonymous can view the page')

        # Test as logged in w/o permissions.
        c.login(username='******', password='******')
        response = c.get(url, follow=True)
        self.assertTemplateUsed(response, '404.html',
                                'Rep without permission can view the page')

        # Test as admin.
        c.login(username='******', password='******')
        response = c.get(url, follow=True)
        self.assertTemplateUsed(response, 'profiles_view.html',
                                'Admin can\'t view the page')
Ejemplo n.º 30
0
    def test_06_site_framework(self):
        """Test the site framework, and test if it's possible to
        disable it"""

        # this is necessary to make the test pass
        from pages import settings as pages_settings
        setattr(pages_settings, "SITE_ID", 2)
        setattr(pages_settings, "PAGE_USE_SITE_ID", True)

        c = Client()
        c.login(username= '******', password='******')
        page_data = self.get_new_page_data()
        page_data["sites"] = [2]
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        page = Content.objects.get_content_slug_by_slug(page_data['slug']).page
        self.assertEqual(page.sites.count(), 1)
        self.assertEqual(page.sites.all()[0].id, 2)

        page_data = self.get_new_page_data()
        page_data["sites"] = [3]
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        # we cannot get a slug that doesn't exist
        content = Content.objects.get_content_slug_by_slug("this doesn't exist")
        self.assertEqual(content, None)

        # we cannot get the data posted on another site
        content = Content.objects.get_content_slug_by_slug(page_data['slug'])
        self.assertEqual(content, None)

        setattr(pages_settings, "SITE_ID", 3)
        page = Content.objects.get_content_slug_by_slug(page_data['slug']).page
        self.assertEqual(page.sites.count(), 1)
        self.assertEqual(page.sites.all()[0].id, 3)

        # with param
        self.assertEqual(Page.objects.on_site(2).count(), 1)
        self.assertEqual(Page.objects.on_site(3).count(), 1)

        # without param
        self.assertEqual(Page.objects.on_site().count(), 1)
        setattr(pages_settings, "SITE_ID", 2)
        self.assertEqual(Page.objects.on_site().count(), 1)

        page_data = self.get_new_page_data()
        page_data["sites"] = [2, 3]
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')

        self.assertEqual(Page.objects.on_site(3).count(), 2)
        self.assertEqual(Page.objects.on_site(2).count(), 2)
        self.assertEqual(Page.objects.on_site().count(), 2)

        setattr(pages_settings, "PAGE_USE_SITE_ID", False)

        # we should get everything
        self.assertEqual(Page.objects.on_site().count(), 3)
Ejemplo n.º 31
0
class SysadminBaseTestCase(ModuleStoreTestCase):
    """
    Base class with common methods used in XML and Mongo tests
    """

    TEST_REPO = 'https://github.com/mitocw/edx4edx_lite.git'
    TEST_BRANCH = 'testing_do_not_delete'
    TEST_BRANCH_COURSE = SlashSeparatedCourseKey('MITx', 'edx4edx_branch',
                                                 'edx4edx')

    def setUp(self):
        """Setup test case by adding primary user."""
        super(SysadminBaseTestCase, self).setUp(create_user=False)
        self.user = UserFactory.create(username='******',
                                       email='*****@*****.**',
                                       password='******')
        self.client = Client()

    def _setstaff_login(self):
        """Makes the test user staff and logs them in"""
        GlobalStaff().add_users(self.user)
        self.client.login(username=self.user.username, password='******')

    def _add_edx4edx(self, branch=None):
        """Adds the edx4edx sample course"""
        post_dict = {
            'repo_location': self.TEST_REPO,
            'action': 'add_course',
        }
        if branch:
            post_dict['repo_branch'] = branch
        return self.client.post(reverse('sysadmin_courses'), post_dict)

    def _rm_edx4edx(self):
        """Deletes the sample course from the XML store"""
        def_ms = modulestore()
        course_path = '{0}/edx4edx_lite'.format(
            os.path.abspath(settings.DATA_DIR))
        try:
            # using XML store
            course = def_ms.courses.get(course_path, None)
        except AttributeError:
            # Using mongo store
            course = def_ms.get_course(
                SlashSeparatedCourseKey('MITx', 'edx4edx', 'edx4edx'))

        # Delete git loaded course
        response = self.client.post(
            reverse('sysadmin_courses'), {
                'course_id': course.id.to_deprecated_string(),
                'action': 'del_course',
            })
        self.addCleanup(self._rm_glob, '{0}_deleted_*'.format(course_path))

        return response

    def _rm_glob(self, path):
        """
        Create a shell expansion of passed in parameter and iteratively
        remove them.  Must only expand to directories.
        """
        for path in glob.glob(path):
            shutil.rmtree(path)

    def _mkdir(self, path):
        """
        Create directory and add the cleanup for it.
        """
        os.mkdir(path)
        self.addCleanup(shutil.rmtree, path)
Ejemplo n.º 32
0
class AttachmentTests(TestCaseBase):
    fixtures = ['test_users.json']

    def setUp(self):
        self.old_allowed_types = constance.config.WIKI_ATTACHMENT_ALLOWED_TYPES
        constance.config.WIKI_ATTACHMENT_ALLOWED_TYPES = 'text/plain'
        super(AttachmentTests, self).setUp()
        self.client = Client()  # file views don't need LocalizingClient
        self.client.login(username='******', password='******')

    def tearDown(self):
        constance.config.WIKI_ATTACHMENT_ALLOWED_TYPES = self.old_allowed_types

    def _post_new_attachment(self):
        file_for_upload = make_test_file(
            content='A test file uploaded into kuma.')
        post_data = {
            'title': 'Test uploaded file',
            'description': 'A test file uploaded into kuma.',
            'comment': 'Initial upload',
            'file': file_for_upload,
        }

        resp = self.client.post(reverse('attachments.new_attachment'),
                                data=post_data)
        return resp

    def test_legacy_redirect(self):
        test_user = User.objects.get(username='******')
        test_file_content = 'Meh meh I am a test file.'
        test_files = (
            {
                'file_id': 97,
                'filename': 'Canvas_rect.png',
                'title': 'Canvas rect',
                'slug': 'canvas-rect'
            },
            {
                'file_id': 107,
                'filename': 'Canvas_smiley.png',
                'title': 'Canvas smiley',
                'slug': 'canvas-smiley'
            },
            {
                'file_id': 86,
                'filename': 'Canvas_lineTo.png',
                'title': 'Canvas lineTo',
                'slug': 'canvas-lineto'
            },
            {
                'file_id': 55,
                'filename': 'Canvas_arc.png',
                'title': 'Canvas arc',
                'slug': 'canvas-arc'
            },
        )
        for f in test_files:
            a = Attachment(title=f['title'],
                           slug=f['slug'],
                           mindtouch_attachment_id=f['file_id'])
            a.save()
            now = datetime.datetime.now()
            r = AttachmentRevision(attachment=a,
                                   mime_type='text/plain',
                                   title=f['title'],
                                   slug=f['slug'],
                                   description='',
                                   created=now,
                                   is_approved=True)
            r.creator = test_user
            r.file.save(f['filename'], ContentFile(test_file_content))
            r.make_current()
            mindtouch_url = reverse('attachments.mindtouch_file_redirect',
                                    args=(),
                                    kwargs={
                                        'file_id': f['file_id'],
                                        'filename': f['filename']
                                    })
            resp = self.client.get(mindtouch_url)
            eq_(301, resp.status_code)
            ok_(a.get_file_url() in resp['Location'])

    def test_new_attachment(self):
        resp = self._post_new_attachment()
        eq_(302, resp.status_code)

        attachment = Attachment.objects.get(title='Test uploaded file')
        eq_(resp['Location'],
            'http://testserver%s' % attachment.get_absolute_url())

        rev = attachment.current_revision
        eq_('admin', rev.creator.username)
        eq_('A test file uploaded into kuma.', rev.description)
        eq_('Initial upload', rev.comment)
        ok_(rev.is_approved)

    def test_edit_attachment(self):
        file_for_upload = make_test_file(
            content='I am a test file for editing.')

        post_data = {
            'title': 'Test editing file',
            'description': 'A test file for editing.',
            'comment': 'Initial upload',
            'file': file_for_upload,
        }

        resp = self.client.post(reverse('attachments.new_attachment'),
                                data=post_data)

        tdir = tempfile.gettempdir()
        edited_file_for_upload = tempfile.NamedTemporaryFile(suffix=".txt",
                                                             dir=tdir)
        edited_file_for_upload.write(
            'I am a new version of the test file for editing.')
        edited_file_for_upload.seek(0)

        post_data = {
            'title': 'Test editing file',
            'description': 'A test file for editing.',
            'comment': 'Second revision.',
            'file': edited_file_for_upload,
        }

        attachment = Attachment.objects.get(title='Test editing file')

        resp = self.client.post(reverse('attachments.edit_attachment',
                                        kwargs={
                                            'attachment_id': attachment.id,
                                        }),
                                data=post_data)

        eq_(302, resp.status_code)

        # Re-fetch because it's been updated.
        attachment = Attachment.objects.get(title='Test editing file')
        eq_(resp['Location'],
            'http://testserver%s' % attachment.get_absolute_url())

        eq_(2, attachment.revisions.count())

        rev = attachment.current_revision
        eq_('admin', rev.creator.username)
        eq_('Second revision.', rev.comment)
        ok_(rev.is_approved)

        url = attachment.get_file_url()
        resp = self.client.get(url, HTTP_HOST=settings.ATTACHMENT_HOST)
        eq_('text/plain', rev.mime_type)
        ok_('I am a new version of the test file for editing.' in resp.content)

    def test_attachment_raw_requires_attachment_host(self):
        resp = self._post_new_attachment()
        attachment = Attachment.objects.get(title='Test uploaded file')

        url = attachment.get_file_url()
        resp = self.client.get(url)
        eq_(301, resp.status_code)
        eq_(attachment.get_file_url(), resp['Location'])

        url = attachment.get_file_url()
        resp = self.client.get(url, HTTP_HOST=settings.ATTACHMENT_HOST)
        eq_('ALLOW-FROM: %s' % settings.DOMAIN, resp['x-frame-options'])
        eq_(200, resp.status_code)

    def test_attachment_detail(self):
        file_for_upload = make_test_file(
            content='I am a test file for attachment detail view.')

        post_data = {
            'title': 'Test file for viewing',
            'description': 'A test file for viewing.',
            'comment': 'Initial upload',
            'file': file_for_upload,
        }

        resp = self.client.post(reverse('attachments.new_attachment'),
                                data=post_data)

        attachment = Attachment.objects.get(title='Test file for viewing')

        resp = self.client.get(
            reverse('attachments.attachment_detail',
                    kwargs={
                        'attachment_id': attachment.id,
                    }))
        eq_(200, resp.status_code)

    def test_get_previous(self):
        """
        AttachmentRevision.get_previous() should return this revisions's
        files's most recent approved revision."""
        test_user = User.objects.get(username='******')
        a = Attachment(title='Test attachment for get_previous',
                       slug='test-attachment-for-get-previous')
        a.save()
        r = AttachmentRevision(attachment=a,
                               mime_type='text/plain',
                               title=a.title,
                               slug=a.slug,
                               description='',
                               comment='Initial revision.',
                               created=datetime.datetime.now() -
                               datetime.timedelta(seconds=30),
                               creator=test_user,
                               is_approved=True)
        r.file.save('get_previous_test_file.txt',
                    ContentFile('I am a test file for get_previous'))
        r.save()
        r.make_current()

        r2 = AttachmentRevision(attachment=a,
                                mime_type='text/plain',
                                title=a.title,
                                slug=a.slug,
                                description='',
                                comment='First edit..',
                                created=datetime.datetime.now(),
                                creator=test_user,
                                is_approved=True)
        r2.file.save('get_previous_test_file.txt',
                     ContentFile('I am a test file for get_previous'))
        r2.save()
        r2.make_current()

        eq_(r, r2.get_previous())

    def test_mime_type_filtering(self):
        """Don't allow uploads outside of the explicitly-permitted
        mime-types."""
        #SLIGHT HACK: this requires the default set of allowed
        #mime-types specified in settings.py. Specifically, adding
        #'text/html' to that set will make this test fail.
        test_user = User.objects.get(username='******')
        a = Attachment(title='Test attachment for file type filter',
                       slug='test-attachment-for-file-type-filter')
        a.save()
        r = AttachmentRevision(attachment=a,
                               mime_type='text/plain',
                               title=a.title,
                               slug=a.slug,
                               description='',
                               comment='Initial revision.',
                               created=datetime.datetime.now() -
                               datetime.timedelta(seconds=30),
                               creator=test_user,
                               is_approved=True)
        r.file.save('mime_type_filter_test_file.txt',
                    ContentFile('I am a test file for mime-type filtering'))

        # Shamelessly stolen from Django's own file-upload tests.
        tdir = tempfile.gettempdir()
        file_for_upload = tempfile.NamedTemporaryFile(suffix=".html", dir=tdir)
        file_for_upload.write('<html>I am a file that tests'
                              'mime-type filtering.</html>.')
        file_for_upload.seek(0)

        post_data = {
            'title': 'Test disallowed file type',
            'description': 'A file kuma should disallow on type.',
            'comment': 'Initial upload',
            'file': file_for_upload,
        }

        resp = self.client.post(reverse('attachments.edit_attachment',
                                        kwargs={'attachment_id': a.id}),
                                data=post_data)
        eq_(200, resp.status_code)
        ok_('Files of this type are not permitted.' in resp.content)

    def test_intermediate(self):
        """
        Test that the intermediate DocumentAttachment gets created
        correctly when adding an Attachment with a document_id.

        """
        doc = document(locale='en', slug='attachment-test-intermediate')
        doc.save()
        rev = revision(document=doc, is_approved=True)
        rev.save()

        file_for_upload = make_test_file(
            content='A file for testing intermediate attachment model.')

        post_data = {
            'title': 'Intermediate test file',
            'description': 'Intermediate test file',
            'comment': 'Initial upload',
            'file': file_for_upload,
        }

        add_url = urlparams(reverse('attachments.new_attachment'),
                            document_id=doc.id)
        resp = self.client.post(add_url, data=post_data)
        eq_(302, resp.status_code)

        eq_(1, doc.files.count())

        intermediates = DocumentAttachment.objects.filter(document__pk=doc.id)
        eq_(1, intermediates.count())

        intermediate = intermediates[0]
        eq_('admin', intermediate.attached_by.username)
        eq_(file_for_upload.name.split('/')[-1], intermediate.name)

    def test_files_dict(self):
        doc = document(locale='en', slug='attachment-test-files-dict')
        doc.save()
        rev = revision(document=doc, is_approved=True)
        rev.save()

        test_file_1 = make_test_file(
            content='A file for testing the files dict')

        post_data = {
            'title': 'Files dict test file',
            'description': 'Files dict test file',
            'comment': 'Initial upload',
            'file': test_file_1,
        }

        add_url = urlparams(reverse('attachments.new_attachment'),
                            document_id=doc.id)
        self.client.post(add_url, data=post_data)

        test_file_2 = make_test_file(
            content='Another file for testing the files dict')

        post_data = {
            'title': 'Files dict test file 2',
            'description': 'Files dict test file 2',
            'comment': 'Initial upload',
            'file': test_file_2,
        }

        self.client.post(add_url, data=post_data)

        doc = Document.objects.get(pk=doc.id)

        files_dict = doc.files_dict()

        file1 = files_dict[test_file_1.name.split('/')[-1]]
        eq_('admin', file1['attached_by'])
        eq_('Files dict test file', file1['description'])
        eq_('text/plain', file1['mime_type'])
        ok_(test_file_1.name.split('/')[-1] in file1['url'])

        file2 = files_dict[test_file_2.name.split('/')[-1]]
        eq_('admin', file2['attached_by'])
        eq_('Files dict test file 2', file2['description'])
        eq_('text/plain', file2['mime_type'])
        ok_(test_file_2.name.split('/')[-1] in file2['url'])

    def test_list_files(self):
        list_files_url = reverse('attachments.list_files',
                                 locale=settings.WIKI_DEFAULT_LANGUAGE)
        resp = self.client.get(list_files_url)
        eq_(200, resp.status_code)
        ok_('All Files' in resp.content)
Ejemplo n.º 33
0
class ViewsTestCase(UrlResetMixin, ModuleStoreTestCase, MockRequestSetupMixin):

    @patch.dict("django.conf.settings.FEATURES", {"ENABLE_DISCUSSION_SERVICE": True})
    def setUp(self):

        # Patching the ENABLE_DISCUSSION_SERVICE value affects the contents of urls.py,
        # so we need to call super.setUp() which reloads urls.py (because
        # of the UrlResetMixin)
        super(ViewsTestCase, self).setUp(create_user=False)

        # create a course
        self.course = CourseFactory.create(
            org='MITx', course='999',
            discussion_topics={"Some Topic": {"id": "some_topic"}},
            display_name='Robot Super Course',
        )
        self.course_id = self.course.id
        # seed the forums permissions and roles
        call_command('seed_permissions_roles', self.course_id.to_deprecated_string())

        # Patch the comment client user save method so it does not try
        # to create a new cc user when creating a django user
        with patch('student.models.cc.User.save'):
            uname = 'student'
            email = '*****@*****.**'
            password = '******'

            # Create the user and make them active so we can log them in.
            self.student = User.objects.create_user(uname, email, password)
            self.student.is_active = True
            self.student.save()

            # Enroll the student in the course
            CourseEnrollmentFactory(user=self.student,
                                    course_id=self.course_id)

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

    def test_create_thread(self, mock_request):
        mock_request.return_value.status_code = 200
        self._set_mock_request_data(mock_request, {
            "thread_type": "discussion",
            "title": "Hello",
            "body": "this is a post",
            "course_id": "MITx/999/Robot_Super_Course",
            "anonymous": False,
            "anonymous_to_peers": False,
            "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
            "created_at": "2013-05-10T18:53:43Z",
            "updated_at": "2013-05-10T18:53:43Z",
            "at_position_list": [],
            "closed": False,
            "id": "518d4237b023791dca00000d",
            "user_id": "1",
            "username": "******",
            "votes": {
                "count": 0,
                "up_count": 0,
                "down_count": 0,
                "point": 0
            },
            "abuse_flaggers": [],
            "type": "thread",
            "group_id": None,
            "pinned": False,
            "endorsed": False,
            "unread_comments_count": 0,
            "read": False,
            "comments_count": 0,
        })
        thread = {
            "thread_type": "discussion",
            "body": ["this is a post"],
            "anonymous_to_peers": ["false"],
            "auto_subscribe": ["false"],
            "anonymous": ["false"],
            "title": ["Hello"],
        }
        url = reverse('create_thread', kwargs={'commentable_id': 'i4x-MITx-999-course-Robot_Super_Course',
                                               'course_id': self.course_id.to_deprecated_string()})
        response = self.client.post(url, data=thread)
        assert_true(mock_request.called)
        mock_request.assert_called_with(
            'post',
            '{prefix}/i4x-MITx-999-course-Robot_Super_Course/threads'.format(prefix=CS_PREFIX),
            data={
                'thread_type': 'discussion',
                'body': u'this is a post',
                'anonymous_to_peers': False, 'user_id': 1,
                'title': u'Hello',
                'commentable_id': u'i4x-MITx-999-course-Robot_Super_Course',
                'anonymous': False,
                'course_id': u'MITx/999/Robot_Super_Course',
            },
            params={'request_id': ANY},
            headers=ANY,
            timeout=5
        )
        assert_equal(response.status_code, 200)

    def test_delete_comment(self, mock_request):
        self._set_mock_request_data(mock_request, {
            "user_id": str(self.student.id),
            "closed": False,
        })
        test_comment_id = "test_comment_id"
        request = RequestFactory().post("dummy_url", {"id": test_comment_id})
        request.user = self.student
        request.view_name = "delete_comment"
        response = views.delete_comment(request, course_id=self.course.id.to_deprecated_string(), comment_id=test_comment_id)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(mock_request.called)
        args = mock_request.call_args[0]
        self.assertEqual(args[0], "delete")
        self.assertTrue(args[1].endswith("/{}".format(test_comment_id)))

    def _setup_mock_request(self, mock_request, include_depth=False):
        """
        Ensure that mock_request returns the data necessary to make views
        function correctly
        """
        mock_request.return_value.status_code = 200
        data = {
            "user_id": str(self.student.id),
            "closed": False,
        }
        if include_depth:
            data["depth"] = 0
        self._set_mock_request_data(mock_request, data)

    def _test_request_error(self, view_name, view_kwargs, data, mock_request):
        """
        Submit a request against the given view with the given data and ensure
        that the result is a 400 error and that no data was posted using
        mock_request
        """
        self._setup_mock_request(mock_request, include_depth=(view_name == "create_sub_comment"))

        response = self.client.post(reverse(view_name, kwargs=view_kwargs), data=data)
        self.assertEqual(response.status_code, 400)
        for call in mock_request.call_args_list:
            self.assertEqual(call[0][0].lower(), "get")

    def test_create_thread_no_title(self, mock_request):
        self._test_request_error(
            "create_thread",
            {"commentable_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {"body": "foo"},
            mock_request
        )

    def test_create_thread_empty_title(self, mock_request):
        self._test_request_error(
            "create_thread",
            {"commentable_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {"body": "foo", "title": " "},
            mock_request
        )

    def test_create_thread_no_body(self, mock_request):
        self._test_request_error(
            "create_thread",
            {"commentable_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {"title": "foo"},
            mock_request
        )

    def test_create_thread_empty_body(self, mock_request):
        self._test_request_error(
            "create_thread",
            {"commentable_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {"body": " ", "title": "foo"},
            mock_request
        )

    def test_update_thread_no_title(self, mock_request):
        self._test_request_error(
            "update_thread",
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {"body": "foo"},
            mock_request
        )

    def test_update_thread_empty_title(self, mock_request):
        self._test_request_error(
            "update_thread",
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {"body": "foo", "title": " "},
            mock_request
        )

    def test_update_thread_no_body(self, mock_request):
        self._test_request_error(
            "update_thread",
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {"title": "foo"},
            mock_request
        )

    def test_update_thread_empty_body(self, mock_request):
        self._test_request_error(
            "update_thread",
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {"body": " ", "title": "foo"},
            mock_request
        )

    def test_update_thread_course_topic(self, mock_request):
        self._setup_mock_request(mock_request)
        response = self.client.post(
            reverse("update_thread", kwargs={"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()}),
            data={"body": "foo", "title": "foo", "commentable_id": "some_topic"}
        )
        self.assertEqual(response.status_code, 200)

    @patch('django_comment_client.base.views.get_discussion_categories_ids', return_value=["test_commentable"])
    def test_update_thread_wrong_commentable_id(self, mock_get_discussion_id_map, mock_request):
        self._test_request_error(
            "update_thread",
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {"body": "foo", "title": "foo", "commentable_id": "wrong_commentable"},
            mock_request
        )

    def test_create_comment_no_body(self, mock_request):
        self._test_request_error(
            "create_comment",
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {},
            mock_request
        )

    def test_create_comment_empty_body(self, mock_request):
        self._test_request_error(
            "create_comment",
            {"thread_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {"body": " "},
            mock_request
        )

    def test_create_sub_comment_no_body(self, mock_request):
        self._test_request_error(
            "create_sub_comment",
            {"comment_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {},
            mock_request
        )

    def test_create_sub_comment_empty_body(self, mock_request):
        self._test_request_error(
            "create_sub_comment",
            {"comment_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {"body": " "},
            mock_request
        )

    def test_update_comment_no_body(self, mock_request):
        self._test_request_error(
            "update_comment",
            {"comment_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {},
            mock_request
        )

    def test_update_comment_empty_body(self, mock_request):
        self._test_request_error(
            "update_comment",
            {"comment_id": "dummy", "course_id": self.course_id.to_deprecated_string()},
            {"body": " "},
            mock_request
        )

    def test_update_comment_basic(self, mock_request):
        self._setup_mock_request(mock_request)
        comment_id = "test_comment_id"
        updated_body = "updated body"

        response = self.client.post(
            reverse(
                "update_comment",
                kwargs={"course_id": self.course_id.to_deprecated_string(), "comment_id": comment_id}
            ),
            data={"body": updated_body}
        )

        self.assertEqual(response.status_code, 200)
        mock_request.assert_called_with(
            "put",
            "{prefix}/comments/{comment_id}".format(prefix=CS_PREFIX, comment_id=comment_id),
            headers=ANY,
            params=ANY,
            timeout=ANY,
            data={"body": updated_body}
        )

    def test_flag_thread_open(self, mock_request):
        self.flag_thread(mock_request, False)

    def test_flag_thread_close(self, mock_request):
        self.flag_thread(mock_request, True)

    def flag_thread(self, mock_request, is_closed):
        mock_request.return_value.status_code = 200
        self._set_mock_request_data(mock_request, {
            "title": "Hello",
            "body": "this is a post",
            "course_id": "MITx/999/Robot_Super_Course",
            "anonymous": False,
            "anonymous_to_peers": False,
            "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
            "created_at": "2013-05-10T18:53:43Z",
            "updated_at": "2013-05-10T18:53:43Z",
            "at_position_list": [],
            "closed": is_closed,
            "id": "518d4237b023791dca00000d",
            "user_id": "1", "username": "******",
            "votes": {
                "count": 0,
                "up_count": 0,
                "down_count": 0,
                "point": 0
            },
            "abuse_flaggers": [1],
            "type": "thread",
            "group_id": None,
            "pinned": False,
            "endorsed": False,
            "unread_comments_count": 0,
            "read": False,
            "comments_count": 0,
        })
        url = reverse('flag_abuse_for_thread', kwargs={'thread_id': '518d4237b023791dca00000d', 'course_id': self.course_id.to_deprecated_string()})
        response = self.client.post(url)
        assert_true(mock_request.called)

        call_list = [
            (
                ('get', '{prefix}/threads/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
                {
                    'data': None,
                    'params': {'mark_as_read': True, 'request_id': ANY},
                    'headers': ANY,
                    'timeout': 5
                }
            ),
            (
                ('put', '{prefix}/threads/518d4237b023791dca00000d/abuse_flag'.format(prefix=CS_PREFIX)),
                {
                    'data': {'user_id': '1'},
                    'params': {'request_id': ANY},
                    'headers': ANY,
                    'timeout': 5
                }
            ),
            (
                ('get', '{prefix}/threads/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
                {
                    'data': None,
                    'params': {'mark_as_read': True, 'request_id': ANY},
                    'headers': ANY,
                    'timeout': 5
                }
            )
        ]

        assert_equal(call_list, mock_request.call_args_list)

        assert_equal(response.status_code, 200)

    def test_un_flag_thread_open(self, mock_request):
        self.un_flag_thread(mock_request, False)

    def test_un_flag_thread_close(self, mock_request):
        self.un_flag_thread(mock_request, True)

    def un_flag_thread(self, mock_request, is_closed):
        mock_request.return_value.status_code = 200
        self._set_mock_request_data(mock_request, {
            "title": "Hello",
            "body": "this is a post",
            "course_id": "MITx/999/Robot_Super_Course",
            "anonymous": False,
            "anonymous_to_peers": False,
            "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
            "created_at": "2013-05-10T18:53:43Z",
            "updated_at": "2013-05-10T18:53:43Z",
            "at_position_list": [],
            "closed": is_closed,
            "id": "518d4237b023791dca00000d",
            "user_id": "1",
            "username": "******",
            "votes": {
                "count": 0,
                "up_count": 0,
                "down_count": 0,
                "point": 0
            },
            "abuse_flaggers": [],
            "type": "thread",
            "group_id": None,
            "pinned": False,
            "endorsed": False,
            "unread_comments_count": 0,
            "read": False,
            "comments_count": 0
        })
        url = reverse('un_flag_abuse_for_thread', kwargs={'thread_id': '518d4237b023791dca00000d', 'course_id': self.course_id.to_deprecated_string()})
        response = self.client.post(url)
        assert_true(mock_request.called)

        call_list = [
            (
                ('get', '{prefix}/threads/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
                {
                    'data': None,
                    'params': {'mark_as_read': True, 'request_id': ANY},
                    'headers': ANY,
                    'timeout': 5
                }
            ),
            (
                ('put', '{prefix}/threads/518d4237b023791dca00000d/abuse_unflag'.format(prefix=CS_PREFIX)),
                {
                    'data': {'user_id': '1'},
                    'params': {'request_id': ANY},
                    'headers': ANY,
                    'timeout': 5
                }
            ),
            (
                ('get', '{prefix}/threads/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
                {
                    'data': None,
                    'params': {'mark_as_read': True, 'request_id': ANY},
                    'headers': ANY,
                    'timeout': 5
                }
            )
        ]

        assert_equal(call_list, mock_request.call_args_list)

        assert_equal(response.status_code, 200)

    def test_flag_comment_open(self, mock_request):
        self.flag_comment(mock_request, False)

    def test_flag_comment_close(self, mock_request):
        self.flag_comment(mock_request, True)

    def flag_comment(self, mock_request, is_closed):
        mock_request.return_value.status_code = 200
        self._set_mock_request_data(mock_request, {
            "body": "this is a comment",
            "course_id": "MITx/999/Robot_Super_Course",
            "anonymous": False,
            "anonymous_to_peers": False,
            "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
            "created_at": "2013-05-10T18:53:43Z",
            "updated_at": "2013-05-10T18:53:43Z",
            "at_position_list": [],
            "closed": is_closed,
            "id": "518d4237b023791dca00000d",
            "user_id": "1",
            "username": "******",
            "votes": {
                "count": 0,
                "up_count": 0,
                "down_count": 0,
                "point": 0
            },
            "abuse_flaggers": [1],
            "type": "comment",
            "endorsed": False
        })
        url = reverse('flag_abuse_for_comment', kwargs={'comment_id': '518d4237b023791dca00000d', 'course_id': self.course_id.to_deprecated_string()})
        response = self.client.post(url)
        assert_true(mock_request.called)

        call_list = [
            (
                ('get', '{prefix}/comments/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
                {
                    'data': None,
                    'params': {'request_id': ANY},
                    'headers': ANY,
                    'timeout': 5
                }
            ),
            (
                ('put', '{prefix}/comments/518d4237b023791dca00000d/abuse_flag'.format(prefix=CS_PREFIX)),
                {
                    'data': {'user_id': '1'},
                    'params': {'request_id': ANY},
                    'headers': ANY,
                    'timeout': 5
                }
            ),
            (
                ('get', '{prefix}/comments/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
                {
                    'data': None,
                    'params': {'request_id': ANY},
                    'headers': ANY,
                    'timeout': 5
                }
            )
        ]

        assert_equal(call_list, mock_request.call_args_list)

        assert_equal(response.status_code, 200)

    def test_un_flag_comment_open(self, mock_request):
        self.un_flag_comment(mock_request, False)

    def test_un_flag_comment_close(self, mock_request):
        self.un_flag_comment(mock_request, True)

    def un_flag_comment(self, mock_request, is_closed):
        mock_request.return_value.status_code = 200
        self._set_mock_request_data(mock_request, {
            "body": "this is a comment",
            "course_id": "MITx/999/Robot_Super_Course",
            "anonymous": False,
            "anonymous_to_peers": False,
            "commentable_id": "i4x-MITx-999-course-Robot_Super_Course",
            "created_at": "2013-05-10T18:53:43Z",
            "updated_at": "2013-05-10T18:53:43Z",
            "at_position_list": [],
            "closed": is_closed,
            "id": "518d4237b023791dca00000d",
            "user_id": "1",
            "username": "******",
            "votes": {
                "count": 0,
                "up_count": 0,
                "down_count": 0,
                "point": 0
            },
            "abuse_flaggers": [],
            "type": "comment",
            "endorsed": False
        })
        url = reverse('un_flag_abuse_for_comment', kwargs={'comment_id': '518d4237b023791dca00000d', 'course_id': self.course_id.to_deprecated_string()})
        response = self.client.post(url)
        assert_true(mock_request.called)

        call_list = [
            (
                ('get', '{prefix}/comments/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
                {
                    'data': None,
                    'params': {'request_id': ANY},
                    'headers': ANY,
                    'timeout': 5
                }
            ),
            (
                ('put', '{prefix}/comments/518d4237b023791dca00000d/abuse_unflag'.format(prefix=CS_PREFIX)),
                {
                    'data': {'user_id': '1'},
                    'params': {'request_id': ANY},
                    'headers': ANY,
                    'timeout': 5
                }
            ),
            (
                ('get', '{prefix}/comments/518d4237b023791dca00000d'.format(prefix=CS_PREFIX)),
                {
                    'data': None,
                    'params': {'request_id': ANY},
                    'headers': ANY,
                    'timeout': 5
                }
            )
        ]

        assert_equal(call_list, mock_request.call_args_list)

        assert_equal(response.status_code, 200)
Ejemplo n.º 34
0
class TestViews(TestCase):
    def setUp(self):
        self.client = Client()
        self.maxDiff = None

    def test_index(self):
        c = self.client.get('/')
        self.assertEqual(200, c.status_code, 'Status code')
        self.assertTrue('0</b></span> registros de visitas' in str(c.content),
                        'Number of records in db.')

    def test_about(self):
        c = self.client.get('/about/')
        self.assertEqual(200, c.status_code, 'Status code')

    def test_search(self):
        c = self.client.get('/search/?q=romulo')
        self.assertEqual(200, c.status_code)

    def test_search_date(self):
        c = self.client.get('/search_date/?q=30/05/2014')
        self.assertEqual(200, c.status_code)

    def test_search_date_empty(self):
        c = self.client.get('/search_date/?q=')
        self.assertEqual(302, c.status_code)

    def test_search_date_empty2(self):
        c = self.client.get('/search_date/')
        self.assertEqual(302, c.status_code)

    def test_search_date_invalid(self):
        c = self.client.get('/search_date/?q=30/05/20120302')
        self.assertEqual(200, c.status_code)

    def test_search_date_invalid2(self):
        c = self.client.get('/search_date/?q=30/05/2012&page=10')
        self.assertEqual(404, c.status_code)

    def test_search_date_invalid3(self):
        c = self.client.get('/search_date/?q=30/05/2012&page=0')
        self.assertEqual(404, c.status_code)

    def test_search_date_invalid4(self):
        c = self.client.get('/search_date/?q=30/05/2012&page=abadca')
        self.assertEqual(404, c.status_code)

    def test_search_view__user_1_credits(self):
        self.setup_subscriber()
        self.subscriber.credits = 1
        self.subscriber.save()
        self.client.login(username="******", password="******")
        c = self.client.get('/search_date/?q=2010-01-01')
        self.assertIn("luego de usar 1", str(c.content))

    def setup_subscriber(self):
        self.user = User.objects.create_superuser("john", "*****@*****.**",
                                                  "smith")
        self.subscriber = Subscriber.objects.create(
            user=self.user, expiration=datetime.datetime.today(), credits=600)

    def test_query_is_dni(self):
        items = [
            {
                'query': 'yoni pacheco',
                'expected': False,
            },
            {
                'query': '10468395',
                'expected': True,
            },
            {
                'query': 'yoni pacheco 10468395',
                'expected': False,
            },
            {
                'query': '24779433-s',
                'expected': True,
            },
        ]
        for item in items:
            result = query_is_dni(item['query'])
            self.assertEqual(result, item['expected'])
Ejemplo n.º 35
0
class DeleteLanguageViewTest(UnpublishTestCase):
    def setUp(self):
        UnpublishTestCase.setUp(self)
        self.client = Client()
        self.client.login(username=self.user.username, password='******')
        self.url = '/en/teams/%s/delete-language/%s/' % (self.team.slug,
                                                         self.language.pk)

    def test_unpublish_with_forking(self):
        sub_lang1 = self.make_dependent_language('ru', self.versions[0])
        sub_lang2 = self.make_dependent_language('fr', sub_lang1.get_tip())
        forked_lang = self.make_dependent_language('de', self.versions[0])
        forked_lang.is_forked = True
        forked_lang.save()

        response = self.client.get(self.url)
        self.assertEquals(response.status_code, 200)

        response = self.client.post(self.url, {
            'verify_text': 'Yes I want to delete this language',
            'delete_ru': 1,
        })
        self.assertEquals(self.language.subtitleversion_set.extant().count(),
                          0)
        # we should delete russian, but not french or german
        self.assertEquals(sub_lang1.subtitleversion_set.extant().count(), 0)
        self.assertNotEquals(sub_lang2.subtitleversion_set.extant().count(), 0)
        self.assertNotEquals(forked_lang.subtitleversion_set.extant().count(),
                             0)

    def check_user_perm(self, user, should_have_permission):
        self.client.login(username=user.username, password='******')
        response = self.client.get(self.url)
        if should_have_permission:
            self.assertEquals(response.status_code, 200)
        else:
            self.assertRedirects(response,
                                 '/auth/login/?next=' + self.url,
                                 target_status_code=302)
        self.check_button_present(self.versions[-1], should_have_permission)

    def check_button_present(self, version, should_be_present):
        url = '/en/videos/%s/%s/%s/' % (
            version.video.video_id,
            version.subtitle_language.language_code,
            version.subtitle_language.pk,
        )
        response = self.client.get(url)
        button_html = '<a class="button" href="%s">' % self.url
        if should_be_present:
            self.assert_(button_html in response.content.decode('utf-8'))
        else:
            self.assert_(button_html not in response.content.decode('utf-8'))

    def test_permissions(self):
        self.check_user_perm(UserFactory(), False)
        self.check_user_perm(UserFactory(is_staff=True), True)
        for role in (ROLE_ADMIN, ROLE_OWNER):
            member = TeamMemberFactory(team=self.team, role=role)
            self.check_user_perm(member.user, True)
        for role in (ROLE_CONTRIBUTOR, ROLE_MANAGER):
            member = TeamMemberFactory(team=self.team, role=role)
            self.check_user_perm(member.user, False)

    def test_no_button_for_non_team_videos(self):
        non_team_version = pipeline.add_subtitles(self.non_team_video, 'en',
                                                  None)
        self.check_button_present(non_team_version, False)
Ejemplo n.º 36
0
class TestCourseListing(ModuleStoreTestCase, MilestonesTestCaseMixin):
    """
    Unit tests for getting the list of courses for a logged in user
    """
    ENABLED_SIGNALS = ['course_deleted']

    def setUp(self):
        """
        Add a student & teacher
        """
        super().setUp()

        self.student = UserFactory()
        self.teacher = UserFactory()
        GlobalStaff().add_users(self.teacher)
        self.client = Client()
        self.client.login(username=self.teacher.username, password='******')

    def _create_course_with_access_groups(self,
                                          course_location,
                                          metadata=None,
                                          default_store=None):
        """
        Create dummy course with 'CourseFactory' and enroll the student
        """
        metadata = {} if not metadata else metadata
        course = CourseFactory.create(org=course_location.org,
                                      number=course_location.course,
                                      run=course_location.run,
                                      metadata=metadata,
                                      default_store=default_store)

        CourseEnrollment.enroll(self.student, course.id)

        return course

    def tearDown(self):
        """
        Reverse the setup
        """
        self.client.logout()
        super().tearDown()

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    def test_get_course_list(self):
        """
        Test getting courses
        """
        course_location = self.store.make_course_key('Org1', 'Course1', 'Run1')
        self._create_course_with_access_groups(course_location)

        # get dashboard
        courses_list = list(get_course_enrollments(self.student, None, []))
        assert len(courses_list) == 1
        assert courses_list[0].course_id == course_location

        CourseEnrollment.unenroll(self.student, course_location)
        # get dashboard
        courses_list = list(get_course_enrollments(self.student, None, []))
        assert len(courses_list) == 0

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    def test_get_limited_number_of_courses_using_config(self):
        course_location = self.store.make_course_key('Org0', 'Course0', 'Run0')
        self._create_course_with_access_groups(course_location)

        course_location = self.store.make_course_key('Org1', 'Course1', 'Run1')
        self._create_course_with_access_groups(course_location)

        # get dashboard
        courses_list = list(get_course_enrollments(self.student, None, []))
        assert len(courses_list) == 2

        with self.settings(DASHBOARD_COURSE_LIMIT=1):
            course_limit = settings.DASHBOARD_COURSE_LIMIT
            courses_list = list(
                get_course_enrollments(self.student, None, [], course_limit))
            assert len(courses_list) == 1

    def test_errored_course_regular_access(self):
        """
        Test the course list for regular staff when get_course returns an ErrorBlock
        """
        # pylint: disable=protected-access
        mongo_store = modulestore()._get_modulestore_by_type(
            ModuleStoreEnum.Type.mongo)
        course_key = mongo_store.make_course_key('Org1', 'Course1', 'Run1')
        self._create_course_with_access_groups(
            course_key, default_store=ModuleStoreEnum.Type.mongo)

        with mock.patch('xmodule.modulestore.mongo.base.MongoKeyValueStore',
                        mock.Mock(side_effect=Exception)):
            assert isinstance(modulestore().get_course(course_key), ErrorBlock)

            # Invalidate (e.g., delete) the corresponding CourseOverview, forcing get_course to be called.
            CourseOverview.objects.filter(id=course_key).delete()

            courses_list = list(get_course_enrollments(self.student, None, []))
            assert courses_list == []

    def test_course_listing_errored_deleted_courses(self):
        """
        Create good courses, courses that won't load, and deleted courses which still have
        roles. Test course listing.
        """
        mongo_store = modulestore()._get_modulestore_by_type(
            ModuleStoreEnum.Type.mongo)  # lint-amnesty, pylint: disable=protected-access

        good_location = mongo_store.make_course_key('testOrg', 'testCourse',
                                                    'RunBabyRun')
        self._create_course_with_access_groups(
            good_location, default_store=ModuleStoreEnum.Type.mongo)

        course_location = mongo_store.make_course_key('testOrg',
                                                      'doomedCourse',
                                                      'RunBabyRun')
        self._create_course_with_access_groups(
            course_location, default_store=ModuleStoreEnum.Type.mongo)
        mongo_store.delete_course(course_location, ModuleStoreEnum.UserID.test)

        courses_list = list(get_course_enrollments(self.student, None, []))
        assert len(courses_list) == 1, courses_list
        assert courses_list[0].course_id == good_location

    @mock.patch.dict("django.conf.settings.FEATURES",
                     {'ENABLE_PREREQUISITE_COURSES': True})
    def test_course_listing_has_pre_requisite_courses(self):
        """
        Creates four courses. Enroll test user in all courses
        Sets two of them as pre-requisites of another course.
        Checks course where pre-requisite course is set has appropriate info.
        """
        course_location2 = self.store.make_course_key('Org1', 'Course2',
                                                      'Run2')
        self._create_course_with_access_groups(course_location2)
        pre_requisite_course_location = self.store.make_course_key(
            'Org1', 'Course3', 'Run3')
        self._create_course_with_access_groups(pre_requisite_course_location)
        pre_requisite_course_location2 = self.store.make_course_key(
            'Org1', 'Course4', 'Run4')
        self._create_course_with_access_groups(pre_requisite_course_location2)
        # create a course with pre_requisite_courses
        pre_requisite_courses = [
            str(pre_requisite_course_location),
            str(pre_requisite_course_location2),
        ]
        course_location = self.store.make_course_key('Org1', 'Course1', 'Run1')
        self._create_course_with_access_groups(
            course_location, {'pre_requisite_courses': pre_requisite_courses})

        set_prerequisite_courses(course_location, pre_requisite_courses)
        # get dashboard
        course_enrollments = list(
            get_course_enrollments(self.student, None, []))
        courses_having_prerequisites = frozenset(
            enrollment.course_id for enrollment in course_enrollments
            if enrollment.course_overview.pre_requisite_courses)
        courses_requirements_not_met = get_pre_requisite_courses_not_completed(
            self.student, courses_having_prerequisites)
        assert len(courses_requirements_not_met[course_location]
                   ['courses']) == len(pre_requisite_courses)
Ejemplo n.º 37
0
    def test_not_superuser_permissions(self):

        # grab bobby
        bob = get_user_model().objects.get(username='******')

        # grab a layer
        layer = Layer.objects.all()[0]

        # verify bobby has view/change permissions on it but not manage
        self.assertFalse(
            bob.has_perm('change_resourcebase_permissions',
                         layer.get_self_resource()))

        c = Client()
        self.assertTrue(c.login(username='******', password='******'))

        # 1. view_resourcebase
        # 1.1 has view_resourcebase: verify that bobby can access the layer
        # detail page
        self.assertTrue(
            bob.has_perm('view_resourcebase', layer.get_self_resource()))

        response = c.get(reverse('layer_detail', args=(layer.typename, )))
        self.assertEquals(response.status_code, 200)
        # 1.2 has not view_resourcebase: verify that bobby can not access the
        # layer detail page
        remove_perm('view_resourcebase', bob, layer.get_self_resource())
        anonymous_group = Group.objects.get(name='anonymous')
        remove_perm('view_resourcebase', anonymous_group,
                    layer.get_self_resource())
        response = c.get(reverse('layer_detail', args=(layer.typename, )))
        self.assertEquals(response.status_code, 401)

        # 2. change_resourcebase
        # 2.1 has not change_resourcebase: verify that bobby cannot access the
        # layer replace page
        response = c.get(reverse('layer_replace', args=(layer.typename, )))
        self.assertEquals(response.status_code, 401)
        # 2.2 has change_resourcebase: verify that bobby can access the layer
        # replace page
        assign_perm('change_resourcebase', bob, layer.get_self_resource())
        self.assertTrue(
            bob.has_perm('change_resourcebase', layer.get_self_resource()))
        response = c.get(reverse('layer_replace', args=(layer.typename, )))
        self.assertEquals(response.status_code, 200)

        # 3. delete_resourcebase
        # 3.1 has not delete_resourcebase: verify that bobby cannot access the
        # layer delete page
        response = c.get(reverse('layer_remove', args=(layer.typename, )))
        self.assertEquals(response.status_code, 401)
        # 3.2 has delete_resourcebase: verify that bobby can access the layer
        # delete page
        assign_perm('delete_resourcebase', bob, layer.get_self_resource())
        self.assertTrue(
            bob.has_perm('delete_resourcebase', layer.get_self_resource()))
        response = c.get(reverse('layer_remove', args=(layer.typename, )))
        self.assertEquals(response.status_code, 200)

        # 4. change_resourcebase_metadata
        # 4.1 has not change_resourcebase_metadata: verify that bobby cannot
        # access the layer metadata page
        response = c.get(reverse('layer_metadata', args=(layer.typename, )))
        self.assertEquals(response.status_code, 401)
        # 4.2 has delete_resourcebase: verify that bobby can access the layer
        # delete page
        assign_perm('change_resourcebase_metadata', bob,
                    layer.get_self_resource())
        self.assertTrue(
            bob.has_perm('change_resourcebase_metadata',
                         layer.get_self_resource()))
        response = c.get(reverse('layer_metadata', args=(layer.typename, )))
        self.assertEquals(response.status_code, 200)

        # 5. change_resourcebase_permissions
        # should be impossible for the user without change_resourcebase_permissions
        # to change permissions as the permission form is not available in the
        # layer detail page?

        # 6. change_layer_data
        # must be done in integration test sending a WFS-T request with CURL

        # 7. change_layer_style
        # 7.1 has not change_layer_style: verify that bobby cannot access
        # the layer style page
        response = c.get(reverse('layer_style_manage',
                                 args=(layer.typename, )))
        self.assertEquals(response.status_code, 401)
        # 7.2 has change_layer_style: verify that bobby can access the
        # change layer style page
        assign_perm('change_layer_style', bob, layer)
        self.assertTrue(bob.has_perm('change_layer_style', layer))
        response = c.get(reverse('layer_style_manage',
                                 args=(layer.typename, )))
        self.assertEquals(response.status_code, 200)
Ejemplo n.º 38
0
class DashboardTest(ModuleStoreTestCase, TestVerificationBase):
    """
    Tests for dashboard utility functions
    """
    ENABLED_SIGNALS = ['course_published']

    def setUp(self):
        super(DashboardTest, self).setUp()
        self.course = CourseFactory.create()
        self.user = UserFactory.create(username="******",
                                       email="*****@*****.**",
                                       password='******')
        self.client = Client()
        cache.clear()

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    def _check_verification_status_on(self, mode, value):
        """
        Check that the css class and the status message are in the dashboard html.
        """
        CourseModeFactory.create(mode_slug=mode, course_id=self.course.id)
        CourseEnrollment.enroll(self.user,
                                self.course.location.course_key,
                                mode=mode)

        if mode == 'verified':
            # Simulate a successful verification attempt
            attempt = self.create_and_submit_attempt_for_user(self.user)
            attempt.approve()

        response = self.client.get(reverse('dashboard'))
        if mode in ['professional', 'no-id-professional']:
            self.assertContains(response, 'class="course professional"')
        else:
            self.assertContains(response, 'class="course {0}"'.format(mode))
        self.assertContains(response, value)

    @patch.dict("django.conf.settings.FEATURES",
                {'ENABLE_VERIFIED_CERTIFICATES': True})
    def test_verification_status_visible(self):
        """
        Test that the certificate verification status for courses is visible on the dashboard.
        """
        self.client.login(username="******", password="******")
        self._check_verification_status_on(
            'verified', 'You&#39;re enrolled as a verified student')
        self._check_verification_status_on(
            'honor', 'You&#39;re enrolled as an honor code student')
        self._check_verification_status_off('audit', '')
        self._check_verification_status_on(
            'professional',
            'You&#39;re enrolled as a professional education student')
        self._check_verification_status_on(
            'no-id-professional',
            'You&#39;re enrolled as a professional education student',
        )

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    def _check_verification_status_off(self, mode, value):
        """
        Check that the css class and the status message are not in the dashboard html.
        """
        CourseModeFactory.create(mode_slug=mode, course_id=self.course.id)
        CourseEnrollment.enroll(self.user,
                                self.course.location.course_key,
                                mode=mode)

        if mode == 'verified':
            # Simulate a successful verification attempt
            attempt = self.create_and_submit_attempt_for_user(self.user)
            attempt.approve()

        response = self.client.get(reverse('dashboard'))

        if mode == 'audit':
            # Audit mode does not have a banner.  Assert no banner element.
            self.assertEqual(pq(response.content)(".sts-enrollment").length, 0)
        else:
            self.assertNotContains(response,
                                   "class=\"course {0}\"".format(mode))
            self.assertNotContains(response, value)

    @patch.dict("django.conf.settings.FEATURES",
                {'ENABLE_VERIFIED_CERTIFICATES': False})
    def test_verification_status_invisible(self):
        """
        Test that the certificate verification status for courses is not visible on the dashboard
        if the verified certificates setting is off.
        """
        self.client.login(username="******", password="******")
        self._check_verification_status_off(
            'verified', 'You\'re enrolled as a verified student')
        self._check_verification_status_off(
            'honor', 'You\'re enrolled as an honor code student')
        self._check_verification_status_off('audit', '')

    def test_course_mode_info(self):
        verified_mode = CourseModeFactory.create(
            course_id=self.course.id,
            mode_slug='verified',
            mode_display_name='Verified',
            expiration_datetime=datetime.now(pytz.UTC) + timedelta(days=1))
        enrollment = CourseEnrollment.enroll(self.user, self.course.id)
        course_mode_info = complete_course_mode_info(self.course.id,
                                                     enrollment)
        self.assertTrue(course_mode_info['show_upsell'])
        self.assertEqual(course_mode_info['days_for_upsell'], 1)

        verified_mode.expiration_datetime = datetime.now(
            pytz.UTC) + timedelta(days=-1)
        verified_mode.save()
        course_mode_info = complete_course_mode_info(self.course.id,
                                                     enrollment)
        self.assertFalse(course_mode_info['show_upsell'])
        self.assertIsNone(course_mode_info['days_for_upsell'])

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    def test_linked_in_add_to_profile_btn_not_appearing_without_config(self):
        # Without linked-in config don't show Add Certificate to LinkedIn button
        self.client.login(username="******", password="******")

        CourseModeFactory.create(course_id=self.course.id,
                                 mode_slug='verified',
                                 mode_display_name='verified',
                                 expiration_datetime=datetime.now(pytz.UTC) -
                                 timedelta(days=1))

        CourseEnrollment.enroll(self.user, self.course.id, mode='honor')

        self.course.start = datetime.now(pytz.UTC) - timedelta(days=2)
        self.course.end = datetime.now(pytz.UTC) - timedelta(days=1)
        self.course.display_name = u"Omega"
        self.course = self.update_course(self.course, self.user.id)

        download_url = 'www.edx.org'
        GeneratedCertificateFactory.create(
            user=self.user,
            course_id=self.course.id,
            status=CertificateStatuses.downloadable,
            mode='honor',
            grade='67',
            download_url=download_url)
        response = self.client.get(reverse('dashboard'))

        self.assertEqual(response.status_code, 200)
        self.assertNotContains(response, 'Add Certificate to LinkedIn')

        response_url = 'https://www.linkedin.com/profile/add?startTask=CERTIFICATION_NAME'
        self.assertNotContains(response, escape(response_url))

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    @patch.dict('django.conf.settings.FEATURES',
                {'CERTIFICATES_HTML_VIEW': False})
    def test_linked_in_add_to_profile_btn_with_certificate(self):
        # If user has a certificate with valid linked-in config then Add Certificate to LinkedIn button
        # should be visible. and it has URL value with valid parameters.
        self.client.login(username="******", password="******")

        linkedin_config = LinkedInAddToProfileConfiguration.objects.create(
            company_identifier='1337', enabled=True)
        CourseModeFactory.create(course_id=self.course.id,
                                 mode_slug='verified',
                                 mode_display_name='verified',
                                 expiration_datetime=datetime.now(pytz.UTC) -
                                 timedelta(days=1))
        CourseEnrollment.enroll(self.user, self.course.id, mode='honor')
        self.course.certificate_available_date = datetime.now(
            pytz.UTC) - timedelta(days=1)
        self.course.start = datetime.now(pytz.UTC) - timedelta(days=2)
        self.course.end = datetime.now(pytz.UTC) - timedelta(days=1)
        self.course.display_name = 'Omega'
        self.course = self.update_course(self.course, self.user.id)

        cert = GeneratedCertificateFactory.create(
            user=self.user,
            course_id=self.course.id,
            status=CertificateStatuses.downloadable,
            mode='honor',
            grade='67',
            download_url='https://www.edx.org')
        response = self.client.get(reverse('dashboard'))

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'Add Certificate to LinkedIn')

        # We can switch to this and the commented out assertContains once edx-platform reaches Python 3.8
        # expected_url = (
        #     'https://www.linkedin.com/profile/add?startTask=CERTIFICATION_NAME&'
        #     'name={platform}+Honor+Code+Certificate+for+Omega&certUrl={cert_url}&'
        #     'organizationId={company_identifier}'
        # ).format(
        #     platform=quote(settings.PLATFORM_NAME.encode('utf-8')),
        #     cert_url=quote(cert.download_url, safe=''),
        #     company_identifier=linkedin_config.company_identifier,
        # )

        # self.assertContains(response, escape(expected_url))

        # These can be removed (in favor of the above) once we are on Python 3.8. Fails in 3.5 because of dict ordering
        self.assertContains(
            response,
            escape(
                'https://www.linkedin.com/profile/add?startTask=CERTIFICATION_NAME'
            ))
        self.assertContains(
            response,
            escape('&name={platform}+Honor+Code+Certificate+for+Omega'.format(
                platform=quote(settings.PLATFORM_NAME.encode('utf-8')))))
        self.assertContains(
            response,
            escape('&certUrl={cert_url}'.format(
                cert_url=quote(cert.download_url, safe=''))))
        self.assertContains(
            response,
            escape('&organizationId={company_identifier}'.format(
                company_identifier=linkedin_config.company_identifier)))

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
    def test_dashboard_metadata_caching(self, modulestore_type):
        """
        Check that the student dashboard makes use of course metadata caching.

        After creating a course, that course's metadata should be cached as a
        CourseOverview. The student dashboard should never have to make calls to
        the modulestore.

        Arguments:
            modulestore_type (ModuleStoreEnum.Type): Type of modulestore to create
                test course in.

        Note to future developers:
            If you break this test so that the "check_mongo_calls(0)" fails,
            please do NOT change it to "check_mongo_calls(n>1)". Instead, change
            your code to not load courses from the module store. This may
            involve adding fields to CourseOverview so that loading a full
            CourseDescriptor isn't necessary.
        """
        # Create a course and log in the user.
        # Creating a new course will trigger a publish event and the course will be cached
        test_course = CourseFactory.create(default_store=modulestore_type,
                                           emit_signals=True)
        self.client.login(username="******", password="******")

        with check_mongo_calls(0):
            CourseEnrollment.enroll(self.user, test_course.id)

        # Subsequent requests will only result in SQL queries to load the
        # CourseOverview object that has been created.
        with check_mongo_calls(0):
            response_1 = self.client.get(reverse('dashboard'))
            self.assertEqual(response_1.status_code, 200)
            response_2 = self.client.get(reverse('dashboard'))
            self.assertEqual(response_2.status_code, 200)

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    def test_dashboard_header_nav_has_find_courses(self):
        self.client.login(username="******", password="******")
        response = self.client.get(reverse("dashboard"))

        # "Explore courses" is shown in the side panel
        self.assertContains(response, "Explore courses")

        # But other links are hidden in the navigation
        self.assertNotContains(response, "How it Works")
        self.assertNotContains(response, "Schools & Partners")

    def test_course_mode_info_with_honor_enrollment(self):
        """It will be true only if enrollment mode is honor and course has verified mode."""
        course_mode_info = self._enrollment_with_complete_course('honor')
        self.assertTrue(course_mode_info['show_upsell'])
        self.assertEqual(course_mode_info['days_for_upsell'], 1)

    @ddt.data('verified', 'credit')
    def test_course_mode_info_with_different_enrollments(
            self, enrollment_mode):
        """If user enrollment mode is either verified or credit then show_upsell
        will be always false.
        """
        course_mode_info = self._enrollment_with_complete_course(
            enrollment_mode)
        self.assertFalse(course_mode_info['show_upsell'])
        self.assertIsNone(course_mode_info['days_for_upsell'])

    def _enrollment_with_complete_course(self, enrollment_mode):
        """"Dry method for course enrollment."""
        CourseModeFactory.create(course_id=self.course.id,
                                 mode_slug='verified',
                                 mode_display_name='Verified',
                                 expiration_datetime=datetime.now(pytz.UTC) +
                                 timedelta(days=1))
        enrollment = CourseEnrollment.enroll(self.user,
                                             self.course.id,
                                             mode=enrollment_mode)
        return complete_course_mode_info(self.course.id, enrollment)
Ejemplo n.º 39
0
class RosettaTestCase(TestCase):
    urls = 'rosetta.tests.urls'

    def __init__(self, *args, **kwargs):
        super(RosettaTestCase, self).__init__(*args, **kwargs)
        self.curdir = os.path.dirname(__file__)
        self.dest_file = os.path.normpath(
            os.path.join(self.curdir, '../locale/xx/LC_MESSAGES/django.po'))

    def setUp(self):
        user = User.objects.create_user('test_admin', '*****@*****.**',
                                        'test_password')
        user2 = User.objects.create_user('test_admin2', '*****@*****.**',
                                         'test_password')
        user3 = User.objects.create_user('test_admin3', '*****@*****.**',
                                         'test_password')

        user.is_superuser, user2.is_superuser, user3.is_superuser = True, True, True
        user.is_staff, user2.is_staff, user3.is_staff = True, True, False

        user.save()
        user2.save()
        user3.save()

        self.client2 = Client()

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

        self.__old_settings_languages = settings.LANGUAGES
        settings.LANGUAGES = (('xx', 'dummy language'),
                              ('fr_FR.utf8', 'French (France), UTF8'))

        self.__session_engine = settings.SESSION_ENGINE
        self.__storage_class = rosetta_settings.STORAGE_CLASS
        self.__require_auth = rosetta_settings.ROSETTA_REQUIRES_AUTH
        self.__google_translate = rosetta_settings.GOOGLE_TRANSLATE
        self.__enable_translation = rosetta_settings.ENABLE_TRANSLATION_SUGGESTIONS

        shutil.copy(self.dest_file, self.dest_file + '.orig')

    def tearDown(self):
        settings.LANGUAGES = self.__old_settings_languages
        settings.SESSION_ENGINE = self.__session_engine
        rosetta_settings.STORAGE_CLASS = self.__storage_class
        rosetta_settings.ROSETTA_REQUIRES_AUTH = self.__require_auth
        rosetta_settings.GOOGLE_TRANSLATE = self.__google_translate
        rosetta_settings.ENABLE_TRANSLATION_SUGGESTIONS = self.__enable_translation
        shutil.move(self.dest_file + '.orig', self.dest_file)

    def test_1_ListLoading(self):
        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertTrue(
            os.path.normpath('rosetta/locale/xx/LC_MESSAGES/django.po') in str(
                r.content))

    def test_2_PickFile(self):
        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(
            reverse(
                'rosetta-language-selection', args=(
                    'xx',
                    0,
                ), kwargs=dict()) + '?rosetta')
        r = self.client.get(reverse('rosetta-home'))

        self.assertTrue('dummy language' in str(r.content))

    def test_3_DownloadZIP(self):
        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')

        r = self.client.get(
            reverse(
                'rosetta-language-selection', args=('xx', 0), kwargs=dict()) +
            '?rosetta')
        r = self.client.get(reverse('rosetta-home'))
        r = self.client.get(reverse('rosetta-download-file') + '?rosetta')
        self.assertTrue('content-type' in r._headers.keys())
        self.assertTrue('application/x-zip' in r._headers.get('content-type'))

    def test_4_DoChanges(self):
        shutil.copy(
            os.path.normpath(os.path.join(self.curdir,
                                          './django.po.template')),
            self.dest_file)

        # Load the template file
        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=('xx', 0),
                    kwargs=dict()))
        r = self.client.get(reverse('rosetta-home') + '?filter=untranslated')
        r = self.client.get(reverse('rosetta-home'))
        # make sure both strings are untranslated
        self.assertTrue('dummy language' in str(r.content))
        self.assertTrue('String 1' in str(r.content))
        self.assertTrue('String 2' in str(r.content))
        self.assertTrue('m_e48f149a8b2e8baa81b816c0edf93890' in str(r.content))

        # post a translation
        r = self.client.post(
            reverse('rosetta-home'),
            dict(m_e48f149a8b2e8baa81b816c0edf93890='Hello, world',
                 _next='_next'))

        # reload all untranslated strings
        r = self.client.get(
            reverse(
                'rosetta-language-selection', args=('xx', 0), kwargs=dict()) +
            '?rosetta')
        r = self.client.get(reverse('rosetta-home') + '?filter=untranslated')
        r = self.client.get(reverse('rosetta-home'))

        # the translated string no longer is up for translation
        self.assertTrue('String 1' in str(r.content))
        self.assertTrue('String 2' not in str(r.content))

        # display only translated strings
        r = self.client.get(reverse('rosetta-home') + '?filter=translated')
        r = self.client.get(reverse('rosetta-home'))

        # The tranlsation was persisted
        self.assertTrue('String 1' not in str(r.content))
        self.assertTrue('String 2' in str(r.content))
        self.assertTrue('Hello, world' in str(r.content))

    def test_5_TestIssue67(self):
        # testcase for issue 67: http://code.google.com/p/django-rosetta/issues/detail?id=67
        shutil.copy(
            os.path.normpath(
                os.path.join(self.curdir, './django.po.issue67.template')),
            self.dest_file)
        # Make sure the plurals string is valid
        f_ = open(self.dest_file, 'rb')
        content = f_.read()
        f_.close()
        self.assertTrue('Hello, world' not in six.text_type(content))
        self.assertTrue('|| n%100>=20) ? 1 : 2)' in six.text_type(content))
        del (content)

        # Load the template file
        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')

        r = self.client.get(
            reverse(
                'rosetta-language-selection', args=('xx', 0), kwargs=dict()) +
            '?rosetta')
        r = self.client.get(reverse('rosetta-home') + '?filter=untranslated')
        r = self.client.get(reverse('rosetta-home'))

        # make sure all strings are untranslated
        self.assertTrue('dummy language' in str(r.content))
        self.assertTrue('String 1' in str(r.content))
        self.assertTrue('String 2' in str(r.content))
        self.assertTrue('m_e48f149a8b2e8baa81b816c0edf93890' in str(r.content))

        # post a translation
        r = self.client.post(
            reverse('rosetta-home'),
            dict(m_e48f149a8b2e8baa81b816c0edf93890='Hello, world',
                 _next='_next'))

        # Make sure the plurals string is still valid
        f_ = open(self.dest_file, 'rb')
        content = f_.read()
        f_.close()
        self.assertTrue('Hello, world' in str(content))
        self.assertTrue('|| n%100>=20) ? 1 : 2)' in str(content))
        self.assertTrue('or n%100>=20) ? 1 : 2)' not in str(content))
        del (content)

    def test_6_ExcludedApps(self):

        rosetta_settings.EXCLUDED_APPLICATIONS = ('rosetta', )

        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertTrue(
            'rosetta/locale/xx/LC_MESSAGES/django.po' not in str(r.content))

        rosetta_settings.EXCLUDED_APPLICATIONS = ()

        r = self.client.get(reverse('rosetta-pick-file') + '?rosetta')
        self.assertTrue(
            'rosetta/locale/xx/LC_MESSAGES/django.po' in str(r.content))

    def test_7_selfInApplist(self):
        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertTrue(
            'rosetta/locale/xx/LC_MESSAGES/django.po' in str(r.content))

        self.client.get(reverse('rosetta-pick-file') + '?filter=project')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertTrue(
            'rosetta/locale/xx/LC_MESSAGES/django.po' not in str(r.content))

    def test_8_hideObsoletes(self):
        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(reverse('rosetta-pick-file'))
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=('xx', 0),
                    kwargs=dict()))

        # not in listing
        for p in range(1, 5):
            r = self.client.get(reverse('rosetta-home') + '?page=%d' % p)
            self.assertTrue('dummy language' in str(r.content))
            self.assertTrue('Les deux' not in str(r.content))

        r = self.client.get(reverse('rosetta-home') + '?query=Les%20Deux')
        self.assertTrue('dummy language' in str(r.content))
        self.assertTrue('Les deux' not in str(r.content))

    def test_9_concurrency(self):
        shutil.copy(
            os.path.normpath(os.path.join(self.curdir,
                                          './django.po.template')),
            self.dest_file)

        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client2.get(
            reverse('rosetta-pick-file') + '?filter=third-party')

        self.client.get(
            reverse('rosetta-language-selection',
                    args=('xx', 0),
                    kwargs=dict()))
        self.client2.get(
            reverse('rosetta-language-selection',
                    args=('xx', 0),
                    kwargs=dict()))

        # Load the template file
        r = self.client.get(reverse('rosetta-home') + '?filter=untranslated')
        r = self.client.get(reverse('rosetta-home'))
        r2 = self.client2.get(reverse('rosetta-home') + '?filter=untranslated')
        r2 = self.client2.get(reverse('rosetta-home'))

        self.assertTrue('String 1' in str(r.content))
        self.assertTrue('String 1' in str(r2.content))
        self.assertTrue('m_08e4e11e2243d764fc45a5a4fba5d0f2' in str(r.content))
        r = self.client.post(
            reverse('rosetta-home'),
            dict(m_08e4e11e2243d764fc45a5a4fba5d0f2='Hello, world',
                 _next='_next'),
            follow=True)
        r2 = self.client2.get(reverse('rosetta-home'))

        # Client 2 reloads the home, forces a reload of the catalog,
        # the untranslated string1 is now translated
        self.assertTrue('String 1' not in str(r2.content))
        self.assertTrue('String 2' in str(r2.content))

        r = self.client.get(reverse('rosetta-home') + '?filter=untranslated')
        r = self.client.get(reverse('rosetta-home'))
        r2 = self.client2.get(reverse('rosetta-home') + '?filter=untranslated')
        r2 = self.client2.get(reverse('rosetta-home'))

        self.assertTrue(
            'String 2' in str(r2.content)
            and 'm_e48f149a8b2e8baa81b816c0edf93890' in str(r2.content))
        self.assertTrue(
            'String 2' in str(r.content)
            and 'm_e48f149a8b2e8baa81b816c0edf93890' in str(r.content))

        # client 2 posts!
        r2 = self.client2.post(reverse('rosetta-home'),
                               dict(m_e48f149a8b2e8baa81b816c0edf93890=
                                    'Hello, world, from client two!',
                                    _next='_next'),
                               follow=True)

        self.assertTrue('save-conflict' not in str(r2.content))

        # uh-oh here comes client 1
        r = self.client.post(reverse('rosetta-home'),
                             dict(m_e48f149a8b2e8baa81b816c0edf93890=
                                  'Hello, world, from client one!',
                                  _next='_next'),
                             follow=True)
        # An error message is displayed
        self.assertTrue('save-conflict' in str(r.content))

        # client 2 won
        pofile_content = open(self.dest_file, 'r').read()
        self.assertTrue('Hello, world, from client two!' in pofile_content)

        # Both clients show all strings, error messages are gone
        r = self.client.get(reverse('rosetta-home') + '?filter=translated')
        self.assertTrue('save-conflict' not in str(r.content))
        r2 = self.client2.get(reverse('rosetta-home') + '?filter=translated')
        self.assertTrue('save-conflict' not in str(r2.content))
        r = self.client.get(reverse('rosetta-home'))
        self.assertTrue('save-conflict' not in str(r.content))
        r2 = self.client2.get(reverse('rosetta-home'))
        self.assertTrue('save-conflict' not in str(r2.content))

        # Both have client's two version
        self.assertTrue('Hello, world, from client two!' in str(r.content))
        self.assertTrue('Hello, world, from client two!' in str(r2.content))
        self.assertTrue('save-conflict' not in str(r2.content))
        self.assertTrue('save-conflict' not in str(r.content))

    def test_10_issue_79_num_entries(self):
        shutil.copy(
            os.path.normpath(
                os.path.join(self.curdir, './django.po.issue79.template')),
            self.dest_file)
        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(reverse('rosetta-pick-file'))

        self.assertTrue('<td class="ch-messages r">1</td>' in str(r.content))
        self.assertTrue('<td class="ch-progress r">%s%%</td>' %
                        str(floatformat(0.0, 2)) in str(r.content))
        self.assertTrue('<td class="ch-obsolete r">1</td>' in str(r.content))

    def test_11_issue_80_tab_indexes(self):
        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=(
                        'xx',
                        0,
                    ),
                    kwargs=dict()))
        r = self.client.get(reverse('rosetta-home'))
        self.assertTrue('tabindex="3"' in str(r.content))

    def test_12_issue_82_staff_user(self):
        settings.ROSETTA_REQUIRES_AUTH = True

        self.client3 = Client()
        self.client3.login(username='******', password='******')

        self.client3.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client3.get(
            reverse('rosetta-language-selection',
                    args=('xx', 0),
                    kwargs=dict()))
        r = self.client3.get(reverse('rosetta-home'))
        self.assertTrue(not r.content)

        settings.ROSETTA_REQUIRES_AUTH = False

        self.client3.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client3.get(
            reverse('rosetta-language-selection',
                    args=(
                        'xx',
                        0,
                    ),
                    kwargs=dict()))
        r = self.client3.get(reverse('rosetta-home'))
        self.assertFalse(not r.content)

    def test_13_catalog_filters(self):
        settings.LANGUAGES = (
            ('fr', 'French'),
            ('xx', 'Dummy Language'),
        )
        cache.delete('rosetta_django_paths')
        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertTrue(
            os.path.normpath('rosetta/locale/xx/LC_MESSAGES/django.po') in str(
                r.content))
        self.assertTrue(('contrib') not in str(r.content))

        self.client.get(reverse('rosetta-pick-file') + '?filter=django')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertTrue(
            os.path.normpath('rosetta/locale/xx/LC_MESSAGES/django.po') not in
            str(r.content))

        if django.VERSION[0:2] >= (1, 3):
            self.assertTrue(('contrib') in str(r.content))

        self.client.get(reverse('rosetta-pick-file') + '?filter=all')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertTrue(
            os.path.normpath('rosetta/locale/xx/LC_MESSAGES/django.po') in str(
                r.content))

        if django.VERSION[0:2] >= (1, 3):
            self.assertTrue(('contrib') in str(r.content))

        self.client.get(reverse('rosetta-pick-file') + '?filter=project')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertTrue(
            os.path.normpath('rosetta/locale/xx/LC_MESSAGES/django.po') not in
            str(r.content))
        if django.VERSION[0:2] >= (1, 3):
            self.assertTrue(('contrib') not in str(r.content))

    def test_14_issue_99_context_and_comments(self):
        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=('xx', 0),
                    kwargs=dict()))
        r = self.client.get(reverse('rosetta-home'))
        self.assertTrue(
            'This is a text of the base template' in str(r.content))
        self.assertTrue('Context hint' in str(r.content))

    def test_15_issue_87_entry_changed_signal(self):
        # copy the template file
        shutil.copy(
            os.path.normpath(os.path.join(self.curdir,
                                          './django.po.template')),
            self.dest_file)

        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=(
                        'xx',
                        0,
                    ),
                    kwargs=dict()))
        r = self.client.get(reverse('rosetta-home'))

        @receiver(entry_changed)
        def test_receiver(sender, **kwargs):
            self.test_old_msgstr = kwargs.get('old_msgstr')
            self.test_new_msgstr = sender.msgstr
            self.test_msg_id = sender.msgid

        self.assertTrue('m_e48f149a8b2e8baa81b816c0edf93890' in str(r.content))

        # post a translation
        r = self.client.post(
            reverse('rosetta-home'),
            dict(m_e48f149a8b2e8baa81b816c0edf93890='Hello, world',
                 _next='_next'))

        self.assertTrue(self.test_old_msgstr == '')
        self.assertTrue(self.test_new_msgstr == 'Hello, world')
        self.assertTrue(self.test_msg_id == 'String 2')

        del (self.test_old_msgstr, self.test_new_msgstr, self.test_msg_id)

    def test_16_issue_101_post_save_signal(self):
        shutil.copy(
            os.path.normpath(os.path.join(self.curdir,
                                          './django.po.template')),
            self.dest_file)
        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=('xx', 0),
                    kwargs=dict()))
        r = self.client.get(reverse('rosetta-home'))

        @receiver(post_save)
        def test_receiver(sender, **kwargs):
            self.test_sig_lang = kwargs.get('language_code')

        self.assertTrue('m_e48f149a8b2e8baa81b816c0edf93890' in str(r.content))

        # post a translation
        r = self.client.post(
            reverse('rosetta-home'),
            dict(m_e48f149a8b2e8baa81b816c0edf93890='Hello, world',
                 _next='_next'))

        self.assertTrue(self.test_sig_lang == 'xx')
        del (self.test_sig_lang)

    def test_17_issue_103_post_save_signal_has_request(self):
        shutil.copy(
            os.path.normpath(os.path.join(self.curdir,
                                          './django.po.template')),
            self.dest_file)

        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=('xx', 0),
                    kwargs=dict()))
        r = self.client.get(reverse('rosetta-home'))

        @receiver(post_save)
        def test_receiver(sender, **kwargs):
            self.test_16_has_request = 'request' in kwargs

        self.assertTrue('m_e48f149a8b2e8baa81b816c0edf93890' in str(r.content))

        # post a translation
        r = self.client.post(
            reverse('rosetta-home'),
            dict(m_e48f149a8b2e8baa81b816c0edf93890='Hello, world',
                 _next='_next'))

        self.assertTrue(self.test_16_has_request)
        del (self.test_16_has_request)
        # reset the original file

    def test_18_Test_Issue_gh24(self):
        shutil.copy(
            os.path.normpath(
                os.path.join(self.curdir, './django.po.issue24gh.template')),
            self.dest_file)

        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=(
                        'xx',
                        0,
                    ),
                    kwargs=dict()))
        r = self.client.get(reverse('rosetta-home'))

        self.assertTrue('m_bb9d8fe6159187b9ea494c1b313d23d4' in str(r.content))

        # post a translation, it should have properly wrapped lines
        r = self.client.post(
            reverse('rosetta-home'),
            dict(
                m_bb9d8fe6159187b9ea494c1b313d23d4=
                'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.',
                _next='_next'))
        pofile_content = open(self.dest_file, 'r').read()
        self.assertTrue('"pede mollis pretium."' in pofile_content)

        # Again, with unwrapped lines
        shutil.copy(
            os.path.normpath(
                os.path.join(self.curdir, './django.po.issue24gh.template')),
            self.dest_file)
        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=(
                        'xx',
                        0,
                    ),
                    kwargs=dict()))
        r = self.client.get(reverse('rosetta-home'))
        self.assertTrue('m_bb9d8fe6159187b9ea494c1b313d23d4' in str(r.content))
        rosetta_settings.POFILE_WRAP_WIDTH = 0
        r = self.client.post(
            reverse('rosetta-home'),
            dict(
                m_bb9d8fe6159187b9ea494c1b313d23d4=
                'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.',
                _next='_next'))
        pofile_content = open(self.dest_file, 'r').read()
        self.assertTrue('felis eu pede mollis pretium."' in pofile_content)

    def test_19_Test_Issue_gh34(self):
        shutil.copy(
            os.path.normpath(
                os.path.join(self.curdir, './django.po.issue34gh.template')),
            self.dest_file)

        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=(
                        'xx',
                        0,
                    ),
                    kwargs=dict()))
        r = self.client.get(reverse('rosetta-home'))
        self.assertTrue(
            'm_ff7060c1a9aae9c42af4d54ac8551f67_1' in str(r.content))
        self.assertTrue(
            'm_ff7060c1a9aae9c42af4d54ac8551f67_0' in str(r.content))
        self.assertTrue('m_09f7e02f1290be211da707a266f153b3' in str(r.content))

        # post a translation, it should have properly wrapped lines
        r = self.client.post(
            reverse('rosetta-home'),
            dict(m_ff7060c1a9aae9c42af4d54ac8551f67_0='Foo %s',
                 m_ff7060c1a9aae9c42af4d54ac8551f67_1='Bar %s',
                 m_09f7e02f1290be211da707a266f153b3='Salut',
                 _next='_next'))
        pofile_content = open(self.dest_file, 'r').read()
        self.assertTrue('msgstr "Salut\\n"' in pofile_content)
        self.assertTrue('msgstr[0] ""\n"\\n"\n"Foo %s\\n"' in pofile_content)
        self.assertTrue('msgstr[1] ""\n"\\n"\n"Bar %s\\n"' in pofile_content)

    def test_20_Test_Issue_gh38(self):
        if django.VERSION[0:2] >= (1, 4):
            self.assertTrue(
                'django.contrib.sessions.middleware.SessionMiddleware' in
                settings.MIDDLEWARE_CLASSES)

            settings.SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"

            # One: cache backend
            rosetta_settings.STORAGE_CLASS = 'rosetta.storage.CacheRosettaStorage'

            shutil.copy(
                os.path.normpath(
                    os.path.join(self.curdir,
                                 './django.po.issue38gh.template')),
                self.dest_file)

            self.client.get(
                reverse('rosetta-pick-file') + '?filter=third-party')
            self.client.get(
                reverse('rosetta-language-selection',
                        args=(
                            'xx',
                            0,
                        ),
                        kwargs=dict()))
            r = self.client.get(reverse('rosetta-home'))
            self.assertFalse(
                len(str(self.client.cookies.get('sessionid'))) > 4096)
            self.assertTrue(
                'm_9efd113f7919952523f06e0d88da9c54' in str(r.content))
            r = self.client.post(
                reverse('rosetta-home'),
                dict(
                    m_9efd113f7919952523f06e0d88da9c54='Testing cookie length',
                    _next='_next'))
            pofile_content = open(self.dest_file, 'r').read()
            self.assertTrue('Testing cookie length' in pofile_content)

            self.client.get(reverse('rosetta-home') + '?filter=translated')
            r = self.client.get(reverse('rosetta-home'))
            self.assertTrue('Testing cookie length' in str(r.content))
            self.assertTrue(
                'm_9f6c442c6d579707440ba9dada0fb373' in str(r.content))

            # Two, the cookie backend
            if django.VERSION[0:2] < (1, 6):
                rosetta_settings.STORAGE_CLASS = 'rosetta.storage.SessionRosettaStorage'

                shutil.copy(
                    os.path.normpath(
                        os.path.join(self.curdir,
                                     './django.po.issue38gh.template')),
                    self.dest_file)

                self.client.get(
                    reverse('rosetta-pick-file') + '?filter=third-party')
                self.client.get(
                    reverse('rosetta-language-selection',
                            args=(
                                'xx',
                                0,
                            ),
                            kwargs=dict()))
                r = self.client.get(reverse('rosetta-home'))
                self.assertTrue(
                    len(str(self.client.cookies.get('sessionid'))) > 4096)
                # boom: be a good browser, truncate the cookie
                self.client.cookies['sessionid'] = six.text_type(
                    self.client.cookies.get('sessionid'))[:4096]
                r = self.client.get(reverse('rosetta-home'))

                self.assertFalse(
                    'm_9efd113f7919952523f06e0d88da9c54' in str(r.content))

    def test_21_concurrency_of_cache_backend(self):
        rosetta_settings.STORAGE_CLASS = 'rosetta.storage.CacheRosettaStorage'
        shutil.copy(
            os.path.normpath(
                os.path.join(self.curdir, './django.po.issue38gh.template')),
            self.dest_file)

        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        self.client.get(
            reverse('rosetta-language-selection',
                    args=(
                        'xx',
                        0,
                    ),
                    kwargs=dict()))

        self.client2.get(reverse('rosetta-pick-file') + '?filter=third-party')
        self.client2.get(
            reverse('rosetta-language-selection',
                    args=(
                        'xx',
                        0,
                    ),
                    kwargs=dict()))

        self.assertTrue(
            self.client.session.get('rosetta_cache_storage_key_prefix') !=
            self.client2.session.get('rosetta_cache_storage_key_prefix'))

    def test_22_Test_Issue_gh39(self):
        shutil.copy(
            os.path.normpath(
                os.path.join(self.curdir, './django.po.issue39gh.template')),
            self.dest_file)

        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=('xx', 0),
                    kwargs=dict()))
        r = self.client.get(reverse('rosetta-home'))
        # We have distinct hashes, even though the msgid and msgstr are identical
        #print (r.content)
        self.assertTrue('m_4765f7de94996d3de5975fa797c3451f' in str(r.content))
        self.assertTrue('m_08e4e11e2243d764fc45a5a4fba5d0f2' in str(r.content))

    def test_23_save_header_data(self):
        shutil.copy(
            os.path.normpath(os.path.join(self.curdir,
                                          './django.po.template')),
            self.dest_file)

        unicode_user = User.objects.create_user('test_unicode',
                                                '*****@*****.**',
                                                'test_unicode')
        unicode_user.first_name = "aéaéaé aàaàaàa"
        unicode_user.last_name = "aâââ üüüü"
        unicode_user.is_superuser, unicode_user.is_staff = True, True
        unicode_user.save()

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

        # Load the template file
        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=('xx', 0),
                    kwargs=dict()))
        r = self.client.get(reverse('rosetta-home') + '?filter=untranslated')
        r = self.client.get(reverse('rosetta-home'))
        # make sure both strings are untranslated
        self.assertTrue('dummy language' in str(r.content))
        self.assertTrue('String 1' in str(r.content))
        self.assertTrue('String 2' in str(r.content))
        self.assertTrue('m_e48f149a8b2e8baa81b816c0edf93890' in str(r.content))

        # post a translation
        r = self.client.post(
            reverse('rosetta-home'),
            dict(m_e48f149a8b2e8baa81b816c0edf93890='Hello, world',
                 _next='_next'))
        # read the result
        f_ = open(self.dest_file, 'rb')
        content = six.text_type(f_.read())
        f_.close()
        #print (content)
        # make sure unicode data was properly converted to ascii
        self.assertTrue('Hello, world' in content)
        self.assertTrue('*****@*****.**' in content)
        self.assertTrue('aeaeae aaaaaaa aaaa uuuu' in content)

    def test_24_percent_transaltion(self):
        shutil.copy(
            os.path.normpath(os.path.join(self.curdir,
                                          './django.po.template')),
            self.dest_file)

        # Load the template file
        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=('xx', 0),
                    kwargs=dict()))
        r = self.client.get(reverse('rosetta-home') + '?filter=untranslated')
        r = self.client.get(reverse('rosetta-home'))

        self.assertTrue('Progress: 0.00%' in str(r.content))
        r = self.client.post(
            reverse('rosetta-home'),
            dict(m_e48f149a8b2e8baa81b816c0edf93890='Hello, world',
                 _next='_next'))
        r = self.client.get(reverse('rosetta-home'))
        self.assertTrue('Progress: 25.00%' in str(r.content))

    def test_25_replace_access_control(self):
        # Test default access control allows access
        url = reverse('rosetta-home')
        response = self.client.get(url)
        self.assertEqual(200, response.status_code)

        # Now replace access control, and check we get redirected
        settings.ROSETTA_ACCESS_CONTROL_FUNCTION = 'rosetta.tests.no_access'
        response = self.client.get(url)
        self.assertEqual(302, response.status_code)

        # Restore setting to default
        settings.ROSETTA_ACCESS_CONTROL_FUNCTION = None

    def test_26_urlconf_accept_dots_and_underscores(self):
        resolver_match = resolve("/rosetta/select/fr_FR.utf8/0/")
        self.assertEqual(resolver_match.url_name, "rosetta-language-selection")
        self.assertEqual(resolver_match.kwargs['langid'], 'fr_FR.utf8')

    def test_27_extended_urlconf_language_code_loads_file(self):
        r = self.client.get(reverse('rosetta-pick-file') + '?filter=all')
        r = self.client.get(
            reverse('rosetta-language-selection',
                    args=('fr_FR.utf8', 0),
                    kwargs=dict()))
        r = self.client.get(reverse('rosetta-home'))
        self.assertTrue('French (France), UTF8' in str(r.content))
        self.assertTrue('m_71a6479faf8712e37dd5755cd1d11804' in str(r.content))

    def test_28_issue_gh87(self):
        "make sure that rosetta_i18n_catalog_filter is passed into the context"
        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertTrue('<li class="active"><a href="?filter=third-party">' in
                        str(r.content))

    def test_29_unsupported_p3_django_16_storage(self):
        if django.VERSION[0:2] >= (1, 6):
            self.assertTrue(
                'django.contrib.sessions.middleware.SessionMiddleware' in
                settings.MIDDLEWARE_CLASSES)

            settings.SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"
            rosetta_settings.STORAGE_CLASS = 'rosetta.storage.SessionRosettaStorage'

            try:
                self.client.get(
                    reverse('rosetta-pick-file') + '?filter=third-party')
                self.fail()
            except ImproperlyConfigured:
                pass

    def test_30_pofile_names(self):
        POFILENAMES = rosetta_settings.POFILENAMES
        rosetta_settings.POFILENAMES = ('pr44.po', )

        os.unlink(self.dest_file)
        destfile = os.path.normpath(
            os.path.join(self.curdir, '../locale/xx/LC_MESSAGES/pr44.po'))
        shutil.copy(
            os.path.normpath(os.path.join(self.curdir, './pr44.po.template')),
            destfile)

        self.client.get(reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(reverse('rosetta-home'))
        self.assertTrue('xx/LC_MESSAGES/pr44.po' in str(r.content))

        r = self.client.get(
            reverse(
                'rosetta-language-selection', args=(
                    'xx',
                    0,
                ), kwargs=dict()) + '?rosetta')
        r = self.client.get(reverse('rosetta-home'))

        self.assertTrue('dummy language' in str(r.content))

        os.unlink(destfile)
        rosetta_settings.POFILENAMES = POFILENAMES

    def test_31_pr_102__exclude_paths(self):
        ROSETTA_EXCLUDED_PATHS = rosetta_settings.ROSETTA_EXCLUDED_PATHS

        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertTrue(
            os.path.normpath('rosetta/locale/xx/LC_MESSAGES/django.po') in str(
                r.content))

        exclude_path = os.path.normpath(os.path.join(self.curdir, '../locale'))
        rosetta_settings.ROSETTA_EXCLUDED_PATHS = [
            exclude_path,
        ]

        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertFalse(
            os.path.normpath('rosetta/locale/xx/LC_MESSAGES/django.po') in str(
                r.content))

        rosetta_settings.ROSETTA_EXCLUDED_PATHS = ROSETTA_EXCLUDED_PATHS

    def test_32_pr_103__language_groups(self):
        ROSETTA_LANGUAGE_GROUPS = rosetta_settings.ROSETTA_LANGUAGE_GROUPS
        rosetta_settings.ROSETTA_LANGUAGE_GROUPS = False

        # Default behavior: non admins need to be in a translators group, they see
        # all catalogs
        translators = Group.objects.create(name='translators')
        translators_xx = Group.objects.create(name='translators-xx')

        user4 = User.objects.create_user('test_admin4', '*****@*****.**',
                                         'test_password')
        user4.groups.add(translators)
        user4.is_superuser = False
        user4.is_staff = True
        user4.save()
        self.client.login(username='******', password='******')

        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertTrue(
            os.path.normpath('rosetta/locale/xx/LC_MESSAGES/django.po') in str(
                r.content))

        # Activate the option, user doesn't see the XX catalog
        rosetta_settings.ROSETTA_LANGUAGE_GROUPS = True

        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertFalse(
            os.path.normpath('rosetta/locale/xx/LC_MESSAGES/django.po') in str(
                r.content))

        # Now add them to the custom group
        user4.groups.add(translators_xx)

        r = self.client.get(
            reverse('rosetta-pick-file') + '?filter=third-party')
        r = self.client.get(reverse('rosetta-pick-file'))
        self.assertTrue(
            os.path.normpath('rosetta/locale/xx/LC_MESSAGES/django.po') in str(
                r.content))

        rosetta_settings.ROSETTA_LANGUAGE_GROUPS = ROSETTA_LANGUAGE_GROUPS

    def test_33_pr_116_google_translate(self):
        rosetta_settings.GOOGLE_TRANSLATE = True
        rosetta_settings.ENABLE_TRANSLATION_SUGGESTIONS = True

        r = self.client.get(
            reverse('translate_text') + '?from=en&to=fr&text=Hello,+world!')
        self.assertTrue(
            six.text_type("Bonjour le monde!") in six.text_type(r.content))

    def test_34_issue_113_app_configs(self):
        if django.VERSION[0:2] >= (1, 7):
            r = self.client.get(reverse('rosetta-pick-file') + '?filter=all')
            r = self.client.get(reverse('rosetta-pick-file'))
            self.assertTrue('rosetta/select/xx/1/">Test_App' in str(r.content))
Ejemplo n.º 40
0
class SurveyViewsTests(ModuleStoreTestCase):
    """
    All tests for the views.py file
    """
    def setUp(self):
        """
        Set up the test data used in the specific tests
        """
        super(SurveyViewsTests, self).setUp()

        self.client = Client()

        # Create two accounts
        self.password = '******'
        self.student = UserFactory.create(username='******',
                                          email='*****@*****.**',
                                          password=self.password)

        self.test_survey_name = 'TestSurvey'
        self.test_form = '''
            <input name="field1" /><input name="field2" /><select name="ddl"><option>1</option></select>
            <textarea name="textarea" />
        '''

        self.student_answers = OrderedDict({
            u'field1': u'value1',
            u'field2': u'value2',
            u'ddl': u'1',
            u'textarea': u'textarea'
        })

        self.course = CourseFactory.create(
            display_name='Test Course',
            course_survey_required=True,
            course_survey_name=self.test_survey_name)

        self.survey = SurveyForm.create(self.test_survey_name, self.test_form)

        self.view_url = reverse('view_survey', args=[self.test_survey_name])
        self.postback_url = reverse('submit_answers',
                                    args=[self.test_survey_name])

        self.client.login(username=self.student.username,
                          password=self.password)

    def test_unauthenticated_survey_view(self):
        """
        Asserts that an unauthenticated user cannot access a survey
        """
        anon_user = Client()

        resp = anon_user.get(self.view_url)
        self.assertEquals(resp.status_code, 302)

    def test_survey_not_found(self):
        """
        Asserts that if we ask for a Survey that does not exist, then we get a 302 redirect
        """
        resp = self.client.get(reverse('view_survey', args=['NonExisting']))
        self.assertEquals(resp.status_code, 302)

    def test_authenticated_survey_view(self):
        """
        Asserts that an authenticated user can see the survey
        """
        resp = self.client.get(self.view_url)
        self.assertEquals(resp.status_code, 200)

        # is the SurveyForm html present in the HTML response?
        self.assertIn(self.test_form, resp.content)

    def test_unautneticated_survey_postback(self):
        """
        Asserts that an anonymous user cannot answer a survey
        """
        anon_user = Client()
        resp = anon_user.post(self.postback_url, self.student_answers)
        self.assertEquals(resp.status_code, 302)

    def test_survey_postback_to_nonexisting_survey(self):
        """
        Asserts that any attempts to post back to a non existing survey returns a 404
        """
        resp = self.client.post(
            reverse('submit_answers', args=['NonExisting']),
            self.student_answers)
        self.assertEquals(resp.status_code, 404)

    def test_survey_postback(self):
        """
        Asserts that a well formed postback of survey answers is properly stored in the
        database
        """
        resp = self.client.post(self.postback_url, self.student_answers)
        self.assertEquals(resp.status_code, 200)
        data = json.loads(resp.content)
        self.assertIn('redirect_url', data)

        answers = self.survey.get_answers(self.student)
        self.assertEquals(answers[self.student.id], self.student_answers)

    def test_strip_extra_fields(self):
        """
        Verify that any not expected field name in the post-back is not stored
        in the database
        """
        data = dict.copy(self.student_answers)

        data['csrfmiddlewaretoken'] = 'foo'
        data['_redirect_url'] = 'bar'
        data['course_id'] = unicode(self.course.id)

        resp = self.client.post(self.postback_url, data)
        self.assertEquals(resp.status_code, 200)
        answers = self.survey.get_answers(self.student)
        self.assertNotIn('csrfmiddlewaretoken', answers[self.student.id])
        self.assertNotIn('_redirect_url', answers[self.student.id])
        self.assertNotIn('course_id', answers[self.student.id])

        # however we want to make sure we persist the course_id
        answer_objs = SurveyAnswer.objects.filter(user=self.student,
                                                  form=self.survey)

        for answer_obj in answer_objs:
            self.assertEquals(unicode(answer_obj.course_key),
                              data['course_id'])

    def test_encoding_answers(self):
        """
        Verify that if some potentially harmful input data is sent, that is is properly HTML encoded
        """
        data = dict.copy(self.student_answers)

        data[
            'field1'] = '<script type="javascript">alert("Deleting filesystem...")</script>'

        resp = self.client.post(self.postback_url, data)
        self.assertEquals(resp.status_code, 200)
        answers = self.survey.get_answers(self.student)
        self.assertEqual(
            '&lt;script type=&quot;javascript&quot;&gt;alert(&quot;Deleting filesystem...&quot;)&lt;/script&gt;',
            answers[self.student.id]['field1'])
Ejemplo n.º 41
0
 def test_perms_faqs_manage_article_admin(self):
     '''Test the manage article view'''
     c = Client()
     c.login(username=self.admin_user.username, password='******')
     response = c.get(reverse('feedback-manage-article'))
     self.failUnlessEqual(response.status_code, 200)
Ejemplo n.º 42
0
class TestingViews(TestCase):
    def setUp(self):
        """
        Set up the client and credentials.
        """

        self.client = Client()
        self.credentials = {'username': '******', 'password': '******'}
        User.objects.create_user(**self.credentials)

    def test_accessible_by_name(self):
        """
        Test diary's accessible by name.
        """

        response = self.client.get(reverse('login'))
        self.assertEqual(response.status_code, 200)

    def test_accessible_by_location(self):
        """
        Test diary's accessible by location.
        """

        response = self.client.get('/login/')
        self.assertEqual(response.status_code, 200)

    def test_post_request(self):
        """
        Test the submission of post request.
        """

        response = self.client.post('/login/', {
            'username': '******',
            'password': '******'
        })
        self.assertEqual(response.status_code, 200)

    def no_test_user_authenticated(self):
        """
        Test if the login is sucess or not.
        """

        response = self.client.post('/login/', self.credentials, follow=True)
        self.assertTrue(response.context['user'].is_authenticated)

    def test_login_required_index_page(self):
        """
        Test that index page should redirect to login page when it's not authenticated.
        """

        response = self.client.get(reverse('diary:index'))
        self.assertTrue(response.status_code, 302)

    def test_index_accessible(self):
        """
        Test if index page is accessible or not.
        """

        self.client.login(username='******', password='******')
        response = self.client.get(reverse('diary:index'))
        self.assertEqual(response.status_code, 200)

    def test_login_using_template(self):
        """
        Test that the login page is using the correct template path.
        """

        response = self.client.get(reverse('login'))
        self.assertTemplateUsed(response, 'registration/login.html')

    def test_index_using_template(self):
        """
        Test that the index page is using the correct template path.
        """

        self.client.login(username='******', password='******')
        response = self.client.get(reverse('diary:index'))
        self.assertTemplateUsed(response, 'diary/index.html')
Ejemplo n.º 43
0
class TBXURLs(TestCase):

    fixtures = ['test_data']

    def setUp(self):
        self.c = Client()
        self.user = User.objects.create_user(username="******",
                                             email="*****@*****.**",
                                             password="******")
        self.user.save()

    def login(self):
        self.c.login(username='******', password='******')

    def is_tbx(self, response):
        assert "attachment;" in response['Content-Disposition']
        assert "tbx" in response['Content-Disposition']
        self.assertContains(response, '<martif type="TBX"')

    def not_tbx(self, response):
        assert 'Content-Disposition' not in response
        self.assertNotContains(response, '<martif type="TBX"')

    def test_autoterm(self):
        response = self.c.get('/autoterm/gl/', data={})
        self.is_tbx(response)

    def test_export(self):
        self.login()
        response = self.c.get('/export/', data={"from_glossaries": 1})
        self.assertContains(response, 'Export')
        self.assertNotContains(response, "This field is required")

        for export_terms in ("", "all", "preferred", "preferred+admitted",
                             "preferred+admitted+not_recommended"):
            response = self.c.post('/export/',
                                   data={
                                       "from_glossaries": 1,
                                       "export_terms": export_terms,
                                   })
            self.is_tbx(response)

    def test_export_externalresources(self):
        self.login()
        response = self.c.post('/export/',
                               data={
                                   "from_glossaries": 2,
                                   "export_terms": "all",
                               })
        self.is_tbx(response)
        self.assertNotContains(response, 'xref')

        r = ExternalResource(concept_id=7,
                             language=None,
                             link_type_id="externalCrossReference")
        r.save()
        response = self.c.post('/export/',
                               data={
                                   "from_glossaries": 2,
                                   "export_terms": "all",
                               })
        self.is_tbx(response)
        self.assertContains(response, 'xref')

    def test_tbx_import(self):
        self.login()
        response = self.c.post('/import/', data={})
        for field in [
                "name",
                "description",
                "source_language",
                "imported_file",
        ]:
            self.assertFormError(response, "import_form", field,
                                 "This field is required.")
            self.assertNotContains(response, "succesful")
        for filename in [
                'empty.tbx',
                'small.tbx',  # first "fail"
                'small.tbx',  # then pass, if we add the language
                'most.tbx',
        ]:
            with open(os.path.join(os.path.dirname(__file__), filename),
                      'r') as f:
                response = self.c.post(
                    '/import/', {
                        "name": "test name",
                        "description": "test description",
                        "source_language": 'en',
                        'imported_file': f
                    })
            if b"no Language with that code" in response.content:
                # first attempt to import a file with Zulu
                Language(iso_code="zu").save()
                self.assertNotContains(response, "succesful")
                continue
            self.assertEqual(response.status_code, 200)
            self.assertContains(response, "succesful")
            self.assertNotContains(response, "This field is required.")
            glossary = Glossary.objects.get(name="test name")
            if filename == 'most.tbx':
                self.assertEqual(glossary.source_language.iso_code, 'en')
                self.assertSequenceEqual(
                    glossary.other_languages.values_list('iso_code',
                                                         flat=True), ('zu', ))
            Glossary.delete(glossary)

            with open(os.path.join(os.path.dirname(__file__), 'empty.tbx'),
                      'r') as f:
                response = self.c.post(
                    '/import/', {
                        "name": "empty",
                        "description": "empty",
                        "source_language": 'en',
                        'imported_file': f
                    })
                f.seek(0)
                response = self.c.post(
                    '/import/', {
                        "name": "empty",
                        "description": "empty",
                        "source_language": 'en',
                        'imported_file': f
                    })
                self.assertNotContains(response, "succesful")
                self.assertContains(
                    response,
                    "Already exists a glossary with the given name. You should provide another one."
                )
Ejemplo n.º 44
0
class TimeStampModelTests(TestCase):
    """
    The container Class that holds all the tests.
    :param TestCase: TestCase module to do test cases.

    """
    def setUp(self):
        """
        Initial setup for all the test cases.
        A user names jacob is created here and Client is initiated.
        """
        self.client = Client()
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')

    def testModelInstanceCreation(self):
        """
		This test directly tests the model creation.
		Tries to create a timestamp object with curent time and the already created user.

		"""
        ts = TimeStamp(user=self.user, time_stamp=timezone.now())
        self.assertIs(type(ts), TimeStamp)

    def testTimeStampsLimit(self):
        """
        This test checks whether the timeStamp didn't exceed the limit.
        This is checked by attempting to create more timestamps than the limit.
        This also checks whether the timeStamp manager is working properly.

        """
        # Tries to get value of MAX_TIMESTAMPS from settings
        # and if it does not xist assign the value of 5.
        # This is equivalent of   maxStamps=settings.MAX_TIMESTAMPS if hasattr(settings.MAX_TIMESTAMPS) else 5
        maxStamps = getattr(settings, 'MAX_TIMESTAMPS', 5)
        for i in range(maxStamps +
                       1):  # Create more timestamps than the max Value
            self.failUnlessEqual(
                type(TimeStamp.objects.create_timestamp(self.user)), TimeStamp
            )  # Check whether the timestamps are created successfully.
        logintime_list = TimeStamp.objects.filter(user=self.user)
        self.assertIs(
            len(logintime_list),
            maxStamps)  # Check whether the timestamp didn't exceed the limit.

    def testLogins(self):
        """
        This test checks whether a login action is creating a timeStamp successfully.
        This also checks whethr a login is successfull.

        """
        self.failUnlessEqual(
            self.client.login(username=self.user.username,
                              password='******'),
            True)  # Checcks whether login is successful.
        self.client.logout()
        logintime_list = TimeStamp.objects.filter(user=self.user)
        self.assertIs(len(logintime_list),
                      1)  # Checks whether a timeeStamp is creatd for the login

    def testUserDeletion(self):
        """
        This test checks whether deleting a user also deletes the corresponding timeStamps.
        This basically checks the integrity of the database.

        """
        self.failUnlessEqual(
            self.client.login(username=self.user.username,
                              password='******'), True)
        self.client.logout()
        logintime_list = TimeStamp.objects.filter(user=self.user)
        self.assertIs(len(logintime_list), 1)
        self.user.delete()
        logintime_list = TimeStamp.objects.filter(user=self.user)
        self.assertIs(
            len(logintime_list),
            0)  #  Checks whether a timeeStamp is deleted for the user
Ejemplo n.º 45
0
class URLsB(TestCase):

    fixtures = ['test_data']

    def setUp(self):
        self.c = Client()
        self.user = User.objects.create_user(username="******",
                                             email="*****@*****.**",
                                             password="******")
        self.user.save()

    def login(self):
        self.c.login(username='******', password='******')

    def test_simple_post(self):
        for url in [
                '/',  # proposal
                '/search/',
                '/advanced_search/',
                #                '/import/',###
                '/accounts/login/',
                '/accounts/register/',
                #                '/admin/',
        ]:
            #print url
            response = self.c.post(url, data={})
            self.assertEqual(response.status_code, 200)

    def test_invalid_suggestion(self):
        self.login()
        response = self.c.post('/', data={})
        for field in [
                "for_glossary",
                "language",
                "term",
                "definition",
        ]:
            self.assertFormError(response, "proposal_form", field,
                                 "This field is required.")

    def test_valid_suggestion(self):
        self.login()
        response = self.c.post('/',
                               data={
                                   "for_glossary": 1,
                                   "language": 'en',
                                   "term": "asdf",
                                   "definition": "asdf",
                               })
        self.assertContains(response, "Thank you")

    def test_profile_detail(self):
        response = self.c.get('/profiles/test/')
        self.assertContains(response, 'test')
        response = self.c.get('/profiles/test/', {"page": 2})
        self.assertContains(response, 'test')
        response = self.c.get('/profiles/test/', {"page": "abc"})
        self.assertContains(response, 'test')

    def test_search(self):
        response = self.c.get('/search/', {"search_string": "abc"})
        self.assertEqual(response.status_code, 200)
        response = self.c.get(
            '/advanced_search/', {
                "search_string": "abc",
                "filter_by_glossary": 1,
                "filter_by_language": "en",
                "filter_by_part_of_speech": 1,
                "filter_by_administrative_status": "preferredTerm-admn-sts",
                "also_show_partial_matches": True,
            })
        self.assertContains(response, "No results found.")
        response = self.c.get(
            '/advanced_search/', {
                "search_string": "tab",
                "filter_by_glossary": 1,
                "filter_by_language": "en",
            })
        self.assertNotContains(response, "No results found.")

    def test_concept(self):
        response = self.c.get('/concepts/1/')
        self.assertNotContains(response, "Definition")
        self.assertNotContains(response, "External resources")
        self.assertNotContains(response, "Related")
        concept = Concept.objects.get(id=1)
        concept2 = Concept(id=200, glossary_id=1)
        concept2.save()
        concept.related_concepts.add(concept2)
        response = self.c.get('/concepts/1/')
        self.assertContains(response, "Related")

    def test_concept_in_language(self):
        response = self.c.get('/concepts/1/en/')
        self.assertNotContains(response, "Definition")
        self.assertNotContains(response, "External resources")
        concept = Concept.objects.get(id=1)
        concept_in_lang, created = ConceptInLanguage.objects.get_or_create(
            concept=concept,
            language_id="en",
        )
        concept_in_lang.summary = "Soomaaariii"
        concept_in_lang.is_finalized = True
        concept_in_lang.save()
        translation = concept.translation_set.get(language_id="en")
        translation.part_of_speech = PartOfSpeech.objects.get(
            tbx_representation="noun")
        translation.is_finalized = True
        translation.save()
        definition = Definition(concept=concept, language_id="en", text="xxxx")
        definition.save()
        response = self.c.get('/concepts/1/en/')
        self.assertContains(response, "Definition")
        self.assertContains(response, "Noun")

    def test_concept_source(self):
        response = self.c.get('/concepts_source/1/')
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "search")
        self.assertNotContains(response, "buscar")
        self.assertNotContains(response, "Finalise term information")
        self.assertNotContains(response,
                               "Enter correction or alternative term")
        self.assertNotContains(response, "Submit")

        self.login()
        response = self.c.get('/concepts_source/1/')
        self.assertEqual(response.status_code, 200)
        # This user has no rights for this Glossary
        self.assertNotContains(response, "Finalise term information")
        self.assertNotContains(response, "Submit")

        self.c.login(username='******', password='******')
        response = self.c.get('/concepts_source/1/')
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Finalise term information")
        self.assertContains(response, "Add corrected or alternative term")
        self.assertContains(response, "Submit")

        response = self.c.post('/concepts_source/1/',
                               data={
                                   "translation": "SEARCHxxx",
                               })
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "successnote")
        self.assertContains(response, "search")
        self.assertContains(response, "SEARCHxxx")

        response = self.c.post('/concepts_source/1/',
                               data={
                                   "translation": "SEARCHyyy",
                                   "definition": "definizione uno",
                               })
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "successnote")
        self.assertContains(response, "search")
        self.assertContains(response, "SEARCHxxx")
        self.assertContains(response, "SEARCHyyy")
        self.assertContains(response, "definizione uno")

        response = self.c.post('/concepts_source/1/',
                               data={
                                   "definition": "newer definition",
                               })
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "successnote")
        self.assertContains(response, "newer definition")
        self.assertNotContains(response, "definizione uno")

        # too long
        response = self.c.post('/concepts_source/1/',
                               data={
                                   "translation": "x" * 200,
                               })
        self.assertEqual(response.status_code, 200)
        self.assertNotContains(response, "xxxxxxxxxx")

        # duplicate
        response = self.c.post('/concepts_source/1/',
                               data={
                                   "translation": "SEARCHxxx",
                               })
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "errornote")
        self.assertContains(response, "already present")
        self.assertContains(response, "SEARCHxxx")

    def test_definition_history(self):
        self.c.login(username='******', password='******')
        response = self.c.get('/concepts_source/1/')
        self.assertEqual(response.status_code, 200)
        self.assertNotContains(response, "today")
        self.assertContains(response, "usuario", count=2)  #header

        response = self.c.post('/concepts_source/1/',
                               data={
                                   "definition": "Long definition...",
                               })
        self.assertContains(response, "today")
        self.assertContains(response, "usuario", count=4)  #header + history

    def test_concept_target(self):
        # language not added to glossary
        response = self.c.get('/concepts/2/gl/edit')
        self.assertEqual(response.status_code, 404)
        gl = Language.objects.get(iso_code='gl')
        glossary = Glossary.objects.get(pk=1)
        glossary.other_languages.add(gl)

        response = self.c.get('/concepts/2/gl/edit')
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Galician")
        self.assertContains(response, "xanela")
        self.assertNotContains(response, "Submit")

        self.login()
        response = self.c.get('/concepts/2/gl/edit')
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Galician")
        self.assertContains(response, "xanela")
        # This user has no rights for this Glossary
        self.assertNotContains(response, "Finalise term information")
        self.assertNotContains(response, "Submit")

        self.c.login(username='******', password='******')
        response = self.c.get('/concepts_source/1/')
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Finalise term information")
        self.assertContains(response, "Add corrected or alternative term")
        self.assertContains(response, "Submit")

        response = self.c.post('/concepts/2/gl/edit',
                               data={
                                   "translation": "SEARCHxxx",
                               })
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "successnote")
        self.assertContains(response, "search")
        self.assertContains(response, "SEARCHxxx")

        response = self.c.post('/concepts/2/gl/edit',
                               data={
                                   "translation": "SEARCHyyy",
                                   "definition": "definizione uno",
                               })
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "successnote")
        self.assertContains(response, "search")
        self.assertContains(response, "SEARCHxxx")
        self.assertContains(response, "SEARCHyyy")
        self.assertContains(response, "definizione uno")

        response = self.c.post('/concepts/2/gl/edit',
                               data={
                                   "definition": "newer definition",
                               })
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "successnote")
        self.assertContains(response, "newer definition")
        self.assertNotContains(response, "definizione uno")

        # too long
        response = self.c.post('/concepts/2/gl/edit',
                               data={
                                   "translation": "x" * 200,
                               })
        self.assertEqual(response.status_code, 200)
        self.assertNotContains(response, "xxxxxxxxxx")

        # duplicate
        response = self.c.post('/concepts/2/gl/edit',
                               data={
                                   "translation": "SEARCHxxx",
                               })
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "errornote")
        self.assertContains(response, "already present")
        self.assertContains(response, "SEARCHxxx")

    def test_glossaries(self):
        response = self.c.get('/glossaries/1/')
        self.assertContains(response, "Concepts")

        #        response = self.c.post('/glossaries/1/', data={
        #            'collaboration_role': 'S', # Specialist
        #        })
        #        self.assertNotContains(response, "You will receive a message")

        self.login()
        response = self.c.get('/glossaries/1/')
        self.assertContains(response, "Glossary collaborators")

        glossary = Glossary.objects.get(pk=1)
        glossary.assign_owner_permissions(self.user)
        glossary.save()
        response = self.c.get('/glossaries/1/')
        self.assertContains(response, "edit this glossary")

        if settings.FEATURES.get('collaboration', True):
            response = self.c.post(
                '/glossaries/1/',
                data={
                    'collaboration_role': 'S',  # Specialist
                })
            self.assertContains(response, "You will receive a message")
            response = self.c.post('/glossaries/1/',
                                   data={
                                       'collaboration_role': 'S',
                                   })
            self.assertContains(response, "You already sent")
            response = self.c.post('/glossaries/1/',
                                   data={
                                       'subscribe_to_this_glossary': True,
                                   })

        if settings.FEATURES.get('subscription', True):
            self.assertContains(response, "You have subscribed")
            response = self.c.post('/glossaries/1/', data={})  # empty form
            self.assertEqual(response.status_code, 200)
class TestViews(TestCase):
    
    def setUp(self):
        '''
        Set up a client to be able to login users in order to test views
        using @login_required decorators.
        '''
        self.client = Client()
        self.user = User.objects.create_user('joanna',
                                             '*****@*****.**',
                                             'secret')

    def test_get_all_tickets_page(self):
        '''
        Test all tickets page - if redirected to the correct URL and that
        a correct template is used
        '''
        page = self.client.get('/tickets/')
        self.assertEqual(page.status_code, 200)
        self.assertTemplateUsed(page, 'all_tickets.html')
        
    def test_get_all_tickets_with_filters_page(self):
        '''
        Test all tickets page with filters - if redirected to the correct
        URL and that a correct template is used.
        '''
        page = self.client.get(
            '/tickets/?ticket-type=Feature&ticket-status=Open/')
        self.assertEqual(page.status_code, 200)
        self.assertTemplateUsed(page, 'all_tickets.html')
        
        page = self.client.get('/tickets/?ticket-type=Feature/')
        self.assertEqual(page.status_code, 200)
        self.assertTemplateUsed(page, 'all_tickets.html')
        
        page = self.client.get('/tickets/?ticket-status=Open/')
        self.assertEqual(page.status_code, 200)
        self.assertTemplateUsed(page, 'all_tickets.html')
        
    def test_get_add_ticket_page(self):
        '''
        Test add ticket page - if redirected to the correct URL and that
        a correct template is used.
        '''
        # Login user
        self.client.login(username='******', password='******')
        
        page = self.client.get('/tickets/new/')
        self.assertEqual(page.status_code, 200)
        self.assertTemplateUsed(page, 'add_ticket.html')
    
    def test_get_edit_ticket_page(self):
        '''
        Test edit ticket page - if redirected to the correct URL and that
        a correct template is used.
        '''
        # Login user
        self.client.login(username='******', password='******')
        
        # Create a ticket
        ticket = Ticket(subject='Test Subject',
                        ticket_type='Bug',
                        ticket_status='Open',
                        description='Testing description of a ticket')
        ticket.save()

        page = self.client.get('/tickets/edit/ticket/{0}/'.format(ticket.id))
        self.assertEqual(page.status_code, 200)
        self.assertTemplateUsed(page, 'add_ticket.html')
    
    def test_get_upvote_ticket_without_donation_page(self):
        '''
        Test that checks if page reverses to view ticket page after
        the ticket is upvoted.
        Ticket type bug does not require donation.
        '''
        # Login user
        self.client.login(username='******', password='******')
        
        # Create a ticket
        ticket = Ticket(subject='Test Subject',
                        ticket_type='Bug',
                        ticket_status='Open',
                        description='Testing description of a ticket')
        ticket.save()
        
        page = self.client.get('/tickets/upvote/ticket/{0}/'.format(ticket.id))
        self.assertEqual(page.status_code, 302)
        self.client.post(reverse('view_ticket', kwargs={'pk': 1}))
    
    def test_get_downvote_ticket_page(self):
        '''
        Test that checks if redirects to the correct url after
        the ticket is downvoted.
        '''
        # Login user
        self.client.login(username='******', password='******')
        
        # Create a ticket
        ticket = Ticket(user=self.user,
                        subject='Test Subject',
                        ticket_type='Bug',
                        ticket_status='Open',
                        description='Testing description of a ticket')
        ticket.save()
        
        # Create upvote so it exist before you test downvote url
        upvote = Upvote(ticket=ticket,
                        user=self.user)
        upvote.save()
        
        page = self.client.get(
            '/tickets/downvote/ticket/{0}/'.format(ticket.id))
        self.assertEqual(page.status_code, 302)
     
    def test_get_delete_ticket_by_author_page(self):
        '''
        Test case where ticket author deletes their own ticket.
        '''
        # Login user
        self.client.login(username='******', password='******')
        
        # Create a ticket
        ticket = Ticket(user=self.user,
                        subject='Test Subject',
                        ticket_type='Bug',
                        ticket_status='Open',
                        description='Testing description of a ticket')
        ticket.save()
        
        page = self.client.get('/tickets/delete/ticket/{0}/'.format(ticket.id))
        self.assertEqual(page.status_code, 302)
    
    def test_get_delete_ticket_by_other_user_page(self):
        '''
        Test case when user attempts to delete a ticket created by other user.
        '''
        # Login user
        self.client.login(username='******', password='******')
        
        # Create other user that will be an author of the ticket
        other_user = User.objects.create_user('john',
                                              '*****@*****.**',
                                              'secret2')

        # Create a ticket
        ticket = Ticket(user=other_user,
                        subject='Test Subject',
                        ticket_type='Bug',
                        ticket_status='Open',
                        description='Testing description of a ticket')
        ticket.save()
        
        page = self.client.get('/tickets/delete/ticket/{0}/'.format(ticket.id))
        self.assertEqual(page.status_code, 302)
        self.client.post(reverse('view_ticket', kwargs={'pk': 1}))
        
    def test_404_error_if_comment_does_not_exist(self):
        '''
        Test if error will come up if attempted to edit comment that
        does not exist.
        '''
        # Login user
        self.client.login(username='******', password='******')
        
        # Create a ticket
        ticket = Ticket(user=self.user,
                        subject='Test Subject',
                        ticket_type='Bug',
                        ticket_status='Open',
                        description='Testing description of a ticket')
        ticket.save()
        
        page = self.client.get(
            '/tickets/view/ticket/{0}/comments/edit/comment/{1}'.format(
                ticket.id, None))
        self.assertEqual(page.status_code, 404)
    
    def test_get_delete_comment_by_author_page(self):
        '''
        Test case where comment author deletes their own comment.
        '''
        # Login user
        self.client.login(username='******', password='******')
        
        # Create a ticket
        ticket = Ticket(user=self.user,
                        subject='Test Subject',
                        ticket_type='Bug',
                        ticket_status='Open',
                        description='Testing description of a ticket')
        ticket.save()
        
        # Create a comment
        comment = Comment(user=self.user,
                          ticket=ticket,
                          comment='Testing comment description')
        comment.save()
        
        page = self.client.get(
            '/tickets/view/ticket/{0}/comments/delete/comment/{1}'.format(
                ticket.id, comment.id), follow=True)
        self.assertEqual(page.status_code, 200)
    
    def test_get_delete_comment_by_other_user_page(self):
        '''
        Test case where a user tries to delete someone else's comment.
        '''
        # Login user
        self.client.login(username='******', password='******')
        
        # Create other user that will be an author of the comment
        other_user = User.objects.create_user('john',
                                              '*****@*****.**',
                                              'secret2')
        
        # Create a ticket
        ticket = Ticket(user=self.user,
                        subject='Test Subject',
                        ticket_type='Bug',
                        ticket_status='Open',
                        description='Testing description of a ticket')
        ticket.save()
        
        # Create a comment
        comment = Comment(user=other_user,
                          ticket=ticket,
                          comment='Testing comment description')
        comment.save()
        
        # Test redirect when comment is deleted
        page = self.client.get(
            '/tickets/view/ticket/{0}/comments/delete/comment/{1}'.format(
                ticket.id, comment.id), follow=True)
        self.assertEqual(page.status_code, 200)
        
        # Test error message
        messages = list(page.context['messages'])
        self.assertEqual(len(messages), 1)
        self.assertEqual(str(messages[0]), "Error! You don't have a"
                         " permission to delete this comment.")
Ejemplo n.º 47
0
class InterviewerViewTest(BaseTest):
    def setUp(self):
        self.client = Client()
        self.user_without_permission = User.objects.create_user(
            username='******', email='*****@*****.**', password='******')
        self.raj = self.assign_permission_to(
            User.objects.create_user('demo5', '*****@*****.**', 'demo5'),
            'can_view_interviewers')
        self.assign_permission_to(self.raj, 'can_view_interviewers')
        self.client.login(username='******', password='******')
        self.ea = EnumerationArea.objects.create(name="BUBEMBE",
                                                 code="11-BUBEMBE")
        self.country = LocationType.objects.create(name="country",
                                                   slug="country")
        self.kampala = Location.objects.create(name="Kampala",
                                               type=self.country)
        self.ea.locations.add(self.kampala)
        self.survey = Survey.objects.create(name="survey A")
        self.form_data = {
            'name': 'Interviewer_1',
            'date_of_birth': '1987-08-06',
            'gender': 1,
            'ea': self.ea
        }

    # def test_new(self):
    #     ea_num = EnumerationArea.objects.create(name="enumeratiname",code="enumerationcode")
    #     z = Interviewer.objects.create(name="daddar",gender=1,date_of_birth="1989-05-15",level_of_education="Primary",language="English",weights=0,ea_id=ea_num.id)
    #     response = self.client.get(reverse('new_interviewer_page'))
    #     self.assertIn(response.status_code, [200,302])
    #     templates = [template.name for template in response.templates]
    #     self.assertIn('interviewers/interviewer_form.html', templates)
    #     self.assertEquals(response.context['action'], reverse('new_interviewer_page'))
    #     self.assertEquals(response.context['id'], 'create-interviewer-form')
    #     self.assertEquals(response.context['class'], 'interviewer-form')
    #     self.assertEquals(response.context['button_label'], 'Save')
    #     self.assertEquals(response.context['loading_text'], 'Creating...')
    #     self.assertIsInstance(response.context['form'], InterviewerForm)
    #     USSDAccessFormSet = inlineformset_factory(
    #         Interviewer, USSDAccess, form=USSDAccessForm, extra=extra)
    #     ussd_access_form = USSDAccessFormSet(
    #         prefix='ussd_access', instance=None)
    #     odk_access_form = ODKAccessForm(instance=None)
    #     self.assertIsInstance(response.context['ussd_access_form'], ussd_access_form)
    #     self.assertIsInstance(response.context['odk_access_form'], odk_access_form)
    #     self.assertEqual(response.context['title'], 'New Interviewer')

    # @patch('django.contrib.messages.success')
    # def test_create_interviewer(self, success_message):
    #     form_data = self.form_data
    #     investigator = Interviewer.objects.filter(name=form_data['name'])
    #     self.failIf(investigator)
    #     response = self.client.post(reverse('new_interviewer_page'), data=form_data)
    #     self.failUnlessEqual(response.status_code, 302)
    #     investigator = Interviewer.objects.get(name=form_data['name'])
    #     self.failUnless(investigator.id)
    #     for key in ['name','gender','date_of_birth','ea']:
    #         value = getattr(investigator, key)
    #         self.assertEqual(form_data[key], str(value))
    #     investigator = Interviewer.objects.filter(name=investigator)
    #     self.failUnless(investigator)
    #     self.assertEquals(
    #         investigator[0].date_of_birth, form_data['date_of_birth'])
    #     assert success_message.called

    # def test_index(self):
    #     ea_numb = EnumerationArea.objects.create(name="enumeraame",code="enumeratcode")
    #     z1 = Interviewer.objects.create(name="dady",gender=1,date_of_birth="1977-05-15",level_of_education="Primary",language="English",weights=0,ea_id=ea_numb.id)
    #     response = self.client.get(reverse('interviewers_page'))
    #     self.assertIn(response.status_code, [200,302])

    # def test_list_interviewers(self):
    #     self.eam = EnumerationArea.objects.create(name="ypal", code="06-ypal")
    #     investigator = Interviewer.objects.create(name="dilip",
    #                                                    ea=self.eam,
    #                                                    gender='1', level_of_education='Primary',
    #                                                    language='Eglish', weights=0, date_of_birth='1992-02-05')
    #     response = self.client.get(reverse('interviewers_page'))
    #     # self.failUnlessEqual(response.status_code, 200)
    #     self.assertIn(response.status_code, [200,302])
    #     templates = [template.name for template in response.templates]
    #     self.assertIn('interviewers/index.html', templates)
    #     self.assertIn(investigator, response.context['interviewers'])
    #     self.assertNotEqual(None, response.context['request'])

    # def test_edit_interviewer_view(self):
    #     x = Interviewer.objects.create(name="Investigator1",
    #                                                    ea=self.ea,
    #                                                    gender='1', level_of_education='Primary',
    #                                                    language='Eglish', weights=0,date_of_birth='1987-01-01')
    #     response = self.client.get(reverse('view_interviewer_page',kwargs={'interviewer_id':x.id}))
    #     self.assertIn(response.status_code, [200,302])
    #     # url = reverse(
    #     #     'view_interviewer_page',
    #     #     kwargs={"interviewer_id":  investigator.pk,"mode":'edit'})
    #     # response = self.client.get(url)
    #     # self.failUnlessEqual(response.status_code, 200)
    #     templates = [template.name for template in response.templates]
    #     self.assertIn('interviewers/interviewer_form.html', templates)
    #     self.assertEquals(response.context['action'], url)
    #     self.assertEquals(response.context['id'], 'create-interviewer-form')
    #     self.assertEquals(response.context['class'], 'interviewer-form')
    #     self.assertEquals(response.context['title'], 'Edit Interviewer')
    #     self.assertEquals(response.context['button_label'], 'Save')
    #     self.assertEquals(response.context['loading_text'], 'Saving...')
    #     self.assertIsInstance(response.context['form'], InterviewerForm)
    #     USSDAccessFormSet = inlineformset_factory(
    #         Interviewer, USSDAccess, form=USSDAccessForm, extra=extra)
    #     ussd_access_form = USSDAccessFormSet(
    #         prefix='ussd_access', instance=investigator)
    #     odk_access_form = ODKAccessForm(instance=investigator.odk_access[0])
    #     self.assertIsInstance(response.context['ussd_access_form'], ussd_access_form)
    #     self.assertIsInstance(response.context['odk_access_form'], odk_access_form)
    #     self.assertEqual(response.context['title'], 'New Interviewer')

    # def test_edit_interviewer_updates_interviewer_information(self):
    #     self.eas = EnumerationArea.objects.create(name="dams", code="17-dams")
    #     form_data = {
    #         'name': 'Interviewer_4',
    #         'date_of_birth': '1987-08-06',
    #         'gender': 0,
    #         'ea':self.eas.id
    #     }
    #     self.failIf(Interviewer.objects.filter(name=form_data['name']))
    #     y = Interviewer.objects.create(name="Investigator2",
    #                                                    ea=self.ea,
    #                                                    gender='1', level_of_education='Primary',
    #                                                    language='Eglish', weights=0,date_of_birth='1987-01-01')
    #     data = {
    #         'name': 'Interviewer_4',
    #         'date_of_birth': '1987-08-06',
    #         'gender': 1,
    #         'ea':self.eas.id
    #     }
    #     # url = reverse(
    #     #     'view_interviewer_page',
    #     #     kwargs={"interviewer_id":  investigator.pk,"mode":'edit'})
    #     # response = self.client.post(url, data=data)
    #     # self.failUnlessEqual(response.status_code, 302)
    #     response = self.client.get(reverse('view_interviewer_page',kwargs={'interviewer_id':y.id}))
    #     self.assertIn(response.status_code, [200,302])
    #     edited_user = Interviewer.objects.filter(name=data['name'],gender=data['gender'])
    #     self.assertEqual(1, edited_user.count())

    # def test_view_interviewer_details(self):
    #     self.ea1 = EnumerationArea.objects.create(name="BUBEMBE1", code="11-BUBEMBE1")
    #     self.country1 = LocationType.objects.create(name="country1", slug="country1")
    #     self.kampala1 = Location.objects.create(name="Kampala1", type=self.country1)
    #     self.ea1.locations.add(self.kampala1)
    #     investigators = Interviewer.objects.create(name="sandi",
    #                                                    ea=self.ea1,
    #                                                    gender='1', level_of_education='Primary',
    #                                                    language='Eglish', weights=0, date_of_birth='1987-01-01')
    #     response = self.client.get(reverse('view_interviewer_page', kwargs={'interviewer_id':investigators.id}))
    #     self.assertIn(response.status_code, [302,200])
    #     templates = [template.name for template in response.templates]
    #     self.assertIn('interviewers/interviewer_form.html', templates)
    #     self.assertEquals(response.context['Edit Interviewer'], user)
    #     self.assertEquals(
    #         response.context['cancel_url'],
    #         reverse('interviewers_page'))

    def test_unblock_interviwer_details(self):
        investigator = Interviewer.objects.create(name="Investigator6",
                                                  ea=self.ea,
                                                  gender='1',
                                                  level_of_education='Primary',
                                                  language='Eglish',
                                                  weights=0,
                                                  date_of_birth='1987-01-01')
        response = self.client.get(
            reverse('unblock_interviewer_page',
                    kwargs={'interviewer_id': investigator.id}))
        self.assertIn(response.status_code, [302, 200])
        investigator = Interviewer.objects.get(name='Investigator6')
        self.assertEquals(investigator.is_blocked, False)
        # self.assertIn("Interviewer USSD Access successfully unblocked.", response.cookies['messages'].value)
        # self.assertRedirects(response, expected_url=reverse('interviewers_page'), msg_prefix='')

    def test_block_interviewer_details(self):
        investigator = Interviewer.objects.create(name="Investigator5",
                                                  ea=self.ea,
                                                  gender='1',
                                                  level_of_education='Primary',
                                                  language='Eglish',
                                                  weights=0,
                                                  date_of_birth='1987-01-01')
        response = self.client.get(
            reverse('block_interviewer_page',
                    kwargs={'interviewer_id': investigator.id}))
        self.assertIn(response.status_code, [302, 200])
        z3 = Interviewer.objects.get(name='Investigator5')
        self.assertEquals(z3.is_blocked, True)
        # self.assertIn("Interviewer USSD Access successfully blocked.", response.cookies['messages'].value)
        # self.assertRedirects(response, expected_url=reverse('interviewers_page'))

    def test_block_interviwer_when_no_such_interviewer_exist(self):
        url = reverse('block_interviewer_page',
                      kwargs={"interviewer_id": 99999})
        response = self.client.get(url)
        self.assertRedirects(response,
                             expected_url=reverse('interviewers_page'))
        self.assertIn("Interviewer does not exist.",
                      response.cookies['messages'].value)

    def test_block_interviwer_when_no_such_interviewer_exist(self):
        url = reverse('unblock_interviewer_page',
                      kwargs={"interviewer_id": 99999})
        response = self.client.get(url)
        # self.assertRedirects(response, expected_url=reverse('interviewers_page'))
        # self.assertIn("Interviewer does not exist.", response.cookies['messages'].value)

    # def test_download_interviewers(self):
    #     response = self.client.get(reverse('download_interviewers'))
    #     # self.failUnlessEqual(response.status_code, 200)
    #     self.assertIn(response.status_code, [200,302])
    #     rtype = response.headers.get('content_type')
    #     self.assertIn('text/csv', rtype)
    #     res_csv = 'attachment; \
    #     filename="%s.csv"' % filename
    #     self.assertIn(response['Content-Disposition'], res_csv)

    # def test_view_interviewer_details_when_no_such_interviewer_exists(self):
    #     investigator = Interviewer.objects.create(name="Investigator10",
    #                                                    ea=self.ea,
    #                                                    gender='1', level_of_education='Primary',
    #                                                    language='Eglish', weights=0,date_of_birth='1987-01-01')
    #     self.client.get(reverse('view_interviewer_page', kwargs={"interviewer_id":investigator.id}))
    #     self.assertIn(response.status_code, [200,302])
    # url = reverse(
    #     'view_interviewer_page',
    #     kwargs={"interviewer_id":  investigator.id})
    # response = self.client.get(url)
    # self.assertRedirects(response, expected_url=reverse('interviewers_page'))
    # self.assertIn("Interviewer not found.", response.cookies['messages'].value)

    def test_restricted_permission(self):
        investigator = Interviewer.objects.create(name="Investigator",
                                                  ea=self.ea,
                                                  gender='1',
                                                  level_of_education='Primary',
                                                  language='Eglish',
                                                  weights=0,
                                                  date_of_birth='1987-01-01')
        self.assert_restricted_permission_for(reverse('interviewers_page'))
Ejemplo n.º 48
0
class URLsA(TestCase):

    fixtures = ['test_data']

    def setUp(self):
        self.c = Client()
        self.user = User.objects.create_user(username="******",
                                             email="*****@*****.**",
                                             password="******")
        self.user.save()

    def login(self):
        self.c.login(username='******', password='******')

    #TODO: consider using reverse(<viewname>) instead of hardcoding urls
    def test_plain_200_urls(self):
        for url in [
                '/',
                '/search/',
                '/advanced_search/',
                '/proposals/',
                '/feeds/all/',
                '/feeds/glossaries/',
                '/feeds/concepts/',
                '/feeds/translations/',
                '/feeds/comments/',
                '/autoterm/',
                '/profiles/',
                '/help/',
                '/accounts/login/',
                '/accounts/register/',
        ]:
            #print(url)
            response = self.c.get(url)
            self.assertEqual(response.status_code, 200)

    def test_plain_302_urls(self):
        for url in [
                '/import/',
                '/export/',
                '/admin/',
        ]:
            #print(url)
            response = self.c.get(url)
            self.assertEqual(response.status_code, 302)

    def test_post_403_urls(self):
        client = Client(enforce_csrf_checks=True)
        for url in [
                '/',  # proposal
                '/search/',
                '/advanced_search/',
                '/import/',
                '/export/',
                '/accounts/login/',
        ]:
            #print(url)
            response = client.post(url)
            self.assertEqual(response.status_code, 403)

    def test_user_200_urls(self):
        self.login()
        for url in [
                '/',
                '/export/',
                '/search/',
                '/advanced_search/',
                '/proposals/',
                '/feeds/all/',
                '/feeds/glossaries/',
                '/feeds/concepts/',
                '/feeds/translations/',
                '/feeds/comments/',
                '/autoterm/',
                '/profiles/',
                '/help/',
                ####
                '/import/',
                ###
                '/accounts/logout/',  # last: now logged out
        ]:
            #print(url)
            response = self.c.get(url)
            self.assertEqual(response.status_code, 200)
        # test that the logout worked:
        self.test_plain_302_urls()
Ejemplo n.º 49
0
class TestWebInterface(LocalTestCase):
    def setUp(self):
        super(TestWebInterface, self).setUp()
        self.client = Client()

    def test_set_recovery_instructions(self):
        # Get service page - will get 200 from login page
        resp = self.client.get(reverse('update-service',
                                       kwargs={'pk': self.service.id}),
                               follow=True)
        self.assertEqual(resp.status_code, 200)
        self.assertIn('username', resp.content)

        # Log in
        self.client.login(username=self.username, password=self.password)
        resp = self.client.get(
            reverse('update-service', kwargs={'pk': self.service.id}))
        self.assertEqual(resp.status_code, 200)
        self.assertNotIn('username', resp.content)

        snippet_link = 'https://sub.hackpad.com/wiki-7YaNlsC11bB.js'
        self.assertEqual(self.service.hackpad_id, None)
        resp = self.client.post(
            reverse('update-service', kwargs={'pk': self.service.id}),
            data={
                'name': self.service.name,
                'hackpad_id': snippet_link,
            },
            follow=True,
        )
        self.assertEqual(resp.status_code, 200)
        reloaded = Service.objects.get(id=self.service.id)
        self.assertEqual(reloaded.hackpad_id, snippet_link)
        # Now one on the blacklist
        blacklist_link = 'https://unapproved_link.domain.com/wiki-7YaNlsC11bB.js'
        resp = self.client.post(
            reverse('update-service', kwargs={'pk': self.service.id}),
            data={
                'name': self.service.name,
                'hackpad_id': blacklist_link,
            },
            follow=True,
        )
        self.assertEqual(resp.status_code, 200)
        self.assertIn('valid JS snippet link', resp.content)
        reloaded = Service.objects.get(id=self.service.id)
        # Still the same
        self.assertEqual(reloaded.hackpad_id, snippet_link)

    def test_create_instance(self):
        instances = Instance.objects.all()
        self.assertEqual(len(instances), 0)
        self.client.login(username=self.username, password=self.password)
        resp = self.client.post(
            reverse('create-instance'),
            data={
                'name': 'My little instance',
            },
            follow=True,
        )
        instances = Instance.objects.all()
        self.assertEqual(len(instances), 1)
        instance = instances[0]
        self.assertEqual(len(instance.status_checks.all()), 1)

    def test_checks_report(self):
        form = StatusCheckReportForm({
            'service':
            self.service.id,
            'checks': [self.graphite_check.id],
            'date_from':
            date.today() - timedelta(days=1),
            'date_to':
            date.today(),
        })
        self.assertTrue(form.is_valid())
        checks = form.get_report()
        self.assertEqual(len(checks), 1)
        check = checks[0]
        self.assertEqual(len(check.problems), 1)
        self.assertEqual(check.success_rate, 50)
Ejemplo n.º 50
0
 def test_schedule_view(self):
     c = Client()
     self.assertTrue(c.login(username='******', password='******'))
     resp = c.get('/mail/schedule/')
     self.assertEquals(resp.status_code, 200)
Ejemplo n.º 51
0
def test_action_created_for_invoices():
    client = factories.Client.create()
    owner = factories.User.create(password="******")
    test_client = Client()
    assert test_client.login(username=owner.username, password="******")
    data = {
        'client': client.id,
        'name': "Invoice's history",
        'items-TOTAL_FORMS': u'1',
        'items-INITIAL_FORMS': u'0',
        'items-MIN_NUM_FORMS': u'0',
        'items-MAX_NUM_FORMS': u'1000',
        'items-0-id': "",
        'items-0-description': 'Computer',
        'items-0-quantity': 1,
        'items-0-vat': 20.0,
        'items-0-amount': 1000,
    }
    response = test_client.post(reverse('invoice-new'), data=data, follow=True)

    # Check the form is valid
    # response.redirect_chain
    assert response.status_code == 200
    assert hasattr(response, 'redirect_chain')

    # Make sure we have a new invoice creation action
    last_action = History.objects.all().order_by('-id')[0]
    assert last_action.action == 'created'
    assert last_action.content_type == ContentType.objects.get(
        app_label="invoice", model="invoice")
    assert last_action.object_id == '1'
    assert last_action.user == owner

    invoice = models.Invoice.objects.all().order_by('-id')[0]

    # Now update the invoice
    data['items-à-quantity'] = 2
    response = test_client.post(reverse('invoice-update',
                                        kwargs={'invoice_id': invoice.id}),
                                data=data,
                                follow=True)

    # Check the form is valid
    # response.redirect_chain
    assert response.status_code == 200
    assert hasattr(response, 'redirect_chain')

    # Make sure we have a new invoice creation action
    last_action = History.objects.all().order_by('-id')[0]
    assert last_action.action == 'updated'
    assert last_action.content_type == ContentType.objects.get(
        app_label="invoice", model="invoice")
    assert last_action.object_id == '1'
    assert last_action.user == owner

    # Validate the invoice
    response = test_client.get(reverse('invoice-validate',
                                       kwargs={'invoice_id': invoice.id}),
                               follow=True)
    assert response.status_code == 200

    # Ensure we marked the invoice as validated
    last_action = History.objects.all().order_by('-id')[0]
    assert last_action.action == 'unpaid'
    assert last_action.content_type == ContentType.objects.get(
        app_label="invoice", model="invoice")
    assert last_action.object_id == '1'
    assert last_action.user == owner

    # Pay the invoice
    response = test_client.get(reverse('invoice-paid',
                                       kwargs={'invoice_id': invoice.id}),
                               follow=True)
    assert response.status_code == 200

    # Ensure we marked the invoice as validated
    last_action = History.objects.all().order_by('-id')[0]
    assert last_action.action == 'paid'
    assert last_action.content_type == ContentType.objects.get(
        app_label="invoice", model="invoice")
    assert last_action.object_id == '1'
    assert last_action.user == owner

    # Move the invoice back into sent state
    invoice = models.Invoice.objects.get(id=invoice.id)
    invoice.status = 'draft'
    invoice.save()

    # Cancel the invoice
    response = test_client.get(reverse('invoice-cancel',
                                       kwargs={'invoice_id': invoice.id}),
                               follow=True)
    assert response.status_code == 200

    # Ensure we marked the invoice as validated
    last_action = History.objects.all().order_by('-id')[0]
    assert last_action.action == 'canceled'
    assert last_action.content_type == ContentType.objects.get(
        app_label="invoice", model="invoice")
    assert last_action.object_id == '1'
    assert last_action.user == owner
Ejemplo n.º 52
0
class Test_Import(TestCase):
    fixtures = [
        'apps/rss_feeds/fixtures/initial_data.json', 'opml_import.json'
    ]

    def setUp(self):
        self.client = Client()

    def test_opml_import(self):
        self.client.login(username='******', password='******')
        user = User.objects.get(username='******')

        # Verify user has no feeds
        subs = UserSubscription.objects.filter(user=user)
        self.assertEqual(subs.count(), 0)

        f = open(os.path.join(os.path.dirname(__file__), 'fixtures/opml.xml'))
        response = self.client.post(reverse('opml-upload'), {'file': f})
        self.assertEqual(response.status_code, 200)

        # Verify user now has feeds
        subs = UserSubscription.objects.filter(user=user)
        self.assertEqual(subs.count(), 54)

        usf = UserSubscriptionFolders.objects.get(user=user)
        print(json_functions.decode(usf.folders))
        self.assertEqual(json_functions.decode(usf.folders), [{
            'Tech': [
                4, 5, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
                24, 25, 26, 27, 28
            ]
        }, 1, 2, 3, 6, {
            'New York': [1, 2, 3, 4, 5, 6, 7, 8, 9]
        }, {
            'tech': []
        }, {
            'Blogs': [
                29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
                {
                    'The Bloglets': [45, 46, 47, 48, 49]
                }
            ]
        }, {
            'Cooking': [50, 51, 52, 53]
        }, 54])

    def test_opml_import__empty(self):
        self.client.login(username='******', password='******')
        user = User.objects.get(username='******')

        # Verify user has default feeds
        subs = UserSubscription.objects.filter(user=user)
        self.assertEqual(subs.count(), 0)

        response = self.client.post(reverse('opml-upload'))
        self.assertEqual(response.status_code, 200)

        # Verify user now has feeds
        subs = UserSubscription.objects.filter(user=user)

        self.assertEquals(subs.count(), 0)
Ejemplo n.º 53
0
class ShoppingViewsTestCase(unittest.TestCase):
    """
    This test derives django.utils.unittest.TestCate rather than the default django.test.TestCase.
    Thus, self.client is not automatically created and fixtures not automatically loaded. This
    will be achieved manually by a custom implementation of setUp()
    """
    fixtures = [
        'kcs_categories.yaml', 'kcs_products.yaml', 'kcs_promotions.yaml',
        'kcs_promocode.yaml', 'kcs_operators_configs.yaml', 'kcs_members.yaml',
        'kcs_profiles.yaml', 'kcs_setup_data.yaml'
    ]

    def setUp(self):
        self.client = Client()
        for fixture in self.fixtures:
            call_command('loaddata', fixture)
            call_command('loaddata', 'umbrella')

    def tearDown(self):
        wipe_test_data()
        wipe_test_data('umbrella')

    @override_settings(IKWEN_SERVICE_ID='56eb6d04b37b3379b531b103')
    def test_ProductDetail_with_active_promotion(self):
        """
        ProductDetail view must load the correct product in the page
        """
        coca_promo = Promotion.objects.get(pk='56b3744479b531e011456651')
        coca_promo.is_active = True
        coca_promo.save()
        response = self.client.get(
            reverse('shopping:product_detail', args=('food', 'coca-cola')))
        self.assertEqual(response.status_code, 200)
        product = response.context['product']
        self.assertEqual(product.name, 'Coca-Cola')
        self.assertEqual(product.on_sale, True)
        self.assertEqual(product.previous_price, 450)
        self.assertEqual(product.retail_price, 405)

    def test_apply_promotion_discount_on_product_list(self):
        """
            here we test the complete operation of the promotion management function;
            here for a given promotion, the test will determine if in the end, the promotion will normally apply
            where it is necessary and with the expected values

        """
        # promoted_category = ProductCategory.objects.get(pk='569228a9b37b3301e0706b52')
        # product_in_category = Product.objects.filter(category=promoted_category)
        all_site_product = Product.objects.all()
        specific_promoted_item, item_in_promoted_category, item_in_site = {}, {}, {}
        promotions = Promotion.objects.all()
        for promotion in promotions:
            promotion.is_active = True
            promotion.save()

        final_product_list = apply_promotion_discount(list(all_site_product))
        for product in final_product_list:
            if product.id == '55d1fa8feb60008099bd4152':  #Coca-Cola
                specific_promoted_item = product
            if product.id == '55d1fa8feb60008099bd4153':  #Mutzig
                item_in_promoted_category = product
            if product.id == '55d1fa8feb60008099bd4151':  #Samsung Galaxy S7
                item_in_site = product

        self.assertEqual(specific_promoted_item.name, 'Coca-Cola')
        self.assertEqual(specific_promoted_item.on_sale, True)
        self.assertEqual(specific_promoted_item.previous_price, 450)
        self.assertEqual(specific_promoted_item.retail_price, 405)

        self.assertEqual(item_in_promoted_category.name, 'Mutzig')
        self.assertEqual(item_in_promoted_category.on_sale, True)
        self.assertEqual(item_in_promoted_category.previous_price, 550)
        self.assertEqual(item_in_promoted_category.retail_price, 440)

        self.assertEqual(item_in_site.name, 'Samsung Galaxy S7')
        self.assertEqual(item_in_site.on_sale, True)
        self.assertEqual(item_in_site.previous_price, 480000)
        self.assertEqual(item_in_site.retail_price, 456000)

    def test_apply_promotion_discount_on_category_only(self):
        """
            here we test the complete operation of the promotion management function;
            here for a given promotion, the test will determine if at the end, the promotion will normally be apply
            on the category "Food" products only

        """
        all_site_product = Product.objects.all()
        specific_promoted_item, item_in_promoted_category, item_in_site = {}, {}, {}
        promotions = Promotion.objects.all()
        for promotion in promotions:
            promotion.is_active = False
            if promotion.category:
                promotion.is_active = True
            promotion.save()

        final_product_list = apply_promotion_discount(list(all_site_product))
        for product in final_product_list:
            if product.id == '55d1fa8feb60008099bd4152':
                specific_promoted_item = product
            if product.id == '55d1fa8feb60008099bd4153':
                item_in_promoted_category = product
            if product.id == '55d1fa8feb60008099bd4151':
                item_in_site = product

        self.assertEqual(specific_promoted_item.name, 'Coca-Cola')
        self.assertEqual(specific_promoted_item.on_sale, False)
        self.assertEqual(specific_promoted_item.retail_price, 450)

        self.assertEqual(item_in_promoted_category.name, 'Mutzig')
        self.assertEqual(item_in_promoted_category.on_sale, False)
        self.assertEqual(item_in_promoted_category.retail_price, 550)

        self.assertEqual(item_in_site.name, 'Samsung Galaxy S7')
        self.assertEqual(item_in_site.on_sale, True)
        self.assertEqual(item_in_site.previous_price, 480000)
        self.assertEqual(item_in_site.retail_price, 456000)

    @override_settings(IKWEN_SERVICE_ID='56eb6d04b37b3379b531b103')
    def test_confirm_checkout_with_authenticated_user(self):
        res = self.client.get(reverse('sales:find_promo_code'),
                              {'code': 'partner15'})
        self.assertEqual(res.status_code, 200)
        self.client.login(username='******', password='******')
        response = self.client.post(
            reverse('shopping:paypal_set_checkout'), {
                'name': 'Simo Messina',
                'phone': '655003321',
                'email': '*****@*****.**',
                'country_iso2': 'CM',
                'city': 'Yaounde',
                'address': 'Odza',
                'entries':
                '55d1fa8feb60008099bd4151:1,55d1fa8feb60008099bd4153:6',
                'delivery_option_id': '55d1feb9b37b301e070604a0',
                'success_url': reverse('shopping:checkout')
            })
        # json_resp = json.loads(response.content)
        # response = self.client.post(reverse('shopping:paypal_do_checkout'),  data={'order_id': json_resp['order_id']})
        order = Order.objects.all()[0]
        self.assertEqual(order.items_count, 7)
        self.assertEqual(order.coupon.rate, 15)
        # self.assertEqual(order.total_cost, 459135)
        self.assertEqual(order.items_cost, 410805)
Ejemplo n.º 54
0
class TestDomainViews(TestCase):
    def setUp(self):
        self.client = Client()

        self.domain = Domain(name="fandago", is_active=True)
        self.domain.save()

        self.username = '******'
        self.password = '******'
        self.user = WebUser.create(self.domain.name,
                                   self.username,
                                   self.password,
                                   is_admin=True)
        self.user.eula.signed = True
        self.user.save()

        self.app = Application.new_app(domain="fandago", name="cheeto")
        self.app.save()

    def tearDown(self):
        self.user.delete()
        self.domain.delete()

    def test_allow_domain_requests(self):
        self.client.login(username=self.username, password=self.password)

        public_domain = Domain(name="public", is_active=True)
        public_domain.allow_domain_requests = True
        public_domain.save()

        response = self.client.get(reverse("domain_homepage",
                                           args=[public_domain.name]),
                                   follow=True)
        self.assertEqual(response.status_code, 200)

        public_domain.delete()

    def test_disallow_domain_requests(self):
        self.client.login(username=self.username, password=self.password)

        private_domain = Domain(name="private", is_active=True)
        private_domain.save()

        response = self.client.get(reverse("domain_homepage",
                                           args=[private_domain.name]),
                                   follow=True)
        self.assertEqual(response.status_code, 404)

        private_domain.delete()

    def test_add_repeater(self):
        forwarding_url = 'https://example.com/forwarding'

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

        post_url = reverse('add_repeater',
                           kwargs={
                               'domain': self.domain.name,
                               'repeater_type': 'AppStructureRepeater'
                           })
        response = self.client.post(post_url, {'url': forwarding_url},
                                    follow=True)
        self.assertEqual(response.status_code, 200)

        self.client.logout()

        app_structure_repeaters = AppStructureRepeater.by_domain(
            self.domain.name)
        self.assertEqual(len(app_structure_repeaters), 1)

        for app_structure_repeater in app_structure_repeaters:
            app_structure_repeater.delete()

    def delete_domain_snapshots(self):
        for snap in self.domain.snapshots():
            snap.delete()

    @teardown(delete_domain_snapshots)
    def test_exchange_snapshot_view(self):
        """
        Tests creating a new exchange snapshot and then creating another snapshot
        """

        self.client.login(username=self.username, password=self.password)
        app_publish = "{}-publish".format(self.app._id)
        filename = 'file.txt'

        data = {
            'title': 'Title',
            'short_description': 'Description',
            'description': 'Description',
            'project_type': 'MCH',
            'license': 'cc',
            'documentation_file': SimpleUploadedFile(filename, b'contents'),
            'publish_on_submit': 'yes',
            'cda_confirmed': True,
            app_publish: True,
        }

        response = self.client.post(reverse(
            CreateNewExchangeSnapshotView.urlname, args=[self.domain.name]),
                                    data,
                                    follow=True)
        self.assertEqual(response.status_code, 200)
        published = self.domain.published_snapshot()
        self.assertIsNotNone(published)

        self.assertEqual(published.title, data['title'])
        self.assertEqual(published.documentation_file_path, filename)

        # Should keep documentation file when old_documentation_file is specified
        del data['documentation_file']
        data['old_documentation_file'] = True

        response = self.client.post(reverse(
            CreateNewExchangeSnapshotView.urlname, args=[self.domain.name]),
                                    data,
                                    follow=True)
        self.domain = Domain.get(self.domain._id)
        self.assertEqual(response.status_code, 200)
        snapshots = list(self.domain.snapshots())
        self.assertEqual(len(snapshots), 2)
        self.assertEqual(snapshots[0].documentation_file_path, filename)
        self.assertEqual(snapshots[1].documentation_file_path, filename)
Ejemplo n.º 55
0
class ContentStoreToyCourseTest(ModuleStoreTestCase):
    """
    Tests that use the toy course.
    """

    def setUp(self):
        """
        Create user and login.
        """
        self.staff_pwd = super(ContentStoreToyCourseTest, self).setUp()
        self.staff_usr = self.user
        self.non_staff_usr, self.non_staff_pwd = self.create_non_staff_user()

        self.client = Client()
        self.contentstore = contentstore()

        self.course_key = SlashSeparatedCourseKey('edX', 'toy', '2012_Fall')

        import_from_xml(
            modulestore(), self.user.id, 'common/test/data/', ['toy'],
            static_content_store=self.contentstore, verbose=True
        )

        # A locked asset
        self.locked_asset = self.course_key.make_asset_key('asset', 'sample_static.txt')
        self.url_locked = self.locked_asset.to_deprecated_string()
        self.contentstore.set_attr(self.locked_asset, 'locked', True)

        # An unlocked asset
        self.unlocked_asset = self.course_key.make_asset_key('asset', 'another_static.txt')
        self.url_unlocked = self.unlocked_asset.to_deprecated_string()
        self.length_unlocked = self.contentstore.get_attr(self.unlocked_asset, 'length')

    def test_unlocked_asset(self):
        """
        Test that unlocked assets are being served.
        """
        self.client.logout()
        resp = self.client.get(self.url_unlocked)
        self.assertEqual(resp.status_code, 200)  # pylint: disable=E1103

    def test_locked_asset_not_logged_in(self):
        """
        Test that locked assets behave appropriately in case the user is not
        logged in.
        """
        self.client.logout()
        resp = self.client.get(self.url_locked)
        self.assertEqual(resp.status_code, 403)  # pylint: disable=E1103

    def test_locked_asset_not_registered(self):
        """
        Test that locked assets behave appropriately in case user is logged in
        in but not registered for the course.
        """
        self.client.login(username=self.non_staff_usr, password=self.non_staff_pwd)
        resp = self.client.get(self.url_locked)
        self.assertEqual(resp.status_code, 403)  # pylint: disable=E1103

    def test_locked_asset_registered(self):
        """
        Test that locked assets behave appropriately in case user is logged in
        and registered for the course.
        """
        CourseEnrollment.enroll(self.non_staff_usr, self.course_key)
        self.assertTrue(CourseEnrollment.is_enrolled(self.non_staff_usr, self.course_key))

        self.client.login(username=self.non_staff_usr, password=self.non_staff_pwd)
        resp = self.client.get(self.url_locked)
        self.assertEqual(resp.status_code, 200)  # pylint: disable=E1103

    def test_locked_asset_staff(self):
        """
        Test that locked assets behave appropriately in case user is staff.
        """
        self.client.login(username=self.staff_usr, password=self.staff_pwd)
        resp = self.client.get(self.url_locked)
        self.assertEqual(resp.status_code, 200)  # pylint: disable=E1103

    def test_range_request_full_file(self):
        """
        Test that a range request from byte 0 to last,
        outputs partial content status code and valid Content-Range and Content-Length.
        """
        resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes=0-')

        self.assertEqual(resp.status_code, 206)  # HTTP_206_PARTIAL_CONTENT
        self.assertEqual(
            resp['Content-Range'],
            'bytes {first}-{last}/{length}'.format(
                first=0, last=self.length_unlocked - 1,
                length=self.length_unlocked
            )
        )
        self.assertEqual(resp['Content-Length'], str(self.length_unlocked))

    def test_range_request_partial_file(self):
        """
        Test that a range request for a partial file,
        outputs partial content status code and valid Content-Range and Content-Length.
        first_byte and last_byte are chosen to be simple but non trivial values.
        """
        first_byte = self.length_unlocked / 4
        last_byte = self.length_unlocked / 2
        resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes={first}-{last}'.format(
            first=first_byte, last=last_byte)
        )

        self.assertEqual(resp.status_code, 206)  # HTTP_206_PARTIAL_CONTENT
        self.assertEqual(resp['Content-Range'], 'bytes {first}-{last}/{length}'.format(
            first=first_byte, last=last_byte, length=self.length_unlocked))
        self.assertEqual(resp['Content-Length'], str(last_byte - first_byte + 1))

    def test_range_request_malformed_missing_equal(self):
        """
        Test that a range request with malformed Range (missing '=') outputs status 400.
        """
        resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes 0-')
        self.assertEqual(resp.status_code, 400)  # HTTP_400_BAD_REQUEST

    def test_range_request_malformed_not_bytes(self):
        """
        Test that a range request with malformed Range (not "bytes") outputs status 400.
        "Accept-Ranges: bytes" tells the user that only "bytes" ranges are allowed
        """
        resp = self.client.get(self.url_unlocked, HTTP_RANGE='bits=0-')
        self.assertEqual(resp.status_code, 400)  # HTTP_400_BAD_REQUEST

    def test_range_request_malformed_missing_minus(self):
        """
        Test that a range request with malformed Range (missing '-') outputs status 400.
        """
        resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes=0')
        self.assertEqual(resp.status_code, 400)  # HTTP_400_BAD_REQUEST

    def test_range_request_malformed_first_not_integer(self):
        """
        Test that a range request with malformed Range (first is not an integer) outputs status 400.
        """
        resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes=one-')
        self.assertEqual(resp.status_code, 400)  # HTTP_400_BAD_REQUEST

    def test_range_request_malformed_invalid_range(self):
        """
        Test that a range request with malformed Range (first_byte > last_byte) outputs status 400.
        """
        first_byte = self.length_unlocked / 2
        last_byte = self.length_unlocked / 4
        resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes={first}-{last}'.format(
            first=first_byte, last=last_byte)
        )

        self.assertEqual(resp.status_code, 400)  # HTTP_400_BAD_REQUEST

    def test_range_request_malformed_out_of_bounds(self):
        """
        Test that a range request with malformed Range (last_byte == totalLength, offset by 1 error)
        outputs status 400.
        """
        last_byte = self.length_unlocked
        resp = self.client.get(self.url_unlocked, HTTP_RANGE='bytes=0-{last}'.format(
            last=last_byte)
        )

        self.assertEqual(resp.status_code, 400)  # HTTP_400_BAD_REQUEST
Ejemplo n.º 56
0
 def adminClient(self):
     c = Client()
     c.login(username='******', password='******')
     return c
Ejemplo n.º 57
0
class SurveyViewTest(BaseTest):
    def setUp(self):
        self.client = Client()
        user_without_permission = User.objects.create_user(
            username='******', email='*****@*****.**', password='******')
        raj = self.assign_permission_to(
            User.objects.create_user('demo12', '*****@*****.**', 'demo12'),
            'can_view_batches')
        self.listing_form = mommy.make(ListingTemplate)
        question1 = mommy.make(Question,
                               qset=self.listing_form,
                               answer_type=NumericalAnswer.choice_name())
        question2 = mommy.make(Question,
                               qset=self.listing_form,
                               answer_type=TextAnswer.choice_name())
        question3 = mommy.make(Question,
                               qset=self.listing_form,
                               answer_type=VideoAnswer.choice_name())
        self.client.login(username='******', password='******')
        self.form_data = {
            'name':
            'survey demo12',
            'description':
            'survey description demo12',
            'has_sampling':
            True,
            'sample_size':
            10,
            'random_sample_label':
            'q1 {{%s}} q2: {{%s}}' %
            (question1.identifier, question2.identifier)
        }

    def test_view_survey_list(self):
        survey_1 = mommy.make(Survey)
        # survey_2 = mommy.make(Survey)
        response = self.client.get(reverse('survey_list_page'))
        self.assertEqual(200, response.status_code)
        templates = [template.name for template in response.templates]
        self.assertIn('surveys/index.html', templates)
        self.assertIn(survey_1, response.context['surveys'])
        # self.assertIn(survey_2, response.context['surveys'])
        self.assertIsNotNone(response.context['request'])
        self.assertIsInstance(response.context['survey_form'], SurveyForm)

    def test_add_survey(self):
        response = self.client.get(reverse('new_survey_page'))
        self.assertEqual(200, response.status_code)
        templates = [template.name for template in response.templates]
        self.assertIn('surveys/new.html', templates)
        self.assertIsInstance(response.context['survey_form'], SurveyForm)
        self.assertIn('add-survey-form', response.context['id'])
        self.assertIn('Create', response.context['button_label'])
        self.assertIn('New Survey', response.context['title'])
        self.assertIn(response.context['action'],
                      [reverse('new_survey_page'), '.'])

    def test_new_should_create_survey_on_post(self):
        user = mommy.make(UserProfile)
        form_data = deepcopy(self.form_data)
        form_data['name'] = 'new_name'
        form_data['description'] = 'edited_description'
        all_surveys = Survey.objects.filter(**self.form_data)
        self.failIf(all_surveys)
        form_data['email_group'] = user.id
        form_data['listing_form'] = self.listing_form.id
        response = self.client.post(reverse('new_survey_page'), data=form_data)
        self.assertRedirects(response,
                             expected_url=reverse('survey_list_page'),
                             status_code=302,
                             target_status_code=200,
                             msg_prefix='')
        retrieved_surveys = Survey.objects.filter(name=form_data['name'])
        self.assertEquals(1, retrieved_surveys.count())
        self.assertIn('Survey successfully added.',
                      response.cookies['messages'].__str__())

    def test_new_should_not_create_survey_on_post_if_survey_with_same_name_exists(
            self):
        user = mommy.make(UserProfile)
        form_data = self.form_data
        Survey.objects.create(**form_data)
        form_data['email_group'] = user.id
        response = self.client.post(reverse('new_survey_page'), data=form_data)
        error_message = 'Survey with name %s already exist.' % form_data['name']
        self.assertIn(error_message,
                      response.context['survey_form'].errors['name'])

    def test_new_should_have_a_sample_size_of_zero_if_has_sampling_is_false(
            self):
        user = mommy.make(UserProfile)
        form_data = self.form_data
        form_data['has_sampling'] = False
        form_data['email_group'] = user.id
        response = self.client.post(reverse('new_survey_page'), data=form_data)
        self.assertRedirects(response,
                             expected_url=reverse('survey_list_page'),
                             status_code=302,
                             target_status_code=200,
                             msg_prefix='')
        retrieved_surveys = Survey.objects.filter(name=form_data['name'],
                                                  has_sampling=False)
        self.assertEquals(1, len(retrieved_surveys))
        self.assertIn('Survey successfully added.',
                      response.cookies['messages'].__str__())
        self.assertEqual(0, retrieved_surveys[0].sample_size)

    def test_restricted_permissions(self):
        self.assert_restricted_permission_for('/groups/new/')
        self.assert_restricted_permission_for('/groups/')
        self.assert_restricted_permission_for('/surveys/1/delete/')
        self.assert_restricted_permission_for('/surveys/1/edit/')

    def test_edit_should_get_form_with_data_of_the_survey(self):
        survey = Survey.objects.create(**self.form_data)
        self.failUnless(survey)
        response = self.client.get('/surveys/%d/edit/' % survey.id)
        self.assertEqual(200, response.status_code)
        templates = [template.name for template in response.templates]
        self.assertIn('surveys/new.html', templates)
        self.assertIsInstance(response.context['survey_form'], SurveyForm)
        self.assertIn('edit-survey-form', response.context['id'])
        self.assertIn('Save', response.context['button_label'])
        self.assertIn('Edit Survey', response.context['title'])
        self.assertIn('/surveys/%d/edit/' % survey.id,
                      response.context['action'])

    def test_post_to_edit_page_should_edit_the_survey(self):
        survey = mommy.make(Survey, **self.form_data)
        user = mommy.make(UserProfile)
        survey.email_group.add(user)
        self.failUnless(survey)
        form_data = deepcopy(self.form_data)
        form_data['name'] = 'edited_name'
        form_data['description'] = 'edited_description'
        form_data['email_group'] = user.id
        form_data['listing_form'] = self.listing_form.id
        edit_url = reverse('edit_survey_page', args=(survey.id, ))
        response = self.client.post(edit_url, data=form_data)
        self.failIf(Survey.objects.filter(name=survey.name))
        survey = Survey.objects.get(name=form_data['name'],
                                    description=form_data['description'])
        self.failUnless(survey)
        self.assertRedirects(response,
                             '/surveys/',
                             status_code=302,
                             target_status_code=200,
                             msg_prefix='')
        success_message = 'Survey successfully edited.'
        self.assertIn(success_message, response.cookies['messages'].value)

    def test_delete_should_delete_the_survey(self):
        survey = Survey.objects.create(**self.form_data)
        self.failUnless(survey)
        response = self.client.get('/surveys/%d/delete/' % survey.id)
        self.assertRedirects(response,
                             reverse('survey_list_page'),
                             status_code=302,
                             target_status_code=200,
                             msg_prefix='')

    def test_should_throw_error_if_deleting_non_existing_survey(self):
        url = reverse('delete_survey', args=(390, ))
        response = self.client.get(url)
        self.assertEquals(response.status_code, 302)
        self.assertIn('/object_does_not_exist/', response.url)

    def test_can_delete_survey_only_if_it_has_no_interview(self):
        survey = mommy.make(Survey)
        url = reverse('delete_survey', args=(survey.id, ))
        response = self.client.get(url)
        self.assertRedirects(response,
                             reverse('survey_list_page'),
                             status_code=302,
                             target_status_code=200,
                             msg_prefix='')
        self.assertEquals(Survey.objects.filter(id=survey.id).count(), 0)
        # now check if this is ignored if survey has interview
        survey = mommy.make(Survey)
        interview = mommy.make(Interview, survey=survey)
        response = self.client.get(reverse('delete_survey',
                                           args=(survey.id, )))
        self.failUnless(Survey.objects.filter(id=survey.id).count())

    def test_should_throw_error_if_deleting_with_an_open_batch(self):
        survey = Survey.objects.create(**self.form_data)
        batch = Batch.objects.create(order=1, survey=survey)
        ea = EnumerationArea.objects.create(name='EA2')
        country = LocationType.objects.create(name='country', slug='country')
        kampala = Location.objects.create(name='Kampala', type=country)
        ea.locations.add(kampala)
        investigator = Interviewer.objects.create(name='Investigator',
                                                  ea=ea,
                                                  gender='1',
                                                  level_of_education='Primary',
                                                  language='Eglish',
                                                  weights=0)
        batch.open_for_location(kampala)
        response = self.client.get('/surveys/%s/delete/' % survey.id)
        self.assertRedirects(response,
                             '/surveys/',
                             status_code=302,
                             target_status_code=200,
                             msg_prefix='')

    def test_survey_does_not_exist_page_reidrects(self):
        url = reverse('edit_survey_page', args=(300, ))
        response = self.client.get(url)
        self.assertRedirects(response,
                             reverse('survey_list_page'),
                             status_code=302,
                             target_status_code=200,
                             msg_prefix='')

    def test_sampling_criteria_page_is_accessible_with_view_batches_permission(
            self):
        survey = mommy.make(Survey)
        sampling_criteria_url = reverse('listing_criteria_page',
                                        args=(survey.id, ))
        self.assert_restricted_permission_for(sampling_criteria_url)

    def test_post_sampling_criteria_page(self):
        self.assertEquals(Survey.objects.count(), 0)
        self.test_new_should_create_survey_on_post()
        survey = Survey.objects.first()
        sampling_criteria_url = reverse('listing_criteria_page',
                                        args=(survey.id, ))
        response = self.client.get(sampling_criteria_url)
        self.assertEquals(response.status_code, 200)

    def test_create_delete_sampling_criteria(self):
        self.assertEquals(Survey.objects.count(), 0)
        self.test_new_should_create_survey_on_post()
        survey = Survey.objects.first()
        self.failUnless(survey)
        sampling_criteria_url = reverse('listing_criteria_page',
                                        args=(survey.id, ))
        form_data = {
            'survey': survey.id,
            'validation_test': 'equals',
            'value': 1,
            'listing_question': self.listing_form.questions.first().id,
        }
        self.assertEquals(survey.randomization_criteria.count(),
                          0)  # confirm nothin exists
        response = self.client.post(sampling_criteria_url, data=form_data)
        self.assertRedirects(response,
                             sampling_criteria_url,
                             status_code=302,
                             target_status_code=200,
                             msg_prefix='')
        self.assertEquals(survey.randomization_criteria.count(),
                          1)  # confirm one criteria created
        delete_criteria_url = reverse('delete_listing_criterion',
                                      args=(survey.id, ))
        response = self.client.post(delete_criteria_url,
                                    data=form_data)  # delete criteria
        self.assertEquals(survey.randomization_criteria.count(),
                          0)  # confirm deleted
        self.assertRedirects(response,
                             sampling_criteria_url,
                             status_code=302,
                             target_status_code=200,
                             msg_prefix='')

    def test_only_ussd_question_types_are_used_form_randomization(self):
        self.assertEquals(Survey.objects.count(), 0)
        self.test_new_should_create_survey_on_post()
        survey = Survey.objects.first()
        self.failUnless(survey)
        sampling_criteria_url = reverse('listing_criteria_page',
                                        args=(survey.id, ))
        form_data = {
            'survey':
            survey.id,
            'validation_test':
            'equals',
            'value':
            1,
            'listing_question':
            self.listing_form.questions.get(
                answer_type=VideoAnswer.choice_name()).id,
        }
        self.assertEquals(survey.randomization_criteria.count(),
                          0)  # confirm nothin exists
        response = self.client.post(sampling_criteria_url, data=form_data)
        self.assertEquals(survey.randomization_criteria.count(),
                          0)  # confirm nothin exists
        self.assertEquals(response.context['sampling_form'].is_valid(), False)

    def test_clone_survey_clones_batch_in_another_survey(self):
        self.test_new_should_create_survey_on_post()
        survey = Survey.objects.first()
        batch = mommy.make(Batch, survey=survey, description='')
        clone_url = reverse('clone_survey_page', args=(survey.id, ))
        response = self.client.get(clone_url)
        self.assertRedirects(response,
                             reverse('survey_list_page'),
                             status_code=302,
                             target_status_code=200,
                             msg_prefix='')
        cloned_survey = Survey.objects.exclude(name=survey.name).first()
        self.failUnless(cloned_survey)
        self.assertFalse(cloned_survey.name == survey.name)
        self.assertIn(survey.name, cloned_survey.name)
        self.assertIn(batch.name, cloned_survey.batches.first().name)
        self.assertIn(batch.description,
                      cloned_survey.batches.first().description)

    def test_only_super_user_can_wipe_data(self):
        user = User.objects.create_user('user1', '*****@*****.**', 'demo12')
        user.is_superuser = True
        user.is_staff = True
        user.save()
        super_user = self.assign_permission_to(user, 'can_have_super_powers')
        self.test_new_should_create_survey_on_post()
        survey = Survey.objects.first()
        batch = mommy.make(Batch, survey=survey, description='')
        wipe_off_url = reverse('wipe_survey_data', args=(survey.id, ))
        interview = mommy.make(Interview, survey=survey, question_set=batch)
        response = self.client.get(wipe_off_url)
        # confirm interview was not deleted.
        self.assertEquals(Interview.objects.filter(id=interview.id).count(), 1)
        self.client.logout()
        self.client.login(username='******', password='******')
        superpowers_url = reverse(
            'activate_super_powers_page')  # first activate superperwers
        response = self.client.get(superpowers_url)
        # views_helper.activate_super_powers()
        response = self.client.get(wipe_off_url)
        # confirm interview was not deleted.
        self.assertEquals(Interview.objects.filter(id=interview.id).count(), 1)
Ejemplo n.º 58
0
class ShopTest(TestCase):
    fixtures = [
        'l10n-data.yaml', 'sample-store-data.yaml', 'products.yaml',
        'test-config.yaml', 'initial_data.yaml'
    ]

    def setUp(self):
        # Every test needs a client
        cache_delete()
        self.client = Client()
        self.US = Country.objects.get(iso2_code__iexact="US")
        rebuild_pricing()
        current_site = Site.objects.get_current()
        cache_key = "cat-%s-%s" % (current_site.id, get_language())
        cache.delete(cache_key)
        self.old_language_code = settings.LANGUAGE_CODE
        settings.LANGUAGE_CODE = 'en-us'

    def tearDown(self):
        cache_delete()
        settings.LANGUAGE_CODE = self.old_language_code

    def test_main_page(self):
        """
        Look at the main page
        """
        response = self.client.get(prefix + '/')

        # Check that the rendered context contains 4 products
        self.assertContains(response,
                            '<div class = "productImage">',
                            count=4,
                            status_code=200)

    def test_contact_form(self):
        """
        Validate the contact form works
        """

        response = self.client.get(prefix + '/contact/')
        self.assertContains(response,
                            '<h3>Contact Information</h3>',
                            count=1,
                            status_code=200)
        response = self.client.post(
            prefix + '/contact/', {
                'name': 'Test Runner',
                'sender': '*****@*****.**',
                'subject': 'A question to test',
                'inquiry': 'General Question',
                'contents': 'A lot of info goes here.'
            })
        self.assertRedirects(response,
                             prefix + '/contact/thankyou/',
                             status_code=302,
                             target_status_code=200)
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].subject, 'A question to test')

    def test_new_account(self):
        """
        Validate account creation process
        """
        shop_config = Config.objects.get_current()
        subject = u"Welcome to %s" % shop_config.store_name
        response = self.client.get('/accounts/register/')
        self.assertContains(response,
                            "Please Enter Your Account Information",
                            count=1,
                            status_code=200)
        response = self.client.post(
            '/accounts/register/', {
                'email': '*****@*****.**',
                'first_name': 'Paul',
                'last_name': 'Test',
                'password1': 'pass1',
                'password2': 'pass1',
                'newsletter': '0'
            })
        self.assertRedirects(response,
                             '/accounts/register/complete/',
                             status_code=302,
                             target_status_code=200)
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].subject, subject)

        response = self.client.get('/accounts/')
        self.assertContains(response,
                            "Welcome, Paul Test.",
                            count=1,
                            status_code=200)
        response = self.client.get('/accounts/logout/')

    def test_cart_adding(self, retest=False):
        """
        Validate we can add some items to the cart
        """
        response = self.client.get(prefix + '/product/dj-rocks/')
        if not retest:
            self.assertContains(response,
                                "Django Rocks shirt",
                                count=2,
                                status_code=200)
        response = self.client.post(prefix + '/cart/add/', {
            "productname": "dj-rocks",
            "1": "L",
            "2": "BL",
            "quantity": 2
        })
        if not retest:
            self.assertRedirects(response,
                                 prefix + '/cart/',
                                 status_code=302,
                                 target_status_code=200)
        response = self.client.get(prefix + '/cart/')
        self.assertContains(response,
                            "Django Rocks shirt (Large/Blue)",
                            count=1,
                            status_code=200)

    def test_cart_adding_errors_nonexistent(self):
        """
        Test proper error reporting when attempting to add items to the cart.
        """

        # Attempting to add a nonexistent product should result in a 404 error.
        response = self.client.post(prefix + '/cart/add/', {
            'productname': 'nonexistent-product',
            'quantity': '1'
        })
        self.assertContains(response,
                            "The product you have requested does not exist.",
                            count=1,
                            status_code=404)

    def test_cart_adding_errors_inactive(self):
        # You should not be able to add a product that is inactive.
        py_shirt = Product.objects.get(slug='PY-Rocks')
        py_shirt.active = False
        py_shirt.save()
        response = self.client.post(prefix + '/cart/add/', {
            'productname': 'PY-Rocks',
            'quantity': '1'
        })
        self.assertContains(response,
                            "That product is not available at the moment.",
                            count=1,
                            status_code=404)

    def test_cart_adding_errors_invalid_qty(self):
        # You should not be able to add a product with a non-valid decimal quantity.
        response = self.client.post(prefix + '/cart/add/', {
            'productname': 'neat-book',
            '3': 'soft',
            'quantity': '1.5a'
        },
                                    follow=True)

        url = prefix + '/product/neat-book-soft/'
        self.assertRedirects(response,
                             url,
                             status_code=302,
                             target_status_code=200)
        self.assertContains(response, "Invalid quantity.", count=1)

    def test_cart_adding_errors_less_zero(self):
        # You should not be able to add a product with a quantity less than zero.
        response = self.client.post(prefix + '/cart/add/', {
            'productname': 'neat-book',
            '3': 'soft',
            'quantity': '0'
        },
                                    follow=True)

        url = prefix + '/product/neat-book-soft/'
        self.assertRedirects(response,
                             url,
                             status_code=302,
                             target_status_code=200)
        self.assertContains(response,
                            "Please enter a positive number.",
                            count=1)

    def test_cart_adding_errors_out_of_stock(self):
        # If no_stock_checkout is False, you should not be able to order a
        # product that is out of stock.
        setting = config_get('PRODUCT', 'NO_STOCK_CHECKOUT')
        setting.update(False)
        response = self.client.post(prefix + '/cart/add/', {
            'productname': 'neat-book',
            '3': 'soft',
            'quantity': '1'
        },
                                    follow=True)

        url = prefix + '/product/neat-book-soft/'
        self.assertRedirects(response,
                             url,
                             status_code=302,
                             target_status_code=200)
        self.assertContains(
            response,
            "A really neat book (Soft cover)&#39; is out of stock.",
            count=1)

    def test_product(self):
        # Test for an easily missed reversion. When you lookup a productvariation product then
        # you should get the page of the parent configurableproduct, but with the options for
        # that variation already selected
        response = self.client.get(prefix + '/product/neat-book-soft/')
        self.assertContains(response,
                            'option value="soft" selected="selected"')
        amount = moneyfmt(Decimal('5.00'))
        self.assertContains(response, smart_str(amount))

    def test_orphaned_product(self):
        """
        Get the page of a Product that is not in a Category.
        """
        Product.objects.create(name="Orphaned Product",
                               slug="orphaned-product",
                               site=Site.objects.get_current())
        response = self.client.get(prefix + '/product/orphaned-product/')
        self.assertContains(response, 'Orphaned Product')
        self.assertContains(response, 'Software')

    def test_get_price(self):
        """
        Get the price and productname of a ProductVariation.
        """
        response = self.client.get(prefix + '/product/dj-rocks/')
        self.assertContains(response,
                            "Django Rocks shirt",
                            count=2,
                            status_code=200)

        # this tests the unmolested price from the ConfigurableProduct, and
        # makes sure we get a good productname back for the ProductVariation
        response = self.client.post(prefix + '/product/dj-rocks/prices/', {
            "1": "S",
            "2": "B",
            "quantity": '1'
        })
        content = response.content.split(',')
        self.assertEquals(content[0], '["dj-rocks-s-b"')
        self.assert_(content[1].endswith('20.00"]'))

        # This tests the option price_change feature, and again the productname
        response = self.client.post(prefix + '/product/dj-rocks/prices/', {
            "1": "L",
            "2": "BL",
            "quantity": '2'
        })
        content = response.content.split(',')
        self.assertEqual(content[0], '["dj-rocks-l-bl"')
        self.assert_(content[1].endswith('23.00"]'))

    def test_cart_removing(self):
        """
        Validate we can remove an item
        """
        setting = config_get('PRODUCT', 'NO_STOCK_CHECKOUT')
        setting.update(True)

        self.test_cart_adding(retest=True)
        response = self.client.get(prefix + '/cart/')
        cartitem_id = response.context[0]['cart'].cartitem_set.all()[0].id
        response = self.client.post(prefix + '/cart/remove/',
                                    {'cartitem': str(cartitem_id)})
        #self.assertRedirects(response, prefix + '/cart/',
        #    status_code=302, target_status_code=200)
        response = self.client.get(prefix + '/cart/')
        self.assertContains(response,
                            "Your cart is empty.",
                            count=1,
                            status_code=200)

    def test_checkout(self):
        """
        Run through a full checkout process
        """
        cache_delete()
        tax = config_get('TAX', 'MODULE')
        tax.update('tax.modules.percent')
        pcnt = config_get('TAX', 'PERCENT')
        pcnt.update('10')
        shp = config_get('TAX', 'TAX_SHIPPING_PERCENT')
        shp.update(False)

        self.test_cart_adding()
        response = self.client.post(url('satchmo_checkout-step1'),
                                    get_step1_post_data(self.US))
        self.assertRedirects(response,
                             url('DUMMY_satchmo_checkout-step2'),
                             status_code=302,
                             target_status_code=200)
        data = {
            'credit_type': 'Visa',
            'credit_number': '4485079141095836',
            'month_expires': '1',
            'year_expires': '2015',
            'ccv': '552',
            'shipping': 'FlatRate'
        }
        response = self.client.post(url('DUMMY_satchmo_checkout-step2'), data)
        self.assertRedirects(response,
                             url('DUMMY_satchmo_checkout-step3'),
                             status_code=302,
                             target_status_code=200)
        response = self.client.get(url('DUMMY_satchmo_checkout-step3'))
        amount = smart_str('Shipping + ' + moneyfmt(Decimal('4.00')))
        self.assertContains(response, amount, count=1, status_code=200)

        amount = smart_str('Tax + ' + moneyfmt(Decimal('4.60')))
        self.assertContains(response, amount, count=1, status_code=200)

        amount = smart_str('Total = ' + moneyfmt(Decimal('54.60')))
        self.assertContains(response, amount, count=1, status_code=200)

        response = self.client.post(url('DUMMY_satchmo_checkout-step3'),
                                    {'process': 'True'})
        self.assertRedirects(response,
                             url('DUMMY_satchmo_checkout-success'),
                             status_code=302,
                             target_status_code=200)
        self.assertEqual(len(mail.outbox), 1)

        # Log in as a superuser
        user = User.objects.create_user('fredsu', '*****@*****.**', 'passwd')
        user.is_staff = True
        user.is_superuser = True
        user.save()
        self.client.login(username='******', password='******')

        # Test invoice, packing slip and shipping label generation
        order_id = Order.objects.all()[0].id
        response = self.client.get('/admin/print/invoice/%d/' % order_id)
        self.assertEqual(response.status_code, 200)
        response = self.client.get('/admin/print/packingslip/%d/' % order_id)
        self.assertEqual(response.status_code, 200)
        response = self.client.get('/admin/print/shippinglabel/%d/' % order_id)
        self.assertEqual(response.status_code, 200)

    def test_two_checkouts_dont_duplicate_contact(self):
        """
        Two checkouts with the same email address do not duplicate contacts
        Ticket #1264 [Invalid]
        """

        tax = config_get('TAX', 'MODULE')
        tax.update('tax.modules.percent')
        pcnt = config_get('TAX', 'PERCENT')
        pcnt.update('10')
        shp = config_get('TAX', 'TAX_SHIPPING_PERCENT')
        shp.update(False)

        # First checkout
        self.test_cart_adding()
        response = self.client.post(url('satchmo_checkout-step1'),
                                    get_step1_post_data(self.US))
        self.assertRedirects(response,
                             url('DUMMY_satchmo_checkout-step2'),
                             status_code=302,
                             target_status_code=200)
        data = {
            'credit_type': 'Visa',
            'credit_number': '4485079141095836',
            'month_expires': '1',
            'year_expires': '2015',
            'ccv': '552',
            'shipping': 'FlatRate'
        }
        response = self.client.post(url('DUMMY_satchmo_checkout-step2'), data)
        self.assertRedirects(response,
                             url('DUMMY_satchmo_checkout-step3'),
                             status_code=302,
                             target_status_code=200)
        response = self.client.get(url('DUMMY_satchmo_checkout-step3'))
        amount = smart_str('Shipping + ' + moneyfmt(Decimal('4.00')))
        self.assertContains(response, amount, count=1, status_code=200)

        amount = smart_str('Tax + ' + moneyfmt(Decimal('4.60')))
        self.assertContains(response, amount, count=1, status_code=200)

        amount = smart_str('Total = ' + moneyfmt(Decimal('54.60')))
        self.assertContains(response, amount, count=1, status_code=200)

        response = self.client.post(url('DUMMY_satchmo_checkout-step3'),
                                    {'process': 'True'})
        self.assertRedirects(response,
                             url('DUMMY_satchmo_checkout-success'),
                             status_code=302,
                             target_status_code=200)

        # Second checkout
        self.test_cart_adding()
        response = self.client.post(url('satchmo_checkout-step1'),
                                    get_step1_post_data(self.US))
        self.assertRedirects(response,
                             url('DUMMY_satchmo_checkout-step2'),
                             status_code=302,
                             target_status_code=200)
        data = {
            'credit_type': 'Visa',
            'credit_number': '4485079141095836',
            'month_expires': '1',
            'year_expires': '2015',
            'ccv': '552',
            'shipping': 'FlatRate'
        }
        response = self.client.post(url('DUMMY_satchmo_checkout-step2'), data)
        self.assertRedirects(response,
                             url('DUMMY_satchmo_checkout-step3'),
                             status_code=302,
                             target_status_code=200)
        response = self.client.get(url('DUMMY_satchmo_checkout-step3'))
        amount = smart_str('Shipping + ' + moneyfmt(Decimal('4.00')))
        self.assertContains(response, amount, count=1, status_code=200)

        amount = smart_str('Tax + ' + moneyfmt(Decimal('4.60')))
        self.assertContains(response, amount, count=1, status_code=200)

        amount = smart_str('Total = ' + moneyfmt(Decimal('54.60')))
        self.assertContains(response, amount, count=1, status_code=200)

        response = self.client.post(url('DUMMY_satchmo_checkout-step3'),
                                    {'process': 'True'})
        self.assertRedirects(response,
                             url('DUMMY_satchmo_checkout-success'),
                             status_code=302,
                             target_status_code=200)

        self.assertEqual(len(mail.outbox), 2)

        qs = Contact.objects.filter(email="*****@*****.**")
        # We expects that the contact do not duplicate
        self.assertEqual(len(qs), 1)

    def test_contact_login(self):
        """Check that when a user logs in, the user's existing Contact will be
        used.
        """
        user = User.objects.create_user('teddy', '*****@*****.**',
                                        'guz90tyc')
        contact = Contact.objects.create(user=user,
                                         first_name="Teddy",
                                         last_name="Tester")
        self.client.login(username='******', password='******')
        self.test_cart_adding()
        response = self.client.get(url('satchmo_checkout-step1'))
        self.assertContains(response, "Teddy", status_code=200)

    def test_registration_keeps_contact(self):
        """Check that if a user creates a Contact and later registers,
        the existing Contact will be attached to the User.
        """
        self.test_cart_adding()
        response = self.client.post(prefix + '/checkout/',
                                    get_step1_post_data(self.US))
        self.assert_(self.client.session.get(CUSTOMER_ID) is not None)
        response = self.client.get('/accounts/register/')
        self.assertContains(response, "Teddy", status_code=200)
        origcontact = Contact.objects.get(email="*****@*****.**")
        self.assert_(origcontact)
        data = {
            'email': '*****@*****.**',
            'first_name': 'Teddy',
            'last_name': 'Tester',
            'password1': 'guz90tyc',
            'password2': 'guz90tyc',
            'newsletter': '0'
        }
        response = self.client.post('/accounts/register/', data)
        self.assertRedirects(response,
                             '/accounts/register/complete/',
                             status_code=302,
                             target_status_code=200)
        user = User.objects.get(email="*****@*****.**")
        contact = user.contact_set.get()
        #TODO: Broken test case
        #self.assertEqual(contact, origcontact)

    def test_contact_email_security(self):
        """
        Validate that we can't create a new contact with an existing contact's email address.
        Ticket #233
        """
        self.test_new_account()
        response = self.client.get('/accounts/register/')
        init_data = {
            'email': '*****@*****.**',
            'first_name': 'New',
            'last_name': 'Tester',
            'password1': 'new123pass',
            'password2': 'new123pass',
            'newsletter': '0'
        }
        response = self.client.post('/accounts/register/', init_data)
        self.assertRedirects(response,
                             '/accounts/register/complete/',
                             status_code=302,
                             target_status_code=200)
        response = self.client.get('/accounts/update')
        full_data = {
            'first_name': 'New',
            'last_name': 'Tester',
            'email': '*****@*****.**',
            'phone': '901-881-1230',
            'street1': '8 First Street',
            'city': 'Littleton',
            'state': 'MA',
            'postal_code': '01229',
            'country': self.US.pk,
            'ship_street1': '11 Easy Street',
            'ship_city': 'Littleton',
            'ship_state': 'MA',
            'ship_postal_code': '01229',
        }
        response = self.client.post('/accounts/update/', full_data)
        self.assertContains(response,
                            "That email address is already in use",
                            status_code=200)
        full_data['email'] = '*****@*****.**'
        response = self.client.post('/accounts/update/', full_data)
        response = self.client.get('/accounts/')
        self.assertContains(response, "Email: [email protected]")

    def test_contact_attaches_to_user(self):
        """Check that if a User registers and later creates a Contact, the
        Contact will be attached to the existing User.
        """
        user = User.objects.create_user('teddy', '*****@*****.**',
                                        'guz90tyc')
        self.assertEqual(user.contact_set.count(), 0)
        self.client.login(username='******', password='******')
        self.test_cart_adding()
        response = self.client.post(prefix + '/checkout/',
                                    get_step1_post_data(self.US))
        self.assertEqual(user.contact_set.count(), 1)

    def test_logout(self):
        """The logout view should remove the user and contact id from the
        session.
        """
        user = User.objects.create_user('teddy', '*****@*****.**',
                                        'guz90tyc')
        self.client.login(username='******', password='******')
        response = self.client.get('/accounts/')  # test logged in status
        self.assertContains(
            response,
            "the user you've logged in as doesn't have any contact information.",
            status_code=200)
        self.test_cart_adding()
        self.client.post(prefix + '/checkout/', get_step1_post_data(self.US))
        self.assert_(self.client.session.get(CUSTOMER_ID) is not None)
        response = self.client.get('/accounts/logout/?next=%s' %
                                   (prefix + '/checkout/'))
        self.assertRedirects(response,
                             prefix + '/checkout/',
                             status_code=302,
                             target_status_code=200)
        self.assert_(self.client.session.get(CUSTOMER_ID) is None)
        response = self.client.get('/accounts/')  # test logged in status
        self.assertRedirects(response,
                             '/accounts/login/?next=/accounts/',
                             status_code=302,
                             target_status_code=200)

    def test_search(self):
        """
        Do some basic searches to make sure it all works as expected
        """
        response = self.client.get(prefix + '/search/', {'keywords': 'python'})
        self.assertContains(response, "Python Rocks shirt", count=1)
        response = self.client.get(prefix + '/search/',
                                   {'keywords': 'django+book'})
        self.assertContains(response, "Nothing found")
        response = self.client.get(prefix + '/search/', {'keywords': 'shirt'})
        self.assertContains(response, "Shirts", count=2)
        self.assertContains(response, "Short Sleeve", count=2)
        self.assertContains(response, "Django Rocks shirt", count=10)
        self.assertContains(response, "Python Rocks shirt", count=1)
Ejemplo n.º 59
0
class AnnalistUserEditViewTest(AnnalistTestCase):
    """
    Tests Annalist user edit view
    """
    def setUp(self):
        init_annalist_test_site()
        self.testsite = Site(TestBaseUri, TestBaseDir)
        self.testcoll = Collection.create(self.testsite, "testcoll",
                                          collection_create_values("testcoll"))
        # For checking Location: header values...
        self.continuation_url = TestHostUri + entitydata_list_type_url(
            coll_id="testcoll", type_id=layout.USER_TYPEID)
        # Login and permissions
        create_test_user(self.testcoll,
                         "testuser",
                         "testpassword",
                         user_permissions=[
                             "VIEW", "CREATE", "UPDATE", "DELETE", "CONFIG",
                             "ADMIN"
                         ])
        self.client = Client(HTTP_HOST=TestHost)
        loggedin = self.client.login(username="******",
                                     password="******")
        self.assertTrue(loggedin)
        return

    def tearDown(self):
        resetSitedata(scope="collections")
        return

    #   -----------------------------------------------------------------------------
    #   Helpers
    #   -----------------------------------------------------------------------------

    def _check_annalist_user_values(self, user_id, user_permissions):
        "Helper function checks content of annalist user entry with supplied user_id"
        self.assertTrue(AnnalistUser.exists(self.testcoll, user_id))
        t = AnnalistUser.load(self.testcoll, user_id)
        self.assertEqual(t.get_id(), user_id)
        self.assertEqual(t.get_view_url_path(),
                         annalistuser_url("testcoll", user_id))
        v = annalistuser_values(coll_id="testcoll",
                                user_id=user_id,
                                user_name="User %s" % user_id,
                                user_uri="mailto:%[email protected]" % user_id,
                                user_permissions=user_permissions)
        self.assertDictionaryMatch(t.get_values(), v)
        return t

    #   -----------------------------------------------------------------------------
    #   Form rendering tests
    #   -----------------------------------------------------------------------------

    def test_object_render(self):
        # Test new Django 1.7 object-as-template include capability,
        # per https://docs.djangoproject.com/en/dev/ref/templates/builtins/#include
        class RenderObject(object):
            def __init__(self):
                return

            def render(self, context):
                return context['render_value']

            def __str__(self):
                return "RenderObject"

        template = Template("{{render_object}}: {% include render_object %}")
        context = Context({
            'render_object': RenderObject(),
            'render_value': "Hello world!"
        })
        result = template.render(context)
        # log.info(result)
        self.assertEqual(result, "RenderObject: Hello world!")
        return

    def test_tokenlist_reendering(self):
        field_placement = ({
            'field': "small-12 columns",
            'label': "small-12 medium-2 columns",
            'value': "small-12 medium-10 columns"
        })
        field = context_field({
            'field_placement':
            field_placement,
            'field_label':
            "Permissions",
            'field_placeholder':
            "(user permissions)",
            'field_name':
            "User_permissions",
            'field_value':
            ["VIEW", "CREATE", "UPDATE", "DELETE", "CONFIG", "ADMIN"]
        })
        context = Context({'field': field})
        rendered = get_field_tokenset_renderer().label_edit().render(context)
        rendered = re.sub(r'\s+', " ", rendered)
        self.assertIn('''<div class="small-12 columns">''', rendered)
        self.assertIn('''<div class="row view-value-row">''', rendered)
        self.assertIn(
            '''<div class="view-label small-12 medium-2 columns"> ''' +
            '''<span>Permissions</span> ''' + '''</div>''', rendered)
        self.assertIn(
            '''<div class="view-value small-12 medium-10 columns">''',
            rendered)
        self.assertIn(
            '''<input type="text" size="64" name="User_permissions" ''',
            rendered)
        self.assertIn('''placeholder="(user permissions)"''', rendered)
        self.assertIn('''value="VIEW CREATE UPDATE DELETE CONFIG ADMIN"/>''',
                      rendered)
        return

    def test_included_tokenlist_rendering(self):
        field_placement = ({
            'field': "small-12 columns",
            'label': "small-12 medium-2 columns",
            'value': "small-12 medium-10 columns"
        })
        field = context_field({
            'field_placement':
            field_placement,
            'field_label':
            "Permissions",
            'field_placeholder':
            "(user permissions)",
            'field_name':
            "User_permissions",
            'field_value':
            ["VIEW", "CREATE", "UPDATE", "DELETE", "CONFIG", "ADMIN"],
            'field_render_object':
            get_field_tokenset_renderer().label_edit()
        })
        template = Template(
            "{% include field.description.field_render_object %}")
        context = Context({
            'render_object':
            get_field_tokenset_renderer().label_edit(),
            'field':
            field
        })
        rendered = template.render(context)
        rendered = re.sub(r'\s+', " ", rendered)
        self.assertIn('''<div class="small-12 columns">''', rendered)
        self.assertIn('''<div class="row view-value-row">''', rendered)
        self.assertIn(
            '''<div class="view-label small-12 medium-2 columns"> ''' +
            '''<span>Permissions</span> ''' + '''</div>''', rendered)
        self.assertIn(
            '''<div class="view-value small-12 medium-10 columns">''',
            rendered)
        self.assertIn(
            '''<input type="text" size="64" name="User_permissions" ''',
            rendered)
        self.assertIn('''placeholder="(user permissions)"''', rendered)
        self.assertIn('''value="VIEW CREATE UPDATE DELETE CONFIG ADMIN"/>''',
                      rendered)
        return

    def test_get_new_user_form_rendering(self):
        u = entitydata_edit_url("new",
                                "testcoll",
                                layout.USER_TYPEID,
                                view_id="User_view")
        r = self.client.get(u)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.reason_phrase, "OK")
        field_vals = default_fields(
            coll_id="testcoll",
            type_id=layout.USER_TYPEID,
            entity_id="00000001",
            tooltip1=context_view_field(r.context, 0, 0)['field_tooltip'],
            tooltip2=context_view_field(r.context, 1, 0)['field_tooltip'],
            tooltip3=context_view_field(r.context, 2, 0)['field_tooltip'],
            tooltip4=context_view_field(r.context, 3, 0)['field_tooltip'],
            tooltip5=context_view_field(r.context, 4, 0)['field_tooltip'])
        formrow1 = """
            <div class="small-12 medium-6 columns" title="%(tooltip1)s">
                <div class="row view-value-row">
                    <div class="%(label_classes)s">
                        <span>User Id</span>
                    </div>
                    <div class="%(input_classes)s">
                        <input type="text" size="64" name="entity_id" 
                                   placeholder="(user id)" 
                                   value="00000001" />
                    </div>
                </div>
            </div>
            """ % field_vals(width=6)
        formrow2 = """
            <div class="small-12 columns" title="%(tooltip2)s">
                <div class="row view-value-row">
                    <div class="%(label_classes)s">
                        <span>User name</span>
                    </div>
                    <div class="%(input_classes)s">
                        <input type="text" size="64" name="User_name" 
                               placeholder="(user name)"
                               value="" />
                    </div>
                </div>
            </div>
            """ % field_vals(width=12)
        formrow3 = """
            <div class="small-12 columns" title="%(tooltip3)s">
                <div class="row view-value-row">
                    <div class="%(label_classes)s">
                        <span>Description</span>
                    </div>
                    <div class="%(input_classes)s">
                        <textarea cols="64" rows="6" name="User_description" 
                                  class="small-rows-4 medium-rows-8"
                                  placeholder="(user description)"
                                  >
                        </textarea>
                    </div>
                </div>
            </div>
            """ % field_vals(width=12)
        formrow4 = """
            <div class="small-12 columns" title="%(tooltip4)s">
                <div class="row view-value-row">
                    <div class="%(label_classes)s">
                        <span>User URI</span>
                    </div>
                    <div class="%(input_classes)s">
                        <input type="text" size="64" name="User_uri" 
                               placeholder="(User URI - e.g. mailto:[email protected])"
                               value=""/>
                    </div>
                </div>
            </div>
            """ % field_vals(width=12)
        formrow5 = """
            <div class="small-12 columns" title="%(tooltip5)s">
                <div class="row view-value-row">
                    <div class="%(label_classes)s">
                        <span>Permissions</span>
                    </div>
                    <div class="%(input_classes)s">
                        <input type="text" size="64" name="User_permissions" 
                               placeholder="(user permissions; e.g. &#39;VIEW CREATE UPDATE DELETE CONFIG&#39;)"
                               value=""/>
                    </div>
                </div>
            </div>
            """ % field_vals(width=12)
        # log.info(r.content)
        self.assertContains(r, formrow1, html=True)
        self.assertContains(r, formrow2, html=True)
        self.assertContains(r, formrow3, html=True)
        self.assertContains(r, formrow4, html=True)
        self.assertContains(r, formrow5, html=True)
        return

    def test_user_permissions_form_rendering(self):
        # Test rendering of permissions from list in entity
        u = entitydata_edit_url("edit",
                                "testcoll",
                                layout.USER_TYPEID,
                                "testuser",
                                view_id="User_view")
        r = self.client.get(u)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.reason_phrase, "OK")
        field_vals = default_fields(coll_id="testcoll",
                                    type_id=layout.USER_TYPEID,
                                    entity_id="testuser",
                                    tooltip=context_view_field(
                                        r.context, 4, 0)['field_tooltip'])
        formrow5 = """
            <div class="small-12 columns" title="%(tooltip)s">
                <div class="row view-value-row">
                    <div class="%(label_classes)s">
                        <span>Permissions</span>
                    </div>
                    <div class="%(input_classes)s">
                        <input type="text" size="64" name="User_permissions" 
                               placeholder="(user permissions; e.g. &#39;VIEW CREATE UPDATE DELETE CONFIG&#39;)"
                               value="VIEW CREATE UPDATE DELETE CONFIG ADMIN"/>
                    </div>
                </div>
            </div>
            """ % field_vals(width=12)
        # log.info(r.content)
        # log.info
        # for i in range(len(r.context['fields'])):
        #     log.info("Field %d: %r"%(i, r.context['fields'][i]))
        self.assertContains(r, formrow5, html=True)
        return

    def test_bad_user_permissions_form_rendering(self):
        # Test handling of permissions not stored in entity as a list of values
        create_user_permissions(self.testcoll,
                                "baduserperms",
                                user_permissions="VIEW CREATE UPDATE DELETE")
        u = entitydata_edit_url("edit",
                                "testcoll",
                                layout.USER_TYPEID,
                                "baduserperms",
                                view_id="User_view")
        with SuppressLogging(logging.WARNING):
            r = self.client.get(u)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.reason_phrase, "OK")
        field_vals = default_fields(coll_id="testcoll",
                                    type_id=layout.USER_TYPEID,
                                    entity_id="baduserperms",
                                    tooltip=context_view_field(
                                        r.context, 4, 0)['field_tooltip'])
        formrow5 = """
            <div class="small-12 columns" title="%(tooltip)s">
                <div class="row view-value-row">
                    <div class="%(label_classes)s">
                        <span>Permissions</span>
                    </div>
                    <div class="%(input_classes)s">
                        <input type="text" size="64" name="User_permissions" 
                               placeholder="(user permissions; e.g. &#39;VIEW CREATE UPDATE DELETE CONFIG&#39;)"
                               value="VIEW CREATE UPDATE DELETE"/>
                    </div>
                </div>
            </div>
            """ % field_vals(width=12)
        # log.info(r.content)
        self.assertContains(r, formrow5, html=True)
        return

    #   -----------------------------------------------------------------------------
    #   Form response tests
    #   -----------------------------------------------------------------------------

    #   -------- edit user --------

    def test_post_edit_user(self):
        # The main purpose of this test is to check that user permissions are saved properly
        self.assertFalse(AnnalistUser.exists(self.testcoll, "edituser"))
        f = user_view_form_data(action="edit",
                                orig_id="_default_user_perms",
                                orig_coll="_annalist_site",
                                user_id="edituser",
                                user_name="User edituser",
                                user_uri="mailto:[email protected]",
                                user_permissions="VIEW CREATE UPDATE DELETE")
        u = entitydata_edit_url("edit",
                                "testcoll",
                                layout.USER_TYPEID,
                                entity_id="_default_user_perms",
                                view_id="User_view")
        r = self.client.post(u, f)
        self.assertEqual(r.status_code, 302)
        self.assertEqual(r.reason_phrase, "FOUND")
        self.assertEqual(r.content, "")
        self.assertEqual(r['location'], self.continuation_url)
        # Check that new user exists
        self.assertTrue(AnnalistUser.exists(self.testcoll, "edituser"))
        self._check_annalist_user_values(
            "edituser", ["VIEW", "CREATE", "UPDATE", "DELETE"])
        return

    #   -------- copy user --------

    def test_post_copy_user(self):
        # The main purpose of this test is to check that user permissions are saved properly
        self.assertFalse(AnnalistUser.exists(self.testcoll, "copyuser"))
        f = user_view_form_data(action="copy",
                                orig_id="_default_user_perms",
                                orig_coll="_annalist_site",
                                user_id="copyuser",
                                user_name="User copyuser",
                                user_uri="mailto:[email protected]",
                                user_permissions="VIEW CREATE UPDATE DELETE")
        u = entitydata_edit_url("copy",
                                "testcoll",
                                layout.USER_TYPEID,
                                entity_id="_default_user_perms",
                                view_id="User_view")
        r = self.client.post(u, f)
        self.assertEqual(r.status_code, 302)
        self.assertEqual(r.reason_phrase, "FOUND")
        self.assertEqual(r.content, "")
        self.assertEqual(r['location'], self.continuation_url)
        # Check that new user exists
        self.assertTrue(AnnalistUser.exists(self.testcoll, "copyuser"))
        self._check_annalist_user_values(
            "copyuser", ["VIEW", "CREATE", "UPDATE", "DELETE"])
        return
Ejemplo n.º 60
0
class ContentStoreToyCourseTest(ModuleStoreTestCase):
    """
    Tests that use the toy course.
    """

    def setUp(self):
        """
        Create user and login.
        """

        settings.MODULESTORE['default']['OPTIONS']['fs_root'] = path('common/test/data')
        settings.MODULESTORE['direct']['OPTIONS']['fs_root'] = path('common/test/data')

        self.client = Client()
        self.contentstore = contentstore()

        # A locked asset
        self.loc_locked = Location('c4x', 'edX', 'toy', 'asset', 'sample_static.txt')
        self.url_locked = StaticContent.get_url_path_from_location(self.loc_locked)

        # An unlocked asset
        self.loc_unlocked = Location('c4x', 'edX', 'toy', 'asset', 'another_static.txt')
        self.url_unlocked = StaticContent.get_url_path_from_location(self.loc_unlocked)

        import_from_xml(modulestore('direct'), 'common/test/data/', ['toy'],
                static_content_store=self.contentstore, verbose=True)

        self.contentstore.set_attr(self.loc_locked, 'locked', True)

        # Create user
        self.usr = '******'
        self.pwd = 'foo'
        email = '*****@*****.**'
        self.user = User.objects.create_user(self.usr, email, self.pwd)
        self.user.is_active = True
        self.user.save()

        # Create staff user
        self.staff_usr = '******'
        self.staff_pwd = 'foo'
        staff_email = '*****@*****.**'
        self.staff_user = User.objects.create_user(self.staff_usr, staff_email,
                self.staff_pwd)
        self.staff_user.is_active = True
        self.staff_user.is_staff = True
        self.staff_user.save()

    def tearDown(self):

        MongoClient().drop_database(TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'])
        _CONTENTSTORE.clear()

    def test_unlocked_asset(self):
        """
        Test that unlocked assets are being served.
        """
        self.client.logout()
        resp = self.client.get(self.url_unlocked)
        self.assertEqual(resp.status_code, 200) # pylint: disable=E1103

    def test_locked_asset_not_logged_in(self):
        """
        Test that locked assets behave appropriately in case the user is not
        logged in.
        """
        self.client.logout()
        resp = self.client.get(self.url_locked)
        self.assertEqual(resp.status_code, 403) # pylint: disable=E1103

    def test_locked_asset_not_registered(self):
        """
        Test that locked assets behave appropriately in case user is logged in
        in but not registered for the course.
        """
        self.client.login(username=self.usr, password=self.pwd)
        resp = self.client.get(self.url_locked)
        self.assertEqual(resp.status_code, 403) # pylint: disable=E1103

    def test_locked_asset_registered(self):
        """
        Test that locked assets behave appropriately in case user is logged in
        and registered for the course.
        """
        # pylint: disable=E1101
        course_id = "/".join([self.loc_locked.org, self.loc_locked.course, '2012_Fall'])
        CourseEnrollment.enroll(self.user, course_id)
        self.assertTrue(CourseEnrollment.is_enrolled(self.user, course_id))

        self.client.login(username=self.usr, password=self.pwd)
        resp = self.client.get(self.url_locked)
        self.assertEqual(resp.status_code, 200) # pylint: disable=E1103

    def test_locked_asset_staff(self):
        """
        Test that locked assets behave appropriately in case user is staff.
        """
        # pylint: disable=E1101
        course_id = "/".join([self.loc_locked.org, self.loc_locked.course, '2012_Fall'])

        self.client.login(username=self.staff_usr, password=self.staff_pwd)
        resp = self.client.get(self.url_locked)
        self.assertEqual(resp.status_code, 200) # pylint: disable=E1103