Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 
like image 649
sorin Avatar asked Apr 16 '13 14:04

sorin


People also ask

What is capsys in Python?

The capsys builtin fixture provides two bits of functionality: it allows you to retrieve stdout and stderr from some code, and it disables output capture temporarily.

Can I use Unittest with Pytest?

pytest supports running Python unittest -based tests out of the box. It's meant for leveraging existing unittest -based test suites to use pytest as a test runner and also allow to incrementally adapt the test suite to take full advantage of pytest's features.

What is Pytest Unittest?

unittest offers a way of collecting several tests into one, but they don't show up as individual tests in result reports. If one test fails and the rest pass, then the entire group will still return a single failing result. pytest offers its own solution in which each test can pass or fail independently.


1 Answers

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

like image 160
Thomas Wright Avatar answered Sep 23 '22 00:09

Thomas Wright