File: test_zipmodule.py

package info (click to toggle)
python-acres 0.5.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 292 kB
  • sloc: python: 194; makefile: 11
file content (61 lines) | stat: -rw-r--r-- 1,832 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import os
import sys
import zipfile
from pathlib import Path
from types import ModuleType

from acres import Loader


def test_zipimport(tmp_path: Path) -> None:
    # Setup... no need for a fixture for a single test
    target_file = tmp_path / 'mymodule.zip'
    with zipfile.ZipFile(target_file, mode='w') as mymod:
        mymod.writestr(
            'mypkg/__init__.py',
            'from . import data\n',
        )
        mymod.writestr(
            'mypkg/data/__init__.py',
            'from acres import Loader\nload_resource = Loader(__spec__.name)\n',
        )
        mymod.writestr(
            'mypkg/data/resource.txt',
            'some text\n',
        )

    sys.path.insert(0, str(target_file))

    # Test
    import mypkg  # type: ignore[import-not-found]

    # The test shouldn't get this far if these fail, but they help the type checker
    assert isinstance(mypkg, ModuleType)
    assert isinstance(mypkg.__file__, str)
    assert mypkg.__file__.endswith(os.path.join('mymodule.zip', 'mypkg', '__init__.py'))

    loader: Loader = mypkg.data.load_resource

    # This check verifies the above annotation and ensures full resolution of types below
    assert isinstance(loader, Loader)

    readable = loader.readable('resource.txt')
    assert not isinstance(readable, Path)
    assert readable.read_text() == 'some text\n'

    with loader.as_path('resource.txt') as path:
        assert isinstance(path, Path)
        assert path.exists()
        assert path.read_text() == 'some text\n'
    assert not path.exists()

    cached = loader.cached('resource.txt')
    assert isinstance(cached, Path)
    assert cached.exists()
    assert cached.read_text() == 'some text\n'

    new_loader = Loader('mypkg.data')
    assert new_loader.cached('resource.txt') == cached

    # Teardown
    sys.path.pop(0)