Python Unit Test with unittest



Unit Testing is a one of the best practice that should be performed starting from the first stages and throughout the whole process of development. Unit tests are written to detect bugs early in the development of the application when bugs are less frequent and less expensive to fix.

In this playground I’ll cover the basics of how to create and run a simple test using unittest.

The source code is on GitHub, please feel free to come up with proposals to improve it.

Creating a simple test:

Supposing that we have a very simple add function which return the sum of two integer.

To create a unit test, we have to:

  • Create a class derived from unittest.TestCase
  • Create a function that start with "test"
What's the result of 3 + 4 !!

In the second example we will check if the result of 3 + 4 equals 8

What's the result of 3 + 4 !!

In these two example we used assertEqual() function to check for an expected result.

unittest provide others functions such as:

  • assertTrue() or assertFalse() to verify a condition
  • assertRaises() to verify that a specific exception gets raised.
  • setUp() and tearDown() methods to define instructions that will be executed before and after each test method

Using assertRaises

Raise Exception when the separator is not a string

Using assertTrue and assertIn

'1' exist in the list but FOo is not uppercase


When a setUp() method is defined, the test runner will run that method prior to each test.

setUp() executed before each test !

Test discovery

Test discovery is used when you have many test files in that case It would be annoying to have to run each test file separately.

Supposing that you have all your test files in a "tests" directory. To run all of the unittests, use python -m unittest discover tests

Create your playground on
This playground was created on, our hands-on, knowledge-sharing platform for developers.
Go to
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
Online Participants