Source file
src/runtime/cgo/handle_test.go
1
2
3
4
5 package cgo
6
7 import (
8 "reflect"
9 "testing"
10 )
11
12 func TestHandle(t *testing.T) {
13 v := 42
14
15 tests := []struct {
16 v1 any
17 v2 any
18 }{
19 {v1: v, v2: v},
20 {v1: &v, v2: &v},
21 {v1: nil, v2: nil},
22 }
23
24 for _, tt := range tests {
25 h1 := NewHandle(tt.v1)
26 h2 := NewHandle(tt.v2)
27
28 if uintptr(h1) == 0 || uintptr(h2) == 0 {
29 t.Fatalf("NewHandle returns zero")
30 }
31
32 if uintptr(h1) == uintptr(h2) {
33 t.Fatalf("Duplicated Go values should have different handles, but got equal")
34 }
35
36 h1v := h1.Value()
37 h2v := h2.Value()
38 if !reflect.DeepEqual(h1v, h2v) || !reflect.DeepEqual(h1v, tt.v1) {
39 t.Fatalf("Value of a Handle got wrong, got %+v %+v, want %+v", h1v, h2v, tt.v1)
40 }
41
42 h1.Delete()
43 h2.Delete()
44 }
45
46 siz := 0
47 handles.Range(func(k, v any) bool {
48 siz++
49 return true
50 })
51 if siz != 0 {
52 t.Fatalf("handles are not cleared, got %d, want %d", siz, 0)
53 }
54 }
55
56 func TestInvalidHandle(t *testing.T) {
57 t.Run("zero", func(t *testing.T) {
58 h := Handle(0)
59
60 defer func() {
61 if r := recover(); r != nil {
62 return
63 }
64 t.Fatalf("Delete of zero handle did not trigger a panic")
65 }()
66
67 h.Delete()
68 })
69
70 t.Run("invalid", func(t *testing.T) {
71 h := NewHandle(42)
72
73 defer func() {
74 if r := recover(); r != nil {
75 h.Delete()
76 return
77 }
78 t.Fatalf("Invalid handle did not trigger a panic")
79 }()
80
81 Handle(h + 1).Delete()
82 })
83 }
84
85 func BenchmarkHandle(b *testing.B) {
86 b.Run("non-concurrent", func(b *testing.B) {
87 for i := 0; i < b.N; i++ {
88 h := NewHandle(i)
89 _ = h.Value()
90 h.Delete()
91 }
92 })
93 b.Run("concurrent", func(b *testing.B) {
94 b.RunParallel(func(pb *testing.PB) {
95 var v int
96 for pb.Next() {
97 h := NewHandle(v)
98 _ = h.Value()
99 h.Delete()
100 }
101 })
102 })
103 }
104
View as plain text