tests.py 85 KB

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