Skip to content

Instantly share code, notes, and snippets.

@mjuenema
Last active January 27, 2021 22:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjuenema/86968b8d93d4ce60f5ff4c2d596ac33e to your computer and use it in GitHub Desktop.
Save mjuenema/86968b8d93d4ce60f5ff4c2d596ac33e to your computer and use it in GitHub Desktop.
Capture and test sys.stdout with nosetest

Capture and test sys.stdout with nosetest

import sys
import tempfile

import sys
import tempfile

class Base(object):
    def setup(self):
        sys.stdout = self._stdout = tempfile.NamedTemporaryFile('w+', delete=False)
        sys.stderr.write(self._stdout.name + ' ')

    def teardown(self):
        self._stdout.close()
        sys.stdout = sys.__stdout__

    @property
    def stdout(self):
        self._stdout.seek(0)
        return self._stdout.read()[:-1]    # Remove trailing \n:w


class Test(Base):

    def test1(self):
        print("123")
        assert self.stdout == "123"
        print("456")
        assert self.stdout == "123\n456"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment