team-ljyzipelo

공개
690줄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
314 fn archive_flow(name: &str, format: Format) {
315 let scratch = Scratch::new();
316 let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
317 .join("../../tests/rust-app-real-worker/fixtures")
318 .join(name);
319 let archive = scratch.path(name);
320 fs::copy(fixture, &archive).unwrap();
321 let original = fs::read(&archive).unwrap();
322 let output = make_directory(&scratch.path("output"));
323 let (factory, observed) = observed_factory();
324 let mut screen = Screen::new(factory);
325 screen.open(&archive);
326 assert_eq!(screen.app.model.list_id.as_ref().unwrap().format, format);
327 assert_eq!(screen.app.model.entries[0].name, "content.txt");
328 screen.extract(&output);
329 assert_eq!(
330 fs::read(output.join("content.txt")).unwrap(),
331 b"Zipelo real worker flow\n"
332 );
333 assert_eq!(fs::read(archive).unwrap(), original);
334 assert_eq!(observed.borrow().jobs.len(), 2);
335 assert_reaped(&observed);
336 }
337 #[test]
338 fn seven_zip_open_and_extract_via_actual_widgets_and_worker() {
339 for name in ["lzma.7z", "lzma2.7z"] {
340 let scratch = Scratch::new();
341 let archive = scratch.path(name);
342 fs::copy(
343 Path::new(env!("CARGO_MANIFEST_DIR"))
344 .join("../../tests/rust-archive-worker/fixtures/7z")
345 .join(name),
346 &archive,
347 )
348 .unwrap();
349 let original = fs::read(&archive).unwrap();
350 let output = make_directory(&scratch.path("output"));
351 let (factory, observed) = observed_factory();
352 let mut screen = Screen::new(factory);
353 screen.open(&archive);
354 assert_eq!(
355 screen.app.model.list_id.as_ref().unwrap().format,
356 Format::SevenZip
357 );
358 assert!(screen.app.model.can_extract());
359 screen.extract(&output);
360 assert_eq!(
361 fs::read(output.join("folder/hello.txt")).unwrap(),
362 b"Zipelo 7z interoperability\n".repeat(100)
363 );
364 assert_eq!(fs::read(archive).unwrap(), original);
365 assert_eq!(observed.borrow().jobs.len(), 2);
366 assert_reaped(&observed);
367 }
368 }
369 #[test]
370 fn zip_open_and_extract_via_actual_widgets_and_worker() {
371 archive_flow("sample.zip", Format::Zip);
372 }
373 #[test]
374 fn targz_open_and_extract_via_actual_widgets_and_worker() {
375 archive_flow("sample.tar.gz", Format::TarGzip);
376 }
377
378 #[test]
379 fn empty_directory_zip_extracts_successfully_with_existing_directory_reuse() {
380 let scratch = Scratch::new();
381 let source = make_directory(&scratch.path("empty-source"));
382 fs::create_dir(source.join("child")).unwrap();
383 let archive = scratch.path("empty-source.zip");
384 let output = make_directory(&scratch.path("output"));
385 let (factory, observed) = observed_factory();
386 let mut screen = Screen::new(factory);
387 screen.app.add_sources(vec![source]);
388 screen.render(vec![]);
389 screen.click("압축하기");
390 screen.settle();
391 assert!(archive.is_file());
392 screen.open(&archive);
393 assert!(
394 screen
395 .app
396 .model
397 .entries
398 .iter()
399 .all(|entry| entry.kind == Kind::Directory)
400 );
401 for expected in [2, 0] {
402 screen.extract(&output);
403 assert!(output.join("empty-source/child").is_dir());
404 assert_eq!(
405 screen.app.model.terminal.as_ref().unwrap().created_count,
406 expected
407 );
408 let shown = screen.render(vec![]);
409 assert!(shown.iter().any(|(text, _)| text == "압축을 풀었습니다"));
410 assert!(
411 !shown
412 .iter()
413 .any(|(text, _)| text.contains("저장이 끝났는지"))
414 );
415 screen.click("확인");
416 }
417 assert_reaped(&observed);
418 }
419
420 #[test]
421 fn create_zip_reopen_and_extract_via_actual_widgets_and_worker() {
422 let scratch = Scratch::new();
423 let source = scratch.path("one.txt");
424 fs::write(&source, b"ZIP creation through real worker\n").unwrap();
425 let archive = scratch.path("new.zip");
426 let output = make_directory(&scratch.path("output"));
427 let (factory, observed) = observed_factory();
428 let mut screen = Screen::new(factory);
429 screen.app.add_sources(vec![source.clone()]);
430 screen.render(vec![]);
431 screen.set_text("zip-name", archive.file_name().unwrap().to_str().unwrap());
432 screen.click("압축하기");
433 assert!(screen.app.model.busy());
434 screen.settle();
435 assert!(archive.is_file());
436 screen.open(&archive);
437 assert_eq!(screen.app.model.entries[0].name, "one.txt");
438 screen.extract(&output);
439 assert_eq!(
440 fs::read(output.join("one.txt")).unwrap(),
441 fs::read(source).unwrap()
442 );
443 assert_eq!(observed.borrow().jobs.len(), 3);
444 assert_reaped(&observed);
445 }
446}
447#[test]
448fn missing_worker_is_an_error_without_a_fake_result() {
449 let scratch = Scratch::new();
450 let mut factory = ProcessFactory::new(scratch.path("not-installed"));
451 let mut model = Model::default();
452 assert!(!model.begin(
453 Start::List {
454 archive: scratch.path("sample.zip")
455 },
456 &mut factory
457 ));
458 assert!(!model.busy());
459 assert!(model.error.is_some());
460 assert!(!model.confirmed);
461}
462#[test]
463fn broken_or_incomplete_worker_output_is_not_success() {
464 for name in ["truncated", "wrong-action", "early-exit"] {
465 let scratch = Scratch::new();
466 let probe = scratch.path(&format!("{name}{}", std::env::consts::EXE_SUFFIX));
467 fs::copy(binary("zipelo-real-worker-probe"), &probe).unwrap();
468 let mut factory = ProcessFactory::new(probe);
469 let mut model = Model::default();
470 assert!(
471 model.begin(
472 Start::List {
473 archive: scratch.path("sample.zip")
474 },
475 &mut factory
476 ),
477 "{:?}",
478 model.error
479 );
480 model.request_close();
481 model.confirm_close();
482 assert_eq!(model.close, Close::Waiting);
483 wait(&mut model);
484 assert!(!model.confirmed);
485 assert!(model.error.is_some());
486 assert_eq!(model.close, Close::Review);
487 model.acknowledge_close();
488 assert_eq!(model.close, Close::Allowed);
489 }
490}
491#[cfg(target_os = "linux")]
492#[test]
493fn dropping_live_connection_kills_and_reaps_owned_child() {
494 let scratch = Scratch::new();
495 let probe = scratch.path("hang");
496 fs::copy(binary("zipelo-real-worker-probe"), &probe).unwrap();
497 let mut factory = ProcessFactory::new(probe);
498 let mut model = Model::default();
499 assert!(
500 model.begin(
501 Start::List {
502 archive: scratch.path("sample.zip")
503 },
504 &mut factory
505 ),
506 "{:?}",
507 model.error
508 );
509 let deadline = Instant::now() + Duration::from_secs(5);
510 while !scratch.path("probe.pid").exists() {
511 assert!(Instant::now() < deadline);
512 std::thread::sleep(Duration::from_millis(2));
513 }
514 let pid = fs::read_to_string(scratch.path("probe.pid")).unwrap();
515 drop(model);
516 assert!(!Path::new("/proc").join(pid).exists());
517}
518
519#[test]
520fn failed_start_serialization_reaps_the_real_worker_without_terminal() {
521 let scratch = Scratch::new();
522 let mut factory = ProcessFactory::new(binary("zipelo-archive-worker"));
523 let mut model = Model::default();
524 let archive = scratch.path(&"a".repeat(40000));
525 assert!(!model.begin(Start::List { archive }, &mut factory));
526 assert!(model.busy());
527 model.request_close();
528 model.confirm_close();
529 assert_eq!(model.close, Close::Waiting);
530 wait(&mut model);
531 assert!(!model.confirmed);
532 assert!(model.terminal.is_none());
533 assert!(model.error.is_some());
534 assert_eq!(model.close, Close::Review);
535}
536
537#[test]
538fn late_cancel_after_child_reap_keeps_the_original_terminal_result() {
539 let scratch = Scratch::new();
540 let archive = scratch.path("sample.zip");
541 fs::copy(
542 Path::new(env!("CARGO_MANIFEST_DIR"))
543 .join("../../tests/rust-app-real-worker/fixtures/sample.zip"),
544 &archive,
545 )
546 .unwrap();
547 let mut factory = ProcessFactory::new(binary("zipelo-archive-worker"));
548 let mut connection = factory.connect(1).unwrap();
549 connection
550 .send(Request {
551 job_id: 1,
552 sequence: 0,
553 command: Command::Start(Start::List { archive }),
554 })
555 .unwrap();
556 let deadline = Instant::now() + Duration::from_secs(10);
557 let mut terminal = false;
558 loop {
559 assert!(Instant::now() < deadline);
560 match connection.poll() {
561 Some(HostEvent::CleanupComplete) => break,
562 Some(HostEvent::Frame {
563 event: Event::Terminal(value),
564 ..
565 }) => {
566 assert_eq!(value.outcome, Outcome::Completed);
567 terminal = true;
568 }
569 Some(HostEvent::Fault(message)) => panic!("{message}"),
570 _ => std::thread::sleep(Duration::from_millis(1)),
571 }
572 }
573 assert!(terminal);
574 assert!(
575 connection
576 .send(Request {
577 job_id: 1,
578 sequence: 1,
579 command: Command::Cancel
580 })
581 .is_ok()
582 );
583 loop {
584 assert!(Instant::now() < deadline);
585 match connection.poll() {
586 Some(HostEvent::Exited { success }) => {
587 assert!(success);
588 break;
589 }
590 Some(HostEvent::Fault(message)) => panic!("{message}"),
591 _ => std::thread::sleep(Duration::from_millis(1)),
592 }
593 }
594 assert!(connection.poll().is_none());
595}
596
597#[test]
598fn cancel_racing_child_exit_preserves_completed_result_before_poll() {
599 struct CompletedFactory(ProcessFactory);
600 struct BufferedConnection {
601 inner: Box<dyn Connection>,
602 pending: std::collections::VecDeque<HostEvent>,
603 }
604 impl Factory for CompletedFactory {
605 fn connect(&mut self, job_id: u64) -> Result<Box<dyn Connection>, String> {
606 Ok(Box::new(BufferedConnection {
607 inner: self.0.connect(job_id)?,
608 pending: Default::default(),
609 }))
610 }
611 }
612 impl Connection for BufferedConnection {
613 fn send(&mut self, request: Request) -> Result<(), String> {
614 let starting = matches!(&request.command, Command::Start(_));
615 self.inner.send(request)?;
616 if starting {
617 let deadline = Instant::now() + Duration::from_secs(20);
618 loop {
619 assert!(Instant::now() < deadline, "작업자 종료 대기 시간 초과");
620 if let Some(event) = self.inner.poll() {
621 let exited = matches!(&event, HostEvent::Exited { .. });
622 self.pending.push_back(event);
623 if exited {
624 break;
625 }
626 } else {
627 std::thread::sleep(Duration::from_millis(1));
628 }
629 }
630 }
631 Ok(())
632 }
633 fn poll(&mut self) -> Option<HostEvent> {
634 self.pending.pop_front().or_else(|| self.inner.poll())
635 }
636 }
637 let archive = Path::new(env!("CARGO_MANIFEST_DIR"))
638 .join("../../tests/rust-app-real-worker/fixtures/sample.zip")
639 .canonicalize()
640 .unwrap();
641 for iteration in 0..100 {
642 let mut factory = CompletedFactory(ProcessFactory::new(binary("zipelo-archive-worker")));
643 let mut model = Model::default();
644 assert!(
645 model.begin(
646 Start::List {
647 archive: archive.clone()
648 },
649 &mut factory
650 ),
651 "{:?}",
652 model.error
653 );
654 assert!(model.terminal.is_none());
655 model.cancel();
656 wait(&mut model);
657 assert!(model.confirmed, "iteration={iteration}: {:?}", model.error);
658 assert_eq!(model.terminal.as_ref().unwrap().outcome, Outcome::Completed);
659 assert!(model.error.is_none());
660 }
661}
662
663#[test]
664fn cancel_racing_exit_without_terminal_remains_unconfirmed() {
665 let scratch = Scratch::new();
666 let probe = scratch.path("early-exit");
667 fs::copy(binary("zipelo-real-worker-probe"), &probe).unwrap();
668 let mut factory = ProcessFactory::new(probe);
669 let mut model = Model::default();
670 assert!(
671 model.begin(
672 Start::List {
673 archive: scratch.path("sample.zip")
674 },
675 &mut factory
676 ),
677 "{:?}",
678 model.error
679 );
680 std::thread::sleep(Duration::from_millis(2));
681 model.cancel();
682 model.request_close();
683 model.confirm_close();
684 assert_eq!(model.close, Close::Waiting);
685 wait(&mut model);
686 assert!(!model.confirmed);
687 assert!(model.terminal.is_none());
688 assert!(model.error.is_some());
689 assert_eq!(model.close, Close::Review);
690}