Python is a widely used programming language preferred for application development because it is interpreted, object-oriented with built in dynamic data structures. Python is a very user friendly language due to its easy syntax that enhances readability which results in reduced maintenance cost.
Python's interpreter and its support for an extensive library, it encourages program modularity and code reusability.
Python Unit Testing:
Unit testing in Python is as important as in any other programming language.
'Unittest' is the module for Python tests. It is also referred to as 'PyUnit', offers support for fixtures, test suites and test runner to enable automated testing.
Before divulging into the actual working of Pyunit, let us look at few general guidelines to be followed to achieve a successful testing.
The primary motto of testing should be to test only a bit of the whole functionality.
Each test must be independent in nature, that is, a unit or module must be able to run without the need for any other module irrespective of the fact that the modules are in order.
Optimize each test. Efforts should be made to minimise the time required by a module to execute. A test may take longer due to its underlying data structure.
A function name must be descriptive in nature. The meaning of what the function is meant for must be self-explanatory.
How to prepare the test case:
In a python code written for testing, the 'munittest' module must create an instance for TestCase to accomplish the task of automating tests.
Doctest module are less detailed and primarily used for representing the main use cases of a module and its components. Doctests run automatically every time a test suite runs.
Tools in PyUnit:
Py.test - This is simply the tool for executing a test case. Write a function or piece of code to implement a functionality and run the py.test command.
Nose - It reduces the overhead of creating manual test suites. This tool offers support for many plugins to support features like xUnit compatible test output.
Tox - It allows automating test environment and conducting tests against multiple interpreter configurations.
Unittest2 - this tool enables us to import the module with name 'unittest' to make porting to newer versions of Python easier.
Import unittest2 as unittest
By doing this, we can easily switch to newer Python version when we do not require the unittest2 module. We simply change the import to 'unittest2' .
Mock - used as 'unittest.mock'. This tool allows replacing certain portion of our system under test with mock objects.