How to access the py.test capsys from inside a test?

北慕城南 提交于 2020-12-10 00:17:11

问题


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) 

回答1:


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'

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



来源:https://stackoverflow.com/questions/16039463/how-to-access-the-py-test-capsys-from-inside-a-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!