team-ljyzipelo

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