简体   繁体   English

如何模拟在 python 中为特定路径打开的文件?

[英]How do I mock a file open for a specific path in python?

So I know that in my unit test I can mock a context manager open(), ie:所以我知道在我的单元测试中我可以模拟一个上下文管理器 open(),即:

with open('file_path', 'r') as stats:

mocked with嘲笑

with mock.patch('builtins.open', mock.mock_open(read_data=mock_json)):

but is there a way for me to only mock it for a specific file path?但是有没有办法让我只为特定的文件路径模拟它? Or maybe some other way to ensure that the context manager gets called with the correct path in a unit test?或者可能是其他方式来确保在单元测试中使用正确的路径调用上下文管理器?

To mock open only for a specific path, you have to provide your own mock object that handles open differently, depending on the path.要仅为特定路径模拟open ,您必须提供自己的模拟对象,根据路径以不同方式处理open Assuming we have some function:假设我们有一些功能:

def do_open(path):
    with open(path, "r") as f:
        return f.read()

where open shall be mocked to return a file with the content "bar" if path is "foo", but otherwise just work as usual, you could do something like this:如果path为“foo”,则应模拟open以返回内容为“bar”的文件,否则照常工作,您可以执行以下操作:

from unittest import mock
from my_module.do_open import do_open

builtin_open = open  # save the unpatched version

def mock_open(*args, **kwargs):
    if args[0] == "foo":
        # mocked open for path "foo"
        return mock.mock_open(read_data="bar")(*args, **kwargs)
    # unpatched version for every other path
    return builtin_open(*args, **kwargs)

@mock.patch("builtins.open", mock_open)
def test_open():
    assert do_open("foo") == "bar"
    assert do_open(__file__) != "bar"

If you don't want to save the original open in a global variable, you could also wrap that into a class:如果您不想将原始open保存在全局变量中,也可以将其包装到一个类中:

class MockOpen:
    builtin_open = open

    def open(self, *args, **kwargs):
        if args[0] == "foo":
            return mock.mock_open(read_data="bar")(*args, **kwargs)
        return self.builtin_open(*args, **kwargs)

@mock.patch("builtins.open", MockOpen().open)
def test_open():
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM