加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 使用fixture时没有被pytest capsys捕获的stdout

发布时间:2020-12-20 13:16:20 所属栏目:Python 来源:网络整理
导读:我正在使用pytest fixture来模拟用于测试脚本的命令行参数.这样,每个测试函数共享的参数只需要在一个地方声明.我也试图使用pytest的capsys来捕获脚本打印的输出.考虑以下愚蠢的例子. from __future__ import print_functionimport pytestimport othermodfrom
我正在使用pytest fixture来模拟用于测试脚本的命令行参数.这样,每个测试函数共享的参数只需要在一个地方声明.我也试图使用pytest的capsys来捕获脚本打印的输出.考虑以下愚蠢的例子.

from __future__ import print_function
import pytest
import othermod
from sys import stdout


@pytest.fixture
def shared_args():
    args = type('',(),{})()
    args.out = stdout
    args.prefix = 'dude:'
    return args


def otherfunction(message,prefix,stream):
    print(prefix,message,file=stream)


def test_dudesweet(shared_args,capsys):
    otherfunction('sweet',shared_args.prefix,shared_args.out)
    out,err = capsys.readouterr()
    assert out == 'dude: sweetn'

这里,capsys没有正确捕获sys.stderr.如果我从sys import stdout和args.out = stdout直接进入测试函数,事情按预期工作.但这会使事情变得更加混乱,因为我必须为每个测试重新声明这些语句.难道我做错了什么?我可以使用带固定装置的帽子吗?

解决方法

在测试运行之前调用Fixture.在您的示例中,shared_args fixture在其他函数可以向stdout写入任何内容之前读取stdout.

解决问题的一种方法是让你的灯具返回一个可以做你想做的事情的功能.您可以根据您的使用情况确定夹具的范围.

from __future__ import print_function
import pytest
from sys import stdout
import os


@pytest.fixture(scope='function')
def shared_args():
    def args_func():
        args = type('',{})()
        args.out = stdout
        args.prefix = 'dude:'
        return args
    return args_func


def otherfunction(message,capsys):
    prefix,out = shared_args().prefix,shared_args().out
    otherfunction('sweet',out)
    out,err = capsys.readouterr()
    assert out == 'dude: sweetn'

您没有正确使用capsys.readouterr().请在此处查看capsys的正确用法:https://stackoverflow.com/a/26618230/2312300

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读