/
gctest.go
220 lines (190 loc) · 5.2 KB
/
gctest.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// Copyright © 2019 Martin Tournoij – This file is part of GoatCounter and
// published under the terms of a slightly modified EUPL v1.2 license, which can
// be found in the LICENSE file or at https://license.goatcounter.com
// Package gctest contains testing helpers.
package gctest
import (
"context"
"os"
"os/exec"
"testing"
"golang.org/x/text/language"
"zgo.at/goatcounter/v2"
"zgo.at/goatcounter/v2/cron"
"zgo.at/goatcounter/v2/db/migrate/gomig"
"zgo.at/z18n"
"zgo.at/zdb"
"zgo.at/zdb/drivers/go-sqlite3"
"zgo.at/zstd/zcrypto"
"zgo.at/zstd/zgo"
"zgo.at/zstd/zstring"
)
var pgSQL = false
func init() {
sqlite3.DefaultHook(goatcounter.SQLiteHook)
goatcounter.InitGeoDB("")
}
// Context creates a new test context.
func Context(db zdb.DB) context.Context {
ctx := goatcounter.NewContext(db)
ctx = z18n.With(ctx, z18n.NewBundle(language.BritishEnglish).Locale("en-GB"))
goatcounter.Config(ctx).BcryptMinCost = true
goatcounter.Config(ctx).GoatcounterCom = true
goatcounter.Config(ctx).Domain = "test"
return ctx
}
// Reset global state.
func Reset() {
goatcounter.Memstore.Reset()
}
// DB starts a new database test.
func DB(t testing.TB) context.Context {
t.Helper()
return db(t, false)
}
// DBFile is like DB(), but guarantees that the database will be written to
// disk, whereas DB() may store it in memory.
//
// You can get the connection string from the GCTEST_CONNECT environment
// variable.
func DBFile(t testing.TB) context.Context {
t.Helper()
return db(t, true)
}
// TODO: this should use zdb.StartTest(); need to be able to pass in some
// zdb.ConnectOptions{} to that though.
// TODO: we can create unlogged tables in PostgreSQL, which should be faster:
// create unlogged table foo [..]
func db(t testing.TB, storeFile bool) context.Context {
t.Helper()
dbname := "goatcounter_test_" + zcrypto.Secret64()
conn := "sqlite3+:memory:?cache=shared"
if storeFile {
conn = "sqlite+" + t.TempDir() + "/goatcounter.sqlite3"
}
if pgSQL {
os.Setenv("PGDATABASE", dbname)
conn = "postgresql+"
}
os.Setenv("GCTEST_CONNECT", conn)
db, err := zdb.Connect(context.Background(), zdb.ConnectOptions{
Connect: conn,
Files: os.DirFS(zgo.ModuleRoot()),
Migrate: []string{"all"},
GoMigrations: gomig.Migrations,
Create: true,
})
if err != nil {
t.Fatalf("connect to DB: %s", err)
}
ctx := Context(db)
goatcounter.Memstore.TestInit(db)
ctx = initData(ctx, db, t)
t.Cleanup(func() {
goatcounter.Memstore.Reset()
db.Close()
if db.SQLDialect() == zdb.DialectPostgreSQL {
exec.Command("dropdb", dbname).Run()
}
})
return ctx
}
func initData(ctx context.Context, db zdb.DB, t testing.TB) context.Context {
site := goatcounter.Site{Code: "gctest", Cname: zstring.NewPtr("gctest.localhost").P, Plan: goatcounter.PlanFree}
err := site.Insert(ctx)
if err != nil {
t.Fatalf("create site: %s", err)
}
ctx = goatcounter.WithSite(ctx, &site)
user := goatcounter.User{
Site: site.ID,
Access: goatcounter.UserAccesses{"all": goatcounter.AccessAdmin},
Email: "test@gctest.localhost",
EmailVerified: true,
Password: []byte("coconuts"),
}
err = user.Insert(ctx, false)
if err != nil {
t.Fatalf("create user: %s", err)
}
ctx = goatcounter.WithUser(ctx, &user)
return ctx
}
// StoreHits is a convenient helper to store hits in the DB via Memstore and
// cron.UpdateStats().
func StoreHits(ctx context.Context, t *testing.T, wantFail bool, hits ...goatcounter.Hit) []goatcounter.Hit {
t.Helper()
for i := range hits {
if hits[i].Session.IsZero() {
hits[i].Session = goatcounter.TestSession
}
if hits[i].Site == 0 {
hits[i].Site = 1
}
if hits[i].Path == "" {
hits[i].Path = "/"
}
}
goatcounter.Memstore.Append(hits...)
hits, err := goatcounter.Memstore.Persist(ctx)
if !wantFail && err != nil {
t.Fatalf("gctest.StoreHits failed: %s", err)
}
if wantFail && err == nil {
t.Fatal("gc.StoreHits: no error while wantError is true")
}
sites := make(map[int64]struct{})
for _, h := range hits {
sites[h.Site] = struct{}{}
}
for s := range sites {
err = cron.UpdateStats(ctx, nil, s, hits)
if err != nil {
t.Fatal(err)
}
}
return hits
}
// Site creates a new user/site pair.
//
// You can set values for the site by passing the sute or user parameters, but
// they may be nul to just set them to some sensible defaults.
func Site(ctx context.Context, t *testing.T, site *goatcounter.Site, user *goatcounter.User) context.Context {
if site == nil {
site = &goatcounter.Site{}
}
if user == nil {
user = &goatcounter.User{}
}
if site.Code == "" {
site.Code = "gctest-" + zcrypto.Secret64()
}
if site.Plan == "" {
site.Plan = goatcounter.PlanFree
}
err := site.Insert(ctx)
if err != nil {
t.Fatal(err)
}
ctx = goatcounter.WithSite(ctx, site)
err = site.UpdateStripe(ctx)
if err != nil {
t.Fatal(err)
}
user.Site = site.ID
if user.Email == "" {
user.Email = "test@example.com"
}
if len(user.Password) == 0 {
user.Password = []byte("coconuts")
}
if user.Access == nil {
user.Access = goatcounter.UserAccesses{"all": goatcounter.AccessAdmin}
}
err = user.Insert(ctx, false)
if err != nil {
t.Fatalf("get/create user: %s", err)
}
ctx = goatcounter.WithUser(ctx, user)
return ctx
}