tests.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. from __future__ import with_statement
  2. from difflib import SequenceMatcher
  3. import os
  4. from unittest import TestCase
  5. import sys
  6. import django
  7. from django import template
  8. from django.conf import settings
  9. from django.template.loader import render_to_string
  10. import pep8
  11. from sekizai.context import SekizaiContext
  12. from sekizai.helpers import get_namespaces
  13. from sekizai.helpers import get_varname
  14. from sekizai.helpers import validate_template
  15. from sekizai.helpers import Watcher
  16. from sekizai.templatetags.sekizai_tags import import_processor
  17. from sekizai.templatetags.sekizai_tags import validate_context
  18. try:
  19. unicode_compat = unicode
  20. except NameError:
  21. unicode_compat = str
  22. try:
  23. from io import StringIO
  24. except ImportError:
  25. from StringIO import StringIO
  26. def null_processor(context, data, namespace):
  27. return ''
  28. def namespace_processor(context, data, namespace):
  29. return namespace
  30. class SettingsOverride(object):
  31. """
  32. Overrides Django settings within a context and resets them to their inital
  33. values on exit.
  34. Example:
  35. with SettingsOverride(DEBUG=True):
  36. # do something
  37. """
  38. class NULL:
  39. pass
  40. def __init__(self, **overrides):
  41. self.overrides = overrides
  42. def __enter__(self):
  43. self.old = {}
  44. for key, value in self.overrides.items():
  45. self.old[key] = getattr(settings, key, self.NULL)
  46. setattr(settings, key, value)
  47. def __exit__(self, type, value, traceback):
  48. for key, value in self.old.items():
  49. if value is self.NULL:
  50. delattr(settings, key)
  51. else:
  52. setattr(settings, key, value)
  53. class CaptureStdout(object):
  54. """
  55. Overrides sys.stdout with a StringIO stream.
  56. """
  57. def __init__(self):
  58. self.old = None
  59. def __enter__(self):
  60. self.old = sys.stdout
  61. new = sys.stdout = StringIO()
  62. return new
  63. def __exit__(self, exc_type, exc_val, exc_tb):
  64. sys.stdout = self.old
  65. class Match(tuple): # pragma: no cover
  66. @property
  67. def a(self):
  68. return self[0]
  69. @property
  70. def b(self):
  71. return self[1]
  72. @property
  73. def size(self):
  74. return self[2]
  75. def _backwards_compat_match(thing): # pragma: no cover
  76. if isinstance(thing, tuple):
  77. return Match(thing)
  78. return thing
  79. class BitDiffResult(object):
  80. def __init__(self, status, message):
  81. self.status = status
  82. self.message = message
  83. class BitDiff(object):
  84. """
  85. Visual aid for failing tests
  86. """
  87. def __init__(self, expected):
  88. self.expected = [repr(unicode_compat(bit)) for bit in expected]
  89. def test(self, result):
  90. result = [repr(unicode_compat(bit)) for bit in result]
  91. if self.expected == result:
  92. return BitDiffResult(True, "success")
  93. else: # pragma: no cover
  94. longest = max(
  95. [len(x) for x in self.expected] +
  96. [len(x) for x in result] +
  97. [len('Expected')]
  98. )
  99. sm = SequenceMatcher()
  100. sm.set_seqs(self.expected, result)
  101. matches = sm.get_matching_blocks()
  102. lasta = 0
  103. lastb = 0
  104. data = []
  105. for match in [_backwards_compat_match(match) for match in matches]:
  106. unmatcheda = self.expected[lasta:match.a]
  107. unmatchedb = result[lastb:match.b]
  108. unmatchedlen = max([len(unmatcheda), len(unmatchedb)])
  109. unmatcheda += ['' for x in range(unmatchedlen)]
  110. unmatchedb += ['' for x in range(unmatchedlen)]
  111. for i in range(unmatchedlen):
  112. data.append((False, unmatcheda[i], unmatchedb[i]))
  113. for i in range(match.size):
  114. data.append((
  115. True, self.expected[match.a + i], result[match.b + i]
  116. ))
  117. lasta = match.a + match.size
  118. lastb = match.b + match.size
  119. padlen = (longest - len('Expected'))
  120. padding = ' ' * padlen
  121. line1 = '-' * padlen
  122. line2 = '-' * (longest - len('Result'))
  123. msg = '\nExpected%s | | Result' % padding
  124. msg += '\n--------%s-|---|-------%s' % (line1, line2)
  125. for success, a, b in data:
  126. pad = ' ' * (longest - len(a))
  127. if success:
  128. msg += '\n%s%s | | %s' % (a, pad, b)
  129. else:
  130. msg += '\n%s%s | ! | %s' % (a, pad, b)
  131. return BitDiffResult(False, msg)
  132. def update_template_debug(debug=True):
  133. """
  134. Helper method for updating the template debug option based on
  135. the django version. Use the results of this function as the context.
  136. :return: SettingsOverride object
  137. """
  138. if django.VERSION[0] == 1 and django.VERSION[1] < 8:
  139. return SettingsOverride(TEMPLATE_DEBUG=debug)
  140. else:
  141. # Create our overridden template settings with debug turned off.
  142. templates_override = settings.TEMPLATES
  143. templates_override[0]['OPTIONS'].update({
  144. 'debug': debug
  145. })
  146. from django.template.engine import Engine
  147. # Engine gets created based on template settings initial value so
  148. # changing the settings after the fact won't update, so do it
  149. # manually. Necessary when testing validate_context
  150. # with render method and want debug off.
  151. Engine.get_default().debug = debug
  152. return SettingsOverride(TEMPLATES=templates_override)
  153. class SekizaiTestCase(TestCase):
  154. @classmethod
  155. def setUpClass(cls):
  156. cls._template_dirs = settings.TEMPLATE_DIRS
  157. template_dir = os.path.join(
  158. os.path.dirname(__file__),
  159. 'test_templates'
  160. )
  161. settings.TEMPLATE_DIRS = list(cls._template_dirs) + [template_dir]
  162. @classmethod
  163. def tearDownClass(cls):
  164. settings.TEMPLATE_DIRS = cls._template_dirs
  165. def _render(self, tpl, ctx=None, ctxclass=SekizaiContext):
  166. ctx = ctx or {}
  167. return render_to_string(tpl, ctxclass(ctx))
  168. def _get_bits(self, tpl, ctx=None, ctxclass=SekizaiContext):
  169. ctx = ctx or {}
  170. rendered = self._render(tpl, ctx, ctxclass)
  171. bits = [
  172. bit for bit in [bit.strip('\n')
  173. for bit in rendered.split('\n')] if bit
  174. ]
  175. return bits, rendered
  176. def _test(self, tpl, res, ctx=None, ctxclass=SekizaiContext):
  177. """
  178. Helper method to render template and compare it's bits
  179. """
  180. ctx = ctx or {}
  181. bits, rendered = self._get_bits(tpl, ctx, ctxclass)
  182. differ = BitDiff(res)
  183. result = differ.test(bits)
  184. self.assertTrue(result.status, result.message)
  185. return rendered
  186. def test_pep8(self):
  187. sekizai_dir = os.path.dirname(os.path.abspath(__file__))
  188. pep8style = pep8.StyleGuide()
  189. with CaptureStdout() as stdout:
  190. result = pep8style.check_files([sekizai_dir])
  191. errors = stdout.getvalue()
  192. self.assertEqual(
  193. result.total_errors, 0,
  194. "Code not PEP8 compliant:\n{0}".format(errors)
  195. )
  196. def test_basic_dual_block(self):
  197. """
  198. Basic dual block testing
  199. """
  200. bits = [
  201. 'my css file', 'some content', 'more content', 'final content',
  202. 'my js file'
  203. ]
  204. self._test('basic.html', bits)
  205. def test_named_endaddtoblock(self):
  206. """
  207. Testing with named endaddblock
  208. """
  209. bits = ["mycontent"]
  210. self._test('named_end.html', bits)
  211. def test_eat_content_before_render_block(self):
  212. """
  213. Testing that content get's eaten if no render_blocks is available
  214. """
  215. bits = ["mycontent"]
  216. self._test("eat.html", bits)
  217. def test_sekizai_context_required(self):
  218. """
  219. Test that the template tags properly fail if not used with either
  220. SekizaiContext or the context processor.
  221. """
  222. self.assertRaises(
  223. template.TemplateSyntaxError,
  224. self._render, 'basic.html', {}, template.Context
  225. )
  226. def test_complex_template_inheritance(self):
  227. """
  228. Test that (complex) template inheritances work properly
  229. """
  230. bits = [
  231. "head start",
  232. "some css file",
  233. "head end",
  234. "include start",
  235. "inc add js",
  236. "include end",
  237. "block main start",
  238. "extinc",
  239. "block main end",
  240. "body pre-end",
  241. "inc js file",
  242. "body end"
  243. ]
  244. self._test("inherit/extend.html", bits)
  245. """
  246. Test that blocks (and block.super) work properly with sekizai
  247. """
  248. bits = [
  249. "head start",
  250. "visible css file",
  251. "some css file",
  252. "head end",
  253. "include start",
  254. "inc add js",
  255. "include end",
  256. "block main start",
  257. "block main base contents",
  258. "more contents",
  259. "block main end",
  260. "body pre-end",
  261. "inc js file",
  262. "body end"
  263. ]
  264. self._test("inherit/super_blocks.html", bits)
  265. def test_namespace_isolation(self):
  266. """
  267. Tests that namespace isolation works
  268. """
  269. bits = ["the same file", "the same file"]
  270. self._test('namespaces.html', bits)
  271. def test_variable_namespaces(self):
  272. """
  273. Tests variables and filtered variables as block names.
  274. """
  275. bits = ["file one", "file two"]
  276. self._test('variables.html', bits, {'blockname': 'one'})
  277. def test_invalid_addtoblock(self):
  278. """
  279. Tests that template syntax errors are raised properly in templates
  280. rendered by sekizai tags
  281. """
  282. self.assertRaises(
  283. template.TemplateSyntaxError,
  284. self._render, 'errors/failadd.html'
  285. )
  286. def test_invalid_renderblock(self):
  287. self.assertRaises(
  288. template.TemplateSyntaxError,
  289. self._render, 'errors/failrender.html'
  290. )
  291. def test_invalid_include(self):
  292. self.assertRaises(
  293. template.TemplateSyntaxError,
  294. self._render, 'errors/failinc.html'
  295. )
  296. def test_invalid_basetemplate(self):
  297. self.assertRaises(
  298. template.TemplateSyntaxError,
  299. self._render, 'errors/failbase.html'
  300. )
  301. def test_invalid_basetemplate_two(self):
  302. self.assertRaises(
  303. template.TemplateSyntaxError,
  304. self._render, 'errors/failbase2.html'
  305. )
  306. def test_with_data(self):
  307. """
  308. Tests the with_data/add_data tags.
  309. """
  310. bits = ["1", "2"]
  311. self._test('with_data.html', bits)
  312. def test_easy_inheritance(self):
  313. self.assertEqual('content', self._render("easy_inherit.html").strip())
  314. def test_validate_context(self):
  315. sekizai_ctx = SekizaiContext()
  316. django_ctx = template.Context()
  317. self.assertRaises(
  318. template.TemplateSyntaxError,
  319. validate_context, django_ctx
  320. )
  321. self.assertEqual(validate_context(sekizai_ctx), True)
  322. with update_template_debug(debug=False):
  323. self.assertEqual(validate_context(django_ctx), False)
  324. self.assertEqual(validate_context(sekizai_ctx), True)
  325. bits = ['some content', 'more content', 'final content']
  326. self._test('basic.html', bits, ctxclass=template.Context)
  327. def test_post_processor_null(self):
  328. bits = ['header', 'footer']
  329. self._test('processors/null.html', bits)
  330. def test_post_processor_namespace(self):
  331. bits = ['header', 'footer', 'js']
  332. self._test('processors/namespace.html', bits)
  333. def test_import_processor_failfast(self):
  334. self.assertRaises(TypeError, import_processor, 'invalidpath')
  335. def test_unique(self):
  336. bits = ['unique data']
  337. self._test('unique.html', bits)
  338. def test_strip(self):
  339. tpl = template.Template("""
  340. {% load sekizai_tags %}
  341. {% addtoblock 'a' strip %} test{% endaddtoblock %}
  342. {% addtoblock 'a' strip %}test {% endaddtoblock %}
  343. {% render_block 'a' %}""")
  344. context = SekizaiContext()
  345. output = tpl.render(context)
  346. self.assertEqual(output.count('test'), 1, output)
  347. def test_addtoblock_processor_null(self):
  348. bits = ['header', 'footer']
  349. self._test('processors/addtoblock_null.html', bits)
  350. def test_addtoblock_processor_namespace(self):
  351. bits = ['header', 'footer', 'js']
  352. self._test('processors/addtoblock_namespace.html', bits)
  353. class HelperTests(TestCase):
  354. def test_validate_template_js_css(self):
  355. self.assertTrue(validate_template('basic.html', ['js', 'css']))
  356. def test_validate_template_js(self):
  357. self.assertTrue(validate_template('basic.html', ['js']))
  358. def test_validate_template_css(self):
  359. self.assertTrue(validate_template('basic.html', ['css']))
  360. def test_validate_template_empty(self):
  361. self.assertTrue(validate_template('basic.html', []))
  362. def test_validate_template_notfound(self):
  363. self.assertFalse(validate_template('basic.html', ['notfound']))
  364. def test_get_namespaces_easy_inherit(self):
  365. self.assertEqual(get_namespaces('easy_inherit.html'), ['css'])
  366. def test_get_namespaces_chain_inherit(self):
  367. self.assertEqual(get_namespaces('inherit/chain.html'), ['css', 'js'])
  368. def test_get_namespaces_space_chain_inherit(self):
  369. self.assertEqual(
  370. get_namespaces('inherit/spacechain.html'),
  371. ['css', 'js']
  372. )
  373. def test_get_namespaces_var_inherit(self):
  374. self.assertEqual(get_namespaces('inherit/varchain.html'), [])
  375. def test_get_namespaces_sub_var_inherit(self):
  376. self.assertEqual(get_namespaces('inherit/subvarchain.html'), [])
  377. def test_get_namespaces_null_ext(self):
  378. self.assertEqual(get_namespaces('inherit/nullext.html'), [])
  379. def test_deactivate_validate_template(self):
  380. with SettingsOverride(SEKIZAI_IGNORE_VALIDATION=True):
  381. self.assertTrue(validate_template('basic.html', ['js', 'css']))
  382. self.assertTrue(validate_template('basic.html', ['js']))
  383. self.assertTrue(validate_template('basic.html', ['css']))
  384. self.assertTrue(validate_template('basic.html', []))
  385. self.assertTrue(validate_template('basic.html', ['notfound']))
  386. def test_watcher_add_namespace(self):
  387. context = SekizaiContext()
  388. watcher = Watcher(context)
  389. varname = get_varname()
  390. context[varname]['key'].append('value')
  391. changes = watcher.get_changes()
  392. self.assertEqual(changes, {'key': ['value']})
  393. def test_watcher_add_data(self):
  394. context = SekizaiContext()
  395. varname = get_varname()
  396. context[varname]['key'].append('value')
  397. watcher = Watcher(context)
  398. context[varname]['key'].append('value2')
  399. changes = watcher.get_changes()
  400. self.assertEqual(changes, {'key': ['value2']})