设置doublex间谍在每次调用时返回不同的值

时间:2017-02-15 08:31:28

标签: python mocking pytest spy

我想测试代码库中请求重试的处理。为此,我想定义一个spy,它为同一个调用返回不同的值。我正在使用doublexpy.test进行测试:

这是一个工作测试用例,用于单个调用:

import pytest
from doublex import Spy, assert_that, ANY_ARG, is_


@pytest.mark.unit
def test__me():

    with Spy() as spy:
        spy.foo(ANY_ARG).returns(10)

    assert_that(spy.foo(), is_(10))

重试将通过完全相同的调用(即使用相同的参数)执行,但将返回不同的值。它会与此类似(不起作用):

import pytest
from doublex import Spy, assert_that, ANY_ARG, is_


@pytest.mark.unit
def test__me():

    # TODO: how to setup a spy returning changing values, with fixed calling arguments?
    with Spy() as spy:
        spy.foo(ANY_ARG).returns(10)
        spy.foo(ANY_ARG).returns(11)

    # Each invocation will return a different value
    assert_that(spy.foo(), is_(10))
    assert_that(spy.foo(), is_(11))

如何设置每个调用返回不同值的间谍?

1 个答案:

答案 0 :(得分:1)

您可以使用.delegates()代替.returns()

with Stub() as stub:
    stub.foo().delegates([1, 2, 3])

assert_that(stub.foo(), is_(1))
assert_that(stub.foo(), is_(2))
assert_that(stub.foo(), is_(3))

请注意,第四次拨打stub.foo()会提升StopIteration。为避免这种情况,您可以将函数而不是列表传递给.delegates()