π‘οΈ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Add pytest API test suite and CI workflow
Omega (QA)575c1255e143
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlnew file mode 100644index 0000000..0959e16--- /dev/null+++ b/.github/workflows/tests.yml@@ -0,0 +1,50 @@+name: Tests++on:+ pull_request:+ push:+ branches: [main]++jobs:+ pytest:+ runs-on: ubuntu-latest++ services:+ postgres:+ image: postgres:15+ env:+ POSTGRES_USER: warranty_user+ POSTGRES_PASSWORD: ci-test-password+ POSTGRES_DB: postgres+ ports:+ - 5432:5432+ options: >-+ --health-cmd "pg_isready -U warranty_user"+ --health-interval 5s+ --health-timeout 3s+ --health-retries 10++ env:+ DB_HOST: 127.0.0.1+ DB_PORT: "5432"+ DB_NAME: warranty_test_suite+ DB_USER: warranty_user+ DB_PASSWORD: ci-test-password+ SECRET_KEY: ci-test-secret-key+ UPLOAD_FOLDER: /tmp/warracker-test-uploads++ steps:+ - uses: actions/checkout@v6++ - uses: actions/setup-python@v5+ with:+ python-version: "3.13"+ cache: pip++ - name: Install dependencies+ run: |+ pip install -r backend/requirements.txt+ pip install pytest++ - name: Run tests+ run: python -m pytest -qdiff --git a/pytest.ini b/pytest.ininew file mode 100644index 0000000..4584de7--- /dev/null+++ b/pytest.ini@@ -0,0 +1,3 @@+[pytest]+testpaths = tests+pythonpath = .diff --git a/tests/README.md b/tests/README.mdnew file mode 100644index 0000000..5ac92e4--- /dev/null+++ b/tests/README.md@@ -0,0 +1,52 @@+# Warracker test suite++API tests for the Flask backend, run with pytest. The suite boots the+real application against a dedicated PostgreSQL database that is+dropped and recreated on every run, with the production migrations+applied. The only fake is Paperless-ngx (`mock_paperless.py`).++## Running locally++You need a PostgreSQL server and a role that can create databases+(the suite creates and drops its own database).++```bash+pip install -r backend/requirements.txt+pip install pytest++DB_HOST=127.0.0.1 DB_PORT=5432 \+DB_NAME=warranty_test_suite \+DB_USER=warranty_user DB_PASSWORD=<your-dev-password> \+python -m pytest+```++Environment variables (defaults in `conftest.py`): `DB_HOST`,+`DB_PORT`, `DB_NAME`, `DB_USER`, `DB_PASSWORD`. `SECRET_KEY` and+`UPLOAD_FOLDER` are set to throwaway test values automatically.++CI runs the same suite on every pull request+(`.github/workflows/tests.yml`).++## What's covered++- `test_smoke.py` β health endpoint, auth required, login, warranty+ create/read/update/delete.+- `test_validation_and_stats.py` β product-name length limit,+ expiration-before-purchase rejection (create and update),+ statistics bucket boundaries (expiring today is not expired),+ claim status validation, CSV import tag splitting.+- `test_paperless_security.py` β the Paperless-ngx access-control+ battery from GHSA-fv62-3hrm-gf83 / GHSA-3h89-rqfj-5674: cross-user+ search/download/link blocking, claim-document privacy, first-linker+ ownership, admin access, global-view rules (viewing shared,+ linking never).++## Notes++- Tests within `test_paperless_security.py` share a module-scoped+ scenario (users, uploads, links) and run in file order, like the+ script they were ported from.+- Everything else uses a fresh registered user per test, so tests+ stay independent and statistics counts stay isolated.+- Add tests with the feature: a fix for a bug should land with the+ test that would have caught it.diff --git a/tests/conftest.py b/tests/conftest.pynew file mode 100644index 0000000..900fbfd--- /dev/null+++ b/tests/conftest.py@@ -0,0 +1,172 @@+"""Fixtures for the Warracker API test suite.++The suite runs the real Flask app through its test client against a+dedicated PostgreSQL database that is dropped and recreated on every+run, with the production migrations applied β the same schema users+run. No application code is mocked; the only fake is Paperless-ngx+(tests/mock_paperless.py).++Environment (local defaults shown; CI sets its own):+ DB_HOST=127.0.0.1 DB_PORT=5432 DB_NAME=warranty_test_suite+ DB_USER=warranty_user DB_PASSWORD=... (role needs CREATEDB)+ SECRET_KEY / UPLOAD_FOLDER are set to throwaway test values.++Run: pip install pytest && python -m pytest+"""+import itertools+import os+import subprocess+import sys+import tempfile+import threading+import uuid++REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+sys.path.insert(0, REPO_ROOT)+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))++# The backend reads DB_* / SECRET_KEY at import time, so the test+# environment must be in place before anything imports it.+os.environ.setdefault("DB_HOST", "127.0.0.1")+os.environ.setdefault("DB_PORT", "5432")+os.environ.setdefault("DB_NAME", "warranty_test_suite")+os.environ.setdefault("DB_USER", "warranty_user")+os.environ.setdefault("DB_PASSWORD", "warranty_password")+os.environ.setdefault("SECRET_KEY", "warracker-test-secret-key-0123456789")+os.environ.setdefault(+ "UPLOAD_FOLDER",+ os.path.join(tempfile.gettempdir(), "warracker-test-uploads"),+)+os.makedirs(os.environ["UPLOAD_FOLDER"], exist_ok=True)++import psycopg2 # noqa: E402+import pytest # noqa: E402+++def _connect(dbname):+ return psycopg2.connect(+ host=os.environ["DB_HOST"],+ port=os.environ["DB_PORT"],+ dbname=dbname,+ user=os.environ["DB_USER"],+ password=os.environ["DB_PASSWORD"],+ )++[email protected](scope="session", autouse=True)+def _prepared_database():+ """Drop + recreate the suite database and apply all migrations."""+ name = os.environ["DB_NAME"]+ conn = _connect("postgres")+ conn.autocommit = True+ with conn.cursor() as cur:+ cur.execute(+ "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "+ "WHERE datname = %s",+ (name,),+ )+ cur.execute(f'DROP DATABASE IF EXISTS "{name}"')+ cur.execute(f'CREATE DATABASE "{name}"')+ conn.close()++ migrations = os.path.join(REPO_ROOT, "backend", "migrations",+ "apply_migrations.py")+ subprocess.run(+ [sys.executable, migrations],+ cwd=REPO_ROOT, env=dict(os.environ), check=True,+ capture_output=True, text=True,+ )+ yield++[email protected](scope="session")+def app():+ from backend import create_app++ return create_app("testing")++[email protected](scope="session")+def client(app):+ return app.test_client()+++_counter = itertools.count(1)+++def _register(client, username=None):+ n = next(_counter)+ username = username or f"user{n}_{uuid.uuid4().hex[:6]}"+ r = client.post("/api/auth/register", json={+ "username": username,+ "email": f"{username}@test.local",+ "password": "TestPass123!",+ "first_name": "Test",+ "last_name": "User",+ })+ assert r.status_code in (200, 201), r.get_data(as_text=True)+ token = r.get_json()["token"]+ return {+ "username": username,+ "headers": {"Authorization": f"Bearer {token}"},+ }++[email protected](scope="session")+def user_factory(client):+ """Callable that registers a fresh user and returns its auth bundle."""+ def _make(username=None):+ return _register(client, username)++ return _make++[email protected](scope="session")+def admin_user(user_factory):+ """The first registered user becomes owner + admin."""+ return user_factory("testadmin")++[email protected](scope="session")+def warranty_factory(client):+ """Callable posting a warranty form; returns the response."""+ def _make(headers, **fields):+ data = {+ "product_name": "Widget",+ "purchase_date": "2025-01-01",+ "exact_expiration_date": "2027-01-01",+ }+ data.update(fields)+ return client.post("/api/warranties", data=data, headers=headers)++ return _make++[email protected](scope="session")+def paperless_url():+ import mock_paperless++ server, url = mock_paperless.create_server()+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ yield url+ server.shutdown()++[email protected](scope="session")+def paperless_configured(admin_user, paperless_url):+ """Point the app's site settings at the mock Paperless server."""+ conn = _connect(os.environ["DB_NAME"])+ with conn, conn.cursor() as cur:+ for key, value in (+ ("paperless_enabled", "true"),+ ("paperless_url", paperless_url),+ ("paperless_api_token", "test-token"),+ ):+ cur.execute(+ "INSERT INTO site_settings (key, value) VALUES (%s, %s) "+ "ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value",+ (key, value),+ )+ conn.close()+ return paperless_urldiff --git a/tests/mock_paperless.py b/tests/mock_paperless.pynew file mode 100644index 0000000..0aef543--- /dev/null+++ b/tests/mock_paperless.py@@ -0,0 +1,140 @@+"""Self-contained mock of the Paperless-ngx REST API surface Warracker uses.++Implements: document list/search, post_document upload, task polling,+document info/preview/download/thumb. NOT a real Paperless instance.+Used only by the test suite (tests/test_paperless_security.py).+"""+import base64+import json+import re+import uuid+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from urllib.parse import urlparse, parse_qs++PDF_BYTES = b"%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]>>endobj\ntrailer<</Root 1 0 R>>\n%%EOF"+# 1x1 transparent PNG+PNG_BYTES = base64.b64decode(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII="+)++DOCS = [+ {"id": 1, "title": "Invoice - Laptop 2026", "created": "2026-01-20T10:00:00Z",+ "mime_type": "application/pdf", "archived_file_name": "invoice-laptop.pdf"},+ {"id": 2, "title": "Manual - Headphones", "created": "2026-06-05T10:00:00Z",+ "mime_type": "application/pdf", "archived_file_name": "manual-headphones.pdf"},+]+TASKS = {} # task_id -> doc_id+NEXT_ID = [3]+++class Handler(BaseHTTPRequestHandler):+ def log_message(self, *a):+ pass++ def _json(self, obj, status=200):+ body = json.dumps(obj).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def _bytes(self, data, ctype):+ self.send_response(200)+ self.send_header("Content-Type", ctype)+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def do_GET(self):+ u = urlparse(self.path)+ path, qs = u.path, parse_qs(u.query)++ if path == "/api/documents/":+ docs = DOCS+ # checksum dedup lookup: mock docs have no checksums -> no match+ if "checksum__iexact" in qs:+ docs = []+ q = qs.get("query", [""])[0].lower()+ if q:+ docs = [d for d in DOCS if q in d["title"].lower()]+ ti = qs.get("title__icontains", [""])[0].lower()+ if ti:+ docs = [d for d in docs if ti in d["title"].lower()]+ page_size = int(qs.get("page_size", ["25"])[0])+ docs = docs[:page_size]+ return self._json({"count": len(docs), "next": None, "previous": None, "results": docs})++ m = re.match(r"^/api/documents/(\d+)/$", path)+ if m:+ doc = next((d for d in DOCS if d["id"] == int(m.group(1))), None)+ return self._json(doc if doc else {"detail": "Not found"},+ status=200 if doc else 404)++ m = re.match(r"^/api/documents/(\d+)/(preview|download)/$", path)+ if m:+ return self._bytes(PDF_BYTES, "application/pdf")++ m = re.match(r"^/api/documents/(\d+)/thumb/$", path)+ if m:+ return self._bytes(PNG_BYTES, "image/png")++ m = re.match(r"^/api/tasks/([0-9a-f-]+)/$", path)+ if m:+ tid = m.group(1)+ if tid in TASKS:+ return self._json({"id": tid, "state": "SUCCESS",+ "result": f"document id {TASKS[tid]}"})+ return self._json({"detail": "Not found"}, status=404)++ if path == "/api/tasks/":+ tid = qs.get("task_id", [""])[0]+ if tid in TASKS:+ return self._json([{"id": tid, "state": "SUCCESS",+ "result": f"document id {TASKS[tid]}"}])+ return self._json([])++ if path == "/api/tags/":+ return self._json({"count": 2, "next": None, "previous": None,+ "results": [{"id": 1, "name": "invoice"},+ {"id": 2, "name": "manual"}]})++ self._json({"detail": "not found"}, status=404)++ def do_POST(self):+ u = urlparse(self.path)+ if u.path == "/api/documents/post_document/":+ length = int(self.headers.get("Content-Length", 0))+ body = self.rfile.read(length) if length else b""+ # extract filename from multipart+ m = re.search(rb'filename="([^"]+)"', body)+ fname = m.group(1).decode(errors="replace") if m else "upload.pdf"+ # Real Paperless-ngx honors the submitted 'title' form field+ mt = re.search(rb'name="title"\r\n\r\n([^\r\n]+)', body)+ title = mt.group(1).decode(errors="replace") if mt else fname+ doc_id = NEXT_ID[0]+ NEXT_ID[0] += 1+ DOCS.append({"id": doc_id, "title": title,+ "created": "2026-09-30T10:00:00Z",+ "mime_type": "application/pdf",+ "archived_file_name": fname})+ task_id = str(uuid.uuid4())+ TASKS[task_id] = doc_id+ # Return task UUID as plain text (like real Paperless-ngx),+ # toggleable to JSON string via ?json=1 for branch testing+ if parse_qs(urlparse(self.path).query).get("json"):+ return self._json(task_id)+ body = task_id.encode()+ self.send_response(200)+ self.send_header("Content-Type", "text/plain")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)+ return+ self._json({"detail": "not found"}, status=404)+++def create_server():+ """Start the mock on an ephemeral localhost port; returns (server, url)."""+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ return server, f"http://127.0.0.1:{server.server_address[1]}"diff --git a/tests/test_paperless_security.py b/tests/test_paperless_security.pynew file mode 100644index 0000000..bb4506c--- /dev/null+++ b/tests/test_paperless_security.py@@ -0,0 +1,214 @@+"""Paperless-ngx access-control battery.++Ported from the QA security script test_paperless_security.py (27+checks), written for GHSA-fv62-3hrm-gf83 and GHSA-3h89-rqfj-5674 plus+the claim-documents extension. Runs against a mock Paperless server+(tests/mock_paperless.py) with three actors: an admin, a document+owner (user A), and an attacker (user B).++Global view is ON (the default): invoice/manual documents stay+viewable across users by design, but linking, claim documents, and+document metadata must never cross accounts.++The module-scoped `scenario` fixture performs the successful-path+setup in order; the tests then run the blocked/allowed assertions.+"""+import io+from types import SimpleNamespace++import pytest+++def _upload(client, headers, title):+ r = client.post(+ "/api/paperless/upload", headers=headers,+ data={"title": title,+ "file": (io.BytesIO(b"%PDF-1.4 test document"), "doc.pdf")},+ content_type="multipart/form-data")+ body = r.get_json()+ assert body and body.get("success"), f"upload failed: {body}"+ return body["document_id"]+++def _search_ids(client, headers):+ r = client.get("/api/paperless/search", headers=headers,+ query_string={"query": ""})+ return [d["id"] for d in r.get_json().get("results", [])]++[email protected](scope="module")+def scenario(client, admin_user, user_factory, warranty_factory,+ paperless_configured):+ ns = SimpleNamespace()+ ns.admin = admin_user["headers"]+ ns.a = user_factory()["headers"]+ ns.b = user_factory()["headers"]++ # Admin uploads a private document.+ ns.d_admin = _upload(client, ns.admin, "ADMIN-SECRET-INVOICE")++ # User A uploads a document and links it to their own warranty.+ ns.d_a = _upload(client, ns.a, "A-Invoice-Doc")+ r = warranty_factory(ns.a, paperless_invoice_id=str(ns.d_a))+ assert r.status_code == 201, r.get_data(as_text=True)+ ns.wid_a = r.get_json()["id"]++ # Attacker's own plain warranty (target for blocked link attempts).+ r = warranty_factory(ns.b)+ assert r.status_code == 201, r.get_data(as_text=True)+ ns.wid_b = r.get_json()["id"]++ # A search-and-links their own manual document.+ ns.d_a3 = _upload(client, ns.a, "A-Manual-Doc")+ r = client.post("/api/paperless-search-and-link", headers=ns.a, json={+ "warranty_id": ns.wid_a, "document_type": "manual",+ "search_title": "A-Manual-Doc"})+ assert r.status_code == 200, r.get_data(as_text=True)++ # A's claim with A's own Paperless claim document.+ r = client.post(f"/api/warranties/{ns.wid_a}/claims", headers=ns.a,+ json={"claim_date": "2026-02-01", "status": "Submitted",+ "description": "A claim"})+ assert r.status_code == 201, r.get_data(as_text=True)+ ns.cid_a = r.get_json()["id"]+ ns.d_a2 = _upload(client, ns.a, "A-Claim-Evidence")+ r = client.post(+ f"/api/warranties/{ns.wid_a}/claims/{ns.cid_a}/documents",+ headers=ns.a, data={"paperless_document_id": str(ns.d_a2)})+ assert r.status_code == 201, r.get_data(as_text=True)++ # First-linker claims the unowned mock document id 1.+ r = warranty_factory(ns.a, paperless_invoice_id="1")+ assert r.status_code == 201, r.get_data(as_text=True)++ return ns+++# --- Attacker battery: every route to the admin's document must fail ---++def test_attacker_search_excludes_admin_doc(client, scenario):+ assert scenario.d_admin not in _search_ids(client, scenario.b)+++def test_attacker_direct_download_blocked(client, scenario):+ r = client.get(f"/api/paperless-file/{scenario.d_admin}",+ headers=scenario.b)+ assert r.status_code in (403, 404)+++def test_attacker_create_warranty_link_blocked(client, scenario,+ warranty_factory):+ r = warranty_factory(scenario.b,+ paperless_invoice_id=str(scenario.d_admin))+ assert r.status_code == 403+++def test_attacker_search_and_link_blocked(client, scenario):+ r = client.post("/api/paperless-search-and-link", headers=scenario.b,+ json={"warranty_id": scenario.wid_b,+ "document_type": "other",+ "search_title": "ADMIN-SECRET-INVOICE"})+ assert r.status_code == 403+++def test_attacker_update_warranty_link_blocked(client, scenario):+ r = client.put(f"/api/warranties/{scenario.wid_b}", headers=scenario.b,+ data={"product_name": "Widget",+ "purchase_date": "2025-01-01",+ "exact_expiration_date": "2027-01-01",+ "paperless_other_id": str(scenario.d_admin)})+ assert r.status_code == 403+++def test_attacker_debug_endpoints_blocked(client, scenario):+ r = client.get(f"/api/paperless/debug-document/{scenario.d_admin}",+ headers=scenario.b)+ assert r.status_code == 403+ r = client.get("/api/paperless/debug", headers=scenario.b)+ assert r.status_code == 403+++def test_attacker_claim_document_link_blocked(client, scenario):+ r = client.post(f"/api/warranties/{scenario.wid_b}/claims",+ headers=scenario.b,+ json={"claim_date": "2026-01-10", "status": "Submitted",+ "description": "attacker claim"})+ cid_b = r.get_json()["id"]+ r = client.post(+ f"/api/warranties/{scenario.wid_b}/claims/{cid_b}/documents",+ headers=scenario.b,+ data={"paperless_document_id": str(scenario.d_admin)})+ assert r.status_code == 403+++# --- Legitimate owner flows ----------------------------------------------++def test_owner_search_scoping(client, scenario):+ assert scenario.d_a in _search_ids(client, scenario.a)+ assert scenario.d_a not in _search_ids(client, scenario.b)+++def test_owner_download_works(client, scenario):+ r = client.get(f"/api/paperless-file/{scenario.d_a}",+ headers=scenario.a)+ assert r.status_code == 200+++def test_global_view_shares_viewing_not_linking(client, scenario,+ warranty_factory):+ # Invoice-type documents stay viewable across users by design...+ r = client.get(f"/api/paperless-file/{scenario.d_a}",+ headers=scenario.b)+ assert r.status_code == 200+ # ...but linking someone else's document is always blocked.+ r = warranty_factory(scenario.b,+ paperless_invoice_id=str(scenario.d_a))+ assert r.status_code == 403+++def test_claim_document_privacy(client, scenario):+ r = client.get(+ f"/api/warranties/{scenario.wid_a}/claims/{scenario.cid_a}/documents",+ headers=scenario.a)+ assert r.status_code == 200 and len(r.get_json()) == 1++ r = client.get(+ f"/api/warranties/{scenario.wid_a}/claims/{scenario.cid_a}/documents",+ headers=scenario.b)+ assert r.status_code == 404++ # Claim metadata embedded in the claims list: documents only for owner.+ r = client.get(f"/api/warranties/{scenario.wid_a}/claims",+ headers=scenario.b)+ assert all(len(c.get("documents") or []) == 0 for c in r.get_json())+ r = client.get(f"/api/warranties/{scenario.wid_a}/claims",+ headers=scenario.a)+ assert any(len(c.get("documents") or []) == 1 for c in r.get_json())++ # The claim document file itself never crosses accounts.+ r = client.get(f"/api/paperless-file/{scenario.d_a2}",+ headers=scenario.b)+ assert r.status_code in (403, 404)+++def test_first_linker_claims_unowned_document(client, scenario,+ warranty_factory):+ # scenario setup: user A already claimed mock document 1.+ r = warranty_factory(scenario.b, paperless_invoice_id="1")+ assert r.status_code == 403+++def test_admin_keeps_full_access(client, scenario):+ ids = _search_ids(client, scenario.admin)+ assert scenario.d_admin in ids and scenario.d_a in ids+ r = client.get(f"/api/paperless-file/{scenario.d_a}",+ headers=scenario.admin)+ assert r.status_code == 200+ r = client.get(f"/api/paperless/debug-document/{scenario.d_admin}",+ headers=scenario.admin)+ assert r.status_code == 200+++def test_unknown_document_404(client, scenario):+ r = client.get("/api/paperless-file/99999", headers=scenario.a)+ assert r.status_code == 404diff --git a/tests/test_smoke.py b/tests/test_smoke.pynew file mode 100644index 0000000..4ead71d--- /dev/null+++ b/tests/test_smoke.py@@ -0,0 +1,58 @@+"""Smoke tests: the app boots, auth works, warranty CRUD round-trips."""+++def test_health(client):+ r = client.get("/api/health")+ assert r.status_code == 200+++def test_warranties_require_auth(client):+ r = client.get("/api/warranties")+ assert r.status_code == 401+++def test_login_round_trip(client, user_factory):+ user = user_factory()+ r = client.post("/api/auth/login", json={+ "username": user["username"], "password": "TestPass123!"})+ assert r.status_code == 200+ assert r.get_json()["token"]+++def test_warranty_crud(client, user_factory, warranty_factory):+ user = user_factory()+ h = user["headers"]++ r = warranty_factory(h, product_name="Smoke Widget")+ assert r.status_code == 201, r.get_data(as_text=True)+ wid = r.get_json()["id"]++ r = client.get("/api/warranties", headers=h)+ assert r.status_code == 200+ body = r.get_json()+ items = body.get("warranties", body) if isinstance(body, dict) else body+ ids = [w["id"] for w in items]+ assert wid in ids++ # There is no single-warranty GET endpoint; reads go through the list.+ r = client.put(f"/api/warranties/{wid}", headers=h, data={+ "product_name": "Renamed Widget",+ "purchase_date": "2025-01-01",+ "exact_expiration_date": "2027-01-01",+ "is_lifetime": "false",+ })+ assert r.status_code == 200, r.get_data(as_text=True)++ r = client.get("/api/warranties", headers=h)+ body = r.get_json()+ items = body.get("warranties", body) if isinstance(body, dict) else body+ renamed = [w for w in items if w["id"] == wid]+ assert renamed and renamed[0]["product_name"] == "Renamed Widget"++ r = client.delete(f"/api/warranties/{wid}", headers=h)+ assert r.status_code in (200, 204), r.get_data(as_text=True)++ r = client.get("/api/warranties", headers=h)+ body = r.get_json()+ items = body.get("warranties", body) if isinstance(body, dict) else body+ assert wid not in [w["id"] for w in items]diff --git a/tests/test_validation_and_stats.py b/tests/test_validation_and_stats.pynew file mode 100644index 0000000..7925212--- /dev/null+++ b/tests/test_validation_and_stats.py@@ -0,0 +1,117 @@+"""Validation limits, statistics buckets, claim statuses, CSV import.++Ported from the QA regression script test_fixes.py (16 checks), which+verified fixes for findings F1-F5. Each test uses its own fresh user+so statistics counts stay isolated.+"""+import io+from datetime import date, timedelta++TODAY = date.today()+TODAY_S = TODAY.isoformat()+NEXT_YEAR = (TODAY + timedelta(days=365)).isoformat()+++def _add(client, headers, name, purchase, exp_date=None, lifetime=False,+ duration=None):+ form = {"product_name": name, "purchase_date": purchase,+ "is_lifetime": str(lifetime).lower()}+ if exp_date:+ form["exact_expiration_date"] = exp_date+ if duration:+ form.update({"warranty_duration_years": str(duration[0]),+ "warranty_duration_months": str(duration[1]),+ "warranty_duration_days": str(duration[2])})+ return client.post("/api/warranties", data=form, headers=headers)+++def test_product_name_length(client, user_factory):+ h = user_factory()["headers"]+ r = _add(client, h, "x" * 500, TODAY_S, exp_date=NEXT_YEAR)+ assert r.status_code == 400+ r = _add(client, h, "x" * 255, TODAY_S, exp_date=NEXT_YEAR)+ assert r.status_code == 201, r.get_data(as_text=True)+ wid = r.get_json()["id"]+ r = client.put(f"/api/warranties/{wid}", headers=h, data={+ "product_name": "y" * 500, "purchase_date": TODAY_S,+ "exact_expiration_date": NEXT_YEAR, "is_lifetime": "false"})+ assert r.status_code == 400+++def test_expiration_not_before_purchase(client, user_factory):+ h = user_factory()["headers"]+ r = _add(client, h, "Backwards", TODAY_S,+ exp_date=(TODAY - timedelta(days=10)).isoformat())+ assert r.status_code == 400+ r = _add(client, h, "Backwards2", TODAY_S, exp_date=TODAY_S)+ assert r.status_code == 201, r.get_data(as_text=True)++ r = _add(client, h, "OK name", TODAY_S, exp_date=NEXT_YEAR)+ wid = r.get_json()["id"]+ r = client.put(f"/api/warranties/{wid}", headers=h, data={+ "product_name": "OK name", "purchase_date": TODAY_S,+ "exact_expiration_date": (TODAY - timedelta(days=5)).isoformat(),+ "is_lifetime": "false"})+ assert r.status_code == 400+++def test_statistics_buckets(client, user_factory):+ h = user_factory()["headers"]+ # Two long-lived warranties plus one expiring today.+ for name in ("LongA", "LongB"):+ r = _add(client, h, name, TODAY_S, exp_date=NEXT_YEAR)+ assert r.status_code == 201, r.get_data(as_text=True)+ r = _add(client, h, "ExpiresToday",+ (TODAY - timedelta(days=364)).isoformat(), exp_date=TODAY_S)+ assert r.status_code == 201, r.get_data(as_text=True)+ r = _add(client, h, "ExpiredY",+ (TODAY - timedelta(days=400)).isoformat(),+ exp_date=(TODAY - timedelta(days=1)).isoformat())+ assert r.status_code == 201, r.get_data(as_text=True)++ st = client.get("/api/statistics", headers=h).get_json()+ assert st["expired"] == 1 # only yesterday's+ assert st["expiring_soon"] >= 1 # today's is expiring, not expired+ assert st["active"] >= 3 # two long-lived + today's+++def test_claim_status_validation(client, user_factory, warranty_factory):+ h = user_factory()["headers"]+ wid = warranty_factory(h).get_json()["id"]++ r = client.post(f"/api/warranties/{wid}/claims", headers=h, json={+ "claim_date": TODAY_S, "status": "Bogus"})+ assert r.status_code == 400+ r = client.post(f"/api/warranties/{wid}/claims", headers=h, json={+ "claim_date": TODAY_S, "status": "Submitted"})+ assert r.status_code == 201, r.get_data(as_text=True)+ cid = r.get_json()["id"]++ r = client.put(f"/api/warranties/{wid}/claims/{cid}", headers=h,+ json={"status": "Nope"})+ assert r.status_code == 400+ r = client.put(f"/api/warranties/{wid}/claims/{cid}", headers=h,+ json={"status": "In Progress"})+ assert r.status_code == 200+++def test_csv_import_comma_tags(client, user_factory):+ h = user_factory()["headers"]+ csv_body = (+ "ProductName,PurchaseDate,IsLifetime,WarrantyDurationYears,"+ "WarrantyDurationMonths,WarrantyDurationDays,ExpirationDate,"+ "Status,PurchasePrice,SerialNumber,ProductURL,Tags,Vendor\n"+ f'"TaggedWarranty",{TODAY_S},FALSE,1,0,0,,"",,,'+ f'"http://x.test","alpha, beta",Acme\n'+ )+ r = client.post("/api/warranties/import", headers=h,+ data={"csv_file": (io.BytesIO(csv_body.encode()),+ "t.csv")},+ content_type="multipart/form-data")+ assert r.status_code == 200, r.get_data(as_text=True)++ tags_json = client.get("/api/tags", headers=h).get_json()+ tags_list = (tags_json.get("tags", tags_json)+ if isinstance(tags_json, dict) else tags_json)+ names = sorted(t["name"].lower() for t in tags_list)+ assert names == ["alpha", "beta"] # two tags, not one "alpha, beta"