PageRenderTime 186ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/regressiontests/test_utils/tests.py

https://bitbucket.org/pcelta/python-django
Python | 562 lines | 519 code | 41 blank | 2 comment | 36 complexity | d3251c620379ecc4fca3772570802553 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. # -*- coding: utf-8 -*-
  2. from __future__ import with_statement, absolute_import
  3. from django.forms import EmailField, IntegerField
  4. from django.http import HttpResponse
  5. from django.template.loader import render_to_string
  6. from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature
  7. from django.utils.unittest import skip
  8. from .models import Person
  9. class SkippingTestCase(TestCase):
  10. def test_skip_unless_db_feature(self):
  11. "A test that might be skipped is actually called."
  12. # Total hack, but it works, just want an attribute that's always true.
  13. @skipUnlessDBFeature("__class__")
  14. def test_func():
  15. raise ValueError
  16. self.assertRaises(ValueError, test_func)
  17. class AssertNumQueriesTests(TestCase):
  18. urls = 'regressiontests.test_utils.urls'
  19. def test_assert_num_queries(self):
  20. def test_func():
  21. raise ValueError
  22. self.assertRaises(ValueError,
  23. self.assertNumQueries, 2, test_func
  24. )
  25. def test_assert_num_queries_with_client(self):
  26. person = Person.objects.create(name='test')
  27. self.assertNumQueries(
  28. 1,
  29. self.client.get,
  30. "/test_utils/get_person/%s/" % person.pk
  31. )
  32. self.assertNumQueries(
  33. 1,
  34. self.client.get,
  35. "/test_utils/get_person/%s/" % person.pk
  36. )
  37. def test_func():
  38. self.client.get("/test_utils/get_person/%s/" % person.pk)
  39. self.client.get("/test_utils/get_person/%s/" % person.pk)
  40. self.assertNumQueries(2, test_func)
  41. class AssertNumQueriesContextManagerTests(TestCase):
  42. urls = 'regressiontests.test_utils.urls'
  43. def test_simple(self):
  44. with self.assertNumQueries(0):
  45. pass
  46. with self.assertNumQueries(1):
  47. Person.objects.count()
  48. with self.assertNumQueries(2):
  49. Person.objects.count()
  50. Person.objects.count()
  51. def test_failure(self):
  52. with self.assertRaises(AssertionError) as exc_info:
  53. with self.assertNumQueries(2):
  54. Person.objects.count()
  55. self.assertIn("1 queries executed, 2 expected", str(exc_info.exception))
  56. with self.assertRaises(TypeError):
  57. with self.assertNumQueries(4000):
  58. raise TypeError
  59. def test_with_client(self):
  60. person = Person.objects.create(name="test")
  61. with self.assertNumQueries(1):
  62. self.client.get("/test_utils/get_person/%s/" % person.pk)
  63. with self.assertNumQueries(1):
  64. self.client.get("/test_utils/get_person/%s/" % person.pk)
  65. with self.assertNumQueries(2):
  66. self.client.get("/test_utils/get_person/%s/" % person.pk)
  67. self.client.get("/test_utils/get_person/%s/" % person.pk)
  68. class AssertTemplateUsedContextManagerTests(TestCase):
  69. def test_usage(self):
  70. with self.assertTemplateUsed('template_used/base.html'):
  71. render_to_string('template_used/base.html')
  72. with self.assertTemplateUsed(template_name='template_used/base.html'):
  73. render_to_string('template_used/base.html')
  74. with self.assertTemplateUsed('template_used/base.html'):
  75. render_to_string('template_used/include.html')
  76. with self.assertTemplateUsed('template_used/base.html'):
  77. render_to_string('template_used/extends.html')
  78. with self.assertTemplateUsed('template_used/base.html'):
  79. render_to_string('template_used/base.html')
  80. render_to_string('template_used/base.html')
  81. def test_nested_usage(self):
  82. with self.assertTemplateUsed('template_used/base.html'):
  83. with self.assertTemplateUsed('template_used/include.html'):
  84. render_to_string('template_used/include.html')
  85. with self.assertTemplateUsed('template_used/extends.html'):
  86. with self.assertTemplateUsed('template_used/base.html'):
  87. render_to_string('template_used/extends.html')
  88. with self.assertTemplateUsed('template_used/base.html'):
  89. with self.assertTemplateUsed('template_used/alternative.html'):
  90. render_to_string('template_used/alternative.html')
  91. render_to_string('template_used/base.html')
  92. with self.assertTemplateUsed('template_used/base.html'):
  93. render_to_string('template_used/extends.html')
  94. with self.assertTemplateNotUsed('template_used/base.html'):
  95. render_to_string('template_used/alternative.html')
  96. render_to_string('template_used/base.html')
  97. def test_not_used(self):
  98. with self.assertTemplateNotUsed('template_used/base.html'):
  99. pass
  100. with self.assertTemplateNotUsed('template_used/alternative.html'):
  101. pass
  102. def test_error_message(self):
  103. with self.assertRaisesRegexp(AssertionError, r'^template_used/base\.html'):
  104. with self.assertTemplateUsed('template_used/base.html'):
  105. pass
  106. with self.assertRaisesRegexp(AssertionError, r'^template_used/base\.html'):
  107. with self.assertTemplateUsed(template_name='template_used/base.html'):
  108. pass
  109. with self.assertRaisesRegexp(AssertionError, r'^template_used/base\.html.*template_used/alternative\.html$'):
  110. with self.assertTemplateUsed('template_used/base.html'):
  111. render_to_string('template_used/alternative.html')
  112. def test_failure(self):
  113. with self.assertRaises(TypeError):
  114. with self.assertTemplateUsed():
  115. pass
  116. with self.assertRaises(AssertionError):
  117. with self.assertTemplateUsed(''):
  118. pass
  119. with self.assertRaises(AssertionError):
  120. with self.assertTemplateUsed(''):
  121. render_to_string('template_used/base.html')
  122. with self.assertRaises(AssertionError):
  123. with self.assertTemplateUsed(template_name=''):
  124. pass
  125. with self.assertRaises(AssertionError):
  126. with self.assertTemplateUsed('template_used/base.html'):
  127. render_to_string('template_used/alternative.html')
  128. class SaveRestoreWarningState(TestCase):
  129. def test_save_restore_warnings_state(self):
  130. """
  131. Ensure save_warnings_state/restore_warnings_state work correctly.
  132. """
  133. # In reality this test could be satisfied by many broken implementations
  134. # of save_warnings_state/restore_warnings_state (e.g. just
  135. # warnings.resetwarnings()) , but it is difficult to test more.
  136. import warnings
  137. self.save_warnings_state()
  138. class MyWarning(Warning):
  139. pass
  140. # Add a filter that causes an exception to be thrown, so we can catch it
  141. warnings.simplefilter("error", MyWarning)
  142. self.assertRaises(Warning, lambda: warnings.warn("warn", MyWarning))
  143. # Now restore.
  144. self.restore_warnings_state()
  145. # After restoring, we shouldn't get an exception. But we don't want a
  146. # warning printed either, so we have to silence the warning.
  147. warnings.simplefilter("ignore", MyWarning)
  148. warnings.warn("warn", MyWarning)
  149. # Remove the filter we just added.
  150. self.restore_warnings_state()
  151. class HTMLEqualTests(TestCase):
  152. def test_html_parser(self):
  153. from django.test.html import parse_html
  154. element = parse_html('<div><p>Hello</p></div>')
  155. self.assertEqual(len(element.children), 1)
  156. self.assertEqual(element.children[0].name, 'p')
  157. self.assertEqual(element.children[0].children[0], 'Hello')
  158. parse_html('<p>')
  159. parse_html('<p attr>')
  160. dom = parse_html('<p>foo')
  161. self.assertEqual(len(dom.children), 1)
  162. self.assertEqual(dom.name, 'p')
  163. self.assertEqual(dom[0], 'foo')
  164. def test_parse_html_in_script(self):
  165. from django.test.html import parse_html
  166. parse_html('<script>var a = "<p" + ">";</script>');
  167. parse_html('''
  168. <script>
  169. var js_sha_link='<p>***</p>';
  170. </script>
  171. ''')
  172. # script content will be parsed to text
  173. dom = parse_html('''
  174. <script><p>foo</p> '</scr'+'ipt>' <span>bar</span></script>
  175. ''')
  176. self.assertEqual(len(dom.children), 1)
  177. self.assertEqual(dom.children[0], "<p>foo</p> '</scr'+'ipt>' <span>bar</span>")
  178. def test_self_closing_tags(self):
  179. from django.test.html import parse_html
  180. self_closing_tags = ('br' , 'hr', 'input', 'img', 'meta', 'spacer',
  181. 'link', 'frame', 'base', 'col')
  182. for tag in self_closing_tags:
  183. dom = parse_html('<p>Hello <%s> world</p>' % tag)
  184. self.assertEqual(len(dom.children), 3)
  185. self.assertEqual(dom[0], 'Hello')
  186. self.assertEqual(dom[1].name, tag)
  187. self.assertEqual(dom[2], 'world')
  188. dom = parse_html('<p>Hello <%s /> world</p>' % tag)
  189. self.assertEqual(len(dom.children), 3)
  190. self.assertEqual(dom[0], 'Hello')
  191. self.assertEqual(dom[1].name, tag)
  192. self.assertEqual(dom[2], 'world')
  193. def test_simple_equal_html(self):
  194. self.assertHTMLEqual('', '')
  195. self.assertHTMLEqual('<p></p>', '<p></p>')
  196. self.assertHTMLEqual('<p></p>', ' <p> </p> ')
  197. self.assertHTMLEqual(
  198. '<div><p>Hello</p></div>',
  199. '<div><p>Hello</p></div>')
  200. self.assertHTMLEqual(
  201. '<div><p>Hello</p></div>',
  202. '<div> <p>Hello</p> </div>')
  203. self.assertHTMLEqual(
  204. '<div>\n<p>Hello</p></div>',
  205. '<div><p>Hello</p></div>\n')
  206. self.assertHTMLEqual(
  207. '<div><p>Hello\nWorld !</p></div>',
  208. '<div><p>Hello World\n!</p></div>')
  209. self.assertHTMLEqual(
  210. '<div><p>Hello\nWorld !</p></div>',
  211. '<div><p>Hello World\n!</p></div>')
  212. self.assertHTMLEqual(
  213. '<p>Hello World !</p>',
  214. '<p>Hello World\n\n!</p>')
  215. self.assertHTMLEqual('<p> </p>', '<p></p>')
  216. self.assertHTMLEqual('<p/>', '<p></p>')
  217. self.assertHTMLEqual('<p />', '<p></p>')
  218. self.assertHTMLEqual('<input checked>', '<input checked="checked">')
  219. self.assertHTMLEqual('<p>Hello', '<p> Hello')
  220. self.assertHTMLEqual('<p>Hello</p>World', '<p>Hello</p> World')
  221. def test_ignore_comments(self):
  222. self.assertHTMLEqual(
  223. '<div>Hello<!-- this is a comment --> World!</div>',
  224. '<div>Hello World!</div>')
  225. def test_unequal_html(self):
  226. self.assertHTMLNotEqual('<p>Hello</p>', '<p>Hello!</p>')
  227. self.assertHTMLNotEqual('<p>foo&#20;bar</p>', '<p>foo&nbsp;bar</p>')
  228. self.assertHTMLNotEqual('<p>foo bar</p>', '<p>foo &nbsp;bar</p>')
  229. self.assertHTMLNotEqual('<p>foo nbsp</p>', '<p>foo &nbsp;</p>')
  230. self.assertHTMLNotEqual('<p>foo #20</p>', '<p>foo &#20;</p>')
  231. self.assertHTMLNotEqual(
  232. '<p><span>Hello</span><span>World</span></p>',
  233. '<p><span>Hello</span>World</p>')
  234. self.assertHTMLNotEqual(
  235. '<p><span>Hello</span>World</p>',
  236. '<p><span>Hello</span><span>World</span></p>')
  237. def test_attributes(self):
  238. self.assertHTMLEqual(
  239. '<input type="text" id="id_name" />',
  240. '<input id="id_name" type="text" />')
  241. self.assertHTMLEqual(
  242. '''<input type='text' id="id_name" />''',
  243. '<input id="id_name" type="text" />')
  244. self.assertHTMLNotEqual(
  245. '<input type="text" id="id_name" />',
  246. '<input type="password" id="id_name" />')
  247. def test_complex_examples(self):
  248. self.assertHTMLEqual(
  249. """<tr><th><label for="id_first_name">First name:</label></th>
  250. <td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>
  251. <tr><th><label for="id_last_name">Last name:</label></th>
  252. <td><input type="text" id="id_last_name" name="last_name" value="Lennon" /></td></tr>
  253. <tr><th><label for="id_birthday">Birthday:</label></th>
  254. <td><input type="text" value="1940-10-9" name="birthday" id="id_birthday" /></td></tr>""",
  255. """
  256. <tr><th>
  257. <label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" />
  258. </td></tr>
  259. <tr><th>
  260. <label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="Lennon" id="id_last_name" />
  261. </td></tr>
  262. <tr><th>
  263. <label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" />
  264. </td></tr>
  265. """)
  266. self.assertHTMLEqual(
  267. """<!DOCTYPE html>
  268. <html>
  269. <head>
  270. <link rel="stylesheet">
  271. <title>Document</title>
  272. <meta attribute="value">
  273. </head>
  274. <body>
  275. <p>
  276. This is a valid paragraph
  277. <div> this is a div AFTER the p</div>
  278. </body>
  279. </html>""", """
  280. <html>
  281. <head>
  282. <link rel="stylesheet">
  283. <title>Document</title>
  284. <meta attribute="value">
  285. </head>
  286. <body>
  287. <p> This is a valid paragraph
  288. <!-- browsers would close the p tag here -->
  289. <div> this is a div AFTER the p</div>
  290. </p> <!-- this is invalid HTML parsing, but it should make no
  291. difference in most cases -->
  292. </body>
  293. </html>""")
  294. def test_html_contain(self):
  295. from django.test.html import parse_html
  296. # equal html contains each other
  297. dom1 = parse_html('<p>foo')
  298. dom2 = parse_html('<p>foo</p>')
  299. self.assertTrue(dom1 in dom2)
  300. self.assertTrue(dom2 in dom1)
  301. dom2 = parse_html('<div><p>foo</p></div>')
  302. self.assertTrue(dom1 in dom2)
  303. self.assertTrue(dom2 not in dom1)
  304. self.assertFalse('<p>foo</p>' in dom2)
  305. self.assertTrue('foo' in dom2)
  306. # when a root element is used ...
  307. dom1 = parse_html('<p>foo</p><p>bar</p>')
  308. dom2 = parse_html('<p>foo</p><p>bar</p>')
  309. self.assertTrue(dom1 in dom2)
  310. dom1 = parse_html('<p>foo</p>')
  311. self.assertTrue(dom1 in dom2)
  312. dom1 = parse_html('<p>bar</p>')
  313. self.assertTrue(dom1 in dom2)
  314. def test_count(self):
  315. from django.test.html import parse_html
  316. # equal html contains each other one time
  317. dom1 = parse_html('<p>foo')
  318. dom2 = parse_html('<p>foo</p>')
  319. self.assertEqual(dom1.count(dom2), 1)
  320. self.assertEqual(dom2.count(dom1), 1)
  321. dom2 = parse_html('<p>foo</p><p>bar</p>')
  322. self.assertEqual(dom2.count(dom1), 1)
  323. dom2 = parse_html('<p>foo foo</p><p>foo</p>')
  324. self.assertEqual(dom2.count('foo'), 3)
  325. dom2 = parse_html('<p class="bar">foo</p>')
  326. self.assertEqual(dom2.count('bar'), 0)
  327. self.assertEqual(dom2.count('class'), 0)
  328. self.assertEqual(dom2.count('p'), 0)
  329. self.assertEqual(dom2.count('o'), 2)
  330. dom2 = parse_html('<p>foo</p><p>foo</p>')
  331. self.assertEqual(dom2.count(dom1), 2)
  332. dom2 = parse_html('<div><p>foo<input type=""></p><p>foo</p></div>')
  333. self.assertEqual(dom2.count(dom1), 1)
  334. dom2 = parse_html('<div><div><p>foo</p></div></div>')
  335. self.assertEqual(dom2.count(dom1), 1)
  336. dom2 = parse_html('<p>foo<p>foo</p></p>')
  337. self.assertEqual(dom2.count(dom1), 1)
  338. dom2 = parse_html('<p>foo<p>bar</p></p>')
  339. self.assertEqual(dom2.count(dom1), 0)
  340. def test_parsing_errors(self):
  341. from django.test.html import HTMLParseError, parse_html
  342. with self.assertRaises(AssertionError):
  343. self.assertHTMLEqual('<p>', '')
  344. with self.assertRaises(AssertionError):
  345. self.assertHTMLEqual('', '<p>')
  346. with self.assertRaises(HTMLParseError):
  347. parse_html('</p>')
  348. def test_contains_html(self):
  349. response = HttpResponse('''<body>
  350. This is a form: <form action="" method="get">
  351. <input type="text" name="Hello" />
  352. </form></body>''')
  353. self.assertNotContains(response, "<input name='Hello' type='text'>")
  354. self.assertContains(response, '<form action="" method="get">')
  355. self.assertContains(response, "<input name='Hello' type='text'>", html=True)
  356. self.assertNotContains(response, '<form action="" method="get">', html=True)
  357. invalid_response = HttpResponse('''<body <bad>>''')
  358. with self.assertRaises(AssertionError):
  359. self.assertContains(invalid_response, '<p></p>')
  360. with self.assertRaises(AssertionError):
  361. self.assertContains(response, '<p "whats" that>')
  362. def test_unicode_handling(self):
  363. from django.http import HttpResponse
  364. response = HttpResponse('<p class="help">Some help text for the title (with unicode ŠĐĆŽćžšđ)</p>')
  365. self.assertContains(response, '<p class="help">Some help text for the title (with unicode ŠĐĆŽćžšđ)</p>', html=True)
  366. class SkippingExtraTests(TestCase):
  367. fixtures = ['should_not_be_loaded.json']
  368. # HACK: This depends on internals of our TestCase subclasses
  369. def __call__(self, result=None):
  370. # Detect fixture loading by counting SQL queries, should be zero
  371. with self.assertNumQueries(0):
  372. super(SkippingExtraTests, self).__call__(result)
  373. @skip("Fixture loading should not be performed for skipped tests.")
  374. def test_fixtures_are_skipped(self):
  375. pass
  376. class AssertRaisesMsgTest(SimpleTestCase):
  377. def test_special_re_chars(self):
  378. """assertRaisesMessage shouldn't interpret RE special chars."""
  379. def func1():
  380. raise ValueError("[.*x+]y?")
  381. self.assertRaisesMessage(ValueError, "[.*x+]y?", func1)
  382. class AssertFieldOutputTests(SimpleTestCase):
  383. def test_assert_field_output(self):
  384. error_invalid = [u'Enter a valid e-mail address.']
  385. self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid})
  386. self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid + [u'Another error']})
  387. self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'Wrong output'}, {'aaa': error_invalid})
  388. self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': [u'Come on, gimme some well formatted data, dude.']})
  389. def test_custom_required_message(self):
  390. class MyCustomField(IntegerField):
  391. default_error_messages = {
  392. 'required': u'This is really required.',
  393. }
  394. self.assertFieldOutput(MyCustomField, {}, {}, empty_value=None)
  395. __test__ = {"API_TEST": r"""
  396. # Some checks of the doctest output normalizer.
  397. # Standard doctests do fairly
  398. >>> from django.utils import simplejson
  399. >>> from django.utils.xmlutils import SimplerXMLGenerator
  400. >>> from StringIO import StringIO
  401. >>> def produce_long():
  402. ... return 42L
  403. >>> def produce_int():
  404. ... return 42
  405. >>> def produce_json():
  406. ... return simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2), 'whiz': 42}])
  407. >>> def produce_xml():
  408. ... stream = StringIO()
  409. ... xml = SimplerXMLGenerator(stream, encoding='utf-8')
  410. ... xml.startDocument()
  411. ... xml.startElement("foo", {"aaa" : "1.0", "bbb": "2.0"})
  412. ... xml.startElement("bar", {"ccc" : "3.0"})
  413. ... xml.characters("Hello")
  414. ... xml.endElement("bar")
  415. ... xml.startElement("whiz", {})
  416. ... xml.characters("Goodbye")
  417. ... xml.endElement("whiz")
  418. ... xml.endElement("foo")
  419. ... xml.endDocument()
  420. ... return stream.getvalue()
  421. >>> def produce_xml_fragment():
  422. ... stream = StringIO()
  423. ... xml = SimplerXMLGenerator(stream, encoding='utf-8')
  424. ... xml.startElement("foo", {"aaa": "1.0", "bbb": "2.0"})
  425. ... xml.characters("Hello")
  426. ... xml.endElement("foo")
  427. ... xml.startElement("bar", {"ccc": "3.0", "ddd": "4.0"})
  428. ... xml.endElement("bar")
  429. ... return stream.getvalue()
  430. # Long values are normalized and are comparable to normal integers ...
  431. >>> produce_long()
  432. 42
  433. # ... and vice versa
  434. >>> produce_int()
  435. 42L
  436. # JSON output is normalized for field order, so it doesn't matter
  437. # which order json dictionary attributes are listed in output
  438. >>> produce_json()
  439. '["foo", {"bar": ["baz", null, 1.0, 2], "whiz": 42}]'
  440. >>> produce_json()
  441. '["foo", {"whiz": 42, "bar": ["baz", null, 1.0, 2]}]'
  442. # XML output is normalized for attribute order, so it doesn't matter
  443. # which order XML element attributes are listed in output
  444. >>> produce_xml()
  445. '<?xml version="1.0" encoding="UTF-8"?>\n<foo aaa="1.0" bbb="2.0"><bar ccc="3.0">Hello</bar><whiz>Goodbye</whiz></foo>'
  446. >>> produce_xml()
  447. '<?xml version="1.0" encoding="UTF-8"?>\n<foo bbb="2.0" aaa="1.0"><bar ccc="3.0">Hello</bar><whiz>Goodbye</whiz></foo>'
  448. >>> produce_xml_fragment()
  449. '<foo aaa="1.0" bbb="2.0">Hello</foo><bar ccc="3.0" ddd="4.0"></bar>'
  450. >>> produce_xml_fragment()
  451. '<foo bbb="2.0" aaa="1.0">Hello</foo><bar ddd="4.0" ccc="3.0"></bar>'
  452. """}