50 lines
1.6 KiB
Go
50 lines
1.6 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"testing"
|
|
"time"
|
|
|
|
_ "modernc.org/sqlite"
|
|
)
|
|
|
|
func TestEnsureMonthlySnapshotRefreshesCurrentMonth(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 accounts (id INTEGER PRIMARY KEY, type TEXT, balance INTEGER, is_active INTEGER)`,
|
|
`CREATE TABLE transactions (id INTEGER PRIMARY KEY, type TEXT, amount INTEGER, account_id INTEGER, to_account_id INTEGER)`,
|
|
`CREATE TABLE assets (id INTEGER PRIMARY KEY, value INTEGER, account_id INTEGER)`,
|
|
`CREATE TABLE liabilities (id INTEGER PRIMARY KEY, principal INTEGER)`,
|
|
`CREATE TABLE asset_snapshots (id INTEGER PRIMARY KEY, date TEXT UNIQUE, total_asset INTEGER, total_debt INTEGER, net_worth INTEGER, created_at TEXT DEFAULT (datetime('now')))`,
|
|
`INSERT INTO assets VALUES (1, 1000, NULL)`,
|
|
} {
|
|
if _, err := db.Exec(stmt); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
svc := NewAssetService(db)
|
|
now := time.Date(2026, 8, 6, 12, 0, 0, 0, time.Local)
|
|
if err := svc.EnsureMonthlySnapshot(context.Background(), now); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := db.Exec(`UPDATE assets SET value = 2500 WHERE id = 1`); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := svc.EnsureMonthlySnapshot(context.Background(), now.AddDate(0, 0, 1)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var count int
|
|
var netWorth int64
|
|
if err := db.QueryRow(`SELECT COUNT(*), MAX(net_worth) FROM asset_snapshots`).Scan(&count, &netWorth); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if count != 1 || netWorth != 2500 {
|
|
t.Fatalf("count=%d netWorth=%d", count, netWorth)
|
|
}
|
|
}
|