forked from miku/esbulk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_test.go
347 lines (331 loc) · 8.84 KB
/
run_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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// Copyright 2021 by Leipzig University Library, http://ub.uni-leipzig.de
// The Finc Authors, http://finc.info
// Martin Czygan, <[email protected]>
//
// This file is part of some open source application.
//
// Some open source application is free software: you can redistribute
// it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// Some open source application is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Foobar. If not, see <http://www.gnu.org/licenses/>.
//
// @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+>
package esbulk
import (
"context"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"strings"
"testing"
"time"
"github.com/segmentio/encoding/json"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
func TestIncompleteConfig(t *testing.T) {
skipNoDocker(t)
var cases = []struct {
help string
r Runner
err error
}{
{help: "no default index name", r: Runner{}, err: ErrNoWorkers},
{help: "no such host", r: Runner{
IndexName: "abc",
BatchSize: 10,
NumWorkers: 1,
Servers: []string{"http://broken.server:9200"},
}, err: &url.Error{Op: "Get", URL: "http://broken.server:9200/abc"}},
}
for _, c := range cases {
err := c.r.Run()
switch err.(type) {
case nil:
if c.err != nil {
t.Fatalf("got: %#v, %T, want: %v [%s]", err, err, c.err, c.help)
}
case *url.Error:
// For now, only check whether we expect an error.
if c.err == nil {
t.Fatalf("got: %#v, %T, want: %v [%s]", err, err, c.err, c.help)
}
default:
if err != c.err {
t.Fatalf("got: %#v, %T, want: %v [%s]", err, err, c.err, c.help)
}
}
}
}
// startServer starts an elasticsearch server from image, exposing the http port.
func startServer(ctx context.Context, image string, httpPort int) (testcontainers.Container, error) {
var (
hp = fmt.Sprintf("%d:9200/tcp", httpPort)
parts = strings.Split(image, ":")
tag string
)
if len(parts) == 2 {
tag = parts[1]
} else {
tag = "latest"
}
var (
name = fmt.Sprintf("esbulk-test-es-%s", tag)
req = testcontainers.ContainerRequest{
Image: image,
Name: name,
Env: map[string]string{
"discovery.type": "single-node",
},
ExposedPorts: []string{hp},
WaitingFor: wait.ForLog("started"),
}
)
return testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
}
func LogReader(t *testing.T, r io.Reader) []byte {
b, err := ioutil.ReadAll(r)
if err != nil {
t.Fatalf("read failed: %s", err)
return nil
}
t.Logf("%s", string(b))
return b
}
func skipNoDocker(t *testing.T) {
cmd := exec.Command("systemctl", "is-active", "docker")
b, err := cmd.CombinedOutput()
if err != nil {
t.Skipf("docker seems inactive or not installed: %v", err)
}
if strings.TrimSpace(string(b)) != "active" {
t.Skipf("docker not installed or not running")
}
}
func TestMinimalConfig(t *testing.T) {
skipNoDocker(t)
ctx := context.Background()
var imageConf = []struct {
Image string
HttpPort int
}{
{"elasticsearch:7.14.1", 39200},
{"elasticsearch:6.8.14", 39200},
{"elasticsearch:5.6.16", 39200},
{"elasticsearch:2.3.4", 39200},
}
log.Printf("testing %d versions: %v", len(imageConf), imageConf)
for _, conf := range imageConf {
c, err := startServer(ctx, conf.Image, conf.HttpPort)
if err != nil {
t.Fatalf("could not start test container: %v", err)
}
base := fmt.Sprintf("http://localhost:%d", conf.HttpPort)
resp, err := http.Get(base)
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close()
LogReader(t, resp.Body)
t.Logf("server should be up at %s", base)
var cases = []struct {
filename string
indexName string
numDocs int64
err error
}{
{"fixtures/v10k.jsonl", "abc", 10000, nil},
}
for _, c := range cases {
f, err := os.Open(c.filename)
if err != nil {
t.Errorf("could not open fixture: %s", c.filename)
}
defer f.Close()
r := Runner{
Servers: []string{"http://localhost:39200"},
BatchSize: 5000,
NumWorkers: 1,
RefreshInterval: "1s",
IndexName: "abc",
DocType: "any", // deprecated with ES7
File: f,
Verbose: true,
}
err = r.Run()
if err != c.err {
t.Fatalf("got %v, want %v", err, c.err)
}
searchURL := fmt.Sprintf("%s/%s/_search", base, r.IndexName)
resp, err = http.Get(searchURL)
if err != nil {
t.Errorf("could not query es: %v", err)
}
defer resp.Body.Close()
b := LogReader(t, resp.Body)
var (
sr7 SearchResponse7
sr6 SearchResponse6
)
if err = json.Unmarshal(b, &sr7); err != nil {
if err = json.Unmarshal(b, &sr6); err != nil {
t.Errorf("could not parse json response (6, 7): %v", err)
} else {
t.Log("es6 detected")
}
}
if sr7.Hits.Total.Value != c.numDocs && sr6.Hits.Total != c.numDocs {
t.Errorf("expected %d docs", c.numDocs)
}
}
// Save logs.
rc, err := c.Logs(ctx)
if err != nil {
log.Printf("logs not available: %v", err)
}
if err := os.MkdirAll("logs", 0755); err != nil {
if !os.IsExist(err) {
log.Printf("create dir failed: %v", err)
}
}
cname, err := c.Name(ctx)
if err != nil {
t.Logf("failed to get container name: %v", err)
}
fn := fmt.Sprintf("logs/%s-%s.log", time.Now().Format("20060102150405"), strings.TrimLeft(cname, "/"))
f, err := os.Create(fn)
if err != nil {
log.Printf("failed to create log file: %v", err)
}
defer f.Close()
log.Printf("logging to %s", fn)
if _, err := io.Copy(f, rc); err != nil {
log.Printf("log failed: %v", err)
}
if err := c.Terminate(ctx); err != nil {
t.Errorf("could not kill container: %v", err)
}
}
}
func TestGH32(t *testing.T) {
skipNoDocker(t)
ctx := context.Background()
c, err := startServer(ctx, "elasticsearch:7.11.2", 39200)
if err != nil {
t.Fatalf("could not start test container: %v", err)
}
base := fmt.Sprintf("http://localhost:%d", 39200)
resp, err := http.Get(base)
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close()
LogReader(t, resp.Body)
t.Logf("server should be up at %s", base)
f, err := os.Open("fixtures/v10k.jsonl")
if err != nil {
t.Errorf("could not open fixture: %v", err)
}
defer f.Close()
r := Runner{
Servers: []string{"http://localhost:39200"},
BatchSize: 5000,
NumWorkers: 1,
RefreshInterval: "1s",
Mapping: `{}`,
IndexName: "abc",
DocType: "any", // deprecated with ES7
File: f,
Verbose: true,
}
// this should fail with #32
err = r.Run()
if err != nil {
t.Logf("expected err: %v", err)
} else {
t.Fatalf("expected fail, see #32")
}
// w/o doctype, we should be good
r = Runner{
Servers: []string{"http://localhost:39200"},
BatchSize: 5000,
NumWorkers: 1,
RefreshInterval: "1s",
Mapping: `{}`,
IndexName: "abc",
File: f,
Verbose: true,
}
err = r.Run()
if err != nil {
t.Fatalf("unexpected failure: %v", err)
}
if err := c.Terminate(ctx); err != nil {
t.Errorf("could not kill container: %v", err)
}
}
type SearchResponse6 struct {
Hits struct {
Hits []struct {
Id string `json:"_id"`
Index string `json:"_index"`
Score float64 `json:"_score"`
Source struct {
V string `json:"v"`
} `json:"_source"`
Type string `json:"_type"`
} `json:"hits"`
MaxScore float64 `json:"max_score"`
Total int64 `json:"total"`
} `json:"hits"`
Shards struct {
Failed int64 `json:"failed"`
Skipped int64 `json:"skipped"`
Successful int64 `json:"successful"`
Total int64 `json:"total"`
} `json:"_shards"`
TimedOut bool `json:"timed_out"`
Took int64 `json:"took"`
}
type SearchResponse7 struct {
Hits struct {
Hits []struct {
Id string `json:"_id"`
Index string `json:"_index"`
Score float64 `json:"_score"`
Source struct {
V string `json:"v"`
} `json:"_source"`
Type string `json:"_type"`
} `json:"hits"`
MaxScore float64 `json:"max_score"`
Total struct {
Relation string `json:"relation"`
Value int64 `json:"value"`
} `json:"total"`
} `json:"hits"`
Shards struct {
Failed int64 `json:"failed"`
Skipped int64 `json:"skipped"`
Successful int64 `json:"successful"`
Total int64 `json:"total"`
} `json:"_shards"`
TimedOut bool `json:"timed_out"`
Took int64 `json:"took"`
}