首页 > 解决方案 > 如何在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'

标签: pythonunit-testingmocking

解决方案


直接访问调用参数:

>>> mock.call(10).args
(10,)

例子:

>>> mock.call(10).args <= mock.call(11).args
True
>>> mock.call(10).args <= mock.call(9).args
False

推荐阅读