unit testing in python
Python hosting: Host, run, and code Python in the cloud!
In the automotive industry, when building a car, various sub-components such as the engine, wheels, and brakes are constructed. These components each have their own unique specifications and requirements.
Without the crucial process of testing, it’s nearly impossible to ascertain if the car will function as expected once all the components are assembled.
Just as one wouldn’t rely on an untested car, the same principle applies to software development. Software is made up of different modules and components.
A significant insight to remember is that the overall quality of software is directly proportional to the quality of its least tested component.
Python Unit Testing with the unittest Module
Python’s unittest module offers a comprehensive framework for unit testing. Consider the following simple function:
def valuePlusOne(x): |
This function can be tested using the assertEquals
method in the following way:
import unittest |
When this testing script runs, the output will be:
---------------------------------------------------------------------- |
Python Unit Testing with py.test
Another popular choice for unit testing in Python is the pytest
module.
To utilize pytest
, first, it needs to be installed:
pip install pytest |
A simple test using pytest
might look like:
def valuePlusOne(x): |
To understand how pytest
responds to failures, modify the function to return an incorrect value and see the result:
def valuePlusOne(x): |
Overview of Python Testing Modules
Python has a rich ecosystem of testing modules available. Some of the prominent ones include Nose, Tox, unittest2, and unittest.mock.
Leave a Reply: