Socialify

Folder ..

Viewing setup_test.go
95 lines (79 loc) • 2.0 KB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package tests

import (
	"log/slog"
	"os"
	"pagoda/config"
	"pagoda/database"
	"pagoda/middleware"
	"pagoda/router"
	"path/filepath"
	"testing"

	"github.com/gofiber/fiber/v2"
	"github.com/stretchr/testify/require"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

var (
	TestApp *fiber.App
	TestDb  *gorm.DB
	DbPath  string
)

func TestMain(m *testing.M) {
	setUp()
	code := m.Run()
	tearDown()
	os.Exit(code)
}

func TestStart(t *testing.T) {
	require.NotNil(t, TestDb, "Test database should be initialized")
	require.NotNil(t, TestApp, "Test Fiber app should be initialized")
}

func setUp() {
	slog.Info("Starting test setup...")
	tempDir, err := os.MkdirTemp("", "test_db_*")
	if err != nil {
		slog.Error("Failed to create temp directory", "error", err)
		os.Exit(1)
	}

	slog.Info("Temporary directory created successfully", "path", tempDir)
	DbPath = filepath.Join(tempDir, "test.db")
	slog.Info("Database path set", "path", DbPath)

	// Set the DSN for the test environment
	config.DSN = "file:" + DbPath + "?cache=shared&mode=memory"
	slog.Info("DSN set", "dsn", config.DSN)

	TestDb, err = gorm.Open(sqlite.Open(config.DSN), &gorm.Config{})
	if err != nil {
		slog.Error("Failed to open database", "error", err)
		os.Exit(1)
	}

	if err = TestDb.AutoMigrate(&database.User{}); err != nil {
		slog.Error("Failed to run migrations", "error", err)
		os.Exit(1)
	}

	database.Database = TestDb
	slog.Info("Database initialised successfully")

	// Initialize the Fiber app
	TestApp = fiber.New()
	TestApp.Use(middleware.Json)
	router.Initialise(TestApp)

	slog.Info("Test environment set up successfully")
}

func tearDown() {
	if TestDb != nil {
		sqlDB, err := TestDb.DB()
		if err != nil {
			slog.Error("Error getting SQL DB", "error", err)
		} else {
			sqlDB.Close()
		}
	}

	if DbPath != "" {
		dir := filepath.Dir(DbPath)
		if err := os.RemoveAll(dir); err != nil {
			slog.Error("Error removing temporary database directory", "error", err)
		} else {
			slog.Info("Temporary database removed successfully")
		}
	}

	slog.Info("Test environment torn down")
}