blob: 63c05d7185b8ef8c6e525b3c81c3c564849353ea [file] [log] [blame]
Russ Coxe4ae30f2011-11-01 21:46:59 -04001// 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 errors_test
6
7import (
Andrew Gerrand3e804f92012-02-18 11:48:33 +11008 "errors"
9 "fmt"
Russ Coxe4ae30f2011-11-01 21:46:59 -040010 "testing"
11)
12
13func TestNewEqual(t *testing.T) {
14 // Different allocations should not be equal.
Andrew Gerrand3e804f92012-02-18 11:48:33 +110015 if errors.New("abc") == errors.New("abc") {
Russ Coxe4ae30f2011-11-01 21:46:59 -040016 t.Errorf(`New("abc") == New("abc")`)
17 }
Andrew Gerrand3e804f92012-02-18 11:48:33 +110018 if errors.New("abc") == errors.New("xyz") {
Russ Coxe4ae30f2011-11-01 21:46:59 -040019 t.Errorf(`New("abc") == New("xyz")`)
20 }
21
22 // Same allocation should be equal to itself (not crash).
Andrew Gerrand3e804f92012-02-18 11:48:33 +110023 err := errors.New("jkl")
Russ Coxe4ae30f2011-11-01 21:46:59 -040024 if err != err {
25 t.Errorf(`err != err`)
26 }
27}
28
29func TestErrorMethod(t *testing.T) {
Andrew Gerrand3e804f92012-02-18 11:48:33 +110030 err := errors.New("abc")
Russ Coxe4ae30f2011-11-01 21:46:59 -040031 if err.Error() != "abc" {
32 t.Errorf(`New("abc").Error() = %q, want %q`, err.Error(), "abc")
33 }
34}
Andrew Gerrand3e804f92012-02-18 11:48:33 +110035
36func ExampleNew() {
37 err := errors.New("emit macho dwarf: elf header corrupted")
38 if err != nil {
39 fmt.Print(err)
40 }
41 // Output: emit macho dwarf: elf header corrupted
42}
43
44// The fmt package's Errorf function lets us use the package's formatting
45// features to create descriptive error messages.
46func ExampleNew_errorf() {
47 const name, id = "bimmler", 17
48 err := fmt.Errorf("user %q (id %d) not found", name, id)
49 if err != nil {
50 fmt.Print(err)
51 }
52 // Output: user "bimmler" (id 17) not found
53}