0

I am creating a unittest and I want to test the output of a method. My code is kinda big so I will use a little example. Let's say my method looks like this.

def foo():
     print "hello"

Now I go to my unittest class and I run the code in the unittest like this.

def test_code():
     firstClass.foo()

I want to test the output I get from the console. I saw some people using subprocess but there I can only give arguments. So my question is how could I get the output from the console to test it in my unittest class.

Blinxen
  • 807
  • 2
  • 13
  • 26

1 Answers1

1

A simple solution would be to remap stdout to a file and process the file post execution of your method inside your unit test class.

import sys
sys.stdout = open('result', 'w')

test_code()
# read 'result'

Edit: Alternatively, you could manipulate the file stream using the StringIO module.

import StringIO
output = StringIO.StringIO()
sys.stdout = output

Example:

#!remap.py
import sys
import StringIO

backup_sys = sys.stdout # backup our standard out
output = StringIO.StringIO() # creates file stream for monitoring test result
sys.stdout = output
print 'test' # prints to our IO stream

sys.stdout = backup_sys # remap back to console
print output.getvalue() # prints the entire contents of the IO stream

Output

test

More details on the module can be found here.

S. Whittaker
  • 118
  • 9
  • Well that might work but I don't want to create a file, because it's just a test. – Blinxen Oct 31 '17 at 11:41
  • I've added an alternative method that may work for you: the `StringIO module`. This will emulate the file write method and allow you to easily remap the `print` function. – S. Whittaker Oct 31 '17 at 11:50