asyncapi-rust 0.4.0

AsyncAPI 3.0 specification generation for Rust WebSockets and async protocols
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
use asyncapi_rust::{AsyncApi, ToAsyncApiMessage, schemars::JsonSchema};
use serde::{Deserialize, Serialize};

// Test basic enum without serde attributes
#[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
pub enum BasicMessage {
    Ping,
    Pong,
}

// Test enum with serde tag
#[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
#[serde(tag = "type")]
pub enum TaggedMessage {
    Echo { text: String },
    Broadcast { room: String, text: String },
}

// Test enum with serde rename on variants
#[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
#[serde(tag = "message")]
pub enum RenamedMessage {
    #[serde(rename = "user.join")]
    UserJoin { username: String },
    #[serde(rename = "user.leave")]
    UserLeave { username: String },
    #[serde(rename = "chat.message")]
    ChatMessage { username: String, text: String },
}

// Test struct
#[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
pub struct SimpleMessage {
    pub id: u64,
    pub text: String,
}

// Test enum with asyncapi attributes
#[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
#[serde(tag = "type")]
pub enum DocumentedMessage {
    /// Join a room
    #[asyncapi(
        summary = "User joins a chat room",
        description = "Sent when a user enters a room"
    )]
    Join { username: String, room: String },

    /// Leave a room
    #[asyncapi(
        summary = "User leaves a chat room",
        description = "Sent when a user exits a room",
        title = "Leave Room"
    )]
    Leave { username: String, room: String },

    /// Binary file transfer
    #[asyncapi(content_type = "application/octet-stream")]
    File { filename: String, data: Vec<u8> },

    /// Binary data with triggers_binary flag
    #[asyncapi(triggers_binary)]
    Binary { data: Vec<u8> },
}

#[test]
fn test_basic_enum_messages() {
    let names = BasicMessage::asyncapi_message_names();
    assert_eq!(names, vec!["Ping", "Pong"]);
    assert_eq!(BasicMessage::asyncapi_message_count(), 2);
    assert_eq!(BasicMessage::asyncapi_tag_field(), None);
}

#[test]
fn test_tagged_enum() {
    let names = TaggedMessage::asyncapi_message_names();
    assert_eq!(names, vec!["Echo", "Broadcast"]);
    assert_eq!(TaggedMessage::asyncapi_message_count(), 2);
    assert_eq!(TaggedMessage::asyncapi_tag_field(), Some("type"));
}

#[test]
fn test_renamed_enum() {
    let names = RenamedMessage::asyncapi_message_names();
    // Message names are variant identifiers, not serde rename strings.
    // The serde rename ("user.join" etc.) stays as the wire discriminant in the payload schema.
    assert_eq!(names, vec!["UserJoin", "UserLeave", "ChatMessage"]);
    assert_eq!(RenamedMessage::asyncapi_message_count(), 3);
    assert_eq!(RenamedMessage::asyncapi_tag_field(), Some("message"));
}

#[test]
fn test_struct_message() {
    let names = SimpleMessage::asyncapi_message_names();
    assert_eq!(names, vec!["SimpleMessage"]);
    assert_eq!(SimpleMessage::asyncapi_message_count(), 1);
    assert_eq!(SimpleMessage::asyncapi_tag_field(), None);
}

#[test]
fn test_schema_generation() {
    let messages = SimpleMessage::asyncapi_messages();
    assert_eq!(messages.len(), 1);

    let message = &messages[0];
    assert_eq!(message.name, Some("SimpleMessage".to_string()));
    assert_eq!(message.content_type, Some("application/json".to_string()));
    assert!(message.payload.is_some());

    // Verify the schema was generated
    if let Some(schema) = &message.payload {
        // Schema should have been converted from schemars output
        // Just verify it exists - the exact structure depends on schemars
        assert!(matches!(schema, asyncapi_rust::Schema::Object(_)));
    }
}

#[test]
fn test_enum_schema_generation() {
    let messages = TaggedMessage::asyncapi_messages();
    assert_eq!(messages.len(), 2);

    let echo = messages
        .iter()
        .find(|m| m.name.as_deref() == Some("Echo"))
        .expect("Echo message should exist");
    let broadcast = messages
        .iter()
        .find(|m| m.name.as_deref() == Some("Broadcast"))
        .expect("Broadcast message should exist");

    // Each message must carry only its own variant schema — no top-level oneOf
    let echo_json = serde_json::to_value(&echo.payload).unwrap();
    let broadcast_json = serde_json::to_value(&broadcast.payload).unwrap();

    assert!(
        echo_json.get("oneOf").is_none(),
        "Echo payload must not be the whole-enum oneOf"
    );
    assert!(
        broadcast_json.get("oneOf").is_none(),
        "Broadcast payload must not be the whole-enum oneOf"
    );

    // Each payload must contain the const for its own discriminant only
    let echo_type_const = echo_json
        .pointer("/properties/type/const")
        .and_then(|v| v.as_str());
    assert_eq!(echo_type_const, Some("Echo"));

    let broadcast_type_const = broadcast_json
        .pointer("/properties/type/const")
        .and_then(|v| v.as_str());
    assert_eq!(broadcast_type_const, Some("Broadcast"));
}

// Regression for #6: per-variant schemas work with a non-"type" tag field name
#[test]
fn test_per_variant_schema_non_type_tag() {
    #[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
    #[serde(tag = "message")]
    pub enum ChannelEvent {
        #[serde(rename = "channel-list")]
        ChannelList { channels: Vec<String> },
        #[serde(rename = "data-changed")]
        DataChanged { project_id: i64 },
    }

    let messages = ChannelEvent::asyncapi_messages();
    assert_eq!(messages.len(), 2);

    let channel_list = messages
        .iter()
        .find(|m| m.name.as_deref() == Some("ChannelList"))
        .expect("ChannelList should exist");
    let data_changed = messages
        .iter()
        .find(|m| m.name.as_deref() == Some("DataChanged"))
        .expect("DataChanged should exist");

    let cl_json = serde_json::to_value(&channel_list.payload).unwrap();
    let dc_json = serde_json::to_value(&data_changed.payload).unwrap();

    // Must be per-variant, not the whole union
    assert!(cl_json.get("oneOf").is_none());
    assert!(dc_json.get("oneOf").is_none());

    // Discriminant must match (tag field is "message", not "type")
    assert_eq!(
        cl_json
            .pointer("/properties/message/const")
            .and_then(|v| v.as_str()),
        Some("channel-list")
    );
    assert_eq!(
        dc_json
            .pointer("/properties/message/const")
            .and_then(|v| v.as_str()),
        Some("data-changed")
    );

    // channel-list payload must have "channels", not "project_id"
    assert!(cl_json.pointer("/properties/channels").is_some());
    assert!(cl_json.pointer("/properties/project_id").is_none());
}

#[test]
fn test_asyncapi_attributes() {
    let messages = DocumentedMessage::asyncapi_messages();
    assert_eq!(messages.len(), 4);

    // Test Join message with summary and description
    let join = &messages[0];
    assert_eq!(join.name, Some("Join".to_string()));
    assert_eq!(join.summary, Some("User joins a chat room".to_string()));
    assert_eq!(
        join.description,
        Some("Sent when a user enters a room".to_string())
    );
    assert_eq!(join.content_type, Some("application/json".to_string()));

    // Test Leave message with custom title
    let leave = &messages[1];
    assert_eq!(leave.name, Some("Leave".to_string()));
    assert_eq!(leave.title, Some("Leave Room".to_string()));
    assert_eq!(leave.summary, Some("User leaves a chat room".to_string()));
    assert_eq!(
        leave.description,
        Some("Sent when a user exits a room".to_string())
    );

    // Test File message with custom content type
    let file = &messages[2];
    assert_eq!(file.name, Some("File".to_string()));
    assert_eq!(
        file.content_type,
        Some("application/octet-stream".to_string())
    );

    // Test Binary message with triggers_binary flag
    let binary = &messages[3];
    assert_eq!(binary.name, Some("Binary".to_string()));
    assert_eq!(
        binary.content_type,
        Some("application/octet-stream".to_string())
    );
}

// Test AsyncApi derive macro
#[derive(AsyncApi)]
#[asyncapi(
    title = "Test API",
    version = "1.0.0",
    description = "A test API specification"
)]
struct TestApi;

#[test]
fn test_asyncapi_derive() {
    let spec = TestApi::asyncapi_spec();

    // Verify basic fields
    assert_eq!(spec.asyncapi, "3.0.0");
    assert_eq!(spec.info.title, "Test API");
    assert_eq!(spec.info.version, "1.0.0");
    assert_eq!(
        spec.info.description,
        Some("A test API specification".to_string())
    );

    // Verify optional fields are None
    assert!(spec.servers.is_none());
    assert!(spec.channels.is_none());
    assert!(spec.operations.is_none());
    assert!(spec.components.is_none());
}

// Test AsyncApi without description
#[derive(AsyncApi)]
#[asyncapi(title = "Minimal API", version = "0.1.0")]
struct MinimalApi;

#[test]
fn test_asyncapi_minimal() {
    let spec = MinimalApi::asyncapi_spec();

    assert_eq!(spec.asyncapi, "3.0.0");
    assert_eq!(spec.info.title, "Minimal API");
    assert_eq!(spec.info.version, "0.1.0");
    assert_eq!(spec.info.description, None);
}

// Test AsyncApi with servers, channels, and operations
#[allow(clippy::duplicated_attributes)] // False positive - different operations can reference same channel
#[derive(AsyncApi)]
#[asyncapi(
    title = "Full API",
    version = "1.0.0",
    description = "Complete API spec"
)]
#[asyncapi_server(
    name = "production",
    host = "api.example.com",
    protocol = "wss",
    description = "Production server"
)]
#[asyncapi_server(name = "development", host = "localhost:8080", protocol = "ws")]
#[asyncapi_channel(name = "chat", address = "/ws/chat")]
#[asyncapi_operation(name = "sendMessage", action = "send", channel = "chat")]
#[asyncapi_operation(name = "receiveMessage", action = "receive", channel = "chat")]
struct FullApi;

#[test]
fn test_asyncapi_full() {
    let spec = FullApi::asyncapi_spec();

    // Verify Info
    assert_eq!(spec.info.title, "Full API");
    assert_eq!(spec.info.version, "1.0.0");
    assert_eq!(spec.info.description, Some("Complete API spec".to_string()));

    // Verify Servers
    let servers = spec.servers.expect("Should have servers");
    assert_eq!(servers.len(), 2);

    let prod_server = servers
        .get("production")
        .expect("Should have production server");
    assert_eq!(prod_server.host, "api.example.com");
    assert_eq!(prod_server.protocol, "wss");
    assert_eq!(
        prod_server.description,
        Some("Production server".to_string())
    );

    let dev_server = servers
        .get("development")
        .expect("Should have development server");
    assert_eq!(dev_server.host, "localhost:8080");
    assert_eq!(dev_server.protocol, "ws");
    assert_eq!(dev_server.description, None);

    // Verify Channels
    let channels = spec.channels.expect("Should have channels");
    assert_eq!(channels.len(), 1);

    let chat_channel = channels.get("chat").expect("Should have chat channel");
    assert_eq!(chat_channel.address, Some("/ws/chat".to_string()));

    // Verify Operations
    let operations = spec.operations.expect("Should have operations");
    assert_eq!(operations.len(), 2);

    let send_op = operations
        .get("sendMessage")
        .expect("Should have sendMessage operation");
    assert!(matches!(
        send_op.action,
        asyncapi_rust::OperationAction::Send
    ));
    assert_eq!(send_op.channel.reference, "#/channels/chat");

    let receive_op = operations
        .get("receiveMessage")
        .expect("Should have receiveMessage operation");
    assert!(matches!(
        receive_op.action,
        asyncapi_rust::OperationAction::Receive
    ));
    assert_eq!(receive_op.channel.reference, "#/channels/chat");
}

// Test AsyncApi with message integration
#[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
#[serde(tag = "type")]
enum ApiMessage {
    #[serde(rename = "user.join")]
    #[asyncapi(summary = "User joins", description = "User enters a room")]
    UserJoin { username: String, room: String },

    #[serde(rename = "user.leave")]
    #[asyncapi(summary = "User leaves")]
    UserLeave { username: String, room: String },
}

#[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
#[serde(tag = "type")]
enum SystemMessage {
    #[serde(rename = "system.status")]
    #[asyncapi(summary = "System status")]
    SystemStatus { status: String },
}

#[derive(AsyncApi)]
#[asyncapi(title = "Message Integration API", version = "1.0.0")]
#[asyncapi_messages(ApiMessage, SystemMessage)]
struct MessageIntegrationApi;

#[test]
fn test_asyncapi_with_messages() {
    let spec = MessageIntegrationApi::asyncapi_spec();

    // Verify Info
    assert_eq!(spec.info.title, "Message Integration API");
    assert_eq!(spec.info.version, "1.0.0");

    // Verify Components exist and have messages
    let components = spec.components.expect("Should have components");
    let messages = components
        .messages
        .expect("Should have messages in components");

    // Verify we have all 3 messages (2 from ApiMessage, 1 from SystemMessage).
    // Keys and name fields use variant identifiers, not serde rename strings.
    assert_eq!(messages.len(), 3);

    // Verify UserJoin message
    let user_join = messages
        .get("UserJoin")
        .expect("Should have UserJoin message");
    assert_eq!(user_join.name, Some("UserJoin".to_string()));
    assert_eq!(user_join.summary, Some("User joins".to_string()));
    assert_eq!(
        user_join.description,
        Some("User enters a room".to_string())
    );
    assert!(user_join.payload.is_some());

    // Verify UserLeave message
    let user_leave = messages
        .get("UserLeave")
        .expect("Should have UserLeave message");
    assert_eq!(user_leave.name, Some("UserLeave".to_string()));
    assert_eq!(user_leave.summary, Some("User leaves".to_string()));

    // Verify SystemStatus message
    let system_status = messages
        .get("SystemStatus")
        .expect("Should have SystemStatus message");
    assert_eq!(system_status.name, Some("SystemStatus".to_string()));
    assert_eq!(system_status.summary, Some("System status".to_string()));
}

// Regression test for issue #4: ToAsyncApiMessage panics on enums with serde_json::Value fields
#[test]
fn test_enum_with_json_value_fields() {
    #[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
    #[serde(tag = "type")]
    pub enum MsgWithValue {
        #[serde(rename = "hello")]
        Hello { version: String },
        #[serde(rename = "result")]
        Result {
            ok: bool,
            #[serde(skip_serializing_if = "Option::is_none")]
            payload: Option<serde_json::Value>,
        },
    }

    // Should not panic
    let messages = MsgWithValue::asyncapi_messages();
    assert_eq!(messages.len(), 2);

    let hello = messages
        .iter()
        .find(|m| m.name.as_deref() == Some("Hello"))
        .expect("Hello message should exist");
    assert!(hello.payload.is_some());

    let result = messages
        .iter()
        .find(|m| m.name.as_deref() == Some("Result"))
        .expect("Result message should exist");
    assert!(result.payload.is_some());
}

// Regression for #7: shared $defs hoisted to components.schemas; payloads have no $defs block
// and $refs point to #/components/schemas/X instead of #/$defs/X.
#[test]
fn test_shared_defs_hoisted_to_components_schemas() {
    // SharedInfo will appear in schemars' $defs because it's used by multiple variants
    #[derive(Serialize, Deserialize, JsonSchema)]
    pub struct SharedInfo {
        pub id: i64,
        pub label: String,
    }

    #[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
    #[serde(tag = "type")]
    pub enum EventMsg {
        #[serde(rename = "event-a")]
        EventA { info: SharedInfo },
        #[serde(rename = "event-b")]
        EventB { info: SharedInfo, extra: String },
    }

    #[derive(AsyncApi)]
    #[asyncapi(title = "Hoisting Test", version = "1.0.0")]
    #[asyncapi_messages(EventMsg)]
    struct HoistApi;

    // asyncapi_schemas() must expose the shared type
    let schemas = EventMsg::asyncapi_schemas();
    assert!(
        schemas.contains_key("SharedInfo"),
        "SharedInfo must appear in asyncapi_schemas()"
    );

    // No message payload may contain a $defs block
    let messages = EventMsg::asyncapi_messages();
    for msg in &messages {
        let payload_json = serde_json::to_value(&msg.payload).unwrap();
        assert!(
            payload_json.get("$defs").is_none(),
            "payload for '{}' must not contain $defs",
            msg.name.as_deref().unwrap_or("?")
        );
    }

    // Any $ref in a payload must point to #/components/schemas/, not #/$defs/
    fn find_bad_refs(v: &serde_json::Value) -> Vec<String> {
        let mut bad = Vec::new();
        match v {
            serde_json::Value::Object(map) => {
                if let Some(r) = map.get("$ref").and_then(|r| r.as_str()) {
                    if r.starts_with("#/$defs/") {
                        bad.push(r.to_string());
                    }
                }
                for val in map.values() {
                    bad.extend(find_bad_refs(val));
                }
            }
            serde_json::Value::Array(arr) => {
                for val in arr {
                    bad.extend(find_bad_refs(val));
                }
            }
            _ => {}
        }
        bad
    }

    for msg in &messages {
        let payload_json = serde_json::to_value(&msg.payload).unwrap();
        let bad = find_bad_refs(&payload_json);
        assert!(
            bad.is_empty(),
            "payload for '{}' still has #/$defs/ refs: {:?}",
            msg.name.as_deref().unwrap_or("?"),
            bad
        );
    }

    // The full spec must have components.schemas populated with SharedInfo
    let spec = HoistApi::asyncapi_spec();
    let comp_schemas = spec
        .components
        .as_ref()
        .and_then(|c| c.schemas.as_ref())
        .expect("components.schemas must be populated");

    assert!(
        comp_schemas.contains_key("SharedInfo"),
        "components.schemas must contain SharedInfo"
    );

    // And each message payload in components.messages must also be clean
    let comp_messages = spec
        .components
        .as_ref()
        .and_then(|c| c.messages.as_ref())
        .expect("components.messages must be populated");

    for (name, msg) in comp_messages {
        let payload_json = serde_json::to_value(&msg.payload).unwrap();
        assert!(
            payload_json.get("$defs").is_none(),
            "components.messages.{name}.payload must not contain $defs"
        );
        let bad = find_bad_refs(&payload_json);
        assert!(
            bad.is_empty(),
            "components.messages.{name}.payload has unrewritten refs: {bad:?}"
        );
    }
}

// Regression for #8: empty serde rename falls back to variant identifier
#[test]
fn test_empty_serde_rename_fallback() {
    #[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
    #[serde(tag = "message")]
    pub enum ResponseMsg {
        #[serde(rename = "ok")]
        Ok { value: String },
        #[serde(rename = "")]
        Empty,
    }

    let names = ResponseMsg::asyncapi_message_names();
    // "Empty" (variant ident) not "" (serde rename)
    assert!(
        names.contains(&"Empty"),
        "empty serde rename must fall back to variant ident; got: {names:?}"
    );
    assert!(
        !names.contains(&""),
        "empty string must not appear as a message name; got: {names:?}"
    );

    let messages = ResponseMsg::asyncapi_messages();
    assert!(
        messages.iter().any(|m| m.name.as_deref() == Some("Empty")),
        "Empty message must be findable by variant ident"
    );
    assert!(
        !messages.iter().any(|m| m.name.as_deref() == Some("")),
        "empty-string message name must not appear"
    );
}

// Regression for #8: cross-enum discriminant collision resolved via message_name override
#[test]
fn test_cross_enum_collision_resolved_with_message_name() {
    // Two enums with different roles but the same variant identifier / serde rename.
    // The response variant uses #[asyncapi(message_name = "...")] to disambiguate.
    #[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
    #[serde(tag = "message")]
    pub enum Operation {
        #[serde(rename = "get-info")]
        GetInfo { project_id: i64 },
    }

    #[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
    #[serde(tag = "message")]
    pub enum OperationResponse {
        #[serde(rename = "get-info")]
        #[asyncapi(message_name = "GetInfoResponse")]
        GetInfo { id: i64, label: String },
    }

    #[derive(AsyncApi)]
    #[asyncapi(title = "Collision Test", version = "1.0.0")]
    #[asyncapi_messages(Operation, OperationResponse)]
    struct CollisionApi;

    let spec = CollisionApi::asyncapi_spec();
    let messages = spec
        .components
        .as_ref()
        .and_then(|c| c.messages.as_ref())
        .expect("components.messages must be present");

    // Both messages must be present under distinct keys
    assert!(
        messages.contains_key("GetInfo"),
        "GetInfo (request) must be in components.messages"
    );
    assert!(
        messages.contains_key("GetInfoResponse"),
        "GetInfoResponse must be in components.messages"
    );
    assert_eq!(
        messages.len(),
        2,
        "both messages must survive — no silent overwrite"
    );

    // Payloads must be distinct (request has project_id, response has label)
    let req_json = serde_json::to_value(&messages["GetInfo"].payload).unwrap();
    let res_json = serde_json::to_value(&messages["GetInfoResponse"].payload).unwrap();
    assert!(
        req_json.pointer("/properties/project_id").is_some(),
        "GetInfo payload must have project_id"
    );
    assert!(
        res_json.pointer("/properties/label").is_some(),
        "GetInfoResponse payload must have label"
    );

    // Wire discriminant in both payloads must still be "get-info"
    assert_eq!(
        req_json
            .pointer("/properties/message/const")
            .and_then(|v| v.as_str()),
        Some("get-info"),
        "GetInfo discriminant must be 'get-info'"
    );
    assert_eq!(
        res_json
            .pointer("/properties/message/const")
            .and_then(|v| v.as_str()),
        Some("get-info"),
        "GetInfoResponse discriminant must be 'get-info'"
    );
}

// Regression for #8: message_name attribute is honoured for naming in components.messages
#[test]
fn test_message_name_override_attribute() {
    #[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
    #[serde(tag = "type")]
    pub enum Event {
        #[serde(rename = "editor-update")]
        #[asyncapi(message_name = "EditorUpdate", summary = "Editor state changed")]
        Update { content: String },
    }

    let names = Event::asyncapi_message_names();
    assert_eq!(names, vec!["EditorUpdate"]);

    let messages = Event::asyncapi_messages();
    let msg = &messages[0];
    assert_eq!(msg.name.as_deref(), Some("EditorUpdate"));
    assert_eq!(msg.summary.as_deref(), Some("Editor state changed"));

    // Wire discriminant in the payload must still be "editor-update"
    let payload_json = serde_json::to_value(&msg.payload).unwrap();
    assert_eq!(
        payload_json
            .pointer("/properties/type/const")
            .and_then(|v| v.as_str()),
        Some("editor-update")
    );
}

// ── Roundtrip deserialization ────────────────────────────────────────────────

// A spec with servers, channels, operations, and components must survive
// serialize → deserialize → re-serialize with all fields intact.
#[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
#[serde(tag = "type")]
enum RoundtripMsg {
    #[serde(rename = "ping")]
    #[asyncapi(summary = "Ping")]
    Ping { seq: u32 },
    #[serde(rename = "pong")]
    #[asyncapi(summary = "Pong")]
    Pong { seq: u32, latency_ms: u32 },
}

#[derive(AsyncApi)]
#[asyncapi(
    title = "Roundtrip API",
    version = "2.0.0",
    description = "Used for roundtrip tests"
)]
#[asyncapi_server(name = "prod", host = "ws.example.com", protocol = "wss")]
#[asyncapi_channel(name = "ping", address = "/ws/ping")]
// Two operations share channel = "ping" — clippy::duplicated_attributes is a false positive here
#[allow(clippy::duplicated_attributes)]
#[asyncapi_operation(name = "sendPing", action = "send", channel = "ping")]
#[asyncapi_operation(name = "receivePong", action = "receive", channel = "ping")]
#[asyncapi_messages(RoundtripMsg)]
struct RoundtripApi;

#[test]
fn test_full_spec_roundtrip() {
    use asyncapi_rust::AsyncApiSpec;

    let original = RoundtripApi::asyncapi_spec();

    // Serialize to JSON
    let json = serde_json::to_string_pretty(&original).expect("serialization failed");

    // Deserialize back
    let restored: AsyncApiSpec =
        serde_json::from_str(&json).expect("deserialization failed — JSON was:\n{json}");

    // Info survives
    assert_eq!(restored.info.title, "Roundtrip API");
    assert_eq!(restored.info.version, "2.0.0");
    assert_eq!(
        restored.info.description,
        Some("Used for roundtrip tests".to_string())
    );

    // Servers survive
    let servers = restored
        .servers
        .as_ref()
        .expect("servers must survive roundtrip");
    assert!(servers.contains_key("prod"), "prod server must survive");
    assert_eq!(servers["prod"].protocol, "wss");

    // Channels survive
    let channels = restored
        .channels
        .as_ref()
        .expect("channels must survive roundtrip");
    assert!(channels.contains_key("ping"));
    assert_eq!(channels["ping"].address, Some("/ws/ping".to_string()));

    // Operations survive with correct action
    let ops = restored
        .operations
        .as_ref()
        .expect("operations must survive roundtrip");
    assert_eq!(ops.len(), 2);
    assert!(matches!(
        ops["sendPing"].action,
        asyncapi_rust::OperationAction::Send
    ));
    assert!(matches!(
        ops["receivePong"].action,
        asyncapi_rust::OperationAction::Receive
    ));

    // Components.messages survive with payloads intact
    let msgs = restored
        .components
        .as_ref()
        .and_then(|c| c.messages.as_ref())
        .expect("components.messages must survive roundtrip");
    assert!(msgs.contains_key("Ping"), "Ping message must survive");
    assert!(msgs.contains_key("Pong"), "Pong message must survive");
    assert!(msgs["Ping"].payload.is_some(), "Ping payload must survive");
    assert!(msgs["Pong"].payload.is_some(), "Pong payload must survive");
    assert_eq!(msgs["Ping"].summary.as_deref(), Some("Ping"));

    // Re-serialize the restored spec — must produce valid JSON again
    let rejson = serde_json::to_string(&restored).expect("re-serialization failed");
    assert!(rejson.contains("Roundtrip API"));
    assert!(rejson.contains("wss"));
}

// ── Schema::Any ──────────────────────────────────────────────────────────────

#[test]
fn test_schema_any_roundtrip() {
    use asyncapi_rust::Schema;

    // Boolean JSON Schema values (true/false) are valid per the spec but are
    // not objects, so they fall through Reference and Object to Schema::Any.
    let true_schema: Schema =
        serde_json::from_value(serde_json::json!(true)).expect("true should deserialize");
    assert!(
        matches!(true_schema, Schema::Any(_)),
        "boolean true must deserialize as Schema::Any"
    );

    let false_schema: Schema =
        serde_json::from_value(serde_json::json!(false)).expect("false should deserialize");
    assert!(
        matches!(false_schema, Schema::Any(_)),
        "boolean false must deserialize as Schema::Any"
    );

    // Schema::Any round-trips: serialize back produces the original value
    let json_val = serde_json::to_value(&true_schema).unwrap();
    assert_eq!(json_val, serde_json::json!(true));

    // Numeric Schema::Any (also not a valid Object or Reference)
    let num_schema: Schema =
        serde_json::from_value(serde_json::json!(42)).expect("number should deserialize");
    assert!(
        matches!(num_schema, Schema::Any(_)),
        "number must deserialize as Schema::Any"
    );

    // Manually constructed Schema::Any serializes correctly
    let any = Schema::Any(serde_json::json!({"x-custom": "extension-only schema"}));
    let serialized = serde_json::to_value(&any).unwrap();
    assert_eq!(serialized["x-custom"], "extension-only schema");
}

#[test]
fn test_schema_any_in_generated_messages() {
    // Verifies the regression from #4: an enum with serde_json::Value fields
    // must produce Schema::Any (not panic) for the open-ended payload property.
    #[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
    #[serde(tag = "type")]
    pub enum MsgWithAny {
        #[serde(rename = "typed")]
        Typed { id: u32 },
        #[serde(rename = "open")]
        Open {
            #[serde(skip_serializing_if = "Option::is_none")]
            data: Option<serde_json::Value>,
        },
    }

    let messages = MsgWithAny::asyncapi_messages();
    assert_eq!(messages.len(), 2);

    let open_msg = messages
        .iter()
        .find(|m| m.name.as_deref() == Some("Open"))
        .expect("Open message must exist");

    // The payload itself must be present and parseable
    assert!(open_msg.payload.is_some(), "Open payload must be present");

    // The payload schema's "data" property must be Schema::Any (open-ended)
    let payload_json = serde_json::to_value(&open_msg.payload).unwrap();
    let data_schema = payload_json.pointer("/properties/data");
    assert!(
        data_schema.is_some(),
        "data property must appear in payload schema"
    );
    // Deserialize the data property's schema — must not panic and must be Schema::Any
    if let Some(ds) = data_schema {
        let schema: asyncapi_rust::Schema = serde_json::from_value(ds.clone())
            .expect("data property schema must deserialize without panic");
        assert!(
            matches!(schema, asyncapi_rust::Schema::Any(_)),
            "serde_json::Value field must produce Schema::Any; got: {ds}"
        );
    }
}

// ── Untagged serde enums ─────────────────────────────────────────────────────

#[test]
fn test_untagged_enum() {
    #[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
    #[serde(untagged)]
    pub enum UntaggedMsg {
        Number(i64),
        Text { content: String },
        Object { id: u32, label: String },
    }

    // Must not panic and must return one message per variant
    let names = UntaggedMsg::asyncapi_message_names();
    assert_eq!(names, vec!["Number", "Text", "Object"]);
    assert_eq!(UntaggedMsg::asyncapi_tag_field(), None);

    let messages = UntaggedMsg::asyncapi_messages();
    assert_eq!(messages.len(), 3);

    // With no tag, all messages fall back to the full schema (anyOf/oneOf union)
    // — not per-variant. Verify they have payloads and correct names.
    for msg in &messages {
        assert!(
            msg.payload.is_some(),
            "untagged variant '{}' must have a payload",
            msg.name.as_deref().unwrap_or("?")
        );
    }

    // Payloads should reflect the full union schema — each should contain
    // the oneOf or anyOf that schemars generates for untagged enums.
    let number_msg = messages
        .iter()
        .find(|m| m.name.as_deref() == Some("Number"))
        .expect("Number message must exist");
    let payload_json = serde_json::to_value(&number_msg.payload).unwrap();
    // schemars generates oneOf or anyOf for untagged — either is valid
    let has_union = payload_json.get("oneOf").is_some() || payload_json.get("anyOf").is_some();
    assert!(
        has_union,
        "untagged enum payload should be a union schema; got: {payload_json}"
    );
}

// ── Adjacently-tagged serde enums ────────────────────────────────────────────

#[test]
fn test_adjacently_tagged_enum() {
    #[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
    #[serde(tag = "kind", content = "payload")]
    pub enum AdjacentMsg {
        #[serde(rename = "ping")]
        Ping,
        #[serde(rename = "data")]
        Data { value: String, count: u32 },
    }

    // Must not panic
    let names = AdjacentMsg::asyncapi_message_names();
    assert_eq!(names, vec!["Ping", "Data"]);
    // Tag field is "kind" (the tag half; content is separate)
    assert_eq!(AdjacentMsg::asyncapi_tag_field(), Some("kind"));

    let messages = AdjacentMsg::asyncapi_messages();
    assert_eq!(messages.len(), 2);

    for msg in &messages {
        assert!(
            msg.payload.is_some(),
            "adjacently-tagged variant '{}' must have a payload",
            msg.name.as_deref().unwrap_or("?")
        );
    }

    // The "kind" discriminant must appear somewhere in each payload schema.
    // Whether it's per-variant or the full union depends on schemars' output
    // for adjacently-tagged enums — we don't assert a specific shape, just
    // that the schema is present and the discriminant value is represented.
    let ping = messages
        .iter()
        .find(|m| m.name.as_deref() == Some("Ping"))
        .expect("Ping must exist");
    let data = messages
        .iter()
        .find(|m| m.name.as_deref() == Some("Data"))
        .expect("Data must exist");

    let ping_json = serde_json::to_value(&ping.payload).unwrap();
    let data_json = serde_json::to_value(&data.payload).unwrap();

    // Both payloads must be non-null JSON objects
    assert!(ping_json.is_object() || ping_json.is_boolean());
    assert!(data_json.is_object() || data_json.is_boolean());

    // The wire discriminant value "ping" / "data" must appear somewhere in
    // the serialized payload schema (either as per-variant const or in the oneOf)
    let ping_str = serde_json::to_string(&ping_json).unwrap();
    let data_str = serde_json::to_string(&data_json).unwrap();
    assert!(
        ping_str.contains("ping"),
        "discriminant 'ping' must appear in Ping payload schema"
    );
    assert!(
        data_str.contains("data"),
        "discriminant 'data' must appear in Data payload schema"
    );
}