Implement a Python script to perform unit testing with pytest.
- User
Implement a Python script to perform unit testing with pytest.
Assistant
1. Understand the Goal: The user wants a Python script that demonstrates how to perform unit testing using the
pytestframework.-
Identify Key Components:
- Code to Test (SUT - System Under Test): I need a simple Python module with a few functions to test. Good candidates are:
- A basic arithmetic function (e.g.,
add). - A function with edge cases (e.g., division by zero, string manipulation).
- A class method (optional, but good for completeness).
- A basic arithmetic function (e.g.,
- Test Code (The Unit Tests): I need a separate file (or a clearly defined section) containing test functions that
pytestcan discover.- Use
assertstatements. - Demonstrate checking for exceptions (using
pytest.raises).
- Use
- Execution Instructions: Explain how to run the tests (command line).
- Project Structure: Show how files should be organized.
- Code to Test (SUT - System Under Test): I need a simple Python module with a few functions to test. Good candidates are:
-
Drafting the Code - Step-by-Step:
-
Step 1: The Application Code (
main.pyorcalculator.py) Let's create a simplecalculator.py.def add(a, b): return a + b def subtract(a, b): return a - b def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b -
Step 2: The Test Code (
test_calculator.py)pytestlooks for files starting withtest_or ending with_test.py.import pytest from calculator import add, subtract, divide def test_add_positive_numbers(): assert add(2, 3) == 5 def test_add_negative_numbers(): assert add(-1, -1) == -2 def test_subtract(): assert subtract(5, 2) == 3 def test_divide_by_zero(): # Check if exception is raised with pytest.raises(ValueError): divide(10, 0) -
Step 3: Putting it together in a single script representation (if requested, but usually better as separate files). However, the user asked for "a Python script". While unit testing is best done with separate files, for a demonstration, I can provide the code blocks clearly and explain how to set them up. I will provide a self-contained example where the logic is defined, then tested, but strictly speaking,
pytestrequires importable modules. The best approach is to provide two files in the answer and explain the directory structure.
-
-
Refining the Content:
- Prerequisites: Mention
pip install pytest. - Structure:
- Directory layout.
operations.py(The logic).test_operations.py(The tests).
- Key Features to Demonstrate:
- Simple assertion (
assert). - Testing exceptions (
pytest.raises). - Parameterization (Bonus: makes the answer better). Let's add
@pytest.mark.parametrize. It shows the power ofpytest.
- Simple assertion (
- Prerequisites: Mention
-
Writing the Response (Mental Draft):
- Intro: Explain what pytest is and how to install it.
- File 1:
app.py(contains the code to test). - File 2:
test_app.py(contains the tests). - Execution: Show the terminal command
pytest -v. - Explanation: Break down what
assertandpytest.raisesdo.
-
Adding Parameterization (Self-Correction/Enhancement): Instead of writing
test_add_1,test_add_2, I'll use parameterization. It's a very "pytest" way of doing things.@pytest.mark.parametrize("a, b, expected", [(1, 2, 3), (0, 0, 0), (-1, 1, 0)]) def test_add(a, b, expected): assert add(a, b) == expected -
Final Polish: Ensure the code is copy-pasteable and runnable. Make sure to explain why we separate the code (SUT) from the tests.
- Code Logic: A simple math class/function is easiest to understand.
- Error Handling: Include a division function that raises an error to show how to test errors.
-
Constructing the Final Output:
- Step 1: Installation.
- Step 2: Project Structure.
- Step 3: The Logic (
operations.py). - Step 4: The Tests (
test_operations.py). - Step 5: Running the tests.
- Step 6: Explanation of features used (assert, raises, parametrize).
This structure looks solid. It answers the prompt directly while providing best practices (separation of concerns) and advanced features (parameterization).
(Self-Correction during drafting): The user asked for "a Python script". If I just give one file,
pytestmight get confused trying to import itself or run tests on the test code logic if not careful. The standard is two files. I will stick to the standard 2-file approach because it is the correct way to usepytest. I will explain that clearly.Let's double check the code syntax.
pytest.raises(ValueError)matchesraise ValueError(...). Correct.assert func() == expected. Correct. Commandpytestorpytest -v. Correct.Ready to generate. Here is a complete guide and implementation for unit testing using
pytest.To follow best practices, we will separate the code into two files:
- The Application Code: The logic you want to test.
- The Test Code: The script that verifies the logic.
Prerequisites
First, ensure you have
pytestinstalled:pip install pytest
Step 1: Create the Application Code
Create a file named
operations.py. This contains the actual logic we want to test.# operations.py def add(a, b): """Returns the sum of two numbers.""" return a + b def subtract(a, b): """Returns the difference of two numbers.""" return a - b def divide(a, b): """Divides a by b. Raises ValueError if b is zero.""" if b == 0: raise ValueError("Cannot divide by zero") return a / b
Step 2: Create the Test Script
Create a file named
test_operations.py. By default,pytestautomatically discovers files that start withtest_or end with_test.py.# test_operations.py import pytest from operations import add, subtract, divide # 1. Basic Test def test_add_positive_numbers(): assert add(2, 3) == 5 def test_add_negative_numbers(): assert add(-1, -1) == -2 # 2. Testing Exceptions def test_divide_by_zero(): # We assert that the following code raises a ValueError with pytest.raises(ValueError) as excinfo: divide(10, 0) # Optional: Check the error message content assert str(excinfo.value) == "Cannot divide by zero" # 3. Parameterized Tests (Running the same test with different data) # This is a powerful feature of pytest to avoid writing repetitive code. @pytest.mark.parametrize("a, b, expected", [ (10, 2, 5), (0, 5, 0), (-10, 2, -5), (5, 2, 2.5), ]) def test_divide_various_inputs(a, b, expected): assert divide(a, b) == expected # 4. Fixture (Setup/Teardown) # Fixtures are used to initialize data or objects needed for tests. @pytest.fixture def sample_numbers(): return (10, 5) def test_subtract_with_fixture(sample_numbers): a, b = sample_numbers assert subtract(a, b) == 5
Step 3: Run the Tests
Open your terminal or command prompt, navigate to the folder containing these files, and run:
pytestTo see more details (verbose mode):
pytest -vExplanation of Key Concepts Used
assert: The core of testing. If the statement followingassertisTrue, the test passes. If it isFalse, the test fails.pytest.raises: Used to verify that a function specifically throws an error (like trying to divide by zero). If the error is not thrown, the test fails.@pytest.mark.parametrize: Allows you to run a single test function multiple times with different input arguments. This keeps your code clean.@pytest.fixture: Used to set up data (like database connections or sample variables) that can be shared across multiple tests.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.