我想在 pytest 测试中使用 stdin [英] I want to use stdin in a pytest test

查看:46
本文介绍了我想在 pytest 测试中使用 stdin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PyTest 文档指出 stdin 被重定向到 null,因为没有人愿意在批处理测试上下文中进行交互式测试.这是真的,但交互式并不是标准输入的唯一用途.我想测试使用 stdin 的代码,就像它使用任何其他文件一样.我很高兴捕获 stdout 和 sterr,但如何以符合 PyTest 的方式将 stdin 连接到 io.StringIO 对象?

The PyTest documentation states that stdin is redirected to null as no-one will want to do interactive testing in a batch test context. This is true, but interactive is not the only use of stdin. I want to test code that uses stdin just as it would use any other file. I am happy with stdout and sterr being captured but how to actually have stdin connected to an io.StringIO object say in a PyTest conformant way?

推荐答案

您可以 猴子补丁:

def test_method(monkeypatch):
    monkeypatch.setattr('sys.stdin', io.StringIO('my input'))
    # test code

这篇关于我想在 pytest 测试中使用 stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆