Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions python-fullstack/backend/service.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Application rules shared by the REST endpoints; kept independent of FastAPI."""

import math
import re
from datetime import datetime, timezone
from urllib.parse import urlparse
Expand Down Expand Up @@ -85,6 +86,59 @@ def url(data, key, required=False):
return value


def email(data, key, required=True):
val = text(data, key, 1 if required else 0, 254)
if not val:
return ""
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
need(
re.match(pattern, val) is not None and ".." not in val,
f"{key} must be a valid email address",
422,
)
return val.lower()


def number(data, key, low=None, high=None):
value = data.get(key)
need(
isinstance(value, (int, float))
and not isinstance(value, bool)
and math.isfinite(value),
f"{key} must be a number",
422,
)
fval = float(value)
if low is not None:
need(fval >= low, f"{key} must be at least {low}", 422)
if high is not None:
need(fval <= high, f"{key} must be at most {high}", 422)
return fval


def string_list(data, key, min_items=0, max_items=100, item_min_len=1, item_max_len=100):
val = data.get(key)
if val is None and min_items == 0 and key not in data:
return []
need(isinstance(val, (list, tuple)), f"{key} must be a list", 422)
need(
min_items <= len(val) <= max_items,
f"{key} must contain {min_items}–{max_items} items",
422,
)
result = []
for item in val:
need(isinstance(item, str), f"Items in {key} must be text", 422)
s = item.strip()
need(
item_min_len <= len(s) <= item_max_len,
f"Items in {key} must be {item_min_len}–{item_max_len} characters",
422,
)
result.append(s)
return result


def date(data, key):
value = text(data, key, 1, 40)
try:
Expand Down
59 changes: 58 additions & 1 deletion python-fullstack/backend/tests/test_service_validation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import pytest
from service import ApiError, boolean, choice, date, integer, text, url
from service import ApiError, boolean, choice, date, email, integer, number, string_list, text, url


def test_text_validator():
Expand Down Expand Up @@ -113,3 +113,60 @@ def test_date_validator():
# Invalid date format
with pytest.raises(ApiError):
date({"due": "invalid-date-string"}, "due")


def test_email_validator():
assert email({"mail": "Student@Example.Com"}, "mail") == "student@example.com"
assert email({"mail": "admin+test@domain.co.uk"}, "mail") == "admin+test@domain.co.uk"

# Optional email
assert email({}, "mail", required=False) == ""
assert email({"mail": ""}, "mail", required=False) == ""

# Required missing
with pytest.raises(ApiError):
email({}, "mail", required=True)

# Invalid formats
with pytest.raises(ApiError):
email({"mail": "not-an-email"}, "mail")
with pytest.raises(ApiError):
email({"mail": "missing-domain@"}, "mail")
with pytest.raises(ApiError):
email({"mail": "user..name@example.com"}, "mail")


def test_number_validator():
assert number({"grade": 95.5}, "grade") == 95.5
assert number({"grade": 100}, "grade", low=0, high=100) == 100.0
assert number({"grade": 0}, "grade", low=0, high=100) == 0.0

# Bounds
with pytest.raises(ApiError):
number({"grade": -0.1}, "grade", low=0)
with pytest.raises(ApiError):
number({"grade": 100.1}, "grade", high=100)

# Non-numbers / booleans / NaN
with pytest.raises(ApiError):
number({"grade": True}, "grade")
with pytest.raises(ApiError):
number({"grade": float("nan")}, "grade")
with pytest.raises(ApiError):
number({"grade": "95.5"}, "grade")


def test_string_list_validator():
assert string_list({"tags": ["python", "algorithms"]}, "tags") == ["python", "algorithms"]
assert string_list({"tags": [" spaced "]}, "tags") == ["spaced"]
assert string_list({}, "tags", min_items=0) == []

# Item length / min items
with pytest.raises(ApiError):
string_list({"tags": []}, "tags", min_items=1)
with pytest.raises(ApiError):
string_list({"tags": [""]}, "tags", item_min_len=1)
with pytest.raises(ApiError):
string_list({"tags": [123]}, "tags")
with pytest.raises(ApiError):
string_list({"tags": "not-a-list"}, "tags")
Loading