About testing your code in Python (Part 1) — Introduction

Today's post starts a series about unit testing with pyTest. We'll cover why you should test your code and what makes pyTest an excellent choice for testing it.

About the Importance of Testing

Let's first address the elephant in the room: Why should you test your code at all?

Testing your code gives you peace of mind: Let's assume you're the world's best and smartest Python programmer. Still, as a human being, you're prone to making mistakes, syntactical or logical. The latter ones are harder to catch, and therefore testing if your code logic behaves as it should, saves you countless headaches.

Tests are a quick way to document your code: No matter what, documenting your code is a crucial part for making your code useful to others, or to remember what you did these many months ago. Unit tests, or their test cases for that matter, can serve as an interim documentation until you have something better, like a proper documentation.

Unit tests got your back and help not only to increase your code's quality but help you to structure and understand your code much better.

Why using a Testing Framework

Now, that we know the benefits of testing our code, wouldn't be print statements sufficient? They should help us test our code, and we have some kind of documentation as well. Why should we learn an additional framework?

The point here is about reproducibility. Code is very dynamic, meaning that you will add, change and remove functionalities down the line. A framework provides you the ability to automate the process of checking if your code behaves as you expect.

Therefore, you don't have to keep track of that one ominous print statement somewhere in your code. Moreover, you have a separation of concerns, meaning the files containing your code are only for that matter, while you have dedicated code for your tests. Finally, a framework is easy to execute: You fire a single command, and it tests all your cases and gives you a nice overview if and where something failed.

Why pyTest?

Testing with a framework is the way to go, but which framework should we use?

Although there are many frameworks out there, and all of them have their own right to exist, I recommend using pyTest. The reason is that building a good test suite with pyTest is easy and quick.

Ultimately, you develop your application and don't want to spend more time than necessary with your test suite. Without functionality to test, tests are useless after all.

In a nutshell

Testing your code is important, and you should use a framework, namely pyTest, for testing your code. In the upcoming part we will focus on the process of designing, writing, and executing tests for a sample project.