blob: 7e0e77f2a7920b3e4aa21da06a22fcc41deae2f1 [file] [log] [blame]
Marcel van Lohuizen20feca12019-01-26 23:43:21 +01001// Copyright 2011 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
5package xerrors_test
6
7import (
8 "fmt"
Damien Neil10f36292019-01-31 12:58:24 -08009 "regexp"
Marcel van Lohuizen20feca12019-01-26 23:43:21 +010010 "testing"
11
12 "golang.org/x/xerrors"
13)
14
15func TestNewEqual(t *testing.T) {
16 // Different allocations should not be equal.
17 if xerrors.New("abc") == xerrors.New("abc") {
18 t.Errorf(`New("abc") == New("abc")`)
19 }
20 if xerrors.New("abc") == xerrors.New("xyz") {
21 t.Errorf(`New("abc") == New("xyz")`)
22 }
23
24 // Same allocation should be equal to itself (not crash).
25 err := xerrors.New("jkl")
26 if err != err {
27 t.Errorf(`err != err`)
28 }
29}
30
31func TestErrorMethod(t *testing.T) {
32 err := xerrors.New("abc")
33 if err.Error() != "abc" {
34 t.Errorf(`New("abc").Error() = %q, want %q`, err.Error(), "abc")
35 }
36}
37
Damien Neil10f36292019-01-31 12:58:24 -080038func TestNewDetail(t *testing.T) {
39 got := fmt.Sprintf("%+v", xerrors.New("error"))
40 want := `(?s)error:.+errors_test.go:\d+`
41 ok, err := regexp.MatchString(want, got)
42 if err != nil {
43 t.Fatal(err)
44 }
45 if !ok {
46 t.Errorf(`fmt.Sprintf("%%+v", New("error")) = %q, want %q"`, got, want)
47 }
48}
49
Marcel van Lohuizen20feca12019-01-26 23:43:21 +010050func ExampleNew() {
51 err := xerrors.New("emit macho dwarf: elf header corrupted")
52 if err != nil {
53 fmt.Print(err)
54 }
55 // Output: emit macho dwarf: elf header corrupted
56}
57
58// The fmt package's Errorf function lets us use the package's formatting
59// features to create descriptive error messages.
60func ExampleNew_errorf() {
61 const name, id = "bimmler", 17
62 err := fmt.Errorf("user %q (id %d) not found", name, id)
63 if err != nil {
64 fmt.Print(err)
65 }
66 // Output: user "bimmler" (id 17) not found
67}