【问题标题】:pytest mock os.listdir to return empty listpytest mock os.listdir 返回空列表
【发布时间】:2018-09-24 21:44:20
【问题描述】:

我的程序中有一个函数列出给定路径中的所有文件,我正在尝试编写一个测试,当提供的路径中不存在文件时通过测试(空输出,即[])我正在学习关于 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.listdirreturn 值更改为空列表,[] 以模拟空目录。

当我运行上面的命令时,我得到以下错误,

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/')

【问题讨论】:

  • 添加get_list的代码。我们需要看看listdir是如何使用/导入的。
  • 我已经添加了代码@wim 谢谢
  • 你为什么将stdout=[] 传递给assert_called_with?您断言 stdout=[]listdir 调用的关键字参数之一,而没有传递这样的参数。
  • 我在看在线教程或 pytest。这就是他们建议设置stdout 值的方式,我一定把它弄糊涂了。感谢您清除它

标签: python pytest


【解决方案1】:

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 的用户将需要在不同的命名空间中进行模拟!

【讨论】:

  • 非常感谢。您能否建议我在哪里可以找到关于pytest-mock 的易于理解的好文档?
  • mock 的标准库文档。请注意,mocker 夹具只是注入模拟命名空间。
猜你喜欢
  • 1970-01-01
  • 2020-05-07
  • 1970-01-01
  • 2017-06-30
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 2019-08-18
相关资源
最近更新 更多