From 858080fbab9209e4bc8f2587a0377a964d844be7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Olivier=20Mengu=C3=A9?= Date: Thu, 9 Nov 2023 01:07:57 +0100 Subject: [PATCH] assert: more unsafe.Pointer tests 1. Isolate tests that use the "unsafe" package in a separate package assert/internal/unsafetests. That way the assert package is not tainted with unsafe. 2. Remove one reference to the private assert.isNil() in assert tests. 3. Add more tests of assert.Nil and assert.NotNil with unsafe.Pointer. --- assert/assertions_test.go | 8 ----- assert/internal/unsafetests/doc.go | 4 +++ .../internal/unsafetests/unsafetests_test.go | 34 +++++++++++++++++++ 3 files changed, 38 insertions(+), 8 deletions(-) create mode 100644 assert/internal/unsafetests/doc.go create mode 100644 assert/internal/unsafetests/unsafetests_test.go diff --git a/assert/assertions_test.go b/assert/assertions_test.go index d2a25c245..61577e50c 100644 --- a/assert/assertions_test.go +++ b/assert/assertions_test.go @@ -16,7 +16,6 @@ import ( "strings" "testing" "time" - "unsafe" ) var ( @@ -3138,10 +3137,3 @@ func TestErrorAs(t *testing.T) { }) } } - -func TestIsNil(t *testing.T) { - var n unsafe.Pointer = nil - if !isNil(n) { - t.Fatal("fail") - } -} diff --git a/assert/internal/unsafetests/doc.go b/assert/internal/unsafetests/doc.go new file mode 100644 index 000000000..08172d511 --- /dev/null +++ b/assert/internal/unsafetests/doc.go @@ -0,0 +1,4 @@ +// This package exists just to isolate tests that reference the [unsafe] package. +// +// The tests in this package are totally safe. +package unsafetests diff --git a/assert/internal/unsafetests/unsafetests_test.go b/assert/internal/unsafetests/unsafetests_test.go new file mode 100644 index 000000000..b7f01a660 --- /dev/null +++ b/assert/internal/unsafetests/unsafetests_test.go @@ -0,0 +1,34 @@ +package unsafetests_test + +import ( + "fmt" + "testing" + "unsafe" + + "github.com/stretchr/testify/assert" +) + +type ignoreTestingT struct{} + +var _ assert.TestingT = ignoreTestingT{} + +func (ignoreTestingT) Helper() {} + +func (ignoreTestingT) Errorf(format string, args ...interface{}) { + // Run the formatting, but ignore the result + msg := fmt.Sprintf(format, args...) + _ = msg +} + +func TestUnsafePointers(t *testing.T) { + var ignore ignoreTestingT + + assert.True(t, assert.Nil(t, unsafe.Pointer(nil), "unsafe.Pointer(nil) is nil")) + assert.False(t, assert.NotNil(ignore, unsafe.Pointer(nil), "unsafe.Pointer(nil) is nil")) + + assert.True(t, assert.Nil(t, unsafe.Pointer((*int)(nil)), "unsafe.Pointer((*int)(nil)) is nil")) + assert.False(t, assert.NotNil(ignore, unsafe.Pointer((*int)(nil)), "unsafe.Pointer((*int)(nil)) is nil")) + + assert.False(t, assert.Nil(ignore, unsafe.Pointer(new(int)), "unsafe.Pointer(new(int)) is NOT nil")) + assert.True(t, assert.NotNil(t, unsafe.Pointer(new(int)), "unsafe.Pointer(new(int)) is NOT nil")) +}