Пример #1
0
    def test_request_with_workspace_referer_requires_permission(self):

        client = Client()

        client.login(username='test', password='test')
        response = client.get(self.basic_url, HTTP_HOST='localhost', HTTP_REFERER='http://localhost/test2/workspace')
        self.assertEqual(response.status_code, 403)
Пример #2
0
    def test_sitemap(self):
        """
        Ensures the generated sitemap has correct priorities
        """

        FireDepartment.objects.create(name='testy2', population=2, featured=True)
        FireDepartment.objects.create(name='testy3', population=3)
        FireDepartment.objects.create(name='testy4', population=4)

        c = Client()
        response = c.get('/sitemap.xml')
        self.assertEqual(response.status_code, 200)
        soup = BeautifulSoup(response.content, 'xml')
        sitemap_list = soup.find_all('url')
        self.assertEqual(len(sitemap_list), 3+6)  # 3 test departments and 6 set navigation pages
        # find the three elements
        for testy in sitemap_list:
            if 'testy2' in testy.loc.get_text():
                testy2 = testy
            elif 'testy3' in testy.loc.get_text():
                testy3 = testy
            elif 'testy4' in testy.loc.get_text():
                testy4 = testy
        # assert that testy2 has higher priority than testy4 (because its featured) and 4 has more than 3
        self.assertGreater(float(testy2.priority.get_text()), float(testy4.priority.get_text()))
        self.assertGreater(float(testy4.priority.get_text()), float(testy3.priority.get_text()))
Пример #3
0
class HostHeaderTestCase(TestCase):

    """Testing boot traffic."""

    def test_underscore_host(self):
        """When host is '_'."""
        self.c = Client(HTTP_HOST='_')
        resp = self.c.get('/')
        self.assertEqual(resp.status_code, 302)

    def test_empy_host(self):
        """When host is ''."""
        self.c = Client(HTTP_HOST='')
        resp = self.c.get('/')
        self.assertEqual(resp.status_code, 302)

    def test_oddchar_host(self):
        """When host is ''."""
        self.c = Client(HTTP_HOST='$')
        resp = self.c.get('/')
        self.assertEqual(resp.status_code, 302)

    def test_wildcard_host(self):
        """When host is ''*.live.akvo-ops.org"""
        self.c = Client(HTTP_HOST='*.live.akvo-ops.org')
        resp = self.c.get('/')
        self.assertEqual(resp.status_code, 302)
Пример #4
0
class WebhooksGET_TestCase(TestCase):

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

    def _get_query(self, challenge='test challenge',
                   mode='subscribe',
                   token=settings.FACEBOOK_WEBHOOK_TOKEN):
        return {
            'hub.mode': mode,
            'hub.verify_token': token,
            'hub.challenge': challenge
        }

    def test_verification_ok(self):
        url = reverse('webhooks', )
        challenge = 'get OK test challenge'
        response = self.client.get(url, self._get_query(challenge=challenge))
        self.assertEqual(response.status_code, 200)
        # must return the challange
        self.assertEqual(response.content, challenge)

    def test_verification_fail_with_invalid_params(self):
        url = reverse('webhooks', )
        response = self.client.get(url, )
        self.assertEqual(response.status_code, 400)

    def test_verification_fail_with_wrong_token(self):
        url = reverse('webhooks', )
        response = self.client.get(url, self._get_query(token='false token'))
        # must fail with invalid token
        self.assertEqual(response.status_code, 400)
Пример #5
0
    def get_logged_in_client(self, username=None, password=None):
        if not username: username = self.TEST_USERNAME
        if not password: password = self.TEST_PASSWORD

        client = Client()
        client.login(username=username, password=password)
        return client
Пример #6
0
class PhotoTestCase(TestCase):

    maxDiff = None
    fixtures = ['main/tests/fixtures/competitions.yaml', 'main/tests/fixtures/prizes.yaml',
                'main/tests/fixtures/votes.yaml',
                'main/tests/fixtures/winners.yaml',]


    def test_history_clean(self):
        u = MyUser.objects.get(email='test1@mail.ru')
        self.assertTrue(u.is_active)
        self.assertTrue(u.check_password("1"))

        self.c = Client()
        response = self.c.post('/api/v1/auth/login/', {'email': 'test1@mail.ru', 'password': '1'})
        self.assertEquals(response.status_code, 200)

        response = self.c.get('/api/v1/photos/?competition_id=1')
        photos = json.loads(response.content)['results']
        self.assertEqual(len(photos), 1)

        response = self.c.get('/api/v1/competitions/1/clean_view_history/')

        response = self.c.get('/api/v1/photos/?competition_id=1')
        photos = json.loads(response.content)['results']
        self.assertEqual(len(photos), 3)
Пример #7
0
    def test_activate(self):
        c = Client()

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

        response = c.post('/signup/activate/', {'ps1_email': 'J.R.Hacker@example.com'}, follow=True)
        self.assertEqual(response.status_code, 200)

        # "read" email
        token = self.get_token()
        activation_url = '/signup/activate/confirm/{}'.format(token.token)
        response = c.get(activation_url)
        self.assertEqual(response.status_code, 200)
        
        post_data = {
            'preferred_username': 'jay',
            'first_name': 'Jay',
            'last_name': 'Hacker',
            'preferred_email': 'J.R.Hacker@example.com',
            'token': token.token,
        }
        response = c.post(activation_url, post_data, follow=True)
        self.assertEqual(response.status_code, 200)

        jay = Person.objects.get(pk=self.person.pk)
        self.assertIsNotNone(jay.user)
        PS1User.objects.delete_user(jay.user)
Пример #8
0
 def test_editor_tour_renders(self):
     """
     Ensure the editor tour view renders.
     """
     c = Client()
     response = c.get(reverse('editor_tour'))
     self.assertEqual(response.status_code, 200)
Пример #9
0
 def setUp(self):
     self.jpg = VersatileImageTestModel.objects.get(img_type='jpg')
     self.png = VersatileImageTestModel.objects.get(img_type='png')
     self.gif = VersatileImageTestModel.objects.get(img_type='gif')
     self.delete_test = VersatileImageTestModel.objects.get(
         img_type='delete_test'
     )
     self.widget_test = VersatileImageWidgetTestModel.objects.get(pk=1)
     password = '12345'
     user = User.objects.create_user(
         username='test',
         email='test@test.com',
         password=password
     )
     user.is_active = True
     user.is_staff = True
     user.is_superuser = True
     user.save()
     client = Client()
     login = client.login(
         username='test',
         password=password
     )
     self.assertTrue(login)
     self.user = user
     self.client = client
Пример #10
0
class SearchTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        home_url = urlresolvers.reverse('catalog_home')
        response = self.client.get(home_url)
        self.failUnless(response.status_code, httplib.OK)

    def test_html_escaped(self):
        """ search text displayed on results page is HTML-encoded """
        search_term = '<script>alert(xss)</script>'
        search_url = urlresolvers.reverse('search_results')
        search_request = search_url + '?q=' + search_term
        response = self.client.get(search_request)
        self.failUnlessEqual(response.status_code, httplib.OK)
        escaped_term = html.escape(search_term)
        self.assertContains(response, escaped_term)
    def test_RI(self):
        """ search text displayed on results page is HTML-encoded """
        search_term = 'RI'
        search_url = urlresolvers.reverse('search_results')
        search_request = search_url + '?q=' + search_term
        response = self.client.get(search_request)
        self.assertContains(response, 'Warwick')

    def test_MA(self):
        """ search text displayed on results page is HTML-encoded """
        search_term = 'MA'
        search_url = urlresolvers.reverse('search_results')
        search_request = search_url + '?q=' + search_term
        response = self.client.get(search_request)
        self.assertContains(response, 'Boston')
Пример #11
0
 def test_photo_view(self):
     photo = Photo.objects.all()[0]
     c = Client()
     c.login(username='user1', password='user1_password')
     response = c.get('/images/photos/{}/'.format(photo.id))
     self.assertIn(photo.title, response.content)
     self.assertIn(photo.description, response.content)
Пример #12
0
    def test_cookies(self):

        client = Client()
        client.login(username='test', password='test')
        client.cookies[str('test')] = 'test'

        def cookie_response(method, url, *args, **kwargs):
            if 'Cookie' in kwargs['headers']:
                return {'content': kwargs['headers']['Cookie'], 'headers': {'Set-Cookie': 'newcookie1=test; path=/, newcookie2=val1; path=/abc/d, newcookie3=c'}}
            else:
                return {'status_code': 404}

        self.network._servers['http']['example.com'].add_response('GET', '/path', cookie_response)
        response = client.get(self.basic_url, HTTP_HOST='localhost', HTTP_REFERER='http://localhost/test/workspace')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.read_response(response), b'test=test')

        self.assertTrue('newcookie1' in response.cookies)
        self.assertEqual(response.cookies[str('newcookie1')].value, 'test')
        cookie_path = reverse('wirecloud|proxy', kwargs={'protocol': 'http', 'domain': 'example.com', 'path': '/'})
        self.assertEqual(response.cookies[str('newcookie1')]['path'], cookie_path)

        self.assertTrue('newcookie2' in response.cookies)
        self.assertEqual(response.cookies[str('newcookie2')].value, 'val1')
        cookie_path = reverse('wirecloud|proxy', kwargs={'protocol': 'http', 'domain': 'example.com', 'path': '/abc/d'})
        self.assertEqual(response.cookies[str('newcookie2')]['path'], cookie_path)

        self.assertTrue('newcookie3' in response.cookies)
        self.assertEqual(response.cookies[str('newcookie3')].value, 'c')
        cookie_path = reverse('wirecloud|proxy', kwargs={'protocol': 'http', 'domain': 'example.com', 'path': '/path'})
        self.assertEqual(response.cookies[str('newcookie3')]['path'], cookie_path)
Пример #13
0
    def test_basic_proxy_requests_from_proxied_content(self):

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

        proxied_url = 'http://localhost' + reverse('wirecloud|proxy', kwargs={'protocol': 'http', 'domain': 'example.com', 'path': '/path'})
        self.check_basic_requests(client, proxied_url)
Пример #14
0
    def test_basic_proxy_requests_from_widget(self):

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

        widget_url = reverse('wirecloud.widget_code_entry', kwargs={"vendor": "Wirecloud", "name": "Test", "version": "1.0"})
        self.check_basic_requests(client, 'http://localhost' + widget_url)
 def setUp(self):
     self.csrf_client = Client(enforce_csrf_checks=True)
     self.non_csrf_client = Client(enforce_csrf_checks=False)
     self.username = 'john'
     self.email = 'lennon@thebeatles.com'
     self.password = 'password'
     self.user = User.objects.create_user(self.username, self.email, self.password)
Пример #16
0
class StudentsDetailTest(TestCase):
	def setUp(self):
		self.client = Client()
		insert_student()

	def test_detail_page_student(self):
		response = self.client.get('/students/1/')
		self.assertEqual(response.status_code, 200)
		self.assertTemplateUsed(response, 'students/student_detail.html')

	def test_mail_check_student(self):
		response = self.client.get('/students/1/')
		self.assertContains(response, 'test1@test.com')

	def test_course_check_student(self):
		response = self.client.get('/students/1/')
		self.assertContains(response, 'Python/Django')
		self.assertContains(response, '/courses/1/')

	def test_skype_check_student(self):
		response = self.client.get('/students/1/')
		self.assertContains(response, 'test1')

	def test_phone_check_student(self):
		response = self.client.get('/students/1/')
		self.assertContains(response, '099-999-99-99')
class TestURNSubmissionFailureMessage(TestCase):
    def setUp(self):
        self.court = Court.objects.create(
            court_code="0000",
            region_code="06",
            court_name="test court",
            court_address="test address",
            court_telephone="0800 MAKEAPLEA",
            court_email="court@example.org",
            submission_email="court@example.org",
            plp_email="plp@example.org",
            enabled=True,
            display_case_data=True,
            validate_urn=True,
            test_mode=False)

        self.case = Case.objects.create(
            urn="06YY0000000",
            imported=True
        )

        self.client = Client()

    def test_single_failure_no_message(self):
        response = self.client.post('/plea/enter_urn/', data=dict(urn="06xx0000000"))

        self.assertContains(response, "You need to fix the errors on this page before continuing.")
        self.assertNotContains(response, "Your reference number has not been recognised")

    def test_message_appears_after_multiple_failures(self):

        for i in range(3):
            response = self.client.post('/plea/enter_urn/', data=dict(urn="06xx0000000"))

        self.assertContains(response, "Your reference number has not been recognised")
Пример #18
0
 def get_logged_in_trudy_client(self):
     client = Client()
     client.login(
         username=TEST_USER_USERNAME2,
         password=TEST_USER_PASSWORD2
     )
     return client
Пример #19
0
    def skip_test_should_service_authenticated_user(self):
        c = Client()
        c.login(username='developer1', password='top_secret')

        response = c.get(reverse('scrumboard:item_create'))

        assert response.status_code == 200
Пример #20
0
class HomePageViewTest(BaseTest):

    def setUp(self):
        self.client = Client()
        self.user, self.country = self.create_user_with_no_permissions()
        self.assign('can_submit_responses', self.user)
        self.client.login(username=self.user.username, password='pass')

    def test_get(self):
        response = self.client.get("/")
        self.assertEqual(200, response.status_code)
        templates = [template.name for template in response.templates]
        self.assertIn('home/index.html', templates)

    def test_homepage_redirects_to_first_section_of_first_questionnaire_if_any_if_logged_in_as_data_submitter(self):
        questionnaire = Questionnaire.objects.create(name="JRF", description="bla")
        section = Section.objects.create(title="section", order=1, questionnaire=questionnaire, name="section")
        Section.objects.create(title="section", order=2, questionnaire=questionnaire, name="section")

        response = self.client.get("/")
        expected_url = "/questionnaire/entry/%d/section/%d/" % (questionnaire.id, section.id)
        self.assertRedirects(response, expected_url=expected_url)

    def test_login_required_for_home_get(self):
        self.assert_login_required('/')
Пример #21
0
class WebhooksPOST_TestCase(TestCase):

    def setUp(self):
        self.client = Client()
        factories.models.User.update_friends = Mock()

    def tearDown(self):
        factories.models.User.update_friends = origin_update_friends

    def _get_body(self, obj='user', entry={'id': -1}):
        return dumps({
            'object': obj,
            'entry': [entry]
        })

    def _get_signature(self, body):
        key = settings.SOCIAL_AUTH_FACEBOOK_SECRET
        return "sha1={}".format(hmac.new(key, body, sha1).hexdigest())

    def test_update_ok(self):
        user = factories.UsersFactory.create()
        body = self._get_body(entry={'id': user.uid})

        signature = self._get_signature(body)

        url = reverse('webhooks', )
        response = self.client.post(url, body,
                                    content_type="application/json",
                                    **{'HTTP_X_HUB_SIGNATURE': signature})
        self.assertEqual(response.content, 'Ok')
        self.assertEqual(response.status_code, 200)
        self.assertTrue(user.update_friends.called)

    def test_update_fails_with_wrong_body(self):
        body = self._get_body(obj='wrong object')
        url = reverse('webhooks', )
        response = self.client.post(url, body, content_type="application/json")
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content, 'Invalid webhook')

    def test_update_fails_with_wrong_uid(self):
        body = self._get_body()
        url = reverse('webhooks', )
        signature = self._get_signature(body)
        response = self.client.post(url, body,
                                    content_type="application/json",
                                    **{'HTTP_X_HUB_SIGNATURE': signature})
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content, 'Invalid user id')

    def test_update_fails_with_wrong_signature(self):
        user = factories.UsersFactory.create()
        body = self._get_body(entry={'id': user.uid})
        url = reverse('webhooks', )
        response = self.client.post(url, body,
                                    content_type="application/json",
                                    **{'HTTP_X_HUB_SIGNATURE': 'sha1=invalid'})
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content, 'Invalid signature')
        self.assertFalse(user.update_friends.called)
Пример #22
0
    def test_do_pagination(self):
        # get first page for not giving integer as page number
        c = Client()
        response = c.get('/?page=bad_page_number')
        self.assertTrue(b'Proyectos de Ley' in response.content)

        # user gives empty page
        response = c.get('/?page=')
        self.assertTrue(b'Proyectos de Ley' in response.content)

        # user gives empty page
        response = c.get('/?page=100')
        self.assertTrue(b'Proyectos de Ley' in response.content)

        # user gives pagination more than 20
        entries = []
        j = 1
        for i in self.dummy_items:
            i['id'] = j
            entries.append(Proyecto(**i))
            j += 1
        Proyecto.objects.bulk_create(entries)
        response = c.get('/?page=21')
        self.assertFalse(b'/?page=10' in response.content)
        self.assertTrue(b'/?page=22' in response.content)
Пример #23
0
 def test_post_user_check_result_false(self):
     client = Client()
     client.post(
         '/users_check/', {'id_user_1': 123, 'id_user_2': 3}
     )
     self.assertEqual('res' in client._session().keys(), True)
     self.assertEqual(False in client._session().values(), True)
Пример #24
0
 def test_simple_redirect(self):
     client = Client()
     endpoint = reverse("utm-redirect-pk", kwargs={"pk": self.test_obj.id})
     response = client.get(endpoint)
     self.assertEqual(response.status_code, 301)
     parsed = urlparse.urlparse(response["Location"])
     self.assertEqual(parsed.path, self.test_obj.get_absolute_url())
Пример #25
0
class SmokeTest(TestCase):

    def setUp(self):
        self.client = Client()
        self.user = User.objects.create(username="chipy",)
        self.sponsor = Sponsor.objects.create(
            slug="chipy",
            name="Chipy"
        )

    def test__sponsor_detail__GET(self):
        # SETUP

        # TEST
        response = self.client.get(
            reverse_lazy('sponsor_detail', args=[self.sponsor.slug]), follow=True)

        # CHECK
        self.assertEqual(response.status_code, 200)

    def test__sponsor_list__GET(self):
        # SETUP

        # TEST
        response = self.client.get(
            reverse_lazy('sponsor_list'), follow=True)

        # CHECK
        self.assertEqual(response.status_code, 200)
 def test_token_login_form(self):
     """Ensure token login view using form POST works."""
     client = Client(enforce_csrf_checks=True)
     response = client.post('/auth-token/',
                            {'username': self.username, 'password': self.password})
     self.assertEqual(response.status_code, 200)
     self.assertEqual(json.loads(response.content)['token'], self.key)
Пример #27
0
 def test_rechazar_solicitud(self):
     c = Client()
     c.login(username='super', password='super')
     url = reverse('solicitudCambio.views.rechazar_solicitud', args=[self.solicitud.id])
     response = c.get(url)
     url_retorno = reverse('solicitudCambio.views.listar_solicitudes')
     self.assertRedirects(response, url_retorno)
class BasicAuthTests(TestCase):
    """Basic authentication"""
    urls = 'rest_framework.tests.authentication'

    def setUp(self):
        self.csrf_client = Client(enforce_csrf_checks=True)
        self.username = 'john'
        self.email = 'lennon@thebeatles.com'
        self.password = 'password'
        self.user = User.objects.create_user(self.username, self.email, self.password)

    def test_post_form_passing_basic_auth(self):
        """Ensure POSTing json over basic auth with correct credentials passes and does not require CSRF"""
        auth = 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password)).strip()
        response = self.csrf_client.post('/basic/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
        self.assertEqual(response.status_code, 200)

    def test_post_json_passing_basic_auth(self):
        """Ensure POSTing form over basic auth with correct credentials passes and does not require CSRF"""
        auth = 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password)).strip()
        response = self.csrf_client.post('/basic/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth)
        self.assertEqual(response.status_code, 200)

    def test_post_form_failing_basic_auth(self):
        """Ensure POSTing form over basic auth without correct credentials fails"""
        response = self.csrf_client.post('/basic/', {'example': 'example'})
        self.assertEqual(response.status_code, 401)

    def test_post_json_failing_basic_auth(self):
        """Ensure POSTing json over basic auth without correct credentials fails"""
        response = self.csrf_client.post('/basic/', json.dumps({'example': 'example'}), 'application/json')
        self.assertEqual(response.status_code, 401)
        self.assertEqual(response['WWW-Authenticate'], 'Basic realm="api"')
class AnonymousUserViewingThePages(TestCase):
    def setUp(self):
        from django.test import Client
        self.client = Client()
    def test_homepage(self):
        home = self.client.get("/")
        self.assertEqual(home.status_code,200)
    def test_help_all_items(self):
        response = self.client.get(reverse('aristotle:about_all_items'))
        self.assertEqual(response.status_code,200)
    def test_visible_item(self):
        wg = models.Workgroup.objects.create(name="Setup WG")
        ra = models.RegistrationAuthority.objects.create(name="Test RA")
        wg.registrationAuthorities.add(ra)
        item = models.ObjectClass.objects.create(name="Test OC",workgroup=wg)
        s = models.Status.objects.create(
                concept=item,
                registrationAuthority=ra,
                registrationDate=timezone.now(),
                state=ra.locked_state
                )
        home = self.client.get(url_slugify_concept(item))
        #Anonymous users requesting a hidden page will be redirected to login
        self.assertEqual(home.status_code,302)
        s.state = ra.public_state
        s.save()
        home = self.client.get(url_slugify_concept(item))
        self.assertEqual(home.status_code,200)
Пример #30
0
    def test_upload(self):
        """Can we create an image on the filestore?"""
        username, user = _make_user()
        c = Client()

        with open(UPLOAD_FILE) as photo_fd:
            response = c.post("/umedia/", {
                    "title": "a picture of me I just took",
                    "photo": photo_fd
                    })
            self.assertEquals(302, response.status_code)
            parsed = urlparse.urlparse(response["Location"])
            self.assertEquals(parsed.path, settings.LOGIN_URL)

        # Now login
        loggedin = c.login(username=username, password="secret")
        self.assertTrue(loggedin)
        with open(UPLOAD_FILE) as photo_fd:
            response = c.post("/umedia/", {
                    "title": "a picture of me I just took",
                    "photo": photo_fd
                    })
            self.assertEquals(201, response.status_code)

            # What's the url
            parsed = urlparse.urlparse(response["Location"])

            # Check we've got the correct file type
            self.assertEquals(os.path.splitext(parsed.path)[1][1:], "jpg")
            
            # Check that is starts with something under the MEDIA_DOMAIN
            self.assertEquals(
                settings.MEDIA_DOMAIN, 
                ".".join(parsed.netloc.split(".")[2:])
                )