假如有这样一段代码要测试:
# hello.py
def welcome() -> str:name = input("What's your name? ").strip()if not name:return 'Welcome to Guangdong~'return f'Hi, {name}. You are welcome!'
测试代码可以这样写:
# test_hello.py
# pip install pytest pytest_mock
import pytest
from pytest_mock import MockerFixture
from hello import welcomedef test_welcome(# Use pytest-mock to mock user input# https://github.com/pytest-dev/pytest-mockmocker: MockerFixture,
):mocker.patch("builtins.input", return_value="")assert welcome() == 'Welcome to Guangdong~'mocker.patch("builtins.input", return_value=" ")assert welcome() == 'Welcome to Guangdong~'mocker.patch("builtins.input", return_value="Waket")assert welcome() == 'Hi, Waket. You are welcome!'mocker.patch("builtins.input", return_value="Joe")assert welcome() == 'Hi, Joe. You are welcome!'
运行:
pytest test_hello.py