| 1 |
import io |
| 2 |
import unittest |
| 3 |
|
| 4 |
from importlib import resources |
| 5 |
from . import data01 |
| 6 |
from .resources import util |
| 7 |
|
| 8 |
|
| 9 |
class CommonTests(util.CommonTests, unittest.TestCase): |
| 10 |
def execute(self, package, path): |
| 11 |
with resources.as_file(resources.files(package).joinpath(path)): |
| 12 |
pass |
| 13 |
|
| 14 |
|
| 15 |
class PathTests: |
| 16 |
def test_reading(self): |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
target = resources.files(self.data) / 'utf-8.file' |
| 21 |
with resources.as_file(target) as path: |
| 22 |
self.assertTrue(path.name.endswith("utf-8.file"), repr(path)) |
| 23 |
|
| 24 |
with path.open('r', encoding='utf-8') as file: |
| 25 |
text = file.read() |
| 26 |
self.assertEqual('Hello, UTF-8 world!\n', text) |
| 27 |
|
| 28 |
|
| 29 |
class PathDiskTests(PathTests, unittest.TestCase): |
| 30 |
data = data01 |
| 31 |
|
| 32 |
def test_natural_path(self): |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
target = resources.files(self.data) / 'utf-8.file' |
| 37 |
with resources.as_file(target) as path: |
| 38 |
assert 'data' in str(path) |
| 39 |
|
| 40 |
|
| 41 |
class PathMemoryTests(PathTests, unittest.TestCase): |
| 42 |
def setUp(self): |
| 43 |
file = io.BytesIO(b'Hello, UTF-8 world!\n') |
| 44 |
self.addCleanup(file.close) |
| 45 |
self.data = util.create_package( |
| 46 |
file=file, path=FileNotFoundError("package exists only in memory") |
| 47 |
) |
| 48 |
self.data.__spec__.origin = None |
| 49 |
self.data.__spec__.has_location = False |
| 50 |
|
| 51 |
|
| 52 |
class PathZipTests(PathTests, util.ZipSetup, unittest.TestCase): |
| 53 |
def test_remove_in_context_manager(self): |
| 54 |
|
| 55 |
|
| 56 |
target = resources.files(self.data) / 'utf-8.file' |
| 57 |
with resources.as_file(target) as path: |
| 58 |
path.unlink() |
| 59 |
|
| 60 |
|
| 61 |
if __name__ == '__main__': |
| 62 |
unittest.main() |