Data Validation & Unit Testing
Customer data is never as clean as promised. Learn how to validate data structures and business rules with Pydantic, write automated test suites with Pytest, and isolate new features using Git branches before bad inputs crash your pipeline.
Prerequisites
- Module 00.1 completed: You should understand Python virtual environments, basic Python functions, and terminal exit codes.
- Python 3.10 or later: This lesson uses modern Python type-hint syntax. The examples have been tested with Python 3.12.
- A clean workspace: Open your terminal and navigate to your main FDE project folder, outside your
fde-00-1directory.
Why Validation and Testing Matter
- Pydantic validates and coerces: Pydantic validates incoming data against declared types and constraints. By default, it can coerce compatible values, such as converting the string
"5"into the integer5. Strict mode can be enabled when coercion is not acceptable. You can also encode business rules, such as maximum retries and valid URL formats, directly into a schema. - Pytest checks expected behavior: Instead of manually checking every output, automated tests verify that your code behaves as expected for valid inputs, invalid inputs, and important edge cases. This gives you confidence when changing or extending existing code.
- Git branches isolate your work: Developing directly on
mainmakes it harder to separate stable code from unfinished features. A feature branch lets you experiment, test changes, and merge them intomainafter they are ready.
Important distinction: Validation is not verification. Pydantic’s HttpUrl checks whether a value has a valid HTTP or HTTPS URL structure. It does not check whether the website is reachable, whether its API is operational, or whether you have permission to access it. Those checks belong to application and integration logic, which we will explore in later modules.
Hands-On Lab: Validate and Test an Agent Configuration
Core exercise: 30–40 minutes. Full completion, including Git branching and the practice assignment: 1–2 hours.
Step 1: Create the Project and Install Dependencies
Create a new folder named fde-00-2 and initialize a virtual environment.
# 1. Create and enter the project folder
mkdir fde-00-2
cd fde-00-2
# 2A. macOS / Linux
python3 -m venv .venv
source .venv/bin/activate
# 2B. Windows Command Prompt (CMD)
py -m venv .venv
.venv\Scripts\activate.bat
# 2C. Windows PowerShell
py -m venv .venv
.\.venv\Scripts\Activate.ps1
PowerShell troubleshooting: If script execution is blocked, your organization’s security policy may prevent virtual environment activation. If permitted, you can use Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser. Otherwise, use Command Prompt or follow your organization’s approved Python setup instructions.
To avoid command-line quotation mark differences across operating systems, open this folder in your code editor (such as VS Code) and manually create a file named requirements.txt containing exactly these two lines:
pydantic==2.5.3
pytest==7.4.3
Return to your terminal and install the packages:
python -m pip install -r requirements.txt
Using python -m pip helps ensure packages are installed through the Python interpreter associated with your active virtual environment.
Step 2: Create a Pydantic Model (config_parser.py)
Imagine you are building a web scraper agent. It needs a target URL, a retry limit, and a bounded timeout. We will use Pydantic’s Field constraints and HttpUrl type to enforce these rules.
Create config_parser.py in your editor:
from pydantic import BaseModel, Field, HttpUrl, ValidationError
class AgentConfig(BaseModel):
target_url: HttpUrl
max_retries: int = Field(default=3, ge=0, le=10)
timeout_seconds: float = Field(gt=0, le=300)
def parse_config(data: dict) -> AgentConfig | None:
# Some applications should let ValidationError propagate
# so the calling service can handle the details.
# Here, we catch it and return None to demonstrate
# one possible validation boundary.
try:
# ** unpacks dictionary keys into keyword arguments
return AgentConfig(**data)
except ValidationError as exc:
print(
f"Validation failed: "
f"{exc.error_count()} error(s) found"
)
return None
Understand the constraints:
HttpUrlrequires a valid HTTP or HTTPS URL structure.ge=0means the retry count must be greater than or equal to zero.le=10means the retry count cannot exceed ten.gt=0means the timeout must be greater than zero.le=300means the timeout cannot exceed 300 seconds.
The parse_config() function catches validation errors and returns None. This is a deliberate design choice for this exercise, not a universal rule. In a production application, you may instead propagate the exception or return a structured error that the calling service can handle.
Step 3: Write Your Test Suite (test_config.py)
Instead of manually running a script to inspect its output, we will write automated tests. Pytest discovers files beginning with test_ and functions beginning with test_.
Create test_config.py in the same directory as config_parser.py:
from config_parser import parse_config
def test_valid_config_uses_defaults():
data = {
"target_url": "https://api.example.com/",
"timeout_seconds": 10.5
}
config = parse_config(data)
assert config is not None
# HttpUrl is a Pydantic URL object.
# Convert it to a string for comparison.
assert str(config.target_url) == "https://api.example.com/"
assert config.max_retries == 3
def test_pydantic_coerces_types():
# Pydantic converts the compatible string "5" into integer 5.
data = {
"target_url": "https://api.example.com/",
"max_retries": "5",
"timeout_seconds": 10.5
}
config = parse_config(data)
assert config is not None
assert config.max_retries == 5
def test_missing_required_field_fails():
# timeout_seconds is required.
data = {
"target_url": "https://api.example.com/"
}
assert parse_config(data) is None
def test_invalid_url_fails():
data = {
"target_url": "hello",
"timeout_seconds": 10.5
}
assert parse_config(data) is None
def test_negative_retries_fails():
data = {
"target_url": "https://api.example.com/",
"max_retries": -1,
"timeout_seconds": 10.5
}
assert parse_config(data) is None
def test_max_retries_above_limit_fails():
data = {
"target_url": "https://api.example.com/",
"max_retries": 11,
"timeout_seconds": 10.5
}
assert parse_config(data) is None
def test_zero_timeout_fails():
data = {
"target_url": "https://api.example.com/",
"timeout_seconds": 0
}
assert parse_config(data) is None
def test_timeout_above_limit_fails():
data = {
"target_url": "https://api.example.com/",
"timeout_seconds": 301
}
assert parse_config(data) is None
What are we testing?
- Valid configuration and default values.
- Automatic type coercion.
- Missing required fields.
- Invalid URL formats.
- Negative retry counts.
- Retry counts above the permitted maximum.
- Zero timeout values.
- Timeout values above the permitted maximum.
Step 4: Run the Tests
Run Pytest from inside your fde-00-2 directory:
python -m pytest -v
You should see eight green PASSED indicators.
Understand the exit codes:
0: All collected tests passed successfully.1: One or more tests failed.2: The test run was interrupted.3: An internal error occurred.4: Pytest encountered a command-line usage error.5: No tests were collected.
Check the exit code using the appropriate command for your terminal:
# macOS / Linux
echo $?
# Windows PowerShell
$LASTEXITCODE
# Windows CMD
echo %ERRORLEVEL%
CI/CD pipelines use these exit codes to decide whether a build should continue. A failed test suite can therefore prevent an unverified change from being deployed.
Step 5: Establish a Git Baseline and Create a Feature Branch
In a real engineering environment, a feature branch needs a baseline commit to branch off from. We will first commit our working project on main, then create a separate feature branch for the practice assignment.
In your code editor, manually create a file named .gitignore with these contents:
.venv/
__pycache__/
.pytest_cache/
Initialize Git and create the baseline commit:
# 1. Initialize the repository
git init
# 2. Ensure the primary branch is named main
git branch -M main
# 3. Add the project files
git add .
# 4. Create the initial baseline commit
git commit -m "Add initial project files"
# 5. Create a feature branch
git checkout -b feature/agent-validation
Your project now has a stable starting point on main and a separate branch for new development.
You will implement the optional API key field, add tests, commit your changes, and merge the feature branch in the Practice Assignment tab.
Failure Notes & Done When
- Import errors: Ensure
config_parser.pyandtest_config.pyare in the same directory and run Pytest from insidefde-00-2. - Package installation errors: Confirm that your virtual environment is activated and that
requirements.txtcontains the correct package names and versions. - Git identity errors: If Git asks you to configure your identity, set your author details:
These settings apply to the current repository. Use your actual name and an appropriate email address.git config user.name "Your Name" git config user.email "you@example.com" - Git merge errors: Check your current branch with
git branch. Ensure you committed your feature changes before switching tomain.
Done when:
- Your virtual environment is working.
- Your Pydantic model validates the required configuration and business rules.
- All ten automated tests pass (after completing the practice assignment).
- Your optional API key feature is committed on the feature branch.
- Your feature branch has been merged into your local
mainbranch.
Author: Vardaan · Tested with Python 3.12, Pydantic 2.5.3, and Pytest 7.4.3. The instructions cover macOS, Linux, Windows CMD and Windows PowerShell.
Build this
Your task: Extend AgentConfig to support an optional API key. This simulates a small configuration change you might make when integrating an external service.
- Update the model: Add the following field to AgentConfig:
api_key: str | None = None - Test the default: Write a test confirming that
api_keyis None when no key is provided. - Test a supplied value: Write another test confirming that a placeholder value such as "test-key-123" is accepted.
- Run the full test suite: Use
python -m pytest -vand confirm that all ten tests pass. - Commit your feature: Stage your changes and create a commit on
feature/agent-validation. - Merge into main: Switch back to main and merge your completed feature branch.
Security reminder: Use placeholder values in this exercise. Never print, commit, or expose real API keys. In production applications, secrets should be managed through environment variables or an appropriate secrets manager.
Test your understanding
- Why use
python -m pip installinstead of just running a standard pip install command? - What is the difference between Pydantic's default type coercion and strict validation?
- What is the difference between data validation (using Pydantic) and data verification?
- Why must your test file and test functions begin with
test_? - Why should you make an initial baseline commit on main before creating a new feature branch?
- In our script, we catch ValidationError and return None. In what scenario would you intentionally let that exception propagate instead?
Reveal self-review answers (attempt the questions first)
- Module execution (
python -m): Usingpython -mensures packages and tools run from the active virtual environment rather than a stray global executable. - Type coercion vs. strict validation: Pydantic's default mode coerces compatible inputs (such as parsing a numeric string into an integer or float), whereas strict validation rejects types that do not match the declared field type without coercion.
- Data validation vs. data verification: Validation checks that data conforms to shape, types, and schema rules (such as a valid URL format or non-empty string); verification checks whether that value actually works or exists in the real world (such as reaching an endpoint or authenticating a credential).
- Pytest naming convention: Prefixing test files and functions with
test_letspytestautomatically discover and collect them during test runs without extra configuration. - Baseline commit on
main: Making an initial baseline commit onmaingives your feature branch a clean, known-good starting point so diffs stay focused and merges remain straightforward. - Propagating
ValidationError: LetValidationErrorpropagate when a caller or upstream layer needs structured error details, HTTP/API error responses, or explicit failure handling rather than silently falling back to a default orNone.
Questions or notes on this module?