Debian Codegraph @

tests/tests.rs

raw symbols ◀ ▶ SCIP
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright 2021-2024 Martin Pool
2
3 //! Public API tests for `cp_r`.
4
5 use std::fs::{create_dir, metadata, read, write, DirEntry, FileType};
6 use std::io;
7 use std::path::{Path, PathBuf};
8
9 use tempfile::TempDir;
10
11 use cp_r::*;
12
13 #[test]
14 fn basic_copy() {
15 let src = tempfile::tempdir().unwrap();
16 let dest = tempfile::tempdir().unwrap();
17 let file_content = b"hello world\n";
18 let file_name = "a file";
19 let src_file_path = src.path().join(file_name);
20 write(&src_file_path, file_content).unwrap();
21
22 let stats = CopyOptions::default()
23 .copy_tree(src.path(), dest.path())
24 .unwrap();
25
26 let dest_file_path = &dest.path().join(file_name);
27 assert_eq!(read(dest_file_path).unwrap(), file_content);
28 assert_eq!(stats.files, 1);
29 assert_eq!(stats.file_bytes, file_content.len() as u64);
30
31 let src_mtime = metadata(&src_file_path).unwrap().modified().unwrap();
32 let dest_mtime = metadata(dest_file_path).unwrap().modified().unwrap();
33 dbg!(src_mtime, dest_mtime);
34
35 // Filesystems might not retain perfect resolution on mtimes, but they should at least be
36 // within 1ms everywhere(?); the error might be in either direction.
37 let d = dest_mtime
38 .duration_since(src_mtime)
39 .or_else(|_| src_mtime.duration_since(dest_mtime))
40 .unwrap();
41 dbg!(d);
42 assert!(d.as_micros() < 1000);
43 }
44
45 #[test]
46 fn subdirs() {
47 let src = TempDir::new().unwrap();
48 let dest = TempDir::new().unwrap();
49
50 create_dir(src.path().join("a")).unwrap();
51 create_dir(src.path().join("a").join("aa")).unwrap();
52 create_dir(src.path().join("b")).unwrap();
53 create_dir(src.path().join("b/bb")).unwrap();
54
55 let file_content = b"some file content\n";
56 write(src.path().join("a/aa/aaafile"), file_content).unwrap();
57
58 // Note here that we can just path a reference to the TempDirs without calling
59 // `.path()`, because they `AsRef` to a `Path`.
60 let stats = CopyOptions::default().copy_tree(&src, &dest).unwrap();
61
62 assert_eq!(
63 read(dest.path().join("a/aa/aaafile")).unwrap(),
64 file_content
65 );
66 assert!(metadata(dest.path().join("b/bb"))
67 .unwrap()
68 .file_type()
69 .is_dir());
70 assert_eq!(stats.files, 1);
71 assert_eq!(stats.file_bytes, file_content.len() as u64);
72 assert_eq!(stats.dirs, 4);
73 }
74
75 #[test]
76 fn clean_error_on_nonexistent_source() {
77 let dest = tempfile::tempdir().unwrap();
78 let err = CopyOptions::new().copy_tree("nothing", &dest).unwrap_err();
79 println!("err = {:#?}", err);
80 assert!(err.path().starts_with("nothing"));
81 assert_eq!(err.kind(), ErrorKind::ReadDir);
82 assert_eq!(err.io_error().unwrap().kind(), io::ErrorKind::NotFound);
83 }
84
85 #[test]
86 fn create_destination_by_default() {
87 let empty_src = tempfile::tempdir().unwrap();
88 let dest_parent = tempfile::tempdir().unwrap();
89 let dest = dest_parent.path().join("nonexistent_child");
90 let stats = CopyOptions::new()
91 .copy_tree(empty_src.path(), &dest)
92 .unwrap();
93 assert!(dest.is_dir());
94 assert_eq!(stats.dirs, 1);
95 assert_eq!(stats.files, 0);
96 }
97
98 #[test]
99 fn create_destination_when_requested() {
100 let empty_src = tempfile::tempdir().unwrap();
101 let dest_parent = tempfile::tempdir().unwrap();
102 let dest = dest_parent.path().join("nonexistent_child");
103 let stats = CopyOptions::new()
104 .create_destination(true)
105 .copy_tree(&empty_src, &dest)
106 .unwrap();
107 assert!(dest.is_dir());
108 assert_eq!(stats.dirs, 1);
109 assert_eq!(stats.files, 0);
110 }
111
112 #[test]
113 fn optionally_destination_must_exist() {
114 // TODO: At least add an option to create the destination if it does not exist.
115 // But, for now, it must.
116 let dest_parent = tempfile::tempdir().unwrap();
117 let dest = dest_parent.path().join("nonexistent_child");
118 let err = CopyOptions::new()
119 .create_destination(false)
120 .copy_tree("src", &dest)
121 .unwrap_err();
122 println!("err = {:#?}", err);
123 assert_eq!(err.kind(), ErrorKind::DestinationDoesNotExist);
124 assert!(
125 err.path().starts_with(&dest),
126 "path in the error relates to the destination"
127 );
128 assert!(err.io_error().is_none(), "no underlying io::Error");
129 }
130
131 #[cfg(unix)]
132 #[ignore]
133 #[test]
134 fn clean_error_failing_to_copy_devices() {
135 let dest = tempfile::tempdir().unwrap();
136 let err = CopyOptions::new()
137 .copy_tree("/dev", dest.path())
138 .unwrap_err();
139 println!("{:#?}", err);
140 let kind = err.kind();
141 assert!(
142 kind == ErrorKind::UnsupportedFileType || kind == ErrorKind::CopyFile,
143 "unexpected ErrorKind {:?}",
144 kind
145 );
146 // Depending on OS peculiarities, we might detect this at different points, and therefore
147 // return different error kinds, and there may or may not be an ioerror.
148 assert!(err.path().strip_prefix("/dev/").is_ok());
149 let formatted = format!("{}", err);
150 assert!(
151 formatted.starts_with("unsupported file type: /dev/")
152 || formatted.contains(
153 "the source path is neither a regular file nor a symlink to a regular file"
154 ),
155 "unexpected string format: {:?}",
156 formatted
157 );
158 }
159
160 #[cfg(unix)]
161 #[test]
162 fn copy_dangling_symlink() {
163 let src = tempfile::tempdir().unwrap();
164 let dest = tempfile::tempdir().unwrap();
165 std::os::unix::fs::symlink("dangling target", src.path().join("a_link")).unwrap();
166 let stats = CopyOptions::new()
167 .copy_tree(src.path(), dest.path())
168 .unwrap();
169 println!("{:#?}", stats);
170 assert_eq!(
171 stats,
172 CopyStats {
173 files: 0,
174 dirs: 0,
175 symlinks: 1,
176 file_bytes: 0,
177 filtered_out: 0,
178 }
179 );
180 }
181
182 #[test]
183 fn filter_by_path() {
184 let src = tempfile::tempdir().unwrap();
185 let dest = tempfile::tempdir().unwrap();
186
187 create_dir(src.path().join("a")).unwrap();
188 create_dir(src.path().join("b")).unwrap();
189 create_dir(src.path().join("b/bb")).unwrap();
190 create_dir(src.path().join("a").join("aa")).unwrap();
191
192 let file_content = b"some file content\n";
193 write(src.path().join("a/aa/aaafile"), file_content).unwrap();
194
195 fn not_b(path: &Path, _: &DirEntry) -> cp_r::Result<bool> {
196 Ok(path != Path::new("b"))
197 }
198 let stats = CopyOptions::new()
199 .filter(not_b)
200 .copy_tree(src.path(), dest.path())
201 .unwrap();
202
203 assert_eq!(
204 read(dest.path().join("a/aa/aaafile")).unwrap(),
205 file_content
206 );
207 assert!(!dest.path().join("b").exists());
208 assert_eq!(
209 stats,
210 CopyStats {
211 files: 1,
212 file_bytes: file_content.len() as u64,
213 dirs: 2,
214 symlinks: 0,
215 filtered_out: 1,
216 }
217 );
218 }
219
220 const AAA_CONTENT: &[u8] = b"some file content\n";
221
222 fn setup_a_b_src() -> tempfile::TempDir {
223 let src = tempfile::tempdir().unwrap();
224 create_dir(src.path().join("a")).unwrap();
225 create_dir(src.path().join("b")).unwrap();
226 create_dir(src.path().join("b/bb")).unwrap();
227 create_dir(src.path().join("a").join("aa")).unwrap();
228
229 let file_content = AAA_CONTENT;
230 write(src.path().join("a/aa/aaafile"), file_content).unwrap();
231
232 src
233 }
234
235 #[test]
236 fn filter_by_mut_closure() {
237 let src = setup_a_b_src();
238 let dest = tempfile::tempdir().unwrap();
239
240 // Filter paths and also collect all the paths we've seen, as an example of a filter
241 // that's more than a simple function pointer.
242 let mut filter_seen_paths: Vec<String> = Vec::new();
243 let stats = CopyOptions::default()
244 .filter(|path: &Path, _de| {
245 filter_seen_paths.push(path.to_str().unwrap().replace('\\', "/"));
246 Ok(path != Path::new("b"))
247 })
248 .copy_tree(src.path(), dest.path())
249 .unwrap();
250
251 assert_eq!(read(dest.path().join("a/aa/aaafile")).unwrap(), AAA_CONTENT,);
252 assert!(!dest.path().join("b").exists());
253 assert_eq!(
254 stats,
255 CopyStats {
256 files: 1,
257 file_bytes: AAA_CONTENT.len() as u64,
258 dirs: 2,
259 symlinks: 0,
260 filtered_out: 1,
261 }
262 );
263 // The order in which entries are seen is not guaranteed, and in practice
264 // will be partly determined by the unpredictable order that the filesystem
265 // returns directory entries.
266 //
267 // "b" is seen (because the filter records it before filtering it out), but
268 // b's children are not visited.
269 filter_seen_paths.sort_unstable();
270 assert_eq!(filter_seen_paths, ["a", "a/aa", "a/aa/aaafile", "b"]);
271 }
272
273 #[test]
274 fn after_entry_copied_callback() {
275 let src = setup_a_b_src();
276 let dest = tempfile::tempdir().unwrap();
277 let mut progress_seen: Vec<(PathBuf, FileType)> = Vec::new();
278 let mut last_stats = CopyStats::default();
279
280 // We can't count on the entries being seen in any particular order, but there are other
281 // properties we can check...
282 let final_stats = CopyOptions::new()
283 .after_entry_copied(|p, ft, stats| {
284 assert!(
285 !progress_seen.iter().any(|(pp, _)| pp == p),
286 "filename has not been seen before"
287 );
288 progress_seen.push((p.to_owned(), *ft));
289 if ft.is_file() {
290 assert_eq!(stats.files, last_stats.files + 1);
291 } else if ft.is_dir() {
292 assert_eq!(stats.dirs, last_stats.dirs + 1);
293 } else {
294 panic!("unexpected file type {:?}", ft);
295 }
296 last_stats = stats.clone();
297 Ok(())
298 })
299 .copy_tree(src.path(), dest.path())
300 .unwrap();
301 assert_eq!(
302 last_stats, final_stats,
303 "progress after the final copy include stats equal to the overall final stats"
304 );
305 }
306
307 #[test]
308 fn after_entry_callback_error_terminates_copy() {
309 let src = setup_a_b_src();
310 let dest = tempfile::tempdir().unwrap();
311
312 // Stop after copying one file. The order in which files are copied is not defined, but we should see
313 // exactly one in the result.
314 let options = CopyOptions::new().after_entry_copied(|p, ft, _stats| {
315 if ft.is_file() {
316 Err(Error::new(ErrorKind::Interrupted, p))
317 } else {
318 Ok(())
319 }
320 });
321 let result = options.copy_tree(src.path(), dest.path());
322
323 let err = result.unwrap_err();
324 let err_str = err.to_string();
325 assert!(
326 err_str.starts_with("interrupted"),
327 "unexpected err_str: {:?}",
328 err_str
329 );
330
331 let err_debug = format!("{:?}", err);
332 assert!(
333 err_debug.starts_with("Error") && err_debug.contains("kind: Interrupted"),
334 "unexpected err_debug: {:?}",
335 err_debug
336 );
337 }