From 357419dc8592c03d7e0254b8ac642a9f586703d0 Mon Sep 17 00:00:00 2001 From: RAM PRASAD ATLURI <116977270+ATLURI0001@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:14:51 +0530 Subject: [PATCH] feat(service): add email, number, and string_list schema validators --- python-fullstack/backend/service.py | 54 +++++++++++++++++ .../backend/tests/test_service_validation.py | 59 ++++++++++++++++++- 2 files changed, 112 insertions(+), 1 deletion(-) diff --git a/python-fullstack/backend/service.py b/python-fullstack/backend/service.py index fc8f83c..fae0b0a 100644 --- a/python-fullstack/backend/service.py +++ b/python-fullstack/backend/service.py @@ -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 @@ -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: diff --git a/python-fullstack/backend/tests/test_service_validation.py b/python-fullstack/backend/tests/test_service_validation.py index 1ff657e..36ba1b5 100644 --- a/python-fullstack/backend/tests/test_service_validation.py +++ b/python-fullstack/backend/tests/test_service_validation.py @@ -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(): @@ -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")