PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/compressor/tests/test_base.py

http://github.com/jezdez/django_compressor
Python | 456 lines | 447 code | 9 blank | 0 comment | 1 complexity | 5d4b26649a97bce2c24807d571e3497e MD5 | raw file
Possible License(s): Apache-2.0
  1. import os
  2. import re
  3. import sys
  4. from tempfile import mkdtemp
  5. from shutil import rmtree, copytree
  6. from bs4 import BeautifulSoup
  7. from django.core.cache.backends import locmem
  8. from django.test import SimpleTestCase
  9. from django.test.utils import override_settings
  10. from compressor import cache as cachemod
  11. from compressor.base import SOURCE_FILE, SOURCE_HUNK
  12. from compressor.cache import get_cachekey, get_precompiler_cachekey, get_hexdigest
  13. from compressor.conf import settings
  14. from compressor.css import CssCompressor
  15. from compressor.exceptions import FilterDoesNotExist, FilterError
  16. from compressor.js import JsCompressor
  17. from compressor.storage import DefaultStorage
  18. def make_soup(markup):
  19. return BeautifulSoup(markup, "html.parser")
  20. def css_tag(href, **kwargs):
  21. rendered_attrs = ''.join([' %s="%s"' % (k, v) for k, v in kwargs.items()])
  22. template = '<link rel="stylesheet" href="%s" type="text/css"%s>'
  23. return template % (href, rendered_attrs)
  24. class TestPrecompiler(object):
  25. """A filter whose output is always the string 'OUTPUT' """
  26. def __init__(self, content, attrs, filter_type=None, filename=None,
  27. charset=None):
  28. pass
  29. def input(self, **kwargs):
  30. return 'OUTPUT'
  31. class PassthroughPrecompiler(object):
  32. """A filter whose outputs the input unmodified """
  33. def __init__(self, content, attrs, filter_type=None, filename=None,
  34. charset=None):
  35. self.content = content
  36. def input(self, **kwargs):
  37. return self.content
  38. test_dir = os.path.abspath(os.path.join(os.path.dirname(__file__)))
  39. class PrecompilerAndAbsoluteFilterTestCase(SimpleTestCase):
  40. def setUp(self):
  41. self.html_orig = '<link rel="stylesheet" href="/static/css/relative_url.css" type="text/css" />'
  42. self.html_auto_close_removed = '<link rel="stylesheet" href="/static/css/relative_url.css" type="text/css">'
  43. self.html_link_to_precompiled_css = '<link rel="stylesheet" href="/static/CACHE/css/relative_url.e8602322bfa6.css" type="text/css">'
  44. self.html_link_to_absolutized_css = '<link rel="stylesheet" href="/static/CACHE/css/relative_url.376db5682982.css" type="text/css">'
  45. self.css_orig = "p { background: url('../img/python.png'); }" # content of relative_url.css
  46. self.css_absolutized = "p { background: url('/static/img/python.png?ccb38978f900'); }"
  47. def helper(self, enabled, use_precompiler, use_absolute_filter, expected_output):
  48. precompiler = (('text/css', 'compressor.tests.test_base.PassthroughPrecompiler'),) if use_precompiler else ()
  49. filters = ('compressor.filters.css_default.CssAbsoluteFilter',) if use_absolute_filter else ()
  50. with self.settings(COMPRESS_ENABLED=enabled,
  51. COMPRESS_PRECOMPILERS=precompiler,
  52. COMPRESS_FILTERS={'css': filters}):
  53. css_node = CssCompressor('css', self.html_orig)
  54. output = list(css_node.hunks())[0]
  55. self.assertEqual(output, expected_output)
  56. @override_settings(COMPRESS_CSS_HASHING_METHOD="content")
  57. def test_precompiler_enables_absolute(self):
  58. """
  59. Tests whether specifying a precompiler also runs the CssAbsoluteFilter even if
  60. compression is disabled, but only if the CssAbsoluteFilter is actually contained
  61. in the filters setting.
  62. While at it, ensure that everything runs as expected when compression is enabled.
  63. """
  64. self.helper(enabled=False, use_precompiler=False, use_absolute_filter=False, expected_output=self.html_auto_close_removed)
  65. self.helper(enabled=False, use_precompiler=False, use_absolute_filter=True, expected_output=self.html_auto_close_removed)
  66. self.helper(enabled=False, use_precompiler=True, use_absolute_filter=False, expected_output=self.html_link_to_precompiled_css)
  67. self.helper(enabled=False, use_precompiler=True, use_absolute_filter=True, expected_output=self.html_link_to_absolutized_css)
  68. self.helper(enabled=True, use_precompiler=False, use_absolute_filter=False, expected_output=self.css_orig)
  69. self.helper(enabled=True, use_precompiler=False, use_absolute_filter=True, expected_output=self.css_absolutized)
  70. self.helper(enabled=True, use_precompiler=True, use_absolute_filter=False, expected_output=self.css_orig)
  71. self.helper(enabled=True, use_precompiler=True, use_absolute_filter=True, expected_output=self.css_absolutized)
  72. @override_settings(
  73. COMPRESS_ENABLED=True,
  74. COMPRESS_PRECOMPILERS=(),
  75. COMPRESS_DEBUG_TOGGLE='nocompress',
  76. )
  77. class CompressorTestCase(SimpleTestCase):
  78. def setUp(self):
  79. self.css = """\
  80. <link rel="stylesheet" href="/static/css/one.css" type="text/css">
  81. <style type="text/css">p { border:5px solid green;}</style>
  82. <link rel="stylesheet" href="/static/css/two.css" type="text/css">"""
  83. self.css_node = CssCompressor('css', self.css)
  84. self.js = """\
  85. <script src="/static/js/one.js" type="text/javascript"></script>
  86. <script type="text/javascript">obj.value = "value";</script>"""
  87. self.js_node = JsCompressor('js', self.js)
  88. def assertEqualCollapsed(self, a, b):
  89. """
  90. assertEqual with internal newlines collapsed to single, and
  91. trailing whitespace removed.
  92. """
  93. def collapse(s):
  94. return re.sub(r'\n+', '\n', s).rstrip()
  95. self.assertEqual(collapse(a), collapse(b))
  96. def assertEqualSplits(self, a, b):
  97. """
  98. assertEqual for splits, particularly ignoring the presence of
  99. a trailing newline on the content.
  100. """
  101. def mangle(split):
  102. return [(x[0], x[1], x[2], x[3].rstrip()) for x in split]
  103. self.assertEqual(mangle(a), mangle(b))
  104. def test_css_split(self):
  105. out = [
  106. (
  107. SOURCE_FILE,
  108. os.path.join(settings.COMPRESS_ROOT, 'css', 'one.css'),
  109. 'css/one.css', '<link rel="stylesheet" href="/static/css/one.css" type="text/css">',
  110. ),
  111. (
  112. SOURCE_HUNK,
  113. 'p { border:5px solid green;}',
  114. None,
  115. '<style type="text/css">p { border:5px solid green;}</style>',
  116. ),
  117. (
  118. SOURCE_FILE,
  119. os.path.join(settings.COMPRESS_ROOT, 'css', 'two.css'),
  120. 'css/two.css',
  121. '<link rel="stylesheet" href="/static/css/two.css" type="text/css">',
  122. ),
  123. ]
  124. split = self.css_node.split_contents()
  125. split = [(x[0], x[1], x[2], self.css_node.parser.elem_str(x[3])) for x in split]
  126. self.assertEqualSplits(split, out)
  127. def test_css_hunks(self):
  128. out = ['body { background:#990; }', 'p { border:5px solid green;}', 'body { color:#fff; }']
  129. self.assertEqual(out, list(self.css_node.hunks()))
  130. def test_css_output(self):
  131. out = 'body { background:#990; }\np { border:5px solid green;}\nbody { color:#fff; }'
  132. hunks = '\n'.join([h for h in self.css_node.hunks()])
  133. self.assertEqual(out, hunks)
  134. def test_css_output_with_bom_input(self):
  135. out = 'body { background:#990; }\n.compress-test {color: red;}'
  136. css = ("""<link rel="stylesheet" href="/static/css/one.css" type="text/css" />
  137. <link rel="stylesheet" href="/static/css/utf-8_with-BOM.css" type="text/css" />""")
  138. css_node_with_bom = CssCompressor('css', css)
  139. hunks = '\n'.join([h for h in css_node_with_bom.hunks()])
  140. self.assertEqual(out, hunks)
  141. def test_css_mtimes(self):
  142. is_date = re.compile(r'^\d{10}[\.\d]+$')
  143. for date in self.css_node.mtimes:
  144. self.assertTrue(is_date.match(str(float(date))),
  145. "mtimes is returning something that doesn't look like a date: %s" % date)
  146. @override_settings(COMPRESS_ENABLED=False)
  147. def test_css_return_if_off(self):
  148. self.assertEqualCollapsed(self.css, self.css_node.output())
  149. def test_cachekey(self):
  150. is_cachekey = re.compile(r'\w{12}')
  151. self.assertTrue(is_cachekey.match(self.css_node.cachekey),
  152. r"cachekey is returning something that doesn't look like r'\w{12}'")
  153. def test_css_return_if_on(self):
  154. output = css_tag('/static/CACHE/css/58a8c0714e59.css')
  155. self.assertEqual(output, self.css_node.output().strip())
  156. def test_css_preload_output(self):
  157. # this needs to have the same hash as in the test above
  158. out = '<link rel="preload" href="/static/CACHE/css/58a8c0714e59.css" as="style" />'
  159. self.assertEqual(out, self.css_node.output(mode="preload"))
  160. def test_js_split(self):
  161. out = [
  162. (
  163. SOURCE_FILE,
  164. os.path.join(settings.COMPRESS_ROOT, 'js', 'one.js'),
  165. 'js/one.js',
  166. '<script src="/static/js/one.js" type="text/javascript"></script>',
  167. ),
  168. (
  169. SOURCE_HUNK,
  170. 'obj.value = "value";',
  171. None,
  172. '<script type="text/javascript">obj.value = "value";</script>',
  173. ),
  174. ]
  175. split = self.js_node.split_contents()
  176. split = [(x[0], x[1], x[2], self.js_node.parser.elem_str(x[3])) for x in split]
  177. self.assertEqualSplits(split, out)
  178. def test_js_hunks(self):
  179. out = ['obj = {};', 'obj.value = "value";']
  180. self.assertEqual(out, list(self.js_node.hunks()))
  181. def test_js_output(self):
  182. out = '<script src="/static/CACHE/js/8a0fed36c317.js"></script>'
  183. self.assertEqual(out, self.js_node.output())
  184. def test_js_preload_output(self):
  185. # this needs to have the same hash as in the test above
  186. out = '<link rel="preload" href="/static/CACHE/js/8a0fed36c317.js" as="script" />'
  187. self.assertEqual(out, self.js_node.output(mode="preload"))
  188. def test_js_override_url(self):
  189. self.js_node.context.update({'url': 'This is not a url, just a text'})
  190. out = '<script src="/static/CACHE/js/8a0fed36c317.js"></script>'
  191. self.assertEqual(out, self.js_node.output())
  192. def test_css_override_url(self):
  193. self.css_node.context.update({'url': 'This is not a url, just a text'})
  194. output = css_tag('/static/CACHE/css/58a8c0714e59.css')
  195. self.assertEqual(output, self.css_node.output().strip())
  196. @override_settings(COMPRESS_PRECOMPILERS=(), COMPRESS_ENABLED=False)
  197. def test_js_return_if_off(self):
  198. self.assertEqualCollapsed(self.js, self.js_node.output())
  199. def test_js_return_if_on(self):
  200. output = '<script src="/static/CACHE/js/8a0fed36c317.js"></script>'
  201. self.assertEqual(output, self.js_node.output())
  202. @override_settings(COMPRESS_OUTPUT_DIR='custom')
  203. def test_custom_output_dir1(self):
  204. output = '<script src="/static/custom/js/8a0fed36c317.js"></script>'
  205. self.assertEqual(output, JsCompressor('js', self.js).output())
  206. @override_settings(COMPRESS_OUTPUT_DIR='')
  207. def test_custom_output_dir2(self):
  208. output = '<script src="/static/js/8a0fed36c317.js"></script>'
  209. self.assertEqual(output, JsCompressor('js', self.js).output())
  210. @override_settings(COMPRESS_OUTPUT_DIR='/custom/nested/')
  211. def test_custom_output_dir3(self):
  212. output = '<script src="/static/custom/nested/js/8a0fed36c317.js"></script>'
  213. self.assertEqual(output, JsCompressor('js', self.js).output())
  214. @override_settings(COMPRESS_PRECOMPILERS=(
  215. ('text/foobar', 'compressor.tests.test_base.TestPrecompiler'),
  216. ), COMPRESS_ENABLED=True)
  217. def test_precompiler_class_used(self):
  218. css = '<style type="text/foobar">p { border:10px solid red;}</style>'
  219. css_node = CssCompressor('css', css)
  220. output = make_soup(css_node.output('inline'))
  221. self.assertEqual(output.text, 'OUTPUT')
  222. @override_settings(COMPRESS_PRECOMPILERS=(
  223. ('text/foobar', 'compressor.tests.test_base.NonexistentFilter'),
  224. ), COMPRESS_ENABLED=True)
  225. def test_nonexistent_precompiler_class_error(self):
  226. css = '<style type="text/foobar">p { border:10px solid red;}</style>'
  227. css_node = CssCompressor('css', css)
  228. self.assertRaises(FilterDoesNotExist, css_node.output, 'inline')
  229. @override_settings(COMPRESS_PRECOMPILERS=(
  230. ('text/foobar', './foo -I ./bar/baz'),
  231. ), COMPRESS_ENABLED=True)
  232. def test_command_with_dot_precompiler(self):
  233. css = '<style type="text/foobar">p { border:10px solid red;}</style>'
  234. css_node = CssCompressor('css', css)
  235. self.assertRaises(FilterError, css_node.output, 'inline')
  236. @override_settings(COMPRESS_PRECOMPILERS=(
  237. ('text/django', 'compressor.filters.template.TemplateFilter'),
  238. ), COMPRESS_ENABLED=True)
  239. def test_template_precompiler(self):
  240. css = '<style type="text/django">p { border:10px solid {% if 1 %}green{% else %}red{% endif %};}</style>'
  241. css_node = CssCompressor('css', css)
  242. output = make_soup(css_node.output('inline'))
  243. self.assertEqual(output.text, 'p { border:10px solid green;}')
  244. class CssMediaTestCase(SimpleTestCase):
  245. def setUp(self):
  246. self.css = """\
  247. <link rel="stylesheet" href="/static/css/one.css" type="text/css" media="screen">
  248. <style type="text/css" media="print">p { border:5px solid green;}</style>
  249. <link rel="stylesheet" href="/static/css/two.css" type="text/css" media="all">
  250. <style type="text/css">h1 { border:5px solid green;}</style>"""
  251. def test_css_output(self):
  252. css_node = CssCompressor('css', self.css)
  253. links = make_soup(css_node.output()).find_all('link')
  254. media = ['screen', 'print', 'all', None]
  255. self.assertEqual(len(links), 4)
  256. self.assertEqual(media, [l.get('media', None) for l in links])
  257. def test_avoid_reordering_css(self):
  258. css = self.css + '<style type="text/css" media="print">p { border:10px solid red;}</style>'
  259. css_node = CssCompressor('css', css)
  260. media = ['screen', 'print', 'all', None, 'print']
  261. links = make_soup(css_node.output()).find_all('link')
  262. self.assertEqual(media, [l.get('media', None) for l in links])
  263. @override_settings(COMPRESS_PRECOMPILERS=(
  264. ('text/foobar', '%s %s {infile} {outfile}' % (sys.executable, os.path.join(test_dir, 'precompiler.py'))),
  265. ), COMPRESS_ENABLED=False)
  266. def test_passthough_when_compress_disabled(self):
  267. css = """\
  268. <link rel="stylesheet" href="/static/css/one.css" type="text/css" media="screen">
  269. <link rel="stylesheet" href="/static/css/two.css" type="text/css" media="screen">
  270. <style type="text/foobar" media="screen">h1 { border:5px solid green;}</style>"""
  271. css_node = CssCompressor('css', css)
  272. output = make_soup(css_node.output()).find_all(['link', 'style'])
  273. self.assertEqual(['/static/css/one.css', '/static/css/two.css', None],
  274. [l.get('href', None) for l in output])
  275. self.assertEqual(['screen', 'screen', 'screen'],
  276. [l.get('media', None) for l in output])
  277. @override_settings(COMPRESS_VERBOSE=True)
  278. class VerboseTestCase(CompressorTestCase):
  279. pass
  280. class CacheBackendTestCase(CompressorTestCase):
  281. def test_correct_backend(self):
  282. from compressor.cache import cache
  283. self.assertEqual(cache.__class__, locmem.LocMemCache)
  284. class JsAsyncDeferTestCase(SimpleTestCase):
  285. def setUp(self):
  286. self.js = """\
  287. <script src="/static/js/one.js" type="text/javascript"></script>
  288. <script src="/static/js/two.js" type="text/javascript" async></script>
  289. <script src="/static/js/three.js" type="text/javascript" defer></script>
  290. <script type="text/javascript">obj.value = "value";</script>
  291. <script src="/static/js/one.js" type="text/javascript" async></script>
  292. <script src="/static/js/two.js" type="text/javascript" async></script>
  293. <script src="/static/js/three.js" type="text/javascript"></script>"""
  294. def test_js_output(self):
  295. def extract_attr(tag):
  296. if tag.has_attr('async'):
  297. return 'async'
  298. if tag.has_attr('defer'):
  299. return 'defer'
  300. js_node = JsCompressor('js', self.js)
  301. output = [None, 'async', 'defer', None, 'async', None]
  302. scripts = make_soup(js_node.output()).find_all('script')
  303. attrs = [extract_attr(s) for s in scripts]
  304. self.assertEqual(output, attrs)
  305. class JSWithParensTestCase(SimpleTestCase):
  306. def setUp(self):
  307. self.js = """
  308. <script src="/static/js/one.js"></script>
  309. <script src="/static/js/two.js"></script>
  310. """
  311. def test_js_content(self):
  312. js_node = JsCompressor('js', self.js)
  313. content = js_node.filter_input()
  314. self.assertEqual(content[0], 'obj = {};;')
  315. self.assertEqual(content[1], 'pollos = {};')
  316. class CacheTestCase(SimpleTestCase):
  317. def setUp(self):
  318. cachemod._cachekey_func = None
  319. def test_get_cachekey_basic(self):
  320. self.assertEqual(get_cachekey("foo"), "django_compressor.foo")
  321. @override_settings(COMPRESS_CACHE_KEY_FUNCTION='.leading.dot')
  322. def test_get_cachekey_leading_dot(self):
  323. self.assertRaises(ImportError, lambda: get_cachekey("foo"))
  324. @override_settings(COMPRESS_CACHE_KEY_FUNCTION='invalid.module')
  325. def test_get_cachekey_invalid_mod(self):
  326. self.assertRaises(ImportError, lambda: get_cachekey("foo"))
  327. def test_get_precompiler_cachekey(self):
  328. try:
  329. get_precompiler_cachekey("asdf", "asdf")
  330. except TypeError:
  331. self.fail("get_precompiler_cachekey raised TypeError unexpectedly")
  332. class CompressorInDebugModeTestCase(SimpleTestCase):
  333. def setUp(self):
  334. self.css = '<link rel="stylesheet" href="/static/css/one.css" type="text/css" />'
  335. self.tmpdir = mkdtemp()
  336. new_static_root = os.path.join(self.tmpdir, "static")
  337. copytree(settings.STATIC_ROOT, new_static_root)
  338. self.override_settings = self.settings(
  339. COMPRESS_ENABLED=True,
  340. COMPRESS_PRECOMPILERS=(),
  341. COMPRESS_DEBUG_TOGGLE='nocompress',
  342. DEBUG=True,
  343. STATIC_ROOT=new_static_root,
  344. COMPRESS_ROOT=new_static_root,
  345. STATICFILES_DIRS=[settings.COMPRESS_ROOT]
  346. )
  347. self.override_settings.__enter__()
  348. def tearDown(self):
  349. rmtree(self.tmpdir)
  350. self.override_settings.__exit__(None, None, None)
  351. def test_filename_in_debug_mode(self):
  352. # In debug mode, compressor should look for files using staticfiles
  353. # finders only, and not look into the global static directory, where
  354. # files can be outdated
  355. css_filename = os.path.join(settings.COMPRESS_ROOT, "css", "one.css")
  356. # Store the hash of the original file's content
  357. with open(css_filename) as f:
  358. css_content = f.read()
  359. hashed = get_hexdigest(css_content, 12)
  360. # Now modify the file in the STATIC_ROOT
  361. test_css_content = "p { font-family: 'test' }"
  362. with open(css_filename, "a") as css:
  363. css.write("\n")
  364. css.write(test_css_content)
  365. # We should generate a link with the hash of the original content, not
  366. # the modified one
  367. expected = '<link rel="stylesheet" href="/static/CACHE/css/%s.css" type="text/css">' % hashed
  368. compressor = CssCompressor('css', self.css)
  369. compressor.storage = DefaultStorage()
  370. output = compressor.output()
  371. self.assertEqual(expected, output)
  372. with open(os.path.join(settings.COMPRESS_ROOT, "CACHE", "css",
  373. "%s.css" % hashed), "r") as f:
  374. result = f.read()
  375. self.assertTrue(test_css_content not in result)