使用带有 Python mock 的生成器来复制服务器响应

Using a generator with Python mock to replicate server responses

我想使用一个列表(转换为生成器)作为我的 API 调用(使用 unittest.mock)的模拟。我的函数是:

def monitor_order(order_id)
    order_info = client.get_order_status(order_id)
    order_status = order_info['status']

    while order_status != 'filled':
        print('order_status: ', order_status)
        time.sleep(5)
        order_info = client.get_order_status(order_id)
        order_status = order_info['status']

    return order_info

我的测试函数是:

@patch('my_package.client.get_order_status')
def test_monitor_order(mocked_get_order_status):
    order_states = [
        dict(status='open'),
        dict(status='open'),
        dict(status='filled'),
    ]

    # Make into a generator
    status_changes = (status for status in order_states)
    mocked_get_order_status.return_value = next(order_states)

    # Execute function to test
    monitor_order("dummy_order")

但是我看到执行测试的时候状态一直是'open':

order_status:  open
order_status:  open
order_status:  open

我想我明白为什么它是错误的,但我怎样才能正确实施它?

为了达到你想要的效果,你可以按如下方式重写你的测试:

@patch('my_package.client.get_order_status')
def test_monitor_order(mocked_get_order_status):
    order_states = [
        dict(status='open'),
        dict(status='open'),
        dict(status='filled'),
    ]

    mocked_get_order_status.side_effect = order_states

    # Execute function to test
    monitor_order("dummy_order")