DEV Community

Cover image for Tests Everywhere - Python
Roger Viñas Alcon
Roger Viñas Alcon

Posted on • Updated on

Tests Everywhere - Python

GitHub logo rogervinas / tests-everywhere

🤠 Tests, Tests Everywhere!

Python testing this simple Hello World with unittest

Show me the code

Implementation

  1. Create HelloMessage class in hello_message.py:
class HelloMessage:
  def __init__(self):
    self.text = "Hello World!"
Enter fullscreen mode Exit fullscreen mode
  1. Create HelloConsole class in hello_console.py:
from builtins import print as __print__

class HelloConsole:
  def print(self, text):
    __print__(text)
Enter fullscreen mode Exit fullscreen mode

Note that we have to import print system function as __print__ to avoid conflict with HelloConsole own print method.

  1. Create HelloApp class in hello_app.py:
class HelloApp:
  def __init__(self, message, console):
    self.message = message
    self.console = console

  def print_hello(self):
    self.console.print(self.message.text)
Enter fullscreen mode Exit fullscreen mode
  1. Create main function in __main__.py that wraps it all together:
message = HelloMessage()
console = HelloConsole()
app = HelloApp(message, console)
app.print_hello()
Enter fullscreen mode Exit fullscreen mode

Test

Following unittest > Basic example and unittest.mock > Quick Guide guides ...

  1. Test HelloMessage in test_hello_message.py:
class HelloMessageTest(unittest.TestCase):
  def test_should_return_hello_world(self):
    message = HelloMessage()
    self.assertEqual(message.text, "Hello World!")
Enter fullscreen mode Exit fullscreen mode
  1. Test HelloApp in test_hello_app.py:
class HelloAppTest(unittest.TestCase):
  def test_should_print_hello_message(self):
    message_text = "Hello Test!"

    # 2.1 Create a mock of HelloMessage
    message = MagicMock()
    # 2.2 Return "Hello Test!" whenever text is called
    message.text = message_text

    # 2.3 Create a mock of HelloConsole
    console = MagicMock()
    # 2.4 Mock print method
    console.print = MagicMock()

    # 2.5 Create a HelloApp, the one we want to test, passing the mocks
    app = HelloApp(message, console)
    # 2.6 Execute the method we want to test
    app.print_hello()

    # 2.7 Verify HelloConsole mock print() method
    # has been called once with "Hello Test!"
    console.print.assert_called_once_with(message_text)
Enter fullscreen mode Exit fullscreen mode
  1. Test output should look like:
test_should_print_hello_message (test.test_hello_app.HelloAppTest.test_should_print_hello_message) ... ok
test_should_return_hello_world (test.test_hello_message.HelloMessageTest.test_should_return_hello_world) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK
Enter fullscreen mode Exit fullscreen mode

Happy Testing! 💙

Top comments (0)