【问题标题】:patching random.choice in each run for a test case在每次运行中为测试用例修补 random.choice
【发布时间】:2020-05-13 11:45:45
【问题描述】:

我有一个函数循环一定次数,每次从列表中选择一个随机元素。

问题出在为此编写测试用例时。

示例代码

def func(given):
    combo = [filled by a function]
    for i in range(0,given):
        com = random.choice(combo)

我的测试用例就像

@patch('random.choice',2)
def test_func():
    func(250)
    assert(expected,actual)

所以当测试用例运行时,我想在每次运行中为 random.choice 动态赋予不同的值。

如何做到这一点?

【问题讨论】:

  • 题意不清楚? “每次运行都不同”是什么意思?如果您要求一个随机数,它可能会连续两次出现相同的数字。如果我们避免这种情况,我们将失去随机性
  • 你想要这个 --> docs.pytest.org/en/latest/parametrize.html 这意味着切换到pytest
  • @BaruchG。我的意思是,当 func 被调用 250 次时,我想在 250 次调用中将测试用例中的值注入 random.choice。

标签: python unit-testing random


【解决方案1】:

假设您使用的是mock,则可以使用patchside_effect参数。

如果您传递一个可迭代对象,则每次调用修补对象时,都会返回可迭代对象中的下一个值。因为一个例子总是更清楚,这里有一个简单的例子:

import mock
import random

def my_function_to_test():
    value = random.randint(0, 10)
    print("Value: %d" % value)
    return value

@mock.patch('random.randint', side_effect=[1, 2, 3])
def test(mocked_random):
    value1 = my_function_to_test()
    print('My value is 1: %s' % (value1 == 1))

    value2 = my_function_to_test()
    print('My value is 2: %s' % (value2 == 2))

    value3 = my_function_to_test()
    print('My value is 3: %s' % (value3 == 3))

if __name__ == "__main__":
    test()

你应该得到:

Value: 1
My value is 1: True
Value: 2
My value is 2: True
Value: 3
My value is 3: True

这不是像 unittest 或任何等效测试框架那样的真正测试,但想法就在这里。

请注意,大多数时候你应该小心使用修补对象,因为mock.patch 使用的可迭代对象中有值,否则你会得到一个StopIteration 异常。在上面的示例中,这意味着我不能使用已修补的random.randint 超过 3 次。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-05
    • 2017-08-09
    • 2013-08-17
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 2013-01-24
    • 2015-11-27
    相关资源
    最近更新 更多