Damien Neil | 3448815 | 2018-09-26 11:45:18 -0700 | [diff] [blame] | 1 | // 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 | |
Damien Neil | d8bb7a1 | 2018-10-09 09:50:34 -0700 | [diff] [blame] | 5 | package errors_test |
Damien Neil | 3448815 | 2018-09-26 11:45:18 -0700 | [diff] [blame] | 6 | |
| 7 | import ( |
| 8 | "fmt" |
| 9 | "testing" |
| 10 | |
Damien Neil | d8bb7a1 | 2018-10-09 09:50:34 -0700 | [diff] [blame] | 11 | "golang.org/x/exp/errors" |
Damien Neil | 3448815 | 2018-09-26 11:45:18 -0700 | [diff] [blame] | 12 | ) |
| 13 | |
| 14 | func TestNewEqual(t *testing.T) { |
| 15 | // Different allocations should not be equal. |
Damien Neil | d8bb7a1 | 2018-10-09 09:50:34 -0700 | [diff] [blame] | 16 | if errors.New("abc") == errors.New("abc") { |
Damien Neil | 3448815 | 2018-09-26 11:45:18 -0700 | [diff] [blame] | 17 | t.Errorf(`New("abc") == New("abc")`) |
| 18 | } |
Damien Neil | d8bb7a1 | 2018-10-09 09:50:34 -0700 | [diff] [blame] | 19 | if errors.New("abc") == errors.New("xyz") { |
Damien Neil | 3448815 | 2018-09-26 11:45:18 -0700 | [diff] [blame] | 20 | t.Errorf(`New("abc") == New("xyz")`) |
| 21 | } |
| 22 | |
| 23 | // Same allocation should be equal to itself (not crash). |
Damien Neil | d8bb7a1 | 2018-10-09 09:50:34 -0700 | [diff] [blame] | 24 | err := errors.New("jkl") |
Damien Neil | 3448815 | 2018-09-26 11:45:18 -0700 | [diff] [blame] | 25 | if err != err { |
| 26 | t.Errorf(`err != err`) |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | func TestErrorMethod(t *testing.T) { |
Damien Neil | d8bb7a1 | 2018-10-09 09:50:34 -0700 | [diff] [blame] | 31 | err := errors.New("abc") |
Damien Neil | 3448815 | 2018-09-26 11:45:18 -0700 | [diff] [blame] | 32 | if err.Error() != "abc" { |
| 33 | t.Errorf(`New("abc").Error() = %q, want %q`, err.Error(), "abc") |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | func ExampleNew() { |
Damien Neil | d8bb7a1 | 2018-10-09 09:50:34 -0700 | [diff] [blame] | 38 | err := errors.New("emit macho dwarf: elf header corrupted") |
Damien Neil | 3448815 | 2018-09-26 11:45:18 -0700 | [diff] [blame] | 39 | if err != nil { |
| 40 | fmt.Print(err) |
| 41 | } |
| 42 | // Output: emit macho dwarf: elf header corrupted |
| 43 | } |
| 44 | |
| 45 | // The fmt package's Errorf function lets us use the package's formatting |
| 46 | // features to create descriptive error messages. |
| 47 | func ExampleNew_errorf() { |
| 48 | const name, id = "bimmler", 17 |
| 49 | err := fmt.Errorf("user %q (id %d) not found", name, id) |
| 50 | if err != nil { |
| 51 | fmt.Print(err) |
| 52 | } |
| 53 | // Output: user "bimmler" (id 17) not found |
| 54 | } |