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
相关推荐
冻柠檬飞冰走茶18 分钟前
PTA基础编程题目集 7-15 计算圆周率(C语言实现)
c语言·开发语言·数据结构·算法
凡尘——雨落凡尘28 分钟前
Python列表索引越界IndexError问题深度解析与解决办法
python·indexerror·list index out of range
前端炒粉30 分钟前
简易实现ssr
开发语言·前端·javascript
库克克36 分钟前
【C++】 unordered_map 与unordered_set
开发语言·c++
郝同学今天有进步吗1 小时前
构建 LangGraph Code Review Agent(七):实现规则匹配、Finding Guardrails 与 Markdown 报告
python·ai·fastapi·code review
雪的季节1 小时前
人工智能 AI 5问
开发语言
xuhe22 小时前
一劳永逸!解决 AutoDL 系统盘(30GB)爆满与 pip 缓存迁移
linux·python·ai·jupyter
李迟2 小时前
一种轻量级C++ CSV文件读写库的实现方案
开发语言·c++
小园子的小菜2 小时前
Java 并发编程:线程安全队列全解 —— 阻塞与非阻塞实现原理及源码深度剖析
java·开发语言
CodexDave2 小时前
Python 自动化接单实战(一):把 CSV 需求做成配置驱动解析器
java·python·自动化·json·数据清洗·python自动化·csv处理