“Pytest is a free and open-source Python testing tool that allows you to create small, readable, and manageable tests. It is a popular testing framework for Python as it is easy for beginners and can handle simple to complex testing operations.
Whether a beginner or a seasoned developer, creating tests for your programs allows you to create heavily readable and manageable programs.”
This article will show you how to install the Pytest library in your Python environment.
Requirements
We have tested the installation process provided in this article for Ubuntu 16 and above, Debian 8 and above, and any other Debian-based distribution.
Requirements:
- Permission to install Python packages (sudo or root account)
- Python3 and Pip3 package installer.
- A network connection.
Once you have the above requirements satisfied, we can begin.
Method 1 – Installing Pytest With APT
The apt package manager is the first and most common method of installing the pytest package on your system.
By default, the pytest package is available in most Linux distributions.
Start by updating your repository index:
Next, run the search command to verify that the pytest package is available:
The command should list the available packages for the python3-pytest package. We are interested in the first result, as shown in the output above.
Next, we can run apt to install the package as shown:
Ensure you have installed the latest version of the Python 3 interpreter and pip is available.
Method 2 – Installing Pytest With PIP
If you do not wish to use apt to install Python packages, you can choose pip as it allows you to specify the target package version.
Start by updating the system repo index:
Next, install the pytest package by running the command:
In some cases, the above command may fail if the pip command is under the pip3 binary. Run the command below to fix it.
The commands above should download and install the pytest package on your system.
Verify Package Version
Upon completion, check the installed version by executing the command:
The command should return information about the installed package version as shown:
Quick Testing Example
The code below illustrates how we can use the pytest framework to test a simple application.
Edit the file:
Add the code as shown below:
return a * b
def test_func():
assert(multiply(10, 10))
The code above contains a simple function that returns the product of two input values. We then use the assert function to test if the function passes the multiplication of 10 by 10.
If the function returns 100, the program passes; otherwise, it fails.
Test the code:
We can see from the output above that the function passes.
Conclusion
This article covered installing and setting up the pytest framework on Linux. You can explore the docs to learn how to use the pytest framework.
Thanks for tuning in & Happy coding!!