Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 出于测试目的,使函数返回可预测的值_Python_Django_Pytest - Fatal编程技术网

Python 出于测试目的,使函数返回可预测的值

Python 出于测试目的,使函数返回可预测的值,python,django,pytest,Python,Django,Pytest,我需要一个函数来在运行测试时返回可预测的值。 例如,我有一个函数get_usd_rates(),它从一些API加载美元汇率 到目前为止,当我在任何其他函数中使用它时,我只是将传递率作为一个可选参数,仅用于测试目的。看起来有点老套,但它奏效了。像这样: def some_other_函数(速率=无): 如果费率为零: 费率=获取美元费率() #对利率做点什么 但现在我面临的情况是,我无法将额外的参数传递给函数(django模型的私有类方法,在模型字段更改时调用) 有没有办法让get_usd_ra

我需要一个函数来在运行测试时返回可预测的值。 例如,我有一个函数
get_usd_rates()
,它从一些API加载美元汇率

到目前为止,当我在任何其他函数中使用它时,我只是将传递率作为一个可选参数,仅用于测试目的。看起来有点老套,但它奏效了。像这样:

def some_other_函数(速率=无):
如果费率为零:
费率=获取美元费率()
#对利率做点什么
但现在我面临的情况是,我无法将额外的参数传递给函数(django模型的私有类方法,在模型字段更改时调用)

有没有办法让
get_usd_rates()
函数知道测试正在运行,并且在这种情况下总是返回一些预定义的值而不会对性能产生明显影响?
或者什么是处理此问题的最佳方法。

您需要做的是
mock
方法。这是unittest模块中的一个模块。尝试使用
mock.patch

from unittest.mock import patch

@patch('path.to.get_usd_rates')
def your_test_function(mock_get_usd_rates):
    mock_get_usd_rates.return_value = "Some predefined value"
    # Rest of your test (Anywhere that get_usd_rates is used will now automaticlly use mock_get_usd_rates)
这里发生的情况是,
mock.patch
将用一个mock替换函数get\u usd\u rates,您可以在该mock上设置您想要的返回值。除了decorator(上下文管理器等)引用之外,还有多种方法可以实现这一点: