-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_test.go
More file actions
1083 lines (941 loc) · 28.5 KB
/
api_test.go
File metadata and controls
1083 lines (941 loc) · 28.5 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 protolite
import (
"reflect"
"strings"
"testing"
"github.com/anirudhraja/protolite/schema"
"github.com/anirudhraja/protolite/wire"
)
func TestProtolite_Parse(t *testing.T) {
proto := NewProtolite([]string{""})
t.Run("empty_data", func(t *testing.T) {
result, err := proto.Parse([]byte{})
if err != nil {
t.Fatalf("Parse failed: %v", err)
}
if len(result) != 0 {
t.Errorf("Expected empty result, got %v", result)
}
})
t.Run("simple_varint", func(t *testing.T) {
// Create a simple protobuf message: field 1 = varint 42
encoder := wire.NewEncoder()
// Field tag for field 1, wire type varint (0)
ve := wire.NewVarintEncoder(encoder)
tag := wire.MakeTag(wire.FieldNumber(1), wire.WireVarint)
ve.EncodeVarint(uint64(tag))
ve.EncodeVarint(42)
result, err := proto.Parse(encoder.Bytes())
if err != nil {
t.Fatalf("Parse failed: %v", err)
}
expected := map[string]interface{}{
"field_1": map[string]interface{}{
"type": "varint",
"value": uint64(42),
},
}
if !reflect.DeepEqual(result, expected) {
t.Errorf("Expected %v, got %v", expected, result)
}
})
t.Run("multiple_fields", func(t *testing.T) {
// Create protobuf with multiple fields
encoder := wire.NewEncoder()
ve := wire.NewVarintEncoder(encoder)
be := wire.NewBytesEncoder(encoder)
// Field 1: varint 123
tag1 := wire.MakeTag(wire.FieldNumber(1), wire.WireVarint)
ve.EncodeVarint(uint64(tag1))
ve.EncodeVarint(123)
// Field 2: string "hello"
tag2 := wire.MakeTag(wire.FieldNumber(2), wire.WireBytes)
ve.EncodeVarint(uint64(tag2))
be.EncodeString("hello")
result, err := proto.Parse(encoder.Bytes())
if err != nil {
t.Fatalf("Parse failed: %v", err)
}
if len(result) != 2 {
t.Errorf("Expected 2 fields, got %d", len(result))
}
// Check field 1
field1, ok := result["field_1"].(map[string]interface{})
if !ok {
t.Errorf("field_1 should be a map")
} else {
if field1["type"] != "varint" || field1["value"] != uint64(123) {
t.Errorf("field_1 incorrect: %v", field1)
}
}
// Check field 2
field2, ok := result["field_2"].(map[string]interface{})
if !ok {
t.Errorf("field_2 should be a map")
} else {
if field2["type"] != "bytes" {
t.Errorf("field_2 type incorrect: %v", field2["type"])
}
if bytes, ok := field2["value"].([]byte); !ok || string(bytes) != "hello" {
t.Errorf("field_2 value incorrect: %v", field2["value"])
}
}
})
}
func TestProtolite_WithSchema(t *testing.T) {
proto := NewProtolite([]string{""})
// Define a test message schema
testMessage := &schema.Message{
Name: "TestMessage",
Fields: []*schema.Field{
{
Name: "id",
Number: 1,
Type: schema.FieldType{
Kind: schema.KindPrimitive,
PrimitiveType: schema.TypeInt32,
},
},
{
Name: "name",
Number: 2,
Type: schema.FieldType{
Kind: schema.KindPrimitive,
PrimitiveType: schema.TypeString,
},
},
{
Name: "active",
Number: 3,
Type: schema.FieldType{
Kind: schema.KindPrimitive,
PrimitiveType: schema.TypeBool,
},
},
},
}
// We need to manually create a registry with the message since RegisterSchema isn't implemented
// For testing, we'll use the wire functions directly
testData := map[string]interface{}{
"id": int32(123),
"name": "test message",
"active": true,
}
t.Run("marshal_unmarshal_roundtrip", func(t *testing.T) {
// Encode using wire functions
encodedData, err := wire.EncodeMessage(testData, testMessage, nil)
if err != nil {
t.Fatalf("Failed to encode: %v", err)
}
// Parse using schema-less parsing
result, err := proto.Parse(encodedData)
if err != nil {
t.Fatalf("Parse failed: %v", err)
}
// Should have 3 fields
if len(result) != 3 {
t.Errorf("Expected 3 fields, got %d", len(result))
}
// Check that all fields are present
fields := []string{"field_1", "field_2", "field_3"}
for _, field := range fields {
if _, ok := result[field]; !ok {
t.Errorf("Missing field: %s", field)
}
}
})
}
func TestProtolite_UnmarshalToStruct(t *testing.T) {
proto := &protolite{}
// Define a Go struct for testing
type TestStruct struct {
ID int32 `json:"id"`
Name string `json:"name"`
Active bool `json:"active"`
}
testData := map[string]interface{}{
"id": int32(123),
"name": "test name",
"active": true,
}
t.Run("map_to_struct", func(t *testing.T) {
var result TestStruct
err := proto.mapToStruct(testData, &result)
if err != nil {
t.Fatalf("mapToStruct failed: %v", err)
}
if result.ID != 123 {
t.Errorf("Expected ID=123, got %d", result.ID)
}
if result.Name != "test name" {
t.Errorf("Expected Name='test name', got '%s'", result.Name)
}
if !result.Active {
t.Errorf("Expected Active=true, got %v", result.Active)
}
})
t.Run("snake_case_conversion", func(t *testing.T) {
type TestStruct2 struct {
UserID int32 `json:"user_id"`
UserName string `json:"user_name"`
}
testData2 := map[string]interface{}{
"user_id": int32(456),
"user_name": "john doe",
}
var result TestStruct2
err := proto.mapToStruct(testData2, &result)
if err != nil {
t.Fatalf("mapToStruct failed: %v", err)
}
if result.UserID != 456 {
t.Errorf("Expected UserID=456, got %d", result.UserID)
}
if result.UserName != "john doe" {
t.Errorf("Expected UserName='john doe', got '%s'", result.UserName)
}
})
t.Run("invalid_target", func(t *testing.T) {
var notAPointer TestStruct
err := proto.mapToStruct(testData, notAPointer)
if err == nil {
t.Error("Expected error for non-pointer target")
}
var notAStruct *string
err = proto.mapToStruct(testData, notAStruct)
if err == nil {
t.Error("Expected error for non-struct target")
}
})
}
func TestProtolite_toSnakeCase(t *testing.T) {
tests := []struct {
input string
expected string
}{
{"", ""},
{"ID", "id"},
{"UserID", "user_id"},
{"UserName", "user_name"},
{"XMLParser", "xml_parser"},
{"HTTPSConnection", "https_connection"},
{"SimpleField", "simple_field"},
{"alreadySnake", "already_snake"},
}
for _, test := range tests {
result := toSnakeCase(test.input)
if result != test.expected {
t.Errorf("toSnakeCase(%q) = %q, expected %q", test.input, result, test.expected)
}
}
}
func TestProtolite_setFieldValue(t *testing.T) {
proto := &protolite{}
t.Run("string_field", func(t *testing.T) {
type TestStruct struct {
Name string
}
var s TestStruct
field := reflect.ValueOf(&s).Elem().Field(0)
err := proto.setFieldValue(field, "test value")
if err != nil {
t.Fatalf("setFieldValue failed: %v", err)
}
if s.Name != "test value" {
t.Errorf("Expected 'test value', got '%s'", s.Name)
}
})
t.Run("int_field", func(t *testing.T) {
type TestStruct struct {
ID int32
}
var s TestStruct
field := reflect.ValueOf(&s).Elem().Field(0)
err := proto.setFieldValue(field, int32(123))
if err != nil {
t.Fatalf("setFieldValue failed: %v", err)
}
if s.ID != 123 {
t.Errorf("Expected 123, got %d", s.ID)
}
})
t.Run("bool_field", func(t *testing.T) {
type TestStruct struct {
Active bool
}
var s TestStruct
field := reflect.ValueOf(&s).Elem().Field(0)
err := proto.setFieldValue(field, true)
if err != nil {
t.Fatalf("setFieldValue failed: %v", err)
}
if !s.Active {
t.Errorf("Expected true, got %v", s.Active)
}
})
t.Run("type_mismatch", func(t *testing.T) {
type TestStruct struct {
Name string
}
var s TestStruct
field := reflect.ValueOf(&s).Elem().Field(0)
err := proto.setFieldValue(field, 123)
if err == nil {
t.Error("Expected error for type mismatch")
}
})
t.Run("nil_value", func(t *testing.T) {
type TestStruct struct {
Name string
}
var s TestStruct
field := reflect.ValueOf(&s).Elem().Field(0)
err := proto.setFieldValue(field, nil)
if err != nil {
t.Fatalf("setFieldValue failed for nil: %v", err)
}
// Name should remain empty string
if s.Name != "" {
t.Errorf("Expected empty string, got '%s'", s.Name)
}
})
}
func TestProtolite_SchemaRequired(t *testing.T) {
proto := NewProtolite([]string{""})
t.Run("load_schema_from_file", func(t *testing.T) {
// Test that LoadSchemaFromFile works (even if the file doesn't exist, it should return a proper error)
err := proto.LoadSchemaFromFile("/nonexistent/path.proto")
if err == nil {
t.Error("Expected error for non-existent file")
}
// Should get a "path does not exist" error from the registry
if !strings.Contains(err.Error(), "path does not exist") {
t.Errorf("Expected path error, got: %v", err)
}
})
}
func TestProtolite_Integration(t *testing.T) {
// This test demonstrates the full workflow of encoding and parsing
t.Run("encode_and_parse_workflow", func(t *testing.T) {
// Define a message schema
message := &schema.Message{
Name: "User",
Fields: []*schema.Field{
{
Name: "id",
Number: 1,
Type: schema.FieldType{
Kind: schema.KindPrimitive,
PrimitiveType: schema.TypeInt32,
},
},
{
Name: "email",
Number: 2,
Type: schema.FieldType{
Kind: schema.KindPrimitive,
PrimitiveType: schema.TypeString,
},
},
{
Name: "verified",
Number: 3,
Type: schema.FieldType{
Kind: schema.KindPrimitive,
PrimitiveType: schema.TypeBool,
},
},
},
}
// Create test data
userData := map[string]interface{}{
"id": int32(12345),
"email": "user@example.com",
"verified": true,
}
// Encode using wire functions (since MarshalWithSchema needs registry)
encodedData, err := wire.EncodeMessage(userData, message, nil)
if err != nil {
t.Fatalf("Failed to encode: %v", err)
}
// Parse without schema using Protolite
proto := NewProtolite([]string{""})
parsedData, err := proto.Parse(encodedData)
if err != nil {
t.Fatalf("Failed to parse: %v", err)
}
// Verify we got the expected structure
if len(parsedData) != 3 {
t.Errorf("Expected 3 fields, got %d", len(parsedData))
}
// Check field 1 (id)
if field1, ok := parsedData["field_1"].(map[string]interface{}); ok {
if field1["type"] != "varint" {
t.Errorf("field_1 should be varint type")
}
if field1["value"] != uint64(12345) {
t.Errorf("field_1 value should be 12345, got %v", field1["value"])
}
} else {
t.Error("field_1 missing or wrong type")
}
// Check field 2 (email)
if field2, ok := parsedData["field_2"].(map[string]interface{}); ok {
if field2["type"] != "bytes" {
t.Errorf("field_2 should be bytes type")
}
if bytes, ok := field2["value"].([]byte); !ok || string(bytes) != "user@example.com" {
t.Errorf("field_2 value should be 'user@example.com', got %v", field2["value"])
}
} else {
t.Error("field_2 missing or wrong type")
}
// Check field 3 (verified)
if field3, ok := parsedData["field_3"].(map[string]interface{}); ok {
if field3["type"] != "varint" {
t.Errorf("field_3 should be varint type")
}
if field3["value"] != uint64(1) { // true = 1
t.Errorf("field_3 value should be 1, got %v", field3["value"])
}
} else {
t.Error("field_3 missing or wrong type")
}
})
}
func TestProtolite_UnmarshalWithSchema(t *testing.T) {
proto := NewProtolite([]string{"", "sampleapp/testdata"})
t.Run("unmarshal_with_schema", func(t *testing.T) {
if err := proto.LoadSchemaFromFile("sampleapp/testdata/post.proto"); err != nil {
t.Fatalf("Failed to load post.proto: %v", err)
}
if err := proto.LoadSchemaFromFile("sampleapp/testdata/user.proto"); err != nil {
t.Fatalf("Failed to load user.proto: %v", err)
}
// Verify both files are loaded
pImpl := proto.(*protolite)
protoFiles := pImpl.registry.ListProtoFiles()
if len(protoFiles) != 2 {
t.Errorf("Expected 2 proto files, got %d", len(protoFiles))
for _, path := range protoFiles {
t.Logf("Loaded file: %s", path)
}
}
// Check specific files exist
hasUser := false
hasPost := false
for _, path := range protoFiles {
if path == "sampleapp/testdata/user.proto" {
hasUser = true
}
if path == "sampleapp/testdata/post.proto" {
hasPost = true
}
}
if !hasUser {
t.Error("user.proto not found in registry")
}
if !hasPost {
t.Error("post.proto not found in registry")
}
// Create User data with 2 Posts
userData := map[string]interface{}{
"id": int32(1),
"name": "John Doe",
"email": "john.doe@example.com",
"active": true,
"status": "USER_ACTIVE", // ACTIVE
"posts": []map[string]interface{}{
{
"id": int32(101),
"title": "My First Blog Post",
"content": "This is my first blog post about Go programming and protobuf.",
"author_id": int32(1),
"status": "POST_PUBLISHED", // PUBLISHED
"tags": []string{"go", "programming", "protobuf"},
"created_at": int64(1640995200), // 2022-01-01 00:00:00 UTC
"updated_at": int64(1640995200),
"view_count": int32(150),
"featured": true,
},
{
"id": int32(102),
"title": "Advanced Protobuf Patterns",
"content": "In this post, I'll share advanced protobuf patterns and best practices.",
"author_id": int32(1),
"status": "POST_PUBLISHED", // PUBLISHED
"tags": []string{"protobuf", "advanced", "patterns"},
"created_at": int64(1641081600), // 2022-01-02 00:00:00 UTC
"updated_at": int64(1641168000), // 2022-01-03 00:00:00 UTC (updated)
"view_count": int32(275),
"featured": false,
},
},
"metadata": map[string]string{
"timezone": "UTC",
"theme": "dark",
"language": "en",
"newsletter": "subscribed",
},
"created_at": int64(1609459200), // 2021-01-01 00:00:00 UTC
"scores": []int32{42, 39, 21},
"cool_list": []interface{}{int32(42), nil, int32(39), int32(21)},
"show_me_null": map[string]interface{}{
"null": nil,
},
"graphql_union": map[string]interface{}{
"__typename": "Number",
"number": int32(42),
},
"raw_json": map[string]interface{}{
"lat": 1.23,
"long": 4.56,
},
"fixed32_list": []interface{}{uint32(1), uint32(2), uint32(3)},
}
t.Logf("Original User Data: %+v", userData)
// Marshal the user data with schema
encodedData, err := proto.MarshalWithSchema(userData, "User")
if err != nil {
t.Fatalf("Failed to marshal user data: %v", err)
}
t.Logf("Encoded data size: %d bytes", len(encodedData))
// Test Parse (schema-less)
parsedData, err := proto.Parse(encodedData)
if err != nil {
t.Fatalf("Failed to parse data: %v", err)
}
t.Logf("Parsed data (schema-less): %+v", parsedData)
// Test UnmarshalWithSchema (schema-based)
userMap, err := proto.UnmarshalWithSchema(encodedData, "User")
if err != nil {
t.Fatalf("Failed to unmarshal: %v", err)
}
t.Logf("Unmarshaled User: %+v", userMap)
// Verify user fields
if userMap["id"] != int32(1) {
t.Errorf("Expected user id=1, got %v", userMap["id"])
}
if userMap["name"] != "John Doe" {
t.Errorf("Expected user name='John Doe', got %v", userMap["name"])
}
if userMap["email"] != "john.doe@example.com" {
t.Errorf("Expected user email='john.doe@example.com', got %v", userMap["email"])
}
if userMap["active"] != true {
t.Errorf("Expected user active=true, got %v", userMap["active"])
}
if userMap["status"] != "USER_ACTIVE" {
t.Errorf("Expected user status=1, got %v", userMap["status"])
}
// Verify posts
posts, ok := userMap["posts"].([]interface{})
if !ok {
t.Fatalf("Expected posts to be a slice, got %T", userMap["posts"])
}
if len(posts) != 2 {
t.Errorf("Expected 2 posts, got %d", len(posts))
}
// Verify first post
if len(posts) > 0 {
post1, ok := posts[0].(map[string]interface{})
if !ok {
t.Fatalf("Expected first post to be a map, got %T", posts[0])
}
if post1["id"] != int32(101) {
t.Errorf("Expected first post id=101, got %v", post1["id"])
}
if post1["title"] != "My First Blog Post" {
t.Errorf("Expected first post title='My First Blog Post', got %v", post1["title"])
}
if post1["author_id"] != int32(1) {
t.Errorf("Expected first post author_id=1, got %v", post1["author_id"])
}
if post1["status"] != "POST_PUBLISHED" {
t.Errorf("Expected first post status=1, got %v", post1["status"])
}
if post1["view_count"] != int32(150) {
t.Errorf("Expected first post view_count=150, got %v", post1["view_count"])
}
if post1["featured"] != true {
t.Errorf("Expected first post featured=true, got %v", post1["featured"])
}
// Check tags
tags1, ok := post1["tags"].([]interface{})
if !ok {
t.Errorf("Expected first post tags to be a slice, got %T", post1["tags"])
} else if len(tags1) != 3 {
t.Errorf("Expected first post to have 3 tags, got %d", len(tags1))
} else {
expectedTags1 := []string{"go", "programming", "protobuf"}
for i, tag := range expectedTags1 {
if i < len(tags1) && tags1[i] != tag {
t.Errorf("Expected first post tag[%d]='%s', got %v", i, tag, tags1[i])
}
}
}
t.Logf("First Post: %+v", post1)
}
// Verify second post
if len(posts) > 1 {
post2, ok := posts[1].(map[string]interface{})
if !ok {
t.Fatalf("Expected second post to be a map, got %T", posts[1])
}
if post2["id"] != int32(102) {
t.Errorf("Expected second post id=102, got %v", post2["id"])
}
if post2["title"] != "Advanced Protobuf Patterns" {
t.Errorf("Expected second post title='Advanced Protobuf Patterns', got %v", post2["title"])
}
if post2["author_id"] != int32(1) {
t.Errorf("Expected second post author_id=1, got %v", post2["author_id"])
}
if post2["status"] != "POST_PUBLISHED" {
t.Errorf("Expected second post status=1, got %v", post2["status"])
}
if post2["view_count"] != int32(275) {
t.Errorf("Expected second post view_count=275, got %v", post2["view_count"])
}
if post2["featured"] != false {
t.Errorf("Expected second post featured=false, got %v", post2["featured"])
}
// Check tags
tags2, ok := post2["tags"].([]interface{})
if !ok {
t.Errorf("Expected second post tags to be a slice, got %T", post2["tags"])
} else if len(tags2) != 3 {
t.Errorf("Expected second post to have 3 tags, got %d", len(tags2))
} else {
expectedTags2 := []string{"protobuf", "advanced", "patterns"}
for i, tag := range expectedTags2 {
if i < len(tags2) && tags2[i] != tag {
t.Errorf("Expected second post tag[%d]='%s', got %v", i, tag, tags2[i])
}
}
}
t.Logf("Second Post: %+v", post2)
}
// Verify metadata
metadata, ok := userMap["metadata"].(map[string]interface{})
if !ok {
t.Errorf("Expected metadata to be a map[string]interface{}, got %T", userMap["metadata"])
} else {
expectedMetadata := map[string]string{
"timezone": "UTC",
"theme": "dark",
"language": "en",
"newsletter": "subscribed",
}
for key, expectedValue := range expectedMetadata {
if metadata[key] != expectedValue {
t.Errorf("Expected metadata[%s]='%s', got %v", key, expectedValue, metadata[key])
}
}
}
// Verify created_at
if userMap["created_at"] != int64(1609459200) {
t.Errorf("Expected user created_at=1609459200, got %v", userMap["created_at"])
}
// Verify scores
scores, ok := userMap["scores"].([]interface{})
if !ok {
t.Fatalf("Expected scores to be a slice, got %T", userMap["scores"])
}
gotScores := make([]int32, 0, len(scores))
for i := 0; i < len(scores); i++ {
gotScores = append(gotScores, scores[i].(int32))
}
if !reflect.DeepEqual(userData["scores"], gotScores) {
t.Fatalf("Expected scores to be %v, got %v", userData["scores"], gotScores)
}
// Verify cool_list
coolList, ok := userMap["cool_list"].([]interface{})
if !ok {
t.Fatalf("Expected cool_list to be a slice, got %T", userMap["cool_list"])
}
if !reflect.DeepEqual(userData["cool_list"], coolList) {
t.Fatalf("Expected cool_list to be %v, got %v", userData["cool_list"], coolList)
}
// Verify show_me_null
showMeNull, ok := userMap["show_me_null"].(map[string]interface{})
if !ok {
t.Fatalf("Expected show_me_null to be a map, got %T", userMap["show_me_null"])
}
null, ok := showMeNull["null"]
if !ok {
t.Fatalf("Expected null key present in map")
}
if null != nil {
t.Fatalf("Expected nil value of key null, got %v", null)
}
// Verify graphql_union
graphqlUnion, ok := userMap["graphql_union"].(map[string]interface{})
if !ok {
t.Fatalf("Expected graphql_union to be a map, got %T", userMap["graphql_union"])
}
if !reflect.DeepEqual(userData["graphql_union"], graphqlUnion) {
t.Fatalf("Expected graphql_union to be %v, got %v", userData["graphql_union"], graphqlUnion)
}
// Verify raw_json
rawJSON, ok := userMap["raw_json"].(map[string]interface{})
if !ok {
t.Fatalf("Expected raw_json to be a map, got %T", userMap["raw_json"])
}
if !reflect.DeepEqual(userData["raw_json"], rawJSON) {
t.Fatalf("Expected raw_json to be %v, got %v", userData["raw_json"], rawJSON)
}
// Verify fixed32 list
fixed32List, ok := userMap["fixed32_list"]
if !ok {
t.Fatalf("Expected fixed32_list to be list, got %T", userMap["fixed32_list"])
}
if !reflect.DeepEqual(fixed32List, userData["fixed32_list"]) {
t.Fatalf("Expected fixed32_list to be %v, got %v", userData["fixed32_list"], fixed32List)
}
t.Log("✅ User-Posts relationship test completed successfully!")
t.Log("✅ Both proto files loaded correctly")
t.Log("✅ User with 2 Posts marshaled and unmarshaled correctly")
t.Log("✅ All field values verified")
})
}
// TestLoadSchemaFromReader tests loading schema from an io.Reader
func TestLoadSchemaFromReader(t *testing.T) {
// Create a simple proto schema as a string
protoContent := `
syntax = "proto3";
package example;
message SimpleUser {
int32 id = 1;
string name = 2;
string email = 3;
bool active = 4;
}
`
// Create a reader from the proto content
reader := strings.NewReader(protoContent)
// Create Protolite instance with the testdata directory for any imports
proto := NewProtolite([]string{"./sampleapp/testdata"})
// Load schema from reader with a unique identifier
err := proto.LoadSchemaFromReader(reader, "simple_user.proto")
if err != nil {
t.Fatalf("Failed to load schema from reader: %v", err)
}
// Test that we can use the schema
testData := map[string]interface{}{
"id": int32(123),
"name": "John Doe",
"email": "john@example.com",
"active": true,
}
// Marshal the data
encoded, err := proto.MarshalWithSchema(testData, "SimpleUser")
if err != nil {
t.Fatalf("Failed to marshal: %v", err)
}
if len(encoded) == 0 {
t.Fatal("Expected non-empty encoded data")
}
// Unmarshal back
result, err := proto.UnmarshalWithSchema(encoded, "SimpleUser")
if err != nil {
t.Fatalf("Failed to unmarshal: %v", err)
}
// Verify the data
if result["id"].(int32) != 123 {
t.Errorf("Expected id=123, got %v", result["id"])
}
if result["name"].(string) != "John Doe" {
t.Errorf("Expected name='John Doe', got %v", result["name"])
}
if result["email"].(string) != "john@example.com" {
t.Errorf("Expected email='john@example.com', got %v", result["email"])
}
if result["active"].(bool) != true {
t.Errorf("Expected active=true, got %v", result["active"])
}
}
func TestLoadSchemaFromReaderWithStruct(t *testing.T) {
// Create a proto schema
protoContent := `
syntax = "proto3";
package example;
message Product {
int32 product_id = 1;
string product_name = 2;
double price = 3;
bool in_stock = 4;
}
`
reader := strings.NewReader(protoContent)
proto := NewProtolite([]string{"./sampleapp/testdata"})
err := proto.LoadSchemaFromReader(reader, "product.proto")
if err != nil {
t.Fatalf("Failed to load schema from reader: %v", err)
}
// Define a matching Go struct
type Product struct {
ProductID int32 `json:"product_id"`
ProductName string `json:"product_name"`
Price float64 `json:"price"`
InStock bool `json:"in_stock"`
}
testData := map[string]interface{}{
"product_id": int32(456),
"product_name": "Laptop",
"price": 999.99,
"in_stock": true,
}
// Marshal
encoded, err := proto.MarshalWithSchema(testData, "Product")
if err != nil {
t.Fatalf("Failed to marshal: %v", err)
}
// Unmarshal to struct
var product Product
err = proto.UnmarshalToStruct(encoded, "Product", &product)
if err != nil {
t.Fatalf("Failed to unmarshal to struct: %v", err)
}
// Verify
if product.ProductID != 456 {
t.Errorf("Expected ProductID=456, got %v", product.ProductID)
}
if product.ProductName != "Laptop" {
t.Errorf("Expected ProductName='Laptop', got %v", product.ProductName)
}
if product.Price != 999.99 {
t.Errorf("Expected Price=999.99, got %v", product.Price)
}
if product.InStock != true {
t.Errorf("Expected InStock=true, got %v", product.InStock)
}
}
// TestLoadSchemaMultipleTimes verifies that loading the same schema multiple times
// doesn't cause re-processing of already loaded proto files
func TestLoadSchemaMultipleTimes(t *testing.T) {
proto := NewProtolite([]string{"./sampleapp/testdata"})
// Load the same schema multiple times
err := proto.LoadSchemaFromFile("user.proto")
if err != nil {
t.Fatalf("First load failed: %v", err)
}
// Load again - should skip already processed files
err = proto.LoadSchemaFromFile("user.proto")
if err != nil {
t.Fatalf("Second load failed: %v", err)
}
// Load again - should still work
err = proto.LoadSchemaFromFile("user.proto")
if err != nil {
t.Fatalf("Third load failed: %v", err)
}
// Verify that the schema is still functional
testData := map[string]interface{}{
"id": int32(1),
"name": "Test User",
"active": true,
}
encoded, err := proto.MarshalWithSchema(testData, "User")
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
result, err := proto.UnmarshalWithSchema(encoded, "User")
if err != nil {
t.Fatalf("Unmarshal failed: %v", err)
}
if result["id"].(int32) != 1 {
t.Errorf("Expected id=1, got %v", result["id"])
}
if result["name"].(string) != "Test User" {
t.Errorf("Expected name='Test User', got %v", result["name"])
}
}
// TestLoadSchemaFromReaderMultipleTimes verifies deduplication with reader-based loading
func TestLoadSchemaFromReaderMultipleTimes(t *testing.T) {
protoContent := `
syntax = "proto3";
package test;
message Item {
int32 id = 1;
string name = 2;
}
`
proto := NewProtolite([]string{"./sampleapp/testdata"})
// Load from reader first time
reader1 := strings.NewReader(protoContent)
err := proto.LoadSchemaFromReader(reader1, "item.proto")
if err != nil {
t.Fatalf("First load failed: %v", err)
}
// Load from reader second time with same identifier - should skip
reader2 := strings.NewReader(protoContent)
err = proto.LoadSchemaFromReader(reader2, "item.proto")