aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/go.uber.org/zap/error_test.go
blob: 4bfa370d2aa29b191380f3320617b876d458febd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zap

import (
	"errors"
	"fmt"
	"testing"

	"go.uber.org/zap/zapcore"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestErrorConstructors(t *testing.T) {
	fail := errors.New("fail")

	tests := []struct {
		name   string
		field  Field
		expect Field
	}{
		{"Error", Skip(), Error(nil)},
		{"Error", Field{Key: "error", Type: zapcore.ErrorType, Interface: fail}, Error(fail)},
		{"NamedError", Skip(), NamedError("foo", nil)},
		{"NamedError", Field{Key: "foo", Type: zapcore.ErrorType, Interface: fail}, NamedError("foo", fail)},
		{"Any:Error", Any("k", errors.New("v")), NamedError("k", errors.New("v"))},
		{"Any:Errors", Any("k", []error{errors.New("v")}), Errors("k", []error{errors.New("v")})},
	}

	for _, tt := range tests {
		if !assert.Equal(t, tt.expect, tt.field, "Unexpected output from convenience field constructor %s.", tt.name) {
			t.Logf("type expected: %T\nGot: %T", tt.expect.Interface, tt.field.Interface)
		}
		assertCanBeReused(t, tt.field)
	}
}

func TestErrorArrayConstructor(t *testing.T) {
	tests := []struct {
		desc     string
		field    Field
		expected []interface{}
	}{
		{"empty errors", Errors("", []error{}), []interface{}{}},
		{
			"errors",
			Errors("", []error{nil, errors.New("foo"), nil, errors.New("bar")}),
			[]interface{}{map[string]interface{}{"error": "foo"}, map[string]interface{}{"error": "bar"}},
		},
	}

	for _, tt := range tests {
		enc := zapcore.NewMapObjectEncoder()
		tt.field.Key = "k"
		tt.field.AddTo(enc)
		assert.Equal(t, tt.expected, enc.Fields["k"], "%s: unexpected map contents.", tt.desc)
		assert.Equal(t, 1, len(enc.Fields), "%s: found extra keys in map: %v", tt.desc, enc.Fields)
	}
}

func TestErrorsArraysHandleRichErrors(t *testing.T) {
	errs := []error{fmt.Errorf("egad")}

	enc := zapcore.NewMapObjectEncoder()
	Errors("k", errs).AddTo(enc)
	assert.Equal(t, 1, len(enc.Fields), "Expected only top-level field.")

	val := enc.Fields["k"]
	arr, ok := val.([]interface{})
	require.True(t, ok, "Expected top-level field to be an array.")
	require.Equal(t, 1, len(arr), "Expected only one error object in array.")

	serialized := arr[0]
	errMap, ok := serialized.(map[string]interface{})
	require.True(t, ok, "Expected serialized error to be a map, got %T.", serialized)
	assert.Equal(t, "egad", errMap["error"], "Unexpected standard error string.")
}

func TestErrArrayBrokenEncoder(t *testing.T) {
	t.Parallel()

	failWith := errors.New("great sadness")
	err := (brokenArrayObjectEncoder{
		Err:           failWith,
		ObjectEncoder: zapcore.NewMapObjectEncoder(),
	}).AddArray("errors", errArray{
		errors.New("foo"),
		errors.New("bar"),
	})
	require.Error(t, err, "Expected error from broken encoder.")
	assert.ErrorIs(t, err, failWith, "Unexpected error.")
}

// brokenArrayObjectEncoder is an ObjectEncoder
// that builds a broken ArrayEncoder.
type brokenArrayObjectEncoder struct {
	zapcore.ObjectEncoder
	zapcore.ArrayEncoder

	Err error // error to return
}

func (enc brokenArrayObjectEncoder) AddArray(key string, marshaler zapcore.ArrayMarshaler) error {
	return enc.ObjectEncoder.AddArray(key,
		zapcore.ArrayMarshalerFunc(func(ae zapcore.ArrayEncoder) error {
			enc.ArrayEncoder = ae
			return marshaler.MarshalLogArray(enc)
		}))
}

func (enc brokenArrayObjectEncoder) AppendObject(zapcore.ObjectMarshaler) error {
	return enc.Err
}