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
相关推荐
databook1 天前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室1 天前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三1 天前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
这里有鱼汤2 天前
小白必看:QMT里的miniQMT入门教程
后端·python