tsk-5: Add contact (#7)
Closes #5 Reviewed-on: phoenix/textsender-api#7 Co-authored-by: phoenix <kundeng00@pm.me> Co-committed-by: phoenix <kundeng00@pm.me>
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/joho/godotenv"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/config"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/db"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/handler"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/handler/endpoint"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||
)
|
||||
|
||||
var testRouter *mux.Router
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
cfg := load()
|
||||
|
||||
db, err := db.NewDatabase(cfg.GetDBConnString())
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
panic("Failed to initialize database")
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
err = db.ResetDatabase(ctx)
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
panic("Failed to initialize database")
|
||||
}
|
||||
|
||||
contactStore := store.NewContactStore(db.Pool)
|
||||
contactHandler := handler.NewContactHandler(contactStore)
|
||||
|
||||
testRouter = mux.NewRouter()
|
||||
testRouter.HandleFunc(endpoint.ADD_CONTACT_ENDPOINT, contactHandler.AddContact).Methods("POST")
|
||||
|
||||
code := m.Run()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func load() *config.Config {
|
||||
resetDb := flag.Bool("reset-db", false, "Reset the database schema and exit")
|
||||
port := flag.String("port", config.PORT, "Server port")
|
||||
flag.Parse()
|
||||
|
||||
cwd, _ := os.Getwd()
|
||||
envPath := path.Join(cwd, ".env")
|
||||
|
||||
err := godotenv.Load(envPath)
|
||||
if err != nil {
|
||||
envPath = path.Join(cwd, "../..", ".env")
|
||||
if err := godotenv.Load(envPath); err != nil {
|
||||
panic("Error loading .env file: " + err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
unpackedConnString := config.UnpackDBConnString()
|
||||
dbConnString := unpackedConnString.Parse()
|
||||
|
||||
return &config.Config{
|
||||
DBConnString: dbConnString,
|
||||
ServerPort: *port,
|
||||
ResetDB: *resetDb,
|
||||
}
|
||||
}
|
||||
|
||||
func resetTestDB(t *testing.T) {
|
||||
t.Helper()
|
||||
_, err := db.Pool.Exec(context.Background(), "DELETE FROM contacts")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to reset test database: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user