team-ljyzipelo

공개
1,158줄41 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 assert!(blocked_open("run.desktop"));
338 assert!(!blocked_open("사진.jpg"));
339 assert!(!blocked_open("exe"));
340 // Linux는 스크립트를 편집기로 열므로 막지 않음.
341 #[cfg(not(windows))]
342 assert!(!blocked_open("app.js"));
343 #[cfg(windows)]
344 assert!(blocked_open("app.js"));
345 assert_eq!(
346 open_blocked_text("폴더/setup.EXE"),
347 "실행 파일(.EXE)은 안전을 위해 바로 열 수 없습니다"
348 );
349 assert_eq!(middle_text("가나다라마바사아자차", 7), "가나다…아자차");
350 assert_eq!(bytes_text(21), "21 B");
351}
352
353static SCRATCH_ID: AtomicU64 = AtomicU64::new(0);
354pub(super) struct Folder(pub(super) PathBuf);
355impl Folder {
356 pub(super) fn new() -> Self {
357 let root = PathBuf::from(std::env::var_os("ZIPELO_TEST_WORK_DIR").expect("runner 작업 경로 필요")).join("fixtures/rust-app-ui");
358 fs::create_dir_all(&root).unwrap();
359 let path = root.join(format!(
360 "presentation-{}-{}",
361 std::process::id(),
362 SCRATCH_ID.fetch_add(1, Ordering::Relaxed)
363 ));
364 fs::create_dir(&path).unwrap();
365 Self(path.canonicalize().unwrap())
366 }
367}
368impl Drop for Folder {
369 fn drop(&mut self) {
370 fs::remove_dir_all(&self.0).unwrap();
371 }
372}
373
374#[test]
375fn unique_folder_numbers_existing_names() {
376 let scratch = Folder::new();
377 let base = scratch.0.join("자료");
378 assert_eq!(unique_folder(&base), base);
379 fs::create_dir(&base).unwrap();
380 assert_eq!(unique_folder(&base), scratch.0.join("자료 (1)"));
381 fs::write(scratch.0.join("자료 (1)"), b"").unwrap();
382 assert_eq!(unique_folder(&base), scratch.0.join("자료 (2)"));
383}
384
385#[test]
386fn automatic_destination_creation_and_failure_are_distinct() {
387 let scratch = Folder::new();
388 let output = scratch.0.join("output");
389 assert!(prepare_destination(&output, true).unwrap());
390 assert!(!prepare_destination(&output, true).unwrap());
391 assert!(prepare_destination(&scratch.0.join("missing/child"), true).is_err());
392 assert!(prepare_destination(&scratch.0.join("chosen-missing"), false).is_err());
393 let file = scratch.0.join("file");
394 fs::write(&file, "existing").unwrap();
395 assert!(prepare_destination(&file, true).is_err());
396 assert_eq!(fs::read_to_string(file).unwrap(), "existing");
397}
398#[test]
399fn only_new_empty_output_is_removed_and_nonempty_is_preserved() {
400 let scratch = Folder::new();
401 let empty = scratch.0.join("empty");
402 assert!(prepare_destination(&empty, true).unwrap());
403 remove_owned_empty(&empty);
404 assert!(!empty.exists());
405 let nonempty = scratch.0.join("nonempty");
406 assert!(prepare_destination(&nonempty, true).unwrap());
407 fs::write(nonempty.join("existing"), "keep").unwrap();
408 remove_owned_empty(&nonempty);
409 assert_eq!(
410 fs::read_to_string(nonempty.join("existing")).unwrap(),
411 "keep"
412 );
413 assert!(!prepare_destination(&scratch.0, false).unwrap());
414 assert!(scratch.0.is_dir());
415}
416#[cfg(unix)]
417#[test]
418fn browser_and_output_do_not_follow_symbolic_links() {
419 let scratch = Folder::new();
420 let link = scratch.0.join("link");
421 std::os::unix::fs::symlink(&scratch.0, &link).unwrap();
422 let rows = directory_entries(&scratch.0).unwrap();
423 assert!(rows.iter().any(|entry| entry.link && entry.path == link));
424 assert!(directory_entries(&link).is_err());
425 assert!(prepare_destination(&link, true).is_err());
426}
427
428#[cfg(feature = "ui")]
429mod widgets {
430 use super::*;
431 use crate::dialogs::TestDialogs;
432 use eframe::egui::{self, epaint::Shape};
433 use zipelo_ui_memory_app::{archive_dialog::Purpose, archive_screen::ArchiveApp};
434
435 fn labels(shapes: &[egui::epaint::ClippedShape]) -> Vec<(String, egui::Pos2)> {
436 fn walk(shape: &Shape, result: &mut Vec<(String, egui::Pos2)>) {
437 match shape {
438 Shape::Text(text) => result.push((
439 text.galley.job.text.clone(),
440 text.pos + text.galley.rect.size() / 2.0,
441 )),
442 Shape::Vec(shapes) => {
443 for shape in shapes {
444 walk(shape, result);
445 }
446 }
447 _ => {}
448 }
449 }
450 let mut result = Vec::new();
451 for shape in shapes {
452 walk(&shape.shape, &mut result);
453 }
454 result
455 }
456
457 fn render(
458 ctx: &egui::Context,
459 app: &mut ArchiveApp,
460 events: Vec<egui::Event>,
461 ) -> Vec<(String, egui::Pos2)> {
462 let mut output = ctx.run_ui(
463 egui::RawInput {
464 screen_rect: Some(egui::Rect::from_min_size(
465 egui::Pos2::ZERO,
466 egui::vec2(760.0, 540.0),
467 )),
468 events,
469 ..Default::default()
470 },
471 |ui| app.show(ui),
472 );
473 output.textures_delta.clear();
474 labels(&output.shapes)
475 }
476
477 fn click(ctx: &egui::Context, app: &mut ArchiveApp, label: &str) {
478 render(ctx, app, vec![]);
479 let point = render(ctx, app, vec![])
480 .into_iter()
481 .filter(|(text, _)| text == label)
482 .max_by(|a, b| a.1.y.total_cmp(&b.1.y))
483 .unwrap_or_else(|| panic!("항목 없음: {label}"))
484 .1;
485 for pressed in [true, false] {
486 render(
487 ctx,
488 app,
489 vec![
490 egui::Event::PointerMoved(point),
491 egui::Event::PointerButton {
492 pos: point,
493 button: egui::PointerButton::Primary,
494 pressed,
495 modifiers: egui::Modifiers::NONE,
496 },
497 ],
498 );
499 }
500 }
501
502 fn key(key: egui::Key) -> egui::Event {
503 egui::Event::Key {
504 key,
505 physical_key: None,
506 pressed: true,
507 repeat: false,
508 modifiers: egui::Modifiers::NONE,
509 }
510 }
511
512 fn text(ctx: &egui::Context, app: &mut ArchiveApp, id: &str, value: &str) {
513 ctx.memory_mut(|memory| memory.request_focus(egui::Id::unique(id)));
514 render(
515 ctx,
516 app,
517 vec![
518 egui::Event::Key {
519 key: egui::Key::A,
520 physical_key: None,
521 pressed: true,
522 repeat: false,
523 modifiers: egui::Modifiers::COMMAND,
524 },
525 egui::Event::Text(value.into()),
526 ],
527 );
528 }
529
530 #[test]
531 fn recovery_save_uses_native_dialog_and_partial_copy_keeps_warning_when_opened() {
532 let scratch = Folder::new();
533 let factory = FakeFactory::manual();
534 let archive = scratch.0.join("손상.zip");
535 let output = scratch.0.join("복구본.zip");
536 let mut app = ArchiveApp::new(Box::new(factory.clone()), Some(archive.clone()), false);
537 {
538 let mut state = factory.state.borrow_mut();
539 state.frame(Event::Accepted { encryption: false });
540 state.frame(Event::Terminal(Terminal {
541 outcome: Outcome::Failed,
542 error: Some(ErrorCode::Integrity),
543 publication: Publication::None,
544 created_count: 0,
545 retained_partial_count: 0,
546 durability: Durability::NotApplicable,
547 cleanup: Cleanup::Complete,
548 }));
549 state.queue.extend([
550 HostEvent::StdoutEof,
551 HostEvent::StderrEof,
552 HostEvent::Exited { success: true },
553 ]);
554 }
555 pump(&mut app.model);
556 let dialogs = TestDialogs::default();
557 dialogs
558 .0
559 .borrow_mut()
560 .answers
561 .push_back(Some(vec![output.clone()]));
562 app.set_dialogs(Box::new(dialogs.clone()));
563 let ctx = egui::Context::default();
564 click(&ctx, &mut app, "복구본 저장 위치 선택");
565 assert_eq!(
566 dialogs.0.borrow().requests[0].purpose,
567 Purpose::SaveRecoveryZip
568 );
569 assert_eq!(
570 dialogs.0.borrow().requests[0].file_name,
571 "손상-recovered.zip"
572 );
573 assert!(
574 matches!(factory.state.borrow().starts.last(), Some(Start::RecoverZip { archive: actual, output_file }) if actual == &archive && output_file == &output)
575 );
576 {
577 let mut state = factory.state.borrow_mut();
578 state.frame(Event::Accepted { encryption: false });
579 state.frame(Event::RecoveryEntry(RecoveryEntry {
580 candidate_id: 0,
581 source_offset: 0,
582 name: Some("내용.txt".into()),
583 kind: Some(worker_protocol::protocol::EntryKind::File),
584 status: RecoveryStatus::Verified,
585 reason: RecoveryReason::MetadataMissing,
586 declared_size: Some(0),
587 verified_size: Some(0),
588 sha256: Some([1; 32]),
589 }));
590 state.frame(Event::RecoveryEnd(RecoveryEnd {
591 mode: RecoveryMode::LocalChain,
592 source_bytes: 128,
593 source_sha256: [2; 32],
594 known_entries: None,
595 verified_entries: 1,
596 lost_entries: 0,
597 unverified_entries: 0,
598 unknown_loss: true,
599 }));
600 state.frame(Event::Output {
601 entry_id: None,
602 relative_name: "복구본.zip".into(),
603 disposition: Disposition::Created,
604 });
605 state.frame(Event::Terminal(Terminal {
606 outcome: Outcome::Failed,
607 error: Some(ErrorCode::RecoveryIncomplete),
608 publication: Publication::Complete,
609 created_count: 1,
610 retained_partial_count: 0,
611 durability: Durability::Synced,
612 cleanup: Cleanup::Complete,
613 }));
614 state.queue.extend([
615 HostEvent::StdoutEof,
616 HostEvent::StderrEof,
617 HostEvent::Exited { success: true },
618 ]);
619 }
620 pump(&mut app.model);
621 assert!(app.model.confirmed, "{:?}", app.model.error);
622 click(&ctx, &mut app, "복구본 열기");
623 assert!(
624 matches!(factory.state.borrow().starts.last(), Some(Start::List { archive }) if archive == &output)
625 );
626 let labels = render(&ctx, &mut app, vec![]);
627 assert!(
628 labels
629 .iter()
630 .any(|(text, _)| text.contains("전체 목록을 알 수 없어"))
631 );
632 }
633
634 fn loaded(scratch: &Folder, factory: &FakeFactory) -> ArchiveApp {
635 let mut app = ArchiveApp::new(
636 Box::new(factory.clone()),
637 Some(scratch.0.join("sample.zip")),
638 false,
639 );
640 pump(&mut app.model);
641 app.set_dialogs(Box::new(TestDialogs::default()));
642 app
643 }
644
645 fn policy_render(
646 ctx: &egui::Context,
647 app: &mut ArchiveApp,
648 events: Vec<egui::Event>,
649 ) -> Vec<(String, egui::Pos2)> {
650 let mut output = ctx.run_ui(
651 egui::RawInput {
652 screen_rect: Some(egui::Rect::from_min_size(
653 egui::Pos2::ZERO,
654 egui::vec2(1060.0, 720.0),
655 )),
656 events,
657 ..Default::default()
658 },
659 |ui| app.show(ui),
660 );
661 output.textures_delta.clear();
662 labels(&output.shapes)
663 }
664
665 fn policy_focus(ctx: &egui::Context, app: &mut ArchiveApp, label: &str) {
666 policy_render(ctx, app, vec![]);
667 for _ in 0..100 {
668 let shown = policy_render(ctx, app, vec![]);
669 let point = shown
670 .iter()
671 .rev()
672 .find(|(text, _)| text == label)
673 .unwrap_or_else(|| panic!("표시 없음: {label}"))
674 .1;
675 if ctx
676 .memory(|memory| memory.focused())
677 .and_then(|id| ctx.read_response(id))
678 .is_some_and(|response| response.rect.contains(point))
679 {
680 return;
681 }
682 policy_render(ctx, app, vec![key(egui::Key::Tab)]);
683 let mut released = key(egui::Key::Tab);
684 if let egui::Event::Key { pressed, .. } = &mut released {
685 *pressed = false;
686 }
687 policy_render(ctx, app, vec![released]);
688 }
689 panic!("키보드 초점 없음: {label}");
690 }
691
692 fn policy_click(ctx: &egui::Context, app: &mut ArchiveApp, label: &str) {
693 policy_render(ctx, app, vec![]);
694 let point = policy_render(ctx, app, vec![])
695 .iter()
696 .rev()
697 .find(|(text, _)| text == label)
698 .unwrap()
699 .1;
700 for pressed in [true, false] {
701 policy_render(
702 ctx,
703 app,
704 vec![
705 egui::Event::PointerMoved(point),
706 egui::Event::PointerButton {
707 pos: point,
708 button: egui::PointerButton::Primary,
709 pressed,
710 modifiers: egui::Modifiers::NONE,
711 },
712 ],
713 );
714 }
715 }
716
717 #[test]
718 fn destination_failure_sends_no_request_and_explains_folder_change() {
719 let scratch = Folder::new();
720 let factory = FakeFactory::default();
721 let mut app = loaded(&scratch, &factory);
722 let file = scratch.0.join("existing.txt");
723 fs::write(&file, "preserve").unwrap();
724 app.choose_destination(file.clone());
725 assert!(!app.begin_extract());
726 assert_eq!(factory.state.borrow().starts.len(), 1);
727 let ctx = egui::Context::default();
728 render(&ctx, &mut app, vec![]);
729 assert!(
730 render(&ctx, &mut app, vec![])
731 .iter()
732 .any(|(text, _)| text == FOLDER_ERROR)
733 );
734 assert_eq!(fs::read_to_string(file).unwrap(), "preserve");
735 }
736
737 #[test]
738 fn cancelling_removes_only_automatically_created_empty_folder() {
739 for case in ["automatic-empty", "automatic-nonempty", "chosen-empty"] {
740 let scratch = Folder::new();
741 let factory = FakeFactory::default();
742 let mut app = loaded(&scratch, &factory);
743 factory.state.borrow_mut().manual = true;
744 let destination = if case == "chosen-empty" {
745 let path = scratch.0.join("chosen");
746 fs::create_dir(&path).unwrap();
747 app.choose_destination(path.clone());
748 path
749 } else {
750 scratch.0.join("sample")
751 };
752 assert!(app.begin_extract());
753 if case == "automatic-nonempty" {
754 fs::write(destination.join("preserve"), "keep").unwrap();
755 }
756 {
757 let mut state = factory.state.borrow_mut();
758 state.frame(Event::Accepted { encryption: true });
759 state.finish(Outcome::Cancelled, Publication::None);
760 }
761 let ctx = egui::Context::default();
762 for _ in 0..30 {
763 render(&ctx, &mut app, vec![]);
764 }
765 assert!(!app.model.busy());
766 assert_eq!(destination.exists(), case != "automatic-empty");
767 }
768 }
769
770 #[test]
771 fn password_secondary_enter_does_not_submit_valid_input() {
772 for encrypt in [false, true] {
773 for label in ["보기", "숨기기", "취소"] {
774 let scratch = Folder::new();
775 let factory = FakeFactory::manual();
776 let mut app = ArchiveApp::new(Box::new(factory.clone()), None, false);
777 assert!(app.model.begin(
778 Start::CreateZip {
779 sources: vec![(scratch.0.join("source"), "source".into())],
780 output_file: scratch.0.join("output.zip"),
781 method: Method::Deflate,
782 aes256: true
783 },
784 &mut factory.clone()
785 ));
786 {
787 let mut worker = factory.state.borrow_mut();
788 worker.frame(Event::Accepted { encryption: true });
789 worker.frame(Event::PasswordRequired {
790 challenge_id: 17,
791 attempt: 1,
792 encrypt,
793 });
794 }
795 let ctx = egui::Context::default();
796 for _ in 0..12 {
797 policy_render(&ctx, &mut app, vec![]);
798 }
799 text(&ctx, &mut app, "archive-password-input", "fixture-secret");
800 if encrypt {
801 text(&ctx, &mut app, "archive-password-confirm", "fixture-secret");
802 }
803 if label == "숨기기" {
804 policy_click(&ctx, &mut app, "보기");
805 }
806 policy_focus(&ctx, &mut app, label);
807 policy_render(&ctx, &mut app, vec![key(egui::Key::Enter)]);
808 assert!(!factory.state.borrow().password_seen, "{label}");
809 assert_eq!(factory.state.borrow().starts.len(), 1);
810 }
811 }
812 }
813
814 #[test]
815 fn directory_only_extraction_displays_success() {
816 let scratch = Folder::new();
817 let factory = FakeFactory::default();
818 let mut app = loaded(&scratch, &factory);
819 app.model.entries = vec![Entry {
820 id: 0,
821 name: "empty".into(),
822 kind: Kind::Directory,
823 bytes: Some(0),
824 packed: None,
825 encrypted: false,
826 }];
827 factory.state.borrow_mut().manual = true;
828 assert!(app.begin_extract());
829 {
830 let mut worker = factory.state.borrow_mut();
831 worker.frame(Event::Accepted { encryption: false });
832 worker.frame(Event::Output {
833 entry_id: None,
834 relative_name: "empty".into(),
835 disposition: Disposition::Created,
836 });
837 worker.finish(Outcome::Completed, Publication::Complete);
838 }
839 let ctx = egui::Context::default();
840 for _ in 0..30 {
841 policy_render(&ctx, &mut app, vec![]);
842 }
843 let shown = policy_render(&ctx, &mut app, vec![]);
844 assert!(shown.iter().any(|(text, _)| text == "압축을 풀었습니다"));
845 assert!(!shown.iter().any(|(text, _)| text == UNCERTAIN));
846 }
847
848 #[test]
849 fn completed_results_keep_folder_action_and_distinguish_durability() {
850 for creating in [false, true] {
851 for durability in [
852 Durability::Synced,
853 Durability::Unconfirmed,
854 Durability::Failed,
855 ] {
856 let scratch = Folder::new();
857 let factory = FakeFactory::default();
858 let mut app = loaded(&scratch, &factory);
859 factory.state.borrow_mut().manual = true;
860 let ctx = egui::Context::default();
861 let name = if creating {
862 let source = scratch.0.join("source.txt");
863 fs::write(&source, b"source").unwrap();
864 app.add_sources(vec![source]);
865 policy_render(&ctx, &mut app, vec![]);
866 policy_click(&ctx, &mut app, "압축하기");
867 match factory.state.borrow().starts.last().unwrap() {
868 Start::CreateZip { output_file, .. } => output_file
869 .file_name()
870 .unwrap()
871 .to_str()
872 .unwrap()
873 .to_owned(),
874 _ => panic!("생성 요청 누락"),
875 }
876 } else {
877 assert!(app.begin_extract());
878 "읽어주세요.txt".to_owned()
879 };
880 {
881 let mut worker = factory.state.borrow_mut();
882 worker.frame(Event::Accepted { encryption: false });
883 worker.frame(Event::Output {
884 entry_id: None,
885 relative_name: name,
886 disposition: Disposition::Created,
887 });
888 worker.finish(Outcome::Completed, Publication::Complete);
889 for event in &mut worker.queue {
890 if let HostEvent::Frame {
891 event: Event::Terminal(terminal),
892 ..
893 } = event
894 {
895 terminal.durability = durability;
896 }
897 }
898 }
899 for _ in 0..30 {
900 policy_render(&ctx, &mut app, vec![]);
901 }
902 let shown = policy_render(&ctx, &mut app, vec![]);
903 let title = if creating {
904 "ZIP 파일을 만들었습니다"
905 } else {
906 "압축을 풀었습니다"
907 };
908 assert!(
909 shown.iter().any(|(text, _)| text == title),
910 "{durability:?}: {shown:?}"
911 );
912 assert!(shown.iter().any(|(text, _)| text == "폴더 열기"));
913 assert!(!shown.iter().any(|(text, _)| text == "다시 시도"));
914 assert!(!shown.iter().any(|(text, _)| text == SYNC_WARNING));
915 let sync_failed = if creating {
916 "파일을 디스크에 완전히 저장하지 못했습니다. 저장 위치 폴더를 확인하세요."
917 } else {
918 "파일을 디스크에 완전히 저장하지 못했습니다. 풀 위치 폴더를 확인하세요."
919 };
920 assert_eq!(
921 shown.iter().any(|(text, _)| text == sync_failed),
922 durability == Durability::Failed
923 );
924 policy_click(&ctx, &mut app, "자세히 보기");
925 let details = policy_render(&ctx, &mut app, vec![]);
926 assert_eq!(
927 details.iter().any(|(text, _)| text == SYNC_WARNING),
928 durability == Durability::Unconfirmed
929 );
930 policy_click(&ctx, &mut app, "자세히 닫기");
931 let closed = policy_render(&ctx, &mut app, vec![]);
932 assert!(!closed.iter().any(|(text, _)| text == SYNC_WARNING));
933 assert_eq!(
934 closed.iter().any(|(text, _)| text == sync_failed),
935 durability == Durability::Failed
936 );
937 assert!(closed.iter().any(|(text, _)| text == "폴더 열기"));
938 }
939 }
940 }
941
942 #[test]
943 fn durability_warning_visibility_matches_completed_failed_and_partial_results() {
944 for (outcome, publication, saved, expected_files) in [
945 (Outcome::Completed, Publication::Complete, 1, 1),
946 (Outcome::Failed, Publication::None, 0, 1),
947 (Outcome::Failed, Publication::Partial, 1, 2),
948 ] {
949 for durability in [
950 Durability::Synced,
951 Durability::Unconfirmed,
952 Durability::Failed,
953 ] {
954 let scratch = Folder::new();
955 let factory = FakeFactory::default();
956 let mut app = loaded(&scratch, &factory);
957 app.model.entries = (0..expected_files)
958 .map(|id| Entry {
959 id,
960 name: format!("{id}.txt"),
961 kind: Kind::File,
962 bytes: Some(1),
963 packed: None,
964 encrypted: false,
965 })
966 .collect();
967 factory.state.borrow_mut().manual = true;
968 assert!(app.begin_extract());
969 {
970 let mut worker = factory.state.borrow_mut();
971 worker.frame(Event::Accepted { encryption: false });
972 if saved > 0 {
973 worker.frame(Event::Output {
974 entry_id: Some(0),
975 relative_name: "0.txt".into(),
976 disposition: Disposition::Created,
977 });
978 }
979 worker.finish(outcome, publication);
980 for event in &mut worker.queue {
981 if let HostEvent::Frame {
982 event: Event::Terminal(terminal),
983 ..
984 } = event
985 {
986 terminal.created_count = saved;
987 terminal.durability = durability;
988 terminal.error = (outcome == Outcome::Failed).then_some(ErrorCode::Io);
989 }
990 }
991 }
992 let ctx = egui::Context::default();
993 for _ in 0..30 {
994 policy_render(&ctx, &mut app, vec![]);
995 }
996 let completed = outcome == Outcome::Completed;
997 let shown = policy_render(&ctx, &mut app, vec![]);
998 let warning = match durability {
999 Durability::Unconfirmed => Some(SYNC_WARNING),
1000 Durability::Failed => Some(
1001 "파일을 디스크에 완전히 저장하지 못했습니다. 풀 위치 폴더를 확인하세요.",
1002 ),
1003 _ => None,
1004 };
1005 let visible =
1006 warning.is_some() && !(completed && durability == Durability::Unconfirmed);
1007 assert_eq!(
1008 shown.iter().any(|(text, _)| Some(text.as_str()) == warning),
1009 visible,
1010 "{outcome:?}/{publication:?}: {shown:?}"
1011 );
1012 assert_eq!(shown.iter().any(|(text, _)| text == "폴더 열기"), completed);
1013 assert_eq!(
1014 shown.iter().any(|(text, _)| text == "압축을 풀었습니다"),
1015 completed
1016 );
1017 assert_eq!(
1018 shown
1019 .iter()
1020 .any(|(text, _)| text == "압축을 풀지 못했습니다"),
1021 !completed
1022 );
1023 assert_eq!(
1024 shown.iter().any(|(text, _)| text == PARTIAL),
1025 publication == Publication::Partial
1026 );
1027 policy_click(&ctx, &mut app, "자세히 보기");
1028 let details = policy_render(&ctx, &mut app, vec![]);
1029 assert_eq!(
1030 details
1031 .iter()
1032 .filter(|(text, _)| Some(text.as_str()) == warning)
1033 .count(),
1034 usize::from(warning.is_some()),
1035 "{outcome:?}/{publication:?}: {details:?}"
1036 );
1037 policy_click(&ctx, &mut app, "자세히 닫기");
1038 let closed = policy_render(&ctx, &mut app, vec![]);
1039 assert_eq!(
1040 closed
1041 .iter()
1042 .any(|(text, _)| Some(text.as_str()) == warning),
1043 visible
1044 );
1045 }
1046 }
1047 }
1048 include!("toolbar.rs");
1049 include!("long_layout.rs");
1050 include!("explorer_selection.rs");
1051 include!("window_frame.rs");
1052 include!("work_window.rs");
1053 include!("create_window.rs");
1054}
1055
1056#[cfg(feature = "ui")]
1057#[test]
1058fn create_dialog_keeps_title_and_actions_visible_after_resize() {
1059 use eframe::egui::{self, epaint::Shape};
1060 use zipelo_ui_memory_app::archive_screen::ArchiveApp;
1061 let scratch = Folder::new();
1062 let mut app = ArchiveApp::new(Box::new(FakeFactory::default()), None, false);
1063 fs::write(scratch.0.join("one.txt"), b"fixture").unwrap();
1064 fs::create_dir(scratch.0.join("photos")).unwrap();
1065 app.add_sources(vec![scratch.0.join("one.txt"), scratch.0.join("photos")]);
1066 let ctx = egui::Context::default();
1067 for size in [egui::vec2(1060.0, 720.0), egui::vec2(760.0, 540.0)] {
1068 let mut texts = Vec::new();
1069 for _ in 0..8 {
1070 let mut output = ctx.run_ui(
1071 egui::RawInput {
1072 screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)),
1073 ..Default::default()
1074 },
1075 |ui| app.show(ui),
1076 );
1077 output.textures_delta.clear();
1078 fn walk(shape: &Shape, output: &mut Vec<(String, egui::Pos2)>) {
1079 match shape {
1080 Shape::Text(text) => output.push((
1081 text.galley.job.text.clone(),
1082 text.pos + text.galley.rect.size() / 2.0,
1083 )),
1084 Shape::Vec(shapes) => {
1085 for shape in shapes {
1086 walk(shape, output);
1087 }
1088 }
1089 _ => {}
1090 }
1091 }
1092 texts.clear();
1093 for shape in &output.shapes {
1094 walk(&shape.shape, &mut texts);
1095 }
1096 }
1097 for label in ["ZIP 만들기", "압축하기", "취소"] {
1098 let positions = texts
1099 .iter()
1100 .filter(|(text, _)| text == label)
1101 .map(|(_, p)| p)
1102 .collect::<Vec<_>>();
1103 assert!(!positions.is_empty(), "{label}");
1104 assert!(
1105 positions.iter().all(|p| p.y >= 0.0 && p.y <= size.y),
1106 "{label}: {positions:?}"
1107 );
1108 }
1109 }
1110}
1111#[test]
1112fn folder_open_command_preserves_shell_characters_as_one_argument() {
1113 let path = path("한글 폴더 ; $(touch unexpected)");
1114 let command = folder_command(&path);
1115 assert_eq!(
1116 command.get_program(),
1117 if cfg!(windows) {
1118 "explorer"
1119 } else {
1120 "xdg-open"
1121 }
1122 );
1123 assert_eq!(
1124 command.get_args().collect::<Vec<_>>(),
1125 vec![path.as_os_str()]
1126 );
1127}
1128
1129#[test]
1130fn late_cancel_and_terminal_wait_use_finishing_text() {
1131 let mut model = Model::default();
1132 model.progress = Some((Stage::Decode, 1, Some(2), 0));
1133 assert_eq!(activity_text(&model, false), "압축을 푸는 중");
1134 model.cancel = Some(CancelStatus::Requested);
1135 assert_eq!(activity_text(&model, false), "취소하는 중...");
1136 for state in [CancelStatus::TooLate, CancelStatus::Finished] {
1137 model.cancel = Some(state);
1138 assert_eq!(activity_text(&model, false), "마무리하는 중");
1139 }
1140 model.cancel = Some(CancelStatus::Requested);
1141 model.terminal = Some(terminal());
1142 assert_eq!(activity_text(&model, false), "마무리하는 중");
1143}
1144#[test]
1145fn client_protocol_errors_hide_internal_terms_but_preserve_exit_uncertainty() {
1146 for error in [
1147 "작업 ID 한도에 도달했습니다",
1148 "작업자 응답 순서나 작업 ID가 일치하지 않습니다",
1149 "작업 승인 응답이 없습니다",
1150 "출력 보고 한도 초과",
1151 ] {
1152 assert_eq!(client_error_text(error), INTERNAL);
1153 }
1154 assert_eq!(
1155 client_error_text("작업자 종료 결과를 확인할 수 없습니다. 출력 상태를 확인하세요"),
1156 UNCONFIRMED_FINISH
1157 );
1158}