|
| 1 | +package require |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + assert "github.com/stretchr/testify/assert" |
| 7 | +) |
| 8 | + |
| 9 | +func TestNilPtr(t *testing.T) { |
| 10 | + t.Run("should accept nil pointer & return nil", func(t *testing.T) { |
| 11 | + var nilPtr *int |
| 12 | + assert.Nil(t, NilPtr("Test pointer", nilPtr)) |
| 13 | + }) |
| 14 | + t.Run("should panic when pointer is not nil", func(t *testing.T) { |
| 15 | + assert.PanicsWithValue(t, "assertion failed: Test pointer should be a nil pointer", func() { |
| 16 | + value := "test" |
| 17 | + NilPtr("Test pointer", &value) |
| 18 | + }) |
| 19 | + }) |
| 20 | + t.Run("should use given name in panic message", func(t *testing.T) { |
| 21 | + assert.PanicsWithValue(t, "assertion failed: Other pointer should be a nil pointer", func() { |
| 22 | + value := 42 |
| 23 | + NilPtr("Other pointer", &value) |
| 24 | + }) |
| 25 | + }) |
| 26 | +} |
| 27 | + |
| 28 | +func TestNotNilPtr(t *testing.T) { |
| 29 | + t.Run("should accept not-nil pointer & return same pointer", func(t *testing.T) { |
| 30 | + value := 42 |
| 31 | + assert.Same(t, &value, NotNilPtr("Test pointer", &value)) |
| 32 | + }) |
| 33 | + t.Run("should panic when pointer is nil", func(t *testing.T) { |
| 34 | + assert.PanicsWithValue(t, "assertion failed: Test pointer should not be a nil pointer", func() { |
| 35 | + var nilPtr *string |
| 36 | + NotNilPtr("Test pointer", nilPtr) |
| 37 | + }) |
| 38 | + }) |
| 39 | + t.Run("should use given name in panic message", func(t *testing.T) { |
| 40 | + assert.PanicsWithValue(t, "assertion failed: Other pointer should not be a nil pointer", func() { |
| 41 | + var nilPtr *float64 |
| 42 | + NotNilPtr("Other pointer", nilPtr) |
| 43 | + }) |
| 44 | + }) |
| 45 | +} |
| 46 | + |
| 47 | +func BenchmarkNilPtr(b *testing.B) { |
| 48 | + var nilPtr *int |
| 49 | + b.ResetTimer() |
| 50 | + for i := 0; i < b.N; i++ { |
| 51 | + NilPtr("Benchmark pointer", nilPtr) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +func BenchmarkNotNilPtr(b *testing.B) { |
| 56 | + value := "benchmark" |
| 57 | + b.ResetTimer() |
| 58 | + for i := 0; i < b.N; i++ { |
| 59 | + NotNilPtr("Benchmark pointer", &value) |
| 60 | + } |
| 61 | +} |
0 commit comments