errors_test.go 1.2 KB

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