我知道如何使用單個input函式測驗 python 函式,但我似乎無法弄清楚如何測驗其中包含多個input函式的 python 函式。
請參閱下面的最小示例代碼test.py:
import pytest
import mock
import builtins
def unsubscribe():
if input("are you unsubscribing? [y/n]") == "n":
return "we are glad to have you back"
else:
if input("would you like a 20%% off discount code? [y/n]") == "y":
return "your discount code is SAVE20, and we are glad you have you back"
else:
return "we are sad to see you go"
def test_unsubscribe():
with mock.patch.object(builtins, 'input', lambda _: 'n'):
assert unsubscribe() == "we are glad to have you back"
with mock.patch.object(builtins, 'input', lambda _: 'y'):
assert unsubscribe() == "your discount code is SAVE20, and we are glad you have you back"
# what to put here to test the below
# assert unsubscribe() == "we are sad to see you go"
使用當前方法,模擬補丁將每個input函式替換為 alln或 all y,這導致第一個輸入y和第二個輸入的控制流n無法訪問。對包含多個函式的 python 函式進行單元測驗的正確方法是input什么?
uj5u.com熱心網友回復:
你可以用side_effect這個。Side_effect將串列作為輸入,并按照元素的順序為您提供結果。
假設您將測驗和源代碼放在不同的目錄中
@patch('sample.input')
def test_options(mock_input):
mock_input.side_effect = ['y', 'y']
result = unsubscribe()
assert result == "your discount code is SAVE20, and we are glad you have you back"
您可以通過為用例定義所需的確切輸出來將其帶到下一步,而不是任意傳遞 yes 和 no 值
@patch('sample.input')
def test_options(mock_input):
def input_side_effect(*args, **kwargs):
m = {
'are you unsubscribing? [y/n]': 'y',
'would you like a 20%% off discount code? [y/n]': 'y',
}.get(args[0])
if m:
return m
pytest.fail('This question is not expected')
mock_input.side_effect = input_side_effect
result = unsubscribe()
assert result == "your discount code is SAVE20, and we are glad you have you back"
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/460509.html
標籤:Python python-3.x 单元测试 pytest
上一篇:Flutter單元測驗-如何測驗對欄位的訪問是否會引發LateInitializationError
下一篇:獲取AttributeError:嘗試使用unittest框架對views.py進行單元測驗時,“TestCase”物件沒有屬性“assertTemplateUsed”
