| 1 |
// Licensed under the MIT license, see LICENSE file for details. |
| 2 |
|
| 3 |
//go:build go1.14 |
| 4 |
// +build go1.14 |
| 5 |
|
| 6 |
package quicktest_test |
| 7 |
|
| 8 |
import ( |
| 9 |
"testing" |
| 10 |
|
| 11 |
qt "github.com/frankban/quicktest" |
| 12 |
) |
| 13 |
|
| 14 |
// This file defines tests that are only valid since the Cleanup |
| 15 |
// method was added in Go 1.14. |
| 16 |
|
| 17 |
func TestCCleanup(t *testing.T) { |
| 18 |
c := qt.New(t) |
| 19 |
cleanups := 0 |
| 20 |
c.Run("defer", func(c *qt.C) { |
| 21 |
c.Cleanup(func() { |
| 22 |
cleanups++ |
| 23 |
}) |
| 24 |
}) |
| 25 |
c.Assert(cleanups, qt.Equals, 1) |
| 26 |
} |
| 27 |
|
| 28 |
func TestCDeferWithoutDone(t *testing.T) { |
| 29 |
c := qt.New(t) |
| 30 |
tc := &testingTWithCleanup{ |
| 31 |
TB: t, |
| 32 |
cleanup: func() {}, |
| 33 |
} |
| 34 |
c1 := qt.New(tc) |
| 35 |
c1.Defer(func() {}) |
| 36 |
c1.Defer(func() {}) |
| 37 |
c.Assert(tc.cleanup, qt.PanicMatches, `Done not called after Defer`) |
| 38 |
} |
| 39 |
|
| 40 |
func TestCDeferFromDefer(t *testing.T) { |
| 41 |
c := qt.New(t) |
| 42 |
tc := &testingTWithCleanup{ |
| 43 |
TB: t, |
| 44 |
cleanup: func() {}, |
| 45 |
} |
| 46 |
c1 := qt.New(tc) |
| 47 |
c1.Defer(func() { |
| 48 |
c1.Log("defer 1") |
| 49 |
// This defer is triggered from the first Done(). |
| 50 |
// It should have its own Done() call too. |
| 51 |
c1.Defer(func() { |
| 52 |
c1.Log("defer 2") |
| 53 |
}) |
| 54 |
}) |
| 55 |
c1.Done() |
| 56 |
// Check that we report the missing second Done(). |
| 57 |
c.Assert(tc.cleanup, qt.PanicMatches, `Done not called after Defer`) |
| 58 |
} |
| 59 |
|
| 60 |
func TestCDeferVsCleanupOrder(t *testing.T) { |
| 61 |
c := qt.New(t) |
| 62 |
var defers []int |
| 63 |
c.Run("subtest", func(c *qt.C) { |
| 64 |
c.Defer(func() { |
| 65 |
defers = append(defers, 0) |
| 66 |
}) |
| 67 |
c.Cleanup(func() { |
| 68 |
defers = append(defers, 1) |
| 69 |
}) |
| 70 |
c.Defer(func() { |
| 71 |
defers = append(defers, 2) |
| 72 |
}) |
| 73 |
c.Cleanup(func() { |
| 74 |
defers = append(defers, 3) |
| 75 |
}) |
| 76 |
}) |
| 77 |
c.Assert(defers, qt.DeepEquals, []int{3, 2, 1, 0}) |
| 78 |
} |
| 79 |
|
| 80 |
type testingTWithCleanup struct { |
| 81 |
testing.TB |
| 82 |
cleanup func() |
| 83 |
} |
| 84 |
|
| 85 |
func (t *testingTWithCleanup) Cleanup(f func()) { |
| 86 |
oldCleanup := t.cleanup |
| 87 |
t.cleanup = func() { |
| 88 |
defer oldCleanup() |
| 89 |
f() |
| 90 |
} |
| 91 |
} |