desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'If we\'re not under txn management, the txn will never be
marked as dirty.'
| @skipUnlessDBFeature('has_select_for_update')
def test_transaction_not_dirty_unmanaged(self):
| transaction.managed(False)
transaction.leave_transaction_management()
people = list(Person.objects.select_for_update())
self.assertFalse(transaction.is_dirty())
|
'Test that we can clear the behavior by calling prefetch_related()'
| def test_clear(self):
| with self.assertNumQueries(5):
with_prefetch = Author.objects.prefetch_related('books')
without_prefetch = with_prefetch.prefetch_related(None)
lists = [list(a.books.all()) for a in without_prefetch]
|
'Test we can follow a m2m and another m2m'
| def test_m2m_then_m2m(self):
| with self.assertNumQueries(3):
qs = Author.objects.prefetch_related('books__read_by')
lists = [[[unicode(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs]
self.assertEqual(lists, [[[u'Amy'], [u'Belinda']], [[u'Amy']], [[u'Amy'], []], [[u'Amy', u'Belinda']]])
|
'Test that objects retrieved with .get() get the prefetch behavior.'
| def test_get(self):
| with self.assertNumQueries(3):
author = Author.objects.prefetch_related('books__read_by').get(name='Charlotte')
lists = [[unicode(r) for r in b.read_by.all()] for b in author.books.all()]
self.assertEqual(lists, [[u'Amy'], [u'Belinda']])
|
'Test we can follow an m2m relation after a relation like ForeignKey
that doesn\'t have many objects'
| def test_foreign_key_then_m2m(self):
| with self.assertNumQueries(2):
qs = Author.objects.select_related('first_book').prefetch_related('first_book__read_by')
lists = [[unicode(r) for r in a.first_book.read_by.all()] for a in qs]
self.assertEqual(lists, [[u'Amy'], [u'Amy'], [u'Amy'], [u'Amy', 'Belinda']])
|
'Test that we can traverse a \'content_object\' with prefetch_related() and
get to related objects on the other side (assuming it is suitably
filtered)'
| def test_traverse_GFK(self):
| TaggedItem.objects.create(tag='awesome', content_object=self.book1)
TaggedItem.objects.create(tag='awesome', content_object=self.book2)
TaggedItem.objects.create(tag='awesome', content_object=self.book3)
TaggedItem.objects.create(tag='awesome', content_object=self.reader1)
TaggedItem.objects.create(... |
'In-bulk does correctly prefetch objects by not using .iterator()
directly.'
| def test_in_bulk(self):
| boss1 = Employee.objects.create(name='Peter')
boss2 = Employee.objects.create(name='Jack')
with self.assertNumQueries(2):
bulk = Employee.objects.prefetch_related('serfs').in_bulk([boss1.pk, boss2.pk])
for b in bulk.values():
list(b.serfs.all())
|
'GET a view'
| def test_get_view(self):
| data = {'var': u'\xf2'}
response = self.client.get('/test_client/get_view/', data)
self.assertContains(response, 'This is a test')
self.assertEqual(response.context['var'], u'\xf2')
self.assertEqual(response.templates[0].name, 'GET Template')
|
'GET a view that normally expects POSTs'
| def test_get_post_view(self):
| response = self.client.get('/test_client/post_view/', {})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.templates[0].name, 'Empty GET Template')
self.assertTemplateUsed(response, 'Empty GET Template')
self.assertTemplateNotUsed(response, 'Empty POST Template... |
'POST an empty dictionary to a view'
| def test_empty_post(self):
| response = self.client.post('/test_client/post_view/', {})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.templates[0].name, 'Empty POST Template')
self.assertTemplateNotUsed(response, 'Empty GET Template')
self.assertTemplateUsed(response, 'Empty POST Templa... |
'POST some data to a view'
| def test_post(self):
| post_data = {'value': 37}
response = self.client.post('/test_client/post_view/', post_data)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['data'], '37')
self.assertEqual(response.templates[0].name, 'POST Template')
self.assertTrue(('Data received' in respons... |
'Check the value of HTTP headers returned in a response'
| def test_response_headers(self):
| response = self.client.get('/test_client/header_view/')
self.assertEqual(response['X-DJANGO-TEST'], 'Slartibartfast')
|
'POST raw data (with a content type) to a view'
| def test_raw_post(self):
| test_doc = '<?xml version="1.0" encoding="utf-8"?><library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library>'
response = self.client.post('/test_client/raw_post_view/', test_doc, content_type='text/xml')
self.assertEqual(response.status_code, 200)
self.assertEqual(res... |
'GET a URL that redirects elsewhere'
| def test_redirect(self):
| response = self.client.get('/test_client/redirect_view/')
self.assertRedirects(response, '/test_client/get_view/')
host = 'django.testserver'
client_providing_host = Client(HTTP_HOST=host)
response = client_providing_host.get('/test_client/redirect_view/')
self.assertRedirects(response, '/test_c... |
'GET a URL that redirects with given GET parameters'
| def test_redirect_with_query(self):
| response = self.client.get('/test_client/redirect_view/', {'var': 'value'})
self.assertRedirects(response, 'http://testserver/test_client/get_view/?var=value')
|
'GET a URL that redirects permanently elsewhere'
| def test_permanent_redirect(self):
| response = self.client.get('/test_client/permanent_redirect_view/')
self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=301)
client_providing_host = Client(HTTP_HOST='django.testserver')
response = client_providing_host.get('/test_client/permanent_redirect_view/')
s... |
'GET a URL that does a non-permanent redirect'
| def test_temporary_redirect(self):
| response = self.client.get('/test_client/temporary_redirect_view/')
self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=302)
|
'GET a URL that redirects to a non-200 page'
| def test_redirect_to_strange_location(self):
| response = self.client.get('/test_client/double_redirect_view/')
self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/', target_status_code=301)
|
'A URL that redirects can be followed to termination.'
| def test_follow_redirect(self):
| response = self.client.get('/test_client/double_redirect_view/', follow=True)
self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=302, target_status_code=200)
self.assertEqual(len(response.redirect_chain), 2)
|
'GET a URL that redirects to an http URI'
| def test_redirect_http(self):
| response = self.client.get('/test_client/http_redirect_view/', follow=True)
self.assertFalse(response.test_was_secure_request)
|
'GET a URL that redirects to an https URI'
| def test_redirect_https(self):
| response = self.client.get('/test_client/https_redirect_view/', follow=True)
self.assertTrue(response.test_was_secure_request)
|
'GET a URL that responds as \'404:Not Found\''
| def test_notfound_response(self):
| response = self.client.get('/test_client/bad_view/')
self.assertContains(response, 'MAGIC', status_code=404)
|
'POST valid data to a form'
| def test_valid_form(self):
| post_data = {'text': 'Hello World', 'email': 'foo@example.com', 'value': 37, 'single': 'b', 'multi': ('b', 'c', 'e')}
response = self.client.post('/test_client/form_view/', post_data)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'Valid POST Template')
|
'GET a form, providing hints in the GET data'
| def test_valid_form_with_hints(self):
| hints = {'text': 'Hello World', 'multi': ('b', 'c', 'e')}
response = self.client.get('/test_client/form_view/', data=hints)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'Form GET Template')
self.assertContains(response, 'Select a valid choice.', 0)
|
'POST incomplete data to a form'
| def test_incomplete_data_form(self):
| post_data = {'text': 'Hello World', 'value': 37}
response = self.client.post('/test_client/form_view/', post_data)
self.assertContains(response, 'This field is required.', 3)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'Invalid POST Template')
... |
'POST erroneous data to a form'
| def test_form_error(self):
| post_data = {'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b', 'c', 'e')}
response = self.client.post('/test_client/form_view/', post_data)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'Invalid POST Templ... |
'POST valid data to a form using multiple templates'
| def test_valid_form_with_template(self):
| post_data = {'text': 'Hello World', 'email': 'foo@example.com', 'value': 37, 'single': 'b', 'multi': ('b', 'c', 'e')}
response = self.client.post('/test_client/form_view_with_template/', post_data)
self.assertContains(response, 'POST data OK')
self.assertTemplateUsed(response, 'form_view.html')... |
'POST incomplete data to a form using multiple templates'
| def test_incomplete_data_form_with_template(self):
| post_data = {'text': 'Hello World', 'value': 37}
response = self.client.post('/test_client/form_view_with_template/', post_data)
self.assertContains(response, 'POST data has errors')
self.assertTemplateUsed(response, 'form_view.html')
self.assertTemplateUsed(response, 'base.html')
se... |
'POST erroneous data to a form using multiple templates'
| def test_form_error_with_template(self):
| post_data = {'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b', 'c', 'e')}
response = self.client.post('/test_client/form_view_with_template/', post_data)
self.assertContains(response, 'POST data has errors')
self.assertTemplateUsed(re... |
'GET an invalid URL'
| def test_unknown_page(self):
| response = self.client.get('/test_client/unknown_view/')
self.assertEqual(response.status_code, 404)
|
'Make sure that URL ;-parameters are not stripped.'
| def test_url_parameters(self):
| response = self.client.get('/test_client/unknown_view/;some-parameter')
self.assertEqual(response.request['PATH_INFO'], '/test_client/unknown_view/;some-parameter')
|
'Request a page that is protected with @login_required'
| def test_view_with_login(self):
| response = self.client.get('/test_client/login_protected_view/')
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_view/')
login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in')
respo... |
'Request a page that is protected with a @login_required method'
| def test_view_with_method_login(self):
| response = self.client.get('/test_client/login_protected_method_view/')
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_method_view/')
login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log ... |
'Request a page that is protected with @login_required(redirect_field_name=\'redirect_to\')'
| def test_view_with_login_and_custom_redirect(self):
| response = self.client.get('/test_client/login_protected_view_custom_redirect/')
self.assertRedirects(response, 'http://testserver/accounts/login/?redirect_to=/test_client/login_protected_view_custom_redirect/')
login = self.client.login(username='testclient', password='password')
self.assertTrue(login,... |
'Request a page that is protected with @login, but use bad credentials'
| def test_view_with_bad_login(self):
| login = self.client.login(username='otheruser', password='nopassword')
self.assertFalse(login)
|
'Request a page that is protected with @login, but use an inactive login'
| def test_view_with_inactive_login(self):
| login = self.client.login(username='inactive', password='password')
self.assertFalse(login)
|
'Request a logout after logging in'
| def test_logout(self):
| self.client.login(username='testclient', password='password')
response = self.client.get('/test_client/login_protected_view/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['user'].username, 'testclient')
self.client.logout()
response = self.client.get('/test_clie... |
'Request a page that is protected with @permission_required'
| def test_view_with_permissions(self):
| response = self.client.get('/test_client/permission_protected_view/')
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_view/')
login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in')... |
'Request a page that is protected with @permission_required but raises a exception'
| def test_view_with_permissions_exception(self):
| response = self.client.get('/test_client/permission_protected_view_exception/')
self.assertEquals(response.status_code, 403)
login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in')
response = self.client.get('/test_client/permission_p... |
'Request a page that is protected with a @permission_required method'
| def test_view_with_method_permissions(self):
| response = self.client.get('/test_client/permission_protected_method_view/')
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_method_view/')
login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not ... |
'Request a page that modifies the session'
| def test_session_modifying_view(self):
| try:
self.client.session['tobacconist']
self.fail("Shouldn't have a session value")
except KeyError:
pass
from django.contrib.sessions.models import Session
response = self.client.post('/test_client/session_view/')
self.assertEqual(self.client.session['tobacconist... |
'Request a page that is known to throw an error'
| def test_view_with_exception(self):
| self.assertRaises(KeyError, self.client.get, '/test_client/broken_view/')
try:
self.client.get('/test_client/broken_view/')
self.fail('Should raise an error')
except KeyError:
pass
|
'Test that mail is redirected to a dummy outbox during test setup'
| def test_mail_sending(self):
| response = self.client.get('/test_client/mail_sending_view/')
self.assertEqual(response.status_code, 200)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, 'Test message')
self.assertEqual(mail.outbox[0].body, 'This is a test email')
self.assertEqual(m... |
'Test that mass mail is redirected to a dummy outbox during test setup'
| def test_mass_mail_sending(self):
| response = self.client.get('/test_client/mass_mail_sending_view/')
self.assertEqual(response.status_code, 200)
self.assertEqual(len(mail.outbox), 2)
self.assertEqual(mail.outbox[0].subject, 'First Test message')
self.assertEqual(mail.outbox[0].body, 'This is the first test email... |
'A client can be instantiated with CSRF checks enabled'
| def test_csrf_enabled_client(self):
| csrf_client = Client(enforce_csrf_checks=True)
response = self.client.post('/test_client/post_view/', {})
self.assertEqual(response.status_code, 200)
response = csrf_client.post('/test_client/post_view/', {})
self.assertEqual(response.status_code, 403)
|
'A test case can specify a custom class for self.client.'
| def test_custom_test_client(self):
| self.assertEqual(hasattr(self.client, 'i_am_customized'), True)
|
'Verbose version of get_articles_from_same_day_1, which does a custom
database query for the sake of demonstration.'
| def articles_from_same_day_2(self):
| from django.db import connection
cursor = connection.cursor()
cursor.execute('\n SELECT id, headline, pub_date\n FROM custom_methods_article\n WHERE pub... |
'If a related_name is given you can\'t use the field name instead'
| def test_reverse_field_name_disallowed(self):
| self.assertRaises(FieldError, Poll.objects.get, choice__name__exact='This is the answer')
|
'Test that update changes the right number of rows for a nonempty queryset'
| def test_nonempty_update(self):
| num_updated = self.a1.b_set.update(y=100)
self.assertEqual(num_updated, 20)
cnt = B.objects.filter(y=100).count()
self.assertEqual(cnt, 20)
|
'Test that update changes the right number of rows for an empty queryset'
| def test_empty_update(self):
| num_updated = self.a2.b_set.update(y=100)
self.assertEqual(num_updated, 0)
cnt = B.objects.filter(y=100).count()
self.assertEqual(cnt, 0)
|
'Test that update changes the right number of rows for an empty queryset
when the update affects only a base table'
| def test_nonempty_update_with_inheritance(self):
| num_updated = self.a1.d_set.update(y=100)
self.assertEqual(num_updated, 20)
cnt = D.objects.filter(y=100).count()
self.assertEqual(cnt, 20)
|
'Test that update changes the right number of rows for an empty queryset
when the update affects only a base table'
| def test_empty_update_with_inheritance(self):
| num_updated = self.a2.d_set.update(y=100)
self.assertEqual(num_updated, 0)
cnt = D.objects.filter(y=100).count()
self.assertEqual(cnt, 0)
|
'Objects are updated by first filtering the candidates into a queryset
and then calling the update() method. It executes immediately and
returns nothing.'
| def test_update(self):
| resp = DataPoint.objects.filter(value='apple').update(name='d1')
self.assertEqual(resp, 1)
resp = DataPoint.objects.filter(value='apple')
self.assertEqual(list(resp), [self.d0])
|
'We can update multiple objects at once.'
| def test_update_multiple_objects(self):
| resp = DataPoint.objects.filter(value='banana').update(value='pineapple')
self.assertEqual(resp, 2)
self.assertEqual(DataPoint.objects.get(name='d2').value, u'pineapple')
|
'Foreign key fields can also be updated, although you can only update
the object referred to, not anything inside the related object.'
| def test_update_fk(self):
| resp = RelatedPoint.objects.filter(name='r1').update(data=self.d0)
self.assertEqual(resp, 1)
resp = RelatedPoint.objects.filter(data__name='d0')
self.assertEqual(list(resp), [self.r1])
|
'Multiple fields can be updated at once'
| def test_update_multiple_fields(self):
| resp = DataPoint.objects.filter(value='apple').update(value='fruit', another_value='peach')
self.assertEqual(resp, 1)
d = DataPoint.objects.get(name='d0')
self.assertEqual(d.value, u'fruit')
self.assertEqual(d.another_value, u'peach')
|
'In the rare case you want to update every instance of a model, update()
is also a manager method.'
| def test_update_all(self):
| self.assertEqual(DataPoint.objects.update(value='thing'), 3)
resp = DataPoint.objects.values('value').distinct()
self.assertEqual(list(resp), [{'value': u'thing'}])
|
'We do not support update on already sliced query sets.'
| def test_update_slice_fail(self):
| method = DataPoint.objects.all()[:2].update
self.assertRaises(AssertionError, method, another_value='another thing')
|
'The main test here is that the all the models can be created without
any database errors. We can also do some more simple insertion and
lookup tests whilst we\'re here to show that the second of models do
refer to the tables from the first set.'
| def test_simple(self):
| a = A01.objects.create(f_a='foo', f_b=42)
B01.objects.create(fk_a=a, f_a='fred', f_b=1729)
c = C01.objects.create(f_a='barney', f_b=1)
c.mm_a = [a]
a2 = A02.objects.all()[0]
self.assertTrue(isinstance(a2, A02))
self.assertEqual(a2.f_a, 'foo')
b2 = B02.objects.all()[0]
self.assertTrue... |
'The intermediary table between two unmanaged models should not be created.'
| def test_many_to_many_between_unmanaged(self):
| table = Unmanaged2._meta.get_field('mm').m2m_db_table()
tables = connection.introspection.table_names()
self.assertTrue((table not in tables), ("Table '%s' should not exist, but it does." % table))
|
'An intermediary table between a managed and an unmanaged model should be created.'
| def test_many_to_many_between_unmanaged_and_managed(self):
| table = Managed1._meta.get_field('mm').m2m_db_table()
tables = connection.introspection.table_names()
self.assertTrue((table in tables), ("Table '%s' does not exist." % table))
|
'Ensure select_related together with only on a proxy model behaves
as expected. See #17876.'
| def test_defer_proxy(self):
| related = Secondary.objects.create(first='x1', second='x2')
ChildProxy.objects.create(name='p1', value='xx', related=related)
children = ChildProxy.objects.all().select_related().only('id', 'name')
self.assertEqual(len(children), 1)
child = children[0]
self.assert_delayed(child, 1)
self.asse... |
'Regression test for #6045: references to other models can be unicode
strings, providing they are directly convertible to ASCII.'
| def test_m2m_with_unicode_reference(self):
| m1 = UnicodeReferenceModel.objects.create()
m2 = UnicodeReferenceModel.objects.create()
m2.others.add(m1)
m2.save()
list(m2.others.all())
|
'Ensure that a lookup query containing non-fields raises the proper
exception.'
| def test_nonfield_lookups(self):
| with self.assertRaises(FieldError):
Article.objects.filter(headline__blahblah=99)
with self.assertRaises(FieldError):
Article.objects.filter(headline__blahblah__exact=99)
with self.assertRaises(FieldError):
Article.objects.filter(blahblah=99)
|
'Ensure that genuine field names don\'t collide with built-in lookup
types (\'year\', \'gt\', \'range\', \'in\' etc.).
Refs #11670.'
| def test_lookup_collision(self):
| season_2009 = Season.objects.create(year=2009, gt=111)
season_2009.games.create(home='Houston Astros', away='St. Louis Cardinals')
season_2010 = Season.objects.create(year=2010, gt=222)
season_2010.games.create(home='Houston Astros', away='Chicago Cubs')
season_2010.games.create(home=... |
'QuerySet.distinct(\'field\', ...) works'
| @skipUnlessDBFeature('can_distinct_on_fields')
def test_basic_distinct_on(self):
| qsets = ((Staff.objects.distinct().order_by('name'), ['<Staff: p1>', '<Staff: p1>', '<Staff: p2>', '<Staff: p3>']), (Staff.objects.distinct('name').order_by('name'), ['<Staff: p1>', '<Staff: p2>', '<Staff: p3>']), (Staff.objects.distinct('organisation').order_by('organisation', 'name'), ['<Staf... |
'Test the {% localtime %} templatetag and related filters.'
| @requires_tz_support
def test_localtime_templatetag_and_filters(self):
| datetimes = {'utc': datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC), 'eat': datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), 'ict': datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT), 'naive': datetime.datetime(2011, 9, 1, 13, 20, 30)}
templates = {'notag': Template('{% load tz %}{{ d... |
'Test the |localtime, |utc, and |timezone filters with pytz.'
| @skipIf((pytz is None), 'this test requires pytz')
def test_localtime_filters_with_pytz(self):
| tpl = Template('{% load tz %}{{ dt|localtime }}|{{ dt|utc }}')
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 12, 20, 30)})
timezone._localtime = None
with self.settings(TIME_ZONE='Europe/Paris'):
self.assertEqual(tpl.render(ctx), '2011-09-01T12:20:30+02:00|2011-09-01T10... |
'Test the |localtime, |utc, and |timezone filters on bad inputs.'
| def test_localtime_filters_do_not_raise_exceptions(self):
| tpl = Template('{% load tz %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:tz }}')
with self.settings(USE_TZ=True):
ctx = Context({'dt': None, 'tz': ICT})
self.assertEqual(tpl.render(ctx), 'None|||')
ctx = Context({'dt': 'not a date', 'tz'... |
'Test the {% timezone %} templatetag.'
| @requires_tz_support
def test_timezone_templatetag(self):
| tpl = Template('{% load tz %}{{ dt }}|{% timezone tz1 %}{{ dt }}|{% timezone tz2 %}{{ dt }}{% endtimezone %}{% endtimezone %}')
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC), 'tz1': ICT, 'tz2': None})
self.assertEqual(tpl.... |
'Test the {% timezone %} templatetag with pytz.'
| @skipIf((pytz is None), 'this test requires pytz')
def test_timezone_templatetag_with_pytz(self):
| tpl = Template('{% load tz %}{% timezone tz %}{{ dt }}{% endtimezone %}')
ctx = Context({'dt': datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), 'tz': pytz.timezone('Europe/Paris')})
self.assertEqual(tpl.render(ctx), '2011-09-01T12:20:30+02:00')
ctx = Context({'dt': da... |
'Test the {% get_current_timezone %} templatetag.'
| @skipIf(sys.platform.startswith('win'), 'Windows uses non-standard time zone names')
def test_get_current_timezone_templatetag(self):
| tpl = Template('{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}')
self.assertEqual(tpl.render(Context()), ('Africa/Nairobi' if pytz else 'EAT'))
with timezone.override(UTC):
self.assertEqual(tpl.render(Context()), 'UTC')
tpl = Template('{% load ... |
'Test the {% get_current_timezone %} templatetag with pytz.'
| @skipIf((pytz is None), 'this test requires pytz')
def test_get_current_timezone_templatetag_with_pytz(self):
| tpl = Template('{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}')
with timezone.override(pytz.timezone('Europe/Paris')):
self.assertEqual(tpl.render(Context()), 'Europe/Paris')
tpl = Template("{% load tz %}{% timezone 'Europe/Paris' %}... |
'Test the django.core.context_processors.tz template context processor.'
| @skipIf(sys.platform.startswith('win'), 'Windows uses non-standard time zone names')
def test_tz_template_context_processor(self):
| tpl = Template('{{ TIME_ZONE }}')
self.assertEqual(tpl.render(Context()), '')
self.assertEqual(tpl.render(RequestContext(HttpRequest())), ('Africa/Nairobi' if pytz else 'EAT'))
|
'The MyPerson model should be generating the same database queries as
the Person model (when the same manager is used in each case).'
| def test_same_manager_queries(self):
| my_person_sql = MyPerson.other.all().query.get_compiler(DEFAULT_DB_ALIAS).as_sql()
person_sql = Person.objects.order_by('name').query.get_compiler(DEFAULT_DB_ALIAS).as_sql()
self.assertEqual(my_person_sql, person_sql)
|
'The StatusPerson models should have its own table (it\'s using ORM-level
inheritance).'
| def test_inheretance_new_table(self):
| sp_sql = StatusPerson.objects.all().query.get_compiler(DEFAULT_DB_ALIAS).as_sql()
p_sql = Person.objects.all().query.get_compiler(DEFAULT_DB_ALIAS).as_sql()
self.assertNotEqual(sp_sql, p_sql)
|
'Creating a Person makes them accessible through the MyPerson proxy.'
| def test_basic_proxy(self):
| person = Person.objects.create(name='Foo McBar')
self.assertEqual(len(Person.objects.all()), 1)
self.assertEqual(len(MyPerson.objects.all()), 1)
self.assertEqual(MyPerson.objects.get(name='Foo McBar').id, person.id)
self.assertFalse(MyPerson.objects.get(id=person.id).has_special_name())
|
'Person is not proxied by StatusPerson subclass.'
| def test_no_proxy(self):
| Person.objects.create(name='Foo McBar')
self.assertEqual(list(StatusPerson.objects.all()), [])
|
'A new MyPerson also shows up as a standard Person.'
| def test_basic_proxy_reverse(self):
| MyPerson.objects.create(name='Bazza del Frob')
self.assertEqual(len(MyPerson.objects.all()), 1)
self.assertEqual(len(Person.objects.all()), 1)
LowerStatusPerson.objects.create(status='low', name='homer')
lsps = [lsp.name for lsp in LowerStatusPerson.objects.all()]
self.assertEqual(lsps, ['... |
'Correct type when querying a proxy of proxy'
| def test_correct_type_proxy_of_proxy(self):
| Person.objects.create(name='Foo McBar')
MyPerson.objects.create(name='Bazza del Frob')
LowerStatusPerson.objects.create(status='low', name='homer')
pp = sorted([mpp.name for mpp in MyPersonProxy.objects.all()])
self.assertEqual(pp, ['Bazza del Frob', 'Foo McBar', 'homer'])
|
'Proxy models are included in the ancestors for a model\'s DoesNotExist
and MultipleObjectsReturned'
| def test_proxy_included_in_ancestors(self):
| Person.objects.create(name='Foo McBar')
MyPerson.objects.create(name='Bazza del Frob')
LowerStatusPerson.objects.create(status='low', name='homer')
max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id']
self.assertRaises(Person.DoesNotExist, MyPersonProxy.objects.get, name='Za... |
'All base classes must be non-abstract'
| def test_abc(self):
| def build_abc():
class NoAbstract(Abstract, ):
class Meta:
proxy = True
self.assertRaises(TypeError, build_abc)
|
'The proxy must actually have one concrete base class'
| def test_no_cbc(self):
| def build_no_cbc():
class TooManyBases(Person, Abstract, ):
class Meta:
proxy = True
self.assertRaises(TypeError, build_no_cbc)
|
'Test save signals for proxy models'
| def test_proxy_model_signals(self):
| output = []
def make_handler(model, event):
def _handler(*args, **kwargs):
output.append(('%s %s save' % (model, event)))
return _handler
h1 = make_handler('MyPerson', 'pre')
h2 = make_handler('MyPerson', 'post')
h3 = make_handler('Person', 'pre')
h4 = make_hand... |
'Proxy objects can be deleted'
| def test_proxy_delete(self):
| User.objects.create(name='Bruce')
u2 = UserProxy.objects.create(name='George')
resp = [u.name for u in UserProxy.objects.all()]
self.assertEqual(resp, ['Bruce', 'George'])
u2.delete()
resp = [u.name for u in UserProxy.objects.all()]
self.assertEqual(resp, ['Bruce'])
|
'We can still use `select_related()` to include related models in our
querysets.'
| def test_select_related(self):
| country = Country.objects.create(name='Australia')
state = State.objects.create(name='New South Wales', country=country)
resp = [s.name for s in State.objects.select_related()]
self.assertEqual(resp, ['New South Wales'])
resp = [s.name for s in StateProxy.objects.select_related()]
se... |
'Registering a new serializer populates the full registry. Refs #14823'
| def test_register(self):
| serializers.register_serializer('json3', 'django.core.serializers.json')
public_formats = serializers.get_public_serializer_formats()
self.assertIn('json3', public_formats)
self.assertIn('json2', public_formats)
self.assertIn('xml', public_formats)
|
'Unregistering a serializer doesn\'t cause the registry to be repopulated. Refs #14823'
| def test_unregister(self):
| serializers.unregister_serializer('xml')
serializers.register_serializer('json3', 'django.core.serializers.json')
public_formats = serializers.get_public_serializer_formats()
self.assertNotIn('xml', public_formats)
self.assertIn('json3', public_formats)
|
'Requesting a list of serializer formats popuates the registry'
| def test_builtin_serializers(self):
| all_formats = set(serializers.get_serializer_formats())
public_formats = set(serializers.get_public_serializer_formats())
(self.assertIn('xml', all_formats),)
self.assertIn('xml', public_formats)
self.assertIn('json2', all_formats)
self.assertIn('json2', public_formats)
self.assertIn('python... |
'Tests that basic serialization works.'
| def test_serialize(self):
| serial_str = serializers.serialize(self.serializer_name, Article.objects.all())
self.assertTrue(self._validate_output(serial_str))
|
'Tests that serialized content can be deserialized.'
| def test_serializer_roundtrip(self):
| serial_str = serializers.serialize(self.serializer_name, Article.objects.all())
models = list(serializers.deserialize(self.serializer_name, serial_str))
self.assertEqual(len(models), 2)
|
'Tests the ability to create new objects by
modifying serialized content.'
| def test_altering_serialized_output(self):
| old_headline = 'Poker has no place on ESPN'
new_headline = 'Poker has no place on television'
serial_str = serializers.serialize(self.serializer_name, Article.objects.all())
serial_str = serial_str.replace(old_headline, new_headline)
models = list(serializers.deserializ... |
'Tests that if you use your own primary key field
(such as a OneToOneField), it doesn\'t appear in the
serialized field list - it replaces the pk identifier.'
| def test_one_to_one_as_pk(self):
| profile = AuthorProfile(author=self.joe, date_of_birth=datetime(1970, 1, 1))
profile.save()
serial_str = serializers.serialize(self.serializer_name, AuthorProfile.objects.all())
self.assertFalse(self._get_field_values(serial_str, 'author'))
for obj in serializers.deserialize(self.serializer_name, se... |
'Tests that output can be restricted to a subset of fields'
| def test_serialize_field_subset(self):
| valid_fields = ('headline', 'pub_date')
invalid_fields = ('author', 'categories')
serial_str = serializers.serialize(self.serializer_name, Article.objects.all(), fields=valid_fields)
for field_name in invalid_fields:
self.assertFalse(self._get_field_values(serial_str, field_name))
for field_... |
'Tests that unicode makes the roundtrip intact'
| def test_serialize_unicode(self):
| actor_name = u'Za\u017c\xf3\u0142\u0107'
movie_title = u'G\u0119\u015bl\u0105 ja\u017a\u0144'
ac = Actor(name=actor_name)
mv = Movie(title=movie_title, actor=ac)
ac.save()
mv.save()
serial_str = serializers.serialize(self.serializer_name, [mv])
self.assertEqual(self._get_field_values(... |
'Ensure no superfluous queries are made when serializing ForeignKeys
#17602'
| def test_serialize_superfluous_queries(self):
| ac = Actor(name='Actor name')
ac.save()
mv = Movie(title='Movie title', actor_id=ac.pk)
mv.save()
with self.assertNumQueries(0):
serial_str = serializers.serialize(self.serializer_name, [mv])
|
'Tests that serialized data with no primary key results
in a model instance with no id'
| def test_serialize_with_null_pk(self):
| category = Category(name='Reference')
serial_str = serializers.serialize(self.serializer_name, [category])
pk_value = self._get_pk_values(serial_str)[0]
self.assertFalse(pk_value)
cat_obj = list(serializers.deserialize(self.serializer_name, serial_str))[0].object
self.assertEqual(cat_obj.id, Non... |
'Tests that float values serialize and deserialize intact'
| def test_float_serialization(self):
| sc = Score(score=3.4)
sc.save()
serial_str = serializers.serialize(self.serializer_name, [sc])
deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str))
self.assertEqual(deserial_objs[0].object.score, Approximate(3.4, places=1))
|
'Tests that custom fields serialize and deserialize intact'
| def test_custom_field_serialization(self):
| team_str = 'Spartak Moskva'
player = Player()
player.name = 'Soslan Djanaev'
player.rank = 1
player.team = Team(team_str)
player.save()
serial_str = serializers.serialize(self.serializer_name, Player.objects.all())
team = self._get_field_values(serial_str, 'team')
self.assertTr... |
'Tests that year values before 1000AD are properly formatted'
| def test_pre_1000ad_date(self):
| a = Article.objects.create(author=self.jane, headline='Nobody remembers the early years', pub_date=datetime(1, 2, 3, 4, 5, 6))
serial_str = serializers.serialize(self.serializer_name, [a])
date_values = self._get_field_values(serial_str, 'pub_date')
self.assertEqual(date_values[0].replace('T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.