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
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
/*! Available responses back from the kernel.
*/
use header::Header;
use metadata::Metadata;
use serde_derive::Deserialize;
use serde_json::Value;
use std::collections::HashMap;

/// Link pointing to some help text.
#[derive(Deserialize, Debug, PartialEq, Eq)]
pub struct HelpLink {
    /// The text to display.
    pub text: String,
    /// The url to point to.
    pub url: String,
}

/** Overall response type

There are two responses available:

- responses that come from sending a shell message, and
- responses that come from the IOPub socket.

These two responses are then wrapped into a single `Response` type so that functions can return any
response.
*/
#[derive(Debug)]
pub enum Response {
    /// Response from sending a shell message.
    Shell(ShellResponse),
    /// Response from the IOPub socket, sent from the kernel.
    IoPub(IoPubResponse),
}

/// Responses from sending shell messages.
#[derive(Debug)]
pub enum ShellResponse {
    /// Response from asking for information about the running kernel.
    KernelInfo {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: KernelInfoContent,
    },
    /// Response from sending an execute request.
    Execute {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: ExecuteReplyContent,
    },
    /// Response from inspecting a code block.
    Inspect {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: InspectContent,
    },
    /// Resposne from asking for code completion.
    Complete {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: CompleteContent,
    },
    /// Response from fetching kernel command history.
    History {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: HistoryContent,
    },
    /// Response from asking the kernel if the code is complete.
    IsComplete {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: IsCompleteStatus,
    },
    /// Response from asking to shut down the kernel.
    Shutdown {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: ShutdownContent,
    },
    /// Response from asking information about comms.
    CommInfo {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: CommInfoContent,
    },
}

/// Responses from the IOPub channel.
#[derive(Debug)]
pub enum IoPubResponse {
    /// Response from the kernel showing the current kernel status.
    Status {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: StatusContent,
    },
    /// Response when any code is run so all clients are aware of it.
    ExecuteInput {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: ExecuteInputContent,
    },
    /// Response when something is written to stdout/stderr.
    Stream {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: StreamContent,
    },
    /// Response when a response has mutliple formats.
    ExecuteResult {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: ExecuteResultContent,
    },
    /// Response when an error occurs.
    Error {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: ErrorContent,
    },
    /// Response when the kernel askes the client to clear it's output.
    ClearOutput {
        /// Header from the kernel.
        header: Header,
        /// Header sent to the kernel.
        parent_header: Header,
        /// Metadata about the response.
        metadata: Metadata,
        /// Main response content.
        content: ClearOutputContent,
    },
}

/// Content for a KernelInfo response.
#[derive(Deserialize, Debug)]
pub struct KernelInfoContent {
    /// Status of the request.
    pub status: Status,
    /// Version of the messaging protocol.
    pub protocol_version: String,
    /// The kernel implementation name.
    pub implementation: String,
    /// The kernel implementation version.
    pub implementation_version: String,
    /// Information about the language of code for the kernel.
    pub language_info: LanguageInfo,
    /// A banner of information about the kernel.
    pub banner: String,
    /// List of help entries.
    pub help_links: Vec<HelpLink>,
}

/// Information about the language of code for the kernel.
#[derive(Deserialize, Debug)]
pub struct LanguageInfo {
    /// Name of the programming language the kernel implements.
    pub name: String,
    /// The language version number.
    pub version: String,
    /// Mimetype for script files in this language.
    pub mimetype: String,
    /// Extension including the dot e.g. '.py'
    pub file_extension: String,
    /// Pygments lexer for highlighting.
    pub pygments_lexer: String,
    /// Codemirror mode, for highlighting in the notebook.
    pub codemirror_mode: Value,
    /// If notebooks written with this kernel should be exported with something other than the
    /// general 'script' exporter.
    pub nbconvert_exporter: String,
}

/// Information from code execution.
#[derive(Deserialize, Debug)]
pub struct ExecuteReplyContent {
    /// Status of the request.
    pub status: Status,
    /// Global execution count.
    pub execution_count: i64,
    // status == "ok" fields
    /// List of payload dicts (deprecated).
    pub payload: Option<Vec<HashMap<String, Value>>>,
    /// Results for the user expressions.
    pub user_expressions: Option<HashMap<String, Value>>,
    // status == "error" fields
    /// Exception name as a string.
    pub ename: Option<String>,
    /// Exception value, as a string.
    pub evalue: Option<String>,
    /// Traceback frames as strings.
    pub traceback: Option<Vec<String>>,
}

/// Response from the IOPub status messages
#[derive(Deserialize, Debug)]
pub struct StatusContent {
    /// The state of the kernel.
    pub execution_state: ExecutionState,
}

/// Response when code is input to the kernel.
#[derive(Deserialize, Debug)]
pub struct ExecuteInputContent {
    /// The code that was run.
    pub code: String,
    /// Counter for the execution number.
    pub execution_count: i64,
}

/// Response from inspecting code
#[derive(Deserialize, Debug)]
pub struct InspectContent {
    /// Status of the request.
    pub status: Status,
    /// Whether the object was found or not.
    pub found: bool,
    /// Empty if nothing is found.
    pub data: HashMap<String, Value>,
    /// Metadata.
    pub metadata: HashMap<String, Value>,
}

/// Response when printing to stdout/stderr.
#[derive(Deserialize, Debug)]
pub struct StreamContent {
    /// Type of the stream.
    pub name: StreamType,
    /// Text to be written to the stream.
    pub text: String,
}

/// Content of an error response.
#[derive(Deserialize, Debug)]
pub struct ErrorContent {
    /// Exception name as a string.
    pub ename: String,
    /// Exception value, as a string.
    pub evalue: String,
    /// Traceback frames as strings.
    pub traceback: Vec<String>,
}

/// Content when asking for code completion.
#[derive(Deserialize, Debug)]
pub struct CompleteContent {
    /// Status of the request.
    pub status: Status,
    /// List of all matches.
    pub matches: Vec<String>,
    /// The start index text that should be replaced by the match.
    pub cursor_start: u64,
    /// The end index text that should be replaced by the match.
    pub cursor_end: u64,
    /// Extra information.
    pub metadata: HashMap<String, Value>,
}

/// Content when asking for history entries.
#[derive(Deserialize, Debug)]
pub struct HistoryContent {
    /// Status of the request.
    pub status: Status,
    /// List of history items.
    pub history: Vec<Value>,
}

/// Response when asking the kernel to shutdown.
#[derive(Deserialize, Debug)]
pub struct ShutdownContent {
    /// Status of the request.
    pub status: Status,
    /// Whether restart was requested.
    pub restart: bool,
}

/// Response when asking for comm info.
#[derive(Deserialize, Debug)]
pub struct CommInfoContent {
    /// Status of the request.
    pub status: Status,
    /// Map of available comms.
    pub comms: HashMap<String, HashMap<String, String>>,
}

/// Response when requesting to execute code.
#[derive(Deserialize, Debug)]
pub struct ExecuteResultContent {
    /// Global execution count.
    pub execution_count: i64,
    /// The result of the execution.
    pub data: HashMap<String, String>,
    /// Metadata about the execution.
    pub metadata: Value,
}

/// Response when the kernel asks the client to clear the output.
#[derive(Deserialize, Debug)]
pub struct ClearOutputContent {
    /// Wait to clear the output until new output is available.
    pub wait: bool,
}

/// State of the kernel.
#[derive(Deserialize, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ExecutionState {
    /// Running code.
    Busy,
    /// Doing nothing.
    Idle,
    /// Booting.
    Starting,
}

/// Status of if entered code is complete (i.e. does not need another " character).
#[derive(Deserialize, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum IsCompleteStatus {
    /// Entered code is complete.
    Complete,
    /// More code is required. The argument is the indent value for the prompt.
    Incomplete(String),
    /// Invalid completion.
    Invalid,
    /// Unknown completion.
    Unknown,
}

/// Type of stream, either stdout or stderr.
#[derive(Deserialize, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
#[allow(missing_docs)]
pub enum StreamType {
    Stdout,
    Stderr,
}

/// Status of the request.
#[derive(Deserialize, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
#[allow(missing_docs)]
pub enum Status {
    Ok,
    Error,
    Abort,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helpers::*;
    use crate::wire::WireMessage;

    #[test]
    fn test_kernel_info_message_parsing() {
        let auth = FakeAuth::create();
        let raw_response = vec![
            "<IDS|MSG>".to_string().into_bytes(),
            expected_signature().into_bytes(),
            // Header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "kernel_info_reply",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Parent header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "kernel_info_request",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Metadata
            r#"{}"#.to_string().into_bytes(),
            // Content
            r#"{
                "banner": "banner",
                "implementation": "implementation",
                "implementation_version": "implementation_version",
                "protocol_version": "protocol_version",
                "status": "ok",
                "language_info": {
                    "name": "python",
                    "version": "3.7.0",
                    "mimetype": "text/x-python",
                    "file_extension": ".py",
                    "pygments_lexer": "ipython3",
                    "codemirror_mode": {
                        "name": "ipython",
                        "version": 3
                    },
                    "nbconvert_exporter": "python"
                },
                "help_links": [{"text": "text", "url": "url"}]
            }"#.to_string()
            .into_bytes(),
        ];
        let msg = WireMessage::from_raw_response(raw_response, auth.clone()).unwrap();
        let response = msg.into_response().unwrap();
        match response {
            Response::Shell(ShellResponse::KernelInfo {
                header,
                parent_header: _parent_header,
                metadata: _metadata,
                content,
            }) => {
                // Check the header
                assert_eq!(header.msg_type, "kernel_info_reply");

                // Check the content
                assert_eq!(content.banner, "banner");
                assert_eq!(content.implementation, "implementation");
                assert_eq!(content.implementation_version, "implementation_version");
                assert_eq!(content.protocol_version, "protocol_version");
                assert_eq!(content.status, Status::Ok);
                assert_eq!(
                    content.help_links,
                    vec![HelpLink {
                        text: "text".to_string(),
                        url: "url".to_string(),
                    }]
                );
                assert_eq!(content.language_info.name, "python");
            }
            _ => unreachable!("Incorrect response type, should be KernelInfo"),
        }
    }

    #[test]
    fn test_execute_request_message_parsing() {
        let auth = FakeAuth::create();
        let raw_response = vec![
            "<IDS|MSG>".to_string().into_bytes(),
            expected_signature().into_bytes(),
            // Header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "execute_reply",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Parent header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "execute_request",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Metadata
            r#"{}"#.to_string().into_bytes(),
            // Content
            r#"{
                "status": "ok",
                "execution_count": 4
            }"#.to_string()
            .into_bytes(),
        ];
        let msg = WireMessage::from_raw_response(raw_response, auth.clone()).unwrap();
        let response = msg.into_response().unwrap();
        match response {
            Response::Shell(ShellResponse::Execute {
                header,
                parent_header: _parent_header,
                metadata: _metadata,
                content,
            }) => {
                // Check the header
                assert_eq!(header.msg_type, "execute_reply");

                // Check the content
                assert_eq!(content.status, Status::Ok);
                assert_eq!(content.execution_count, 4);
            }
            _ => unreachable!("Incorrect response type, should be KernelInfo"),
        }
    }

    #[test]
    fn test_status_message_parsing() {
        let auth = FakeAuth::create();
        let raw_response = vec![
            "<IDS|MSG>".to_string().into_bytes(),
            expected_signature().into_bytes(),
            // Header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "status",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Parent header, not relevant
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "execute_request",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Metadata
            r#"{}"#.to_string().into_bytes(),
            // Content
            r#"{
                "status": "ok",
                "execution_state": "busy"
            }"#.to_string()
            .into_bytes(),
        ];
        let msg = WireMessage::from_raw_response(raw_response, auth.clone()).unwrap();
        let response = msg.into_response().unwrap();
        match response {
            Response::IoPub(IoPubResponse::Status {
                header,
                parent_header: _parent_header,
                metadata: _metadata,
                content,
            }) => {
                // Check the header
                assert_eq!(header.msg_type, "status");

                // Check the content
                assert_eq!(content.execution_state, ExecutionState::Busy);
            }
            _ => unreachable!("Incorrect response type, should be Status"),
        }
    }

    #[test]
    fn test_execute_input_parsing() {
        let auth = FakeAuth::create();
        let raw_response = vec![
            "<IDS|MSG>".to_string().into_bytes(),
            expected_signature().into_bytes(),
            // Header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "execute_input",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Parent header, not relevant
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Metadata
            r#"{}"#.to_string().into_bytes(),
            // Content
            r#"{
                "status": "ok",
                "code": "a = 10",
                "execution_count": 4
            }"#.to_string()
            .into_bytes(),
        ];
        let msg = WireMessage::from_raw_response(raw_response, auth.clone()).unwrap();
        let response = msg.into_response().unwrap();
        match response {
            Response::IoPub(IoPubResponse::ExecuteInput {
                header,
                parent_header: _parent_header,
                metadata: _metadata,
                content,
            }) => {
                // Check the header
                assert_eq!(header.msg_type, "execute_input");

                // Check the content
                assert_eq!(content.code, "a = 10");
                assert_eq!(content.execution_count, 4);
            }
            _ => unreachable!("Incorrect response type, should be Status"),
        }
    }

    #[test]
    fn test_stream_parsing() {
        let auth = FakeAuth::create();
        let raw_response = vec![
            "<IDS|MSG>".to_string().into_bytes(),
            expected_signature().into_bytes(),
            // Header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "stream",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Parent header, not relevant
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Metadata
            r#"{}"#.to_string().into_bytes(),
            // Content
            r#"{
                "status": "ok",
                "name": "stdout",
                "text": "10"
            }"#.to_string()
            .into_bytes(),
        ];
        let msg = WireMessage::from_raw_response(raw_response, auth.clone()).unwrap();
        let response = msg.into_response().unwrap();
        match response {
            Response::IoPub(IoPubResponse::Stream {
                header,
                parent_header: _parent_header,
                metadata: _metadata,
                content,
            }) => {
                // Check the header
                assert_eq!(header.msg_type, "stream");

                // Check the content
                assert_eq!(content.name, StreamType::Stdout);
                assert_eq!(content.text, "10");
            }
            _ => unreachable!("Incorrect response type, should be Stream"),
        }
    }

    #[test]
    fn test_is_complete_message_parsing() {
        let auth = FakeAuth::create();
        let raw_response = vec![
            "<IDS|MSG>".to_string().into_bytes(),
            expected_signature().into_bytes(),
            // Header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "is_complete_reply",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Parent header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "is_complete_request",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Metadata
            r#"{}"#.to_string().into_bytes(),
            // Content
            r#"{
                "status": "complete"
            }"#.to_string()
            .into_bytes(),
        ];
        let msg = WireMessage::from_raw_response(raw_response, auth.clone()).unwrap();
        let response = msg.into_response().unwrap();
        match response {
            Response::Shell(ShellResponse::IsComplete {
                header,
                parent_header: _parent_header,
                metadata: _metadata,
                content,
            }) => {
                // Check the header
                assert_eq!(header.msg_type, "is_complete_reply");

                // Check the content
                assert_eq!(content, IsCompleteStatus::Complete);
            }
            _ => unreachable!("Incorrect response type, should be IsComplete"),
        }
    }

    #[test]
    fn test_is_complete_message_parsing_with_incomplete_reply() {
        let auth = FakeAuth::create();
        let raw_response = vec![
            "<IDS|MSG>".to_string().into_bytes(),
            expected_signature().into_bytes(),
            // Header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "is_complete_reply",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Parent header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "is_complete_request",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Metadata
            r#"{}"#.to_string().into_bytes(),
            // Content
            r#"{
                "status": "incomplete",
                "indent": "  "
            }"#.to_string()
            .into_bytes(),
        ];
        let msg = WireMessage::from_raw_response(raw_response, auth.clone()).unwrap();
        let response = msg.into_response().unwrap();
        match response {
            Response::Shell(ShellResponse::IsComplete {
                header,
                parent_header: _parent_header,
                metadata: _metadata,
                content,
            }) => {
                // Check the header
                assert_eq!(header.msg_type, "is_complete_reply");

                // Check the content
                assert_eq!(content, IsCompleteStatus::Incomplete("  ".to_string()));
            }
            _ => unreachable!("Incorrect response type, should be IsComplete"),
        }
    }

    #[test]
    fn test_shutdown_message_parsing() {
        let auth = FakeAuth::create();
        let raw_response = vec![
            "<IDS|MSG>".to_string().into_bytes(),
            expected_signature().into_bytes(),
            // Header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "shutdown_reply",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Parent header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "kernel_info_request",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Metadata
            r#"{}"#.to_string().into_bytes(),
            // Content
            r#"{
                "status": "ok",
                "restart": false
            }"#.to_string()
            .into_bytes(),
        ];
        let msg = WireMessage::from_raw_response(raw_response, auth.clone()).unwrap();
        let response = msg.into_response().unwrap();
        match response {
            Response::Shell(ShellResponse::Shutdown {
                header,
                parent_header: _parent_header,
                metadata: _metadata,
                content,
            }) => {
                // Check the header
                assert_eq!(header.msg_type, "shutdown_reply");

                // Check the content
                assert_eq!(content.restart, false);
            }
            _ => unreachable!("Incorrect response type, should be KernelInfo"),
        }
    }

    #[test]
    fn test_comm_info_message_parsing() {
        let auth = FakeAuth::create();
        let raw_response = vec![
            "<IDS|MSG>".to_string().into_bytes(),
            expected_signature().into_bytes(),
            // Header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "comm_info_reply",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Parent header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "comm_info_request",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Metadata
            r#"{}"#.to_string().into_bytes(),
            // Content
            r#"{
                "status": "ok",
                "comms": {
                    "u-u-i-d": {
                        "target_name": "foobar"
                    }
                }
            }"#.to_string()
            .into_bytes(),
        ];
        let msg = WireMessage::from_raw_response(raw_response, auth.clone()).unwrap();
        let response = msg.into_response().unwrap();
        match response {
            Response::Shell(ShellResponse::CommInfo {
                header,
                parent_header: _parent_header,
                metadata: _metadata,
                content,
            }) => {
                // Check the header
                assert_eq!(header.msg_type, "comm_info_reply");

                // Check the content
                assert_eq!(content.comms["u-u-i-d"]["target_name"], "foobar");
            }
            _ => unreachable!("Incorrect response type, should be CommInfo"),
        }
    }

    #[test]
    fn test_execute_result_message_parsing() {
        use serde_json::json;

        let auth = FakeAuth::create();
        let raw_response = vec![
            "<IDS|MSG>".to_string().into_bytes(),
            expected_signature().into_bytes(),
            // Header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "execute_result",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Parent header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "execute_request",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Metadata
            r#"{}"#.to_string().into_bytes(),
            // Content
            r#"{
                "data": {
                    "text/plain": "10"
                },
                "metadata": {},
                "execution_count": 46
            }"#.to_string()
            .into_bytes(),
        ];
        let msg = WireMessage::from_raw_response(raw_response, auth.clone()).unwrap();
        let response = msg.into_response().unwrap();
        match response {
            Response::IoPub(IoPubResponse::ExecuteResult {
                header,
                parent_header: _parent_header,
                metadata: _metadata,
                content,
            }) => {
                // Check the header
                assert_eq!(header.msg_type, "execute_result");

                // Check the content
                assert_eq!(content.data["text/plain"], "10");
                assert_eq!(content.metadata, json!({}));
                assert_eq!(content.execution_count, 46);
            }
            _ => unreachable!("Incorrect response type, should be ExecuteResult"),
        }
    }

    #[test]
    fn test_clear_output_message_parsing() {
        let auth = FakeAuth::create();
        let raw_response = vec![
            "<IDS|MSG>".to_string().into_bytes(),
            expected_signature().into_bytes(),
            // Header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "clear_output",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Parent header
            r#"{
                "date": "",
                "msg_id": "",
                "username": "",
                "session": "",
                "msg_type": "execute_request",
                "version": ""
            }"#.to_string()
            .into_bytes(),
            // Metadata
            r#"{}"#.to_string().into_bytes(),
            // Content
            r#"{
                "wait": false
            }"#.to_string()
            .into_bytes(),
        ];
        let msg = WireMessage::from_raw_response(raw_response, auth.clone()).unwrap();
        let response = msg.into_response().unwrap();
        match response {
            Response::IoPub(IoPubResponse::ClearOutput {
                header,
                parent_header: _parent_header,
                metadata: _metadata,
                content,
            }) => {
                // Check the header
                assert_eq!(header.msg_type, "clear_output");

                // Check the content
                assert_eq!(content.wait, false);
            }
            _ => unreachable!("Incorrect response type, should be ClearOutput"),
        }
    }
}