Last modified: Mar 25, 2025 By Alexander Williams
How to Install Pytest in Python Step by Step
Pytest is a popular testing framework for Python. It makes writing and running tests easy. This guide will show you how to install Pytest step by step.
Table Of Contents
Prerequisites
Before installing Pytest, ensure you have Python installed. You can check by running python --version
in your terminal.
python --version
If Python is not installed, download it from the official website. Also, ensure pip is available. Pip is Python's package installer.
Install Pytest Using Pip
The easiest way to install Pytest is using pip. Open your terminal or command prompt and run the following command.
pip install pytest
This will download and install Pytest and its dependencies. Wait for the installation to complete.
Verify the Installation
After installation, verify Pytest is installed correctly. Run the following command to check the Pytest version.
pytest --version
You should see the installed Pytest version. If you encounter ModuleNotFoundError, check our guide on How To Solve ModuleNotFoundError.
Create a Simple Test
Now, let's create a simple test to see Pytest in action. Create a file named test_sample.py
and add the following code.
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
This code defines a function add
and a test function test_add
. The test checks if add(2, 3)
returns 5.
Run the Test
To run the test, navigate to the folder containing test_sample.py
in your terminal. Then, run the following command.
pytest test_sample.py
Pytest will execute the test and show the results. You should see a message indicating the test passed.
Understanding Pytest Output
Pytest provides detailed output. A passed test shows a green dot. A failed test shows a red F and an error message.
For example, modify the test to fail by changing the assertion to assert add(2, 3) == 6
.
def test_add():
assert add(2, 3) == 6
Run the test again. Pytest will show a failure message with details.
Advanced Pytest Features
Pytest offers many advanced features. You can run multiple tests, use fixtures, and generate reports. Explore the official documentation for more.
For now, focus on writing simple tests. As you get comfortable, you can explore these advanced features.
Conclusion
Installing Pytest in Python is simple. Use pip install pytest
to get started. Write tests in files prefixed with test_
and run them with the pytest
command.
Pytest helps ensure your code works as expected. Start testing your Python projects today. If you face issues, refer to the ModuleNotFoundError guide.