-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcommand_test.go
More file actions
87 lines (81 loc) · 2.42 KB
/
Copy pathcommand_test.go
File metadata and controls
87 lines (81 loc) · 2.42 KB
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
package main
import (
"bytes"
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/apstndb/execspansql/jqresult"
)
func TestRunCLIInvalidArgumentsReturnsError(t *testing.T) {
if err := runCLI(t.Context(), []string{"--unknown-option"}); err == nil {
t.Fatal("expected argument error")
}
}
func TestRunCLIHelpReturnsWithoutExecution(t *testing.T) {
out, err := captureStdout(t, func() error { return runCLI(t.Context(), []string{"--help"}) })
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out, "Usage: execspansql") {
t.Fatalf("help = %q", out)
}
}
func TestPrepareCommandFreezesInputs(t *testing.T) {
dir := t.TempDir()
sql, params, filter := filepath.Join(dir, "query.sql"), filepath.Join(dir, "params.json"), filepath.Join(dir, "filter.jq")
for path, content := range map[string]string{sql: "SELECT @v", params: `{"v":1}`, filter: ".rows"} {
if err := os.WriteFile(path, []byte(content), 0600); err != nil {
t.Fatal(err)
}
}
o, err := processFlags([]string{"db", "--project", "p", "--instance", "i", "--sql-file", sql, "--param-file", params, "--filter-file", filter})
if err != nil {
t.Fatal(err)
}
prepared, err := prepareCommand(o)
if err != nil {
t.Fatal(err)
}
for _, path := range []string{sql, params, filter} {
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
}
if prepared.statement.SQL != "SELECT @v" || len(prepared.statement.Params) != 1 || prepared.jqCode == nil {
t.Fatalf("unresolved command: %+v", prepared)
}
value, ok := prepared.jqCode.Run(map[string]any{"rows": 7}).Next()
if !ok || value != 7 {
t.Fatalf("compiled filter result=%v, ok=%v", value, ok)
}
}
func TestPrintJQHonorsCancellation(t *testing.T) {
for _, mode := range []jqresult.InputMode{jqresult.InputEager, jqresult.InputLazy} {
t.Run(string(mode), func(t *testing.T) {
code, err := jqresult.Compile("def spin: spin; spin", mode)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(t.Context())
cancel()
var out bytes.Buffer
enc, err := newEncoder(&out, "json", false, false)
if err != nil {
t.Fatal(err)
}
var input any = map[string]any{}
if mode == jqresult.InputLazy {
input = jqresult.NewLazy(nil, false)
}
if err := printJQ(ctx, code, input, enc); !errors.Is(err, context.Canceled) {
t.Fatalf("error=%v, want canceled", err)
}
if out.Len() != 0 {
t.Fatalf("canceled filter emitted %q", out.String())
}
})
}
}