class LevelSelectionTestCase(TestCase):
    def setUp(self):
        self.client = Client()

    def test_list_episodes_with_translated_episode_names(self):
        with add_new_language():
            url = reverse("levels")
            response = self.client.get(url, **{"HTTP_ACCEPT_LANGUAGE": "foo-br"})

            assert_that(response.status_code, equal_to(200))
            self._assert_that_response_contains_episode_name(
                response, "crwdns4197:0crwdne4197:0"
            )
            self._assert_that_response_contains_level_with_title(
                response, "crwdns3456:0crwdne3456:0"
            )

    def test_list_episodes(self):
        url = reverse("levels")
        response = self.client.get(url)

        assert_that(response.status_code, equal_to(200))
        self._assert_that_response_contains_episode_name(response, "Getting Started")
        self._assert_that_response_contains_level_with_title(
            response, "Can you help the van get to the house? "
        )

    def _assert_that_response_contains_episode_name(self, response, expected):
        assert_that(response.context["episodeData"][0]["name"], equal_to(expected))

    def _assert_that_response_contains_level_with_title(self, response, expected):
        assert_that(
            response.context["episodeData"][0]["levels"][0]["title"], equal_to(expected)
        )
Пример #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)
Пример #3
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
class LinksContextProcessorTestCase(TestCase):
    def setUp(self):
        super(LinksContextProcessorTestCase, self).setUp()
        self.client = Client()

    def test_empty_links(self):
        with self.assertNumQueries(1):
            response = self.client.get("/")
            self.assertEqual(response.context["links"].count(), 0)

    def test_links(self):
        with self.assertNumQueries(4):
            link_1 = Link.objects.create(
                title="About", url="/about", weight=2)
            link_2 = Link.objects.create(
                title="Google", url="http://www.google.com", weight=1)
            link_3 = Link.objects.create(
                title="Links", url="/links", weight=3)

            response = self.client.get("/")
            self.assertEqual(response.context["links"].count(), 3)

            links = response.context["links"]
            self.assertEqual(link_2, links[0])
            self.assertEqual(link_1, links[1])
            self.assertEqual(link_3, links[2])
Пример #5
0
 def test_optional_email_verification(self):
     c = Client()
     # Signup
     c.get(reverse('account_signup'))
     resp = c.post(reverse('account_signup'),
                   {'username': '******',
                    'email': '*****@*****.**',
                    'password1': 'johndoe',
                    'password2': 'johndoe'})
     # Logged in
     self.assertEqual(resp['location'],
                      'http://testserver'+settings.LOGIN_REDIRECT_URL)
     self.assertEqual(resp.status_code, 302)
     self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
     self.assertEqual(len(mail.outbox), 1)
     # Logout & login again
     c.logout()
     # Wait for cooldown
     EmailConfirmation.objects.update(sent=now() - timedelta(days=1))
     # Signup
     resp = c.post(reverse('account_login'),
                   {'login': '******',
                    'password': '******'})
     self.assertEqual(resp.status_code, 302)
     self.assertEqual(resp['location'],
                      'http://testserver'+settings.LOGIN_REDIRECT_URL)
     self.assertEqual(mail.outbox[0].to, ['*****@*****.**'])
     # There was an issue that we sent out email confirmation mails
     # on each login in case of optional verification. Make sure
     # this is not the case:
     self.assertEqual(len(mail.outbox), 1)
Пример #6
0
def test_xblock_with_handlers():
    # Tests of handler urls.
    client = Client()

    # The view sends a list of URLs to try.
    response = client.get("/view/with-handlers/")
    parsed = response.content.split(":::")
    assert_equals(len(parsed), 3)
    urls = json.loads(parsed[1])

    # These have to correspond to the urls in XBlockWithHandlers.student_view above.
    expecteds = [
        {"suffix": "", "a": "no-a", "b": "no-b"},
        {"suffix": "with_some_suffix", "a": "no-a", "b": "no-b"},
        {"suffix": "", "a": "123", "b": "no-b"},
        {"suffix": "", "a": "123", "b": "456"},
        {"suffix": "another_suffix", "a": "123", "b": "456"},
        {"suffix": "", "a": "no-a", "b": "no-b"},
        {"suffix": "with_some_suffix", "a": "no-a", "b": "no-b"},
        {"suffix": "", "a": "123", "b": "no-b"},
        {"suffix": "", "a": "123", "b": "456"},
        {"suffix": "another_suffix", "a": "123", "b": "456"},
    ]

    for url, expected in zip(urls, expecteds):
        print url  # so we can see which one failed, if any.
        response = client.get(url)
        assert_equals(response.status_code, 200)
        actual = json.loads(response.content)
        assert_equals(actual, expected)
Пример #7
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)
Пример #8
0
    def test_badge_p(self):
        c = Client()

        response = c.get('/p/')
        self.assertEqual(response.status_code, 404)

        response = c.get('/p/nsstringmask/badge.png')
        self.assertEqual(response.status_code, 200)
        self.assertTrue('error' in response.content)

        response = c.get('/p/NSStringMask/badge.png')
        self.assertEqual(response.status_code, 200)
        self.assertFalse('error' in response.content)

        response = c.get('/p/aowdijaowijaowidjaowidjaowij/badge.png')
        self.assertEqual(response.status_code, 200)
        self.assertTrue('error' in response.content)

        response = c.get('/p/nsstr/ingmask/badge.png')
        self.assertEqual(response.status_code, 200)
        self.assertTrue('error' in response.content)

    # def setup_databases(self):
    #     """Overrides DjangoTestSuiteRunner"""
    #     pass
    #
    # def teardown_databases(self, *args):
    #     """Overrides DjangoTestSuiteRunner"""
    #     pass
Пример #9
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)
Пример #10
0
Файл: tests.py Проект: 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)
Пример #11
0
Файл: tests.py Проект: 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)
Пример #12
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)
Пример #13
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)
Пример #14
0
class TestLoginWithHadoop(PseudoHdfsTestBase):

  def setUp(self):
    # Simulate first login ever
    User.objects.all().delete()
    self.c = Client()

  def test_login(self):
    response = self.c.get('/accounts/login/')
    assert_equal(200, response.status_code, "Expected ok status.")
    assert_true(response.context['first_login_ever'])

    response = self.c.post('/accounts/login/', dict(username="******", password="******"))
    assert_equal(302, response.status_code, "Expected ok redirect status.")
    assert_true(self.fs.exists("/user/foo"))

    response = self.c.get('/accounts/login/')
    assert_equal(200, response.status_code, "Expected ok status.")
    assert_false(response.context['first_login_ever'])

  def test_login_home_creation_failure(self):
    response = self.c.get('/accounts/login/')
    assert_equal(200, response.status_code, "Expected ok status.")
    assert_true(response.context['first_login_ever'])

    # Create home directory as a file in order to fail in the home creation later
    cluster = pseudo_hdfs4.shared_cluster()
    fs = cluster.fs
    assert_false(cluster.fs.exists("/user/foo2"))
    fs.do_as_superuser(fs.create, "/user/foo2")

    response = self.c.post('/accounts/login/', dict(username="******", password="******"), follow=True)
    assert_equal(200, response.status_code, "Expected ok status.")
    assert_true('/beeswax' in response.content, response.content)
Пример #15
0
class ProxyTests(TestCase):
    def setUp(self):
        self.c = Client()

    @override_settings(GRAPHITE_BASE="http://mock.example.com")
    def test_render_proxy(self):
        httpretty.enable()
        httpretty.register_uri(
            httpretty.GET,
            "http://mock.example.com/render/?foo=bar",
            body="success",
        )
        response = self.c.get("/render/?foo=bar")
        self.assertEqual(response.content, "success")
        httpretty.disable()
        httpretty.reset()

    @override_settings(GRAPHITE_BASE="http://mock.example.com")
    def test_metric_proxy(self):
        httpretty.enable()
        httpretty.register_uri(
            httpretty.GET,
            "http://mock.example.com/metrics/?foo=bar",
            body="success",
        )
        response = self.c.get("/metrics/?foo=bar")
        self.assertEqual(response.content, "success")
        httpretty.disable()
        httpretty.reset()
Пример #16
0
class TestAPI(TestCase):
    def setUp(self):
        self.client = Client()

        data = []
        for i in range(500):
            m = Visitor(full_name='Romulo', id=i)
            data.append(m)
        Visitor.objects.bulk_create(data)

        # build index with our test data
        haystack.connections.reload('default')
        call_command('rebuild_index', interactive=False, verbosity=0)
        super(TestAPI, self).setUp()
        self.maxDiff = None

    def test_search_return_json(self):
        c = self.client.get('/api/search.json/romulo/')
        self.assertEqual(200, c.status_code)

    def test_search_return_json_with_pagination(self):
        c = self.client.get('/api/search.json/romulo/?page=2')
        self.assertEqual(200, c.status_code)

    def test_search_return_json_with_invalid_pagination(self):
        c = self.client.get('/api/search.json/romulo/?page=100')
        self.assertTrue('Invalid page' in str(c.content))
Пример #17
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')
Пример #18
0
 def test_render(self):
     '''Check whether the template renders'''
     client = Client()
     response = client.get(reverse('cui_test'))
     self.assertEqual(response.status_code, 200)
     response = client.get(reverse('cui_local'))
     self.assertEqual(response.status_code, 200)
Пример #19
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)
Пример #20
0
 def test_new_map_with_empty_bbox_layer(self):
     # TODO: Should this test have assertions in it?
     with patch('geonode.maps.models.Layer.objects.gs_catalog') as mock_gs:
         mock_gs.get_resource.return_value.latlon_bbox = ["0", "0", "0", "0"]
         client = Client()
         layer = Layer.objects.all()[0]
         client.get("/maps/new?layer=" + layer.typename)
Пример #21
0
class MessengerViewsTest(TestCase):
    """ Tests for profile edit views """

    def setUp(self):
        self.client = Client()
        self.messenger_path = reverse('profile:messenger')

    def test_messenger_page_with_auth(self):
        """ Test messenger view with auth """

        self.client.login(username='******', password='******')
        response = self.client.get(self.messenger_path, follow=True)

        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'messenger.html')
        self.assertTrue('<!DOCTYPE html>' in response.content)
        self.assertTrue(response.context['user'].is_authenticated())

    def test_messenger_page_without_auth(self):
        """ Test messenger view without auth """

        response = self.client.get(self.messenger_path, follow=True)

        self.assertEqual(response.status_code, 200)
        self.assertRedirects(
            response,
            "{0}?next={1}".format(settings.LOGIN_URL, self.messenger_path)
        )
Пример #22
0
class ViewsStaffMemberRequiredTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.app = ApplicationFactory.create()
        self.request = Request.objects.create(version='1.0.0.0')
        self.app_request = AppRequest.objects.create(
            request=self.request,
            appid=self.app.id,
        )

    def test_omaha_statistics(self):
        url = reverse('omaha_statistics')
        response = self.client.get(url)
        self.assertRedirects(response, '/admin/login/?next=%s' % url)

    def test_omaha_statistics_detail(self):
        url = reverse('omaha_statistics_detail', kwargs=dict(name=self.app.name))
        response = self.client.get(url)
        self.assertRedirects(response, '/admin/login/?next=%s' % url)

    def test_omaha_request_list(self):
        url = reverse('omaha_request_list', kwargs=dict(name=self.app.name))
        response = self.client.get(url)
        self.assertRedirects(response, '/admin/login/?next=%s' % url)

    def test_omaha_request_detail(self):
        url = reverse('omaha_request_detail', kwargs=dict(pk=self.app_request.pk))
        response = self.client.get(url)
        self.assertRedirects(response, '/admin/login/?next=%s' % url)

    def test_omaha_set_timezone(self):
        url = reverse('set_timezone')
        response = self.client.get(url)
        self.assertRedirects(response, '/admin/login/?next=%s' % url)
Пример #23
0
class TestUrlPatterns(unittest.TestCase):
    def setUp(self):
        self.client = Client()

    def test_redirect(self):
        response = self.client.get('/en-US/gloubi-boulga/')
        eq_(response.status_code, 301)
        eq_(response['Location'], 'http://testserver/en-US/mock/view/')

    def test_temporary_redirect(self):
        response = self.client.get('/en-US/gloubi-boulga/tmp/')
        eq_(response.status_code, 302)
        eq_(response['Location'], 'http://testserver/en-US/mock/view/')

    def test_external_redirect(self):
        response = self.client.get('/en-US/gloubi-boulga/ext/')
        eq_(response.status_code, 301)
        eq_(response['Location'], 'https://marketplace.mozilla.org')

    def test_callable_redirect(self):
        response = self.client.get('/en-US/gloubi-boulga/call/')
        eq_(response.status_code, 301)
        eq_(response['Location'], 'http://testserver/qwer')

        response = self.client.get('/en-US/gloubi-boulga/call/?test=1')
        eq_(response.status_code, 301)
        eq_(response['Location'], 'http://testserver/asdf')
Пример #24
0
    def test_bundles(self):
        c = Client()

        # Test top level bundle schema
        response = c.get('/test_api/v1/')
        self.assertEqual(response.status_code, 200)
        output = json.loads(response.content)
        self.assertEqual(len(output), 4)

        # Test second level bundle schema
        response = c.get('/test_api/v1/media/')
        self.assertEqual(response.status_code, 200)
        output = json.loads(response.content)
        self.assertEqual(len(output), 2)

        # Test top-level bundle view callback
        response = c.get('/test_api/v1/media/books/', data={'always_win': True})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, "WIN")

        # Test second level bundle view callback
        response = c.get('/test_api/v1/media/books/', data={'always_fail': True})
        self.assertEqual(response.status_code, 500)
        self.assertEqual(response.content, "FAIL")

        # Test bundle view callbacks firing in right order
        response = c.get(
            '/test_api/v1/media/books/',
            data={'always_win': True, 'always_fail': True}
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, "WIN")
Пример #25
0
class Test_SourceDetail(TestCase):
    """Tests the source_detail view"""
    def setUp(self):
        self.client = Client()
        self.editor = User.objects.create(username='******')
        self.source = Source.objects.create(year="1991", author='Smith', 
                                    slug='smith1991', reference='...',
                                    comment='...', editor=self.editor)
        self.url = reverse('source-detail', kwargs={'slug': self.source.slug})
        
    def test_200ok(self):
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
    
    def test_template_used(self):
        response = self.client.get(self.url)
        self.assertTemplateUsed(response, 'core/source_detail.html')
    
    def test_404_on_missing_source(self):
        response = self.client.get('/source/fudge')
        self.assertEqual(response.status_code, 404)
    
    def test_find_valid_source(self):
        response = self.client.get(self.url)
        self.assertContains(response, 'Smith')
        self.assertContains(response, '1991')
class TestWatchViews(TestCase):
    def setUp(self):
        # Every test needs a client.
        self.user = test_data.createDummyUserRandom(login='******', password='******')
        self.client = Client()
        self.client.login(username=self.user.username, password='******')

    def test_watch_unwatch_issue(self):
        issue = test_data.create_dummy_issue()
        self.assertTrue(not watch_services.is_watching_issue(self.user, issue.id))

        response = self.client.get(_reverse('watchIssue', issue_id=issue.id))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, 'WATCHING')
        self.assertTrue(watch_services.is_watching_issue(self.user, issue.id))

        response = self.client.get(_reverse('unwatchIssue', issue_id=issue.id))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, 'NOT_WATCHING')
        self.assertTrue(not watch_services.is_watching_issue(self.user, issue.id))

    def test_watch_unwatch_offer(self):
        offer = test_data.create_dummy_offer_usd()
        self.assertTrue(not watch_services.is_watching_offer(self.user, offer.id))

        response = self.client.get(_reverse('watchOffer', offer_id=offer.id))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, 'WATCHING')
        self.assertTrue(watch_services.is_watching_offer(self.user, offer.id))

        response = self.client.get(_reverse('unwatchOffer', offer_id=offer.id))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, 'NOT_WATCHING')
        self.assertTrue(not watch_services.is_watching_offer(self.user, offer.id))
Пример #27
0
class RequestTest(TestCase):
    def setUp(self):
        self.client = Client()


    def test_subscribe_view_works(self):
        response = self.client.get(reverse('subscribe'))
        self.assertEqual(response.status_code, 200)


    def test_subscription_optin_view_works(self):
        response = self.client.get(reverse('subscription-opt-in'))
        self.assertEqual(response.status_code, 200)


    def test_subscription_optout_view_works(self):
        response = self.client.get(reverse('unsubscription-opt-out'))
        self.assertEqual(response.status_code, 200)


    def test_subscription_activate_view_works(self):
        response = self.client.get(reverse('subscription-activate',
                                        kwargs={'activation_key':000}))
        self.assertEqual(response.status_code, 200)


    def test_subscription_deactivate_view_works(self):
        response = self.client.get(reverse('subscription-deactivate',
                                           kwargs={'deactivation_key':000}))
        self.assertEqual(response.status_code, 200)
Пример #28
0
class FilteringAppRequestsByUserIdTest(TestCase):

    def setUp(self):
        self.client = Client()
        self.app = ApplicationFactory.create(id='{D0AB2EBC-931B-4013-9FEB-C9C4C2225C0}')
        self.userid1 = UUID(int=1)
        self.userid2 = UUID(int=2)
        self.app_req1 = AppRequestFactory(request=RequestFactory(userid=self.userid1))
        self.app_req2 = AppRequestFactory(request=RequestFactory(userid=self.userid1))
        self.app_req3 = AppRequestFactory(request=RequestFactory(userid=self.userid2))
        self.user = User.objects.create_superuser(
            username='******', email='*****@*****.**', password='******')
        self.client.login(username='******', password='******')

    def test_filtering(self):
        url = reverse('omaha_request_list', kwargs=dict(name=self.app.name))
        data = {'request__userid': '',
                'request__created': '',
                'event_type': '',
                'event_result': ''}
        resp = self.client.get(url, data)
        d = pq(resp.content)
        res = d('#apprequest-table tbody tr')
        self.assertEqual(len(res), 3)
        data = {'request__userid': self.userid1,
                'request__created': '',
                'event_type': '',
                'event_result': ''}
        resp = self.client.get(url, data)
        d = pq(resp.content)
        res = d('#apprequest-table tbody tr')
        self.assertEqual(len(res), 2)
Пример #29
0
class FormTest(TestCase):
    """ Tests for forms """
    def setUp(self):
        self.client = Client()

    def test_task_form_opens(self):
        response = self.client.get('/new_task/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'new_task.html', 'base.html')

    def test_story_form_opens(self):
        response = self.client.get('/new_story/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'new_story.html', 'base.html')

    def test_task_form_fails(self):
        story = Story.objects.create(story_name='Story 1', 
                                     time_est=dt.datetime(2015, 6, 1, 12))
        response = self.client.post('/new_task/', {'task_name':'Task',
                                                   'time_est': 'invalid_time',
                                                   'developer': Task.DEVELOPERS[0][0],
                                                   'iteration': 1,
                                                   'story': story}, follow=True)

        self.assertFormError(response, 'form', 'time_est', 'Enter valid deadline (eg.: 2015-05-17 10:35)')

    def test_task_form_passes(self):
        story = Story.objects.create(story_name='Story 1', 
                                     time_est=dt.datetime(2015, 6, 1, 12))
        response = self.client.post('/new_task/', {'task_name':'Task',
                                                   'time_est': dt.datetime(2015, 4, 23, 12, 15),
                                                   'developer': Task.DEVELOPERS[0][0],
                                                   'iteration': 1,
                                                   'story': story}, follow=True)
Пример #30
0
    def test_layer_acls(self):
        """ Verify that the layer_acls view is behaving as expected
        """

        # Test that HTTP_AUTHORIZATION in request.META is working properly
        valid_uname_pw = "%s:%s" % (settings.GEOSERVER_CREDENTIALS[0],settings.GEOSERVER_CREDENTIALS[1])
        invalid_uname_pw = "%s:%s" % ("n0t", "v@l1d")

        valid_auth_headers = {
            'HTTP_AUTHORIZATION': 'basic ' + base64.b64encode(valid_uname_pw),
        }
        
        invalid_auth_headers = {
            'HTTP_AUTHORIZATION': 'basic ' + base64.b64encode(invalid_uname_pw),
        }
       
        # Test that requesting when supplying the GEOSERVER_CREDENTIALS returns the expected json 
        expected_result = {'rw': [],'ro': [],'name': settings.GEOSERVER_CREDENTIALS[0],'is_superuser':  True,'is_anonymous': False}
        c = Client()
        response = c.get('/data/acls', **valid_auth_headers)
        response_json = json.loads(response.content)
        self.assertEquals(expected_result, response_json) 

        # Test that requesting when supplying invalid credentials returns the appropriate error code
        response = c.get('/data/acls', **invalid_auth_headers)
        self.assertEquals(response.status_code, 401)
       
        # Test logging in using Djangos normal auth system 
        c.login(username='******', password='******')
       
        # Basic check that the returned content is at least valid json
        response = c.get("/data/acls")
        response_json = json.loads(response.content)
Пример #31
0
class DashboardTest(ModuleStoreTestCase):
    """
    Tests for dashboard utility functions
    """
    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(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 = SoftwareSecurePhotoVerification.objects.create(
                user=self.user)
            attempt.mark_ready()
            attempt.submit()
            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\'re enrolled as a verified student')
        self._check_verification_status_on(
            'honor', 'You\'re enrolled as an honor code student')
        self._check_verification_status_on('audit',
                                           'You\'re auditing this course')
        self._check_verification_status_on(
            'professional',
            'You\'re enrolled as a professional education student')
        self._check_verification_status_on(
            'no-id-professional',
            'You\'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(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 = SoftwareSecurePhotoVerification.objects.create(
                user=self.user)
            attempt.mark_ready()
            attempt.submit()
            attempt.approve()

        response = self.client.get(reverse('dashboard'))
        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',
                                            'You\'re auditing this course')

    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.assertEquals(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_refundable(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,
                                             mode='verified')

        self.assertTrue(enrollment.refundable())

        verified_mode.expiration_datetime = datetime.now(
            pytz.UTC) - timedelta(days=1)
        verified_mode.save()
        self.assertFalse(enrollment.refundable())

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    @patch('courseware.views.log.warning')
    @patch.dict('django.conf.settings.FEATURES',
                {'ENABLE_PAID_COURSE_REGISTRATION': True})
    def test_blocked_course_scenario(self, log_warning):

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

        #create testing invoice 1
        sale_invoice_1 = shoppingcart.models.Invoice.objects.create(
            total_amount=1234.32,
            company_name='Test1',
            company_contact_name='Testw',
            company_contact_email='*****@*****.**',
            customer_reference_number='2Fwe23S',
            recipient_name='Testw_1',
            recipient_email='*****@*****.**',
            internal_reference="A",
            course_id=self.course.id,
            is_valid=False)
        invoice_item = shoppingcart.models.CourseRegistrationCodeInvoiceItem.objects.create(
            invoice=sale_invoice_1,
            qty=1,
            unit_price=1234.32,
            course_id=self.course.id)
        course_reg_code = shoppingcart.models.CourseRegistrationCode(
            code="abcde",
            course_id=self.course.id,
            created_by=self.user,
            invoice=sale_invoice_1,
            invoice_item=invoice_item,
            mode_slug='honor')
        course_reg_code.save()

        cart = shoppingcart.models.Order.get_cart_for_user(self.user)
        shoppingcart.models.PaidCourseRegistration.add_to_order(
            cart, self.course.id)
        resp = self.client.post(reverse('shoppingcart.views.use_code'),
                                {'code': course_reg_code.code})
        self.assertEqual(resp.status_code, 200)

        redeem_url = reverse('register_code_redemption',
                             args=[course_reg_code.code])
        response = self.client.get(redeem_url)
        self.assertEquals(response.status_code, 200)
        # check button text
        self.assertTrue('Activate Course Enrollment' in response.content)

        #now activate the user by enrolling him/her to the course
        response = self.client.post(redeem_url)
        self.assertEquals(response.status_code, 200)

        response = self.client.get(reverse('dashboard'))
        self.assertIn(
            'You can no longer access this course because payment has not yet been received',
            response.content)
        optout_object = Optout.objects.filter(user=self.user,
                                              course_id=self.course.id)
        self.assertEqual(len(optout_object), 1)

        # Direct link to course redirect to user dashboard
        self.client.get(
            reverse(
                'courseware',
                kwargs={"course_id": self.course.id.to_deprecated_string()}))
        log_warning.assert_called_with(
            u'User %s cannot access the course %s because payment has not yet been received',
            self.user, self.course.id.to_deprecated_string())

        # Now re-validating the invoice
        invoice = shoppingcart.models.Invoice.objects.get(id=sale_invoice_1.id)
        invoice.is_valid = True
        invoice.save()

        response = self.client.get(reverse('dashboard'))
        self.assertNotIn(
            'You can no longer access this course because payment has not yet been received',
            response.content)

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    def test_refundable_of_purchased_course(self):

        self.client.login(username="******", password="******")
        CourseModeFactory.create(course_id=self.course.id,
                                 mode_slug='honor',
                                 min_price=10,
                                 currency='usd',
                                 mode_display_name='honor',
                                 expiration_datetime=datetime.now(pytz.UTC) +
                                 timedelta(days=1))
        enrollment = CourseEnrollment.enroll(self.user,
                                             self.course.id,
                                             mode='honor')

        # TODO: Until we can allow course administrators to define a refund period for paid for courses show_refund_option should be False. # pylint: disable=fixme
        self.assertFalse(enrollment.refundable())

        resp = self.client.post(reverse('student.views.dashboard', args=[]))
        self.assertIn('You will not be refunded the amount you paid.',
                      resp.content)

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    def test_refundable_when_certificate_exists(self):
        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='verified')

        self.assertTrue(enrollment.refundable())

        GeneratedCertificateFactory.create(
            user=self.user,
            course_id=self.course.id,
            status=CertificateStatuses.downloadable,
            mode='verified')

        self.assertFalse(enrollment.refundable())

    @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.assertEquals(response.status_code, 200)
        self.assertNotIn('Add Certificate to LinkedIn', response.content)

        response_url = 'http://www.linkedin.com/profile/add?_ed='
        self.assertNotContains(response, 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="******")
        LinkedInAddToProfileConfiguration(
            company_identifier='0_mC_o2MizqdtZEmkVXjH4eYwMj4DnkCWrZP_D9',
            enabled=True).save()

        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.assertEquals(response.status_code, 200)
        self.assertIn('Add Certificate to LinkedIn', response.content)

        expected_url = (
            'http://www.linkedin.com/profile/add'
            '?_ed=0_mC_o2MizqdtZEmkVXjH4eYwMj4DnkCWrZP_D9&'
            'pfCertificationName=edX+Honor+Code+Certificate+for+Omega&'
            'pfCertificationUrl=www.edx.org&'
            'source=o')
        self.assertContains(response, expected_url)

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

        The first time the student dashboard displays a specific course, it will
        make a call to the module store. After that first request, though, the
        course's metadata should be cached as a CourseOverview.

        Arguments:
            modulestore_type (ModuleStoreEnum.Type): Type of modulestore to create
                test course in.
            expected_mongo_calls (int >=0): Number of MongoDB queries expected for
                a single call to the module store.

        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, log in the user, and enroll them in the course.
        test_course = CourseFactory.create(default_store=modulestore_type)
        self.client.login(username="******", password="******")
        CourseEnrollment.enroll(self.user, test_course.id)

        # The first request will result in a modulestore query.
        with check_mongo_calls(expected_mongo_calls):
            response_1 = self.client.get(reverse('dashboard'))
            self.assertEquals(response_1.status_code, 200)

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

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

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

        # But other links are hidden in the navigation
        self.assertNotContains(response, "How it Works")
        self.assertNotContains(response, "Schools & Partners")
Пример #32
0
class IPv4GetTestCase(NetworkApiTestCase):
    fixtures = [
        'networkapi/config/fixtures/initial_config.json',
        'networkapi/system/fixtures/initial_variables.json',
        'networkapi/usuario/fixtures/initial_usuario.json',
        'networkapi/grupo/fixtures/initial_ugrupo.json',
        'networkapi/usuario/fixtures/initial_usuariogrupo.json',
        'networkapi/api_ogp/fixtures/initial_objecttype.json',
        'networkapi/api_ogp/fixtures/initial_objectgrouppermissiongeneral.json',
        'networkapi/grupo/fixtures/initial_permissions.json',
        'networkapi/grupo/fixtures/initial_permissoes_administrativas.json',
        'networkapi/api_ip/fixtures/initial_base.json',
        'networkapi/api_ip/fixtures/initial_base_v4.json',
    ]

    def setUp(self):
        self.client = Client()
        self.user = Usuario(id=1, nome='test')

    def tearDown(self):
        pass

    def test_try_create_auto_ip(self):
        """Tests if NAPI can allocate automatically an IPv4 Address
        in a Network with available addresses.
        """

        name_file = 'api_ip/tests/sanity/ipv4/json/post/ipv4_auto_net_free.json'

        # Does get request
        response = self.client.post(
            '/api/v3/ipv4/',
            data=json.dumps(self.load_json_file(name_file)),
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(201, response.status_code)

        url = prepare_url('/api/v3/ipv4/%s/' % response.data[0]['id'],
                          fields=['ip_formated'])
        response = self.client.get(
            url,
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(200, response.status_code)
        self.compare_values('10.0.1.2', response.data['ips'][0]['ip_formated'])

    def test_try_create_invalid_ip(self):
        """Tests if NAPI deny manually creation of invalid IPv4 Address
        (e.g.: 10.0.0.430).
        """

        name_file = 'api_ip/tests/sanity/ipv4/json/post/ipv4_10_0_0_430_net_5.json'
        response = self.client.post(
            '/api/v3/ipv4/',
            data=json.dumps(self.load_json_file(name_file)),
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(400, response.status_code)
        self.compare_values(
            'Error save new IP.: 10.0.0.430',
            response.data['detail'])

    def test_try_create_ip_associating_to_equipment(self):
        """Tests if NAPI can allocate an IPv4 Address manually and associate
        it to an equipment in a Network with available addresses.
        """

        name_file = 'api_ip/tests/sanity/ipv4/json/post/ipv4_10_0_0_99_net_5_eqpt_1.json'
        response = self.client.post(
            '/api/v3/ipv4/',
            data=json.dumps(self.load_json_file(name_file)),
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(201, response.status_code)

        url = prepare_url('/api/v3/ipv4/%s/' % response.data[0]['id'],
                          fields=['ip_formated'])
        response = self.client.get(
            url,
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(200, response.status_code)
        self.compare_values('10.0.0.99',
                            response.data['ips'][0]['ip_formated'])

    def test_try_create_ip_in_full_network(self):
        """Tests if NAPI deny an IPv4 manually creation in a full network."""

        name_file = 'api_ip/tests/sanity/ipv4/json/post/ipv4_10_0_4_1_net_8.json'
        response = self.client.post(
            '/api/v3/ipv4/',
            data=json.dumps(self.load_json_file(name_file)),
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(400, response.status_code)
        self.compare_values(
            'Ip 10.0.4.1 not available for network 8.',
            response.data['detail'])

    def test_try_create_out_of_range_ip_in_network(self):
        """Tests if NAPI deny out of range network IPv4 manually creation."""

        name_file = 'api_ip/tests/sanity/ipv4/json/post/out_of_range_ipv4_172_0_0_5_net_5.json'
        response = self.client.post(
            '/api/v3/ipv4/',
            data=json.dumps(self.load_json_file(name_file)),
            content_type='application/json',
            HTTP_AUTHORIZATION=self.get_http_authorization('test'))

        self.compare_status(400, response.status_code)
        self.compare_values(
            'Ip 172.0.0.5 not available for network 5.',
            response.data['detail'])
Пример #33
0
class MiddlewareTestCase(SettingsMixin, test.TestCase):
    fixtures = ['session_security_test_user']

    def setUp(self):
        super(MiddlewareTestCase, self).setUp()
        self.client = Client()

    def test_auto_logout(self):
        self.client.login(username='******', password='******')
        response = self.client.get('/admin/')
        self.assertTrue('_auth_user_id' in self.client.session)
        time.sleep(self.max_expire_after)
        response = self.client.get('/admin/')
        self.assertFalse('_auth_user_id' in self.client.session)

    def test_last_activity_in_future(self):
        self.client.login(username='******', password='******')
        now = datetime.now()
        future = now + timedelta(0, self.max_expire_after * 2)
        set_last_activity(self.client.session, future)
        response = self.client.get('/admin/')
        self.assertTrue('_auth_user_id' in self.client.session)

    def test_non_javascript_browse_no_logout(self):
        self.client.login(username='******', password='******')
        response = self.client.get('/admin/')
        time.sleep(self.max_warn_after)
        response = self.client.get('/admin/')
        self.assertTrue('_auth_user_id' in self.client.session)
        time.sleep(self.min_warn_after)
        response = self.client.get('/admin/')
        self.assertTrue('_auth_user_id' in self.client.session)

    def test_javascript_activity_no_logout(self):
        self.client.login(username='******', password='******')
        response = self.client.get('/admin/')
        time.sleep(self.max_warn_after)
        self.client.get('/session_security/ping/?idleFor=1')
        self.assertTrue('_auth_user_id' in self.client.session)
        time.sleep(self.min_warn_after)
        self.client.get('/admin/')
        self.assertTrue('_auth_user_id' in self.client.session)

    def test_url_names(self):
        self.client.login(username='******', password='******')
        # Confirm activity is updating
        response = self.client.get('/admin/')
        activity1 = get_last_activity(self.client.session)
        time.sleep(min(2, self.min_warn_after))
        response = self.client.get('/admin/')
        activity2 = get_last_activity(self.client.session)
        self.assertTrue(activity2 > activity1)
        # Confirm activity on ignored URL is NOT updated
        time.sleep(min(2, self.min_warn_after))
        response = self.client.get('/ignore/')
        activity3 = get_last_activity(self.client.session)
        self.assertEqual(activity2, activity3)
Пример #34
0
 def fetch_response(self, url_name, group):
     url = reverse(url_name)
     client = Client()
     return client.get('%s?week=%s&group=%s' %
                       (url, group.week, group.group))
Пример #35
0
class ImagestoreTest(TestCase):
    def setUp(self):
        self.image_file = open(os.path.join(os.path.dirname(__file__), 'test_img.jpg'), 'rb')
        self.user = User.objects.create_user('zeus', '*****@*****.**', 'zeus')
        self.user.user_permissions.add(*Permission.objects.filter(content_type__app_label='imagestore'))
        self.client = Client()
        self.album = Album(name='test album', user=self.user)
        self.album.save()

    def _upload_test_image(self, username='******', password='******'):
        self.client.login(username=username, password=password)
        self.image_file = open(os.path.join(os.path.dirname(__file__), 'test_img.jpg'), 'rb')
        response = self.client.get(reverse('imagestore:upload'))
        self.assertEqual(response.status_code, 200)
        tree = html.fromstring(response.content)
        values = dict(tree.xpath('//form[@method="post"]')[0].form_values())
        values['image'] = self.image_file
        values['album'] = Album.objects.filter(user=self.user)[0].id
        values['some_int'] = random.randint(1, 100)
        response = self.client.post(reverse('imagestore:upload'), values, follow=True)
        return response

    def _create_test_album(self, username='******', password='******'):
        self.client.login(username=username, password=password)
        response = self.client.get(reverse('imagestore:create-album'))
        self.assertEqual(response.status_code, 200)
        tree = html.fromstring(response.content)
        values = dict(tree.xpath('//form[@method="post"]')[0].form_values())
        values['name'] = 'test album creation'
        response = self.client.post(reverse('imagestore:create-album'), values, follow=True)
        return response

    def test_empty_index(self):
        response = self.client.get(reverse('imagestore:index'))
        self.assertEqual(response.status_code, 200)

    def test_empty_album(self):
        self.album.is_public = False
        self.album.save()
        response = self.client.get(self.album.get_absolute_url())
        self.assertTrue(response.status_code == 403)
        self.client.login(username='******', password='******')
        self.user.is_superuser = True
        self.user.save()
        response = self.client.get(self.album.get_absolute_url())
        self.assertEqual(response.status_code, 200)

    def test_user(self):
        response = self.client.get(reverse('imagestore:user', kwargs={'username': '******'}))
        self.assertEqual(response.status_code, 200)

    def test_album_creation(self):
        response = self._create_test_album()
        self.assertEqual(response.status_code, 200)

    def test_album_edit(self):
        response = self._create_test_album()
        album_id = Album.objects.get(name='test album creation').id
        self.client.login(username='******', password='******')
        response = self.client.get(reverse('imagestore:update-album', kwargs={'pk': album_id}))
        self.assertEqual(response.status_code, 200)
        tree = html.fromstring(response.content)
        values = dict(tree.xpath('//form[@method="post"]')[0].form_values())
        values['name'] = 'test album update'
        self.client.post(reverse('imagestore:update-album', kwargs={'pk': album_id}), values, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(Album.objects.get(id=album_id).name == 'test album update')

    def test_album_delete(self):
        response = self._create_test_album()
        self.client.login(username='******', password='******')
        album_id = Album.objects.get(name='test album creation').id
        response = self.client.post(reverse('imagestore:delete-album', kwargs={'pk': album_id}), follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(len(Album.objects.filter(id=album_id)) == 0)

    def test_image_upload(self):
        response = self._create_test_album()
        response = self._upload_test_image()
        self.assertEqual(response.status_code, 200)
        img = Image.objects.get(user__username='******')
        img_url = img.get_absolute_url()
        response = self.client.get(img_url)
        self.assertEqual(response.status_code, 200)
        self.test_user()
        self.assertIsNotNone(img.some_int)

    def test_tagging(self):
        response = self._create_test_album()
        self.client.login(username='******', password='******')
        response = self.client.get(reverse('imagestore:upload'))
        self.assertEqual(response.status_code, 200)
        tree = html.fromstring(response.content)
        values = dict(tree.xpath('//form[@method="post"]')[0].form_values())
        values['image'] = self.image_file
        values['tags'] = 'one, tow, three'
        values['some_int'] = random.randint(1, 100)
        values['album'] = Album.objects.filter(user=self.user)[0].id
        self.client.post(reverse('imagestore:upload'), values, follow=True)
        self.assertEqual(response.status_code, 200)
        response = self.client.get(reverse('imagestore:tag', kwargs={'tag': 'one'}))
        self.assertEqual(response.status_code, 200)
        self.assertTrue(len(response.context['image_list']) == 1)

    def test_delete(self):
        User.objects.create_user('bad', '*****@*****.**', 'bad')
        response = self._create_test_album()
        self._upload_test_image()
        self.client.login(username='******', password='******')
        image_id = Image.objects.get(user__username='******').id
        response = self.client.post(reverse('imagestore:delete-image', kwargs={'pk': image_id}), follow=True)
        self.assertEqual(response.status_code, 404)
        self.client.login(username='******', password='******')
        response = self.client.post(reverse('imagestore:delete-image', kwargs={'pk': image_id}), follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(Image.objects.all()), 0)

    def test_update_image(self):
        self._upload_test_image()
        self.client.login(username='******', password='******')
        image_id = Image.objects.get(user__username='******').id
        response = self.client.get(reverse('imagestore:update-image', kwargs={'pk': image_id}), follow=True)
        self.assertEqual(response.status_code, 200)
        tree = html.fromstring(response.content)
        values = dict(tree.xpath('//form[@method="post"]')[0].form_values())
        values['tags'] = 'one, tow, three'
        values['title'] = 'changed title'
        values['album'] = Album.objects.filter(user=self.user)[0].id
        self.client.post(reverse('imagestore:update-image', kwargs={'pk': image_id}), values, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(Image.objects.get(user__username='******').title == 'changed title')

    def test_prev_next_with_ordering(self):
        self.test_album_creation()
        for i in range(1, 6):
            self._upload_test_image()
            img = Image.objects.order_by('-id')[0]
            img.order = i
            img.save()
        # Swap two id's
        im1 = Image.objects.get(order=2)
        im2 = Image.objects.get(order=4)
        im1.order, im2.order = 4, 2
        im1.save()
        im2.save()
        response = self.client.get(Image.objects.get(order=3).get_absolute_url())
        self.assertEqual(response.context['next'], im1)
        self.assertEqual(response.context['previous'], im2)

    def test_album_order(self):
        self.album.delete()
        a1 = Album.objects.create(name='b2', order=1, user=self.user)
        a2 = Album.objects.create(name='a1', order=2, user=self.user)
        response = self.client.get(reverse('imagestore:index'))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['object_list'][0].name, 'b2')
        self.assertEqual(response.context['object_list'][1].name, 'a1')
        a1.order, a2.order = 2, 1
        a1.save()
        a2.save()
        response = self.client.get(reverse('imagestore:index'))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['object_list'][0].name, 'a1')
        self.assertEqual(response.context['object_list'][1].name, 'b2')

    def test_imagestore_alt(self):
        self._upload_test_image()
        image = Image.objects.all()[0]
        image.album = None
        image.title = ''
        image.save()

        # empty title, empty brief = empty result
        result = imagestore_alt(image)
        self.assertEqual(result, 'alt=""')

        album = Album.objects.all()[0]
        album.brief = 'album brief'
        album.save()
        image.album = album
        image.save()
        counter = random.randint(0, 111)

        # empty title, not empty brief = brief in result
        result = imagestore_alt(image)
        self.assertIn(album.brief, result)
        self.assertNotIn(str(counter), result)  # insure next assertIn from mistake
        self.assertIn(result.count('\''), (0, 2))
        self.assertIn(result.count('\"'), (0, 2))

        # same behaviour plus counter
        result = imagestore_alt(image, counter)
        self.assertIn(album.brief, result)
        self.assertIn(str(counter), result)
        self.assertIn(result.count('\''), (0, 2))
        self.assertIn(result.count('\"'), (0, 2))

        # IMAGESTORE_BRIEF_TO_ALT_TEMPLATE affects on result format
        with self.settings(IMAGESTORE_BRIEF_TO_ALT_TEMPLATE='{1}_{0}'):
            result = imagestore_alt(image, counter)
            self.assertIn('{1}_{0}'.format(album.brief, counter), result)

        # but does not affect on single and double quotes
        with self.settings(IMAGESTORE_BRIEF_TO_ALT_TEMPLATE='{1}_\'_\"_{0}'):
            result = imagestore_alt(image, counter)
            self.assertIn(result.count('\''), (0, 2))
            self.assertIn(result.count('\"'), (0, 2))

        # quotes shall not pass
        album.brief = 'album \' \" brief'
        album.save()
        result = imagestore_alt(image, counter)
        self.assertIn(result.count('\''), (0, 2))
        self.assertIn(result.count('\"'), (0, 2))
        counter = '1 \'\" 2'
        result = imagestore_alt(image, counter)
        self.assertIn(result.count('\''), (0, 2))
        self.assertIn(result.count('\"'), (0, 2))

        # not empty title = title in result (only)
        image.title = 'image title'
        image.save()
        result = imagestore_alt(image, counter)
        self.assertIn(image.title, result)
        self.assertNotIn(album.brief, result)
        self.assertNotIn(str(counter), result)
        self.assertIn(result.count('\''), (0, 2))
        self.assertIn(result.count('\"'), (0, 2))

        # quotes escaped again
        image.title = 'image \' \" title'
        image.save()
        result = imagestore_alt(image, counter)
        self.assertIn(result.count('\''), (0, 2))
        self.assertIn(result.count('\"'), (0, 2))
Пример #36
0
class ViewsTestCase(IssuesTestCase):

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

        from django.test.client import Client

        self.client = Client()

    def test_no_issues(self):

        from django.core.urlresolvers import reverse

        # Can't access when we are not logged in.
        response = self.client.get(reverse('issue_list'))
        self.assertEqual(response.status_code, 302)

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

        response = self.client.get(reverse('issue_list'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "You don't have any issues at the moment.")

    def test_report(self):

        from django.core.urlresolvers import reverse
        from resources.models import Resource
        from issues.models import Issue, \
            SEVERITY_LOW, SEVERITY_MEDIUM, SEVERITY_HIGH, SEVERITY_CRITICAL


        # Can't access when we are not logged in.
        response = self.client.get(reverse(
            'resource_report',
            kwargs={'object_id': self.resource1.id}))
        self.assertEqual(response.status_code, 302)

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

        response = self.client.get(reverse(
            'resource_report',
            kwargs={'object_id': self.resource1.id}))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "ALISS: report %s" % self.resource1.title)

        response = self.client.post(
            reverse(
                'resource_report',
                kwargs={'object_id': self.resource1.id}),
            data={'severity': '1', 'message': 'I am reporting this now.'})
        self.assertEqual(response.status_code, 302)

        issue = Issue.objects.first()
        self.assertEqual(issue.severity, 1)
        self.assertEqual(issue.message, 'I am reporting this now.')
        self.assertEqual(issue.reporter, self.bob)
        self.assertEqual(issue.related_document, self.resource1)

        response = self.client.post(reverse('issue_list'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'I am reporting this now.')

        response = self.client.post(reverse('issue_detail', kwargs={'object_id': issue.id}))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'I am reporting this now.')
Пример #37
0
class BadgeTests(AskbotTestCase):

    def setUp(self):
        self.u1 = self.create_user(username = '******')
        self.u2 = self.create_user(username = '******')
        self.u3 = self.create_user(username = '******')
        self.client = Client()

    def assert_have_badge(self, badge_key, recipient = None, expected_count = 1):
        """note - expected_count matches total number of
        badges within test, not the one that was awarded between the calls
        to this assertion"""
        filters = {'badge__slug': badge_key, 'user': recipient}
        count = models.Award.objects.filter(**filters).count()
        self.assertEquals(count, expected_count)

    def assert_accepted_answer_badge_works(self,
                                    badge_key = None,
                                    min_score = None,
                                    expected_count = 1,
                                    previous_count = 0,
                                    trigger = None
                                ):
        assert(trigger in ('accept_best_answer', 'upvote_answer'))
        question = self.post_question(user = self.u1)
        answer = self.post_answer(user = self.u2, question = question)
        answer.score = min_score - 1
        answer.save()

        recipient = answer.author

        if trigger == 'accept_best_answer':
            self.u1.upvote(answer)
            self.assert_have_badge(badge_key, recipient, previous_count)
            self.u1.accept_best_answer(answer)
        else:
            self.u1.accept_best_answer(answer)
            self.assert_have_badge(badge_key, recipient, previous_count)
            self.u1.upvote(answer)
        self.assert_have_badge(badge_key, recipient, expected_count)

    def assert_upvoted_answer_badge_works(self, 
                                    badge_key = None,
                                    min_score = None,
                                    multiple = False
                                ):
        """test answer badge where answer author is the recipient
        where badge award is triggered by upvotes
        * min_score - minimum # of upvotes required
        * multiple - multiple award or not
        * badge_key - key on askbot.models.badges.Badge object
        """
        question = self.post_question(user = self.u1)
        answer = self.post_answer(user = self.u2, question = question)
        answer.score = min_score - 1
        answer.save()
        self.u1.upvote(answer)
        self.assert_have_badge(badge_key, recipient = self.u2)
        self.u3.upvote(answer)
        self.assert_have_badge(badge_key, recipient = self.u2, expected_count = 1)
        
        #post another question and check that there are no new badges
        question2 = self.post_question(user = self.u1)
        answer2 = self.post_answer(user = self.u2, question = question2)
        answer2.score = min_score - 1
        answer2.save()
        self.u1.upvote(answer2)

        if multiple == True:
            expected_count = 2
        else:
            expected_count = 1

        self.assert_have_badge(
                badge_key,
                recipient = self.u2,
                expected_count = expected_count
            )

    def assert_upvoted_question_badge_works(self, 
                                    badge_key = None,
                                    min_score = None,
                                    multiple = False
                                ):
        """test question badge where question author is the recipient
        where badge award is triggered by upvotes
        * min_score - minimum # of upvotes required
        * multiple - multiple award or not
        * badge_key - key on askbot.models.badges.Badge object
        """
        question = self.post_question(user = self.u1)
        question.score = min_score - 1
        question.save()
        self.u2.upvote(question)
        self.assert_have_badge(badge_key, recipient = self.u1)
        self.u3.upvote(question)
        self.assert_have_badge(badge_key, recipient = self.u1, expected_count = 1)
        
        #post another question and check that there are no new badges
        question2 = self.post_question(user = self.u1)
        question2.score = min_score - 1
        question2.save()
        self.u2.upvote(question2)

        if multiple == True:
            expected_count = 2
        else:
            expected_count = 1

        self.assert_have_badge(
                        badge_key,
                        recipient = self.u1,
                        expected_count = expected_count
                    )

    def test_disciplined_badge(self):
        question = self.post_question(user = self.u1)
        question.score = settings.DISCIPLINED_BADGE_MIN_UPVOTES
        question.save()
        self.u1.delete_question(question)
        self.assert_have_badge('disciplined', recipient = self.u1)

        question2 = self.post_question(user = self.u1)
        question2.score = settings.DISCIPLINED_BADGE_MIN_UPVOTES
        question2.save()
        self.u1.delete_question(question2)
        self.assert_have_badge('disciplined', recipient = self.u1, expected_count = 2)

    def test_peer_pressure_badge(self):
        question = self.post_question(user = self.u1)
        answer = self.post_answer(user = self.u1, question = question)
        answer.score = -1*settings.PEER_PRESSURE_BADGE_MIN_DOWNVOTES
        answer.save()
        self.u1.delete_answer(answer)
        self.assert_have_badge('peer-pressure', recipient = self.u1)

    def test_teacher_badge(self):
        self.assert_upvoted_answer_badge_works(
            badge_key = 'teacher',
            min_score = settings.TEACHER_BADGE_MIN_UPVOTES,
            multiple = False
        )

    def test_nice_answer_badge(self):
        self.assert_upvoted_answer_badge_works(
            badge_key = 'nice-answer',
            min_score = settings.NICE_ANSWER_BADGE_MIN_UPVOTES,
            multiple = True
        )

    def test_nice_question_badge(self):
        self.assert_upvoted_question_badge_works(
            badge_key = 'nice-question',
            min_score = settings.NICE_QUESTION_BADGE_MIN_UPVOTES,
            multiple = True
        )

    def test_popular_question_badge(self):
        question = self.post_question(user = self.u1)
        min_views = settings.POPULAR_QUESTION_BADGE_MIN_VIEWS
        question.thread.view_count = min_views - 1
        question.thread.save()

        #patch not_a_robot_request to return True
        from askbot.utils import functions
        functions.not_a_robot_request = lambda v: True

        url = question.get_absolute_url()

        self.client.login(method='force', user_id = self.u2.id)
        self.client.get(url)
        self.assert_have_badge('popular-question', recipient = self.u1)

        self.client.login(method='force', user_id = self.u3.id)
        self.client.get(url)
        self.assert_have_badge('popular-question', recipient = self.u1, expected_count = 1)

        question2 = self.post_question(user = self.u1)
        question2.thread.view_count = min_views - 1
        question2.thread.save()
        self.client.login(method='force', user_id = self.u2.id)
        self.client.get(question2.get_absolute_url())
        self.assert_have_badge('popular-question', recipient = self.u1, expected_count = 2)

    def test_student_badge(self):
        question = self.post_question(user = self.u1)
        self.u2.upvote(question)
        self.assert_have_badge('student', recipient = self.u1)
        self.u3.upvote(question)
        self.assert_have_badge('student', recipient = self.u1, expected_count = 1)

        question2 = self.post_question(user = self.u1)
        self.u2.upvote(question)
        self.assert_have_badge('student', recipient = self.u1, expected_count = 1)

    def test_supporter_badge(self):
        question = self.post_question(user = self.u1)
        self.u2.upvote(question)
        self.assert_have_badge('supporter', recipient = self.u2)

        answer = self.post_answer(user = self.u1, question = question)
        self.u3.upvote(answer)
        self.assert_have_badge('supporter', recipient = self.u3)
        self.u2.upvote(answer)
        self.assert_have_badge('supporter', recipient = self.u2, expected_count = 1)

    def test_critic_badge(self):
        question = self.post_question(user = self.u1)
        self.u2.downvote(question)
        self.assert_have_badge('critic', recipient = self.u2)

        answer = self.post_answer(user = self.u1, question = question)
        self.u3.downvote(answer)
        self.assert_have_badge('critic', recipient = self.u3)
        self.u2.downvote(answer)
        self.assert_have_badge('critic', recipient = self.u2, expected_count = 1)

    def test_self_learner_badge(self):
        question = self.post_question(user = self.u1)
        answer = self.post_answer(user = self.u1, question = question)
        min_votes = settings.SELF_LEARNER_BADGE_MIN_UPVOTES
        answer.score = min_votes - 1
        answer.save()
        self.u2.upvote(answer)
        self.assert_have_badge('self-learner', recipient = self.u1)

        #copy-paste of the first question, except expect second badge
        question = self.post_question(user = self.u1)
        answer = self.post_answer(user = self.u1, question = question)
        answer.score = min_votes - 1
        answer.save()
        self.u2.upvote(answer)
        self.assert_have_badge('self-learner', recipient = self.u1, expected_count = 2)

        question = self.post_question(user = self.u2)
        answer = self.post_answer(user = self.u1, question = question)
        answer.score = min_votes - 1
        answer.save()
        self.u2.upvote(answer)
        #no badge when asker != answerer
        self.assert_have_badge(
            'self-learner',
            recipient = self.u1,
            expected_count = 2
        )

    def test_civic_duty_badge(self):
        settings.update('CIVIC_DUTY_BADGE_MIN_VOTES', 2)
        question = self.post_question(user = self.u1)
        answer = self.post_answer(user = self.u2, question = question)
        answer2 = self.post_answer(user = self.u1, question = question)
        self.u3.upvote(question)
        self.u3.downvote(answer)
        self.assert_have_badge('civic-duty', recipient = self.u3)
        self.u3.upvote(answer2)
        self.assert_have_badge('civic-duty', recipient = self.u3, expected_count = 1)
        self.u3.downvote(answer)
        self.assert_have_badge('civic-duty', recipient = self.u3, expected_count = 1)

    def test_scholar_badge(self):
        question = self.post_question(user = self.u1)
        answer = self.post_answer(user = self.u2, question = question)
        self.u1.accept_best_answer(answer)
        self.assert_have_badge('scholar', recipient = self.u1)
        question2 = self.post_question(user = self.u1)
        answer2 = self.post_answer(user = self.u2, question = question2)
        self.u1.accept_best_answer(answer2)
        self.assert_have_badge(
            'scholar',
            recipient = self.u1,
            expected_count=1
        )

    def assert_enlightened_badge_works(self, trigger):
        self.assert_accepted_answer_badge_works(
            'enlightened',
            min_score = settings.ENLIGHTENED_BADGE_MIN_UPVOTES,
            expected_count = 1,
            trigger = trigger
        )
        self.assert_accepted_answer_badge_works(
            'enlightened',
            min_score = settings.ENLIGHTENED_BADGE_MIN_UPVOTES,
            expected_count = 1,
            previous_count = 1,
            trigger = trigger
        )

    def assert_guru_badge_works(self, trigger):
        self.assert_accepted_answer_badge_works(
            'guru',
            min_score = settings.GURU_BADGE_MIN_UPVOTES,
            expected_count = 1,
            trigger = trigger
        )
        self.assert_accepted_answer_badge_works(
            'guru',
            min_score = settings.GURU_BADGE_MIN_UPVOTES,
            previous_count = 1,
            expected_count = 2,
            trigger = trigger
        )

    def test_enlightened_badge1(self):
        self.assert_enlightened_badge_works('upvote_answer')

    def test_enlightened_badge2(self):
        self.assert_enlightened_badge_works('accept_best_answer')

    def test_guru_badge1(self):
        self.assert_guru_badge_works('upvote_answer')

    def test_guru_badge1(self):
        self.assert_guru_badge_works('accept_best_answer')

    def test_necromancer_badge(self):
        question = self.post_question(user = self.u1)
        now = datetime.datetime.now()
        delta = datetime.timedelta(settings.NECROMANCER_BADGE_MIN_DELAY + 1)
        future = now + delta
        answer = self.post_answer(
                        user = self.u2,
                        question = question,
                        timestamp = future
                    ) 
        answer.score = settings.NECROMANCER_BADGE_MIN_UPVOTES - 1
        answer.save()
        self.assert_have_badge('necromancer', self.u2, expected_count = 0)
        self.u1.upvote(answer)
        self.assert_have_badge('necromancer', self.u2, expected_count = 1)

    def test_citizen_patrol_question(self):
        self.u2.set_status('m')
        question = self.post_question(user = self.u1)
        self.u2.flag_post(question)
        self.assert_have_badge('citizen-patrol', self.u2)
        question = self.post_question(user = self.u1)
        self.u2.flag_post(question)
        self.assert_have_badge('citizen-patrol', self.u2, 1)

    def test_citizen_patrol_answer(self):
        self.u2.set_status('m')
        question = self.post_question(user = self.u1)
        answer = self.post_answer(user = self.u1, question = question)
        self.u2.flag_post(answer)
        self.assert_have_badge('citizen-patrol', self.u2)
        question = self.post_question(user = self.u1)
        answer = self.post_answer(user = self.u1, question = question)
        self.u2.flag_post(answer)
        self.assert_have_badge('citizen-patrol', self.u2, 1)

    def test_editor_badge_question(self):
        self.u2.set_status('m')
        question = self.post_question(user = self.u1)
        self.u2.edit_question(
            question = question,
            title = 'hahaha',
            body_text = 'heheeh',
            revision_comment = 'ihihih'
        )
        self.assert_have_badge('editor', self.u2, 1)
        #double check that its not multiple
        question = self.post_question(user = self.u1)
        self.u2.edit_question(
            question = question,
            title = 'hahaha',
            body_text = 'heheeh',
            revision_comment = 'ihihih'
        )
        self.assert_have_badge('editor', self.u2, 1)

    def test_editor_badge_answer(self):
        self.u2.set_status('m')
        question = self.post_question(user = self.u1)
        answer = self.post_answer(user = self.u1, question = question)
        self.u2.edit_answer(answer = answer, body_text = 'hahaha')
        self.assert_have_badge('editor', self.u2, 1)
        #double check that its not multiple
        question = self.post_question(user = self.u1)
        answer = self.post_answer(user = self.u1, question = question)
        self.u2.edit_answer(answer = answer, body_text = 'hahaha')
        self.assert_have_badge('editor', self.u2, 1)

    def test_associate_editor_badge(self):
        self.u2.set_status('m')
        question = self.post_question(user = self.u1)
        settings.update('ASSOCIATE_EDITOR_BADGE_MIN_EDITS', 2)
        self.u2.edit_question(
            question = question,
            title = 'hahaha',
            body_text = 'sdgsdjghsldkfshd',
            revision_comment = 'sdgdfgsgfs'
        )
        self.assert_have_badge('strunk-and-white', self.u2, 0)
        self.u2.edit_question(
            question = question,
            title = 'hahaha',
            body_text = 'sdgsdjghsldkfshd',
            revision_comment = 'sdgdfgsgfs'
        )
        self.assert_have_badge('strunk-and-white', self.u2, 1)
        self.u2.edit_question(
            question = question,
            title = 'hahaha',
            body_text = 'sdgsdjghsldkfshd',
            revision_comment = 'sdgdfgsgfs'
        )
        self.assert_have_badge('strunk-and-white', self.u2, 1)

    def test_organizer_badge(self):
        question = self.post_question(user = self.u1)
        self.u1.retag_question(question = question, tags = 'blah boom')
        self.assert_have_badge('organizer', self.u1, 1)
        self.u1.retag_question(question = question, tags = 'blah pooh')
        self.assert_have_badge('organizer', self.u1, 1)

    def test_autobiographer_badge(self):
        self.u1.real_name = 'blah'
        self.u1.website = 'cnn.com'
        self.u1.location = 'irvine'
        self.u1.about = 'blah'
        self.u1.save()
        award_badges_signal.send(None,
            event = 'update_user_profile',
            actor = self.u1,
            context_object = self.u1
        )
        self.assert_have_badge('autobiographer', self.u1, 1)
        award_badges_signal.send(None,
            event = 'update_user_profile',
            actor = self.u1,
            context_object = self.u1
        )
        self.assert_have_badge('autobiographer', self.u1, 1)

    def test_stellar_badge1(self):
        question = self.post_question(user = self.u1)
        settings.update('STELLAR_QUESTION_BADGE_MIN_STARS', 2)
        self.u2.toggle_favorite_question(question)
        self.assert_have_badge('stellar-question', self.u1, 0)
        self.u3.toggle_favorite_question(question)
        self.assert_have_badge('stellar-question', self.u1, 1)

    def test_stellar_badge2(self):
        question = self.post_question(user = self.u1)
        settings.update('STELLAR_QUESTION_BADGE_MIN_STARS', 2)
        self.u2.toggle_favorite_question(question)
        self.assert_have_badge('stellar-question', self.u1, 0)
        self.u1.toggle_favorite_question(question)
        """no gaming"""
        self.assert_have_badge('stellar-question', self.u1, 0)
    
    def test_stellar_badge3(self):
        question = self.post_question(user = self.u1)
        settings.update('STELLAR_QUESTION_BADGE_MIN_STARS', 2)
        self.u2.toggle_favorite_question(question)
        self.assert_have_badge('stellar-question', self.u1, 0)
        self.u3.toggle_favorite_question(question)
        #award now
        self.assert_have_badge('stellar-question', self.u1, 1)
        self.u3.toggle_favorite_question(question)
        #dont take back
        self.assert_have_badge('stellar-question', self.u1, 1)
        self.u3.toggle_favorite_question(question)
        #dont reaward
        self.assert_have_badge('stellar-question', self.u1, 1)

    def test_commentator_badge(self):
        question = self.post_question(user = self.u1)
        min_comments = settings.COMMENTATOR_BADGE_MIN_COMMENTS
        for i in xrange(min_comments - 1):
            self.post_comment(user = self.u1, parent_post = question)

        self.assert_have_badge('commentator', self.u1, 0)
        self.post_comment(user = self.u1, parent_post = question) 
        self.assert_have_badge('commentator', self.u1, 1)
        self.post_comment(user = self.u1, parent_post = question) 
        self.assert_have_badge('commentator', self.u1, 1)

    def test_taxonomist_badge(self):
        self.post_question(user = self.u1, tags = 'test')
        min_use = settings.TAXONOMIST_BADGE_MIN_USE_COUNT
        for i in xrange(min_use - 2):
            self.post_question(user = self.u2, tags = 'test')
        self.assert_have_badge('taxonomist', self.u1, 0)
        self.post_question(user = self.u2, tags = 'test')
        self.assert_have_badge('taxonomist', self.u1, 1)

    def test_enthusiast_badge(self):
        yesterday = datetime.datetime.now() - datetime.timedelta(1)
        self.u1.last_seen = yesterday
        prev_visit_count = settings.ENTHUSIAST_BADGE_MIN_DAYS - 1
        self.u1.consecutive_days_visit_count = prev_visit_count
        self.u1.save()
        self.assert_have_badge('enthusiast', self.u1, 0)
        self.client.login(method = 'force', user_id = self.u1.id)
        self.client.get('/' + django_settings.ASKBOT_URL)
        self.assert_have_badge('enthusiast', self.u1, 1)
Пример #38
0
    def test_ajax_layer_permissions(self):
        """Verify that the ajax_layer_permissions view is behaving as expected
        """

        # Setup some layer names to work with
        valid_layer_typename = Layer.objects.all()[0].id
        invalid_layer_id = 9999999

        c = Client()

        # Test that an invalid layer.typename is handled for properly
        response = c.post(reverse('resource_permissions',
                                  args=(
                                      'layer',
                                      invalid_layer_id,
                                  )),
                          data=json.dumps(self.perm_spec),
                          content_type="application/json")
        self.assertEquals(response.status_code, 404)

        # Test that GET returns permissions
        response = c.get(
            reverse('resource_permissions',
                    args=(
                        'layer',
                        valid_layer_typename,
                    )))
        assert ('permissions' in response.content)

        # Test that a user is required to have maps.change_layer_permissions

        # First test un-authenticated
        response = c.post(reverse('resource_permissions',
                                  args=(
                                      'layer',
                                      valid_layer_typename,
                                  )),
                          data=json.dumps(self.perm_spec),
                          content_type="application/json")
        self.assertEquals(response.status_code, 401)

        # Next Test with a user that does NOT have the proper perms
        logged_in = c.login(username='******', password='******')
        self.assertEquals(logged_in, True)
        response = c.post(reverse('resource_permissions',
                                  args=(
                                      'layer',
                                      valid_layer_typename,
                                  )),
                          data=json.dumps(self.perm_spec),
                          content_type="application/json")
        self.assertEquals(response.status_code, 401)

        # Login as a user with the proper permission and test the endpoint
        logged_in = c.login(username='******', password='******')
        self.assertEquals(logged_in, True)

        response = c.post(reverse('resource_permissions',
                                  args=(
                                      'layer',
                                      valid_layer_typename,
                                  )),
                          data=json.dumps(self.perm_spec),
                          content_type="application/json")

        # Test that the method returns 200
        self.assertEquals(response.status_code, 200)
Пример #39
0
class TestStatusCodes(TestCase):

    def setUp(self):
        """Initialize each test."""

        # required for loading data
        loading.cache.loaded = False

        # initialize database from json file
        call_command('loaddata', 'liby/books/fixtures/development.json', verbosity=0)

        # add one blog post
        self.blogpost = BlogPost.objects.create(
            title="Title #1",
            body="Some long text for testing body.",
            created=now(),
        )

        # add tags to blog post
        self.blogpost.tags.add("tag1", "tag2")

        self.client = Client()

    def tearDown(self):
        """Tear down after each test, flush database and client."""
        call_command('flush', interactive=False, verbosity=0)
        del self.client

    def test_blog(self):
        """Test if main blog page returns status code 200."""
        response = self.client.get('/blog/')
        self.assertEqual(response.status_code, 200)

    def test_blog_at(self):
        """Test if first blog page returns status code 200."""
        response = self.client.get('/blog/1')
        self.assertEqual(response.status_code, 200)

    def test_blog_404(self):
        """Test if n-th blog page returns status code 404."""
        response = self.client.get('/blog/1000')
        self.assertEqual(response.status_code, 404)

    def test_blog_archives(self):
        """Test if archives of blogs page returns status code 200."""
        response = self.client.get('/blog/archives/')
        self.assertEqual(response.status_code, 200)

    def test_tag_page(self):
        """Test if tag page returns status code 200."""
        response = self.client.get('/blog/tag/tag1')
        self.assertEqual(response.status_code, 200)

    def test_tag_404(self):
        """Test if nonexistent tag page returns status code 200."""
        response = self.client.get('/blog/tag/notag')
        self.assertEqual(response.status_code, 404)

    def test_feed(self):
        """Test if feed url returns status code 200."""
        response = self.client.get('/blog/feed/')
        self.assertEqual(response.status_code, 200)

    def test_404(self):
        """Test if nonexistent page has status code 404."""
        response = self.client.get('/blog/nopage/')
        self.assertEqual(response.status_code, 404)
Пример #40
0
 def test_data(self):
     '''/data/ -> Test accessing the data page'''
     c = Client()
     response = c.get(reverse('layer_browse'))
     self.failUnlessEqual(response.status_code, 200)
Пример #41
0
 def testIndexPage(self):
     c = Client()
     response = c.get('/objectbrowser/')
     self.assertEqual(response.status_code, 200)
Пример #42
0
    def test_open_now(self):
        dummy_cache = cache.get_cache(
            'django.core.cache.backends.dummy.DummyCache')
        with patch.object(models, 'cache', dummy_cache):
            open_in_range_spot = Spot.objects.create(
                name="This spot is open now",
                latitude=Decimal('40.0000898315'),
                longitude=Decimal('-50.0'))
            closed_in_range_spot = Spot.objects.create(
                name="This spot is closed now",
                latitude=Decimal('40.0000898315'),
                longitude=Decimal('-50.0'))

            open_outof_range_spot = Spot.objects.create(
                name="This spot is open now",
                latitude=Decimal('45.0000898315'),
                longitude=Decimal('-55.0'))
            closed_outof_range_spot = Spot.objects.create(
                name="This spot is closed now",
                latitude=Decimal('45.0000898315'),
                longitude=Decimal('-55.0'))

            now = datetime.time(datetime.now())

            open_start = alternate_date.time(now.hour - 1, now.minute)
            open_end = alternate_date.time(now.hour + 1, now.minute)

            closed_start = alternate_date.time(now.hour + 1, now.minute)
            closed_end = alternate_date.time(now.hour + 2, now.minute)

            day_lookup = ["su", "m", "t", "w", "th", "f", "sa"]
            day_num = int(strftime("%w", localtime()))
            today = day_lookup[day_num]

            open_hours1 = SpotAvailableHours.objects.create(
                spot=open_in_range_spot,
                day=today,
                start_time=open_start,
                end_time=open_end)
            closed_hours1 = SpotAvailableHours.objects.create(
                spot=closed_in_range_spot,
                day=today,
                start_time=closed_start,
                end_time=closed_end)

            open_hours2 = SpotAvailableHours.objects.create(
                spot=open_outof_range_spot,
                day=today,
                start_time=open_start,
                end_time=open_end)
            closed_hours2 = SpotAvailableHours.objects.create(
                spot=closed_outof_range_spot,
                day=today,
                start_time=closed_start,
                end_time=closed_end)

            c = Client()
            response = c.get(
                "/api/v1/spot", {
                    'center_latitude': "40",
                    'center_longitude': -50,
                    'distance': 100,
                    'open_now': True
                })
            spots = json.loads(response.content)

            has_open_in_range = False
            has_open_outof_range = False
            has_closed_in_range = False
            has_closed_outof_range = False

            for spot in spots:
                if spot['id'] == open_in_range_spot.pk:
                    has_open_in_range = True
                if spot['id'] == closed_in_range_spot.pk:
                    has_closed_in_range = True
                if spot['id'] == open_outof_range_spot.pk:
                    has_open_outof_range = True
                if spot['id'] == closed_outof_range_spot.pk:
                    has_closed_outof_range = True

            self.assertEquals(has_open_in_range, True,
                              "Found the open spot in range")
            self.assertEquals(has_closed_in_range, False,
                              "Did not find the closed spot in range")
            self.assertEquals(has_open_outof_range, False,
                              "Did not find the open spot out of range")
            self.assertEquals(has_closed_outof_range, False,
                              "Did not find the closed spot out of range")
Пример #43
0
class BasicViewTest(TestCase):
    def setUp(self):
        self.c = Client()
        self.u = User.objects.create(username='******')
        self.u.set_password('test')
        self.u.save()
        self.c.login(username="******", password="******")
        Flag.objects.create(name='simulation', everyone=True)

    def test_root(self):
        response = self.c.get("/run/new/")
        self.assertEquals(response.status_code, 200)

    def test_root_post_invalid(self):
        response = self.c.post("/run/new/")
        self.assertEquals(response.status_code, 200)
        self.assertTrue("errorlist" in response.content)

    def test_root_post_valid(self):
        response = self.c.post(
            "/run/new/",
            dict(
                ticks=10,
                number_agents=10,
                gamma_1=1.0,
                gamma_2=1.0,
                gamma_3=1.0,
                gamma_4=1.0,
                gamma_5=1.0,
                gamma_6=1.0,
                sigma_1=6.2,
                sigma_2=5.,
                agent_initial_mass_mean=100.,
                agent_initial_mass_sigma=20.,
                agent_base_output_mean=100.,
                agent_base_output_sigma=5.,
                recreation_activity_alpha=0.5,
                recreation_activity_lambda=0.1,
                domestic_activity_alpha=0.5,
                domestic_activity_lambda=0.1,
                transport_activity_alpha=0.5,
                transport_activity_lambda=0.1,
                education_activity_alpha=0.5,
                education_activity_lambda=0.1,
                food_exposure_alpha=0.5,
                food_exposure_lambda=0.1,
                energy_density_alpha=0.5,
                energy_density_lambda=0.1,
                food_advertising_alpha=0.5,
                food_advertising_lambda=0.1,
                food_convenience_alpha=0.5,
                food_convenience_lambda=0.1,
                food_literacy_alpha=0.5,
                food_literacy_lambda=0.1,
                recreation_activity_weight=1.0,
                domestic_activity_weight=1.0,
                transport_activity_weight=1.0,
                education_activity_weight=1.0,
                food_exposure_weight=1.0,
                energy_density_weight=1.0,
                food_advertising_weight=1.0,
                food_convenience_weight=1.0,
                food_literacy_weight=1.0,
            ))
        self.assertEquals(response.status_code, 302)

    def test_demo_mode(self):
        Flag.objects.create(name='demo_mode', everyone=True)
        response = self.c.post(
            "/run/new/",
            dict(
                ticks=10,
                number_agents=10,
                gamma_1=1.0,
                gamma_2=1.0,
                gamma_3=1.0,
                gamma_4=1.0,
                gamma_5=1.0,
                gamma_6=1.0,
                sigma_1=6.2,
                sigma_2=5.,
                agent_initial_mass_mean=100.,
                agent_initial_mass_sigma=20.,
                agent_base_output_mean=100.,
                agent_base_output_sigma=5.,
                recreation_activity_alpha=0.5,
                recreation_activity_lambda=0.1,
                domestic_activity_alpha=0.5,
                domestic_activity_lambda=0.1,
                transport_activity_alpha=0.5,
                transport_activity_lambda=0.1,
                education_activity_alpha=0.5,
                education_activity_lambda=0.1,
                food_exposure_alpha=0.5,
                food_exposure_lambda=0.1,
                energy_density_alpha=0.5,
                energy_density_lambda=0.1,
                food_advertising_alpha=0.5,
                food_advertising_lambda=0.1,
                food_convenience_alpha=0.5,
                food_convenience_lambda=0.1,
                food_literacy_alpha=0.5,
                food_literacy_lambda=0.1,
                recreation_activity_weight=1.0,
                domestic_activity_weight=1.0,
                transport_activity_weight=1.0,
                education_activity_weight=1.0,
                food_exposure_weight=1.0,
                energy_density_weight=1.0,
                food_advertising_weight=1.0,
                food_convenience_weight=1.0,
                food_literacy_weight=1.0,
                intervention_increase_physical_activity='high',
            ))
        self.assertEquals(response.status_code, 302)

    def test_smoketest(self):
        response = self.c.get("/smoketest/")
        self.assertEquals(response.status_code, 200)
Пример #44
0
class RegistrationTest(TestCase):
    def setUp(self):
        self.user = TestUser()
        self.client = Client()
        self.default_data = {
            'username': self.user.username,
            'first_name': self.user.firstname,
            'last_name': self.user.lastname,
            'email': self.user.email,
            'password': self.user.password
        }
        self.required_error = 'This field is required.'
        self.invalid_error = 'Enter a valid value.'

    def testRegistrationForm(self):
        response = self.client.get('/register/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'patchwork/registration_form.html')

    def testBlankFields(self):
        for field in ['username', 'email', 'password']:
            data = self.default_data.copy()
            del data[field]
            response = self.client.post('/register/', data)
            self.assertEqual(response.status_code, 200)
            self.assertFormError(response, 'form', field, self.required_error)

    def testInvalidUsername(self):
        data = self.default_data.copy()
        data['username'] = '******'
        response = self.client.post('/register/', data)
        self.assertEqual(response.status_code, 200)
        self.assertFormError(response, 'form', 'username', self.invalid_error)

    def testExistingUsername(self):
        user = create_user()
        data = self.default_data.copy()
        data['username'] = user.username
        response = self.client.post('/register/', data)
        self.assertEqual(response.status_code, 200)
        self.assertFormError(
            response, 'form', 'username',
            'This username is already taken. Please choose '
            'another.')

    def testExistingEmail(self):
        user = create_user()
        data = self.default_data.copy()
        data['email'] = user.email
        response = self.client.post('/register/', data)
        self.assertEqual(response.status_code, 200)
        self.assertFormError(
            response, 'form', 'email', 'This email address is already in use '
            'for the account "%s".\n' % user.username)

    def testValidRegistration(self):
        response = self.client.post('/register/', self.default_data)
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'confirmation email has been sent')

        # check for presence of an inactive user object
        users = User.objects.filter(username=self.user.username)
        self.assertEqual(users.count(), 1)
        user = users[0]
        self.assertEqual(user.username, self.user.username)
        self.assertEqual(user.email, self.user.email)
        self.assertEqual(user.is_active, False)

        # check for confirmation object
        confs = EmailConfirmation.objects.filter(user=user,
                                                 type='registration')
        self.assertEqual(len(confs), 1)
        conf = confs[0]
        self.assertEqual(conf.email, self.user.email)

        # check for a sent mail
        self.assertEqual(len(mail.outbox), 1)
        msg = mail.outbox[0]
        self.assertEqual(msg.subject, 'Patchwork account confirmation')
        self.assertIn(self.user.email, msg.to)
        self.assertIn(_confirmation_url(conf), msg.body)

        # ...and that the URL is valid
        response = self.client.get(_confirmation_url(conf))
        self.assertEqual(response.status_code, 200)
Пример #45
0
class TestDotlang(TestCase):
    def setUp(self):
        cache.clear()
        clear_url_caches()
        self.client = Client()

    def test_parse(self):
        path = os.path.join(ROOT, 'test.lang')
        parsed = parse(path)
        expected = {
            u'Hooray! Your Firefox is up to date.':
            u'F\xe9licitations&nbsp;! '
            u'Votre Firefox a \xe9t\xe9 mis \xe0 jour.',
            u'Your Firefox is out of date.':
            u'Votre Firefox ne semble pas \xe0 jour.'
        }
        eq_(parsed, expected)

    def test_parse_utf8_error(self):
        path = os.path.join(ROOT, 'test_utf8_error.lang')
        parsed = parse(path)
        eq_(len(mail.outbox), 1)
        eq_(mail.outbox[0].subject, '[Django] %s is corrupted' % path)
        expected = {
            u'Update now': u'Niha rojane bike',
            u'Supported Devices': u'C�haz�n pi�tgiriy'
        }
        eq_(parsed, expected)
        mail.outbox = []

    def test_parse_ingnores_untranslated(self):
        """parse should skip strings that aren't translated."""
        path = os.path.join(ROOT, 'locale/de/main.lang')
        parsed = parse(path)
        expected = {u'The State of Mozilla': u'Awesome Baby! YEEEAAHHHH!!'}
        self.assertDictEqual(parsed, expected)

    def test_format_identifier_re(self):
        eq_(FORMAT_IDENTIFIER_RE.findall('%s %s'), [('%s', ''), ('%s', '')])

        eq_(FORMAT_IDENTIFIER_RE.findall('%(foo_bar)s %s'),
            [('%(foo_bar)s', 'foo_bar'), ('%s', '')])

    @patch.object(settings, 'ROOT', ROOT)
    def test_format_identifier_mismatch(self):
        path = 'format_identifier_mismatch'
        expected = '%(foo)s is the new %s'
        with self.activate('en-US'):
            result = translate(expected, [path])
        eq_(expected, result)
        eq_(len(mail.outbox), 1)
        eq_(mail.outbox[0].subject,
            '[Django] locale/en-US/%s.lang is corrupted' % path)
        mail.outbox = []

    @patch.object(settings, 'ROOT', ROOT)
    def test_format_identifier_order(self):
        """
        Test that the order in which the format identifier appears doesn't
        matter
        """
        path = 'format_identifier_mismatch'
        expected = '%(foo)s is the new %(bar)s'
        with self.activate('en-US'):
            result = translate(expected, [path])
        assert_not_equal(expected, result)
        eq_(len(mail.outbox), 0)

    @patch.object(env, 'loader', FileSystemLoader(TEMPLATE_DIRS))
    @patch.object(settings, 'ROOT_URLCONF', 'l10n_utils.tests.test_files.urls')
    @patch.object(settings, 'ROOT', ROOT)
    def test_lang_files_queried_in_order(self):
        """The more specific lang files should be searched first."""
        response = self.client.get('/de/trans-block-reload-test/')
        doc = pq(response.content)
        gettext_call = doc('h1')
        eq_(gettext_call.text(), 'Die Lage von Mozilla')

    @patch.object(settings, 'ROOT', ROOT)
    def test_extract_message_tweaks_do_not_break(self):
        """
        Extraction and translation matching should tweak msgids the same.
        """
        clean_string = u'Stuff about many things.'
        dirty_string = u'Stuff\xa0about\r\nmany\t   things.'
        trans_string = u'This is the translation.'

        # extraction
        with open(os.path.join(ROOT, 'extract_me.py')) as pyfile:
            vals = extract_tower_python(pyfile, ['_'], [], {}).next()
        eq_(vals[2], clean_string)

        # translation
        # path won't exist for en-US as there isn't a dir for that
        # in locale.
        with self.activate('en-US'):
            result = translate(dirty_string, ['does_not_exist'])
            eq_(result, dirty_string)

            result = translate(dirty_string, ['tweaked_message_translation'])
            eq_(result, trans_string)

    @patch('l10n_utils.dotlang.translate')
    def test_new_lang_files_do_not_modify_settings(self, trans_patch):
        """
        Test to make sure that building the new lang files list does not
        modify `settings.DOTLANG_FILES`.
        """
        old_setting = settings.DOTLANG_FILES[:]
        trans_str = 'Translate me'
        _(trans_str)
        call_lang_files = [LANG_FILES] + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)
        eq_(old_setting, settings.DOTLANG_FILES)

    @patch('l10n_utils.dotlang.translate')
    def test_gettext_ignores_default_lang_files(self, trans_patch):
        """
        The `l10n_utils.dotlang._` function should search .lang files
        specified in the module from which it's called before the
        default files, but it should not include the defaults twice.
        """
        # use LANG_FILES global in this module
        global LANG_FILES
        old_lang_files = LANG_FILES

        trans_str = 'Translate me'
        LANG_FILES = [settings.DOTLANG_FILES[0], 'dude', 'donnie', 'walter']
        _(trans_str)
        call_lang_files = LANG_FILES[1:] + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)

        # restore original value to avoid test leakage
        LANG_FILES = old_lang_files

    @patch('l10n_utils.dotlang.translate')
    def test_gettext_searches_specified_lang_files(self, trans_patch):
        """
        The `l10n_utils.dotlang._` function should search .lang files
        specified in the module from which it's called before the
        default files.
        """
        # use LANG_FILES global in this module
        global LANG_FILES
        old_lang_files = LANG_FILES

        # test the case when LANG_FILES is a string
        trans_str = 'Translate me'
        _(trans_str)
        call_lang_files = [LANG_FILES] + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)

        # test the case when LANG_FILES is a list
        LANG_FILES = ['dude', 'donnie', 'walter']
        _(trans_str)
        call_lang_files = LANG_FILES + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)

        # restore original value to avoid test leakage
        LANG_FILES = old_lang_files

    @patch('l10n_utils.dotlang.translate')
    def test_gettext_searches_kwarg_specified_lang_files(self, trans_patch):
        """
        The `l10n_utils.dotlang._` function should search .lang files
        specified in the `lang_files` keyword arg, and not the ones from the
        module.
        """
        # test the case when LANG_FILES is a string
        trans_str = 'Translate me'
        _(trans_str, lang_files='maude')
        call_lang_files = ['maude'] + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)

        # test the case when LANG_FILES is a list
        lang_files_list = ['maude', 'bunny', 'uli']
        _(trans_str, lang_files=lang_files_list)
        call_lang_files = lang_files_list + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)

    @patch('l10n_utils.dotlang.translate')
    def test_gettext_lazy_searches_kwarg_specified_lang_files(
            self, trans_patch):
        """
        The `l10n_utils.dotlang._lazy` function should search .lang files
        specified in the `lang_files` keyword arg, and not the ones from the
        module.
        """
        # test the case when LANG_FILES is a string
        trans_str = 'Translate me'
        # have to call __unicode__ directly because the value is a Mock
        # object, and the `unicode()` function throws an exception.
        _lazy(trans_str, lang_files='maude').__unicode__()
        call_lang_files = ['maude'] + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)

        # test the case when LANG_FILES is a list
        lang_files_list = ['maude', 'bunny', 'uli']
        _lazy(trans_str, lang_files=lang_files_list).__unicode__()
        print lang_files_list
        call_lang_files = lang_files_list + settings.DOTLANG_FILES
        trans_patch.assert_called_with(trans_str, call_lang_files)

    @patch('l10n_utils.dotlang.translate')
    def test_lazy_gettext_searches_specified_lang_files(self, trans_patch):
        """
        The `l10n_utils.dotlang._lazy` function should search .lang files
        specified in the module from which it's called before the
        default files.
        """
        from l10n_utils.tests.test_files import extract_me_with_langfiles_lazy

        dude_says = extract_me_with_langfiles_lazy.do_translate()
        dirty_string = u"I'm The Dude, so that's what you call me, man."
        self.assertFalse(trans_patch.called)
        # have to call __unicode__ directly because the value is a Mock
        # object, and the `unicode()` function throws an exception.
        dude_says.__unicode__()
        trans_patch.assert_called_with(dirty_string, ['donnie', 'walter'] +
                                       settings.DOTLANG_FILES)

    @patch('l10n_utils.dotlang.translate')
    def test_gettext_works_without_extra_lang_files(self, trans_patch):
        """
        The `l10n_utils.dotlang._` function should search the default .lang
        files if no others are specified.
        """
        from l10n_utils.tests.test_files import extract_me

        extract_me.do_translate()
        dirty_string = u'Stuff\xa0about\r\nmany\t   things.'
        trans_patch.assert_called_with(dirty_string, settings.DOTLANG_FILES)

    def test_gettext_str_interpolation(self):
        result = _('The %s %s.', 'dude', 'abides')
        eq_(result, 'The dude abides.')
def test_django_app():
    client = Client()
    response = client.get('/')
    assert response.content == b'Hello, World!'
Пример #47
0
class TestModelAdmin(unittest.TestCase):
    def setUp(self):
        # Every test needs a client.
        User.objects.all().delete()
        self.user_smb = User.objects.create_user('somebody__else',
                                                 '*****@*****.**',
                                                 'somebody__else')
        self.user_smb.is_staff = True
        self.user_smb.save()
        self.user = User.objects.create_user('new_unittest',
                                             '*****@*****.**',
                                             'new_test_password')
        init_user_group('w3af_webui')
        call_command('set_role_for_user', 'new_unittest')
        self.user.is_staff = True
        self.user.is_superuser = True
        self.user.save()
        self.client = Client()
        self.client.login(username=self.user.username,
                          password='******')
        self.profile = any_model(ScanProfile, user=self.user)
        self.target = any_model(Target, user=self.user)
        self.not_mine_target = any_model(Target, user=self.user_smb)
        self.scan_task = any_model(
            ScanTask,
            user=self.user,
            status=settings.TASK_STATUS['free'],
            target=self.target,
            last_updated='0',
        )
        self.scan = Scan.objects.create(
            scan_task=self.scan_task,
            data='test',
        )

    def tearDown(self):
        self.user.delete()
        self.user_smb.delete()
        self.profile.delete()
        Target.objects.all().delete()
        self.scan_task.delete()
        self.scan.delete()

    def test_scan_list(self):
        # Issue a GET request.
        response = self.client.get('/w3af_webui/scan/')
        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)

    def test_scantask_list(self):
        # ScanTask: Issue a GET request.
        response = self.client.get('/w3af_webui/scantask/')
        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)

    def test_edit_scantask(self):
        # Issue a GET request.
        response = self.client.get(
            '/w3af_webui/scantask/%s/' % self.scan_task.id,
            follow=True,
        )
        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)

    def test_target_list(self):
        # Target: Issue a GET request.
        response = self.client.get('/w3af_webui/target/')
        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)

    def test_edit_target(self):
        # My Target: Issue a GET request.
        response = self.client.get(
            '/w3af_webui/target/%s/' % self.target.id,
            follow=True,
        )
        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)
        return

    def test_scanprofile_list(self):
        # Target: Issue a GET request.
        response = self.client.get('/w3af_webui/scanprofile/')
        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)

    def test_edit_scanprofile(self):
        # Target: Issue a GET request.
        response = self.client.get(
            '/w3af_webui/scanprofile/%s/' % self.profile.id,
            follow=True,
        )
        # Check that the response is 200 OK.
        self.assertEqual(response.status_code, 200)
Пример #48
0
class KnowledgeViewsTest(TestCase):
    "Knowledge functional tests for views"

    username = "******"
    password = "******"
    prepared = False
    authentication_headers = {
        "CONTENT_TYPE": "application/json",
        "HTTP_AUTHORIZATION": "Basic YXBpX3Rlc3Q6YXBpX3Bhc3N3b3Jk"
    }
    content_type = 'application/json'
    prepared = False

    def setUp(self):
        "Initial Setup"
        if not self.prepared:
            # Clean up first
            Object.objects.all().delete()

            # Create objects
            try:
                self.group = Group.objects.get(name='test')
            except Group.DoesNotExist:
                Group.objects.all().delete()
                self.group = Group(name='test')
                self.group.save()

            try:
                self.user = DjangoUser.objects.get(username=self.username)
                self.user.set_password(self.password)
                try:
                    self.profile = self.user.get_profile()
                except Exception:
                    User.objects.all().delete()
                    self.user = DjangoUser(username=self.username, password='')
                    self.user.set_password(self.password)
                    self.user.save()
            except DjangoUser.DoesNotExist:
                User.objects.all().delete()
                self.user = DjangoUser(username=self.username, password='')
                self.user.set_password(self.password)
                self.user.save()

            try:
                perspective = Perspective.objects.get(name='default')
            except Perspective.DoesNotExist:
                Perspective.objects.all().delete()
                perspective = Perspective(name='default')
                perspective.set_default_user()
                perspective.save()
            ModuleSetting.set('default_perspective', perspective.id)

            self.folder = KnowledgeFolder(name='test', treepath='test')
            self.folder.set_default_user()
            self.folder.save()

            self.category = KnowledgeCategory(name='test', treepath='test')
            self.category.set_default_user()
            self.category.save()

            self.item = KnowledgeItem(name='test',
                                      folder=self.folder,
                                      category=self.category,
                                      treepath='test')
            self.item.set_default_user()
            self.item.save()

            # parent folder
            self.parent = KnowledgeFolder(name='test', treepath='test')
            self.parent.set_default_user()
            self.parent.save()

            self.client = Client()

            self.prepared = True

    def test_unauthenticated_access(self):
        "Test index page at /api/knowledge/folders"
        response = self.client.get('/api/knowledge/folders')
        # Redirects as unauthenticated
        self.assertEquals(response.status_code, 401)

    def test_get_folders_list(self):
        """ Test index page api/knowledge/folders """
        response = self.client.get(path=reverse('api_knowledge_folders'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_folder(self):
        response = self.client.get(path=reverse(
            'api_knowledge_folders', kwargs={'object_ptr': self.folder.id}),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_update_folder(self):
        updates = {
            'name': 'Api folder update',
            'parent': self.parent.id,
            'details': '<p>api details</p>'
        }
        response = self.client.put(path=reverse(
            'api_knowledge_folders', kwargs={'object_ptr': self.folder.id}),
                                   content_type=self.content_type,
                                   data=json.dumps(updates),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(updates["name"], data["name"])
        self.assertEquals(updates["parent"], data["parent"]["id"])
        self.assertEquals(updates["details"], data["details"])

    def test_get_categories_list(self):
        """ Test index page api/knowledge/categories """
        response = self.client.get(path=reverse('api_knowledge_categories'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_category(self):
        response = self.client.get(path=reverse(
            'api_knowledge_categories',
            kwargs={'object_ptr': self.category.id}),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_update_category(self):
        updates = {
            'name': 'Api catagory update',
            'details': '<p>api details</p>'
        }
        response = self.client.put(path=reverse(
            'api_knowledge_categories',
            kwargs={'object_ptr': self.category.id}),
                                   content_type=self.content_type,
                                   data=json.dumps(updates),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(updates["name"], data["name"])
        self.assertEquals(updates["details"], data["details"])

    def test_get_items_list(self):
        """ Test index page api/knowledge/items """
        response = self.client.get(path=reverse('api_knowledge_items'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_item(self):
        response = self.client.get(path=reverse(
            'api_knowledge_items', kwargs={'object_ptr': self.item.id}),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_update_item(self):
        updates = {
            'name': 'Api item update',
            'folder': self.folder.id,
            'category': self.category.id,
            'body': '<p>api body</p>'
        }
        response = self.client.put(path=reverse(
            'api_knowledge_items', kwargs={'object_ptr': self.item.id}),
                                   content_type=self.content_type,
                                   data=json.dumps(updates),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 400)
Пример #49
0
class SnippetTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.new_url = reverse("snippet_new")

    def valid_form_data(self, **kwargs):
        data = {
            "content": u"Hello Wörld.\n\tGood Bye",
            "lexer": config.LEXER_DEFAULT,
            "expires": config.EXPIRE_DEFAULT,
        }
        if kwargs:
            data.update(kwargs)
        return data

    def test_about(self):
        response = self.client.get(reverse("dpaste_about"))
        self.assertEqual(response.status_code, 200)

    # -------------------------------------------------------------------------
    # New Snippet
    # -------------------------------------------------------------------------
    def test_empty(self):
        """
        The browser sent a content field but with no data.
        """
        # No data
        self.client.post(self.new_url, {})
        self.assertEqual(Snippet.objects.count(), 0)

        data = self.valid_form_data()

        # No content
        data["content"] = ""
        self.client.post(self.new_url, data)
        self.assertEqual(Snippet.objects.count(), 0)

        # Just some spaces
        data["content"] = "   "
        self.client.post(self.new_url, data)
        self.assertEqual(Snippet.objects.count(), 0)

        # Linebreaks or tabs only are not valid either
        data["content"] = "\n\t "
        self.client.post(self.new_url, data)
        self.assertEqual(Snippet.objects.count(), 0)

    def test_new_snippet(self):
        # Simple GET
        response = self.client.get(self.new_url, follow=True)

        # POST data
        data = self.valid_form_data()
        response = self.client.post(self.new_url, data, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 1)
        self.assertContains(response, data["content"])

        # The unicode method contains the snippet id so we can easily print
        # the id using {{ snippet }}
        snippet = Snippet.objects.all()[0]
        self.assertTrue(snippet.secret_id in snippet.__str__())

    def test_new_snippet_custom_lexer(self):
        # You can pass a lexer key in GET.l
        data = self.valid_form_data()
        url = "%s?l=haskell" % self.new_url
        response = self.client.post(url, data, follow=True)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 1)

        # If you pass an invalid key it wont fail and just fallback
        # to the default lexer.
        data = self.valid_form_data()
        url = "%s?l=invalid-lexer" % self.new_url
        response = self.client.post(url, data, follow=True)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 2)

    def test_new_spam_snippet(self):
        """
        The form has a `title` field acting as a honeypot, if its filled,
        the snippet is considered as spam. We let the user know its spam.
        """
        data = self.valid_form_data()
        data["title"] = "Any content"
        response = self.client.post(self.new_url, data, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 0)

    def test_new_snippet_onetime(self):
        """
        One-Time snippets get deleted after two views.
        """
        # POST data
        data = self.valid_form_data()
        data["expires"] = "onetime"

        # First view, the author gets redirected after posting
        response = self.client.post(self.new_url, data, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 1)
        self.assertContains(response, data["content"])

        # Second View, another user looks at the snippet
        response = self.client.get(response.request["PATH_INFO"], follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 1)
        self.assertContains(response, data["content"])

        # Third/Further View, another user looks at the snippet but it was deleted
        response = self.client.get(response.request["PATH_INFO"], follow=True)
        self.assertEqual(response.status_code, 404)
        self.assertEqual(Snippet.objects.count(), 0)

    def test_snippet_notfound(self):
        url = reverse("snippet_details", kwargs={"snippet_id": "abcd"})
        response = self.client.get(url, follow=True)
        self.assertEqual(response.status_code, 404)

    def test_random_slug_generation(self):
        """
        The default slug length is 4 so with 10000 random slug generation we
        will run into duplicates, but those slugs are extended now.
        """
        config.SLUG_LENGTH = 1

        for i in range(0, 100):
            Snippet.objects.create(content="foobar")
        slug_list = Snippet.objects.values_list("secret_id", flat=True).order_by(
            "published"
        )

        # All 1001 Snippets have been created
        self.assertEqual(len(set(slug_list)), 100)

        # There will be a couple of snippets with at least 2 characters
        # in slug length
        extended_snippet = (
            Snippet.objects.extra(select={"length": "Length(secret_id)"})
            .order_by("-length")
            .first()
        )
        self.assertTrue(len(extended_snippet.secret_id) > 1)

        # Set back to default
        config.SLUG_LENGTH = 4

    # -------------------------------------------------------------------------
    # Reply
    # -------------------------------------------------------------------------
    def test_reply(self):
        data = self.valid_form_data()
        response = self.client.post(self.new_url, data, follow=True)
        response = self.client.post(response.request["PATH_INFO"], data, follow=True)
        self.assertContains(response, data["content"])
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 2)

    def test_reply_invalid(self):
        data = self.valid_form_data()
        response = self.client.post(self.new_url, data, follow=True)
        del data["content"]
        response = self.client.post(response.request["PATH_INFO"], data, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 1)

    # -------------------------------------------------------------------------
    # Delete
    # -------------------------------------------------------------------------
    def test_snippet_delete_post(self):
        """
        You can delete a snippet by passing the slug in POST.snippet_id
        """
        data = self.valid_form_data()
        self.client.post(self.new_url, data, follow=True)

        snippet_id = Snippet.objects.all()[0].secret_id
        url = reverse("snippet_details", kwargs={"snippet_id": snippet_id})
        response = self.client.post(url, {"delete": 1}, follow=True)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 0)

    def test_snippet_delete_that_doesnotexist_returns_404(self):
        data = self.valid_form_data()
        self.client.post(self.new_url, data, follow=True)

        url = reverse("snippet_details", kwargs={"snippet_id": "doesnotexist"})
        response = self.client.post(url, {"delete": 1}, follow=True)

        self.assertEqual(response.status_code, 404)
        self.assertEqual(Snippet.objects.count(), 1)

    def test_snippet_delete_do_not_pass_delete_action(self):
        data = self.valid_form_data()
        self.client.post(self.new_url, data, follow=True)

        # Do not pass delete=1
        snippet_id = Snippet.objects.all()[0].secret_id
        url = reverse("snippet_details", kwargs={"snippet_id": snippet_id})
        response = self.client.post(url, {}, follow=True)

        # Returns regular snippet details page
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 1)

    def test_snippet_is_removed_when_expired_and_as_soon_as_fetched(self):
        data = self.valid_form_data()
        self.client.post(self.new_url, data, follow=True)

        # Set the expire time of the snippet to the past.
        s = Snippet.objects.all()[0]
        s.expires = s.expires - timedelta(days=30)
        s.save()

        # Next time its fetched its automatically deleted.
        snippet_id = Snippet.objects.all()[0].secret_id
        url = reverse("snippet_details", kwargs={"snippet_id": snippet_id})
        response = self.client.get(url, follow=True)

        self.assertEqual(response.status_code, 404)
        self.assertEqual(Snippet.objects.count(), 0)

    # -------------------------------------------------------------------------
    # Snippet Functions
    # -------------------------------------------------------------------------
    def test_raw(self):
        data = self.valid_form_data()
        self.client.post(self.new_url, data, follow=True)
        response = self.client.get(
            reverse(
                "snippet_details_raw",
                kwargs={"snippet_id": Snippet.objects.all()[0].secret_id},
            )
        )

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, data["content"])

    def test_slim(self):
        data = self.valid_form_data()
        self.client.post(self.new_url, data, follow=True)
        response = self.client.get(
            reverse(
                "snippet_details_slim",
                kwargs={"snippet_id": Snippet.objects.all()[0].secret_id},
            )
        )

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Hello")

    # -------------------------------------------------------------------------
    # XSS and correct escaping
    # -------------------------------------------------------------------------
    XSS_ORIGINAL = "<script>hello</script>"
    XSS_ESCAPED = "&lt;script&gt;hello&lt;/script&gt;"

    def test_xss_text_lexer(self):
        # Simple 'text' lexer
        data = self.valid_form_data(
            content=self.XSS_ORIGINAL, lexer=config.PLAIN_TEXT_SYMBOL
        )
        response = self.client.post(self.new_url, data, follow=True)
        self.assertContains(response, self.XSS_ESCAPED)

    def test_xss_code_lexer(self):
        # Simple 'code' lexer
        data = self.valid_form_data(
            content=self.XSS_ORIGINAL, lexer=config.PLAIN_CODE_SYMBOL
        )
        response = self.client.post(self.new_url, data, follow=True)
        self.assertContains(response, self.XSS_ESCAPED)

    def test_xss_pygments_lexer(self):
        # Pygments based lexer
        data = self.valid_form_data(content=self.XSS_ORIGINAL, lexer="python")
        response = self.client.post(self.new_url, data, follow=True)
        self.assertContains(response, self.XSS_ESCAPED)

    def test_leading_white_is_retained_in_db(self):
        """
        Leading Whitespace is retained in the db.
        """
        content = " one\n  two\n   three\n    four"
        data = self.valid_form_data(content=content)
        self.client.post(self.new_url, data, follow=True)
        self.assertEqual(Snippet.objects.all()[0].content, content)

    def test_highlighting(self):
        # You can pass any lexer to the pygmentize function and it will
        # never fail loudly.
        PygmentsHighlighter().highlight("code", "python")
        PygmentsHighlighter().highlight("code", "doesnotexist")

    # -------------------------------------------------------------------------
    # History
    # -------------------------------------------------------------------------
    def test_snippet_history(self):
        response = self.client.get(reverse("snippet_history"))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 0)

        data = self.valid_form_data()
        self.client.post(self.new_url, data, follow=True)
        response = self.client.get(reverse("snippet_history"))

        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 1)

    def test_snippet_history_delete_all(self):
        # Empty list, delete all raises no error
        response = self.client.post(
            reverse("snippet_history"), {"delete": 1}, follow=True
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 0)

        # Create two sample pasts
        data = self.valid_form_data()
        self.client.post(self.new_url, data, follow=True)
        data = self.valid_form_data()
        self.client.post(self.new_url, data, follow=True)
        self.assertEqual(Snippet.objects.count(), 2)

        # Delete all of them
        response = self.client.post(
            reverse("snippet_history"), {"delete": 1}, follow=True
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(Snippet.objects.count(), 0)

    # -------------------------------------------------------------------------
    # Management Command
    # -------------------------------------------------------------------------
    def test_delete_management(self):
        # Create two snippets
        data = self.valid_form_data()
        self.client.post(self.new_url, data, follow=True)
        data = self.valid_form_data()
        self.client.post(self.new_url, data, follow=True)
        self.assertEqual(Snippet.objects.count(), 2)

        # But the management command will only remove snippets past
        # its expiration date, so change one to last month
        s = Snippet.objects.all()[0]
        s.expires = s.expires - timedelta(days=30)
        s.save()

        # You can call the management command with --dry-run which will
        # list snippets to delete, but wont actually do.
        management.call_command("cleanup_snippets", dry_run=True)
        self.assertEqual(Snippet.objects.count(), 2)

        # Calling the management command will delete this one
        management.call_command("cleanup_snippets")
        self.assertEqual(Snippet.objects.count(), 1)

    def test_delete_management_snippet_never_expires_not_get_deleted(self,):
        """
        Snippets without an expiration date wont get deleted automatically.
        """
        data = self.valid_form_data()
        data["expires"] = "never"
        self.client.post(self.new_url, data, follow=True)

        self.assertEqual(Snippet.objects.count(), 1)
        management.call_command("cleanup_snippets")
        self.assertEqual(Snippet.objects.count(), 1)
Пример #50
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 = User.objects.create_user('student', '*****@*****.**',
                                                self.password)

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

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

        self.course = CourseFactory.create(
            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'

        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])

    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'])
Пример #51
0
class PermafrostViewTests(TestCase):
    fixtures = ['unit_test']

    def setUp(self):
        self.client = Client()
        self.pf_role = PermafrostRole.objects.create(category="staff", name="Test Role", site=Site.objects.get_current())
        PermafrostRole.objects.create(category="staff", name="Test Role", site=Site.objects.get(pk=2))
        self.super_user = get_user_model().objects.get(pk=1)
        self.client.force_login(self.super_user)

    def test_permafrost_base_url_resolves(self):
        found = resolve("/permafrost/")
        self.assertEqual(found.view_name, "permafrost:role-list")
        self.assertEqual(found.func.view_class, PermafrostRoleListView)
    
    def test_permafrost_manage_base_url_resolves(self):
        found = resolve("/permafrost/manage/")
        self.assertEqual(found.view_name, "permafrost:roles-manage")
        self.assertEqual(found.func.view_class, PermafrostRoleManageView)
    
    def test_permaforst_manage_single_role_object_in_context(self):
        uri = reverse('permafrost:roles-manage')
        response = self.client.get(uri)
        self.assertIn('object', response.context)
        self.assertEqual(response.context['object'], PermafrostRole.on_site.all().first())
    
    def test_manage_permafrost_roles_returns_correct_template(self):
        uri = reverse('permafrost:roles-manage')
        response = self.client.get(uri)
        objects = PermafrostRole.on_site.all()
        default_role = objects.first()
        self.assertTemplateUsed(response, 'permafrost/base.html')
        self.assertTemplateUsed(response, 'permafrost/permafrostrole_manage.html')

    def test_permafrostrole_manage_template_displays_list_of_roles_on_site(self):
        uri = reverse('permafrost:roles-manage')
        import html
        response = self.client.get(uri)
        objects = PermafrostRole.on_site.all()
        
        self.assertTrue(len(objects))
        
        for object in objects:
            self.assertContains(response, html.escape(f'{object}'))
    
    def test_permafrostrole_manage_template_displays_selected_role_details(self):
        uri = reverse('permafrost:roles-manage')
        response = self.client.get(uri)
        default_role = PermafrostRole.on_site.first()  
        self.assertContains(response, f'<h2>{default_role.name}</h2>')
        self.assertContains(response, f'<p>Role Type: <span class="font-weight-bold">{default_role.get_category_display()}</span></p>')
        self.assertContains(response, f'<p>{default_role.description}</p>')

    def test_permafrostrole_manage_template_displays_selected_role_permissions(self):
        ## arrange 
        default_role = PermafrostRole.on_site.first()
        optional_permission = Permission.objects.get_by_natural_key(*('view_permafrostrole', 'permafrost', 'permafrostrole')) 
        default_role.permissions_add(optional_permission)
        ## act
        uri = reverse('permafrost:roles-manage')
        response = self.client.get(uri)
        ## assert
        self.assertEqual(len(default_role.permissions().all()), 2)

        for permission in default_role.permissions().all():
            if permission.id in default_role.all_perm_ids():
                self.assertContains(response, f'{permission.name}')

    def test_permafrostrole_manage_template_hides_selected_role_permissions_not_in_permafrost_categories(self):
        ## arrange 
        default_role = PermafrostRole.on_site.first()
        ## act
        uri = reverse('permafrost:roles-manage')
        response = self.client.get(uri)
        ## assert
        self.assertEqual(len(default_role.permissions().all()), 1)

        for permission in default_role.permissions().all():
            if permission.id not in default_role.all_perm_ids():
                self.assertNotContains(response, f'{permission.name}')

    def test_list_view_returns_roles_on_current_site(self):
        uri = reverse('permafrost:role-list')
        response = self.client.get(uri)
        site_id = get_current_site()

        try:
            roles = response.context['object_list']
            self.assertTrue(all(role.site.id == site_id for role in roles))
        except:
            print("Returned site ids")
            print([role.site.id for role in response.context['object_list']])
            print("")
            pass
        pass
    
    def test_administration_create_url_resolves(self):
        found = resolve("/permafrost/role/create/")
        self.assertEqual(found.view_name, "permafrost:role-create")
        self.assertEqual(found.func.view_class, PermafrostRoleCreateView)
    
    def test_administration_create_url_response_with_correct_template(self):
        url = reverse("permafrost:role-create")
        response = self.client.get(url)
        ## ensure _create.html extends the base template
        self.assertTemplateUsed(response, "permafrost/base.html")
        
        self.assertTemplateUsed(response, "permafrost/permafrostrole_form.html")

    def test_select_role_type_form_renders_on_GET(self):
        url = reverse("permafrost:role-create")
        response = self.client.get(url)
        try:
            self.assertContains(response, "Create Role")
            self.assertContains(response, 'id="role_form"')
            self.assertContains(response, 'name="name"')
            self.assertContains(response, 'name="description"')
            self.assertContains(response, 'name="category"')

            self.assertIsInstance(response.context['form'], SelectPermafrostRoleTypeForm)
        except:
            print("")
            print(response.content.decode())
            raise
    
    def test_role_edit_url_resolves(self):
        found = resolve(f"/permafrost/role/{self.pf_role.slug}/update/")
        self.assertEqual(found.view_name, "permafrost:role-update")
        self.assertEqual(found.func.view_class, PermafrostRoleUpdateView)
    
    def test_administration_edit_url_response_with_correct_template(self):
        url = reverse("permafrost:role-update", kwargs={'slug': self.pf_role.slug})
        response = self.client.get(url)
        ## ensure _create.html extends the base template
        self.assertTemplateUsed(response, "permafrost/base.html")
        
        self.assertTemplateUsed(response, "permafrost/permafrostrole_form.html")
    
    def test_update_role_form_renders_on_GET(self):
        url = reverse("permafrost:role-update",  kwargs={'slug': self.pf_role.slug})
        response = self.client.get(url)
        try:
            self.assertContains(response, "Edit Permissions: Test Role")
            self.assertContains(response, 'id="role_form"')
            self.assertContains(response, 'name="name"')
            self.assertContains(response, 'name="description"')
            self.assertContains(response, 'name="category"')
            self.assertContains(response, 'name="permissions"')
            
            ## add deleted field down the line
            # self.assertContains(response, 'name="deleted"')
            
            self.assertIsInstance(response.context['form'], PermafrostRoleUpdateForm)
        except:
            print("")
            print(response.content.decode())
            raise
    
    def test_role_update_resolves(self):
        found = resolve('/permafrost/role/test-role/update/')
        self.assertEqual(found.view_name, "permafrost:role-update")
        self.assertEqual(found.func.view_class, PermafrostRoleUpdateView)

    def test_role_update_GET_returns_correct_template(self):
        uri = reverse('permafrost:role-update', kwargs={'slug': 'test-role'})
        response = self.client.get(uri)
        self.assertTemplateUsed(response, 'permafrost/base.html')
        self.assertTemplateUsed(response, 'permafrost/permafrostrole_form.html')

    def test_update_form_has_selected_optional_permission(self):
        ## add optional permissions
        self.pf_role.permissions_set(Permission.objects.filter(codename__in=['add_permafrostrole', 'change_permafrostrole']))
        
        uri = reverse('permafrost:role-update', kwargs={'slug': 'test-role'})
        response = self.client.get(uri)
        try:
            self.assertContains(response, """<input 
                                class="ml-auto" 
                                type="checkbox" 
                                name="permissions" 
                                value="37"
                                 checked
                            >""")
            self.assertContains(response, """<input 
                                class="ml-auto" 
                                type="checkbox" 
                                name="permissions" 
                                value="38"
                                 checked
                            >""")
        except:
            print("")
            print(response.content.decode())
            print("")
            raise
    
    def test_role_detail_GET_returns_404_if_not_on_current_site(self):
        uri = reverse('permafrost:role-update', kwargs={'slug': 'administrator'})
        response = self.client.get(uri)
        try:
            self.assertContains(response, "Not Found", status_code=404)
        except:
            print("")
            print(response.content.decode())
            raise

    def test_role_update_POST_updates_name(self):
        uri = reverse('permafrost:role-update', kwargs={'slug': 'test-role'})
        response = self.client.post(uri, data={'name': 'Test Change'}, follow=True)
        self.assertContains(response, "Test Change")
        updated_role = PermafrostRole.objects.get(pk=self.pf_role.pk)
        self.assertEqual(updated_role.name, "Test Change")
    
    def test_role_update_POST_updates_when_no_values_are_changed(self):
        uri = reverse('permafrost:role-update', kwargs={'slug': 'test-role'})
       
        request = RequestFactory().post(uri, data={'name': 'Test Role'}, follow=True)

        request.user = self.super_user
        request.site = Site.objects.get(pk=2)
        response = PermafrostRoleUpdateView.as_view()(request, slug='test-role')
        response.client = self.client
        self.assertRedirects(response, '/permafrost/role/test-role/')
        updated_role = PermafrostRole.objects.get(pk=self.pf_role.pk)

    
    def test_optional_permissions_are_updated_on_POST(self):
        ## ensure role currently has no optional permissions
        allowed_optional_permission_ids =[permission.id for permission in self.pf_role.optional_permissions()]
        current_permission_ids = [permission.id for permission in self.pf_role.permissions().all()]
        current_optional_permission_ids = [id for id in current_permission_ids if id in allowed_optional_permission_ids]
        
        self.assertFalse(current_optional_permission_ids)
        
        uri = reverse('permafrost:role-update', kwargs={'slug': 'test-role'})
        data = model_to_dict(self.pf_role)
        data.update({'permissions': ['37','38']})
        ## listcomp below used to remove 'description': None
        post_data = {k: v for k, v in data.items() if v is not None}
        self.client.post(uri, data=post_data, follow=True)
        
        updated_permission_ids_1 = [permission.id for permission in self.pf_role.permissions().all() if permission.id in allowed_optional_permission_ids]
        
        self.assertEqual(updated_permission_ids_1, [37, 38])
        
        ## remove one permission
        
        data.update({'permissions': ['37']})
        ## listcomp below used to remove 'description': None
        post_data = {k: v for k, v in data.items() if v is not None}
        self.client.post(uri, data=post_data, follow=True)

        updated_permission_ids_2 = [permission.id for permission in self.pf_role.permissions().all() if permission.id in allowed_optional_permission_ids]
        
        self.assertEqual(updated_permission_ids_2, [37])

    def test_optional_permissions_are_removed_when_empty_array_submitted_to_POST(self):
        ## arrange: add optional permissions
        self.pf_role.permissions_set(Permission.objects.filter(codename__in=['add_permafrostrole', 'change_permafrostrole']))
        
        ## ensure optional role count is 2
        allowed_optional_permission_ids =[permission.id for permission in self.pf_role.optional_permissions()]
        current_permission_ids = [permission.id for permission in self.pf_role.permissions().all()]
        current_optional_permission_ids = [id for id in current_permission_ids if id in allowed_optional_permission_ids]
        self.assertEqual(len(current_optional_permission_ids), 2)
        
        uri = reverse('permafrost:role-update', kwargs={'slug': 'test-role'})
        data = model_to_dict(self.pf_role)
        data.update({'optional_staff_perms': []})
        ## iterator below used to remove 'description': None
        data = {k: v for k, v in data.items() if v is not None}
        response = self.client.post(uri, data=data, follow=True)
        
        updated_permission_ids = [permission.id for permission in self.pf_role.permissions().all() if permission.id in allowed_optional_permission_ids]
        try:
            self.assertEqual(updated_permission_ids, [])
        except:
            print("")
            print(response.content.decode())
            print("")
            raise

    def test_delete_role_POST(self):
        uri = reverse('permafrost:role-update', kwargs={'slug': 'test-role'})
        data = model_to_dict(self.pf_role)
        data.update({'deleted': True})
        ## iterator below used to remove 'description': None
        data = {k: v for k, v in data.items() if v is not None}
        response = self.client.post(uri, data=data, follow=True)
        
        try:
            updated_role = PermafrostRole.objects.get(slug=self.pf_role.slug, site__id=1)
            self.assertEqual(updated_role.deleted, True)
        except:
            print("")
            print(model_to_dict(PermafrostRole.objects.get(slug=self.pf_role.slug, site__id=1)))
            print("")
            raise
    
    def test_site_added_on_create_POST(self):
        site = get_current_site()
        data = {
            'name': 'Test Site Role',
            'description': 'Test guaranteed site added on create',
            'category': 'user'
        }
        uri = reverse('permafrost:role-create')
        response = self.client.post(uri , data=data)
        try:
            role = PermafrostRole.objects.get(name='Test Site Role')
            self.assertEqual(role.site.id, site)
        except:
            print("")
            print(response.content.decode())
            print("")
            raise
Пример #52
0
 def test_no_integration_api(self, db):
     url = self.BASE_URL + f"/rasa-conversations/integrations/?domain={TEST_DOMAIN}"
     client = Client()
     response = client.get(url)
     assert response.status_code == 200
     assert response.data == {}
Пример #53
0
 def test_gun_doesnt_exist(self):
     client = Client()
     response = client.get('/guns/7654/')
     self.assertEquals(404, response.status_code)
Пример #54
0
class ZoneTest(TestCase):
    fixtures = ["initial_data"]

    def setUp(self):
        self.client = Client()
        self.client.login(username="******", password="******")

        superzone = Zone.objects.get(name="Haiti")
        zone = Zone(name="zone",
                    superzone=superzone,
                    subzones=["zone"],
                    fountain_price=100,
                    fountain_duration=10,
                    kiosk_price=200,
                    kiosk_duration=12,
                    indiv_base_price=300)
        zone.save()

        superzone.subzones.append(zone.name)
        superzone.save()

        fountain = Element(name="fountain",
                           type=ElementType.FOUNTAIN.name,
                           status=ElementStatus.OK.name,
                           location="fountain",
                           zone=superzone)
        fountain.save()

        user = User.objects.create_user(username="******",
                                        email="*****@*****.**",
                                        password="******",
                                        first_name="test",
                                        last_name="test")
        user.profile.phone_number = None
        user.profile.zone = zone
        user.profile.save()
        my_group = Group.objects.get(name='Gestionnaire de zone')
        my_group.user_set.add(user)

        user = User.objects.create_user(username="******",
                                        email="*****@*****.**",
                                        password="******",
                                        first_name="test",
                                        last_name="test")
        user.profile.phone_number = None
        user.profile.outlets.append(fountain.id)
        user.profile.save()
        my_group = Group.objects.get(name='Gestionnaire de fontaine')
        my_group.user_set.add(user)

    def tearDown(self):
        self.client.logout()

    def test_view_zone(self):
        response = self.client.get("/gestion/")
        self.assertEqual(response.status_code, 200)

    def test_view_zone_not_connected(self):
        self.client.logout()

        response = self.client.get("/gestion/")
        self.assertEqual(response.status_code, 302)

    def test_view_zone_sub(self):
        self.client.login(username="******", password="******")

        response = self.client.get("/gestion/")
        self.assertEqual(response.status_code, 200)

    def test_view_zone_fountain(self):
        self.client.login(username="******", password="******")

        response = self.client.get("/gestion/")
        self.assertEqual(response.status_code, 200)
Пример #55
0
class MainSiteTestCase(TestCase):
    """
    this tests the main functionalities of the site
    to make sure it works appropiately.
    """

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


    def test_login_ok(self):
        """
        tests the login is loading ok
        :return: error if any
        """
        endpoint = 'website:login'
        response = self.client.get(reverse(endpoint))
        self.assertTrue(response.status_code == 200,"There's a problem with your request.")

    def test_post_login(self):
        """
        tries to log in
        :return:
        """
        endpoint = reverse("website:login")
        data = {
            'email': self.user.email,
            'password': self.user._password
        }
        response = self.client.post(path=endpoint,data=data)
        self.assertEqual(response.status_code,302, "The login has failed.")
        self.assertNotIn('Login', response.content.decode(), "You weren't capable of logging in")
        self.assertNotIn('error', response.content.decode(), "You weren't capable of logging in")

    @unittest.expectedFailure
    def test_post_login_fail(self):
        """
        tries to login without credentials
        :return:
        """
        endpoint = reverse("website:login")

        data = {
            'email': "",
            'password': self.user.password
        }
        response = self.client.post(path=endpoint, data=data)
        print(dir(response))
        self.assertIn('error', response.content.decode(), "You weren't capable of logging in")

    @unittest.expectedFailure
    def test_dashboard_access_denied(self):
        endpoint = 'website:dashboard'
        response = self.client.get(reverse(endpoint))
        self.assertTrue('dashboard' in response.url, "There's a problem with your request.")


    def test_objective_listing(self):
        """
        tests the response of the listing items
        :return: error if any
        """
        endpoint = 'http://127.0.0.1:8000/api/handle_objectives/'
        token = Token.objects.get_or_create(user=self.user)[0]
        data = {
            'authtoken': token.key
        }
        response = self.client.get(path=endpoint,data=data, headers={'Autorization': f"Token {token.key}"})
        self.assertEqual(response.status_code,200,
                         f"Error: {response.json()['error'] if 'error' in response.json().keys() else response.json()}")
        self.assertIn('objective_list' , response.json().keys(),"The request was a success but it didn't render the list")



    def test_objective_creation(self):
        """
        tests how the objects are created
        :return: error if any
        """
        endpoint = 'http://127.0.0.1:8000/api/handle_objectives/'
        token = Token.objects.get_or_create(user=self.user)[0]
        data = {
            'authtoken': token.key,
            'goals': json.dumps([1,2,3]),
            'goals_description':['simple goal','simple goal','simple goal'],
            'consecution_percentages':[20,30,50],
            'description':'adding new values for our clients',
            'metric': 'new increases for clients',
            'new_x': 2.0,
        }
        response = self.client.post(path=endpoint, data=data,headers={'Autorization': f"Token {token.key}"})
        self.assertEqual(response.status_code, 200,
                         f"Error: {response.json()['error'] if 'error' in response.json().keys() else response.json()}")


    @unittest.expectedFailure
    def test_objective_creation_fail(self):
        """
        tests how the objects are created
        :return: error if any
        """
        endpoint = 'http://127.0.0.1:8000/api/handle_objectives/'
        token = Token.objects.get_or_create(user=self.user)[0]
        data = {
            'authtoken': token.key,
            'goals': json.dumps([1, 2, 3]),
            'goals_description': json.dumps(['simple goal', 'simple goal', 'simple goal']),
            'consecution_percentages': json.dumps([20, 30]),
            'description': 'adding new values for our clients',
            'metric': 'new increases for clients',
            'new_x': 10.0,

        }
        response = self.client.post(path=endpoint, data=data,headers={'Autorization': f"Token {token.key}"})
        self.assertEqual(response.status_code, 200,
                         f"Error: {response.json()['error'] if 'error' in response.json().keys() else response.json()}")

    @unittest.expectedFailure
    def test_objective_creation_fail_http_method_type(self):
        """
        tests how the objects are created
        :return: error if any
        """
        endpoint = 'http://127.0.0.1:8000/api/handle_objectives/'
        token = Token.objects.get_or_create(user=self.user)[0]
        data = {
            'authtoken': token.key,
            'goals': json.dumps([1, 2, 3]),
            'goals_description': ['simple goal', 'simple goal', 'simple goal'],
            'consecution_percentages': [20, 30, 50],
            'description': 'adding new values for our clients',
            'metric': 'new increases for clients',
            'new_x': 10.0,
        }
        response = self.client.get(path=endpoint, data=data,headers={'Autorization': f"Token {token.key}"})
        self.assertEqual(response.status_code, 200,
                        f"Error: {response.json()['error'] if 'error' in response.json().keys() else response.json()}")

    def test_objective_update(self):
        """
        tests how the objects are created
        :return: error if any
        """
        token = Token.objects.get_or_create(user=self.user)[0]
        objective = Objective.objects.create(metric='new increases for clients',
                                             description='adding new values for our clients')
        endpoint = f'http://127.0.0.1:8000/api/handle_objectives/{objective.id}/'

        goals = [
            {'goal':90.99,
             'consecution_percentage':20.00,
             'description':'test goal'
             },

            {'goal': 300.99,
             'consecution_percentage': 60.00,
             'description': 'test goal'
             },
        ]
        for goal in goals:
            ObjectiveGoal.objects.update_or_create(objective=objective,
                                        goal=goal['goal'],
                                        description=goal['description'],
                                        consecution_percentage=goal['consecution_percentage'])
        data = {
            'authtoken': token.key,
            'goals': json.dumps([g.goal for g in objective.objectivegoal_set.all()]),
            'goals_description': [g.description for g in objective.objectivegoal_set.all()],
            'consecution_percentages': [g.consecution_percentage for g in objective.objectivegoal_set.all()],
            'description': 'adding new values for ourselves',
            'objective_id': objective.id,
            'new_x': 91.0,
            'metric': objective.metric,
        }
        response = self.client.put(path=endpoint, data=data,headers={'Autorization': f"Token {token.key}"})
        self.assertEqual(response.status_code, 200,
                         f"Error: {response.json()['error'] if 'error' in response.json().keys() else response.json()}")


    @unittest.expectedFailure
    def test_objective_update_fail(self):
        """
        tests how the objects are created
        :return: error if any
        """
        endpoint = reverse('website:handle_objective')
        token = Token.objects.get_or_create(user=self.user)[0]
        objective = Objective.objects.create(metric='new increases for clients',
                                             description='adding new values for our clients')
        endpoint = f'http://127.0.0.1:8000/api/handle_objectives/{objective.id}/'

        goals = [
            {'goal': 90.99,
             'consecution_percentage': 20.00,
             'description': 'test goal'
             },

            {'goal': 300.99,
             'consecution_percentage': 60.00,
             'description': 'test goal'
             },
        ]
        for goal in goals:
            ObjectiveGoal.objects.update_or_create(objective=objective,
                                                   goal=goal['goal'],
                                                   description=goal['description'],
                                                   consecution_percentage=goal['consecution_percentage'])
        data = {
            'authtoken': token.key,
            'goals': json.dumps([g['description'] for g in goals]),
            'goals_description': json.dumps([g['description'] for g in goals]),
            'consecution_percentages': json.dumps([1]),
            'description': 'adding new values for ourselves',
            'new_x':10.0,
            'metric': objective.metric,
        }
        response = self.client.post(path=endpoint, data=data,headers={'Autorization': f"Token {token.key}"})
        self.assertEqual(response.status_code, 200,
                         f"Error: {response.json()['error'] if 'error' in response.json().keys() else response.json()}")

    def test_objective_deletion(self):
        """
        tests if the object is removed
        :return: error if any
        """
        token = Token.objects.get_or_create(user=self.user)[0]
        objective = Objective.objects.create(metric='new increases for clients',
                                             description='adding new values for our clients')
        endpoint = f'http://127.0.0.1:8000/api/handle_objectives/{objective.id}/'
        data = {
            'authtoken': token.key,
        }
        response = self.client.delete(endpoint,data=data,headers={'Autorization': f"Token {token.key}"})
        self.assertEqual(response.status_code,200,
                         f"Error: {response.json()['error'] if 'error' in response.json().keys() else response.json()}")


    @unittest.expectedFailure
    def test_objective_deletion_fail(self):
        """
        tests if the object is removed
        :return: error if any
        """
        token = Token.objects.get_or_create(user=self.user)[0]
        objective = Objective.objects.create(metric='new increases for clients',
                                             description='adding new values for our clients')
        endpoint = f'http://127.0.0.1:8000/api/handle_objectives/{objective.id}/'
        data = {
            'authtoken': token.key,
        }
        response = self.client.post(endpoint, data=data,headers={'Autorization': f"Token {token.key}"})
        self.assertEqual(response.status_code, 200,
                         f"Error: {response.json()['error'] if 'error' in response.json().keys() else response.json()}")


    def tearDown(self):
        del self.user
        super().tearDown()
Пример #56
0
class DashboardTest(ModuleStoreTestCase):
    """
    Tests for dashboard utility functions
    """
    def setUp(self):
        super(DashboardTest, self).setUp()
        self.course = CourseFactory.create()
        self.user = UserFactory.create(username="******",
                                       email="*****@*****.**",
                                       password='******')
        self.client = Client()

    @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(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 = SoftwareSecurePhotoVerification.objects.create(
                user=self.user)
            attempt.mark_ready()
            attempt.submit()
            attempt.approve()

        response = self.client.get(reverse('dashboard'))
        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\'re enrolled as a verified student')
        self._check_verification_status_on(
            'honor', 'You\'re enrolled as an honor code student')
        self._check_verification_status_on('audit',
                                           'You\'re auditing this course')

    @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(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 = SoftwareSecurePhotoVerification.objects.create(
                user=self.user)
            attempt.mark_ready()
            attempt.submit()
            attempt.approve()

        response = self.client.get(reverse('dashboard'))
        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',
                                            'You\'re auditing this course')

    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.assertEquals(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_refundable(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,
                                             mode='verified')

        self.assertTrue(enrollment.refundable())

        verified_mode.expiration_datetime = datetime.now(
            pytz.UTC) - timedelta(days=1)
        verified_mode.save()
        self.assertFalse(enrollment.refundable())

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    @patch('courseware.views.log.warning')
    @patch.dict('django.conf.settings.FEATURES',
                {'ENABLE_PAID_COURSE_REGISTRATION': True})
    def test_blocked_course_scenario(self, log_warning):

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

        #create testing invoice 1
        sale_invoice_1 = shoppingcart.models.Invoice.objects.create(
            total_amount=1234.32,
            company_name='Test1',
            company_contact_name='Testw',
            company_contact_email='*****@*****.**',
            customer_reference_number='2Fwe23S',
            recipient_name='Testw_1',
            recipient_email='*****@*****.**',
            internal_reference="A",
            course_id=self.course.id,
            is_valid=False)
        course_reg_code = shoppingcart.models.CourseRegistrationCode(
            code="abcde",
            course_id=self.course.id,
            created_by=self.user,
            invoice=sale_invoice_1,
            mode_slug='honor')
        course_reg_code.save()

        cart = shoppingcart.models.Order.get_cart_for_user(self.user)
        shoppingcart.models.PaidCourseRegistration.add_to_order(
            cart, self.course.id)
        resp = self.client.post(reverse('shoppingcart.views.use_code'),
                                {'code': course_reg_code.code})
        self.assertEqual(resp.status_code, 200)

        redeem_url = reverse('register_code_redemption',
                             args=[course_reg_code.code])
        response = self.client.get(redeem_url)
        self.assertEquals(response.status_code, 200)
        # check button text
        self.assertTrue('Activate Course Enrollment' in response.content)

        #now activate the user by enrolling him/her to the course
        response = self.client.post(redeem_url)
        self.assertEquals(response.status_code, 200)

        response = self.client.get(reverse('dashboard'))
        self.assertIn(
            'You can no longer access this course because payment has not yet been received',
            response.content)
        optout_object = Optout.objects.filter(user=self.user,
                                              course_id=self.course.id)
        self.assertEqual(len(optout_object), 1)

        # Direct link to course redirect to user dashboard
        self.client.get(
            reverse(
                'courseware',
                kwargs={"course_id": self.course.id.to_deprecated_string()}))
        log_warning.assert_called_with(
            u'User %s cannot access the course %s because payment has not yet been received',
            self.user, self.course.id.to_deprecated_string())

        # Now re-validating the invoice
        invoice = shoppingcart.models.Invoice.objects.get(id=sale_invoice_1.id)
        invoice.is_valid = True
        invoice.save()

        response = self.client.get(reverse('dashboard'))
        self.assertNotIn(
            'You can no longer access this course because payment has not yet been received',
            response.content)

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    def test_refundable_of_purchased_course(self):

        self.client.login(username="******", password="******")
        CourseModeFactory.create(course_id=self.course.id,
                                 mode_slug='honor',
                                 min_price=10,
                                 currency='usd',
                                 mode_display_name='honor',
                                 expiration_datetime=datetime.now(pytz.UTC) +
                                 timedelta(days=1))
        enrollment = CourseEnrollment.enroll(self.user,
                                             self.course.id,
                                             mode='honor')

        # TODO: Until we can allow course administrators to define a refund period for paid for courses show_refund_option should be False. # pylint: disable=fixme
        self.assertFalse(enrollment.refundable())

        resp = self.client.post(reverse('student.views.dashboard', args=[]))
        self.assertIn('You will not be refunded the amount you paid.',
                      resp.content)

    @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                         'Test only valid in lms')
    def test_refundable_when_certificate_exists(self):
        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='verified')

        self.assertTrue(enrollment.refundable())

        GeneratedCertificateFactory.create(
            user=self.user,
            course_id=self.course.id,
            status=CertificateStatuses.downloadable,
            mode='verified')

        self.assertFalse(enrollment.refundable())
Пример #57
0
 def get_ticket_response(self):
     c = Client()
     c.login(username=self.user.username, password=self.password)
     response = c.get(reverse('ticket_detail', kwargs={'pk': self.ticket.id}))
     self.assertEqual(response.status_code, 200)
     return response
Пример #58
0
 def test_empty_guns(self):
     client = Client()
     response = client.get('/guns/')
     self.assertIsInstance(response, HttpResponse)
     self.assertEquals(('Content-Type', 'application/json'),
                       response._headers['content-type'])
Пример #59
0
 def test_topic_content_acks_per_user_csv(self):
     c = Client()
     response = c.get(reverse('topic_content_acks_per_user_csv'))
     self.assertEqual(response.status_code, 200)
Пример #60
0
 def test_user_details(self):
     c = Client()
     response = c.get(UserWrapper(self.user).get_absolute_url())
     self.assertEqual(200, response.status_code)
     self.assertEqual(self.ticket, response.context['ticket_list'][0])