python - 如何在python中测试模拟调用的值是否在可能值范围内
问题描述
有没有办法测试发送到模拟调用的值time.sleep
?以下未按预期工作。
# tmp.py
import time
from random import randint
from unittest import mock
from unittest import TestCase
def retry_delay(tries, delay):
delay = int(delay) # ensure it's compatible with randint
cap = 600 # 10 minutes
if cap < delay:
cap = delay
exp_delay = int(delay + pow(tries, 2))
pause = randint(delay, min(cap, exp_delay))
time.sleep(pause)
class TestDelay(TestCase):
def setUp(self):
pass
@mock.patch('time.sleep')
def test_retry_delay(self, mock_sleep):
delay_time = 10 # something less than the default max of 600
retry_delay(1, delay_time)
assert mock_sleep.call_count == 1
sleep_call = mock_sleep.call_args
assert mock.call(delay_time) <= sleep_call
进入--pdb
单元测试表明mock.call
支持不等式,例如
$ nosetests --pdb tmp.py
(Pdb) mock.call(10) <= mock.call(10)
True
(Pdb) mock.call(10) <= mock.call(8)
False
(Pdb) sleep_call
call(10)
(Pdb) type(sleep_call)
<class 'mock.mock._Call'>
(Pdb) mock.call(10)
call(10)
(Pdb) type(mock.call(10))
<class 'mock.mock._Call'>
(Pdb) mock.call(10) <= sleep_call
*** TypeError: '<=' not supported between instances of 'str' and 'tuple'
解决方案
直接访问调用参数:
>>> mock.call(10).args
(10,)
例子:
>>> mock.call(10).args <= mock.call(11).args
True
>>> mock.call(10).args <= mock.call(9).args
False
推荐阅读
- python - Django 的 Manager 类中是否有 create() 方法?
- node.js - 如何使用 sinon 和 mocha 在 node js 中模拟可配置的中间件
- android - 在 VS Code 中在 Android 手机上运行 Flutter 应用
- clang++ - Emscripten EMSCRIPTEN_KEEPALIVE / EXPORTED_FUNCTIONS 来自除 main 之外的 hpp/cpp 文件
- html - 如何判断网页的哪个部分与特定的 React 组件相关联
- c# - 当阅读器关闭时,C# 尝试调用深度无效
- java - Spring Boot Hibernate 在第一次使用空数据库启动时抛出约束警告
- node.js - process.env.MONGODB_URI 是什么意思?
- angular - 打开菜单时如何聚焦输入元素?
- python - 使用 python 和 kerberos 验证凭据