I have a python3.7 script, which takes a YAML file as input and processes it depending on the instructions within. The YAML file I am using for unit testing looks like this:
... tasks: - echo '1' - echo '2' - echo '3' - echo '4' - echo '5' The script loops over tasks and then runs each one, using os.system() call.
The manual testing indicates, that the output is as expected:
1 2 3 4 5 But I can't make it work in my unit test. Here's how I'm trying to capture the output:
from application import application from io import StringIO import unittest from unittest.mock import patch class TestApplication(unittest.TestCase): def test_application_tasks(self): expected = ['1','2','3','4','5'] with patch('sys.stdout', new=StringIO()) as fakeOutput: application.parse_event('some event') # print() is called here within parse_event() self.assertEqual(fakeOutput.getvalue().strip().split(), expected) When running python3 -m unittest discover -s tests, all I get is AssertionError: Lists differ: [] != ['1', '2', '3', '4', '5'].
I also tried using with patch('sys.stdout', new_callable=StringIO) as fakeOutput: instead, but to no avail.
Another thing I tried was self.assertEqual(fakeOutput.getvalue(), '1\n2\n3\n4\n5'), and here what the unittest outputs:
AssertionError: '' != '1\n2\n3\n4\n5' + 1 + 2 + 3 + 4 + 5 Obviously, the script works and outputs the right result, but fakeOutput does not capture it.
Using patch as a decorator does not work either:
from application import application from io import StringIO import unittest from unittest.mock import patch class TestApplication(unittest.TestCase): @patch('sys.stdout', new_callable=StringIO) def test_application_tasks(self): expected = ['1','2','3','4','5'] application.parse_event('some event') # print() is called here within parse_event() self.assertEqual(fakeOutput.getvalue().strip().split(), expected) Would output absolutely the same error: AssertionError: Lists differ: [] != ['1', '2', '3', '4', '5']
application? A trivial definition withprint("Here is some output")does not reproduce the behavior you describe.os.systemthough I'll take a guess...echoright away