Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Python Unit Testing by unittest Module

unittest is a built-in Python module for creating and running tests for your code. It provides a test framework similar to other xUnit frameworks, such as JUnit for Java. In this tutorial, we'll cover the basics of setting up and running tests using the unittest module.

  • Create a Python module to test: Let's create a simple Python module with a few functions that we want to test. Save the following code as calculator.py:
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero.")
    return a / b
  • Create a test file: Create a new file named test_calculator.py in the same directory as calculator.py. This is where we'll define our test cases.

  • Import the necessary modules: At the top of test_calculator.py, import the unittest module and the functions from the calculator module:

import unittest
from calculator import add, subtract, multiply, divide
  • Write test cases: Test cases in unittest are classes that inherit from unittest.TestCase. Define a new class for your test case and create methods for each individual test. Test method names should start with test_. For example:
class TestCalculator(unittest.TestCase):

    def test_add(self):
        self.assertEqual(add(1, 2), 3)
        self.assertEqual(add(-1, 1), 0)

    def test_subtract(self):
        self.assertEqual(subtract(3, 2), 1)
        self.assertEqual(subtract(2, 5), -3)

    def test_multiply(self):
        self.assertEqual(multiply(2, 3), 6)
        self.assertEqual(multiply(-2, 3), -6)

    def test_divide(self):
        self.assertEqual(divide(4, 2), 2)
        self.assertEqual(divide(9, 3), 3)

        with self.assertRaises(ValueError):
            divide(10, 0)

In this example, we have a test case TestCalculator with four test methods for testing the add, subtract, multiply, and divide functions from the calculator module.

  • Run the tests: To run your tests, you can use the command line or add a "main" block to your test file. Here, we'll add a main block to test_calculator.py:
if __name__ == '__main__':
    unittest.main()

Now, run test_calculator.py as a script:

python test_calculator.py
  • Review the test results: After running the tests, the test runner will provide a summary of the test results. If all tests pass, you'll see a message like this:
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK

If any tests fail, the test runner will display an error message along with the traceback and a summary of the failed tests.

Using the unittest module in Python, you can create test cases to verify the functionality of your code. Writing and running tests helps improve code quality, catch bugs early, and save time and effort in the long run.

  1. Writing Tests in Python Using unittest:

    • Description: Python's unittest module provides a framework for writing and running tests. Tests are written as methods within test classes.
    • Code: Example of writing a simple test in Python with unittest:
      import unittest
      
      class MyTestCase(unittest.TestCase):
          def test_example(self):
              self.assertEqual(1 + 1, 2)
      
  2. Running Unit Tests in Python with unittest:

    • Description: Execute tests using the unittest test runner. Running tests can be done using the unittest.main() function or command-line execution.
    • Code: Example of running tests in Python with unittest:
      import unittest
      
      if __name__ == '__main__':
          unittest.main()
      
  3. Assertions in Python unittest:

    • Description: Python unittest provides various assertion methods for validating test outcomes, such as assertEqual, assertRaises, etc.
    • Code: Example of using assertions in Python unittest:
      import unittest
      
      class MyTestCase(unittest.TestCase):
          def test_example(self):
              self.assertEqual(1 + 1, 2)
              self.assertRaises(ValueError, int, 'invalid')
      
  4. Fixture Setup in Python unittest:

    • Description: Set up fixtures (preconditions) for tests using the setUp method. This method is called before each test method.
    • Code: Example of fixture setup in Python unittest:
      import unittest
      
      class MyTestCase(unittest.TestCase):
          def setUp(self):
              # Set up fixtures here
      
          def test_example(self):
              # Test using fixtures
      
  5. Mocking in Python unittest:

    • Description: Use the unittest.mock module to replace parts of your system with mock objects for testing.
    • Code: Example of using mocking in Python unittest:
      import unittest
      from unittest.mock import patch
      
      class MyTestCase(unittest.TestCase):
          @patch('mymodule.myfunction')
          def test_example(self, mock_myfunction):
              mock_myfunction.return_value = 'mocked result'
              result = mymodule.myfunction()
              self.assertEqual(result, 'mocked result')
      
  6. Test Discovery in Python unittest:

    • Description: Discover and run tests automatically by using the unittest test discovery mechanism.
    • Code: Example of test discovery in Python unittest:
      python -m unittest discover
      
  7. Grouping Tests in Python unittest:

    • Description: Group tests using test suites and the TestLoader class in Python unittest.
    • Code: Example of grouping tests in Python unittest:
      import unittest
      
      class MyTestCase1(unittest.TestCase):
          def test_example(self):
              self.assertEqual(1 + 1, 2)
      
      class MyTestCase2(unittest.TestCase):
          def test_another_example(self):
              self.assertEqual(2 * 2, 4)
      
      suite = unittest.TestLoader().loadTestsFromTestCase(MyTestCase1)
      suite.addTest(unittest.TestLoader().loadTestsFromTestCase(MyTestCase2))
      
  8. Parameterized Tests in Python unittest:

    • Description: Parameterize tests to run with different input values using the @unittest.parametrized decorator.
    • Code: Example of parameterized tests in Python unittest:
      import unittest
      from parameterized import parameterized
      
      class MyTestCase(unittest.TestCase):
          @parameterized.expand([(1, 1, 2), (2, 3, 5), (3, 4, 7)])
          def test_addition(self, a, b, result):
              self.assertEqual(a + b, result)
      
  9. Skipping Tests in Python unittest:

    • Description: Skip tests conditionally using the @unittest.skip decorator or by raising unittest.SkipTest.
    • Code: Example of skipping tests in Python unittest:
      import unittest
      
      class MyTestCase(unittest.TestCase):
          @unittest.skip("Skipping this test")
          def test_skipped_example(self):
              # Test logic
      
          def test_conditionally_skipped(self):
              if not some_condition:
                  self.skipTest("Condition not met, skipping test")
              # Test logic
      
  10. Python unittest Command Line Options:

    • Description: Use various command-line options to customize the behavior of Python unittest, such as specifying the test module or test class.
    • Code: Example of running specific tests using command-line options:
      python -m unittest mymodule.MyTestCase