Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

ci(workflows): use native uv and speed up test suites (#870)

Albert Dolkun9af6a01f846b
diff --git a/.github/ci/changes.py b/.github/ci/changes.py
new file mode 100644
index 00000000..6a75de90
--- /dev/null
+++ b/.github/ci/changes.py
@@ -0,0 +1,63 @@
+"""Select complete CI suites only when a verified PR merge proves relevance."""
+
+import json
+import os
+import subprocess
+from pathlib import Path
+
+PROSE = {
+ b"README.md", b"CONTRIBUTING.md",
+ b"CODE_OF_CONDUCT.md", b"SECURITY.md", b"LICENSE",
+}
+
+
+def git(*args):
+ return subprocess.check_output(["git", *args], stderr=subprocess.PIPE, timeout=30)
+
+
+def changed_jobs():
+ # Every push validates the integrated codebase, including documentation pushes.
+ if os.environ.get("GITHUB_EVENT_NAME") != "pull_request":
+ return True, True, True
+
+ try:
+ event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_bytes())
+ pr = event["pull_request"]
+ if os.environ["GITHUB_REF"] != f"refs/pull/{event['number']}/merge":
+ raise ValueError("checkout is not the PR merge ref")
+ parents = git("rev-list", "--parents", "-n", "1", "HEAD").decode("ascii").split()
+ if parents != [os.environ["GITHUB_SHA"], pr["base"]["sha"], pr["head"]["sha"]]:
+ raise ValueError("checkout does not match the event's merge and parents")
+
+ # NULs preserve odd filenames; disabling renames retains both sides of a move.
+ diff = git("diff", "--no-ext-diff", "--no-renames", "--name-only", "-z",
+ "HEAD^1", "HEAD", "--")
+ if not diff.endswith(b"\0"):
+ raise ValueError("empty or incomplete changed-file list")
+ backend = frontend = helm = False
+ for path in diff[:-1].split(b"\0"):
+ if path.startswith(b"backend/"):
+ backend = True
+ elif path.startswith(b"frontend/"):
+ frontend = True
+ elif path.startswith(b"charts/securo/"):
+ helm = True
+ elif path in PROSE or (path.startswith(b"docs/") and path.endswith(b".md")):
+ continue
+ else:
+ # Unknown/shared paths (including workflows and this script) run everything.
+ return True, True, True
+ return backend, frontend, helm
+ except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as error:
+ print(f"Cannot determine PR relevance ({type(error).__name__}); running all suites.")
+ return True, True, True
+
+
+if __name__ == "__main__":
+ backend, frontend, helm = changed_jobs()
+ outputs = (f"run_backend={str(backend).lower()}\n"
+ f"run_frontend={str(frontend).lower()}\nrun_helm={str(helm).lower()}\n")
+ # Failure to publish is a failed step, never a successful skip.
+ with open(os.environ["GITHUB_OUTPUT"], "a") as output:
+ output.write(outputs)
+ print(outputs, end="")
diff --git a/.github/ci/test_changes.py b/.github/ci/test_changes.py
new file mode 100644
index 00000000..66def9d5
--- /dev/null
+++ b/.github/ci/test_changes.py
@@ -0,0 +1,184 @@
+"""Run with python3 .github/ci/test_changes.py; no application dependencies needed."""
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+SELECTOR = Path(__file__).with_name("changes.py").resolve()
+
+
+class CIChangesTest(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.repo = Path(self.temp.name) / "repo"
+ self.repo.mkdir()
+ self.env = dict(os.environ, GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull)
+ self.git("init", "-q", "-b", "base")
+ self.git("config", "user.name", "CI Test")
+ self.git("config", "user.email", "[email protected]")
+ for name in ("README.md", "docs/guide.md", "backend/old.py", "frontend/old.ts", "charts/securo/old.yaml"):
+ self.write(name, "original\n")
+ self.git("add", ".")
+ self.git("commit", "-qm", "base")
+ self.base = self.git("rev-parse", "HEAD")
+
+ def git(self, *args):
+ return subprocess.check_output(
+ ["git", "-c", "commit.gpgSign=false", "-c", f"core.hooksPath={os.devnull}", *args],
+ cwd=self.repo, env=self.env, stderr=subprocess.PIPE,
+ ).decode().strip()
+
+ def write(self, name, text):
+ path = self.repo / name
+ if text is None:
+ path.unlink()
+ else:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+
+ def merge(self, files):
+ self.git("switch", "-C", "feature", self.base)
+ for name, text in files.items():
+ self.write(name, text)
+ self.git("add", "-A")
+ self.git("commit", "--allow-empty", "-qm", "feature")
+ head = self.git("rev-parse", "HEAD")
+ self.git("switch", "--detach", self.base)
+ self.git("merge", "--no-ff", "--no-edit", "feature")
+ self.event = {"number": 123, "pull_request": {
+ "base": {"sha": self.base}, "head": {"sha": head},
+ }}
+ self.env.update(GITHUB_EVENT_NAME="pull_request", GITHUB_REF="refs/pull/123/merge",
+ GITHUB_SHA=self.git("rev-parse", "HEAD"))
+
+ def select(self, expected, overrides=None, event_text=None):
+ event_file = Path(self.temp.name) / "event.json"
+ event_file.write_text(json.dumps(self.event) if event_text is None else event_text)
+ output_file = Path(self.temp.name) / "output"
+ output_file.write_text("")
+ env = dict(self.env, GITHUB_EVENT_PATH=str(event_file), GITHUB_OUTPUT=str(output_file))
+ env.update(overrides or {})
+ result = subprocess.run([sys.executable, "-B", str(SELECTOR)], cwd=self.repo,
+ env=env, capture_output=True, text=True, check=False)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(output_file.read_text(),
+ f"run_backend={expected[0]}\nrun_frontend={expected[1]}\nrun_helm={expected[2]}\n")
+
+ def test_component_docs_and_shared_paths(self):
+ cases = [
+ ({"README.md": "docs", "docs/new.md": "docs"}, ("false", "false", "false")),
+ ({"frontend/new.ts": "code"}, ("false", "true", "false")),
+ ({"backend/new.py": "code"}, ("true", "false", "false")),
+ ({"backend/README.md": "fixture"}, ("true", "false", "false")),
+ ({"backend/new.py": "code", "frontend/new.ts": "code"}, ("true", "true", "false")),
+ ({"charts/securo/new.yaml": "chart"}, ("false", "false", "true")),
+ ({"charts/securo/README.md": "docs"}, ("false", "false", "true")),
+ ]
+ for name in (".github/workflows/ci.yml", ".github/ci/changes.py",
+ ".github/ci/test_changes.py", "charts/other/Chart.yaml", "docker-compose.yml", "mise.toml",
+ "docs/tool.py", "unexpected.md", "new-package/code.py"):
+ cases.append(({name: "shared"}, ("true", "true", "true")))
+ for files, expected in cases:
+ with self.subTest(files=files):
+ self.merge(files)
+ self.select(expected)
+
+ def test_deleted_and_renamed_files(self):
+ for old, new, expected in (
+ ("backend/old.py", None, ("true", "false", "false")),
+ ("frontend/old.ts", None, ("false", "true", "false")),
+ ("backend/old.py", "docs/moved.md", ("true", "false", "false")),
+ ("frontend/old.ts", "docs/moved.md", ("false", "true", "false")),
+ ("backend/old.py", "frontend/moved.ts", ("true", "true", "false")),
+ ("charts/securo/old.yaml", None, ("false", "false", "true")),
+ ("charts/securo/old.yaml", "docs/moved.md", ("false", "false", "true")),
+ ("charts/securo/old.yaml", "backend/moved.py", ("true", "false", "true")),
+ ("docs/guide.md", "backend/moved.py", ("true", "false", "false")),
+ ):
+ with self.subTest(old=old, new=new):
+ files = {old: None}
+ if new:
+ files[new] = "original\n"
+ self.merge(files)
+ self.select(expected)
+
+ def test_odd_names_and_large_diffs(self):
+ names = ["space name", "tab\tname", "line\nbackend/fake.py", "quotes'\"",
+ "$(touch injected)", "`touch injected`", "-leading", "日本語"]
+ self.merge({f"frontend/{name}.ts": "code" for name in names})
+ self.select(("false", "true", "false"))
+ self.assertFalse((self.repo / "injected").exists())
+ # Git filenames are bytes; this also works on systems rejecting undecodable names.
+ if sys.platform.startswith("linux"):
+ self.merge({"backend/odd-\udcff.py": "code"})
+ self.select(("true", "false", "false"))
+ self.merge({**{f"docs/{i}.md": "docs" for i in range(350)},
+ "backend/last.py": "code"})
+ self.select(("true", "false", "false"))
+
+ def test_merge_includes_all_pr_commits_but_not_base_only_changes(self):
+ self.git("switch", "-c", "feature")
+ self.write("frontend/first.ts", "first")
+ self.git("add", ".")
+ self.git("commit", "-qm", "first")
+ self.write("README.md", "last PR commit only changes docs")
+ self.git("commit", "-qam", "second")
+ head = self.git("rev-parse", "HEAD")
+ self.git("switch", "base")
+ self.write("backend/base-only.py", "base advanced")
+ self.git("add", ".")
+ self.git("commit", "-qm", "base advanced")
+ base = self.git("rev-parse", "HEAD")
+ self.git("merge", "--no-ff", "--no-edit", "feature")
+ self.event = {"number": 123, "pull_request": {
+ "base": {"sha": base}, "head": {"sha": head},
+ }}
+ self.env.update(GITHUB_EVENT_NAME="pull_request", GITHUB_REF="refs/pull/123/merge",
+ GITHUB_SHA=self.git("rev-parse", "HEAD"))
+ self.select(("false", "true", "false"))
+
+ def test_unverifiable_inputs_and_non_pr_events_run_everything(self):
+ self.merge({"README.md": "docs"})
+ for overrides in (
+ {"GITHUB_REF": "refs/heads/feature"}, {"GITHUB_SHA": "0" * 40},
+ {"GITHUB_EVENT_PATH": "/missing/event.json"},
+ {"GITHUB_EVENT_NAME": "push"}, {"GITHUB_EVENT_NAME": "workflow_dispatch"},
+ {"PATH": ""},
+ ):
+ with self.subTest(overrides=overrides):
+ self.select(("true", "true", "true"), overrides)
+ for event_text in ("{", "null", "[]", "{}", '{"number":123,"pull_request":null}'):
+ with self.subTest(event_text=event_text):
+ self.select(("true", "true", "true"), event_text=event_text)
+ self.event["pull_request"]["base"]["sha"] = "0" * 40
+ self.select(("true", "true", "true"))
+ self.merge({})
+ self.select(("true", "true", "true"))
+
+ def test_checkout_depth_and_head_ref(self):
+ self.merge({"README.md": "docs"})
+ source = self.repo
+ for depth, expected in ((2, ("false", "false", "false")), (1, ("true", "true", "true"))):
+ clone = Path(self.temp.name) / f"depth-{depth}"
+ self.git("clone", "-q", f"--depth={depth}", source.as_uri(), str(clone))
+ self.repo = clone
+ self.select(expected)
+ self.repo = source
+ self.git("switch", "feature")
+ self.select(("true", "true", "true"), {"GITHUB_SHA": self.git("rev-parse", "HEAD")})
+
+ def test_output_publication_failure_fails_step(self):
+ self.merge({"README.md": "docs"})
+ result = subprocess.run([sys.executable, "-B", str(SELECTOR)], cwd=self.repo,
+ env=dict(self.env, GITHUB_OUTPUT=str(self.repo)),
+ capture_output=True, text=True, check=False)
+ self.assertNotEqual(result.returncode, 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index dbba7b9e..b583e1ab 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,10 +6,30 @@ on:
pull_request:
branches: [main]
+# Only superseded PR runs are cancelled; every main push is validated.
+concurrency:
+ group: ci-${{ github.event.pull_request.number || github.run_id }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
jobs:
backend-tests:
name: Backend Tests
runs-on: ubuntu-latest
+ # PostgreSQL starts on skipped PRs too; split setup if that cost dominates.
+ services:
+ postgres:
+ image: pgvector/pgvector:pg16
+ env:
+ POSTGRES_USER: securo_test
+ POSTGRES_PASSWORD: securo_test
+ POSTGRES_DB: securo_test
+ ports:
+ - 5432/tcp
+ options: >-
+ --health-cmd "pg_isready -h 127.0.0.1 -U securo_test -d securo_test"
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
defaults:
run:
working-directory: backend
@@ -22,86 +42,66 @@ jobs:
- name: Detect backend-relevant changes
id: backend-changes
working-directory: .
- run: |
- set -euo pipefail
-
- # Keep the required Backend Tests check fast for PRs that only touch
- # frontend/docs files. Pushes to main still run the full backend suite.
- if [ "${{ github.event_name }}" != "pull_request" ]; then
- echo "run_backend=true" >> "$GITHUB_OUTPUT"
- exit 0
- fi
-
- changed_files="$(git diff --name-only HEAD^1 HEAD)"
- printf '%s\n' "$changed_files"
-
- if printf '%s\n' "$changed_files" | grep -Eq '^(backend/.*|\.github/workflows/ci\.yml)$'; then
- echo "run_backend=true" >> "$GITHUB_OUTPUT"
- else
- echo "run_backend=false" >> "$GITHUB_OUTPUT"
- fi
+ run: python3 .github/ci/changes.py
- name: Skip backend tests
- if: steps.backend-changes.outputs.run_backend != 'true'
+ if: steps.backend-changes.outputs.run_backend == 'false'
run: echo "No backend-relevant changes; skipping backend test suite."
- name: Set up Python
- if: steps.backend-changes.outputs.run_backend == 'true'
+ if: steps.backend-changes.outputs.run_backend != 'false'
uses: actions/setup-python@v7
with:
# Single source of truth with the Docker image: CI must test the
# same interpreter the backend ships with.
python-version-file: backend/.python-version
- cache: pip
+
+ - name: Set up uv
+ if: steps.backend-changes.outputs.run_backend != 'false'
+ uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1
+ with:
+ version: "0.12.17"
+ enable-cache: true
+ cache-dependency-glob: |
+ backend/uv.lock
+ backend/pyproject.toml
+ backend/.python-version
- name: Install dependencies
- if: steps.backend-changes.outputs.run_backend == 'true'
- run: |
- # Everything comes from uv.lock: export it (--frozen never touches
- # the lock) and hand it to pip with hash checking, so CI installs
- # exactly the audited versions.
- # renovate: datasource=pypi depName=uv
- pip install -q uv==0.12.17
- uv export --frozen --all-extras --no-emit-project -o /tmp/requirements-dev.txt
- pip install --require-hashes -r /tmp/requirements-dev.txt
- pip install --no-deps -e .
-
- - name: Verify lockfile is in sync
- if: steps.backend-changes.outputs.run_backend == 'true'
- run: |
- # Fails if pyproject.toml changed without regenerating uv.lock
- # (someone edited deps without running scripts/lock.sh).
- uv lock --check
+ if: steps.backend-changes.outputs.run_backend != 'false'
+ run: uv sync --locked --all-extras
- name: Lint with Ruff
- if: steps.backend-changes.outputs.run_backend == 'true'
- run: ruff check .
+ if: steps.backend-changes.outputs.run_backend != 'false'
+ run: uv run --no-sync ruff check .
- name: Type check with ty
- if: steps.backend-changes.outputs.run_backend == 'true'
- run: ty check .
+ if: steps.backend-changes.outputs.run_backend != 'false'
+ run: uv run --no-sync ty check .
- name: Run tests with coverage
- if: steps.backend-changes.outputs.run_backend == 'true'
+ if: steps.backend-changes.outputs.run_backend != 'false'
+ env:
+ POSTGRES_TEST_URL: postgresql+asyncpg://securo_test:[email protected]:${{ job.services.postgres.ports['5432'] }}/securo_test
run: |
- pytest -n auto --dist loadfile --cov=app --cov-report=xml --cov-report=term-missing --cov-fail-under=60 -ra -W error
+ uv run --no-sync pytest -n auto --dist loadfile --cov=app --cov-report=xml --cov-report=term-missing --cov-fail-under=60 -ra -W error
- name: Upload coverage report
- if: ${{ always() && steps.backend-changes.outputs.run_backend == 'true' }}
+ if: ${{ always() && steps.backend-changes.outputs.run_backend != 'false' }}
uses: actions/upload-artifact@v7
with:
name: coverage-report
path: backend/coverage.xml
- name: Extract coverage percentage
- if: github.ref == 'refs/heads/main' && steps.backend-changes.outputs.run_backend == 'true'
+ if: github.ref == 'refs/heads/main' && steps.backend-changes.outputs.run_backend != 'false'
id: coverage
run: |
COVERAGE=$(python -c "import xml.etree.ElementTree as ET; print(round(float(ET.parse('coverage.xml').getroot().attrib['line-rate']) * 100))")
echo "percentage=$COVERAGE" >> $GITHUB_OUTPUT
- name: Update coverage badge
- if: github.repository == 'securo-finance/securo' && github.ref == 'refs/heads/main' && steps.backend-changes.outputs.run_backend == 'true'
+ if: github.repository == 'securo-finance/securo' && github.ref == 'refs/heads/main' && steps.backend-changes.outputs.run_backend != 'false'
uses: schneegans/[email protected]
with:
auth: ${{ secrets.GIST_TOKEN }}
@@ -123,6 +123,9 @@ jobs:
# once both sides are together is visible here and nowhere else.
- uses: actions/checkout@v7
+ - name: Test CI change selection
+ run: python3 .github/ci/test_changes.py
+
- name: Check the Alembic revision chain
run: python3 backend/scripts/check_migration_chain.py
@@ -135,8 +138,20 @@ jobs:
steps:
- uses: actions/checkout@v7
+ with:
+ fetch-depth: 2
+
+ - name: Detect frontend-relevant changes
+ id: frontend-changes
+ working-directory: .
+ run: python3 .github/ci/changes.py
+
+ - name: Skip frontend checks
+ if: steps.frontend-changes.outputs.run_frontend == 'false'
+ run: echo "No frontend-relevant changes; skipping frontend checks."
- name: Set up Node.js
+ if: steps.frontend-changes.outputs.run_frontend != 'false'
uses: actions/setup-node@v7
with:
node-version: "22"
@@ -144,15 +159,19 @@ jobs:
cache-dependency-path: frontend/package-lock.json
- name: Install dependencies
+ if: steps.frontend-changes.outputs.run_frontend != 'false'
run: npm ci
- name: Lint
+ if: steps.frontend-changes.outputs.run_frontend != 'false'
run: npm run lint -- --max-warnings=0
- name: Type check & Build
+ if: steps.frontend-changes.outputs.run_frontend != 'false'
run: npm run build
- name: Run tests
+ if: steps.frontend-changes.outputs.run_frontend != 'false'
run: npm test
helm-checks:
@@ -165,38 +184,24 @@ jobs:
- name: Detect helm-relevant changes
id: helm-changes
- run: |
- set -euo pipefail
-
- if [ "${{ github.event_name }}" != "pull_request" ]; then
- echo "run_helm=true" >> "$GITHUB_OUTPUT"
- exit 0
- fi
-
- changed_files="$(git diff --name-only HEAD^1 HEAD)"
-
- if echo "$changed_files" | grep -Eq '^(charts/securo/.*|\.github/workflows/ci\.yml)$'; then
- echo "run_helm=true" >> "$GITHUB_OUTPUT"
- else
- echo "run_helm=false" >> "$GITHUB_OUTPUT"
- fi
+ run: python3 .github/ci/changes.py
- name: Skip helm checks
- if: steps.helm-changes.outputs.run_helm != 'true'
+ if: steps.helm-changes.outputs.run_helm == 'false'
run: echo "No helm-relevant changes; skipping helm lint."
- name: Set up Helm
- if: steps.helm-changes.outputs.run_helm == 'true'
+ if: steps.helm-changes.outputs.run_helm != 'false'
uses: azure/setup-helm@v5
with:
version: v4.3.0
- name: Lint Helm Chart
- if: steps.helm-changes.outputs.run_helm == 'true'
+ if: steps.helm-changes.outputs.run_helm != 'false'
run: helm lint charts/securo
- name: Validate Helm Chart with Kubeconform
- if: steps.helm-changes.outputs.run_helm == 'true'
+ if: steps.helm-changes.outputs.run_helm != 'false'
run: |
curl -sL https://github.com/yannh/kubeconform/releases/latest/download/kubeconform-linux-amd64.tar.gz | tar -xz
sudo mv kubeconform /usr/local/bin/
diff --git a/backend/pyproject.toml b/backend/pyproject.toml
index 60c52497..a299b1b8 100644
--- a/backend/pyproject.toml
+++ b/backend/pyproject.toml
@@ -71,6 +71,9 @@ dev = [
include = ["app*"]
[tool.pytest.ini_options]
+# Fail on configuration/marker typos, duplicate parameter IDs and unexpected
+# xfail passes instead of silently weakening the suite.
+strict = true
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "session"
asyncio_default_test_loop_scope = "session"
@@ -96,6 +99,9 @@ omit = [
# 3.12+-only construct is caught here rather than by a self-hoster on 3.11.
python-version = "3.11"
+[tool.ty.rules]
+unused-ignore-comment = "error"
+
[tool.ruff]
line-length = 100
target-version = "py311"
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 7f2c6d5a..c890bf11 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -45,6 +45,8 @@ setattr(_pgv, "Vector", _VectorJSON)
import pytest # noqa: E402
import pytest_asyncio # noqa: E402
from httpx import ASGITransport, AsyncClient # noqa: E402
+from sqlalchemy.dialects.postgresql import UUID # noqa: E402
+from sqlalchemy.ext.compiler import compiles # noqa: E402
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker # noqa: E402
from app.core.database import Base, get_async_session # noqa: E402
@@ -78,12 +80,9 @@ from app.agents.models import ( # noqa: E402,F401
LlmUsage,
)
-# Use SQLite for tests — fast, no external dependency.
-# Keep the DB file off the bind-mounted project dir (macOS bind mounts
-# have known SQLite locking/journal quirks under aiosqlite) — /tmp is a
-# tmpfs inside the container. StaticPool + a single shared connection
-# is required so async fixtures and tests running on the shared
-# session-scoped event loop see the same in-memory schema state.
+# In-memory SQLite keeps tests independent of external databases and other
+# workers. StaticPool shares the connection across fixtures and tests on the
+# session-scoped event loop so they see the same schema state.
from sqlalchemy.pool import StaticPool # noqa: E402
TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"
@@ -97,22 +96,11 @@ engine = create_async_engine(
TestSessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
-# The models declare ids with the PostgreSQL UUID type, and on SQLite the
-# DDL comes out as a literal `UUID`. SQLite does not know that type, so the
-# column gets NUMERIC affinity, and any stored text that parses as a number
-# is silently converted to one. A uuid4 hex made only of digits, or of digits
-# with a single "e" ("6778776194704156e000000000000016" is valid scientific
-# notation), comes back as a float and uuid.UUID() raises. With tens of
-# thousands of ids per run that hit roughly one run in ten, on whatever test
-# happened to draw the number. Declaring the column as CHAR(32) gives it TEXT
-# affinity, which is what the hex string needs. Test-only: Postgres keeps its
-# native type.
-from sqlalchemy.dialects.postgresql import UUID as _PgUUID # noqa: E402
-from sqlalchemy.ext.compiler import compiles # noqa: E402
-
-
-@compiles(_PgUUID, "sqlite")
-def _pg_uuid_as_text_on_sqlite(type_, compiler, **kw):
+# SQLite gives the PostgreSQL UUID type numeric affinity, corrupting UUID hex
+# that looks like a number. Keep its normal bind/result handling but store text;
+# the dialect-specific hook leaves PostgreSQL's native UUID DDL unchanged.
+@compiles(UUID, "sqlite")
+def _compile_sqlite_uuid(type_, compiler, **kw):
return "CHAR(32)"
@@ -124,12 +112,6 @@ async def setup_database():
yield
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
- # Clean up test db file
- import os
- try:
- os.remove("/tmp/securo_test.db")
- except FileNotFoundError:
- pass
@pytest_asyncio.fixture
@@ -144,11 +126,53 @@ async def session() -> AsyncGenerator[AsyncSession, None]:
@pytest_asyncio.fixture
async def clean_db(session: AsyncSession):
"""Clean all data between tests."""
- for table in reversed(Base.metadata.sorted_tables):
- await session.execute(table.delete())
+ import aiosqlite
+
+ assert not (session.new or session.dirty or session.deleted), (
+ "clean_db requires a fresh session without pending ORM changes"
+ )
+ # Batch the same deletes into one driver round trip. An explicit BEGIN keeps
+ # cleanup atomic: executescript otherwise runs each delete in autocommit.
+ statements = ";\n".join(
+ str(table.delete().compile(dialect=engine.dialect))
+ for table in reversed(Base.metadata.sorted_tables)
+ )
+ connection = await session.connection()
+ raw = await connection.get_raw_connection()
+ driver = raw.driver_connection
+ assert isinstance(driver, aiosqlite.Connection)
+ # executescript implicitly commits an existing SQLite transaction. Fail
+ # before touching data if a caller violates this fixture's fresh-session contract.
+ assert not driver.in_transaction, "clean_db requires a fresh session without a transaction"
+ async with driver.executescript("BEGIN;\n" + statements):
+ pass
await session.commit()
[email protected](scope="session", autouse=True)
+def _fast_password_hashes():
+ """Exercise real password hashing, verification and upgrades at test-only costs."""
+ import bcrypt
+ from pwdlib.hashers.argon2 import Argon2Hasher
+
+ gensalt = bcrypt.gensalt
+
+ def _test_gensalt(*args, **kwargs):
+ if args or kwargs:
+ return gensalt(*args, **kwargs)
+ return gensalt(rounds=4)
+
+ def _test_argon2_hasher(*args, **kwargs):
+ # Explicit constructor calls retain all production parameter defaults.
+ if args or kwargs:
+ return Argon2Hasher(*args, **kwargs)
+ return Argon2Hasher(time_cost=1, memory_cost=8, parallelism=1)
+
+ with patch("bcrypt.gensalt", _test_gensalt), \
+ patch("fastapi_users.password.Argon2Hasher", _test_argon2_hasher):
+ yield
+
+
async def override_get_async_session() -> AsyncGenerator[AsyncSession, None]:
async with TestSessionLocal() as session:
yield session
diff --git a/backend/tests/test_agents_mcp_tools.py b/backend/tests/test_agents_mcp_tools.py
index 1c6f4791..7972a291 100644
--- a/backend/tests/test_agents_mcp_tools.py
+++ b/backend/tests/test_agents_mcp_tools.py
@@ -355,18 +355,6 @@ async def test_aggregate_by_category(
assert "Transporte" in labels or "Alimentação" in labels
[email protected](reason="aggregate by month uses PostgreSQL to_char, not portable to SQLite test DB")
-async def test_aggregate_by_month(
- session: AsyncSession, ctx: CallContext, test_transactions
-):
- handler = REGISTRY["aggregate"].handler
- result = await handler(session=session, ctx=ctx, metric="count", group_by="month")
- assert "items" in result
- for item in result["items"]:
- if item["bucket"]:
- assert len(item["bucket"]) == 7 and item["bucket"][4] == "-"
-
-
async def test_aggregate_unknown_group_by(session: AsyncSession, ctx: CallContext):
handler = REGISTRY["aggregate"].handler
result = await handler(session=session, ctx=ctx, group_by="bogus")
diff --git a/backend/tests/test_credit_card_accounting_mode.py b/backend/tests/test_credit_card_accounting_mode.py
index 2d379101..312b5182 100644
--- a/backend/tests/test_credit_card_accounting_mode.py
+++ b/backend/tests/test_credit_card_accounting_mode.py
@@ -684,19 +684,6 @@ class TestBudgetVsActual:
# ---------------------------------------------------------------------------
-class TestIncomeExpensesReport:
- @pytest.mark.asyncio
- async def test_monthly_report_follows_mode(
- self, session, test_user, cc_account, test_categories
- ):
- # This path uses Postgres-specific `to_char`, which SQLite (the test DB)
- # doesn't implement. Rather than duplicate the query, we skip here and
- # rely on the fact that `get_income_expenses_report` uses the exact
- # same `report_date` expression as the dashboard queries above — if
- # those tests pass, this one is wired identically.
- pytest.skip("get_income_expenses_report uses Postgres to_char — SQLite test DB doesn't support it")
-
-
# ---------------------------------------------------------------------------
# Invariant: account balance queries are NOT affected by mode.
# ---------------------------------------------------------------------------
diff --git a/backend/tests/test_dashboard_api.py b/backend/tests/test_dashboard_api.py
index 76810871..d65c1fd7 100644
--- a/backend/tests/test_dashboard_api.py
+++ b/backend/tests/test_dashboard_api.py
@@ -270,20 +270,6 @@ async def test_recurring_projection_respects_end_date(
assert cat_spending["projected_total"] == 60.0
[email protected](reason="to_char() is PostgreSQL-specific; tests use SQLite")
-async def test_monthly_trend_numeric_fields(client, auth_headers, test_transactions):
- """Monthly trend returns numeric values, not strings."""
- response = await client.get("/api/dashboard/monthly-trend", headers=auth_headers)
- assert response.status_code == 200
- data = response.json()
- assert len(data) > 0
-
- for item in data:
- assert isinstance(item["income"], (int, float))
- assert isinstance(item["expenses"], (int, float))
-
-
@pytest.mark.asyncio
async def test_opening_balance_not_counted_as_monthly_income(client, auth_headers):
"""Opening balance transactions must NOT inflate monthly_income on dashboard."""
diff --git a/backend/tests/test_fixture_isolation.py b/backend/tests/test_fixture_isolation.py
new file mode 100644
index 00000000..f7a5168f
--- /dev/null
+++ b/backend/tests/test_fixture_isolation.py
@@ -0,0 +1,131 @@
+"""Fast fixtures must retain committed-data isolation and real password checks."""
+
+import sqlite3
+import subprocess
+import sys
+from inspect import unwrap
+
+import argon2
+import bcrypt
+import pytest
+from fastapi_users import password
+from sqlalchemy import func, select, text
+from sqlalchemy.exc import IntegrityError
+
+from app.core.database import Base
+from app.models.app_settings import AppSetting
+from app.models.transaction import Transaction
+from app.models.user import User
+from tests.conftest import TestSessionLocal, clean_db
+
+
+async def test_cleanup_removes_independently_committed_rows_and_keeps_schema(
+ session, test_transactions
+):
+ tables = tuple(Base.metadata.sorted_tables)
+ for key in ("first-session", "second-session"):
+ async with TestSessionLocal() as writer:
+ writer.add(AppSetting(key=key, value="synthetic"))
+ await writer.commit()
+
+ await unwrap(clean_db)(session)
+
+ async with TestSessionLocal() as observer:
+ for table in tables:
+ assert await observer.scalar(select(func.count()).select_from(table)) == 0
+ observer.add(AppSetting(key="schema-still-usable", value="synthetic"))
+ await observer.commit()
+ assert tuple(Base.metadata.sorted_tables) == tables
+
+
+async def test_failed_cleanup_rolls_back_earlier_deletes(session, test_transactions):
+ before = len(test_transactions)
+ await session.execute(text(
+ "CREATE TEMP TRIGGER fail_cleanup BEFORE DELETE ON users "
+ "BEGIN SELECT RAISE(ABORT, 'synthetic cleanup failure'); END"
+ ))
+ await session.commit()
+ try:
+ with pytest.raises((sqlite3.IntegrityError, IntegrityError), match="cleanup failure"):
+ await unwrap(clean_db)(session)
+ await session.rollback()
+ async with TestSessionLocal() as observer:
+ assert await observer.scalar(select(func.count()).select_from(Transaction)) == before
+ finally:
+ await session.execute(text("DROP TRIGGER fail_cleanup"))
+ await session.commit()
+ await unwrap(clean_db)(session)
+ assert await session.scalar(select(func.count()).select_from(Transaction)) == 0
+
+
[email protected]("pending", ["new", "dirty", "deleted", "flushed"])
+async def test_cleanup_rejects_pending_state_without_committing_it(session, test_user, pending):
+ user_id, email = test_user.id, test_user.email
+ if pending in {"new", "flushed"}:
+ session.add(AppSetting(key="pending-row", value="synthetic"))
+ if pending == "flushed":
+ await session.flush()
+ elif pending == "dirty":
+ test_user.email = "[email protected]"
+ else:
+ await session.delete(test_user)
+
+ with pytest.raises(AssertionError, match="fresh session"):
+ await unwrap(clean_db)(session)
+ await session.rollback()
+
+ async with TestSessionLocal() as observer:
+ user = await observer.get(User, user_id)
+ assert user is not None and user.email == email
+ assert await observer.get(AppSetting, "pending-row") is None
+ await unwrap(clean_db)(session)
+
+
+def test_password_fixture_preserves_verification_upgrade_and_production_defaults():
+ helper = password.PasswordHelper()
+ hashed = helper.hash("synthetic-password")
+ parameters = argon2.extract_parameters(hashed)
+ assert (parameters.time_cost, parameters.memory_cost, parameters.parallelism) == (1, 8, 1)
+ assert parameters.hash_len == argon2.DEFAULT_HASH_LENGTH
+ assert parameters.salt_len == argon2.DEFAULT_RANDOM_SALT_LENGTH
+ assert helper.verify_and_update("synthetic-password", hashed) == (True, None)
+ assert helper.verify_and_update("wrong-password", hashed) == (False, None)
+
+ assert bcrypt.gensalt().startswith(b"$2b$04$")
+ assert bcrypt.gensalt(5).startswith(b"$2b$05$")
+ assert bcrypt.gensalt(rounds=5, prefix=b"2a").startswith(b"$2a$05$")
+ assert bcrypt.gensalt(prefix=b"2a").startswith(b"$2a$12$")
+ legacy = bcrypt.hashpw(b"synthetic-password", bcrypt.gensalt()).decode()
+ valid, upgraded = helper.verify_and_update("synthetic-password", legacy)
+ assert valid and upgraded is not None and upgraded.startswith("$argon2id$")
+ assert helper.verify_and_update("synthetic-password", upgraded) == (True, None)
+ assert helper.verify_and_update("wrong-password", legacy) == (False, None)
+
+ explicit = password.Argon2Hasher(time_cost=2, memory_cost=32, parallelism=2)
+ parameters = argon2.extract_parameters(explicit.hash("synthetic-password"))
+ assert (parameters.time_cost, parameters.memory_cost, parameters.parallelism) == (2, 32, 2)
+ positional = password.Argon2Hasher(2, 32, 2)
+ parameters = argon2.extract_parameters(positional.hash("synthetic-password"))
+ assert (parameters.time_cost, parameters.memory_cost, parameters.parallelism) == (2, 32, 2)
+ partial_keywords = password.Argon2Hasher(time_cost=2)
+ parameters = argon2.extract_parameters(partial_keywords.hash("synthetic-password"))
+ assert parameters.time_cost == 2
+ assert parameters.memory_cost == argon2.DEFAULT_MEMORY_COST
+ assert parameters.parallelism == argon2.DEFAULT_PARALLELISM
+ subprocess.run(
+ [sys.executable, "-c", """
+import argon2
+import bcrypt
+from fastapi_users.password import PasswordHelper
+assert bcrypt.gensalt().startswith(b"$2b$12$")
+helper = PasswordHelper()
+hashed = helper.hash('synthetic-password')
+parameters = argon2.extract_parameters(hashed)
+assert parameters.time_cost == argon2.DEFAULT_TIME_COST
+assert parameters.memory_cost == argon2.DEFAULT_MEMORY_COST
+assert parameters.parallelism == argon2.DEFAULT_PARALLELISM
+assert helper.verify_and_update('synthetic-password', hashed) == (True, None)
+assert helper.verify_and_update('wrong-password', hashed) == (False, None)
+"""],
+ check=True,
+ )
diff --git a/backend/tests/test_report_service.py b/backend/tests/test_report_service.py
index 30dd27a5..45c073bf 100644
--- a/backend/tests/test_report_service.py
+++ b/backend/tests/test_report_service.py
@@ -487,79 +487,6 @@ async def test_net_worth_api_requires_auth(client):
# ---------------------------------------------------------------------------
[email protected](reason="to_char() is PostgreSQL-specific; tests use SQLite")
-async def test_income_expenses_api_endpoint(client, auth_headers, test_transactions):
- """GET /reports/income-expenses returns valid response."""
- response = await client.get(
- "/api/reports/income-expenses",
- params={"months": 12, "interval": "monthly"},
- headers=auth_headers,
- )
- assert response.status_code == 200
- data = response.json()
-
- assert data["meta"]["type"] == "income_expenses"
- assert data["meta"]["series_keys"] == [
- "income", "expenses", "projectedIncome", "projectedExpenses"
- ]
- assert "summary" in data
- assert "trend" in data
-
- # Summary should have income, expenses, netIncome breakdowns
- breakdown_keys = [b["key"] for b in data["summary"]["breakdowns"]]
- assert "income" in breakdown_keys
- assert "expenses" in breakdown_keys
- assert "netIncome" in breakdown_keys
-
- # Verify math: net income = income - expenses
- breakdowns = {b["key"]: b["value"] for b in data["summary"]["breakdowns"]}
- assert abs(breakdowns["netIncome"] - (breakdowns["income"] - breakdowns["expenses"])) < 0.01
-
- # Each trend point has income/expenses breakdowns
- for dp in data["trend"]:
- assert "income" in dp["breakdowns"]
- assert "expenses" in dp["breakdowns"]
- # value = net income = income - expenses
- expected_net = dp["breakdowns"]["income"] - dp["breakdowns"]["expenses"]
- assert abs(dp["value"] - expected_net) < 0.01
-
-
[email protected](reason="to_char() is PostgreSQL-specific; tests use SQLite")
-async def test_income_expenses_excludes_opening_balance(client, auth_headers):
- """Income expenses report excludes opening balance transactions."""
- # Create account with opening balance
- acc_resp = await client.post(
- "/api/accounts",
- json={"name": "IE Test", "type": "checking", "balance": 10000.00, "currency": "BRL"},
- headers=auth_headers,
- )
- assert acc_resp.status_code == 201
-
- response = await client.get(
- "/api/reports/income-expenses",
- params={"months": 1, "interval": "monthly"},
- headers=auth_headers,
- )
- assert response.status_code == 200
- data = response.json()
-
- # Opening balance should NOT appear as income
- breakdowns = {b["key"]: b["value"] for b in data["summary"]["breakdowns"]}
- assert breakdowns["income"] == 0.0
-
-
[email protected](reason="to_char() is PostgreSQL-specific; tests use SQLite")
-async def test_income_expenses_excludes_transfers(client, auth_headers):
- """Income expenses report excludes transfer pair transactions."""
- response = await client.get(
- "/api/reports/income-expenses",
- params={"months": 12, "interval": "monthly"},
- headers=auth_headers,
- )
- assert response.status_code == 200
# Just verify the endpoint works — transfer exclusion is enforced by the SQL filter
@@ -879,36 +806,6 @@ async def test_net_worth_report_has_empty_category_trend(session: AsyncSession,
# ---------------------------------------------------------------------------
[email protected](reason="to_char() is PostgreSQL-specific; tests use SQLite")
-async def test_income_expenses_has_category_trend(client, auth_headers, test_transactions):
- """GET /reports/income-expenses response includes category_trend array."""
- response = await client.get(
- "/api/reports/income-expenses",
- params={"months": 12, "interval": "monthly"},
- headers=auth_headers,
- )
- assert response.status_code == 200
- data = response.json()
-
- assert "category_trend" in data
- assert isinstance(data["category_trend"], list)
-
- # Each item should have the expected shape
- for item in data["category_trend"]:
- assert "key" in item
- assert "label" in item
- assert "color" in item
- assert "total" in item
- assert "group" in item
- assert item["group"] in ("income", "expenses")
- assert "series" in item
- assert isinstance(item["series"], list)
- for point in item["series"]:
- assert "date" in point
- assert "value" in point
-
-
# ---------------------------------------------------------------------------
# _asset_value_at
# ---------------------------------------------------------------------------
diff --git a/backend/tests/test_reports_postgres.py b/backend/tests/test_reports_postgres.py
new file mode 100644
index 00000000..b6dcb6ef
--- /dev/null
+++ b/backend/tests/test_reports_postgres.py
@@ -0,0 +1,272 @@
+"""Real PostgreSQL report/API/MCP checks using the shared disposable schemas."""
+import os
+import uuid
+from datetime import date, timedelta
+from decimal import Decimal
+
+import pytest
+import pytest_asyncio
+from httpx import ASGITransport, AsyncClient
+from sqlalchemy import select, text
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from app.core.database import Base, get_async_session
+from app.main import app
+from app.models.transaction import Transaction
+from app.services import admin_service, report_service
+import mcp_server.tools # noqa: F401 -- registers the real MCP handlers
+from mcp_server.auth import CallContext
+from mcp_server.registry import REGISTRY
+
+pytestmark = pytest.mark.asyncio
+
+
+@pytest_asyncio.fixture
+async def postgres_sessions():
+ """Give each PostgreSQL test its own schema, including under xdist."""
+ url = os.environ.get("POSTGRES_TEST_URL")
+ if not url:
+ if os.environ.get("CI"):
+ pytest.fail("CI must supply POSTGRES_TEST_URL for PostgreSQL tests")
+ pytest.skip("isolated PostgreSQL not configured")
+ schema = f"postgres_test_{uuid.uuid4().hex}"
+ pg_engine = create_async_engine(url)
+ scoped = pg_engine.execution_options(schema_translate_map={None: schema})
+ try:
+ async with pg_engine.begin() as conn:
+ await conn.execute(text(f'CREATE SCHEMA "{schema}"'))
+ async with scoped.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ yield async_sessionmaker(scoped, expire_on_commit=False)
+ finally:
+ try:
+ async with pg_engine.begin() as conn:
+ await conn.execute(text(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE'))
+ finally:
+ await pg_engine.dispose()
+
+
+@pytest_asyncio.fixture
+async def session(postgres_sessions):
+ async with postgres_sessions() as session:
+ yield session
+ await session.rollback()
+
+
+def clean_db(postgres_sessions):
+ """The reused user/data fixtures start in a fresh per-test PostgreSQL schema."""
+
+
+@pytest_asyncio.fixture
+async def client(postgres_sessions, monkeypatch):
+ async def pg_session():
+ async with postgres_sessions() as session:
+ yield session
+
+ monkeypatch.setitem(app.dependency_overrides, get_async_session, pg_session)
+ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
+ yield client
+
+
+async def test_income_expenses_api_endpoint(client, auth_headers, test_transactions):
+ """GET /reports/income-expenses returns valid response."""
+ response = await client.get(
+ "/api/reports/income-expenses",
+ params={"months": 12, "interval": "monthly"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ data = response.json()
+
+ assert data["meta"]["type"] == "income_expenses"
+ assert data["meta"]["series_keys"] == [
+ "income", "expenses", "projectedIncome", "projectedExpenses"
+ ]
+ assert "summary" in data
+ assert "trend" in data
+
+ # Summary should have income, expenses, netIncome breakdowns
+ breakdown_keys = [b["key"] for b in data["summary"]["breakdowns"]]
+ assert "income" in breakdown_keys
+ assert "expenses" in breakdown_keys
+ assert "netIncome" in breakdown_keys
+
+ # Nonzero fixtures make grouping and exclusion failures observable.
+ totals = {b["key"]: b["value"] for b in data["summary"]["breakdowns"]}
+ assert totals["income"] == pytest.approx(8150)
+ assert totals["expenses"] == pytest.approx(110.40)
+
+ # Verify math: net income = income - expenses
+ breakdowns = {b["key"]: b["value"] for b in data["summary"]["breakdowns"]}
+ assert abs(breakdowns["netIncome"] - (breakdowns["income"] - breakdowns["expenses"])) < 0.01
+
+ # Each trend point has income/expenses breakdowns
+ for dp in data["trend"]:
+ assert "income" in dp["breakdowns"]
+ assert "expenses" in dp["breakdowns"]
+ # value = net income = income - expenses
+ expected_net = dp["breakdowns"]["income"] - dp["breakdowns"]["expenses"]
+ assert abs(dp["value"] - expected_net) < 0.01
+
+
+async def test_income_expenses_excludes_opening_balance(client, auth_headers):
+ """Income expenses report excludes opening balance transactions."""
+ # Create account with opening balance
+ acc_resp = await client.post(
+ "/api/accounts",
+ json={"name": "IE Test", "type": "checking", "balance": 10000.00, "currency": "BRL"},
+ headers=auth_headers,
+ )
+ assert acc_resp.status_code == 201
+
+ response = await client.get(
+ "/api/reports/income-expenses",
+ params={"months": 1, "interval": "monthly"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ data = response.json()
+
+ # Opening balance should NOT appear as income
+ breakdowns = {b["key"]: b["value"] for b in data["summary"]["breakdowns"]}
+ assert breakdowns["income"] == 0.0
+
+
+async def test_income_expenses_has_category_trend(client, auth_headers, test_transactions, test_categories):
+ """GET /reports/income-expenses response includes category_trend array."""
+ response = await client.get(
+ "/api/reports/income-expenses",
+ params={"months": 12, "interval": "monthly"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ data = response.json()
+
+ assert "category_trend" in data
+ assert isinstance(data["category_trend"], list)
+
+ # Each item should have the expected shape
+ for item in data["category_trend"]:
+ assert "key" in item
+ assert "label" in item
+ assert "color" in item
+ assert "total" in item
+ assert "group" in item
+ assert item["group"] in ("income", "expenses")
+ assert "series" in item
+ assert isinstance(item["series"], list)
+ for point in item["series"]:
+ assert "date" in point
+ assert "value" in point
+
+ categories = {item["key"]: item for item in data["category_trend"]}
+ for category, expected in zip(test_categories, (45, 25.50, 8000), strict=True):
+ item = categories[str(category.id)]
+ assert item["label"] == category.name
+ assert item["color"] == category.color
+ assert item["total"] == pytest.approx(expected)
+ assert sum(point["value"] for point in item["series"]) == pytest.approx(expected)
+
+
+async def test_income_expenses_excludes_transfers(
+ client, auth_headers, session, test_account, test_transactions,
+):
+ before = await client.get("/api/reports/income-expenses", headers=auth_headers)
+ assert before.status_code == 200
+ destination = await client.post(
+ "/api/accounts",
+ json={"name": "Transfer destination", "type": "savings", "balance": 0, "currency": "BRL"},
+ headers=auth_headers,
+ )
+ assert destination.status_code == 201
+ transfer = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": destination.json()["id"],
+ "description": "Synthetic transfer", "amount": 500,
+ "date": date.today().isoformat(),
+ },
+ headers=auth_headers,
+ )
+ assert transfer.status_code == 201
+ legs = list(await session.scalars(select(Transaction).where(Transaction.transfer_pair_id.is_not(None))))
+ assert len(legs) == 2
+ assert {leg.amount for leg in legs} == {Decimal("500")}
+ response = await client.get("/api/reports/income-expenses", headers=auth_headers)
+ assert response.status_code == 200
+ assert response.json()["summary"]["breakdowns"] == before.json()["summary"]["breakdowns"]
+ totals = {b["key"]: b["value"] for b in response.json()["summary"]["breakdowns"]}
+ assert totals["income"] == pytest.approx(8150)
+ assert totals["expenses"] == pytest.approx(110.40)
+
+
+async def test_monthly_trend_numeric_fields(client, auth_headers, session, test_transactions):
+ today = date.today()
+ previous_month = today.replace(day=1) - timedelta(days=1)
+ test_transactions[0].date = previous_month
+ test_transactions[0].effective_date = previous_month
+ await session.commit()
+ response = await client.get("/api/dashboard/monthly-trend", headers=auth_headers)
+ assert response.status_code == 200
+ data = response.json()
+ assert len(data) > 0
+ for item in data:
+ assert isinstance(item["income"], (int, float))
+ assert isinstance(item["expenses"], (int, float))
+ buckets = {item["month"]: item for item in data}
+ assert buckets[previous_month.strftime("%Y-%m")]["expenses"] == pytest.approx(25.50)
+ current = buckets[today.strftime("%Y-%m")]
+ assert current["income"] == pytest.approx(8150)
+ assert current["expenses"] == pytest.approx(84.90)
+
+
+async def test_aggregate_by_month(session, test_user, test_transactions):
+ today = date.today()
+ previous_month = today.replace(day=1) - timedelta(days=1)
+ test_transactions[0].date = previous_month
+ await session.commit()
+ result = await REGISTRY["aggregate"].handler(
+ session=session,
+ ctx=CallContext(user_id=test_user.id, conversation_id=uuid.uuid4()),
+ metric="count", group_by="month",
+ )
+ assert "items" in result
+ for item in result["items"]:
+ if item["bucket"]:
+ assert len(item["bucket"]) == 7 and item["bucket"][4] == "-"
+ assert {item["bucket"]: item["value"] for item in result["items"]} == {
+ previous_month.strftime("%Y-%m"): 1,
+ today.strftime("%Y-%m"): 4,
+ }
+
+
+async def test_monthly_report_follows_mode(session, test_user, test_account, monkeypatch):
+ class ReportDate(date):
+ @classmethod
+ def today(cls):
+ return cls(2026, 2, 1)
+
+ monkeypatch.setattr(report_service, "date", ReportDate)
+ test_account.type = "credit_card"
+ for when, effective, amount in [
+ (date(2025, 12, 30), date(2026, 1, 16), Decimal("120")),
+ (date(2026, 1, 5), date(2026, 1, 16), Decimal("30")),
+ ]:
+ session.add(Transaction(
+ user_id=test_user.id, account_id=test_account.id,
+ description="Synthetic card purchase", amount=amount, amount_primary=amount,
+ currency="BRL", date=when, effective_date=effective, type="debit", source="manual",
+ ))
+ await session.commit()
+ for mode, expected in [("cash", {"2025-12": 120, "2026-01": 30}),
+ ("accrual", {"2025-12": 0, "2026-01": 150})]:
+ await admin_service.set_app_setting(session, "credit_card_accounting_mode", mode)
+ report = await report_service.get_income_expenses_report(
+ session, test_account.workspace_id, test_user.id, months=3, interval="monthly", currency="BRL",
+ )
+ buckets = {point.date: point.breakdowns["expenses"] for point in report.trend}
+ assert {month: buckets[month] for month in expected} == expected
+ assert sum(buckets.values()) == 150
+ assert next(b.value for b in report.summary.breakdowns if b.key == "expenses") == 150
diff --git a/backend/tests/test_sqlite_uuid.py b/backend/tests/test_sqlite_uuid.py
new file mode 100644
index 00000000..76b6cdcc
--- /dev/null
+++ b/backend/tests/test_sqlite_uuid.py
@@ -0,0 +1,68 @@
+"""SQLite must preserve PostgreSQL-model UUIDs instead of coercing them to numbers."""
+
+from datetime import date
+from decimal import Decimal
+from uuid import UUID
+
+from sqlalchemy import select, text
+from sqlalchemy.dialects import postgresql
+
+from app.models.category import Category
+from app.models.transaction import Transaction
+
+
+async def test_uuid_identity_survives_sqlite_roundtrip_and_foreign_key_lookup(
+ session, test_user, test_account, test_workspace
+):
+ ids = [
+ UUID("50109654-5514-4562-8123-456789012345"),
+ UUID("50109654-5514-4562-8123-456789012346"), # Same float, distinct UUID.
+ UUID("00000000-0000-4000-8000-000000000001"),
+ UUID("12345678-1234-4123-8123-123456789e10"),
+ UUID("abcdefab-cdef-4abc-8def-abcdefabcdef"),
+ ]
+ for value in ids:
+ session.add(Category(
+ id=value,
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name=str(value),
+ ))
+ await session.flush()
+ transaction = Transaction(
+ id=value,
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=test_account.id,
+ category_id=value,
+ description="UUID roundtrip",
+ amount=Decimal("1.00"),
+ date=date(2026, 8, 15),
+ type="debit",
+ source="manual",
+ )
+ session.add(transaction)
+ await session.commit()
+ await session.refresh(transaction)
+ assert transaction.id == value
+ assert transaction.category_id == value
+
+ result = await session.execute(
+ select(Transaction.id, Transaction.category_id, Category.id)
+ .join(Category, Transaction.category_id == Category.id)
+ .where(Transaction.id == value)
+ )
+ assert result.one() == (value, value, value)
+
+ stored = await session.execute(text(
+ "SELECT id, category_id, typeof(id), typeof(category_id) "
+ "FROM transactions ORDER BY id"
+ ))
+ assert stored.all() == sorted((value.hex, value.hex, "text", "text") for value in ids)
+
+
+def test_postgresql_uuid_columns_keep_native_ddl():
+ for table in (Transaction.__table__, Category.__table__):
+ for column in table.columns:
+ if isinstance(column.type, postgresql.UUID):
+ assert column.type.compile(dialect=postgresql.dialect()) == "UUID"
diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts
index bca0833a..0210e62e 100644
--- a/frontend/vitest.config.ts
+++ b/frontend/vitest.config.ts
@@ -1,7 +1,10 @@
-import { defineConfig } from 'vitest/config'
+import { configDefaults, defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
import path from 'node:path'
+// These library suites need the DOM (browser styles, i18n, overlay lookups).
+const nodeTests = ['src/lib/!(theme-utils|workspace-kinds|overlay-layers).test.ts']
+
export default defineConfig({
plugins: [react()],
define: {
@@ -19,14 +22,28 @@ export default defineConfig({
],
},
test: {
- // jsdom for everything, not only the component tests. The pure-function
- // suites under src/lib run fine in it and keeping one environment means a
- // new test file works wherever it is dropped, with no per-file docblock to
- // forget.
- environment: 'jsdom',
- setupFiles: ['./src/test/setup.ts'],
// Vite serves the app's CSS through Tailwind; none of it affects what the
// tests assert, so skip the transform and keep the suite fast.
css: false,
+ projects: [
+ {
+ extends: true,
+ test: {
+ name: 'node',
+ environment: 'node',
+ include: nodeTests,
+ },
+ },
+ {
+ extends: true,
+ test: {
+ name: 'dom',
+ environment: 'jsdom',
+ setupFiles: ['./src/test/setup.ts'],
+ // Every other discovered test keeps the browser environment.
+ exclude: [...configDefaults.exclude, ...nodeTests],
+ },
+ },
+ ],
},
})