Replacing tmp_path
with FakePath
#1147
-
I am not sure if this is the most idiomatic way to do this or if there is a better way. I am replacing def fake_path(path: Path | str) -> FakePath:
"""
Get a pyfakefs fake `Path` class.
"""
fake_pathlib_module = FakePathlibModule(FakeFilesystem()) # type: ignore[no-untyped-call]
return fake_pathlib_module.Path(path) # type: ignore[no-untyped-call] For example: -def test_case(tmp_path:Path) -> None:
+def test_case(fake_path:FakePath) -> None:
with pytest.raises(FileNotFoundError, match=r"No such file or directory: '.*not/found'"):
- assert tmp_path / "not/found"
+ assert fake_path("not/found") Questions
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
While it is possible to instantiate and use the fake fs classes directly (this was the original use case at Google when the library was first written, and partly still is today), you shouldn't need to do this if you use Your specific use case (replacement of @pytest.fixture
def temp_path(fs):
tmp_dir = tempfile.TemporaryDirectory()
yield Path(tmp_dir.name) This would return a newly created fake directory, which will be removed after the test. This should be completely sufficient to replace @pytest.fixture
def temp_path(fs):
tmp_path = Path("/tmp/foo")
tmp_path.mkdir()
yield tmp_path
tmp_path.rmdir() # this is not strictly needed, as the fake fs is removed after the test As for question 3 (typing): as in most use cases these classes should not be needed, and typing can be a bit tricky given the changes between the Python versions, this is currently not done. Maybe I'll add it some time later... |
Beta Was this translation helpful? Give feedback.
While it is possible to instantiate and use the fake fs classes directly (this was the original use case at Google when the library was first written, and partly still is today), you shouldn't need to do this if you use
pytest
with thefs
fixture,unittest
withfake_filesystem_unittest.TestCase
, orfake_filesystem_unittest.Patcher
directly. In these cases, it is sufficient to use just the standard filesystem functions, and, if wanted, some of the convenience functions.Your specific use case (replacement of
tmp_path
) can be achieved by just usingtempfile
:This would return a newly …