refactor(testing.pytest): change mock_pkg interface
being more explicit about what the fixture provides as an output, instead of solely describing the site effects. Also the consumer is now responsible for the module directory layout.
This commit is contained in:
parent
e6bf657919
commit
aa2540cf3f
2 changed files with 28 additions and 19 deletions
|
|
@ -7,6 +7,8 @@ import pytest
|
|||
|
||||
from byteb4rb1e.testing.pytest import get_current_test
|
||||
|
||||
_SITE_PACKAGE_COUNTER: Dict[str, int] = {}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def current_test() -> Tuple[Path, str]:
|
||||
|
|
@ -16,25 +18,27 @@ def current_test() -> Tuple[Path, str]:
|
|||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_pkg(tmp_path):
|
||||
def _create(name: str, files: Dict[str, Union[str, bytes]]):
|
||||
pkg_path = tmp_path / name.replace('.', os.path.sep)
|
||||
def mock_system_site_package_dir(tmp_path):
|
||||
global _SITE_PACKAGE_COUNTER
|
||||
|
||||
package_id = _SITE_PACKAGE_COUNTER.setdefault(tmp_path, 0)
|
||||
_SITE_PACKAGE_COUNTER[tmp_path] += 1
|
||||
|
||||
sys_path = tmp_path / str(package_id)
|
||||
|
||||
def _create(name: str) -> Path:
|
||||
pkg_path = sys_path / name.replace('.', os.path.sep)
|
||||
|
||||
pkg_path.mkdir(parents=True)
|
||||
|
||||
(pkg_path / "__init__.py").touch()
|
||||
|
||||
for fname, content in files.items():
|
||||
fpath = (pkg_path / fname)
|
||||
fpath.parent.mkdir(parents=True, exist_ok=True)
|
||||
if isinstance(content, str):
|
||||
fpath.write_text(content)
|
||||
else:
|
||||
fpath.write_bytes(content)
|
||||
sys.path.insert(0, str(sys_path))
|
||||
|
||||
sys.path.insert(0, str(tmp_path))
|
||||
return name, pkg_path
|
||||
return pkg_path
|
||||
|
||||
yield _create
|
||||
|
||||
# cleanup sys.path after test
|
||||
if str(tmp_path) in sys.path:
|
||||
sys.path.remove(str(tmp_path))
|
||||
if str(sys_path) in sys.path:
|
||||
sys.path.remove(str(sys_path))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue