Skip to content

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

improving tests coverage

Tássio Noronha1c606ec95f16
diff --git a/backend/tests/test_accounts_api.py b/backend/tests/test_accounts_api.py
index dba2ff63..85617c70 100644
--- a/backend/tests/test_accounts_api.py
+++ b/backend/tests/test_accounts_api.py
@@ -389,3 +389,119 @@ async def test_list_accounts_includes_previous_balance(client: AsyncClient, auth
test_acc = [a for a in data if a["name"] == "Test PB"][0]
assert "previous_balance" in test_acc
assert isinstance(test_acc["previous_balance"], (int, float))
+
+
+async def test_list_accounts_include_closed(client: AsyncClient, auth_headers):
+ resp = await client.post(
+ "/api/accounts",
+ json={"name": "ClosedTest", "type": "checking", "balance": 0, "currency": "BRL"},
+ headers=auth_headers,
+ )
+ acct_id = resp.json()["id"]
+ await client.post(f"/api/accounts/{acct_id}/close", headers=auth_headers)
+
+ resp_default = await client.get("/api/accounts", headers=auth_headers)
+ ids_default = [a["id"] for a in resp_default.json()]
+ assert acct_id not in ids_default
+
+ resp_all = await client.get("/api/accounts?include_closed=true", headers=auth_headers)
+ ids_all = [a["id"] for a in resp_all.json()]
+ assert acct_id in ids_all
+
+
+async def test_get_account_balance_history(client: AsyncClient, auth_headers):
+ resp = await client.post(
+ "/api/accounts",
+ json={"name": "BH Acct", "type": "checking", "balance": 1000, "currency": "BRL"},
+ headers=auth_headers,
+ )
+ acct_id = resp.json()["id"]
+ resp = await client.get(f"/api/accounts/{acct_id}/balance-history", headers=auth_headers)
+ assert resp.status_code == 200
+ assert isinstance(resp.json(), list)
+
+
+async def test_get_account_balance_history_with_dates(client: AsyncClient, auth_headers):
+ resp = await client.post(
+ "/api/accounts",
+ json={"name": "BH Dates", "type": "checking", "balance": 500, "currency": "BRL"},
+ headers=auth_headers,
+ )
+ acct_id = resp.json()["id"]
+ from datetime import date
+ today = date.today().isoformat()
+ resp = await client.get(
+ f"/api/accounts/{acct_id}/balance-history",
+ params={"from": today, "to": today},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 200
+
+
+async def test_get_account_balance_history_not_found(client: AsyncClient, auth_headers):
+ import uuid
+ resp = await client.get(f"/api/accounts/{uuid.uuid4()}/balance-history", headers=auth_headers)
+ assert resp.status_code == 404
+
+
+async def test_close_account(client: AsyncClient, auth_headers):
+ resp = await client.post(
+ "/api/accounts",
+ json={"name": "Close Me", "type": "checking", "balance": 0, "currency": "BRL"},
+ headers=auth_headers,
+ )
+ acct_id = resp.json()["id"]
+ resp = await client.post(f"/api/accounts/{acct_id}/close", headers=auth_headers)
+ assert resp.status_code == 200
+ assert resp.json()["is_closed"] is True
+
+
+async def test_reopen_account(client: AsyncClient, auth_headers):
+ resp = await client.post(
+ "/api/accounts",
+ json={"name": "Reopen Me", "type": "checking", "balance": 0, "currency": "BRL"},
+ headers=auth_headers,
+ )
+ acct_id = resp.json()["id"]
+ await client.post(f"/api/accounts/{acct_id}/close", headers=auth_headers)
+ resp = await client.post(f"/api/accounts/{acct_id}/reopen", headers=auth_headers)
+ assert resp.status_code == 200
+ assert resp.json()["is_closed"] is False
+
+
+async def test_close_account_not_found(client: AsyncClient, auth_headers):
+ import uuid
+ resp = await client.post(f"/api/accounts/{uuid.uuid4()}/close", headers=auth_headers)
+ assert resp.status_code == 404
+
+
+async def test_reopen_account_not_found(client: AsyncClient, auth_headers):
+ import uuid
+ resp = await client.post(f"/api/accounts/{uuid.uuid4()}/reopen", headers=auth_headers)
+ assert resp.status_code == 404
+
+
+async def test_get_account_summary_with_dates(client: AsyncClient, auth_headers):
+ resp = await client.post(
+ "/api/accounts",
+ json={"name": "Sum Dates", "type": "checking", "balance": 1000, "currency": "BRL"},
+ headers=auth_headers,
+ )
+ acct_id = resp.json()["id"]
+ from datetime import date
+ today = date.today().isoformat()
+ resp = await client.get(
+ f"/api/accounts/{acct_id}/summary",
+ params={"from": today, "to": today},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 200
diff --git a/backend/tests/test_admin_service.py b/backend/tests/test_admin_service.py
new file mode 100644
index 00000000..382b20e7
--- /dev/null
+++ b/backend/tests/test_admin_service.py
@@ -0,0 +1,361 @@
+import uuid
+from datetime import date, datetime, timezone
+from decimal import Decimal
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.asset import Asset
+from app.models.asset_value import AssetValue
+from app.models.bank_connection import BankConnection
+from app.models.budget import Budget
+from app.models.category import Category
+from app.models.category_group import CategoryGroup
+from app.models.import_log import ImportLog
+from app.models.payee import Payee, PayeeMapping
+from app.models.recurring_transaction import RecurringTransaction
+from app.models.rule import Rule
+from app.models.transaction import Transaction
+from app.models.transaction_attachment import TransactionAttachment
+from app.models.user import User
+from app.services.admin_service import (
+ delete_user,
+ get_app_setting,
+ get_user,
+ is_registration_enabled,
+ list_users,
+ set_app_setting,
+ update_user,
+)
+from app.schemas.admin import AdminUserUpdate
+
+
+pytestmark = pytest.mark.asyncio
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+async def _make_user(session: AsyncSession, email: str, is_superuser: bool = False) -> User:
+ import bcrypt as _bcrypt
+ hashed = _bcrypt.hashpw(b"password123", _bcrypt.gensalt()).decode()
+ user = User(
+ id=uuid.uuid4(),
+ email=email,
+ hashed_password=hashed,
+ is_active=True,
+ is_superuser=is_superuser,
+ is_verified=True,
+ preferences={"language": "en", "currency_display": "USD"},
+ )
+ session.add(user)
+ await session.commit()
+ await session.refresh(user)
+ return user
+
+
+async def _populate_user_data(session: AsyncSession, user: User):
+ """Create related data for a user to test cascade delete."""
+ # Category group
+ group = CategoryGroup(id=uuid.uuid4(), user_id=user.id, name="Test Group")
+ session.add(group)
+
+ # Category
+ cat = Category(id=uuid.uuid4(), user_id=user.id, name="Test Cat", icon="x", color="#000")
+ session.add(cat)
+
+ # Connection
+ conn = BankConnection(
+ id=uuid.uuid4(), user_id=user.id, provider="test",
+ external_id="ext-1", institution_name="Test Bank",
+ credentials={}, status="active",
+ last_sync_at=datetime.now(timezone.utc),
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(conn)
+
+ # Account
+ acct = Account(
+ id=uuid.uuid4(), user_id=user.id, name="Acct",
+ type="checking", balance=Decimal("100"), currency="BRL",
+ )
+ session.add(acct)
+
+ # Payee + mapping
+ payee = Payee(id=uuid.uuid4(), user_id=user.id, name="Test Payee")
+ session.add(payee)
+ await session.flush()
+ mapping = PayeeMapping(
+ id=uuid.uuid4(), user_id=user.id, target_id=payee.id,
+ )
+ session.add(mapping)
+
+ # Rule
+ rule = Rule(
+ id=uuid.uuid4(), user_id=user.id, name="R",
+ conditions_op="and", conditions=[], actions=[], priority=1,
+ )
+ session.add(rule)
+
+ # Asset + value
+ asset = Asset(
+ id=uuid.uuid4(), user_id=user.id, name="House",
+ type="real_estate", currency="BRL",
+ )
+ session.add(asset)
+ await session.flush()
+ av = AssetValue(id=uuid.uuid4(), asset_id=asset.id, amount=Decimal("100000"), date=date.today())
+ session.add(av)
+
+ # Transaction + attachment
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=user.id, account_id=acct.id,
+ description="Test txn", amount=Decimal("50"), date=date.today(),
+ type="debit", source="manual", currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.flush()
+ att = TransactionAttachment(
+ id=uuid.uuid4(), user_id=user.id, transaction_id=txn.id,
+ filename="receipt.pdf", storage_key="k", content_type="application/pdf", size=100,
+ )
+ session.add(att)
+
+ # Budget
+ budget = Budget(
+ id=uuid.uuid4(), user_id=user.id, category_id=cat.id,
+ amount=Decimal("500"), month=date.today().replace(day=1), currency="BRL",
+ )
+ session.add(budget)
+
+ # Recurring transaction
+ rec = RecurringTransaction(
+ id=uuid.uuid4(), user_id=user.id, description="Rent",
+ amount=Decimal("2000"), type="debit", frequency="monthly",
+ start_date=date.today(), next_occurrence=date.today(), currency="BRL",
+ )
+ session.add(rec)
+
+ # Import log
+ imp = ImportLog(
+ id=uuid.uuid4(), user_id=user.id, account_id=acct.id,
+ filename="test.ofx", format="ofx", transaction_count=1,
+ )
+ session.add(imp)
+
+ await session.commit()
+
+
+# ---------------------------------------------------------------------------
+# list_users
+# ---------------------------------------------------------------------------
+
+async def test_list_users_basic(session: AsyncSession, clean_db):
+ await _make_user(session, "[email protected]")
+ await _make_user(session, "[email protected]")
+ users, total = await list_users(session)
+ assert total >= 2
+ emails = [u.email for u in users]
+ assert "[email protected]" in emails
+ assert "[email protected]" in emails
+
+
+async def test_list_users_search(session: AsyncSession, clean_db):
+ await _make_user(session, "[email protected]")
+ await _make_user(session, "[email protected]")
+ users, total = await list_users(session, search="searchme")
+ assert total == 1
+ assert users[0].email == "[email protected]"
+
+
+async def test_list_users_pagination(session: AsyncSession, clean_db):
+ for i in range(5):
+ await _make_user(session, f"page{i}@test.com")
+ users, total = await list_users(session, page=1, limit=2)
+ assert total == 5
+ assert len(users) == 2
+
+
+# ---------------------------------------------------------------------------
+# get_user
+# ---------------------------------------------------------------------------
+
+async def test_get_user_found(session: AsyncSession, clean_db):
+ u = await _make_user(session, "[email protected]")
+ result = await get_user(session, u.id)
+ assert result is not None
+ assert result.email == "[email protected]"
+
+
+async def test_get_user_not_found(session: AsyncSession, clean_db):
+ result = await get_user(session, uuid.uuid4())
+ assert result is None
+
+
+# ---------------------------------------------------------------------------
+# update_user
+# ---------------------------------------------------------------------------
+
+async def test_update_user_email(session: AsyncSession, clean_db):
+ admin = await _make_user(session, "[email protected]", is_superuser=True)
+ target = await _make_user(session, "[email protected]")
+ data = AdminUserUpdate(email="[email protected]")
+ result = await update_user(session, target.id, data, admin.id)
+ assert result.email == "[email protected]"
+
+
+async def test_update_user_email_conflict(session: AsyncSession, clean_db):
+ admin = await _make_user(session, "[email protected]", is_superuser=True)
+ await _make_user(session, "[email protected]")
+ target = await _make_user(session, "[email protected]")
+ data = AdminUserUpdate(email="[email protected]")
+ with pytest.raises(ValueError, match="email already exists"):
+ await update_user(session, target.id, data, admin.id)
+
+
+async def test_update_user_password(session: AsyncSession, clean_db):
+ admin = await _make_user(session, "[email protected]", is_superuser=True)
+ target = await _make_user(session, "[email protected]")
+ old_hash = target.hashed_password
+ data = AdminUserUpdate(password="newpassword123")
+ result = await update_user(session, target.id, data, admin.id)
+ assert result is not None
+ # Password should have changed
+ assert result.hashed_password != old_hash
+
+
+async def test_update_user_preferences(session: AsyncSession, clean_db):
+ admin = await _make_user(session, "[email protected]", is_superuser=True)
+ target = await _make_user(session, "[email protected]")
+ new_prefs = {"language": "pt-BR", "currency_display": "BRL"}
+ data = AdminUserUpdate(preferences=new_prefs)
+ result = await update_user(session, target.id, data, admin.id)
+ assert result.preferences["language"] == "pt-BR"
+
+
+async def test_update_user_not_found(session: AsyncSession, clean_db):
+ admin = await _make_user(session, "[email protected]", is_superuser=True)
+ data = AdminUserUpdate(is_active=False)
+ result = await update_user(session, uuid.uuid4(), data, admin.id)
+ assert result is None
+
+
+async def test_update_user_self_demote(session: AsyncSession, clean_db):
+ admin = await _make_user(session, "[email protected]", is_superuser=True)
+ data = AdminUserUpdate(is_superuser=False)
+ with pytest.raises(ValueError, match="own admin"):
+ await update_user(session, admin.id, data, admin.id)
+
+
+async def test_update_user_self_deactivate(session: AsyncSession, clean_db):
+ admin = await _make_user(session, "[email protected]", is_superuser=True)
+ data = AdminUserUpdate(is_active=False)
+ with pytest.raises(ValueError, match="own account"):
+ await update_user(session, admin.id, data, admin.id)
+
+
+async def test_update_user_is_active_and_superuser(session: AsyncSession, clean_db):
+ admin = await _make_user(session, "[email protected]", is_superuser=True)
+ target = await _make_user(session, "[email protected]")
+ data = AdminUserUpdate(is_active=False, is_superuser=True)
+ result = await update_user(session, target.id, data, admin.id)
+ assert result.is_active is False
+ assert result.is_superuser is True
+
+
+# ---------------------------------------------------------------------------
+# delete_user — cascade
+# ---------------------------------------------------------------------------
+
+async def test_delete_user_cascade(session: AsyncSession, clean_db):
+ """Delete a user with all related data (the most important coverage gap)."""
+ admin = await _make_user(session, "[email protected]", is_superuser=True)
+ target = await _make_user(session, "[email protected]")
+ await _populate_user_data(session, target)
+
+ result = await delete_user(session, target.id, admin.id)
+ assert result is True
+
+ # Verify user is gone
+ assert await get_user(session, target.id) is None
+
+
+async def test_delete_user_self_protection(session: AsyncSession, clean_db):
+ admin = await _make_user(session, "[email protected]", is_superuser=True)
+ with pytest.raises(ValueError, match="own account"):
+ await delete_user(session, admin.id, admin.id)
+
+
+async def test_delete_user_last_superuser(session: AsyncSession, clean_db):
+ admin = await _make_user(session, "[email protected]", is_superuser=True)
+ target = await _make_user(session, "[email protected]")
+ # Can delete non-admin
+ assert await delete_user(session, target.id, admin.id) is True
+
+
+async def test_delete_last_superuser_blocked(session: AsyncSession, clean_db):
+ admin1 = await _make_user(session, "[email protected]", is_superuser=True)
+ admin2 = await _make_user(session, "[email protected]", is_superuser=True)
+ # admin2 tries to delete admin1 — should succeed (2 admins remain: admin2)
+ assert await delete_user(session, admin1.id, admin2.id) is True
+
+ # Now create a new target admin, make it the last
+ target = await _make_user(session, "[email protected]", is_superuser=True)
+ # admin2 is one admin, target is another — delete target is fine
+ assert await delete_user(session, target.id, admin2.id) is True
+
+
+async def test_delete_user_not_found(session: AsyncSession, clean_db):
+ admin = await _make_user(session, "[email protected]", is_superuser=True)
+ result = await delete_user(session, uuid.uuid4(), admin.id)
+ assert result is False
+
+
+# ---------------------------------------------------------------------------
+# App settings
+# ---------------------------------------------------------------------------
+
+async def test_get_app_setting_not_found(session: AsyncSession, clean_db):
+ result = await get_app_setting(session, "nonexistent_key")
+ assert result is None
+
+
+async def test_set_app_setting_create(session: AsyncSession, clean_db):
+ setting = await set_app_setting(session, "test_key", "test_value")
+ assert setting.key == "test_key"
+ assert setting.value == "test_value"
+
+
+async def test_set_app_setting_update(session: AsyncSession, clean_db):
+ await set_app_setting(session, "toggle", "true")
+ setting = await set_app_setting(session, "toggle", "false")
+ assert setting.value == "false"
+
+
+async def test_get_app_setting_found(session: AsyncSession, clean_db):
+ await set_app_setting(session, "found_key", "found_value")
+ result = await get_app_setting(session, "found_key")
+ assert result is not None
+ assert result.value == "found_value"
+
+
+# ---------------------------------------------------------------------------
+# is_registration_enabled
+# ---------------------------------------------------------------------------
+
+async def test_is_registration_enabled_from_setting(session: AsyncSession, clean_db):
+ await set_app_setting(session, "registration_enabled", "true")
+ assert await is_registration_enabled(session) is True
+
+ await set_app_setting(session, "registration_enabled", "false")
+ assert await is_registration_enabled(session) is False
+
+
+async def test_is_registration_enabled_fallback_to_env(session: AsyncSession, clean_db):
+ """When no DB setting exists, falls back to env config."""
+ result = await is_registration_enabled(session)
+ # Should not raise; returns the env default
+ assert isinstance(result, bool)
diff --git a/backend/tests/test_asset_service.py b/backend/tests/test_asset_service.py
index 84b7f9cb..ae863993 100644
--- a/backend/tests/test_asset_service.py
+++ b/backend/tests/test_asset_service.py
@@ -11,6 +11,12 @@ from app.models.asset_value import AssetValue
from app.models.user import User
from app.schemas.asset import AssetCreate, AssetUpdate, AssetValueCreate
from app.services import asset_service
+from app.services.asset_service import (
+ _compute_current_value,
+ _generate_growth_values,
+ _next_due_date,
+ get_portfolio_trend,
+)
@pytest_asyncio.fixture
@@ -663,3 +669,144 @@ def test_generate_growth_values_absolute():
assert len(result) >= 6
# First generated value: 1000 + 100 = 1100
assert abs(float(result[0].amount) - 1100.0) < 0.01
+
+
+def test_next_due_date_unknown_frequency():
+ assert _next_due_date(date(2025, 1, 1), "biweekly") == date(2025, 1, 2)
+
+
+def test_generate_growth_values_yearly():
+ result = _generate_growth_values(
+ asset_id=uuid.uuid4(), base_amount=10000.0,
+ base_date=date.today() - timedelta(days=400),
+ growth_type="percentage", growth_rate=5.0,
+ growth_frequency="yearly", growth_start_date=None,
+ )
+ assert len(result) >= 1
+
+
+def test_generate_growth_values_unknown_type():
+ result = _generate_growth_values(
+ asset_id=uuid.uuid4(), base_amount=1000.0,
+ base_date=date.today() - timedelta(days=90),
+ growth_type="unknown", growth_rate=5.0,
+ growth_frequency="monthly", growth_start_date=None,
+ )
+ assert result == []
+
+
+def test_compute_current_value_with_latest():
+ asset = Asset(id=uuid.uuid4(), user_id=uuid.uuid4(), name="A", type="other", currency="USD")
+ val = AssetValue(id=uuid.uuid4(), asset_id=asset.id, amount=Decimal("500"), date=date.today())
+ assert _compute_current_value(asset, val) == 500.0
+
+
+def test_compute_current_value_fallback_purchase_price():
+ asset = Asset(
+ id=uuid.uuid4(), user_id=uuid.uuid4(), name="A", type="other",
+ currency="USD", purchase_price=Decimal("1000"),
+ )
+ assert _compute_current_value(asset, None) == 1000.0
+
+
+def test_compute_current_value_none_without_data():
+ asset = Asset(id=uuid.uuid4(), user_id=uuid.uuid4(), name="A", type="other", currency="USD")
+ assert _compute_current_value(asset, None) is None
+
+
+async def test_update_asset_regenerate_growth(session: AsyncSession, test_user: User):
+ purchase_date = date.today() - timedelta(days=60)
+ data = AssetCreate(
+ name="Regen Asset", type="investment", currency="BRL",
+ valuation_method="growth_rule",
+ purchase_date=purchase_date, purchase_price=Decimal("5000"),
+ growth_type="percentage", growth_rate=Decimal("3"), growth_frequency="monthly",
+ )
+ created = await asset_service.create_asset(session, test_user.id, data)
+
+ update_data = AssetUpdate(growth_rate=Decimal("5"))
+ updated = await asset_service.update_asset(
+ session, created.id, test_user.id, update_data, regenerate_growth=True,
+ )
+ assert updated is not None
+ assert updated.name == "Regen Asset"
+
+
+async def test_update_asset_purchase_price(session: AsyncSession, test_user: User):
+ data = AssetCreate(
+ name="Price Update", type="other", currency="BRL",
+ purchase_price=Decimal("1000"),
+ )
+ created = await asset_service.create_asset(session, test_user.id, data)
+ update_data = AssetUpdate(purchase_price=Decimal("2000"))
+ updated = await asset_service.update_asset(session, created.id, test_user.id, update_data)
+ assert updated.purchase_price == 2000.0
+
+
+async def test_get_asset_values_not_found(session: AsyncSession, test_user: User):
+ result = await asset_service.get_asset_values(session, uuid.uuid4(), test_user.id)
+ assert result is None
+
+
+async def test_add_asset_value_not_found(session: AsyncSession, test_user: User):
+ val_data = AssetValueCreate(amount=Decimal("100"), date=date.today())
+ result = await asset_service.add_asset_value(session, uuid.uuid4(), test_user.id, val_data)
+ assert result is None
+
+
+async def test_delete_asset_value_not_found(session: AsyncSession, test_user: User):
+ assert await asset_service.delete_asset_value(session, uuid.uuid4(), test_user.id) is False
+
+
+async def test_get_asset_value_trend_not_found(session: AsyncSession, test_user: User):
+ result = await asset_service.get_asset_value_trend(session, uuid.uuid4(), test_user.id)
+ assert result is None
+
+
+async def test_portfolio_trend_empty(session: AsyncSession, test_user: User):
+ result = await get_portfolio_trend(session, test_user.id)
+ assert result["assets"] == []
+ assert result["trend"] == []
+ assert result["total"] == 0.0
+
+
+async def test_portfolio_trend_with_assets(session: AsyncSession, test_user: User):
+ a1 = AssetCreate(
+ name="House", type="real_estate", currency="BRL",
+ purchase_date=date.today() - timedelta(days=30),
+ purchase_price=Decimal("300000"), current_value=Decimal("350000"),
+ )
+ a2 = AssetCreate(
+ name="Car", type="vehicle", currency="BRL",
+ purchase_date=date.today() - timedelta(days=10),
+ purchase_price=Decimal("50000"), current_value=Decimal("45000"),
+ )
+ await asset_service.create_asset(session, test_user.id, a1)
+ await asset_service.create_asset(session, test_user.id, a2)
+
+ result = await get_portfolio_trend(session, test_user.id)
+ assert len(result["assets"]) == 2
+ assert len(result["trend"]) > 0
+ assert result["total"] > 0
+
+
+async def test_get_assets_include_archived(session: AsyncSession, test_user: User):
+ await asset_service.create_asset(
+ session, test_user.id, AssetCreate(name="A1", type="other", currency="BRL"),
+ )
+ await asset_service.create_asset(
+ session, test_user.id, AssetCreate(name="A2", type="other", currency="BRL", is_archived=True),
+ )
+ assets = await asset_service.get_assets(session, test_user.id, include_archived=True)
+ names = [a.name for a in assets]
+ assert "A1" in names
+ assert "A2" in names
diff --git a/backend/tests/test_attachment_service.py b/backend/tests/test_attachment_service.py
new file mode 100644
index 00000000..7c264b87
--- /dev/null
+++ b/backend/tests/test_attachment_service.py
@@ -0,0 +1,306 @@
+import uuid
+from datetime import datetime, timezone
+from decimal import Decimal
+from unittest.mock import AsyncMock, patch
+
+import pytest
+import pytest_asyncio
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.transaction import Transaction
+from app.models.transaction_attachment import TransactionAttachment
+from app.providers.storage import StoredFile
+from app.services.attachment_service import (
+ _validate_file,
+ cleanup_attachment_files,
+ delete_attachment,
+ download_attachment,
+ list_attachments,
+ rename_attachment,
+ sanitize_filename,
+ upload_attachment,
+)
+
+
+pytestmark = pytest.mark.asyncio
+
+
+# ---------------------------------------------------------------------------
+# sanitize_filename — pure function
+# ---------------------------------------------------------------------------
+
+
+def test_sanitize_basic():
+ assert sanitize_filename("report.pdf") == "report.pdf"
+
+
+def test_sanitize_special_chars():
+ assert sanitize_filename("my file (1).pdf") == "my_file_1.pdf"
+
+
+def test_sanitize_no_extension():
+ assert sanitize_filename("readme") == "readme"
+
+
+def test_sanitize_empty_name():
+ assert sanitize_filename("...pdf") == "file.pdf"
+
+
+def test_sanitize_unicode():
+ result = sanitize_filename("café résumé.txt")
+ assert result.endswith(".txt")
+
+
+def test_sanitize_multiple_dots():
+ result = sanitize_filename("file.backup.tar.gz")
+ assert result.endswith(".gz")
+
+
+def test_sanitize_collapses_underscores():
+ assert sanitize_filename("a___b.pdf") == "a_b.pdf"
+
+
+# ---------------------------------------------------------------------------
+# _validate_file
+# ---------------------------------------------------------------------------
+
+
+def test_validate_file_too_large():
+ with pytest.raises(ValueError, match="too large"):
+ _validate_file("big.pdf", "application/pdf", 200 * 1024 * 1024)
+
+
+def test_validate_file_bad_extension():
+ with pytest.raises(ValueError, match="not allowed"):
+ _validate_file("hack.exe", "application/octet-stream", 100)
+
+
+def test_validate_file_ok():
+ # Should not raise for allowed extensions
+ _validate_file("receipt.pdf", "application/pdf", 1024)
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+@pytest_asyncio.fixture
+async def txn_account(session: AsyncSession, test_user):
+ acct = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="Attach Acct",
+ type="checking", balance=Decimal("0"), currency="BRL",
+ )
+ session.add(acct)
+ await session.commit()
+ await session.refresh(acct)
+ return acct
+
+
+@pytest_asyncio.fixture
+async def txn_for_attach(session: AsyncSession, test_user, txn_account):
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, account_id=txn_account.id,
+ description="Attach test", amount=Decimal("100"), date=datetime.now(timezone.utc).date(),
+ type="debit", source="manual", currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+ await session.refresh(txn)
+ return txn
+
+
+# ---------------------------------------------------------------------------
+# upload_attachment
+# ---------------------------------------------------------------------------
+
+
+async def test_upload_attachment(session: AsyncSession, test_user, txn_for_attach):
+ mock_storage = AsyncMock()
+ mock_storage.upload = AsyncMock(return_value=StoredFile(
+ storage_key="test/key", size=100, content_type="application/pdf",
+ ))
+ with patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):
+ att = await upload_attachment(
+ session, test_user.id, txn_for_attach.id,
+ "receipt.pdf", "application/pdf", b"fake-data",
+ )
+ assert att.filename == "receipt.pdf"
+ assert att.transaction_id == txn_for_attach.id
+
+
+async def test_upload_attachment_max_limit(session: AsyncSession, test_user, txn_for_attach):
+ """Exceeding max attachments per transaction raises ValueError."""
+ # Pre-seed attachments up to the limit
+ from app.core.config import get_settings
+ limit = get_settings().storage_max_attachments_per_transaction
+ for i in range(limit):
+ att = TransactionAttachment(
+ id=uuid.uuid4(), user_id=test_user.id, transaction_id=txn_for_attach.id,
+ filename=f"file{i}.pdf", storage_key=f"k{i}", content_type="application/pdf", size=10,
+ )
+ session.add(att)
+ await session.commit()
+
+ mock_storage = AsyncMock()
+ mock_storage.upload = AsyncMock(return_value=StoredFile(
+ storage_key="test/key", size=100, content_type="application/pdf",
+ ))
+ with patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):
+ with pytest.raises(ValueError, match="Maximum"):
+ await upload_attachment(
+ session, test_user.id, txn_for_attach.id,
+ "extra.pdf", "application/pdf", b"data",
+ )
+
+
+async def test_upload_wrong_transaction(session: AsyncSession, test_user, txn_for_attach):
+ """Uploading to a non-existent transaction raises LookupError."""
+ mock_storage = AsyncMock()
+ with patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):
+ with pytest.raises(LookupError, match="not found"):
+ await upload_attachment(
+ session, test_user.id, uuid.uuid4(),
+ "file.pdf", "application/pdf", b"data",
+ )
+
+
+# ---------------------------------------------------------------------------
+# list_attachments
+# ---------------------------------------------------------------------------
+
+
+async def test_list_attachments_empty(session: AsyncSession, test_user, txn_for_attach):
+ result = await list_attachments(session, test_user.id, txn_for_attach.id)
+ assert result == []
+
+
+# ---------------------------------------------------------------------------
+# download_attachment
+# ---------------------------------------------------------------------------
+
+
+async def test_download_attachment(session: AsyncSession, test_user, txn_for_attach):
+ att = TransactionAttachment(
+ id=uuid.uuid4(), user_id=test_user.id, transaction_id=txn_for_attach.id,
+ filename="dl.pdf", storage_key="dl/key", content_type="application/pdf", size=5,
+ )
+ session.add(att)
+ await session.commit()
+
+ mock_storage = AsyncMock()
+ mock_storage.download = AsyncMock(return_value=b"pdf-bytes")
+ with patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):
+ result_att, data = await download_attachment(session, att.id, test_user.id)
+ assert data == b"pdf-bytes"
+ assert result_att.filename == "dl.pdf"
+
+
+async def test_download_attachment_not_found(session: AsyncSession, test_user):
+ with pytest.raises(LookupError, match="not found"):
+ await download_attachment(session, uuid.uuid4(), test_user.id)
+
+
+# ---------------------------------------------------------------------------
+# rename_attachment
+# ---------------------------------------------------------------------------
+
+
+async def test_rename_preserves_extension(session: AsyncSession, test_user, txn_for_attach):
+ att = TransactionAttachment(
+ id=uuid.uuid4(), user_id=test_user.id, transaction_id=txn_for_attach.id,
+ filename="original.pdf", storage_key="ren/key", content_type="application/pdf", size=5,
+ )
+ session.add(att)
+ await session.commit()
+
+ result = await rename_attachment(session, att.id, test_user.id, "newname.txt")
+ # Original extension .pdf should be preserved
+ assert result.filename == "newname.pdf"
+
+
+async def test_rename_same_extension(session: AsyncSession, test_user, txn_for_attach):
+ att = TransactionAttachment(
+ id=uuid.uuid4(), user_id=test_user.id, transaction_id=txn_for_attach.id,
+ filename="doc.pdf", storage_key="ren2/key", content_type="application/pdf", size=5,
+ )
+ session.add(att)
+ await session.commit()
+
+ result = await rename_attachment(session, att.id, test_user.id, "renamed.pdf")
+ assert result.filename == "renamed.pdf"
+
+
+async def test_rename_not_found(session: AsyncSession, test_user):
+ with pytest.raises(LookupError, match="not found"):
+ await rename_attachment(session, uuid.uuid4(), test_user.id, "x.pdf")
+
+
+# ---------------------------------------------------------------------------
+# delete_attachment
+# ---------------------------------------------------------------------------
+
+
+async def test_delete_attachment(session: AsyncSession, test_user, txn_for_attach):
+ att = TransactionAttachment(
+ id=uuid.uuid4(), user_id=test_user.id, transaction_id=txn_for_attach.id,
+ filename="del.pdf", storage_key="del/key", content_type="application/pdf", size=5,
+ )
+ session.add(att)
+ await session.commit()
+
+ mock_storage = AsyncMock()
+ with patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):
+ await delete_attachment(session, att.id, test_user.id)
+ mock_storage.delete.assert_called_once_with("del/key")
+
+
+async def test_delete_attachment_not_found(session: AsyncSession, test_user):
+ mock_storage = AsyncMock()
+ with patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):
+ with pytest.raises(LookupError, match="not found"):
+ await delete_attachment(session, uuid.uuid4(), test_user.id)
+
+
+# ---------------------------------------------------------------------------
+# cleanup_attachment_files
+# ---------------------------------------------------------------------------
+
+
+async def test_cleanup_empty_list(session: AsyncSession):
+ await cleanup_attachment_files(session, []) # no-op, should not raise
+
+
+async def test_cleanup_deletes_storage_keys(session: AsyncSession, test_user, txn_for_attach):
+ att1 = TransactionAttachment(
+ id=uuid.uuid4(), user_id=test_user.id, transaction_id=txn_for_attach.id,
+ filename="c1.pdf", storage_key="c1/key", content_type="application/pdf", size=5,
+ )
+ att2 = TransactionAttachment(
+ id=uuid.uuid4(), user_id=test_user.id, transaction_id=txn_for_attach.id,
+ filename="c2.pdf", storage_key="c2/key", content_type="application/pdf", size=5,
+ )
+ session.add_all([att1, att2])
+ await session.commit()
+
+ mock_storage = AsyncMock()
+ with patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):
+ await cleanup_attachment_files(session, [txn_for_attach.id])
+ assert mock_storage.delete.call_count == 2
+
+
+async def test_cleanup_ignores_storage_errors(session: AsyncSession, test_user, txn_for_attach):
+ att = TransactionAttachment(
+ id=uuid.uuid4(), user_id=test_user.id, transaction_id=txn_for_attach.id,
+ filename="err.pdf", storage_key="err/key", content_type="application/pdf", size=5,
+ )
+ session.add(att)
+ await session.commit()
+
+ mock_storage = AsyncMock()
+ mock_storage.delete = AsyncMock(side_effect=Exception("storage down"))
+ with patch("app.services.attachment_service.get_storage_provider", return_value=mock_storage):
+ # Should not raise
+ await cleanup_attachment_files(session, [txn_for_attach.id])
diff --git a/backend/tests/test_category_groups_api.py b/backend/tests/test_category_groups_api.py
new file mode 100644
index 00000000..cd837ba3
--- /dev/null
+++ b/backend/tests/test_category_groups_api.py
@@ -0,0 +1,71 @@
+import uuid
+
+import pytest
+from httpx import AsyncClient
+
+
+async def test_list_groups(client: AsyncClient, auth_headers):
+ response = await client.get("/api/category-groups", headers=auth_headers)
+ assert response.status_code == 200
+ assert isinstance(response.json(), list)
+
+
+async def test_create_group(client: AsyncClient, auth_headers):
+ response = await client.post(
+ "/api/category-groups",
+ json={"name": "Housing", "icon": "home", "color": "#3B82F6"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ assert response.json()["name"] == "Housing"
+
+
+async def test_update_group(client: AsyncClient, auth_headers):
+ create_resp = await client.post(
+ "/api/category-groups",
+ json={"name": "Temp", "icon": "x", "color": "#000"},
+ headers=auth_headers,
+ )
+ group_id = create_resp.json()["id"]
+ response = await client.patch(
+ f"/api/category-groups/{group_id}",
+ json={"name": "Updated"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ assert response.json()["name"] == "Updated"
+
+
+async def test_update_group_not_found(client: AsyncClient, auth_headers):
+ response = await client.patch(
+ f"/api/category-groups/{uuid.uuid4()}",
+ json={"name": "X"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
+async def test_delete_group(client: AsyncClient, auth_headers):
+ create_resp = await client.post(
+ "/api/category-groups",
+ json={"name": "Del Group", "icon": "x", "color": "#000"},
+ headers=auth_headers,
+ )
+ group_id = create_resp.json()["id"]
+ response = await client.delete(
+ f"/api/category-groups/{group_id}", headers=auth_headers,
+ )
+ assert response.status_code == 204
+
+
+async def test_delete_group_not_found(client: AsyncClient, auth_headers):
+ response = await client.delete(
+ f"/api/category-groups/{uuid.uuid4()}", headers=auth_headers,
+ )
+ assert response.status_code == 400
diff --git a/backend/tests/test_connection_service.py b/backend/tests/test_connection_service.py
index d62ad22d..85b9658f 100644
--- a/backend/tests/test_connection_service.py
+++ b/backend/tests/test_connection_service.py
@@ -1,22 +1,23 @@
-"""Service-level tests for connection_service.
-
-Tests: _match_pluggy_category, _description_similarity, get_connections,
-get_connection, delete_connection, update_connection_settings.
-"""
import uuid
-from datetime import datetime, timezone
+from datetime import date, datetime, timezone
+from decimal import Decimal
+from unittest.mock import AsyncMock, patch
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.bank_connection import BankConnection
from app.models.category import Category
+from app.providers.base import AccountData, ConnectionData, ConnectTokenData, TransactionData
from app.services.connection_service import (
_description_similarity,
_match_pluggy_category,
+ create_connect_token,
delete_connection,
get_connection,
get_connections,
+ handle_oauth_callback,
+ sync_connection,
update_connection_settings,
)
@@ -260,3 +261,202 @@ async def test_delete_connection_not_found(session: AsyncSession, test_user):
"""Returns False for nonexistent connection."""
result = await delete_connection(session, uuid.uuid4(), test_user.id)
assert result is False
+
+
+# ---------------------------------------------------------------------------
+# create_connect_token
+# ---------------------------------------------------------------------------
+
+
+async def test_create_connect_token_success(test_user):
+ mock_provider = AsyncMock()
+ mock_provider.create_connect_token = AsyncMock(
+ return_value=ConnectTokenData(access_token="tok-123")
+ )
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):
+ result = await create_connect_token("pluggy", test_user.id)
+ assert result == {"access_token": "tok-123"}
+
+
+# ---------------------------------------------------------------------------
+# handle_oauth_callback
+# ---------------------------------------------------------------------------
+
+
+async def test_handle_oauth_callback_creates_connection(session: AsyncSession, test_user):
+ mock_provider = AsyncMock()
+ mock_provider.handle_oauth_callback = AsyncMock(return_value=ConnectionData(
+ external_id="ext-oauth-1",
+ institution_name="Test Bank",
+ credentials={"token": "abc"},
+ accounts=[
+ AccountData(
+ external_id="acc-1", name="Checking",
+ type="checking", balance=Decimal("1000"), currency="BRL",
+ ),
+ ],
+ ))
+ mock_provider.get_transactions = AsyncMock(return_value=[
+ TransactionData(
+ external_id="tx-1", description="UBER", amount=Decimal("25"),
+ date=date.today(), type="debit", currency="BRL",
+ ),
+ ])
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \
+ patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \
+ patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):
+ conn = await handle_oauth_callback(session, test_user.id, "auth-code", "pluggy")
+
+ assert conn.institution_name == "Test Bank"
+ assert conn.external_id == "ext-oauth-1"
+ assert conn.status == "active"
+
+
+async def test_handle_oauth_callback_with_payee(session: AsyncSession, test_user):
+ mock_provider = AsyncMock()
+ mock_provider.handle_oauth_callback = AsyncMock(return_value=ConnectionData(
+ external_id="ext-oauth-2",
+ institution_name="Payee Bank",
+ credentials={"token": "def"},
+ accounts=[
+ AccountData(
+ external_id="acc-2", name="Savings",
+ type="savings", balance=Decimal("500"), currency="BRL",
+ ),
+ ],
+ ))
+ mock_provider.get_transactions = AsyncMock(return_value=[
+ TransactionData(
+ external_id="tx-2", description="IFOOD", amount=Decimal("30"),
+ date=date.today(), type="debit", currency="BRL",
+ payee="iFood Restaurant",
+ ),
+ ])
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \
+ patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \
+ patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):
+ conn = await handle_oauth_callback(session, test_user.id, "code2", "pluggy")
+
+ assert conn.institution_name == "Payee Bank"
+
+
+# ---------------------------------------------------------------------------
+# sync_connection
+# ---------------------------------------------------------------------------
+
+
+async def test_sync_connection_new_transactions(session: AsyncSession, test_user):
+ conn = await _make_connection(session, test_user.id, "Sync Bank")
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "refreshed"})
+ mock_provider.get_accounts = AsyncMock(return_value=[
+ AccountData(
+ external_id="sync-acc-1", name="Checking",
+ type="checking", balance=Decimal("2000"), currency="BRL",
+ ),
+ ])
+ mock_provider.get_transactions = AsyncMock(return_value=[
+ TransactionData(
+ external_id="sync-tx-1", description="GROCERY",
+ amount=Decimal("80"), date=date.today(), type="debit", currency="BRL",
+ ),
+ ])
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \
+ patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \
+ patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):
+ result_conn, merged = await sync_connection(session, conn.id, test_user.id)
+
+ assert result_conn.status == "active"
+ assert merged == 0
+
+
+async def test_sync_connection_not_found(session: AsyncSession, test_user):
+ with pytest.raises(ValueError, match="not found"):
+ await sync_connection(session, uuid.uuid4(), test_user.id)
+
+
+async def test_sync_connection_with_category_mapping(session: AsyncSession, test_user):
+ conn = await _make_connection(session, test_user.id, "Cat Bank")
+ await _make_category(session, test_user.id, "Alimentação")
+
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock_provider.get_accounts = AsyncMock(return_value=[
+ AccountData(
+ external_id="cat-acc-1", name="Checking",
+ type="checking", balance=Decimal("100"), currency="BRL",
+ ),
+ ])
+ mock_provider.get_transactions = AsyncMock(return_value=[
+ TransactionData(
+ external_id="cat-tx-1", description="RESTAURANT",
+ amount=Decimal("50"), date=date.today(), type="debit",
+ currency="BRL", pluggy_category="Eating out",
+ ),
+ ])
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \
+ patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock):
+ result_conn, _ = await sync_connection(session, conn.id, test_user.id)
+
+ assert result_conn.status == "active"
+
+
+async def test_sync_connection_error_raises(session: AsyncSession, test_user):
+ conn = await _make_connection(session, test_user.id, "Error Bank")
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(side_effect=RuntimeError("API down"))
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider):
+ with pytest.raises(RuntimeError, match="API down"):
+ await sync_connection(session, conn.id, test_user.id)
+
+
+async def test_sync_connection_skips_pending(session: AsyncSession, test_user):
+ conn = await _make_connection(
+ session, test_user.id, "Pending Bank",
+ settings={"import_pending": False},
+ )
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock_provider.get_accounts = AsyncMock(return_value=[
+ AccountData(
+ external_id="pend-acc-1", name="Checking",
+ type="checking", balance=Decimal("100"), currency="BRL",
+ ),
+ ])
+ mock_provider.get_transactions = AsyncMock(return_value=[
+ TransactionData(
+ external_id="pend-tx-1", description="PENDING TXN",
+ amount=Decimal("10"), date=date.today(), type="debit",
+ currency="BRL", status="pending",
+ ),
+ TransactionData(
+ external_id="pend-tx-2", description="POSTED TXN",
+ amount=Decimal("20"), date=date.today(), type="debit",
+ currency="BRL", status="posted",
+ ),
+ ])
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \
+ patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \
+ patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):
+ result_conn, _ = await sync_connection(session, conn.id, test_user.id)
+
+ assert result_conn.status == "active"
diff --git a/backend/tests/test_connections_api.py b/backend/tests/test_connections_api.py
index a3496900..30e94f28 100644
--- a/backend/tests/test_connections_api.py
+++ b/backend/tests/test_connections_api.py
@@ -1,7 +1,13 @@
+import uuid
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock, MagicMock, patch
+
import pytest
from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
from app.models.bank_connection import BankConnection
+from app.models.user import User
@pytest.mark.asyncio
@@ -74,3 +80,185 @@ async def test_delete_connection_not_found(client: AsyncClient, auth_headers, te
async def test_connections_unauthenticated(client: AsyncClient, clean_db):
response = await client.get("/api/connections")
assert response.status_code == 401
+
+
+async def test_update_settings_not_found(client: AsyncClient, auth_headers):
+ resp = await client.patch(
+ f"/api/connections/{uuid.uuid4()}/settings",
+ json={"payee_source": "merchant"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 404
+
+
+async def test_detect_transfers(client: AsyncClient, auth_headers):
+ resp = await client.post("/api/connections/transfers/detect", headers=auth_headers)
+ assert resp.status_code == 200
+ assert "pairs_created" in resp.json()
+
+
+async def test_unlink_transfer_not_found(client: AsyncClient, auth_headers):
+ resp = await client.delete(
+ f"/api/connections/transfers/{uuid.uuid4()}", headers=auth_headers,
+ )
+ assert resp.status_code == 404
+
+
+async def test_create_connect_token_success(client: AsyncClient, auth_headers):
+ mock_token = MagicMock()
+ mock_token.access_token = "test-token-123"
+ with patch("app.services.connection_service.get_provider") as mock_gp:
+ mock_gp.return_value.create_connect_token = AsyncMock(return_value=mock_token)
+ resp = await client.post(
+ "/api/connections/connect-token",
+ json={"provider": "pluggy"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 200
+ assert resp.json()["access_token"] == "test-token-123"
+
+
+async def test_create_connect_token_value_error(client: AsyncClient, auth_headers):
+ with patch("app.services.connection_service.get_provider") as mock_gp:
+ mock_gp.side_effect = ValueError("Unknown provider")
+ resp = await client.post(
+ "/api/connections/connect-token",
+ json={"provider": "invalid"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 400
+
+
+async def test_create_connect_token_server_error(client: AsyncClient, auth_headers):
+ with patch("app.services.connection_service.get_provider") as mock_gp:
+ mock_gp.return_value.create_connect_token = AsyncMock(
+ side_effect=RuntimeError("Provider down")
+ )
+ resp = await client.post(
+ "/api/connections/connect-token",
+ json={"provider": "pluggy"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 500
+
+
+async def test_oauth_callback_success(client: AsyncClient, auth_headers):
+ conn_data = MagicMock()
+ conn_data.external_id = "ext-oauth-1"
+ conn_data.institution_name = "Test Bank"
+ conn_data.credentials = {"token": "abc"}
+ conn_data.accounts = []
+
+ with patch("app.services.connection_service.get_provider") as mock_gp:
+ mock_gp.return_value.handle_oauth_callback = AsyncMock(return_value=conn_data)
+ resp = await client.post(
+ "/api/connections/oauth/callback",
+ json={"code": "auth-code-123", "provider": "pluggy"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 200
+ assert resp.json()["institution_name"] == "Test Bank"
+
+
+async def test_oauth_callback_failure(client: AsyncClient, auth_headers):
+ with patch("app.services.connection_service.get_provider") as mock_gp:
+ mock_gp.return_value.handle_oauth_callback = AsyncMock(
+ side_effect=Exception("OAuth failed")
+ )
+ resp = await client.post(
+ "/api/connections/oauth/callback",
+ json={"code": "bad-code", "provider": "pluggy"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 400
+
+
+async def test_sync_connection_not_found(client: AsyncClient, auth_headers):
+ resp = await client.post(
+ f"/api/connections/{uuid.uuid4()}/sync", headers=auth_headers,
+ )
+ assert resp.status_code == 404
+
+
+async def test_reconnect_token_not_found(client: AsyncClient, auth_headers):
+ resp = await client.post(
+ f"/api/connections/{uuid.uuid4()}/reconnect-token", headers=auth_headers,
+ )
+ assert resp.status_code == 404
+
+
+async def test_reconnect_token_no_item_id(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user: User,
+):
+ conn = BankConnection(
+ id=uuid.uuid4(), user_id=test_user.id, provider="test",
+ external_id="ext-recon-no-item", institution_name="NoItem Bank",
+ credentials={}, status="active",
+ last_sync_at=datetime.now(timezone.utc),
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(conn)
+ await session.commit()
+ resp = await client.post(
+ f"/api/connections/{conn.id}/reconnect-token", headers=auth_headers,
+ )
+ assert resp.status_code == 400
+ assert "item_id" in resp.json()["detail"]
+
+
+async def test_reconnect_token_with_item_id(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user: User,
+):
+ conn = BankConnection(
+ id=uuid.uuid4(), user_id=test_user.id, provider="test",
+ external_id="ext-recon-ok", institution_name="Recon Bank",
+ credentials={"item_id": "item-abc-123"}, status="error",
+ last_sync_at=datetime.now(timezone.utc),
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(conn)
+ await session.commit()
+
+ mock_token = MagicMock()
+ mock_token.access_token = "recon-token"
+ with patch("app.services.connection_service.get_provider") as mock_gp:
+ mock_gp.return_value.create_connect_token = AsyncMock(return_value=mock_token)
+ resp = await client.post(
+ f"/api/connections/{conn.id}/reconnect-token", headers=auth_headers,
+ )
+ assert resp.status_code == 200
+ assert resp.json()["access_token"] == "recon-token"
+
+
+async def test_update_settings_success(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user: User,
+):
+ conn = BankConnection(
+ id=uuid.uuid4(), user_id=test_user.id, provider="test",
+ external_id="ext-settings-1", institution_name="Settings Bank",
+ credentials={}, status="active", settings={"payee_source": "auto"},
+ last_sync_at=datetime.now(timezone.utc),
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(conn)
+ await session.commit()
+ resp = await client.patch(
+ f"/api/connections/{conn.id}/settings",
+ json={"payee_source": "merchant"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 200
+ assert resp.json()["settings"]["payee_source"] == "merchant"
diff --git a/backend/tests/test_currencies_api.py b/backend/tests/test_currencies_api.py
new file mode 100644
index 00000000..f08a6379
--- /dev/null
+++ b/backend/tests/test_currencies_api.py
@@ -0,0 +1,24 @@
+import pytest
+from httpx import AsyncClient
+
+
+async def test_list_currencies(client: AsyncClient):
+ response = await client.get("/api/currencies")
+ assert response.status_code == 200
+ data = response.json()
+ assert isinstance(data, list)
+ assert len(data) > 0
+ for currency in data:
+ assert "code" in currency
+ assert "symbol" in currency
+ assert "name" in currency
+ assert "flag" in currency
+
+
+async def test_currencies_include_brl_and_usd(client: AsyncClient):
+ response = await client.get("/api/currencies")
+ codes = [c["code"] for c in response.json()]
+ assert "BRL" in codes
+ assert "USD" in codes
diff --git a/backend/tests/test_dashboard_service.py b/backend/tests/test_dashboard_service.py
index 791a0d09..302ddb5d 100644
--- a/backend/tests/test_dashboard_service.py
+++ b/backend/tests/test_dashboard_service.py
@@ -1,9 +1,3 @@
-"""Service-level tests for dashboard_service.
-
-Tests: _month_range, get_summary, get_spending_by_category,
-get_projected_transactions, _account_balance_at, _total_balance_by_currency,
-_get_open_accounts.
-"""
import uuid
from datetime import date, timedelta
from decimal import Decimal
@@ -15,11 +9,15 @@ from app.models.account import Account
from app.models.category import Category
from app.models.recurring_transaction import RecurringTransaction
from app.models.transaction import Transaction
+from app.models.bank_connection import BankConnection
from app.services.dashboard_service import (
+ _balance_at,
+ _get_recurring_projections,
_month_range,
_get_open_accounts,
_account_balance_at,
_total_balance_by_currency,
+ get_balance_history,
get_summary,
get_spending_by_category,
get_projected_transactions,
@@ -449,3 +447,316 @@ async def test_get_projected_transactions_no_category(session: AsyncSession, tes
proj = projections[0]
assert proj.category_name is None
assert proj.category_id is None
+
+
+async def test_account_balance_manual_future_date(session, test_user):
+ acct = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="FutDate",
+ type="checking", balance=Decimal("0"), currency="BRL",
+ )
+ session.add(acct)
+ await session.commit()
+ await session.refresh(acct)
+
+ today = date.today()
+ from datetime import datetime, timezone
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, account_id=acct.id,
+ description="Today only", amount=Decimal("500"), date=today,
+ type="credit", source="manual", currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ yesterday = today - timedelta(days=1)
+ bal = await _account_balance_at(session, acct, yesterday)
+ assert bal == 0.0
+
+
+async def test_account_balance_bank_credit_card(session, test_user):
+ from datetime import datetime, timezone
+ conn = BankConnection(
+ id=uuid.uuid4(), user_id=test_user.id, provider="test",
+ external_id="ext-cc-ds", institution_name="CC Bank",
+ credentials={}, status="active",
+ last_sync_at=datetime.now(timezone.utc),
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(conn)
+ await session.flush()
+ cc = Account(
+ id=uuid.uuid4(), user_id=test_user.id, connection_id=conn.id,
+ name="CC", type="credit_card", balance=Decimal("1500"), currency="BRL",
+ )
+ session.add(cc)
+ await session.commit()
+ await session.refresh(cc)
+
+ bal = await _account_balance_at(session, cc, date.today())
+ assert bal == -1500.0
+
+
+async def test_get_open_accounts_excludes_closed(session, test_user):
+ closed = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="Closed",
+ type="checking", balance=Decimal("0"), currency="BRL", is_closed=True,
+ )
+ session.add(closed)
+ await session.commit()
+ accounts = await _get_open_accounts(session, test_user.id)
+ assert all(a.id != closed.id for a in accounts)
+
+
+async def test_balance_at_single_currency(session, test_user):
+ acct = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="BalAt",
+ type="checking", balance=Decimal("0"), currency="BRL",
+ )
+ session.add(acct)
+ await session.commit()
+ from datetime import datetime, timezone
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, account_id=acct.id,
+ description="Income", amount=Decimal("3000"), date=date.today(),
+ type="credit", source="manual", currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ bal = await _balance_at(session, test_user.id, date.today())
+ assert bal >= 3000.0
+
+
+async def test_get_summary_past_month(session, test_user):
+ past = date.today().replace(day=1) - timedelta(days=30)
+ past_month = past.replace(day=1)
+ summary = await get_summary(session, test_user.id, month=past_month)
+ assert summary is not None
+
+
+async def test_spending_by_category_with_categorized(session, test_user, test_categories):
+ acct = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="SpendCat",
+ type="checking", balance=Decimal("0"), currency="BRL",
+ )
+ session.add(acct)
+ await session.commit()
+ from datetime import datetime, timezone
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, account_id=acct.id,
+ category_id=test_categories[0].id,
+ description="Food", amount=Decimal("200"), date=date.today(),
+ type="debit", source="manual", currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ result = await get_spending_by_category(session, test_user.id)
+ cat_names = [s.category_name for s in result]
+ assert test_categories[0].name in cat_names
+
+
+async def test_get_recurring_projections(session, test_user):
+ today = date.today()
+ month_start = today.replace(day=1)
+ if today.month == 12:
+ month_end = date(today.year + 1, 1, 1)
+ else:
+ month_end = date(today.year, today.month + 1, 1)
+
+ rec = RecurringTransaction(
+ id=uuid.uuid4(), user_id=test_user.id,
+ description="Rent", amount=Decimal("2000"), type="debit",
+ frequency="monthly", start_date=month_start,
+ next_occurrence=month_start, currency="BRL",
+ )
+ session.add(rec)
+ await session.commit()
+
+ projections = await _get_recurring_projections(session, test_user.id, month_start, month_end)
+ assert len(projections) >= 1
+ assert projections[0]["amount"] == 2000.0
+
+
+async def test_balance_history_basic(session, test_user):
+ acct = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="BH",
+ type="checking", balance=Decimal("0"), currency="BRL",
+ )
+ session.add(acct)
+ await session.commit()
+ from datetime import datetime, timezone
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, account_id=acct.id,
+ description="BH txn", amount=Decimal("1000"), date=date.today(),
+ type="credit", source="manual", currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ history = await get_balance_history(session, test_user.id)
+ assert len(history.current) > 0
+ assert len(history.previous) > 0
+
+
+async def test_balance_history_past_month(session, test_user):
+ past = date.today().replace(day=1) - timedelta(days=15)
+ past_month = past.replace(day=1)
+ history = await get_balance_history(session, test_user.id, month=past_month)
+ assert len(history.current) > 0
+
+
+# ---------------------------------------------------------------------------
+# get_projected_transactions
+# ---------------------------------------------------------------------------
+
+
+async def test_get_projected_transactions_empty(session, test_user):
+ result = await get_projected_transactions(session, test_user.id)
+ assert result == []
+
+
+async def test_get_projected_transactions_with_recurring(session, test_user):
+ today = date.today()
+ month_start = today.replace(day=1)
+ cat = Category(
+ id=uuid.uuid4(), user_id=test_user.id,
+ name="Rent", icon="home", color="#000",
+ )
+ session.add(cat)
+ rec = RecurringTransaction(
+ id=uuid.uuid4(), user_id=test_user.id,
+ description="Monthly Rent", amount=Decimal("2500"),
+ type="debit", frequency="monthly", currency="BRL",
+ start_date=month_start, next_occurrence=month_start,
+ category_id=cat.id,
+ )
+ session.add(rec)
+ await session.commit()
+
+ result = await get_projected_transactions(session, test_user.id, month=month_start)
+ assert len(result) >= 1
+ assert result[0].description == "Monthly Rent"
+ assert result[0].category_name == "Rent"
+ assert result[0].amount == 2500.0
+
+
+# ---------------------------------------------------------------------------
+# get_summary with recurring projections
+# ---------------------------------------------------------------------------
+
+
+async def test_get_summary_includes_recurring_projections(session, test_user):
+ today = date.today()
+ month_start = today.replace(day=1)
+
+ acct = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="Summary Acct",
+ type="checking", balance=Decimal("5000"), currency="BRL",
+ )
+ session.add(acct)
+ rec = RecurringTransaction(
+ id=uuid.uuid4(), user_id=test_user.id,
+ description="Salary", amount=Decimal("10000"),
+ type="credit", frequency="monthly", currency="BRL",
+ start_date=month_start, next_occurrence=month_start,
+ )
+ session.add(rec)
+ await session.commit()
+
+ summary = await get_summary(session, test_user.id, month=month_start)
+ assert summary.monthly_income >= 10000.0
+
+
+# ---------------------------------------------------------------------------
+# get_spending_by_category with recurring projections
+# ---------------------------------------------------------------------------
+
+
+async def test_spending_by_category_includes_recurring(session, test_user):
+ today = date.today()
+ month_start = today.replace(day=1)
+
+ cat = Category(
+ id=uuid.uuid4(), user_id=test_user.id,
+ name="Transport", icon="car", color="#3B82F6",
+ )
+ session.add(cat)
+
+ acct = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="Spend Acct",
+ type="checking", balance=Decimal("0"), currency="BRL",
+ )
+ session.add(acct)
+
+ rec = RecurringTransaction(
+ id=uuid.uuid4(), user_id=test_user.id,
+ description="Gas", amount=Decimal("200"),
+ type="debit", frequency="monthly", currency="BRL",
+ start_date=month_start, next_occurrence=month_start,
+ category_id=cat.id,
+ )
+ session.add(rec)
+ await session.commit()
+
+ spending = await get_spending_by_category(session, test_user.id, month=month_start)
+ assert len(spending) >= 1
+ transport = next((s for s in spending if s.category_name == "Transport"), None)
+ assert transport is not None
+ assert transport.total >= 200.0
+
+
+# ---------------------------------------------------------------------------
+# _balance_at multi-currency
+# ---------------------------------------------------------------------------
+
+
+async def test_balance_at_multi_currency(session, test_user):
+ acct_brl = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="BRL Acct",
+ type="checking", balance=Decimal("0"), currency="BRL",
+ )
+ acct_usd = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="USD Acct",
+ type="checking", balance=Decimal("0"), currency="USD",
+ )
+ session.add_all([acct_brl, acct_usd])
+
+ from datetime import datetime, timezone
+ for acct, amount in [(acct_brl, Decimal("1000")), (acct_usd, Decimal("200"))]:
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, account_id=acct.id,
+ description="Deposit", amount=amount, date=date.today(),
+ type="credit", source="manual", currency=acct.currency,
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ total = await _balance_at(session, test_user.id, date.today())
+ assert total > 0
+
+
+# ---------------------------------------------------------------------------
+# _total_balance_by_currency
+# ---------------------------------------------------------------------------
+
+
diff --git a/backend/tests/test_export_api.py b/backend/tests/test_export_api.py
index f0ea4488..e6d02630 100644
--- a/backend/tests/test_export_api.py
+++ b/backend/tests/test_export_api.py
@@ -1,14 +1,21 @@
import io
import json
+import uuid
import zipfile
+from datetime import date
+from decimal import Decimal
import pytest
from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
from app.models.account import Account
+from app.models.asset import Asset
+from app.models.asset_value import AssetValue
from app.models.category import Category
from app.models.rule import Rule
from app.models.transaction import Transaction
+from app.models.user import User
@pytest.mark.asyncio
@@ -93,3 +100,45 @@ async def test_backup_with_data(
assert isinstance(transactions[0]["date"], str)
# Verify decimals are serialized as strings
assert isinstance(transactions[0]["amount"], str)
+
+
+async def test_backup_with_assets(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user: User,
+):
+ asset = Asset(
+ id=uuid.uuid4(), user_id=test_user.id, name="Export Asset",
+ type="other", currency="BRL", purchase_price=Decimal("1000"),
+ )
+ session.add(asset)
+ await session.flush()
+ av = AssetValue(
+ id=uuid.uuid4(), asset_id=asset.id,
+ amount=Decimal("1200"), date=date.today(),
+ )
+ session.add(av)
+ await session.commit()
+
+ resp = await client.get("/api/export/backup", headers=auth_headers)
+ assert resp.status_code == 200
+ buf = io.BytesIO(resp.content)
+ with zipfile.ZipFile(buf) as zf:
+ assets = json.loads(zf.read("assets.json"))
+ asset_values = json.loads(zf.read("asset_values.json"))
+ assert len(assets) >= 1
+ assert len(asset_values) >= 1
+
+
+async def test_backup_metadata_structure(client: AsyncClient, auth_headers):
+ resp = await client.get("/api/export/backup", headers=auth_headers)
+ assert resp.status_code == 200
+ assert "application/zip" in resp.headers.get("content-type", "")
+ buf = io.BytesIO(resp.content)
+ with zipfile.ZipFile(buf) as zf:
+ names = zf.namelist()
+ assert "metadata.json" in names
+ meta = json.loads(zf.read("metadata.json"))
+ assert "export_date" in meta
+ assert meta["format_version"] == "1.0"
+ assert "entity_counts" in meta
diff --git a/backend/tests/test_local_storage.py b/backend/tests/test_local_storage.py
new file mode 100644
index 00000000..db4156b8
--- /dev/null
+++ b/backend/tests/test_local_storage.py
@@ -0,0 +1,118 @@
+import tempfile
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from app.providers.local_storage import LocalStorageProvider
+from app.providers.storage import StoredFile
+
+
+# ---------------------------------------------------------------------------
+# StoredFile dataclass
+# ---------------------------------------------------------------------------
+
+
+def test_stored_file_creation():
+ sf = StoredFile(storage_key="user/file.pdf", size=1024, content_type="application/pdf")
+ assert sf.storage_key == "user/file.pdf"
+ assert sf.size == 1024
+ assert sf.content_type == "application/pdf"
+
+
+# ---------------------------------------------------------------------------
+# StorageProvider interface
+# ---------------------------------------------------------------------------
+
+
+def test_storage_provider_get_url_default():
+ """Base get_url returns None."""
+ # Can't instantiate ABC directly, use LocalStorageProvider
+ provider = LocalStorageProvider()
+ assert provider.get_url("any/key") is None
+
+
+def test_storage_provider_name():
+ provider = LocalStorageProvider()
+ assert provider.name == "local"
+
+
+# ---------------------------------------------------------------------------
+# LocalStorageProvider tests
+# ---------------------------------------------------------------------------
+
+
+def storage_dir():
+ with tempfile.TemporaryDirectory() as tmpdir:
+ yield tmpdir
+
+
+def local_storage(storage_dir):
+ with patch("app.providers.local_storage.get_settings") as mock_settings:
+ settings = mock_settings.return_value
+ settings.storage_local_path = storage_dir
+ provider = LocalStorageProvider()
+ yield provider
+
+
+async def test_upload_creates_file(local_storage, storage_dir):
+ result = await local_storage.upload("test/file.txt", b"hello world", "text/plain")
+ assert result.storage_key == "test/file.txt"
+ assert result.size == 11
+ assert result.content_type == "text/plain"
+ # File should exist on disk
+ assert (Path(storage_dir) / "test" / "file.txt").exists()
+
+
+async def test_upload_creates_parent_dirs(local_storage, storage_dir):
+ await local_storage.upload("a/b/c/deep.txt", b"data", "text/plain")
+ assert (Path(storage_dir) / "a" / "b" / "c" / "deep.txt").exists()
+
+
+async def test_download_reads_file(local_storage, storage_dir):
+ await local_storage.upload("dl/test.txt", b"content", "text/plain")
+ data = await local_storage.download("dl/test.txt")
+ assert data == b"content"
+
+
+async def test_download_file_not_found(local_storage):
+ with pytest.raises(FileNotFoundError):
+ await local_storage.download("nonexistent/file.txt")
+
+
+async def test_delete_removes_file(local_storage, storage_dir):
+ await local_storage.upload("del/test.txt", b"data", "text/plain")
+ assert (Path(storage_dir) / "del" / "test.txt").exists()
+ await local_storage.delete("del/test.txt")
+ assert not (Path(storage_dir) / "del" / "test.txt").exists()
+
+
+async def test_delete_nonexistent_no_error(local_storage):
+ """Deleting a file that doesn't exist should not raise."""
+ await local_storage.delete("ghost/file.txt")
+
+
+async def test_path_traversal_blocked(local_storage):
+ with pytest.raises(ValueError, match="Invalid storage key"):
+ await local_storage.upload("../../etc/passwd", b"evil", "text/plain")
+
+
+async def test_path_traversal_download_blocked(local_storage):
+ with pytest.raises(ValueError, match="Invalid storage key"):
+ await local_storage.download("../../etc/passwd")
+
+
+async def test_path_traversal_delete_blocked(local_storage):
+ with pytest.raises(ValueError, match="Invalid storage key"):
+ await local_storage.delete("../../etc/passwd")
diff --git a/backend/tests/test_providers.py b/backend/tests/test_providers.py
new file mode 100644
index 00000000..1f04fde4
--- /dev/null
+++ b/backend/tests/test_providers.py
@@ -0,0 +1,98 @@
+import pytest
+from unittest.mock import patch
+
+from app.providers import (
+ register_provider,
+ get_provider,
+ list_providers,
+ all_known_providers,
+ get_storage_provider,
+ _PROVIDERS,
+)
+from app.providers.base import BankProvider
+
+
+class FakeProvider(BankProvider):
+ @property
+ def name(self) -> str:
+ return "fake"
+
+ @property
+ def flow_type(self) -> str:
+ return "widget"
+
+ def get_oauth_url(self, redirect_uri: str, state: str) -> str:
+ return "https://fake.example.com"
+
+ async def handle_oauth_callback(self, code: str):
+ pass
+
+ async def get_accounts(self, credentials: dict):
+ return []
+
+ async def get_transactions(self, credentials, account_id, since, **kw):
+ return []
+
+ async def refresh_credentials(self, credentials: dict) -> dict:
+ return credentials
+
+
[email protected](autouse=True)
+def _clean_registry():
+ """Remove the 'fake' provider after each test."""
+ yield
+ _PROVIDERS.pop("fake", None)
+
+
+def test_register_and_get_provider():
+ register_provider("fake", FakeProvider)
+ provider = get_provider("fake")
+ assert provider.name == "fake"
+ assert provider.flow_type == "widget"
+
+
+def test_get_provider_unknown():
+ with pytest.raises(ValueError, match="Unknown provider"):
+ get_provider("nonexistent_provider")
+
+
+def test_list_providers_includes_registered():
+ register_provider("fake", FakeProvider)
+ result = list_providers()
+ names = [p["name"] for p in result]
+ assert "fake" in names
+
+
+def test_all_known_providers():
+ result = all_known_providers()
+ assert isinstance(result, list)
+ for p in result:
+ assert "name" in p
+ assert "configured" in p
+
+
+def test_get_storage_provider_local():
+ import app.providers as providers_mod
+ original = providers_mod._storage_provider
+ providers_mod._storage_provider = None
+ try:
+ with patch("app.core.config.get_settings") as mock_settings:
+ mock_settings.return_value.storage_provider = "local"
+ mock_settings.return_value.storage_local_path = "/tmp/test-storage"
+ provider = get_storage_provider()
+ assert provider.name == "local"
+ finally:
+ providers_mod._storage_provider = original
+
+
+def test_get_storage_provider_unsupported():
+ import app.providers as providers_mod
+ original = providers_mod._storage_provider
+ providers_mod._storage_provider = None
+ try:
+ with patch("app.core.config.get_settings") as mock_settings:
+ mock_settings.return_value.storage_provider = "s3"
+ with pytest.raises(NotImplementedError, match="s3"):
+ get_storage_provider()
+ finally:
+ providers_mod._storage_provider = original
diff --git a/backend/tests/test_report_service.py b/backend/tests/test_report_service.py
index 11f136c8..b0d328e3 100644
--- a/backend/tests/test_report_service.py
+++ b/backend/tests/test_report_service.py
@@ -1,17 +1,22 @@
-"""Tests for report service and API endpoints."""
import uuid
-from datetime import date, timedelta
+from datetime import date, datetime, timedelta, timezone
from decimal import Decimal
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.account import Account
+from app.models.asset import Asset
+from app.models.asset_value import AssetValue
+from app.models.bank_connection import BankConnection
from app.models.transaction import Transaction
+from app.models.user import User
from app.schemas.report import CategoryTrendItem, ReportDataPoint, ReportResponse
from app.services.report_service import (
+ _asset_value_at,
_date_points,
_format_date_label,
+ _net_worth_at,
get_net_worth_report,
)
@@ -534,3 +539,233 @@ async def test_income_expenses_has_category_trend(client, auth_headers, test_tra
for point in item["series"]:
assert "date" in point
assert "value" in point
+
+
+# ---------------------------------------------------------------------------
+# _asset_value_at
+# ---------------------------------------------------------------------------
+
+
+async def _make_manual_account(session, user_id, name, currency="BRL", acct_type="checking"):
+ acct = Account(
+ id=uuid.uuid4(), user_id=user_id, name=name,
+ type=acct_type, balance=Decimal("0"), currency=currency,
+ )
+ session.add(acct)
+ await session.commit()
+ await session.refresh(acct)
+ return acct
+
+
+async def _add_txn(session, user_id, account_id, amount, txn_type, txn_date, source="manual"):
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=user_id, account_id=account_id,
+ description=f"Test {txn_type}", amount=Decimal(str(amount)),
+ date=txn_date, type=txn_type, source=source, currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+ return txn
+
+
+async def test_asset_value_at_with_entries(session: AsyncSession, test_user: User):
+ asset = Asset(
+ id=uuid.uuid4(), user_id=test_user.id, name="House",
+ type="real_estate", currency="BRL",
+ )
+ session.add(asset)
+ await session.flush()
+
+ v1 = AssetValue(
+ id=uuid.uuid4(), asset_id=asset.id,
+ amount=Decimal("100000"), date=date.today() - timedelta(days=30),
+ )
+ v2 = AssetValue(
+ id=uuid.uuid4(), asset_id=asset.id,
+ amount=Decimal("110000"), date=date.today(),
+ )
+ session.add_all([v1, v2])
+ await session.commit()
+
+ total = await _asset_value_at(session, test_user.id, date.today(), "BRL")
+ assert total == 110000.0
+
+
+async def test_asset_value_at_fallback_purchase_price(session: AsyncSession, test_user: User):
+ asset = Asset(
+ id=uuid.uuid4(), user_id=test_user.id, name="Car",
+ type="vehicle", currency="BRL",
+ purchase_price=Decimal("50000"),
+ purchase_date=date.today() - timedelta(days=60),
+ )
+ session.add(asset)
+ await session.commit()
+
+ total = await _asset_value_at(session, test_user.id, date.today(), "BRL")
+ assert total == 50000.0
+
+
+async def test_asset_value_at_excludes_archived(session: AsyncSession, test_user: User):
+ asset = Asset(
+ id=uuid.uuid4(), user_id=test_user.id, name="Sold Car",
+ type="vehicle", currency="BRL",
+ purchase_price=Decimal("30000"), is_archived=True,
+ )
+ session.add(asset)
+ await session.commit()
+
+ total = await _asset_value_at(session, test_user.id, date.today(), "BRL")
+ assert total == 0.0
+
+
+async def test_asset_value_at_excludes_sold(session: AsyncSession, test_user: User):
+ asset = Asset(
+ id=uuid.uuid4(), user_id=test_user.id, name="Sold Asset",
+ type="vehicle", currency="BRL",
+ purchase_price=Decimal("20000"),
+ sell_date=date.today() - timedelta(days=10),
+ )
+ session.add(asset)
+ await session.commit()
+
+ total = await _asset_value_at(session, test_user.id, date.today(), "BRL")
+ assert total == 0.0
+
+
+async def test_asset_value_at_purchase_date_after_cutoff(session: AsyncSession, test_user: User):
+ asset = Asset(
+ id=uuid.uuid4(), user_id=test_user.id, name="Future Asset",
+ type="other", currency="BRL",
+ purchase_price=Decimal("5000"),
+ purchase_date=date.today() + timedelta(days=30),
+ )
+ session.add(asset)
+ await session.commit()
+
+ total = await _asset_value_at(session, test_user.id, date.today(), "BRL")
+ assert total == 0.0
+
+
+# ---------------------------------------------------------------------------
+# _net_worth_at
+# ---------------------------------------------------------------------------
+
+
+async def test_net_worth_with_credit_card(session: AsyncSession, test_user: User):
+ checking = await _make_manual_account(session, test_user.id, "NW Check")
+ await _add_txn(session, test_user.id, checking.id, 5000, "credit", date.today())
+
+ conn = BankConnection(
+ id=uuid.uuid4(), user_id=test_user.id, provider="test",
+ external_id="ext-cc-nw", institution_name="CC",
+ credentials={}, status="active",
+ last_sync_at=datetime.now(timezone.utc),
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(conn)
+ await session.flush()
+ cc = Account(
+ id=uuid.uuid4(), user_id=test_user.id, connection_id=conn.id,
+ name="CC", type="credit_card", balance=Decimal("1000"), currency="BRL",
+ )
+ session.add(cc)
+ await session.commit()
+
+ dp = await _net_worth_at(session, test_user.id, date.today(), "BRL")
+ assert dp.breakdowns["accounts"] == 5000.0
+ assert dp.breakdowns["liabilities"] == 1000.0
+ assert dp.value == 4000.0
+
+
+async def test_net_worth_with_assets(session: AsyncSession, test_user: User):
+ checking = await _make_manual_account(session, test_user.id, "NW Assets Check")
+ await _add_txn(session, test_user.id, checking.id, 3000, "credit", date.today())
+
+ asset = Asset(
+ id=uuid.uuid4(), user_id=test_user.id, name="Apartment",
+ type="real_estate", currency="BRL",
+ purchase_price=Decimal("200000"),
+ purchase_date=date.today() - timedelta(days=30),
+ )
+ session.add(asset)
+ await session.commit()
+
+ dp = await _net_worth_at(session, test_user.id, date.today(), "BRL")
+ assert dp.breakdowns["accounts"] == 3000.0
+ assert dp.breakdowns["assets"] == 200000.0
+ assert dp.value == 203000.0
+
+
+async def test_net_worth_negative_manual_balance(session: AsyncSession, test_user: User):
+ acct = await _make_manual_account(session, test_user.id, "NW Negative")
+ await _add_txn(session, test_user.id, acct.id, 1000, "debit", date.today())
+
+ dp = await _net_worth_at(session, test_user.id, date.today(), "BRL")
+ assert dp.breakdowns["accounts"] == -1000.0
+
+
+# ---------------------------------------------------------------------------
+# get_net_worth_report — composition and intervals
+# ---------------------------------------------------------------------------
+
+
+async def test_net_worth_composition_includes_accounts(session: AsyncSession, test_user: User):
+ acct = await _make_manual_account(session, test_user.id, "Comp Acct")
+ await _add_txn(session, test_user.id, acct.id, 10000, "credit", date.today())
+
+ report = await get_net_worth_report(session, test_user.id, months=1, interval="monthly")
+ comp_labels = [c.label for c in report.composition]
+ assert "Comp Acct" in comp_labels
+
+
+async def test_net_worth_composition_includes_assets(session: AsyncSession, test_user: User):
+ asset = Asset(
+ id=uuid.uuid4(), user_id=test_user.id, name="Comp Asset",
+ type="investment", currency="BRL",
+ purchase_price=Decimal("5000"),
+ purchase_date=date.today() - timedelta(days=5),
+ )
+ session.add(asset)
+ await session.commit()
+
+ report = await get_net_worth_report(session, test_user.id, months=1, interval="monthly")
+ comp_labels = [c.label for c in report.composition]
+ assert "Comp Asset" in comp_labels
+
+
+async def test_net_worth_weekly_interval(session: AsyncSession, test_user: User):
+ acct = await _make_manual_account(session, test_user.id, "Weekly Test")
+ await _add_txn(session, test_user.id, acct.id, 1000, "credit", date.today())
+
+ report = await get_net_worth_report(session, test_user.id, months=2, interval="weekly")
+ assert report.meta.interval == "weekly"
+ assert len(report.trend) > 1
+
+
+async def test_net_worth_daily_interval(session: AsyncSession, test_user: User):
+ acct = await _make_manual_account(session, test_user.id, "Daily Test")
+ await _add_txn(session, test_user.id, acct.id, 500, "credit", date.today())
+
+ report = await get_net_worth_report(session, test_user.id, months=1, interval="daily")
+ assert report.meta.interval == "daily"
+ assert len(report.trend) > 10
+
+
+async def test_net_worth_change_percent_zero_previous(session: AsyncSession, test_user: User):
+ report = await get_net_worth_report(session, test_user.id, months=1, interval="monthly")
+ if report.summary.primary_value == 0:
+ assert report.summary.change_percent is None
diff --git a/backend/tests/test_transaction_service.py b/backend/tests/test_transaction_service.py
index 91cfe01a..fcb8e2d0 100644
--- a/backend/tests/test_transaction_service.py
+++ b/backend/tests/test_transaction_service.py
@@ -9,10 +9,12 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.models.account import Account
from app.models.rule import Rule
from app.models.transaction import Transaction
-from app.schemas.transaction import TransactionCreate, TransactionUpdate
+from app.schemas.transaction import TransactionCreate, TransactionUpdate, TransferCreate
from app.services.transaction_service import (
+ _apply_fx_override,
bulk_update_category,
create_transaction,
+ create_transfer,
delete_transaction,
get_transaction,
get_transactions,
@@ -496,3 +498,304 @@ async def test_bulk_update_category_clear(
await session.refresh(txn)
assert txn.category_id is None
+
+
+# ---------------------------------------------------------------------------
+# _apply_fx_override
+# ---------------------------------------------------------------------------
+
+
+def test_apply_fx_override_both():
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=uuid.uuid4(), account_id=uuid.uuid4(),
+ description="T", amount=Decimal("100"), date=date.today(),
+ type="debit", source="manual",
+ )
+ _apply_fx_override(txn, 100, amount_primary=500.0, fx_rate_used=5.0)
+ assert txn.amount_primary == Decimal("500.0")
+ assert txn.fx_rate_used == Decimal("5.0")
+
+
+def test_apply_fx_override_only_amount_primary():
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=uuid.uuid4(), account_id=uuid.uuid4(),
+ description="T", amount=Decimal("100"), date=date.today(),
+ type="debit", source="manual",
+ )
+ _apply_fx_override(txn, 100, amount_primary=250.0)
+ assert txn.amount_primary == Decimal("250.0")
+ assert txn.fx_rate_used == Decimal("2.5")
+
+
+def test_apply_fx_override_only_fx_rate():
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=uuid.uuid4(), account_id=uuid.uuid4(),
+ description="T", amount=Decimal("100"), date=date.today(),
+ type="debit", source="manual",
+ )
+ _apply_fx_override(txn, 100, fx_rate_used=3.0)
+ assert txn.fx_rate_used == Decimal("3.0")
+ assert txn.amount_primary == Decimal("300.00")
+
+
+def test_apply_fx_override_zero_amount():
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=uuid.uuid4(), account_id=uuid.uuid4(),
+ description="T", amount=Decimal("0"), date=date.today(),
+ type="debit", source="manual",
+ )
+ _apply_fx_override(txn, 0, amount_primary=0.0)
+ assert txn.amount_primary == Decimal("0.0")
+ assert txn.fx_rate_used == Decimal("1")
+
+
+# ---------------------------------------------------------------------------
+# create_transaction — FX and category
+# ---------------------------------------------------------------------------
+
+
+async def test_create_transaction_with_fx_override(session: AsyncSession, test_user, txn_account):
+ data = TransactionCreate(
+ account_id=txn_account.id, description="USD Purchase",
+ amount=Decimal("100"), date=date.today(), type="debit",
+ amount_primary=Decimal("500"), fx_rate_used=Decimal("5"),
+ )
+ txn = await create_transaction(session, test_user.id, data)
+ assert txn.amount_primary == Decimal("500")
+ assert txn.fx_rate_used == Decimal("5")
+
+
+# ---------------------------------------------------------------------------
+# create_transfer
+# ---------------------------------------------------------------------------
+
+
+@pytest_asyncio.fixture
+async def txn_account_usd(session: AsyncSession, test_user) -> Account:
+ acct = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="USD Acct",
+ type="checking", balance=Decimal("5000"), currency="USD",
+ )
+ session.add(acct)
+ await session.commit()
+ await session.refresh(acct)
+ return acct
+
+
+async def test_create_transfer_same_currency(session: AsyncSession, test_user, txn_account):
+ acct2 = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="Savings",
+ type="savings", balance=Decimal("0"), currency="BRL",
+ )
+ session.add(acct2)
+ await session.commit()
+
+ data = TransferCreate(
+ from_account_id=txn_account.id, to_account_id=acct2.id,
+ description="Transfer", amount=Decimal("1000"), date=date.today(),
+ )
+ debit_tx, credit_tx = await create_transfer(session, test_user.id, data)
+ assert debit_tx.type == "debit"
+ assert credit_tx.type == "credit"
+ assert debit_tx.transfer_pair_id == credit_tx.transfer_pair_id
+ assert debit_tx.amount == credit_tx.amount
+
+
+async def test_create_transfer_same_account(session: AsyncSession, test_user, txn_account):
+ data = TransferCreate(
+ from_account_id=txn_account.id, to_account_id=txn_account.id,
+ description="Self", amount=Decimal("100"), date=date.today(),
+ )
+ with pytest.raises(ValueError, match="same account"):
+ await create_transfer(session, test_user.id, data)
+
+
+async def test_create_transfer_cross_currency(session: AsyncSession, test_user, txn_account, txn_account_usd):
+ data = TransferCreate(
+ from_account_id=txn_account.id, to_account_id=txn_account_usd.id,
+ description="Cross-currency", amount=Decimal("500"), date=date.today(),
+ fx_rate=Decimal("0.2"),
+ )
+ debit_tx, credit_tx = await create_transfer(session, test_user.id, data)
+ assert debit_tx.currency == "BRL"
+ assert credit_tx.currency == "USD"
+ assert credit_tx.amount == Decimal("100.00")
+
+
+async def test_create_transfer_cross_currency_auto_fx(session: AsyncSession, test_user, txn_account, txn_account_usd):
+ data = TransferCreate(
+ from_account_id=txn_account.id, to_account_id=txn_account_usd.id,
+ description="Auto FX", amount=Decimal("500"), date=date.today(),
+ )
+ debit_tx, credit_tx = await create_transfer(session, test_user.id, data)
+ assert debit_tx.type == "debit"
+ assert credit_tx.type == "credit"
+
+
+async def test_create_transfer_invalid_from_account(session: AsyncSession, test_user, txn_account):
+ data = TransferCreate(
+ from_account_id=uuid.uuid4(), to_account_id=txn_account.id,
+ description="Bad from", amount=Decimal("100"), date=date.today(),
+ )
+ with pytest.raises(ValueError, match="Source account not found"):
+ await create_transfer(session, test_user.id, data)
+
+
+async def test_create_transfer_invalid_to_account(session: AsyncSession, test_user, txn_account):
+ data = TransferCreate(
+ from_account_id=txn_account.id, to_account_id=uuid.uuid4(),
+ description="Bad to", amount=Decimal("100"), date=date.today(),
+ )
+ with pytest.raises(ValueError, match="Destination account not found"):
+ await create_transfer(session, test_user.id, data)
+
+
+# ---------------------------------------------------------------------------
+# get_transactions — additional filters
+# ---------------------------------------------------------------------------
+
+
+async def test_get_transactions_uncategorized(session: AsyncSession, test_user, txn_account, test_categories):
+ await create_transaction(session, test_user.id, TransactionCreate(
+ account_id=txn_account.id, description="Uncategorized",
+ amount=Decimal("50"), date=date.today(), type="debit",
+ ))
+ await create_transaction(session, test_user.id, TransactionCreate(
+ account_id=txn_account.id, description="Categorized",
+ amount=Decimal("50"), date=date.today(), type="debit",
+ category_id=test_categories[0].id,
+ ))
+ txns, _ = await get_transactions(session, test_user.id, uncategorized=True)
+ descs = [t.description for t in txns]
+ assert "Uncategorized" in descs
+ assert "Categorized" not in descs
+
+
+async def test_get_transactions_date_filter(session: AsyncSession, test_user, txn_account):
+ from datetime import timedelta
+ today = date.today()
+ yesterday = today - timedelta(days=1)
+ await create_transaction(session, test_user.id, TransactionCreate(
+ account_id=txn_account.id, description="Today",
+ amount=Decimal("10"), date=today, type="debit",
+ ))
+ await create_transaction(session, test_user.id, TransactionCreate(
+ account_id=txn_account.id, description="Yesterday",
+ amount=Decimal("10"), date=yesterday, type="debit",
+ ))
+ txns, _ = await get_transactions(session, test_user.id, from_date=today, to_date=today)
+ descs = [t.description for t in txns]
+ assert "Today" in descs
+ assert "Yesterday" not in descs
+
+
+async def test_get_transactions_exclude_transfers(session: AsyncSession, test_user, txn_account):
+ acct2 = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="Sav",
+ type="savings", balance=Decimal("0"), currency="BRL",
+ )
+ session.add(acct2)
+ await session.commit()
+
+ await create_transfer(session, test_user.id, TransferCreate(
+ from_account_id=txn_account.id, to_account_id=acct2.id,
+ description="Xfer", amount=Decimal("100"), date=date.today(),
+ ))
+ await create_transaction(session, test_user.id, TransactionCreate(
+ account_id=txn_account.id, description="Regular",
+ amount=Decimal("50"), date=date.today(), type="debit",
+ ))
+ txns, _ = await get_transactions(session, test_user.id, exclude_transfers=True)
+ descs = [t.description for t in txns]
+ assert "Regular" in descs
+
+
+async def test_get_transactions_skip_pagination(session: AsyncSession, test_user, txn_account):
+ for i in range(5):
+ await create_transaction(session, test_user.id, TransactionCreate(
+ account_id=txn_account.id, description=f"Txn{i}",
+ amount=Decimal("10"), date=date.today(), type="debit",
+ ))
+ txns, total = await get_transactions(session, test_user.id, skip_pagination=True, limit=2)
+ assert len(txns) == total
+
+
+# ---------------------------------------------------------------------------
+# update_transaction — FX and cascade
+# ---------------------------------------------------------------------------
+
+
+async def test_update_transaction_fx_override(session: AsyncSession, test_user, txn_account):
+ txn = await create_transaction(session, test_user.id, TransactionCreate(
+ account_id=txn_account.id, description="FX Test",
+ amount=Decimal("100"), date=date.today(), type="debit",
+ ))
+ data = TransactionUpdate(amount_primary=Decimal("500"), fx_rate_used=Decimal("5"))
+ updated = await update_transaction(session, txn.id, test_user.id, data)
+ assert updated.amount_primary == Decimal("500")
+
+
+async def test_update_transaction_restamp_on_amount_change(session: AsyncSession, test_user, txn_account):
+ txn = await create_transaction(session, test_user.id, TransactionCreate(
+ account_id=txn_account.id, description="Restamp",
+ amount=Decimal("100"), date=date.today(), type="debit",
+ ))
+ data = TransactionUpdate(amount=Decimal("200"))
+ updated = await update_transaction(session, txn.id, test_user.id, data)
+ assert updated.amount == Decimal("200")
+
+
+async def test_update_transfer_cascades(session: AsyncSession, test_user, txn_account):
+ acct2 = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="CascSav",
+ type="savings", balance=Decimal("0"), currency="BRL",
+ )
+ session.add(acct2)
+ await session.commit()
+
+ debit_tx, credit_tx = await create_transfer(session, test_user.id, TransferCreate(
+ from_account_id=txn_account.id, to_account_id=acct2.id,
+ description="Cascade Xfer", amount=Decimal("200"), date=date.today(),
+ ))
+ data = TransactionUpdate(description="Updated Xfer")
+ updated = await update_transaction(session, debit_tx.id, test_user.id, data)
+ assert updated.description == "Updated Xfer"
+
+ paired = await get_transaction(session, credit_tx.id, test_user.id)
+ assert paired.description == "Updated Xfer"
+
+
+# ---------------------------------------------------------------------------
+# delete_transaction — transfer cascade
+# ---------------------------------------------------------------------------
+
+
+async def test_delete_transfer_cascades(session: AsyncSession, test_user, txn_account):
+ acct2 = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="DelSav",
+ type="savings", balance=Decimal("0"), currency="BRL",
+ )
+ session.add(acct2)
+ await session.commit()
+
+ debit_tx, credit_tx = await create_transfer(session, test_user.id, TransferCreate(
+ from_account_id=txn_account.id, to_account_id=acct2.id,
+ description="Del Xfer", amount=Decimal("300"), date=date.today(),
+ ))
+ assert await delete_transaction(session, debit_tx.id, test_user.id) is True
+ assert await get_transaction(session, credit_tx.id, test_user.id) is None
diff --git a/backend/tests/test_transactions_api.py b/backend/tests/test_transactions_api.py
index 54b64999..c83aa8aa 100644
--- a/backend/tests/test_transactions_api.py
+++ b/backend/tests/test_transactions_api.py
@@ -380,3 +380,87 @@ async def test_exclude_transfers_false_includes_all(
assert response.status_code == 200
data = response.json()
assert data["total"] == 4
+
+
+async def test_export_csv_format(client: AsyncClient, auth_headers, test_transactions):
+ resp = await client.get("/api/transactions/export", headers=auth_headers)
+ assert resp.status_code == 200
+ assert "text/csv" in resp.headers.get("content-type", "")
+ content = resp.text
+ assert content.startswith("\ufeff")
+ assert "date" in content
+ assert "description" in content
+ assert "amount" in content
+
+
+async def test_export_csv_with_type_filter(client: AsyncClient, auth_headers, test_transactions):
+ resp = await client.get(
+ "/api/transactions/export",
+ params={"type": "debit"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 200
+
+
+async def test_export_csv_uncategorized(client: AsyncClient, auth_headers, test_transactions):
+ resp = await client.get(
+ "/api/transactions/export",
+ params={"uncategorized": "true"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 200
+
+
+async def test_bulk_categorize(
+ client: AsyncClient, auth_headers, test_transactions, test_categories,
+):
+ txn_id = str(test_transactions[4].id)
+ resp = await client.patch(
+ "/api/transactions/bulk-categorize",
+ json={"transaction_ids": [txn_id], "category_id": str(test_categories[0].id)},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 200
+ assert resp.json()["updated"] == 1
+
+
+async def test_create_transfer_api(client: AsyncClient, auth_headers, test_account):
+ dest_resp = await client.post(
+ "/api/accounts",
+ json={"name": "Transfer Dest", "type": "savings", "balance": 0, "currency": "BRL"},
+ headers=auth_headers,
+ )
+ dest_id = dest_resp.json()["id"]
+ resp = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": dest_id,
+ "description": "API Transfer",
+ "amount": 500,
+ "date": date.today().isoformat(),
+ },
+ headers=auth_headers,
+ )
+ assert resp.status_code == 201
+
+
+async def test_create_transfer_invalid_account(client: AsyncClient, auth_headers):
+ resp = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(uuid.uuid4()),
+ "to_account_id": str(uuid.uuid4()),
+ "description": "Bad Transfer",
+ "amount": 100,
+ "date": date.today().isoformat(),
+ },
+ headers=auth_headers,
+ )
+ assert resp.status_code == 400
diff --git a/backend/tests/test_two_factor.py b/backend/tests/test_two_factor.py
index 025c075d..642f2e73 100644
--- a/backend/tests/test_two_factor.py
+++ b/backend/tests/test_two_factor.py
@@ -175,3 +175,47 @@ async def test_disable_2fa(client: AsyncClient, test_user_with_2fa):
)
assert response.status_code == 200
assert response.json()["detail"] == "2FA disabled"
+
+
+async def test_enable_2fa_without_setup(client: AsyncClient, auth_headers):
+ resp = await client.post(
+ "/api/auth/2fa/enable",
+ json={"code": "123456"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 400
+ assert "setup" in resp.json()["detail"].lower()
+
+
+async def test_verify_2fa_invalid_token(client: AsyncClient):
+ resp = await client.post(
+ "/api/auth/2fa/verify",
+ json={"temp_token": "fake-token", "code": "123456"},
+ )
+ assert resp.status_code == 401
+
+
+async def test_verify_2fa_with_valid_token(client: AsyncClient, test_user_with_2fa):
+ mock_r = AsyncMock()
+ mock_r.get = AsyncMock(return_value=str(test_user_with_2fa.id))
+ mock_r.delete = AsyncMock()
+ pipe = AsyncMock()
+ pipe.execute = AsyncMock(return_value=[0, 0, True, True])
+ mock_r.pipeline = lambda: pipe
+
+ async def _fake():
+ return mock_r
+
+ with patch("app.api.two_factor.get_redis", _fake), \
+ patch("app.core.rate_limit.get_redis", _fake), \
+ patch("app.api.custom_auth.get_redis", _fake):
+ totp = pyotp.TOTP(test_user_with_2fa.totp_secret)
+ resp = await client.post(
+ "/api/auth/2fa/verify",
+ json={"temp_token": "valid-temp-token", "code": totp.now()},
+ )
+ assert resp.status_code == 200
+ assert "access_token" in resp.json()