Skip to content

Commit cfb7d2d

Browse files
fernandez14elliotcourant
authored andcommitted
add test
1 parent 6cfb6f4 commit cfb7d2d

File tree

2 files changed

+67
-1
lines changed

2 files changed

+67
-1
lines changed

extra/pgotel/pgotel.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ func (h *TracingHook) AfterQuery(ctx context.Context, evt *pg.QueryEvent) error
126126
span.RecordError(evt.Err)
127127
span.SetStatus(codes.Error, evt.Err.Error())
128128
}
129-
} else if evt.Result != nil && (reflect.ValueOf(evt.Result).Kind() != reflect.Ptr || !reflect.ValueOf(evt.Result).IsNil()) {
129+
} else if hasResults(evt) {
130130
numRow := evt.Result.RowsAffected()
131131
if numRow == 0 {
132132
numRow = evt.Result.RowsReturned()
@@ -139,6 +139,10 @@ func (h *TracingHook) AfterQuery(ctx context.Context, evt *pg.QueryEvent) error
139139
return nil
140140
}
141141

142+
func hasResults(evt *pg.QueryEvent) bool {
143+
return evt.Result != nil && (reflect.ValueOf(evt.Result).Kind() != reflect.Ptr || !reflect.ValueOf(evt.Result).IsNil())
144+
}
145+
142146
func funcFileLine(pkg string) (string, string, int) {
143147
const depth = 16
144148
var pcs [depth]uintptr

extra/pgotel/pgotel_test.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package pgotel
2+
3+
import (
4+
"testing"
5+
6+
"github.com/go-pg/pg/v10"
7+
"github.com/go-pg/pg/v10/orm"
8+
)
9+
10+
// mockResult is a mock implementation of the Result interface
11+
type mockResult struct {
12+
model orm.Model
13+
rowsAffected int
14+
rowsReturned int
15+
}
16+
17+
func (m mockResult) Model() orm.Model {
18+
return m.model
19+
}
20+
21+
func (m mockResult) RowsAffected() int {
22+
return m.rowsAffected
23+
}
24+
25+
func (m mockResult) RowsReturned() int {
26+
return m.rowsReturned
27+
}
28+
29+
func TestHasResults(t *testing.T) {
30+
// Define test cases
31+
testCases := []struct {
32+
name string
33+
event *pg.QueryEvent
34+
expected bool
35+
}{
36+
{
37+
name: "Nil Result",
38+
event: &pg.QueryEvent{Result: nil},
39+
expected: false,
40+
},
41+
{
42+
name: "Nil Pointer Result",
43+
event: &pg.QueryEvent{Result: (*mockResult)(nil)},
44+
expected: false,
45+
},
46+
{
47+
name: "Non-Nil Result",
48+
event: &pg.QueryEvent{Result: mockResult{rowsAffected: 1, rowsReturned: 1}},
49+
expected: true,
50+
},
51+
}
52+
53+
// Run test cases
54+
for _, tc := range testCases {
55+
t.Run(tc.name, func(t *testing.T) {
56+
result := hasResults(tc.event)
57+
if result != tc.expected {
58+
t.Errorf("hasResults(%v) = %v, want %v", tc.event, result, tc.expected)
59+
}
60+
})
61+
}
62+
}

0 commit comments

Comments
 (0)