procfs2 0.2.4

A modern, zero-copy, strongly-typed Rust library for reading Linux /proc and /sys
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
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
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
//! Integration tests for procfs2 against live /proc and /sys.
//!
//! These tests run against the actual /proc and /sys filesystems on the system.

#![cfg(target_os = "linux")]

#[cfg(test)]
mod tests {
    use procfs2::proc::{
        ConsoleFlags, DeviceKind, Process, buddyinfo, consoles, cpu_pressure, cpuinfo, crypto,
        devices, diskstats, filesystems, interrupts, io_pressure, iomem, ioports, irq_pressure,
        loadavg, locks, meminfo, memory_pressure, misc, modules, mounts, pagetypeinfo, partitions,
        softirqs, stat, swaps, uptime, version, vmstat, zoneinfo,
    };
    use procfs2::sys;

    /// `/proc/pagetypeinfo` is mode 0400 (root-only) on some systems.
    /// Returns `None` when unreadable for that reason; panics on other
    /// failures so tests still catch genuine parse bugs.
    fn pagetypeinfo_or_skip() -> Option<procfs2::proc::PageTypeInfo> {
        match pagetypeinfo() {
            Ok(info) => Some(info),
            Err(procfs2::Error::Io { error: e, .. })
                if e.kind() == std::io::ErrorKind::PermissionDenied =>
            {
                None
            }
            Err(e) => panic!("Failed to read /proc/pagetypeinfo: {e}"),
        }
    }

    /// True if `/proc/sys/kernel/kptr_restrict` is 2, which hides kernel
    /// pointers from readers without `CAP_SYSLOG`. At 1 only other users'
    /// processes are hidden, which does not apply to a child we spawned.
    fn kptr_hides_us() -> bool {
        std::fs::read_to_string("/proc/sys/kernel/kptr_restrict")
            .expect("kptr_restrict should be readable")
            .trim()
            .parse::<u32>()
            .expect("invalid kptr_restrict")
            >= 2
    }

    /// Reads the wchan of a freshly spawned child, waiting for it to stop
    /// being runnable first.
    ///
    /// A child needs a moment to finish `exec` and reach the `nanosleep`
    /// it was started with, and a runnable task reports 0. Returns `None`
    /// if the value never settles, or if `kptr_restrict` hides it.
    fn blocked_child_wchan(child: &Process) -> Option<procfs2::proc::process::Wchan> {
        use procfs2::proc::process::Wchan;

        if kptr_hides_us() {
            return None;
        }
        for _ in 0..100 {
            let wchan = child.wchan().expect("Failed to read child wchan");
            if wchan != Wchan::RunningOrUnavailable {
                return Some(wchan);
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        None
    }

    #[test]
    fn test_live_meminfo() {
        let info = meminfo().expect("Failed to read /proc/meminfo");
        assert!(info.total.0 > 0, "Total memory should be > 0");
    }

    #[test]
    fn test_live_uptime() {
        let up = uptime().expect("Failed to read /proc/uptime");
        assert!(up.total.as_secs() > 0, "Uptime should be > 0");
    }

    #[test]
    fn test_live_loadavg() {
        let load = loadavg().expect("Failed to read /proc/loadavg");
        assert!(load.one >= 0.0);
    }

    #[test]
    fn test_live_stat() {
        let st = stat().expect("Failed to read /proc/stat");
        assert!(!st.per_cpu.is_empty());
    }

    #[test]
    fn test_live_version() {
        let ver = version().expect("Failed to read /proc/version");
        assert!(ver.major > 0);
    }

    #[test]
    fn test_live_cpuinfo() {
        let cpus = cpuinfo().expect("Failed to read /proc/cpuinfo");
        assert!(!cpus.is_empty());
    }

    #[test]
    fn test_live_cpuinfo_fields() {
        let cpus = cpuinfo().expect("Failed to read /proc/cpuinfo");

        // Every core should report a positive clock speed and family.
        for cpu in &cpus {
            assert!(cpu.cpu_mhz > 0.0, "cpu MHz should be a positive value");
            assert!(cpu.cpu_family > 0, "cpu family should be a positive value");
            assert!(!cpu.model_name.is_empty(), "model name should not be empty");
        }
    }

    #[test]
    fn test_live_cpuinfo_dedup() {
        let cpus = cpuinfo().expect("Failed to read /proc/cpuinfo");

        // No CPU should share the same processor number.
        let mut processors: Vec<u32> = cpus.iter().map(|c| c.processor).collect();
        processors.sort_unstable();
        processors.dedup();
        assert_eq!(
            processors.len(),
            cpus.len(),
            "processor numbers should be unique"
        );
    }

    #[test]
    fn test_live_current_process() {
        let process = Process::current().expect("Failed to get current process");
        assert!(process.pid > 0, "PID should be > 0");
    }

    #[test]
    fn test_live_process_status() {
        let process = Process::current().expect("Failed to get current process");
        let status = process.status().expect("Failed to read process status");
        assert!(!status.name.is_empty());
    }

    #[test]
    fn test_live_process_maps() {
        let process = Process::current().expect("Failed to get current process");
        let maps = process.maps().expect("Failed to read process maps");
        assert!(!maps.is_empty());
    }

    #[test]
    fn test_process_iteration() {
        let mut count = 0;
        for result in Process::all() {
            if result.is_ok() {
                count += 1;
            }
        }
        assert!(count >= 1);
    }

    #[test]
    fn test_process_new() {
        let me = Process::current().expect("Failed to get current process");

        // Valid pid resolves
        assert!(Process::new(me.pid).is_ok());

        // pid 0 never exists in /proc
        match Process::new(0) {
            Err(procfs2::Error::ProcessGone(0)) => {}
            other => panic!("expected ProcessGone for pid 0, got {:?}", other),
        }
    }

    #[test]
    fn test_live_process_cmdline() {
        let me = Process::current().expect("Failed to get current process");
        let cmdline = me.cmdline().expect("Failed to read process cmdline");
        assert!(!cmdline.is_empty(), "cmdline should not be empty");
    }

    #[test]
    fn test_live_process_environ() {
        let me = Process::current().expect("Failed to get current process");
        let environ = me.environ().expect("Failed to read process environ");
        assert!(!environ.is_empty(), "environ should not be empty");
    }

    #[test]
    fn test_live_process_exe() {
        let me = Process::current().expect("Failed to get current process");
        let exe = me.exe().expect("Failed to read process exe");
        assert!(exe.is_absolute(), "exe path should be absolute");
        assert!(exe.exists(), "exe path should exist");
    }

    #[test]
    fn test_live_process_cwd() {
        let me = Process::current().expect("Failed to get current process");
        let cwd = me.cwd().expect("Failed to read process cwd");
        assert!(cwd.is_absolute(), "cwd should be absolute");
        assert!(cwd.is_dir(), "cwd should be a directory");
    }

    #[test]
    fn test_live_process_smaps() {
        let me = Process::current().expect("Failed to get current process");
        let smaps = me.smaps().expect("Failed to read process smaps");
        assert!(!smaps.is_empty(), "smaps should not be empty");
    }

    #[test]
    fn test_live_process_smaps_rollup() {
        let me = Process::current().expect("Failed to get current process");
        let rollup = me.smaps_rollup().expect("Failed to read smaps_rollup");

        // A running process must occupy at least some memory
        assert!(rollup.rss_kb > 0, "rss should be > 0");
    }

    #[test]
    fn test_live_process_fds() {
        let me = Process::current().expect("Failed to get current process");

        // Concurrent test threads open/close fds while we enumerate,
        // so read_link may transiently fail on a closing fd. Retry.
        let mut fds = None;
        for _ in 0..5 {
            if let Ok(v) = me.fds() {
                fds = Some(v);
                break;
            }
        }
        let fds = fds.expect("Failed to read process fds");

        // stdin/stdout/stderr are always open
        assert!(!fds.is_empty(), "should have at least one open fd");
    }

    #[test]
    fn test_live_process_limits() {
        let me = Process::current().expect("Failed to get current process");
        let limits = me.limits().expect("Failed to read process limits");

        // Open files limit should be a sensible value
        assert!(
            limits.max_open_files.soft.is_some(),
            "open files soft limit should be set"
        );
    }

    #[test]
    fn test_live_process_cgroup() {
        let me = Process::current().expect("Failed to get current process");
        let cgroups = me.cgroup().expect("Failed to read process cgroup");
        assert!(
            !cgroups.is_empty(),
            "process should be in at least one cgroup"
        );
    }

    #[test]
    fn test_live_process_namespaces() {
        let me = Process::current().expect("Failed to get current process");
        let ns = me.namespaces().expect("Failed to read process namespaces");

        // These namespaces exist on all modern kernels
        assert!(ns.mnt.is_some(), "mnt namespace should be present");
        assert!(ns.pid.is_some(), "pid namespace should be present");
        assert!(ns.net.is_some(), "net namespace should be present");
    }

    #[test]
    fn test_live_process_threads() {
        let me = Process::current().expect("Failed to get current process");
        let count = me.threads().filter(|r| r.is_ok()).count();
        assert!(count >= 1, "process should have at least one thread");
    }

    #[test]
    fn test_live_process_syscall() {
        let me = Process::current().expect("Failed to get current process");
        let syscall = me.syscall().expect("Failed to read process syscall");

        // The syscall state must be one of the three valid states
        match syscall.state {
            procfs2::proc::process::SyscallState::Running => {
                // Not blocked in a syscall
            }
            procfs2::proc::process::SyscallState::BlockedNotInSyscall => {
                // Blocked but not in a syscall - nr should be -1
                assert_eq!(syscall.nr, Some(-1));
            }
            procfs2::proc::process::SyscallState::InSyscall => {
                // Currently in a syscall - nr should be >= 0
                assert!(syscall.nr.is_some_and(|n| n >= 0));
                // Args should be present
                for arg in syscall.args {
                    assert!(arg.is_some(), "InSyscall should have all 6 args");
                }
            }
        }
    }

    #[test]
    fn test_live_process_syscall_sp_ip() {
        let me = Process::current().expect("Failed to get current process");
        let syscall = me.syscall().expect("Failed to read process syscall");

        // Stack pointer and instruction pointer should be valid addresses
        // when the process is in a syscall or blocked (not when "running")
        if syscall.state != procfs2::proc::process::SyscallState::Running {
            assert!(
                syscall.sp > 0,
                "stack pointer should be non-zero when not running"
            );
            assert!(
                syscall.ip > 0,
                "instruction pointer should be non-zero when not running"
            );
        }
    }

    #[test]
    fn test_live_process_statm() {
        let me = Process::current().expect("Failed to get current process");
        let statm = me.statm().expect("Failed to read process statm");

        // Every running process occupies at least one resident page.
        assert!(
            statm.size >= statm.resident,
            "size should cover the resident set"
        );
        assert!(statm.resident > 0, "process should have resident pages");
        assert!(
            statm.text + statm.data <= statm.size,
            "text and data should fit within size"
        );
    }

    #[test]
    fn test_live_process_statm_obsolete_fields() {
        let me = Process::current().expect("Failed to get current process");
        let statm = me.statm().expect("Failed to read process statm");

        // lib and dt have been zero since Linux 2.6.
        assert_eq!(statm.lib, 0, "lib should be zero");
        assert_eq!(statm.dt, 0, "dt should be zero");
    }

    #[test]
    fn test_live_process_statm_matches_stat() {
        let me = Process::current().expect("Failed to get current process");
        let statm = me.statm().expect("Failed to read process statm");
        let stat = me.stat().expect("Failed to read process stat");

        // statm.resident and stat.rss are the same value in pages.
        // The two reads race with the process's own page activity, so
        // allow a little slack between them.
        let rss = stat.rss.max(0);
        let diff = (statm.resident as i64 - rss).unsigned_abs();
        assert!(
            diff < 1000,
            "statm resident ({}) should track stat rss ({rss})",
            statm.resident
        );
    }

    #[test]
    fn test_live_process_auxv() {
        let me = Process::current().expect("Failed to get current process");
        let auxv = me.auxv().expect("Failed to read process auxv");

        // Every process has a populated auxiliary vector.
        assert!(!auxv.entries.is_empty(), "auxv should not be empty");
        assert!(
            auxv.get(procfs2::proc::process::auxv_type::AT_PAGESZ)
                .is_some(),
            "auxv should contain AT_PAGESZ"
        );
    }

    #[test]
    fn test_live_process_auxv_page_size() {
        let me = Process::current().expect("Failed to get current process");
        let auxv = me.auxv().expect("Failed to read process auxv");

        // The page size is a power of two and matches the raw entry.
        let raw = auxv
            .get(procfs2::proc::process::auxv_type::AT_PAGESZ)
            .expect("AT_PAGESZ should be present");
        assert!(raw.is_power_of_two(), "page size should be a power of two");
        assert_eq!(auxv.page_size(), raw, "page_size should match AT_PAGESZ");
    }

    #[test]
    fn test_live_process_auxv_known_entries() {
        let me = Process::current().expect("Failed to get current process");
        let auxv = me.auxv().expect("Failed to read process auxv");

        use procfs2::proc::process::auxv_type;

        // The kernel reports a positive clock tick rate and the
        // executable always has a non-zero entry point.
        assert!(auxv.get(auxv_type::AT_CLKTCK).is_some_and(|v| v > 0));
        assert!(auxv.get(auxv_type::AT_ENTRY).is_some_and(|v| v != 0));

        // An unknown tag has no entry.
        assert_eq!(auxv.get(u64::MAX), None);
    }

    #[test]
    fn test_live_process_pagemap_count() {
        let me = Process::current().expect("Failed to get current process");
        let maps = me.maps().expect("Failed to read process maps");
        let first = maps.first().expect("process should have at least one map");

        let entries = me
            .pagemap(first.address.start, first.address.end)
            .expect("Failed to read process pagemap");

        // The range yields exactly one entry per page.
        let page_size = me.auxv().expect("Failed to read auxv").page_size();
        let expected = first.address.end.div_ceil(page_size) - first.address.start / page_size;
        assert_eq!(entries.len() as u64, expected, "one entry per page");
    }

    #[test]
    fn test_live_process_pagemap_resident() {
        let me = Process::current().expect("Failed to get current process");
        let maps = me.maps().expect("Failed to read process maps");

        // A running process has resident pages; scanning the mapped
        // regions should turn up at least one present entry.
        let mut resident = 0;
        for map in &maps {
            let entries = me
                .pagemap(map.address.start, map.address.end)
                .expect("Failed to read process pagemap");
            resident += entries.iter().filter(|e| e.is_mapped()).count();
        }
        assert!(resident > 0, "process should have resident pages");
    }

    #[test]
    fn test_live_process_pagemap_empty_range() {
        let me = Process::current().expect("Failed to get current process");

        // A zero-length range yields no entries.
        let entries = me
            .pagemap(0x1000, 0x1000)
            .expect("Failed to read process pagemap");
        assert!(entries.is_empty(), "empty range should yield no entries");
    }

    #[test]
    fn test_live_process_loginuid() {
        let me = Process::current().expect("Failed to get current process");

        // The kernel allows the login uid to be set only once per
        // process, so two reads must agree. Kernels without auditing
        // (`CONFIG_AUDITSYSCALL`) have no loginuid file at all.
        let Some(a) = me.loginuid().expect("Failed to read process loginuid") else {
            return;
        };
        let b = me
            .loginuid()
            .expect("Failed to read process loginuid")
            .expect("loginuid vanished between reads");
        assert_eq!(a, b, "loginuid should be immutable for a process");
    }

    #[test]
    fn test_live_process_loginuid_matches_file() {
        let me = Process::current().expect("Failed to get current process");

        // Compare against the raw file, which the kernel writes as a
        // single decimal number plus newline.
        let Some(parsed) = me.loginuid().expect("Failed to read process loginuid") else {
            return;
        };
        let raw = std::fs::read_to_string("/proc/self/loginuid")
            .expect("loginuid file should exist on this kernel");
        let expected: u32 = raw.trim().parse().expect("invalid loginuid in file");
        assert_eq!(parsed, expected, "parse should match raw file contents");
    }

    #[test]
    fn test_live_process_loginuid_inherited() {
        let me = Process::current().expect("Failed to get current process");
        let Some(parent) = me.loginuid().expect("Failed to read process loginuid") else {
            return;
        };

        // /proc/PID/loginuid is mode 0644, readable for any process.
        let mut child = std::process::Command::new("/bin/sleep")
            .arg("1")
            .spawn()
            .expect("Failed to spawn child process");
        let child_proc = Process::new(child.id()).expect("Failed to get child process");
        let child_loginuid = child_proc
            .loginuid()
            .expect("Failed to read child loginuid");
        child.wait().expect("Failed to wait on child");
        let Some(child_loginuid) = child_loginuid else {
            return;
        };

        // The login uid survives fork, so the child inherits ours.
        assert_eq!(
            child_loginuid, parent,
            "child should inherit parent's loginuid"
        );
    }

    #[test]
    fn test_live_process_sessionid() {
        let me = Process::current().expect("Failed to get current process");

        // The audit session id is fixed for a process, so two reads
        // must agree. Kernels without auditing (`CONFIG_AUDITSYSCALL`)
        // have no sessionid file at all.
        let Some(a) = me.sessionid().expect("Failed to read process sessionid") else {
            return;
        };
        let b = me
            .sessionid()
            .expect("Failed to read process sessionid")
            .expect("sessionid vanished between reads");
        assert_eq!(a, b, "sessionid should be immutable for a process");
    }

    #[test]
    fn test_live_process_sessionid_matches_file() {
        let me = Process::current().expect("Failed to get current process");

        // Compare against the raw file, which the kernel writes as a
        // single decimal number plus newline.
        let Some(parsed) = me.sessionid().expect("Failed to read process sessionid") else {
            return;
        };
        let raw = std::fs::read_to_string("/proc/self/sessionid")
            .expect("sessionid file should exist on this kernel");
        let expected: u32 = raw.trim().parse().expect("invalid sessionid in file");
        assert_eq!(parsed, expected, "parse should match raw file contents");
    }

    #[test]
    fn test_live_process_sessionid_inherited() {
        let me = Process::current().expect("Failed to get current process");
        let Some(parent) = me.sessionid().expect("Failed to read process sessionid") else {
            return;
        };

        // /proc/PID/sessionid is mode 0444, readable for any process.
        let mut child = std::process::Command::new("/bin/sleep")
            .arg("1")
            .spawn()
            .expect("Failed to spawn child process");
        let child_proc = Process::new(child.id()).expect("Failed to get child process");
        let child_sessionid = child_proc
            .sessionid()
            .expect("Failed to read child sessionid");
        child.wait().expect("Failed to wait on child");
        let Some(child_sessionid) = child_sessionid else {
            return;
        };

        // The audit session id survives fork, so the child inherits ours.
        assert_eq!(
            child_sessionid, parent,
            "child should inherit parent's sessionid"
        );
    }

    #[test]
    fn test_live_process_coredump_filter() {
        let me = Process::current().expect("Failed to get current process");

        // The filter lives in the address space, and only changed through
        // an explicit write, so two reads must agree. Kernels built
        // without core dump support (`CONFIG_ELF_CORE`) have no
        // coredump_filter file at all.
        let Some(filter) = me
            .coredump_filter()
            .expect("Failed to read process coredump_filter")
        else {
            return;
        };
        let again = me
            .coredump_filter()
            .expect("Failed to read process coredump_filter")
            .expect("coredump_filter vanished between reads");
        assert_eq!(
            filter, again,
            "coredump_filter should be stable for a process"
        );
    }

    #[test]
    fn test_live_process_coredump_filter_matches_file() {
        let me = Process::current().expect("Failed to get current process");

        // Compare against the raw file, which the kernel writes as eight
        // zero-padded hex digits plus newline, e.g. 00000033.
        let Some(parsed) = me
            .coredump_filter()
            .expect("Failed to read process coredump_filter")
        else {
            return;
        };
        let raw = std::fs::read_to_string("/proc/self/coredump_filter")
            .expect("coredump_filter file should exist on this kernel");
        let expected =
            u32::from_str_radix(raw.trim(), 16).expect("invalid coredump_filter in file");
        assert_eq!(
            parsed.bits(),
            expected,
            "parse should match raw file contents"
        );
    }

    #[test]
    fn test_live_process_coredump_filter_inherited() {
        let me = Process::current().expect("Failed to get current process");
        let Some(parent) = me
            .coredump_filter()
            .expect("Failed to read process coredump_filter")
        else {
            return;
        };

        // /proc/PID/coredump_filter is mode 0644, readable for any
        // process, and its value is inherited via fork.
        let mut child = std::process::Command::new("/bin/sleep")
            .arg("1")
            .spawn()
            .expect("Failed to spawn child process");
        let child_proc = Process::new(child.id()).expect("Failed to get child process");
        let child_filter = child_proc
            .coredump_filter()
            .expect("Failed to read child coredump_filter");
        child.wait().expect("Failed to wait on child");
        let Some(child_filter) = child_filter else {
            return;
        };

        // The filter is per-address-space, and the child shares the
        // parent's address space at fork.
        assert_eq!(
            child_filter, parent,
            "child should inherit parent's coredump_filter"
        );
    }

    #[test]
    fn test_live_process_oom_score() {
        let me = Process::current().expect("Failed to get current process");

        // The OOM score is recomputed on each read, and only drifts when
        // memory usage or oom_score_adj changes, so back-to-back reads
        // are effectively stable.
        let a = me.oom_score().expect("Failed to read process oom_score");
        let b = me.oom_score().expect("Failed to read process oom_score");
        assert_eq!(a, b, "oom_score should be stable between reads");
    }

    #[test]
    fn test_live_process_oom_score_matches_file() {
        let me = Process::current().expect("Failed to get current process");

        // Compare against the raw file, a single decimal number plus
        // newline.
        let raw = std::fs::read_to_string("/proc/self/oom_score")
            .expect("oom_score file should exist on this kernel");
        let expected: u16 = raw.trim().parse().expect("invalid oom_score in file");
        let parsed = me.oom_score().expect("Failed to read process oom_score");
        assert_eq!(parsed, expected, "parse should match raw file contents");
    }

    #[test]
    fn test_live_process_oom_score_range() {
        let me = Process::current().expect("Failed to get current process");

        // The kernel computes the score as a scaled badness value. For
        // real processes the result is well under a few thousand, and
        // roots out parse or cast mistakes immediately if it ever isn't.
        let score = me.oom_score().expect("Failed to read process oom_score");
        assert!(
            score <= 2000,
            "oom_score {score} outside the documented range"
        );
    }

    #[test]
    fn test_live_process_oom_score_adj() {
        let me = Process::current().expect("Failed to get current process");

        // oom_score_adj only changes via an explicit write, so two
        // reads must agree. The value is signed: system processes can
        // run with -1000.
        let a = me
            .oom_score_adj()
            .expect("Failed to read process oom_score_adj");
        let b = me
            .oom_score_adj()
            .expect("Failed to read process oom_score_adj");
        assert_eq!(a, b, "oom_score_adj should be stable between reads");
    }

    #[test]
    fn test_live_process_oom_score_adj_matches_file() {
        let me = Process::current().expect("Failed to get current process");

        // Compare against the raw file, a single decimal number (which
        // may be negative) plus newline.
        let raw = std::fs::read_to_string("/proc/self/oom_score_adj")
            .expect("oom_score_adj file should exist on this kernel");
        let expected: i16 = raw.trim().parse().expect("invalid oom_score_adj in file");
        let parsed = me
            .oom_score_adj()
            .expect("Failed to read process oom_score_adj");
        assert_eq!(parsed, expected, "parse should match raw file contents");
    }

    #[test]
    fn test_live_process_oom_score_adj_range() {
        let me = Process::current().expect("Failed to get current process");

        // The kernel clamps the value to [-1000, 1000]. A value outside
        // that bounds a parse or sign mistake.
        let adj = me
            .oom_score_adj()
            .expect("Failed to read process oom_score_adj");
        assert!(
            (-1000..=1000).contains(&adj),
            "oom_score_adj {adj} outside the documented range"
        );
    }

    #[test]
    fn test_live_process_wchan() {
        use procfs2::proc::process::Wchan;

        let me = Process::current().expect("Failed to get current process");
        let wchan = me.wchan().expect("Failed to read process wchan");

        // The value is a snapshot of where the task was when the file
        // was read, so all that can be checked is that it came back in
        // one of the three shapes the kernel writes.
        match wchan {
            Wchan::RunningOrUnavailable => {}
            Wchan::Symbol(name) => assert!(
                !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
                "symbol {name:?} should be a bare kernel identifier"
            ),
            Wchan::Address(addr) => assert_ne!(addr, 0, "address should not be zero"),
        }
    }

    #[test]
    fn test_live_process_wchan_blocked() {
        // A process asleep in nanosleep stays put for the whole test,
        // so its wchan is stable and not the runnable case.
        let mut child = std::process::Command::new("/bin/sleep")
            .arg("2")
            .spawn()
            .expect("Failed to spawn child process");
        let child_proc = Process::new(child.id()).expect("Failed to get child process");

        let blocked = blocked_child_wchan(&child_proc);
        let again = child_proc.wchan().expect("Failed to re-read child wchan");
        child.wait().expect("Failed to wait on child");

        assert!(
            blocked.is_some() || kptr_hides_us(),
            "a sleeping process should report where it is blocked"
        );
        if let Some(blocked) = blocked {
            assert_eq!(blocked, again, "wchan should be stable while blocked");
        }
    }

    #[test]
    fn test_live_process_wchan_matches_file() {
        use procfs2::proc::process::Wchan;

        // Compare against the raw file, which the kernel writes as one
        // token: `0`, a hex address, or a symbol name, plus newline.
        let mut child = std::process::Command::new("/bin/sleep")
            .arg("2")
            .spawn()
            .expect("Failed to spawn child process");
        let child_proc = Process::new(child.id()).expect("Failed to get child process");

        let parsed = blocked_child_wchan(&child_proc).unwrap_or(Wchan::RunningOrUnavailable);
        let raw = std::fs::read_to_string(format!("/proc/{}/wchan", child.id()))
            .expect("wchan file should exist on this kernel");
        child.wait().expect("Failed to wait on child");

        let field = raw.trim();
        if field == "0" {
            assert_eq!(parsed, Wchan::RunningOrUnavailable);
        } else if let Ok(addr) = u64::from_str_radix(field, 16) {
            assert_eq!(parsed, Wchan::Address(addr), "parse should match raw file");
        } else {
            assert_eq!(
                parsed,
                Wchan::Symbol(field.to_string()),
                "parse should match raw file contents"
            );
        }
    }

    #[test]
    fn test_live_devices() {
        let devices = devices().expect("Failed to read /proc/devices");

        // Every kernel registers at least one device
        assert!(!devices.is_empty(), "Should have at least one device");
        assert!(
            devices.iter().any(|d| d.major > 0),
            "Device major numbers should be > 0"
        );
    }

    #[test]
    fn test_live_devices_both_kinds() {
        let devices = devices().expect("Failed to read /proc/devices");

        // Both character and block devices should be registered
        assert!(
            devices.iter().any(|d| d.kind == DeviceKind::Character),
            "Should have at least one character device"
        );
        assert!(
            devices.iter().any(|d| d.kind == DeviceKind::Block),
            "Should have at least one block device"
        );
    }

    #[test]
    fn test_live_devices_names() {
        let devices = devices().expect("Failed to read /proc/devices");

        // Names are single whitespace-free tokens
        for d in &devices {
            assert!(!d.name.is_empty(), "Device name should not be empty");
            assert!(
                !d.name.contains(' '),
                "Device name should not contain spaces"
            );
        }
    }

    #[test]
    fn test_live_filesystems() {
        let fs_list = filesystems().expect("Failed to read /proc/filesystems");

        // Every kernel supports proc, tmpfs and at least one disk fs
        assert!(!fs_list.is_empty(), "Should have at least one filesystem");
        assert!(
            fs_list.iter().any(|f| f.name.as_ref() == "proc"),
            "proc filesystem should be listed"
        );
        assert!(
            fs_list.iter().any(|f| f.name.as_ref() == "tmpfs"),
            "tmpfs filesystem should be listed"
        );
    }

    #[test]
    fn test_live_filesystems_both_kinds() {
        let fs_list = filesystems().expect("Failed to read /proc/filesystems");

        // Pseudo-filesystems (nodev) and device-backed filesystems exist
        assert!(
            fs_list.iter().any(|f| !f.dev),
            "Should have at least one nodev filesystem"
        );
        assert!(
            fs_list.iter().any(|f| f.dev),
            "Should have at least one device-backed filesystem"
        );
    }

    #[test]
    fn test_live_filesystems_names() {
        let fs_list = filesystems().expect("Failed to read /proc/filesystems");

        // Names are non-empty and free of tabs
        for f in &fs_list {
            assert!(!f.name.is_empty(), "Filesystem name should not be empty");
            assert!(
                !f.name.contains('\t'),
                "Filesystem name should not contain tabs"
            );
        }
    }

    #[test]
    fn test_live_mounts() {
        let mounts = mounts().expect("Failed to read /proc/mounts");

        // The root filesystem is always mounted.
        assert!(!mounts.is_empty(), "Should have at least one mount");
    }

    #[test]
    fn test_live_mounts_root() {
        let mounts = mounts().expect("Failed to read /proc/mounts");

        // The root mount always exists and resolves to "/".
        let root = mounts
            .iter()
            .find(|m| m.file.as_ref() == "/")
            .expect("root mount should exist");
        assert!(!root.vfstype.is_empty(), "Root vfstype should not be empty");
        let _ = root.spec;
        let _ = root.mntops;
        let _ = root.freq;
        let _ = root.passno;
    }

    #[test]
    fn test_live_mounts_fields() {
        let mounts = mounts().expect("Failed to read /proc/mounts");

        // Every mount has a filesystem type and a mount point.
        for m in &mounts {
            assert!(!m.vfstype.is_empty(), "vfstype should not be empty");
            assert!(!m.file.is_empty(), "Mount point should not be empty");
            let _ = m.spec;
            let _ = m.mntops;
            let _ = m.freq;
            let _ = m.passno;
        }
    }

    #[test]
    fn test_live_swaps() {
        let swaps = swaps().expect("Failed to read /proc/swaps");

        // Swap areas may be absent (e.g. VMs), so don't require any.
        for s in &swaps {
            assert!(!s.filename.is_empty(), "Filename should not be empty");
            assert!(s.size.0 > 0, "Swap size should be > 0");
            assert!(s.used.0 <= s.size.0, "Used should not exceed size");
        }
    }

    #[test]
    fn test_live_swaps_fields() {
        let swaps = swaps().expect("Failed to read /proc/swaps");

        // Every entry has a valid type and a numeric priority.
        for s in &swaps {
            match s.kind {
                procfs2::proc::SwapType::Partition | procfs2::proc::SwapType::File => {}
            }
            let _ = s.priority;
        }
    }

    #[test]
    fn test_live_partitions() {
        let partitions = partitions().expect("Failed to read /proc/partitions");

        // Every system has at least one block device / partition
        assert!(!partitions.is_empty(), "Should have at least one partition");
        for p in &partitions {
            assert!(!p.name.is_empty(), "Partition name should not be empty");
            assert!(p.blocks.0 > 0, "Partition blocks should be > 0");
        }
    }

    #[test]
    fn test_live_partitions_fields() {
        let partitions = partitions().expect("Failed to read /proc/partitions");

        // Every entry has a positive major number and a whitespace-free name
        for p in &partitions {
            assert!(p.major > 0, "Major number should be > 0");
            assert!(
                !p.name.contains(' '),
                "Partition name should not contain spaces"
            );
            let _ = p.minor;
        }
    }

    #[test]
    fn test_live_diskstats() {
        let stats = diskstats().expect("Failed to read /proc/diskstats");

        // Every block device and partition is listed alongside its whole disk
        assert!(!stats.is_empty(), "Should have at least one disk entry");
        for s in &stats {
            assert!(!s.name.is_empty(), "Device name should not be empty");
            assert!(
                !s.name.contains(' '),
                "Device name should not contain spaces"
            );
            assert!(s.major > 0, "Major number should be > 0");
            let _ = s.minor;
        }
    }

    #[test]
    fn test_live_diskstats_io() {
        let stats = diskstats().expect("Failed to read /proc/diskstats");

        // Every entry must have all counters present.
        for s in &stats {
            let _ = s.reads_completed;
            let _ = s.writes_completed;
            let _ = s.sectors_read;
            let _ = s.sectors_written;
        }

        // The whole-disk entry (e.g. sda, nvme0n1) must have done some I/O.
        assert!(
            stats
                .iter()
                .any(|s| s.reads_completed > 0 || s.writes_completed > 0),
            "Should have at least one device with I/O stats"
        );
    }

    #[test]
    fn test_live_diskstats_flush_fields() {
        let stats = diskstats().expect("Failed to read /proc/diskstats");

        // Modern kernels (5.5+) always emit the flush fields. Whole-disk
        // entries track flush requests, so they should have a value.
        for s in &stats {
            let _ = s.flush_completed;
            let _ = s.time_flushing;
            let _ = s.io_in_progress;
        }
    }

    #[test]
    fn test_live_vmstat() {
        let vmstat = vmstat().expect("Failed to read /proc/vmstat");

        // The file holds well over a hundred counters on modern kernels,
        // including the long-stable zone and event counters below.
        assert!(vmstat.len() > 50, "Should have many vmstat counters");
        for key in ["nr_free_pages", "nr_dirty", "pgpgin", "pgfault", "oom_kill"] {
            assert!(vmstat.contains_key(key), "vmstat should contain {key}");
        }
    }

    #[test]
    fn test_live_vmstat_values() {
        let vmstat = vmstat().expect("Failed to read /proc/vmstat");

        // Keys are single whitespace-free tokens and every value is a
        // non-negative counter.
        for (key, &value) in &vmstat {
            assert!(!key.is_empty(), "Key should not be empty");
            assert!(
                !key.contains(char::is_whitespace),
                "Key should not contain whitespace"
            );
            let _ = value;
        }

        // The system has been allocating/freeing pages since boot, so the
        // total free page count must be positive.
        assert!(
            vmstat.get("nr_free_pages").is_some_and(|&v| v > 0),
            "nr_free_pages should be > 0"
        );
    }

    #[test]
    fn test_live_zoneinfo() {
        let zones = zoneinfo().expect("Failed to read /proc/zoneinfo");

        // Every kernel has at least one memory zone; the Normal zone is
        // always populated on 64-bit systems.
        assert!(!zones.is_empty(), "Should have at least one zone");
        let normal = zones
            .iter()
            .find(|z| z.name.as_ref() == "Normal")
            .expect("Should have a Normal zone");
        assert!(normal.pages.present > 0, "Normal zone should be populated");
        assert!(
            !normal.protection.is_empty(),
            "Normal zone should have protection values"
        );
        assert!(
            normal.stats.contains_key("nr_free_pages"),
            "Normal zone should have nr_free_pages"
        );
    }

    #[test]
    fn test_live_zoneinfo_fields() {
        let zones = zoneinfo().expect("Failed to read /proc/zoneinfo");

        // Every zone has a non-empty name; populated zones (managed > 0)
        // must have their `free` page count match the per-zone counter.
        for z in &zones {
            assert!(!z.name.is_empty(), "Zone name should not be empty");
            if z.pages.managed > 0 {
                assert_eq!(
                    z.pages.free,
                    z.stats.get("nr_free_pages").copied().unwrap_or(0),
                    "free pages should match nr_free_pages for {}",
                    z.name
                );
            }
        }
    }

    #[test]
    fn test_live_zoneinfo_pagesets() {
        let zones = zoneinfo().expect("Failed to read /proc/zoneinfo");

        // Every populated zone has one pageset per online CPU, with
        // ascending CPU ids starting at 0.
        for z in zones.iter().filter(|z| z.pages.managed > 0) {
            assert!(!z.pagesets.is_empty(), "{} should have pagesets", z.name);
            for (i, pcp) in z.pagesets.iter().enumerate() {
                assert_eq!(pcp.cpu, i as u32, "{} pageset CPU ids", z.name);
            }
        }
    }

    #[test]
    fn test_live_buddyinfo() {
        let buddy = buddyinfo().expect("Failed to read /proc/buddyinfo");

        // Every kernel has at least one populated zone with buddy lists,
        // and the Normal zone is always present on 64-bit systems.
        assert!(!buddy.is_empty(), "Should have at least one zone");
        let normal = buddy
            .iter()
            .find(|b| b.zone.as_ref() == "Normal")
            .expect("Should have a Normal zone");
        assert!(
            !normal.free_lists.is_empty(),
            "Normal zone should have free lists"
        );
    }

    #[test]
    fn test_live_buddyinfo_fields() {
        let buddy = buddyinfo().expect("Failed to read /proc/buddyinfo");

        // Every entry has a non-empty whitespace-free zone name and at
        // least one buddy order count.
        for b in &buddy {
            assert!(!b.zone.is_empty(), "Zone name should not be empty");
            assert!(
                !b.zone.contains(char::is_whitespace),
                "Zone name should not contain whitespace"
            );
            assert!(
                !b.free_lists.is_empty(),
                "{} should have at least one free list",
                b.zone
            );
            let _ = b.node;
        }
    }

    #[test]
    fn test_live_buddyinfo_orders() {
        let buddy = buddyinfo().expect("Failed to read /proc/buddyinfo");

        // The kernel emits the same MAX_ORDER column count on every line,
        // so all zones share a consistent free-list length.
        let orders = buddy[0].free_lists.len();
        assert!(orders > 0, "Should have at least one order");
        for b in &buddy {
            assert_eq!(
                b.free_lists.len(),
                orders,
                "{} free-list length should match",
                b.zone
            );
        }
    }

    #[test]
    fn test_live_pagetypeinfo() {
        let Some(info) = pagetypeinfo_or_skip() else {
            return;
        };

        // The page-block header describes the allocator's block size,
        // and both tables are present on every kernel.
        assert!(info.page_block_order > 0, "Page block order should be > 0");
        assert!(info.pages_per_block > 0, "Pages per block should be > 0");
        assert!(!info.free.is_empty(), "Should have free-list rows");
        assert!(!info.blocks.is_empty(), "Should have block-count rows");

        // A page block covers 1 << page_block_order pages.
        assert_eq!(
            info.pages_per_block,
            1u64 << info.page_block_order,
            "pages_per_block should equal 1 << page_block_order"
        );
    }

    #[test]
    fn test_live_pagetypeinfo_free() {
        let Some(info) = pagetypeinfo_or_skip() else {
            return;
        };

        // Every free-list row names a zone and migrate type, carries a
        // consistent number of orders (MAX_ORDER), and the zone field
        // matches one of the block-count rows.
        let orders = info.free[0].orders.len();
        assert!(orders > 0, "Should have at least one order");
        for f in &info.free {
            assert!(!f.zone.is_empty(), "Zone name should not be empty");
            assert!(
                !f.migrate_type.is_empty(),
                "Migrate type should not be empty"
            );
            assert_eq!(
                f.orders.len(),
                orders,
                "{} {} free-list length should match",
                f.zone,
                f.migrate_type
            );
            assert!(
                info.blocks.iter().any(|b| b.zone == f.zone),
                "{} should appear in block counts",
                f.zone
            );
        }
    }

    #[test]
    fn test_live_pagetypeinfo_blocks() {
        let Some(info) = pagetypeinfo_or_skip() else {
            return;
        };

        // Every block-count row has a consistent number of columns,
        // matching the migrate-type header (varies by kernel config).
        let types = info.blocks[0].types.len();
        assert!(types > 0, "Should have at least one migrate type");
        for b in &info.blocks {
            assert!(!b.zone.is_empty(), "Zone name should not be empty");
            assert_eq!(
                b.types.len(),
                types,
                "{} block-count length should match",
                b.zone
            );
        }
    }

    #[test]
    fn test_live_softirqs() {
        let si = softirqs().expect("Failed to read /proc/softirqs");

        // The header lists the online CPUs, and every kernel registers
        // at least the classic softirq types below.
        assert!(!si.cpus.is_empty(), "Should have at least one CPU");
        assert!(!si.rows.is_empty(), "Should have at least one softirq");
        for key in ["HI", "TIMER", "NET_TX", "NET_RX", "BLOCK", "SCHED", "RCU"] {
            assert!(
                si.rows.iter().any(|r| r.name.as_ref() == key),
                "softirqs should contain {key}"
            );
        }
    }

    #[test]
    fn test_live_softirqs_fields() {
        let si = softirqs().expect("Failed to read /proc/softirqs");

        // Names are whitespace-free tokens without the trailing colon,
        // and each row carries one counter per listed CPU.
        for r in &si.rows {
            assert!(!r.name.is_empty(), "Softirq name should not be empty");
            assert!(
                !r.name.contains(':') && !r.name.contains(char::is_whitespace),
                "Softirq name should be a bare token"
            );
            assert_eq!(
                r.per_cpu.len(),
                si.cpus.len(),
                "{} should have one count per CPU",
                r.name
            );
        }

        // Header CPU ids are unique and ascending.
        for pair in si.cpus.windows(2) {
            assert!(pair[0] < pair[1], "CPU ids should ascend");
        }

        // Timers fire constantly on any running system.
        let timer = si
            .rows
            .iter()
            .find(|r| r.name.as_ref() == "TIMER")
            .expect("TIMER softirq should exist");
        assert!(
            timer.per_cpu.iter().sum::<u64>() > 0,
            "TIMER counts should be > 0"
        );
    }

    #[test]
    fn test_live_softirqs_monotonic() {
        let first = softirqs().expect("Failed to read /proc/softirqs");
        let second = softirqs().expect("Failed to re-read /proc/softirqs");

        // Counters are cumulative since boot, so a second sample can
        // only stay equal or grow. Rows keep file order, so match by
        // position.
        assert_eq!(
            first.rows.len(),
            second.rows.len(),
            "row count should match"
        );
        for (a, b) in first.rows.iter().zip(&second.rows) {
            assert_eq!(a.name, b.name, "row order should be stable");
            for (&x, &y) in a.per_cpu.iter().zip(&b.per_cpu) {
                assert!(y >= x, "{} counter went backwards: {} -> {}", a.name, x, y);
            }
        }
    }

    #[test]
    fn test_live_interrupts() {
        let irq = interrupts().expect("Failed to read /proc/interrupts");

        // Every running system has at least a timer IRQ and the classic
        // x86 aggregate counters.
        assert!(!irq.cpus.is_empty(), "Should have at least one CPU");
        assert!(!irq.rows.is_empty(), "Should have at least one IRQ row");
        assert!(
            !irq.counts.is_empty(),
            "Should have at least one aggregate counter"
        );
        for key in ["NMI", "LOC", "RES", "CAL", "TLB"] {
            assert!(
                irq.counts.iter().any(|c| c.name.as_ref() == key),
                "interrupts should contain aggregate {key}"
            );
        }
    }

    #[test]
    fn test_live_interrupts_fields() {
        let irq = interrupts().expect("Failed to read /proc/interrupts");

        // Every IRQ row has one count per listed CPU and non-empty info.
        for r in &irq.rows {
            assert_eq!(
                r.per_cpu.len(),
                irq.cpus.len(),
                "IRQ {} should have one count per CPU",
                r.irq
            );
            assert!(!r.info.is_empty(), "IRQ {} should have info", r.irq);
        }

        // Aggregate count names are bare tokens without a colon.
        for c in &irq.counts {
            assert!(!c.name.is_empty(), "Aggregate name should not be empty");
            assert!(
                !c.name.contains(':'),
                "Aggregate name should not contain ':'"
            );
            // Values are either per-CPU or a single system-wide total.
            assert!(
                c.values.len() == 1 || c.values.len() == irq.cpus.len(),
                "{} should have per-cpu or single total values",
                c.name
            );
        }
    }

    #[test]
    fn test_live_interrupts_monotonic() {
        let first = interrupts().expect("Failed to read /proc/interrupts");
        let second = interrupts().expect("Failed to re-read /proc/interrupts");

        // Counters are cumulative since boot, so a second sample can
        // only stay equal or grow.
        assert_eq!(
            first.rows.len(),
            second.rows.len(),
            "IRQ row count should match"
        );
        for (a, b) in first.rows.iter().zip(&second.rows) {
            assert_eq!(a.irq, b.irq, "IRQ numbers should be stable");
            for (&x, &y) in a.per_cpu.iter().zip(&b.per_cpu) {
                assert!(
                    y >= x,
                    "IRQ {} counter went backwards: {} -> {}",
                    a.irq,
                    x,
                    y
                );
            }
        }
        for (a, b) in first.counts.iter().zip(&second.counts) {
            assert_eq!(a.name, b.name, "Aggregate names should be stable");
            for (&x, &y) in a.values.iter().zip(&b.values) {
                assert!(y >= x, "{} counter went backwards: {} -> {}", a.name, x, y);
            }
        }
    }

    #[test]
    fn test_live_iomem() {
        let regions = iomem().expect("Failed to read /proc/iomem");
        assert!(
            !regions.is_empty(),
            "Should have at least one memory region"
        );
    }

    #[test]
    fn test_live_iomem_fields() {
        let regions = iomem().expect("Failed to read /proc/iomem");

        // Every entry spans a valid range with a non-empty description.
        for r in &regions {
            assert!(
                r.start <= r.end,
                "Start address {:x} should be <= end address {:x}",
                r.start,
                r.end,
            );
            assert!(!r.name.is_empty(), "Region name should not be empty");
        }
    }

    #[test]
    fn test_live_iomem_system_ram() {
        let regions = iomem().expect("Failed to read /proc/iomem");

        // Every running system has System RAM and at least one root-level entry.
        assert!(
            regions.iter().any(|r| r.name.as_ref() == "System RAM"),
            "Should have at least one System RAM region"
        );
        assert!(
            regions.iter().any(|r| r.depth == 0),
            "Should have at least one root-level entry"
        );
    }

    #[test]
    fn test_live_ioports() {
        let regions = ioports().expect("Failed to read /proc/ioports");
        assert!(
            !regions.is_empty(),
            "Should have at least one I/O port region"
        );
    }

    #[test]
    fn test_live_ioports_fields() {
        let regions = ioports().expect("Failed to read /proc/ioports");

        // Every entry spans a valid range with a non-empty description.
        for r in &regions {
            assert!(
                r.start <= r.end,
                "Port start {} should be <= end {}",
                r.start,
                r.end,
            );
            assert!(!r.name.is_empty(), "Port region name should not be empty");
        }
    }

    #[test]
    fn test_live_ioports_depth() {
        let regions = ioports().expect("Failed to read /proc/ioports");

        // The file always has at least one root-level entry.
        assert!(
            regions.iter().any(|r| r.depth == 0),
            "Should have at least one root-level entry"
        );

        // Classic ISA devices are always present on x86 systems.
        assert!(
            regions.iter().any(|r| r.name.as_ref() == "dma1"),
            "Should have a dma1 entry"
        );
        assert!(
            regions.iter().any(|r| r.name.as_ref() == "pic1"),
            "Should have a pic1 entry"
        );
    }

    #[test]
    fn test_live_misc() {
        let devices = misc().expect("Failed to read /proc/misc");
        assert!(!devices.is_empty(), "Should have at least one misc device");
    }

    #[test]
    fn test_live_misc_fields() {
        let devices = misc().expect("Failed to read /proc/misc");

        // Every entry has a valid minor number and a non-empty name.
        for d in &devices {
            assert!(!d.name.is_empty(), "Misc device name should not be empty");
            let _ = d.minor;
        }
    }

    #[test]
    fn test_live_misc_known() {
        let devices = misc().expect("Failed to read /proc/misc");

        // fuse is registered on every modern kernel.
        assert!(
            devices.iter().any(|d| d.name.as_ref() == "fuse"),
            "Should have a fuse misc device"
        );
    }

    #[test]
    fn test_live_modules() {
        let mods = modules().expect("Failed to read /proc/modules");
        assert!(!mods.is_empty(), "Should have at least one loaded module");
    }

    #[test]
    fn test_live_modules_fields() {
        let mods = modules().expect("Failed to read /proc/modules");

        // Every entry has a non-empty name, positive size, and valid state.
        for m in &mods {
            assert!(!m.name.is_empty(), "Module name should not be empty");
            assert!(m.size > 0, "Module size should be > 0");
            assert!(
                m.state.as_ref() == "Live"
                    || m.state.as_ref() == "Loading"
                    || m.state.as_ref() == "Unloading",
                "Module state should be Live, Loading, or Unloading"
            );
            let _ = m.ref_count;
            let _ = m.address;
        }
    }

    #[test]
    fn test_live_modules_live() {
        let mods = modules().expect("Failed to read /proc/modules");

        // At least one module must be live with a dependency list.
        assert!(
            mods.iter().any(|m| m.state.as_ref() == "Live"),
            "Should have at least one live module"
        );
        assert!(
            mods.iter().any(|m| m.deps.as_ref() != "-"),
            "Should have at least one module with dependencies"
        );
    }

    #[test]
    fn test_live_crypto() {
        let entries = crypto().expect("Failed to read /proc/crypto");
        assert!(!entries.is_empty(), "Should have at least one crypto entry");
    }

    #[test]
    fn test_live_crypto_fields() {
        let entries = crypto().expect("Failed to read /proc/crypto");
        for entry in &entries {
            assert!(!entry.name.is_empty(), "Crypto name should not be empty");
            assert!(
                !entry.driver.is_empty(),
                "Crypto driver should not be empty"
            );
            assert!(
                !entry.crypto_type.is_empty(),
                "Crypto type should not be empty"
            );
            let _ = entry.priority;
            let _ = entry.ref_count;
        }
    }

    #[test]
    fn test_live_crypto_self_tests() {
        let entries = crypto().expect("Failed to read /proc/crypto");
        assert!(
            entries
                .iter()
                .any(|entry| entry.self_test.as_ref() == "passed"),
            "Should have at least one passed crypto self-test"
        );
    }

    #[test]
    fn test_live_consoles() {
        let cons = consoles().expect("Failed to read /proc/consoles");

        // The kernel lists every registered console; a headless system may
        // have no tty, so we only require the list to be non-empty.
        assert!(!cons.is_empty(), "Should have at least one console");
    }

    #[test]
    fn test_live_consoles_fields() {
        let cons = consoles().expect("Failed to read /proc/consoles");

        // Every console has a non-empty name and a device when one exists.
        for c in &cons {
            assert!(!c.name.is_empty(), "Console name should not be empty");
            match (c.major, c.minor) {
                (Some(major), Some(minor)) => {
                    assert!(major > 0, "Console major should be > 0");
                    let _ = minor;
                }
                (None, None) => {}
                _ => panic!("Console major/minor should both be set or both absent"),
            }
        }
    }

    #[test]
    fn test_live_consoles_flags() {
        let cons = consoles().expect("Failed to read /proc/consoles");

        // The kernel lists every registered console (enabled or not) with an
        // indeterminate flag set, so we only check that the decoded flags are
        // a valid subset of the known bits — i.e. the parser didn't mangle the
        // R/W/U and state flags.
        for c in &cons {
            let unknown = c.flags.bits() & !ConsoleFlags::all().bits();
            assert!(
                unknown == 0,
                "Console flags contain unknown bits: {unknown:#b}"
            );
        }
    }

    #[test]
    fn test_live_locks() {
        let lock_list = locks().expect("Failed to read /proc/locks");

        // Locks may be absent on a quiet system, so don't require any.
        for l in &lock_list {
            assert!(l.pid != 0, "Lock PID should not be 0");
            assert!(l.inode > 0, "Lock inode should be > 0");
        }
    }

    #[test]
    fn test_live_locks_fields() {
        let lock_list = locks().expect("Failed to read /proc/locks");

        for l in &lock_list {
            match l.lock_type {
                procfs2::proc::LockType::Flock
                | procfs2::proc::LockType::Ofdlck
                | procfs2::proc::LockType::Posix => {}
            }
            match l.class {
                procfs2::proc::LockClass::Advisory | procfs2::proc::LockClass::Mandatory => {}
            }
            match l.access {
                procfs2::proc::LockAccess::Read | procfs2::proc::LockAccess::Write => {}
            }
            let _ = l.start;
            let _ = l.end;
        }
    }

    #[test]
    fn test_live_locks_no_zero_pid() {
        let lock_list = locks().expect("Failed to read /proc/locks");

        // OFD locks show -1, POSIX/FLOCK show a positive PID.
        // No lock should have pid == 0.
        for l in &lock_list {
            assert!(
                l.pid != 0,
                "Lock PID should be non-zero (got 0 for {:?})",
                l.lock_type,
            );
        }
    }

    #[test]
    fn test_live_cpu_pressure() {
        let psi = cpu_pressure().expect("Failed to read /proc/pressure/cpu");

        // Averages are percentages in [0, 100]; total is microseconds.
        assert!(psi.some.avg10 >= 0.0, "avg10 should be >= 0");
        assert!(psi.full.avg10 >= 0.0, "full avg10 should be >= 0");
        let _ = psi.some.total;
    }

    #[test]
    fn test_live_memory_and_io_pressure() {
        let mem = memory_pressure().expect("Failed to read /proc/pressure/memory");
        let io = io_pressure().expect("Failed to read /proc/pressure/io");

        // Both files report `some` and `full` lines.
        assert!(mem.some.avg10 >= 0.0);
        assert!(mem.full.avg10 >= 0.0);
        assert!(io.some.avg10 >= 0.0);
        assert!(io.full.avg10 >= 0.0);
    }

    #[test]
    fn test_live_irq_pressure() {
        // IRQ pressure is not compiled in on some kernels; the library
        // reports that as None rather than an error.
        let Some(psi) = irq_pressure().expect("Failed to read /proc/pressure/irq (when supported)")
        else {
            return;
        };

        // IRQ only reports `full`; averages are non-negative percentages.
        assert!(psi.full.avg10 >= 0.0, "avg10 should be >= 0");
        assert!(psi.full.avg60 >= 0.0, "avg60 should be >= 0");
        assert!(psi.full.avg300 >= 0.0, "avg300 should be >= 0");
        let _ = psi.full.total;
    }

    #[test]
    fn test_live_net_snmp() {
        let stats = procfs2::proc::net::snmp().expect("Failed to read /proc/net/snmp");
        assert!(stats.ip.default_ttl > 0, "IP default TTL should be > 0");
        assert!(stats.tcp.rto_min > 0, "TCP minimum RTO should be > 0");
    }

    #[test]
    fn test_live_net_snmp_counters() {
        let stats = procfs2::proc::net::snmp().expect("Failed to read /proc/net/snmp");
        assert!(stats.ip.in_receives >= stats.ip.in_delivers);
        assert!(stats.tcp.in_segs > 0, "TCP input segments should be > 0");
        assert!(
            stats.udp.out_datagrams > 0,
            "UDP output datagrams should be > 0"
        );
    }

    #[test]
    fn test_live_net_snmp_consistent() {
        let first = procfs2::proc::net::snmp().expect("Failed to read /proc/net/snmp");
        let second = procfs2::proc::net::snmp().expect("Failed to reread /proc/net/snmp");
        assert!(second.ip.in_receives >= first.ip.in_receives);
        assert!(second.tcp.in_segs >= first.tcp.in_segs);
        assert!(second.udp.in_datagrams >= first.udp.in_datagrams);
    }

    #[test]
    fn test_live_net_snmp6() {
        let stats = procfs2::proc::net::snmp6().expect("Failed to read /proc/net/snmp6");
        assert!(stats.ip.in_delivers <= stats.ip.in_receives);
    }

    #[test]
    fn test_live_net_snmp6_counters() {
        let stats = procfs2::proc::net::snmp6().expect("Failed to read /proc/net/snmp6");
        // A locally generated datagram counted in `out_requests` is either
        // handed to the lower layers (`out_transmits`) or dropped
        // (`out_discards` / `out_no_routes`), so these must account for it.
        assert!(
            stats.ip.out_requests
                <= stats.ip.out_transmits + stats.ip.out_discards + stats.ip.out_no_routes,
            "out_requests should be accounted for by transmits or drops"
        );
        let _ = stats.udp.out_datagrams;
    }

    #[test]
    fn test_live_net_snmp6_consistent() {
        let first = procfs2::proc::net::snmp6().expect("Failed to read /proc/net/snmp6");
        let second = procfs2::proc::net::snmp6().expect("Failed to reread /proc/net/snmp6");
        assert!(second.ip.in_receives >= first.ip.in_receives);
        assert!(second.icmp.in_msgs >= first.icmp.in_msgs);
        assert!(second.udp.out_datagrams >= first.udp.out_datagrams);
    }

    #[test]
    fn test_live_net_route() {
        let routes: Vec<_> = procfs2::proc::net::route().filter_map(|r| r.ok()).collect();

        // At least one route exists (loopback or default).
        assert!(!routes.is_empty(), "Should have at least one route");
    }

    #[test]
    fn test_live_net_route_fields() {
        let routes: Vec<_> = procfs2::proc::net::route().filter_map(|r| r.ok()).collect();

        // Every route has the full set of numeric fields.
        for r in &routes {
            assert!(!r.iface.is_empty(), "Route iface should not be empty");
            let _ = r.destination;
            let _ = r.gateway;
            let _ = r.mask;
            let _ = r.flags;
            let _ = r.refcnt;
            let _ = r.use_;
            let _ = r.metric;
            let _ = r.mtu;
            let _ = r.window;
            let _ = r.irtt;
        }
    }

    #[test]
    fn test_live_net_route_default() {
        let routes: Vec<_> = procfs2::proc::net::route().filter_map(|r| r.ok()).collect();

        // The default route, when present, is 0.0.0.0 with a 0 mask.
        for r in &routes {
            if r.destination.is_unspecified() && r.mask.is_unspecified() {
                let _ = r.gateway;
                let _ = r.metric;
            }
        }
    }

    #[test]
    fn test_live_net_dev() {
        let devices: Vec<_> = procfs2::proc::net::dev().filter_map(|r| r.ok()).collect();

        // The loopback interface is always present.
        assert!(!devices.is_empty(), "Should have at least one interface");
        assert!(
            devices.iter().any(|d| d.name.as_ref() == "lo"),
            "Should have a loopback interface"
        );
    }

    #[test]
    fn test_live_net_dev_fields() {
        let devices: Vec<_> = procfs2::proc::net::dev().filter_map(|r| r.ok()).collect();

        // Every interface carries the full 16-column counter set.
        for d in &devices {
            assert!(!d.name.is_empty(), "Interface name should not be empty");
            let _ = d.rx_bytes;
            let _ = d.rx_packets;
            let _ = d.rx_errors;
            let _ = d.rx_drop;
            let _ = d.rx_fifo_errors;
            let _ = d.rx_frame_errors;
            let _ = d.rx_compressed;
            let _ = d.rx_multicast;
            let _ = d.tx_bytes;
            let _ = d.tx_packets;
            let _ = d.tx_errors;
            let _ = d.tx_drop;
            let _ = d.tx_fifo_errors;
            let _ = d.tx_collisions;
            let _ = d.tx_carrier_errors;
            let _ = d.tx_compressed;
        }
    }

    #[test]
    fn test_live_net_dev_loopback_activity() {
        let devices: Vec<_> = procfs2::proc::net::dev().filter_map(|r| r.ok()).collect();

        // Loopback carries at least some traffic while the test runs.
        let lo = devices
            .iter()
            .find(|d| d.name.as_ref() == "lo")
            .expect("loopback interface should exist");
        assert!(lo.rx_packets > 0, "loopback should have received packets");
        assert!(
            lo.tx_packets > 0,
            "loopback should have transmitted packets"
        );
    }

    #[test]
    fn test_live_net_arp() {
        // The ARP table may legitimately be empty; just ensure no parse
        // errors.
        let entries: Vec<_> = procfs2::proc::net::arp().filter_map(|r| r.ok()).collect();
        assert!(
            procfs2::proc::net::arp().all(|r| r.is_ok()),
            "ARP entries should parse"
        );
        let _ = entries;
    }

    #[test]
    fn test_live_net_arp_fields() {
        let entries: Vec<_> = procfs2::proc::net::arp().filter_map(|r| r.ok()).collect();

        // Every entry has an IP, a hardware info, and a device.
        for e in &entries {
            let _ = e.ip;
            let _ = e.hw_type;
            let _ = e.flags;
            let _ = e.mac;
            assert!(!e.device.is_empty(), "ARP device should not be empty");
        }
    }

    #[test]
    fn test_live_net_arp_consistency() {
        let first: Vec<_> = procfs2::proc::net::arp().filter_map(|r| r.ok()).collect();
        let second: Vec<_> = procfs2::proc::net::arp().filter_map(|r| r.ok()).collect();

        // The ARP table is stable in practice between two reads; if it
        // changed, skip rather than fail.
        if first.len() == second.len() {
            for (a, b) in first.iter().zip(&second) {
                assert_eq!(a.ip, b.ip, "ARP entry should keep its IP");
            }
        }
    }

    #[test]
    fn test_live_net_tcp() {
        // Connections may be empty; ensure the file parses without errors.
        let entries: Vec<_> = procfs2::proc::net::tcp().collect();
        assert!(
            entries.iter().all(|r| r.is_ok()),
            "TCP entries should parse"
        );
    }

    #[test]
    fn test_live_net_tcp_loopback() {
        let entries: Vec<_> = procfs2::proc::net::tcp().filter_map(|r| r.ok()).collect();

        // A listening TCP socket bound anywhere is normal.
        for e in &entries {
            let _ = e.local;
            let _ = e.remote;
            let _ = e.state;
            let _ = e.inode;
            let _ = e.uid;
            let _ = e.rx_queue;
            let _ = e.tx_queue;
        }
    }

    #[test]
    fn test_live_net_tcp_states() {
        let entries: Vec<_> = procfs2::proc::net::tcp().collect();

        // Any parsed state decodes to a known variant.
        for r in entries {
            let e = r.expect("TCP entry should parse");
            match e.state {
                procfs2::proc::net::TcpState::Established
                | procfs2::proc::net::TcpState::SynSent
                | procfs2::proc::net::TcpState::SynRecv
                | procfs2::proc::net::TcpState::FinWait1
                | procfs2::proc::net::TcpState::FinWait2
                | procfs2::proc::net::TcpState::TimeWait
                | procfs2::proc::net::TcpState::Close
                | procfs2::proc::net::TcpState::CloseWait
                | procfs2::proc::net::TcpState::LastAck
                | procfs2::proc::net::TcpState::Listen
                | procfs2::proc::net::TcpState::Closing
                | procfs2::proc::net::TcpState::NewSynRecv => {}
            }
        }
    }

    #[test]
    fn test_live_net_tcp6() {
        // Pure-IPv6 connections yield parse errors by design (documented
        // limitation), so only assert that collection does not panic.
        let _ = procfs2::proc::net::tcp6().count();
    }

    #[test]
    fn test_live_net_tcp6_mapped() {
        // IPv4-mapped entries come back as IPv4.
        for entry in procfs2::proc::net::tcp6().flatten() {
            assert!(
                entry.local.ip().is_loopback() || !entry.local.ip().is_unspecified(),
                "mapped entry should invert to the original IPv4"
            );
            let _ = entry.remote;
            let _ = entry.state;
        }
    }

    #[test]
    fn test_live_net_tcp6_fallback() {
        // parse_tcp6_entries() always yields IPv6 sockets without the
        // IPv4-only remapping.
        for entry in procfs2::proc::net::tcp::parse_tcp6_entries().flatten() {
            let _ = entry.local;
            let _ = entry.remote;
            let _ = entry.inode;
        }
    }

    #[test]
    fn test_live_net_udp() {
        let entries: Vec<_> = procfs2::proc::net::udp().collect();
        assert!(
            entries.iter().all(|r| r.is_ok()),
            "UDP entries should parse"
        );
    }

    #[test]
    fn test_live_net_udp_loopback() {
        let entries: Vec<_> = procfs2::proc::net::udp().filter_map(|r| r.ok()).collect();

        for e in &entries {
            let _ = e.local;
            let _ = e.remote;
            let _ = e.state;
            let _ = e.uid;
            let _ = e.inode;
            let _ = e.rx_queue;
            let _ = e.tx_queue;
        }
    }

    #[test]
    fn test_live_net_udp_states() {
        let entries: Vec<_> = procfs2::proc::net::udp().collect();

        // UDP sockets are either unconnected (0x07) or connected (0x01).
        for r in entries {
            let e = r.expect("UDP entry should parse");
            assert!(
                e.state == 0x07 || e.state == 0x01,
                "UDP state {:#x} should be 0x01 or 0x07",
                e.state
            );
        }
    }

    #[test]
    fn test_live_net_udp6() {
        let entries: Vec<_> = procfs2::proc::net::udp6().collect();
        assert!(
            entries.iter().all(|r| r.is_ok()),
            "UDP6 entries should parse"
        );
    }

    #[test]
    fn test_live_net_udp6_fields() {
        let entries: Vec<_> = procfs2::proc::net::udp6().filter_map(|r| r.ok()).collect();

        for e in &entries {
            let _ = e.local;
            let _ = e.remote;
            let _ = e.state;
            let _ = e.uid;
            let _ = e.inode;
        }
    }

    #[test]
    fn test_live_net_udp6_ipv4_mixed() {
        // udp6 may mix IPv6 and IPv4-mapped sockets; both parse fine.
        let _count: usize = procfs2::proc::net::udp6().filter_map(|r| r.ok()).count();
    }

    #[test]
    fn test_live_net_unix() {
        let entries: Vec<_> = procfs2::proc::net::unix().collect();
        assert!(
            entries.iter().all(|r| r.is_ok()),
            "Unix socket entries should parse"
        );
    }

    #[test]
    fn test_live_net_unix_path() {
        // Most systems have a few bound abstract or filesystem sockets.
        let entries: Vec<_> = procfs2::proc::net::unix().filter_map(|r| r.ok()).collect();

        let has_path = entries.iter().any(|e| e.path.is_some());
        // Can't require one — some containers have none.
        let _ = has_path;

        for e in &entries {
            let _ = e.ino;
            let _ = e.ref_count;
            let _ = e.protocol;
            let _ = e.type_;
            let _ = e.state;
            let _ = e.inode;
        }
    }

    #[test]
    fn test_live_net_unix_state() {
        let entries: Vec<_> = procfs2::proc::net::unix().collect();

        // Unix socket state reuses the kernel TCP state codes
        // (include/net/tcp_states.h), which run 0..TCP_NEW_SYN_RECV (12).
        for r in entries {
            let e = r.expect("Unix socket entry should parse");
            assert!(
                e.state <= 12,
                "Unix socket state {} should be a valid TCP state code",
                e.state
            );
        }
    }

    #[test]
    fn test_live_sys_block() {
        let devices: Vec<_> = sys::BlockDevice::all().filter_map(|r| r.ok()).collect();
        assert!(!devices.is_empty(), "Should have at least one block device");

        // Skip devices that report a size of 0 (e.g. unbound loop devices
        // on CI runners), which may appear before the real disk.
        let dev = devices
            .iter()
            .find(|dev| dev.size().map(|s| s.0 > 0).unwrap_or(false))
            .expect("Should have a block device with a nonzero size");

        let stat = dev.stat().expect("Failed to read block device stat");
        assert!(dev.size().expect("Failed to read device size").0 > 0);
        assert!(stat.reads_completed > 0 || stat.writes_completed > 0);
    }

    #[test]
    fn test_live_sys_cpu() {
        let count = sys::cpu_count().expect("Failed to read cpu count");
        assert!(count > 0, "CPU count should be > 0");

        let cpus = sys::online_cpus().expect("Failed to read online cpus");
        assert!(!cpus.is_empty(), "Should have at least one online CPU");
    }

    #[test]
    fn test_live_sys_net() {
        let ifaces: Vec<_> = sys::NetInterface::all().filter_map(|r| r.ok()).collect();
        assert!(!ifaces.is_empty(), "Should have at least one interface");

        if let Some(iface) = ifaces.first() {
            let stats = iface.stats().expect("Failed to read interface stats");
            assert!(
                iface.mtu().expect("Failed to read mtu") > 0,
                "MTU should be > 0"
            );
            assert!(
                iface
                    .flags()
                    .expect("Failed to read flags")
                    .contains(sys::NetIfFlags::UP),
                "interface should be up"
            );
            let _ = stats.rx_bytes.0;
        }
    }

    #[test]
    fn test_live_sys_power() {
        // Power supplies may be absent (e.g. some VMs); just check that
        // any present supply reports a valid type.
        let supplies: Vec<_> = sys::PowerSupply::all().filter_map(|r| r.ok()).collect();
        for ps in &supplies {
            assert!(ps.kind().is_ok(), "Power supply kind should parse");
        }
    }
}