Django Tutorial
Django Create A Complete Project
Django Template
Django Database Query
Django Form
Django Authentication and Permission Management
Django unittest
Django Advanced
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.
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
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.
test_calculator.py
:if __name__ == '__main__': unittest.main()
Now, run test_calculator.py
as a script:
python test_calculator.py
.... ---------------------------------------------------------------------- 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.
Writing Tests in Python Using unittest:
unittest
module provides a framework for writing and running tests. Tests are written as methods within test classes.unittest
:import unittest class MyTestCase(unittest.TestCase): def test_example(self): self.assertEqual(1 + 1, 2)
Running Unit Tests in Python with unittest:
unittest
test runner. Running tests can be done using the unittest.main()
function or command-line execution.unittest
:import unittest if __name__ == '__main__': unittest.main()
Assertions in Python unittest:
unittest
provides various assertion methods for validating test outcomes, such as assertEqual
, assertRaises
, etc.unittest
:import unittest class MyTestCase(unittest.TestCase): def test_example(self): self.assertEqual(1 + 1, 2) self.assertRaises(ValueError, int, 'invalid')
Fixture Setup in Python unittest:
setUp
method. This method is called before each test method.unittest
:import unittest class MyTestCase(unittest.TestCase): def setUp(self): # Set up fixtures here def test_example(self): # Test using fixtures
Mocking in Python unittest:
unittest.mock
module to replace parts of your system with mock objects for testing.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')
Test Discovery in Python unittest:
unittest
test discovery mechanism.unittest
:python -m unittest discover
Grouping Tests in Python unittest:
TestLoader
class in Python unittest
.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))
Parameterized Tests in Python unittest:
@unittest.parametrized
decorator.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)
Skipping Tests in Python unittest:
@unittest.skip
decorator or by raising unittest.SkipTest
.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
Python unittest Command Line Options:
unittest
, such as specifying the test module or test class.python -m unittest mymodule.MyTestCase