xref: /aosp_15_r20/external/crosvm/base/tests/linux/main.rs (revision bb4ee6a4ae7042d18b07a98463b9c8b875e44b39)
1 // Copyright 2022 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #![cfg(any(target_os = "android", target_os = "linux"))]
6 
7 use std::path::Path;
8 
9 use base::safe_descriptor_from_path;
10 use base::Error;
11 use base::FromRawDescriptor;
12 use base::SafeDescriptor;
13 use libc::EBADF;
14 use libc::EINVAL;
15 
16 /// Runs all unix specific integration tests in a single binary.
17 mod net;
18 mod syslog;
19 mod tube;
20 
21 #[test]
safe_descriptor_from_path_valid()22 fn safe_descriptor_from_path_valid() {
23     assert!(safe_descriptor_from_path(Path::new("/proc/self/fd/2"))
24         .unwrap()
25         .is_some());
26 }
27 
28 #[test]
safe_descriptor_from_path_invalid_integer()29 fn safe_descriptor_from_path_invalid_integer() {
30     assert_eq!(
31         safe_descriptor_from_path(Path::new("/proc/self/fd/blah")),
32         Err(Error::new(EINVAL))
33     );
34 }
35 
36 #[test]
safe_descriptor_from_path_invalid_fd()37 fn safe_descriptor_from_path_invalid_fd() {
38     assert_eq!(
39         safe_descriptor_from_path(Path::new("/proc/self/fd/42")),
40         Err(Error::new(EBADF))
41     );
42 }
43 
44 #[test]
safe_descriptor_from_path_none()45 fn safe_descriptor_from_path_none() {
46     assert_eq!(
47         safe_descriptor_from_path(Path::new("/something/else")).unwrap(),
48         None
49     );
50 }
51 
52 #[test]
53 #[allow(clippy::eq_op)]
clone_equality()54 fn clone_equality() {
55     // SAFETY: Safe because return value is checked.
56     let ret = unsafe { libc::eventfd(0, 0) };
57     if ret < 0 {
58         panic!("failed to create eventfd");
59     }
60     // SAFETY: Safe because ret is valid and return value is checked.
61     let descriptor = unsafe { SafeDescriptor::from_raw_descriptor(ret) };
62 
63     assert_eq!(descriptor, descriptor);
64 
65     assert_eq!(
66         descriptor,
67         descriptor.try_clone().expect("failed to clone eventfd")
68     );
69 
70     // SAFETY: Safe because return value is checked.
71     let ret = unsafe { libc::eventfd(0, 0) };
72     if ret < 0 {
73         panic!("failed to create eventfd");
74     }
75 
76     // SAFETY: Safe because ret is valid and return value is checked.
77     let another = unsafe { SafeDescriptor::from_raw_descriptor(ret) };
78 
79     assert_ne!(descriptor, another);
80 }
81