|
| 1 | +package coverage |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + "testing" |
| 6 | +) |
| 7 | + |
| 8 | +func mockExit(t *testing.T, code int) func(int) { |
| 9 | + t.Helper() |
| 10 | + |
| 11 | + return func(c int) { |
| 12 | + if code != c { |
| 13 | + t.Errorf("[expected]: %d \n[received]:%d\n", code, c) |
| 14 | + } |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +type mockTestingM struct { |
| 19 | + code int |
| 20 | +} |
| 21 | + |
| 22 | +func (m mockTestingM) Run() int { |
| 23 | + return m.code |
| 24 | +} |
| 25 | + |
| 26 | +func TestCoverage(t *testing.T) { |
| 27 | + t.Run("should run tests successfully", func(t *testing.T) { |
| 28 | + exitFunc = mockExit(t, 0) |
| 29 | + coverModeFunc = func() string { return "mock-mode" } |
| 30 | + coverageFunc = func() float64 { return 1 } |
| 31 | + m := mockTestingM{code: 0} |
| 32 | + |
| 33 | + Run(m, 100) |
| 34 | + }) |
| 35 | + |
| 36 | + t.Run("should fail if no cover enabled", func(t *testing.T) { |
| 37 | + exitFunc = mockExit(t, 1) |
| 38 | + coverModeFunc = func() string { return "" } |
| 39 | + coverageFunc = func() float64 { return 1 } |
| 40 | + m := mockTestingM{code: 0} |
| 41 | + s := strings.Builder{} |
| 42 | + writer = &s |
| 43 | + |
| 44 | + Run(m, 100) |
| 45 | + if s.String() != "\nFAIL coverage is not enabled. You can enable by using `-cover`\n\n" { |
| 46 | + t.Errorf("expected coverage not enabled msg but got: %s\f", s.String()) |
| 47 | + } |
| 48 | + }) |
| 49 | + |
| 50 | + t.Run("should fail if coverage is not met", func(t *testing.T) { |
| 51 | + exitFunc = mockExit(t, 1) |
| 52 | + coverModeFunc = func() string { return "mock-mode" } |
| 53 | + coverageFunc = func() float64 { return 0.5 } |
| 54 | + m := mockTestingM{code: 0} |
| 55 | + s := strings.Builder{} |
| 56 | + writer = &s |
| 57 | + |
| 58 | + Run(m, 51) |
| 59 | + if s.String() != "\nFAIL Coverage threshold not met 51.0 >= 50.0 for coverage.TestCoverage\n\n" { |
| 60 | + t.Errorf("expected coverage threshold error but got: %s\n", s.String()) |
| 61 | + } |
| 62 | + }) |
| 63 | + |
| 64 | + t.Run("should call callback funcs", func(t *testing.T) { |
| 65 | + exitFunc = mockExit(t, 0) |
| 66 | + coverModeFunc = func() string { return "mock-mode" } |
| 67 | + coverageFunc = func() float64 { return 1 } |
| 68 | + m := mockTestingM{code: 0} |
| 69 | + called := 0 |
| 70 | + |
| 71 | + Run(m, 100, func() { |
| 72 | + called++ |
| 73 | + }) |
| 74 | + |
| 75 | + if called != 1 { |
| 76 | + t.Errorf("callback expected to be called once but called: %d\n", called) |
| 77 | + } |
| 78 | + }) |
| 79 | +} |
0 commit comments