Unit Testing in Python
Configuring tests on your python project is important as it lets you identify any kind of faults and defects in your system at an early stage, which improves the quality of your product and builds confidence in it. In unit testing, we perform the lowest level of testing; where individual units are tested like functions, subroutines, and classes are tested to verify if they are given the desired result or not. Unit testing is an integral part of the software development process, independently and individually reviewing the smallest parts of your application or units. With unit tests, you can isolate written code and determine if it works as it should, and if done currently, unit testing can detect early flaws in code that can be hard to find in later stages.
Unit testing makes your code unique, and future-proof since you forecast scenarios where your sample code could fail or produce a bug. To keep programs running effectively, unit tests should be performed frequently, manually, or automatically by developers or software engineers.
Advantages of Unit Testing
- Early detection of problems reduces compound errors: Fixing application issues and source code problems is cheaper when you identify and tests all units earlier than fixing it later. With unit testing, you can reduce compound errors on your application directory files, and identify code bugs before you deploy your application to staging or production environments.
- Debugging processes are made easier: Developers can quickly change the codebase, re-use code samples and templates and eventually migrate to new projects.
Basic Example
The python pytest
unittest
module lets you configure and tests the units of your individual code workflow. Here is a Python script to test four string methods:
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('workflow'.upper(), 'WORKFLOW')
def test_lower(self):
self.assertEqual('WORKFLOW'.lower(), 'workflow')
def test_isupper(self):
self.assertTrue('WORKFLOW'.isupper())
self.assertFalse('Workflow'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['workflow', 'deployment'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
In this tutorial, we’ll learn how to write a sample unit test for our Python projects using the Pytest framework.
Get Started
- Install
pytest
using pip3pip3 install pytest
Thepip
command will install thepytest
package on your OS.
- Confirm if
pytest
was installed usingpytest -h
command. This will print out all the flags in your terminal.
- In the script below, we’ve two functions in a file called func.py; the first is a simple add function that adds two values. And the second one is the core function, which returns the division of two values. With unit tests, you can review the units in question, make tests cases and scripts, and finally test code changes.
def add(x=7, u=4):
return x + u
def core(x=14, u=2):
return x / u
- Next, for us to test our function, we’ve to create a new file like
test_func.py
. After creating the file, import thefunc
python script and define the test functions with the assert function, this lets you make sure your function is returning the desired result. Below, we're performing the unit tests on a standalone module to check whether all functions are developed correctly.
import func
def test_add():
assert func.add(7, 3) == 10
def test_core():
assert func.core(10, 2) == 5
- To test your code, run
pytest func.py
in your terminal.
- If you input an unexpected value in your
test_func
file.
import func
def test_add():
assert func.add(7, 3) == 80
def test_core():
assert func.core(10, 2) == 16
- When you run the tests, it's going to fail and give you the output of the asserting failure.
Conclusion
You can see how you can write and configure unit tests to detect errors and early faults in your code, which may be more difficult to find in later application testing stages. Unit testing occurs in the first level of software testing, performed before any other testing, to make sure a unit doesn't rely on external code or functions. If you'd like to see a working example of this, check out our Python SDK documentation.