Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - assertLess() function in unittest
Next article icon

Python Unittest Tutorial | Unit Testing in Python using unittest Framework

Last Updated : 22 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Unit Testing is the first level of software testing where the smallest testable parts of software are tested. This is used to validate that each software unit performs as designed. The unittest test framework is Python xUnit style framework. In this article, we will learn about unittest framework with the help of examples.

Table of Content

  • What is Python Unittest?
  • Why Choose Unittest in Python?
  • Assert Methods in Python Unittest Framework
  • Implementing Unit Tests Using Python Unittest

What is Python Unittest?

Python Unittest is a built-in testing framework that provides a set of tools for testing our code's functionality in a more systematic and organized manner. With unittest framework, we can create test cases, fixtures, and suites to verify if our code behaves as expected. It allows us to write test methods within classes that check different aspects of our code such as input, output, and edge cases. It also supports test discovery making it easy for us to automate test execution across our project.

Why Choose Unittest in Python?

Developers often choose Python's unittest framework for its built-in nature, widespread familiarity, comprehensive features, seamless integration with other tools, and proven reliability. As part of Python's standard library, unittest requires no additional installations, making it easily accessible. Unit tests promote consistency in testing practices, aiding collaboration and maintenance. While other frameworks like Pytest and nose offer alternatives, unittest remains a popular choice for its stability and versatility.

Assert Methods in Python Unittest Framework

unittest has lots of methods to assert on the values, types, and existence of variables. Below are some of the methods that are commonly used to write assertions.

Method

Description

.assertEqual(a, b)

Checks if a is equal to b, similar to the expression a == b.

.assertTrue(x)

Asserts that the boolean value of x is True, equivalent to bool(x) is True.

.assertIsInstance(a, b)

Asserts that a is an instance of class b, similar to the expression isinstance(a, b).

.assertIsNone(x)

Ensures that x is None, similar to the expression x is None.

.assertFalse(x)

Asserts that the boolean value of x is False, similar to bool(x) is False.

.assertIs(a, b)

Verifies if a is identical to b, akin to the expression a is b.

.assertIn(a, b)

Checks if a is a member of b, akin to the expression a in b.

OOP Concepts Supported by Unittest Framework

The White Box Testing method is used for Unit tests. Below are some of supported oops concept by Unitttest framework:

  • test fixture: A test fixture is used as a baseline for running tests to ensure that there is a fixed environment in which tests are run so that results are repeatable. Examples :
    • creating temporary databases.
    • starting a server process.
  • test case: A test case is a set of conditions which is used to determine whether a system under test works correctly.
  • test suite: Test suite is a collection of testcases that are used to test a software program to show that it has some specified set of behaviours by executing the aggregated tests together.
  • test runner: A test runner is a component which set up the execution of tests and provides the outcome to the user.

Python Unittest Example

Now, we will implement the unit test using Python Unittest framework.

Example 1: test.py

Here, we will write a a simple function named add() that takes two numbers and returns their sum. Additionally, it includes a test case class TestAddFunction that inherits from unittest.TestCase. Within this class, three test methods are defined to verify different scenarios of the add() function.

Python3
import unittest  def add(a, b):     return a + b  class TestAddFunction(unittest.TestCase):     def test_add_positive_numbers(self):         self.assertEqual(add(1, 2), 3)      def test_add_negative_numbers(self):         self.assertEqual(add(-1, -2), -3)      def test_add_mixed_numbers(self):         self.assertEqual(add(1, -2), -1)         self.assertEqual(add(-1, 2), 1)  if __name__ == '__main__':     unittest.main() 

This is the basic test code using unittest framework, which is having a single test. This test() method will fail if TRUE is ever FALSE.

Now, we will see how to run Unittest file in Python. To run the unit tests, run the following command in your terminal:

python test.py

Output:

...
----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

For instance, if we change the expected value from 3 to, let's say, 2 in the test_add_positive_numbers, the test would fail and we'd have this output.

Output:

..F
======================================================================
FAIL: test_add_positive_numbers (__main__.TestAddFunction)
----------------------------------------------------------------------
Traceback (most recent call last):
File "f:\GeeksforGeeks\example_package\main.py", line 8, in test_add_positive_numbers
self.assertEqual(add(1, 2), 2)
AssertionError: 3 != 2

----------------------------------------------------------------------
Ran 3 tests in 0.001s

FAILED (failures=1)

Here, in the output the "." on the first line of output means that a test passed. "-v" option is added in the command line while running the tests to obtain more detailed test results.

Command:

python test.py -v

Output:

test_add_mixed_numbers (__main__.TestAddFunction) ... ok
test_add_negative_numbers (__main__.TestAddFunction) ... ok
test_add_positive_numbers (__main__.TestAddFunction) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.002s

OK

Outcomes Possible in Unit Testing

There are three types of possible test outcomes :

  • OK - This means that all the tests are passed.
  • FAIL - This means that the test did not pass and an AssertionError exception is raised.
  • ERROR - This means that the test raises an exception other than AssertionError.

Let's walk through an another example to understand the implementation of unittest framework.

Example 2

Python3
import unittest  class TestStringMethods(unittest.TestCase):      def setUp(self):         pass      # Returns True if the string contains 4 a.     def test_strings_a(self):         self.assertEqual('a'*4, 'aaaa')      # Returns True if the string is in upper case.     def test_upper(self):         self.assertEqual('foo'.upper(), 'FOO')      def test_isupper(self):         self.assertTrue('FOO'.isupper())         self.assertFalse('Foo'.isupper())      def test_strip(self):         s = 'geeksforgeeks'         self.assertEqual(s.strip('geek'), 'sforgeeks')      # Returns true if the string splits and matches     # the given output.     def test_split(self):         s = 'hello world'         self.assertEqual(s.split(), ['hello', 'world'])         with self.assertRaises(TypeError):             s.split(2)  if __name__ == '__main__':     unittest.main() 

unittest.TestCase is used to create test cases by subclassing it. The last block of the code at the bottom allows us to run all the tests just by running the file. Basic terms used in the code :

  1. assertEqual() - This statement is used to check if the result obtained is equal to the expected result.
  2. assertTrue() / assertFalse() - This statement is used to verify if a given statement is true or false.
  3. assertRaises() - This statement is used to raise a specific exception.

Description of Tests

  1. test_strings_a(): This test is used to test the property of string in which a character say 'a' multiplied by a number say 'x' gives the output as x times 'a'. The assertEqual() statement returns true in this case if the result matches the given output.
  2. test_upper(): This test is used to check if the given string is converted to uppercase or not. The assertEqual() statement returns true if the string returned is in uppercase.
  3. test_isupper(): This test is used to test the property of string which returns TRUE if the string is in uppercase else returns False. The assertTrue() / assertFalse() statement is used for this verification.
  4. test_strip(): This test is used to check if all chars passed in the function have been stripped from the string. The assertEqual() statement returns true if the string is stripped and matches the given output.
  5. test_split(): This test is used to check the split function of the string which splits the string through the argument passed in the function and returns the result as list. The assertEqual() statement returns true in this case if the result matches the given output.

unittest.main() provides a command-line interface to the test script. On running the above script from the command line, following output is produced:

.....
----------------------------------------------------------------------
Ran 5 tests in 0.000s

OK

Next Article
Python - assertLess() function in unittest

A

Aditi Gupta
Improve
Article Tags :
  • Python
  • Python unittest-library
  • Python Testing
Practice Tags :
  • python

Similar Reads

    Python Unittest Tutorial | Unit Testing in Python using unittest Framework
    Unit Testing is the first level of software testing where the smallest testable parts of software are tested. This is used to validate that each software unit performs as designed. The unittest test framework is Python xUnit style framework. In this article, we will learn about unittest framework wi
    7 min read

    Python Unittest Comparison Assertions

    Python - assertLess() function in unittest
    assertLess() in Python is an unittest library function that is used in unit testing to check whether the first given value is less than the second value or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. This function check that
    2 min read
    Python - assertGreater() function in unittest
    assertGreater() in Python is an unittest library function that is used in unit testing to check whether the first given value is greater than the second value or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. This function check
    2 min read
    Python - assertGreaterEqual() function in unittest
    assertGreaterEqual() in Python is an unittest library function that is used in unit testing to check whether the first given value is greater than or equal to the second value or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. Th
    2 min read
    Python - assertLessEqual() function in unittest
    assertLessEqual() in Python is an unittest library function that is used in unit testing to check whether the first given value is less than or equal to the second value or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. This fun
    2 min read

    Python Unittest Approximate Value Assertions

    Python unittest - assertNotAlmostEqual() function
    assertNotAlmostEqual() in Python is a unittest library function that is used in unit testing to check whether two given values are not approximately. This function will take five parameters as input and return a boolean value depending upon the assert condition. This function check that first and se
    3 min read
    Python unittest - assertAlmostEqual() function
    assertAlmostEqual() in Python is a unittest library function that is used in unit testing to check whether two given values are almost equal or not. This function will take five parameters as input and return a boolean value depending upon the assert condition. This function check that first and sec
    3 min read

    Python Unittest Type Assertions

    Python unittest - assertIsInstance() function
    assertIsInstance() in Python is a unittest library function that is used in unit testing to check whether an object is an instance of a given class or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. If the object is an instance o
    2 min read
    Python unittest - assertNotIsInstance() function
    assertNotIsInstance() in Python is a unittest library function that is used in unit testing to check whether an object is not an instance of a given class or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. If the object is not an
    2 min read

    Python Unittest Membership Assertions

    Python unittest - assertIn() function
    assertIn() in Python is a unittest library function that is used in unit testing to check whether a string is contained in other or not. This function will take three string parameters as input and return a boolean value depending upon the assert condition. If the key is contained in container strin
    2 min read
    Python unittest - assertNotIn() function
    assertNotIn() in Python is a unittest library function that is used in unit testing to check whether a string is not contained in other. This function will take three string parameters as input and return a boolean value depending upon the assert condition. If the key is not contained in container s
    2 min read

    Python Unittest Equality Assertions

    Python unittest - assertEqual() function
    assertEqual() is a function from Python's unittest library used for unit testing. It checks whether two values are equal and returns a boolean result based on the condition. If both values are equal, the test passes otherwise it fails and raises an AssertionError with an optional error message. For
    3 min read
    Python unittest - assertNotEqual() function
    assertNotEqual() in Python is a unittest library function that is used in unit testing to check the inequality of two values. This function will take three parameters as input and return a boolean value depending upon the assert condition. If both input values are unequal assertNotEqual() will retur
    2 min read

    Python Unittest None Assertions

    Python unittest - assertIsNotNone() function
    assertIsNotNone() in Python is a unittest library function that is used in unit testing to check that input value is not None. This function will take two parameters as input and return a boolean value depending upon assert condition. If input value is not equal to None assertIsNotNone() will return
    2 min read
    Python unittest - assertIsNone() function
    assertIsNone() in Python is a unittest library function that is used in unit testing to check that input value is None or not. This function will take two parameters as input and return a boolean value depending upon assert condition. If input value is equal to None assertIsNone() will return true e
    2 min read

    Python Unittest Identity Assertions

    Python unittest - assertIn() function
    assertIn() in Python is a unittest library function that is used in unit testing to check whether a string is contained in other or not. This function will take three string parameters as input and return a boolean value depending upon the assert condition. If the key is contained in container strin
    2 min read
    Python unittest - assertIsNot() function
    assertIsNot() in Python is a unittest library function that is used in unit testing to test whether first and second input value don't evaluate to the same object or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. If both inputs
    2 min read

    Python Unittest Boolean Assertions

    Python unittest - assertFalse() function
    assertFalse() in Python is a unittest library function that is used in unit testing to compare test value with false. This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is false then assertFalse() will return true else return
    2 min read
    Python unittest - assertTrue() function
    assertTrue() in Python is a unittest library function that is used in unit testing to compare test value with true. This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is true then assertTrue() will return true else return fal
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences