diff --git a/src/byteb4rb1e/utils/testing/pytest/fixtures.py b/src/byteb4rb1e/utils/testing/pytest/fixtures.py index dc87091..3362010 100644 --- a/src/byteb4rb1e/utils/testing/pytest/fixtures.py +++ b/src/byteb4rb1e/utils/testing/pytest/fixtures.py @@ -1,6 +1,7 @@ import os from pathlib import Path -from typing import Tuple +import sys +from typing import Dict, Tuple, Union import pytest @@ -12,3 +13,28 @@ def current_test() -> Tuple[Path, str]: """ """ return get_current_test() + + +@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) + 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(tmp_path)) + return name, pkg_path + + yield _create + + # cleanup sys.path after test + if str(tmp_path) in sys.path: + sys.path.remove(str(tmp_path)) diff --git a/tests/integration/byteb4rb1e/utils/testing/pytest/test_fixtures.py b/tests/integration/byteb4rb1e/utils/testing/pytest/test_fixtures.py index 56302e5..c6b8e1f 100644 --- a/tests/integration/byteb4rb1e/utils/testing/pytest/test_fixtures.py +++ b/tests/integration/byteb4rb1e/utils/testing/pytest/test_fixtures.py @@ -1,10 +1,12 @@ from pathlib import Path +import importlib.resources import pytest pytestmark = pytest.mark.pytest -from byteb4rb1e.utils.testing.pytest.fixtures import current_test +from byteb4rb1e.utils.testing.pytest.decorators import run_in_subprocess_once +from byteb4rb1e.utils.testing.pytest.fixtures import current_test, mock_pkg def test_current_test(current_test): @@ -14,3 +16,18 @@ def test_current_test(current_test): assert str(Path(__file__)) == str(suite_path) assert case_name == "test_current_test" + + +@run_in_subprocess_once() +def test_mock_pkg(mock_pkg): + """ + """ + dummy_data = 'Hello' + + mock_pkg('foobarpkg', { + 'data.txt': dummy_data + }) + + result = next(importlib.resources.files('foobarpkg').glob('data.txt')).read_text() + + assert result == dummy_data