pathlib.Path() inconsistent behavior #655
Description
Activity
This is a known limitation to pyfakefs (and other patching methods). From the documentation of the
modules_to_reloadargument:If initializing a global variable using a file system function, the initialization will be done using the real file system:
from pathlib import Path path = Path("/example_home")
In this case, path will hold the real file system path inside the test. The same is true, if a file system function is used in a decorator (...).
To get these cases to work as expected under test, the respective modules containing the code shall be added to the modules_to_reload argument (a module list). The passed modules will be reloaded, thus allowing pyfakefs to patch them dynamically. All modules loaded after the initial patching described above will be patched using this second mechanism.As reloading the test itself does not make sense,
modules_to_reloadwould not help for your example, and I don't know a way of how to fix this without changing the definition. A workaround would be to use an accessor function instead of the function, or lazy initialization of the global variable aftersetupPyfakefs. Both are not ideal, but as I wrote that is a limitation of patching in general.@mrbean-bremen thanks for pointing this out, I did not notice that in the documentation and that really helps.
- locked and limited conversation to collaborators
on Jan 14, 2022
Describe the bug
We have tests that are broken when they use
Pathobjects instantiated beforesetUpPyfakefs()is called. If the objects are re-instantiated aftersetUpPyfakefs()things go back to the fake filesystem.Recasting the
Pathobjects aftersetUpPyfakefs()is called is a workaround on the issue but I suspect many unittests will now write to the real filesystem as a side effect (we have internal tests that do just that). In the lucky cases were we used '/fake' or other similarly broken paths, on purpose, the tests fails explicitly. In other cases we are concerned that directories might be deleted by tests when they should have been left alone.How To Reproduce
Please provide a unit test or a minimal code snippet that reproduces the
problem.
The
test_global_pathfails but I would expect that to pass as modules from the code under test might have instantiated pathlib.Path instances during import time for example. This breaks the assumption that fakefs will capture all filesystem access.Your environment
Please run the following and paste the output.