Port test_wwrite_to_fd

This commit is contained in:
Johannes Altmanninger
2023-12-09 21:02:14 +01:00
parent d5ccbb6e9c
commit fe19cbded0
3 changed files with 47 additions and 48 deletions

View File

@@ -5,6 +5,7 @@
pub mod gettext;
pub mod printf;
#[cfg(test)]
#[allow(unused_imports)] // Easy way to suppress warnings while we have two testing modes.
mod tests;
pub mod wcstod;
pub mod wcstoi;

View File

@@ -1,3 +1,10 @@
use crate::ffi_tests::add_test;
use libc::{c_void, O_CREAT, O_RDWR, O_TRUNC, SEEK_SET};
use rand::random;
use std::ffi::CString;
use crate::fallback::fish_mkstemp_cloexec;
use super::*;
#[test]
@@ -49,3 +56,42 @@ fn test_wdirname_wbasename() {
assert_eq!(wdirname(&longpath), longpath_dir);
assert_eq!(wbasename(&longpath), "overlong"L);
}
add_test!("test_wwrite_to_fd", || {
let (fd, filename) =
fish_mkstemp_cloexec(CString::new("/tmp/fish_test_wwrite.XXXXXX").unwrap());
{
let mut tmpfd = AutoCloseFd::new(fd);
assert!(tmpfd.is_valid());
tmpfd.close();
}
let sizes = [0, 1, 2, 3, 5, 13, 23, 64, 128, 255, 4096, 4096 * 2];
for &size in &sizes {
let fd = AutoCloseFd::new(unsafe {
libc::open(filename.as_ptr(), O_RDWR | O_TRUNC | O_CREAT, 0o666)
});
assert!(fd.is_valid());
let mut input = WString::new();
for _i in 0..size {
input.push(random());
}
let amt = wwrite_to_fd(&input, fd.fd()).unwrap();
let narrow = wcs2string(&input);
assert_eq!(amt, narrow.len());
assert!(unsafe { libc::lseek(fd.fd(), 0, SEEK_SET) } >= 0);
let mut contents = vec![0u8; narrow.len()];
let read_amt = unsafe {
libc::read(
fd.fd(),
(&mut contents[0]) as *mut u8 as *mut c_void,
narrow.len(),
)
};
assert!(usize::try_from(read_amt).unwrap() == narrow.len());
assert_eq!(&contents, &narrow);
}
unsafe { libc::remove(filename.as_ptr()) };
});