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
相关推荐
微笑星河q7 小时前
C++类和对象(下)初始化列表、类型转换、static、友元、内部类、匿名对象
开发语言·c++
凤年徐7 小时前
【Python】Python 语法速通指南
开发语言·python
quantdash_cc7 小时前
量化数据清洗应该放在数据层还是策略层?从系统架构看清职责边界
开发语言·python·数据分析·系统架构·量化交易·股票数据·quantdash
梅雅达编程笔记7 小时前
Day 06 · 第一个 API 接口:从 Model 到 JSON
python·django·drf·后端开发·restful api·序列化器
yi0117 小时前
DAY28: LeetCode 111. 二叉树的最小深度
人工智能·笔记·python·算法·leetcode·二叉树·递归
|_⊙7 小时前
C++ 类和对象零散知识点
开发语言·c++
xiangyun617 小时前
C++ list 模拟实现(二):const迭代器与反向迭代器,模板的黑魔法
开发语言·数据库·c++·算法·stl·list
诺伦7 小时前
从一键分发到 AI 自动运营:内容矩阵工具三代技术架构拆解 | RiseClaw玄策
python·agent·架构设计·增长运营·ai自动运营·内容营销自动化
DLite8 小时前
NLang 0.9.0发布:成为可嵌入语言
开发语言·编程语言·编译技术·nlang
有同事要进步8 小时前
LeetCode 14. 最长公共前缀:纵向扫描一次讲透
开发语言·python