我有一些加载到本地 JSON 文件中的 Python 代码:
with open("/path/to/file.json") as f:
json_str = f.read()
# Now do stuff with this JSON string
在测试中,我想将该 JSON 文件修补为位于我的存储库测试目录中的 JSON 文件 ("/path/to/repo/test/fake_file.txt) json”
)。
我该如何去做呢?
另一项要求是我实际上在本地有一个 "/path/to/file.json"
版本,但我不想更改它。我希望它在测试时修补,并在测试完成后取消修补。
注意:我使用 pytest,插件 pyfakefs 似乎可以做到这一点。遗憾的是,我不知道如何让它在另一个本地文件中进行修补(从我的存储库的测试目录中)。我愿意接受使用普通 Python 3.10+ 和/或 pyfakefs 的解决方案。
I have some Python code that loads in a local JSON file:
with open("/path/to/file.json") as f:
json_str = f.read()
# Now do stuff with this JSON string
In testing, I want to patch that JSON file to be a JSON file located in my repo's test directory ("/path/to/repo/test/fake_file.json"
).
How can I go about doing that?
One other requirement is I actually have a version of "/path/to/file.json"
locally, but I don't want to change it. I want it patched over at test time, and unpatched upon test completion.
Note: I use pytest
, and it seems like the plug-in pyfakefs
would do this. Sadly, I can't figure out how to get it to patch in another local file (from within my repo's test directory). I am open to solutions using vanilla Python 3.10+ and/or pyfakefs
.
发布评论
评论(1)
使用 pyfakefs,您可以将真实文件映射到假文件系统。在您的情况下,您可以使用 add_real_file :
这会将您现有的文件映射到假文件系统中的
target_path
中(如果target_path
不是如果给定,它会将其映射到与源文件相同的位置)。同一位置是否存在真实文件并不重要,因为真实文件系统将在假文件系统中被忽略。如果您在测试代码中读取
"/path/to/file.json"
,它实际上会读取"/path/to/repo/test/fake_file.json"
(映射文件仅按需读取)。请注意,默认情况下,该文件映射为只读,因此如果您想在测试代码中更改它,则必须在映射调用中设置
read_only=False
。这将使假文件系统中的文件可写,但写入它当然不会触及真实文件系统中的文件。免责声明:
我是 pyfakefs 的贡献者。
With
pyfakefs
, you can map real files into the fake file system. In your case, you can use add_real_file:This will map your existing file into
target_path
in the fake file system (iftarget_path
is not given, it will map it to the same location as the source file).It does not matter if there is a real file at the same location, as the real file system will be ignored in the fake file system. If you read
"/path/to/file.json"
in your test code, it will actually read"/path/to/repo/test/fake_file.json"
(mapped files are only read on demand).Note that by default the file is mapped read only, so if you want to change it in your tested code, you have to set
read_only=False
in the mapping call. This will make the file in the fake file system writable, though writing to it will not touch the file in the real file system, of course.Disclaimer:
I'm a contributor to pyfakefs.