|
4 | 4 |
|
5 | 5 | package testing
|
6 | 6 |
|
| 7 | +import ( |
| 8 | + "bytes" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +// See also TestBenchmarkBLoop* in other files. |
| 13 | + |
7 | 14 | func TestBenchmarkBLoop(t *T) {
|
8 | 15 | var initialStart highPrecisionTime
|
9 | 16 | var firstStart highPrecisionTime
|
@@ -68,4 +75,57 @@ func TestBenchmarkBLoop(t *T) {
|
68 | 75 | }
|
69 | 76 | }
|
70 | 77 |
|
71 |
| -// See also TestBenchmarkBLoop* in other files. |
| 78 | +func TestBenchmarkBLoopBreak(t *T) { |
| 79 | + var bState *B |
| 80 | + var bLog bytes.Buffer |
| 81 | + bRet := Benchmark(func(b *B) { |
| 82 | + // The Benchmark function provides no access to the failure state and |
| 83 | + // discards the log, so capture the B and save its log. |
| 84 | + bState = b |
| 85 | + b.common.w = &bLog |
| 86 | + |
| 87 | + for i := 0; b.Loop(); i++ { |
| 88 | + if i == 2 { |
| 89 | + break |
| 90 | + } |
| 91 | + } |
| 92 | + }) |
| 93 | + if !bState.failed { |
| 94 | + t.Errorf("benchmark should have failed") |
| 95 | + } |
| 96 | + const wantLog = "benchmark function returned without B.Loop" |
| 97 | + if log := bLog.String(); !strings.Contains(log, wantLog) { |
| 98 | + t.Errorf("missing error %q in output:\n%s", wantLog, log) |
| 99 | + } |
| 100 | + // A benchmark that exits early should not report its target iteration count |
| 101 | + // because it's not meaningful. |
| 102 | + if bRet.N != 0 { |
| 103 | + t.Errorf("want N == 0, got %d", bRet.N) |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +func TestBenchmarkBLoopError(t *T) { |
| 108 | + // Test that a benchmark that exits early because of an error doesn't *also* |
| 109 | + // complain that the benchmark exited early. |
| 110 | + var bState *B |
| 111 | + var bLog bytes.Buffer |
| 112 | + bRet := Benchmark(func(b *B) { |
| 113 | + bState = b |
| 114 | + b.common.w = &bLog |
| 115 | + |
| 116 | + for i := 0; b.Loop(); i++ { |
| 117 | + b.Error("error") |
| 118 | + return |
| 119 | + } |
| 120 | + }) |
| 121 | + if !bState.failed { |
| 122 | + t.Errorf("benchmark should have failed") |
| 123 | + } |
| 124 | + const noWantLog = "benchmark function returned without B.Loop" |
| 125 | + if log := bLog.String(); strings.Contains(log, noWantLog) { |
| 126 | + t.Errorf("unexpected error %q in output:\n%s", noWantLog, log) |
| 127 | + } |
| 128 | + if bRet.N != 0 { |
| 129 | + t.Errorf("want N == 0, got %d", bRet.N) |
| 130 | + } |
| 131 | +} |
0 commit comments