Created
September 19, 2018 09:48
-
-
Save pitrk/11755d23fd6ca441b1ef6c09f644a103 to your computer and use it in GitHub Desktop.
Testing if function prints something correctly in python 3 with unittest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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