This repository has been archived by the owner on Nov 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main_test.go
113 lines (99 loc) · 2.29 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
111
112
113
package main
import (
"database/sql"
"flag"
"fmt"
"github.com/datatogether/sqlutil"
"github.com/gchaincl/dotsql"
_ "github.com/lib/pq"
"os"
"testing"
)
func TestMain(m *testing.M) {
var err error
flag.Parse()
cfg, err = initConfig("test")
if err != nil {
// panic if the server is missing a vital configuration detail
panic(fmt.Errorf("server configuration error: %s", err.Error()))
}
teardown := setupTestDatabase()
retCode := m.Run()
teardown()
os.Exit(retCode)
}
func setupTestDatabase() func() {
var err error
appDB, err = sqlutil.SetupConnection("postgres", cfg.PostgresDbUrl)
if err != nil {
appDB.Close()
panic(err.Error())
}
teardown, err := initializeAppSchema(appDB)
if err != nil {
panic(err.Error())
}
if err := resetTestData(appDB,
"primers",
"sources",
"urls",
"links",
"metadata",
"snapshots",
"collections",
"archive_requests",
"uncrawlables"); err != nil {
panic(err.Error())
}
return teardown
}
// WARNING - THIS ZAPS WHATEVER DB IT'S GIVEN. DO NOT CALL THIS SHIT.
// used for testing only, returns a teardown func
func initializeAppSchema(db *sql.DB) (func(), error) {
schema, err := dotsql.LoadFromFile("sql/schema.sql")
if err != nil {
return nil, err
}
for _, cmd := range []string{
"drop-all",
"create-primers",
"create-sources",
"create-urls",
"create-links",
"create-metadata",
"create-snapshots",
"create-collections",
"create-archive_requests",
"create-uncrawlables",
} {
if _, err := schema.Exec(db, cmd); err != nil {
fmt.Println(cmd, "error:", err)
return nil, err
}
}
teardown := func() {
if _, err := schema.Exec(db, "drop-all"); err != nil {
panic(err.Error())
}
}
return teardown, nil
}
// drops test data tables & re-inserts base data from sql/test_data.sql, based on
// passed in table names
func resetTestData(db *sql.DB, tables ...string) error {
schema, err := dotsql.LoadFromFile("sql/test_data.sql")
if err != nil {
return err
}
for _, t := range tables {
if _, err := schema.Exec(db, fmt.Sprintf("delete-%s", t)); err != nil {
err = fmt.Errorf("error delete-%s: %s", t, err.Error())
return err
}
if _, err := schema.Exec(db, fmt.Sprintf("insert-%s", t)); err != nil {
err = fmt.Errorf("error insert-%s: %s", t, err.Error())
return err
}
}
return nil
}