test_gzip_cache.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # -*- coding: utf-8 -*-
  2. '''Core plugins unit tests'''
  3. import os
  4. import tempfile
  5. import unittest
  6. import time
  7. from contextlib import contextmanager
  8. from tempfile import mkdtemp
  9. from shutil import rmtree
  10. from hashlib import md5
  11. import gzip_cache
  12. @contextmanager
  13. def temporary_folder():
  14. """creates a temporary folder, return it and delete it afterwards.
  15. This allows to do something like this in tests:
  16. >>> with temporary_folder() as d:
  17. # do whatever you want
  18. """
  19. tempdir = mkdtemp()
  20. try:
  21. yield tempdir
  22. finally:
  23. rmtree(tempdir)
  24. class TestGzipCache(unittest.TestCase):
  25. def test_should_compress(self):
  26. # Some filetypes should compress and others shouldn't.
  27. self.assertTrue(gzip_cache.should_compress('foo.html'))
  28. self.assertTrue(gzip_cache.should_compress('bar.css'))
  29. self.assertTrue(gzip_cache.should_compress('baz.js'))
  30. self.assertTrue(gzip_cache.should_compress('foo.txt'))
  31. self.assertFalse(gzip_cache.should_compress('foo.gz'))
  32. self.assertFalse(gzip_cache.should_compress('bar.png'))
  33. self.assertFalse(gzip_cache.should_compress('baz.mp3'))
  34. self.assertFalse(gzip_cache.should_compress('foo.mov'))
  35. def test_creates_gzip_file(self):
  36. # A file matching the input filename with a .gz extension is created.
  37. # The plugin walks over the output content after the finalized signal
  38. # so it is safe to assume that the file exists (otherwise walk would
  39. # not report it). Therefore, create a dummy file to use.
  40. with temporary_folder() as tempdir:
  41. _, a_html_filename = tempfile.mkstemp(suffix='.html', dir=tempdir)
  42. gzip_cache.create_gzip_file(a_html_filename)
  43. self.assertTrue(os.path.exists(a_html_filename + '.gz'))
  44. def test_creates_same_gzip_file(self):
  45. # Should create the same gzip file from the same contents.
  46. # gzip will create a slightly different file because it includes
  47. # a timestamp in the compressed file by default. This can cause
  48. # problems for some caching strategies.
  49. with temporary_folder() as tempdir:
  50. _, a_html_filename = tempfile.mkstemp(suffix='.html', dir=tempdir)
  51. a_gz_filename = a_html_filename + '.gz'
  52. gzip_cache.create_gzip_file(a_html_filename)
  53. gzip_hash = get_md5(a_gz_filename)
  54. time.sleep(1)
  55. gzip_cache.create_gzip_file(a_html_filename)
  56. self.assertEqual(gzip_hash, get_md5(a_gz_filename))
  57. def get_md5(filepath):
  58. with open(filepath, 'rb') as fh:
  59. return md5(fh.read()).hexdigest()