-
Notifications
You must be signed in to change notification settings - Fork 1
/
integ_test.go
474 lines (376 loc) · 10.9 KB
/
integ_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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
package xlripper
import (
"bufio"
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math"
"os"
"path"
"strconv"
"strings"
"testing"
)
const (
extMeta = "meta.json"
extXLSX = "xlsx"
// when this is specified only a test with this meta filename will run.
// e.g. when onlyRunthisTest = "large.meta.json" then only that test will run.
onlyRunThisTest = ""
)
type Manifest struct {
Name string `json:"name"`
Description string `json:"description"`
Epsilon float64 `json:"epsilon"`
IsFailureExpected bool `json:"is_failure_expected"`
Sheets []string `json:"sheets"`
}
type IntegTest struct {
Manifest Manifest
MetaFilename string
Root string
FileXLSX os.FileInfo
FileSheets []os.FileInfo
}
func TestInteg(t *testing.T) {
myDir := thisDir()
integDir := path.Join(myDir, "integ")
stats, err := os.Stat(integDir)
if os.IsNotExist(err) {
// abort if the git submodule is not there
fmt.Printf("integ tests are not available\n")
return
} else if err != nil {
fmt.Printf("error inspecting integ dir %s\n", err.Error())
return
}
mode := stats.Mode()
if !mode.IsDir() {
fmt.Printf("integ tests are not available\n")
return
}
files, err := ioutil.ReadDir(integDir)
if err != nil {
t.Errorf("error listing integ directory %s", err.Error())
}
jsonFiles := make([]os.FileInfo, 0)
for _, f := range files {
nm := strings.ToLower(f.Name())
if len(nm) >= len(extMeta) {
ext := nm[len(nm)-len(extMeta):]
if ext == extMeta {
if len(onlyRunThisTest) == 0 || f.Name() == onlyRunThisTest {
jsonFiles = append(jsonFiles, f)
}
}
}
}
tests := make([]IntegTest, 0)
metaParseLoop:
for _, jsonFile := range jsonFiles {
jsonPath := path.Join(integDir, jsonFile.Name())
ofile, err := os.Open(jsonPath)
if err != nil {
t.Errorf("error trying to open %s - %s", jsonPath, err.Error())
continue metaParseLoop
}
jsonBuf := bytes.Buffer{}
jsonBufw := bufio.NewWriter(&jsonBuf)
io.Copy(jsonBufw, ofile)
jsonBytes := jsonBuf.Bytes()
ofile.Close()
m := Manifest{}
err = json.Unmarshal(jsonBytes, &m)
if err != nil {
t.Errorf("error unmarshaling %s - %s", jsonPath, err.Error())
continue metaParseLoop
}
if len(m.Sheets) == 0 {
t.Errorf("no sheets were found in the manifest %s", jsonPath)
continue metaParseLoop
}
itest := IntegTest{}
if m.Epsilon <= 0 {
m.Epsilon = epsilon
}
itest.Manifest = m
itest.Root = jsonFile.Name()[:len(jsonFile.Name())-len(extMeta)]
itest.MetaFilename = jsonFile.Name()
if len(itest.Root) > 0 {
if itest.Root[0:1] == "." {
itest.Root = itest.Root[1:]
}
}
if len(itest.Root) > 0 {
if itest.Root[len(itest.Root)-1:] == "." {
itest.Root = itest.Root[:len(itest.Root)-1]
}
}
if len(itest.Root) > 0 {
tests = append(tests, itest)
}
}
tests = gatherTests(t, tests, files, integDir)
for _, itest := range tests {
t.Run(t.Name()+"_"+itest.Root, func(t *testing.T) {
runIntegTest(t, itest, integDir)
})
}
}
func gatherTests(t *testing.T, tests []IntegTest, files []os.FileInfo, dir string) []IntegTest {
for itestIX, itest := range tests {
expectedX := strings.ToLower(itest.Root + "." + extXLSX)
if itest.Manifest.Name != expectedX {
t.Errorf("the name found in %s should be %s", itest.MetaFilename, expectedX)
}
isXLSXFound := false
xlsxFileSearchLoop:
for _, f := range files {
if strings.ToLower(f.Name()) == expectedX {
itest.FileXLSX = f
isXLSXFound = true
break xlsxFileSearchLoop
}
}
if !isXLSXFound {
t.Errorf("the xlsx file %s could not be found", expectedX)
}
expectedNumSheets := len(itest.Manifest.Sheets)
if expectedNumSheets == 0 {
t.Errorf("the manifest has zero sheets: %s", itest.MetaFilename)
}
itest.FileSheets = make([]os.FileInfo, 0)
for sheetIX, _ := range itest.Manifest.Sheets {
sheetCsvName := fmt.Sprintf("%s.sheet%d.csv", itest.Root, sheetIX)
isFound := false
sheetFileSearchLoop:
for _, f := range files {
searchName := strings.ToLower(f.Name())
if searchName == sheetCsvName {
itest.FileSheets = append(itest.FileSheets, f)
isFound = true
break sheetFileSearchLoop
}
}
if !isFound {
t.Errorf("%s was not found", sheetCsvName)
}
}
tests[itestIX] = itest
}
return tests
}
func runIntegTest(t *testing.T, test IntegTest, dir string) {
tn := fmt.Sprintf("Integ Test %s", test.FileXLSX.Name())
xlsxPath := path.Join(dir, test.FileXLSX.Name())
parser, err := NewParser(xlsxPath)
if err != nil {
t.Errorf("error opening parser for %s: %s", test.FileXLSX.Name(), err.Error())
return
}
wantNumSheets := len(test.Manifest.Sheets)
gotNumSheets := parser.NumSheets()
if wantNumSheets != gotNumSheets {
t.Error(tfail(tn, "parser.NumSheets()", itos(gotNumSheets), itos(wantNumSheets)))
return
}
for sheetIX := 0; sheetIX < wantNumSheets; sheetIX++ {
testSheetName(t, tn, sheetIX, parser, test)
}
for sheetIX := 0; sheetIX < wantNumSheets; sheetIX++ {
//sheetName := parser.SheetNames()[sheetIX]
localTestName := fmt.Sprintf("%s sheet[%d]", tn, sheetIX)
testSheetDataParsing(t, localTestName, sheetIX, parser, test, dir)
}
}
func testSheetName(t *testing.T, testName string, sheetIndex int, parser Parser, test IntegTest) {
want := test.Manifest.Sheets[sheetIndex]
got := parser.SheetNames()[sheetIndex]
if want != got {
t.Errorf(testName, fmt.Sprintf("parser.SheetNames()[%d]", sheetIndex), got, want)
}
}
func testSheetDataParsing(t *testing.T, testName string, sheetIndex int, parser Parser, test IntegTest, dir string) {
//sheetName := parser.SheetNames()[sheetIndex]
csvFilename := test.FileSheets[sheetIndex].Name()
csvPath := path.Join(dir, csvFilename)
ofile, err := os.Open(csvPath)
if err != nil {
t.Errorf("error occurred opening %s: %s", csvFilename, err.Error())
}
defer ofile.Close()
csvReader := csv.NewReader(ofile)
csvReader.LazyQuotes = true
csvReader.TrimLeadingSpace = true
// Read reads one record (a slice of fields) from r. If the record has an unexpected number of fields, Read returns
// the record along with the error ErrFieldCount. Except for that case, Read always returns either a non-nil record
// or a non-nil error, but not both. If there is no data left to be read, Read returns nil, io.EOF. If ReuseRecord
// is true, the returned slice may be shared between multiple calls to Read.
csvRows := make([][]string, 0)
csvLoop:
for {
row, err := csvReader.Read()
if err == io.EOF {
break csvLoop
} else if err != nil {
t.Errorf("failure parsing %s: %s", csvFilename, err.Error())
break csvLoop
}
csvRows = append(csvRows, row)
}
sheet, err := parser.ParseOne(sheetIndex)
if err != nil {
t.Errorf("%s: received error during xlsx paring of sheet %d: %s", testName, sheetIndex, err.Error())
}
numRows, numCols := findMaxRowAndColumnLengths(sheet, csvRows)
failures := 0
for rowIX := 0; rowIX < numRows; rowIX++ {
for colIX := 0; colIX < numCols; colIX++ {
csvVal, csvOK := getCsvValue(csvRows, rowIX, colIX)
xlsxVal, xlsxOK := getXLSXValue(sheet, rowIX, colIX)
thisTest := fmt.Sprintf("%s rowIX %d, colIX %d", testName, rowIX, colIX)
if csvOK && len(csvVal) > 0 {
if !xlsxOK {
t.Errorf(tfail(thisTest, "csvOK && len(csvVal) > 0 && !xlsxOK", btos(true), btos(false)))
}
} else if xlsxOK && len(xlsxVal) > 0 {
if !csvOK {
t.Errorf(tfail(thisTest, "xlsxOK && len(xlsxVal) > 0 && !csvOK", btos(true), btos(false)))
}
}
testPasses := areEqual(csvVal, xlsxVal, test)
if !testPasses {
testPasses = areEqualArduously(csvVal, xlsxVal, test)
}
if !testPasses {
t.Error(tfail(thisTest, "xlsxVal", xlsxVal, csvVal))
failures++
if failures >= 100 {
t.Errorf("%s: more than 100 failures, aborting assertions on this file", testName)
return
}
}
}
}
}
func areEqualWhenTrimming(a, b string, test IntegTest) (equal bool) {
testPasses := false
aRunes := []rune(a)
bRunes := []rune(b)
if len(aRunes) == len(bRunes) {
// there's nothing else to try if the rune lengths are equal
return false
}
// check for garbage space at both ends of the a
if len(aRunes) == len(bRunes)+2 {
testPasses = areEqualArduously(b, string(aRunes[1:len(aRunes)-1]), test)
}
if testPasses {
return true
}
// check for garbage space on the end of the a
if len(aRunes) == len(bRunes)+1 {
testPasses = areEqualArduously(b, string(aRunes[1:]), test)
}
if testPasses {
return true
}
// check for garbage space at the start of the a
if len(aRunes) == len(bRunes)+1 {
testPasses = areEqualArduously(b, string(aRunes[:len(aRunes)-1]), test)
}
if testPasses {
return true
}
return testPasses
}
func areEqualArduously(csvVal, xlsxVal string, test IntegTest) (equal bool) {
testPasses := areEqual(csvVal, xlsxVal, test)
if testPasses {
return true
}
testPasses = areEqualWhenTrimming(csvVal, xlsxVal, test)
if testPasses {
return true
}
testPasses = areEqualWhenTrimming(xlsxVal, csvVal, test)
if testPasses {
return true
}
// last resot
// if dollarsigns or commas are found, try removing them and recursively trying again
if strings.Index(csvVal, "$") >= 0 || strings.Index(csvVal, ",") >= 0 {
unformatted := strings.Replace(csvVal, "$", "", -1)
unformatted = strings.Replace(unformatted, ",", "", -1)
testPasses = areEqualArduously(unformatted, xlsxVal, test)
return testPasses
}
return testPasses
}
func areEqual(want, got string, test IntegTest) (equal bool) {
if want == got {
return true
}
// check if they are different by some floating point imprecision
csvFloat, csvFloatErr := strconv.ParseFloat(want, 64)
xlsxFloat, xlsxFloatErr := strconv.ParseFloat(got, 64)
if csvFloatErr == nil && xlsxFloatErr == nil {
diff := math.Abs(csvFloat - xlsxFloat)
if diff < test.Manifest.Epsilon {
return true
}
}
return false
}
func findMaxRowAndColumnLengths(sheet Sheet, csvRows [][]string) (numRows, numCols int) {
xNumCols := len(sheet.Columns)
xNumRows := -1
for _, c := range sheet.Columns {
if len(c.Cells) > xNumRows {
xNumRows = len(c.Cells)
}
}
cNumRows := len(csvRows)
cNumCols := -1
for _, r := range csvRows {
if len(r) > cNumCols {
cNumCols = len(r)
}
}
maxCols := maxi(xNumCols, cNumCols)
maxRows := maxi(xNumRows, cNumRows)
return maxRows, maxCols
}
func getCsvValue(csvRows [][]string, rowIX, colIX int) (value string, ok bool) {
if rowIX < 0 || colIX < 0 {
return "", false
}
if rowIX >= len(csvRows) {
return "", false
}
row := csvRows[rowIX]
if colIX >= len(row) {
return "", false
}
return row[colIX], true
}
func getXLSXValue(sheet Sheet, rowIX, colIX int) (value string, ok bool) {
if colIX < 0 || rowIX < 0 {
return "", false
}
if colIX >= len(sheet.Columns) {
return "", false
}
col := sheet.Columns[colIX]
if rowIX >= len(col.Cells) {
return "", false
}
cell := col.Cells[rowIX]
if cell == nil {
return "", true
}
return *cell, true
}