如何解决django-使用模拟测试django-admin命令
我有一条命令(我们叫它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
我想使用unittest.mock.mock_open()
模拟从文件中读取内容。
基于上面链接中显示的示例,我目前(在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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。