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.

59 lines
1.9 KiB

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