-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
110 lines (94 loc) · 2.43 KB
/
main_test.go
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package crudui
import (
"context"
"database/sql"
"fmt"
"log"
"net/http"
"os"
"testing"
"time"
_ "github.com/lib/pq"
"github.com/ory/dockertest/v3"
)
// Global vars used across all the tests
var dbUser = "ui"
var dbPass = "ui123"
var dbName = "ui"
var dbConn *sql.DB
var dockerPool *dockertest.Pool
var dockerResource *dockertest.Resource
var httpPort = "32778"
var httpCancelCtx context.CancelFunc
var httpURI = "/ui/v1/"
var testController *Controller
// Test structs that should appear in the UI
type Person struct {
ID int64
Flags int64
Name string `ui:"req lenmin:5 lenmax:200"`
Age int `ui:"req valmin:0 valmax:150"`
PostCode string `ui_regexp:"^[0-9][0-9]-[0-9][0-9][0-9]$"`
Email string `ui:"req email"`
}
type Group struct {
ID int64
Flags int64
Name string `ui:"req lenmin:3 lenmax:100"`
Description string `ui:"lenmax:5000"`
}
func TestMain(m *testing.M) {
createDocker()
defer removeDocker()
createController()
createDBStructure()
createHTTPServer()
code := m.Run()
os.Exit(code)
}
func createDocker() {
var err error
dockerPool, err = dockertest.NewPool("")
if err != nil {
log.Fatalf("Could not connect to docker: %s", err)
}
dockerResource, err = dockerPool.Run("postgres", "13", []string{"POSTGRES_PASSWORD=" + dbPass, "POSTGRES_USER=" + dbUser, "POSTGRES_DB=" + dbName})
if err != nil {
log.Fatalf("Could not start resource: %s", err)
}
if err = dockerPool.Retry(func() error {
var err error
dbConn, err = sql.Open("postgres", fmt.Sprintf("host=localhost user=%s password=%s port=%s dbname=%s sslmode=disable", dbUser, dbPass, dockerResource.GetPort("5432/tcp"), dbName))
if err != nil {
return err
}
return dbConn.Ping()
}); err != nil {
log.Fatalf("Could not connect to docker: %s", err)
}
}
func createController() {
testController = NewController(dbConn, "ui_", nil)
}
func createDBStructure() {
testController.orm.CreateTables(&Person{})
testController.orm.CreateTables(&Group{})
}
func createHTTPServer() {
var ctx context.Context
ctx, httpCancelCtx = context.WithCancel(context.Background())
go func(ctx context.Context) {
go func() {
http.Handle(httpURI, testController.Handler(
httpURI,
func() interface{} { return &Person{} },
func() interface{} { return &Group{} },
))
http.ListenAndServe(":"+httpPort, nil)
}()
}(ctx)
time.Sleep(2 * time.Second)
}
func removeDocker() {
dockerPool.Purge(dockerResource)
}