Mike Driscoll Profile picture
I tweet about everything #Python Writing about Python @mousevspython @realpython Teaching at @TeachMePy Author of multiple books - https://t.co/MdP25zw5zQ

Nov 19, 2021, 13 tweets

Today we are going to talk about the basics of unit testing in #Python

πŸ§΅πŸπŸ‘‡

The Python programming language includes built-in packages for testing:

🐍 doctest
🐍 unittest

I already did a thread on Python's `doctest`:

To get started with unit testing in Python, you need some code to unit test

Here's some code you can use that you can save as "mymath.py"

To add a unit test in Python, you normally create a new file with the same name as the file you are testing, but prepended with the word "test" -> "test_mymath.py"

Then you subclass `unittest.TestCase` and create one or more test methods

Here's an example:

To keep things simple, save the test file in the same directory as the file that you are testing.

Then open up a terminal and navigate to the folder that has your code.

Finally, you run the following command:

What does this output mean? You will see dots or periods for each test that passes and "F"s for tests that fail.

In this example, you have 3 tests and 3 periods, so they all passed!

If you'd like more information about what tests are running, you can pass the `-v` argument for verbose mode:

You can get a full listing of the arguments you can pass to your test by using `-h` for help:

You can even specify which tests you want it to run specifically rather than running all of them:

You can do a lot with `unittest`. Check out the full documentation for details:

docs.python.org/3/library/unit…

The examples in this thread come from my unittest tutorial on @mousevspython

My tutorial also covers:

🐍 More complex tests
🐍 Test suites
🐍 Skipping tests
🐍 Integrating with doctest

blog.pythonlibrary.org/2016/07/07/pyt…

I hope you enjoyed learning the basics of unit testing with Python.

Follow me for more great Python content!

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling