Replies: 2 comments 3 replies
-
The reason for this is that we usually want to be able to import real modules in tests - most tests depend on this. That being said, there is a possibility to patch import importlib.util
import sys
from pathlib import Path
import pytest
from pyfakefs.fake_filesystem import PatchMode
from pyfakefs.fake_filesystem_unittest import Patcher
@pytest.fixture
def fs_patch_open():
with Patcher(patch_open_code=PatchMode.AUTO) as p:
yield p.fs
def test_import(fs_patch_open):
module_path = Path('heya.py')
module_path.write_text('x = 1234')
... should work for you. Note that this is not a common use case and basically not tested - I would not exclude all sorts of problems and side effects if using this for tests in a larger code base. |
Beta Was this translation helpful? Give feedback.
-
That works, thanks. Unfortunately I've had to rewrite my code to use def test_import(fs_patch_open):
module_path = Path('heya.py')
module_path.write_text('x = 1234')
sys.path.insert(0, str(module_path.parent))
importlib.import_module(module_path.stem) # throws ModuleNotFoundError Is there an easy workaround for this as well? |
Beta Was this translation helpful? Give feedback.
-
Describe the bug
Files that only exist on the fake file system cannot be imported, neither with a regular
import
statement nor viaimportlib
.How To Reproduce
Your environment
Windows-11-10.0.22631-SP0
Python 3.12.0 (tags/v3.12.0:0fb18b0, Oct 2 2023, 13:03:39) [MSC v.1935 64 bit (AMD64)]
pyfakefs 5.7.1
pytest 7.3.2
Beta Was this translation helpful? Give feedback.
All reactions