team-ljyzipelo

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