tests.py 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074
  1. import logging
  2. import os
  3. import unittest
  4. import warnings
  5. from io import StringIO
  6. from unittest import mock
  7. from django.conf import settings
  8. from django.contrib.staticfiles.finders import get_finder, get_finders
  9. from django.contrib.staticfiles.storage import staticfiles_storage
  10. from django.core.exceptions import ImproperlyConfigured
  11. from django.core.files.storage import default_storage
  12. from django.db import (
  13. IntegrityError, connection, connections, models, router, transaction,
  14. )
  15. from django.forms import (
  16. CharField, EmailField, Form, IntegerField, ValidationError,
  17. formset_factory,
  18. )
  19. from django.http import HttpResponse
  20. from django.template.loader import render_to_string
  21. from django.test import (
  22. SimpleTestCase, TestCase, TransactionTestCase, skipIfDBFeature,
  23. skipUnlessDBFeature,
  24. )
  25. from django.test.html import HTMLParseError, parse_html
  26. from django.test.testcases import DatabaseOperationForbidden
  27. from django.test.utils import (
  28. CaptureQueriesContext, TestContextDecorator, ignore_warnings, isolate_apps,
  29. override_settings, setup_test_environment,
  30. )
  31. from django.urls import NoReverseMatch, path, reverse, reverse_lazy
  32. from django.utils.deprecation import RemovedInDjango50Warning
  33. from django.utils.log import DEFAULT_LOGGING
  34. from .models import Car, Person, PossessedCar
  35. from .views import empty_response
  36. class SkippingTestCase(SimpleTestCase):
  37. def _assert_skipping(self, func, expected_exc, msg=None):
  38. try:
  39. if msg is not None:
  40. with self.assertRaisesMessage(expected_exc, msg):
  41. func()
  42. else:
  43. with self.assertRaises(expected_exc):
  44. func()
  45. except unittest.SkipTest:
  46. self.fail('%s should not result in a skipped test.' % func.__name__)
  47. def test_skip_unless_db_feature(self):
  48. """
  49. Testing the django.test.skipUnlessDBFeature decorator.
  50. """
  51. # Total hack, but it works, just want an attribute that's always true.
  52. @skipUnlessDBFeature("__class__")
  53. def test_func():
  54. raise ValueError
  55. @skipUnlessDBFeature("notprovided")
  56. def test_func2():
  57. raise ValueError
  58. @skipUnlessDBFeature("__class__", "__class__")
  59. def test_func3():
  60. raise ValueError
  61. @skipUnlessDBFeature("__class__", "notprovided")
  62. def test_func4():
  63. raise ValueError
  64. self._assert_skipping(test_func, ValueError)
  65. self._assert_skipping(test_func2, unittest.SkipTest)
  66. self._assert_skipping(test_func3, ValueError)
  67. self._assert_skipping(test_func4, unittest.SkipTest)
  68. class SkipTestCase(SimpleTestCase):
  69. @skipUnlessDBFeature('missing')
  70. def test_foo(self):
  71. pass
  72. self._assert_skipping(
  73. SkipTestCase('test_foo').test_foo,
  74. ValueError,
  75. "skipUnlessDBFeature cannot be used on test_foo (test_utils.tests."
  76. "SkippingTestCase.test_skip_unless_db_feature.<locals>.SkipTestCase) "
  77. "as SkippingTestCase.test_skip_unless_db_feature.<locals>.SkipTestCase "
  78. "doesn't allow queries against the 'default' database."
  79. )
  80. def test_skip_if_db_feature(self):
  81. """
  82. Testing the django.test.skipIfDBFeature decorator.
  83. """
  84. @skipIfDBFeature("__class__")
  85. def test_func():
  86. raise ValueError
  87. @skipIfDBFeature("notprovided")
  88. def test_func2():
  89. raise ValueError
  90. @skipIfDBFeature("__class__", "__class__")
  91. def test_func3():
  92. raise ValueError
  93. @skipIfDBFeature("__class__", "notprovided")
  94. def test_func4():
  95. raise ValueError
  96. @skipIfDBFeature("notprovided", "notprovided")
  97. def test_func5():
  98. raise ValueError
  99. self._assert_skipping(test_func, unittest.SkipTest)
  100. self._assert_skipping(test_func2, ValueError)
  101. self._assert_skipping(test_func3, unittest.SkipTest)
  102. self._assert_skipping(test_func4, unittest.SkipTest)
  103. self._assert_skipping(test_func5, ValueError)
  104. class SkipTestCase(SimpleTestCase):
  105. @skipIfDBFeature('missing')
  106. def test_foo(self):
  107. pass
  108. self._assert_skipping(
  109. SkipTestCase('test_foo').test_foo,
  110. ValueError,
  111. "skipIfDBFeature cannot be used on test_foo (test_utils.tests."
  112. "SkippingTestCase.test_skip_if_db_feature.<locals>.SkipTestCase) "
  113. "as SkippingTestCase.test_skip_if_db_feature.<locals>.SkipTestCase "
  114. "doesn't allow queries against the 'default' database."
  115. )
  116. class SkippingClassTestCase(TestCase):
  117. def test_skip_class_unless_db_feature(self):
  118. @skipUnlessDBFeature("__class__")
  119. class NotSkippedTests(TestCase):
  120. def test_dummy(self):
  121. return
  122. @skipUnlessDBFeature("missing")
  123. @skipIfDBFeature("__class__")
  124. class SkippedTests(TestCase):
  125. def test_will_be_skipped(self):
  126. self.fail("We should never arrive here.")
  127. @skipIfDBFeature("__dict__")
  128. class SkippedTestsSubclass(SkippedTests):
  129. pass
  130. test_suite = unittest.TestSuite()
  131. test_suite.addTest(NotSkippedTests('test_dummy'))
  132. try:
  133. test_suite.addTest(SkippedTests('test_will_be_skipped'))
  134. test_suite.addTest(SkippedTestsSubclass('test_will_be_skipped'))
  135. except unittest.SkipTest:
  136. self.fail('SkipTest should not be raised here.')
  137. result = unittest.TextTestRunner(stream=StringIO()).run(test_suite)
  138. self.assertEqual(result.testsRun, 3)
  139. self.assertEqual(len(result.skipped), 2)
  140. self.assertEqual(result.skipped[0][1], 'Database has feature(s) __class__')
  141. self.assertEqual(result.skipped[1][1], 'Database has feature(s) __class__')
  142. def test_missing_default_databases(self):
  143. @skipIfDBFeature('missing')
  144. class MissingDatabases(SimpleTestCase):
  145. def test_assertion_error(self):
  146. pass
  147. suite = unittest.TestSuite()
  148. try:
  149. suite.addTest(MissingDatabases('test_assertion_error'))
  150. except unittest.SkipTest:
  151. self.fail("SkipTest should not be raised at this stage")
  152. runner = unittest.TextTestRunner(stream=StringIO())
  153. msg = (
  154. "skipIfDBFeature cannot be used on <class 'test_utils.tests."
  155. "SkippingClassTestCase.test_missing_default_databases.<locals>."
  156. "MissingDatabases'> as it doesn't allow queries against the "
  157. "'default' database."
  158. )
  159. with self.assertRaisesMessage(ValueError, msg):
  160. runner.run(suite)
  161. @override_settings(ROOT_URLCONF='test_utils.urls')
  162. class AssertNumQueriesTests(TestCase):
  163. def test_assert_num_queries(self):
  164. def test_func():
  165. raise ValueError
  166. with self.assertRaises(ValueError):
  167. self.assertNumQueries(2, test_func)
  168. def test_assert_num_queries_with_client(self):
  169. person = Person.objects.create(name='test')
  170. self.assertNumQueries(
  171. 1,
  172. self.client.get,
  173. "/test_utils/get_person/%s/" % person.pk
  174. )
  175. self.assertNumQueries(
  176. 1,
  177. self.client.get,
  178. "/test_utils/get_person/%s/" % person.pk
  179. )
  180. def test_func():
  181. self.client.get("/test_utils/get_person/%s/" % person.pk)
  182. self.client.get("/test_utils/get_person/%s/" % person.pk)
  183. self.assertNumQueries(2, test_func)
  184. @unittest.skipUnless(
  185. connection.vendor != 'sqlite' or not connection.is_in_memory_db(),
  186. 'For SQLite in-memory tests, closing the connection destroys the database.'
  187. )
  188. class AssertNumQueriesUponConnectionTests(TransactionTestCase):
  189. available_apps = []
  190. def test_ignores_connection_configuration_queries(self):
  191. real_ensure_connection = connection.ensure_connection
  192. connection.close()
  193. def make_configuration_query():
  194. is_opening_connection = connection.connection is None
  195. real_ensure_connection()
  196. if is_opening_connection:
  197. # Avoid infinite recursion. Creating a cursor calls
  198. # ensure_connection() which is currently mocked by this method.
  199. with connection.cursor() as cursor:
  200. cursor.execute('SELECT 1' + connection.features.bare_select_suffix)
  201. ensure_connection = 'django.db.backends.base.base.BaseDatabaseWrapper.ensure_connection'
  202. with mock.patch(ensure_connection, side_effect=make_configuration_query):
  203. with self.assertNumQueries(1):
  204. list(Car.objects.all())
  205. class AssertQuerysetEqualTests(TestCase):
  206. @classmethod
  207. def setUpTestData(cls):
  208. cls.p1 = Person.objects.create(name='p1')
  209. cls.p2 = Person.objects.create(name='p2')
  210. def test_empty(self):
  211. self.assertQuerysetEqual(Person.objects.filter(name='p3'), [])
  212. def test_ordered(self):
  213. self.assertQuerysetEqual(
  214. Person.objects.all().order_by('name'),
  215. [self.p1, self.p2],
  216. )
  217. def test_unordered(self):
  218. self.assertQuerysetEqual(
  219. Person.objects.all().order_by('name'),
  220. [self.p2, self.p1],
  221. ordered=False
  222. )
  223. def test_queryset(self):
  224. self.assertQuerysetEqual(
  225. Person.objects.all().order_by('name'),
  226. Person.objects.all().order_by('name'),
  227. )
  228. def test_flat_values_list(self):
  229. self.assertQuerysetEqual(
  230. Person.objects.all().order_by('name').values_list('name', flat=True),
  231. ['p1', 'p2'],
  232. )
  233. def test_transform(self):
  234. self.assertQuerysetEqual(
  235. Person.objects.all().order_by('name'),
  236. [self.p1.pk, self.p2.pk],
  237. transform=lambda x: x.pk
  238. )
  239. def test_repr_transform(self):
  240. self.assertQuerysetEqual(
  241. Person.objects.all().order_by('name'),
  242. [repr(self.p1), repr(self.p2)],
  243. transform=repr,
  244. )
  245. def test_undefined_order(self):
  246. # Using an unordered queryset with more than one ordered value
  247. # is an error.
  248. msg = (
  249. 'Trying to compare non-ordered queryset against more than one '
  250. 'ordered value.'
  251. )
  252. with self.assertRaisesMessage(ValueError, msg):
  253. self.assertQuerysetEqual(
  254. Person.objects.all(),
  255. [self.p1, self.p2],
  256. )
  257. # No error for one value.
  258. self.assertQuerysetEqual(Person.objects.filter(name='p1'), [self.p1])
  259. def test_repeated_values(self):
  260. """
  261. assertQuerysetEqual checks the number of appearance of each item
  262. when used with option ordered=False.
  263. """
  264. batmobile = Car.objects.create(name='Batmobile')
  265. k2000 = Car.objects.create(name='K 2000')
  266. PossessedCar.objects.bulk_create([
  267. PossessedCar(car=batmobile, belongs_to=self.p1),
  268. PossessedCar(car=batmobile, belongs_to=self.p1),
  269. PossessedCar(car=k2000, belongs_to=self.p1),
  270. PossessedCar(car=k2000, belongs_to=self.p1),
  271. PossessedCar(car=k2000, belongs_to=self.p1),
  272. PossessedCar(car=k2000, belongs_to=self.p1),
  273. ])
  274. with self.assertRaises(AssertionError):
  275. self.assertQuerysetEqual(
  276. self.p1.cars.all(),
  277. [batmobile, k2000],
  278. ordered=False
  279. )
  280. self.assertQuerysetEqual(
  281. self.p1.cars.all(),
  282. [batmobile] * 2 + [k2000] * 4,
  283. ordered=False
  284. )
  285. def test_maxdiff(self):
  286. names = ['Joe Smith %s' % i for i in range(20)]
  287. Person.objects.bulk_create([Person(name=name) for name in names])
  288. names.append('Extra Person')
  289. with self.assertRaises(AssertionError) as ctx:
  290. self.assertQuerysetEqual(
  291. Person.objects.filter(name__startswith='Joe'),
  292. names,
  293. ordered=False,
  294. transform=lambda p: p.name,
  295. )
  296. self.assertIn('Set self.maxDiff to None to see it.', str(ctx.exception))
  297. original = self.maxDiff
  298. self.maxDiff = None
  299. try:
  300. with self.assertRaises(AssertionError) as ctx:
  301. self.assertQuerysetEqual(
  302. Person.objects.filter(name__startswith='Joe'),
  303. names,
  304. ordered=False,
  305. transform=lambda p: p.name,
  306. )
  307. finally:
  308. self.maxDiff = original
  309. exception_msg = str(ctx.exception)
  310. self.assertNotIn('Set self.maxDiff to None to see it.', exception_msg)
  311. for name in names:
  312. self.assertIn(name, exception_msg)
  313. @override_settings(ROOT_URLCONF='test_utils.urls')
  314. class CaptureQueriesContextManagerTests(TestCase):
  315. @classmethod
  316. def setUpTestData(cls):
  317. cls.person_pk = str(Person.objects.create(name='test').pk)
  318. def test_simple(self):
  319. with CaptureQueriesContext(connection) as captured_queries:
  320. Person.objects.get(pk=self.person_pk)
  321. self.assertEqual(len(captured_queries), 1)
  322. self.assertIn(self.person_pk, captured_queries[0]['sql'])
  323. with CaptureQueriesContext(connection) as captured_queries:
  324. pass
  325. self.assertEqual(0, len(captured_queries))
  326. def test_within(self):
  327. with CaptureQueriesContext(connection) as captured_queries:
  328. Person.objects.get(pk=self.person_pk)
  329. self.assertEqual(len(captured_queries), 1)
  330. self.assertIn(self.person_pk, captured_queries[0]['sql'])
  331. def test_nested(self):
  332. with CaptureQueriesContext(connection) as captured_queries:
  333. Person.objects.count()
  334. with CaptureQueriesContext(connection) as nested_captured_queries:
  335. Person.objects.count()
  336. self.assertEqual(1, len(nested_captured_queries))
  337. self.assertEqual(2, len(captured_queries))
  338. def test_failure(self):
  339. with self.assertRaises(TypeError):
  340. with CaptureQueriesContext(connection):
  341. raise TypeError
  342. def test_with_client(self):
  343. with CaptureQueriesContext(connection) as captured_queries:
  344. self.client.get("/test_utils/get_person/%s/" % self.person_pk)
  345. self.assertEqual(len(captured_queries), 1)
  346. self.assertIn(self.person_pk, captured_queries[0]['sql'])
  347. with CaptureQueriesContext(connection) as captured_queries:
  348. self.client.get("/test_utils/get_person/%s/" % self.person_pk)
  349. self.assertEqual(len(captured_queries), 1)
  350. self.assertIn(self.person_pk, captured_queries[0]['sql'])
  351. with CaptureQueriesContext(connection) as captured_queries:
  352. self.client.get("/test_utils/get_person/%s/" % self.person_pk)
  353. self.client.get("/test_utils/get_person/%s/" % self.person_pk)
  354. self.assertEqual(len(captured_queries), 2)
  355. self.assertIn(self.person_pk, captured_queries[0]['sql'])
  356. self.assertIn(self.person_pk, captured_queries[1]['sql'])
  357. @override_settings(ROOT_URLCONF='test_utils.urls')
  358. class AssertNumQueriesContextManagerTests(TestCase):
  359. def test_simple(self):
  360. with self.assertNumQueries(0):
  361. pass
  362. with self.assertNumQueries(1):
  363. Person.objects.count()
  364. with self.assertNumQueries(2):
  365. Person.objects.count()
  366. Person.objects.count()
  367. def test_failure(self):
  368. msg = (
  369. '1 != 2 : 1 queries executed, 2 expected\nCaptured queries were:\n'
  370. '1.'
  371. )
  372. with self.assertRaisesMessage(AssertionError, msg):
  373. with self.assertNumQueries(2):
  374. Person.objects.count()
  375. with self.assertRaises(TypeError):
  376. with self.assertNumQueries(4000):
  377. raise TypeError
  378. def test_with_client(self):
  379. person = Person.objects.create(name="test")
  380. with self.assertNumQueries(1):
  381. self.client.get("/test_utils/get_person/%s/" % person.pk)
  382. with self.assertNumQueries(1):
  383. self.client.get("/test_utils/get_person/%s/" % person.pk)
  384. with self.assertNumQueries(2):
  385. self.client.get("/test_utils/get_person/%s/" % person.pk)
  386. self.client.get("/test_utils/get_person/%s/" % person.pk)
  387. @override_settings(ROOT_URLCONF='test_utils.urls')
  388. class AssertTemplateUsedContextManagerTests(SimpleTestCase):
  389. def test_usage(self):
  390. with self.assertTemplateUsed('template_used/base.html'):
  391. render_to_string('template_used/base.html')
  392. with self.assertTemplateUsed(template_name='template_used/base.html'):
  393. render_to_string('template_used/base.html')
  394. with self.assertTemplateUsed('template_used/base.html'):
  395. render_to_string('template_used/include.html')
  396. with self.assertTemplateUsed('template_used/base.html'):
  397. render_to_string('template_used/extends.html')
  398. with self.assertTemplateUsed('template_used/base.html'):
  399. render_to_string('template_used/base.html')
  400. render_to_string('template_used/base.html')
  401. def test_nested_usage(self):
  402. with self.assertTemplateUsed('template_used/base.html'):
  403. with self.assertTemplateUsed('template_used/include.html'):
  404. render_to_string('template_used/include.html')
  405. with self.assertTemplateUsed('template_used/extends.html'):
  406. with self.assertTemplateUsed('template_used/base.html'):
  407. render_to_string('template_used/extends.html')
  408. with self.assertTemplateUsed('template_used/base.html'):
  409. with self.assertTemplateUsed('template_used/alternative.html'):
  410. render_to_string('template_used/alternative.html')
  411. render_to_string('template_used/base.html')
  412. with self.assertTemplateUsed('template_used/base.html'):
  413. render_to_string('template_used/extends.html')
  414. with self.assertTemplateNotUsed('template_used/base.html'):
  415. render_to_string('template_used/alternative.html')
  416. render_to_string('template_used/base.html')
  417. def test_not_used(self):
  418. with self.assertTemplateNotUsed('template_used/base.html'):
  419. pass
  420. with self.assertTemplateNotUsed('template_used/alternative.html'):
  421. pass
  422. def test_error_message(self):
  423. msg = 'No templates used to render the response'
  424. with self.assertRaisesMessage(AssertionError, msg):
  425. with self.assertTemplateUsed('template_used/base.html'):
  426. pass
  427. with self.assertRaisesMessage(AssertionError, msg):
  428. with self.assertTemplateUsed(template_name='template_used/base.html'):
  429. pass
  430. msg2 = (
  431. "Template 'template_used/base.html' was not a template used to render "
  432. "the response. Actual template(s) used: template_used/alternative.html"
  433. )
  434. with self.assertRaisesMessage(AssertionError, msg2):
  435. with self.assertTemplateUsed('template_used/base.html'):
  436. render_to_string('template_used/alternative.html')
  437. with self.assertRaisesMessage(AssertionError, 'No templates used to render the response'):
  438. response = self.client.get('/test_utils/no_template_used/')
  439. self.assertTemplateUsed(response, 'template_used/base.html')
  440. def test_msg_prefix(self):
  441. msg_prefix = 'Prefix'
  442. msg = f'{msg_prefix}: No templates used to render the response'
  443. with self.assertRaisesMessage(AssertionError, msg):
  444. with self.assertTemplateUsed('template_used/base.html', msg_prefix=msg_prefix):
  445. pass
  446. with self.assertRaisesMessage(AssertionError, msg):
  447. with self.assertTemplateUsed(
  448. template_name='template_used/base.html',
  449. msg_prefix=msg_prefix,
  450. ):
  451. pass
  452. msg = (
  453. f"{msg_prefix}: Template 'template_used/base.html' was not a "
  454. f"template used to render the response. Actual template(s) used: "
  455. f"template_used/alternative.html"
  456. )
  457. with self.assertRaisesMessage(AssertionError, msg):
  458. with self.assertTemplateUsed('template_used/base.html', msg_prefix=msg_prefix):
  459. render_to_string('template_used/alternative.html')
  460. def test_count(self):
  461. with self.assertTemplateUsed('template_used/base.html', count=2):
  462. render_to_string('template_used/base.html')
  463. render_to_string('template_used/base.html')
  464. msg = (
  465. "Template 'template_used/base.html' was expected to be rendered "
  466. "3 time(s) but was actually rendered 2 time(s)."
  467. )
  468. with self.assertRaisesMessage(AssertionError, msg):
  469. with self.assertTemplateUsed('template_used/base.html', count=3):
  470. render_to_string('template_used/base.html')
  471. render_to_string('template_used/base.html')
  472. def test_failure(self):
  473. msg = 'response and/or template_name argument must be provided'
  474. with self.assertRaisesMessage(TypeError, msg):
  475. with self.assertTemplateUsed():
  476. pass
  477. msg = 'No templates used to render the response'
  478. with self.assertRaisesMessage(AssertionError, msg):
  479. with self.assertTemplateUsed(''):
  480. pass
  481. with self.assertRaisesMessage(AssertionError, msg):
  482. with self.assertTemplateUsed(''):
  483. render_to_string('template_used/base.html')
  484. with self.assertRaisesMessage(AssertionError, msg):
  485. with self.assertTemplateUsed(template_name=''):
  486. pass
  487. msg = (
  488. "Template 'template_used/base.html' was not a template used to "
  489. "render the response. Actual template(s) used: "
  490. "template_used/alternative.html"
  491. )
  492. with self.assertRaisesMessage(AssertionError, msg):
  493. with self.assertTemplateUsed('template_used/base.html'):
  494. render_to_string('template_used/alternative.html')
  495. def test_assert_used_on_http_response(self):
  496. response = HttpResponse()
  497. msg = '%s() is only usable on responses fetched using the Django test Client.'
  498. with self.assertRaisesMessage(ValueError, msg % 'assertTemplateUsed'):
  499. self.assertTemplateUsed(response, 'template.html')
  500. with self.assertRaisesMessage(ValueError, msg % 'assertTemplateNotUsed'):
  501. self.assertTemplateNotUsed(response, 'template.html')
  502. class HTMLEqualTests(SimpleTestCase):
  503. def test_html_parser(self):
  504. element = parse_html('<div><p>Hello</p></div>')
  505. self.assertEqual(len(element.children), 1)
  506. self.assertEqual(element.children[0].name, 'p')
  507. self.assertEqual(element.children[0].children[0], 'Hello')
  508. parse_html('<p>')
  509. parse_html('<p attr>')
  510. dom = parse_html('<p>foo')
  511. self.assertEqual(len(dom.children), 1)
  512. self.assertEqual(dom.name, 'p')
  513. self.assertEqual(dom[0], 'foo')
  514. def test_parse_html_in_script(self):
  515. parse_html('<script>var a = "<p" + ">";</script>')
  516. parse_html('''
  517. <script>
  518. var js_sha_link='<p>***</p>';
  519. </script>
  520. ''')
  521. # script content will be parsed to text
  522. dom = parse_html('''
  523. <script><p>foo</p> '</scr'+'ipt>' <span>bar</span></script>
  524. ''')
  525. self.assertEqual(len(dom.children), 1)
  526. self.assertEqual(dom.children[0], "<p>foo</p> '</scr'+'ipt>' <span>bar</span>")
  527. def test_self_closing_tags(self):
  528. self_closing_tags = [
  529. 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link',
  530. 'meta', 'param', 'source', 'track', 'wbr',
  531. # Deprecated tags
  532. 'frame', 'spacer',
  533. ]
  534. for tag in self_closing_tags:
  535. with self.subTest(tag):
  536. dom = parse_html('<p>Hello <%s> world</p>' % tag)
  537. self.assertEqual(len(dom.children), 3)
  538. self.assertEqual(dom[0], 'Hello')
  539. self.assertEqual(dom[1].name, tag)
  540. self.assertEqual(dom[2], 'world')
  541. dom = parse_html('<p>Hello <%s /> world</p>' % tag)
  542. self.assertEqual(len(dom.children), 3)
  543. self.assertEqual(dom[0], 'Hello')
  544. self.assertEqual(dom[1].name, tag)
  545. self.assertEqual(dom[2], 'world')
  546. def test_simple_equal_html(self):
  547. self.assertHTMLEqual('', '')
  548. self.assertHTMLEqual('<p></p>', '<p></p>')
  549. self.assertHTMLEqual('<p></p>', ' <p> </p> ')
  550. self.assertHTMLEqual(
  551. '<div><p>Hello</p></div>',
  552. '<div><p>Hello</p></div>')
  553. self.assertHTMLEqual(
  554. '<div><p>Hello</p></div>',
  555. '<div> <p>Hello</p> </div>')
  556. self.assertHTMLEqual(
  557. '<div>\n<p>Hello</p></div>',
  558. '<div><p>Hello</p></div>\n')
  559. self.assertHTMLEqual(
  560. '<div><p>Hello\nWorld !</p></div>',
  561. '<div><p>Hello World\n!</p></div>')
  562. self.assertHTMLEqual(
  563. '<div><p>Hello\nWorld !</p></div>',
  564. '<div><p>Hello World\n!</p></div>')
  565. self.assertHTMLEqual(
  566. '<p>Hello World !</p>',
  567. '<p>Hello World\n\n!</p>')
  568. self.assertHTMLEqual('<p> </p>', '<p></p>')
  569. self.assertHTMLEqual('<p/>', '<p></p>')
  570. self.assertHTMLEqual('<p />', '<p></p>')
  571. self.assertHTMLEqual('<input checked>', '<input checked="checked">')
  572. self.assertHTMLEqual('<p>Hello', '<p> Hello')
  573. self.assertHTMLEqual('<p>Hello</p>World', '<p>Hello</p> World')
  574. def test_ignore_comments(self):
  575. self.assertHTMLEqual(
  576. '<div>Hello<!-- this is a comment --> World!</div>',
  577. '<div>Hello World!</div>')
  578. def test_unequal_html(self):
  579. self.assertHTMLNotEqual('<p>Hello</p>', '<p>Hello!</p>')
  580. self.assertHTMLNotEqual('<p>foo&#20;bar</p>', '<p>foo&nbsp;bar</p>')
  581. self.assertHTMLNotEqual('<p>foo bar</p>', '<p>foo &nbsp;bar</p>')
  582. self.assertHTMLNotEqual('<p>foo nbsp</p>', '<p>foo &nbsp;</p>')
  583. self.assertHTMLNotEqual('<p>foo #20</p>', '<p>foo &#20;</p>')
  584. self.assertHTMLNotEqual(
  585. '<p><span>Hello</span><span>World</span></p>',
  586. '<p><span>Hello</span>World</p>')
  587. self.assertHTMLNotEqual(
  588. '<p><span>Hello</span>World</p>',
  589. '<p><span>Hello</span><span>World</span></p>')
  590. def test_attributes(self):
  591. self.assertHTMLEqual(
  592. '<input type="text" id="id_name" />',
  593. '<input id="id_name" type="text" />')
  594. self.assertHTMLEqual(
  595. '''<input type='text' id="id_name" />''',
  596. '<input id="id_name" type="text" />')
  597. self.assertHTMLNotEqual(
  598. '<input type="text" id="id_name" />',
  599. '<input type="password" id="id_name" />')
  600. def test_class_attribute(self):
  601. pairs = [
  602. ('<p class="foo bar"></p>', '<p class="bar foo"></p>'),
  603. ('<p class=" foo bar "></p>', '<p class="bar foo"></p>'),
  604. ('<p class=" foo bar "></p>', '<p class="bar foo"></p>'),
  605. ('<p class="foo\tbar"></p>', '<p class="bar foo"></p>'),
  606. ('<p class="\tfoo\tbar\t"></p>', '<p class="bar foo"></p>'),
  607. ('<p class="\t\t\tfoo\t\t\tbar\t\t\t"></p>', '<p class="bar foo"></p>'),
  608. ('<p class="\t \nfoo \t\nbar\n\t "></p>', '<p class="bar foo"></p>'),
  609. ]
  610. for html1, html2 in pairs:
  611. with self.subTest(html1):
  612. self.assertHTMLEqual(html1, html2)
  613. def test_boolean_attribute(self):
  614. html1 = '<input checked>'
  615. html2 = '<input checked="">'
  616. html3 = '<input checked="checked">'
  617. self.assertHTMLEqual(html1, html2)
  618. self.assertHTMLEqual(html1, html3)
  619. self.assertHTMLEqual(html2, html3)
  620. self.assertHTMLNotEqual(html1, '<input checked="invalid">')
  621. self.assertEqual(str(parse_html(html1)), '<input checked>')
  622. self.assertEqual(str(parse_html(html2)), '<input checked>')
  623. self.assertEqual(str(parse_html(html3)), '<input checked>')
  624. def test_non_boolean_attibutes(self):
  625. html1 = '<input value>'
  626. html2 = '<input value="">'
  627. html3 = '<input value="value">'
  628. self.assertHTMLEqual(html1, html2)
  629. self.assertHTMLNotEqual(html1, html3)
  630. self.assertEqual(str(parse_html(html1)), '<input value="">')
  631. self.assertEqual(str(parse_html(html2)), '<input value="">')
  632. def test_normalize_refs(self):
  633. pairs = [
  634. ('&#39;', '&#x27;'),
  635. ('&#39;', "'"),
  636. ('&#x27;', '&#39;'),
  637. ('&#x27;', "'"),
  638. ("'", '&#39;'),
  639. ("'", '&#x27;'),
  640. ('&amp;', '&#38;'),
  641. ('&amp;', '&#x26;'),
  642. ('&amp;', '&'),
  643. ('&#38;', '&amp;'),
  644. ('&#38;', '&#x26;'),
  645. ('&#38;', '&'),
  646. ('&#x26;', '&amp;'),
  647. ('&#x26;', '&#38;'),
  648. ('&#x26;', '&'),
  649. ('&', '&amp;'),
  650. ('&', '&#38;'),
  651. ('&', '&#x26;'),
  652. ]
  653. for pair in pairs:
  654. with self.subTest(repr(pair)):
  655. self.assertHTMLEqual(*pair)
  656. def test_complex_examples(self):
  657. self.assertHTMLEqual(
  658. """<tr><th><label for="id_first_name">First name:</label></th>
  659. <td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>
  660. <tr><th><label for="id_last_name">Last name:</label></th>
  661. <td><input type="text" id="id_last_name" name="last_name" value="Lennon" /></td></tr>
  662. <tr><th><label for="id_birthday">Birthday:</label></th>
  663. <td><input type="text" value="1940-10-9" name="birthday" id="id_birthday" /></td></tr>""",
  664. """
  665. <tr><th>
  666. <label for="id_first_name">First name:</label></th><td>
  667. <input type="text" name="first_name" value="John" id="id_first_name" />
  668. </td></tr>
  669. <tr><th>
  670. <label for="id_last_name">Last name:</label></th><td>
  671. <input type="text" name="last_name" value="Lennon" id="id_last_name" />
  672. </td></tr>
  673. <tr><th>
  674. <label for="id_birthday">Birthday:</label></th><td>
  675. <input type="text" name="birthday" value="1940-10-9" id="id_birthday" />
  676. </td></tr>
  677. """)
  678. self.assertHTMLEqual(
  679. """<!DOCTYPE html>
  680. <html>
  681. <head>
  682. <link rel="stylesheet">
  683. <title>Document</title>
  684. <meta attribute="value">
  685. </head>
  686. <body>
  687. <p>
  688. This is a valid paragraph
  689. <div> this is a div AFTER the p</div>
  690. </body>
  691. </html>""", """
  692. <html>
  693. <head>
  694. <link rel="stylesheet">
  695. <title>Document</title>
  696. <meta attribute="value">
  697. </head>
  698. <body>
  699. <p> This is a valid paragraph
  700. <!-- browsers would close the p tag here -->
  701. <div> this is a div AFTER the p</div>
  702. </p> <!-- this is invalid HTML parsing, but it should make no
  703. difference in most cases -->
  704. </body>
  705. </html>""")
  706. def test_html_contain(self):
  707. # equal html contains each other
  708. dom1 = parse_html('<p>foo')
  709. dom2 = parse_html('<p>foo</p>')
  710. self.assertIn(dom1, dom2)
  711. self.assertIn(dom2, dom1)
  712. dom2 = parse_html('<div><p>foo</p></div>')
  713. self.assertIn(dom1, dom2)
  714. self.assertNotIn(dom2, dom1)
  715. self.assertNotIn('<p>foo</p>', dom2)
  716. self.assertIn('foo', dom2)
  717. # when a root element is used ...
  718. dom1 = parse_html('<p>foo</p><p>bar</p>')
  719. dom2 = parse_html('<p>foo</p><p>bar</p>')
  720. self.assertIn(dom1, dom2)
  721. dom1 = parse_html('<p>foo</p>')
  722. self.assertIn(dom1, dom2)
  723. dom1 = parse_html('<p>bar</p>')
  724. self.assertIn(dom1, dom2)
  725. dom1 = parse_html('<div><p>foo</p><p>bar</p></div>')
  726. self.assertIn(dom2, dom1)
  727. def test_count(self):
  728. # equal html contains each other one time
  729. dom1 = parse_html('<p>foo')
  730. dom2 = parse_html('<p>foo</p>')
  731. self.assertEqual(dom1.count(dom2), 1)
  732. self.assertEqual(dom2.count(dom1), 1)
  733. dom2 = parse_html('<p>foo</p><p>bar</p>')
  734. self.assertEqual(dom2.count(dom1), 1)
  735. dom2 = parse_html('<p>foo foo</p><p>foo</p>')
  736. self.assertEqual(dom2.count('foo'), 3)
  737. dom2 = parse_html('<p class="bar">foo</p>')
  738. self.assertEqual(dom2.count('bar'), 0)
  739. self.assertEqual(dom2.count('class'), 0)
  740. self.assertEqual(dom2.count('p'), 0)
  741. self.assertEqual(dom2.count('o'), 2)
  742. dom2 = parse_html('<p>foo</p><p>foo</p>')
  743. self.assertEqual(dom2.count(dom1), 2)
  744. dom2 = parse_html('<div><p>foo<input type=""></p><p>foo</p></div>')
  745. self.assertEqual(dom2.count(dom1), 1)
  746. dom2 = parse_html('<div><div><p>foo</p></div></div>')
  747. self.assertEqual(dom2.count(dom1), 1)
  748. dom2 = parse_html('<p>foo<p>foo</p></p>')
  749. self.assertEqual(dom2.count(dom1), 1)
  750. dom2 = parse_html('<p>foo<p>bar</p></p>')
  751. self.assertEqual(dom2.count(dom1), 0)
  752. # HTML with a root element contains the same HTML with no root element.
  753. dom1 = parse_html('<p>foo</p><p>bar</p>')
  754. dom2 = parse_html('<div><p>foo</p><p>bar</p></div>')
  755. self.assertEqual(dom2.count(dom1), 1)
  756. # Target of search is a sequence of child elements and appears more
  757. # than once.
  758. dom2 = parse_html('<div><p>foo</p><p>bar</p><p>foo</p><p>bar</p></div>')
  759. self.assertEqual(dom2.count(dom1), 2)
  760. # Searched HTML has additional children.
  761. dom1 = parse_html('<a/><b/>')
  762. dom2 = parse_html('<a/><b/><c/>')
  763. self.assertEqual(dom2.count(dom1), 1)
  764. # No match found in children.
  765. dom1 = parse_html('<b/><a/>')
  766. self.assertEqual(dom2.count(dom1), 0)
  767. # Target of search found among children and grandchildren.
  768. dom1 = parse_html('<b/><b/>')
  769. dom2 = parse_html('<a><b/><b/></a><b/><b/>')
  770. self.assertEqual(dom2.count(dom1), 2)
  771. def test_root_element_escaped_html(self):
  772. html = '&lt;br&gt;'
  773. parsed = parse_html(html)
  774. self.assertEqual(str(parsed), html)
  775. def test_parsing_errors(self):
  776. with self.assertRaises(AssertionError):
  777. self.assertHTMLEqual('<p>', '')
  778. with self.assertRaises(AssertionError):
  779. self.assertHTMLEqual('', '<p>')
  780. error_msg = (
  781. "First argument is not valid HTML:\n"
  782. "('Unexpected end tag `div` (Line 1, Column 6)', (1, 6))"
  783. )
  784. with self.assertRaisesMessage(AssertionError, error_msg):
  785. self.assertHTMLEqual('< div></ div>', '<div></div>')
  786. with self.assertRaises(HTMLParseError):
  787. parse_html('</p>')
  788. def test_escaped_html_errors(self):
  789. msg = (
  790. '<p>\n<foo>\n</p>'
  791. ' != '
  792. '<p>\n&lt;foo&gt;\n</p>\n'
  793. )
  794. with self.assertRaisesMessage(AssertionError, msg):
  795. self.assertHTMLEqual('<p><foo></p>', '<p>&lt;foo&gt;</p>')
  796. with self.assertRaisesMessage(AssertionError, msg):
  797. self.assertHTMLEqual('<p><foo></p>', '<p>&#60;foo&#62;</p>')
  798. def test_contains_html(self):
  799. response = HttpResponse('''<body>
  800. This is a form: <form method="get">
  801. <input type="text" name="Hello" />
  802. </form></body>''')
  803. self.assertNotContains(response, "<input name='Hello' type='text'>")
  804. self.assertContains(response, '<form method="get">')
  805. self.assertContains(response, "<input name='Hello' type='text'>", html=True)
  806. self.assertNotContains(response, '<form method="get">', html=True)
  807. invalid_response = HttpResponse('''<body <bad>>''')
  808. with self.assertRaises(AssertionError):
  809. self.assertContains(invalid_response, '<p></p>')
  810. with self.assertRaises(AssertionError):
  811. self.assertContains(response, '<p "whats" that>')
  812. def test_unicode_handling(self):
  813. response = HttpResponse('<p class="help">Some help text for the title (with Unicode ŠĐĆŽćžšđ)</p>')
  814. self.assertContains(
  815. response,
  816. '<p class="help">Some help text for the title (with Unicode ŠĐĆŽćžšđ)</p>',
  817. html=True
  818. )
  819. class JSONEqualTests(SimpleTestCase):
  820. def test_simple_equal(self):
  821. json1 = '{"attr1": "foo", "attr2":"baz"}'
  822. json2 = '{"attr1": "foo", "attr2":"baz"}'
  823. self.assertJSONEqual(json1, json2)
  824. def test_simple_equal_unordered(self):
  825. json1 = '{"attr1": "foo", "attr2":"baz"}'
  826. json2 = '{"attr2":"baz", "attr1": "foo"}'
  827. self.assertJSONEqual(json1, json2)
  828. def test_simple_equal_raise(self):
  829. json1 = '{"attr1": "foo", "attr2":"baz"}'
  830. json2 = '{"attr2":"baz"}'
  831. with self.assertRaises(AssertionError):
  832. self.assertJSONEqual(json1, json2)
  833. def test_equal_parsing_errors(self):
  834. invalid_json = '{"attr1": "foo, "attr2":"baz"}'
  835. valid_json = '{"attr1": "foo", "attr2":"baz"}'
  836. with self.assertRaises(AssertionError):
  837. self.assertJSONEqual(invalid_json, valid_json)
  838. with self.assertRaises(AssertionError):
  839. self.assertJSONEqual(valid_json, invalid_json)
  840. def test_simple_not_equal(self):
  841. json1 = '{"attr1": "foo", "attr2":"baz"}'
  842. json2 = '{"attr2":"baz"}'
  843. self.assertJSONNotEqual(json1, json2)
  844. def test_simple_not_equal_raise(self):
  845. json1 = '{"attr1": "foo", "attr2":"baz"}'
  846. json2 = '{"attr1": "foo", "attr2":"baz"}'
  847. with self.assertRaises(AssertionError):
  848. self.assertJSONNotEqual(json1, json2)
  849. def test_not_equal_parsing_errors(self):
  850. invalid_json = '{"attr1": "foo, "attr2":"baz"}'
  851. valid_json = '{"attr1": "foo", "attr2":"baz"}'
  852. with self.assertRaises(AssertionError):
  853. self.assertJSONNotEqual(invalid_json, valid_json)
  854. with self.assertRaises(AssertionError):
  855. self.assertJSONNotEqual(valid_json, invalid_json)
  856. class XMLEqualTests(SimpleTestCase):
  857. def test_simple_equal(self):
  858. xml1 = "<elem attr1='a' attr2='b' />"
  859. xml2 = "<elem attr1='a' attr2='b' />"
  860. self.assertXMLEqual(xml1, xml2)
  861. def test_simple_equal_unordered(self):
  862. xml1 = "<elem attr1='a' attr2='b' />"
  863. xml2 = "<elem attr2='b' attr1='a' />"
  864. self.assertXMLEqual(xml1, xml2)
  865. def test_simple_equal_raise(self):
  866. xml1 = "<elem attr1='a' />"
  867. xml2 = "<elem attr2='b' attr1='a' />"
  868. with self.assertRaises(AssertionError):
  869. self.assertXMLEqual(xml1, xml2)
  870. def test_simple_equal_raises_message(self):
  871. xml1 = "<elem attr1='a' />"
  872. xml2 = "<elem attr2='b' attr1='a' />"
  873. msg = '''{xml1} != {xml2}
  874. - <elem attr1='a' />
  875. + <elem attr2='b' attr1='a' />
  876. ? ++++++++++
  877. '''.format(xml1=repr(xml1), xml2=repr(xml2))
  878. with self.assertRaisesMessage(AssertionError, msg):
  879. self.assertXMLEqual(xml1, xml2)
  880. def test_simple_not_equal(self):
  881. xml1 = "<elem attr1='a' attr2='c' />"
  882. xml2 = "<elem attr1='a' attr2='b' />"
  883. self.assertXMLNotEqual(xml1, xml2)
  884. def test_simple_not_equal_raise(self):
  885. xml1 = "<elem attr1='a' attr2='b' />"
  886. xml2 = "<elem attr2='b' attr1='a' />"
  887. with self.assertRaises(AssertionError):
  888. self.assertXMLNotEqual(xml1, xml2)
  889. def test_parsing_errors(self):
  890. xml_unvalid = "<elem attr1='a attr2='b' />"
  891. xml2 = "<elem attr2='b' attr1='a' />"
  892. with self.assertRaises(AssertionError):
  893. self.assertXMLNotEqual(xml_unvalid, xml2)
  894. def test_comment_root(self):
  895. xml1 = "<?xml version='1.0'?><!-- comment1 --><elem attr1='a' attr2='b' />"
  896. xml2 = "<?xml version='1.0'?><!-- comment2 --><elem attr2='b' attr1='a' />"
  897. self.assertXMLEqual(xml1, xml2)
  898. def test_simple_equal_with_leading_or_trailing_whitespace(self):
  899. xml1 = "<elem>foo</elem> \t\n"
  900. xml2 = " \t\n<elem>foo</elem>"
  901. self.assertXMLEqual(xml1, xml2)
  902. def test_simple_not_equal_with_whitespace_in_the_middle(self):
  903. xml1 = "<elem>foo</elem><elem>bar</elem>"
  904. xml2 = "<elem>foo</elem> <elem>bar</elem>"
  905. self.assertXMLNotEqual(xml1, xml2)
  906. def test_doctype_root(self):
  907. xml1 = '<?xml version="1.0"?><!DOCTYPE root SYSTEM "example1.dtd"><root />'
  908. xml2 = '<?xml version="1.0"?><!DOCTYPE root SYSTEM "example2.dtd"><root />'
  909. self.assertXMLEqual(xml1, xml2)
  910. def test_processing_instruction(self):
  911. xml1 = (
  912. '<?xml version="1.0"?>'
  913. '<?xml-model href="http://www.example1.com"?><root />'
  914. )
  915. xml2 = (
  916. '<?xml version="1.0"?>'
  917. '<?xml-model href="http://www.example2.com"?><root />'
  918. )
  919. self.assertXMLEqual(xml1, xml2)
  920. self.assertXMLEqual(
  921. '<?xml-stylesheet href="style1.xslt" type="text/xsl"?><root />',
  922. '<?xml-stylesheet href="style2.xslt" type="text/xsl"?><root />',
  923. )
  924. class SkippingExtraTests(TestCase):
  925. fixtures = ['should_not_be_loaded.json']
  926. # HACK: This depends on internals of our TestCase subclasses
  927. def __call__(self, result=None):
  928. # Detect fixture loading by counting SQL queries, should be zero
  929. with self.assertNumQueries(0):
  930. super().__call__(result)
  931. @unittest.skip("Fixture loading should not be performed for skipped tests.")
  932. def test_fixtures_are_skipped(self):
  933. pass
  934. class AssertRaisesMsgTest(SimpleTestCase):
  935. def test_assert_raises_message(self):
  936. msg = "'Expected message' not found in 'Unexpected message'"
  937. # context manager form of assertRaisesMessage()
  938. with self.assertRaisesMessage(AssertionError, msg):
  939. with self.assertRaisesMessage(ValueError, "Expected message"):
  940. raise ValueError("Unexpected message")
  941. # callable form
  942. def func():
  943. raise ValueError("Unexpected message")
  944. with self.assertRaisesMessage(AssertionError, msg):
  945. self.assertRaisesMessage(ValueError, "Expected message", func)
  946. def test_special_re_chars(self):
  947. """assertRaisesMessage shouldn't interpret RE special chars."""
  948. def func1():
  949. raise ValueError("[.*x+]y?")
  950. with self.assertRaisesMessage(ValueError, "[.*x+]y?"):
  951. func1()
  952. class AssertWarnsMessageTests(SimpleTestCase):
  953. def test_context_manager(self):
  954. with self.assertWarnsMessage(UserWarning, 'Expected message'):
  955. warnings.warn('Expected message', UserWarning)
  956. def test_context_manager_failure(self):
  957. msg = "Expected message' not found in 'Unexpected message'"
  958. with self.assertRaisesMessage(AssertionError, msg):
  959. with self.assertWarnsMessage(UserWarning, 'Expected message'):
  960. warnings.warn('Unexpected message', UserWarning)
  961. def test_callable(self):
  962. def func():
  963. warnings.warn('Expected message', UserWarning)
  964. self.assertWarnsMessage(UserWarning, 'Expected message', func)
  965. def test_special_re_chars(self):
  966. def func1():
  967. warnings.warn('[.*x+]y?', UserWarning)
  968. with self.assertWarnsMessage(UserWarning, '[.*x+]y?'):
  969. func1()
  970. # TODO: Remove when dropping support for PY39.
  971. class AssertNoLogsTest(SimpleTestCase):
  972. @classmethod
  973. def setUpClass(cls):
  974. super().setUpClass()
  975. logging.config.dictConfig(DEFAULT_LOGGING)
  976. cls.addClassCleanup(logging.config.dictConfig, settings.LOGGING)
  977. def setUp(self):
  978. self.logger = logging.getLogger('django')
  979. @override_settings(DEBUG=True)
  980. def test_fails_when_log_emitted(self):
  981. msg = "Unexpected logs found: ['INFO:django:FAIL!']"
  982. with self.assertRaisesMessage(AssertionError, msg):
  983. with self.assertNoLogs('django', 'INFO'):
  984. self.logger.info('FAIL!')
  985. @override_settings(DEBUG=True)
  986. def test_text_level(self):
  987. with self.assertNoLogs('django', 'INFO'):
  988. self.logger.debug('DEBUG logs are ignored.')
  989. @override_settings(DEBUG=True)
  990. def test_int_level(self):
  991. with self.assertNoLogs('django', logging.INFO):
  992. self.logger.debug('DEBUG logs are ignored.')
  993. @override_settings(DEBUG=True)
  994. def test_default_level(self):
  995. with self.assertNoLogs('django'):
  996. self.logger.debug('DEBUG logs are ignored.')
  997. @override_settings(DEBUG=True)
  998. def test_does_not_hide_other_failures(self):
  999. msg = '1 != 2'
  1000. with self.assertRaisesMessage(AssertionError, msg):
  1001. with self.assertNoLogs('django'):
  1002. self.assertEqual(1, 2)
  1003. class AssertFieldOutputTests(SimpleTestCase):
  1004. def test_assert_field_output(self):
  1005. error_invalid = ['Enter a valid email address.']
  1006. self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid})
  1007. with self.assertRaises(AssertionError):
  1008. self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid + ['Another error']})
  1009. with self.assertRaises(AssertionError):
  1010. self.assertFieldOutput(EmailField, {'a@a.com': 'Wrong output'}, {'aaa': error_invalid})
  1011. with self.assertRaises(AssertionError):
  1012. self.assertFieldOutput(
  1013. EmailField, {'a@a.com': 'a@a.com'}, {'aaa': ['Come on, gimme some well formatted data, dude.']}
  1014. )
  1015. def test_custom_required_message(self):
  1016. class MyCustomField(IntegerField):
  1017. default_error_messages = {
  1018. 'required': 'This is really required.',
  1019. }
  1020. self.assertFieldOutput(MyCustomField, {}, {}, empty_value=None)
  1021. @override_settings(ROOT_URLCONF='test_utils.urls')
  1022. class AssertURLEqualTests(SimpleTestCase):
  1023. def test_equal(self):
  1024. valid_tests = (
  1025. ('http://example.com/?', 'http://example.com/'),
  1026. ('http://example.com/?x=1&', 'http://example.com/?x=1'),
  1027. ('http://example.com/?x=1&y=2', 'http://example.com/?y=2&x=1'),
  1028. ('http://example.com/?x=1&y=2', 'http://example.com/?y=2&x=1'),
  1029. ('http://example.com/?x=1&y=2&a=1&a=2', 'http://example.com/?a=1&a=2&y=2&x=1'),
  1030. ('/path/to/?x=1&y=2&z=3', '/path/to/?z=3&y=2&x=1'),
  1031. ('?x=1&y=2&z=3', '?z=3&y=2&x=1'),
  1032. ('/test_utils/no_template_used/', reverse_lazy('no_template_used')),
  1033. )
  1034. for url1, url2 in valid_tests:
  1035. with self.subTest(url=url1):
  1036. self.assertURLEqual(url1, url2)
  1037. def test_not_equal(self):
  1038. invalid_tests = (
  1039. # Protocol must be the same.
  1040. ('http://example.com/', 'https://example.com/'),
  1041. ('http://example.com/?x=1&x=2', 'https://example.com/?x=2&x=1'),
  1042. ('http://example.com/?x=1&y=bar&x=2', 'https://example.com/?y=bar&x=2&x=1'),
  1043. # Parameters of the same name must be in the same order.
  1044. ('/path/to?a=1&a=2', '/path/to/?a=2&a=1')
  1045. )
  1046. for url1, url2 in invalid_tests:
  1047. with self.subTest(url=url1), self.assertRaises(AssertionError):
  1048. self.assertURLEqual(url1, url2)
  1049. def test_message(self):
  1050. msg = (
  1051. "Expected 'http://example.com/?x=1&x=2' to equal "
  1052. "'https://example.com/?x=2&x=1'"
  1053. )
  1054. with self.assertRaisesMessage(AssertionError, msg):
  1055. self.assertURLEqual('http://example.com/?x=1&x=2', 'https://example.com/?x=2&x=1')
  1056. def test_msg_prefix(self):
  1057. msg = (
  1058. "Prefix: Expected 'http://example.com/?x=1&x=2' to equal "
  1059. "'https://example.com/?x=2&x=1'"
  1060. )
  1061. with self.assertRaisesMessage(AssertionError, msg):
  1062. self.assertURLEqual(
  1063. 'http://example.com/?x=1&x=2', 'https://example.com/?x=2&x=1',
  1064. msg_prefix='Prefix: ',
  1065. )
  1066. class TestForm(Form):
  1067. field = CharField()
  1068. def clean_field(self):
  1069. value = self.cleaned_data.get('field', '')
  1070. if value == 'invalid':
  1071. raise ValidationError('invalid value')
  1072. return value
  1073. def clean(self):
  1074. if self.cleaned_data.get('field') == 'invalid_non_field':
  1075. raise ValidationError('non-field error')
  1076. return self.cleaned_data
  1077. @classmethod
  1078. def _get_cleaned_form(cls, field_value):
  1079. form = cls({'field': field_value})
  1080. form.full_clean()
  1081. return form
  1082. @classmethod
  1083. def valid(cls):
  1084. return cls._get_cleaned_form('valid')
  1085. @classmethod
  1086. def invalid(cls, nonfield=False):
  1087. return cls._get_cleaned_form('invalid_non_field' if nonfield else 'invalid')
  1088. class TestFormset(formset_factory(TestForm)):
  1089. @classmethod
  1090. def _get_cleaned_formset(cls, field_value):
  1091. formset = cls({
  1092. 'form-TOTAL_FORMS': '1',
  1093. 'form-INITIAL_FORMS': '0',
  1094. 'form-0-field': field_value,
  1095. })
  1096. formset.full_clean()
  1097. return formset
  1098. @classmethod
  1099. def valid(cls):
  1100. return cls._get_cleaned_formset('valid')
  1101. @classmethod
  1102. def invalid(cls, nonfield=False, nonform=False):
  1103. if nonform:
  1104. formset = cls({}, error_messages={'missing_management_form': 'error'})
  1105. formset.full_clean()
  1106. return formset
  1107. return cls._get_cleaned_formset('invalid_non_field' if nonfield else 'invalid')
  1108. class AssertFormErrorTests(SimpleTestCase):
  1109. def test_non_client_response(self):
  1110. msg = (
  1111. 'assertFormError() is only usable on responses fetched using the '
  1112. 'Django test Client.'
  1113. )
  1114. response = HttpResponse()
  1115. with self.assertRaisesMessage(ValueError, msg):
  1116. self.assertFormError(response, 'formset', 0, 'field', 'invalid value')
  1117. def test_response_with_no_context(self):
  1118. msg = 'Response did not use any contexts to render the response'
  1119. response = mock.Mock(context=[])
  1120. with self.assertRaisesMessage(AssertionError, msg):
  1121. self.assertFormError(response, 'form', 'field', 'invalid value')
  1122. msg_prefix = 'Custom prefix'
  1123. with self.assertRaisesMessage(AssertionError, f'{msg_prefix}: {msg}'):
  1124. self.assertFormError(
  1125. response,
  1126. 'form',
  1127. 'field',
  1128. 'invalid value',
  1129. msg_prefix=msg_prefix,
  1130. )
  1131. def test_form_not_in_context(self):
  1132. msg = "The form 'form' was not used to render the response"
  1133. response = mock.Mock(context=[{}])
  1134. with self.assertRaisesMessage(AssertionError, msg):
  1135. self.assertFormError(response, 'form', 'field', 'invalid value')
  1136. def test_field_not_in_form(self):
  1137. msg = "The form 'form' in context 0 does not contain the field 'other_field'"
  1138. response = mock.Mock(context=[{'form': TestForm.invalid()}])
  1139. with self.assertRaisesMessage(AssertionError, msg):
  1140. self.assertFormError(response, 'form', 'other_field', 'invalid value')
  1141. def test_field_not_in_form_multicontext(self):
  1142. msg = "The form 'form' in context 1 does not contain the field 'other_field'"
  1143. response = mock.Mock(context=[{}, {'form': TestForm.invalid()}])
  1144. with self.assertRaisesMessage(AssertionError, msg):
  1145. self.assertFormError(response, 'form', 'other_field', 'invalid value')
  1146. def test_field_with_no_errors(self):
  1147. msg = "The field 'field' on form 'form' in context 0 contains no errors"
  1148. response = mock.Mock(context=[{'form': TestForm.valid()}])
  1149. with self.assertRaisesMessage(AssertionError, msg):
  1150. self.assertFormError(response, 'form', 'field', 'invalid value')
  1151. def test_field_with_no_errors_multicontext(self):
  1152. msg = "The field 'field' on form 'form' in context 1 contains no errors"
  1153. response = mock.Mock(context=[{}, {'form': TestForm.valid()}])
  1154. with self.assertRaisesMessage(AssertionError, msg):
  1155. self.assertFormError(response, 'form', 'field', 'invalid value')
  1156. def test_field_with_different_error(self):
  1157. msg = (
  1158. "The field 'field' on form 'form' in context 0 does not contain "
  1159. "the error 'other error' (actual errors: ['invalid value'])"
  1160. )
  1161. response = mock.Mock(context=[{'form': TestForm.invalid()}])
  1162. with self.assertRaisesMessage(AssertionError, msg):
  1163. self.assertFormError(response, 'form', 'field', 'other error')
  1164. def test_field_with_different_error_multicontext(self):
  1165. msg = (
  1166. "The field 'field' on form 'form' in context 1 does not contain "
  1167. "the error 'other error' (actual errors: ['invalid value'])"
  1168. )
  1169. response = mock.Mock(context=[{}, {'form': TestForm.invalid()}])
  1170. with self.assertRaisesMessage(AssertionError, msg):
  1171. self.assertFormError(response, 'form', 'field', 'other error')
  1172. def test_basic_positive_assertion(self):
  1173. response = mock.Mock(context=[{'form': TestForm.invalid()}])
  1174. self.assertFormError(response, 'form', 'field', 'invalid value')
  1175. def test_basic_positive_assertion_multicontext(self):
  1176. response = mock.Mock(context=[{}, {'form': TestForm.invalid()}])
  1177. self.assertFormError(response, 'form', 'field', 'invalid value')
  1178. def test_empty_errors_unbound_form(self):
  1179. response = mock.Mock(context=[{'form': TestForm()}])
  1180. self.assertFormError(response, 'form', 'field', [])
  1181. def test_empty_errors_valid_form(self):
  1182. response = mock.Mock(context=[{'form': TestForm.valid()}])
  1183. self.assertFormError(response, 'form', 'field', [])
  1184. def test_empty_errors_invalid_form(self):
  1185. response = mock.Mock(context=[{'form': TestForm.invalid()}])
  1186. self.assertFormError(response, 'form', 'field', [])
  1187. def test_non_field_errors(self):
  1188. response = mock.Mock(context=[{'form': TestForm.invalid(nonfield=True)}])
  1189. self.assertFormError(response, 'form', None, 'non-field error')
  1190. @ignore_warnings(category=RemovedInDjango50Warning)
  1191. def test_errors_none(self):
  1192. response = mock.Mock(context=[{'form': TestForm.invalid()}])
  1193. self.assertFormError(response, 'form', 'field', None)
  1194. def test_errors_none_warning(self):
  1195. response = mock.Mock(context=[{'form': TestForm.invalid()}])
  1196. msg = (
  1197. 'Passing errors=None to assertFormError() is deprecated, use '
  1198. 'errors=[] instead.'
  1199. )
  1200. with self.assertWarnsMessage(RemovedInDjango50Warning, msg):
  1201. self.assertFormError(response, 'form', 'value', None)
  1202. class AssertFormsetErrorTests(SimpleTestCase):
  1203. def _get_formset_data(self, field_value):
  1204. return {
  1205. 'form-TOTAL_FORMS': '1',
  1206. 'form-INITIAL_FORMS': '0',
  1207. 'form-0-field': field_value,
  1208. }
  1209. def test_non_client_response(self):
  1210. msg = (
  1211. 'assertFormsetError() is only usable on responses fetched using '
  1212. 'the Django test Client.'
  1213. )
  1214. response = HttpResponse()
  1215. with self.assertRaisesMessage(ValueError, msg):
  1216. self.assertFormsetError(response, 'formset', 0, 'field', 'invalid value')
  1217. def test_response_with_no_context(self):
  1218. msg = 'Response did not use any contexts to render the response'
  1219. response = mock.Mock(context=[])
  1220. with self.assertRaisesMessage(AssertionError, msg):
  1221. self.assertFormsetError(response, 'formset', 0, 'field', 'invalid value')
  1222. def test_formset_not_in_context(self):
  1223. msg = "The formset 'formset' was not used to render the response"
  1224. response = mock.Mock(context=[{}])
  1225. with self.assertRaisesMessage(AssertionError, msg):
  1226. self.assertFormsetError(response, 'formset', 0, 'field', 'invalid value')
  1227. def test_field_not_in_form(self):
  1228. msg = (
  1229. "The formset 'formset', form 0 in context 0 does not contain the "
  1230. "field 'other_field'"
  1231. )
  1232. response = mock.Mock(context=[{'formset': TestFormset.invalid()}])
  1233. with self.assertRaisesMessage(AssertionError, msg):
  1234. self.assertFormsetError(
  1235. response,
  1236. 'formset',
  1237. 0,
  1238. 'other_field',
  1239. 'invalid value',
  1240. )
  1241. def test_field_not_in_form_multicontext(self):
  1242. msg = (
  1243. "The formset 'formset', form 0 in context 1 does not contain the "
  1244. "field 'other_field'"
  1245. )
  1246. response = mock.Mock(context=[{}, {'formset': TestFormset.invalid()}])
  1247. with self.assertRaisesMessage(AssertionError, msg):
  1248. self.assertFormsetError(
  1249. response,
  1250. 'formset',
  1251. 0,
  1252. 'other_field',
  1253. 'invalid value',
  1254. )
  1255. def test_field_with_no_errors(self):
  1256. msg = (
  1257. "The field 'field' on formset 'formset', form 0 in context 0 "
  1258. "contains no errors"
  1259. )
  1260. response = mock.Mock(context=[{'formset': TestFormset.valid()}])
  1261. with self.assertRaisesMessage(AssertionError, msg):
  1262. self.assertFormsetError(response, 'formset', 0, 'field', 'invalid value')
  1263. def test_field_with_no_errors_multicontext(self):
  1264. msg = (
  1265. "The field 'field' on formset 'formset', form 0 in context 1 "
  1266. "contains no errors"
  1267. )
  1268. response = mock.Mock(context=[{}, {'formset': TestFormset.valid()}])
  1269. with self.assertRaisesMessage(AssertionError, msg):
  1270. self.assertFormsetError(response, 'formset', 0, 'field', 'invalid value')
  1271. def test_field_with_different_error(self):
  1272. msg = (
  1273. "The field 'field' on formset 'formset', form 0 in context 0 does"
  1274. " not contain the error 'other error' (actual errors: ['invalid "
  1275. "value'])"
  1276. )
  1277. response = mock.Mock(context=[{'formset': TestFormset.invalid()}])
  1278. with self.assertRaisesMessage(AssertionError, msg):
  1279. self.assertFormsetError(response, 'formset', 0, 'field', 'other error')
  1280. def test_field_with_different_error_multicontext(self):
  1281. msg = (
  1282. "The field 'field' on formset 'formset', form 0 in context 1 does"
  1283. " not contain the error 'other error' (actual errors: ['invalid "
  1284. "value'])"
  1285. )
  1286. response = mock.Mock(context=[{}, {'formset': TestFormset.invalid()}])
  1287. with self.assertRaisesMessage(AssertionError, msg):
  1288. self.assertFormsetError(response, 'formset', 0, 'field', 'other error')
  1289. def test_basic_positive_assertion(self):
  1290. response = mock.Mock(context=[{'formset': TestFormset.invalid()}])
  1291. self.assertFormsetError(response, 'formset', 0, 'field', 'invalid value')
  1292. def test_basic_positive_assertion_multicontext(self):
  1293. response = mock.Mock(context=[{}, {'formset': TestFormset.invalid()}])
  1294. self.assertFormsetError(response, 'formset', 0, 'field', 'invalid value')
  1295. def test_empty_errors_unbound_formset(self):
  1296. response = mock.Mock(context=[{'formset': TestFormset()}])
  1297. self.assertFormsetError(response, 'formset', 0, 'field', [])
  1298. def test_empty_errors_valid_formset(self):
  1299. response = mock.Mock(context=[{}, {'formset': TestFormset.valid()}])
  1300. self.assertFormsetError(response, 'formset', 0, 'field', [])
  1301. def test_empty_errors_invalid_formset(self):
  1302. response = mock.Mock(context=[{}, {'formset': TestFormset.invalid()}])
  1303. self.assertFormsetError(response, 'formset', 0, 'field', [])
  1304. def test_non_field_errors(self):
  1305. response = mock.Mock(context=[
  1306. {},
  1307. {'formset': TestFormset.invalid(nonfield=True)},
  1308. ])
  1309. self.assertFormsetError(response, 'formset', 0, None, 'non-field error')
  1310. def test_non_form_errors(self):
  1311. response = mock.Mock(context=[
  1312. {},
  1313. {'formset': TestFormset.invalid(nonform=True)},
  1314. ])
  1315. self.assertFormsetError(response, 'formset', None, None, 'error')
  1316. def test_formset_named_form(self):
  1317. formset = TestFormset.invalid()
  1318. # The mocked context emulates the template-based rendering of the
  1319. # formset.
  1320. response = mock.Mock(context=[
  1321. {'form': formset},
  1322. {'form': formset.management_form},
  1323. ])
  1324. self.assertFormsetError(response, 'form', 0, 'field', 'invalid value')
  1325. @ignore_warnings(category=RemovedInDjango50Warning)
  1326. def test_errors_none(self):
  1327. response = mock.Mock(context=[{'formset': TestFormset.invalid()}])
  1328. self.assertFormsetError(response, 'formset', 0, 'field', None)
  1329. def test_errors_none_warning(self):
  1330. response = mock.Mock(context=[{'formset': TestFormset.invalid()}])
  1331. msg = (
  1332. 'Passing errors=None to assertFormsetError() is deprecated, use '
  1333. 'errors=[] instead.'
  1334. )
  1335. with self.assertWarnsMessage(RemovedInDjango50Warning, msg):
  1336. self.assertFormsetError(response, 'formset', 0, 'field', None)
  1337. class FirstUrls:
  1338. urlpatterns = [path('first/', empty_response, name='first')]
  1339. class SecondUrls:
  1340. urlpatterns = [path('second/', empty_response, name='second')]
  1341. class SetupTestEnvironmentTests(SimpleTestCase):
  1342. def test_setup_test_environment_calling_more_than_once(self):
  1343. with self.assertRaisesMessage(RuntimeError, "setup_test_environment() was already called"):
  1344. setup_test_environment()
  1345. def test_allowed_hosts(self):
  1346. for type_ in (list, tuple):
  1347. with self.subTest(type_=type_):
  1348. allowed_hosts = type_('*')
  1349. with mock.patch('django.test.utils._TestState') as x:
  1350. del x.saved_data
  1351. with self.settings(ALLOWED_HOSTS=allowed_hosts):
  1352. setup_test_environment()
  1353. self.assertEqual(settings.ALLOWED_HOSTS, ['*', 'testserver'])
  1354. class OverrideSettingsTests(SimpleTestCase):
  1355. # #21518 -- If neither override_settings nor a setting_changed receiver
  1356. # clears the URL cache between tests, then one of test_first or
  1357. # test_second will fail.
  1358. @override_settings(ROOT_URLCONF=FirstUrls)
  1359. def test_urlconf_first(self):
  1360. reverse('first')
  1361. @override_settings(ROOT_URLCONF=SecondUrls)
  1362. def test_urlconf_second(self):
  1363. reverse('second')
  1364. def test_urlconf_cache(self):
  1365. with self.assertRaises(NoReverseMatch):
  1366. reverse('first')
  1367. with self.assertRaises(NoReverseMatch):
  1368. reverse('second')
  1369. with override_settings(ROOT_URLCONF=FirstUrls):
  1370. self.client.get(reverse('first'))
  1371. with self.assertRaises(NoReverseMatch):
  1372. reverse('second')
  1373. with override_settings(ROOT_URLCONF=SecondUrls):
  1374. with self.assertRaises(NoReverseMatch):
  1375. reverse('first')
  1376. self.client.get(reverse('second'))
  1377. self.client.get(reverse('first'))
  1378. with self.assertRaises(NoReverseMatch):
  1379. reverse('second')
  1380. with self.assertRaises(NoReverseMatch):
  1381. reverse('first')
  1382. with self.assertRaises(NoReverseMatch):
  1383. reverse('second')
  1384. def test_override_media_root(self):
  1385. """
  1386. Overriding the MEDIA_ROOT setting should be reflected in the
  1387. base_location attribute of django.core.files.storage.default_storage.
  1388. """
  1389. self.assertEqual(default_storage.base_location, '')
  1390. with self.settings(MEDIA_ROOT='test_value'):
  1391. self.assertEqual(default_storage.base_location, 'test_value')
  1392. def test_override_media_url(self):
  1393. """
  1394. Overriding the MEDIA_URL setting should be reflected in the
  1395. base_url attribute of django.core.files.storage.default_storage.
  1396. """
  1397. self.assertEqual(default_storage.base_location, '')
  1398. with self.settings(MEDIA_URL='/test_value/'):
  1399. self.assertEqual(default_storage.base_url, '/test_value/')
  1400. def test_override_file_upload_permissions(self):
  1401. """
  1402. Overriding the FILE_UPLOAD_PERMISSIONS setting should be reflected in
  1403. the file_permissions_mode attribute of
  1404. django.core.files.storage.default_storage.
  1405. """
  1406. self.assertEqual(default_storage.file_permissions_mode, 0o644)
  1407. with self.settings(FILE_UPLOAD_PERMISSIONS=0o777):
  1408. self.assertEqual(default_storage.file_permissions_mode, 0o777)
  1409. def test_override_file_upload_directory_permissions(self):
  1410. """
  1411. Overriding the FILE_UPLOAD_DIRECTORY_PERMISSIONS setting should be
  1412. reflected in the directory_permissions_mode attribute of
  1413. django.core.files.storage.default_storage.
  1414. """
  1415. self.assertIsNone(default_storage.directory_permissions_mode)
  1416. with self.settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o777):
  1417. self.assertEqual(default_storage.directory_permissions_mode, 0o777)
  1418. def test_override_database_routers(self):
  1419. """
  1420. Overriding DATABASE_ROUTERS should update the master router.
  1421. """
  1422. test_routers = [object()]
  1423. with self.settings(DATABASE_ROUTERS=test_routers):
  1424. self.assertEqual(router.routers, test_routers)
  1425. def test_override_static_url(self):
  1426. """
  1427. Overriding the STATIC_URL setting should be reflected in the
  1428. base_url attribute of
  1429. django.contrib.staticfiles.storage.staticfiles_storage.
  1430. """
  1431. with self.settings(STATIC_URL='/test/'):
  1432. self.assertEqual(staticfiles_storage.base_url, '/test/')
  1433. def test_override_static_root(self):
  1434. """
  1435. Overriding the STATIC_ROOT setting should be reflected in the
  1436. location attribute of
  1437. django.contrib.staticfiles.storage.staticfiles_storage.
  1438. """
  1439. with self.settings(STATIC_ROOT='/tmp/test'):
  1440. self.assertEqual(staticfiles_storage.location, os.path.abspath('/tmp/test'))
  1441. def test_override_staticfiles_storage(self):
  1442. """
  1443. Overriding the STATICFILES_STORAGE setting should be reflected in
  1444. the value of django.contrib.staticfiles.storage.staticfiles_storage.
  1445. """
  1446. new_class = 'ManifestStaticFilesStorage'
  1447. new_storage = 'django.contrib.staticfiles.storage.' + new_class
  1448. with self.settings(STATICFILES_STORAGE=new_storage):
  1449. self.assertEqual(staticfiles_storage.__class__.__name__, new_class)
  1450. def test_override_staticfiles_finders(self):
  1451. """
  1452. Overriding the STATICFILES_FINDERS setting should be reflected in
  1453. the return value of django.contrib.staticfiles.finders.get_finders.
  1454. """
  1455. current = get_finders()
  1456. self.assertGreater(len(list(current)), 1)
  1457. finders = ['django.contrib.staticfiles.finders.FileSystemFinder']
  1458. with self.settings(STATICFILES_FINDERS=finders):
  1459. self.assertEqual(len(list(get_finders())), len(finders))
  1460. def test_override_staticfiles_dirs(self):
  1461. """
  1462. Overriding the STATICFILES_DIRS setting should be reflected in
  1463. the locations attribute of the
  1464. django.contrib.staticfiles.finders.FileSystemFinder instance.
  1465. """
  1466. finder = get_finder('django.contrib.staticfiles.finders.FileSystemFinder')
  1467. test_path = '/tmp/test'
  1468. expected_location = ('', test_path)
  1469. self.assertNotIn(expected_location, finder.locations)
  1470. with self.settings(STATICFILES_DIRS=[test_path]):
  1471. finder = get_finder('django.contrib.staticfiles.finders.FileSystemFinder')
  1472. self.assertIn(expected_location, finder.locations)
  1473. class TestBadSetUpTestData(TestCase):
  1474. """
  1475. An exception in setUpTestData() shouldn't leak a transaction which would
  1476. cascade across the rest of the test suite.
  1477. """
  1478. class MyException(Exception):
  1479. pass
  1480. @classmethod
  1481. def setUpClass(cls):
  1482. try:
  1483. super().setUpClass()
  1484. except cls.MyException:
  1485. cls._in_atomic_block = connection.in_atomic_block
  1486. @classmethod
  1487. def tearDownClass(Cls):
  1488. # override to avoid a second cls._rollback_atomics() which would fail.
  1489. # Normal setUpClass() methods won't have exception handling so this
  1490. # method wouldn't typically be run.
  1491. pass
  1492. @classmethod
  1493. def setUpTestData(cls):
  1494. # Simulate a broken setUpTestData() method.
  1495. raise cls.MyException()
  1496. def test_failure_in_setUpTestData_should_rollback_transaction(self):
  1497. # setUpTestData() should call _rollback_atomics() so that the
  1498. # transaction doesn't leak.
  1499. self.assertFalse(self._in_atomic_block)
  1500. class CaptureOnCommitCallbacksTests(TestCase):
  1501. databases = {'default', 'other'}
  1502. callback_called = False
  1503. def enqueue_callback(self, using='default'):
  1504. def hook():
  1505. self.callback_called = True
  1506. transaction.on_commit(hook, using=using)
  1507. def test_no_arguments(self):
  1508. with self.captureOnCommitCallbacks() as callbacks:
  1509. self.enqueue_callback()
  1510. self.assertEqual(len(callbacks), 1)
  1511. self.assertIs(self.callback_called, False)
  1512. callbacks[0]()
  1513. self.assertIs(self.callback_called, True)
  1514. def test_using(self):
  1515. with self.captureOnCommitCallbacks(using='other') as callbacks:
  1516. self.enqueue_callback(using='other')
  1517. self.assertEqual(len(callbacks), 1)
  1518. self.assertIs(self.callback_called, False)
  1519. callbacks[0]()
  1520. self.assertIs(self.callback_called, True)
  1521. def test_different_using(self):
  1522. with self.captureOnCommitCallbacks(using='default') as callbacks:
  1523. self.enqueue_callback(using='other')
  1524. self.assertEqual(callbacks, [])
  1525. def test_execute(self):
  1526. with self.captureOnCommitCallbacks(execute=True) as callbacks:
  1527. self.enqueue_callback()
  1528. self.assertEqual(len(callbacks), 1)
  1529. self.assertIs(self.callback_called, True)
  1530. def test_pre_callback(self):
  1531. def pre_hook():
  1532. pass
  1533. transaction.on_commit(pre_hook, using='default')
  1534. with self.captureOnCommitCallbacks() as callbacks:
  1535. self.enqueue_callback()
  1536. self.assertEqual(len(callbacks), 1)
  1537. self.assertNotEqual(callbacks[0], pre_hook)
  1538. def test_with_rolled_back_savepoint(self):
  1539. with self.captureOnCommitCallbacks() as callbacks:
  1540. try:
  1541. with transaction.atomic():
  1542. self.enqueue_callback()
  1543. raise IntegrityError
  1544. except IntegrityError:
  1545. # Inner transaction.atomic() has been rolled back.
  1546. pass
  1547. self.assertEqual(callbacks, [])
  1548. def test_execute_recursive(self):
  1549. with self.captureOnCommitCallbacks(execute=True) as callbacks:
  1550. transaction.on_commit(self.enqueue_callback)
  1551. self.assertEqual(len(callbacks), 2)
  1552. self.assertIs(self.callback_called, True)
  1553. def test_execute_tree(self):
  1554. """
  1555. A visualisation of the callback tree tested. Each node is expected to
  1556. be visited only once:
  1557. └─branch_1
  1558. ├─branch_2
  1559. │ ├─leaf_1
  1560. │ └─leaf_2
  1561. └─leaf_3
  1562. """
  1563. branch_1_call_counter = 0
  1564. branch_2_call_counter = 0
  1565. leaf_1_call_counter = 0
  1566. leaf_2_call_counter = 0
  1567. leaf_3_call_counter = 0
  1568. def leaf_1():
  1569. nonlocal leaf_1_call_counter
  1570. leaf_1_call_counter += 1
  1571. def leaf_2():
  1572. nonlocal leaf_2_call_counter
  1573. leaf_2_call_counter += 1
  1574. def leaf_3():
  1575. nonlocal leaf_3_call_counter
  1576. leaf_3_call_counter += 1
  1577. def branch_1():
  1578. nonlocal branch_1_call_counter
  1579. branch_1_call_counter += 1
  1580. transaction.on_commit(branch_2)
  1581. transaction.on_commit(leaf_3)
  1582. def branch_2():
  1583. nonlocal branch_2_call_counter
  1584. branch_2_call_counter += 1
  1585. transaction.on_commit(leaf_1)
  1586. transaction.on_commit(leaf_2)
  1587. with self.captureOnCommitCallbacks(execute=True) as callbacks:
  1588. transaction.on_commit(branch_1)
  1589. self.assertEqual(branch_1_call_counter, 1)
  1590. self.assertEqual(branch_2_call_counter, 1)
  1591. self.assertEqual(leaf_1_call_counter, 1)
  1592. self.assertEqual(leaf_2_call_counter, 1)
  1593. self.assertEqual(leaf_3_call_counter, 1)
  1594. self.assertEqual(callbacks, [branch_1, branch_2, leaf_3, leaf_1, leaf_2])
  1595. class DisallowedDatabaseQueriesTests(SimpleTestCase):
  1596. def test_disallowed_database_connections(self):
  1597. expected_message = (
  1598. "Database connections to 'default' are not allowed in SimpleTestCase "
  1599. "subclasses. Either subclass TestCase or TransactionTestCase to "
  1600. "ensure proper test isolation or add 'default' to "
  1601. "test_utils.tests.DisallowedDatabaseQueriesTests.databases to "
  1602. "silence this failure."
  1603. )
  1604. with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message):
  1605. connection.connect()
  1606. with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message):
  1607. connection.temporary_connection()
  1608. def test_disallowed_database_queries(self):
  1609. expected_message = (
  1610. "Database queries to 'default' are not allowed in SimpleTestCase "
  1611. "subclasses. Either subclass TestCase or TransactionTestCase to "
  1612. "ensure proper test isolation or add 'default' to "
  1613. "test_utils.tests.DisallowedDatabaseQueriesTests.databases to "
  1614. "silence this failure."
  1615. )
  1616. with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message):
  1617. Car.objects.first()
  1618. def test_disallowed_database_chunked_cursor_queries(self):
  1619. expected_message = (
  1620. "Database queries to 'default' are not allowed in SimpleTestCase "
  1621. "subclasses. Either subclass TestCase or TransactionTestCase to "
  1622. "ensure proper test isolation or add 'default' to "
  1623. "test_utils.tests.DisallowedDatabaseQueriesTests.databases to "
  1624. "silence this failure."
  1625. )
  1626. with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message):
  1627. next(Car.objects.iterator())
  1628. class AllowedDatabaseQueriesTests(SimpleTestCase):
  1629. databases = {'default'}
  1630. def test_allowed_database_queries(self):
  1631. Car.objects.first()
  1632. def test_allowed_database_chunked_cursor_queries(self):
  1633. next(Car.objects.iterator(), None)
  1634. class DatabaseAliasTests(SimpleTestCase):
  1635. def setUp(self):
  1636. self.addCleanup(setattr, self.__class__, 'databases', self.databases)
  1637. def test_no_close_match(self):
  1638. self.__class__.databases = {'void'}
  1639. message = (
  1640. "test_utils.tests.DatabaseAliasTests.databases refers to 'void' which is not defined "
  1641. "in settings.DATABASES."
  1642. )
  1643. with self.assertRaisesMessage(ImproperlyConfigured, message):
  1644. self._validate_databases()
  1645. def test_close_match(self):
  1646. self.__class__.databases = {'defualt'}
  1647. message = (
  1648. "test_utils.tests.DatabaseAliasTests.databases refers to 'defualt' which is not defined "
  1649. "in settings.DATABASES. Did you mean 'default'?"
  1650. )
  1651. with self.assertRaisesMessage(ImproperlyConfigured, message):
  1652. self._validate_databases()
  1653. def test_match(self):
  1654. self.__class__.databases = {'default', 'other'}
  1655. self.assertEqual(self._validate_databases(), frozenset({'default', 'other'}))
  1656. def test_all(self):
  1657. self.__class__.databases = '__all__'
  1658. self.assertEqual(self._validate_databases(), frozenset(connections))
  1659. @isolate_apps('test_utils', attr_name='class_apps')
  1660. class IsolatedAppsTests(SimpleTestCase):
  1661. def test_installed_apps(self):
  1662. self.assertEqual([app_config.label for app_config in self.class_apps.get_app_configs()], ['test_utils'])
  1663. def test_class_decoration(self):
  1664. class ClassDecoration(models.Model):
  1665. pass
  1666. self.assertEqual(ClassDecoration._meta.apps, self.class_apps)
  1667. @isolate_apps('test_utils', kwarg_name='method_apps')
  1668. def test_method_decoration(self, method_apps):
  1669. class MethodDecoration(models.Model):
  1670. pass
  1671. self.assertEqual(MethodDecoration._meta.apps, method_apps)
  1672. def test_context_manager(self):
  1673. with isolate_apps('test_utils') as context_apps:
  1674. class ContextManager(models.Model):
  1675. pass
  1676. self.assertEqual(ContextManager._meta.apps, context_apps)
  1677. @isolate_apps('test_utils', kwarg_name='method_apps')
  1678. def test_nested(self, method_apps):
  1679. class MethodDecoration(models.Model):
  1680. pass
  1681. with isolate_apps('test_utils') as context_apps:
  1682. class ContextManager(models.Model):
  1683. pass
  1684. with isolate_apps('test_utils') as nested_context_apps:
  1685. class NestedContextManager(models.Model):
  1686. pass
  1687. self.assertEqual(MethodDecoration._meta.apps, method_apps)
  1688. self.assertEqual(ContextManager._meta.apps, context_apps)
  1689. self.assertEqual(NestedContextManager._meta.apps, nested_context_apps)
  1690. class DoNothingDecorator(TestContextDecorator):
  1691. def enable(self):
  1692. pass
  1693. def disable(self):
  1694. pass
  1695. class TestContextDecoratorTests(SimpleTestCase):
  1696. @mock.patch.object(DoNothingDecorator, 'disable')
  1697. def test_exception_in_setup(self, mock_disable):
  1698. """An exception is setUp() is reraised after disable() is called."""
  1699. class ExceptionInSetUp(unittest.TestCase):
  1700. def setUp(self):
  1701. raise NotImplementedError('reraised')
  1702. decorator = DoNothingDecorator()
  1703. decorated_test_class = decorator.__call__(ExceptionInSetUp)()
  1704. self.assertFalse(mock_disable.called)
  1705. with self.assertRaisesMessage(NotImplementedError, 'reraised'):
  1706. decorated_test_class.setUp()
  1707. decorated_test_class.doCleanups()
  1708. self.assertTrue(mock_disable.called)
  1709. def test_cleanups_run_after_tearDown(self):
  1710. calls = []
  1711. class SaveCallsDecorator(TestContextDecorator):
  1712. def enable(self):
  1713. calls.append('enable')
  1714. def disable(self):
  1715. calls.append('disable')
  1716. class AddCleanupInSetUp(unittest.TestCase):
  1717. def setUp(self):
  1718. calls.append('setUp')
  1719. self.addCleanup(lambda: calls.append('cleanup'))
  1720. decorator = SaveCallsDecorator()
  1721. decorated_test_class = decorator.__call__(AddCleanupInSetUp)()
  1722. decorated_test_class.setUp()
  1723. decorated_test_class.tearDown()
  1724. decorated_test_class.doCleanups()
  1725. self.assertEqual(calls, ['enable', 'setUp', 'cleanup', 'disable'])