@@ -3,16 +3,20 @@ package teststore
3
3
import (
4
4
"context"
5
5
"fmt"
6
+ "net"
7
+ "os"
6
8
"testing"
7
9
10
+ "github.com/joho/godotenv"
11
+
12
+ "github.com/yourselfhosted/slash/server/common"
8
13
"github.com/yourselfhosted/slash/server/profile"
9
14
"github.com/yourselfhosted/slash/store"
10
15
"github.com/yourselfhosted/slash/store/db"
11
- "github.com/yourselfhosted/slash/test"
12
16
)
13
17
14
18
func NewTestingStore (ctx context.Context , t * testing.T ) * store.Store {
15
- profile := test . GetTestingProfile (t )
19
+ profile := getTestingProfile (t )
16
20
dbDriver , err := db .NewDBDriver (profile )
17
21
if err != nil {
18
22
fmt .Printf ("failed to create db driver, error: %+v\n " , err )
@@ -41,3 +45,48 @@ func resetTestingDB(ctx context.Context, profile *profile.Profile, dbDriver stor
41
45
}
42
46
}
43
47
}
48
+
49
+ func getUnusedPort () int {
50
+ // Get a random unused port
51
+ listener , err := net .Listen ("tcp" , "localhost:0" )
52
+ if err != nil {
53
+ panic (err )
54
+ }
55
+ defer listener .Close ()
56
+
57
+ // Get the port number
58
+ port := listener .Addr ().(* net.TCPAddr ).Port
59
+ return port
60
+ }
61
+
62
+ func getTestingProfile (t * testing.T ) * profile.Profile {
63
+ if err := godotenv .Load (".env" ); err != nil {
64
+ t .Log ("failed to load .env file, but it's ok" )
65
+ }
66
+
67
+ // Get a temporary directory for the test data.
68
+ dir := t .TempDir ()
69
+ mode := "prod"
70
+ port := getUnusedPort ()
71
+ driver := getDriverFromEnv ()
72
+ dsn := os .Getenv ("DSN" )
73
+ if driver == "sqlite" {
74
+ dsn = fmt .Sprintf ("%s/slash_%s.db" , dir , mode )
75
+ }
76
+ return & profile.Profile {
77
+ Mode : mode ,
78
+ Port : port ,
79
+ Data : dir ,
80
+ DSN : dsn ,
81
+ Driver : driver ,
82
+ Version : common .GetCurrentVersion (mode ),
83
+ }
84
+ }
85
+
86
+ func getDriverFromEnv () string {
87
+ driver := os .Getenv ("DRIVER" )
88
+ if driver == "" {
89
+ driver = "sqlite"
90
+ }
91
+ return driver
92
+ }
0 commit comments