【问题标题】:django - testing a django-admin command using mockdjango - 使用 mock 测试 django-admin 命令
【发布时间】:2020-08-14 03:28:34
【问题描述】:

我有一个命令(我们称之为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'

我在这里做错了什么?谢谢!

【问题讨论】:

    标签: python django unit-testing mocking


    【解决方案1】:

    我假设具有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)
    

    【讨论】:

      猜你喜欢
      • 2014-11-10
      • 2010-11-20
      • 2016-10-22
      • 1970-01-01
      • 2022-10-19
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多