【问题标题】:Mock function use two times/same name模拟函数使用两次/同名
【发布时间】:2021-12-07 17:39:13
【问题描述】:

我有一个要测试的函数,它调用同一个函数两次,但是这个函数返回两个不同的数据。我需要为第一个变量创建一个模拟,然后为第二个变量创建一个模拟,我有一个解决方案,但在某些情况下它不起作用。我希望能够模拟使用 api_call() 的 api_result_first 变量和 api_result_second 变量。

你有什么想法吗?

我的代码:

import pandas as pd
import time
import random 

def api_call():
  time.sleep(2)
  return random.randint(0,9)

def slow_function():
   api_result_first = api_call()
   api_result_second = api_call()
   result = api_result_first + api_result_second
   return result

我的 Pystest:

from a import *
import pytest

# https://changhsinlee.com/pytest-mock/

def test_aa(mocker):
    mocker.patch("a.api_call", return_value="ok")
    value = slow_function()
    assert isinstance(value, int)

【问题讨论】:

    标签: python testing mocking pytest


    【解决方案1】:

    使用side_effects 提供要使用的返回值序列。

    def test_aa(mocker):
        mocker.patch("a.api_call", side_effects=[3, 5])
        value = slow_function()
        assert value == 8
    

    【讨论】:

    • 谢谢,完美!
    • 我在我身边进行了测试,但无法正常工作。模拟返回我这种对象:。是否可以为每个变量名分配一个模拟值?
    猜你喜欢
    • 2016-04-18
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多