简体   繁体   中英

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

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) 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM