below-dump 0.5.0

Dump crate for below
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
// Copyright (c) Facebook, Inc. and its affiliates.
//
// Licensed 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.

use serde_json::Value;

use super::*;
use command::{expand_fields, GeneralOpt, OutputFormat};
use common::logutil::get_logger;
use model::{Collector, EnumIter, Queriable};
use print::HasRenderConfigForDump;
use tmain::Dumper;

use tempdir::TempDir;

#[test]
// Test correctness of system decoration
fn test_dump_sys_content() {
    let mut collector = Collector::new(Default::default());
    let logger = get_logger();
    collector.update_model(&logger).expect("Fail to get model");

    let mut opts: GeneralOpt = Default::default();
    let mut fields = command::expand_fields(command::DEFAULT_SYSTEM_FIELDS, true);
    for subquery_id in model::SingleCpuModelFieldId::unit_variant_iter() {
        fields.push(DumpField::FieldId(model::SystemModelFieldId::Cpus(
            model::VecFieldId {
                idx: Some(31),
                subquery_id,
            },
        )));
    }
    opts.output_format = Some(OutputFormat::Json);
    let system_dumper = system::System::new(&opts, fields.clone());

    // update model again to populate cpu and io data
    let model = collector.update_model(&logger).expect("Fail to get model");
    let mut system_content: Vec<u8> = Vec::new();
    let mut round = 0;
    let ctx = CommonFieldContext { timestamp: 0 };
    system_dumper
        .dump_model(&ctx, &model, &mut system_content, &mut round, false)
        .expect("Failed to dump system model");

    // verify json correctness
    assert!(!system_content.is_empty());
    let jval: Value =
        serde_json::from_slice(&system_content).expect("Fail parse json of system dump");

    for dump_field in fields.iter() {
        match dump_field {
            DumpField::Common(_) => continue,
            DumpField::FieldId(field_id) => {
                let rc = model::SystemModel::get_render_config_for_dump(&field_id);
                assert_eq!(
                    rc.render(model.system.query(&field_id), false),
                    jval[rc.render_title(false)]
                        .as_str()
                        .unwrap_or_else(|| panic!(
                            "Key not found in Json: {}",
                            rc.render_title(false)
                        ))
                        .to_owned(),
                    "Model value and json value do not match for field: {}",
                    field_id.to_string(),
                );
            }
        }
    }
}

#[test]
fn test_dump_sys_titles() {
    let titles = expand_fields(command::DEFAULT_SYSTEM_FIELDS, true)
        .into_iter()
        .chain(
            model::SingleCpuModelFieldId::unit_variant_iter().map(|subquery_id| {
                DumpField::FieldId(model::SystemModelFieldId::Cpus(model::VecFieldId {
                    idx: Some(31),
                    subquery_id,
                }))
            }),
        )
        .filter_map(|dump_field| match dump_field {
            DumpField::Common(_) => None,
            DumpField::FieldId(field_id) => {
                let rc = model::SystemModel::get_render_config_for_dump(&field_id);
                Some(rc.render_title(false))
            }
        })
        .collect::<Vec<_>>();
    let expected_titles = vec![
        "Hostname",
        "Usage",
        "User",
        "System",
        "Idle",
        "Nice",
        "IOWait",
        "Irq",
        "SoftIrq",
        "Stolen",
        "Guest",
        "Guest Nice",
        "Total",
        "Free",
        "Available",
        "Buffers",
        "Cached",
        "Swap Cached",
        "Active",
        "Inactive",
        "Anon",
        "File",
        "Unevictable",
        "Mlocked",
        "Swap Total",
        "Swap Free",
        "Dirty",
        "Writeback",
        "Anon Pages",
        "Mapped",
        "Shmem",
        "Kreclaimable",
        "Slab",
        "Slab Reclaimable",
        "Slab Unreclaimable",
        "Kernel Stack",
        "Page Tables",
        "Anon Huge Pages",
        "Shmem Huge Pages",
        "File Huge Pages",
        "Hugetlb",
        "Cma Total",
        "Cma Free",
        "Vmalloc Total",
        "Vmalloc Used",
        "Vmalloc Chunk",
        "Direct Map 4K",
        "Direct Map 2M",
        "Direct Map 1G",
        "Page In",
        "Page Out",
        "Swap In",
        "Swap Out",
        "Pgsteal Kswapd",
        "Pgsteal Direct",
        "Pgscan Kswapd",
        "Pgscan Direct",
        "OOM Kills",
        "Kernel Version",
        "OS Release",
        "Total Interrupts",
        "Context Switches",
        "Boot Time Epoch",
        "Total Procs",
        "Running Procs",
        "Blocked Procs",
        "CPU 31 Idx",
        "CPU 31 Usage",
        "CPU 31 User",
        "CPU 31 System",
        "CPU 31 Idle",
        "CPU 31 Nice",
        "CPU 31 IOWait",
        "CPU 31 Irq",
        "CPU 31 SoftIrq",
        "CPU 31 Stolen",
        "CPU 31 Guest",
        "CPU 31 Guest Nice",
    ];
    assert_eq!(titles, expected_titles);
}

#[test]
// Test correctness of process decoration
// This test will also test JSON correctness.
fn test_dump_process_content() {
    let mut collector = Collector::new(Default::default());
    let logger = get_logger();
    collector.update_model(&logger).expect("Fail to get model");

    let mut opts: GeneralOpt = Default::default();
    let fields = command::expand_fields(command::DEFAULT_PROCESS_FIELDS, true);
    opts.output_format = Some(OutputFormat::Json);
    let process_dumper = process::Process::new(&opts, None, fields.clone());

    // update model again to populate cpu and io data
    let model = collector.update_model(&logger).expect("Fail to get model");
    let mut process_content: Vec<u8> = Vec::new();
    let mut round = 0;
    let ctx = CommonFieldContext { timestamp: 0 };
    process_dumper
        .dump_model(&ctx, &model, &mut process_content, &mut round, false)
        .expect("Failed to dump process model");

    // verify json correctness
    assert!(!process_content.is_empty());
    let jval: Value =
        serde_json::from_slice(&process_content).expect("Fail parse json of process dump");

    // verify content correctness, test first 5 should be enough
    let mut count = 5;
    for value in jval.as_array().unwrap() {
        let pid = value["Pid"].as_str().unwrap();
        let spm = model
            .process
            .processes
            .get(&pid.parse().unwrap())
            .expect("Json pid and spm pid not match");

        for dump_field in fields.iter() {
            match dump_field {
                DumpField::Common(_) => continue,
                DumpField::FieldId(field_id) => {
                    let rc = model::SingleProcessModel::get_render_config_for_dump(&field_id);
                    assert_eq!(
                        rc.render(spm.query(&field_id), false),
                        value[rc.render_title(false)]
                            .as_str()
                            .unwrap_or_else(|| panic!(
                                "Key not found in Json: {}",
                                rc.render_title(false)
                            ))
                            .to_owned(),
                        "Model value and json value do not match for field: {}",
                        field_id.to_string(),
                    );
                }
            }
        }
        count -= 1;
        if count == 0 {
            break;
        }
    }
}

#[test]
fn test_dump_proc_titles() {
    let titles = expand_fields(command::DEFAULT_PROCESS_FIELDS, true)
        .iter()
        .filter_map(|dump_field| match dump_field {
            DumpField::Common(_) => None,
            DumpField::FieldId(field_id) => {
                let rc = model::SingleProcessModel::get_render_config_for_dump(&field_id);
                Some(rc.render_title(false))
            }
        })
        .collect::<Vec<_>>();
    let expected_titles = vec![
        "Pid",
        "Ppid",
        "Comm",
        "State",
        "CPU",
        "User CPU",
        "Sys CPU",
        "Threads",
        "Minflt",
        "Majflt",
        "RSS",
        "VM Size",
        "Lock",
        "Pin",
        "Anon",
        "File",
        "Shmem",
        "PTE",
        "Swap",
        "Huge TLB",
        "Reads",
        "Writes",
        "RW",
        "Uptime(sec)",
        "Cgroup",
        "Cmdline",
        "Exe Path",
    ];
    assert_eq!(titles, expected_titles);
}

#[test]
fn test_dump_proc_select() {
    let mut collector = Collector::new(Default::default());
    let logger = get_logger();
    collector.update_model(&logger).expect("Fail to get model");
    // update model again to populate cpu and io data
    let model = collector.update_model(&logger).expect("Fail to get model");

    let fields = command::expand_fields(command::DEFAULT_PROCESS_FIELDS, true);
    let mut opts: GeneralOpt = Default::default();
    opts.everything = true;
    opts.output_format = Some(OutputFormat::Json);
    opts.filter = Some(
        regex::Regex::new(&model.process.processes.iter().last().unwrap().0.to_string())
            .expect("Fail to construct regex"),
    );
    let process_dumper = process::Process::new(
        &opts,
        Some(model::SingleProcessModelFieldId::Pid),
        fields.clone(),
    );

    let mut process_content: Vec<u8> = Vec::new();
    let mut round = 0;
    let ctx = CommonFieldContext { timestamp: 0 };
    process_dumper
        .dump_model(&ctx, &model, &mut process_content, &mut round, false)
        .expect("Failed to dump process model");

    // test select filter
    let jval: Value =
        serde_json::from_slice(&process_content).expect("Fail parse json of process dump");
    assert_eq!(jval.as_array().unwrap().len(), 1);

    // test select rsort top
    opts.sort = true;
    opts.top = 5;
    opts.filter = None;
    let process_dumper = process::Process::new(
        &opts,
        Some(model::SingleProcessModelFieldId::Pid),
        fields.clone(),
    );

    process_content = Vec::new();
    round = 0;
    process_dumper
        .dump_model(&ctx, &model, &mut process_content, &mut round, false)
        .expect("Failed to dump process model");

    assert_eq!(round, 5);
    let jval: Value =
        serde_json::from_slice(&process_content).expect("Fail parse json of process dump");

    let mut prev_id = 0;
    for item in jval.as_array().unwrap() {
        let pid = item["Pid"].as_str().unwrap();
        let cur_id = pid.parse::<i32>().unwrap();
        if prev_id > 0 {
            assert!(prev_id < cur_id, "prev_id: {}, cur_id: {}", prev_id, cur_id);
        }
        prev_id = cur_id;
    }

    // test select sort top
    opts.sort = false;
    opts.rsort = true;
    let process_dumper =
        process::Process::new(&opts, Some(model::SingleProcessModelFieldId::Pid), fields);

    process_content = Vec::new();
    round = 0;
    process_dumper
        .dump_model(&ctx, &model, &mut process_content, &mut round, false)
        .expect("Failed to dump process model");

    assert_eq!(round, 5);
    let jval: Value =
        serde_json::from_slice(&process_content).expect("Fail parse json of process dump");

    prev_id = 0;
    for item in jval.as_array().unwrap() {
        let pid = item["Pid"].as_str().unwrap();
        let cur_id = pid.parse::<i32>().unwrap();
        if prev_id > 0 {
            assert!(prev_id > cur_id, "prev_id: {}, cur_id: {}", prev_id, cur_id);
        }
        prev_id = cur_id;
    }
}

fn traverse_cgroup_tree(model: &model::CgroupModel, jval: &Value) {
    for dump_field in expand_fields(command::DEFAULT_CGROUP_FIELDS, true) {
        match dump_field {
            DumpField::Common(_) => continue,
            DumpField::FieldId(field_id) => {
                let rc = model::SingleCgroupModel::get_render_config_for_dump(&field_id);
                assert_eq!(
                    rc.render(model.data.query(&field_id), false),
                    jval[rc.render_title(false)]
                        .as_str()
                        .unwrap_or_else(|| panic!(
                            "Key not found in Json: {}",
                            rc.render_title(false)
                        ))
                        .to_owned(),
                    "Model value and json value do not match for field: {}",
                    field_id.to_string(),
                );
            }
        }
    }
    model
        .children
        .iter()
        .zip(jval["children"].as_array().unwrap().iter())
        .take(2)
        .for_each(|(child_model, child_jval)| traverse_cgroup_tree(child_model, child_jval));
}

#[test]
fn test_dump_cgroup_content() {
    let mut collector = Collector::new(Default::default());
    let logger = get_logger();
    collector.update_model(&logger).expect("Fail to get model");

    let mut opts: GeneralOpt = Default::default();
    let fields = command::expand_fields(command::DEFAULT_CGROUP_FIELDS, true);
    opts.output_format = Some(OutputFormat::Json);
    let cgroup_dumper = cgroup::Cgroup::new(&opts, None, fields);

    // update model again to populate cpu and io data
    let model = collector.update_model(&logger).expect("Fail to get model");
    let mut cgroup_content: Vec<u8> = Vec::new();
    let mut round = 0;
    let ctx = CommonFieldContext { timestamp: 0 };
    cgroup_dumper
        .dump_model(&ctx, &model, &mut cgroup_content, &mut round, false)
        .expect("Failed to dump cgroup model");

    // verify json correctness
    assert!(!cgroup_content.is_empty());
    let mut jval: Value =
        serde_json::from_slice(&cgroup_content).expect("Fail parse json of process dump");
    traverse_cgroup_tree(&model.cgroup, &mut jval);
}

#[test]
fn test_dump_cgroup_titles() {
    let titles = expand_fields(command::DEFAULT_CGROUP_FIELDS, true)
        .iter()
        .filter_map(|dump_field| match dump_field {
            DumpField::Common(_) => None,
            DumpField::FieldId(field_id) => {
                let rc = model::SingleCgroupModel::get_render_config_for_dump(&field_id);
                Some(rc.render_title(false))
            }
        })
        .collect::<Vec<_>>();
    let expected_titles = vec![
        "Name",
        "Inode Number",
        "CPU Usage",
        "CPU User",
        "CPU Sys",
        "Nr Period",
        "Nr Throttled",
        "Throttled Pct",
        "Mem Total",
        "Mem Swap",
        "Mem Anon",
        "Mem File",
        "Kernel Stack",
        "Mem Slab",
        "Mem Sock",
        "Mem Shmem",
        "File Mapped",
        "File Dirty",
        "File WB",
        "Anon THP",
        "Inactive Anon",
        "Active Anon",
        "Inactive File",
        "Active File",
        "Unevictable",
        "Slab Reclaimable",
        "Slab Unreclaimable",
        "Pgfault",
        "Pgmajfault",
        "Workingset Refault",
        "Workingset Activate",
        "Workingset Nodereclaim",
        "Pgrefill",
        "Pgscan",
        "Pgsteal",
        "Pgactivate",
        "Pgdeactivate",
        "Pglazyfree",
        "Pglazyfreed",
        "THP Fault Alloc",
        "THP Collapse Alloc",
        "Memory High",
        "Events Low",
        "Events High",
        "Events Max",
        "Events OOM",
        "Events Kill",
        "RBytes",
        "WBytes",
        "R I/O",
        "W I/O",
        "DBytes",
        "D I/O",
        "RW Total",
        "CPU Pressure",
        "I/O Some Pressure",
        "I/O Pressure",
        "Memory Some Pressure",
        "Memory Pressure",
    ];
    assert_eq!(titles, expected_titles);
}

#[test]
// Test correctness of iface decoration
// This test will also test JSON correctness.
fn test_dump_iface_content() {
    let mut collector = Collector::new(Default::default());
    let logger = get_logger();
    collector.update_model(&logger).expect("Fail to get model");

    let mut opts: GeneralOpt = Default::default();
    let fields = command::expand_fields(command::DEFAULT_IFACE_FIELDS, true);
    opts.output_format = Some(OutputFormat::Json);
    let iface_dumper = iface::Iface::new(&opts, None, fields.clone());

    // update model again to populate net data
    let model = collector.update_model(&logger).expect("Fail to get model");
    let mut iface_content: Vec<u8> = Vec::new();
    let mut round = 0;
    let ctx = CommonFieldContext { timestamp: 0 };
    iface_dumper
        .dump_model(&ctx, &model, &mut iface_content, &mut round, false)
        .expect("Failed to dump iface model");

    // verify json correctness
    assert!(!iface_content.is_empty());
    let jval: Value =
        serde_json::from_slice(&iface_content).expect("Fail parse json of network dump");

    // verify content correctness, test first 5 should be enough
    let mut count = 5;
    for value in jval.as_array().unwrap() {
        let iface = value["Interface"].as_str().unwrap();
        let snm = model
            .network
            .interfaces
            .get(iface)
            .expect("Json iface and snm iface not match");

        for dump_field in fields.iter() {
            match dump_field {
                DumpField::Common(_) => continue,
                DumpField::FieldId(field_id) => {
                    let rc = model::SingleNetModel::get_render_config_for_dump(&field_id);
                    assert_eq!(
                        rc.render(snm.query(&field_id), false),
                        value[rc.render_title(false)]
                            .as_str()
                            .unwrap_or_else(|| panic!(
                                "Key not found in Json: {}",
                                rc.render_title(false)
                            ))
                            .to_owned(),
                        "Model value and json value do not match for field: {}",
                        field_id.to_string(),
                    );
                }
            }
        }
        count -= 1;
        if count == 0 {
            break;
        }
    }
}

#[test]
fn test_dump_iface_titles() {
    let titles = expand_fields(command::DEFAULT_IFACE_FIELDS, true)
        .iter()
        .filter_map(|dump_field| match dump_field {
            DumpField::Common(_) => None,
            DumpField::FieldId(field_id) => {
                let rc = model::SingleNetModel::get_render_config_for_dump(&field_id);
                Some(rc.render_title(false))
            }
        })
        .collect::<Vec<_>>();
    let expected_titles = vec![
        "Collisions",
        "Multicast",
        "Interface",
        "RX Bytes/s",
        "TX Bytes/s",
        "I/O Bytes/s",
        "RX Pkts/s",
        "TX Pkts/s",
        "RX Bytes",
        "RX Compressed",
        "RX CRC Errors",
        "RX Dropped",
        "RX Errors",
        "RX Fifo Errors",
        "RX Frame Errors",
        "RX Length Errors",
        "RX Missed Errors",
        "RX Nohandler",
        "RX Over Errors",
        "RX Packets",
        "TX Aborted Errors",
        "TX Bytes",
        "TX Carrier Errors",
        "TX Compressed",
        "TX Dropped",
        "TX Errors",
        "TX Fifo Errors",
        "TX Heartbeat Errors",
        "TX Packets",
        "TX Window Errors",
    ];
    assert_eq!(titles, expected_titles);
}

#[test]
// Test correctness of network decoration
// This test will also test JSON correctness.
fn test_dump_network_content() {
    let mut collector = Collector::new(Default::default());
    let logger = get_logger();
    collector.update_model(&logger).expect("Fail to get model");

    let mut opts: GeneralOpt = Default::default();
    let fields = command::expand_fields(command::DEFAULT_NETWORK_FIELDS, true);
    opts.output_format = Some(OutputFormat::Json);
    let network_dumper = network::Network::new(&opts, fields.clone());

    // update model again to populate net data
    let model = collector.update_model(&logger).expect("Fail to get model");
    let mut network_content: Vec<u8> = Vec::new();
    let mut round = 0;
    let ctx = CommonFieldContext { timestamp: 0 };
    network_dumper
        .dump_model(&ctx, &model, &mut network_content, &mut round, false)
        .expect("Failed to dump network model");

    // verify json correctness
    assert!(!network_content.is_empty());
    let jval: Value =
        serde_json::from_slice(&network_content).expect("Fail parse json of network dump");

    for dump_field in fields.iter() {
        match dump_field {
            DumpField::Common(_) => continue,
            DumpField::FieldId(field_id) => {
                let rc = model::NetworkModel::get_render_config_for_dump(&field_id);
                assert_eq!(
                    rc.render(model.network.query(&field_id), false),
                    jval[rc.render_title(false)]
                        .as_str()
                        .unwrap_or_else(|| panic!(
                            "Key not found in Json: {}",
                            rc.render_title(false),
                        ))
                        .to_owned(),
                    "Model value and json value do not match for field: {}",
                    field_id.to_string(),
                );
            }
        }
    }
}

#[test]
fn test_dump_network_titles() {
    let titles = expand_fields(command::DEFAULT_NETWORK_FIELDS, true)
        .iter()
        .filter_map(|dump_field| match dump_field {
            DumpField::Common(_) => None,
            DumpField::FieldId(field_id) => {
                let rc = model::NetworkModel::get_render_config_for_dump(&field_id);
                Some(rc.render_title(false))
            }
        })
        .collect::<Vec<_>>();
    let expected_titles = vec![
        "IpForwPkts/s",
        "IpInPkts/s",
        "IpForwDatagrams/s",
        "IpInDiscardPkts/s",
        "IpInDeliversPkts/s",
        "IpOutReqs/s",
        "IpOutDiscardPkts/s",
        "IpOutNoRoutesPkts/s",
        "IpInMcastPkts/s",
        "IpOutMcastPkts/s",
        "IpInBcastPkts/s",
        "IpOutBcastPkts/s",
        "IpInOctets/s",
        "IpOutOctets/s",
        "IpInMcastOctets/s",
        "IpOutMcastOctets/s",
        "IpInBcastOctets/s",
        "IpOutBcastOctets/s",
        "IpInNoEctPkts/s",
        "Ip6InPkts/s",
        "Ip6InHdrErrs",
        "Ip6InNoRoutesPkts/s",
        "Ip6InAddrErrs",
        "Ip6InDiscardsPkts/s",
        "Ip6InDeliversPkts/s",
        "Ip6ForwDatagrams/s",
        "Ip6OutReqs/s",
        "Ip6OutNoRoutesPkts/s",
        "Ip6InMcastPkts/s",
        "Ip6OutMcastPkts/s",
        "Ip6InOctets/s",
        "Ip6OutOctets/s",
        "Ip6InMcastOctets/s",
        "Ip6OutMcastOctets/s",
        "Ip6InBcastOctets/s",
        "Ip6OutBcastOctets/s",
        "IcmpInMsg/s",
        "IcmpInErrs",
        "IcmpInDestUnreachs",
        "IcmpOutMsg/s",
        "IcmpOutErrs",
        "IcmpOutDestUnreachs",
        "Icmp6InMsg/s",
        "Icmp6InErrs",
        "Icmp6InDestUnreachs",
        "Icmp6OutMsg/s",
        "Icmp6OutErrs",
        "Icmp6OutDestUnreachs",
    ];
    assert_eq!(titles, expected_titles);
}

#[test]
// Test correctness of transport decoration
// This test will also test JSON correctness.
fn test_dump_transport_content() {
    let mut collector = Collector::new(Default::default());
    let logger = get_logger();
    collector.update_model(&logger).expect("Fail to get model");

    let mut opts: GeneralOpt = Default::default();
    let fields = command::expand_fields(command::DEFAULT_TRANSPORT_FIELDS, true);
    opts.output_format = Some(OutputFormat::Json);
    let transport_dumper = transport::Transport::new(&opts, fields.clone());

    // update model again to populate net data
    let model = collector.update_model(&logger).expect("Fail to get model");
    let mut transport_content: Vec<u8> = Vec::new();
    let mut round = 0;
    let ctx = CommonFieldContext { timestamp: 0 };
    transport_dumper
        .dump_model(&ctx, &model, &mut transport_content, &mut round, false)
        .expect("Failed to dump transport model");

    // verify json correctness
    assert!(!transport_content.is_empty());
    let jval: Value =
        serde_json::from_slice(&transport_content).expect("Fail parse json of network dump");

    for dump_field in fields.iter() {
        match dump_field {
            DumpField::Common(_) => continue,
            DumpField::FieldId(field_id) => {
                let rc = model::NetworkModel::get_render_config_for_dump(&field_id);
                assert_eq!(
                    rc.render(model.network.query(&field_id), false),
                    jval[rc.render_title(false)]
                        .as_str()
                        .unwrap_or_else(|| panic!(
                            "Key not found in Json: {}",
                            rc.render_title(false),
                        ))
                        .to_owned(),
                    "Model value and json value do not match for field: {}",
                    field_id.to_string(),
                );
            }
        }
    }
}

#[test]
fn test_dump_transport_titles() {
    let titles = expand_fields(command::DEFAULT_TRANSPORT_FIELDS, true)
        .iter()
        .filter_map(|dump_field| match dump_field {
            DumpField::Common(_) => None,
            DumpField::FieldId(field_id) => {
                let rc = model::NetworkModel::get_render_config_for_dump(&field_id);
                Some(rc.render_title(false))
            }
        })
        .collect::<Vec<_>>();
    let expected_titles = vec![
        "TcpActiveOpens/s",
        "TcpPassiveOpens/s",
        "TcpAttemptFails/s",
        "TcpEstabResets/s",
        "CurEstabConn",
        "TcpInSegs/s",
        "TcpOutSegs/s",
        "TcpRetransSegs/s",
        "TcpRetransSegs",
        "TcpInErrors",
        "TcpOutRsts/s",
        "TcpInCsumErrors",
        "UdpInPkts/s",
        "UdpNoPorts",
        "UdpInErrs",
        "UdpOutPkts/s",
        "UdpRcvbufErrs",
        "UdpSndBufErrs",
        "UdpIgnoredMulti",
        "Udp6InPkts/s",
        "Udp6NoPorts",
        "Udp6InErrs",
        "Udp6OutPkts/s",
        "Udp6RcvbufErrs",
        "Udp6SndBufErrs",
        "Udp6InCsumErrs",
        "Udp6IgnoredMulti",
    ];
    assert_eq!(titles, expected_titles);
}

#[test]
// Test correctness of disk decoration
// This test will also test JSON correctness.
fn test_dump_disk_content() {
    let mut collector = Collector::new(Default::default());
    let logger = get_logger();
    collector.update_model(&logger).expect("Fail to get model");

    let mut opts: GeneralOpt = Default::default();
    let fields = command::expand_fields(command::DEFAULT_DISK_FIELDS, true);
    opts.output_format = Some(OutputFormat::Json);
    let disk_dumper = disk::Disk::new(&opts, None, fields.clone());

    // update model again to populate disk data
    let model = collector.update_model(&logger).expect("Fail to get model");
    let mut disk_content: Vec<u8> = Vec::new();
    let mut round = 0;
    let ctx = CommonFieldContext { timestamp: 0 };
    disk_dumper
        .dump_model(&ctx, &model, &mut disk_content, &mut round, false)
        .expect("Failed to dump disk model");

    // verify json correctness
    assert!(!disk_content.is_empty());
    let jval: Value = serde_json::from_slice(&disk_content).expect("Fail parse json of disk dump");

    // verify content correctness, test first 5 should be enough
    let mut count = 5;
    for value in jval.as_array().unwrap() {
        let name = value["Name"].as_str().unwrap();
        let sdm = model
            .system
            .disks
            .get(name)
            .expect("Json pid and sdm pid not match");

        for dump_field in fields.iter() {
            match dump_field {
                DumpField::Common(_) => continue,
                DumpField::FieldId(field_id) => {
                    let rc = model::SingleDiskModel::get_render_config_for_dump(&field_id);
                    assert_eq!(
                        rc.render(sdm.query(&field_id), false),
                        value[rc.render_title(false)]
                            .as_str()
                            .unwrap_or_else(|| panic!(
                                "Key not found in Json: {}",
                                rc.render_title(false),
                            ))
                            .to_owned(),
                        "Model value and json value do not match for field: {}",
                        field_id.to_string(),
                    );
                }
            }
        }
        count -= 1;
        if count == 0 {
            break;
        }
    }
}

#[test]
fn test_dump_disk_titles() {
    let titles = expand_fields(command::DEFAULT_DISK_FIELDS, true)
        .iter()
        .filter_map(|dump_field| match dump_field {
            DumpField::Common(_) => None,
            DumpField::FieldId(field_id) => {
                let rc = model::SingleDiskModel::get_render_config_for_dump(&field_id);
                Some(rc.render_title(false))
            }
        })
        .collect::<Vec<_>>();
    let expected_titles = vec![
        "Name",
        "Disk",
        "Major",
        "Minor",
        "Read",
        "Read Completed",
        "Read Merged",
        "Read Sectors",
        "Time Spend Read",
        "Write",
        "Write Completed",
        "Write Merged",
        "Write Sectors",
        "Time Spend Write",
        "Discard",
        "Discard Completed",
        "Discard Merged",
        "Discard Sectors",
        "Time Spend Discard",
        "Disk Usage",
        "Partition Size",
        "Filesystem Type",
    ];
    assert_eq!(titles, expected_titles);
}

#[test]
fn test_parse_pattern() {
    let tempdir = TempDir::new("below_dump_pattern").expect("Failed to create temp dir");
    let path = tempdir.path().join("belowrc");

    let mut file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .truncate(true)
        .create(true)
        .open(&path)
        .expect("Fail to open belowrc in tempdir");
    let belowrc_str = r#"
[dump.system]
demacia = ["datetime", "os_release"]

[dump.process]
proc = ["datetime", "mem.anon"]
"#;
    file.write_all(belowrc_str.as_bytes())
        .expect("Faild to write temp belowrc file during testing ignore");
    file.flush().expect("Failed to flush during testing ignore");

    let sys_res = parse_pattern::<command::SystemOptionField>(
        path.to_string_lossy().to_string(),
        "demacia".into(),
        "system",
    )
    .expect("Failed to parse system pattern");

    assert_eq!(
        sys_res[0],
        command::SystemOptionField::Unit(SystemField::Common(CommonField::Datetime))
    );
    assert_eq!(
        sys_res[1],
        command::SystemOptionField::Unit(SystemField::FieldId(
            model::SystemModelFieldId::OsRelease
        ))
    );

    let proc_res = parse_pattern::<command::ProcessOptionField>(
        path.to_string_lossy().to_string(),
        "proc".into(),
        "process",
    )
    .expect("Failed to parse process pattern");

    assert_eq!(
        proc_res[0],
        command::ProcessOptionField::Unit(ProcessField::Common(CommonField::Datetime))
    );
    assert_eq!(
        proc_res[1],
        command::ProcessOptionField::Unit(ProcessField::FieldId(
            model::SingleProcessModelFieldId::Mem(model::ProcessMemoryModelFieldId::Anon)
        ))
    );
}