desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Test other units.'
| def test_other_units(self):
| self.assertEqual(timesince(self.t, (self.t + self.oneminute)), u'1 minute')
self.assertEqual(timesince(self.t, (self.t + self.onehour)), u'1 hour')
self.assertEqual(timesince(self.t, (self.t + self.oneday)), u'1 day')
self.assertEqual(timesince(self.t, (self.t + self.oneweek)), u'1 week')
self.assertEqual(timesince(self.t, (self.t + self.onemonth)), u'1 month')
self.assertEqual(timesince(self.t, (self.t + self.oneyear)), u'1 year')
|
'Test multiple units.'
| def test_multiple_units(self):
| self.assertEqual(timesince(self.t, ((self.t + (2 * self.oneday)) + (6 * self.onehour))), u'2 days, 6 hours')
self.assertEqual(timesince(self.t, ((self.t + (2 * self.oneweek)) + (2 * self.oneday))), u'2 weeks, 2 days')
|
'If the two differing units aren\'t adjacent, only the first unit is
displayed.'
| def test_display_first_unit(self):
| self.assertEqual(timesince(self.t, (((self.t + (2 * self.oneweek)) + (3 * self.onehour)) + (4 * self.oneminute))), u'2 weeks')
self.assertEqual(timesince(self.t, ((self.t + (4 * self.oneday)) + (5 * self.oneminute))), u'4 days')
|
'When the second date occurs before the first, we should always
get 0 minutes.'
| def test_display_second_before_first(self):
| self.assertEqual(timesince(self.t, (self.t - self.onemicrosecond)), u'0 minutes')
self.assertEqual(timesince(self.t, (self.t - self.onesecond)), u'0 minutes')
self.assertEqual(timesince(self.t, (self.t - self.oneminute)), u'0 minutes')
self.assertEqual(timesince(self.t, (self.t - self.onehour)), u'0 minutes')
self.assertEqual(timesince(self.t, (self.t - self.oneday)), u'0 minutes')
self.assertEqual(timesince(self.t, (self.t - self.oneweek)), u'0 minutes')
self.assertEqual(timesince(self.t, (self.t - self.onemonth)), u'0 minutes')
self.assertEqual(timesince(self.t, (self.t - self.oneyear)), u'0 minutes')
self.assertEqual(timesince(self.t, ((self.t - (2 * self.oneday)) - (6 * self.onehour))), u'0 minutes')
self.assertEqual(timesince(self.t, ((self.t - (2 * self.oneweek)) - (2 * self.oneday))), u'0 minutes')
self.assertEqual(timesince(self.t, (((self.t - (2 * self.oneweek)) - (3 * self.onehour)) - (4 * self.oneminute))), u'0 minutes')
self.assertEqual(timesince(self.t, ((self.t - (4 * self.oneday)) - (5 * self.oneminute))), u'0 minutes')
|
'When using two different timezones.'
| def test_different_timezones(self):
| now = datetime.datetime.now()
now_tz = datetime.datetime.now(LocalTimezone(now))
now_tz_i = datetime.datetime.now(FixedOffset(((3 * 60) + 15)))
self.assertEqual(timesince(now), u'0 minutes')
self.assertEqual(timesince(now_tz), u'0 minutes')
self.assertEqual(timeuntil(now_tz, now_tz_i), u'0 minutes')
|
'Both timesince and timeuntil should work on date objects (#17937).'
| def test_date_objects(self):
| today = datetime.date.today()
self.assertEqual(timesince((today + self.oneday)), u'0 minutes')
self.assertEqual(timeuntil((today - self.oneday)), u'0 minutes')
|
'Timesince should work with both date objects (#9672)'
| def test_both_date_objects(self):
| today = datetime.date.today()
self.assertEqual(timeuntil((today + self.oneday), today), u'1 day')
self.assertEqual(timeuntil((today - self.oneday), today), u'0 minutes')
self.assertEqual(timeuntil((today + self.oneweek), today), u'1 week')
|
'Overwriting an item keeps its place.'
| def test_overwrite_ordering(self):
| self.d1[1] = 'ONE'
self.assertEqual(list(six.itervalues(self.d1)), ['seven', 'ONE', 'nine'])
|
'New items go to the end.'
| def test_append_items(self):
| self.d1[0] = 'nil'
self.assertEqual(list(six.iterkeys(self.d1)), [7, 1, 9, 0])
|
'Deleting an item, then inserting the same key again will place it
at the end.'
| def test_delete_and_insert(self):
| del self.d2[7]
self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0])
self.d2[7] = 'lucky number 7'
self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0, 7])
|
'Initialising a SortedDict with two keys will just take the first one.
A real dict will actually take the second value so we will too, but
we\'ll keep the ordering from the first key found.'
| def test_init_keys(self):
| tuples = ((2, 'two'), (1, 'one'), (2, 'second-two'))
d = SortedDict(tuples)
self.assertEqual(list(six.iterkeys(d)), [2, 1])
real_dict = dict(tuples)
self.assertEqual(sorted(six.itervalues(real_dict)), ['one', 'second-two'])
self.assertEqual(list(six.itervalues(d)), ['second-two', 'one'])
|
'MergeDict can merge MultiValueDicts'
| def test_mergedict_merges_multivaluedict(self):
| multi1 = MultiValueDict({'key1': ['value1'], 'key2': ['value2', 'value3']})
multi2 = MultiValueDict({'key2': ['value4'], 'key4': ['value5', 'value6']})
mm = MergeDict(multi1, multi2)
self.assertEqual(mm.getlist('key2'), ['value2', 'value3'])
self.assertEqual(mm.getlist('key4'), ['value5', 'value6'])
self.assertEqual(mm.getlist('undefined'), [])
self.assertEqual(sorted(six.iterkeys(mm)), ['key1', 'key2', 'key4'])
self.assertEqual(len(list(six.itervalues(mm))), 3)
self.assertTrue(('value1' in six.itervalues(mm)))
self.assertEqual(sorted(six.iteritems(mm), key=(lambda k: k[0])), [('key1', 'value1'), ('key2', 'value3'), ('key4', 'value6')])
self.assertEqual([(k, mm.getlist(k)) for k in sorted(mm)], [('key1', ['value1']), ('key2', ['value2', 'value3']), ('key4', ['value5', 'value6'])])
|
'Create temporary directory for testing extraction.'
| def setUp(self):
| self.old_cwd = os.getcwd()
self.tmpdir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.tmpdir)
self.archive_path = os.path.join(TEST_DIR, self.archive)
os.chdir(TEST_DIR)
|
'Normal module existence can be tested'
| def test_loader(self):
| test_module = import_module('regressiontests.utils.test_module')
test_no_submodule = import_module('regressiontests.utils.test_no_submodule')
self.assertTrue(module_has_submodule(test_module, 'good_module'))
mod = import_module('regressiontests.utils.test_module.good_module')
self.assertEqual(mod.content, 'Good Module')
self.assertTrue(module_has_submodule(test_module, 'bad_module'))
self.assertRaises(ImportError, import_module, 'regressiontests.utils.test_module.bad_module')
self.assertFalse(module_has_submodule(test_module, 'no_such_module'))
self.assertRaises(ImportError, import_module, 'regressiontests.utils.test_module.no_such_module')
self.assertFalse(module_has_submodule(test_module, 'django'))
self.assertRaises(ImportError, import_module, 'regressiontests.utils.test_module.django')
import types
self.assertFalse(module_has_submodule(sys.modules['regressiontests.utils'], 'types'))
self.assertFalse(module_has_submodule(test_no_submodule, 'anything'))
self.assertRaises(ImportError, import_module, 'regressiontests.utils.test_no_submodule.anything')
|
'Module existence can be tested inside eggs'
| def test_shallow_loader(self):
| egg_name = ('%s/test_egg.egg' % self.egg_dir)
sys.path.append(egg_name)
egg_module = import_module('egg_module')
self.assertTrue(module_has_submodule(egg_module, 'good_module'))
mod = import_module('egg_module.good_module')
self.assertEqual(mod.content, 'Good Module')
self.assertTrue(module_has_submodule(egg_module, 'bad_module'))
self.assertRaises(ImportError, import_module, 'egg_module.bad_module')
self.assertFalse(module_has_submodule(egg_module, 'no_such_module'))
self.assertRaises(ImportError, import_module, 'egg_module.no_such_module')
|
'Modules deep inside an egg can still be tested for existence'
| def test_deep_loader(self):
| egg_name = ('%s/test_egg.egg' % self.egg_dir)
sys.path.append(egg_name)
egg_module = import_module('egg_module.sub1.sub2')
self.assertTrue(module_has_submodule(egg_module, 'good_module'))
mod = import_module('egg_module.sub1.sub2.good_module')
self.assertEqual(mod.content, 'Deep Good Module')
self.assertTrue(module_has_submodule(egg_module, 'bad_module'))
self.assertRaises(ImportError, import_module, 'egg_module.sub1.sub2.bad_module')
self.assertFalse(module_has_submodule(egg_module, 'no_such_module'))
self.assertRaises(ImportError, import_module, 'egg_module.sub1.sub2.no_such_module')
|
'Test that force_bytes knows how to convert to bytes an exception
containing non-ASCII characters in its args.'
| def test_force_bytes_exception(self):
| error_msg = u'This is an exception, voil\xe0'
exc = ValueError(error_msg)
result = force_bytes(exc)
self.assertEqual(result, error_msg.encode(u'utf-8'))
|
'Regression for #12524
Check that pre-1000AD dates are padded with zeros if necessary'
| def test_zero_padding(self):
| self.assertEqual(date(1, 1, 1).strftime('%Y/%m/%d was a %A'), '0001/01/01 was a Monday')
|
'Test that lazy also finds base class methods in the proxy object'
| def test_lazy_base_class(self):
| class Base(object, ):
def base_method(self):
pass
class Klazz(Base, ):
pass
t = lazy((lambda : Klazz()), Klazz)()
self.assertTrue(('base_method' in dir(t)))
|
'Test a middleware that implements process_view.'
| def test_process_view_middleware(self):
| process_view(self.rf.get('/'))
|
'Test a middleware that implements process_view, operating on a callable class.'
| def test_callable_process_view_middleware(self):
| class_process_view(self.rf.get('/'))
|
'Test that all methods of middleware are called for normal HttpResponses'
| def test_full_dec_normal(self):
| @full_dec
def normal_view(request):
t = Template('Hello world')
return HttpResponse(t.render(Context({})))
request = self.rf.get('/')
response = normal_view(request)
self.assertTrue(getattr(request, 'process_request_reached', False))
self.assertTrue(getattr(request, 'process_view_reached', False))
self.assertFalse(getattr(request, 'process_template_response_reached', False))
self.assertTrue(getattr(request, 'process_response_reached', False))
|
'Test that all methods of middleware are called for TemplateResponses in
the right sequence.'
| def test_full_dec_templateresponse(self):
| @full_dec
def template_response_view(request):
t = Template('Hello world')
return TemplateResponse(request, t, {})
request = self.rf.get('/')
response = template_response_view(request)
self.assertTrue(getattr(request, 'process_request_reached', False))
self.assertTrue(getattr(request, 'process_view_reached', False))
self.assertTrue(getattr(request, 'process_template_response_reached', False))
self.assertFalse(response._is_rendered)
self.assertFalse(getattr(request, 'process_response_reached', False))
response.render()
self.assertTrue(getattr(request, 'process_response_reached', False))
self.assertEqual(request.process_response_content, 'Hello world')
|
'Check that function(value) equals output. If output is None,
check that function(value) equals value.'
| def check_output(self, function, value, output=None):
| if (output is None):
output = value
self.assertEqual(function(value), output)
|
'Regression for #16632.
`fix_IE_for_vary` shouldn\'t crash when there\'s no Content-Type header.'
| def test_fix_IE_for_vary(self):
| def response_with_unsafe_content_type():
r = HttpResponse(content_type='text/unsafe')
r['Vary'] = 'Cookie'
return r
def no_content_response_with_unsafe_content_type():
r = response_with_unsafe_content_type()
del r['Content-Type']
return r
rf = RequestFactory()
request = rf.get('/')
ie_request = rf.get('/', HTTP_USER_AGENT='MSIE')
response = response_with_unsafe_content_type()
utils.fix_IE_for_vary(request, response)
self.assertTrue(('Vary' in response))
response = response_with_unsafe_content_type()
utils.fix_IE_for_vary(ie_request, response)
self.assertFalse(('Vary' in response))
response = no_content_response_with_unsafe_content_type()
utils.fix_IE_for_vary(request, response)
self.assertTrue(('Vary' in response))
response = no_content_response_with_unsafe_content_type()
utils.fix_IE_for_vary(ie_request, response)
self.assertFalse(('Vary' in response))
|
'Issue 13864: force_update fails on subclassed models, if they don\'t
specify custom fields.'
| def test_force_update_on_inherited_model_without_fields(self):
| a = SubCounter(name='count', value=1)
a.save()
a.value = 2
a.save(force_update=True)
|
'Test that signals that disconnect when being called don\'t mess future
dispatching.'
| def test_disconnect_in_dispatch(self):
| (a, b) = (MyReceiver(1), MyReceiver(2))
signals.post_save.connect(sender=Person, receiver=a)
signals.post_save.connect(sender=Person, receiver=b)
p = Person.objects.create(first_name='John', last_name='Smith')
self.assertTrue(a._run)
self.assertTrue(b._run)
self.assertEqual(signals.post_save.receivers, [])
|
'Test that the backend\'s FOR UPDATE variant appears in
generated SQL when select_for_update is invoked.'
| @skipUnlessDBFeature('has_select_for_update')
def test_for_update_sql_generated(self):
| list(Person.objects.all().select_for_update())
self.assertTrue(self.has_for_update_sql(connection))
|
'Test that the backend\'s FOR UPDATE NOWAIT variant appears in
generated SQL when select_for_update is invoked.'
| @skipUnlessDBFeature('has_select_for_update_nowait')
def test_for_update_sql_generated_nowait(self):
| list(Person.objects.all().select_for_update(nowait=True))
self.assertTrue(self.has_for_update_sql(connection, nowait=True))
|
'If nowait is specified, we expect an error to be raised rather
than blocking.'
| @requires_threading
@skipUnlessDBFeature('has_select_for_update_nowait')
@unittest.skipIf((sys.version_info[:3] == (2, 6, 1)), 'Python version is 2.6.1')
def test_nowait_raises_error_on_block(self):
| self.start_blocking_transaction()
status = []
thread = threading.Thread(target=self.run_select_for_update, args=(status,), kwargs={'nowait': True})
thread.start()
time.sleep(1)
thread.join()
self.end_blocking_transaction()
self.check_exc(status[(-1)])
|
'If a SELECT...FOR UPDATE NOWAIT is run on a database backend
that supports FOR UPDATE but not NOWAIT, then we should find
that a DatabaseError is raised.'
| @skipIfDBFeature('has_select_for_update_nowait')
@skipUnlessDBFeature('has_select_for_update')
@unittest.skipIf((sys.version_info[:3] == (2, 6, 1)), 'Python version is 2.6.1')
def test_unsupported_nowait_raises_error(self):
| self.assertRaises(DatabaseError, list, Person.objects.all().select_for_update(nowait=True))
|
'Utility method that runs a SELECT FOR UPDATE against all
Person instances. After the select_for_update, it attempts
to update the name of the only record, save, and commit.
This function expects to run in a separate thread.'
| def run_select_for_update(self, status, nowait=False):
| status.append('started')
try:
transaction.enter_transaction_management(True)
transaction.managed(True)
people = list(Person.objects.all().select_for_update(nowait=nowait))
people[0].name = 'Fred'
people[0].save()
transaction.commit()
except DatabaseError as e:
status.append(e)
finally:
connection.close()
|
'Check that a thread running a select_for_update that
accesses rows being touched by a similar operation
on another connection blocks correctly.'
| @requires_threading
@skipUnlessDBFeature('has_select_for_update')
@skipUnlessDBFeature('supports_transactions')
def test_block(self):
| self.start_blocking_transaction()
status = []
thread = threading.Thread(target=self.run_select_for_update, args=(status,))
thread.start()
sanity_count = 0
while ((len(status) != 1) and (sanity_count < 10)):
sanity_count += 1
time.sleep(1)
if (sanity_count >= 10):
raise ValueError('Thread did not run and block')
p = Person.objects.get(pk=self.person.pk)
self.assertEqual('Reinhardt', p.name)
self.end_blocking_transaction()
thread.join(5.0)
self.assertFalse(thread.isAlive())
transaction.commit()
p = Person.objects.get(pk=self.person.pk)
self.assertEqual('Fred', p.name)
|
'Check that running a raw query which can\'t obtain a FOR UPDATE lock
raises the correct exception'
| @requires_threading
@skipUnlessDBFeature('has_select_for_update')
def test_raw_lock_not_available(self):
| self.start_blocking_transaction()
def raw(status):
try:
list(Person.objects.raw(('SELECT * FROM %s %s' % (Person._meta.db_table, connection.ops.for_update_sql(nowait=True)))))
except DatabaseError as e:
status.append(e)
finally:
connection.close()
status = []
thread = threading.Thread(target=raw, kwargs={'status': status})
thread.start()
time.sleep(1)
thread.join()
self.end_blocking_transaction()
self.check_exc(status[(-1)])
|
'Check that a select_for_update sets the transaction to be
dirty when executed under txn management. Setting the txn dirty
means that it will be either committed or rolled back by Django,
which will release any locks held by the SELECT FOR UPDATE.'
| @skipUnlessDBFeature('has_select_for_update')
def test_transaction_dirty_managed(self):
| people = list(Person.objects.select_for_update())
self.assertTrue(transaction.is_dirty())
|
'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(u'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(u'books__read_by')
lists = [[[six.text_type(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(u'books__read_by').get(name=u'Charlotte')
lists = [[six.text_type(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(u'first_book').prefetch_related(u'first_book__read_by')
lists = [[six.text_type(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', u'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=u'awesome', content_object=self.book1)
TaggedItem.objects.create(tag=u'awesome', content_object=self.book2)
TaggedItem.objects.create(tag=u'awesome', content_object=self.book3)
TaggedItem.objects.create(tag=u'awesome', content_object=self.reader1)
TaggedItem.objects.create(tag=u'awesome', content_object=self.reader2)
ct = ContentType.objects.get_for_model(Book)
with self.assertNumQueries(3):
qs = TaggedItem.objects.filter(content_type=ct, tag=u'awesome').prefetch_related(u'content_object__read_by')
readers_of_awesome_books = set([r.name for tag in qs for r in tag.content_object.read_by.all()])
self.assertEqual(readers_of_awesome_books, set([u'me', u'you', u'someone']))
|
'In-bulk does correctly prefetch objects by not using .iterator()
directly.'
| def test_in_bulk(self):
| boss1 = Employee.objects.create(name=u'Peter')
boss2 = Employee.objects.create(name=u'Jack')
with self.assertNumQueries(2):
bulk = Employee.objects.prefetch_related(u'serfs').in_bulk([boss1.pk, boss2.pk])
for b in bulk.values():
list(b.serfs.all())
|
'Test that .dates() returns a distinct set of dates when applied to a
QuerySet with aggregation.
Refs #18056. Previously, .dates() would return distinct (date_kind,
aggregation) sets, in this case (year, num_authors), so 2008 would be
returned twice because there are books from 2008 with a different
number of authors.'
| def test_dates_with_aggregation(self):
| dates = Book.objects.annotate(num_authors=Count('authors')).dates('pubdate', 'year')
self.assertQuerysetEqual(dates, ['datetime.datetime(1991, 1, 1, 0, 0)', 'datetime.datetime(1995, 1, 1, 0, 0)', 'datetime.datetime(2007, 1, 1, 0, 0)', 'datetime.datetime(2008, 1, 1, 0, 0)'])
|
'GET a view'
| def test_get_view(self):
| data = {u'var': u'\xf2'}
response = self.client.get(u'/test_client/get_view/', data)
self.assertContains(response, u'This is a test')
self.assertEqual(response.context[u'var'], u'\xf2')
self.assertEqual(response.templates[0].name, u'GET Template')
|
'GET a view that normally expects POSTs'
| def test_get_post_view(self):
| response = self.client.get(u'/test_client/post_view/', {})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.templates[0].name, u'Empty GET Template')
self.assertTemplateUsed(response, u'Empty GET Template')
self.assertTemplateNotUsed(response, u'Empty POST Template')
|
'POST an empty dictionary to a view'
| def test_empty_post(self):
| response = self.client.post(u'/test_client/post_view/', {})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.templates[0].name, u'Empty POST Template')
self.assertTemplateNotUsed(response, u'Empty GET Template')
self.assertTemplateUsed(response, u'Empty POST Template')
|
'POST some data to a view'
| def test_post(self):
| post_data = {u'value': 37}
response = self.client.post(u'/test_client/post_view/', post_data)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context[u'data'], u'37')
self.assertEqual(response.templates[0].name, u'POST Template')
self.assertContains(response, u'Data received')
|
'Check the value of HTTP headers returned in a response'
| def test_response_headers(self):
| response = self.client.get(u'/test_client/header_view/')
self.assertEqual(response[u'X-DJANGO-TEST'], u'Slartibartfast')
|
'POST raw data (with a content type) to a view'
| def test_raw_post(self):
| test_doc = u'<?xml version="1.0" encoding="utf-8"?><library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library>'
response = self.client.post(u'/test_client/raw_post_view/', test_doc, content_type=u'text/xml')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.templates[0].name, u'Book template')
self.assertEqual(response.content, 'Blink - Malcolm Gladwell')
|
'GET a URL that redirects elsewhere'
| def test_redirect(self):
| response = self.client.get(u'/test_client/redirect_view/')
self.assertRedirects(response, u'/test_client/get_view/')
host = u'django.testserver'
client_providing_host = Client(HTTP_HOST=host)
response = client_providing_host.get(u'/test_client/redirect_view/')
self.assertRedirects(response, u'/test_client/get_view/', host=host)
|
'GET a URL that redirects with given GET parameters'
| def test_redirect_with_query(self):
| response = self.client.get(u'/test_client/redirect_view/', {u'var': u'value'})
self.assertRedirects(response, u'http://testserver/test_client/get_view/?var=value')
|
'GET a URL that redirects permanently elsewhere'
| def test_permanent_redirect(self):
| response = self.client.get(u'/test_client/permanent_redirect_view/')
self.assertRedirects(response, u'http://testserver/test_client/get_view/', status_code=301)
client_providing_host = Client(HTTP_HOST=u'django.testserver')
response = client_providing_host.get(u'/test_client/permanent_redirect_view/')
self.assertRedirects(response, u'http://django.testserver/test_client/get_view/', status_code=301)
|
'GET a URL that does a non-permanent redirect'
| def test_temporary_redirect(self):
| response = self.client.get(u'/test_client/temporary_redirect_view/')
self.assertRedirects(response, u'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(u'/test_client/double_redirect_view/')
self.assertRedirects(response, u'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(u'/test_client/double_redirect_view/', follow=True)
self.assertRedirects(response, u'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(u'/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(u'/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(u'/test_client/bad_view/')
self.assertContains(response, u'MAGIC', status_code=404)
|
'POST valid data to a form'
| def test_valid_form(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/', post_data)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, u'Valid POST Template')
|
'GET a form, providing hints in the GET data'
| def test_valid_form_with_hints(self):
| hints = {u'text': u'Hello World', u'multi': (u'b', u'c', u'e')}
response = self.client.get(u'/test_client/form_view/', data=hints)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, u'Form GET Template')
self.assertContains(response, u'Select a valid choice.', 0)
|
'POST incomplete data to a form'
| def test_incomplete_data_form(self):
| post_data = {u'text': u'Hello World', u'value': 37}
response = self.client.post(u'/test_client/form_view/', post_data)
self.assertContains(response, u'This field is required.', 3)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, u'Invalid POST Template')
self.assertFormError(response, u'form', u'email', u'This field is required.')
self.assertFormError(response, u'form', u'single', u'This field is required.')
self.assertFormError(response, u'form', u'multi', u'This field is required.')
|
'POST erroneous data to a form'
| def test_form_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')
self.assertFormError(response, u'form', u'email', u'Enter a valid email address.')
|
'POST valid data to a form using multiple templates'
| def test_valid_form_with_template(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')
self.assertTemplateUsed(response, u'form_view.html')
self.assertTemplateUsed(response, u'base.html')
self.assertTemplateNotUsed(response, u'Valid POST Template')
|
'POST incomplete data to a form using multiple templates'
| def test_incomplete_data_form_with_template(self):
| post_data = {u'text': u'Hello World', u'value': 37}
response = self.client.post(u'/test_client/form_view_with_template/', post_data)
self.assertContains(response, u'POST data has errors')
self.assertTemplateUsed(response, u'form_view.html')
self.assertTemplateUsed(response, u'base.html')
self.assertTemplateNotUsed(response, u'Invalid POST Template')
self.assertFormError(response, u'form', u'email', u'This field is required.')
self.assertFormError(response, u'form', u'single', u'This field is required.')
self.assertFormError(response, u'form', u'multi', u'This field is required.')
|
'POST erroneous data to a form using multiple templates'
| def test_form_error_with_template(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_with_template/', post_data)
self.assertContains(response, u'POST data has errors')
self.assertTemplateUsed(response, u'form_view.html')
self.assertTemplateUsed(response, u'base.html')
self.assertTemplateNotUsed(response, u'Invalid POST Template')
self.assertFormError(response, u'form', u'email', u'Enter a valid email address.')
|
'GET an invalid URL'
| def test_unknown_page(self):
| response = self.client.get(u'/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(u'/test_client/unknown_view/;some-parameter')
self.assertEqual(response.request[u'PATH_INFO'], u'/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(u'/test_client/login_protected_view/')
self.assertRedirects(response, u'http://testserver/accounts/login/?next=/test_client/login_protected_view/')
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')
|
'Request a page that is protected with a @login_required method'
| def test_view_with_method_login(self):
| response = self.client.get(u'/test_client/login_protected_method_view/')
self.assertRedirects(response, u'http://testserver/accounts/login/?next=/test_client/login_protected_method_view/')
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_method_view/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context[u'user'].username, u'testclient')
|
'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(u'/test_client/login_protected_view_custom_redirect/')
self.assertRedirects(response, u'http://testserver/accounts/login/?redirect_to=/test_client/login_protected_view_custom_redirect/')
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_custom_redirect/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context[u'user'].username, u'testclient')
|
'Request a page that is protected with @login, but use bad credentials'
| def test_view_with_bad_login(self):
| login = self.client.login(username=u'otheruser', password=u'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=u'inactive', password=u'password')
self.assertFalse(login)
|
'Request a logout after logging in'
| def test_logout(self):
| self.client.login(username=u'testclient', password=u'password')
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')
self.client.logout()
response = self.client.get(u'/test_client/login_protected_view/')
self.assertRedirects(response, u'http://testserver/accounts/login/?next=/test_client/login_protected_view/')
|
'Request a page that is protected with @permission_required'
| def test_view_with_permissions(self):
| response = self.client.get(u'/test_client/permission_protected_view/')
self.assertRedirects(response, u'http://testserver/accounts/login/?next=/test_client/permission_protected_view/')
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/permission_protected_view/')
self.assertRedirects(response, u'http://testserver/accounts/login/?next=/test_client/permission_protected_view/')
|
'Request a page that is protected with @permission_required but raises a exception'
| def test_view_with_permissions_exception(self):
| response = self.client.get(u'/test_client/permission_protected_view_exception/')
self.assertEqual(response.status_code, 403)
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/permission_protected_view_exception/')
self.assertEqual(response.status_code, 403)
|
'Request a page that is protected with a @permission_required method'
| def test_view_with_method_permissions(self):
| response = self.client.get(u'/test_client/permission_protected_method_view/')
self.assertRedirects(response, u'http://testserver/accounts/login/?next=/test_client/permission_protected_method_view/')
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/permission_protected_method_view/')
self.assertRedirects(response, u'http://testserver/accounts/login/?next=/test_client/permission_protected_method_view/')
|
'Request a page that modifies the session'
| def test_session_modifying_view(self):
| try:
self.client.session[u'tobacconist']
self.fail(u"Shouldn't have a session value")
except KeyError:
pass
from django.contrib.sessions.models import Session
response = self.client.post(u'/test_client/session_view/')
self.assertEqual(self.client.session[u'tobacconist'], u'hovercraft')
|
'Request a page that is known to throw an error'
| def test_view_with_exception(self):
| self.assertRaises(KeyError, self.client.get, u'/test_client/broken_view/')
try:
self.client.get(u'/test_client/broken_view/')
self.fail(u'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(u'/test_client/mail_sending_view/')
self.assertEqual(response.status_code, 200)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, u'Test message')
self.assertEqual(mail.outbox[0].body, u'This is a test email')
self.assertEqual(mail.outbox[0].from_email, u'[email protected]')
self.assertEqual(mail.outbox[0].to[0], u'[email protected]')
self.assertEqual(mail.outbox[0].to[1], u'[email protected]')
|
'Test that mass mail is redirected to a dummy outbox during test setup'
| def test_mass_mail_sending(self):
| response = self.client.get(u'/test_client/mass_mail_sending_view/')
self.assertEqual(response.status_code, 200)
self.assertEqual(len(mail.outbox), 2)
self.assertEqual(mail.outbox[0].subject, u'First Test message')
self.assertEqual(mail.outbox[0].body, u'This is the first test email')
self.assertEqual(mail.outbox[0].from_email, u'[email protected]')
self.assertEqual(mail.outbox[0].to[0], u'[email protected]')
self.assertEqual(mail.outbox[0].to[1], u'[email protected]')
self.assertEqual(mail.outbox[1].subject, u'Second Test message')
self.assertEqual(mail.outbox[1].body, u'This is the second test email')
self.assertEqual(mail.outbox[1].from_email, u'[email protected]')
self.assertEqual(mail.outbox[1].to[0], u'[email protected]')
self.assertEqual(mail.outbox[1].to[1], u'[email protected]')
|
'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(u'/test_client/post_view/', {})
self.assertEqual(response.status_code, 200)
response = csrf_client.post(u'/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, u'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_date = %s\n AND id != %s', [connection.ops.value_to_db_date(self.pub_date), self.id])
return [self.__class__(*row) for row in cursor.fetchall()]
|
'Test that a models.DO_NOTHING relation doesn\'t trigger a query.'
| def test_do_nothing_qscount(self):
| b = Base.objects.create()
with self.assertNumQueries(1):
b.delete()
self.assertEqual(Base.objects.count(), 0)
|
'Deleting an instance of a model proxying a multi-table inherited
subclass should cascade delete down the whole inheritance chain (see
#18083).'
| def test_model_subclass_proxy(self):
| instance = ConcreteModelSubclassProxy.objects.create()
instance.delete()
self.assertEqual(0, ConcreteModelSubclassProxy.objects.count())
self.assertEqual(0, ConcreteModelSubclass.objects.count())
self.assertEqual(0, ConcreteModel.objects.count())
|
'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=u'apple').update(name=u'd1')
self.assertEqual(resp, 1)
resp = DataPoint.objects.filter(value=u'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=u'banana').update(value=u'pineapple')
self.assertEqual(resp, 2)
self.assertEqual(DataPoint.objects.get(name=u'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=u'r1').update(data=self.d0)
self.assertEqual(resp, 1)
resp = RelatedPoint.objects.filter(data__name=u'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=u'apple').update(value=u'fruit', another_value=u'peach')
self.assertEqual(resp, 1)
d = DataPoint.objects.get(name=u'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=u'thing'), 3)
resp = DataPoint.objects.values(u'value').distinct()
self.assertEqual(list(resp), [{u'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=u'another thing')
|
'Test that update queries do not generate non-necessary queries.
Refs #18304.'
| def test_update_query_counts(self):
| c = Chef.objects.create(name='Albert')
ir = ItalianRestaurant.objects.create(name='Ristorante Miron', address='1234 W. Ash', serves_hot_dogs=False, serves_pizza=False, serves_gnocchi=True, rating=4, chef=c)
with self.assertNumQueries(6):
ir.save()
|
'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(isinstance(b2, B02))
self.assertEqual(b2.f_a, 'fred')
self.assertTrue(isinstance(b2.fk_a, A02))
self.assertEqual(b2.fk_a.f_a, 'foo')
self.assertEqual(list(C02.objects.filter(f_a=None)), [])
resp = list(C02.objects.filter(mm_a=a.id))
self.assertEqual(len(resp), 1)
self.assertTrue(isinstance(resp[0], C02))
self.assertEqual(resp[0].f_a, 'barney')
|
'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))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.