package audit import ( "context" "errors" "fmt" "strings" "testing" "github.com/DATA-DOG/go-sqlmock" "gorm.io/driver/mysql" "gorm.io/gorm" ) func newTestDB(t *testing.T) (*gorm.DB, sqlmock.Sqlmock, func()) { t.Helper() sqlDB, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherFunc(func(expected, actual string) error { if strings.Contains(actual, expected) { return nil } return fmt.Errorf("actual sql %q does not contain %q", actual, expected) }))) if err != nil { t.Fatalf("create sqlmock: %v", err) } db, err := gorm.Open(mysql.New(mysql.Config{Conn: sqlDB, SkipInitializeWithVersion: true}), &gorm.Config{SkipDefaultTransaction: true}) if err != nil { _ = sqlDB.Close() t.Fatalf("open gorm: %v", err) } return db, mock, func() { _ = sqlDB.Close() } } func TestWriteAdminAction_RequiresTx(t *testing.T) { err := WriteAdminAction(context.Background(), nil, Entry{ActorUserId: 1, Action: "x"}) if err == nil { t.Fatalf("expected error on nil tx") } } func TestWriteAdminAction_RequiresActorAndAction(t *testing.T) { db, _, cleanup := newTestDB(t) defer cleanup() if err := WriteAdminAction(context.Background(), db, Entry{Action: "x"}); err == nil { t.Fatal("expected error when ActorUserId=0") } if err := WriteAdminAction(context.Background(), db, Entry{ActorUserId: 1}); err == nil { t.Fatal("expected error when Action empty") } } func TestWriteAdminAction_InsertsRow(t *testing.T) { db, mock, cleanup := newTestDB(t) defer cleanup() mock.ExpectExec("INSERT INTO `admin_action_log`"). WillReturnResult(sqlmock.NewResult(1, 1)) err := WriteAdminAction(context.Background(), db, Entry{ ActorUserId: 42, Action: ActionLotteryActivityCreate, TargetIds: "[1,2,3]", RequestBody: []byte(`{"title":"test"}`), IP: "127.0.0.1", UserAgent: "curl/7.85", }) if err != nil { t.Fatalf("WriteAdminAction: %v", err) } if err := mock.ExpectationsWereMet(); err != nil { t.Fatalf("expectations: %v", err) } } func TestHashBody(t *testing.T) { if got := hashBody(nil); got != "" { t.Fatalf("nil body should hash to empty, got %q", got) } if got := hashBody([]byte("")); got != "" { t.Fatalf("empty body should hash to empty, got %q", got) } if got := hashBody([]byte("abc")); len(got) != 40 { t.Fatalf("expected 40-char sha1 hex, got %q", got) } } func TestTruncate(t *testing.T) { if got := truncate("hello", 10); got != "hello" { t.Fatalf("short strings pass through, got %q", got) } if got := truncate("hello world", 5); got != "hello" { t.Fatalf("expected truncation to 5, got %q", got) } } func TestWriteAdminAction_DBError(t *testing.T) { db, mock, cleanup := newTestDB(t) defer cleanup() mock.ExpectExec("INSERT INTO `admin_action_log`"). WillReturnError(errors.New("db down")) err := WriteAdminAction(context.Background(), db, Entry{ ActorUserId: 1, Action: "test", }) if err == nil { t.Fatal("expected error propagation from DB") } }