如何使用monkeypatch测试没有返回值的函数

时间:2021-05-07 07:33:56

标签: python pytest monkeypatching

我正在我的项目中运行一些单元测试,我有一个不返回任何内容的函数。我开始使用monkeypatch、pytests 和Python 3.8 进行测试。波纹管,这是我正在尝试执行测试的代码的一部分。

def test_start_download(monkeypatch):
    def mock_get_file(self, x, y, z):
        assert z == function.get('foo')[0]


    monkeypatch.setattr(Bar, 'foo', lambda x: 'valid_token')
    monkeypatch.setattr(Foo, 'bar', lambda x, y, z: foo_bar)
    monkeypatch.setattr(FooBar, 'foo', mock_get_file)
    monkeypatch.setattr(BarFoo, 'foo', lambda x, y: 'file')

    function.call(1861, 'key', 'C:/User')

这个函数call没有返回任何结果给我,它只是一个下载文件的函数。

1 个答案:

答案 0 :(得分:1)

<块引用>

它只是一个下载文件的函数。

然后测试文件是否出现在它应该出现的位置:

function.call(1861, 'key', 'C:/User')
assert os.path.exists('C:/User/key')  # or whatnot

您可能希望使用 the tmp_path fixture 来避免污染文件系统:

def test_start_download(monkeypatch, tmp_path):
   # ...
   function.call(1861, 'key', str(tmp_path))
   assert (temp_path / 'key').exists()