Python自动化测试之使用pytest-mock模拟用户输入

假如有这样一段代码要测试:

python 复制代码
# 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!'

测试代码可以这样写:

python 复制代码
# test_hello.py
# pip install pytest pytest_mock
import pytest
from pytest_mock import MockerFixture
from hello import welcome

def test_welcome(
    # Use pytest-mock to mock user input
    # https://github.com/pytest-dev/pytest-mock
    mocker: 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!'

运行:

bash 复制代码
pytest test_hello.py
相关推荐
AAA大运重卡何师傅(专跑国道)12 小时前
【无标题】
开发语言·c#
copyer_xyf12 小时前
Python 异常处理
前端·后端·python
XBodhi.12 小时前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio
麻雀飞吧12 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy13 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.13 小时前
【01】Python 机器学习
开发语言·python
为爱停留13 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python
l1t13 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程39-40
开发语言·python
曾阿伦14 小时前
Python 搭建简易HTTP服务
开发语言·python·http
YG亲测源码屋14 小时前
java配置环境变量、jdk环境变量配置、java环境变量设置方法
java·开发语言