簡體   English   中英

Python模擬 - return_value - 獲得“真實”的返回值

[英]Python Mock - return_value - getting the “real” return value

當使用patch.object來模擬一個方法時,有沒有辦法指定對於某些參數值,該方法將運行,因為它根本沒有被模擬,並將返回“real”return_value,以及其他參數值設置特定的return_value?

謝謝。

這是一個解決方案(從我使用過的地方進行了修改),運行得相當好。 它涉及將補丁的side_effect設置為函數。

import os.path
from unittest import mock

def different_return_values(dct):
     def f(*args):
         return dct[args]
     return f

with mock.patch.object(
    os.path,
    'exists',
    side_effect=different_return_values({
        # The "generic" version above makes the arguments in order
        # the keys to this map, you could write a specialized version
        # which has a single argument or *whatever* key combination you
        # like
        ('myfile',): True,
        ('wat',): 'not a real return value but hey, monkeypatch!',
        ('otherfile',): False,
    }),
):
    print(os.path.exists('myfile'))
    print(os.path.exists('wat'))
    print(os.path.exists('otherfile'))

OUTPUT = """\
True
not a real return value but hey, monkeypatch!
False
"""

這里的內容是你可以提供一個更聰明的函數實現你正在修補的side_effecthttpsside_effect

暫無
暫無

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

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