A Quick Guide to Pytest
Recently, while onboarding a new team member, I realized we were missing documentation on pytest. So in this post, I will share with you the onboarding pytest document used on my team, in case you need the same.
1. Writing Your First Test: Basic Payment Functionality
Let’s start with a function that processes payments.
# payment_gateway.py
def process_payment(amount, currency):
if amount <= 0:
raise ZeroDivisionError("Amount must be greater than zero.")
if currency not in ["USD", "EUR", "GBP"]:
raise ValueError("Unsupported currency.")
return {"status": "success", "amount": amount, "currency": currency}
We’ll create our first test to verify the successful processing of a payment.
# run_tests.py
from payment_gateway import process_payment
def test_process_payment_success():
result = process_payment(100, "USD")
assert result == {"status": "success", "amount": 100, "currency": "USD"}
# Run the test
# collected 1 item
# run_tests.py . # [100%]
# ====== 1 passed in 0.14s =====
So what if we want to test more scenarios? For other currencies and amounts — let’s use parameterized tests.