blob: 6c0d7931d81cc9938623638daacd891793999a72 [file] [log] [blame]
Damien Neil34488152018-09-26 11:45:18 -07001// 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 Neild8bb7a12018-10-09 09:50:34 -07005package errors_test
Damien Neil34488152018-09-26 11:45:18 -07006
7import (
8 "fmt"
9 "testing"
10
Damien Neild8bb7a12018-10-09 09:50:34 -070011 "golang.org/x/exp/errors"
Damien Neil34488152018-09-26 11:45:18 -070012)
13
14func TestNewEqual(t *testing.T) {
15 // Different allocations should not be equal.
Damien Neild8bb7a12018-10-09 09:50:34 -070016 if errors.New("abc") == errors.New("abc") {
Damien Neil34488152018-09-26 11:45:18 -070017 t.Errorf(`New("abc") == New("abc")`)
18 }
Damien Neild8bb7a12018-10-09 09:50:34 -070019 if errors.New("abc") == errors.New("xyz") {
Damien Neil34488152018-09-26 11:45:18 -070020 t.Errorf(`New("abc") == New("xyz")`)
21 }
22
23 // Same allocation should be equal to itself (not crash).
Damien Neild8bb7a12018-10-09 09:50:34 -070024 err := errors.New("jkl")
Damien Neil34488152018-09-26 11:45:18 -070025 if err != err {
26 t.Errorf(`err != err`)
27 }
28}
29
30func TestErrorMethod(t *testing.T) {
Damien Neild8bb7a12018-10-09 09:50:34 -070031 err := errors.New("abc")
Damien Neil34488152018-09-26 11:45:18 -070032 if err.Error() != "abc" {
33 t.Errorf(`New("abc").Error() = %q, want %q`, err.Error(), "abc")
34 }
35}
36
37func ExampleNew() {
Damien Neild8bb7a12018-10-09 09:50:34 -070038 err := errors.New("emit macho dwarf: elf header corrupted")
Damien Neil34488152018-09-26 11:45:18 -070039 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.
47func 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}