图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.0 KiB

  1. """
  2. This module adds context manager for temporary files generated by the tests.
  3. """
  4. import shutil
  5. import os
  6. class TmpFileManager:
  7. """
  8. A class to track record of every temporary files created by the tests.
  9. """
  10. tmp_files = set('')
  11. tmp_folders = set('')
  12. @classmethod
  13. def tmp_file(cls, name=''):
  14. cls.tmp_files.add(name)
  15. return name
  16. @classmethod
  17. def tmp_folder(cls, name=''):
  18. cls.tmp_folders.add(name)
  19. return name
  20. @classmethod
  21. def cleanup(cls):
  22. while cls.tmp_files:
  23. file = cls.tmp_files.pop()
  24. if os.path.isfile(file):
  25. os.remove(file)
  26. while cls.tmp_folders:
  27. folder = cls.tmp_folders.pop()
  28. shutil.rmtree(folder)
  29. def cleanup_tmp_files(test_func):
  30. """
  31. A decorator to help test codes remove temporary files after the tests.
  32. """
  33. def wrapper_function():
  34. try:
  35. test_func()
  36. finally:
  37. TmpFileManager.cleanup()
  38. return wrapper_function