Skip to content

Commit 16cc8bc

Browse files
test: add pointer_test.go
* Added tests and benchmarks for funcs NilPtr() & NotNilPtr() * Changed lefthook.yml to run golangci-lint over all files.
1 parent a25ce3d commit 16cc8bc

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed

lefthook.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,4 @@ pre-commit:
1515

1616
lint:
1717
glob: "*.go"
18-
run: golangci-lint run --fix {staged_files}
18+
run: golangci-lint run --fix

pointer_test.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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

Comments
 (0)