python - 如何为相同的功能模拟不同的?
问题描述
这是我要测试的代码
if os.path.exist(path_one):
func1()
elif os.path.exist(path_two):
func2()
在编写单元测试时。我想要
- 模拟第一个 os.path.exist 返回 Flase 所以 func1 不执行
- 模拟第二个 os.path.exist 返回 True 所以 func2 将执行
但是我没有找到一种方法来模拟相同的 func os.path.exist 的不同返回
一种方法是将其包装成不同的 func 和 mock。但我不想仅仅因为单元测试就这样做。有什么好主意吗?
解决方案
您可以将patch()方法与side_effect
.
每当调用 Mock 时要调用的函数。请参阅 side_effect 属性。对于引发异常或动态更改返回值很有用。
例如
main.py
:
import os
def func1():
print('func1')
def func2():
print('func2')
def main():
path_one = 'path_one'
path_two = 'path_two'
if os.path.exists(path_one):
func1()
elif os.path.exists(path_two):
func2()
test_main.py
:
from main import main
from unittest import TestCase, mock
import unittest
class TestMain(TestCase):
@mock.patch('main.os.path.exists')
def test_main(self, mock_exists):
def side_effect(path):
if(path == 'path_one'):
return False
if(path == 'path_two'):
return True
mock_exists.side_effect = side_effect
main()
if __name__ == '__main__':
unittest.main()
测试结果:
func2
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
推荐阅读
- visual-studio - 用于 linux 的 windows 子系统上的外部可执行文件的 launch.vs.json 文件配置
- powershell - 通过 cmd.exe 调用的 powershell.exe 命令中的嵌套 cmd.exe 命令
- salesforce - Salesforce 批量 API 删除运算符
- postgresql - 将文本转换为 UTC 时间戳
- nginx - 在 Ubuntu 服务器上安装 Openresty
- javascript - DataTables 仅打印选定的选项
- laravel - Laravel 用户和多态性
- reactjs - 在 FlatList 中渲染的组件会被重新渲染,即使它们被声明为 PureComponent 并且它们的 props 引用没有改变
- python-3.x - 如何将列的值设置为数据框中的列?
- r - foreach 循环中的变量赋值问题(R)