Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Introduction to Unittest | Unittest Framework
Python Advanced Concepts
course content

Course Content

Python Advanced Concepts

Python Advanced Concepts

1. Modules and Imports
2. Error Handling
3. File Handling
4. Pytest Framework
5. Unittest Framework
6. Iterators and Generators

bookIntroduction to Unittest

Unittest is part of Python's standard library, which means no additional installations are needed to get started. It is designed around the concept of test cases, which are Python classes derived from the framework’s TestCase class. Unittest is an excellent tool for anyone beginning their testing journey because it structures tests in a way that reflects the principles of object-oriented programming.

The Structure of Unittest

In Unittest, each test is a method within a subclass of unittest.TestCase. This design encourages grouping related tests together, which can help organize testing code logically and make it more readable.

Writing a Test with Unittest

Let’s test a simple function that calculates the average of two numbers. Here’s the function we want to test:

Creating a Test Case

To create a test case, you will define a class that inherits from unittest.TestCase. Within this class, you can then define methods to test the calculate_average function.

  • First, you import the Unittest module, which is part of Python's standard library;
  • class TestCalculateAverage(unittest.TestCase) creates a new test case. It inherits from unittest.TestCase, which provides the testing functionality;
  • Each method in the class should start with test_;
  • The methods uses specific assert statement for checking whether condition is true.

Example of a Successful Test Output

When all tests pass in Unittest, the output is straightforward and indicates that all tests ran successfully without any failures. Here's an example of a successful test run:

Example of a Failed Test Output

If one or more tests fail, the output will provide details about the failures, including which tests failed and why. Here’s an example of what it might look like when a test fails:

This output includes:

  • ..F indicates that three tests were run; the first two passed (represented by ..), and the third failed (F);
  • FAILED (failures=1) shows that there was one failure among the tests run;
  • The detailed error report starts with the test identifier (test_average_floats) and the class (TestCalculateAverage). It provides a traceback to the line in your test code that caused the failure and explains the nature of the assertion error, including the expected value, the actual value, and the acceptable margin of error.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 1
We're sorry to hear that something went wrong. What happened?
some-alt