Files

37 lines
1.4 KiB
Go

package service
import (
"context"
"database/sql"
"testing"
_ "modernc.org/sqlite"
)
func TestBudgetOverviewCountsUnbudgetedExpenseInMonthlyTotal(t *testing.T) {
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Close() })
for _, stmt := range []string{
`CREATE TABLE categories (id INTEGER PRIMARY KEY, name TEXT, type TEXT, parent_id INTEGER, sort_order INTEGER, is_active INTEGER)`,
`CREATE TABLE budgets (id INTEGER PRIMARY KEY, year INTEGER, month INTEGER, category_id INTEGER, amount INTEGER, note TEXT, created_at TEXT, updated_at TEXT)`,
`CREATE TABLE transactions (id INTEGER PRIMARY KEY, type TEXT, amount INTEGER, category_id INTEGER, date TEXT)`,
`INSERT INTO categories VALUES (1, '支出', 'expense', NULL, 1, 1), (2, '餐饮', 'expense', 1, 1, 1), (3, '交通', 'expense', 1, 2, 1)`,
`INSERT INTO budgets VALUES (1, 2026, NULL, NULL, 120000, '', '', ''), (2, 2026, NULL, 2, 60000, '', '', '')`,
`INSERT INTO transactions VALUES (1, 'expense', 1000, 2, '2026-08-01'), (2, 'expense', 2000, 3, '2026-08-02')`,
} {
if _, err := db.Exec(stmt); err != nil {
t.Fatal(err)
}
}
overview, err := NewBudgetService(db).Overview(context.Background(), 2026, 8)
if err != nil {
t.Fatal(err)
}
if overview.MonthlySpent != 3000 || overview.MonthlyBudgetedSpent != 1000 || overview.MonthlyUnbudgetedSpent != 2000 {
t.Fatalf("unexpected monthly amounts: %+v", overview)
}
}