2
0

tests.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import unittest
  4. from django.conf.urls import url
  5. from django.core.urlresolvers import reverse
  6. from django.db import connection
  7. from django.forms import EmailField, IntegerField
  8. from django.http import HttpResponse
  9. from django.template.loader import render_to_string
  10. from django.test import SimpleTestCase, TestCase, skipIfDBFeature, skipUnlessDBFeature
  11. from django.test.html import HTMLParseError, parse_html
  12. from django.test.utils import CaptureQueriesContext, override_settings
  13. from django.utils import six
  14. from .models import Person
  15. class SkippingTestCase(TestCase):
  16. def test_skip_unless_db_feature(self):
  17. "A test that might be skipped is actually called."
  18. # Total hack, but it works, just want an attribute that's always true.
  19. @skipUnlessDBFeature("__class__")
  20. def test_func():
  21. raise ValueError
  22. self.assertRaises(ValueError, test_func)
  23. class SkippingClassTestCase(TestCase):
  24. def test_skip_class_unless_db_feature(self):
  25. @skipUnlessDBFeature("__class__")
  26. class NotSkippedTests(unittest.TestCase):
  27. def test_dummy(self):
  28. return
  29. @skipIfDBFeature("__class__")
  30. class SkippedTests(unittest.TestCase):
  31. def test_will_be_skipped(self):
  32. self.fail("We should never arrive here.")
  33. test_suite = unittest.TestSuite()
  34. test_suite.addTest(NotSkippedTests('test_dummy'))
  35. try:
  36. test_suite.addTest(SkippedTests('test_will_be_skipped'))
  37. except unittest.SkipTest:
  38. self.fail("SkipTest should not be raised at this stage")
  39. result = unittest.TextTestRunner(stream=six.StringIO()).run(test_suite)
  40. self.assertEqual(result.testsRun, 2)
  41. self.assertEqual(len(result.skipped), 1)
  42. class AssertNumQueriesTests(TestCase):
  43. urls = 'test_utils.urls'
  44. def test_assert_num_queries(self):
  45. def test_func():
  46. raise ValueError
  47. self.assertRaises(ValueError, self.assertNumQueries, 2, test_func)
  48. def test_assert_num_queries_with_client(self):
  49. person = Person.objects.create(name='test')
  50. self.assertNumQueries(
  51. 1,
  52. self.client.get,
  53. "/test_utils/get_person/%s/" % person.pk
  54. )
  55. self.assertNumQueries(
  56. 1,
  57. self.client.get,
  58. "/test_utils/get_person/%s/" % person.pk
  59. )
  60. def test_func():
  61. self.client.get("/test_utils/get_person/%s/" % person.pk)
  62. self.client.get("/test_utils/get_person/%s/" % person.pk)
  63. self.assertNumQueries(2, test_func)
  64. class AssertQuerysetEqualTests(TestCase):
  65. def setUp(self):
  66. self.p1 = Person.objects.create(name='p1')
  67. self.p2 = Person.objects.create(name='p2')
  68. def test_ordered(self):
  69. self.assertQuerysetEqual(
  70. Person.objects.all().order_by('name'),
  71. [repr(self.p1), repr(self.p2)]
  72. )
  73. def test_unordered(self):
  74. self.assertQuerysetEqual(
  75. Person.objects.all().order_by('name'),
  76. [repr(self.p2), repr(self.p1)],
  77. ordered=False
  78. )
  79. def test_transform(self):
  80. self.assertQuerysetEqual(
  81. Person.objects.all().order_by('name'),
  82. [self.p1.pk, self.p2.pk],
  83. transform=lambda x: x.pk
  84. )
  85. def test_undefined_order(self):
  86. # Using an unordered queryset with more than one ordered value
  87. # is an error.
  88. with self.assertRaises(ValueError):
  89. self.assertQuerysetEqual(
  90. Person.objects.all(),
  91. [repr(self.p1), repr(self.p2)]
  92. )
  93. # No error for one value.
  94. self.assertQuerysetEqual(
  95. Person.objects.filter(name='p1'),
  96. [repr(self.p1)]
  97. )
  98. class CaptureQueriesContextManagerTests(TestCase):
  99. urls = 'test_utils.urls'
  100. def setUp(self):
  101. self.person_pk = six.text_type(Person.objects.create(name='test').pk)
  102. def test_simple(self):
  103. with CaptureQueriesContext(connection) as captured_queries:
  104. Person.objects.get(pk=self.person_pk)
  105. self.assertEqual(len(captured_queries), 1)
  106. self.assertIn(self.person_pk, captured_queries[0]['sql'])
  107. with CaptureQueriesContext(connection) as captured_queries:
  108. pass
  109. self.assertEqual(0, len(captured_queries))
  110. def test_within(self):
  111. with CaptureQueriesContext(connection) as captured_queries:
  112. Person.objects.get(pk=self.person_pk)
  113. self.assertEqual(len(captured_queries), 1)
  114. self.assertIn(self.person_pk, captured_queries[0]['sql'])
  115. def test_nested(self):
  116. with CaptureQueriesContext(connection) as captured_queries:
  117. Person.objects.count()
  118. with CaptureQueriesContext(connection) as nested_captured_queries:
  119. Person.objects.count()
  120. self.assertEqual(1, len(nested_captured_queries))
  121. self.assertEqual(2, len(captured_queries))
  122. def test_failure(self):
  123. with self.assertRaises(TypeError):
  124. with CaptureQueriesContext(connection):
  125. raise TypeError
  126. def test_with_client(self):
  127. with CaptureQueriesContext(connection) as captured_queries:
  128. self.client.get("/test_utils/get_person/%s/" % self.person_pk)
  129. self.assertEqual(len(captured_queries), 1)
  130. self.assertIn(self.person_pk, captured_queries[0]['sql'])
  131. with CaptureQueriesContext(connection) as captured_queries:
  132. self.client.get("/test_utils/get_person/%s/" % self.person_pk)
  133. self.assertEqual(len(captured_queries), 1)
  134. self.assertIn(self.person_pk, captured_queries[0]['sql'])
  135. with CaptureQueriesContext(connection) as captured_queries:
  136. self.client.get("/test_utils/get_person/%s/" % self.person_pk)
  137. self.client.get("/test_utils/get_person/%s/" % self.person_pk)
  138. self.assertEqual(len(captured_queries), 2)
  139. self.assertIn(self.person_pk, captured_queries[0]['sql'])
  140. self.assertIn(self.person_pk, captured_queries[1]['sql'])
  141. class AssertNumQueriesContextManagerTests(TestCase):
  142. urls = 'test_utils.urls'
  143. def test_simple(self):
  144. with self.assertNumQueries(0):
  145. pass
  146. with self.assertNumQueries(1):
  147. Person.objects.count()
  148. with self.assertNumQueries(2):
  149. Person.objects.count()
  150. Person.objects.count()
  151. def test_failure(self):
  152. with self.assertRaises(AssertionError) as exc_info:
  153. with self.assertNumQueries(2):
  154. Person.objects.count()
  155. self.assertIn("1 queries executed, 2 expected", str(exc_info.exception))
  156. self.assertIn("Captured queries were", str(exc_info.exception))
  157. with self.assertRaises(TypeError):
  158. with self.assertNumQueries(4000):
  159. raise TypeError
  160. def test_with_client(self):
  161. person = Person.objects.create(name="test")
  162. with self.assertNumQueries(1):
  163. self.client.get("/test_utils/get_person/%s/" % person.pk)
  164. with self.assertNumQueries(1):
  165. self.client.get("/test_utils/get_person/%s/" % person.pk)
  166. with self.assertNumQueries(2):
  167. self.client.get("/test_utils/get_person/%s/" % person.pk)
  168. self.client.get("/test_utils/get_person/%s/" % person.pk)
  169. class AssertTemplateUsedContextManagerTests(TestCase):
  170. urls = 'test_utils.urls'
  171. def test_usage(self):
  172. with self.assertTemplateUsed('template_used/base.html'):
  173. render_to_string('template_used/base.html')
  174. with self.assertTemplateUsed(template_name='template_used/base.html'):
  175. render_to_string('template_used/base.html')
  176. with self.assertTemplateUsed('template_used/base.html'):
  177. render_to_string('template_used/include.html')
  178. with self.assertTemplateUsed('template_used/base.html'):
  179. render_to_string('template_used/extends.html')
  180. with self.assertTemplateUsed('template_used/base.html'):
  181. render_to_string('template_used/base.html')
  182. render_to_string('template_used/base.html')
  183. def test_nested_usage(self):
  184. with self.assertTemplateUsed('template_used/base.html'):
  185. with self.assertTemplateUsed('template_used/include.html'):
  186. render_to_string('template_used/include.html')
  187. with self.assertTemplateUsed('template_used/extends.html'):
  188. with self.assertTemplateUsed('template_used/base.html'):
  189. render_to_string('template_used/extends.html')
  190. with self.assertTemplateUsed('template_used/base.html'):
  191. with self.assertTemplateUsed('template_used/alternative.html'):
  192. render_to_string('template_used/alternative.html')
  193. render_to_string('template_used/base.html')
  194. with self.assertTemplateUsed('template_used/base.html'):
  195. render_to_string('template_used/extends.html')
  196. with self.assertTemplateNotUsed('template_used/base.html'):
  197. render_to_string('template_used/alternative.html')
  198. render_to_string('template_used/base.html')
  199. def test_not_used(self):
  200. with self.assertTemplateNotUsed('template_used/base.html'):
  201. pass
  202. with self.assertTemplateNotUsed('template_used/alternative.html'):
  203. pass
  204. def test_error_message(self):
  205. with six.assertRaisesRegex(self, AssertionError, r'^template_used/base\.html'):
  206. with self.assertTemplateUsed('template_used/base.html'):
  207. pass
  208. with six.assertRaisesRegex(self, AssertionError, r'^template_used/base\.html'):
  209. with self.assertTemplateUsed(template_name='template_used/base.html'):
  210. pass
  211. with six.assertRaisesRegex(self, AssertionError, r'^template_used/base\.html.*template_used/alternative\.html$'):
  212. with self.assertTemplateUsed('template_used/base.html'):
  213. render_to_string('template_used/alternative.html')
  214. with self.assertRaises(AssertionError) as cm:
  215. response = self.client.get('/test_utils/no_template_used/')
  216. self.assertTemplateUsed(response, 'template_used/base.html')
  217. self.assertEqual(cm.exception.args[0], "No templates used to render the response")
  218. def test_failure(self):
  219. with self.assertRaises(TypeError):
  220. with self.assertTemplateUsed():
  221. pass
  222. with self.assertRaises(AssertionError):
  223. with self.assertTemplateUsed(''):
  224. pass
  225. with self.assertRaises(AssertionError):
  226. with self.assertTemplateUsed(''):
  227. render_to_string('template_used/base.html')
  228. with self.assertRaises(AssertionError):
  229. with self.assertTemplateUsed(template_name=''):
  230. pass
  231. with self.assertRaises(AssertionError):
  232. with self.assertTemplateUsed('template_used/base.html'):
  233. render_to_string('template_used/alternative.html')
  234. class HTMLEqualTests(TestCase):
  235. def test_html_parser(self):
  236. element = parse_html('<div><p>Hello</p></div>')
  237. self.assertEqual(len(element.children), 1)
  238. self.assertEqual(element.children[0].name, 'p')
  239. self.assertEqual(element.children[0].children[0], 'Hello')
  240. parse_html('<p>')
  241. parse_html('<p attr>')
  242. dom = parse_html('<p>foo')
  243. self.assertEqual(len(dom.children), 1)
  244. self.assertEqual(dom.name, 'p')
  245. self.assertEqual(dom[0], 'foo')
  246. def test_parse_html_in_script(self):
  247. parse_html('<script>var a = "<p" + ">";</script>')
  248. parse_html('''
  249. <script>
  250. var js_sha_link='<p>***</p>';
  251. </script>
  252. ''')
  253. # script content will be parsed to text
  254. dom = parse_html('''
  255. <script><p>foo</p> '</scr'+'ipt>' <span>bar</span></script>
  256. ''')
  257. self.assertEqual(len(dom.children), 1)
  258. self.assertEqual(dom.children[0], "<p>foo</p> '</scr'+'ipt>' <span>bar</span>")
  259. def test_self_closing_tags(self):
  260. self_closing_tags = ('br', 'hr', 'input', 'img', 'meta', 'spacer',
  261. 'link', 'frame', 'base', 'col')
  262. for tag in self_closing_tags:
  263. dom = parse_html('<p>Hello <%s> world</p>' % tag)
  264. self.assertEqual(len(dom.children), 3)
  265. self.assertEqual(dom[0], 'Hello')
  266. self.assertEqual(dom[1].name, tag)
  267. self.assertEqual(dom[2], 'world')
  268. dom = parse_html('<p>Hello <%s /> world</p>' % tag)
  269. self.assertEqual(len(dom.children), 3)
  270. self.assertEqual(dom[0], 'Hello')
  271. self.assertEqual(dom[1].name, tag)
  272. self.assertEqual(dom[2], 'world')
  273. def test_simple_equal_html(self):
  274. self.assertHTMLEqual('', '')
  275. self.assertHTMLEqual('<p></p>', '<p></p>')
  276. self.assertHTMLEqual('<p></p>', ' <p> </p> ')
  277. self.assertHTMLEqual(
  278. '<div><p>Hello</p></div>',
  279. '<div><p>Hello</p></div>')
  280. self.assertHTMLEqual(
  281. '<div><p>Hello</p></div>',
  282. '<div> <p>Hello</p> </div>')
  283. self.assertHTMLEqual(
  284. '<div>\n<p>Hello</p></div>',
  285. '<div><p>Hello</p></div>\n')
  286. self.assertHTMLEqual(
  287. '<div><p>Hello\nWorld !</p></div>',
  288. '<div><p>Hello World\n!</p></div>')
  289. self.assertHTMLEqual(
  290. '<div><p>Hello\nWorld !</p></div>',
  291. '<div><p>Hello World\n!</p></div>')
  292. self.assertHTMLEqual(
  293. '<p>Hello World !</p>',
  294. '<p>Hello World\n\n!</p>')
  295. self.assertHTMLEqual('<p> </p>', '<p></p>')
  296. self.assertHTMLEqual('<p/>', '<p></p>')
  297. self.assertHTMLEqual('<p />', '<p></p>')
  298. self.assertHTMLEqual('<input checked>', '<input checked="checked">')
  299. self.assertHTMLEqual('<p>Hello', '<p> Hello')
  300. self.assertHTMLEqual('<p>Hello</p>World', '<p>Hello</p> World')
  301. def test_ignore_comments(self):
  302. self.assertHTMLEqual(
  303. '<div>Hello<!-- this is a comment --> World!</div>',
  304. '<div>Hello World!</div>')
  305. def test_unequal_html(self):
  306. self.assertHTMLNotEqual('<p>Hello</p>', '<p>Hello!</p>')
  307. self.assertHTMLNotEqual('<p>foo&#20;bar</p>', '<p>foo&nbsp;bar</p>')
  308. self.assertHTMLNotEqual('<p>foo bar</p>', '<p>foo &nbsp;bar</p>')
  309. self.assertHTMLNotEqual('<p>foo nbsp</p>', '<p>foo &nbsp;</p>')
  310. self.assertHTMLNotEqual('<p>foo #20</p>', '<p>foo &#20;</p>')
  311. self.assertHTMLNotEqual(
  312. '<p><span>Hello</span><span>World</span></p>',
  313. '<p><span>Hello</span>World</p>')
  314. self.assertHTMLNotEqual(
  315. '<p><span>Hello</span>World</p>',
  316. '<p><span>Hello</span><span>World</span></p>')
  317. def test_attributes(self):
  318. self.assertHTMLEqual(
  319. '<input type="text" id="id_name" />',
  320. '<input id="id_name" type="text" />')
  321. self.assertHTMLEqual(
  322. '''<input type='text' id="id_name" />''',
  323. '<input id="id_name" type="text" />')
  324. self.assertHTMLNotEqual(
  325. '<input type="text" id="id_name" />',
  326. '<input type="password" id="id_name" />')
  327. def test_complex_examples(self):
  328. self.assertHTMLEqual(
  329. """<tr><th><label for="id_first_name">First name:</label></th>
  330. <td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>
  331. <tr><th><label for="id_last_name">Last name:</label></th>
  332. <td><input type="text" id="id_last_name" name="last_name" value="Lennon" /></td></tr>
  333. <tr><th><label for="id_birthday">Birthday:</label></th>
  334. <td><input type="text" value="1940-10-9" name="birthday" id="id_birthday" /></td></tr>""",
  335. """
  336. <tr><th>
  337. <label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" />
  338. </td></tr>
  339. <tr><th>
  340. <label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="Lennon" id="id_last_name" />
  341. </td></tr>
  342. <tr><th>
  343. <label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" />
  344. </td></tr>
  345. """)
  346. self.assertHTMLEqual(
  347. """<!DOCTYPE html>
  348. <html>
  349. <head>
  350. <link rel="stylesheet">
  351. <title>Document</title>
  352. <meta attribute="value">
  353. </head>
  354. <body>
  355. <p>
  356. This is a valid paragraph
  357. <div> this is a div AFTER the p</div>
  358. </body>
  359. </html>""", """
  360. <html>
  361. <head>
  362. <link rel="stylesheet">
  363. <title>Document</title>
  364. <meta attribute="value">
  365. </head>
  366. <body>
  367. <p> This is a valid paragraph
  368. <!-- browsers would close the p tag here -->
  369. <div> this is a div AFTER the p</div>
  370. </p> <!-- this is invalid HTML parsing, but it should make no
  371. difference in most cases -->
  372. </body>
  373. </html>""")
  374. def test_html_contain(self):
  375. # equal html contains each other
  376. dom1 = parse_html('<p>foo')
  377. dom2 = parse_html('<p>foo</p>')
  378. self.assertTrue(dom1 in dom2)
  379. self.assertTrue(dom2 in dom1)
  380. dom2 = parse_html('<div><p>foo</p></div>')
  381. self.assertTrue(dom1 in dom2)
  382. self.assertTrue(dom2 not in dom1)
  383. self.assertFalse('<p>foo</p>' in dom2)
  384. self.assertTrue('foo' in dom2)
  385. # when a root element is used ...
  386. dom1 = parse_html('<p>foo</p><p>bar</p>')
  387. dom2 = parse_html('<p>foo</p><p>bar</p>')
  388. self.assertTrue(dom1 in dom2)
  389. dom1 = parse_html('<p>foo</p>')
  390. self.assertTrue(dom1 in dom2)
  391. dom1 = parse_html('<p>bar</p>')
  392. self.assertTrue(dom1 in dom2)
  393. def test_count(self):
  394. # equal html contains each other one time
  395. dom1 = parse_html('<p>foo')
  396. dom2 = parse_html('<p>foo</p>')
  397. self.assertEqual(dom1.count(dom2), 1)
  398. self.assertEqual(dom2.count(dom1), 1)
  399. dom2 = parse_html('<p>foo</p><p>bar</p>')
  400. self.assertEqual(dom2.count(dom1), 1)
  401. dom2 = parse_html('<p>foo foo</p><p>foo</p>')
  402. self.assertEqual(dom2.count('foo'), 3)
  403. dom2 = parse_html('<p class="bar">foo</p>')
  404. self.assertEqual(dom2.count('bar'), 0)
  405. self.assertEqual(dom2.count('class'), 0)
  406. self.assertEqual(dom2.count('p'), 0)
  407. self.assertEqual(dom2.count('o'), 2)
  408. dom2 = parse_html('<p>foo</p><p>foo</p>')
  409. self.assertEqual(dom2.count(dom1), 2)
  410. dom2 = parse_html('<div><p>foo<input type=""></p><p>foo</p></div>')
  411. self.assertEqual(dom2.count(dom1), 1)
  412. dom2 = parse_html('<div><div><p>foo</p></div></div>')
  413. self.assertEqual(dom2.count(dom1), 1)
  414. dom2 = parse_html('<p>foo<p>foo</p></p>')
  415. self.assertEqual(dom2.count(dom1), 1)
  416. dom2 = parse_html('<p>foo<p>bar</p></p>')
  417. self.assertEqual(dom2.count(dom1), 0)
  418. def test_parsing_errors(self):
  419. with self.assertRaises(AssertionError):
  420. self.assertHTMLEqual('<p>', '')
  421. with self.assertRaises(AssertionError):
  422. self.assertHTMLEqual('', '<p>')
  423. with self.assertRaises(HTMLParseError):
  424. parse_html('</p>')
  425. def test_contains_html(self):
  426. response = HttpResponse('''<body>
  427. This is a form: <form action="" method="get">
  428. <input type="text" name="Hello" />
  429. </form></body>''')
  430. self.assertNotContains(response, "<input name='Hello' type='text'>")
  431. self.assertContains(response, '<form action="" method="get">')
  432. self.assertContains(response, "<input name='Hello' type='text'>", html=True)
  433. self.assertNotContains(response, '<form action="" method="get">', html=True)
  434. invalid_response = HttpResponse('''<body <bad>>''')
  435. with self.assertRaises(AssertionError):
  436. self.assertContains(invalid_response, '<p></p>')
  437. with self.assertRaises(AssertionError):
  438. self.assertContains(response, '<p "whats" that>')
  439. def test_unicode_handling(self):
  440. response = HttpResponse('<p class="help">Some help text for the title (with unicode ŠĐĆŽćžšđ)</p>')
  441. self.assertContains(response, '<p class="help">Some help text for the title (with unicode ŠĐĆŽćžšđ)</p>', html=True)
  442. class XMLEqualTests(TestCase):
  443. def test_simple_equal(self):
  444. xml1 = "<elem attr1='a' attr2='b' />"
  445. xml2 = "<elem attr1='a' attr2='b' />"
  446. self.assertXMLEqual(xml1, xml2)
  447. def test_simple_equal_unordered(self):
  448. xml1 = "<elem attr1='a' attr2='b' />"
  449. xml2 = "<elem attr2='b' attr1='a' />"
  450. self.assertXMLEqual(xml1, xml2)
  451. def test_simple_equal_raise(self):
  452. xml1 = "<elem attr1='a' />"
  453. xml2 = "<elem attr2='b' attr1='a' />"
  454. with self.assertRaises(AssertionError):
  455. self.assertXMLEqual(xml1, xml2)
  456. def test_simple_not_equal(self):
  457. xml1 = "<elem attr1='a' attr2='c' />"
  458. xml2 = "<elem attr1='a' attr2='b' />"
  459. self.assertXMLNotEqual(xml1, xml2)
  460. def test_simple_not_equal_raise(self):
  461. xml1 = "<elem attr1='a' attr2='b' />"
  462. xml2 = "<elem attr2='b' attr1='a' />"
  463. with self.assertRaises(AssertionError):
  464. self.assertXMLNotEqual(xml1, xml2)
  465. def test_parsing_errors(self):
  466. xml_unvalid = "<elem attr1='a attr2='b' />"
  467. xml2 = "<elem attr2='b' attr1='a' />"
  468. with self.assertRaises(AssertionError):
  469. self.assertXMLNotEqual(xml_unvalid, xml2)
  470. def test_comment_root(self):
  471. xml1 = "<?xml version='1.0'?><!-- comment1 --><elem attr1='a' attr2='b' />"
  472. xml2 = "<?xml version='1.0'?><!-- comment2 --><elem attr2='b' attr1='a' />"
  473. self.assertXMLEqual(xml1, xml2)
  474. class SkippingExtraTests(TestCase):
  475. fixtures = ['should_not_be_loaded.json']
  476. # HACK: This depends on internals of our TestCase subclasses
  477. def __call__(self, result=None):
  478. # Detect fixture loading by counting SQL queries, should be zero
  479. with self.assertNumQueries(0):
  480. super(SkippingExtraTests, self).__call__(result)
  481. @unittest.skip("Fixture loading should not be performed for skipped tests.")
  482. def test_fixtures_are_skipped(self):
  483. pass
  484. class AssertRaisesMsgTest(SimpleTestCase):
  485. def test_special_re_chars(self):
  486. """assertRaisesMessage shouldn't interpret RE special chars."""
  487. def func1():
  488. raise ValueError("[.*x+]y?")
  489. self.assertRaisesMessage(ValueError, "[.*x+]y?", func1)
  490. class AssertFieldOutputTests(SimpleTestCase):
  491. def test_assert_field_output(self):
  492. error_invalid = ['Enter a valid email address.']
  493. self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid})
  494. self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid + ['Another error']})
  495. self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'Wrong output'}, {'aaa': error_invalid})
  496. self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': ['Come on, gimme some well formatted data, dude.']})
  497. def test_custom_required_message(self):
  498. class MyCustomField(IntegerField):
  499. default_error_messages = {
  500. 'required': 'This is really required.',
  501. }
  502. self.assertFieldOutput(MyCustomField, {}, {}, empty_value=None)
  503. # for OverrideSettingsTests
  504. def fake_view(request):
  505. pass
  506. class FirstUrls:
  507. urlpatterns = [url(r'first/$', fake_view, name='first')]
  508. class SecondUrls:
  509. urlpatterns = [url(r'second/$', fake_view, name='second')]
  510. class OverrideSettingsTests(TestCase):
  511. """
  512. #21518 -- If neither override_settings nor a settings_changed receiver
  513. clears the URL cache between tests, then one of these two test methods will
  514. fail.
  515. """
  516. @override_settings(ROOT_URLCONF=FirstUrls)
  517. def test_first(self):
  518. reverse('first')
  519. @override_settings(ROOT_URLCONF=SecondUrls)
  520. def test_second(self):
  521. reverse('second')