tests.py 92 KB

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