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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
|
package errors
import (
"encoding/json"
"errors"
"fmt"
"math/rand"
"reflect"
"testing"
)
// TestMultiError_Basic verifies basic MultiError functionality.
// Ensures empty creation, nil error handling, and single error addition work as expected.
func TestMultiError_Basic(t *testing.T) {
m := NewMultiError()
if m.Has() {
t.Error("New MultiError should be empty")
}
m.Add(nil) // Single nil error
if m.Has() {
t.Error("Adding nil should not create error")
}
err1 := errors.New("error 1")
m.Add(err1) // Single error
if !m.Has() {
t.Error("Should detect errors after adding one")
}
if m.Count() != 1 {
t.Errorf("Count should be 1, got %d", m.Count())
}
if m.First() != err1 || m.Last() != err1 {
t.Errorf("First() and Last() should both be %v, got First=%v, Last=%v", err1, m.First(), m.Last())
}
// Test variadic Add with nil and duplicate
m.Add(nil, err1, errors.New("error 1")) // Nil, duplicate, and same message
if m.Count() != 1 {
t.Errorf("Count should remain 1 after adding nil and duplicate, got %d", m.Count())
}
}
// TestMultiError_Sampling tests the sampling behavior of MultiError.
// Adds many unique errors with a 50% sampling rate and checks the resulting ratio is within 45-55%.
func TestMultiError_Sampling(t *testing.T) {
r := rand.New(rand.NewSource(42)) // Fixed seed for reproducible results
m := NewMultiError(WithSampling(50), WithRand(r))
total := 1000
// Add errors in batches to test variadic Add
batchSize := 100
for i := 0; i < total; i += batchSize {
batch := make([]error, batchSize)
for j := 0; j < batchSize; j++ {
batch[j] = errors.New(fmt.Sprintf("test%d", i+j)) // Unique errors
}
m.Add(batch...)
}
count := m.Count()
ratio := float64(count) / float64(total)
// Expect roughly 50% (±5%) due to sampling; adjust range if sampling logic changes
if ratio < 0.45 || ratio > 0.55 {
t.Errorf("Sampling ratio %v not within expected range (45-55%%), count=%d, total=%d", ratio, count, total)
}
}
// TestMultiError_Limit tests the error limit enforcement of MultiError.
// Adds twice the limit of unique errors and verifies the count caps at the limit.
func TestMultiError_Limit(t *testing.T) {
limit := 10
m := NewMultiError(WithLimit(limit))
// Add errors in a single variadic call
errors := make([]error, limit*2)
for i := 0; i < limit*2; i++ {
errors[i] = New(fmt.Sprintf("test%d", i)) // Unique errors
}
m.Add(errors...)
if m.Count() != limit {
t.Errorf("Should cap at %d errors, got %d", limit, m.Count())
}
}
// TestMultiError_Formatting verifies custom formatting in MultiError.
// Adds two errors and checks the custom formatter outputs the expected string.
func TestMultiError_Formatting(t *testing.T) {
customFormat := func(errs []error) string {
return fmt.Sprintf("custom: %d", len(errs))
}
m := NewMultiError(WithFormatter(customFormat))
m.Add(errors.New("test1"), errors.New("test2")) // Add two errors at once
expected := "custom: 2"
if m.Error() != expected {
t.Errorf("Expected %q, got %q", expected, m.Error())
}
}
// TestMultiError_Filter tests the filtering functionality of MultiError.
// Adds three errors, filters out one, and verifies the resulting count is correct.
func TestMultiError_Filter(t *testing.T) {
m := NewMultiError()
m.Add(errors.New("error1"), errors.New("skip"), errors.New("error2")) // Variadic add
filtered := m.Filter(func(err error) bool {
return err.Error() != "skip"
})
if filtered.Count() != 2 {
t.Errorf("Should filter out one error, leaving 2, got %d", filtered.Count())
}
}
// TestMultiError_AsSingle tests the Single() method across different scenarios.
// Verifies behavior for empty, single-error, and multi-error cases.
func TestMultiError_AsSingle(t *testing.T) {
// Subtest: Empty MultiError should return nil
t.Run("Empty", func(t *testing.T) {
m := NewMultiError()
if m.Single() != nil {
t.Errorf("Empty should return nil, got %v", m.Single())
}
})
// Subtest: Single error should return that error
t.Run("Single", func(t *testing.T) {
m := NewMultiError()
err := errors.New("test")
m.Add(err)
if m.Single() != err {
t.Errorf("Should return single error %v, got %v", err, m.Single())
}
})
// Subtest: Multiple errors should return the MultiError itself
t.Run("Multiple", func(t *testing.T) {
m := NewMultiError()
m.Add(errors.New("test1"), errors.New("test2")) // Variadic add
if m.Single() != m {
t.Errorf("Should return self for multiple errors, got %v", m.Single())
}
})
}
// TestMultiError_MarshalJSON tests the JSON serialization of MultiError.
// Verifies correct output for empty, single-error, multiple-error, and mixed-error cases.
func TestMultiError_MarshalJSON(t *testing.T) {
// Subtest: Empty
t.Run("Empty", func(t *testing.T) {
m := NewMultiError()
data, err := json.Marshal(m)
if err != nil {
t.Fatalf("MarshalJSON failed: %v", err)
}
expected := `{"count":0,"errors":[]}`
if string(data) != expected {
t.Errorf("Expected %q, got %q", expected, string(data))
}
})
// Subtest: Single standard error
t.Run("SingleStandardError", func(t *testing.T) {
m := NewMultiError()
err := errors.New("timeout")
m.Add(err)
data, err := json.Marshal(m)
if err != nil {
t.Fatalf("MarshalJSON failed: %v", err)
}
expected := `{"count":1,"errors":[{"error":"timeout"}]}`
var expectedJSON, actualJSON interface{}
if err := json.Unmarshal([]byte(expected), &expectedJSON); err != nil {
t.Fatalf("Failed to parse expected JSON: %v", err)
}
if err := json.Unmarshal(data, &actualJSON); err != nil {
t.Fatalf("Failed to parse actual JSON: %v", err)
}
if !reflect.DeepEqual(expectedJSON, actualJSON) {
t.Errorf("JSON output mismatch.\nGot: %s\nWant: %s", string(data), expected)
}
})
// Subtest: Multiple errors including *Error
t.Run("MultipleMixedErrors", func(t *testing.T) {
m := NewMultiError(WithLimit(5)) // No sampling to ensure all errors are added
m.Add(
New("db error").WithCode(500).With("user_id", 123), // *Error
errors.New("timeout"), // Standard error
nil, // Nil error (skipped by Add)
)
data, err := json.Marshal(m)
if err != nil {
t.Fatalf("MarshalJSON failed: %v", err)
}
expected := `{
"count":2,
"limit":5,
"errors":[
{"error":{"message":"db error","context":{"user_id":123},"code":500}},
{"error":"timeout"}
]
}`
var expectedJSON, actualJSON interface{}
if err := json.Unmarshal([]byte(expected), &expectedJSON); err != nil {
t.Fatalf("Failed to parse expected JSON: %v", err)
}
if err := json.Unmarshal(data, &actualJSON); err != nil {
t.Fatalf("Failed to parse actual JSON: %v", err)
}
if !reflect.DeepEqual(expectedJSON, actualJSON) {
t.Errorf("JSON output mismatch.\nGot: %s\nWant: %s", string(data), expected)
}
})
// Subtest: Concurrent access to ensure thread safety
t.Run("Concurrent", func(t *testing.T) {
m := NewMultiError()
err1 := New("error1").WithCode(400)
err2 := errors.New("error2")
m.Add(err1, err2) // Variadic add
// Run multiple goroutines to marshal concurrently
const numGoroutines = 10
results := make(chan []byte, numGoroutines)
errorsChan := make(chan error, numGoroutines)
for i := 0; i < numGoroutines; i++ {
go func() {
data, err := json.Marshal(m)
if err != nil {
errorsChan <- err
return
}
results <- data
}()
}
// Collect results
expected := `{
"count":2,
"errors":[
{"error":{"message":"error1","code":400}},
{"error":"error2"}
]
}`
var expectedJSON interface{}
if err := json.Unmarshal([]byte(expected), &expectedJSON); err != nil {
t.Fatalf("Failed to parse expected JSON: %v", err)
}
for i := 0; i < numGoroutines; i++ {
select {
case err := <-errorsChan:
t.Errorf("Concurrent MarshalJSON failed: %v", err)
case data := <-results:
var actualJSON interface{}
if err := json.Unmarshal(data, &actualJSON); err != nil {
t.Errorf("Failed to parse actual JSON: %v", err)
}
if !reflect.DeepEqual(expectedJSON, actualJSON) {
t.Errorf("Concurrent JSON output mismatch.\nGot: %s\nWant: %s", string(data), expected)
}
}
}
})
// Subtest: Variadic add with multiple errors
t.Run("VariadicAdd", func(t *testing.T) {
m := NewMultiError(WithLimit(10))
err1 := New("error1").WithCode(400)
err2 := errors.New("error2")
err3 := errors.New("error3")
m.Add(err1, err2, err3, nil, err2) // Mix of unique, nil, and duplicate errors
if m.Count() != 3 {
t.Errorf("Expected 3 errors, got %d", m.Count())
}
data, err := json.Marshal(m)
if err != nil {
t.Fatalf("MarshalJSON failed: %v", err)
}
expected := `{
"count":3,
"limit":10,
"errors":[
{"error":{"message":"error1","code":400}},
{"error":"error2"},
{"error":"error3"}
]
}`
var expectedJSON, actualJSON interface{}
if err := json.Unmarshal([]byte(expected), &expectedJSON); err != nil {
t.Fatalf("Failed to parse expected JSON: %v", err)
}
if err := json.Unmarshal(data, &actualJSON); err != nil {
t.Fatalf("Failed to parse actual JSON: %v", err)
}
if !reflect.DeepEqual(expectedJSON, actualJSON) {
t.Errorf("JSON output mismatch.\nGot: %s\nWant: %s", string(data), expected)
}
})
}
|