如何为圆周长函数编写基础PyTest测试?
Hey there! No worries at all—PyTest can feel overwhelming when you're new to it, but writing a basic test for your circumference function is totally straightforward once we adjust things a bit. Let's walk through this together.
First, let's look at your original function:
import math def getCircumference(): radius = int(input("Please enter a radius size: ")) circumference = 2 * math.pi * radius print("The circumference of the circle is", circumference)
The problem here is that this function relies on user input (input()) and prints the result directly, which makes it hard to test. For testing, we want a pure function—one that takes an input (the radius) and returns the calculated circumference, without relying on external inputs or printing.
Step 1: Refactor Your Function
Let's split your code into two parts: a pure calculation function, and the interactive part that handles input/output. This keeps your original functionality intact while making testing easy:
import math # This is the pure function we'll test def calculate_circumference(radius): return 2 * math.pi * radius # Keep your original interactive function if you want to use it manually def getCircumference(): radius = int(input("Please enter a radius size: ")) circumference = calculate_circumference(radius) print("The circumference of the circle is", circumference)
Step 2: Install PyTest
If you haven't already, install PyTest using pip:
pip install pytest
Step 3: Write Your Test File
Create a new file named test_circumference.py (PyTest automatically recognizes files starting with test_). In this file, we'll write test cases to verify our calculate_circumference function works as expected.
import math # Replace 'your_file_name' with the name of the file where you saved the calculate_circumference function (e.g., main.py) from your_file_name import calculate_circumference def test_circumference_basic(): # Test with radius = 1: circumference should be 2 * π assert calculate_circumference(1) == 2 * math.pi def test_circumference_radius_5(): # Test with radius = 5: circumference should be 10 * π assert calculate_circumference(5) == 10 * math.pi def test_circumference_zero_radius(): # Test edge case: radius = 0 should return 0 assert calculate_circumference(0) == 0
Step 4: Run Your Tests
Open your terminal, navigate to the folder where your test file and function file are located, then run:
pytest
PyTest will run all your test cases and show you a summary:
- A green dot means a test passed
- A red 'F' means a test failed (it will also show you why, like if the calculated value didn't match what you expected)
A Quick Note on assert
The assert statement is the heart of PyTest tests. It checks if the expression after it is True. If it is, the test passes; if not, PyTest tells you exactly what went wrong (e.g., expected value vs. actual value).
内容的提问来源于stack exchange,提问作者Sam Smith

