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
相关推荐
ZTLJQ几秒前
构建现代Web应用:Python全栈框架完全解析
前端·数据库·python
m0_743470371 分钟前
C++中的装饰器模式变体
开发语言·c++·算法
花间相见2 分钟前
【JAVA基础14】—— 二维数组详解:从基础到实战应用
java·python·算法
wjs20243 分钟前
jQuery Mobile 表单滑动条
开发语言
zzb15803 分钟前
Claude Agent SDK 深度剖析:依赖、权衡与架构选择
人工智能·python·ai
2401_864959283 分钟前
分布式日志系统实现
开发语言·c++·算法
linhaijiao4 分钟前
C++与人工智能框架
开发语言·c++·算法
会算数的⑨6 分钟前
Spring AI Alibaba 学习(四):ToolCalling —— 从LLM到Agent的华丽蜕变
java·开发语言·人工智能·后端·学习·saa·ai agent
2301_764441337 分钟前
使用Python 和 Streamlit 构建的多维度游戏玩家数据分析
python·游戏·数据分析
Ivanqhz7 分钟前
linearize:控制流图(CFG)转换为线性指令序列
开发语言·c++·后端·算法·rust