team-ljyzipelo

공개
849줄29 KB
1use super::*;
2use std::{io::Read, process::Child, sync::mpsc, time::Duration};
3
4fn private_dir(path: &std::path::Path) {
5 let mut builder = fs::DirBuilder::new();
6 #[cfg(unix)]
7 {
8 use std::os::unix::fs::DirBuilderExt;
9 builder.mode(0o700);
10 }
11 builder.create(path).unwrap();
12}
13struct Case(PathBuf);
14impl Case {
15 fn new() -> Self {
16 let root = std::env::var_os("TMPDIR")
17 .map(PathBuf::from)
18 .unwrap_or_else(|| {
19 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp")
20 });
21 fs::create_dir_all(&root).unwrap();
22 let path = root.canonicalize().unwrap().join(format!(
23 "zipelo-7zc-{}-{}",
24 std::process::id(),
25 NEXT.fetch_add(1, Ordering::Relaxed)
26 ));
27 private_dir(&path);
28 private_dir(&path.join("tmp"));
29 Self(path)
30 }
31 fn path(&self, name: &str) -> NativePath {
32 NativePath::from_path(&self.0.join(name))
33 }
34 fn request(&self, names: &[&str]) -> Start {
35 Start {
36 action: Action::CreateSevenZip {
37 sources: names
38 .iter()
39 .map(|name| Source {
40 path: self.path(name),
41 archive_name: (*name).to_owned(),
42 })
43 .collect(),
44 output_file: self.path("result.7z"),
45 method: SevenZipMethod::Lzma2,
46 solid: false,
47 encryption: Encryption::None,
48 },
49 limits: Limits::default(),
50 }
51 }
52 fn command(&self) -> Command {
53 let mut cmd = Command::new(env!("CARGO_BIN_EXE_zipelo-archive-worker"));
54 cmd.env("TMPDIR", self.0.join("tmp"))
55 .env("TMP", self.0.join("tmp"))
56 .env("TEMP", self.0.join("tmp"));
57 cmd
58 }
59 fn run(&self, message: Message) -> Vec<Message> {
60 self.run_with(&mut self.command(), message, |_| Vec::new())
61 }
62 fn run_with(
63 &self,
64 command: &mut Command,
65 message: Message,
66 mut respond: impl FnMut(&Message) -> Vec<Message>,
67 ) -> Vec<Message> {
68 struct Running(Child);
69 impl Drop for Running {
70 fn drop(&mut self) {
71 let _ = self.0.kill();
72 let _ = self.0.wait();
73 }
74 }
75 let mut child = Running(
76 command
77 .stdin(Stdio::piped())
78 .stdout(Stdio::piped())
79 .stderr(Stdio::piped())
80 .spawn()
81 .unwrap(),
82 );
83 let mut writer = Writer::new(child.0.stdin.take().unwrap(), 17);
84 writer.send(&message).unwrap();
85 let stdout = child.0.stdout.take().unwrap();
86 let mut stderr = child.0.stderr.take().unwrap();
87 let diagnostic = std::thread::spawn(move || {
88 let mut bytes = Vec::new();
89 stderr.read_to_end(&mut bytes).unwrap();
90 bytes
91 });
92 let (send, receive) = mpsc::sync_channel(128);
93 let reader = std::thread::spawn(move || {
94 let mut reader = Reader::new(stdout);
95 loop {
96 let frame = reader.read();
97 let end = !matches!(frame, Ok(Some(_)));
98 if send.send(frame).is_err() || end {
99 break;
100 }
101 }
102 });
103 let mut events = Vec::new();
104 while let Some((job, _, event)) = receive
105 .recv_timeout(Duration::from_secs(120))
106 .expect("worker timeout")
107 .unwrap()
108 {
109 assert_eq!(job, 17);
110 for reply in respond(&event) {
111 writer.send(&reply).unwrap();
112 }
113 events.push(event);
114 }
115 drop(writer);
116 reader.join().unwrap();
117 assert!(child.0.wait().unwrap().success());
118 assert!(diagnostic.join().unwrap().is_empty());
119 assert!(matches!(events.last(), Some(Message::Terminal(_))));
120 assert_eq!(
121 events
122 .iter()
123 .filter(|e| matches!(e, Message::Terminal(_)))
124 .count(),
125 1
126 );
127 assert_eq!(fs::read_dir(self.0.join("tmp")).unwrap().count(), 0);
128 events
129 }
130 fn list(&self) -> Vec<Message> {
131 self.run(Message::Start(Start {
132 action: Action::List {
133 archive: self.path("result.7z"),
134 },
135 limits: Limits::default(),
136 }))
137 }
138 fn extract(&self, destination: &str) -> Vec<Message> {
139 private_dir(&self.0.join(destination));
140 self.run(Message::Start(Start {
141 action: Action::Extract {
142 archive: self.path("result.7z"),
143 destination: self.path(destination),
144 selection: Selection::All,
145 list_id: None,
146 gzip_output_name: None,
147 },
148 limits: Limits::default(),
149 }))
150 }
151}
152impl Drop for Case {
153 fn drop(&mut self) {
154 fs::remove_dir_all(&self.0).expect("7z 작성 시험 폴더 정리에 실패함");
155 }
156}
157fn success(events: &[Message]) {
158 let t = terminal(events);
159 assert_eq!(t.outcome, Outcome::Completed, "{events:?}");
160 assert_eq!(t.error, ErrorCode::None);
161 assert!(events.iter().any(|e| matches!(
162 e,
163 Message::Progress {
164 stage: Stage::Commit,
165 ..
166 }
167 )));
168 assert_eq!(t.publication, Publication::Complete);
169 assert_eq!(t.created_count, 1);
170 assert_eq!(t.retained_partial_count, 0);
171 assert_eq!(t.cleanup, Cleanup::Complete);
172 assert_eq!(
173 events
174 .iter()
175 .filter(|e| matches!(e, Message::Output { .. }))
176 .count(),
177 1
178 );
179 assert!(events.iter().any(|e| matches!(e, Message::Output { entry_id: None, relative_name, disposition: Disposition::Created } if relative_name == "result.7z")));
180 assert!(!events.iter().any(|e| matches!(
181 e,
182 Message::PasswordRequired { .. } | Message::ConflictRequired { .. }
183 )));
184}
185fn failure(events: &[Message], error: ErrorCode) {
186 let t = terminal(events);
187 assert_eq!(t.error, error, "{events:?}");
188 assert_eq!(
189 t.outcome,
190 if error == ErrorCode::None {
191 Outcome::Cancelled
192 } else {
193 Outcome::Failed
194 }
195 );
196 assert_eq!(t.publication, Publication::None);
197 assert_eq!(t.created_count, 0);
198 assert_eq!(t.retained_partial_count, 0);
199 assert_eq!(t.cleanup, Cleanup::Complete);
200 assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
201}
202fn tree(root: &std::path::Path) -> std::collections::BTreeMap<String, Option<[u8; 32]>> {
203 use sha2::{Digest, Sha256};
204 fn walk(
205 root: &std::path::Path,
206 at: &std::path::Path,
207 result: &mut std::collections::BTreeMap<String, Option<[u8; 32]>>,
208 ) {
209 for entry in fs::read_dir(at).unwrap() {
210 let path = entry.unwrap().path();
211 let name = path
212 .strip_prefix(root)
213 .unwrap()
214 .to_str()
215 .unwrap()
216 .replace('\\', "/");
217 if path.is_dir() {
218 result.insert(name, None);
219 walk(root, &path, result);
220 } else {
221 result.insert(name, Some(Sha256::digest(fs::read(path).unwrap()).into()));
222 }
223 }
224 }
225 let mut result = std::collections::BTreeMap::new();
226 walk(root, root, &mut result);
227 result
228}
229
230#[test]
231fn saving_outside_inside_and_nested_in_source_preserves_the_original_tree() {
232 for parent in ["", "source", "source/nested"] {
233 let c = Case::new();
234 private_dir(&c.0.join("source"));
235 private_dir(&c.0.join("source/nested"));
236 private_dir(&c.0.join("source/nested/empty"));
237 fs::write(c.0.join("source/한글.txt"), b"original").unwrap();
238 fs::write(c.0.join("source/nested/empty.txt"), b"").unwrap();
239 let expected = tree(&c.0.join("source"));
240 let archive = NativePath::from_path(&c.0.join(parent).join("result.7z"));
241 let mut request = c.request(&["source"]);
242 if let Action::CreateSevenZip { output_file, .. } = &mut request.action {
243 *output_file = archive.clone();
244 }
245 success(&c.run(Message::Start(request)));
246 let listed = c.run(Message::Start(Start {
247 action: Action::List {
248 archive: archive.clone(),
249 },
250 limits: Limits::default(),
251 }));
252 assert_eq!(terminal(&listed).outcome, Outcome::Completed, "{listed:?}");
253 private_dir(&c.0.join("decoded"));
254 let extracted = c.run(Message::Start(Start {
255 action: Action::Extract {
256 archive: archive.clone(),
257 destination: c.path("decoded"),
258 selection: Selection::All,
259 list_id: None,
260 gzip_output_name: None,
261 },
262 limits: Limits::default(),
263 }));
264 assert_eq!(
265 terminal(&extracted).outcome,
266 Outcome::Completed,
267 "{extracted:?}"
268 );
269 assert_eq!(tree(&c.0.join("decoded/source")), expected);
270 if let Some(tool) = std::env::var_os("ZIPELO_TEST_7ZIP") {
271 let output = Command::new(tool)
272 .args(["x", "-y"])
273 .arg(archive.to_path().unwrap())
274 .arg(format!("-o{}", c.0.join("independent").display()))
275 .output()
276 .unwrap();
277 assert!(output.status.success(), "{output:?}");
278 assert_eq!(tree(&c.0.join("independent/source")), expected);
279 }
280 assert!(
281 !tree(&c.0.join("source"))
282 .keys()
283 .any(|name| name.contains(".zipelo-"))
284 );
285 }
286}
287
288#[test]
289fn mixed_unicode_files_and_empty_bitmap_boundaries_round_trip() {
290 for count in [7, 8, 9] {
291 let c = Case::new();
292 fs::create_dir_all(c.0.join("원본/폴더/빈 폴더")).unwrap();
293 fs::write(c.0.join("원본/가.txt"), "한글 자료\n".repeat(1000)).unwrap();
294 fs::write(
295 c.0.join("원본/폴더/z"),
296 (0..131_081)
297 .map(|n| ((n * 73) % 251) as u8)
298 .collect::<Vec<_>>(),
299 )
300 .unwrap();
301 for index in 0..count - 3 {
302 fs::write(c.0.join(format!("원본/빈-{index}")), b"").unwrap();
303 }
304 fs::write(c.0.join("원본/\u{20000}.txt"), b"UTF-16 surrogate pair").unwrap();
305 let mut state = 0x1234_5678u32;
306 let noise: Vec<u8> = (0..131_081)
307 .map(|_| {
308 state ^= state << 13;
309 state ^= state >> 17;
310 state ^= state << 5;
311 state as u8
312 })
313 .collect();
314 fs::write(c.0.join("원본/noise.bin"), noise).unwrap();
315 let expected = tree(&c.0.join("원본"));
316 let events = c.run(Message::Start(c.request(&["원본"])));
317 success(&events);
318 assert!(matches!(
319 events[0],
320 Message::Accepted {
321 action: ActionKind::CreateSevenZip,
322 encryption: false
323 }
324 ));
325 let list = c.list();
326 assert_eq!(terminal(&list).outcome, Outcome::Completed, "{list:?}");
327 let extracted = c.extract("decoded");
328 assert_eq!(
329 terminal(&extracted).outcome,
330 Outcome::Completed,
331 "{extracted:?}"
332 );
333 assert_eq!(tree(&c.0.join("decoded/원본")), expected);
334 if let Some(tool) = std::env::var_os("ZIPELO_TEST_7ZIP") {
335 for operation in ["t", "l"] {
336 let output = Command::new(&tool)
337 .args([operation, "-slt"])
338 .arg(c.0.join("result.7z"))
339 .output()
340 .unwrap();
341 assert!(
342 output.status.success(),
343 "{}",
344 String::from_utf8_lossy(&output.stdout)
345 );
346 if operation == "l" {
347 let text = String::from_utf8_lossy(&output.stdout);
348 assert!(text.contains("Method = LZMA2:20"), "{text}");
349 assert!(text.contains("Solid = -"), "{text}");
350 assert!(!text.contains("Encrypted = +"));
351 }
352 }
353 let output = Command::new(tool)
354 .args(["x", "-y"])
355 .arg(c.0.join("result.7z"))
356 .arg(format!("-o{}", c.0.join("independent").display()))
357 .output()
358 .unwrap();
359 assert!(
360 output.status.success(),
361 "{}",
362 String::from_utf8_lossy(&output.stdout)
363 );
364 assert_eq!(tree(&c.0.join("independent/원본")), expected);
365 }
366 }
367}
368
369#[test]
370fn archives_with_only_empty_files_and_directories_are_valid() {
371 for directory in [false, true] {
372 let c = Case::new();
373 if directory {
374 fs::create_dir_all(c.0.join("empty/nested")).unwrap();
375 } else {
376 fs::write(c.0.join("empty"), b"").unwrap();
377 }
378 success(&c.run(Message::Start(c.request(&["empty"]))));
379 let extracted = c.extract("decoded");
380 assert_eq!(
381 terminal(&extracted).outcome,
382 Outcome::Completed,
383 "{extracted:?}"
384 );
385 assert_eq!(c.0.join("decoded/empty").is_dir(), directory);
386 if let Some(tool) = std::env::var_os("ZIPELO_TEST_7ZIP") {
387 assert!(
388 Command::new(tool)
389 .arg("t")
390 .arg(c.0.join("result.7z"))
391 .output()
392 .unwrap()
393 .status
394 .success()
395 );
396 }
397 }
398}
399
400#[test]
401fn existing_output_empty_sources_limits_and_links_are_rejected() {
402 let c = Case::new();
403 fs::write(c.0.join("source"), b"abcdef").unwrap();
404 fs::write(c.0.join("result.7z"), b"preserve").unwrap();
405 failure(
406 &c.run(Message::Start(c.request(&["source"]))),
407 ErrorCode::Conflict,
408 );
409 assert_eq!(fs::read(c.0.join("result.7z")).unwrap(), b"preserve");
410 fs::remove_file(c.0.join("result.7z")).unwrap();
411 failure(
412 &c.run(Message::Start(c.request(&[]))),
413 ErrorCode::InvalidRequest,
414 );
415 for bytes in [5, 6, 7] {
416 let mut start = c.request(&["source"]);
417 start.limits.input = bytes;
418 start.limits.output = bytes;
419 let events = c.run(Message::Start(start));
420 if bytes == 5 {
421 failure(&events, ErrorCode::Limit);
422 } else {
423 success(&events);
424 fs::remove_file(c.0.join("result.7z")).unwrap();
425 }
426 }
427 #[cfg(unix)]
428 {
429 std::os::unix::fs::symlink(c.0.join("source"), c.0.join("link")).unwrap();
430 failure(
431 &c.run(Message::Start(c.request(&["link"]))),
432 ErrorCode::UnsafePath,
433 );
434 }
435 assert!(!c.0.join("result.7z").exists());
436}
437
438#[test]
439fn guarded_approval_decline_and_cancel_preserve_creation_rules() {
440 let c = Case::new();
441 fs::write(c.0.join("source"), b"abcdef").unwrap();
442 for allow in [false, true] {
443 let mut start = c.request(&["source"]);
444 start.limits.output = 5;
445 let message = Message::StartGuarded(GuardedStart {
446 ceiling: Limits {
447 output: 6,
448 ..start.limits
449 },
450 start,
451 interactive: false,
452 });
453 let mut questions = 0;
454 let events = c.run_with(&mut c.command(), message, |event| {
455 if let Message::ResourceRequired {
456 challenge_id,
457 action,
458 scope,
459 ..
460 } = event
461 {
462 assert_eq!(*action, ActionKind::CreateSevenZip);
463 questions += 1;
464 vec![Message::ResourceReply {
465 challenge_id: *challenge_id,
466 scope: *scope,
467 allow,
468 }]
469 } else {
470 Vec::new()
471 }
472 });
473 assert_eq!(questions, 1);
474 if allow {
475 success(&events);
476 fs::remove_file(c.0.join("result.7z")).unwrap();
477 } else {
478 failure(&events, ErrorCode::None);
479 assert!(!c.0.join("result.7z").exists());
480 }
481 }
482}
483
484#[test]
485fn cancel_during_snapshot_or_encoding_publishes_nothing() {
486 for stage in [Stage::Read, Stage::Write] {
487 let c = Case::new();
488 fs::File::create(c.0.join("source"))
489 .unwrap()
490 .set_len(128 * 1024 * 1024)
491 .unwrap();
492 let mut sent = false;
493 let events = c.run_with(
494 &mut c.command(),
495 Message::Start(c.request(&["source"])),
496 |event| {
497 if !sent
498 && matches!(event, Message::Progress { stage: actual, processed_bytes, .. } if *actual == stage && (stage == Stage::Read || *processed_bytes > 0))
499 {
500 sent = true;
501 vec![Message::Cancel]
502 } else {
503 Vec::new()
504 }
505 },
506 );
507 assert!(sent);
508 failure(&events, ErrorCode::None);
509 assert!(!c.0.join("result.7z").exists());
510 assert!(events.iter().any(|e| matches!(
511 e,
512 Message::CancelAck {
513 status: CancelStatus::Requested,
514 ..
515 }
516 )));
517 }
518}
519
520#[cfg(target_os = "linux")]
521fn shim(c: &Case, file: &str) -> PathBuf {
522 let output = c.0.join("fault.so");
523 let status = Command::new("cc")
524 .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
525 .arg(
526 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
527 .join("../../tests/rust-archive-worker")
528 .join(file),
529 )
530 .args(["-ldl", "-o"])
531 .arg(&output)
532 .status()
533 .unwrap();
534 assert!(status.success());
535 output
536}
537
538#[cfg(target_os = "linux")]
539#[test]
540fn storage_failures_keep_real_publication_and_cleanup_state() {
541 for fault in [
542 "temp-full",
543 "space-stage",
544 "create-full",
545 "create-denied",
546 "full",
547 "write-io",
548 "sync-full",
549 "dir-sync-full",
550 ] {
551 let c = Case::new();
552 fs::write(c.0.join("source"), b"a".repeat(100_000)).unwrap();
553 let mut command = c.command();
554 command
555 .env("LD_PRELOAD", shim(&c, "io_fault.c"))
556 .env("ZIPELO_TEST_FAULT", fault)
557 .env("ZIPELO_TEST_MARKER", c.0.join("marker"));
558 let events = c.run_with(&mut command, Message::Start(c.request(&["source"])), |_| {
559 Vec::new()
560 });
561 let error = if matches!(fault, "create-denied" | "write-io") {
562 ErrorCode::Io
563 } else {
564 ErrorCode::DiskFull
565 };
566 if fault == "dir-sync-full" {
567 let t = terminal(&events);
568 assert_eq!(t.error, error, "{events:?}");
569 assert_eq!(t.outcome, Outcome::Failed);
570 assert_eq!(t.created_count, 1);
571 assert_eq!(t.durability, Durability::Failed);
572 assert!(c.0.join("result.7z").is_file());
573 } else {
574 failure(&events, error);
575 assert!(!c.0.join("result.7z").exists());
576 }
577 assert!(!fs::read_dir(&c.0).unwrap().any(|entry| {
578 entry
579 .unwrap()
580 .file_name()
581 .to_string_lossy()
582 .starts_with(".zipelo-")
583 }));
584 }
585}
586
587#[cfg(target_os = "linux")]
588#[test]
589fn source_changes_new_destination_and_cancel_before_publication_are_preserved() {
590 for operation in ["source", "destination", "cancel"] {
591 let c = Case::new();
592 fs::write(c.0.join("source"), b"a".repeat(100_000)).unwrap();
593 let marker = c.0.join("marker");
594 let release = c.0.join("release");
595 let mut command = c.command();
596 command
597 .env("LD_PRELOAD", shim(&c, "io_fault.c"))
598 .env("ZIPELO_TEST_FAULT", "pause")
599 .env("ZIPELO_TEST_MARKER", &marker)
600 .env("ZIPELO_TEST_RELEASE", &release);
601 let mut changed = false;
602 let events = c.run_with(
603 &mut command,
604 Message::Start(c.request(&["source"])),
605 |event| {
606 if !changed
607 && matches!(
608 event,
609 Message::Progress {
610 stage: Stage::Write,
611 total_bytes: Some(_),
612 ..
613 }
614 )
615 {
616 let until = std::time::Instant::now() + Duration::from_secs(5);
617 while !marker.exists() {
618 assert!(std::time::Instant::now() < until);
619 std::thread::sleep(Duration::from_millis(2));
620 }
621 match operation {
622 "source" => fs::write(c.0.join("source"), b"changed").unwrap(),
623 "destination" => fs::write(c.0.join("result.7z"), b"user data").unwrap(),
624 _ => {}
625 }
626 changed = true;
627 let replies = if operation == "cancel" {
628 vec![Message::Cancel]
629 } else {
630 Vec::new()
631 };
632 fs::write(&release, b"resume").unwrap();
633 replies
634 } else {
635 Vec::new()
636 }
637 },
638 );
639 assert!(changed);
640 failure(
641 &events,
642 match operation {
643 "source" => ErrorCode::SourceChanged,
644 "destination" => ErrorCode::Conflict,
645 _ => ErrorCode::None,
646 },
647 );
648 if operation == "destination" {
649 assert_eq!(fs::read(c.0.join("result.7z")).unwrap(), b"user data");
650 } else {
651 assert!(!c.0.join("result.7z").exists());
652 }
653 }
654}
655
656#[cfg(target_os = "linux")]
657#[test]
658fn internal_destination_still_rejects_real_source_changes_and_cancellation() {
659 for parent in ["source", "source/nested"] {
660 for operation in [
661 "add",
662 "foreign-temp",
663 "remove",
664 "rename",
665 "modify",
666 "replace-dir",
667 "cancel",
668 ] {
669 let c = Case::new();
670 private_dir(&c.0.join("source"));
671 private_dir(&c.0.join("source/nested"));
672 let directory = c.0.join(parent);
673 private_dir(&directory.join("empty"));
674 fs::write(directory.join("file"), b"a".repeat(100_000)).unwrap();
675 let mut request = c.request(&["source"]);
676 if let Action::CreateSevenZip { output_file, .. } = &mut request.action {
677 *output_file = NativePath::from_path(&directory.join("result.7z"));
678 }
679 let marker = c.0.join("marker");
680 let release = c.0.join("release");
681 let mut command = c.command();
682 command
683 .env("LD_PRELOAD", shim(&c, "io_fault.c"))
684 .env("ZIPELO_TEST_FAULT", "pause")
685 .env("ZIPELO_TEST_MARKER", &marker)
686 .env("ZIPELO_TEST_RELEASE", &release);
687 let mut changed = false;
688 let events = c.run_with(&mut command, Message::Start(request), |event| {
689 if changed
690 || !matches!(
691 event,
692 Message::Progress {
693 stage: Stage::Write,
694 total_bytes: Some(_),
695 ..
696 }
697 )
698 {
699 return Vec::new();
700 }
701 let until = std::time::Instant::now() + Duration::from_secs(5);
702 while !marker.exists() {
703 assert!(std::time::Instant::now() < until);
704 std::thread::sleep(Duration::from_millis(2));
705 }
706 match operation {
707 "add" => fs::write(directory.join("new-file"), b"user addition").unwrap(),
708 "foreign-temp" => {
709 fs::write(directory.join(".zipelo-user.tmp"), b"user file").unwrap()
710 }
711 "remove" => fs::remove_file(directory.join("file")).unwrap(),
712 "rename" => {
713 fs::rename(directory.join("file"), directory.join("renamed")).unwrap()
714 }
715 "modify" => fs::write(directory.join("file"), b"user modification").unwrap(),
716 "replace-dir" => {
717 fs::rename(directory.join("empty"), c.0.join("old-empty")).unwrap();
718 private_dir(&directory.join("empty"));
719 }
720 _ => {}
721 }
722 changed = true;
723 fs::write(&release, b"resume").unwrap();
724 if operation == "cancel" {
725 vec![Message::Cancel]
726 } else {
727 Vec::new()
728 }
729 });
730 assert!(changed);
731 failure(
732 &events,
733 if operation == "cancel" {
734 ErrorCode::None
735 } else {
736 ErrorCode::SourceChanged
737 },
738 );
739 assert!(!directory.join("result.7z").exists());
740 let expected_temp = if operation == "foreign-temp" { 1 } else { 0 };
741 assert_eq!(
742 fs::read_dir(&directory)
743 .unwrap()
744 .filter(|entry| {
745 entry
746 .as_ref()
747 .unwrap()
748 .file_name()
749 .to_string_lossy()
750 .starts_with(".zipelo-")
751 })
752 .count(),
753 expected_temp
754 );
755 if operation == "foreign-temp" {
756 assert_eq!(
757 fs::read(directory.join(".zipelo-user.tmp")).unwrap(),
758 b"user file"
759 );
760 }
761 if operation == "modify" {
762 assert_eq!(
763 fs::read(directory.join("file")).unwrap(),
764 b"user modification"
765 );
766 }
767 }
768 }
769}
770
771#[cfg(target_os = "linux")]
772#[test]
773fn internal_destination_write_failures_clean_only_the_owned_temporary() {
774 for fault in ["full", "sync-full"] {
775 let c = Case::new();
776 private_dir(&c.0.join("source"));
777 fs::write(c.0.join("source/file"), b"original").unwrap();
778 fs::write(c.0.join("source/.zipelo-user.tmp"), b"keep").unwrap();
779 let expected = tree(&c.0.join("source"));
780 let mut request = c.request(&["source"]);
781 if let Action::CreateSevenZip { output_file, .. } = &mut request.action {
782 *output_file = c.path("source/result.7z");
783 }
784 let mut command = c.command();
785 command
786 .env("LD_PRELOAD", shim(&c, "io_fault.c"))
787 .env("ZIPELO_TEST_FAULT", fault);
788 failure(
789 &c.run_with(&mut command, Message::Start(request), |_| Vec::new()),
790 ErrorCode::DiskFull,
791 );
792 assert_eq!(tree(&c.0.join("source")), expected);
793 }
794}
795
796#[cfg(target_os = "linux")]
797#[test]
798fn encoder_finish_header_write_seek_and_patch_errors_publish_nothing() {
799 for fault in [
800 "encode-full",
801 "finish-full",
802 "header-write",
803 "header-seek",
804 "header-patch",
805 ] {
806 let c = Case::new();
807 fs::write(
808 c.0.join("source"),
809 b"x".repeat(if fault == "encode-full" {
810 3 * 1024 * 1024
811 } else {
812 123
813 }),
814 )
815 .unwrap();
816 let mut command = c.command();
817 command
818 .env("LD_PRELOAD", shim(&c, "seven_zip_create_fault.c"))
819 .env("ZIPELO_7Z_FAULT", fault);
820 let events = c.run_with(&mut command, Message::Start(c.request(&["source"])), |_| {
821 Vec::new()
822 });
823 failure(
824 &events,
825 if fault.ends_with("full") {
826 ErrorCode::DiskFull
827 } else {
828 ErrorCode::Io
829 },
830 );
831 assert!(!c.0.join("result.7z").exists());
832 }
833}
834
835#[cfg(target_os = "linux")]
836#[test]
837fn gigabyte_creation_stays_below_64_mib_peak_rss() {
838 assert!(
839 Command::new("python3")
840 .arg(
841 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
842 .join("../../tests/rust-archive-worker/seven_zip_create_memory.py")
843 )
844 .arg(env!("CARGO_BIN_EXE_zipelo-archive-worker"))
845 .status()
846 .unwrap()
847 .success()
848 );
849}