Unit Testing in Python

Yang Zhou
TechToFreedom
Published in
3 min readAug 13, 2020

--

Unit Testing in Python
Photo by Nicolas Thomas on Unsplash

Introduction

Unit testing is an important part of “Test-Driven Development (TDD)”. It’s used to test the correctness of a module, a function or a class.

Let’s start from a question: how to test a function works correctly or not?

The method is simple:

  • Design some different inputs for the function, and expected results.
  • Run the function using the inputs and check out whether it will return the expected results.

For example, we wrote a function abs(), which is used to find the absolute value of a number, then we can design some inputs and outputs as test cases:

  • Enter a positive number, such as 99, 3.14, and expect the return value to be the same as the input: 99, 3.14.
  • Enter a negative number, such as -10, -6.28, and expect the return value to be opposite to the input: 10, 6.28
  • Enter 0 , expect to return 0 .

If the function passes all the test cases, it works as expected and no bugs found. If not, we should start debugging.

The problem is, every time testing the function, we need to enter the inputs of the test cases manually. Even if we just modified the function a little bit, we have to enter every case and see the results again. It is such a…

--

--