desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'This test is related to the above one, testing that there aren\'t old JOINs in the query.'
def test_order_by_join_unref(self):
qs = Celebrity.objects.order_by(u'greatest_fan__fan_of') self.assertIn(u'OUTER JOIN', str(qs.query)) qs = qs.order_by(u'id') self.assertNotIn(u'OUTER JOIN', str(qs.query))
'Ensure that Meta.ordering=None works the same as Meta.ordering=[]'
def test_ticket17429(self):
original_ordering = Tag._meta.ordering Tag._meta.ordering = None self.assertQuerysetEqual(Tag.objects.all(), [u'<Tag: t1>', u'<Tag: t2>', u'<Tag: t3>', u'<Tag: t4>', u'<Tag: t5>']) Tag._meta.ordering = original_ordering
'Subselects honor any manual ordering'
def test_ordered_subselect(self):
try: query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by(u'-id')[0:2]) self.assertEqual(set(query.values_list(u'id', flat=True)), set([2, 3])) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by(u'-id')[:2]) self.assertEqual(set(query.values_...
'Delete queries can safely contain sliced subqueries'
def test_sliced_delete(self):
try: DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by(u'-id')[0:1]).delete() self.assertEqual(set(DumbCategory.objects.values_list(u'id', flat=True)), set([1, 2])) except DatabaseError: self.assertFalse(connections[DEFAULT_DB_ALIAS].features.allow_sliced_subqueries)
'#13227 -- If a queryset is already evaluated, it can still be used as a query arg'
def test_evaluated_queryset_as_argument(self):
n = Note(note=u'Test1', misc=u'misc') n.save() e = ExtraInfo(info=u'good', note=n) e.save() n_list = Note.objects.all() list(n_list) self.assertEqual(ExtraInfo.objects.filter(note__in=n_list)[0].info, u'good')
'The following case is not handled properly because SQL\'s COL NOT IN (list containing null) handling is too weird to abstract away.'
@unittest.expectedFailure def test_col_not_in_list_containing_null(self):
self.assertQuerysetEqual(NullableName.objects.exclude(name__in=[None]), [u'i1'], attrgetter(u'name'))
'Test that generating the query string doesn\'t alter the query\'s state in irreversible ways. Refs #18248.'
def test_evaluated_proxy_count(self):
ProxyCategory.objects.create() qs = ProxyCategory.objects.all() self.assertEqual(qs.count(), 1) str(qs.query) self.assertEqual(qs.count(), 1)
'Test QueryDict with one key/value pair'
def test_single_key_value(self):
q = QueryDict(str(u'foo=bar')) self.assertEqual(q[u'foo'], u'bar') self.assertRaises(KeyError, q.__getitem__, u'bar') self.assertRaises(AttributeError, q.__setitem__, u'something', u'bar') self.assertEqual(q.get(u'foo', u'default'), u'bar') self.assertEqual(q.get(u'bar', u'default'), u'default')...
'A copy of a QueryDict is mutable.'
def test_mutable_copy(self):
q = QueryDict(str(u'')).copy() self.assertRaises(KeyError, q.__getitem__, u'foo') q[u'name'] = u'john' self.assertEqual(q[u'name'], u'john')
'Test QueryDict with two key/value pairs with same keys.'
def test_multiple_keys(self):
q = QueryDict(str(u'vote=yes&vote=no')) self.assertEqual(q[u'vote'], u'no') self.assertRaises(AttributeError, q.__setitem__, u'something', u'bar') self.assertEqual(q.get(u'vote', u'default'), u'no') self.assertEqual(q.get(u'foo', u'default'), u'default') self.assertEqual(q.getlist(u'vote'), [u'y...
'Regression test for #8278: QueryDict.update(QueryDict)'
def test_update_from_querydict(self):
x = QueryDict(str(u'a=1&a=2'), mutable=True) y = QueryDict(str(u'a=3&a=4')) x.update(y) self.assertEqual(x.getlist(u'a'), [u'1', u'2', u'3', u'4'])
'#13572 - QueryDict with a non-default encoding'
def test_non_default_encoding(self):
q = QueryDict(str(u'cur=%A4'), encoding=u'iso-8859-15') self.assertEqual(q.encoding, u'iso-8859-15') self.assertEqual(list(six.iteritems(q)), [(u'cur', u'\u20ac')]) self.assertEqual(q.urlencode(), u'cur=%A4') q = q.copy() self.assertEqual(q.encoding, u'iso-8859-15') self.assertEqual(list(six...
'Test for bug #14020: Make HttpResponse.get work like dict.get'
def test_dict_behavior(self):
r = HttpResponse() self.assertEqual(r.get(u'test'), None)
'Test that we don\'t output tricky characters in encoded value'
def test_encode(self):
c = SimpleCookie() c[u'test'] = u'An,awkward;value' self.assertTrue((u';' not in c.output().rstrip(u';'))) self.assertTrue((u',' not in c.output().rstrip(u';')))
'Test that we can still preserve semi-colons and commas'
def test_decode(self):
c = SimpleCookie() c[u'test'] = u'An,awkward;value' c2 = SimpleCookie() c2.load(c.output()) self.assertEqual(c[u'test'].value, c2[u'test'].value)
'Test that we haven\'t broken normal encoding'
def test_decode_2(self):
c = SimpleCookie() c[u'test'] = '\xf0' c2 = SimpleCookie() c2.load(c.output()) self.assertEqual(c[u'test'].value, c2[u'test'].value)
'Test that a single non-standard cookie name doesn\'t affect all cookies. Ticket #13007.'
def test_nonstandard_keys(self):
self.assertTrue((u'good_cookie' in parse_cookie(u'good_cookie=yes;bad:cookie=yes').keys()))
'Test that a repeated non-standard name doesn\'t affect all cookies. Ticket #15852'
def test_repeated_nonstandard_keys(self):
self.assertTrue((u'good_cookie' in parse_cookie(u'a:=b; a:=c; good_cookie=yes').keys()))
'Test that we can use httponly attribute on cookies that we load'
def test_httponly_after_load(self):
c = SimpleCookie() c.load(u'name=val') c[u'name'][u'httponly'] = True self.assertTrue(c[u'name'][u'httponly'])
'Tests that django decorators set certain attributes of the wrapped function.'
def test_attributes(self):
self.assertEqual(fully_decorated.__name__, 'fully_decorated') self.assertEqual(fully_decorated.__doc__, 'Expected __doc__') self.assertEqual(fully_decorated.__dict__['anything'], 'Expected __dict__')
'Test that the user_passes_test decorator can be applied multiple times (#9474).'
def test_user_passes_test_composition(self):
def test1(user): user.decorators_applied.append('test1') return True def test2(user): user.decorators_applied.append('test2') return True def callback(request): return request.user.decorators_applied callback = user_passes_test(test1)(callback) callback = user...
'Test that we can call cache_page the new way'
def test_cache_page_new_style(self):
def my_view(request): return 'response' my_view_cached = cache_page(123)(my_view) self.assertEqual(my_view_cached(HttpRequest()), 'response') my_view_cached2 = cache_page(123, key_prefix='test')(my_view) self.assertEqual(my_view_cached2(HttpRequest()), 'response')
'Test that we can call cache_page the old way'
def test_cache_page_old_style(self):
def my_view(request): return 'response' with warnings.catch_warnings(record=True): my_view_cached = cache_page(my_view, 123) self.assertEqual(my_view_cached(HttpRequest()), 'response') my_view_cached2 = cache_page(my_view, 123, key_prefix='test') self.assertEqual(my_view_...
'Test for the require_safe decorator. A view returns either a response or an exception. Refs #15637.'
def test_require_safe_accepts_only_safe_methods(self):
def my_view(request): return HttpResponse('OK') my_safe_view = require_safe(my_view) request = HttpRequest() request.method = 'GET' self.assertTrue(isinstance(my_safe_view(request), HttpResponse)) request.method = 'HEAD' self.assertTrue(isinstance(my_safe_view(request), HttpResponse)...
'Ensures @xframe_options_deny properly sets the X-Frame-Options header.'
def test_deny_decorator(self):
@xframe_options_deny def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r['X-Frame-Options'], 'DENY')
'Ensures @xframe_options_sameorigin properly sets the X-Frame-Options header.'
def test_sameorigin_decorator(self):
@xframe_options_sameorigin def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
'Ensures @xframe_options_exempt properly instructs the XFrameOptionsMiddleware to NOT set the header.'
def test_exempt_decorator(self):
@xframe_options_exempt def a_view(request): return HttpResponse() req = HttpRequest() resp = a_view(req) self.assertEqual(resp.get('X-Frame-Options', None), None) self.assertTrue(resp.xframe_options_exempt) r = XFrameOptionsMiddleware().process_response(req, resp) self.assertEqua...
'Test that empty DATABASES setting default to the dummy backend.'
def test_no_databases(self):
DATABASES = {} conns = ConnectionHandler(DATABASES) self.assertEqual(conns[DEFAULT_DB_ALIAS].settings_dict[u'ENGINE'], u'django.db.backends.dummy')
'Check that auto_increment fields are reset correctly by sql_flush(). Before MySQL version 5.0.13 TRUNCATE did not do auto_increment reset. Refs #16961.'
@unittest.skipUnless((connection.vendor == u'mysql'), u'Test valid only for MySQL') def test_autoincrement(self):
statements = connection.ops.sql_flush(no_style(), tables=[u'test'], sequences=[{u'table': u'test', u'col': u'somecol'}]) found_reset = False for sql in statements: found_reset = (found_reset or (u'ALTER TABLE' in sql)) if (connection.mysql_version < (5, 0, 13)): self.assertTrue(found_...
'Test the custom ``django_date_trunc method``, in particular against fields which clash with strings passed to it (e.g. \'year\') - see #12818__. __: http://code.djangoproject.com/ticket/12818'
def test_django_date_trunc(self):
updated = datetime.datetime(2010, 2, 20) models.SchoolClass.objects.create(year=2009, last_updated=updated) years = models.SchoolClass.objects.dates(u'last_updated', u'year') self.assertEqual(list(years), [datetime.datetime(2010, 1, 1, 0, 0)])
'Test the custom ``django_extract method``, in particular against fields which clash with strings passed to it (e.g. \'day\') - see #12818__. __: http://code.djangoproject.com/ticket/12818'
def test_django_extract(self):
updated = datetime.datetime(2010, 2, 20) models.SchoolClass.objects.create(year=2009, last_updated=updated) classes = models.SchoolClass.objects.filter(last_updated__day=20) self.assertEqual(len(classes), 1)
'Test that last_executed_query() returns an Unicode string'
def test_query_encoding(self):
tags = models.Tag.objects.extra(select={u'f\xf6\xf6': 1}) (sql, params) = tags.query.sql_with_params() cursor = tags.query.get_compiler(u'default').execute_sql(None) last_sql = cursor.db.ops.last_executed_query(cursor, sql, params) self.assertTrue(isinstance(last_sql, six.text_type))
'An executemany call with too many/not enough parameters will raise an exception (Refs #12612)'
def test_bad_parameter_count(self):
cursor = connection.cursor() query = (u'INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % (connection.introspection.table_name_converter(u'backends_square'), connection.ops.quote_name(u'root'), connection.ops.quote_name(u'square'))) self.assertRaises(Exception, cursor.executemany, query, [(1...
'Test creation of model with long name and long pk name doesn\'t error. Ref #8901'
@skipUnlessDBFeature(u'supports_long_model_names') def test_sequence_name_length_limits_create(self):
models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
'Test an m2m save of a model with a long name and a long m2m field name doesn\'t error as on Django >=1.2 this now uses object saves. Ref #8901'
@skipUnlessDBFeature(u'supports_long_model_names') def test_sequence_name_length_limits_m2m(self):
obj = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() rel_obj = models.Person.objects.create(first_name=u'Django', last_name=u'Reinhardt') obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj)
'Test that sequence resetting as part of a flush with model with long name and long pk name doesn\'t error. Ref #8901'
@skipUnlessDBFeature(u'supports_long_model_names') def test_sequence_name_length_limits_flush(self):
VLM = models.VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ VLM_m2m = VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through tables = [VLM._meta.db_table, VLM_m2m._meta.db_table] sequences = [{u'column': VLM._meta.pk.column, u'table': VLM._meta.db_table}] ...
'Sequence names are correct when resetting generic relations (Ref #13941)'
def test_generic_relation(self):
models.Post.objects.create(id=10, name=u'1st post', text=u'hello world') cursor = connection.cursor() commands = connections[DEFAULT_DB_ALIAS].ops.sequence_reset_sql(no_style(), [models.Post]) for sql in commands: cursor.execute(sql) obj = models.Post.objects.create(name=u'New post'...
'Test PostgreSQL version parsing from `SELECT version()` output'
def test_parsing(self):
self.assert_parses(u'PostgreSQL 8.3 beta4', 80300) self.assert_parses(u'PostgreSQL 8.3', 80300) self.assert_parses(u'EnterpriseDB 8.3', 80300) self.assert_parses(u'PostgreSQL 8.3.6', 80306) self.assert_parses(u'PostgreSQL 8.4beta1', 80400) self.assert_parses(u'PostgreSQL 8.3...
'Test PostgreSQL version detection'
def test_version_detection(self):
class CursorMock(object, ): u'Very simple mock of DB-API cursor' def execute(self, arg): pass def fetchone(self): return [u'PostgreSQL 8.3'] class OlderConnectionMock(object, ): u'Mock of psycopg2 (< 2.0.12) connection' ...
'Test that creating an existing table returns a DatabaseError'
def test_duplicate_table_error(self):
cursor = connection.cursor() query = (u'CREATE TABLE %s (id INTEGER);' % models.Article._meta.db_table) with self.assertRaises(DatabaseError): cursor.execute(query)
'Try to create a model instance that violates a FK constraint. If it fails it should fail with IntegrityError.'
def test_integrity_checks_on_creation(self):
a = models.Article(headline=u'This is a test', pub_date=datetime.datetime(2005, 7, 27), reporter_id=30) try: a.save() except IntegrityError: return self.skipTest(u'This backend does not support integrity checks.')
'Try to update a model instance introducing a FK constraint violation. If it fails it should fail with IntegrityError.'
def test_integrity_checks_on_update(self):
models.Article.objects.create(headline=u'Test article', pub_date=datetime.datetime(2010, 9, 4), reporter=self.r) a = models.Article.objects.get(headline=u'Test article') a.reporter_id = 30 try: a.save() except IntegrityError: return self.skipTest(u'This backend does ...
'When constraint checks are disabled, should be able to write bad data without IntegrityErrors.'
def test_disable_constraint_checks_manually(self):
with transaction.commit_manually(): models.Article.objects.create(headline=u'Test article', pub_date=datetime.datetime(2010, 9, 4), reporter=self.r) a = models.Article.objects.get(headline=u'Test article') a.reporter_id = 30 try: connection.disable_constraint_checki...
'When constraint checks are disabled (using context manager), should be able to write bad data without IntegrityErrors.'
def test_disable_constraint_checks_context_manager(self):
with transaction.commit_manually(): models.Article.objects.create(headline=u'Test article', pub_date=datetime.datetime(2010, 9, 4), reporter=self.r) a = models.Article.objects.get(headline=u'Test article') a.reporter_id = 30 try: with connection.constraint_checks_di...
'Constraint checks should raise an IntegrityError when bad data is in the DB.'
def test_check_constraints(self):
with transaction.commit_manually(): models.Article.objects.create(headline=u'Test article', pub_date=datetime.datetime(2010, 9, 4), reporter=self.r) a = models.Article.objects.get(headline=u'Test article') a.reporter_id = 30 try: with connection.constraint_checks_di...
'Ensure that the default connection (i.e. django.db.connection) is different for each thread. Refs #17258.'
def test_default_connection_thread_local(self):
connections_set = set() connection.cursor() connections_set.add(connection.connection) def runner(): from django.db import connection connection.cursor() connections_set.add(connection.connection) for x in range(2): t = threading.Thread(target=runner) t.start(...
'Ensure that the connections are different for each thread. Refs #17258.'
def test_connections_thread_local(self):
connections_dict = {} for conn in connections.all(): connections_dict[id(conn)] = conn def runner(): from django.db import connections for conn in connections.all(): conn.allow_thread_sharing = True connections_dict[id(conn)] = conn for x in range(2): ...
'Ensure that a connection can be passed from one thread to the other. Refs #17258.'
def test_pass_connection_between_threads(self):
models.Person.objects.create(first_name=u'John', last_name=u'Doe') def do_thread(): def runner(main_thread_connection): from django.db import connections connections[u'default'] = main_thread_connection try: models.Person.objects.get(first_name=u'John'...
'Ensure that a connection that is not explicitly shareable cannot be closed by another thread. Refs #17258.'
def test_closing_non_shared_connections(self):
exceptions = set() def runner1(): def runner2(other_thread_connection): try: other_thread_connection.close() except DatabaseError as e: exceptions.add(e) t2 = threading.Thread(target=runner2, args=[connections[u'default']]) t2.start...
'Regression test for the use of None as a query value. None is interpreted as an SQL NULL, but only in __exact queries. Set up some initial polls and choices'
def test_none_as_null(self):
p1 = Poll(question='Why?') p1.save() c1 = Choice(poll=p1, choice='Because.') c1.save() c2 = Choice(poll=p1, choice='Why Not?') c2.save() self.assertQuerysetEqual(Choice.objects.filter(choice__exact=None), []) self.assertQuerysetEqual(Choice.objects.exclude(choice=None).order_by('id'),...
'Querying across reverse relations and then another relation should insert outer joins correctly so as not to exclude results.'
def test_reverse_relations(self):
obj = OuterA.objects.create() self.assertQuerysetEqual(OuterA.objects.filter(inner__second=None), ['<OuterA: OuterA object>']) self.assertQuerysetEqual(OuterA.objects.filter(inner__second__data=None), ['<OuterA: OuterA object>']) inner_obj = Inner.objects.create(first=obj) self.assertQue...
'Ensure that the LiveServerTestCase serves 404s. Refs #2879.'
def test_404(self):
try: self.urlopen(u'/') except HTTPError as err: self.assertEqual(err.code, 404, u'Expected 404 response') else: self.fail(u'Expected 404 response')
'Ensure that the LiveServerTestCase serves views. Refs #2879.'
def test_view(self):
f = self.urlopen(u'/example_view/') self.assertEqual(f.read(), 'example view')
'Ensure that the LiveServerTestCase serves static files. Refs #2879.'
def test_static_files(self):
f = self.urlopen(u'/static/example_static_file.txt') self.assertEqual(f.read().rstrip('\r\n'), 'example static file')
'Ensure that the LiveServerTestCase serves media files. Refs #2879.'
def test_media_files(self):
f = self.urlopen(u'/media/example_media_file.txt') self.assertEqual(f.read().rstrip('\r\n'), 'example media file')
'Ensure that fixtures are properly loaded and visible to the live server thread. Refs #2879.'
def test_fixtures_loaded(self):
f = self.urlopen(u'/model_view/') self.assertEqual(f.read().splitlines(), ['jane', 'robert'])
'Ensure that data written to the database by a view can be read. Refs #2879.'
def test_database_writes(self):
self.urlopen(u'/create_model_instance/') self.assertQuerysetEqual(Person.objects.all().order_by(u'pk'), [u'jane', u'robert', u'emily'], (lambda b: b.name))
'Tests that content is removed from regular and streaming responses with a status_code of 100-199, 204, 304 or a method of "HEAD".'
def test_conditional_content_removal(self):
req = HttpRequest() res = HttpResponse(u'abc') conditional_content_removal(req, res) self.assertEqual(res.content, 'abc') res = StreamingHttpResponse([u'abc']) conditional_content_removal(req, res) self.assertEqual(''.join(res), 'abc') for status_code in (100, 150, 199, 204, 304): ...
'Testing utility asserting that text1 appears before text2 in response content.'
def assertContentBefore(self, response, text1, text2, failing_msg=None):
self.assertEqual(response.status_code, 200) self.assertTrue((response.content.index(force_bytes(text1)) < response.content.index(force_bytes(text2))), failing_msg)
'If you leave off the trailing slash, app should redirect and add it.'
def testTrailingSlashRequired(self):
response = self.client.get((u'/test_admin/%s/admin_views/article/add' % self.urlbit)) self.assertRedirects(response, (u'/test_admin/%s/admin_views/article/add/' % self.urlbit), status_code=301)
'A smoke test to ensure GET on the add_view works.'
def testBasicAddGet(self):
response = self.client.get((u'/test_admin/%s/admin_views/section/add/' % self.urlbit)) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200)
'A smoke test to ensure GET on the change_view works.'
def testBasicEditGet(self):
response = self.client.get((u'/test_admin/%s/admin_views/section/1/' % self.urlbit)) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200)
'A smoke test to ensure GET on the change_view works (returns an HTTP 404 error, see #11191) when passing a string as the PK argument for a model with an integer PK field.'
def testBasicEditGetStringPK(self):
response = self.client.get((u'/test_admin/%s/admin_views/section/abc/' % self.urlbit)) self.assertEqual(response.status_code, 404)
'A smoke test to ensure POST on add_view works.'
def testBasicAddPost(self):
post_data = {u'name': u'Another Section', u'article_set-TOTAL_FORMS': u'3', u'article_set-INITIAL_FORMS': u'0', u'article_set-MAX_NUM_FORMS': u'0'} response = self.client.post((u'/test_admin/%s/admin_views/section/add/' % self.urlbit), post_data) self.assertEqual(response.status_code, 302)
'Ensure http response from a popup is properly escaped.'
def testPopupAddPost(self):
post_data = {u'_popup': u'1', u'title': u'title with a new\nline', u'content': u'some content', u'date_0': u'2010-09-10', u'date_1': u'14:55:39'} response = self.client.post((u'/test_admin/%s/admin_views/article/add/' % self.urlbit), post_data) self.assertEqual(response.status_code, 200) sel...
'A smoke test to ensure POST on edit_view works.'
def testBasicEditPost(self):
response = self.client.post((u'/test_admin/%s/admin_views/section/1/' % self.urlbit), self.inline_post_data) self.assertEqual(response.status_code, 302)
'Test "save as".'
def testEditSaveAs(self):
post_data = self.inline_post_data.copy() post_data.update({u'_saveasnew': u'Save+as+new', u'article_set-1-section': u'1', u'article_set-2-section': u'1', u'article_set-3-section': u'1', u'article_set-4-section': u'1', u'article_set-5-section': u'1'}) response = self.client.post((u'/test_admin/%s/admin_views...
'Ensure we can sort on a list_display field that is a callable (column 2 is callable_year in ArticleAdmin)'
def testChangeListSortingCallable(self):
response = self.client.get((u'/test_admin/%s/admin_views/article/' % self.urlbit), {u'o': 2}) self.assertContentBefore(response, u'Oldest content', u'Middle content', u'Results of sorting on callable are out of order.') self.assertContentBefore(response, u'Middle content', u...
'Ensure we can sort on a list_display field that is a Model method (colunn 3 is \'model_year\' in ArticleAdmin)'
def testChangeListSortingModel(self):
response = self.client.get((u'/test_admin/%s/admin_views/article/' % self.urlbit), {u'o': u'-3'}) self.assertContentBefore(response, u'Newest content', u'Middle content', u'Results of sorting on Model method are out of order.') self.assertContentBefore(response, u'Middle ...
'Ensure we can sort on a list_display field that is a ModelAdmin method (colunn 4 is \'modeladmin_year\' in ArticleAdmin)'
def testChangeListSortingModelAdmin(self):
response = self.client.get((u'/test_admin/%s/admin_views/article/' % self.urlbit), {u'o': u'4'}) self.assertContentBefore(response, u'Oldest content', u'Middle content', u'Results of sorting on ModelAdmin method are out of order.') self.assertContentBefore(response, u'Middle...
'If no ordering is defined in `ModelAdmin.ordering` or in the query string, then the underlying order of the queryset should not be changed, even if it is defined in `Modeladmin.queryset()`. Refs #11868, #7309.'
def testChangeListSortingPreserveQuerySetOrdering(self):
p1 = Person.objects.create(name=u'Amy', gender=1, alive=True, age=80) p2 = Person.objects.create(name=u'Bob', gender=1, alive=True, age=70) p3 = Person.objects.create(name=u'Chris', gender=2, alive=False, age=60) link1 = reverse(u'admin:admin_views_person_change', args=(p1.pk,)) link2 = reverse(u'ad...
'Ensures that the admin shows default sort indicators for all kinds of \'ordering\' fields: field names, method on the model admin and model itself, and other callables. See #17252.'
def testSortIndicatorsAdminOrder(self):
models = [(AdminOrderedField, u'adminorderedfield'), (AdminOrderedModelMethod, u'adminorderedmodelmethod'), (AdminOrderedAdminMethod, u'adminorderedadminmethod'), (AdminOrderedCallable, u'adminorderedcallable')] for (model, url) in models: a1 = model.objects.create(stuff=u'The Last Item', order=3)...
'Ensure admin changelist filters do not contain objects excluded via limit_choices_to. This also tests relation-spanning filters (e.g. \'color__value\').'
def testLimitedFilter(self):
response = self.client.get((u'/test_admin/%s/admin_views/thing/' % self.urlbit)) self.assertEqual(response.status_code, 200) self.assertContains(response, u'<div id="changelist-filter">', msg_prefix=u'Expected filter not found in changelist view') self.assertNotContains(response, u'...
'Ensure incorrect lookup parameters are handled gracefully.'
def testIncorrectLookupParameters(self):
response = self.client.get((u'/test_admin/%s/admin_views/thing/' % self.urlbit), {u'notarealfield': u'5'}) self.assertRedirects(response, (u'/test_admin/%s/admin_views/thing/?e=1' % self.urlbit)) response = self.client.get((u'/test_admin/%s/admin_views/thing/' % self.urlbit), {u'notarealfield__whatever': u'...
'Ensure is_null is handled correctly.'
def testIsNullLookups(self):
Article.objects.create(title=u'I Could Go Anywhere', content=u'Versatile', date=datetime.datetime.now()) response = self.client.get((u'/test_admin/%s/admin_views/article/' % self.urlbit)) self.assertContains(response, u'4 articles') response = self.client.get((u'/test_admin/%s/admin_views/ar...
'Ensures the admin changelist shows correct values in the relevant column for rows corresponding to instances of a model in which a named group has been used in the choices option of a field.'
def testNamedGroupFieldChoicesChangeList(self):
link1 = reverse(u'admin:admin_views_fabric_change', args=(1,), current_app=self.urlbit) link2 = reverse(u'admin:admin_views_fabric_change', args=(2,), current_app=self.urlbit) response = self.client.get((u'/test_admin/%s/admin_views/fabric/' % self.urlbit)) fail_msg = u"Changelist table isn't s...
'Ensures the filter UI shows correctly when at least one named group has been used in the choices option of a model field.'
def testNamedGroupFieldChoicesFilter(self):
response = self.client.get((u'/test_admin/%s/admin_views/fabric/' % self.urlbit)) fail_msg = u"Changelist filter isn't showing options contained inside a model field 'choices' option named group." self.assertContains(response, u'<div id="changelist-filter">') se...
'Check if the JavaScript i18n view returns an empty language catalog if the default language is non-English but the selected language is English. See #13388 and #3594 for more details.'
def testI18NLanguageNonEnglishDefault(self):
with self.settings(LANGUAGE_CODE=u'fr'): with translation.override(u'en-us'): response = self.client.get(u'/test_admin/admin/jsi18n/') self.assertNotContains(response, u'Choisir une heure')
'Makes sure that the fallback language is still working properly in cases where the selected language cannot be found.'
def testI18NLanguageNonEnglishFallback(self):
with self.settings(LANGUAGE_CODE=u'fr'): with translation.override(u'none'): response = self.client.get(u'/test_admin/admin/jsi18n/') self.assertContains(response, u'Choisir une heure')
'Check if L10N is deactivated, the JavaScript i18n view doesn\'t return localized date/time formats. Refs #14824.'
def testL10NDeactivated(self):
with self.settings(LANGUAGE_CODE=u'ru', USE_L10N=False): with translation.override(u'none'): response = self.client.get(u'/test_admin/admin/jsi18n/') self.assertNotContains(response, u'%d.%m.%Y %H:%M:%S') self.assertContains(response, u'%Y-%m-%d %H:%M:%S')
'Regressions test for ticket 15103 - filtering on fields defined in a ForeignKey \'limit_choices_to\' should be allowed, otherwise raw_id_fields can break.'
def test_allowed_filtering_15103(self):
try: self.client.get(u'/test_admin/admin/admin_views/inquisition/?leader__name=Palin&leader__age=27') except SuspiciousOperation: self.fail(u'Filters should be allowed if they are defined on a ForeignKey pointing to this model')
'Tests if the "change password" link in the admin is hidden if the User does not have a usable password set. (against 9bea85795705d015cdadc82c68b99196a8554f5c)'
def test_hide_change_password(self):
user = User.objects.get(username=u'super') password = user.password user.set_unusable_password() user.save() response = self.client.get(u'/test_admin/admin/') self.assertNotContains(response, reverse(u'admin:password_change'), msg_prefix=u'The "change password" link should not ...
'Ensured that the \'show_delete\' context variable in the admin\'s change view actually controls the display of the delete button. Refs #10057.'
def test_change_view_with_show_delete_extra_context(self):
instance = UndeletableObject.objects.create(name=u'foo') response = self.client.get((u'/test_admin/%s/admin_views/undeletableobject/%d/' % (self.urlbit, instance.pk))) self.assertNotContains(response, u'deletelink')
'Ensure that AttributeErrors are allowed to bubble when raised inside a change list view. Requires a model to be created so there\'s something to be displayed Refs: #16655, #18593, and #18747'
def test_allows_attributeerror_to_bubble_up(self):
Simple.objects.create() with self.assertRaises(AttributeError): self.client.get((u'/test_admin/%s/admin_views/simple/' % self.urlbit))
'Tests whether change_view has form_url in response.context'
def testChangeFormUrlHasCorrectValue(self):
response = self.client.get((u'/test_admin/%s/admin_views/section/1/' % self.urlbit)) self.assertTrue((u'form_url' in response.context), msg=u'form_url not present in response.context') self.assertEqual(response.context[u'form_url'], u'pony')
'Ensure that one can use a custom template to render an admin filter. Refs #17515.'
def test_filter_with_custom_template(self):
template_dirs = (settings.TEMPLATE_DIRS + (os.path.join(os.path.dirname(upath(__file__)), u'templates'),)) with self.settings(TEMPLATE_DIRS=template_dirs): response = self.client.get(u'/test_admin/admin/admin_views/color2/') self.assertTrue((u'custom_filter_template.html' in [t.name for t in res...
'JavaScript-assisted auto-focus on first field.'
def testSingleWidgetFirsFieldFocus(self):
response = self.client.get((u'/test_admin/%s/admin_views/picture/add/' % u'admin')) self.assertContains(response, u'<script type="text/javascript">document.getElementById("id_name").focus();</script>')
'JavaScript-assisted auto-focus should work if a model/ModelAdmin setup is such that the first form field has a MultiWidget.'
def testMultiWidgetFirsFieldFocus(self):
response = self.client.get((u'/test_admin/%s/admin_views/reservation/add/' % u'admin')) self.assertContains(response, u'<script type="text/javascript">document.getElementById("id_start_date_0").focus();</script>')
'Ensure that the minified versions of the JS files are only used when DEBUG is False. Refs #17521.'
def test_js_minified_only_if_debug_is_false(self):
with override_settings(DEBUG=False): response = self.client.get((u'/test_admin/%s/admin_views/section/add/' % u'admin')) self.assertNotContains(response, u'jquery.js') self.assertContains(response, u'jquery.min.js') self.assertNotContains(response, u'prepopulate.js') self.ass...
'Ensure save as actually creates a new person'
def test_save_as_duplication(self):
post_data = {u'_saveasnew': u'', u'name': u'John M', u'gender': 1, u'age': 42} response = self.client.post(u'/test_admin/admin/admin_views/person/1/', post_data) self.assertEqual(len(Person.objects.filter(name=u'John M')), 1) self.assertEqual(len(Person.objects.filter(id=1)), 1)
'Ensure that \'save as\' is displayed when activated and after submitting invalid data aside save_as_new will not show us a form to overwrite the initial model.'
def test_save_as_display(self):
response = self.client.get(u'/test_admin/admin/admin_views/person/1/') self.assertTrue(response.context[u'save_as']) post_data = {u'_saveasnew': u'', u'name': u'John M', u'gender': 3, u'alive': u'checked'} response = self.client.post(u'/test_admin/admin/admin_views/person/1/', post_data) self.ass...
'Test setup.'
def setUp(self):
opts = Article._meta add_user = User.objects.get(username=u'adduser') add_user.user_permissions.add(get_perm(Article, opts.get_add_permission())) change_user = User.objects.get(username=u'changeuser') change_user.user_permissions.add(get_perm(Article, opts.get_change_permission())) delete_user =...
'Make sure only staff members can log in. Successful posts to the login page will redirect to the orignal url. Unsuccessfull attempts will continue to render the login page with a 200 status code.'
def testLogin(self):
response = self.client.get(u'/test_admin/admin/') self.assertEqual(response.status_code, 200) login = self.client.post(u'/test_admin/admin/', self.super_login) self.assertRedirects(login, u'/test_admin/admin/') self.assertFalse(login.context) self.client.get(u'/test_admin/admin/logout/') res...
'Test add view restricts access and actually adds items.'
def testAddView(self):
add_dict = {u'title': u'D\xf8m ikke', u'content': u'<p>great article</p>', u'date_0': u'2008-03-18', u'date_1': u'10:54:39', u'section': 1} self.client.get(u'/test_admin/admin/') self.client.post(u'/test_admin/admin/', self.changeuser_login) self.assertEqual(self.client.session.test_cookie_worked(...
'Change view should restrict access and allow users to edit items.'
def testChangeView(self):
change_dict = {u'title': u'Ikke ford\xf8mt', u'content': u'<p>edited article</p>', u'date_0': u'2008-03-18', u'date_1': u'10:54:39', u'section': 1} self.client.get(u'/test_admin/admin/') self.client.post(u'/test_admin/admin/', self.adduser_login) response = self.client.get(u'/test_admin/admin/admi...
'History view should restrict access.'
def testHistoryView(self):
self.client.get(u'/test_admin/admin/') self.client.post(u'/test_admin/admin/', self.adduser_login) response = self.client.get(u'/test_admin/admin/admin_views/article/1/history/') self.assertEqual(response.status_code, 403) self.client.get(u'/test_admin/admin/logout/') self.client.get(u'/test_adm...
'The foreign key widget should only show the "add related" button if the user has permission to add that related item.'
def testConditionallyShowAddSectionLink(self):
url = u'/test_admin/admin/admin_views/article/add/' add_link_text = u' class="add-another"' self.client.get(u'/test_admin/admin/') self.client.post(u'/test_admin/admin/', self.adduser_login) response = self.client.get(url) self.assertNotContains(response, add_link_text) add_user = User.ob...
'Delete view should restrict access and actually delete items.'
def testDeleteView(self):
delete_dict = {u'post': u'yes'} self.client.get(u'/test_admin/admin/') self.client.post(u'/test_admin/admin/', self.adduser_login) response = self.client.get(u'/test_admin/admin/admin_views/article/1/delete/') self.assertEqual(response.status_code, 403) post = self.client.post(u'/test_admin/admi...
'Admin index views don\'t break when user\'s ModelAdmin removes standard urls'
def test_no_standard_modeladmin_urls(self):
self.client.get(u'/test_admin/admin/') self.client.post(u'/test_admin/admin/', self.changeuser_login) r = self.client.get(u'/test_admin/admin/') self.assertEqual(r.status_code, 200) self.client.get(u'/test_admin/admin/logout/')
'Objects should be nested to display the relationships that cause them to be scheduled for deletion.'
def test_nesting(self):
pattern = re.compile('<li>Plot: <a href=".+/admin_views/plot/1/">World Domination</a>\\s*<ul>\\s*<li>Plot details: <a href=".+/admin_views/plotdetails/1/">almost finished</a>') response = self.client.get((u'/test_admin/admin/admin_views/villain/%s/delete/' % quote(1))) self.assertRegexp...