1 use nix::sys::resource::{getrlimit, setrlimit, Resource};
2 use nix::sys::resource::{getrusage, UsageWho};
3 
4 /// Tests the RLIMIT_NOFILE functionality of getrlimit(), where the resource RLIMIT_NOFILE refers
5 /// to the maximum file descriptor number that can be opened by the process (aka the maximum number
6 /// of file descriptors that the process can open, since Linux 4.5).
7 ///
8 /// We first fetch the existing file descriptor maximum values using getrlimit(), then edit the
9 /// soft limit to make sure it has a new and distinct value to the hard limit. We then setrlimit()
10 /// to put the new soft limit in effect, and then getrlimit() once more to ensure the limits have
11 /// been updated.
12 #[test]
test_resource_limits_nofile()13 pub fn test_resource_limits_nofile() {
14     let (mut soft_limit, hard_limit) =
15         getrlimit(Resource::RLIMIT_NOFILE).unwrap();
16 
17     soft_limit -= 1;
18     assert_ne!(soft_limit, hard_limit);
19     setrlimit(Resource::RLIMIT_NOFILE, soft_limit, hard_limit).unwrap();
20 
21     let (new_soft_limit, _) = getrlimit(Resource::RLIMIT_NOFILE).unwrap();
22     assert_eq!(new_soft_limit, soft_limit);
23 }
24 
25 #[test]
test_self_cpu_time()26 pub fn test_self_cpu_time() {
27     // Make sure some CPU time is used.
28     let mut numbers: Vec<i32> = (1..1_000_000).collect();
29     numbers.iter_mut().for_each(|item| *item *= 2);
30 
31     // FIXME: this is here to help ensure the compiler does not optimize the whole
32     // thing away. Replace the assert with test::black_box once stabilized.
33     assert_eq!(numbers[100..200].iter().sum::<i32>(), 30_100);
34 
35     let usage = getrusage(UsageWho::RUSAGE_SELF)
36         .expect("Failed to call getrusage for SELF");
37     let rusage = usage.as_ref();
38 
39     let user = usage.user_time();
40     assert!(user.tv_sec() > 0 || user.tv_usec() > 0);
41     assert_eq!(user.tv_sec(), rusage.ru_utime.tv_sec);
42     assert_eq!(user.tv_usec(), rusage.ru_utime.tv_usec);
43 }
44