-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgolang-coverage-check_test.go
1246 lines (1178 loc) · 34.2 KB
/
golang-coverage-check_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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"errors"
"fmt"
"os"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func newTestOptions() Options {
options := newOptions()
options.rawArgs = []string{}
options.captureOutput = func(string, ...string) ([]string, error) {
panic("captureOutput was called without being set by the test")
}
return options
}
func TestMakeExampleConfig(t *testing.T) {
expected := strings.Split(strings.TrimLeft(strings.ReplaceAll(`
comment: Comment is not interpreted or used; it is provided as a structured way of
adding comments to a config, so that automated editing is easier.
default_coverage: 80
rules:
- comment: Low coverage is acceptable for main()
filename_regex: ""
function_regex: ^main$
receiver_regex: ""
coverage: 50
- comment: All the fooOrDie() functions should be fully tested because they panic()
on failure
filename_regex: ""
function_regex: OrDie$
receiver_regex: ""
coverage: 100
- comment: Improve test coverage for parse_json.go?
filename_regex: ^parse_json.go$
function_regex: ""
receiver_regex: ""
coverage: 73
- comment: Full coverage for other parsers
filename_regex: ^parse.*.go$
function_regex: ""
receiver_regex: ""
coverage: 100
- comment: Url.String() has low coverage
filename_regex: ^urls.go$
function_regex: ^String$
receiver_regex: ^Url$
coverage: 56
- comment: String() everywhere else should have high coverage
filename_regex: ""
function_regex: ^String$
receiver_regex: ""
coverage: 100
`, "\t", " "), "\n"), "\n")
actual := strings.Split(makeExampleConfig()[0], "\n")
assert.Equal(t, expected, actual)
}
func TestGenerateConfig(t *testing.T) {
coverage := []CoverageLine{
{
Filename: "test.go",
LineNumber: "1",
Function: "func1",
Coverage: 20.0,
},
{
Filename: "test.go",
LineNumber: "2",
Function: "func5",
Coverage: 34.0,
},
{
Filename: "test.go",
LineNumber: "9",
Function: "func17",
Coverage: 12.3,
},
}
fim := FunctionInfoMap{
"test.go:9": {
Filename: "test.go",
LineNumber: "9",
Function: "func17",
Receiver: "receiver-receiver-receiver",
},
}
expected := Config{
DefaultCoverage: 100.0,
Rules: []Rule{
{
FilenameRegex: "^test.go$",
FunctionRegex: "^func1$",
ReceiverRegex: "^$",
Comment: "Generated rule for func1, found at test.go:1",
Coverage: 20.0,
},
{
FilenameRegex: "^test.go$",
FunctionRegex: "^func5$",
ReceiverRegex: "^$",
Comment: "Generated rule for func5, found at test.go:2",
Coverage: 34.0,
},
{
FilenameRegex: "^test.go$",
FunctionRegex: "^func17$",
ReceiverRegex: "^receiver-receiver-receiver$",
Comment: "Generated rule for func17, found at test.go:9",
Coverage: 12.3,
},
},
}
generated := generateConfig(coverage, fim)
assert.Equal(t, expected, generated)
}
func TestValidateConfigErrors(t *testing.T) {
table := []struct {
config Config
err string
}{
{
err: "default coverage (101.0) is outside the range 0-100",
config: Config{
DefaultCoverage: 101,
},
},
{
err: "default coverage (-1.0) is outside the range 0-100",
config: Config{
DefaultCoverage: -1,
},
},
{
err: "coverage (1234.0) is outside the range 0-100 in",
config: Config{
DefaultCoverage: 99,
Rules: []Rule{
{
FilenameRegex: "asdf",
Coverage: 1234,
},
},
},
},
{
err: "coverage (-1.0) is outside the range 0-100 in",
config: Config{
DefaultCoverage: 99,
Rules: []Rule{
{
FilenameRegex: "asdf",
Coverage: -1,
},
},
},
},
{
err: "every regex is an empty string in rule",
config: Config{
DefaultCoverage: 99,
Rules: []Rule{
{
Coverage: 1,
},
},
},
},
}
for _, test := range table {
_, err := validateConfig(test.config)
// Note: the error message seems mangled when it's printed here, but it's
// fine when printed for real. I don't understand why and an hour of
// debugging has gotten me nowhere :(
assert.ErrorContains(t, err, test.err, test.config)
}
}
func TestValidateConfigSuccess(t *testing.T) {
config := Config{
Comment: "successful test",
DefaultCoverage: 75.0,
Rules: []Rule{
{
Comment: "successful rule",
FilenameRegex: "foo",
FunctionRegex: "bar",
ReceiverRegex: "baz",
Coverage: 7.0,
},
},
}
config, err := validateConfig(config)
assert.Nil(t, err)
assert.Equal(t, 75.0, config.DefaultCoverage)
assert.Equal(t, 1, len(config.Rules))
rule := config.Rules[0]
assert.Equal(t, "foo", rule.FilenameRegex)
assert.Equal(t, "bar", rule.FunctionRegex)
assert.Equal(t, "baz", rule.ReceiverRegex)
assert.NotNil(t, rule.compiledFilenameRegex)
assert.NotNil(t, rule.compiledFunctionRegex)
assert.NotNil(t, rule.compiledReceiverRegex)
}
func TestParseYAMLConfig_UnmarshalError(t *testing.T) {
_, err := parseYAMLConfig([]byte("asdf"))
assert.ErrorContains(t, err, "failed parsing YAML: yaml: unmarshal errors")
}
func TestParseYAMLConfigSuccess(t *testing.T) {
config, err := parseYAMLConfig([]byte(""))
assert.Nil(t, err)
assert.Equal(t, 0.0, config.DefaultCoverage)
yml := `
default_coverage: 75
rules:
- function_regex: pinky
coverage: 20
comment: nobody understands pinky
- function_regex: the brain
coverage: 90
comment: the brain thinks he's understood
- filename_regex: main.go
coverage: 50
- filename_regex: utils.go
coverage: 95
`
yml = strings.ReplaceAll(yml, "\t", " ")
config, err = parseYAMLConfig([]byte(yml))
assert.Nil(t, err)
assert.Equal(t, 75.0, config.DefaultCoverage)
assert.Equal(t, 4, len(config.Rules))
assert.Equal(t, "pinky", config.Rules[0].FunctionRegex)
}
func TestMakeFunctionInfoMapFailure(t *testing.T) {
options := newTestOptions()
options.dirToParse = "does-not-exist"
_, err := makeFunctionInfoMap(options)
assert.Error(t, err)
}
func TestMakeFunctionInfoMapSuccess(t *testing.T) {
fmap, err := makeFunctionInfoMap(newTestOptions())
assert.Nil(t, err)
fis := []FunctionInfo{
{
Filename: "functions-for-testing-makeFunctionInfoMap.go",
LineNumber: "20",
Function: "functionAtLine20",
Receiver: "",
},
{
Filename: "functions-for-testing-makeFunctionInfoMap.go",
LineNumber: "26",
Function: "String",
Receiver: "methodReceiver",
},
}
for _, fi := range fis {
key := fi.key()
if assert.Contains(t, fmap, key) {
assert.Equal(t, fi, fmap[key])
}
}
}
func TestMakeFunctionInfoMapSupport(t *testing.T) {
// Test that the functions in functions-for-testing-makeFunctionInfoMap.go
// are correct so that other tests have known good data to work with.
assert.Equal(t, "This function is at line 20 to test makeFunctionInfoMap()", functionAtLine20())
mr := methodReceiver{}
assert.Equal(t, "This method has a methodReceiver receiver to test makeFunctionInfoMap()", mr.String())
}
func TestCaptureOutput(t *testing.T) {
output, err := captureOutput("cat", "/non-existent")
assert.Nil(t, output)
assert.ErrorContains(t, err, "cat: /non-existent: No such file or directory")
output, err = captureOutput("cat", "/etc/passwd")
assert.Nil(t, err)
rootLines := []string{}
for _, line := range output {
if strings.HasPrefix(line, "root:") {
rootLines = append(rootLines, line)
}
}
assert.Len(t, rootLines, 1)
}
func TestReadLineWithRetry_Success(t *testing.T) {
file, err := os.Open("go.mod")
assert.Nil(t, err)
line, err := readLineWithRetry(file)
assert.Nil(t, err)
assert.Equal(t, "module github.com/tobinjt/golang-coverage-check\n", line)
}
func TestReadLineWithRetry_EOF(t *testing.T) {
file, err := os.CreateTemp("", "TestReadLineWithRetry_EOF.*")
assert.Nil(t, err)
strCh := make(chan string)
errCh := make(chan error)
runMe := func() {
line, err := readLineWithRetry(file)
strCh <- line
errCh <- err
}
go runMe()
time.Sleep(3 * sleepTime)
length, err := file.WriteString("written to temp file\n")
assert.Nil(t, err)
assert.Greater(t, length, 10)
// Sync and seek back to the start so that the read in the other goroutine
// can complete.
err = file.Sync()
assert.Nil(t, err)
offset, err := file.Seek(0, 0)
assert.Nil(t, err)
assert.Equal(t, int64(0), offset)
line, err := <-strCh, <-errCh
assert.Nil(t, err)
assert.Equal(t, "written to temp file\n", line)
}
func TestReadLineWithRetry_Error(t *testing.T) {
file, err := os.CreateTemp("", "TestReadLineWithRetry_Error.*")
assert.Nil(t, err)
strCh := make(chan string)
errCh := make(chan error)
runMe := func() {
line, err := readLineWithRetry(file)
strCh <- line
errCh <- err
}
go runMe()
time.Sleep(3 * sleepTime)
file.Close()
line, err := <-strCh, <-errCh
assert.ErrorContains(t, err, "file already closed")
assert.Equal(t, "", line)
}
func TestGoCoverCapturePathSuccess(t *testing.T) {
options := newTestOptions()
options.captureOutput = captureOutput
coverageFile, err := options.createTemp("", "golang-coverage-check.*.coverage-data")
assert.Nil(t, err)
path, err := goCoverCapturePath(options, coverageFile.Name())
assert.Nil(t, err)
assert.Equal(t, 1, len(path))
}
func TestGoCoverCapturePath_CreateTempFailed(t *testing.T) {
options := newTestOptions()
options.createTemp = func(string, string) (*os.File, error) {
return nil, errors.New("createTemp failed")
}
path, err := goCoverCapturePath(options, "")
assert.Error(t, err)
assert.Nil(t, path)
}
func TestGoCoverCapturePath_CreateTempFailedSecondTime(t *testing.T) {
options := newTestOptions()
calledBefore := false
options.createTemp = func(dir, pattern string) (*os.File, error) {
if calledBefore {
return nil, errors.New("createTemp failed on second call")
}
calledBefore = true
return os.CreateTemp(dir, pattern)
}
path, err := goCoverCapturePath(options, "")
assert.Nil(t, path)
assert.ErrorContains(t, err, "createTemp failed on second call")
}
func TestGoCoverCapturePath_ReadingFileFailed(t *testing.T) {
options := newTestOptions()
options.captureOutput = func(command string, args ...string) ([]string, error) {
return nil, nil
}
options.readLineWithRetry = func(*os.File) (string, error) {
return "", errors.New("readLineWithRetry failed")
}
path, err := goCoverCapturePath(options, "")
assert.Nil(t, path)
assert.ErrorContains(t, err, "readLineWithRetry failed")
}
func TestGoCoverCapturePath_ChmodFailed(t *testing.T) {
options := newTestOptions()
options.chmod = func(*os.File, os.FileMode) error {
return errors.New("chmod failed")
}
path, err := goCoverCapturePath(options, "")
assert.Nil(t, path)
assert.ErrorContains(t, err, "chmod failed")
}
func TestGoCoverCapturePath_SetenvFailed(t *testing.T) {
options := newTestOptions()
options.setenv = func(string, string) error {
return errors.New("setenv failed")
}
path, err := goCoverCapturePath(options, "")
assert.Nil(t, path)
assert.ErrorContains(t, err, "setenv failed")
}
func TestGoCoverCapturePath_CaptureOutputFailed(t *testing.T) {
options := newTestOptions()
options.captureOutput = func(command string, args ...string) ([]string, error) {
return nil, errors.New("captureOutput failed")
}
path, err := goCoverCapturePath(options, "")
assert.Nil(t, path)
assert.ErrorContains(t, err, "captureOutput failed")
}
func TestGoCoverSuccess(t *testing.T) {
fakeOutput := map[string][]string{
"test --covermode set --coverprofile": {"ignored"},
"tool cover --func": {"expected return value"},
}
commandRun := map[string]bool{}
options := newTestOptions()
options.captureOutput = func(command string, args ...string) ([]string, error) {
// The random filename is always the last arg, so drop it.
parts := args[0 : len(args)-1]
key := strings.Join(parts, " ")
commandRun[key] = true
return fakeOutput[key], nil
}
actual, _, err := goCover(options)
assert.Nil(t, err)
assert.Equal(t, []string{"expected return value"}, actual)
assert.Equal(t, len(commandRun), 2)
assert.True(t, commandRun["test --covermode set --coverprofile"], commandRun)
assert.True(t, commandRun["tool cover --func"], commandRun)
}
func TestGoCoverBrowserFailure(t *testing.T) {
fakeOutput := map[string][]string{
"test --covermode set --coverprofile": {"ignored"},
}
fakeErrors := map[string]error{
"tool cover --html": fmt.Errorf("browser error"),
}
commandRun := map[string]bool{}
options := newTestOptions()
options.coverageHTML = htmlOpenInBrowser
options.captureOutput = func(command string, args ...string) ([]string, error) {
// The random filename is always the last arg, so drop it.
parts := args[0 : len(args)-1]
key := strings.Join(parts, " ")
commandRun[key] = true
return fakeOutput[key], fakeErrors[key]
}
actual, _, err := goCover(options)
assert.Error(t, err)
assert.Nil(t, actual)
assert.Equal(t, 2, len(commandRun), commandRun)
assert.True(t, commandRun["test --covermode set --coverprofile"], commandRun)
assert.True(t, commandRun["tool cover --html"], commandRun)
}
func TestGoCoverBrowser(t *testing.T) {
fakeOutput := map[string][]string{
"test --covermode set --coverprofile": {"ignored"},
"tool cover --func": {"expected return value"},
"tool cover --html": {"ignored"},
}
commandRun := map[string]bool{}
options := newTestOptions()
options.coverageHTML = htmlOpenInBrowser
options.captureOutput = func(command string, args ...string) ([]string, error) {
// The random filename is always the last arg, so drop it.
parts := args[0 : len(args)-1]
key := strings.Join(parts, " ")
commandRun[key] = true
return fakeOutput[key], nil
}
actual, _, err := goCover(options)
assert.Nil(t, err)
assert.Equal(t, []string{"expected return value"}, actual)
assert.Equal(t, 3, len(commandRun), commandRun)
assert.True(t, commandRun["test --covermode set --coverprofile"], commandRun)
assert.True(t, commandRun["tool cover --func"], commandRun)
assert.True(t, commandRun["tool cover --html"], commandRun)
}
func TestGoCoverPathFailure(t *testing.T) {
options := newTestOptions()
options.coverageHTML = htmlShowPath
options.captureOutput = func(command string, args ...string) ([]string, error) {
return nil, nil
}
options.readLineWithRetry = func(*os.File) (string, error) {
return "", errors.New("readLineWithRetry failed")
}
_, path, err := goCover(options)
assert.ErrorContains(t, err, "readLineWithRetry failed")
assert.Nil(t, path)
}
func TestGoCoverPath(t *testing.T) {
fakeOutput := map[string][]string{
"test --covermode set --coverprofile": {"ignored"},
"tool cover --func": {"expected return value"},
"tool cover --html": {"ignored"},
}
commandRun := map[string]bool{}
options := newTestOptions()
options.coverageHTML = htmlShowPath
options.captureOutput = func(command string, args ...string) ([]string, error) {
// The random filename is always the last arg, so drop it.
parts := args[0 : len(args)-1]
key := strings.Join(parts, " ")
commandRun[key] = true
return fakeOutput[key], nil
}
options.readLineWithRetry = func(*os.File) (string, error) {
return "this is the fake path", nil
}
_, path, err := goCover(options)
assert.Nil(t, err)
assert.Equal(t, []string{"this is the fake path"}, path)
assert.Equal(t, 3, len(commandRun), commandRun)
assert.True(t, commandRun["test --covermode set --coverprofile"], commandRun)
assert.True(t, commandRun["tool cover --func"], commandRun)
assert.True(t, commandRun["tool cover --html"], commandRun)
}
func TestGoCoverCaptureFailure(t *testing.T) {
options := newTestOptions()
options.captureOutput = func(string, ...string) ([]string, error) {
return []string{"this should not be seen"}, errors.New("error for testing")
}
actual, _, err := goCover(options)
assert.Nil(t, actual)
assert.ErrorContains(t, err, "error for testing")
}
func TestGoCoverCreateTempFailure(t *testing.T) {
options := newTestOptions()
options.createTemp = func(string, string) (*os.File, error) {
return nil, errors.New("error for testing")
}
actual, _, err := goCover(options)
assert.Nil(t, actual)
assert.ErrorContains(t, err, "error for testing")
}
func validCoverageOutput() []string {
coverage := `
github.com/tobinjt/golang-coverage-check/golang-coverage-check.go:26: String 100.0%
github.com/tobinjt/golang-coverage-check/golang-coverage-check.go:48: String 31.0%
github.com/tobinjt/golang-coverage-check/golang-coverage-check.go:53: makeExampleConfig 50.0%
github.com/tobinjt/golang-coverage-check/golang-coverage-check.go:95: parseYAMLConfig 100.0%
github.com/tobinjt/golang-coverage-check/golang-coverage-check.go:118: realMain 17.3%
github.com/tobinjt/golang-coverage-check/golang-coverage-check.go:140: main 0.0%
total: (statements) 38.1%
`
return strings.Split(coverage, "\n")
}
func TestParseCoverageOutputSuccess(t *testing.T) {
options := newTestOptions()
options.modulePath = "github.com/tobinjt/golang-coverage-check/"
results, err := parseCoverageOutput(options, validCoverageOutput())
assert.Nil(t, err)
assert.Equal(t, 6, len(results))
expected := []CoverageLine{
{
Filename: "golang-coverage-check.go",
LineNumber: "26",
Function: "String",
Coverage: 100.0,
},
{
Filename: "golang-coverage-check.go",
LineNumber: "48",
Function: "String",
Coverage: 31.0,
},
{
Filename: "golang-coverage-check.go",
LineNumber: "53",
Function: "makeExampleConfig",
Coverage: 50.0,
},
{
Filename: "golang-coverage-check.go",
LineNumber: "95",
Function: "parseYAMLConfig",
Coverage: 100.0,
},
{
Filename: "golang-coverage-check.go",
LineNumber: "118",
Function: "realMain",
Coverage: 17.3,
},
{
Filename: "golang-coverage-check.go",
LineNumber: "140",
Function: "main",
Coverage: 0.0,
},
}
assert.Equal(t, expected, results)
}
func TestParseCoverageOutputFailure(t *testing.T) {
options := newTestOptions()
badInputLine := `
github.com/.../golang-coverage-check.go:26: String 100.0%
asdf
github.com/.../golang-coverage-check.go:140: main 0.0%
total: (statements) 38.1%
`
_, err := parseCoverageOutput(options, strings.Split(badInputLine, "\n"))
assert.ErrorContains(t, err, "expected 3 parts, found 1")
badInputLine = `missing-line-number: String 100.0%`
_, err = parseCoverageOutput(options, []string{badInputLine})
assert.ErrorContains(t, err, "expected `filename:linenumber:` in \"missing-line-number:\"")
table := []struct {
input string
err string
}{
{
err: "could not extract percentage from",
input: "1.2",
},
{
err: "could not extract percentage from",
input: "qwerty",
},
{
err: "strconv.ParseFloat: parsing",
input: "asdf%",
},
{
err: "percentage (-12.2) < 0",
input: "-12.2%",
},
{
err: "percentage (105.3) > 100",
input: "105.3%",
},
}
for _, test := range table {
input := fmt.Sprintf("foo.go:26: String %s", test.input)
_, err := parseCoverageOutput(options, []string{input})
assert.ErrorContains(t, err, test.err)
}
}
func stripComments(input []string) []string {
output := []string{}
for _, line := range input {
if !strings.HasPrefix(line, "//") {
output = append(output, line)
}
}
return output
}
func TestCheckCoverage(t *testing.T) {
tests := []struct {
desc string
config Config
fInfoMap FunctionInfoMap
input []string
errors []string
debug []string
}{
{
desc: "Filename matching",
config: Config{
Rules: []Rule{
{
FilenameRegex: "^utils.go$",
Coverage: 100,
},
},
},
input: []string{
"// Matches, insufficient coverage.",
"utils.go:1: ReadFileOrDie 57.0%",
"// Matches, sufficient coverage.",
"utils.go:2: ParseIntOrDie 100.0%",
"// Doesn't match, falls through to default.",
"main.go:1: main 22.0%",
},
errors: []string{
"utils.go:1:\tReadFileOrDie\t57.0%: actual coverage 57.0% < required coverage 100.0%: matching rule",
"matching rule is `FilenameRegex: ^utils.go$ FunctionRegex: ReceiverRegex: Coverage: 100 Comment: `",
},
debug: []string{
// First coverage line.
"Debug info for coverage matching",
"Line utils.go:1:\tReadFileOrDie\t57.0%\n",
"Matching rule: FilenameRegex: ^utils.go$ FunctionRegex: ReceiverRegex: Coverage: 100",
"actual coverage 57.0% < required coverage 100.0%",
// Second coverage line.
"Line utils.go:2:\tParseIntOrDie\t100.0%",
"Matching rule: FilenameRegex: ^utils.go$ FunctionRegex: ReceiverRegex: Coverage: 100 Comment:",
"actual coverage 100.0% >= required coverage 100.0%",
// Third coverage line.
"Line main.go:1:\tmain\t22.0%",
"Default coverage 0.0% satisfied",
},
},
{
desc: "Function matching",
config: Config{
Rules: []Rule{
{
FunctionRegex: "OrDie$",
Coverage: 100,
},
},
},
input: []string{
"// Matches, insufficient coverage.",
"utils.go:1: ReadFileOrDie 57.0%",
"// Matches, sufficient coverage.",
"utils.go:2: ParseIntOrDie 100.0%",
"// Doesn't match, falls through to default.",
"main.go:1: main 100.0%",
},
errors: []string{
"utils.go:1:\tReadFileOrDie\t57.0%: actual coverage 57.0% < required coverage 100.0%: matching rule",
"matching rule is `FilenameRegex: FunctionRegex: OrDie$ ReceiverRegex: Coverage: 100 Comment: `",
},
debug: []string{
// First coverage line.
"Debug info for coverage matching",
"Line utils.go:1:\tReadFileOrDie\t57.0%\n",
"Matching rule: FilenameRegex: FunctionRegex: OrDie$ ReceiverRegex: Coverage: 100",
"actual coverage 57.0% < required coverage 100.0%",
// Second coverage line.
"Line utils.go:2:\tParseIntOrDie\t100.0%",
"Matching rule: FilenameRegex: FunctionRegex: OrDie$ ReceiverRegex: Coverage: 100 Comment:",
"actual coverage 100.0% >= required coverage 100.0%",
// Third coverage line.
"Line main.go:1:\tmain\t100.0%",
"Default coverage 0.0% satisfied",
},
},
{
desc: "Receiver matching",
config: Config{
Rules: []Rule{
{
ReceiverRegex: "^testReceiver$",
Coverage: 100,
},
},
},
input: []string{
"// Matches, insufficient coverage.",
"utils.go:1: Commit 57.0%",
"// Matches, sufficient coverage.",
"utils.go:2: String 100.0%",
"// Doesn't match, falls through to default.",
"main.go:1: main 100.0%",
},
fInfoMap: FunctionInfoMap{
"utils.go:1": {
Filename: "utils.go",
LineNumber: "1",
Function: "Commit",
Receiver: "testReceiver",
},
"utils.go:2": {
Filename: "utils.go",
LineNumber: "2",
Function: "String",
Receiver: "testReceiver",
},
},
errors: []string{
"utils.go:1:\tCommit\t57.0%: actual coverage 57.0% < required coverage 100.0%: matching rule",
"matching rule is `FilenameRegex: FunctionRegex: ReceiverRegex: ^testReceiver$ Coverage: 100 Comment: `",
},
debug: []string{
// First coverage line.
"Debug info for coverage matching",
"Line utils.go:1:\tCommit\t57.0%\n",
"Matching rule: FilenameRegex: FunctionRegex: ReceiverRegex: ^testReceiver$ Coverage: 100",
"actual coverage 57.0% < required coverage 100.0%",
// Second coverage line.
"Line utils.go:2:\tString\t100.0%",
"Matching rule: FilenameRegex: FunctionRegex: ReceiverRegex: ^testReceiver$ Coverage: 100",
"actual coverage 100.0% >= required coverage 100.0%",
// Third coverage line.
"Line main.go:1:\tmain\t100.0%",
"Default coverage 0.0% satisfied",
},
},
{
desc: "Filename, Function, and Receiver matching",
config: Config{
Rules: []Rule{
{
FilenameRegex: "^utils.go$",
FunctionRegex: "^Commit$",
ReceiverRegex: "^testReceiver$",
Coverage: 100,
},
{
FilenameRegex: "^utils.go$",
FunctionRegex: "^String$",
ReceiverRegex: "^testReceiver$",
Coverage: 100,
},
},
},
input: []string{
"// Matches, insufficient coverage.",
"utils.go:1: Commit 57.0%",
"// Matches, sufficient coverage.",
"utils.go:2: String 100.0%",
"// Doesn't match, falls through to default.",
"main.go:1: main 100.0%",
},
fInfoMap: FunctionInfoMap{
"utils.go:1": {
Filename: "utils.go",
LineNumber: "1",
Function: "Commit",
Receiver: "testReceiver",
},
"utils.go:2": {
Filename: "utils.go",
LineNumber: "2",
Function: "String",
Receiver: "testReceiver",
},
},
errors: []string{
"utils.go:1:\tCommit\t57.0%: actual coverage 57.0% < required coverage 100.0%: matching rule",
"matching rule is `FilenameRegex: ^utils.go$ FunctionRegex: ^Commit$ ReceiverRegex: ^testReceiver$ Coverage: 100",
},
debug: []string{
// First coverage line.
"Debug info for coverage matching",
"Line utils.go:1:\tCommit\t57.0%\n",
"Matching rule: FilenameRegex: ^utils.go$ FunctionRegex: ^Commit$ ReceiverRegex: ^testReceiver$ Coverage: 100",
"actual coverage 57.0% < required coverage 100.0%",
// Second coverage line.
"Line utils.go:2:\tString\t100.0%",
"Matching rule: FilenameRegex: ^utils.go$ FunctionRegex: ^String$ ReceiverRegex: ^testReceiver$ Coverage: 100",
"actual coverage 100.0% >= required coverage 100.0%",
// Third coverage line.
"Line main.go:1:\tmain\t100.0%",
"Default coverage 0.0% satisfied",
},
},
{
desc: "Default coverage",
config: Config{
DefaultCoverage: 90,
},
input: []string{
"// Insufficient coverage.",
"utils.go:1: ReadFileOrDie 57.0%",
"// Sufficient coverage.",
"utils.go:2: ParseIntOrDie 100.0%",
},
errors: []string{
"utils.go:1:\tReadFileOrDie\t57.0%: actual coverage 57.0% < default coverage 90.0%",
},
debug: []string{
// First coverage line.
"Debug info for coverage matching",
"Line utils.go:1:\tReadFileOrDie\t57.0%\n",
"Default coverage 90.0% not satisfied",
// Second coverage line.
"Line utils.go:2:\tParseIntOrDie\t100.0%",
"Default coverage 90.0% satisfied",
},
},
{
desc: "No errors",
config: Config{
DefaultCoverage: 90,
},
input: []string{
"// Sufficient coverage.",
"utils.go:2: ParseIntOrDie 100.0%",
},
errors: []string{},
debug: []string{
// First coverage line.
"Line utils.go:2:\tParseIntOrDie\t100.0%",
"Default coverage 90.0% satisfied",
},
},
}
options := newTestOptions()
for _, test := range tests {
coverage, err := parseCoverageOutput(options, stripComments(test.input))
assert.Nil(t, err)
config, err := validateConfig(test.config)
assert.Nil(t, err)
debug, err := checkCoverage(config, coverage, test.fInfoMap)
if len(test.errors) == 0 {
assert.Nil(t, err)
} else {
for i := range test.errors {
assert.ErrorContains(t, err, test.errors[i], "err: "+test.desc)
}
}
debugStr := strings.Join(debug, "\n")
for i := range test.debug {
assert.Contains(t, debugStr, test.debug[i], "debug: "+test.desc)
}
}
}
func TestValidateFlags(t *testing.T) {
table := []struct {
desc string
err string
mod func(opts Options) Options
}{
{
desc: "good arguments",
err: "",
mod: func(opts Options) Options {
return opts
},
},
{
desc: "bad argument to --coverage_html",
err: "unrecognised option for flag --coverage_html: \"rejected\"; valid options are an empty string, \"browser\", or \"path\"",
mod: func(opts Options) Options {
opts.coverageHTML = "rejected"
return opts
},
},
{
desc: "unexpected arguments",
err: "unexpected arguments",
mod: func(opts Options) Options {
opts.parsedArgs = []string{"asdf", "1234"}
return opts
},
},