簡體   English   中英

使 function 返回可預測的值以用於測試目的

[英]Make function return predictable values for testing purposes

我需要一個 function 在運行測試時返回可預測的值。 例如,我有一個 function get_usd_rates() ,它從一些 API 加載美元外匯匯率。

到目前為止,當我在任何其他 function 中使用它時,我只是將 rate 作為可選參數傳遞,僅用於測試目的。 看起來很hacky,但它確實有效。 像這樣:

def some_other_function(rates=None):
    if rates is None:
        rates = get_usd_rates()

    # do something with rates

But now I am facing a situation where I can't pass extra argument to a function (private class method for django model, which is called on model field change).

有沒有辦法讓get_usd_rates() function 意識到測試正在運行並且在這種情況下總是返回一些預定義的值而不會產生明顯的性能影響? 或者解決這個問題的最佳方法是什么。

您需要做的是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將用你設置你想要的返回值的模擬替換你的 function get_usd_rates 。 除了裝飾器(一個的上下文管理器等)之外,還有多種方法可以做到這一點。參考: unittest.mock

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM