team-ljyzipelo

공개
522줄17 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}
62struct ObservedFactory {
63 process: ProcessFactory,
64 observed: Rc<RefCell<Observation>>,
65}
66struct ObservedConnection {
67 connection: Box<dyn Connection>,
68 index: usize,
69 observed: Rc<RefCell<Observation>>,
70}
71impl Factory for ObservedFactory {
72 fn connect(&mut self, job: u64) -> Result<Box<dyn Connection>, String> {
73 let connection = self.process.connect(job)?;
74 let index = self.observed.borrow().jobs.len();
75 self.observed.borrow_mut().jobs.push(Vec::new());
76 Ok(Box::new(ObservedConnection {
77 connection,
78 index,
79 observed: self.observed.clone(),
80 }))
81 }
82}
83impl Connection for ObservedConnection {
84 fn send(&mut self, request: Request) -> Result<(), String> {
85 self.connection.send(request)
86 }
87 fn poll(&mut self) -> Option<HostEvent> {
88 let event = self.connection.poll()?;
89 let label = match &event {
90 HostEvent::StdoutEof => "stdout",
91 HostEvent::StderrEof => "stderr",
92 HostEvent::Exited { .. } => "wait",
93 HostEvent::CleanupComplete => "cleanup",
94 HostEvent::Fault(_) => "fault",
95 HostEvent::Frame {
96 event: Event::Terminal(_),
97 ..
98 } => "terminal",
99 _ => "frame",
100 };
101 self.observed.borrow_mut().jobs[self.index].push(label);
102 Some(event)
103 }
104}
105impl Drop for ObservedConnection {
106 fn drop(&mut self) {
107 self.observed.borrow_mut().jobs[self.index].push("drop");
108 }
109}
110fn observed_factory() -> (ObservedFactory, Rc<RefCell<Observation>>) {
111 let observed = Rc::new(RefCell::new(Observation::default()));
112 (
113 ObservedFactory {
114 process: ProcessFactory::new(binary("zipelo-archive-worker")),
115 observed: observed.clone(),
116 },
117 observed,
118 )
119}
120fn assert_reaped(observed: &Rc<RefCell<Observation>>) {
121 for events in &observed.borrow().jobs {
122 for label in ["terminal", "stdout", "stderr", "cleanup", "wait", "drop"] {
123 assert_eq!(
124 events.iter().filter(|value| **value == label).count(),
125 1,
126 "{events:?}"
127 );
128 }
129 assert!(!events.contains(&"fault"));
130 assert_eq!(&events[events.len() - 2..], &["wait", "drop"]);
131 }
132}
133fn wait(model: &mut Model) {
134 let deadline = Instant::now() + Duration::from_secs(10);
135 while model.busy() {
136 model.poll();
137 assert!(
138 Instant::now() < deadline,
139 "작업자 종료 시간 초과: {}",
140 model.status()
141 );
142 std::thread::sleep(Duration::from_millis(2));
143 }
144}
145fn completed(model: &Model) {
146 assert!(model.confirmed, "{}", model.status());
147 assert_eq!(model.terminal.as_ref().unwrap().outcome, Outcome::Completed);
148}
149#[cfg(feature = "ui")]
150mod screen {
151 use super::*;
152 use eframe::egui::{self, epaint::Shape};
153 use zipelo_ui_memory_app::archive_screen::ArchiveApp;
154 struct Screen {
155 context: egui::Context,
156 app: ArchiveApp,
157 }
158 impl Screen {
159 fn new(factory: ObservedFactory) -> Self {
160 Self {
161 context: egui::Context::default(),
162 app: ArchiveApp::new(Box::new(factory), None, false),
163 }
164 }
165 fn render(&mut self, events: Vec<egui::Event>) -> Vec<(String, egui::Pos2)> {
166 fn text(shape: &Shape, output: &mut Vec<(String, egui::Pos2)>) {
167 match shape {
168 Shape::Text(value) => output.push((
169 value.galley.job.text.clone(),
170 value.pos + value.galley.rect.size() / 2.0,
171 )),
172 Shape::Vec(values) => {
173 for value in values {
174 text(value, output);
175 }
176 }
177 _ => {}
178 }
179 }
180 let mut frame = self.context.run_ui(
181 egui::RawInput {
182 screen_rect: Some(egui::Rect::from_min_size(
183 egui::Pos2::ZERO,
184 egui::vec2(1060.0, 720.0),
185 )),
186 events,
187 ..Default::default()
188 },
189 |ui| self.app.show(ui),
190 );
191 frame.textures_delta.clear();
192 let mut output = Vec::new();
193 for shape in frame.shapes {
194 text(&shape.shape, &mut output);
195 }
196 output
197 }
198 fn locate(&mut self, label: &str) -> egui::Pos2 {
199 self.render(vec![]);
200 self.render(vec![])
201 .into_iter()
202 .filter(|(text, _)| text == label)
203 .max_by(|a, b| a.1.y.total_cmp(&b.1.y))
204 .unwrap_or_else(|| panic!("화면 항목 누락: {label}"))
205 .1
206 }
207 fn click_at(&mut self, point: egui::Pos2) {
208 self.render(vec![
209 egui::Event::PointerMoved(point),
210 egui::Event::PointerButton {
211 pos: point,
212 button: egui::PointerButton::Primary,
213 pressed: true,
214 modifiers: Default::default(),
215 },
216 ]);
217 self.render(vec![egui::Event::PointerButton {
218 pos: point,
219 button: egui::PointerButton::Primary,
220 pressed: false,
221 modifiers: Default::default(),
222 }]);
223 }
224 fn click(&mut self, label: &str) {
225 let point = self.locate(label);
226 self.click_at(point);
227 }
228 fn fill(&mut self, label: &str, offset: egui::Vec2, value: &Path) {
229 let point = self.locate(label) + offset;
230 self.click_at(point);
231 self.render(vec![
232 egui::Event::Key {
233 key: egui::Key::A,
234 physical_key: None,
235 pressed: true,
236 repeat: false,
237 modifiers: egui::Modifiers::COMMAND,
238 },
239 egui::Event::Text(value.to_str().unwrap().to_string()),
240 ]);
241 }
242 fn settle(&mut self) {
243 let deadline = Instant::now() + Duration::from_secs(10);
244 while self.app.model.busy() {
245 self.render(vec![]);
246 assert!(Instant::now() < deadline, "{}", self.app.model.status());
247 std::thread::sleep(Duration::from_millis(2));
248 }
249 completed(&self.app.model);
250 }
251 fn open(&mut self, archive: &Path) {
252 self.click("파일 열기");
253 self.fill("압축파일 절대 경로", egui::vec2(0.0, 22.0), archive);
254 self.click("열기");
255 assert!(self.app.model.busy());
256 self.settle();
257 }
258 fn extract(&mut self, destination: &Path) {
259 self.fill("출력 폴더", egui::vec2(100.0, 0.0), destination);
260 self.click("풀기");
261 assert!(self.app.model.busy());
262 self.settle();
263 assert_eq!(
264 self.app.model.terminal.as_ref().unwrap().publication,
265 Publication::Complete
266 );
267 }
268 }
269 include!("password_flows.rs");
270
271 fn archive_flow(name: &str, format: Format) {
272 let scratch = Scratch::new();
273 let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
274 .join("../../tests/rust-app-real-worker/fixtures")
275 .join(name);
276 let archive = scratch.path(name);
277 fs::copy(fixture, &archive).unwrap();
278 let original = fs::read(&archive).unwrap();
279 let output = make_directory(&scratch.path("output"));
280 let (factory, observed) = observed_factory();
281 let mut screen = Screen::new(factory);
282 screen.open(&archive);
283 assert_eq!(screen.app.model.list_id.as_ref().unwrap().format, format);
284 assert_eq!(screen.app.model.entries[0].name, "content.txt");
285 screen.extract(&output);
286 assert_eq!(
287 fs::read(output.join("content.txt")).unwrap(),
288 b"Zipelo real worker flow\n"
289 );
290 assert_eq!(fs::read(archive).unwrap(), original);
291 assert_eq!(observed.borrow().jobs.len(), 2);
292 assert_reaped(&observed);
293 }
294 #[test]
295 fn zip_open_and_extract_via_actual_widgets_and_worker() {
296 archive_flow("sample.zip", Format::Zip);
297 }
298 #[test]
299 fn targz_open_and_extract_via_actual_widgets_and_worker() {
300 archive_flow("sample.tar.gz", Format::TarGzip);
301 }
302 #[test]
303 fn create_zip_reopen_and_extract_via_actual_widgets_and_worker() {
304 let scratch = Scratch::new();
305 let source = scratch.path("one.txt");
306 fs::write(&source, b"ZIP creation through real worker\n").unwrap();
307 let archive = scratch.path("new.zip");
308 let output = make_directory(&scratch.path("output"));
309 let (factory, observed) = observed_factory();
310 let mut screen = Screen::new(factory);
311 screen.click("ZIP 만들기");
312 screen.fill(
313 "원본 파일 절대 경로 / 한 줄에 하나",
314 egui::vec2(0.0, 25.0),
315 &source,
316 );
317 screen.fill("저장할 ZIP 절대 경로", egui::vec2(0.0, 22.0), &archive);
318 screen.click("ZIP 만들기");
319 assert!(screen.app.model.busy());
320 screen.settle();
321 assert!(archive.is_file());
322 screen.open(&archive);
323 assert_eq!(screen.app.model.entries[0].name, "one.txt");
324 screen.extract(&output);
325 assert_eq!(
326 fs::read(output.join("one.txt")).unwrap(),
327 fs::read(source).unwrap()
328 );
329 assert_eq!(observed.borrow().jobs.len(), 3);
330 assert_reaped(&observed);
331 }
332}
333#[test]
334fn missing_worker_is_an_error_without_a_fake_result() {
335 let scratch = Scratch::new();
336 let mut factory = ProcessFactory::new(scratch.path("not-installed"));
337 let mut model = Model::default();
338 assert!(!model.begin(
339 Start::List {
340 archive: scratch.path("sample.zip")
341 },
342 &mut factory
343 ));
344 assert!(!model.busy());
345 assert!(model.error.is_some());
346 assert!(!model.confirmed);
347}
348#[test]
349fn broken_or_incomplete_worker_output_is_not_success() {
350 for name in ["truncated", "wrong-action", "early-exit"] {
351 let scratch = Scratch::new();
352 let probe = scratch.path(&format!("{name}{}", std::env::consts::EXE_SUFFIX));
353 fs::copy(binary("zipelo-real-worker-probe"), &probe).unwrap();
354 let mut factory = ProcessFactory::new(probe);
355 let mut model = Model::default();
356 assert!(model.begin(
357 Start::List {
358 archive: scratch.path("sample.zip")
359 },
360 &mut factory
361 ));
362 model.request_close();
363 model.confirm_close();
364 assert_eq!(model.close, Close::Waiting);
365 wait(&mut model);
366 assert!(!model.confirmed);
367 assert!(model.error.is_some());
368 assert_eq!(model.close, Close::Review);
369 model.acknowledge_close();
370 assert_eq!(model.close, Close::Allowed);
371 }
372}
373#[cfg(target_os = "linux")]
374#[test]
375fn dropping_live_connection_kills_and_reaps_owned_child() {
376 let scratch = Scratch::new();
377 let probe = scratch.path("hang");
378 fs::copy(binary("zipelo-real-worker-probe"), &probe).unwrap();
379 let mut factory = ProcessFactory::new(probe);
380 let mut model = Model::default();
381 assert!(model.begin(
382 Start::List {
383 archive: scratch.path("sample.zip")
384 },
385 &mut factory
386 ));
387 let deadline = Instant::now() + Duration::from_secs(5);
388 while !scratch.path("probe.pid").exists() {
389 assert!(Instant::now() < deadline);
390 std::thread::sleep(Duration::from_millis(2));
391 }
392 let pid = fs::read_to_string(scratch.path("probe.pid")).unwrap();
393 drop(model);
394 assert!(!Path::new("/proc").join(pid).exists());
395}
396
397#[test]
398fn failed_start_serialization_reaps_the_real_worker_without_terminal() {
399 let scratch = Scratch::new();
400 let mut factory = ProcessFactory::new(binary("zipelo-archive-worker"));
401 let mut model = Model::default();
402 let archive = scratch.path(&"a".repeat(40000));
403 assert!(!model.begin(Start::List { archive }, &mut factory));
404 assert!(model.busy());
405 model.request_close();
406 model.confirm_close();
407 assert_eq!(model.close, Close::Waiting);
408 wait(&mut model);
409 assert!(!model.confirmed);
410 assert!(model.terminal.is_none());
411 assert!(model.error.is_some());
412 assert_eq!(model.close, Close::Review);
413}
414
415#[test]
416fn late_cancel_after_child_reap_keeps_the_original_terminal_result() {
417 let scratch = Scratch::new();
418 let archive = scratch.path("sample.zip");
419 fs::copy(
420 Path::new(env!("CARGO_MANIFEST_DIR"))
421 .join("../../tests/rust-app-real-worker/fixtures/sample.zip"),
422 &archive,
423 )
424 .unwrap();
425 let mut factory = ProcessFactory::new(binary("zipelo-archive-worker"));
426 let mut connection = factory.connect(1).unwrap();
427 connection
428 .send(Request {
429 job_id: 1,
430 sequence: 0,
431 command: Command::Start(Start::List { archive }),
432 })
433 .unwrap();
434 let deadline = Instant::now() + Duration::from_secs(10);
435 let mut terminal = false;
436 loop {
437 assert!(Instant::now() < deadline);
438 match connection.poll() {
439 Some(HostEvent::CleanupComplete) => break,
440 Some(HostEvent::Frame {
441 event: Event::Terminal(value),
442 ..
443 }) => {
444 assert_eq!(value.outcome, Outcome::Completed);
445 terminal = true;
446 }
447 Some(HostEvent::Fault(message)) => panic!("{message}"),
448 _ => std::thread::sleep(Duration::from_millis(1)),
449 }
450 }
451 assert!(terminal);
452 assert!(
453 connection
454 .send(Request {
455 job_id: 1,
456 sequence: 1,
457 command: Command::Cancel
458 })
459 .is_ok()
460 );
461 loop {
462 assert!(Instant::now() < deadline);
463 match connection.poll() {
464 Some(HostEvent::Exited { success }) => {
465 assert!(success);
466 break;
467 }
468 Some(HostEvent::Fault(message)) => panic!("{message}"),
469 _ => std::thread::sleep(Duration::from_millis(1)),
470 }
471 }
472 assert!(connection.poll().is_none());
473}
474
475#[test]
476fn cancel_racing_child_exit_preserves_completed_result_before_poll() {
477 let archive = Path::new(env!("CARGO_MANIFEST_DIR"))
478 .join("../../tests/rust-app-real-worker/fixtures/sample.zip")
479 .canonicalize()
480 .unwrap();
481 for iteration in 0..100 {
482 let mut factory = ProcessFactory::new(binary("zipelo-archive-worker"));
483 let mut model = Model::default();
484 assert!(model.begin(
485 Start::List {
486 archive: archive.clone()
487 },
488 &mut factory
489 ));
490 std::thread::sleep(Duration::from_millis(2));
491 model.cancel();
492 wait(&mut model);
493 assert!(model.confirmed, "iteration={iteration}: {:?}", model.error);
494 assert_eq!(model.terminal.as_ref().unwrap().outcome, Outcome::Completed);
495 assert!(model.error.is_none());
496 }
497}
498
499#[test]
500fn cancel_racing_exit_without_terminal_remains_unconfirmed() {
501 let scratch = Scratch::new();
502 let probe = scratch.path("early-exit");
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!(model.begin(
507 Start::List {
508 archive: scratch.path("sample.zip")
509 },
510 &mut factory
511 ));
512 std::thread::sleep(Duration::from_millis(2));
513 model.cancel();
514 model.request_close();
515 model.confirm_close();
516 assert_eq!(model.close, Close::Waiting);
517 wait(&mut model);
518 assert!(!model.confirmed);
519 assert!(model.terminal.is_none());
520 assert!(model.error.is_some());
521 assert_eq!(model.close, Close::Review);
522}