如何从测试内部访问 py.test capsys? [英] How to access the py.test capsys from inside a test?

查看:46
本文介绍了如何从测试内部访问 py.test capsys?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

py.test 文档说我应该将 capsys 参数添加到我的测试方法中,但在我的情况下这似乎不可能.

py.test documentations says that I should add capsys parameter to my test methods but in my case this doesn't seem to be possible.

class testAll(unittest.TestCase):

    def setUp(self):
        self.cwd = os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0])
        os.chdir(self.cwd)

    def execute(self, cmd, result=0):
        """
        Helper method used by many other tests, that would prevent replicating too much code.
        """
        # cmd = "%s > /dev/null 2>&1" % cmd
        ret = os.system(cmd) >> 8
        self.assertEqual(ret, result, "`%s` returned %s instead of %s (cws=%s)\n\t%s" % (cmd, ret, result, os.getcwd(), OUTPUT)) ### << how to access the output from here

    def test_1(self):
        self.execute("do someting", 0) 

推荐答案

您可以在继承 capsys 夹具的类中定义一个辅助函数:

You could define a helper function in the class that inherits the capsys fixture:

@pytest.fixture(autouse=True)
def capsys(self, capsys):
    self.capsys = capsys

然后在测试内部调用这个函数:

Then call this function inside the test:

out,err = self.capsys.readouterr()

assert out == 'foobar'

感谢 Michał Krassowski 的解决方法,帮助我解决了类似的问题.

Kudos to Michał Krassowski for his workaround which helped me work through a similar problem.

https://github.com/pytest-dev/pytest/issues/2504#issuecomment-309475790

这篇关于如何从测试内部访问 py.test capsys?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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