Skip to content

Instantly share code, notes, and snippets.

@pitrk
Created September 19, 2018 09:48
Show Gist options
  • Save pitrk/11755d23fd6ca441b1ef6c09f644a103 to your computer and use it in GitHub Desktop.
Save pitrk/11755d23fd6ca441b1ef6c09f644a103 to your computer and use it in GitHub Desktop.
Testing if function prints something correctly in python 3 with unittest
# Python 3.7
import io
import unittest
import unittest.mock
# -- function --
def print_hello_world() -> None:
print('Hello World!')
# - test--
class TestFunction(unittest.TestCase):
def test_print_hello_world_prints_correctly_with(self):
with unittest.mock.patch('sys.stdout', new_callable=io.StringIO) as mock_stdout:
print_hello_world()
self.assertEqual(
mock_stdout.getvalue(),
'Hello World!\n' # It's important to remember about '\n'
)
@unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
def test_print_hello_world_prints_correctly_decorator(self, mock_stdout):
print_hello_world()
self.assertEqual(
mock_stdout.getvalue(),
'Hello World!\n' # It's important to remember about '\n'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment