-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_test.go
More file actions
798 lines (711 loc) · 21.9 KB
/
code_test.go
File metadata and controls
798 lines (711 loc) · 21.9 KB
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
// Copyright 2025 TimeWtr
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package errors
import (
"errors"
"fmt"
"net/http"
"testing"
"time"
)
// TestBasicErrorFunctions 测试基础错误函数
func TestBasicErrorFunctions(t *testing.T) {
tests := []struct {
name string
errFunc func() Error
wantCode string
wantType ErrType
wantStatus int
}{
{
name: "资源冲突错误",
errFunc: ResourceConflictError,
wantCode: ErrTypeConflict.String(),
wantType: ErrTypeConflict,
wantStatus: http.StatusConflict,
},
{
name: "资源未找到错误",
errFunc: ResourceNotFoundError,
wantCode: ErrTypeNotFound.String(),
wantType: ErrTypeNotFound,
wantStatus: http.StatusNotFound,
},
{
name: "禁止访问错误",
errFunc: ForbiddenError,
wantCode: ErrTypeForbidden.String(),
wantType: ErrTypeForbidden,
wantStatus: http.StatusForbidden,
},
{
name: "未授权错误",
errFunc: UnAuthorizedError,
wantCode: ErrTypeUnauthorized.String(),
wantType: ErrTypeUnauthorized,
wantStatus: http.StatusUnauthorized,
},
{
name: "超时错误",
errFunc: TimeoutError,
wantCode: ErrTypeTimeout.String(),
wantType: ErrTypeTimeout,
wantStatus: http.StatusRequestTimeout,
},
{
name: "内部错误",
errFunc: InternalError,
wantCode: ErrTypeInternal.String(),
wantType: ErrTypeInternal,
wantStatus: http.StatusInternalServerError,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.errFunc()
if err.Code() != tt.wantCode {
t.Errorf("Code() = %v, want %v", err.Code(), tt.wantCode)
}
if err.Type() != tt.wantType {
t.Errorf("Type() = %v, want %v", err.Type(), tt.wantType)
}
if err.HttpStatus() != tt.wantStatus {
t.Errorf("HttpStatus() = %v, want %v", err.HttpStatus(), tt.wantStatus)
}
if err.Message() == "" {
t.Error("Message() should not be empty")
}
if err.Timestamp().IsZero() {
t.Error("Timestamp() should not be zero")
}
if err.StackTrace() == "" {
t.Error("StackTrace() should not be empty")
}
// 测试错误接口
if err.Error() == "" {
t.Error("Error() should not be empty")
}
// 测试 Unwrap 方法
if err.Unwrap() != nil {
t.Error("Unwrap() should return nil for basic errors")
}
})
}
}
// TestBasicErrorFunctionsNoStack 测试基础错误函数,不带堆栈信息
func TestBasicErrorFunctionsNoStack(t *testing.T) {
tests := []struct {
name string
errFunc func() Error
wantCode string
wantType ErrType
wantStatus int
}{
{
name: "资源冲突错误",
errFunc: ResourceConflictErrorNoStack,
wantCode: ErrTypeConflict.String(),
wantType: ErrTypeConflict,
wantStatus: http.StatusConflict,
},
{
name: "资源未找到错误",
errFunc: ResourceNotFoundErrorNoStack,
wantCode: ErrTypeNotFound.String(),
wantType: ErrTypeNotFound,
wantStatus: http.StatusNotFound,
},
{
name: "禁止访问错误",
errFunc: ForbiddenErrorNoStack,
wantCode: ErrTypeForbidden.String(),
wantType: ErrTypeForbidden,
wantStatus: http.StatusForbidden,
},
{
name: "未授权错误",
errFunc: UnAuthorizedErrorNoStack,
wantCode: ErrTypeUnauthorized.String(),
wantType: ErrTypeUnauthorized,
wantStatus: http.StatusUnauthorized,
},
{
name: "超时错误",
errFunc: TimeoutErrorNoStack,
wantCode: ErrTypeTimeout.String(),
wantType: ErrTypeTimeout,
wantStatus: http.StatusRequestTimeout,
},
{
name: "内部错误",
errFunc: InternalErrorNoStack,
wantCode: ErrTypeInternal.String(),
wantType: ErrTypeInternal,
wantStatus: http.StatusInternalServerError,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.errFunc()
if err.Code() != tt.wantCode {
t.Errorf("Code() = %v, want %v", err.Code(), tt.wantCode)
}
if err.Type() != tt.wantType {
t.Errorf("Type() = %v, want %v", err.Type(), tt.wantType)
}
if err.HttpStatus() != tt.wantStatus {
t.Errorf("HttpStatus() = %v, want %v", err.HttpStatus(), tt.wantStatus)
}
if err.Message() == "" {
t.Error("Message() should not be empty")
}
if err.Timestamp().IsZero() {
t.Error("Timestamp() should not be zero")
}
// 测试错误接口
if err.Error() == "" {
t.Error("Error() should not be empty")
}
// 测试 Unwrap 方法
if err.Unwrap() != nil {
t.Error("Unwrap() should return nil for basic errors")
}
})
}
}
// TestParameterValidationError 测试参数验证错误(返回标准 error 接口)
func TestParameterValidationError(t *testing.T) {
err := ParameterValidationError()
if err == nil {
t.Fatal("ParameterValidationError() should not return nil")
}
// 转换为自定义的 Error 类型进行详细检查
var customErr Error
ok := errors.As(err, &customErr)
if !ok {
t.Fatal("ParameterValidationError() should return Error type")
}
if customErr.Code() != ErrTypeBadRequest.String() {
t.Errorf("Code() = %v, want %v", customErr.Code(), ErrTypeBadRequest.String())
}
if customErr.Type() != ErrTypeBadRequest {
t.Errorf("Type() = %v, want %v", customErr.Type(), ErrTypeBadRequest)
}
if customErr.HttpStatus() != http.StatusBadRequest {
t.Errorf("HttpStatus() = %v, want %v", customErr.HttpStatus(), http.StatusBadRequest)
}
}
// TestFormattedErrorFunctions 测试格式化错误函数
func TestFormattedErrorFunctions(t *testing.T) {
tf := time.Now().Format(time.RFC3339)
tests := []struct {
name string
errFunc func(format string, args ...any) Error
format string
args []any
wantCode string
wantType ErrType
wantMessage string
}{
{
name: "未授权格式化错误",
errFunc: UnAuthorizedErrorf,
format: "User %s token expired at %v",
args: []any{"john_doe", tf},
wantCode: ErrTypeUnauthorized.String(),
wantType: ErrTypeUnauthorized,
wantMessage: fmt.Sprintf("User john_doe token expired at %s", tf),
},
{
name: "资源冲突格式化错误",
errFunc: ResourceConflictErrorf,
format: "Resource %s with ID %s already exists",
args: []any{"user", "12345"},
wantCode: ErrTypeConflict.String(),
wantType: ErrTypeConflict,
wantMessage: "Resource user with ID 12345 already exists",
},
{
name: "参数验证格式化错误",
errFunc: ParameterValidationErrorf,
format: "Field %s validation failed: %s",
args: []any{"email", "invalid format"},
wantCode: ErrTypeBadRequest.String(),
wantType: ErrTypeBadRequest,
wantMessage: "Field email validation failed: invalid format",
},
{
name: "超时格式化错误",
errFunc: TimeoutErrorf,
format: "Operation %s timed out after %v",
args: []any{"database_query", 30 * time.Second},
wantCode: ErrTypeTimeout.String(),
wantType: ErrTypeTimeout,
wantMessage: "Operation database_query timed out after 30s",
},
{
name: "禁止访问格式化错误",
errFunc: ForbiddenErrorf,
format: "User %s cannot access resource %s",
args: []any{"user123", "document_456"},
wantCode: ErrTypeForbidden.String(),
wantType: ErrTypeForbidden,
wantMessage: "User user123 cannot access resource document_456",
},
{
name: "内部格式化错误",
errFunc: InternalErrorf,
format: "Failed to process %s: %v",
args: []any{"request", "connection refused"},
wantCode: ErrTypeInternal.String(),
wantType: ErrTypeInternal,
wantMessage: "Failed to process request: connection refused",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.errFunc(tt.format, tt.args...)
if err.Code() != tt.wantCode {
t.Errorf("Code() = %v, want %v", err.Code(), tt.wantCode)
}
if err.Type() != tt.wantType {
t.Errorf("Type() = %v, want %v", err.Type(), tt.wantType)
}
if err.Message() != tt.wantMessage {
t.Errorf("Message() = %v, want %v", err.Message(), tt.wantMessage)
}
// 测试错误消息包含预期内容
if err.Error() != tt.wantMessage {
t.Errorf("Error() = %v, want %v", err.Error(), tt.wantMessage)
}
})
}
}
// TestErrorWithMetadataFunctions 测试带元数据的错误函数
func TestErrorWithMetadataFunctions(t *testing.T) {
tests := []struct {
name string
errFunc func(metadata map[string]any, format string, args ...any) Error
metadata map[string]any
format string
args []any
wantCode string
wantType ErrType
wantMessage string
wantMetadata map[string]any
}{
{
name: "带元数据的未授权错误",
errFunc: UnAuthorizedErrorWithMeta,
metadata: map[string]any{
"user_id": "user123",
"token_type": "bearer",
"expired_at": time.Now().Add(-1 * time.Hour),
},
format: "Token for user %s expired",
args: []any{"user123"},
wantCode: ErrTypeUnauthorized.String(),
wantType: ErrTypeUnauthorized,
wantMessage: "Token for user user123 expired",
wantMetadata: map[string]any{
"user_id": "user123",
"token_type": "bearer",
"expired_at": time.Time{},
},
},
{
name: "带元数据的资源冲突错误",
errFunc: ResourceConflictErrorWithMeta,
metadata: map[string]any{
"resource_type": "user",
"resource_id": "12345",
"conflict_with": "email@example.com",
},
format: "Resource %s conflict",
args: []any{"user"},
wantCode: ErrTypeConflict.String(),
wantType: ErrTypeConflict,
wantMessage: "Resource user conflict",
wantMetadata: map[string]any{
"resource_type": "user",
"resource_id": "12345",
"conflict_with": "email@example.com",
},
},
{
name: "带元数据的参数验证错误",
errFunc: ParameterValidationErrorWithMeta,
metadata: map[string]any{
"field": "email",
"value": "invalid-email",
"reason": "must be valid email format",
},
format: "Validation failed for field %s",
args: []any{"email"},
wantCode: ErrTypeBadRequest.String(),
wantType: ErrTypeBadRequest,
wantMessage: "Validation failed for field email",
wantMetadata: map[string]any{
"field": "email",
"value": "invalid-email",
"reason": "must be valid email format",
},
},
{
name: "带元数据的超时错误",
errFunc: TimeoutErrorWithMeta,
metadata: map[string]any{
"operation": "database_query",
"timeout": 30 * time.Second,
"attempts": 3,
},
format: "Operation %s timed out",
args: []any{"database_query"},
wantCode: ErrTypeTimeout.String(),
wantType: ErrTypeTimeout,
wantMessage: "Operation database_query timed out",
wantMetadata: map[string]any{
"operation": "database_query",
"timeout": 30 * time.Second,
"attempts": 3,
},
},
{
name: "带元数据的禁止访问错误",
errFunc: ForbiddenErrorWithMeta,
metadata: map[string]any{
"user_id": "user123",
"resource": "document_456",
"permission": "write",
"user_roles": []string{"viewer"},
},
format: "Access denied to %s",
args: []any{"document_456"},
wantCode: ErrTypeForbidden.String(),
wantType: ErrTypeForbidden,
wantMessage: "Access denied to document_456",
wantMetadata: map[string]any{
"user_id": "user123",
"resource": "document_456",
"permission": "write",
"user_roles": []string{"viewer"},
},
},
{
name: "带元数据的内部错误",
errFunc: InternalErrorWithMeta,
metadata: map[string]any{
"component": "database",
"operation": "create_user",
"error_code": "23505",
"stack_trace": "some stack trace...",
},
format: "Internal error in %s",
args: []any{"database"},
wantCode: ErrTypeInternal.String(),
wantType: ErrTypeInternal,
wantMessage: "Internal error in database",
wantMetadata: map[string]any{
"component": "database",
"operation": "create_user",
"error_code": "23505",
"stack_trace": "some stack trace...",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.errFunc(tt.metadata, tt.format, tt.args...)
// 验证基本属性
if err.Code() != tt.wantCode {
t.Errorf("Code() = %v, want %v", err.Code(), tt.wantCode)
}
if err.Type() != tt.wantType {
t.Errorf("Type() = %v, want %v", err.Type(), tt.wantType)
}
if err.Message() != tt.wantMessage {
t.Errorf("Message() = %v, want %v", err.Message(), tt.wantMessage)
}
// 验证元数据
metadata := err.Metadata()
if len(metadata) != len(tt.wantMetadata) {
t.Errorf("Metadata length = %v, want %v", len(metadata), len(tt.wantMetadata))
}
for key, wantValue := range tt.wantMetadata {
actualValue, exists := metadata[key]
if !exists {
t.Errorf("Metadata key %s not found", key)
continue
}
// 特殊处理 time.Time 类型,因为时间比较需要特殊处理
if key == "expired_at" {
if _, isTime := actualValue.(time.Time); !isTime {
t.Errorf("Metadata key %s should be time.Time, got %T", key, actualValue)
}
continue
}
// 比较其他类型的值
if fmt.Sprintf("%v", actualValue) != fmt.Sprintf("%v", wantValue) {
t.Errorf("Metadata[%s] = %v, want %v", key, actualValue, wantValue)
}
}
})
}
}
// TestErrorChaining 测试错误链功能
func TestErrorChaining(t *testing.T) {
// 创建原始错误
originalErr := fmt.Errorf("database connection failed: connection refused")
// 包装错误
wrappedErr := Wrap(originalErr, ErrInternal)
// 验证包装错误
if wrappedErr.Code() != ErrTypeInternal.String() {
t.Errorf("Wrapped error Code() = %v, want %v", wrappedErr.Code(), ErrTypeInternal.String())
}
// 验证错误链
unwrapped := wrappedErr.Unwrap()
if unwrapped == nil {
t.Fatal("Unwrap() should return the original error")
}
if unwrapped.Error() != originalErr.Error() {
t.Errorf("Unwrap().Error() = %v, want %v", unwrapped.Error(), originalErr.Error())
}
// 测试 errors.Is 兼容性
if !errors.Is(wrappedErr, originalErr) {
t.Error("errors.Is should return true for wrapped error and original error")
}
}
// TestErrorChainingWithFormat 测试带格式化的错误链
func TestErrorChainingWithFormat(t *testing.T) {
originalErr := fmt.Errorf("file not found: /path/to/file.txt")
wrappedErr := Wrapf("additional context: %s", originalErr, ErrNotFound)
if wrappedErr.Code() != ErrTypeNotFound.String() {
t.Errorf("Code() = %v, want %v", wrappedErr.Code(), ErrTypeNotFound.String())
}
// 注意:Wrapf 的格式化是针对错误消息的
if wrappedErr.Message() != fmt.Sprintf("additional context: %s", ErrNotFound.Message) {
t.Errorf("Message() = %v, want %v", wrappedErr.Message(),
fmt.Sprintf("additional context: %s", ErrNotFound.Message))
}
if wrappedErr.Unwrap().Error() != originalErr.Error() {
t.Errorf("Unwrap().Error() = %v, want %v", wrappedErr.Unwrap().Error(), originalErr.Error())
}
}
// TestNilErrorHandling 测试对 nil 错误的处理
func TestNilErrorHandling(t *testing.T) {
// 测试 Wrap 和 Wrapf 对 nil 的处理
if Wrap(nil, ErrInternal) != nil {
t.Error("Wrap(nil, errCode) should return nil")
}
if Wrapf("format", nil, ErrInternal) != nil {
t.Error("Wrapf(nil, errCode) should return nil")
}
}
// TestMetadataManipulation 测试元数据操作
func TestMetadataManipulation(t *testing.T) {
err := InternalError()
// 测试 WithMetadata
errWithMeta := err.WithMetadata("key1", "value1")
if errWithMeta.Metadata()["key1"] != "value1" {
t.Error("WithMetadata failed to add metadata")
}
// 测试 WithMetadataMap
errWithMetaMap := err.WithMetadataMap(map[string]any{
"key2": "value2",
"key3": 123,
})
metadata := errWithMetaMap.Metadata()
if metadata["key2"] != "value2" {
t.Error("WithMetadataMap failed to add key2")
}
if metadata["key3"] != 123 {
t.Error("WithMetadataMap failed to add key3")
}
// 测试链式调用
chainErr := err.
WithMetadata("chain1", "value1").
WithMetadata("chain2", "value2").
WithMetadataMap(map[string]any{"chain3": "value3"})
chainMetadata := chainErr.Metadata()
if chainMetadata["chain1"] != "value1" || chainMetadata["chain2"] != "value2" || chainMetadata["chain3"] != "value3" {
t.Error("Chain metadata manipulation failed")
}
}
// TestPredefinedBusinessErrors 测试预定义的业务错误
func TestPredefinedBusinessErrors(t *testing.T) {
tests := []struct {
name string
err *ErrCode
wantCode string
wantType ErrType
wantStatus int
}{
{
name: "用户名已存在错误",
err: ErrUsernameExisted,
wantCode: ErrTypeConflict.String(),
wantType: ErrTypeConflict,
wantStatus: http.StatusConflict,
},
{
name: "邮箱已存在错误",
err: ErrEmailExisted,
wantCode: ErrTypeConflict.String(),
wantType: ErrTypeConflict,
wantStatus: http.StatusConflict,
},
{
name: "手机号已存在错误",
err: ErrPhoneExisted,
wantCode: ErrTypeConflict.String(),
wantType: ErrTypeConflict,
wantStatus: http.StatusConflict,
},
{
name: "业务错误",
err: BusinessError,
wantCode: ErrTypeBusiness.String(),
wantType: ErrTypeBusiness,
wantStatus: http.StatusInternalServerError,
},
{
name: "限流错误",
err: ErrRateLimit,
wantCode: ErrRateLimit.Code,
wantType: ErrTypeRateLimit,
wantStatus: http.StatusTooManyRequests,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := New(tt.err)
if err.Code() != tt.wantCode {
t.Errorf("Code() = %v, want %v", err.Code(), tt.wantCode)
}
if err.Type() != tt.wantType {
t.Errorf("Type() = %v, want %v", err.Type(), tt.wantType)
}
if err.HttpStatus() != tt.wantStatus {
t.Errorf("HttpStatus() = %v, want %v", err.HttpStatus(), tt.wantStatus)
}
})
}
}
// TestNewfWithPredefinedErrors 测试 Newf 与预定义错误码的结合使用
func TestNewfWithPredefinedErrors(t *testing.T) {
username := "testuser"
err := Newf(ErrUsernameExisted, "Username '%s' is already taken", username)
if err.Code() != ErrTypeConflict.String() {
t.Errorf("Code() = %v, want %v", err.Code(), "USERNAME_EXISTED")
}
if err.Type() != ErrTypeConflict {
t.Errorf("Type() = %v, want %v", err.Type(), ErrTypeConflict)
}
if err.HttpStatus() != http.StatusConflict {
t.Errorf("HttpStatus() = %v, want %v", err.HttpStatus(), http.StatusConflict)
}
expectedMessage := fmt.Sprintf("Username '%s' is already taken", username)
if err.Message() != expectedMessage {
t.Errorf("Message() = %v, want %v", err.Message(), expectedMessage)
}
}
// BenchmarkErrorCreation 性能测试
func BenchmarkErrorCreation(b *testing.B) {
b.Run("新建错误", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = New(ErrInternal)
}
})
b.Run("新建格式化错误", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = Newf(ErrInternal, "error with value: %d", i)
}
})
b.Run("包装错误", func(b *testing.B) {
originalErr := fmt.Errorf("original error")
for i := 0; i < b.N; i++ {
_ = Wrap(originalErr, ErrInternal)
}
})
}
// TestConcurrentErrorCreation 并发安全性测试
func TestConcurrentErrorCreation(t *testing.T) {
concurrency := 100
done := make(chan bool, concurrency)
for i := 0; i < concurrency; i++ {
go func(index int) {
err := InternalErrorf("并发错误 %d", index)
// 验证错误基本属性
if err.Code() != ErrTypeInternal.String() {
t.Errorf("Concurrent error Code() = %v, want %v", err.Code(), ErrTypeInternal.String())
}
if err.Type() != ErrTypeInternal {
t.Errorf("Concurrent error Type() = %v, want %v", err.Type(), ErrTypeInternal)
}
done <- true
}(i)
}
// 等待所有 goroutine 完成
for i := 0; i < concurrency; i++ {
<-done
}
}
// TestConcurrentErrorCreationNoStack 并发安全性测试,不带堆栈信息
func TestConcurrentErrorCreationNoStack(t *testing.T) {
concurrency := 100
done := make(chan bool, concurrency)
for i := 0; i < concurrency; i++ {
go func(index int) {
err := InternalErrorfNoStack("并发错误 %d", index)
// 验证错误基本属性
if err.Code() != ErrTypeInternal.String() {
t.Errorf("Concurrent error Code() = %v, want %v", err.Code(), ErrTypeInternal.String())
}
if err.Type() != ErrTypeInternal {
t.Errorf("Concurrent error Type() = %v, want %v", err.Type(), ErrTypeInternal)
}
done <- true
}(i)
}
// 等待所有 goroutine 完成
for i := 0; i < concurrency; i++ {
<-done
}
}
func TestNew(t *testing.T) {
err := New(&ErrCode{
Code: "TEST_CODE",
Message: "这是一个测试错误",
HttpStatus: http.StatusBadRequest,
Type: ErrTypeBusiness,
})
t.Logf("错误: %+v", err)
t.Logf("错误代码: %s", err.Code())
t.Logf("错误消息: %s", err.Message())
t.Logf("错误HTTP状态: %d", err.HttpStatus())
t.Logf("错误类型: %s", err.Type())
}
func TestNewf(t *testing.T) {
err := Newf(&ErrCode{
Code: "TEST_CODE",
Message: "这是一个测试错误",
HttpStatus: http.StatusBadRequest,
Type: ErrTypeBusiness,
}, "这是一个格式化错误: %s", "测试")
t.Logf("错误: %+v", err)
t.Logf("错误代码: %s", err.Code())
t.Logf("错误消息: %s", err.Message())
t.Logf("错误HTTP状态: %d", err.HttpStatus())
t.Logf("错误类型: %s", err.Type())
}