Source file src/fmt/errors_test.go

Documentation: fmt

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package fmt_test
     6  
     7  import (
     8  	"errors"
     9  	"fmt"
    10  	"testing"
    11  )
    12  
    13  func TestErrorf(t *testing.T) {
    14  	wrapped := errors.New("inner error")
    15  	for _, test := range []struct {
    16  		err        error
    17  		wantText   string
    18  		wantUnwrap error
    19  	}{{
    20  		err:        fmt.Errorf("%w", wrapped),
    21  		wantText:   "inner error",
    22  		wantUnwrap: wrapped,
    23  	}, {
    24  		err:        fmt.Errorf("added context: %w", wrapped),
    25  		wantText:   "added context: inner error",
    26  		wantUnwrap: wrapped,
    27  	}, {
    28  		err:        fmt.Errorf("%w with added context", wrapped),
    29  		wantText:   "inner error with added context",
    30  		wantUnwrap: wrapped,
    31  	}, {
    32  		err:        fmt.Errorf("%s %w %v", "prefix", wrapped, "suffix"),
    33  		wantText:   "prefix inner error suffix",
    34  		wantUnwrap: wrapped,
    35  	}, {
    36  		err:        fmt.Errorf("%[2]s: %[1]w", wrapped, "positional verb"),
    37  		wantText:   "positional verb: inner error",
    38  		wantUnwrap: wrapped,
    39  	}, {
    40  		err:      fmt.Errorf("%v", wrapped),
    41  		wantText: "inner error",
    42  	}, {
    43  		err:      fmt.Errorf("added context: %v", wrapped),
    44  		wantText: "added context: inner error",
    45  	}, {
    46  		err:      fmt.Errorf("%v with added context", wrapped),
    47  		wantText: "inner error with added context",
    48  	}, {
    49  		err:      fmt.Errorf("%w is not an error", "not-an-error"),
    50  		wantText: "%!w(string=not-an-error) is not an error",
    51  	}, {
    52  		err:      fmt.Errorf("wrapped two errors: %w %w", errString("1"), errString("2")),
    53  		wantText: "wrapped two errors: 1 %!w(fmt_test.errString=2)",
    54  	}, {
    55  		err:      fmt.Errorf("wrapped three errors: %w %w %w", errString("1"), errString("2"), errString("3")),
    56  		wantText: "wrapped three errors: 1 %!w(fmt_test.errString=2) %!w(fmt_test.errString=3)",
    57  	}, {
    58  		err:        fmt.Errorf("%w", nil),
    59  		wantText:   "%!w(<nil>)",
    60  		wantUnwrap: nil, // still nil
    61  	}} {
    62  		if got, want := errors.Unwrap(test.err), test.wantUnwrap; got != want {
    63  			t.Errorf("Formatted error: %v\nerrors.Unwrap() = %v, want %v", test.err, got, want)
    64  		}
    65  		if got, want := test.err.Error(), test.wantText; got != want {
    66  			t.Errorf("err.Error() = %q, want %q", got, want)
    67  		}
    68  	}
    69  }
    70  
    71  type errString string
    72  
    73  func (e errString) Error() string { return string(e) }
    74  

View as plain text