8

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) 
4

1 回答 1

2

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

于 2020-11-16T17:40:16.607 回答