The Python unit testing framework, sometimes referred to as “PyUnit”.
unittest
supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework. The unittest module provides classes that make it easy to support these qualities for a set of tests.
To achieve this, unittest supports some important concepts:
- test fixture
- A test fixture represents the preparation needed to perform one or more tests, and any associate cleanup actions. This may involve, for example, creating temporary or proxy databases, directories, or starting a server process.
- test case
- A test case is the smallest unit of testing. It checks for a specific response to a particular set of inputs.
unittest
provides a base class,TestCase
, which may be used to create new test cases.
- A test case is the smallest unit of testing. It checks for a specific response to a particular set of inputs.
- test suite
- A test suite is a collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together.
- test runner
- A test runner is a component which orchestrates the execution of tests and provides the outcome to the user. The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests.
The standard workflow is:
- You define your own class derived from
unittest.TestCase
. - Then you fill it with functions that start with
test_
. - You run the tests by placing
unittest.main()
in your file, usually at the bottom.
Example: test_unittest.py
import unittest
class TestUM(unittest.TestCase):
def setUp(self):
pass
def test_example(self):
self.assertEqual(true, true)
if __name__ == '__main__':
unittest.main()
Running unittests:
$ python test_unittest.py
Ref:
pytest
is a mature full-featured Python testing tool that helps you write better programs.The unit test style of deriving from
unittest.TestCase
is something unittest shares with it’s xUnit counterparts like JUnit. It’s informative to know that inheritance is quite important in some languages to get the test framework to work right.But this is Python. We have very powerful introspection and runtime capabilities, and very little information hiding. Pytest takes advantage of this.
An identical test as above could look like this if we use pytest: test_pytest.py
Running unittests:
Test Discovery: pytest.ini
Ref: