|
| 1 | +//go:build go1.20 |
| 2 | +// +build go1.20 |
| 3 | + |
| 4 | +package xerrors |
| 5 | + |
| 6 | +import ( |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "testing" |
| 10 | +) |
| 11 | + |
| 12 | +func TestJoinf_Go120(t *testing.T) { |
| 13 | + err1 := Message("first error") |
| 14 | + err2 := Message("second error") |
| 15 | + tests := []struct { |
| 16 | + format string |
| 17 | + args []any |
| 18 | + want string |
| 19 | + }{ |
| 20 | + {format: "multiple errors: %w: %w", args: []any{err1, err2}, want: "multiple errors: first error: second error"}, |
| 21 | + } |
| 22 | + for n, tt := range tests { |
| 23 | + t.Run(fmt.Sprintf("case-%d", n+1), func(t *testing.T) { |
| 24 | + got := Joinf(tt.format, tt.args...) |
| 25 | + if got == nil { |
| 26 | + t.Errorf("Joinf(%q, %#v): expected non-nil error", tt.format, tt.args) |
| 27 | + return |
| 28 | + } |
| 29 | + if got.Error() != tt.want { |
| 30 | + t.Errorf("Joinf(%q, %#v): got: %q, want %q", tt.format, tt.args, got, tt.want) |
| 31 | + } |
| 32 | + if len(StackTrace(got)) != 0 { |
| 33 | + t.Errorf("Joinf(%q, %#v): returned error must not contain a stack trace", tt.format, tt.args) |
| 34 | + } |
| 35 | + for _, v := range tt.args { |
| 36 | + if err, ok := v.(error); ok { |
| 37 | + if !errors.Is(got, err) { |
| 38 | + t.Errorf("errors.Is(Joinf(errs...), err): must return true") |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + }) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +func TestJoinf_Unwrap(t *testing.T) { |
| 47 | + err1 := Message("first error") |
| 48 | + err2 := Message("second error") |
| 49 | + got := Joinf("%w: %w", err1, err2) |
| 50 | + unwrapper, ok := got.(interface{ Unwrap() error }) |
| 51 | + if !ok { |
| 52 | + t.Fatalf("Join(err1, err2) must implement Unwrap()") |
| 53 | + } |
| 54 | + unwrapped := unwrapper.Unwrap() |
| 55 | + if unwrapped == nil { |
| 56 | + t.Fatalf("Join(err1, err2).Unwrap() must not return nil") |
| 57 | + } |
| 58 | + if !(!errors.Is(unwrapped, err1) && errors.Is(unwrapped, err2)) { |
| 59 | + t.Fatalf("Join(err1, err2).Unwrap() must return the second error") |
| 60 | + } |
| 61 | +} |
0 commit comments