desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Regression test for #7512 ordering across nullable Foreign Keys shouldn\'t exclude results'
def test_ordering_across_null_fk(self):
author_1 = Author.objects.create(name='Tom Jones') author_2 = Author.objects.create(name='Bob Smith') article_1 = Article.objects.create(title='No author on this article') article_2 = Article.objects.create(author=author_1, title='This article written by Tom Jones') article_3 = Article.objects.create(author=author_2, title='This article written by Bob Smith') self.assertTrue((len(list(Article.objects.all())) == 3)) s = SystemInfo.objects.create(system_name='System Info') f = Forum.objects.create(system_info=s, forum_name='First forum') p = Post.objects.create(forum=f, title='First Post') c1 = Comment.objects.create(post=p, comment_text='My first comment') c2 = Comment.objects.create(comment_text='My second comment') s2 = SystemInfo.objects.create(system_name='More System Info') f2 = Forum.objects.create(system_info=s2, forum_name='Second forum') p2 = Post.objects.create(forum=f2, title='Second Post') c3 = Comment.objects.create(comment_text='Another first comment') c4 = Comment.objects.create(post=p2, comment_text='Another second comment') self.assertTrue((len(list(Comment.objects.all())) == 4))
'Test that multicolumn indexes are not included in the introspection results.'
def test_get_indexes_multicol(self):
cursor = connection.cursor() indexes = connection.introspection.get_indexes(cursor, Reporter._meta.db_table) self.assertNotIn(u'first_name', indexes) self.assertIn(u'id', indexes)
'Verify that ``get_wsgi_application`` returns a functioning WSGI callable.'
def test_get_wsgi_application(self):
application = get_wsgi_application() environ = RequestFactory()._base_environ(PATH_INFO=u'/', CONTENT_TYPE=u'text/html; charset=utf-8', REQUEST_METHOD=u'GET') response_data = {} def start_response(status, headers): response_data[u'status'] = status response_data[u'headers'] = headers response = application(environ, start_response) self.assertEqual(response_data[u'status'], u'200 OK') self.assertEqual(response_data[u'headers'], [(u'Content-Type', u'text/html; charset=utf-8')]) self.assertEqual(bytes(response), 'Content-Type: text/html; charset=utf-8\r\n\r\nHello World!')
'If ``WSGI_APPLICATION`` is a dotted path, the referenced object is returned.'
@override_settings(WSGI_APPLICATION=u'regressiontests.wsgi.wsgi.application') def test_success(self):
app = get_internal_wsgi_application() from .wsgi import application self.assertTrue((app is application))
'If ``WSGI_APPLICATION`` is ``None``, the return value of ``get_wsgi_application`` is returned.'
@override_settings(WSGI_APPLICATION=None) def test_default(self):
fake_app = object() def mock_get_wsgi_app(): return fake_app from django.core.servers import basehttp _orig_get_wsgi_app = basehttp.get_wsgi_application basehttp.get_wsgi_application = mock_get_wsgi_app try: app = get_internal_wsgi_application() self.assertTrue((app is fake_app)) finally: basehttp.get_wsgi_application = _orig_get_wsgi_app
'Responses can be inspected for content, including counting repeated substrings'
def test_contains(self):
response = self.client.get(u'/test_client_regress/no_template_view/') self.assertNotContains(response, u'never') self.assertContains(response, u'never', 0) self.assertContains(response, u'once') self.assertContains(response, u'once', 1) self.assertContains(response, u'twice') self.assertContains(response, u'twice', 2) try: self.assertContains(response, u'text', status_code=999) except AssertionError as e: self.assertIn(u"Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertContains(response, u'text', status_code=999, msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertNotContains(response, u'text', status_code=999) except AssertionError as e: self.assertIn(u"Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertNotContains(response, u'text', status_code=999, msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e)) try: self.assertNotContains(response, u'once') except AssertionError as e: self.assertIn(u"Response should not contain 'once'", str(e)) try: self.assertNotContains(response, u'once', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Response should not contain 'once'", str(e)) try: self.assertContains(response, u'never', 1) except AssertionError as e: self.assertIn(u"Found 0 instances of 'never' in response (expected 1)", str(e)) try: self.assertContains(response, u'never', 1, msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Found 0 instances of 'never' in response (expected 1)", str(e)) try: self.assertContains(response, u'once', 0) except AssertionError as e: self.assertIn(u"Found 1 instances of 'once' in response (expected 0)", str(e)) try: self.assertContains(response, u'once', 0, msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Found 1 instances of 'once' in response (expected 0)", str(e)) try: self.assertContains(response, u'once', 2) except AssertionError as e: self.assertIn(u"Found 1 instances of 'once' in response (expected 2)", str(e)) try: self.assertContains(response, u'once', 2, msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Found 1 instances of 'once' in response (expected 2)", str(e)) try: self.assertContains(response, u'twice', 1) except AssertionError as e: self.assertIn(u"Found 2 instances of 'twice' in response (expected 1)", str(e)) try: self.assertContains(response, u'twice', 1, msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Found 2 instances of 'twice' in response (expected 1)", str(e)) try: self.assertContains(response, u'thrice') except AssertionError as e: self.assertIn(u"Couldn't find 'thrice' in response", str(e)) try: self.assertContains(response, u'thrice', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Couldn't find 'thrice' in response", str(e)) try: self.assertContains(response, u'thrice', 3) except AssertionError as e: self.assertIn(u"Found 0 instances of 'thrice' in response (expected 3)", str(e)) try: self.assertContains(response, u'thrice', 3, msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Found 0 instances of 'thrice' in response (expected 3)", str(e))
'Unicode characters can be found in template context'
def test_unicode_contains(self):
r = self.client.get(u'/test_client_regress/check_unicode/') self.assertContains(r, u'\u3055\u304b\u304d') self.assertContains(r, '\xe5\xb3\xa0'.decode(u'utf-8'))
'Unicode characters can be searched for, and not found in template context'
def test_unicode_not_contains(self):
r = self.client.get(u'/test_client_regress/check_unicode/') self.assertNotContains(r, u'\u306f\u305f\u3051') self.assertNotContains(r, '\xe3\x81\xaf\xe3\x81\x9f\xe3\x81\x91'.decode(u'utf-8'))
'Test that we can pass in an unrendered SimpleTemplateReponse without throwing an error. Refs #15826.'
def test_assert_contains_renders_template_response(self):
response = SimpleTemplateResponse(Template(u'Hello'), status=200) self.assertContains(response, u'Hello')
'Test that auto-rendering does not affect responses that aren\'t instances (or subclasses) of SimpleTemplateResponse. Refs #15826.'
def test_assert_contains_using_non_template_response(self):
response = HttpResponse(u'Hello') self.assertContains(response, u'Hello')
'Test that we can pass in an unrendered SimpleTemplateReponse without throwing an error. Refs #15826.'
def test_assert_not_contains_renders_template_response(self):
response = SimpleTemplateResponse(Template(u'Hello'), status=200) self.assertNotContains(response, u'Bye')
'Test that auto-rendering does not affect responses that aren\'t instances (or subclasses) of SimpleTemplateResponse. Refs #15826.'
def test_assert_not_contains_using_non_template_response(self):
response = HttpResponse(u'Hello') self.assertNotContains(response, u'Bye')
'Template usage assertions work then templates aren\'t in use'
def test_no_context(self):
response = self.client.get(u'/test_client_regress/no_template_view/') self.assertTemplateNotUsed(response, u'GET Template') try: self.assertTemplateUsed(response, u'GET Template') except AssertionError as e: self.assertIn(u'No templates used to render the response', str(e)) try: self.assertTemplateUsed(response, u'GET Template', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u'abc: No templates used to render the response', str(e))
'Template assertions work when there is a single context'
def test_single_context(self):
response = self.client.get(u'/test_client/post_view/', {}) try: self.assertTemplateNotUsed(response, u'Empty GET Template') except AssertionError as e: self.assertIn(u"Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateNotUsed(response, u'Empty GET Template', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateUsed(response, u'Empty POST Template') except AssertionError as e: self.assertIn(u"Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e)) try: self.assertTemplateUsed(response, u'Empty POST Template', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e))
'Template assertions work when there are multiple contexts'
def test_multiple_context(self):
post_data = {u'text': u'Hello World', u'email': u'[email protected]', u'value': 37, u'single': u'b', u'multi': (u'b', u'c', u'e')} response = self.client.post(u'/test_client/form_view_with_template/', post_data) self.assertContains(response, u'POST data OK') try: self.assertTemplateNotUsed(response, u'form_view.html') except AssertionError as e: self.assertIn(u"Template 'form_view.html' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateNotUsed(response, u'base.html') except AssertionError as e: self.assertIn(u"Template 'base.html' was used unexpectedly in rendering the response", str(e)) try: self.assertTemplateUsed(response, u'Valid POST Template') except AssertionError as e: self.assertIn(u"Template 'Valid POST Template' was not a template used to render the response. Actual template(s) used: form_view.html, base.html", str(e))
'An assertion is raised if the original page couldn\'t be retrieved as expected'
def test_redirect_page(self):
response = self.client.get(u'/test_client/permanent_redirect_view/') try: self.assertRedirects(response, u'/test_client/get_view/') except AssertionError as e: self.assertIn(u"Response didn't redirect as expected: Response code was 301 (expected 302)", str(e)) try: self.assertRedirects(response, u'/test_client/get_view/', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
'An assertion is raised if the redirect location doesn\'t preserve GET parameters'
def test_lost_query(self):
response = self.client.get(u'/test_client/redirect_view/', {u'var': u'value'}) try: self.assertRedirects(response, u'/test_client/get_view/') except AssertionError as e: self.assertIn(u"Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e)) try: self.assertRedirects(response, u'/test_client/get_view/', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e))
'An assertion is raised if the response redirects to another target'
def test_incorrect_target(self):
response = self.client.get(u'/test_client/permanent_redirect_view/') try: self.assertRedirects(response, u'/test_client/some_view/') except AssertionError as e: self.assertIn(u"Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
'An assertion is raised if the response redirect target cannot be retrieved as expected'
def test_target_page(self):
response = self.client.get(u'/test_client/double_redirect_view/') try: self.assertRedirects(response, u'http://testserver/test_client/permanent_redirect_view/') except AssertionError as e: self.assertIn(u"Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e)) try: self.assertRedirects(response, u'http://testserver/test_client/permanent_redirect_view/', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e))
'You can follow a redirect chain of multiple redirects'
def test_redirect_chain(self):
response = self.client.get(u'/test_client_regress/redirects/further/more/', {}, follow=True) self.assertRedirects(response, u'/test_client_regress/no_template_view/', status_code=301, target_status_code=200) self.assertEqual(len(response.redirect_chain), 1) self.assertEqual(response.redirect_chain[0], (u'http://testserver/test_client_regress/no_template_view/', 301))
'You can follow a redirect chain of multiple redirects'
def test_multiple_redirect_chain(self):
response = self.client.get(u'/test_client_regress/redirects/', {}, follow=True) self.assertRedirects(response, u'/test_client_regress/no_template_view/', status_code=301, target_status_code=200) self.assertEqual(len(response.redirect_chain), 3) self.assertEqual(response.redirect_chain[0], (u'http://testserver/test_client_regress/redirects/further/', 301)) self.assertEqual(response.redirect_chain[1], (u'http://testserver/test_client_regress/redirects/further/more/', 301)) self.assertEqual(response.redirect_chain[2], (u'http://testserver/test_client_regress/no_template_view/', 301))
'You can follow a chain to a non-existent view'
def test_redirect_chain_to_non_existent(self):
response = self.client.get(u'/test_client_regress/redirect_to_non_existent_view2/', {}, follow=True) self.assertRedirects(response, u'/test_client_regress/non_existent_view/', status_code=301, target_status_code=404)
'Redirections to self are caught and escaped'
def test_redirect_chain_to_self(self):
response = self.client.get(u'/test_client_regress/redirect_to_self/', {}, follow=True) self.assertRedirects(response, u'/test_client_regress/redirect_to_self/', status_code=301, target_status_code=301) self.assertEqual(len(response.redirect_chain), 2)
'Circular redirect chains are caught and escaped'
def test_circular_redirect(self):
response = self.client.get(u'/test_client_regress/circular_redirect_1/', {}, follow=True) self.assertRedirects(response, u'/test_client_regress/circular_redirect_2/', status_code=301, target_status_code=301) self.assertEqual(len(response.redirect_chain), 4)
'A redirect chain will be followed from an initial POST post'
def test_redirect_chain_post(self):
response = self.client.post(u'/test_client_regress/redirects/', {u'nothing': u'to_send'}, follow=True) self.assertRedirects(response, u'/test_client_regress/no_template_view/', 301, 200) self.assertEqual(len(response.redirect_chain), 3)
'A redirect chain will be followed from an initial HEAD request'
def test_redirect_chain_head(self):
response = self.client.head(u'/test_client_regress/redirects/', {u'nothing': u'to_send'}, follow=True) self.assertRedirects(response, u'/test_client_regress/no_template_view/', 301, 200) self.assertEqual(len(response.redirect_chain), 3)
'A redirect chain will be followed from an initial OPTIONS request'
def test_redirect_chain_options(self):
response = self.client.options(u'/test_client_regress/redirects/', follow=True) self.assertRedirects(response, u'/test_client_regress/no_template_view/', 301, 200) self.assertEqual(len(response.redirect_chain), 3)
'A redirect chain will be followed from an initial PUT request'
def test_redirect_chain_put(self):
response = self.client.put(u'/test_client_regress/redirects/', follow=True) self.assertRedirects(response, u'/test_client_regress/no_template_view/', 301, 200) self.assertEqual(len(response.redirect_chain), 3)
'A redirect chain will be followed from an initial DELETE request'
def test_redirect_chain_delete(self):
response = self.client.delete(u'/test_client_regress/redirects/', follow=True) self.assertRedirects(response, u'/test_client_regress/no_template_view/', 301, 200) self.assertEqual(len(response.redirect_chain), 3)
'The test client will preserve scheme, host and port changes'
def test_redirect_to_different_host(self):
response = self.client.get(u'/test_client_regress/redirect_other_host/', follow=True) self.assertRedirects(response, u'https://otherserver:8443/test_client_regress/no_template_view/', status_code=301, target_status_code=200) self.assertEqual(response.request.get(u'wsgi.url_scheme'), u'https') self.assertEqual(response.request.get(u'SERVER_NAME'), u'otherserver') self.assertEqual(response.request.get(u'SERVER_PORT'), u'8443')
'An assertion is raised if the original page couldn\'t be retrieved as expected'
def test_redirect_chain_on_non_redirect_page(self):
response = self.client.get(u'/test_client/get_view/', follow=True) try: self.assertRedirects(response, u'/test_client/get_view/') except AssertionError as e: self.assertIn(u"Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) try: self.assertRedirects(response, u'/test_client/get_view/', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
'An assertion is raised if the original page couldn\'t be retrieved as expected'
def test_redirect_on_non_redirect_page(self):
response = self.client.get(u'/test_client/get_view/') try: self.assertRedirects(response, u'/test_client/get_view/') except AssertionError as e: self.assertIn(u"Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) try: self.assertRedirects(response, u'/test_client/get_view/', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
'An assertion is raised if the form name is unknown'
def test_unknown_form(self):
post_data = {u'text': u'Hello World', u'email': u'not an email address', u'value': 37, u'single': u'b', u'multi': (u'b', u'c', u'e')} response = self.client.post(u'/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, u'Invalid POST Template') try: self.assertFormError(response, u'wrong_form', u'some_field', u'Some error.') except AssertionError as e: self.assertIn(u"The form 'wrong_form' was not used to render the response", str(e)) try: self.assertFormError(response, u'wrong_form', u'some_field', u'Some error.', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: The form 'wrong_form' was not used to render the response", str(e))
'An assertion is raised if the field name is unknown'
def test_unknown_field(self):
post_data = {u'text': u'Hello World', u'email': u'not an email address', u'value': 37, u'single': u'b', u'multi': (u'b', u'c', u'e')} response = self.client.post(u'/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, u'Invalid POST Template') try: self.assertFormError(response, u'form', u'some_field', u'Some error.') except AssertionError as e: self.assertIn(u"The form 'form' in context 0 does not contain the field 'some_field'", str(e)) try: self.assertFormError(response, u'form', u'some_field', u'Some error.', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: The form 'form' in context 0 does not contain the field 'some_field'", str(e))
'An assertion is raised if the field doesn\'t have any errors'
def test_noerror_field(self):
post_data = {u'text': u'Hello World', u'email': u'not an email address', u'value': 37, u'single': u'b', u'multi': (u'b', u'c', u'e')} response = self.client.post(u'/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, u'Invalid POST Template') try: self.assertFormError(response, u'form', u'value', u'Some error.') except AssertionError as e: self.assertIn(u"The field 'value' on form 'form' in context 0 contains no errors", str(e)) try: self.assertFormError(response, u'form', u'value', u'Some error.', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: The field 'value' on form 'form' in context 0 contains no errors", str(e))
'An assertion is raised if the field doesn\'t contain the provided error'
def test_unknown_error(self):
post_data = {u'text': u'Hello World', u'email': u'not an email address', u'value': 37, u'single': u'b', u'multi': (u'b', u'c', u'e')} response = self.client.post(u'/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, u'Invalid POST Template') try: self.assertFormError(response, u'form', u'email', u'Some error.') except AssertionError as e: self.assertIn(str_prefix(u"The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [%(_)s'Enter a valid email address.'])"), str(e)) try: self.assertFormError(response, u'form', u'email', u'Some error.', msg_prefix=u'abc') except AssertionError as e: self.assertIn(str_prefix(u"abc: The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [%(_)s'Enter a valid email address.'])"), str(e))
'Checks that an assertion is raised if the form\'s non field errors doesn\'t contain the provided error.'
def test_unknown_nonfield_error(self):
post_data = {u'text': u'Hello World', u'email': u'not an email address', u'value': 37, u'single': u'b', u'multi': (u'b', u'c', u'e')} response = self.client.post(u'/test_client/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, u'Invalid POST Template') try: self.assertFormError(response, u'form', None, u'Some error.') except AssertionError as e: self.assertIn(u"The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e)) try: self.assertFormError(response, u'form', None, u'Some error.', msg_prefix=u'abc') except AssertionError as e: self.assertIn(u"abc: The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e))
'Check that using a different test client doesn\'t violate authentication'
def test_login_different_client(self):
c = Client() login = c.login(username=u'testclient', password=u'password') self.assertTrue(login, u'Could not log in') response = c.get(u'/test_client_regress/login_protected_redirect_view/') self.assertRedirects(response, u'http://testserver/test_client_regress/get_view/')
'A session engine that modifies the session key can be used to log in'
def test_login(self):
login = self.client.login(username=u'testclient', password=u'password') self.assertTrue(login, u'Could not log in') response = self.client.get(u'/test_client/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context[u'user'].username, u'testclient')
'Get a view that has a simple string argument'
def test_simple_argument_get(self):
response = self.client.get(reverse(u'arg_view', args=[u'Slartibartfast'])) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Howdy, Slartibartfast')
'Get a view that has a string argument that requires escaping'
def test_argument_with_space_get(self):
response = self.client.get(reverse(u'arg_view', args=[u'Arthur Dent'])) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Hi, Arthur')
'Post for a view that has a simple string argument'
def test_simple_argument_post(self):
response = self.client.post(reverse(u'arg_view', args=[u'Slartibartfast'])) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Howdy, Slartibartfast')
'Post for a view that has a string argument that requires escaping'
def test_argument_with_space_post(self):
response = self.client.post(reverse(u'arg_view', args=[u'Arthur Dent'])) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'Hi, Arthur')
'#5836 - A stale user exception isn\'t re-raised by the test client.'
def test_exception_cleared(self):
login = self.client.login(username=u'testclient', password=u'password') self.assertTrue(login, u'Could not log in') try: response = self.client.get(u'/test_client_regress/staff_only/') self.fail(u'General users should not be able to visit this page') except SuspiciousOperation: pass login = self.client.login(username=u'staff', password=u'password') self.assertTrue(login, u'Could not log in') try: self.client.get(u'/test_client_regress/staff_only/') except SuspiciousOperation: self.fail(u'Staff should be able to visit this page')
'Errors found when rendering 404 error templates are re-raised'
@override_settings(TEMPLATE_DIRS=(os.path.join(os.path.dirname(upath(__file__)), u'bad_templates'),)) def test_bad_404_template(self):
try: response = self.client.get(u'/no_such_view/') self.fail(u'Should get error about syntax error in template') except TemplateSyntaxError: pass
'TestCase can enforce a custom URLconf on a per-test basis'
def test_urlconf_was_changed(self):
url = reverse(u'arg_view', args=[u'somename']) self.assertEqual(url, u'/arg_view/somename/')
'URLconf is reverted to original value after modification in a TestCase'
def test_urlconf_was_reverted(self):
url = reverse(u'arg_view', args=[u'somename']) self.assertEqual(url, u'/test_client_regress/arg_view/somename/')
'Context variables can be retrieved from a single context'
def test_single_context(self):
response = self.client.get(u'/test_client_regress/request_data/', data={u'foo': u'whiz'}) self.assertEqual(response.context.__class__, Context) self.assertTrue((u'get-foo' in response.context)) self.assertEqual(response.context[u'get-foo'], u'whiz') self.assertEqual(response.context[u'request-foo'], u'whiz') self.assertEqual(response.context[u'data'], u'sausage') try: response.context[u'does-not-exist'] self.fail(u'Should not be able to retrieve non-existent key') except KeyError as e: self.assertEqual(e.args[0], u'does-not-exist')
'Context variables can be retrieved from a list of contexts'
def test_inherited_context(self):
response = self.client.get(u'/test_client_regress/request_data_extended/', data={u'foo': u'whiz'}) self.assertEqual(response.context.__class__, ContextList) self.assertEqual(len(response.context), 2) self.assertTrue((u'get-foo' in response.context)) self.assertEqual(response.context[u'get-foo'], u'whiz') self.assertEqual(response.context[u'request-foo'], u'whiz') self.assertEqual(response.context[u'data'], u'bacon') try: response.context[u'does-not-exist'] self.fail(u'Should not be able to retrieve non-existent key') except KeyError as e: self.assertEqual(e.args[0], u'does-not-exist')
'The session isn\'t lost if a user logs in'
def test_session(self):
response = self.client.get(u'/test_client_regress/check_session/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'NO') response = self.client.get(u'/test_client_regress/set_session/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'set_session') response = self.client.get(u'/test_client_regress/check_session/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'YES') login = self.client.login(username=u'testclient', password=u'password') self.assertTrue(login, u'Could not log in') response = self.client.get(u'/test_client_regress/check_session/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'YES')
'Logout should work whether the user is logged in or not (#9978).'
def test_logout(self):
self.client.logout() login = self.client.login(username=u'testclient', password=u'password') self.assertTrue(login, u'Could not log in') self.client.logout() self.client.logout()
'Request a view via request method GET'
def test_get(self):
response = self.client.get(u'/test_client_regress/request_methods/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: GET')
'Request a view via request method POST'
def test_post(self):
response = self.client.post(u'/test_client_regress/request_methods/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: POST')
'Request a view via request method HEAD'
def test_head(self):
response = self.client.head(u'/test_client_regress/request_methods/') self.assertEqual(response.status_code, 200) self.assertNotEqual(response.content, 'request method: HEAD') self.assertEqual(response.content, '')
'Request a view via request method OPTIONS'
def test_options(self):
response = self.client.options(u'/test_client_regress/request_methods/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: OPTIONS')
'Request a view via request method PUT'
def test_put(self):
response = self.client.put(u'/test_client_regress/request_methods/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: PUT')
'Request a view via request method DELETE'
def test_delete(self):
response = self.client.delete(u'/test_client_regress/request_methods/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: DELETE')
'Request a view with string data via request method POST'
def test_post(self):
data = u'{"test": "json"}' response = self.client.post(u'/test_client_regress/request_methods/', data=data, content_type=u'application/json') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: POST')
'Request a view with string data via request method PUT'
def test_put(self):
data = u'{"test": "json"}' response = self.client.put(u'/test_client_regress/request_methods/', data=data, content_type=u'application/json') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'request method: PUT')
'A simple ASCII-only unicode JSON document can be POSTed'
def test_simple_unicode_payload(self):
json = u'{"english": "mountain pass"}' response = self.client.post(u'/test_client_regress/parse_unicode_json/', json, content_type=u'application/json') self.assertEqual(response.content, json.encode())
'A non-ASCII unicode data encoded as UTF-8 can be POSTed'
def test_unicode_payload_utf8(self):
json = u'{"dog": "\u0441\u043e\u0431\u0430\u043a\u0430"}' response = self.client.post(u'/test_client_regress/parse_unicode_json/', json, content_type=u'application/json; charset=utf-8') self.assertEqual(response.content, json.encode(u'utf-8'))
'A non-ASCII unicode data encoded as UTF-16 can be POSTed'
def test_unicode_payload_utf16(self):
json = u'{"dog": "\u0441\u043e\u0431\u0430\u043a\u0430"}' response = self.client.post(u'/test_client_regress/parse_unicode_json/', json, content_type=u'application/json; charset=utf-16') self.assertEqual(response.content, json.encode(u'utf-16'))
'A non-ASCII unicode data as a non-UTF based encoding can be POSTed'
def test_unicode_payload_non_utf(self):
json = u'{"dog": "\u0441\u043e\u0431\u0430\u043a\u0430"}' response = self.client.post(u'/test_client_regress/parse_unicode_json/', json, content_type=u'application/json; charset=koi8-r') self.assertEqual(response.content, json.encode(u'koi8-r'))
'A test client can receive custom headers'
def test_client_headers(self):
response = self.client.get(u'/test_client_regress/check_headers/', HTTP_X_ARG_CHECK=u'Testing 123') self.assertEqual(response.content, 'HTTP_X_ARG_CHECK: Testing 123') self.assertEqual(response.status_code, 200)
'Test client headers are preserved through redirects'
def test_client_headers_redirect(self):
response = self.client.get(u'/test_client_regress/check_headers_redirect/', follow=True, HTTP_X_ARG_CHECK=u'Testing 123') self.assertEqual(response.content, 'HTTP_X_ARG_CHECK: Testing 123') self.assertRedirects(response, u'/test_client_regress/check_headers/', status_code=301, target_status_code=200)
'HttpRequest.body on a test client GET request should return the empty string.'
def test_body_from_empty_request(self):
self.assertEqual(self.client.get(u'/test_client_regress/body/').content, '')
'HttpRequest.read() on a test client GET request should return the empty string.'
def test_read_from_empty_request(self):
self.assertEqual(self.client.get(u'/test_client_regress/read_all/').content, '')
'HttpRequest.read(LARGE_BUFFER) on a test client GET request should return the empty string.'
def test_read_numbytes_from_empty_request(self):
self.assertEqual(self.client.get(u'/test_client_regress/read_buffer/').content, '')
'HttpRequest.read() on a test client PUT request with some payload should return that payload.'
def test_read_from_nonempty_request(self):
payload = 'foobar' self.assertEqual(self.client.put(u'/test_client_regress/read_all/', data=payload, content_type=u'text/plain').content, payload)
'HttpRequest.read(LARGE_BUFFER) on a test client PUT request with some payload should return that payload.'
def test_read_numbytes_from_nonempty_request(self):
payload = 'foobar' self.assertEqual(self.client.put(u'/test_client_regress/read_buffer/', data=payload, content_type=u'text/plain').content, payload)
'Tests that URLs with slashes go unmolested.'
def test_append_slash_have_slash(self):
settings.APPEND_SLASH = True request = self._get_request(u'slash/') self.assertEqual(CommonMiddleware().process_request(request), None)
'Tests that matches to explicit slashless URLs go unmolested.'
def test_append_slash_slashless_resource(self):
settings.APPEND_SLASH = True request = self._get_request(u'noslash') self.assertEqual(CommonMiddleware().process_request(request), None)
'Tests that APPEND_SLASH doesn\'t redirect to unknown resources.'
def test_append_slash_slashless_unknown(self):
settings.APPEND_SLASH = True request = self._get_request(u'unknown') self.assertEqual(CommonMiddleware().process_request(request), None)
'Tests that APPEND_SLASH redirects slashless URLs to a valid pattern.'
def test_append_slash_redirect(self):
settings.APPEND_SLASH = True request = self._get_request(u'slash') r = CommonMiddleware().process_request(request) self.assertEqual(r.status_code, 301) self.assertEqual(r[u'Location'], u'http://testserver/middleware/slash/')
'Tests that while in debug mode, an exception is raised with a warning when a failed attempt is made to POST to an URL which would normally be redirected to a slashed version.'
def test_append_slash_no_redirect_on_POST_in_DEBUG(self):
settings.APPEND_SLASH = True settings.DEBUG = True request = self._get_request(u'slash') request.method = u'POST' self.assertRaises(RuntimeError, CommonMiddleware().process_request, request) try: CommonMiddleware().process_request(request) except RuntimeError as e: self.assertTrue((u'end in a slash' in str(e))) settings.DEBUG = False
'Tests disabling append slash functionality.'
def test_append_slash_disabled(self):
settings.APPEND_SLASH = False request = self._get_request(u'slash') self.assertEqual(CommonMiddleware().process_request(request), None)
'Tests that URLs which require quoting are redirected to their slash version ok.'
def test_append_slash_quoted(self):
settings.APPEND_SLASH = True request = self._get_request(u'needsquoting#') r = CommonMiddleware().process_request(request) self.assertEqual(r.status_code, 301) self.assertEqual(r[u'Location'], u'http://testserver/middleware/needsquoting%23/')
'Tests that URLs with slashes go unmolested.'
def test_append_slash_have_slash_custom_urlconf(self):
settings.APPEND_SLASH = True request = self._get_request(u'customurlconf/slash/') request.urlconf = u'regressiontests.middleware.extra_urls' self.assertEqual(CommonMiddleware().process_request(request), None)
'Tests that matches to explicit slashless URLs go unmolested.'
def test_append_slash_slashless_resource_custom_urlconf(self):
settings.APPEND_SLASH = True request = self._get_request(u'customurlconf/noslash') request.urlconf = u'regressiontests.middleware.extra_urls' self.assertEqual(CommonMiddleware().process_request(request), None)
'Tests that APPEND_SLASH doesn\'t redirect to unknown resources.'
def test_append_slash_slashless_unknown_custom_urlconf(self):
settings.APPEND_SLASH = True request = self._get_request(u'customurlconf/unknown') request.urlconf = u'regressiontests.middleware.extra_urls' self.assertEqual(CommonMiddleware().process_request(request), None)
'Tests that APPEND_SLASH redirects slashless URLs to a valid pattern.'
def test_append_slash_redirect_custom_urlconf(self):
settings.APPEND_SLASH = True request = self._get_request(u'customurlconf/slash') request.urlconf = u'regressiontests.middleware.extra_urls' r = CommonMiddleware().process_request(request) self.assertFalse((r is None), u'CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf') self.assertEqual(r.status_code, 301) self.assertEqual(r[u'Location'], u'http://testserver/middleware/customurlconf/slash/')
'Tests that while in debug mode, an exception is raised with a warning when a failed attempt is made to POST to an URL which would normally be redirected to a slashed version.'
def test_append_slash_no_redirect_on_POST_in_DEBUG_custom_urlconf(self):
settings.APPEND_SLASH = True settings.DEBUG = True request = self._get_request(u'customurlconf/slash') request.urlconf = u'regressiontests.middleware.extra_urls' request.method = u'POST' self.assertRaises(RuntimeError, CommonMiddleware().process_request, request) try: CommonMiddleware().process_request(request) except RuntimeError as e: self.assertTrue((u'end in a slash' in str(e))) settings.DEBUG = False
'Tests disabling append slash functionality.'
def test_append_slash_disabled_custom_urlconf(self):
settings.APPEND_SLASH = False request = self._get_request(u'customurlconf/slash') request.urlconf = u'regressiontests.middleware.extra_urls' self.assertEqual(CommonMiddleware().process_request(request), None)
'Tests that URLs which require quoting are redirected to their slash version ok.'
def test_append_slash_quoted_custom_urlconf(self):
settings.APPEND_SLASH = True request = self._get_request(u'customurlconf/needsquoting#') request.urlconf = u'regressiontests.middleware.extra_urls' r = CommonMiddleware().process_request(request) self.assertFalse((r is None), u'CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf') self.assertEqual(r.status_code, 301) self.assertEqual(r[u'Location'], u'http://testserver/middleware/customurlconf/needsquoting%23/')
'Regression test for #15152'
def test_non_ascii_query_string_does_not_crash(self):
request = self._get_request(u'slash') request.META[u'QUERY_STRING'] = force_str(u'drink=caf\xe9') response = CommonMiddleware().process_request(request) self.assertEqual(response.status_code, 301)
'Tests that the X_FRAME_OPTIONS setting can be set to SAMEORIGIN to have the middleware use that value for the HTTP header.'
def test_same_origin(self):
settings.X_FRAME_OPTIONS = u'SAMEORIGIN' r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse()) self.assertEqual(r[u'X-Frame-Options'], u'SAMEORIGIN') settings.X_FRAME_OPTIONS = u'sameorigin' r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse()) self.assertEqual(r[u'X-Frame-Options'], u'SAMEORIGIN')
'Tests that the X_FRAME_OPTIONS setting can be set to DENY to have the middleware use that value for the HTTP header.'
def test_deny(self):
settings.X_FRAME_OPTIONS = u'DENY' r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse()) self.assertEqual(r[u'X-Frame-Options'], u'DENY') settings.X_FRAME_OPTIONS = u'deny' r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse()) self.assertEqual(r[u'X-Frame-Options'], u'DENY')
'Tests that if the X_FRAME_OPTIONS setting is not set then it defaults to SAMEORIGIN.'
def test_defaults_sameorigin(self):
del settings.X_FRAME_OPTIONS r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse()) self.assertEqual(r[u'X-Frame-Options'], u'SAMEORIGIN')
'Tests that if the X-Frame-Options header is already set then the middleware does not attempt to override it.'
def test_dont_set_if_set(self):
settings.X_FRAME_OPTIONS = u'DENY' response = HttpResponse() response[u'X-Frame-Options'] = u'SAMEORIGIN' r = XFrameOptionsMiddleware().process_response(HttpRequest(), response) self.assertEqual(r[u'X-Frame-Options'], u'SAMEORIGIN') settings.X_FRAME_OPTIONS = u'SAMEORIGIN' response = HttpResponse() response[u'X-Frame-Options'] = u'DENY' r = XFrameOptionsMiddleware().process_response(HttpRequest(), response) self.assertEqual(r[u'X-Frame-Options'], u'DENY')
'Tests that if the response has a xframe_options_exempt attribute set to False then it still sets the header, but if it\'s set to True then it does not.'
def test_response_exempt(self):
settings.X_FRAME_OPTIONS = u'SAMEORIGIN' response = HttpResponse() response.xframe_options_exempt = False r = XFrameOptionsMiddleware().process_response(HttpRequest(), response) self.assertEqual(r[u'X-Frame-Options'], u'SAMEORIGIN') response = HttpResponse() response.xframe_options_exempt = True r = XFrameOptionsMiddleware().process_response(HttpRequest(), response) self.assertEqual(r.get(u'X-Frame-Options', None), None)
'Tests that the XFrameOptionsMiddleware method that determines the X-Frame-Options header value can be overridden based on something in the request or response.'
def test_is_extendable(self):
class OtherXFrameOptionsMiddleware(XFrameOptionsMiddleware, ): def get_xframe_options_value(self, request, response): if getattr(request, u'sameorigin', False): return u'SAMEORIGIN' if getattr(response, u'sameorigin', False): return u'SAMEORIGIN' return u'DENY' settings.X_FRAME_OPTIONS = u'DENY' response = HttpResponse() response.sameorigin = True r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), response) self.assertEqual(r[u'X-Frame-Options'], u'SAMEORIGIN') request = HttpRequest() request.sameorigin = True r = OtherXFrameOptionsMiddleware().process_response(request, HttpResponse()) self.assertEqual(r[u'X-Frame-Options'], u'SAMEORIGIN') settings.X_FRAME_OPTIONS = u'SAMEORIGIN' r = OtherXFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse()) self.assertEqual(r[u'X-Frame-Options'], u'DENY')
'Tests that compression is performed on responses with compressible content.'
def test_compress_response(self):
r = GZipMiddleware().process_response(self.req, self.resp) self.assertEqual(self.decompress(r.content), self.compressible_string) self.assertEqual(r.get(u'Content-Encoding'), u'gzip') self.assertEqual(r.get(u'Content-Length'), str(len(r.content)))
'Tests that compression is performed on responses with streaming content.'
def test_compress_streaming_response(self):
r = GZipMiddleware().process_response(self.req, self.stream_resp) self.assertEqual(self.decompress(''.join(r)), ''.join(self.sequence)) self.assertEqual(r.get(u'Content-Encoding'), u'gzip') self.assertFalse(r.has_header(u'Content-Length'))
'Tests that compression is performed on responses with a status other than 200. See #10762.'
def test_compress_non_200_response(self):
self.resp.status_code = 404 r = GZipMiddleware().process_response(self.req, self.resp) self.assertEqual(self.decompress(r.content), self.compressible_string) self.assertEqual(r.get(u'Content-Encoding'), u'gzip')
'Tests that compression isn\'t performed on responses with short content.'
def test_no_compress_short_response(self):
self.resp.content = self.short_string r = GZipMiddleware().process_response(self.req, self.resp) self.assertEqual(r.content, self.short_string) self.assertEqual(r.get(u'Content-Encoding'), None)
'Tests that compression isn\'t performed on responses that are already compressed.'
def test_no_compress_compressed_response(self):
self.resp[u'Content-Encoding'] = u'deflate' r = GZipMiddleware().process_response(self.req, self.resp) self.assertEqual(r.content, self.compressible_string) self.assertEqual(r.get(u'Content-Encoding'), u'deflate')
'Tests that compression isn\'t performed on JavaScript requests from Internet Explorer.'
def test_no_compress_ie_js_requests(self):
self.req.META[u'HTTP_USER_AGENT'] = u'Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)' self.resp[u'Content-Type'] = u'application/javascript; charset=UTF-8' r = GZipMiddleware().process_response(self.req, self.resp) self.assertEqual(r.content, self.compressible_string) self.assertEqual(r.get(u'Content-Encoding'), None)
'Tests that compression isn\'t performed on responses with uncompressible content.'
def test_no_compress_uncompressible_response(self):
self.resp.content = self.uncompressible_string r = GZipMiddleware().process_response(self.req, self.resp) self.assertEqual(r.content, self.uncompressible_string) self.assertEqual(r.get(u'Content-Encoding'), None)
'Tests that ETag is changed after gzip compression is performed.'
def test_compress_response(self):
request = self.rf.get(u'/', HTTP_ACCEPT_ENCODING=u'gzip, deflate') response = GZipMiddleware().process_response(request, CommonMiddleware().process_response(request, HttpResponse(self.compressible_string))) gzip_etag = response.get(u'ETag') request = self.rf.get(u'/', HTTP_ACCEPT_ENCODING=u'') response = GZipMiddleware().process_response(request, CommonMiddleware().process_response(request, HttpResponse(self.compressible_string))) nogzip_etag = response.get(u'ETag') self.assertNotEqual(gzip_etag, nogzip_etag)
'# Regression test for #8027: custom ModelForms with fields/fieldsets'
def test_custom_modelforms_with_fields_fieldsets(self):
validate(ValidFields, Song) self.assertRaisesMessage(ImproperlyConfigured, "'InvalidFields.fields' refers to field 'spam' that is missing from the form.", validate, InvalidFields, Song)