首页 > 解决方案 > 如何使用 pytest 测试 python 控制台脚本输出?

问题描述

假设您有一个需要测试输出的 python 脚本,如下所示:

print("Hello World!")

如何使用 pytest 插件 pytest-console-scripts 进行自动化测试?

标签: pythonconsoleoutputpytestscript

解决方案


  1. 安装 pytest-console-scripts
  2. 使用以下脚本进行自动测试:
from pytest_console_scripts import ScriptRunner

class TestHelloWorld:

    def test_success(self, script_runner: ScriptRunner) -> None:
        ret = script_runner.run('helloworld.py', print_result=True, shell=True)
        assert ret.success
        assert ret.stdout == 'Hello World!\n'
        assert ret.stderr ==''

推荐阅读