| 1 |
// Copyright 2020-2025 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package server |
| 15 |
|
| 16 |
import ( |
| 17 |
"strings" |
| 18 |
"testing" |
| 19 |
) |
| 20 |
|
| 21 |
func TestErrCtx(t *testing.T) { |
| 22 |
ctx := "Extra context information" |
| 23 |
e := NewErrorCtx(ErrWrongGateway, "%s", ctx) |
| 24 |
|
| 25 |
if e.Error() != ErrWrongGateway.Error() { |
| 26 |
t.Fatalf("%v and %v are supposed to be identical", e, ErrWrongGateway) |
| 27 |
} |
| 28 |
if e == ErrWrongGateway { |
| 29 |
t.Fatalf("%v and %v can't be compared this way", e, ErrWrongGateway) |
| 30 |
} |
| 31 |
if !ErrorIs(e, ErrWrongGateway) { |
| 32 |
t.Fatalf("%s and %s ", e, ErrWrongGateway) |
| 33 |
} |
| 34 |
if UnpackIfErrorCtx(ErrWrongGateway) != ErrWrongGateway.Error() { |
| 35 |
t.Fatalf("Error of different type should be processed unchanged") |
| 36 |
} |
| 37 |
trace := UnpackIfErrorCtx(e) |
| 38 |
if !strings.HasPrefix(trace, ErrWrongGateway.Error()) { |
| 39 |
t.Fatalf("original error needs to remain") |
| 40 |
} |
| 41 |
if !strings.HasSuffix(trace, ctx) { |
| 42 |
t.Fatalf("ctx needs to be added") |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
func TestErrCtxWrapped(t *testing.T) { |
| 47 |
ctxO := "Original Ctx" |
| 48 |
eO := NewErrorCtx(ErrWrongGateway, "%s", ctxO) |
| 49 |
ctx := "Extra context information" |
| 50 |
e := NewErrorCtx(eO, "%s", ctx) |
| 51 |
|
| 52 |
if e.Error() != ErrWrongGateway.Error() { |
| 53 |
t.Fatalf("%v and %v are supposed to be identical", e, ErrWrongGateway) |
| 54 |
} |
| 55 |
if e == ErrWrongGateway { |
| 56 |
t.Fatalf("%v and %v can't be compared this way", e, ErrWrongGateway) |
| 57 |
} |
| 58 |
if !ErrorIs(e, ErrWrongGateway) { |
| 59 |
t.Fatalf("%s and %s ", e, ErrWrongGateway) |
| 60 |
} |
| 61 |
if UnpackIfErrorCtx(ErrWrongGateway) != ErrWrongGateway.Error() { |
| 62 |
t.Fatalf("Error of different type should be processed unchanged") |
| 63 |
} |
| 64 |
trace := UnpackIfErrorCtx(e) |
| 65 |
if !strings.HasPrefix(trace, ErrWrongGateway.Error()) { |
| 66 |
t.Fatalf("original error needs to remain") |
| 67 |
} |
| 68 |
if !strings.HasSuffix(trace, ctx) { |
| 69 |
t.Fatalf("ctx needs to be added") |
| 70 |
} |
| 71 |
if !strings.Contains(trace, ctxO) { |
| 72 |
t.Fatalf("Needs to contain every context") |
| 73 |
} |
| 74 |
} |