Skip to content

πŸ›‘οΈ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Add tests: config deprecation (#221), notification selection, migration upgrade path

Omega (QA)83fc8badadcd
diff --git a/tests/README.md b/tests/README.md
index 10919f3..6fd3303 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -44,6 +44,17 @@ CI runs the same suite on every pull request
other users get the global-view-shared types (photo, invoice,
manual) but never "other documents" or claim documents; missing
files return a JSON 404.
+- `test_config_deprecation.py` β€” the softened #221 behavior: the
+ built-in DB credential defaults still work in 1.0.5, production
+ init does not refuse to start, and the startup deprecation warning
+ names exactly the unset variables (all four gone in 1.0.6).
+- `test_notifications.py` β€” notification selection: the expiring-soon
+ query includes in-window warranties and excludes expired, lifetime,
+ archived and voided ones, and honors each user's own
+ expiring_soon_days preference.
+- `test_migration_upgrade.py` β€” upgrade path: a database built with
+ the pre-1.0.4 migration set (000-051) upgrades to the current
+ schema with its data intact.
- `test_photo_url.py` β€” product photo by URL (#207): the server
downloads the image once and stores it like an upload; redirects are
followed, non-images are rejected, an uploaded file wins over a URL,
diff --git a/tests/test_config_deprecation.py b/tests/test_config_deprecation.py
new file mode 100644
index 0000000..85747cf
--- /dev/null
+++ b/tests/test_config_deprecation.py
@@ -0,0 +1,112 @@
+"""Deprecation of the built-in database credential defaults (#221).
+
+1.0.5 keeps the defaults working but warns at startup about any of
+DB_USER / DB_PASSWORD / DB_ADMIN_USER / DB_ADMIN_PASSWORD that are not
+set explicitly; 1.0.6 removes the defaults and makes them required.
+These tests pin the softened behavior so the 1.0.6 flip is a
+deliberate change, not a surprise.
+"""
+import logging
+
+import pytest
+from flask import Flask
+
+from backend.config import Config, ProductionConfig
+
+DB_VARS = ("DB_USER", "DB_PASSWORD", "DB_ADMIN_USER", "DB_ADMIN_PASSWORD")
+
+
+def bare_app():
+ return Flask(__name__)
+
+
+def _clear_db_env(monkeypatch):
+ for var in DB_VARS:
+ monkeypatch.delenv(var, raising=False)
+
+
+def test_warns_naming_all_unset_vars(bare_app, monkeypatch, caplog):
+ _clear_db_env(monkeypatch)
+ with caplog.at_level(logging.WARNING, logger="backend.config"):
+ Config._warn_unset_db_vars(bare_app)
+ messages = [r.getMessage() for r in caplog.records
+ if "DEPRECATION WARNING" in r.getMessage()]
+ assert len(messages) == 1
+ for var in DB_VARS:
+ assert var in messages[0]
+ assert "1.0.6" in messages[0]
+
+
+def test_warns_only_for_the_unset_vars(bare_app, monkeypatch, caplog):
+ _clear_db_env(monkeypatch)
+ monkeypatch.setenv("DB_USER", "alice")
+ monkeypatch.setenv("DB_PASSWORD", "secret")
+ with caplog.at_level(logging.WARNING, logger="backend.config"):
+ Config._warn_unset_db_vars(bare_app)
+ messages = [r.getMessage() for r in caplog.records
+ if "DEPRECATION WARNING" in r.getMessage()]
+ assert len(messages) == 1
+ assert "DB_ADMIN_USER" in messages[0]
+ assert "DB_ADMIN_PASSWORD" in messages[0]
+ assert "DB_USER" not in messages[0].split(":", 1)[1].split("not set")[0]
+
+
+def test_no_warning_when_all_set(bare_app, monkeypatch, caplog):
+ for var in DB_VARS:
+ monkeypatch.setenv(var, "set-value")
+ with caplog.at_level(logging.WARNING, logger="backend.config"):
+ Config._warn_unset_db_vars(bare_app)
+ assert not [r for r in caplog.records
+ if "DEPRECATION WARNING" in r.getMessage()]
+
+
+def test_no_warning_in_testing(bare_app, monkeypatch, caplog):
+ _clear_db_env(monkeypatch)
+ bare_app.config["TESTING"] = True
+ with caplog.at_level(logging.WARNING, logger="backend.config"):
+ Config._warn_unset_db_vars(bare_app)
+ assert not [r for r in caplog.records
+ if "DEPRECATION WARNING" in r.getMessage()]
+
+
+def test_production_init_starts_on_defaults(bare_app, monkeypatch, caplog):
+ """The softened #221: production init must not refuse to start."""
+ _clear_db_env(monkeypatch)
+ with caplog.at_level(logging.WARNING, logger="backend.config"):
+ ProductionConfig.init_app(bare_app)
+ assert any("DEPRECATION WARNING" in r.getMessage()
+ for r in caplog.records)
+
+
+def test_builtin_defaults_still_present():
+ """Pins the 1.0.5 state; 1.0.6 removes these defaults on purpose.
+
+ The class attributes are bound from the environment at import
+ time, so read them in a subprocess with the four variables
+ removed from the environment.
+ """
+ import json
+ import os
+ import subprocess
+ import sys
+
+ env = {k: v for k, v in os.environ.items() if k not in DB_VARS}
+ code = (
+ "import json; from backend.config import Config; "
+ "print(json.dumps([Config.DB_USER, Config.DB_PASSWORD, "
+ "Config.DB_ADMIN_USER, Config.DB_ADMIN_PASSWORD]))"
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", code], env=env,
+ capture_output=True, text=True, timeout=60,
+ cwd=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
+ )
+ assert result.returncode == 0, result.stderr
+ values = json.loads(result.stdout.strip().splitlines()[-1])
+ assert values == [
+ "warranty_user",
+ "warranty_password",
+ "warracker_admin",
+ "default_admin_password",
+ ]
diff --git a/tests/test_migration_upgrade.py b/tests/test_migration_upgrade.py
new file mode 100644
index 0000000..7fe2e18
--- /dev/null
+++ b/tests/test_migration_upgrade.py
@@ -0,0 +1,108 @@
+"""Upgrade path: a database at the pre-1.0.4 schema (migrations
+000-051) must upgrade cleanly to the current schema with its data
+intact. 1.0.4 added migrations 052 (claim documents), 053 (voided_at)
+and 054 (Paperless document ownership); this exercises exactly that
+hop the way a real install would, by running apply_migrations.py
+twice: once from a directory trimmed to the old migration set, then
+once from the real one.
+"""
+import os
+import shutil
+import subprocess
+import sys
+import uuid
+
+import psycopg2
+import pytest
+
+REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+MIGRATIONS_DIR = os.path.join(REPO_ROOT, "backend", "migrations")
+PRE_104_CUTOFF = "051" # last migration shipped before 1.0.4
+
+
+def _connect(dbname):
+ pw = os.environ["DB_PASSWORD"]
+ return psycopg2.connect(
+ host=os.environ["DB_HOST"],
+ port=os.environ["DB_PORT"],
+ dbname=dbname,
+ user=os.environ["DB_USER"],
+ password=pw,
+ )
+
+
+def _run_migrations(script_dir, dbname):
+ env = dict(os.environ)
+ env["DB_NAME"] = dbname
+ result = subprocess.run(
+ [sys.executable, os.path.join(script_dir, "apply_migrations.py")],
+ env=env, capture_output=True, text=True, timeout=600,
+ )
+ assert result.returncode == 0, result.stdout[-3000:] + result.stderr[-3000:]
+
+
+def scratch_db():
+ dbname = f"warranty_upgrade_{uuid.uuid4().hex[:8]}"
+ conn = _connect("postgres")
+ conn.autocommit = True
+ with conn.cursor() as cur:
+ cur.execute(f'CREATE DATABASE "{dbname}" OWNER "{os.environ["DB_USER"]}"')
+ conn.close()
+ yield dbname
+ conn = _connect("postgres")
+ conn.autocommit = True
+ with conn.cursor() as cur:
+ cur.execute(f'DROP DATABASE IF EXISTS "{dbname}"')
+ conn.close()
+
+
+def test_upgrade_from_pre_104_schema(scratch_db, tmp_path):
+ # 1. Build the old (pre-1.0.4) schema from a trimmed migration set.
+ old_dir = tmp_path / "migrations_old"
+ old_dir.mkdir()
+ for name in os.listdir(MIGRATIONS_DIR):
+ if name == "apply_migrations.py":
+ shutil.copy(os.path.join(MIGRATIONS_DIR, name), old_dir / name)
+ elif name[:3] <= PRE_104_CUTOFF and name.endswith((".sql", ".py")):
+ shutil.copy(os.path.join(MIGRATIONS_DIR, name), old_dir / name)
+ _run_migrations(str(old_dir), scratch_db)
+
+ # 2. Seed representative pre-1.0.4 data.
+ conn = _connect(scratch_db)
+ with conn, conn.cursor() as cur:
+ cur.execute(
+ "INSERT INTO users (username, email, password_hash) "
+ "VALUES ('upgradeuser', '[email protected]', 'x') RETURNING id")
+ user_id = cur.fetchone()[0]
+ cur.execute(
+ "INSERT INTO warranties (product_name, purchase_date, "
+ "expiration_date, user_id) VALUES ('Legacy Toaster', "
+ "'2024-05-01', '2026-05-01', %s) RETURNING id", (user_id,))
+ warranty_id = cur.fetchone()[0]
+ conn.close()
+
+ # 3. Upgrade with the real migration set.
+ _run_migrations(MIGRATIONS_DIR, scratch_db)
+
+ # 4. The 1.0.4 migrations landed and the old data survived.
+ conn = _connect(scratch_db)
+ with conn.cursor() as cur:
+ cur.execute("SELECT filename FROM migrations")
+ applied = {row[0] for row in cur.fetchall()}
+ assert "052_create_claim_documents_table.sql" in applied
+ assert "053_add_voided_at_to_warranties.sql" in applied
+ assert "054_create_paperless_document_ownership.sql" in applied
+
+ cur.execute(
+ "SELECT product_name, voided_at FROM warranties WHERE id = %s",
+ (warranty_id,))
+ name, voided_at = cur.fetchone()
+ assert name == "Legacy Toaster"
+ assert voided_at is None # pre-existing rows are not voided
+
+ cur.execute("SELECT to_regclass('claim_documents')")
+ assert cur.fetchone()[0] is not None
+ cur.execute("SELECT to_regclass('paperless_document_ownership')")
+ assert cur.fetchone()[0] is not None
+ conn.close()
diff --git a/tests/test_notifications.py b/tests/test_notifications.py
new file mode 100644
index 0000000..619e936
--- /dev/null
+++ b/tests/test_notifications.py
@@ -0,0 +1,91 @@
+"""Notification selection: get_expiring_warranties is the query every
+email and Apprise reminder depends on. It must include warranties
+inside the user's expiring-soon window and exclude everything else:
+expired, lifetime, archived, voided, and other users' settings must
+not leak in.
+"""
+from datetime import date, timedelta
+
+from backend.db_handler import get_db_connection, release_db_connection
+from backend.notifications import get_expiring_warranties
+
+TODAY = date.today()
+
+
+def _insert_warranty(cur, user_id, name, expires, **flags):
+ cur.execute(
+ "INSERT INTO warranties (product_name, purchase_date, "
+ "expiration_date, user_id, is_lifetime, archived_at, voided_at) "
+ "VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING id",
+ (
+ name,
+ TODAY - timedelta(days=300),
+ expires,
+ user_id,
+ flags.get("is_lifetime", False),
+ flags.get("archived_at"),
+ flags.get("voided_at"),
+ ),
+ )
+ return cur.fetchone()[0]
+
+
+def _selected_ids(user_id):
+ rows = get_expiring_warranties(get_db_connection, release_db_connection)
+ return {r["warranty_id"] for r in rows if r["user_id"] == user_id}
+
+
+def test_expiring_selection_window_and_exclusions(client, user_factory,
+ db_connection):
+ user = user_factory()
+ conn = db_connection
+ with conn, conn.cursor() as cur:
+ cur.execute("SELECT id FROM users WHERE username = %s",
+ (user["username"],))
+ user_id = cur.fetchone()[0]
+
+ in_window = _insert_warranty(cur, user_id, "InWindow",
+ TODAY + timedelta(days=10))
+ boundary = _insert_warranty(cur, user_id, "Boundary",
+ TODAY + timedelta(days=30))
+ outside = _insert_warranty(cur, user_id, "Outside",
+ TODAY + timedelta(days=45))
+ expired = _insert_warranty(cur, user_id, "Expired",
+ TODAY - timedelta(days=1))
+ lifetime = _insert_warranty(cur, user_id, "Lifetime", None,
+ is_lifetime=True)
+ archived = _insert_warranty(cur, user_id, "Archived",
+ TODAY + timedelta(days=5),
+ archived_at=TODAY)
+ voided = _insert_warranty(cur, user_id, "Voided",
+ TODAY + timedelta(days=5),
+ voided_at=TODAY)
+
+ selected = _selected_ids(user_id)
+ assert in_window in selected
+ assert boundary in selected # the window is inclusive
+ assert outside not in selected
+ assert expired not in selected
+ assert lifetime not in selected
+ assert archived not in selected
+ assert voided not in selected
+
+
+def test_expiring_selection_honors_user_preference(client, user_factory,
+ db_connection):
+ user = user_factory()
+ conn = db_connection
+ with conn, conn.cursor() as cur:
+ cur.execute("SELECT id FROM users WHERE username = %s",
+ (user["username"],))
+ user_id = cur.fetchone()[0]
+ cur.execute(
+ "INSERT INTO user_preferences (user_id, expiring_soon_days) "
+ "VALUES (%s, 7) ON CONFLICT (user_id) "
+ "DO UPDATE SET expiring_soon_days = 7", (user_id,))
+ near = _insert_warranty(cur, user_id, "Near", TODAY + timedelta(days=6))
+ far = _insert_warranty(cur, user_id, "Far", TODAY + timedelta(days=10))
+
+ selected = _selected_ids(user_id)
+ assert near in selected
+ assert far not in selected # 10 days is outside this user's 7-day window