示例#1
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="******")
        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:])
                )
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)
示例#3
0
 def test_rechazar_solicitud(self):
     c = Client()
     c.login(username='******', password='******')
     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)
示例#4
0
    def test_request_with_workspace_referer_requires_permission(self):

        client = Client()

        client.login(username='******', password='******')
        response = client.get(self.basic_url, HTTP_HOST='localhost', HTTP_REFERER='http://localhost/test2/workspace')
        self.assertEqual(response.status_code, 403)
示例#5
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)
示例#6
0
class SmokeTest(TestCase):

    def setUp(self):
        self.client = Client()
        self.user = User.objects.create(username="******",)
        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)
示例#7
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()))
示例#8
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)
示例#9
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
示例#10
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)
示例#11
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)
示例#12
0
    def skip_test_should_service_authenticated_user(self):
        c = Client()
        c.login(username='******', password='******')

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

        assert response.status_code == 200
示例#13
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': '*****@*****.**'}, 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': '******',
            'first_name': 'Jay',
            'last_name': 'Hacker',
            'preferred_email': '*****@*****.**',
            '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)
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="*****@*****.**",
            submission_email="*****@*****.**",
            plp_email="*****@*****.**",
            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")
示例#15
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='*****@*****.**')
        self.assertTrue(u.is_active)
        self.assertTrue(u.check_password("1"))

        self.c = Client()
        response = self.c.post('/api/v1/auth/login/', {'email': '*****@*****.**', 'password': '******'})
        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)
class BasicAuthTests(TestCase):
    """Basic authentication"""
    urls = 'rest_framework.tests.authentication'

    def setUp(self):
        self.csrf_client = Client(enforce_csrf_checks=True)
        self.username = '******'
        self.email = '*****@*****.**'
        self.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"')
 def setUp(self):
     self.csrf_client = Client(enforce_csrf_checks=True)
     self.non_csrf_client = Client(enforce_csrf_checks=False)
     self.username = '******'
     self.email = '*****@*****.**'
     self.password = '******'
     self.user = User.objects.create_user(self.username, self.email, self.password)
示例#18
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())
 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)
示例#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='******')

    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
    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)
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, '*****@*****.**')

	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')
示例#23
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)
示例#24
0
文件: tests.py 项目: seshaa/test
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')
示例#25
0
 def test_photo_view(self):
     photo = Photo.objects.all()[0]
     c = Client()
     c.login(username='******', password='******')
     response = c.get('/images/photos/{}/'.format(photo.id))
     self.assertIn(photo.title, response.content)
     self.assertIn(photo.description, response.content)
示例#26
0
    def test_basic_proxy_requests_from_proxied_content(self):

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

        proxied_url = 'http://localhost' + reverse('wirecloud|proxy', kwargs={'protocol': 'http', 'domain': 'example.com', 'path': '/path'})
        self.check_basic_requests(client, proxied_url)
示例#27
0
    def test_cookies(self):

        client = Client()
        client.login(username='******', password='******')
        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)
示例#28
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 = '******'
     user = User.objects.create_user(
         username='******',
         email='*****@*****.**',
         password=password
     )
     user.is_active = True
     user.is_staff = True
     user.is_superuser = True
     user.save()
     client = Client()
     login = client.login(
         username='******',
         password=password
     )
     self.assertTrue(login)
     self.user = user
     self.client = client
示例#29
0
    def test_basic_proxy_requests_from_widget(self):

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

        widget_url = reverse('wirecloud.widget_code_entry', kwargs={"vendor": "Wirecloud", "name": "Test", "version": "1.0"})
        self.check_basic_requests(client, 'http://localhost' + widget_url)
示例#30
0
 def get_logged_in_trudy_client(self):
     client = Client()
     client.login(
         username=TEST_USER_USERNAME2,
         password=TEST_USER_PASSWORD2
     )
     return client
示例#31
0
 def setUp(self):
     self.client = Client()
     self.password = '******'
     self.user = UserFactory(username='******', password=self.password)
示例#32
0
 def test_invalid_flight_page(self):
     max_id = Flight.objects.all().aggregate(Max("id"))["id__max"]
     c = Client()
     response = c.get(f"/{max_id + 1}")
     self.assertEqual(response.status_code, 404)
示例#33
0
class One(base.BaseCase):
    def setUp(self):
        self.c = Client()

        # additionalFiles
        #self.msid = 21393
        #self.status = 'poa'
        # self.ajson_fixture_api1 = join(self.fixture_dir, 'v12', 'api1', 'elife-21393-v1.xml.json') # poa, v1
        # self.ajson_fixture_api2 = join(self.fixture_dir, 'v12', 'api2', 'elife-21393-v1.xml.json') # poa, v1
        self.msid = 27134
        self.status = 'vor'
        self.ajson_fixture_api1 = join(self.fixture_dir, 'v12', 'api1', 'elife-27134-v2.xml.json') # vor, v2
        self.ajson_fixture_api2 = join(self.fixture_dir, 'v12', 'api2', 'elife-27134-v2.xml.json') # vor, v2

        self.ajson_api1 = self.load_ajson2(self.ajson_fixture_api1)
        self.ajson_api2 = self.load_ajson2(self.ajson_fixture_api2)

        # what has a good representation of the other elements we want to target?

    def tearDown(self):
        pass

    def test_all(self):
        v1, v2, v12 = 1, 2, 12

        cases = [
            # content, request, response
            #(v1, v1, v1),
            #(v1, v2, v2),

            (v2, v1, v1),
            (v2, v2, v2),

            #(v1, v12, v2),
            (v2, v12, v2),
        ]

        content_idx = {
            v1: self.ajson_fixture_api1,
            v2: self.ajson_fixture_api2
        }

        request_idx = {
            v1: 'application/vnd.elife.article-poa+json; version=1',
            v2: 'application/vnd.elife.article-poa+json; version=2',
            v12: 'application/vnd.elife.article-poa+json; version=1, application/vnd.elife.article-poa+json; version=2',
        }

        response_idx = {
            v1: self.ajson_api1,
            v2: self.ajson_api2
        }

        schema_idx = {
            v1: settings.ALL_SCHEMA_IDX[self.status][1][1],
            v2: settings.ALL_SCHEMA_IDX[self.status][0][1],
        }

        for ckey, rqkey, rskey in cases:
            content = content_idx[ckey]
            request = request_idx[rqkey]
            response = response_idx[rskey]

            name = ' '.join(map(str, [ckey, rqkey, rskey]))
            # print(name)
            with self.subTest(name):
                try:
                    # Lax needs a v1 before a v2 can be published
                    self.add_or_update_article(**{
                        'manuscript_id': self.msid,
                        'version': 1,
                        'published': '2017-07-11T00:00:00Z'
                    })

                    self.publish_ajson(content)
                    actual_resp = self.c.get(reverse('v2:article', kwargs={'id': self.msid}), HTTP_ACCEPT=request)
                    self.assertEqual(actual_resp.status_code, 200)
                    # response is valid
                    self.assertTrue(utils.validate(actual_resp.json(), schema_idx[rskey]))
                    # response is equal to what we're expecting
                    actual_json = self.load_ajson2(actual_resp.json())
                    # slightly more isolated error messages
                    self.assertEqual(actual_json.keys(), response.keys())
                    for key in response.keys():
                        self.assertEqual(actual_json.get(key), response.get(key))

                finally:
                    models.Article.objects.all().delete()

    # deprecation notice

    def test_v1_requests_deprecation_notice_present(self):
        v1_only = 'application/vnd.elife.article-poa+json; version=1'
        resp = self.c.get(reverse('v2:article', kwargs={'id': self.msid}), HTTP_ACCEPT=v1_only)
        self.assertEqual(resp['warning'], "Deprecation: Support for version 1 will be removed")

    def test_v2_requests_deprecation_notice_absent(self):
        v2_only = 'application/vnd.elife.article-poa+json; version=2'
        resp = self.c.get(reverse('v2:article', kwargs={'id': self.msid}), HTTP_ACCEPT=v2_only)
        self.assertFalse(resp.has_header('warning'))

    def test_requests_deprecation_notice_absent(self):
        v1_only = 'application/vnd.elife.article-poa+json; version=1'
        resp = self.c.get(reverse('v2:article-list'), HTTP_ACCEPT=v1_only)
        self.assertEqual(resp['warning'], "Deprecation: Support for version 1 will be removed")
示例#34
0
 def setUp(self):
     self.client = Client()
     self.profiles_url = reverse('profiles')
 def setUp(self):
     self.client = Client()
     self.user = get_user_model().objects.create_user("zoidberg")
class ViewTests(TransactionTestCase):
    """Test the end-to-end use of tokens.

    These tests specifically confirm the way in which request and session tokens
    deal with repeated requests.

    """
    def setUp(self):
        self.client = Client()
        self.user = get_user_model().objects.create_user("zoidberg")

    def test_request_token(self):
        """Test the request tokens only set the user for a single request."""
        token = RequestToken.objects.create_token(
            scope="foo",
            max_uses=2,
            user=self.user,
            login_mode=RequestToken.LOGIN_MODE_REQUEST,
        )
        response = self.client.get(get_url("decorated", token))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.request_user, self.user)
        self.assertEqual(RequestTokenLog.objects.count(), 1)

        response = self.client.get(get_url("undecorated", None))
        self.assertEqual(response.status_code, 200)
        self.assertIsInstance(response.request_user, AnonymousUser)
        self.assertEqual(RequestTokenLog.objects.count(), 1)

    def test_session_token(self):
        """Test that session tokens set the user for all requests."""
        token = RequestToken.objects.create_token(
            scope="foo",
            max_uses=1,
            user=self.user,
            login_mode=RequestToken.LOGIN_MODE_SESSION,
            expiration_time=(datetime.now() +
                             timedelta(minutes=JWT_SESSION_TOKEN_EXPIRY)),
        )

        response = self.client.get(get_url("decorated", token))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.request_user, self.user)
        self.assertEqual(RequestTokenLog.objects.count(), 1)

        # for a session token, all future requests should also be authenticated
        response = self.client.get(get_url("undecorated", None))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.request_user, self.user)
        self.assertEqual(RequestTokenLog.objects.count(), 1)

    def test_get_post_token(self):
        """Test the GET > POST chain."""
        token = RequestToken.objects.create_token(
            scope="bar", login_mode=RequestToken.LOGIN_MODE_NONE, max_uses=100)
        # expiry not set - we will do that explicitly in the POST
        self.assertTrue(token.expiration_time is None)
        # this is the output from the {% request_token %} tag
        html = request_token({"request_token": token.jwt()})

        # initial GET - mark token as used, do not expire
        response = self.client.get(get_url("roundtrip", token))
        self.assertContains(response, html, status_code=200)
        token.refresh_from_db()
        self.assertTrue(token.expiration_time is None)
        self.assertEqual(token.used_to_date, 1)

        # now re-post the token to the same URL - equivalent to POSTing the form
        response = self.client.post(get_url("roundtrip", None),
                                    {JWT_QUERYSTRING_ARG: token.jwt()})
        # 201 is a sentinel status_code so we know that the form has been processed
        self.assertContains(response, "OK", status_code=201)
        token.refresh_from_db()
        # token has been forcibly expired
        self.assertFalse(token.expiration_time is None)
        self.assertTrue(token.expiration_time < tz_now())
        self.assertEqual(token.used_to_date, 2)
示例#37
0
 def setUp(self):
     # Todo test necesita un cliente.
     self.client = Client()
示例#38
0
 def setUp(self):
     self.client = Client()
示例#39
0
class TestCreatePlayerTestCase(TestCase):
    def setUp(self):
        self.team = TeamFactory()
        self.user_password = '******'
        self.user = UserFactory(password=self.user_password)
        self.client = Client()
        self.client.login(username=self.user.username,
                          password=self.user_password)

    def test_create_with_valid_data_with_default_photo(self):
        response = self.client.post('/fifa/api/players/',
                                    {'name': 'TESTPLAYER1',
                                     'age': 19,
                                     'team': self.team.pk,
                                     'photo': ''},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content.decode('utf-8'),
                         '"Player TESTPLAYER1 is created!"')

        player = Player.objects.get(name='TESTPLAYER1', team=self.team)
        self.assertEqual(player.name, 'TESTPLAYER1')
        self.assertEqual(player.age, 19)
        self.assertEqual(player.team.name, self.team.name)
        self.assertEqual(player.photo.url, '/media/static/fifa_league'
                                           '/player/default-player-photo.svg')

    def test_create_with_few_empty_fields(self):
        response = self.client.post('/fifa/api/players/',
                                    {'name': '',
                                     'age': 0,
                                     'team': '',
                                     'photo': ''},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Please enter correct data!')

    def test_create_age_not_number(self):
        response = self.client.post('/fifa/api/players/',
                                    {'name': 'TESTPLAYER1',
                                     'age': 'not number',
                                     'team': self.team.pk,
                                     'photo': ''},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Please enter correct data!')

    def test_create_two_equal(self):
        self.client.post('/fifa/api/players/',
                         {'name': 'TESTPLAYER1',
                          'age': 19,
                          'team': self.team.pk,
                          'photo': ''},
                         HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        response = self.client.post('/fifa/api/players/',
                                    {'name': 'TESTPLAYER1',
                                     'age': 19,
                                     'team': self.team.pk,
                                     'photo': ''},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Player TESTPLAYER1 already exist!'
                         .format(self.team.name))

    def test_unauthenticated_user(self):
        client = Client()
        response = client.post('/fifa/api/players/',
                               {'name': 'TESTPLAYER1',
                                'age': 19,
                                'team': self.team.pk,
                                'photo': ''},
                               HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 403)

    def test_authenticated_user_without_permissions(self):
        client = Client()
        User.objects.create_user(username='******', password='******')
        client.login(username='******', password='******')
        response = client.post('/fifa/api/players/',
                               {'name': 'TESTPLAYER1',
                                'age': 19,
                                'team': self.team.pk,
                                'photo': ''},
                               HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 403)
示例#40
0
class TestUserViewSetAPITestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.password = '******'
        self.user = UserFactory(username='******', password=self.password)

    def test_change_password_with_get_method(self):
        self.client.login(username='******', password=self.password)
        response = self.client.get('/fifa/api/users/{}/change_password/')
        self.assertEqual(response.status_code, 405)

    def test_change_email_with_get_method(self):
        self.client.login(username='******', password=self.password)
        response = self.client.get('/fifa/api/users/{}/change_email/')
        self.assertEqual(response.status_code, 405)

    def test_change_password_with_valid_data(self):
        self.client.login(username='******', password=self.password)
        response = self.client.post('/fifa/api/users/{}/change_password/'
                                    .format(self.user.pk),
                                    {'old_password': self.password,
                                     'new_password1': '1234',
                                     'new_password2': '1234'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content.decode('utf-8'),
                         'Password has changed!')

    def test_change_email_with_valid_data(self):
        self.client.login(username='******', password=self.password)
        response = self.client.post('/fifa/api/users/{}/change_email/'
                                    .format(self.user.pk),
                                    {'new_email': '*****@*****.**'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content.decode('utf-8'),
                         'Email has changed!')
        self.user = User.objects.get(username='******')
        self.assertEqual(self.user.email, '*****@*****.**')

    def test_change_password_unauthenticated_user(self):
        response = self.client.post('/fifa/api/users/{}/change_password/'
                                    .format(self.user.pk),
                                    {'old_password': self.password,
                                     'new_password1': '1234',
                                     'new_password2': '1234'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 403)

    def test_change_email_unauthenticated_user(self):
        response = self.client.post('/fifa/api/users/{}/change_email/'
                                    .format(self.user.pk),
                                    {'old_password': self.password,
                                     'new_password1': '1234',
                                     'new_password2': '1234'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 403)

    def test_change_password_invalid_pk(self):
        self.client.login(username='******', password=self.password)
        response = self.client.post('/fifa/api/users/2/change_password/',
                                    {'old_password': self.password,
                                     'new_password1': '1234',
                                     'new_password2': '1234'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 403)

    def test_change_email_invalid_pk(self):
        self.client.login(username='******', password=self.password)
        response = self.client.post('/fifa/api/users/2/change_email/',
                                    {'new_email': '*****@*****.**'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 403)

    def test_change_password_with_empty_data(self):
        self.client.login(username='******', password=self.password)
        response = self.client.post('/fifa/api/users/{}/change_password/'
                                    .format(self.user.pk),
                                    {'old_password': '',
                                     'new_password1': '',
                                     'new_password2': ''},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Please enter correct data!')

    def test_change_email_with_empty_data(self):
        self.client.login(username='******', password=self.password)
        response = self.client.post('/fifa/api/users/{}/change_email/'
                                    .format(self.user.pk),
                                    {'new_email': ''},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Please enter correct data!')

    def test_change_password_with_bad_old_password(self):
        self.client.login(username='******', password=self.password)
        response = self.client.post('/fifa/api/users/{}/change_password/'
                                    .format(self.user.pk),
                                    {'old_password': '******',
                                     'new_password1': '1234',
                                     'new_password2': '1234'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Bad old password!')

    def test_change_email_with_the_same_email(self):
        self.client.login(username='******', password=self.password)
        response = self.client.post('/fifa/api/users/{}/change_email/'
                                    .format(self.user.pk),
                                    {'new_email': '*****@*****.**'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'You cannot set the same emails!')

    def test_change_password_with_the_same_password(self):
        self.client.login(username='******', password=self.password)
        response = self.client.post('/fifa/api/users/{}/change_password/'
                                    .format(self.user.pk),
                                    {'old_password': '******',
                                     'new_password1': '12345678',
                                     'new_password2': '12345678'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'You cannot set the same password!')

    def test_change_password_with_invalid_double_check_passwords(self):
        self.client.login(username='******', password=self.password)
        response = self.client.post('/fifa/api/users/{}/change_password/'
                                    .format(self.user.pk),
                                    {'old_password': self.password,
                                     'new_password1': '1234',
                                     'new_password2': '5678'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Please enter new passwords correctly!')
示例#41
0
class TestCreateTeamTestCase(TestCase):
    def setUp(self):
        self.user_password = '******'
        self.user = UserFactory(password=self.user_password)
        self.client = Client()
        self.client.login(username=self.user.username,
                          password=self.user_password)

    def test_create_with_valid_data_without_logo(self):
        response = self.client.post('/fifa/api/teams/',
                                    {'name': 'TESTTEAM1',
                                     'description': 'Lorem ipsum',
                                     'logo': ''},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content.decode('utf-8'),
                         '"Team TESTTEAM1 is created!"')

        team = Team.objects.get(name='TESTTEAM1')
        self.assertEqual(team.name, 'TESTTEAM1')
        self.assertEqual(team.description, 'Lorem ipsum')
        self.assertEqual(team.logo.url,
                         '/media/static/fifa_league/'
                         'team/default-team-logo.svg')

    def test_create_with_empty_fields(self):
        response = self.client.post('/fifa/api/teams/',
                                    {'name': '',
                                     'shortcut': '',
                                     'description': '',
                                     'logo': ''},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Please enter correct data!')

    def test_create_two_equal(self):
        self.client.post('/fifa/api/teams/',
                         {'name': 'TESTTEAM1',
                          'shortcut': 'testteam1',
                          'description': 'Lorem ipsum',
                          'logo': ''},
                         HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        response = self.client.post('/fifa/api/teams/',
                                    {'name': 'TESTTEAM1',
                                     'shortcut': 'testteam1',
                                     'description': 'Lorem ipsum lorem',
                                     'logo': ''},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Team TESTTEAM1 already exist!')

    def test_unauthenticated_user(self):
        client = Client()
        response = client.post('/fifa/api/teams/',
                               {'name': 'TESTTEAM1',
                                'shortcut': 'testteam1',
                                'description': 'Lorem ipsum',
                                'logo': ''},
                               HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 403)

    def test_authenticated_user_without_permissions(self):
        client = Client()
        User.objects.create_user(username='******', password='******')
        client.login(username='******', password='******')
        response = client.post('/fifa/api/teams/',
                               {'name': 'TESTTEAM1',
                                'shortcut': 'testteam1',
                                'description': 'Lorem ipsum',
                                'logo': ''},
                               HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 403)
示例#42
0
class TestCreateUserViewTestCase(TestCase):
    def setUp(self):
        self.client = Client()

    def test_create_with_valid_data(self):
        response = self.client.post('/fifa/create_user/',
                                    {'username': '******',
                                     'password': '******',
                                     'password1': '12345678',
                                     'email': '*****@*****.**'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        user = User.objects.get(username='******')
        self.assertEqual(user.username, 'testuser')
        self.assertEqual(response.status_code, 200)
        self.assertIn('_auth_user_id', self.client.session)
        self.assertEqual('1', self.client.session['_auth_user_id'])

    def test_create_two_equal_user(self):
        self.client.post('/fifa/create_user/',
                         {'username': '******',
                          'password': '******',
                          'email': '*****@*****.**'},
                         HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        response = self.client.post('/fifa/create_user/',
                                    {'username': '******',
                                     'password': '******',
                                     'email': '*****@*****.**'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Please enter correct data!')

    def test_create_two_users_with_equal_username(self):
        self.client.post('/fifa/create_user/',
                         {'username': '******',
                          'password': '******',
                          'email': '*****@*****.**'},
                         HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        response = self.client.post('/fifa/create_user/',
                                    {'username': '******',
                                     'password': '******',
                                     'email': '*****@*****.**'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Please enter correct data!')

    def test_create_two_users_with_equal_passwords(self):
        self.client.post('/fifa/create_user/',
                         {'username': '******',
                          'password': '******',
                          'password1': '12345678',
                          'email': '*****@*****.**'},
                         HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        response = self.client.post('/fifa/create_user/',
                                    {'username': '******',
                                     'password': '******',
                                     'password1': '12345678',
                                     'email': '*****@*****.**'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)
        self.assertEqual('2', self.client.session['_auth_user_id'])

    def test_create_user_with_empty_data(self):
        response = self.client.post('/fifa/create_user/',
                                    {'username': '',
                                     'password': '',
                                     'email': '*****@*****.**'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Please enter correct data!')

    def test_create_user_with_empty_password(self):
        response = self.client.post('/fifa/create_user/',
                                    {'username': '******',
                                     'password': '',
                                     'email': '*****@*****.**'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Please enter correct data!')

    def test_create_user_with_bad_confirm_password(self):
        response = self.client.post('/fifa/create_user/',
                                    {'username': '******',
                                     'password': '******',
                                     'password1': '1234',
                                     'email': '*****@*****.**'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Passwords not same!')

    def test_create_users_with_equal_emails(self):
        self.client.post('/fifa/create_user/',
                         {'username': '******',
                          'password': '******',
                          'password1': '12345678',
                          'email': '*****@*****.**'},
                         HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        response = self.client.post('/fifa/create_user/',
                                    {'username': '******',
                                     'password': '******',
                                     'password1': '12345678',
                                     'email': '*****@*****.**'},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'This email already exists!')
示例#43
0
 def setUp(self):
     self.client = Client()
     self.league2 = LeagueFactory(name='TESTLEAGUE2')
     self.teamstat1 = TeamStatFactory()
     self.teamstat2 = TeamStatFactory()
示例#44
0
 def setUp(self):
     self.user_password = '******'
     self.user = UserFactory(password=self.user_password)
     self.client = Client()
     self.client.login(username=self.user.username,
                       password=self.user_password)
# add a bunch of words from txt format
from django.test import Client
import django

from Word_edit import html_form_to_xml

django.setup()
client = Client()

def add_word_using_api(index, word):
    parts = word.split(' ')

    data = {'Stichwort' : parts[0],
            'category' : 'Substantiv',
            'isCreated' : 'True',
            'wordAddr' :  '/Wort/ja/%d.xml' % index,
            'explanation_1': parts[0]
            }
    if len(parts) > 1:
        data['Aussprache'] = parts[1].rstrip()
    if len(parts) > 2:
        data['explanation_1'] = parts[2]
    response = client.post('/Word_edit/create_new_word', data)
    assert(response.status_code == 200)

if __name__ == '__main__':
    
    # treat all words as Substantiv
    noun_len = html_form_to_xml.next_word_address(word_type='Substantiv')
    noun_len = int(noun_len)
    with open('build/word.txt') as f:
示例#46
0
class TestCreateLeagueTestCase(TestCase):
    def setUp(self):
        self.user_password = '******'
        self.user = UserFactory(password=self.user_password)
        self.client = Client()
        self.client.login(username=self.user.username,
                          password=self.user_password)

    def test_create_with_valid_data_and_default_logo(self):
        response = self.client.post('/fifa/api/leagues/',
                                    {'name': 'TESTLEAGUE1',
                                     'short_description': 'Lorem',
                                     'full_description': 'Lorem ipsum',
                                     'logo': ''},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content.decode('utf-8'),
                         '"League TESTLEAGUE1 is create!"')

        league = League.objects.get(name='TESTLEAGUE1')
        self.assertEqual(league.name, 'TESTLEAGUE1')
        self.assertEqual(league.short_description, 'Lorem')
        self.assertEqual(league.full_description, 'Lorem ipsum')
        self.assertEqual(league.logo.url, '/media/static/fifa_league'
                                          '/league/default-league-logo.svg')

    def test_create_with_valid_data_and_custom_logo(self):
        main_dir = os.path.dirname(__file__)
        file = open(os.path.join(main_dir,
                                 'test/files/league-custom-logo.svg'), 'rb')
        response = self.client.post('/fifa/api/leagues/',
                                    {'name': 'TESTLEAGUE1',
                                     'short_description': 'Lorem',
                                     'full_description': 'Lorem ipsum',
                                     'logo': SimpleUploadedFile(file.name,
                                                                file.read())},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content.decode('utf-8'),
                         '"League TESTLEAGUE1 is create!"')

        league = League.objects.get(name='TESTLEAGUE1')
        self.assertEqual(league.name, 'TESTLEAGUE1')
        self.assertEqual(league.short_description, 'Lorem')
        self.assertEqual(league.full_description, 'Lorem ipsum')
        try:
            self.assertEqual(league.logo.url, '/media/uploads/leagues/'
                                              'logos/league-custom-logo.svg')
        finally:
            league.logo.storage.delete(league.logo.name)

    def test_create_with_empty_fields(self):
        response = self.client.post('/fifa/api/leagues/',
                                    {'name': '',
                                     'short_description': 'Lorem',
                                     'full_description': 'Lorem ipsum',
                                     'logo': ''},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'Please enter correct data!')

    def test_create_two_equal(self):
        self.client.post('/fifa/api/leagues/',
                         {'name': 'TESTLEAGUE1',
                          'short_description': 'Lorem',
                          'full_description': 'Lorem ipsum',
                          'logo': ''},
                         HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        response = self.client.post('/fifa/api/leagues/',
                                    {'name': 'TESTLEAGUE1',
                                     'short_description': 'Lorem',
                                     'full_description': 'Lorem ipsum',
                                     'logo': ''},
                                    HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.content.decode('utf-8'),
                         'League TESTLEAGUE1 already exist!')

    def test_unauthenticated_user(self):
        client = Client()
        response = client.post('/fifa/api/leagues/',
                               {'name': 'TESTLEAGUE1',
                                'short_description': 'Lorem',
                                'full_description': 'Lorem ipsum',
                                'logo': ''},
                               HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 403)

    def test_authenticated_user_without_permissions(self):
        client = Client()
        User.objects.create_user(username='******', password='******')
        client.login(username='******', password='******')
        response = client.post('/fifa/api/leagues/',
                               {'name': 'TESTLEAGUE1',
                                'short_description': 'Lorem',
                                'full_description': 'Lorem ipsum',
                                'logo': ''},
                               HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertEqual(response.status_code, 403)
示例#47
0
 def test_user_not_logged(self):
     client = Client()
     User.objects.create_user(username='******')
     response = client.get(path='/', follow=True)
     self.assertContains(response, 'run.jpg')
示例#48
0
class APITestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.league2 = LeagueFactory(name='TESTLEAGUE2')
        self.teamstat1 = TeamStatFactory()
        self.teamstat2 = TeamStatFactory()

    def is_lists_equals(self, valid_list, test_list):
        # length list test
        if len(valid_list) != len(test_list):
            return False

        # JSON keys list test
        valid_list_keys = list(valid_list[0].keys())
        test_list_keys = list(test_list[0].keys())
        for key in valid_list_keys:
            if key not in test_list_keys:
                return False

        # if lists equal test
        if valid_list != test_list:
            return False

        return True

    def test_teams_list(self):
        response = self.client.get('/fifa/api/teams/')

        test_serializers = []

        teams_list = Team.objects.all()
        for team in teams_list:
            test_serializers.append(TeamSerializer(team).data)

        response_data = response.json()

        self.assertTrue(self.is_lists_equals(test_serializers, response_data))

    def test_get_teams_from_league(self):
        league = self.teamstat1.league
        response = self.client.get('/fifa/api/leagues/{}/get_teams/'
                                   .format(league.pk))
        test_serializers = []

        teams_list = TeamStat.objects.filter(league__pk=league.pk)
        for teamstat in teams_list:
            test_serializers.append(TeamSerializer(teamstat.team).data)

        response_data = response.json()
        self.assertTrue(self.is_lists_equals(test_serializers, response_data))

    def test_league_list(self):
        response = self.client.get('/fifa/api/leagues/')
        test_serializers = []

        leagues_list = League.objects.all()
        for league in leagues_list:
            test_serializers.append(LeagueSerializer(league).data)

        response_data = response.json()
        self.assertTrue(self.is_lists_equals(test_serializers, response_data))
示例#49
0
    def test_AuthenticatedRandomIdPing(self):
        self.client = Client()
        self.client.force_login(self.dummyUser)
        response = self.client.get('evoting/voter_login/blank')

        self.assertEqual(response.status_code, 404)
示例#50
0
 def test_user_logged(self):
     client = Client()
     User.objects.create_user(username='******', password='******')
     client.login(username='******', password='******')
     response = client.get(path='/')
     self.assertRedirects(response, '/dashboard/', status_code=302, target_status_code=302)
示例#51
0
    def test_AnonymousPing(self):
        self.client = Client()
        response = self.client.get(self.request_url)

        self.assertEqual(response.status_code, 200)
示例#52
0
	def setUp(self):
		self.client = Client()
		self.register_url = reverse('main:register')
		self.login_url = reverse('main:login')
		self.logout_url = reverse('main:logout')
		self.home_url = reverse('main:homepage')		
示例#53
0
    def test_AnonymousPing(self):
        self.client = Client()
        response = self.client.get(self.request_url)

        self.assertRedirects(response, expected_url='/evoting/home/')
示例#54
0
    def test_AuthenticatedPing(self):
        self.client = Client()
        self.client.force_login(self.dummyUser)
        response = self.client.get(self.request_url)

        self.assertEqual(response.status_code, 302)
示例#55
0
    def test_max_emergency_contact_unique(self):
        '''
        Test: Adding the same emergency contact email is not allowed
        '''
        CONTACTS_EMAILS = [
            '*****@*****.**',
            '*****@*****.**',
        ]

        # Add two emergency contacts with the same email
        for addr in CONTACTS_EMAILS:
            response = self.client.post('/emergencycontact/add/', {
                'first_name': addr[0:5],
                'last_name': addr[0:1],
                'email': addr
            })

        # Check that there is only one emergency contact (second not added)
        self.assertEqual(len(self.test_user.emergency_contacts.all()), 1)

        # Check for an error message (labeled 'dup' in pages/views.py)
        message_list = list(get_messages(response.wsgi_request))
        self.assertEqual(len(message_list), 1)
        self.assertEqual(str(message_list[0]), 'dup')

        # Check whether a redirect to the form occurred
        self.assertEqual(response.status_code, 302)

        # Check whether another user can add the same emergency contact
        test_user_2 = CustomAccount.objects.create(
            username='******',
            password='******',
            email='*****@*****.**',
            first_name='TEST_FIRST_NAME',
            last_name='TEST_LAST_NAME',
            is_active=True,
        )
        # Login the second test user
        test_user_2.set_password(test_user_2.password)
        test_user_2.save()
        client_2 = Client()
        client_2.login(username='******', password='******')
        authenticate(username='******', password='******')

        # Assign the second test user the same emergency contact as the first
        for addr in CONTACTS_EMAILS:
            response = client_2.post('/emergencycontact/add/', {
                'first_name': addr[0:5],
                'last_name': addr[0:1],
                'email': addr
            })

        # Check that there is one emergency contact added for the second user
        self.assertEqual(len(self.test_user.emergency_contacts.all()), 1)

        # Check that the emergency contact for both test users is the same
        self.assertEqual(
            self.test_user.emergency_contacts.values('email')[0],
            test_user_2.emergency_contacts.values('email')[0])

        # Logout the second test user
        client_2.logout()
        test_user_2.delete()
示例#56
0
    def test_AuthenticatedPing(self):
        self.client = Client()
        self.client.force_login(self.dummyUser)
        response = self.client.get(self.request_url)

        self.assertRedirects(response, expected_url='/evoting/home/')
示例#57
0
class TwitterAccountViewCorrectPermissionMixin(object):
    """User testing the views is logged in and has all required permissions."""
    csrf_client = Client(enforce_csrf_checks=True)

    # List
    def test_get_list_view(self):
        response = self.client.get(reverse('twitter:list'))
        self.assertEqual(response.status_code, 200)
        self.assertIn('accounts', response.context)
        self.assertEqual(list(response.context['accounts']),
                         list(TwitterAccount.objects.all()))

    def test_post_list_view_not_allowed(self):
        response = self.client.post(reverse('twitter:list'))
        self.assertEqual(response.status_code, 405)

    # Detail
    def test_get_detail_view(self):
        response = self.client.get(reverse('twitter:detail', kwargs={'pk': 1}))
        self.assertEqual(response.status_code, 200)
        self.assertIn('account', response.context)
        self.assertEqual(response.context['account'],
                         TwitterAccount.objects.get(pk=1))

    def test_get_detail_view_not_existant(self):
        response = self.client.get(
            reverse('twitter:detail', kwargs={'pk': 1000}))
        self.assertEqual(response.status_code, 404)

    def test_post_detail_view_not_allowed(self):
        response = self.client.post(reverse('twitter:detail', kwargs={'pk':
                                                                      1}))
        self.assertEqual(response.status_code, 405)

    # Create
    def test_get_create_view(self):
        response = self.client.get(reverse('twitter:create'))
        self.assertEqual(response.status_code, 200)
        self.assertIn('form', response.context)

    def mocked_requests_get(*args):
        class MockResponse:
            def __init__(self, json_data, status_code):
                self.json_data = json_data
                self.status_code = status_code

            def json(self):
                return self.json_data

        if args[1] == 'users/show':
            r = MockResponse({'id': 1337}, 200)
            return TwitterResponse(r, None)

    @mock.patch('TwitterAPI.TwitterAPI.__init__', mock.Mock(return_value=None))
    @mock.patch('TwitterAPI.TwitterAPI.request', mocked_requests_get)
    def test_post_create_view(self):
        data = {
            'name': 'Random Account',
        }
        response = self.client.post(reverse('twitter:create'),
                                    data,
                                    follow=True)
        self.assertRedirects(response,
                             reverse('twitter:detail', kwargs={'pk': 5}))

    @mock.patch('TwitterAPI.TwitterAPI.__init__', mock.Mock(return_value=None))
    @mock.patch('TwitterAPI.TwitterAPI.request', mocked_requests_get)
    def test_post_create_view_no_data(self):
        response = self.client.post(reverse('twitter:create'))
        self.assertEqual(response.status_code, 200)
        self.assertIn('form', response.context)  # shows form again

    @mock.patch('TwitterAPI.TwitterAPI.__init__', mock.Mock(return_value=None))
    @mock.patch('TwitterAPI.TwitterAPI.request', mocked_requests_get)
    def test_post_create_view_incomplete_data(self):
        data = {}
        response = self.client.post(reverse('twitter:create'), data)
        self.assertEqual(response.status_code, 200)
        self.assertIn('form', response.context)  # shows form again

    def test_post_create_view_without_csrf_token(self):
        response = self.csrf_client.post(reverse('twitter:create'))
        self.assertEqual(response.status_code, 403)

    # Delete
    def test_get_delete_view(self):
        response = self.client.get(reverse('twitter:delete', kwargs={'pk': 1}))
        self.assertEqual(response.status_code, 200)
        self.assertIn('account', response.context)
        self.assertEqual(response.context['account'],
                         TwitterAccount.objects.get(pk=1))

    def test_get_delete_view_not_existant(self):
        response = self.client.get(
            reverse('twitter:delete', kwargs={'pk': 1000}))
        self.assertEqual(response.status_code, 404)

    def test_post_delete_view(self):
        response = self.client.post(reverse('twitter:delete', kwargs={'pk':
                                                                      1}),
                                    follow=True)
        self.assertRedirects(response, reverse('twitter:list'))
        self.assertIsNone(TwitterAccount.objects.filter(pk=1).first())

    def test_post_delete_view_not_existant(self):
        response = self.client.post(
            reverse('twitter:delete', kwargs={'pk': 1000}))
        self.assertEqual(response.status_code, 404)

    def test_post_delete_view_without_csrf_token(self):
        response = self.csrf_client.post(
            reverse('twitter:delete', kwargs={'pk': 1}))
        self.assertEqual(response.status_code, 403)

    # Fetch Tweets
    @mock.patch('twitter.models.TwitterAccount.fetch_tweets',
                mock.Mock(return_value=None))
    def test_post_fetch_tweets_view(self):
        response = self.client.post(
            reverse('twitter:fetch_tweets', kwargs={'pk': 1}), {})
        self.assertEqual(response.status_code, 200)

    def test_get_fetch_tweets_view_not_allowed(self):
        response = self.client.get(
            reverse('twitter:fetch_tweets', kwargs={'pk': 1}))
        self.assertEqual(response.status_code, 405)
示例#58
0
 def test_get_index(self):
     client = Client()
     response = client.get('/')
     self.assertEqual(response.status_code, 200, 'status code must be 200!')
示例#59
0
文件: tests.py 项目: sdan/madras
class AuthTests(TestCase):
    def setUp(self):
        self.user = User.objects.create(
            email="*****@*****.**",
            is_active=True
        )
        self.user.set_password("testing")
        self.user.save()
        self.client = Client()

    def test_login(self):
        data = {"username": "******", "password": "******"}
        resp = self.client.post("/login/", json.dumps(data), content_type="application/json")
        self.assertEqual(resp.status_code, 200)
        resp_data = json.loads(resp.content.decode("utf-8"))
        self.assertTrue("token" in resp_data, resp_data)

    def test_login_fail(self):
        data = {"username": "******", "password": "******"}
        resp = self.client.post("/login/", json.dumps(data), content_type="application/json")
        self.assertEqual(resp.status_code, 400)

    def test_login_fail_not_active(self):
        u = self.user
        u.is_active = False
        u.save()

        data = {"username": "******", "password": "******"}
        resp = self.client.post("/login/", json.dumps(data), content_type="application/json")
        self.assertEqual(resp.status_code, 400)

    def test_registration(self):
        data = {"email": "*****@*****.**", "password": "******"}
        resp = self.client.post("/registration/signup/", data=data)
        self.assertEqual(resp.status_code, 201)
        resp_data = json.loads(resp.content.decode("utf-8"))

        # make sure success code is returned
        self.assertTrue(resp_data.get("success"), resp_data)

        # make sure the user exists
        new_user = User.objects.filter(email="*****@*****.**")
        self.assertTrue(new_user.exists())
        new_user = new_user.first()

        # make sure token activation works
        uid = urlsafe_base64_encode(force_bytes(new_user.pk)).decode("utf-8")
        token = account_activation_token.make_token(new_user)
        resp = self.client.get("/registration/activate/{}/{}/".format(uid, token))
        self.assertEqual(resp.status_code, 302)

        # make sure account is activated
        self.assertTrue(User.objects.get(email="*****@*****.**").is_active)

    def test_registration_staff(self):
        data = {"email": "*****@*****.**", "password": "******"}
        resp = self.client.post("/registration/signup/", data=data)
        self.assertEqual(resp.status_code, 201)

        user = User.objects.filter(email="*****@*****.**")
        self.assertTrue(user.exists())
        self.assertTrue(user[0].is_staff)
示例#60
0
class WithFilterTest(TestCase):
    def setUp(self):
        super().setUp()
        u = User(username='******', is_active=True, is_superuser=True)
        u.set_password('test')
        u.save()
        self.client = Client()
        r = self.client.login(username='******', password='******')
        self.assertTrue(r)

    def test_where(self):
        zoo = Zoo(name='Meerkerk')
        zoo.save()

        gman = Caretaker(name='gman')
        gman.save()
        freeman = Caretaker(name='gordon')
        freeman.save()

        antlion = Animal(zoo=zoo, name='antlion', caretaker=freeman)
        antlion.save()

        sealion = Animal(zoo=zoo, name='sealion')
        sealion.save()

        goat = Animal(zoo=zoo, name='goat', caretaker=gman)
        goat.save()

        # Filter the animal relations on animals with lion in the name
        # This means we don't expect the goat and its caretaker in the with response
        res = self.client.get('/zoo/',
                              data={
                                  'with': 'animals.caretaker',
                                  'where': 'animals(name:contains=lion)'
                              })
        self.assertEqual(res.status_code, 200)
        res = jsonloads(res.content)

        assert_json(
            res, {
                'data': [{
                    'id': zoo.id,
                    'animals': [antlion.id, sealion.id],
                    EXTRA(): None,
                }],
                'with': {
                    'animal': [
                        {
                            'id': antlion.id,
                            EXTRA(): None,
                        },
                        {
                            'id': sealion.id,
                            EXTRA(): None,
                        },
                    ],
                    'caretaker': [
                        {
                            'id': freeman.id,
                            EXTRA(): None,
                        },
                    ]
                },
                EXTRA():
                None,
            })

        # Regression test for missing filter caused by querysets being
        # falsy when there are no records...
        res = self.client.get('/zoo/',
                              data={
                                  'with': 'animals.caretaker',
                                  'where': 'animals(name:contains=nonexistent)'
                              })
        self.assertEqual(res.status_code, 200)
        res = jsonloads(res.content)

        assert_json(
            res, {
                'data': [{
                    'id': zoo.id,
                    'animals': [],
                    EXTRA(): None,
                }],
                'with': {
                    'animal': [],
                    'caretaker': [],
                },
                EXTRA(): None,
            })

    def test_multiple_wheres(self):
        zoo = Zoo(name='Meerkerk')
        zoo.save()

        freeman = Caretaker(name='gordon')
        freeman.save()
        alyx = Caretaker(name='alyx')
        alyx.save()

        antlion = Animal(zoo=zoo, name='antlion', caretaker=freeman)
        antlion.save()

        sealion = Animal(zoo=zoo, name='sealion', caretaker=alyx)
        sealion.save()

        goat = Animal(zoo=zoo, name='goat')
        goat.save()

        res = self.client.get(
            '/zoo/',
            data={
                'with':
                'animals.caretaker',
                'where':
                'animals(name:contains=lion),animals.caretaker(name=gordon)'
            })
        self.assertEqual(res.status_code, 200)
        res = jsonloads(res.content)

        assert_json(
            res,
            {
                'data': [{
                    'id': zoo.id,
                    'animals': [antlion.id, sealion.id],
                    EXTRA(): None,
                }],
                'with': {
                    'animal': [
                        {
                            'id': antlion.id,
                            'caretaker': freeman.id,
                            EXTRA(): None,
                        },
                        {
                            'id': sealion.id,
                            'caretaker': None,  # Was filtered out!
                            EXTRA(): None,
                        },
                    ],
                    'caretaker': [
                        {
                            'id': freeman.id,
                            EXTRA(): None,
                        },
                    ]
                },
                EXTRA():
                None,
            })

    def test_where_and_filter(self):
        zoo1 = Zoo(name='Meerkerk')
        zoo1.save()
        zoo2 = Zoo(name='Hardinxveld')
        zoo2.save()

        freeman = Caretaker(name='gordon')
        freeman.save()
        alyx = Caretaker(name='alyx')
        alyx.save()

        antlion = Animal(zoo=zoo1, name='antlion', caretaker=freeman)
        antlion.save()

        sealion = Animal(zoo=zoo1, name='sealion', caretaker=alyx)
        sealion.save()

        goat1 = Animal(zoo=zoo1, name='goat')
        goat1.save()

        goat2 = Animal(zoo=zoo2, name='goat')
        goat2.save()

        # Instead of filtering the animals relation,
        # we now filter the zoo relation on having certain animals
        res = self.client.get('/zoo/',
                              data={
                                  '.animals.name:contains': 'lion',
                                  'with': 'animals.caretaker',
                                  'where': 'animals.caretaker(name=gordon)'
                              })
        self.assertEqual(res.status_code, 200)
        res = jsonloads(res.content)

        assert_json(
            res,
            {
                'data': [{
                    'id': zoo1.id,
                    'animals': [antlion.id, sealion.id, goat1.id],
                    EXTRA(): None,
                }],
                'with': {
                    'animal': [
                        {
                            'id': antlion.id,
                            'caretaker': freeman.id,
                            EXTRA(): None,
                        },
                        {
                            'id': sealion.id,
                            'caretaker': None,  # Was filtered out!
                            EXTRA(): None,
                        },
                        {
                            'id': goat1.id,
                            'caretaker': None,
                            EXTRA(): None,
                        }
                    ],
                    'caretaker': [
                        {
                            'id': freeman.id,
                            EXTRA(): None,
                        },
                    ]
                },
                EXTRA():
                None,
            })

    def test_where_filter_on_reverse_foreign_key_field_causes_no_duplication_of_main_record(
            self):
        zoo1 = Zoo(name='Meerkerk')
        zoo1.save()
        zoo2 = Zoo(name='Hardinxveld')
        zoo2.save()

        antlion = Animal(zoo=zoo1, name='antlion')
        antlion.save()

        sealion = Animal(zoo=zoo1, name='sealion')
        sealion.save()

        # Because one zoo has multiple animals, this creates a join.
        # Having the join means we'll get multiple records.  Even
        # though the ORM hides this fact from us, we do get the
        # multiple results.  Therefore, Binder must add a distinct()
        # call to counteract this effect.  Performance will suffer
        # but there's not much else we can do.
        res = self.client.get('/zoo/',
                              data={
                                  '.animals.name:contains': 'lion',
                              })
        self.assertEqual(res.status_code, 200)
        res = jsonloads(res.content)

        assert_json(
            res, {
                'data': [{
                    'id': zoo1.id,
                    EXTRA(): None,
                }],
                'meta': {
                    'total_records': 1,
                    EXTRA(): None,
                },
                'with': {},
                EXTRA(): None,
            })

    def test_m2m(self):
        zoo = Zoo(name='Meerkerk')
        zoo.save()

        cp1 = ContactPerson(name='henk')
        cp1.save()
        cp2 = ContactPerson(name='hendrik')
        cp2.save()
        cp3 = ContactPerson(name='hans')
        cp3.save()

        zoo.contacts.set([cp1.id, cp2.id, cp3.id])

        res = self.client.get('/zoo/',
                              data={
                                  'with': 'contacts',
                                  'where': 'contacts(name:startswith=he)'
                              })
        self.assertEqual(res.status_code, 200)
        res = jsonloads(res.content)

        assert_json(
            res, {
                'data': [{
                    'id': zoo.id,
                    'contacts': [cp1.id, cp2.id],
                    EXTRA(): None,
                }],
                'with': {
                    'contact_person': [
                        {
                            'id': cp1.id,
                            EXTRA(): None,
                        },
                        {
                            'id': cp2.id,
                            EXTRA(): None,
                        },
                    ]
                },
                EXTRA():
                None,
            })

    def test_where_filter_on_m2m_field_causes_no_duplication_of_main_record(
            self):
        zoo = Zoo(name='Meerkerk')
        zoo.save()

        cp1 = ContactPerson(name='henk')
        cp1.save()
        cp2 = ContactPerson(name='hendrik')
        cp2.save()
        cp3 = ContactPerson(name='hans')
        cp3.save()

        zoo.contacts.set([cp1.id, cp2.id, cp3.id])

        res = self.client.get('/zoo/',
                              data={'.contacts.name:startswith': 'he'})
        self.assertEqual(res.status_code, 200)
        res = jsonloads(res.content)

        assert_json(
            res, {
                'data': [{
                    'id': zoo.id,
                    EXTRA(): None,
                }],
                'meta': {
                    'total_records': 1,
                    EXTRA(): None,
                },
                'with': {},
                EXTRA(): None,
            })

    def test_where_complains_on_syntax_error(self):
        res = self.client.get('/zoo/', data={'where': 'contacts'})
        self.assertEqual(res.status_code, 418)
        res = jsonloads(res.content)

        assert_json(res, {
            'message': 'Syntax error in {where=contacts}.',
            EXTRA(): None,
        })

    def test_where_complains_if_relation_not_in_with(self):
        res = self.client.get('/zoo/',
                              data={'where': 'contacts(name:startswith=he)'})
        self.assertEqual(res.status_code, 418)
        res = jsonloads(res.content)

        assert_json(
            res, {
                'message':
                'Relation of {where=contacts(name:startswith=he)} is missing from withs {withs=[]}.',
                EXTRA(): None,
            })

    def test_where_complains_on_non_relation_field(self):
        res = self.client.get('/zoo/',
                              data={
                                  'with': 'floor_plan',
                                  'where': 'floor_plan(foo=5)'
                              })
        self.assertEqual(res.status_code, 418)
        res = jsonloads(res.content)

        assert_json(
            res, {
                'message': 'Field is not a related object {Zoo}.{floor_plan}.',
                EXTRA(): None,
            })

    def test_where_complains_on_invalid_value(self):
        res = self.client.get('/zoo/',
                              data={
                                  'with': 'contacts',
                                  'where': 'contacts(id=foo)'
                              })
        self.assertEqual(res.status_code, 418)
        res = jsonloads(res.content)

        assert_json(
            res, {
                'message':
                'Invalid value {foo} for AutoField {ContactPerson}.{id}.',
                EXTRA(): None,
            })

    def test_where_handles_missing_close_parens(self):
        zoo = Zoo(name='Assen')
        zoo.save()
        cp1 = ContactPerson(name='henk')
        cp1.save()
        zoo.contacts.set([cp1])

        res = self.client.get('/zoo/',
                              data={
                                  'with': 'contacts',
                                  'where': 'contacts(name=henk'
                              })

        self.assertEqual(res.status_code, 418)
        res = jsonloads(res.content)

        assert_json(
            res, {
                'message': 'Syntax error in {where=contacts(name=henk}.',
                EXTRA(): None,
            })

    def test_where_ignores_commas_in_parens(self):
        zoo = Zoo(name='Apenheul')
        zoo.save()

        harambe = Animal(name='Harambe', zoo=zoo)
        harambe.save()
        bokito = Animal(name='Bokito', zoo=zoo)
        bokito.save()
        rafiki = Animal(name='Rafiki', zoo=zoo)
        rafiki.save()

        res = self.client.get('/zoo/',
                              data={
                                  'with': 'animals',
                                  'where': 'animals(name:in=Harambe,Bokito)',
                              })

        self.assertEqual(res.status_code, 200)
        res = jsonloads(res.content)

        assert_json(
            res, {
                'data': [{
                    'id': zoo.id,
                    'animals': [harambe.id, bokito.id],
                    EXTRA(): None,
                }],
                'with': {
                    'animal': [
                        {
                            'id': harambe.id,
                            EXTRA(): None,
                        },
                        {
                            'id': bokito.id,
                            EXTRA(): None,
                        },
                    ]
                },
                EXTRA():
                None,
            })