team-ljyzipelo

공개
691줄23 KB
1use std::{
2 cell::RefCell,
3 fs,
4 path::{Path, PathBuf},
5 rc::Rc,
6 sync::atomic::{AtomicU64, Ordering},
7 time::{Duration, Instant},
8};
9use zipelo_ui_memory_app::{archive_process::ProcessFactory, archive_ui::*};
10static NEXT: AtomicU64 = AtomicU64::new(0);
11struct Scratch(PathBuf);
12impl Scratch {
13 fn new() -> Self {
14 let root =
15 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/rust-app-real-worker/runs");
16 fs::create_dir_all(&root).unwrap();
17 let path = root.join(format!(
18 "{}-{}",
19 std::process::id(),
20 NEXT.fetch_add(1, Ordering::Relaxed)
21 ));
22 Self(make_directory(&path))
23 }
24 fn path(&self, name: &str) -> PathBuf {
25 self.0.join(name)
26 }
27}
28impl Drop for Scratch {
29 fn drop(&mut self) {
30 fs::remove_dir_all(&self.0).unwrap();
31 }
32}
33fn make_directory(path: &Path) -> PathBuf {
34 let mut builder = fs::DirBuilder::new();
35 #[cfg(unix)]
36 {
37 use std::os::unix::fs::DirBuilderExt;
38 builder.mode(0o700);
39 }
40 builder.create(path).unwrap();
41 path.canonicalize().unwrap()
42}
43fn binary(name: &str) -> PathBuf {
44 let current = std::env::current_exe().unwrap();
45 let path = current
46 .parent()
47 .unwrap()
48 .parent()
49 .unwrap()
50 .join(format!("{name}{}", std::env::consts::EXE_SUFFIX));
51 assert!(
52 path.is_file(),
53 "실제 작업자와 시험 probe를 먼저 빌드해야 함: {}",
54 path.display()
55 );
56 path
57}
58#[derive(Default)]
59struct Observation {
60 jobs: Vec<Vec<&'static str>>,
61 starts: Vec<Start>,
62}
63struct ObservedFactory {
64 process: ProcessFactory,
65 observed: Rc<RefCell<Observation>>,
66}
67struct ObservedConnection {
68 connection: Box<dyn Connection>,
69 index: usize,
70 observed: Rc<RefCell<Observation>>,
71}
72impl Factory for ObservedFactory {
73 fn connect(&mut self, job: u64) -> Result<Box<dyn Connection>, String> {
74 let connection = self.process.connect(job)?;
75 let index = self.observed.borrow().jobs.len();
76 self.observed.borrow_mut().jobs.push(Vec::new());
77 Ok(Box::new(ObservedConnection {
78 connection,
79 index,
80 observed: self.observed.clone(),
81 }))
82 }
83}
84impl Connection for ObservedConnection {
85 fn send(&mut self, request: Request) -> Result<(), String> {
86 if let Command::Start(start) = &request.command {
87 self.observed.borrow_mut().starts.push(start.clone());
88 }
89 self.connection.send(request)
90 }
91 fn poll(&mut self) -> Option<HostEvent> {
92 let event = self.connection.poll()?;
93 let label = match &event {
94 HostEvent::StdoutEof => "stdout",
95 HostEvent::StderrEof => "stderr",
96 HostEvent::Exited { .. } => "wait",
97 HostEvent::CleanupComplete => "cleanup",
98 HostEvent::Fault(_) => "fault",
99 HostEvent::Frame {
100 event: Event::Terminal(_),
101 ..
102 } => "terminal",
103 _ => "frame",
104 };
105 self.observed.borrow_mut().jobs[self.index].push(label);
106 Some(event)
107 }
108}
109impl Drop for ObservedConnection {
110 fn drop(&mut self) {
111 self.observed.borrow_mut().jobs[self.index].push("drop");
112 }
113}
114fn observed_factory() -> (ObservedFactory, Rc<RefCell<Observation>>) {
115 let observed = Rc::new(RefCell::new(Observation::default()));
116 (
117 ObservedFactory {
118 process: ProcessFactory::new(binary("zipelo-archive-worker")),
119 observed: observed.clone(),
120 },
121 observed,
122 )
123}
124fn assert_reaped(observed: &Rc<RefCell<Observation>>) {
125 for events in &observed.borrow().jobs {
126 for label in ["terminal", "stdout", "stderr", "cleanup", "wait", "drop"] {
127 assert_eq!(
128 events.iter().filter(|value| **value == label).count(),
129 1,
130 "{events:?}"
131 );
132 }
133 assert!(!events.contains(&"fault"));
134 assert_eq!(&events[events.len() - 2..], &["wait", "drop"]);
135 }
136}
137fn wait(model: &mut Model) {
138 let deadline = Instant::now() + Duration::from_secs(10);
139 while model.busy() {
140 model.poll();
141 assert!(
142 Instant::now() < deadline,
143 "작업자 종료 시간 초과: {}",
144 model.status()
145 );
146 std::thread::sleep(Duration::from_millis(2));
147 }
148}
149fn completed(model: &Model) {
150 assert!(model.confirmed, "{}", model.status());
151 assert_eq!(
152 model.terminal.as_ref().unwrap().outcome,
153 Outcome::Completed,
154 "terminal: {:?}",
155 model.terminal
156 );
157}
158#[cfg(feature = "ui")]
159#[path = "../rust-app-ui/dialogs.rs"]
160mod dialogs;
161#[cfg(feature = "ui")]
162mod screen {
163 use super::dialogs::TestDialogs;
164 use super::*;
165 use eframe::egui::{self, epaint::Shape};
166 use zipelo_ui_memory_app::archive_screen::ArchiveApp;
167 struct Screen {
168 context: egui::Context,
169 app: ArchiveApp,
170 dialogs: TestDialogs,
171 }
172 impl Screen {
173 fn new(factory: ObservedFactory) -> Self {
174 let dialogs = TestDialogs::default();
175 let mut app = ArchiveApp::new(Box::new(factory), None, false);
176 app.set_dialogs(Box::new(dialogs.clone()));
177 Self {
178 context: egui::Context::default(),
179 app,
180 dialogs,
181 }
182 }
183 fn render(&mut self, events: Vec<egui::Event>) -> Vec<(String, egui::Pos2)> {
184 fn text(shape: &Shape, output: &mut Vec<(String, egui::Pos2)>) {
185 match shape {
186 Shape::Text(value) => output.push((
187 value.galley.job.text.clone(),
188 value.pos + value.galley.rect.size() / 2.0,
189 )),
190 Shape::Vec(values) => {
191 for value in values {
192 text(value, output);
193 }
194 }
195 _ => {}
196 }
197 }
198 let mut frame = self.context.run_ui(
199 egui::RawInput {
200 screen_rect: Some(egui::Rect::from_min_size(
201 egui::Pos2::ZERO,
202 egui::vec2(1060.0, 720.0),
203 )),
204 events,
205 ..Default::default()
206 },
207 |ui| self.app.show(ui),
208 );
209 frame.textures_delta.clear();
210 let mut output = Vec::new();
211 for shape in frame.shapes {
212 text(&shape.shape, &mut output);
213 }
214 output
215 }
216 fn locate(&mut self, label: &str) -> egui::Pos2 {
217 self.render(vec![]);
218 self.render(vec![])
219 .into_iter()
220 .filter(|(text, _)| text == label)
221 .max_by(|a, b| a.1.y.total_cmp(&b.1.y))
222 .unwrap_or_else(|| panic!("화면 항목 누락: {label}"))
223 .1
224 }
225 fn click_at(&mut self, point: egui::Pos2) {
226 self.render(vec![
227 egui::Event::PointerMoved(point),
228 egui::Event::PointerButton {
229 pos: point,
230 button: egui::PointerButton::Primary,
231 pressed: true,
232 modifiers: Default::default(),
233 },
234 ]);
235 self.render(vec![egui::Event::PointerButton {
236 pos: point,
237 button: egui::PointerButton::Primary,
238 pressed: false,
239 modifiers: Default::default(),
240 }]);
241 }
242 fn click(&mut self, label: &str) {
243 let point = self.locate(label);
244 self.click_at(point);
245 }
246 fn set_text(&mut self, id: &str, value: &str) {
247 if id == "zip-name" {
248 self.dialogs.0.borrow_mut().save_name = Some(value.to_owned());
249 return;
250 }
251 self.render(vec![]);
252 let point = self
253 .context
254 .read_response(egui::Id::unique(id))
255 .unwrap()
256 .rect
257 .center();
258 self.click_at(point);
259 self.context
260 .memory_mut(|memory| memory.request_focus(egui::Id::unique(id)));
261 self.render(vec![
262 egui::Event::Key {
263 key: egui::Key::A,
264 physical_key: None,
265 pressed: true,
266 repeat: false,
267 modifiers: egui::Modifiers::COMMAND,
268 },
269 egui::Event::Text(value.into()),
270 ]);
271 }
272 fn escape(&mut self) {
273 self.render(vec![egui::Event::Key {
274 key: egui::Key::Escape,
275 physical_key: None,
276 pressed: true,
277 repeat: false,
278 modifiers: egui::Modifiers::NONE,
279 }]);
280 }
281 fn settle(&mut self) {
282 let deadline = Instant::now() + Duration::from_secs(10);
283 while self.app.model.busy() {
284 self.render(vec![]);
285 assert!(Instant::now() < deadline, "{}", self.app.model.status());
286 std::thread::sleep(Duration::from_millis(2));
287 }
288 completed(&self.app.model);
289 }
290 fn open(&mut self, archive: &Path) {
291 self.app.open_path(archive.to_path_buf());
292 assert!(self.app.model.busy());
293 self.settle();
294 }
295 fn extract(&mut self, destination: &Path) {
296 self.app.choose_destination(destination.to_path_buf());
297 self.dialogs
298 .0
299 .borrow_mut()
300 .answers
301 .push_back(Some(vec![destination.to_path_buf()]));
302 self.click("압축해제");
303 assert!(self.app.model.busy());
304 self.settle();
305 assert_eq!(
306 self.app.model.terminal.as_ref().unwrap().publication,
307 Publication::Complete
308 );
309 }
310 }
311 include!("password_flows.rs");
312 include!("selection_flows.rs");
313 include!("native_dialog_flows.rs");
314
315 fn archive_flow(name: &str, format: Format) {
316 let scratch = Scratch::new();
317 let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
318 .join("../../tests/rust-app-real-worker/fixtures")
319 .join(name);
320 let archive = scratch.path(name);
321 fs::copy(fixture, &archive).unwrap();
322 let original = fs::read(&archive).unwrap();
323 let output = make_directory(&scratch.path("output"));
324 let (factory, observed) = observed_factory();
325 let mut screen = Screen::new(factory);
326 screen.open(&archive);
327 assert_eq!(screen.app.model.list_id.as_ref().unwrap().format, format);
328 assert_eq!(screen.app.model.entries[0].name, "content.txt");
329 screen.extract(&output);
330 assert_eq!(
331 fs::read(output.join("content.txt")).unwrap(),
332 b"Zipelo real worker flow\n"
333 );
334 assert_eq!(fs::read(archive).unwrap(), original);
335 assert_eq!(observed.borrow().jobs.len(), 2);
336 assert_reaped(&observed);
337 }
338 #[test]
339 fn seven_zip_open_and_extract_via_actual_widgets_and_worker() {
340 for name in ["lzma.7z", "lzma2.7z"] {
341 let scratch = Scratch::new();
342 let archive = scratch.path(name);
343 fs::copy(
344 Path::new(env!("CARGO_MANIFEST_DIR"))
345 .join("../../tests/rust-archive-worker/fixtures/7z")
346 .join(name),
347 &archive,
348 )
349 .unwrap();
350 let original = fs::read(&archive).unwrap();
351 let output = make_directory(&scratch.path("output"));
352 let (factory, observed) = observed_factory();
353 let mut screen = Screen::new(factory);
354 screen.open(&archive);
355 assert_eq!(
356 screen.app.model.list_id.as_ref().unwrap().format,
357 Format::SevenZip
358 );
359 assert!(screen.app.model.can_extract());
360 screen.extract(&output);
361 assert_eq!(
362 fs::read(output.join("folder/hello.txt")).unwrap(),
363 b"Zipelo 7z interoperability\n".repeat(100)
364 );
365 assert_eq!(fs::read(archive).unwrap(), original);
366 assert_eq!(observed.borrow().jobs.len(), 2);
367 assert_reaped(&observed);
368 }
369 }
370 #[test]
371 fn zip_open_and_extract_via_actual_widgets_and_worker() {
372 archive_flow("sample.zip", Format::Zip);
373 }
374 #[test]
375 fn targz_open_and_extract_via_actual_widgets_and_worker() {
376 archive_flow("sample.tar.gz", Format::TarGzip);
377 }
378
379 #[test]
380 fn empty_directory_zip_extracts_successfully_with_existing_directory_reuse() {
381 let scratch = Scratch::new();
382 let source = make_directory(&scratch.path("empty-source"));
383 fs::create_dir(source.join("child")).unwrap();
384 let archive = scratch.path("empty-source.zip");
385 let output = make_directory(&scratch.path("output"));
386 let (factory, observed) = observed_factory();
387 let mut screen = Screen::new(factory);
388 screen.app.add_sources(vec![source]);
389 screen.render(vec![]);
390 screen.click("압축하기");
391 screen.settle();
392 assert!(archive.is_file());
393 screen.open(&archive);
394 assert!(
395 screen
396 .app
397 .model
398 .entries
399 .iter()
400 .all(|entry| entry.kind == Kind::Directory)
401 );
402 for expected in [2, 0] {
403 screen.extract(&output);
404 assert!(output.join("empty-source/child").is_dir());
405 assert_eq!(
406 screen.app.model.terminal.as_ref().unwrap().created_count,
407 expected
408 );
409 let shown = screen.render(vec![]);
410 assert!(shown.iter().any(|(text, _)| text == "압축을 풀었습니다"));
411 assert!(
412 !shown
413 .iter()
414 .any(|(text, _)| text.contains("저장이 끝났는지"))
415 );
416 screen.click("확인");
417 }
418 assert_reaped(&observed);
419 }
420
421 #[test]
422 fn create_zip_reopen_and_extract_via_actual_widgets_and_worker() {
423 let scratch = Scratch::new();
424 let source = scratch.path("one.txt");
425 fs::write(&source, b"ZIP creation through real worker\n").unwrap();
426 let archive = scratch.path("new.zip");
427 let output = make_directory(&scratch.path("output"));
428 let (factory, observed) = observed_factory();
429 let mut screen = Screen::new(factory);
430 screen.app.add_sources(vec![source.clone()]);
431 screen.render(vec![]);
432 screen.set_text("zip-name", archive.file_name().unwrap().to_str().unwrap());
433 screen.click("압축하기");
434 assert!(screen.app.model.busy());
435 screen.settle();
436 assert!(archive.is_file());
437 screen.open(&archive);
438 assert_eq!(screen.app.model.entries[0].name, "one.txt");
439 screen.extract(&output);
440 assert_eq!(
441 fs::read(output.join("one.txt")).unwrap(),
442 fs::read(source).unwrap()
443 );
444 assert_eq!(observed.borrow().jobs.len(), 3);
445 assert_reaped(&observed);
446 }
447}
448#[test]
449fn missing_worker_is_an_error_without_a_fake_result() {
450 let scratch = Scratch::new();
451 let mut factory = ProcessFactory::new(scratch.path("not-installed"));
452 let mut model = Model::default();
453 assert!(!model.begin(
454 Start::List {
455 archive: scratch.path("sample.zip")
456 },
457 &mut factory
458 ));
459 assert!(!model.busy());
460 assert!(model.error.is_some());
461 assert!(!model.confirmed);
462}
463#[test]
464fn broken_or_incomplete_worker_output_is_not_success() {
465 for name in ["truncated", "wrong-action", "early-exit"] {
466 let scratch = Scratch::new();
467 let probe = scratch.path(&format!("{name}{}", std::env::consts::EXE_SUFFIX));
468 fs::copy(binary("zipelo-real-worker-probe"), &probe).unwrap();
469 let mut factory = ProcessFactory::new(probe);
470 let mut model = Model::default();
471 assert!(
472 model.begin(
473 Start::List {
474 archive: scratch.path("sample.zip")
475 },
476 &mut factory
477 ),
478 "{:?}",
479 model.error
480 );
481 model.request_close();
482 model.confirm_close();
483 assert_eq!(model.close, Close::Waiting);
484 wait(&mut model);
485 assert!(!model.confirmed);
486 assert!(model.error.is_some());
487 assert_eq!(model.close, Close::Review);
488 model.acknowledge_close();
489 assert_eq!(model.close, Close::Allowed);
490 }
491}
492#[cfg(target_os = "linux")]
493#[test]
494fn dropping_live_connection_kills_and_reaps_owned_child() {
495 let scratch = Scratch::new();
496 let probe = scratch.path("hang");
497 fs::copy(binary("zipelo-real-worker-probe"), &probe).unwrap();
498 let mut factory = ProcessFactory::new(probe);
499 let mut model = Model::default();
500 assert!(
501 model.begin(
502 Start::List {
503 archive: scratch.path("sample.zip")
504 },
505 &mut factory
506 ),
507 "{:?}",
508 model.error
509 );
510 let deadline = Instant::now() + Duration::from_secs(5);
511 while !scratch.path("probe.pid").exists() {
512 assert!(Instant::now() < deadline);
513 std::thread::sleep(Duration::from_millis(2));
514 }
515 let pid = fs::read_to_string(scratch.path("probe.pid")).unwrap();
516 drop(model);
517 assert!(!Path::new("/proc").join(pid).exists());
518}
519
520#[test]
521fn failed_start_serialization_reaps_the_real_worker_without_terminal() {
522 let scratch = Scratch::new();
523 let mut factory = ProcessFactory::new(binary("zipelo-archive-worker"));
524 let mut model = Model::default();
525 let archive = scratch.path(&"a".repeat(40000));
526 assert!(!model.begin(Start::List { archive }, &mut factory));
527 assert!(model.busy());
528 model.request_close();
529 model.confirm_close();
530 assert_eq!(model.close, Close::Waiting);
531 wait(&mut model);
532 assert!(!model.confirmed);
533 assert!(model.terminal.is_none());
534 assert!(model.error.is_some());
535 assert_eq!(model.close, Close::Review);
536}
537
538#[test]
539fn late_cancel_after_child_reap_keeps_the_original_terminal_result() {
540 let scratch = Scratch::new();
541 let archive = scratch.path("sample.zip");
542 fs::copy(
543 Path::new(env!("CARGO_MANIFEST_DIR"))
544 .join("../../tests/rust-app-real-worker/fixtures/sample.zip"),
545 &archive,
546 )
547 .unwrap();
548 let mut factory = ProcessFactory::new(binary("zipelo-archive-worker"));
549 let mut connection = factory.connect(1).unwrap();
550 connection
551 .send(Request {
552 job_id: 1,
553 sequence: 0,
554 command: Command::Start(Start::List { archive }),
555 })
556 .unwrap();
557 let deadline = Instant::now() + Duration::from_secs(10);
558 let mut terminal = false;
559 loop {
560 assert!(Instant::now() < deadline);
561 match connection.poll() {
562 Some(HostEvent::CleanupComplete) => break,
563 Some(HostEvent::Frame {
564 event: Event::Terminal(value),
565 ..
566 }) => {
567 assert_eq!(value.outcome, Outcome::Completed);
568 terminal = true;
569 }
570 Some(HostEvent::Fault(message)) => panic!("{message}"),
571 _ => std::thread::sleep(Duration::from_millis(1)),
572 }
573 }
574 assert!(terminal);
575 assert!(
576 connection
577 .send(Request {
578 job_id: 1,
579 sequence: 1,
580 command: Command::Cancel
581 })
582 .is_ok()
583 );
584 loop {
585 assert!(Instant::now() < deadline);
586 match connection.poll() {
587 Some(HostEvent::Exited { success }) => {
588 assert!(success);
589 break;
590 }
591 Some(HostEvent::Fault(message)) => panic!("{message}"),
592 _ => std::thread::sleep(Duration::from_millis(1)),
593 }
594 }
595 assert!(connection.poll().is_none());
596}
597
598#[test]
599fn cancel_racing_child_exit_preserves_completed_result_before_poll() {
600 struct CompletedFactory(ProcessFactory);
601 struct BufferedConnection {
602 inner: Box<dyn Connection>,
603 pending: std::collections::VecDeque<HostEvent>,
604 }
605 impl Factory for CompletedFactory {
606 fn connect(&mut self, job_id: u64) -> Result<Box<dyn Connection>, String> {
607 Ok(Box::new(BufferedConnection {
608 inner: self.0.connect(job_id)?,
609 pending: Default::default(),
610 }))
611 }
612 }
613 impl Connection for BufferedConnection {
614 fn send(&mut self, request: Request) -> Result<(), String> {
615 let starting = matches!(&request.command, Command::Start(_));
616 self.inner.send(request)?;
617 if starting {
618 let deadline = Instant::now() + Duration::from_secs(20);
619 loop {
620 assert!(Instant::now() < deadline, "작업자 종료 대기 시간 초과");
621 if let Some(event) = self.inner.poll() {
622 let exited = matches!(&event, HostEvent::Exited { .. });
623 self.pending.push_back(event);
624 if exited {
625 break;
626 }
627 } else {
628 std::thread::sleep(Duration::from_millis(1));
629 }
630 }
631 }
632 Ok(())
633 }
634 fn poll(&mut self) -> Option<HostEvent> {
635 self.pending.pop_front().or_else(|| self.inner.poll())
636 }
637 }
638 let archive = Path::new(env!("CARGO_MANIFEST_DIR"))
639 .join("../../tests/rust-app-real-worker/fixtures/sample.zip")
640 .canonicalize()
641 .unwrap();
642 for iteration in 0..100 {
643 let mut factory = CompletedFactory(ProcessFactory::new(binary("zipelo-archive-worker")));
644 let mut model = Model::default();
645 assert!(
646 model.begin(
647 Start::List {
648 archive: archive.clone()
649 },
650 &mut factory
651 ),
652 "{:?}",
653 model.error
654 );
655 assert!(model.terminal.is_none());
656 model.cancel();
657 wait(&mut model);
658 assert!(model.confirmed, "iteration={iteration}: {:?}", model.error);
659 assert_eq!(model.terminal.as_ref().unwrap().outcome, Outcome::Completed);
660 assert!(model.error.is_none());
661 }
662}
663
664#[test]
665fn cancel_racing_exit_without_terminal_remains_unconfirmed() {
666 let scratch = Scratch::new();
667 let probe = scratch.path("early-exit");
668 fs::copy(binary("zipelo-real-worker-probe"), &probe).unwrap();
669 let mut factory = ProcessFactory::new(probe);
670 let mut model = Model::default();
671 assert!(
672 model.begin(
673 Start::List {
674 archive: scratch.path("sample.zip")
675 },
676 &mut factory
677 ),
678 "{:?}",
679 model.error
680 );
681 std::thread::sleep(Duration::from_millis(2));
682 model.cancel();
683 model.request_close();
684 model.confirm_close();
685 assert_eq!(model.close, Close::Waiting);
686 wait(&mut model);
687 assert!(!model.confirmed);
688 assert!(model.terminal.is_none());
689 assert!(model.error.is_some());
690 assert_eq!(model.close, Close::Review);
691}