test.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """Helpers for testing webassets.
  2. This is included in the webassets package because it is useful for testing
  3. external libraries that use webassets (like the flask-assets wrapper).
  4. """
  5. from __future__ import print_function
  6. import tempfile
  7. import shutil
  8. import os
  9. from os import path
  10. import time
  11. from webassets import Environment, Bundle
  12. from webassets.six.moves import map
  13. from webassets.six.moves import zip
  14. __all__ = ('TempDirHelper', 'TempEnvironmentHelper',)
  15. class TempDirHelper(object):
  16. """Base-class for tests which provides a temporary directory
  17. (which is properly deleted after the test is done), and various
  18. helper methods to do filesystem operations within that directory.
  19. """
  20. default_files = {}
  21. def setup(self):
  22. self._tempdir_created = tempfile.mkdtemp()
  23. self.create_files(self.default_files)
  24. def teardown(self):
  25. shutil.rmtree(self._tempdir_created)
  26. def __enter__(self):
  27. self.setup()
  28. return self
  29. def __exit__(self, type, value, traceback):
  30. self.teardown()
  31. @property
  32. def tempdir(self):
  33. # Use a read-only property here, so the user is
  34. # less likely to modify the attribute, and have
  35. # his data deleted on teardown.
  36. return self._tempdir_created
  37. def create_files(self, files):
  38. """Helper that allows to quickly create a bunch of files in
  39. the media directory of the current test run.
  40. """
  41. import codecs
  42. # Allow passing a list of filenames to create empty files
  43. if not hasattr(files, 'items'):
  44. files = dict(map(lambda n: (n, ''), files))
  45. for name, data in files.items():
  46. dirs = path.dirname(self.path(name))
  47. if not path.exists(dirs):
  48. os.makedirs(dirs)
  49. f = codecs.open(self.path(name), 'w', 'utf-8')
  50. f.write(data)
  51. f.close()
  52. def create_directories(self, *dirs):
  53. """Helper to create directories within the media directory
  54. of the current test's environment.
  55. """
  56. result = []
  57. for dir in dirs:
  58. full_path = self.path(dir)
  59. result.append(full_path)
  60. os.makedirs(full_path)
  61. return result
  62. def exists(self, name):
  63. """Ensure the given file exists within the current test run's
  64. media directory.
  65. """
  66. return path.exists(self.path(name))
  67. def get(self, name):
  68. """Return the given file's contents.
  69. """
  70. with open(self.path(name)) as f:
  71. r = f.read()
  72. print(repr(r))
  73. return r
  74. def unlink(self, name):
  75. os.unlink(self.path(name))
  76. def path(self, name):
  77. """Return the given file's full path."""
  78. return path.join(self._tempdir_created, name)
  79. def setmtime(self, *files, **kwargs):
  80. """Set the mtime of the given files. Useful helper when
  81. needing to test things like the timestamp updater.
  82. Specify ``mtime`` as a keyword argument, or time.time()
  83. will automatically be used. Returns the mtime used.
  84. Specify ``mod`` as a keyword argument, and the modifier
  85. will be added to the ``mtime`` used.
  86. """
  87. mtime = kwargs.pop('mtime', time.time())
  88. mtime += kwargs.pop('mod', 0)
  89. assert not kwargs, "Unsupported kwargs: %s" % ', '.join(kwargs.keys())
  90. for f in files:
  91. os.utime(self.path(f), (mtime, mtime))
  92. return mtime
  93. def p(self, *files):
  94. """Print the contents of the given files to stdout; useful
  95. for some quick debugging.
  96. """
  97. if not files:
  98. files = ['out'] # This is a often used output filename
  99. for f in files:
  100. content = self.get(f)
  101. print(f)
  102. print("-" * len(f))
  103. print(repr(content))
  104. print(content)
  105. print()
  106. class TempEnvironmentHelper(TempDirHelper):
  107. """Base-class for tests which provides a pre-created
  108. environment, based in a temporary directory, and utility
  109. methods to do filesystem operations within that directory.
  110. """
  111. default_files = {'in1': 'A', 'in2': 'B', 'in3': 'C', 'in4': 'D'}
  112. def setup(self):
  113. TempDirHelper.setup(self)
  114. self.env = self._create_environment()
  115. # Unless we explicitly test it, we don't want to use the cache
  116. # during testing.
  117. self.env.cache = False
  118. self.env.manifest = False
  119. def _create_environment(self):
  120. return Environment(self._tempdir_created, '')
  121. def mkbundle(self, *a, **kw):
  122. b = Bundle(*a, **kw)
  123. b.env = self.env
  124. return b