-
Notifications
You must be signed in to change notification settings - Fork 0
/
database_mock.go
73 lines (55 loc) · 1.72 KB
/
database_mock.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
package test
import (
"github.com/thewug/fsb/pkg/storage"
"database/sql"
"os"
"os/exec"
"io/ioutil"
"encoding/json"
"fmt"
"errors"
)
var db_test *sql.DB
var settings struct {
User string `json:"user"`
Dbname string `json:"dbname"`
Host string `json:"host"`
Port string `json:"port"`
}
func dburl() string {
return fmt.Sprintf("postgres://%s:%s@%s:%s/%s", settings.User, settings.User, settings.Host, settings.Port, settings.Dbname)
}
func ensureSettings() error {
if settings.User != "" { return nil }
file, err := os.Open("../../database/test_db.json")
if err != nil { return fmt.Errorf("Couldn't open database test settings! Did you forget to run initialize_test_database.sh? (%w)", err) }
data, err := ioutil.ReadAll(file)
if err != nil { return err }
err = json.Unmarshal(data, &settings)
if err != nil { return err }
if settings.User == "" { return errors.New("settings file did not produce valid configuration") }
return nil
}
func TestDatabase() (*sql.DB, error) {
if db_test != nil { return db_test, nil }
err := ensureSettings()
if err != nil { return nil, err }
db, err := sql.Open("postgres", dburl())
if err != nil { return nil, err }
db_test = db
return db, nil
}
func ResetTestDatabase() error {
err := ensureSettings()
if err != nil { return err }
cmd := exec.Command("../../database/reset_test_database.sh", settings.User, settings.Dbname, settings.Host, settings.Port)
cmd.Env = append(os.Environ(), fmt.Sprintf("PGPASSWORD=%s", settings.User))
return cmd.Run()
}
func Rollbacker(fn func(storage.DBLike) error) (func(storage.DBLike) error) {
return func(tx storage.DBLike) error {
err := fn(tx)
if err == nil { err = storage.NewRollbackAndMask("success") }
return err
}
}