python - pytest 模拟 os.listdir 返回空列表

标签 python pytest

我的程序中有一个函数列出给定路径中的所有文件,我正在尝试编写一个测试,当提供的路径中不存在文件时该测试通过(空输出,即 []) 我正在学习 pytest 的模拟装置来做到这一点。这是我写的,

def test_no_dirs(mocker):
    mocker.patch('os.listdir')
    assert get_list() #get_list returns ['abc.json', 'test.json', 'test2.json']
    os.listdir.assert_called_with('/etc/app_data/',stdout=[])

我首先使用了 mocker 作为参数,然后修补了 os.listdir 函数。 os.listdirget_list() 中调用,但我不知道如何更改 os.listdir 的 return 为空列表,[] 为模拟空目录。

当我运行上面的命令时,出现以下错误,

E       AssertionError: Expected call: listdir('/etc/app_data/', stdout='[]')
E       Actual call: listdir('/etc/app_data/')
E
E       pytest introspection follows:
E
E       Kwargs:
E       assert {} == {'stdout': '[]'}
E         Right contains more items:
E         {'stdout': '[]'}
E         Full diff:
E         - {}
E         + {'stdout': '[]'}

如何模拟 os.listdir 以返回空值并通过测试?

如果我删除 stdout=[],测试 PASS 但它并没有真正做我想做的事情,即在没有文件时通过。

这是get_list()的代码

import os
def get_list():
    return os.listdir('/etc/app_data/')

最佳答案

pytest-mock 版本应如下所示:

def test_no_dirs(mocker):
    mock = mocker.patch('os.listdir', return_value=[])
    result = get_list()
    assert result == []  # because that's the `return_value` mocked
    mock.assert_called_once_with('/etc/app_data/')

请注意,执行 from os import listdir 的用户将需要在不同的命名空间中进行模拟!

关于python - pytest 模拟 os.listdir 返回空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52487769/

相关文章:

Python - 运行 py.test 和覆盖率测试的 tox 中出现调用错误

python - 如何使用python将大量XML插入到另一个XML文件中?

python - python 中压平 Json 文件的问题

python-3.x - Celery 在任务中模拟网络调用

python - 如何清除多个断言语句之间捕获的 stdout/stderr

python - 如何在单元测试中验证python日志格式?

python - 使用 openpyxl 写入一列

python - 如果在 Matplotlib 中指定图形大小,图形标题 (suptitle()) 会消失

python - BigQuery python 插入记录 (\w client.insert_rows)

python - pytest,检索调用 fixture 的测试