team-ljyzipelo

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