team-ljyzipelo

공개
1,349줄48 KB
1use super::*;
2use std::{
3 collections::BTreeSet,
4 fs,
5 sync::atomic::{AtomicU64, Ordering},
6};
7use zipelo_ui_memory_app::archive_present::*;
8
9fn terminal() -> Terminal {
10 Terminal {
11 outcome: Outcome::Failed,
12 error: Some(ErrorCode::Io),
13 publication: Publication::Partial,
14 created_count: 1,
15 retained_partial_count: 0,
16 durability: Durability::Synced,
17 cleanup: Cleanup::Complete,
18 }
19}
20fn targets() -> BTreeSet<String> {
21 ["one.txt".into(), "two.txt".into()].into_iter().collect()
22}
23
24#[test]
25fn partial_extraction_requires_matching_file_reports() {
26 let t = terminal();
27 assert_eq!(
28 warnings(
29 Some(&t),
30 true,
31 Some(&targets()),
32 &BTreeSet::new(),
33 &[("one.txt".into(), Disposition::Created)]
34 ),
35 vec![PARTIAL]
36 );
37}
38#[test]
39fn all_saved_with_temporary_leftover_is_not_partial_extraction() {
40 let mut t = terminal();
41 t.retained_partial_count = 1;
42 t.cleanup = Cleanup::Failed;
43 let files = ["one.txt".into()].into_iter().collect();
44 assert_eq!(
45 warnings(
46 Some(&t),
47 true,
48 Some(&files),
49 &BTreeSet::new(),
50 &[
51 ("one.txt".into(), Disposition::Created),
52 ("temp".into(), Disposition::PartialRetained)
53 ]
54 ),
55 vec![LEFTOVERS]
56 );
57}
58#[test]
59fn leftover_without_file_reports_and_commit_uncertainty_are_unknown() {
60 let mut t = terminal();
61 t.created_count = 0;
62 t.retained_partial_count = 1;
63 for outputs in [
64 vec![("temp".into(), Disposition::PartialRetained)],
65 vec![("one.txt".into(), Disposition::CommitUncertain)],
66 ] {
67 assert!(
68 warnings(Some(&t), true, Some(&targets()), &BTreeSet::new(), &outputs)
69 .contains(&UNCERTAIN)
70 );
71 assert!(
72 !warnings(Some(&t), true, Some(&targets()), &BTreeSet::new(), &outputs)
73 .contains(&PARTIAL)
74 );
75 }
76}
77#[test]
78fn synchronization_and_cleanup_warnings_are_both_visible() {
79 let mut t = terminal();
80 t.created_count = 0;
81 t.durability = Durability::Unconfirmed;
82 t.cleanup = Cleanup::Failed;
83 let result = warnings(Some(&t), true, Some(&targets()), &BTreeSet::new(), &[]);
84 assert!(result.contains(&SYNC_WARNING));
85 assert!(result.contains(&CLEANUP_WARNING));
86}
87#[test]
88fn missing_terminal_exit_or_contradictory_reports_never_claim_unsaved() {
89 let mut t = terminal();
90 t.publication = Publication::None;
91 t.created_count = 0;
92 assert!(definitely_unsaved(Some(&t), true, &[]));
93 assert!(!definitely_unsaved(None, true, &[]));
94 assert!(!definitely_unsaved(Some(&t), false, &[]));
95 let reports = [("one.txt".into(), Disposition::Created)];
96 assert!(!definitely_unsaved(Some(&t), true, &reports));
97 assert!(
98 warnings(Some(&t), true, Some(&targets()), &BTreeSet::new(), &reports).contains(&UNCERTAIN)
99 );
100}
101#[test]
102fn unsafe_path_and_conflict_preserve_result_classification() {
103 for code in [ErrorCode::UnsafePath, ErrorCode::Conflict] {
104 let mut t = terminal();
105 t.error = Some(code);
106 assert_eq!(
107 warnings(
108 Some(&t),
109 true,
110 Some(&targets()),
111 &BTreeSet::new(),
112 &[("one.txt".into(), Disposition::Created)]
113 ),
114 vec![PARTIAL]
115 );
116 t.publication = Publication::Uncertain;
117 assert!(
118 warnings(Some(&t), true, Some(&targets()), &BTreeSet::new(), &[]).contains(&UNCERTAIN)
119 );
120 t.publication = Publication::None;
121 t.created_count = 0;
122 assert!(definitely_unsaved(Some(&t), true, &[]));
123 }
124}
125#[test]
126fn every_error_and_stage_has_user_facing_text() {
127 for code in [
128 ErrorCode::Integrity,
129 ErrorCode::UnsupportedFormat,
130 ErrorCode::UnsupportedFeature,
131 ErrorCode::WrongPassword,
132 ErrorCode::UnsafePath,
133 ErrorCode::Conflict,
134 ErrorCode::Limit,
135 ErrorCode::Io,
136 ErrorCode::DiskFull,
137 ErrorCode::Protocol,
138 ErrorCode::Internal,
139 ErrorCode::SourceChanged,
140 ErrorCode::InvalidRequest,
141 ] {
142 assert!(!error_text(code).is_empty());
143 assert!(!error_text(code).contains("작업자"));
144 }
145 assert_eq!(error_text(ErrorCode::Protocol), INTERNAL);
146 assert_eq!(error_text(ErrorCode::Internal), INTERNAL);
147 assert_eq!(progress_text(Stage::Decode, true), "압축하는 중");
148 assert_eq!(progress_text(Stage::Decode, false), "압축을 푸는 중");
149}
150#[test]
151fn file_targets_follow_requested_ids_without_expanding_directories() {
152 let entries = vec![
153 Entry {
154 id: 0,
155 name: "docs".into(),
156 kind: Kind::Directory,
157 bytes: None,
158 packed: None,
159 encrypted: false,
160 },
161 Entry {
162 id: 1,
163 name: "docs/one.txt".into(),
164 kind: Kind::File,
165 bytes: None,
166 packed: None,
167 encrypted: false,
168 },
169 Entry {
170 id: 2,
171 name: "docs-old/two.txt".into(),
172 kind: Kind::File,
173 bytes: None,
174 packed: None,
175 encrypted: false,
176 },
177 ];
178 assert_eq!(
179 target_files(&entries, &Selection::EntryIds(vec![0]), None),
180 Some(BTreeSet::new())
181 );
182 assert_eq!(
183 target_files(&entries, &Selection::EntryIds(vec![0, 2]), None),
184 Some(["docs-old/two.txt".into()].into_iter().collect())
185 );
186 assert_eq!(
187 target_files(&entries, &Selection::EntryIds(vec![1]), None),
188 Some(["docs/one.txt".into()].into_iter().collect())
189 );
190 assert_eq!(
191 target_files(&entries, &Selection::All, None),
192 Some(
193 ["docs/one.txt".into(), "docs-old/two.txt".into()]
194 .into_iter()
195 .collect()
196 )
197 );
198}
199
200#[test]
201fn directory_reports_allow_empty_and_mixed_archives_without_hiding_unknown_outputs() {
202 let directories = ["parent".into(), "parent/empty".into()]
203 .into_iter()
204 .collect();
205 let empty = BTreeSet::new();
206 let mut t = terminal();
207 t.outcome = Outcome::Completed;
208 t.error = None;
209 t.publication = Publication::Complete;
210 t.created_count = 2;
211 let reports = [
212 ("parent".into(), Disposition::Created),
213 ("parent/empty".into(), Disposition::Created),
214 ];
215 assert!(warnings(Some(&t), true, Some(&empty), &directories, &reports).is_empty());
216 t.created_count = 0;
217 assert!(warnings(Some(&t), true, Some(&empty), &directories, &[]).is_empty());
218 let files = ["parent/file.txt".into()].into_iter().collect();
219 t.created_count = 2;
220 let reports = [
221 ("parent".into(), Disposition::Created),
222 ("parent/file.txt".into(), Disposition::Created),
223 ];
224 assert!(warnings(Some(&t), true, Some(&files), &directories, &reports).is_empty());
225 t.created_count = 1;
226 assert!(
227 warnings(
228 Some(&t),
229 true,
230 Some(&files),
231 &directories,
232 &[("parent".into(), Disposition::Created)]
233 )
234 .contains(&UNCERTAIN)
235 );
236 assert!(
237 warnings(
238 Some(&t),
239 true,
240 Some(&empty),
241 &directories,
242 &[("unknown".into(), Disposition::Created)]
243 )
244 .contains(&UNCERTAIN)
245 );
246 t.publication = Publication::Uncertain;
247 assert!(
248 warnings(
249 Some(&t),
250 true,
251 Some(&empty),
252 &directories,
253 &[("parent".into(), Disposition::CommitUncertain)]
254 )
255 .contains(&UNCERTAIN)
256 );
257}
258
259#[test]
260fn directory_targets_include_selected_members_and_implicit_parents() {
261 let entries = [
262 Entry {
263 id: 0,
264 name: "top".into(),
265 kind: Kind::Directory,
266 bytes: None,
267 packed: None,
268 encrypted: false,
269 },
270 Entry {
271 id: 1,
272 name: "top/empty".into(),
273 kind: Kind::Directory,
274 bytes: None,
275 packed: None,
276 encrypted: false,
277 },
278 Entry {
279 id: 2,
280 name: "top/nested/file.txt".into(),
281 kind: Kind::File,
282 bytes: None,
283 packed: None,
284 encrypted: false,
285 },
286 Entry {
287 id: 3,
288 name: "other/empty".into(),
289 kind: Kind::Directory,
290 bytes: None,
291 packed: None,
292 encrypted: false,
293 },
294 ];
295 assert_eq!(
296 target_directories(&entries, &Selection::EntryIds(vec![0])),
297 ["top".into()].into_iter().collect()
298 );
299 assert_eq!(
300 target_directories(&entries, &Selection::EntryIds(vec![2])),
301 ["top".into(), "top/nested".into()].into_iter().collect()
302 );
303}
304
305#[test]
306fn duplicate_names_prevent_file_completion_assumptions() {
307 let entry = Entry {
308 id: 0,
309 name: "same.txt".into(),
310 kind: Kind::File,
311 bytes: None,
312 packed: None,
313 encrypted: false,
314 };
315 assert!(target_files(&[entry.clone(), entry], &Selection::All, None).is_none());
316 assert_eq!(
317 warnings(Some(&terminal()), true, None, &BTreeSet::new(), &[]),
318 vec![UNCERTAIN]
319 );
320}
321#[test]
322fn default_names_and_middle_truncation_preserve_unicode() {
323 for name in [
324 "자료.tar.gz",
325 "자료.tar.bz2",
326 "자료.TAR.BZ2",
327 "자료.TaR.xZ",
328 "자료.tar.xz",
329 ] {
330 assert_eq!(default_destination(&path(name)), path("자료"));
331 }
332 for name in [".tar.bz2", ".TAR.XZ"] {
333 assert_eq!(default_destination(&path(name)), path("압축 해제"));
334 }
335 assert_eq!(default_destination(&path("자료.zip")), path("자료"));
336 assert!(blocked_open("폴더/setup.EXE"));
337 // desktop 항목은 Linux 차단 목록에만 있음.
338 #[cfg(not(windows))]
339 assert!(blocked_open("run.desktop"));
340 assert!(!blocked_open("사진.jpg"));
341 assert!(!blocked_open("exe"));
342 // Linux는 스크립트를 편집기로 열므로 막지 않음.
343 #[cfg(not(windows))]
344 assert!(!blocked_open("app.js"));
345 #[cfg(windows)]
346 assert!(blocked_open("app.js"));
347 assert_eq!(
348 open_blocked_text("폴더/setup.EXE"),
349 "실행 파일(.EXE)은 안전을 위해 바로 열 수 없습니다"
350 );
351 assert_eq!(middle_text("가나다라마바사아자차", 7), "가나다…아자차");
352 assert_eq!(bytes_text(21), "21 B");
353}
354
355static SCRATCH_ID: AtomicU64 = AtomicU64::new(0);
356pub(super) struct Folder(pub(super) PathBuf);
357impl Folder {
358 pub(super) fn new() -> Self {
359 let root = PathBuf::from(std::env::var_os("ZIPELO_TEST_WORK_DIR").expect("runner 작업 경로 필요")).join("fixtures/rust-app-ui");
360 fs::create_dir_all(&root).unwrap();
361 let path = root.join(format!(
362 "presentation-{}-{}",
363 std::process::id(),
364 SCRATCH_ID.fetch_add(1, Ordering::Relaxed)
365 ));
366 fs::create_dir(&path).unwrap();
367 Self(path.canonicalize().unwrap())
368 }
369}
370impl Drop for Folder {
371 fn drop(&mut self) {
372 fs::remove_dir_all(&self.0).unwrap();
373 }
374}
375
376#[test]
377fn unique_folder_numbers_existing_names() {
378 let scratch = Folder::new();
379 let base = scratch.0.join("자료");
380 assert_eq!(unique_folder(&base), base);
381 fs::create_dir(&base).unwrap();
382 assert_eq!(unique_folder(&base), scratch.0.join("자료 (1)"));
383 fs::write(scratch.0.join("자료 (1)"), b"").unwrap();
384 assert_eq!(unique_folder(&base), scratch.0.join("자료 (2)"));
385}
386
387#[test]
388fn automatic_destination_creation_and_failure_are_distinct() {
389 let scratch = Folder::new();
390 let output = scratch.0.join("output");
391 assert!(prepare_destination(&output, true).unwrap());
392 assert!(!prepare_destination(&output, true).unwrap());
393 assert!(prepare_destination(&scratch.0.join("missing/child"), true).is_err());
394 assert!(prepare_destination(&scratch.0.join("chosen-missing"), false).is_err());
395 let file = scratch.0.join("file");
396 fs::write(&file, "existing").unwrap();
397 assert!(prepare_destination(&file, true).is_err());
398 assert_eq!(fs::read_to_string(file).unwrap(), "existing");
399}
400#[test]
401fn only_new_empty_output_is_removed_and_nonempty_is_preserved() {
402 let scratch = Folder::new();
403 let empty = scratch.0.join("empty");
404 assert!(prepare_destination(&empty, true).unwrap());
405 remove_owned_empty(&empty);
406 assert!(!empty.exists());
407 let nonempty = scratch.0.join("nonempty");
408 assert!(prepare_destination(&nonempty, true).unwrap());
409 fs::write(nonempty.join("existing"), "keep").unwrap();
410 remove_owned_empty(&nonempty);
411 assert_eq!(
412 fs::read_to_string(nonempty.join("existing")).unwrap(),
413 "keep"
414 );
415 assert!(!prepare_destination(&scratch.0, false).unwrap());
416 assert!(scratch.0.is_dir());
417}
418#[cfg(unix)]
419#[test]
420fn browser_and_output_do_not_follow_symbolic_links() {
421 let scratch = Folder::new();
422 let link = scratch.0.join("link");
423 std::os::unix::fs::symlink(&scratch.0, &link).unwrap();
424 let rows = directory_entries(&scratch.0).unwrap();
425 assert!(rows.iter().any(|entry| entry.link && entry.path == link));
426 assert!(directory_entries(&link).is_err());
427 assert!(prepare_destination(&link, true).is_err());
428}
429
430#[cfg(feature = "ui")]
431mod widgets {
432 use super::*;
433 use crate::dialogs::TestDialogs;
434 use eframe::egui::{self, epaint::Shape};
435 use zipelo_ui_memory_app::{archive_dialog::Purpose, archive_screen::ArchiveApp};
436
437 fn labels(shapes: &[egui::epaint::ClippedShape]) -> Vec<(String, egui::Pos2)> {
438 fn walk(shape: &Shape, result: &mut Vec<(String, egui::Pos2)>) {
439 match shape {
440 Shape::Text(text) => result.push((
441 text.galley.job.text.clone(),
442 text.pos + text.galley.rect.size() / 2.0,
443 )),
444 Shape::Vec(shapes) => {
445 for shape in shapes {
446 walk(shape, result);
447 }
448 }
449 _ => {}
450 }
451 }
452 let mut result = Vec::new();
453 for shape in shapes {
454 walk(&shape.shape, &mut result);
455 }
456 result
457 }
458
459 fn render(
460 ctx: &egui::Context,
461 app: &mut ArchiveApp,
462 events: Vec<egui::Event>,
463 ) -> Vec<(String, egui::Pos2)> {
464 let mut output = ctx.run_ui(
465 egui::RawInput {
466 screen_rect: Some(egui::Rect::from_min_size(
467 egui::Pos2::ZERO,
468 egui::vec2(760.0, 540.0),
469 )),
470 events,
471 ..Default::default()
472 },
473 |ui| app.show(ui),
474 );
475 output.textures_delta.clear();
476 labels(&output.shapes)
477 }
478
479 fn click(ctx: &egui::Context, app: &mut ArchiveApp, label: &str) {
480 render(ctx, app, vec![]);
481 let point = render(ctx, app, vec![])
482 .into_iter()
483 .filter(|(text, _)| text == label)
484 .max_by(|a, b| a.1.y.total_cmp(&b.1.y))
485 .unwrap_or_else(|| panic!("항목 없음: {label}"))
486 .1;
487 for pressed in [true, false] {
488 render(
489 ctx,
490 app,
491 vec![
492 egui::Event::PointerMoved(point),
493 egui::Event::PointerButton {
494 pos: point,
495 button: egui::PointerButton::Primary,
496 pressed,
497 modifiers: egui::Modifiers::NONE,
498 },
499 ],
500 );
501 }
502 }
503
504 fn key(key: egui::Key) -> egui::Event {
505 egui::Event::Key {
506 key,
507 physical_key: None,
508 pressed: true,
509 repeat: false,
510 modifiers: egui::Modifiers::NONE,
511 }
512 }
513
514 fn text(ctx: &egui::Context, app: &mut ArchiveApp, id: &str, value: &str) {
515 ctx.memory_mut(|memory| memory.request_focus(egui::Id::unique(id)));
516 render(
517 ctx,
518 app,
519 vec![
520 egui::Event::Key {
521 key: egui::Key::A,
522 physical_key: None,
523 pressed: true,
524 repeat: false,
525 modifiers: egui::Modifiers::COMMAND,
526 },
527 egui::Event::Text(value.into()),
528 ],
529 );
530 }
531
532 #[test]
533 fn recovery_save_uses_native_dialog_and_partial_copy_keeps_warning_when_opened() {
534 let scratch = Folder::new();
535 let factory = FakeFactory::manual();
536 let archive = scratch.0.join("손상.zip");
537 let output = scratch.0.join("복구본.zip");
538 let mut app = ArchiveApp::new(Box::new(factory.clone()), Some(archive.clone()), false);
539 {
540 let mut state = factory.state.borrow_mut();
541 state.frame(Event::Accepted { encryption: false });
542 state.frame(Event::Terminal(Terminal {
543 outcome: Outcome::Failed,
544 error: Some(ErrorCode::Integrity),
545 publication: Publication::None,
546 created_count: 0,
547 retained_partial_count: 0,
548 durability: Durability::NotApplicable,
549 cleanup: Cleanup::Complete,
550 }));
551 state.queue.extend([
552 HostEvent::StdoutEof,
553 HostEvent::StderrEof,
554 HostEvent::Exited { success: true },
555 ]);
556 }
557 pump(&mut app.model);
558 let dialogs = TestDialogs::default();
559 dialogs
560 .0
561 .borrow_mut()
562 .answers
563 .push_back(Some(vec![output.clone()]));
564 app.set_dialogs(Box::new(dialogs.clone()));
565 let ctx = egui::Context::default();
566 click(&ctx, &mut app, "복구본 저장 위치 선택");
567 assert_eq!(
568 dialogs.0.borrow().requests[0].purpose,
569 Purpose::SaveRecoveryZip
570 );
571 assert_eq!(
572 dialogs.0.borrow().requests[0].file_name,
573 "손상-recovered.zip"
574 );
575 assert!(
576 matches!(factory.state.borrow().starts.last(), Some(Start::RecoverZip { archive: actual, output_file }) if actual == &archive && output_file == &output)
577 );
578 {
579 let mut state = factory.state.borrow_mut();
580 state.frame(Event::Accepted { encryption: false });
581 state.frame(Event::RecoveryEntry(RecoveryEntry {
582 candidate_id: 0,
583 source_offset: 0,
584 name: Some("내용.txt".into()),
585 kind: Some(worker_protocol::protocol::EntryKind::File),
586 status: RecoveryStatus::Verified,
587 reason: RecoveryReason::MetadataMissing,
588 declared_size: Some(0),
589 verified_size: Some(0),
590 sha256: Some([1; 32]),
591 }));
592 state.frame(Event::RecoveryEnd(RecoveryEnd {
593 mode: RecoveryMode::LocalChain,
594 source_bytes: 128,
595 source_sha256: [2; 32],
596 known_entries: None,
597 verified_entries: 1,
598 lost_entries: 0,
599 unverified_entries: 0,
600 unknown_loss: true,
601 }));
602 state.frame(Event::Output {
603 entry_id: None,
604 relative_name: "복구본.zip".into(),
605 disposition: Disposition::Created,
606 });
607 state.frame(Event::Terminal(Terminal {
608 outcome: Outcome::Failed,
609 error: Some(ErrorCode::RecoveryIncomplete),
610 publication: Publication::Complete,
611 created_count: 1,
612 retained_partial_count: 0,
613 durability: Durability::Synced,
614 cleanup: Cleanup::Complete,
615 }));
616 state.queue.extend([
617 HostEvent::StdoutEof,
618 HostEvent::StderrEof,
619 HostEvent::Exited { success: true },
620 ]);
621 }
622 pump(&mut app.model);
623 assert!(app.model.confirmed, "{:?}", app.model.error);
624 click(&ctx, &mut app, "복구본 열기");
625 assert!(
626 matches!(factory.state.borrow().starts.last(), Some(Start::List { archive }) if archive == &output)
627 );
628 let labels = render(&ctx, &mut app, vec![]);
629 assert!(
630 labels
631 .iter()
632 .any(|(text, _)| text.contains("전체 목록을 알 수 없어"))
633 );
634 }
635
636 fn loaded(scratch: &Folder, factory: &FakeFactory) -> ArchiveApp {
637 let mut app = ArchiveApp::new(
638 Box::new(factory.clone()),
639 Some(scratch.0.join("sample.zip")),
640 false,
641 );
642 pump(&mut app.model);
643 app.set_dialogs(Box::new(TestDialogs::default()));
644 app
645 }
646
647 fn policy_render(
648 ctx: &egui::Context,
649 app: &mut ArchiveApp,
650 events: Vec<egui::Event>,
651 ) -> Vec<(String, egui::Pos2)> {
652 let mut output = ctx.run_ui(
653 egui::RawInput {
654 screen_rect: Some(egui::Rect::from_min_size(
655 egui::Pos2::ZERO,
656 egui::vec2(1060.0, 720.0),
657 )),
658 events,
659 ..Default::default()
660 },
661 |ui| app.show(ui),
662 );
663 output.textures_delta.clear();
664 labels(&output.shapes)
665 }
666
667 fn policy_focus(ctx: &egui::Context, app: &mut ArchiveApp, label: &str) {
668 policy_render(ctx, app, vec![]);
669 for _ in 0..100 {
670 let shown = policy_render(ctx, app, vec![]);
671 let point = shown
672 .iter()
673 .rev()
674 .find(|(text, _)| text == label)
675 .unwrap_or_else(|| panic!("표시 없음: {label}"))
676 .1;
677 if ctx
678 .memory(|memory| memory.focused())
679 .and_then(|id| ctx.read_response(id))
680 .is_some_and(|response| response.rect.contains(point))
681 {
682 return;
683 }
684 policy_render(ctx, app, vec![key(egui::Key::Tab)]);
685 let mut released = key(egui::Key::Tab);
686 if let egui::Event::Key { pressed, .. } = &mut released {
687 *pressed = false;
688 }
689 policy_render(ctx, app, vec![released]);
690 }
691 panic!("키보드 초점 없음: {label}");
692 }
693
694 fn policy_click(ctx: &egui::Context, app: &mut ArchiveApp, label: &str) {
695 policy_render(ctx, app, vec![]);
696 let point = policy_render(ctx, app, vec![])
697 .iter()
698 .rev()
699 .find(|(text, _)| text == label)
700 .unwrap()
701 .1;
702 for pressed in [true, false] {
703 policy_render(
704 ctx,
705 app,
706 vec![
707 egui::Event::PointerMoved(point),
708 egui::Event::PointerButton {
709 pos: point,
710 button: egui::PointerButton::Primary,
711 pressed,
712 modifiers: egui::Modifiers::NONE,
713 },
714 ],
715 );
716 }
717 }
718
719 #[test]
720 fn destination_failure_sends_no_request_and_explains_folder_change() {
721 let scratch = Folder::new();
722 let factory = FakeFactory::default();
723 let mut app = loaded(&scratch, &factory);
724 let file = scratch.0.join("existing.txt");
725 fs::write(&file, "preserve").unwrap();
726 app.choose_destination(file.clone());
727 assert!(!app.begin_extract());
728 assert_eq!(factory.state.borrow().starts.len(), 1);
729 let ctx = egui::Context::default();
730 render(&ctx, &mut app, vec![]);
731 assert!(
732 render(&ctx, &mut app, vec![])
733 .iter()
734 .any(|(text, _)| text == FOLDER_ERROR)
735 );
736 assert_eq!(fs::read_to_string(file).unwrap(), "preserve");
737 }
738
739 #[test]
740 fn cancelling_removes_only_automatically_created_empty_folder() {
741 for case in ["automatic-empty", "automatic-nonempty", "chosen-empty"] {
742 let scratch = Folder::new();
743 let factory = FakeFactory::default();
744 let mut app = loaded(&scratch, &factory);
745 factory.state.borrow_mut().manual = true;
746 let destination = if case == "chosen-empty" {
747 let path = scratch.0.join("chosen");
748 fs::create_dir(&path).unwrap();
749 app.choose_destination(path.clone());
750 path
751 } else {
752 scratch.0.join("sample")
753 };
754 assert!(app.begin_extract());
755 if case == "automatic-nonempty" {
756 fs::write(destination.join("preserve"), "keep").unwrap();
757 }
758 {
759 let mut state = factory.state.borrow_mut();
760 state.frame(Event::Accepted { encryption: true });
761 state.finish(Outcome::Cancelled, Publication::None);
762 }
763 let ctx = egui::Context::default();
764 for _ in 0..30 {
765 render(&ctx, &mut app, vec![]);
766 }
767 assert!(!app.model.busy());
768 assert_eq!(destination.exists(), case != "automatic-empty");
769 }
770 }
771
772 #[test]
773 fn password_secondary_enter_does_not_submit_valid_input() {
774 for encrypt in [false, true] {
775 for label in ["보기", "숨기기", "취소"] {
776 let scratch = Folder::new();
777 let factory = FakeFactory::manual();
778 let mut app = ArchiveApp::new(Box::new(factory.clone()), None, false);
779 assert!(app.model.begin(
780 Start::CreateZip {
781 sources: vec![(scratch.0.join("source"), "source".into())],
782 output_file: scratch.0.join("output.zip"),
783 method: Method::Deflate,
784 aes256: true
785 },
786 &mut factory.clone()
787 ));
788 {
789 let mut worker = factory.state.borrow_mut();
790 worker.frame(Event::Accepted { encryption: true });
791 worker.frame(Event::PasswordRequired {
792 challenge_id: 17,
793 attempt: 1,
794 encrypt,
795 });
796 }
797 let ctx = egui::Context::default();
798 for _ in 0..12 {
799 policy_render(&ctx, &mut app, vec![]);
800 }
801 text(&ctx, &mut app, "archive-password-input", "fixture-secret");
802 if encrypt {
803 text(&ctx, &mut app, "archive-password-confirm", "fixture-secret");
804 }
805 if label == "숨기기" {
806 policy_click(&ctx, &mut app, "보기");
807 }
808 policy_focus(&ctx, &mut app, label);
809 policy_render(&ctx, &mut app, vec![key(egui::Key::Enter)]);
810 assert!(!factory.state.borrow().password_seen, "{label}");
811 assert_eq!(factory.state.borrow().starts.len(), 1);
812 }
813 }
814 }
815
816 #[test]
817 fn directory_only_extraction_displays_success() {
818 let scratch = Folder::new();
819 let factory = FakeFactory::default();
820 let mut app = loaded(&scratch, &factory);
821 app.model.entries = vec![Entry {
822 id: 0,
823 name: "empty".into(),
824 kind: Kind::Directory,
825 bytes: Some(0),
826 packed: None,
827 encrypted: false,
828 }];
829 factory.state.borrow_mut().manual = true;
830 assert!(app.begin_extract());
831 {
832 let mut worker = factory.state.borrow_mut();
833 worker.frame(Event::Accepted { encryption: false });
834 worker.frame(Event::Output {
835 entry_id: None,
836 relative_name: "empty".into(),
837 disposition: Disposition::Created,
838 });
839 worker.finish(Outcome::Completed, Publication::Complete);
840 }
841 let ctx = egui::Context::default();
842 for _ in 0..30 {
843 policy_render(&ctx, &mut app, vec![]);
844 }
845 let shown = policy_render(&ctx, &mut app, vec![]);
846 assert!(shown.iter().any(|(text, _)| text == "압축을 풀었습니다"));
847 assert!(!shown.iter().any(|(text, _)| text == UNCERTAIN));
848 }
849
850 #[test]
851 fn completed_results_keep_folder_action_and_distinguish_durability() {
852 for creating in [false, true] {
853 for durability in [
854 Durability::Synced,
855 Durability::Unconfirmed,
856 Durability::Failed,
857 ] {
858 let scratch = Folder::new();
859 let factory = FakeFactory::default();
860 let mut app = loaded(&scratch, &factory);
861 factory.state.borrow_mut().manual = true;
862 let ctx = egui::Context::default();
863 let name = if creating {
864 let source = scratch.0.join("source.txt");
865 fs::write(&source, b"source").unwrap();
866 app.add_sources(vec![source]);
867 policy_render(&ctx, &mut app, vec![]);
868 policy_click(&ctx, &mut app, "압축하기");
869 match factory.state.borrow().starts.last().unwrap() {
870 Start::CreateZip { output_file, .. } => output_file
871 .file_name()
872 .unwrap()
873 .to_str()
874 .unwrap()
875 .to_owned(),
876 _ => panic!("생성 요청 누락"),
877 }
878 } else {
879 assert!(app.begin_extract());
880 "읽어주세요.txt".to_owned()
881 };
882 {
883 let mut worker = factory.state.borrow_mut();
884 worker.frame(Event::Accepted { encryption: false });
885 worker.frame(Event::Output {
886 entry_id: None,
887 relative_name: name,
888 disposition: Disposition::Created,
889 });
890 worker.finish(Outcome::Completed, Publication::Complete);
891 for event in &mut worker.queue {
892 if let HostEvent::Frame {
893 event: Event::Terminal(terminal),
894 ..
895 } = event
896 {
897 terminal.durability = durability;
898 }
899 }
900 }
901 for _ in 0..30 {
902 policy_render(&ctx, &mut app, vec![]);
903 }
904 let shown = policy_render(&ctx, &mut app, vec![]);
905 let title = if creating {
906 "ZIP 파일을 만들었습니다"
907 } else {
908 "압축을 풀었습니다"
909 };
910 assert!(
911 shown.iter().any(|(text, _)| text == title),
912 "{durability:?}: {shown:?}"
913 );
914 assert!(shown.iter().any(|(text, _)| text == "폴더 열기"));
915 assert!(!shown.iter().any(|(text, _)| text == "다시 시도"));
916 assert!(!shown.iter().any(|(text, _)| text == SYNC_WARNING));
917 let sync_failed = if creating {
918 "파일을 디스크에 완전히 저장하지 못했습니다. 저장 위치 폴더를 확인하세요."
919 } else {
920 "파일을 디스크에 완전히 저장하지 못했습니다. 풀 위치 폴더를 확인하세요."
921 };
922 assert_eq!(
923 shown.iter().any(|(text, _)| text == sync_failed),
924 durability == Durability::Failed
925 );
926 policy_click(&ctx, &mut app, "자세히 보기");
927 let details = policy_render(&ctx, &mut app, vec![]);
928 assert_eq!(
929 details.iter().any(|(text, _)| text == SYNC_WARNING),
930 durability == Durability::Unconfirmed
931 );
932 policy_click(&ctx, &mut app, "자세히 닫기");
933 let closed = policy_render(&ctx, &mut app, vec![]);
934 assert!(!closed.iter().any(|(text, _)| text == SYNC_WARNING));
935 assert_eq!(
936 closed.iter().any(|(text, _)| text == sync_failed),
937 durability == Durability::Failed
938 );
939 assert!(closed.iter().any(|(text, _)| text == "폴더 열기"));
940 }
941 }
942 }
943
944 #[test]
945 fn durability_warning_visibility_matches_completed_failed_and_partial_results() {
946 for (outcome, publication, saved, expected_files) in [
947 (Outcome::Completed, Publication::Complete, 1, 1),
948 (Outcome::Failed, Publication::None, 0, 1),
949 (Outcome::Failed, Publication::Partial, 1, 2),
950 ] {
951 for durability in [
952 Durability::Synced,
953 Durability::Unconfirmed,
954 Durability::Failed,
955 ] {
956 let scratch = Folder::new();
957 let factory = FakeFactory::default();
958 let mut app = loaded(&scratch, &factory);
959 app.model.entries = (0..expected_files)
960 .map(|id| Entry {
961 id,
962 name: format!("{id}.txt"),
963 kind: Kind::File,
964 bytes: Some(1),
965 packed: None,
966 encrypted: false,
967 })
968 .collect();
969 factory.state.borrow_mut().manual = true;
970 assert!(app.begin_extract());
971 {
972 let mut worker = factory.state.borrow_mut();
973 worker.frame(Event::Accepted { encryption: false });
974 if saved > 0 {
975 worker.frame(Event::Output {
976 entry_id: Some(0),
977 relative_name: "0.txt".into(),
978 disposition: Disposition::Created,
979 });
980 }
981 worker.finish(outcome, publication);
982 for event in &mut worker.queue {
983 if let HostEvent::Frame {
984 event: Event::Terminal(terminal),
985 ..
986 } = event
987 {
988 terminal.created_count = saved;
989 terminal.durability = durability;
990 terminal.error = (outcome == Outcome::Failed).then_some(ErrorCode::Io);
991 }
992 }
993 }
994 let ctx = egui::Context::default();
995 for _ in 0..30 {
996 policy_render(&ctx, &mut app, vec![]);
997 }
998 let completed = outcome == Outcome::Completed;
999 let shown = policy_render(&ctx, &mut app, vec![]);
1000 let warning = match durability {
1001 Durability::Unconfirmed => Some(SYNC_WARNING),
1002 Durability::Failed => Some(
1003 "파일을 디스크에 완전히 저장하지 못했습니다. 풀 위치 폴더를 확인하세요.",
1004 ),
1005 _ => None,
1006 };
1007 let visible =
1008 warning.is_some() && !(completed && durability == Durability::Unconfirmed);
1009 assert_eq!(
1010 shown.iter().any(|(text, _)| Some(text.as_str()) == warning),
1011 visible,
1012 "{outcome:?}/{publication:?}: {shown:?}"
1013 );
1014 assert_eq!(shown.iter().any(|(text, _)| text == "폴더 열기"), completed);
1015 assert_eq!(
1016 shown.iter().any(|(text, _)| text == "압축을 풀었습니다"),
1017 completed
1018 );
1019 assert_eq!(
1020 shown
1021 .iter()
1022 .any(|(text, _)| text == "압축을 풀지 못했습니다"),
1023 !completed
1024 );
1025 assert_eq!(
1026 shown.iter().any(|(text, _)| text == PARTIAL),
1027 publication == Publication::Partial
1028 );
1029 policy_click(&ctx, &mut app, "자세히 보기");
1030 let details = policy_render(&ctx, &mut app, vec![]);
1031 assert_eq!(
1032 details
1033 .iter()
1034 .filter(|(text, _)| Some(text.as_str()) == warning)
1035 .count(),
1036 usize::from(warning.is_some()),
1037 "{outcome:?}/{publication:?}: {details:?}"
1038 );
1039 policy_click(&ctx, &mut app, "자세히 닫기");
1040 let closed = policy_render(&ctx, &mut app, vec![]);
1041 assert_eq!(
1042 closed
1043 .iter()
1044 .any(|(text, _)| Some(text.as_str()) == warning),
1045 visible
1046 );
1047 }
1048 }
1049 }
1050 include!("toolbar.rs");
1051 include!("long_layout.rs");
1052 include!("explorer_selection.rs");
1053 include!("find_escape.rs");
1054 include!("drag_out_flow.rs");
1055 include!("window_frame.rs");
1056 include!("work_window.rs");
1057 include!("create_window.rs");
1058}
1059
1060#[cfg(feature = "ui")]
1061#[test]
1062fn create_dialog_keeps_title_and_actions_visible_after_resize() {
1063 use eframe::egui::{self, epaint::Shape};
1064 use zipelo_ui_memory_app::archive_screen::ArchiveApp;
1065 let scratch = Folder::new();
1066 let mut app = ArchiveApp::new(Box::new(FakeFactory::default()), None, false);
1067 fs::write(scratch.0.join("one.txt"), b"fixture").unwrap();
1068 fs::create_dir(scratch.0.join("photos")).unwrap();
1069 app.add_sources(vec![scratch.0.join("one.txt"), scratch.0.join("photos")]);
1070 let ctx = egui::Context::default();
1071 for size in [egui::vec2(1060.0, 720.0), egui::vec2(760.0, 540.0)] {
1072 let mut texts = Vec::new();
1073 for _ in 0..8 {
1074 let mut output = ctx.run_ui(
1075 egui::RawInput {
1076 screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)),
1077 ..Default::default()
1078 },
1079 |ui| app.show(ui),
1080 );
1081 output.textures_delta.clear();
1082 fn walk(shape: &Shape, output: &mut Vec<(String, egui::Pos2)>) {
1083 match shape {
1084 Shape::Text(text) => output.push((
1085 text.galley.job.text.clone(),
1086 text.pos + text.galley.rect.size() / 2.0,
1087 )),
1088 Shape::Vec(shapes) => {
1089 for shape in shapes {
1090 walk(shape, output);
1091 }
1092 }
1093 _ => {}
1094 }
1095 }
1096 texts.clear();
1097 for shape in &output.shapes {
1098 walk(&shape.shape, &mut texts);
1099 }
1100 }
1101 for label in ["ZIP 만들기", "압축하기", "취소"] {
1102 let positions = texts
1103 .iter()
1104 .filter(|(text, _)| text == label)
1105 .map(|(_, p)| p)
1106 .collect::<Vec<_>>();
1107 assert!(!positions.is_empty(), "{label}");
1108 assert!(
1109 positions.iter().all(|p| p.y >= 0.0 && p.y <= size.y),
1110 "{label}: {positions:?}"
1111 );
1112 }
1113 }
1114}
1115#[test]
1116fn folder_open_command_preserves_shell_characters_as_one_argument() {
1117 let path = path("한글 폴더 ; $(touch unexpected)");
1118 let command = folder_command(&path);
1119 assert_eq!(
1120 command.get_program(),
1121 if cfg!(windows) {
1122 "explorer"
1123 } else {
1124 "xdg-open"
1125 }
1126 );
1127 assert_eq!(
1128 command.get_args().collect::<Vec<_>>(),
1129 vec![path.as_os_str()]
1130 );
1131}
1132
1133#[test]
1134fn late_cancel_and_terminal_wait_use_finishing_text() {
1135 let mut model = Model::default();
1136 model.progress = Some((Stage::Decode, 1, Some(2), 0));
1137 assert_eq!(activity_text(&model, false), "압축을 푸는 중");
1138 model.cancel = Some(CancelStatus::Requested);
1139 assert_eq!(activity_text(&model, false), "취소하는 중...");
1140 for state in [CancelStatus::TooLate, CancelStatus::Finished] {
1141 model.cancel = Some(state);
1142 assert_eq!(activity_text(&model, false), "마무리하는 중");
1143 }
1144 model.cancel = Some(CancelStatus::Requested);
1145 model.terminal = Some(terminal());
1146 assert_eq!(activity_text(&model, false), "마무리하는 중");
1147}
1148#[test]
1149fn client_protocol_errors_hide_internal_terms_but_preserve_exit_uncertainty() {
1150 for error in [
1151 "작업 ID 한도에 도달했습니다",
1152 "작업자 응답 순서나 작업 ID가 일치하지 않습니다",
1153 "작업 승인 응답이 없습니다",
1154 "출력 보고 한도 초과",
1155 ] {
1156 assert_eq!(client_error_text(error), INTERNAL);
1157 }
1158 assert_eq!(
1159 client_error_text("작업자 종료 결과를 확인할 수 없습니다. 출력 상태를 확인하세요"),
1160 UNCONFIRMED_FINISH
1161 );
1162}
1163
1164#[cfg(feature = "ui")]
1165#[cfg(unix)]
1166#[test]
1167fn app_exit_preserves_replaced_open_root() {
1168 use zipelo_ui_memory_app::archive_screen::ArchiveApp;
1169 let scratch = Folder::new();
1170 let mut app = ArchiveApp::new(
1171 Box::new(FakeFactory::default()),
1172 Some(scratch.0.join("sample.zip")),
1173 false,
1174 );
1175 pump(&mut app.model);
1176 assert!(app.open_entry(0));
1177 let root = scratch.0.join(open_root_name("sample.zip"));
1178 fs::rename(&root, scratch.0.join("original")).unwrap();
1179 fs::create_dir(&root).unwrap();
1180 let retained = root.join("keep.txt");
1181 fs::write(&retained, b"user data").unwrap();
1182 drop(app);
1183 assert_eq!(fs::read(retained).unwrap(), b"user data");
1184}
1185
1186#[cfg(feature = "ui")]
1187#[test]
1188fn app_exit_removes_original_open_root() {
1189 use zipelo_ui_memory_app::archive_screen::ArchiveApp;
1190 let scratch = Folder::new();
1191 let mut app = ArchiveApp::new(
1192 Box::new(FakeFactory::default()),
1193 Some(scratch.0.join("sample.zip")),
1194 false,
1195 );
1196 pump(&mut app.model);
1197 assert!(app.open_entry(0));
1198 let root = scratch.0.join(open_root_name("sample.zip"));
1199 fs::write(root.join("opened.txt"), b"temporary").unwrap();
1200 drop(app);
1201 assert!(!root.exists());
1202}
1203
1204#[cfg(feature = "ui")]
1205#[cfg(windows)]
1206#[test]
1207fn open_root_cannot_be_renamed_while_app_holds_it() {
1208 use zipelo_ui_memory_app::archive_screen::ArchiveApp;
1209 let scratch = Folder::new();
1210 let mut app = ArchiveApp::new(
1211 Box::new(FakeFactory::default()),
1212 Some(scratch.0.join("sample.zip")),
1213 false,
1214 );
1215 pump(&mut app.model);
1216 assert!(app.open_entry(0));
1217 let root = scratch.0.join(open_root_name("sample.zip"));
1218 // 열어 둔 핸들이 이름 변경을 막아 경로가 다른 폴더로 바뀌지 않음.
1219 assert!(fs::rename(&root, scratch.0.join("original")).is_err());
1220 drop(app);
1221 assert!(!root.exists());
1222}
1223
1224#[cfg(unix)]
1225fn open_root_with_contents(scratch: &Folder) -> (OpenRoot, PathBuf) {
1226 let root = create_open_root(&scratch.0.join("sample.zip")).unwrap();
1227 let path = root.path().to_path_buf();
1228 fs::create_dir_all(path.join("a/b")).unwrap();
1229 fs::write(path.join("a/b/deep.txt"), b"temporary").unwrap();
1230 fs::write(path.join("top.txt"), b"temporary").unwrap();
1231 (root, path)
1232}
1233
1234#[cfg(unix)]
1235#[test]
1236fn removal_is_bound_to_checked_folder_when_replaced_after_check() {
1237 let scratch = Folder::new();
1238 let (root, path) = open_root_with_contents(&scratch);
1239 let original = scratch.0.join("original");
1240 remove_open_root_with(root, || {
1241 fs::rename(&path, &original).unwrap();
1242 fs::create_dir(&path).unwrap();
1243 fs::write(path.join("keep.txt"), b"user data").unwrap();
1244 });
1245 assert_eq!(fs::read(path.join("keep.txt")).unwrap(), b"user data");
1246 // 확인한 폴더의 내용만 지움.
1247 assert_eq!(fs::read_dir(&original).unwrap().count(), 0);
1248}
1249
1250#[cfg(unix)]
1251#[test]
1252fn removal_does_not_follow_link_swapped_in_after_check() {
1253 let scratch = Folder::new();
1254 let (root, path) = open_root_with_contents(&scratch);
1255 let victim = scratch.0.join("victim");
1256 fs::create_dir(&victim).unwrap();
1257 fs::write(victim.join("keep.txt"), b"user data").unwrap();
1258 let original = scratch.0.join("original");
1259 remove_open_root_with(root, || {
1260 fs::rename(&path, &original).unwrap();
1261 std::os::unix::fs::symlink(&victim, &path).unwrap();
1262 });
1263 assert_eq!(fs::read(victim.join("keep.txt")).unwrap(), b"user data");
1264 assert!(fs::symlink_metadata(&path).unwrap().file_type().is_symlink());
1265 assert_eq!(fs::read_dir(&original).unwrap().count(), 0);
1266}
1267
1268#[cfg(unix)]
1269#[test]
1270fn removal_does_not_follow_links_inside_folder() {
1271 let scratch = Folder::new();
1272 let (root, path) = open_root_with_contents(&scratch);
1273 let victim = scratch.0.join("victim");
1274 fs::create_dir(&victim).unwrap();
1275 fs::write(victim.join("keep.txt"), b"user data").unwrap();
1276 std::os::unix::fs::symlink(&victim, path.join("a/link")).unwrap();
1277 std::os::unix::fs::symlink(victim.join("keep.txt"), path.join("file-link")).unwrap();
1278 remove_open_root(root);
1279 assert!(!path.exists());
1280 assert_eq!(fs::read(victim.join("keep.txt")).unwrap(), b"user data");
1281}
1282
1283#[cfg(unix)]
1284#[test]
1285fn removal_of_original_folder_clears_nested_contents() {
1286 let scratch = Folder::new();
1287 let (root, path) = open_root_with_contents(&scratch);
1288 remove_open_root(root);
1289 assert!(!path.exists());
1290}
1291
1292#[cfg(unix)]
1293#[test]
1294fn creation_does_not_adopt_folder_replaced_before_handle_is_taken() {
1295 let scratch = Folder::new();
1296 let archive = scratch.0.join("sample.zip");
1297 let swapped = scratch.0.join(open_root_name("sample.zip"));
1298 let original = scratch.0.join("original");
1299 let mut swaps = 0;
1300 let root = create_open_root_with(&archive, |path| {
1301 swaps += 1;
1302 if swaps == 1 {
1303 fs::rename(path, &original).unwrap();
1304 fs::create_dir(path).unwrap();
1305 fs::write(path.join("keep.txt"), b"user data").unwrap();
1306 }
1307 })
1308 .unwrap();
1309 // 바뀐 폴더는 원본으로 기록하지 않고 다른 이름의 새 폴더를 씀.
1310 assert_ne!(root.path(), swapped);
1311 assert!(root.is_current());
1312 remove_open_root(root);
1313 assert_eq!(fs::read(swapped.join("keep.txt")).unwrap(), b"user data");
1314}
1315
1316#[cfg(unix)]
1317#[test]
1318fn creation_does_not_adopt_link_replaced_before_handle_is_taken() {
1319 let scratch = Folder::new();
1320 let archive = scratch.0.join("sample.zip");
1321 let link = scratch.0.join(open_root_name("sample.zip"));
1322 let victim = scratch.0.join("victim");
1323 fs::create_dir(&victim).unwrap();
1324 fs::write(victim.join("keep.txt"), b"user data").unwrap();
1325 let mut swaps = 0;
1326 let root = create_open_root_with(&archive, |path| {
1327 swaps += 1;
1328 if swaps == 1 {
1329 fs::remove_dir(path).unwrap();
1330 std::os::unix::fs::symlink(&victim, path).unwrap();
1331 }
1332 })
1333 .unwrap();
1334 assert_ne!(root.path(), link);
1335 remove_open_root(root);
1336 assert_eq!(fs::read(victim.join("keep.txt")).unwrap(), b"user data");
1337 assert!(fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
1338}
1339
1340#[test]
1341fn creation_of_unchanged_folder_is_empty_and_current() {
1342 let scratch = Folder::new();
1343 let root = create_open_root(&scratch.0.join("sample.zip")).unwrap();
1344 let path = root.path().to_path_buf();
1345 assert!(root.is_current());
1346 assert_eq!(fs::read_dir(&path).unwrap().count(), 0);
1347 remove_open_root(root);
1348 assert!(!path.exists());
1349}