/
test_helper.go
286 lines (264 loc) · 7.71 KB
/
test_helper.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package postgres
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"os"
"strings"
"testing"
"time"
"github.com/khulnasoft-lab/godep/internal"
"github.com/khulnasoft-lab/godep/internal/database"
"github.com/khulnasoft-lab/godep/internal/derrors"
"github.com/khulnasoft-lab/godep/internal/testing/sample"
// imported to register the postgres migration driver
_ "github.com/golang-migrate/migrate/v4/database/postgres"
// imported to register the file source migration driver
_ "github.com/golang-migrate/migrate/v4/source/file"
)
// recreateDB drops and recreates the database named dbName.
func recreateDB(dbName string) error {
err := database.DropDB(dbName)
if err != nil {
return err
}
return database.CreateDB(dbName)
}
// SetupTestDB creates a test database named dbName if it does not already
// exist, and migrates it to the latest schema from the migrations directory.
func SetupTestDB(dbName string) (_ *DB, err error) {
defer derrors.Wrap(&err, "SetupTestDB(%q)", dbName)
if err := database.CreateDBIfNotExists(dbName); err != nil {
return nil, fmt.Errorf("CreateDBIfNotExists(%q): %w", dbName, err)
}
if isMigrationError, err := database.TryToMigrate(dbName); err != nil {
if isMigrationError {
// failed during migration stage, recreate and try again
log.Printf("Migration failed for %s: %v, recreating database.", dbName, err)
if err := recreateDB(dbName); err != nil {
return nil, fmt.Errorf("recreateDB(%q): %v", dbName, err)
}
_, err = database.TryToMigrate(dbName)
}
if err != nil {
return nil, fmt.Errorf("unfixable error migrating database: %v.\nConsider running ./devtools/drop_test_dbs.sh", err)
}
}
db, err := database.Open("pgx", database.DBConnURI(dbName), "test")
if err != nil {
return nil, err
}
return New(db), nil
}
// ResetTestDB truncates all data from the given test DB. It should be called
// after every test that mutates the database.
func ResetTestDB(db *DB, t *testing.T) {
t.Helper()
ctx := context.Background()
if err := database.ResetDB(ctx, db.db); err != nil {
t.Fatalf("error resetting test DB: %v", err)
}
db.expoller.Poll(ctx) // clear excluded prefixes
}
// RunDBTests is a wrapper that runs the given testing suite in a test database
// named dbName. The given *DB reference will be set to the instantiated test
// database.
func RunDBTests(dbName string, m *testing.M, testDB **DB) {
database.QueryLoggingDisabled = true
db, err := SetupTestDB(dbName)
if err != nil {
if errors.Is(err, derrors.NotFound) && os.Getenv("GO_DISCOVERY_TESTDB") != "true" {
log.Printf("SKIPPING: could not connect to DB (see doc/postgres.md to set up): %v", err)
return
}
log.Fatal(err)
}
*testDB = db
code := m.Run()
if err := db.Close(); err != nil {
log.Fatal(err)
}
os.Exit(code)
}
// RunDBTestsInParallel sets up numDBs databases, then runs the tests. Before it runs them,
// it sets acquirep to a function that tests should use to acquire a database. The second
// return value of the function should be called in a defer statement to release the database.
// For example:
//
// func Test(t *testing.T) {
// db, release := acquire(t)
// defer release()
// }
func RunDBTestsInParallel(dbBaseName string, numDBs int, m *testing.M, acquirep *func(*testing.T) (*DB, func())) {
start := time.Now()
database.QueryLoggingDisabled = true
dbs := make(chan *DB, numDBs)
for i := 0; i < numDBs; i++ {
db, err := SetupTestDB(fmt.Sprintf("%s-%d", dbBaseName, i))
if err != nil {
if errors.Is(err, derrors.NotFound) && os.Getenv("GO_DISCOVERY_TESTDB") != "true" {
log.Printf("SKIPPING: could not connect to DB (see doc/postgres.md to set up): %v", err)
return
}
log.Fatal(err)
}
dbs <- db
}
*acquirep = func(t *testing.T) (*DB, func()) {
db := <-dbs
release := func() {
ResetTestDB(db, t)
dbs <- db
}
return db, release
}
log.Printf("parallel test setup for %d DBs took %s", numDBs, time.Since(start))
code := m.Run()
if len(dbs) != cap(dbs) {
log.Fatal("not all DBs were released")
}
for i := 0; i < numDBs; i++ {
db := <-dbs
if err := db.Close(); err != nil {
log.Fatal(err)
}
}
os.Exit(code)
}
// MustInsertModule inserts m into db, calling t.Fatal on error.
// It also updates the latest-version information for m.
func MustInsertModule(ctx context.Context, t *testing.T, db *DB, m *internal.Module) {
mustInsertModule(ctx, t, db, m, "", true)
}
func MustInsertModuleGoMod(ctx context.Context, t *testing.T, db *DB, m *internal.Module, goMod string) {
mustInsertModule(ctx, t, db, m, goMod, true)
}
func MustInsertModuleNotLatest(ctx context.Context, t *testing.T, db *DB, m *internal.Module) {
mustInsertModule(ctx, t, db, m, "", false)
}
func mustInsertModule(ctx context.Context, t *testing.T, db *DB, m *internal.Module, goMod string, latest bool) {
t.Helper()
var lmv *internal.LatestModuleVersions
if goMod == "-" {
if err := db.UpdateLatestModuleVersionsStatus(ctx, m.ModulePath, 404); err != nil {
t.Fatal(err)
}
} else if latest {
lmv = addLatest(ctx, t, db, m.ModulePath, m.Version, goMod)
}
if _, err := db.InsertModule(ctx, m, lmv); err != nil {
t.Fatal(err)
}
}
func addLatest(ctx context.Context, t *testing.T, db *DB, modulePath, version, modFile string) *internal.LatestModuleVersions {
if !strings.HasPrefix(strings.TrimSpace(modFile), "module") {
modFile = "module " + modulePath + "\n" + modFile
}
info, err := internal.NewLatestModuleVersions(modulePath, version, version, "", []byte(modFile))
if err != nil {
t.Fatal(err)
}
lmv, err := db.UpdateLatestModuleVersions(ctx, info)
if err != nil {
t.Fatal(err)
}
return lmv
}
// InsertSampleDirectory tree inserts a set of packages for testing
// GetUnit and frontend.FetchDirectoryDetails.
func InsertSampleDirectoryTree(ctx context.Context, t *testing.T, testDB *DB) {
t.Helper()
for _, data := range []struct {
modulePath, version string
suffixes []string
}{
{
"std",
"v1.13.4",
[]string{
"archive/tar",
"archive/zip",
"cmd/go",
"cmd/internal/obj",
"cmd/internal/obj/arm",
"cmd/internal/obj/arm64",
},
},
{
"std",
"v1.13.0",
[]string{
"archive/tar",
"archive/zip",
"cmd/go",
"cmd/internal/obj",
"cmd/internal/obj/arm",
"cmd/internal/obj/arm64",
},
},
{
"github.com/hashicorp/vault/api",
"v1.1.2",
[]string{""},
},
{
"github.com/hashicorp/vault",
"v1.1.2",
[]string{
"api",
"builtin/audit/file",
"builtin/audit/socket",
"vault/replication",
"vault/seal/transit",
},
},
{
"github.com/hashicorp/vault",
"v1.2.3",
[]string{
"builtin/audit/file",
"builtin/audit/socket",
"internal/foo",
"vault/replication",
"vault/seal/transit",
},
},
{
"github.com/hashicorp/vault",
"v1.0.3",
[]string{
"api",
"builtin/audit/file",
"builtin/audit/socket",
},
},
} {
m := sample.Module(data.modulePath, data.version, data.suffixes...)
MustInsertModule(ctx, t, testDB, m)
}
}
// GetFromSearchDocuments retrieves the module path and version for the given
// package path from the search_documents table. If the path is not in the table,
// the third return value is false.
func GetFromSearchDocuments(ctx context.Context, t *testing.T, db *DB, packagePath string) (modulePath, version string, found bool) {
row := db.db.QueryRow(ctx, `
SELECT module_path, version
FROM search_documents
WHERE package_path = $1`,
packagePath)
err := row.Scan(&modulePath, &version)
switch err {
case sql.ErrNoRows:
return "", "", false
case nil:
return modulePath, version, true
default:
t.Fatal(err)
}
return
}