-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathsql_test.go
96 lines (77 loc) · 2.29 KB
/
sql_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
package sql
import (
"context"
"io"
"testing"
"github.com/spf13/afero"
"github.com/dop251/goja"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
"go.k6.io/k6/js/common"
"go.k6.io/k6/js/modulestest"
"go.k6.io/k6/lib"
"go.k6.io/k6/lib/testutils"
"go.k6.io/k6/metrics"
)
// TestSQLiteIntegration performs an integration test creating an SQLite database
func TestSQLiteIntegration(t *testing.T) {
t.Parallel()
fs := afero.NewOsFs()
dbname := "intg_test.db"
t.Cleanup(func() {
if err := fs.Remove(dbname); err != nil {
logrus.Warn(err)
}
})
rt := setupTestEnv(t)
_, err := rt.RunString(`
const db = sql.open("sqlite3", "` + dbname + `");
db.exec("DROP TABLE IF EXISTS test_table;")
db.exec("CREATE TABLE test_table (id integer PRIMARY KEY AUTOINCREMENT, key varchar NOT NULL, value varchar);")
for (let i = 0; i < 5; i++) {
db.exec("INSERT INTO test_table (key, value) VALUES ('key-" + i + "', 'value-" + i + "');")
}
let all_rows = sql.query(db, "SELECT * FROM test_table;")
if (all_rows.length != 5) {
throw new Error("Expected all five rows to be returned; got " + all_rows.length)
}
let one_row = sql.query(db, "SELECT * FROM test_table WHERE key = $1;", "key-2");
if (one_row.length != 1) {
throw new Error("Expected single row to be returned; got " + one_row.length)
}
let no_rows = sql.query(db, "SELECT * FROM test_table WHERE key = $1;", 'bogus-key');
if (no_rows.length != 0) {
throw new Error("Expected no rows to be returned; got " + no_rows.length)
}
db.close()
`)
require.NoError(t, err)
}
func setupTestEnv(t *testing.T) *goja.Runtime {
rt := goja.New()
rt.SetFieldNameMapper(common.FieldNameMapper{})
testLog := logrus.New()
testLog.AddHook(&testutils.SimpleLogrusHook{
HookedLevels: []logrus.Level{logrus.WarnLevel},
})
testLog.SetOutput(io.Discard)
state := &lib.State{
Options: lib.Options{
SystemTags: metrics.NewSystemTagSet(metrics.TagVU),
},
Logger: testLog,
Tags: lib.NewVUStateTags(metrics.NewRegistry().RootTagSet()),
}
root := &RootModule{}
m, ok := root.NewModuleInstance(
&modulestest.VU{
RuntimeField: rt,
InitEnvField: &common.InitEnvironment{},
CtxField: context.Background(),
StateField: state,
},
).(*SQL)
require.True(t, ok)
require.NoError(t, rt.Set("sql", m.Exports().Default))
return rt
}