|
| 1 | +package jsonrpc |
| 2 | + |
| 3 | +import ( |
| 4 | + "reflect" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/stretchr/testify/require" |
| 8 | +) |
| 9 | + |
| 10 | +// Define a custom error type for testing |
| 11 | +type PointerReceiverError struct { |
| 12 | + Message string |
| 13 | +} |
| 14 | + |
| 15 | +func (e *PointerReceiverError) Error() string { |
| 16 | + return e.Message |
| 17 | +} |
| 18 | + |
| 19 | +type ValueReceiverError struct { |
| 20 | + Message string |
| 21 | +} |
| 22 | + |
| 23 | +func (e ValueReceiverError) Error() string { |
| 24 | + return e.Message |
| 25 | +} |
| 26 | + |
| 27 | +// Another custom error type |
| 28 | +type AnotherTestError struct { |
| 29 | + Detail string |
| 30 | +} |
| 31 | + |
| 32 | +func (e *AnotherTestError) Error() string { |
| 33 | + return e.Detail |
| 34 | +} |
| 35 | + |
| 36 | +// Non-error type for negative testing |
| 37 | +type NotAnError struct { |
| 38 | + Field string |
| 39 | +} |
| 40 | + |
| 41 | +func TestNewErrors(t *testing.T) { |
| 42 | + errs := NewErrors() |
| 43 | + |
| 44 | + if errs.byType == nil { |
| 45 | + t.Error("Errors.byType should be initialized") |
| 46 | + } |
| 47 | + |
| 48 | + if errs.byCode == nil { |
| 49 | + t.Error("Errors.byCode should be initialized") |
| 50 | + } |
| 51 | + |
| 52 | + // Check initial registration |
| 53 | + expectedType := reflect.TypeOf(&RPCConnectionError{}) |
| 54 | + if code, exists := errs.byCode[eTempWSError]; !exists { |
| 55 | + t.Errorf("Expected initial ErrorCode %d to be registered", eTempWSError) |
| 56 | + } else if code != expectedType { |
| 57 | + t.Errorf("Expected type %v for ErrorCode %d, got %v", expectedType, eTempWSError, code) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +func TestErrors_GetCode_PointerAndValueTypes(t *testing.T) { |
| 62 | + errs := NewErrors() |
| 63 | + |
| 64 | + // Register TestError with ErrorCode 100 |
| 65 | + errs.Register(100, new(*PointerReceiverError)) |
| 66 | + errs.Register(101, new(*ValueReceiverError)) |
| 67 | + |
| 68 | + // Create both pointer and value instances |
| 69 | + ptrErr := &PointerReceiverError{Message: "pointer error"} |
| 70 | + valErr := ValueReceiverError{Message: "value error"} |
| 71 | + |
| 72 | + tests := []struct { |
| 73 | + name string |
| 74 | + inputErr error |
| 75 | + wantCode ErrorCode |
| 76 | + }{ |
| 77 | + { |
| 78 | + name: "Pointer error", |
| 79 | + inputErr: ptrErr, |
| 80 | + wantCode: 100, |
| 81 | + }, |
| 82 | + { |
| 83 | + name: "Value error (direct, should not match)", |
| 84 | + inputErr: valErr, |
| 85 | + wantCode: 101, |
| 86 | + }, |
| 87 | + } |
| 88 | + |
| 89 | + for _, tt := range tests { |
| 90 | + t.Run(tt.name, func(t *testing.T) { |
| 91 | + gotCode := errs.getErrorCode(tt.inputErr) |
| 92 | + require.Equal(t, tt.wantCode, gotCode, "error code mismatch for %s", tt.name) |
| 93 | + }) |
| 94 | + } |
| 95 | +} |
0 commit comments