76 lines
2.1 KiB
Go
76 lines
2.1 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"os"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"5803025048/W04/internal/database"
|
|
"5803025048/W04/internal/models"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
// testConn dipakai bersama oleh seluruh tes di package ini.
|
|
// Tes berjalan berurutan (tanpa t.Parallel), jadi aman.
|
|
var testConn *pgx.Conn
|
|
|
|
func TestMain(m *testing.M) {
|
|
// Safety guard: tes ini men-TRUNCATE semua tabel.
|
|
name := os.Getenv("DB_NAME")
|
|
if !strings.HasSuffix(name, "_test") {
|
|
log.Fatalf("refusing to run store tests: DB_NAME must end in _test (got %q)", name)
|
|
}
|
|
|
|
// Tidak boleh skip: kalau DB tidak ada / tidak terjangkau, tes GAGAL.
|
|
conn, err := database.Connect()
|
|
if err != nil {
|
|
log.Fatalf("store tests need a reachable PostgreSQL: %v", err)
|
|
}
|
|
|
|
// Skema dibuat lewat kode yang sama dengan yang dipakai server saat startup.
|
|
if err := database.CreateTables(conn); err != nil {
|
|
log.Fatalf("could not create schema: %v", err)
|
|
}
|
|
|
|
testConn = conn
|
|
code := m.Run()
|
|
_ = conn.Close(context.Background())
|
|
os.Exit(code)
|
|
}
|
|
|
|
// resetDB mengosongkan semua tabel. Dipanggil di awal setiap tes.
|
|
func resetDB(t *testing.T) {
|
|
t.Helper()
|
|
if _, err := testConn.Exec(context.Background(), `TRUNCATE TABLE sessions, snippets, users CASCADE`); err != nil {
|
|
t.Fatalf("truncate tables: %v", err)
|
|
}
|
|
}
|
|
|
|
func newTestStores() (*UserStore, *SessionStore, *SnippetStore) {
|
|
mu := &sync.Mutex{}
|
|
return NewUserStore(testConn, mu), NewSessionStore(testConn, mu), NewSnippetStore(testConn, mu)
|
|
}
|
|
|
|
func mustCreateUser(t *testing.T, us *UserStore, username string) *models.User {
|
|
t.Helper()
|
|
u := &models.User{ID: uuid.New().String(), Username: username, PasswordHash: "hash-of-" + username}
|
|
if err := us.Create(context.Background(), u); err != nil {
|
|
t.Fatalf("create user %q: %v", username, err)
|
|
}
|
|
return u
|
|
}
|
|
|
|
// countRows hanya dipanggil dengan nama tabel konstan dari tes ini.
|
|
func countRows(t *testing.T, table string) int {
|
|
t.Helper()
|
|
var n int
|
|
if err := testConn.QueryRow(context.Background(), `SELECT COUNT(*) FROM `+table).Scan(&n); err != nil {
|
|
t.Fatalf("count rows in %s: %v", table, err)
|
|
}
|
|
return n
|
|
}
|