test_path.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import io
  2. import unittest
  3. import importlib_resources as resources
  4. from . import data01
  5. from . import util
  6. class CommonTests(util.CommonTests, unittest.TestCase):
  7. def execute(self, package, path):
  8. with resources.as_file(resources.files(package).joinpath(path)):
  9. pass
  10. class PathTests:
  11. def test_reading(self):
  12. """
  13. Path should be readable.
  14. Test also implicitly verifies the returned object is a pathlib.Path
  15. instance.
  16. """
  17. target = resources.files(self.data) / 'utf-8.file'
  18. with resources.as_file(target) as path:
  19. self.assertTrue(path.name.endswith("utf-8.file"), repr(path))
  20. # pathlib.Path.read_text() was introduced in Python 3.5.
  21. with path.open('r', encoding='utf-8') as file:
  22. text = file.read()
  23. self.assertEqual('Hello, UTF-8 world!\n', text)
  24. class PathDiskTests(PathTests, unittest.TestCase):
  25. data = data01
  26. def test_natural_path(self):
  27. """
  28. Guarantee the internal implementation detail that
  29. file-system-backed resources do not get the tempdir
  30. treatment.
  31. """
  32. target = resources.files(self.data) / 'utf-8.file'
  33. with resources.as_file(target) as path:
  34. assert 'data' in str(path)
  35. class PathMemoryTests(PathTests, unittest.TestCase):
  36. def setUp(self):
  37. file = io.BytesIO(b'Hello, UTF-8 world!\n')
  38. self.addCleanup(file.close)
  39. self.data = util.create_package(
  40. file=file, path=FileNotFoundError("package exists only in memory")
  41. )
  42. self.data.__spec__.origin = None
  43. self.data.__spec__.has_location = False
  44. class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase):
  45. def test_remove_in_context_manager(self):
  46. """
  47. It is not an error if the file that was temporarily stashed on the
  48. file system is removed inside the `with` stanza.
  49. """
  50. target = resources.files(self.data) / 'utf-8.file'
  51. with resources.as_file(target) as path:
  52. path.unlink()
  53. if __name__ == '__main__':
  54. unittest.main()