简体   繁体   English

django - 使用模拟测试 django-admin 命令

[英]django - testing a django-admin command using mock

I have a command (let's call it do_thing ):我有一个命令(我们称之为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

and I want to use unittest.mock.mock_open() to simulate reading from a file.我想使用unittest.mock.mock_open()来模拟从文件中读取。

Based off the example shown in the link above, I currently have (in a test in tests.py ):根据上面链接中显示的示例,我目前有(在tests.py的测试中):

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

However, when I run this, Django/Python acts as if the mock patch had no effect:但是,当我运行它时,Django/Python 就像mock补丁没有效果一样:

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

What am I doing wrong here?我在这里做错了什么? Thank you!谢谢!

I assume the module that has Command class is do_thing .我假设具有Command class 的模块是do_thing so instead of __main__ which works when you directly execute the module, use that exact module name 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)

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

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