-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegration_test.go
More file actions
1394 lines (1150 loc) · 35.2 KB
/
integration_test.go
File metadata and controls
1394 lines (1150 loc) · 35.2 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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gotrycatch
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"sync"
"testing"
"time"
trycatcherrors "github.com/linkerlin/gotrycatch/errors"
)
// =============================================================================
// HTTP Service Integration Tests
// =============================================================================
// TestHTTPServer_ValidationErrorHandling tests HTTP handlers with validation errors
func TestHTTPServer_ValidationErrorHandling(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var caught bool
var responseCode int
var responseBody map[string]interface{}
tb := Try(func() {
username := r.URL.Query().Get("username")
if len(username) < 3 {
panic(trycatcherrors.NewValidationError("username", "must be at least 3 characters", 1001))
}
if len(username) > 20 {
panic(trycatcherrors.NewValidationError("username", "must be at most 20 characters", 1002))
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"status": "success", "username": username})
})
tb = Catch[trycatcherrors.ValidationError](tb, func(err trycatcherrors.ValidationError) {
caught = true
responseCode = http.StatusBadRequest
responseBody = err.ToMap()
})
tb = tb.CatchAny(func(err interface{}) {
caught = true
responseCode = http.StatusInternalServerError
responseBody = map[string]interface{}{"error": fmt.Sprintf("%v", err)}
})
tb.Finally(func() {
if caught {
w.WriteHeader(responseCode)
json.NewEncoder(w).Encode(responseBody)
}
})
})
server := httptest.NewServer(handler)
defer server.Close()
tests := []struct {
name string
username string
expectStatus int
expectError bool
expectErrorFld string
}{
{"valid username", "john", http.StatusOK, false, ""},
{"too short", "ab", http.StatusBadRequest, true, "username"},
{"too long", "thisusernameiswaytoolongexceedinglimit", http.StatusBadRequest, true, "username"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resp, err := http.Get(fmt.Sprintf("%s?username=%s", server.URL, tt.username))
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != tt.expectStatus {
t.Errorf("Expected status %d, got %d", tt.expectStatus, resp.StatusCode)
}
body, _ := io.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
if tt.expectError {
if result["field"] != tt.expectErrorFld {
t.Errorf("Expected field '%s', got '%v'", tt.expectErrorFld, result["field"])
}
} else {
if result["status"] != "success" {
t.Errorf("Expected success, got %v", result)
}
}
})
}
}
// TestHTTPServer_AuthErrorHandling tests HTTP handlers with authentication errors
func TestHTTPServer_AuthErrorHandling(t *testing.T) {
validToken := "valid-token-12345"
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var responseCode int
var responseBody map[string]interface{}
tb := Try(func() {
token := r.Header.Get("Authorization")
if token == "" {
panic(trycatcherrors.NewAuthError("token_verify", "anonymous", "missing token"))
}
if token != "Bearer "+validToken {
panic(trycatcherrors.NewAuthError("token_verify", "unknown", "invalid token"))
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"status": "authenticated"})
})
tb = Catch[trycatcherrors.AuthError](tb, func(err trycatcherrors.AuthError) {
responseCode = http.StatusUnauthorized
responseBody = err.ToMap()
})
tb = tb.CatchAny(func(err interface{}) {
responseCode = http.StatusInternalServerError
responseBody = map[string]interface{}{"error": fmt.Sprintf("%v", err)}
})
tb.Finally(func() {
if responseCode != 0 {
w.WriteHeader(responseCode)
json.NewEncoder(w).Encode(responseBody)
}
})
})
server := httptest.NewServer(handler)
defer server.Close()
tests := []struct {
name string
token string
expectStatus int
}{
{"valid token", "Bearer " + validToken, http.StatusOK},
{"invalid token", "Bearer invalid-token", http.StatusUnauthorized},
{"no token", "", http.StatusUnauthorized},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, _ := http.NewRequest("GET", server.URL, nil)
if tt.token != "" {
req.Header.Set("Authorization", tt.token)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Failed to send request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != tt.expectStatus {
t.Errorf("Expected status %d, got %d", tt.expectStatus, resp.StatusCode)
}
})
}
}
// TestHTTPServer_RateLimitErrorHandling tests HTTP handlers with rate limiting
func TestHTTPServer_RateLimitErrorHandling(t *testing.T) {
var mu sync.Mutex
requestCounts := make(map[string]int)
rateLimit := 3
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
clientID := r.Header.Get("X-Client-ID")
if clientID == "" {
clientID = "anonymous"
}
var responseCode int
var responseBody map[string]interface{}
tb := Try(func() {
mu.Lock()
requestCounts[clientID]++
count := requestCounts[clientID]
mu.Unlock()
if count > rateLimit {
panic(trycatcherrors.NewRateLimitError("api", rateLimit, count, 60))
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "success",
"request": count,
})
})
tb = Catch[trycatcherrors.RateLimitError](tb, func(err trycatcherrors.RateLimitError) {
responseCode = http.StatusTooManyRequests
responseBody = err.ToMap()
})
tb.Finally(func() {
if responseCode != 0 {
w.WriteHeader(responseCode)
json.NewEncoder(w).Encode(responseBody)
}
})
})
server := httptest.NewServer(handler)
defer server.Close()
client := &http.Client{}
for i := 1; i <= 5; i++ {
req, _ := http.NewRequest("GET", server.URL, nil)
req.Header.Set("X-Client-ID", "test-client")
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request %d failed: %v", i, err)
}
defer resp.Body.Close()
if i <= rateLimit {
if resp.StatusCode != http.StatusOK {
t.Errorf("Request %d: expected 200, got %d", i, resp.StatusCode)
}
} else {
if resp.StatusCode != http.StatusTooManyRequests {
t.Errorf("Request %d: expected 429, got %d", i, resp.StatusCode)
}
}
}
}
// TestHTTPServer_MultipleErrorTypes tests handlers handling multiple error types
func TestHTTPServer_MultipleErrorTypes(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var responseCode int
var responseBody map[string]interface{}
tb := Try(func() {
action := r.URL.Query().Get("action")
switch action {
case "validate":
panic(trycatcherrors.NewValidationError("field", "invalid", 1000))
case "auth":
panic(trycatcherrors.NewAuthError("login", "user", "failed"))
case "business":
panic(trycatcherrors.NewBusinessLogicError("rule", "violation"))
case "network":
panic(trycatcherrors.NewNetworkError("http://example.com", 503))
case "database":
panic(trycatcherrors.NewDatabaseError("SELECT", "users", fmt.Errorf("connection failed")))
case "success":
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
return
}
})
tb = Catch[trycatcherrors.ValidationError](tb, func(err trycatcherrors.ValidationError) {
responseCode = http.StatusBadRequest
responseBody = err.ToMap()
})
tb = Catch[trycatcherrors.AuthError](tb, func(err trycatcherrors.AuthError) {
responseCode = http.StatusUnauthorized
responseBody = err.ToMap()
})
tb = Catch[trycatcherrors.BusinessLogicError](tb, func(err trycatcherrors.BusinessLogicError) {
responseCode = http.StatusUnprocessableEntity
responseBody = err.ToMap()
})
tb = Catch[trycatcherrors.NetworkError](tb, func(err trycatcherrors.NetworkError) {
responseCode = http.StatusBadGateway
responseBody = err.ToMap()
})
tb = Catch[trycatcherrors.DatabaseError](tb, func(err trycatcherrors.DatabaseError) {
responseCode = http.StatusServiceUnavailable
responseBody = err.ToMap()
})
tb.Finally(func() {
if responseCode != 0 {
w.WriteHeader(responseCode)
json.NewEncoder(w).Encode(responseBody)
}
})
})
server := httptest.NewServer(handler)
defer server.Close()
tests := []struct {
action string
expectStatus int
expectType string
}{
{"success", http.StatusOK, ""},
{"validate", http.StatusBadRequest, "ValidationError"},
{"auth", http.StatusUnauthorized, "AuthError"},
{"business", http.StatusUnprocessableEntity, "BusinessLogicError"},
{"network", http.StatusBadGateway, "NetworkError"},
{"database", http.StatusServiceUnavailable, "DatabaseError"},
}
for _, tt := range tests {
t.Run(tt.action, func(t *testing.T) {
resp, err := http.Get(fmt.Sprintf("%s?action=%s", server.URL, tt.action))
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != tt.expectStatus {
t.Errorf("Expected status %d, got %d", tt.expectStatus, resp.StatusCode)
}
if tt.expectType != "" {
body, _ := io.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
if result["type"] != tt.expectType {
t.Errorf("Expected type %s, got %v", tt.expectType, result["type"])
}
}
})
}
}
// =============================================================================
// File Operation Integration Tests
// =============================================================================
// TestFileOperations_WriteWithCleanup tests file operations with cleanup in Finally
func TestFileOperations_WriteWithCleanup(t *testing.T) {
tempDir := t.TempDir()
testFile := filepath.Join(tempDir, "test.txt")
var fileHandle *os.File
var writeErr error
tb := Try(func() {
var err error
fileHandle, err = os.Create(testFile)
if err != nil {
panic(trycatcherrors.NewConfigError("file", testFile, err.Error()))
}
_, writeErr = fileHandle.WriteString("Hello, World!")
if writeErr != nil {
panic(writeErr)
}
})
tb = Catch[trycatcherrors.ConfigError](tb, func(err trycatcherrors.ConfigError) {
t.Logf("Config error: %v", err)
})
tb.Finally(func() {
if fileHandle != nil {
fileHandle.Close()
}
})
if writeErr != nil {
t.Errorf("Write failed: %v", writeErr)
}
content, err := os.ReadFile(testFile)
if err != nil {
t.Fatalf("Failed to read file: %v", err)
}
if string(content) != "Hello, World!" {
t.Errorf("Expected 'Hello, World!', got '%s'", content)
}
}
// TestFileOperations_ReadNonExistent tests reading non-existent files
func TestFileOperations_ReadNonExistent(t *testing.T) {
var caughtError trycatcherrors.ConfigError
var caught bool
tb := Try(func() {
_, err := os.ReadFile("/nonexistent/path/to/file.txt")
if err != nil {
panic(trycatcherrors.NewConfigError("file", "/nonexistent/path/to/file.txt", err.Error()))
}
})
tb = Catch[trycatcherrors.ConfigError](tb, func(err trycatcherrors.ConfigError) {
caughtError = err
caught = true
})
tb.Finally(func() {
})
if !caught {
t.Error("Expected ConfigError to be caught")
}
if caughtError.Key != "file" {
t.Errorf("Expected key 'file', got '%s'", caughtError.Key)
}
}
// TestFileOperations_CreateDirectoryStructure tests directory creation with error handling
func TestFileOperations_CreateDirectoryStructure(t *testing.T) {
tempDir := t.TempDir()
createdDirs := []string{}
createdFiles := []string{}
tb := Try(func() {
dirs := []string{"src", "src/models", "src/controllers", "src/views"}
for _, dir := range dirs {
fullPath := filepath.Join(tempDir, dir)
if err := os.MkdirAll(fullPath, 0755); err != nil {
panic(trycatcherrors.NewConfigError("directory", fullPath, err.Error()))
}
createdDirs = append(createdDirs, fullPath)
}
files := map[string]string{
"src/main.go": "package main",
"src/models/user.go": "package models",
}
for filePath, content := range files {
fullPath := filepath.Join(tempDir, filePath)
if err := os.WriteFile(fullPath, []byte(content), 0644); err != nil {
panic(trycatcherrors.NewConfigError("file", fullPath, err.Error()))
}
createdFiles = append(createdFiles, fullPath)
}
})
tb = Catch[trycatcherrors.ConfigError](tb, func(err trycatcherrors.ConfigError) {
t.Errorf("Config error: %v", err)
})
tb.Finally(func() {
t.Logf("Created %d directories and %d files", len(createdDirs), len(createdFiles))
})
for _, dir := range createdDirs {
if _, err := os.Stat(dir); os.IsNotExist(err) {
t.Errorf("Directory not created: %s", dir)
}
}
for _, file := range createdFiles {
if _, err := os.Stat(file); os.IsNotExist(err) {
t.Errorf("File not created: %s", file)
}
}
}
// TestFileOperations_TempFileCleanup tests temporary file cleanup in Finally
func TestFileOperations_TempFileCleanup(t *testing.T) {
tempDir := t.TempDir()
tempFile := filepath.Join(tempDir, "temp_data.txt")
fileExists := true
tb := Try(func() {
if err := os.WriteFile(tempFile, []byte("temporary data"), 0644); err != nil {
panic(err)
}
content, err := os.ReadFile(tempFile)
if err != nil {
panic(err)
}
if string(content) != "temporary data" {
panic(fmt.Errorf("unexpected content: %s", content))
}
panic(trycatcherrors.NewBusinessLogicError("temp_check", "intentional error to test cleanup"))
})
tb = Catch[trycatcherrors.BusinessLogicError](tb, func(err trycatcherrors.BusinessLogicError) {
})
tb.Finally(func() {
if err := os.Remove(tempFile); err == nil {
fileExists = false
}
})
if fileExists {
t.Error("Temp file should have been cleaned up")
}
}
// =============================================================================
// Database Simulation Integration Tests (No Mocking)
// =============================================================================
// In-memory database simulation
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
type InMemoryDB struct {
users map[int]*User
nextID int
mu sync.RWMutex
}
func NewInMemoryDB() *InMemoryDB {
return &InMemoryDB{
users: make(map[int]*User),
nextID: 1,
}
}
func (db *InMemoryDB) Insert(user *User) (*User, error) {
db.mu.Lock()
defer db.mu.Unlock()
if user.Name == "" {
return nil, trycatcherrors.NewValidationError("name", "name is required", 2001)
}
if user.Email == "" {
return nil, trycatcherrors.NewValidationError("email", "email is required", 2002)
}
user.ID = db.nextID
db.users[user.ID] = user
db.nextID++
return user, nil
}
func (db *InMemoryDB) FindByID(id int) (*User, error) {
db.mu.RLock()
defer db.mu.RUnlock()
user, exists := db.users[id]
if !exists {
return nil, trycatcherrors.NewDatabaseError("SELECT", "users", fmt.Errorf("user not found with id %d", id))
}
return user, nil
}
func (db *InMemoryDB) Update(user *User) error {
db.mu.Lock()
defer db.mu.Unlock()
if _, exists := db.users[user.ID]; !exists {
return trycatcherrors.NewDatabaseError("UPDATE", "users", fmt.Errorf("user not found with id %d", user.ID))
}
db.users[user.ID] = user
return nil
}
func (db *InMemoryDB) Delete(id int) error {
db.mu.Lock()
defer db.mu.Unlock()
if _, exists := db.users[id]; !exists {
return trycatcherrors.NewDatabaseError("DELETE", "users", fmt.Errorf("user not found with id %d", id))
}
delete(db.users, id)
return nil
}
// TestDatabaseSimulation_CRUDOperations tests CRUD operations with Try-Catch
func TestDatabaseSimulation_CRUDOperations(t *testing.T) {
db := NewInMemoryDB()
var createdUser *User
var foundUserName string
var updateErr error
var deleted bool
tb := Try(func() {
var err error
createdUser, err = db.Insert(&User{Name: "John Doe", Email: "john@example.com"})
if err != nil {
panic(err)
}
foundUser, err := db.FindByID(createdUser.ID)
if err != nil {
panic(err)
}
foundUserName = foundUser.Name
foundUser.Name = "John Updated"
updateErr = db.Update(foundUser)
if updateErr != nil {
panic(updateErr)
}
if err := db.Delete(createdUser.ID); err != nil {
panic(err)
}
deleted = true
})
tb = Catch[trycatcherrors.ValidationError](tb, func(err trycatcherrors.ValidationError) {
t.Errorf("Validation error: %v", err)
})
tb = Catch[trycatcherrors.DatabaseError](tb, func(err trycatcherrors.DatabaseError) {
t.Errorf("Database error: %v", err)
})
tb.Finally(func() {
t.Logf("User ID %d operations completed", createdUser.ID)
})
if createdUser == nil || createdUser.ID != 1 {
t.Errorf("User creation failed")
}
if foundUserName != "John Doe" {
t.Errorf("User find failed, expected 'John Doe', got '%s'", foundUserName)
}
if updateErr != nil {
t.Errorf("User update failed")
}
if !deleted {
t.Errorf("User deletion failed")
}
}
// TestDatabaseSimulation_ValidationErrors tests validation error handling
func TestDatabaseSimulation_ValidationErrors(t *testing.T) {
db := NewInMemoryDB()
var caughtValidationError trycatcherrors.ValidationError
var caught bool
tb := Try(func() {
_, err := db.Insert(&User{Name: "", Email: "test@example.com"})
if err != nil {
panic(err)
}
})
tb = Catch[trycatcherrors.ValidationError](tb, func(err trycatcherrors.ValidationError) {
caughtValidationError = err
caught = true
})
tb = Catch[trycatcherrors.DatabaseError](tb, func(err trycatcherrors.DatabaseError) {
t.Errorf("Unexpected database error: %v", err)
})
if !caught {
t.Error("Expected ValidationError to be caught")
}
if caughtValidationError.Field != "name" {
t.Errorf("Expected field 'name', got '%s'", caughtValidationError.Field)
}
}
// TestDatabaseSimulation_NotFoundErrors tests not found error handling
func TestDatabaseSimulation_NotFoundErrors(t *testing.T) {
db := NewInMemoryDB()
var caughtDatabaseError trycatcherrors.DatabaseError
var caught bool
tb := Try(func() {
_, err := db.FindByID(999)
if err != nil {
panic(err)
}
})
tb = Catch[trycatcherrors.DatabaseError](tb, func(err trycatcherrors.DatabaseError) {
caughtDatabaseError = err
caught = true
})
if !caught {
t.Error("Expected DatabaseError to be caught")
}
if caughtDatabaseError.Operation != "SELECT" {
t.Errorf("Expected operation 'SELECT', got '%s'", caughtDatabaseError.Operation)
}
}
// =============================================================================
// Multi-Layer Application Integration Tests
// =============================================================================
// Repository layer
type UserRepository struct {
db *InMemoryDB
}
func (r *UserRepository) Create(user *User) (*User, error) {
return r.db.Insert(user)
}
func (r *UserRepository) GetByID(id int) (*User, error) {
return r.db.FindByID(id)
}
// Service layer
type UserService struct {
repo *UserRepository
}
func (s *UserService) CreateUser(name, email string) (*User, error) {
if len(name) < 2 {
return nil, trycatcherrors.NewValidationError("name", "name must be at least 2 characters", 3001)
}
user, err := s.repo.Create(&User{Name: name, Email: email})
if err != nil {
return nil, trycatcherrors.NewDatabaseError("INSERT", "users", err)
}
return user, nil
}
func (s *UserService) GetUser(id int) (*User, error) {
user, err := s.repo.GetByID(id)
if err != nil {
return nil, trycatcherrors.NewDatabaseError("SELECT", "users", err)
}
if user.Email == "" {
return nil, trycatcherrors.NewBusinessLogicError("email_required", "user must have valid email")
}
return user, nil
}
// Controller layer
type UserController struct {
service *UserService
}
func (c *UserController) HandleCreateUser(name, email string) (int, map[string]interface{}) {
var responseCode int
var responseBody map[string]interface{}
tb := Try(func() {
user, err := c.service.CreateUser(name, email)
if err != nil {
panic(err)
}
responseCode = http.StatusCreated
responseBody = map[string]interface{}{
"status": "created",
"user": user,
}
})
tb = Catch[trycatcherrors.ValidationError](tb, func(err trycatcherrors.ValidationError) {
responseCode = http.StatusBadRequest
responseBody = err.ToMap()
})
tb = Catch[trycatcherrors.DatabaseError](tb, func(err trycatcherrors.DatabaseError) {
responseCode = http.StatusInternalServerError
responseBody = err.ToMap()
})
tb.Finally(func() {
})
return responseCode, responseBody
}
func (c *UserController) HandleGetUser(id int) (int, map[string]interface{}) {
var responseCode int
var responseBody map[string]interface{}
tb := Try(func() {
user, err := c.service.GetUser(id)
if err != nil {
panic(err)
}
responseCode = http.StatusOK
responseBody = map[string]interface{}{
"status": "success",
"user": user,
}
})
tb = Catch[trycatcherrors.DatabaseError](tb, func(err trycatcherrors.DatabaseError) {
responseCode = http.StatusNotFound
responseBody = err.ToMap()
})
tb = Catch[trycatcherrors.BusinessLogicError](tb, func(err trycatcherrors.BusinessLogicError) {
responseCode = http.StatusUnprocessableEntity
responseBody = err.ToMap()
})
return responseCode, responseBody
}
// TestMultiLayerApplication_CreateUser tests the full Controller -> Service -> Repository chain
func TestMultiLayerApplication_CreateUser(t *testing.T) {
db := NewInMemoryDB()
repo := &UserRepository{db: db}
service := &UserService{repo: repo}
controller := &UserController{service: service}
tests := []struct {
name string
userName string
email string
expectStatus int
}{
{"valid user", "John Doe", "john@example.com", http.StatusCreated},
{"name too short", "J", "j@example.com", http.StatusBadRequest},
{"empty name", "", "empty@example.com", http.StatusBadRequest},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
code, body := controller.HandleCreateUser(tt.userName, tt.email)
if code != tt.expectStatus {
t.Errorf("Expected status %d, got %d", tt.expectStatus, code)
}
if tt.expectStatus == http.StatusCreated {
if body["status"] != "created" {
t.Errorf("Expected status 'created', got %v", body["status"])
}
}
})
}
}
// TestMultiLayerApplication_GetUser tests user retrieval through all layers
func TestMultiLayerApplication_GetUser(t *testing.T) {
db := NewInMemoryDB()
repo := &UserRepository{db: db}
service := &UserService{repo: repo}
controller := &UserController{service: service}
var createdID int
tb := Try(func() {
user, err := db.Insert(&User{Name: "Test User", Email: "test@example.com"})
if err != nil {
panic(err)
}
createdID = user.ID
})
tb.Finally(func() {})
t.Run("get existing user", func(t *testing.T) {
code, body := controller.HandleGetUser(createdID)
if code != http.StatusOK {
t.Errorf("Expected status %d, got %d", http.StatusOK, code)
}
if body["status"] != "success" {
t.Errorf("Expected status 'success', got %v", body["status"])
}
})
t.Run("get non-existent user", func(t *testing.T) {
code, body := controller.HandleGetUser(9999)
if code != http.StatusNotFound {
t.Errorf("Expected status %d, got %d", http.StatusNotFound, code)
}
if body["type"] != "DatabaseError" {
t.Errorf("Expected type 'DatabaseError', got %v", body["type"])
}
})
}
// =============================================================================
// Error Propagation Integration Tests
// =============================================================================
// TestErrorPropagation_ThroughMultipleLayers tests error propagation through layers
func TestErrorPropagation_ThroughMultipleLayers(t *testing.T) {
db := NewInMemoryDB()
var propagatedError interface{}
var errorType string
tb := Try(func() {
_, err := db.Insert(&User{Name: "", Email: "test@example.com"})
if err != nil {
panic(err)
}
})
tb = Catch[trycatcherrors.ValidationError](tb, func(err trycatcherrors.ValidationError) {
propagatedError = err
errorType = "ValidationError"
})
tb = Catch[trycatcherrors.DatabaseError](tb, func(err trycatcherrors.DatabaseError) {
propagatedError = err
errorType = "DatabaseError"
})
tb.Finally(func() {})
if propagatedError == nil {
t.Error("Expected error to be propagated")
}
if errorType != "ValidationError" {
t.Errorf("Expected ValidationError, got %s", errorType)
}
}
// TestErrorPropagation_NestedTryCatch tests nested try-catch blocks
func TestErrorPropagation_NestedTryCatch(t *testing.T) {
var outerCaught bool
var innerCaught bool
var finallyCalled bool
tb := Try(func() {
tbInner := Try(func() {
panic(trycatcherrors.NewValidationError("inner", "inner error", 1))
})
tbInner = Catch[trycatcherrors.ValidationError](tbInner, func(err trycatcherrors.ValidationError) {
innerCaught = true
panic(trycatcherrors.NewBusinessLogicError("outer", "propagated from inner"))
})
tbInner.Finally(func() {})
})
tb = Catch[trycatcherrors.BusinessLogicError](tb, func(err trycatcherrors.BusinessLogicError) {
outerCaught = true
})
tb.Finally(func() {
finallyCalled = true
})
if !innerCaught {
t.Error("Inner catch not called")
}
if !outerCaught {
t.Error("Outer catch not called")
}
if !finallyCalled {
t.Error("Finally not called")
}
}
// =============================================================================
// Concurrent Integration Tests
// =============================================================================
// TestConcurrent_HTTPRequests tests concurrent HTTP request handling
func TestConcurrent_HTTPRequests(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var responseCode int
tb := Try(func() {
time.Sleep(10 * time.Millisecond)
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
})
tb = tb.CatchAny(func(err interface{}) {
responseCode = http.StatusInternalServerError
})
tb.Finally(func() {
if responseCode != 0 {
w.WriteHeader(responseCode)
}
})
})
server := httptest.NewServer(handler)