Kosal Ang
Wed Mar 13 2024
pytest
is a popular testing framework for Python that makes writing and running unit tests easier and more efficient. Here's a guide on how to use pytest
to unit test your Python code:
Installation:
First, you need to install pytest
if you haven't already done so. You can install it via pip:
1pip install pytest 2
Writing Test Functions:
Create a Python file for your tests, typically named test_<module_name>.py
. In this file, write test functions using the naming convention test_<something>
.
1# test_my_module.py 2 3def test_addition(): 4 assert 1 + 1 == 2 5 6def test_subtraction(): 7 assert 5 - 3 == 2 8
Running Tests:
To run tests, simply execute pytest
in the terminal in the directory containing your test files:
1pytest 2
pytest
will automatically discover and execute your test functions.
Output:
1===================== test session starts ====================== 2platform win32 -- Python 3.12.1, pytest-8.1.1, pluggy-1.4.0 3rootdir: C:\Users\kosal\code\python\test\pytest 4collected 2 items 5 6test_my_module.py .. [100%] 7 8====================== 2 passed in 0.02s ======================= 9
Assertions:
Use Python's assert
statement inside test functions to check if certain conditions are met. If the condition is False
, the test will fail.
Fixtures:
Fixtures are functions that provide data to your tests. They are defined using the @pytest.fixture
decorator.
1import pytest 2 3@pytest.fixture 4def setup_data(): 5 data = {'name': 'John', 'age': 30} 6 return data 7 8def test_data(setup_data): 9 assert setup_data['name'] == 'John' 10 assert setup_data['age'] == 30 11
Parameterized Tests:
You can create parameterized tests using the @pytest.mark.parametrize
decorator.
1import pytest 2 3@pytest.mark.parametrize('a, b, expected', [(1, 1, 2), (2, 3, 5), (5, 5, 10)]) 4def test_addition(a, b, expected): 5 assert a + b == expected 6
Skipping Tests:
You can skip certain tests under specific conditions using the @pytest.mark.skip
decorator.
1import pytest 2 3@pytest.mark.skip(reason="Test not implemented yet") 4def test_some_feature(): 5 ... 6
Assertions and Exceptions:
You can also test for exceptions using context managers.
1import pytest 2 3def test_exception(): 4 with pytest.raises(ValueError): 5 raise ValueError 6
Coverage Reporting:
You can generate test coverage reports using pytest-cov
plugin.
1pip install pytest-cov 2
Run tests with coverage:
1pytest --cov=my_module 2
These are the basic steps to get started with pytest
for unit testing your Python code. pytest
offers many more features and plugins for advanced testing scenarios. You can refer to the official documentation for more details and advanced usage.
Unlock the full potential of Python development with our comprehensive guide on creating and using virtual environments
Learn how to enhance your real-time chat application built with Flask and Socket.IO by displaying the Socket ID of the message sender alongside each message. With this feature, you can easily identify the owner of each message in the chat interface, improving user experience and facilitating debugging. Follow this step-by-step tutorial to integrate Socket ID display functionality into your chat application, empowering you with deeper insights into message origins.
Asynchronous programming with asyncio in Python allows you to write concurrent code that can handle multiple tasks concurrently, making it particularly useful for I/O-bound operations like web scraping
Unlock the full potential of Python for data visualization with Matplotlib. This comprehensive guide covers everything you need to know to create stunning visualizations, from basic plotting to advanced customization techniques.
Web authentication is a vital aspect of web development, ensuring that only authorized users can access protected resources. Flask, a lightweight web framework for Python, provides Flask-Login
Learn how to handle Excel files effortlessly in Python using the Pandas library. This comprehensive guide covers reading, writing, and manipulating Excel data with Pandas, empowering you to perform data analysis and reporting tasks efficiently.
In the realm of Python GUI development, Tkinter stands out as one of the most popular and versatile libraries. Its simplicity and ease of use make it an ideal choice for building graphical user interfaces for various applications.
Learn how to build a scalable microservices architecture using Python and Flask. This comprehensive guide covers setting up Flask for microservices, defining API endpoints, implementing communication between services, containerizing with Docker, deployment strategies, and more.
Learn how to leverage FastAPI, a modern web framework for building APIs with Python, to create high-performance and easy-to-maintain RESTful APIs. FastAPI combines speed, simplicity, and automatic documentation generation, making it an ideal choice for developers looking to rapidly develop and deploy APIs.
Learn how to scrape websites effortlessly using Python's BeautifulSoup library. This beginner-friendly guide walks you through fetching webpages, parsing HTML content, and extracting valuable data with ease.