forked from apache/fory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_generated_code.py
More file actions
1184 lines (1006 loc) · 33.2 KB
/
test_generated_code.py
File metadata and controls
1184 lines (1006 loc) · 33.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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""Tests for generated code consistency across frontends."""
from pathlib import Path
from textwrap import dedent
from typing import Dict, Tuple, Type
import pytest
from fory_compiler.cli import resolve_imports
from fory_compiler.frontend.fbs import FBSFrontend
from fory_compiler.frontend.fdl.lexer import Lexer
from fory_compiler.frontend.fdl.parser import Parser
from fory_compiler.frontend.proto import ProtoFrontend
from fory_compiler.generators.base import BaseGenerator, GeneratorOptions
from fory_compiler.generators.cpp import CppGenerator
from fory_compiler.generators.go import GoGenerator
from fory_compiler.generators.java import JavaGenerator
from fory_compiler.generators.python import PythonGenerator
from fory_compiler.generators.rust import RustGenerator
from fory_compiler.generators.csharp import CSharpGenerator
from fory_compiler.generators.javascript import JavaScriptGenerator
from fory_compiler.generators.swift import SwiftGenerator
from fory_compiler.generators.dart import DartGenerator
from fory_compiler.ir.ast import Schema
from fory_compiler.ir.validator import SchemaValidator
GENERATOR_CLASSES: Tuple[Type[BaseGenerator], ...] = (
JavaGenerator,
PythonGenerator,
CppGenerator,
RustGenerator,
GoGenerator,
CSharpGenerator,
JavaScriptGenerator,
SwiftGenerator,
DartGenerator,
)
def parse_fdl(source: str) -> Schema:
return Parser(Lexer(source).tokenize()).parse()
def parse_proto(source: str) -> Schema:
return ProtoFrontend().parse(source)
def parse_fbs(source: str) -> Schema:
return FBSFrontend().parse(source)
def generate_files(
schema: Schema, generator_cls: Type[BaseGenerator]
) -> Dict[str, str]:
options = GeneratorOptions(output_dir=Path("/tmp"))
generator = generator_cls(schema, options)
return {item.path: item.content for item in generator.generate()}
def render_files(files: Dict[str, str]) -> str:
return "\n".join(content for _, content in sorted(files.items()))
def assert_language_outputs_equal(
schemas: Dict[str, Schema], generator_cls: Type[BaseGenerator]
) -> None:
baseline_label = None
baseline_files: Dict[str, str] = {}
for label, schema in schemas.items():
files = generate_files(schema, generator_cls)
if baseline_label is None:
baseline_label = label
baseline_files = files
continue
assert files == baseline_files, (
f"{generator_cls.language_name} output mismatch for {label} vs {baseline_label}"
)
def assert_all_languages_equal(schemas: Dict[str, Schema]) -> None:
for generator_cls in GENERATOR_CLASSES:
assert_language_outputs_equal(schemas, generator_cls)
def test_generated_code_scalar_types_equivalent():
fdl = dedent(
"""
package gen;
message ScalarTypes {
bool active = 1;
int32 i32 = 2;
int64 i64 = 3;
uint32 u32 = 4;
uint64 u64 = 5;
float32 f32 = 6;
float64 f64 = 7;
string name = 8;
}
"""
)
proto = dedent(
"""
syntax = "proto3";
package gen;
message ScalarTypes {
bool active = 1;
sint32 i32 = 2;
sint64 i64 = 3;
uint32 u32 = 4;
uint64 u64 = 5;
float f32 = 6;
double f64 = 7;
string name = 8;
}
"""
)
fbs = dedent(
"""
namespace gen;
table ScalarTypes {
active:bool;
i32:int;
i64:long;
u32:uint;
u64:ulong;
f32:float;
f64:double;
name:string;
}
"""
)
schemas = {
"fdl": parse_fdl(fdl),
"proto": parse_proto(proto),
"fbs": parse_fbs(fbs),
}
assert_all_languages_equal(schemas)
def test_rust_generated_code_uses_fory_temporal_carriers():
schema = parse_fdl(
dedent(
"""
package gen;
message TemporalTypes {
date day = 1;
timestamp instant = 2;
duration elapsed = 3;
}
"""
)
)
rust_output = render_files(generate_files(schema, RustGenerator))
assert "pub day: ::fory::Date," in rust_output
assert "pub instant: ::fory::Timestamp," in rust_output
assert "pub elapsed: ::fory::Duration," in rust_output
assert "chrono::" not in rust_output
def test_rust_generated_code_can_use_chrono_temporal_types():
schema = parse_fdl(
dedent(
"""
package gen;
option rust_use_chrono_temporal_types = true;
message TemporalTypes {
date day = 1;
timestamp instant = 2;
duration elapsed = 3;
}
"""
)
)
rust_output = render_files(generate_files(schema, RustGenerator))
assert "pub day: ::chrono::NaiveDate," in rust_output
assert "pub instant: ::chrono::NaiveDateTime," in rust_output
assert "pub elapsed: ::chrono::Duration," in rust_output
assert "::fory::Date" not in rust_output
assert "::fory::Timestamp" not in rust_output
assert "::fory::Duration" not in rust_output
def test_rust_nested_container_ref_uses_correct_pointer_type():
schema = parse_fdl(
dedent(
"""
package gen;
message Node {
string value = 1;
}
message Request {
list<list<ref(thread_safe=true) Node>> groups = 1;
map<string, map<string, ref(thread_safe=true) Node>> nodes = 2;
}
"""
)
)
rust_output = render_files(generate_files(schema, RustGenerator))
assert (
"pub groups: ::std::vec::Vec<::std::vec::Vec<::std::sync::Arc<Node>>>,"
in rust_output
)
assert "::std::vec::Vec<::std::vec::Vec<::std::rc::Rc<Node>>>" not in rust_output
assert (
"pub nodes: ::std::collections::HashMap<::std::string::String, "
"::std::collections::HashMap<::std::string::String, ::std::sync::Arc<Node>>>,"
in rust_output
)
assert (
"::std::collections::HashMap<::std::string::String, "
"::std::collections::HashMap<::std::string::String, ::std::rc::Rc<Node>>>"
not in rust_output
)
def test_generated_code_integer_encoding_variants_equivalent():
fdl = dedent(
"""
package gen;
message EncodingTypes {
fixed int32 fi32 = 1;
fixed int64 fi64 = 2;
fixed uint32 fu32 = 3;
fixed uint64 fu64 = 4;
tagged int64 ti64 = 5;
tagged uint64 tu64 = 6;
}
"""
)
proto = dedent(
"""
syntax = "proto3";
package gen;
message EncodingTypes {
sfixed32 fi32 = 1;
sfixed64 fi64 = 2;
fixed32 fu32 = 3;
fixed64 fu64 = 4;
int64 ti64 = 5 [(fory).type = "tagged int64"];
uint64 tu64 = 6 [(fory).type = "tagged uint64"];
}
"""
)
schemas = {
"fdl": parse_fdl(fdl),
"proto": parse_proto(proto),
}
assert_all_languages_equal(schemas)
python_output = render_files(generate_files(schemas["fdl"], PythonGenerator))
assert "pyfory.TaggedInt64" in python_output
assert "pyfory.TaggedUInt64" in python_output
def test_generated_code_list_modifier_aliases_equivalent():
repeated = dedent(
"""
package gen;
message Item {
string name = 1;
}
message Container {
repeated string tags = 1;
optional repeated string labels = 2;
repeated optional string aliases = 3;
ref repeated Item items = 4;
repeated ref Item children = 5;
}
"""
)
list_syntax = dedent(
"""
package gen;
message Item {
string name = 1;
}
message Container {
list<string> tags = 1;
optional list<string> labels = 2;
list<optional string> aliases = 3;
ref list<Item> items = 4;
list<ref Item> children = 5;
}
"""
)
schemas = {
"repeated": parse_fdl(repeated),
"list": parse_fdl(list_syntax),
}
assert_all_languages_equal(schemas)
def test_generated_code_repeated_primitives_are_lists():
fdl = dedent(
"""
package gen;
message ArrayTypes {
repeated bool flags = 1;
repeated int8 i8s = 2;
repeated int16 i16s = 3;
repeated int32 i32s = 4;
repeated int64 i64s = 5;
repeated uint8 u8s = 6;
repeated uint16 u16s = 7;
repeated uint32 u32s = 8;
repeated uint64 u64s = 9;
repeated float32 f32s = 10;
repeated float64 f64s = 11;
}
"""
)
proto = dedent(
"""
syntax = "proto3";
package gen;
message ArrayTypes {
repeated bool flags = 1;
repeated int8 i8s = 2;
repeated int16 i16s = 3;
repeated sint32 i32s = 4;
repeated sint64 i64s = 5;
repeated uint8 u8s = 6;
repeated uint16 u16s = 7;
repeated uint32 u32s = 8;
repeated uint64 u64s = 9;
repeated float f32s = 10;
repeated double f64s = 11;
}
"""
)
schemas = {
"fdl": parse_fdl(fdl),
"proto": parse_proto(proto),
}
assert_all_languages_equal(schemas)
def test_generated_code_flatbuffers_primitive_vectors_are_arrays():
fbs = dedent(
"""
namespace gen;
table ArrayTypes {
flags:[bool];
i8s:[byte];
i16s:[short];
i32s:[int];
i64s:[long];
u8s:[ubyte];
u16s:[ushort];
u32s:[uint];
u64s:[ulong];
f32s:[float];
f64s:[double];
}
"""
)
schema = parse_fbs(fbs)
java_output = render_files(generate_files(schema, JavaGenerator))
assert "private boolean[] flags;" in java_output
assert "private int[] i32s;" in java_output
assert "private @UInt32Type int[] u32s;" in java_output
dart_output = render_files(generate_files(schema, DartGenerator))
assert "BoolList flags = BoolList(0);" in dart_output
assert "Int32List i32s = Int32List(0);" in dart_output
assert "Uint32List u32s = Uint32List(0);" in dart_output
def test_generated_code_list_types_equivalent():
fdl = dedent(
"""
package gen;
message ListItem {
string value = 1;
}
message ListTypes {
repeated string names = 1;
repeated bool flags = 2;
repeated ListItem items = 3;
}
"""
)
proto = dedent(
"""
syntax = "proto3";
package gen;
message ListItem {
string value = 1;
}
message ListTypes {
repeated string names = 1;
repeated bool flags = 2;
repeated ListItem items = 3;
}
"""
)
schemas = {
"fdl": parse_fdl(fdl),
"proto": parse_proto(proto),
}
assert_all_languages_equal(schemas)
def test_generated_code_map_types_equivalent():
fdl = dedent(
"""
package gen;
message MapValue {
string id = 1;
}
message MapTypes {
map<string, int32> counts = 1;
optional map<string, MapValue> entries = 2;
map<string, ref(weak=true, thread_safe=false) MapValue> weak_entries = 3;
optional int32 version = 4;
}
"""
)
proto = dedent(
"""
syntax = "proto3";
package gen;
message MapValue {
string id = 1;
}
message MapTypes {
map<string, sint32> counts = 1;
map<string, MapValue> entries = 2 [(fory).nullable = true];
map<string, MapValue> weak_entries = 3 [
(fory).ref = true,
(fory).weak_ref = true,
(fory).thread_safe_pointer = false
];
optional sint32 version = 4;
}
"""
)
# FlatBuffers does not support maps, compare FDL vs proto only.
schemas = {
"fdl": parse_fdl(fdl),
"proto": parse_proto(proto),
}
assert_all_languages_equal(schemas)
rust_output = render_files(generate_files(schemas["fdl"], RustGenerator))
assert "RcWeak<MapValue>" in rust_output
assert "Option<i32>" in rust_output
cpp_output = render_files(generate_files(schemas["fdl"], CppGenerator))
assert "SharedWeak<MapValue>" in cpp_output
def test_rust_generated_ref_pointer_default_and_thread_safe_option():
schema = parse_fdl(
dedent(
"""
package gen;
message Node {
string value = 1;
}
message Holder {
ref Node default_ref = 1;
ref(thread_safe=true) Node thread_safe_ref = 2;
ref(weak=true) Node default_weak_ref = 3;
ref(weak=true, thread_safe=true) Node thread_safe_weak_ref = 4;
list<ref Node> default_ref_list = 5;
list<ref(thread_safe=true) Node> thread_safe_ref_list = 6;
}
"""
)
)
rust_output = render_files(generate_files(schema, RustGenerator))
assert "pub default_ref: ::std::rc::Rc<Node>," in rust_output
assert "pub thread_safe_ref: ::std::sync::Arc<Node>," in rust_output
assert "pub default_weak_ref: ::fory::RcWeak<Node>," in rust_output
assert "pub thread_safe_weak_ref: ::fory::ArcWeak<Node>," in rust_output
assert "pub default_ref_list: ::std::vec::Vec<::std::rc::Rc<Node>>," in rust_output
assert (
"pub thread_safe_ref_list: ::std::vec::Vec<::std::sync::Arc<Node>>,"
in rust_output
)
def test_generated_code_nested_messages_equivalent():
fdl = dedent(
"""
package gen;
message Outer {
string id = 1;
message Inner {
string value = 1;
}
Inner inner = 2;
}
"""
)
proto = dedent(
"""
syntax = "proto3";
package gen;
message Outer {
string id = 1;
message Inner {
string value = 1;
}
Inner inner = 2;
}
"""
)
# FlatBuffers does not support nested message declarations.
schemas = {
"fdl": parse_fdl(fdl),
"proto": parse_proto(proto),
}
assert_all_languages_equal(schemas)
def test_java_nested_name_registration_uses_owner_namespace():
schema = parse_fdl(
"""
option enable_auto_type_id = false;
package demo;
message Envelope {
message Payload {
int32 value = 1;
}
enum Kind {
UNKNOWN = 0;
ACTIVE = 1;
}
union Choice {
Payload payload = 1;
string note = 2;
}
Payload payload = 1;
Kind kind = 2;
Choice choice = 3;
list<ref Payload> payloads = 4;
}
"""
)
output = render_files(generate_files(schema, JavaGenerator))
assert "import org.apache.fory.annotation.Ref;" in output
assert "private List<@Ref Payload> payloads;" in output
assert 'resolver.register(Envelope.class, "demo", "Envelope");' in output
assert (
'resolver.register(Envelope.Payload.class, "demo.Envelope", "Payload");'
in output
)
assert 'resolver.register(Envelope.Kind.class, "demo.Envelope", "Kind");' in output
assert (
'resolver.registerUnion(Envelope.Choice.class, "demo.Envelope", "Choice"'
in output
)
def test_java_default_package_import_registers_dependency(tmp_path):
common = tmp_path / "common.fdl"
common.write_text(
"""
message Common [id=200] {
string name = 1;
}
"""
)
main = tmp_path / "main.fdl"
main.write_text(
"""
import "common.fdl";
message Holder [id=201] {
Common common = 1;
}
"""
)
schema = resolve_imports(main)
validator = SchemaValidator(schema)
assert validator.validate(), validator.errors
files = generate_files(schema, JavaGenerator)
module = files["MainForyModule.java"]
assert "public final class MainForyModule" in module
assert "fory.register(CommonForyModule.INSTANCE);" in module
assert "CommonForyModule.register(fory)" not in module
def test_java_rejects_mixed_default_and_named_imports(tmp_path):
default_dir = tmp_path / "default_in_named"
default_dir.mkdir()
(default_dir / "common.fdl").write_text(
"""
message Common [id=200] {
string name = 1;
}
"""
)
default_main = default_dir / "main.fdl"
default_main.write_text(
"""
package app;
import "common.fdl";
message Holder [id=201] {
Common common = 1;
}
"""
)
with pytest.raises(ValueError, match="default-package"):
JavaGenerator(
resolve_imports(default_main), GeneratorOptions(output_dir=tmp_path)
)
named_dir = tmp_path / "named_in_default"
named_dir.mkdir()
(named_dir / "common.fdl").write_text(
"""
package shared;
message Common [id=200] {
string name = 1;
}
"""
)
named_main = named_dir / "main.fdl"
named_main.write_text(
"""
import "common.fdl";
message Holder [id=201] {
optional Common common = 1;
}
"""
)
with pytest.raises(ValueError, match="default-package"):
JavaGenerator(
resolve_imports(named_main), GeneratorOptions(output_dir=tmp_path)
)
def test_java_nested_enum_shadowing_does_not_emit_ref_annotations():
schema = parse_fdl(
"""
package demo;
message Node {
Envelope owner = 1;
}
message Envelope {
enum Node {
UNKNOWN = 0;
ACTIVE = 1;
}
Node kind = 1;
list<Node> kinds = 2;
map<string, Node> indexed = 3;
}
"""
)
output = render_files(generate_files(schema, JavaGenerator))
assert "import org.apache.fory.annotation.Ref;" not in output
assert "private Node kind;" in output
assert "private List<Node> kinds;" in output
assert "private Map<String, Node> indexed;" in output
assert "@Ref" not in output
def test_generated_code_tree_ref_options_equivalent():
fdl = dedent(
"""
package tree;
message TreeNode {
string id = 1;
string name = 2;
repeated ref TreeNode children = 3;
ref(weak=true) TreeNode parent = 4;
}
"""
)
proto = dedent(
"""
syntax = "proto3";
package tree;
message TreeNode {
string id = 1;
string name = 2;
repeated TreeNode children = 3 [(fory).ref = true];
TreeNode parent = 4 [(fory).weak_ref = true];
}
"""
)
fbs = dedent(
"""
namespace tree;
table TreeNode {
id: string;
name: string;
children: [TreeNode] (fory_ref: true);
parent: TreeNode (fory_weak_ref: true);
}
"""
)
# Tree ref options should produce identical outputs across frontends.
schemas = {
"fdl": parse_fdl(fdl),
"proto": parse_proto(proto),
"fbs": parse_fbs(fbs),
}
assert_all_languages_equal(schemas)
rust_output = render_files(generate_files(schemas["fdl"], RustGenerator))
assert "RcWeak<TreeNode>" in rust_output
assert "#[derive(::fory::ForyStruct, Clone, PartialEq, Eq, Default)]" in rust_output
cpp_output = render_files(generate_files(schemas["fdl"], CppGenerator))
assert "SharedWeak<TreeNode>" in cpp_output
go_output = render_files(generate_files(schemas["fdl"], GoGenerator))
assert (
'Children []*TreeNode `fory:"id=3,nullable=false,type=list(element=_(nullable=false,ref=true))"`'
in go_output
)
assert 'Parent *TreeNode `fory:"id=4,nullable=false,ref"`' in go_output
java_output = render_files(generate_files(schemas["fdl"], JavaGenerator))
assert "import org.apache.fory.annotation.Ref;" in java_output
assert "private @Ref TreeNode parent;" in java_output
def test_java_float16_equals_hash_contract_generation():
schema = parse_fdl(
dedent(
"""
package gen;
message Float16Contract {
float16 f16 = 1;
optional float16 opt_f16 = 2;
}
"""
)
)
java_output = render_files(generate_files(schema, JavaGenerator))
assert "Objects.equals(f16, that.f16)" in java_output
assert "Objects.equals(optF16, that.optF16)" in java_output
assert "return Objects.hash(f16, optF16);" in java_output
def test_java_repeated_float16_generation_uses_float16_list():
schema = parse_fdl(
dedent(
"""
package gen;
message RepeatedFloat16 {
list<float16> vals = 1;
}
"""
)
)
java_output = render_files(generate_files(schema, JavaGenerator))
assert "import org.apache.fory.collection.Float16List;" in java_output
assert "private Float16List vals;" in java_output
def test_java_nested_array_values_use_deep_equals_hash_generation():
schema = parse_fdl(
dedent(
"""
package gen;
message NestedArrays {
list<array<int32>> groups = 1;
map<string, array<uint8>> bytes_by_name = 2;
}
union NestedArrayUnion {
list<array<int32>> groups = 1;
map<string, array<uint8>> bytes_by_name = 2;
}
"""
)
)
java_output = render_files(generate_files(schema, JavaGenerator))
assert (
"private static boolean deepValueEquals(Object left, Object right)"
in java_output
)
assert "deepValueEquals(groups, that.groups)" in java_output
assert "deepValueEquals(bytesByName, that.bytesByName)" in java_output
assert "deepValueHashCode(groups)" in java_output
assert "deepValueHashCode(bytesByName)" in java_output
assert "index == that.index && deepValueEquals(value, that.value)" in java_output
assert "31 * Integer.hashCode(index) + deepValueHashCode(value)" in java_output
def test_java_unsigned_carriers_and_integer_encoding_annotations():
schema = parse_fdl(
dedent(
"""
package gen;
message UnsignedCarriers {
uint8 u8 = 1;
uint16 u16 = 2;
fixed uint32 fixed_u32 = 3;
uint32 var_u32 = 4;
optional uint32 maybe_u32 = 5;
fixed int32 fixed_i32 = 6;
}
"""
)
)
java_output = render_files(generate_files(schema, JavaGenerator))
assert "import org.apache.fory.annotation.Nullable;" in java_output
assert "import org.apache.fory.config.Int32Encoding;" in java_output
assert "private @UInt8Type int u8;" in java_output
assert "private @UInt16Type int u16;" in java_output
assert (
"private @UInt32Type(encoding = Int32Encoding.FIXED) long fixedU32;"
in java_output
)
assert "private @UInt32Type long varU32;" in java_output
assert "private @Nullable @UInt32Type Long maybeU32;" in java_output
assert (
"private @Int32Type(encoding = Int32Encoding.FIXED) int fixedI32;"
in java_output
)
def test_java_nullable_type_use_annotation_targets_top_level_type():
schema = parse_fdl(
dedent(
"""
package gen;
message Money {
string currency = 1;
}
message NullableTargets {
optional Money money = 1;
optional bytes payload = 2;
optional decimal amount = 3;
}
"""
)
)
java_output = render_files(generate_files(schema, JavaGenerator))
assert "private @Nullable Money money;" in java_output
assert "private byte @Nullable [] payload;" in java_output
assert "private java.math.@Nullable BigDecimal amount;" in java_output
def test_java_evolving_false_generation_uses_struct_evolution_enum():
schema = parse_fdl(
dedent(
"""
package gen;
message DefaultEvolving {
string value = 1;
}
message Stable [evolving=false] {
string name = 1;
message NestedStable [evolving=false] {
int32 id = 1;
}
}
"""
)
)
java_output = render_files(generate_files(schema, JavaGenerator))
assert "import org.apache.fory.annotation.ForyStruct;" in java_output
assert "import org.apache.fory.annotation.ForyStruct.Evolution;" in java_output
assert java_output.count("@ForyStruct(evolution = Evolution.DISABLED)") == 2
assert java_output.count("@ForyStruct") == 3
assert "@ForyStruct(evolving = false)" not in java_output
def test_java_nested_integer_annotations_in_generic_containers():
schema = parse_fdl(
dedent(
"""
package gen;
message NestedIntegerAnnotations {
map<fixed uint32, list<optional tagged uint64>> values = 1;
}
"""
)
)
java_output = render_files(generate_files(schema, JavaGenerator))
assert (
"private Map<@UInt32Type(encoding = Int32Encoding.FIXED) Long, "
"List<@UInt64Type(encoding = Int64Encoding.TAGGED) Long>> values;"
in java_output
)
go_output = render_files(generate_files(schema, GoGenerator))
assert (
'Values map[uint32][]*uint64 `fory:"id=1,type=map(key=uint32(encoding=fixed),'
'value=list(nullable=false,ref=false,element=uint64(encoding=tagged)))"`'
in go_output
)
def test_python_nested_integer_schema_aliases_in_generic_containers():
schema = parse_fdl(
dedent(
"""
package gen;
message NestedIntegerSchemaAliases {
map<fixed int32, list<tagged int64>> signed_values = 1;
map<fixed uint32, list<tagged uint64>> unsigned_values = 2;
}
"""
)
)
python_output = render_files(generate_files(schema, PythonGenerator))
assert (
"signed_values: Dict[pyfory.FixedInt32, List[pyfory.TaggedInt64]]"
in python_output
)
assert (
"unsigned_values: Dict[pyfory.FixedUInt32, List[pyfory.TaggedUInt64]]"
in python_output
)