Python Module unittest: Difference between revisions
Line 22: | Line 22: | ||
=API= | =API= | ||
==<tt>TestCase</tt>== | ==<tt>TestCase</tt>== | ||
A simple [[#Test_Case|test case]] can be implemented by subclassing <code>TestCase</code> as | A simple [[#Test_Case|test case]] can be implemented by subclassing <code>TestCase</code> as shown below. The individual test methods are have names that start with <code>test</code>. This is a naming convention that informs the test runner about which methods to invoke as tests. | ||
<syntaxhighlight lang='py'> | |||
from unittest import TestCase | |||
from my_code_to_test import some_function | |||
class TestMyCode(TestCase): | |||
def test_empty(self): | |||
self.assertFalse(some_function('')) | |||
def test_lower_case(self): | |||
self.assertEqual('A', some_function('a')) | |||
def test_upper_case(self): | |||
self.assertEqual('A', some_function('A')) | |||
def test_exception(self): | |||
with self.assertRaises(ValueError): | |||
some_function('special') | |||
</syntaxhighlight> | |||
Line 29: | Line 50: | ||
====<tt>assertEquals()</tt>==== | ====<tt>assertEquals()</tt>==== | ||
====<tt>assertTrue()</tt>==== | |||
====<tt>assertFalse()</tt>==== | ====<tt>assertFalse()</tt>==== | ||
====<tt>assertRaises()</tt>==== | ====<tt>assertRaises()</tt>==== |
Revision as of 02:34, 12 July 2022
External
Internal
Overview
unittest vs. pytest
TODO: https://www.pythonpool.com/python-unittest-vs-pytest/
Concepts
Test Fixture
A test fixture represents the code needed to prepare the context for running one or more tests (create temporary databases, directories, etc.), and any associated cleanup actions.
Test Case
A test case is the individual unit of testing. In unittest, the test cases inherit from the base class TestCase
.
Test Suite
A collection of test cases, test suites or both.
Test Runner
The test runner is the component that orchestrates the execution of tests and provides the outcomes to the user.
unittest.mock
API
TestCase
A simple test case can be implemented by subclassing TestCase
as shown below. The individual test methods are have names that start with test
. This is a naming convention that informs the test runner about which methods to invoke as tests.
from unittest import TestCase
from my_code_to_test import some_function
class TestMyCode(TestCase):
def test_empty(self):
self.assertFalse(some_function(''))
def test_lower_case(self):
self.assertEqual('A', some_function('a'))
def test_upper_case(self):
self.assertEqual('A', some_function('A'))
def test_exception(self):
with self.assertRaises(ValueError):
some_function('special')