使用mock测试django管理命令



我有一个命令(我们称之为do_thing(:

class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("filename", type=str)
def handle(self, *args, **kwargs):
with open(kwargs["filename"]) as f:
# do something with the data here

并且我想使用CCD_ 2来模拟从文件中读取。

根据上面链接中显示的示例,我目前有(在tests.py中的测试中(:

with patch('__main__.open', mock_open(read_data="some content here")) as m:
call_command("do_thing", "foo.txt")

然而,当我运行这个程序时,Django/Python的行为就像mock补丁没有效果一样:

FileNotFoundError: [Errno 2] No such file or directory: 'foo.txt'

我在这里做错了什么?非常感谢。

我假设具有Command类的模块是do_thing。因此,不要使用直接执行模块时有效的__main__,而是使用确切的模块名称do_thing

with patch('do_thing.open', mock_open(read_data="some content here")) as m:
call_command("do_thing", "foo.txt", run=True)

最新更新