Writing Python Unit Tests in PyCharm

Опубликовано: 22 Сентябрь 2021
на канале: buckmasterinstitute
3,606
4

Created and recorded by Yiming Cai. September 2021

If you ever heard TDD: Test-Driven Development, then you must have heard unit test. Unit test is very important for software development, it is used to test the correctness of a module, a function or a class. With the unit test, we can ensure the behaviour of a program module behaves what we expected.

Why do we need Python unit test

In addition to ensuring that the behaviour of the program meets the developer's expectations, the python unit test can also ensure that the function of a refactored function will not cause new problems. In the process of software development, it is very common to refactor part of the code. If you have good unit tests, you can prevent problems caused by many function refactorings

In this video, I will show you some examples of Python unit test by using PyCharm. Pycharm contains some easy shortcuts to help developers save time when coding, also, they have shortcuts for writing tests.

To generate a new test, simply right click the function you want to test, click generate-test, pycharm will create a new empty test for you.

(Will have examples of sample Python unit test)
(Example I will use is my filename detector)

The purpose of my function is to generate a proper filename from the input. If the input has the wrong format, this function will automatically convert the filename into a proper filename.

We will test four cases in this unit test. Inputs I will use here are empty input, non-string input, most expected input(filename.wav) and input without file format.

Assertequal will be the best choice in this situation. We want to know if our output satisfied our expectations, in this case, a short string.

(write code)

In pycharm, test one unit of python code is also easy. You can found there is a blue play button beside the first line of your test code, click and choose run or debug, the result of this unit test will be shown in the terminal.

Note even if you put four situations for testing, in the terminal you can only see 1 pass. This is because all four tests are included in this specific test for one function.