如何从测试中访问py.test capsys?

时间:2013-04-16 14:14:17

标签: python unit-testing pytest python-unittest

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

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) 

1 个答案:

答案 0 :(得分:-1)

您可以在继承capsys固定装置的类中定义一个辅助函数:

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

然后在测试中调用此函数:

out,err = self.capsys.readouterr()

assert out == 'foobar'

对MichałKrassowski的变通办法表示敬意,这帮助我解决了类似的问题。

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