oxedyne/fe2o3/fe2o3_core/tests/term_line.rs
16.2 KiB, 46 runs
created by r1870400018:77044, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! `term::line::LineReader` fed from a buffer and through a pipe, with what it draws read back. |
| 2 | //! |
| 3 | //! The terminal's own part (echo, line editing, Ctrl-D, the ^C it writes) cannot be had without a |
| 4 | //! terminal; what is tested is everything the reader does with the lines and the signal it is |
| 5 | //! given. The interrupt is a real `SIGINT` sent to this process by `kill`, once the listener is in |
| 6 | //! place, which the reader guarantees before `hear_interrupts` returns. Every hearing reader in |
| 7 | //! the process is told of it, so the tests that send one take `SIGNALS` in turn. The process |
| 8 | //! that must end on Ctrl-C is this test binary run again as a child. |
| 9 | |
| 10 | #![cfg(not(target_arch = "wasm32"))] |
| 11 | |
| 12 | use oxedyne_fe2o3_core::prelude::*; |
| 13 | use oxedyne_fe2o3_core::term::line::{ |
| 14 | LineEvent, |
| 15 | LineLimits, |
| 16 | LineReader, |
| 17 | }; |
| 18 | |
| 19 | use std::{ |
| 20 | io::{ |
| 21 | BufRead, |
| 22 | BufReader, |
| 23 | Cursor, |
| 24 | Read, |
| 25 | Write, |
| 26 | }, |
| 27 | future::Future, |
| 28 | process::{ |
| 29 | Command, |
| 30 | Stdio, |
| 31 | }, |
| 32 | sync::{ |
| 33 | atomic::{ |
| 34 | AtomicUsize, |
| 35 | Ordering, |
| 36 | }, |
| 37 | Arc, |
| 38 | Mutex, |
| 39 | }, |
| 40 | task::{ |
| 41 | Context, |
| 42 | Poll, |
| 43 | Waker, |
| 44 | }, |
| 45 | time::Duration, |
| 46 | }; |
| 47 | |
| 48 | const LIMITS: LineLimits = LineLimits { ahead: 8, len: 1024 }; |
| 49 | |
| 50 | static SIGNALS: Mutex<()> = Mutex::new(()); |
| 51 | |
| 52 | /// Output the test can read back while the reader holds it. |
| 53 | #[derive(Clone, Default)] |
| 54 | struct Screen(Arc<Mutex<Vec<u8>>>); |
| 55 | |
| 56 | impl Screen { |
| 57 | fn take(&self) -> Outcome<String> { |
| 58 | let mut v = lock_mutex!(self.0); |
| 59 | Ok(String::from_utf8_lossy(&std::mem::take(&mut *v)).into_owned()) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | impl Write for Screen { |
| 64 | fn write(&mut self, b: &[u8]) -> std::io::Result<usize> { |
| 65 | match self.0.lock() { |
| 66 | Ok(mut v) => { v.extend_from_slice(b); Ok(b.len()) }, |
| 67 | Err(_) => Err(std::io::Error::other("screen lock poisoned")), |
| 68 | } |
| 69 | } |
| 70 | fn flush(&mut self) -> std::io::Result<()> { Ok(()) } |
| 71 | } |
| 72 | |
| 73 | /// Polls `r.next()` until `screen` shows `want`, then drops the call part way through, as a |
| 74 | /// `select!` arm not taken is. The reader's thread delivers in its own time, so this waits a |
| 75 | /// bounded while for it. |
| 76 | fn poll_until(r: &mut LineReader<Screen>, screen: &Screen, want: &str) -> Outcome<()> { |
| 77 | let mut cx = Context::from_waker(Waker::noop()); |
| 78 | let mut f = std::pin::pin!(r.next()); |
| 79 | let mut seen = String::new(); |
| 80 | for _ in 0..500 { |
| 81 | if let Poll::Ready(e) = f.as_mut().poll(&mut cx) { |
| 82 | return Err(err!("The reader gave {:?} where it should have waited.", e; Test, Unexpected)); |
| 83 | } |
| 84 | seen.push_str(&res!(screen.take())); |
| 85 | if seen == want { |
| 86 | return Ok(()); |
| 87 | } |
| 88 | std::thread::sleep(Duration::from_millis(10)); |
| 89 | } |
| 90 | Err(err!("The screen showed {:?}, not {:?}.", seen, want; Test, Timeout)) |
| 91 | } |
| 92 | |
| 93 | fn reader(input: &'static str) -> Outcome<LineReader<Screen>> { |
| 94 | LineReader::new(Cursor::new(input.as_bytes()), Screen::default(), "> ", LIMITS) |
| 95 | } |
| 96 | |
| 97 | /// Input that counts the bytes taken from it. |
| 98 | struct Counted<R>(R, Arc<AtomicUsize>); |
| 99 | |
| 100 | impl<R: Read> Read for Counted<R> { |
| 101 | fn read(&mut self, b: &mut [u8]) -> std::io::Result<usize> { |
| 102 | let got = self.0.read(b); |
| 103 | if let Ok(n) = got { |
| 104 | self.1.fetch_add(n, Ordering::SeqCst); |
| 105 | } |
| 106 | got |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | /// Waits a bounded while for the reading thread to have taken `want` bytes. |
| 111 | fn taken(count: &AtomicUsize, want: usize) -> Outcome<()> { |
| 112 | for _ in 0..500 { |
| 113 | if count.load(Ordering::SeqCst) == want { |
| 114 | return Ok(()); |
| 115 | } |
| 116 | std::thread::sleep(Duration::from_millis(10)); |
| 117 | } |
| 118 | Err(err!("The reader took {} bytes, not {}.", count.load(Ordering::SeqCst), want; |
| 119 | Test, Timeout)) |
| 120 | } |
| 121 | |
| 122 | fn kill_int(pid: u32) -> Outcome<()> { |
| 123 | let out = res!(Command::new("kill").arg("-INT").arg(fmt!("{}", pid)).output()); |
| 124 | req!(out.status.success(), true); |
| 125 | Ok(()) |
| 126 | } |
| 127 | |
| 128 | #[tokio::test] |
| 129 | async fn backslash_lines_join_into_one_entry() -> Outcome<()> { |
| 130 | let mut r = res!(reader("one \\\ntwo\\\nthree\nfour\r\n")); |
| 131 | req!(res!(r.next().await), LineEvent::Line("one \ntwo\nthree".to_string())); |
| 132 | req!(res!(r.next().await), LineEvent::Line("four".to_string())); |
| 133 | req!(res!(r.next().await), LineEvent::End); |
| 134 | req!(res!(r.next().await), LineEvent::End, "The end is given again."); |
| 135 | Ok(()) |
| 136 | } |
| 137 | |
| 138 | #[tokio::test] |
| 139 | async fn input_ending_mid_entry_gives_the_entry_then_the_end() -> Outcome<()> { |
| 140 | let mut r = res!(reader("a\\\nb\\\n")); |
| 141 | req!(res!(r.next().await), LineEvent::Line("a\nb".to_string())); |
| 142 | req!(res!(r.next().await), LineEvent::End); |
| 143 | let mut r = res!(reader("last")); |
| 144 | req!(res!(r.next().await), LineEvent::Line("last".to_string()), "A last line without its newline."); |
| 145 | req!(res!(r.next().await), LineEvent::End); |
| 146 | let mut r = res!(reader("")); |
| 147 | req!(res!(r.next().await), LineEvent::End); |
| 148 | Ok(()) |
| 149 | } |
| 150 | |
| 151 | #[tokio::test] |
| 152 | async fn lines_through_a_pipe_arrive_as_written_and_output_goes_above_the_prompt() -> Outcome<()> { |
| 153 | let (rd, mut wr) = res!(std::io::pipe()); |
| 154 | let screen = Screen::default(); |
| 155 | let mut r = res!(LineReader::new(BufReader::new(rd), screen.clone(), "> ", LIMITS)) |
| 156 | .continuation(". "); |
| 157 | |
| 158 | res!(r.prompt()); |
| 159 | res!(r.prompt()); |
| 160 | req!(res!(screen.take()), "> ".to_string(), "The prompt is drawn once."); |
| 161 | res!(r.print("news\n")); |
| 162 | req!(res!(screen.take()), "\r\x1b[Knews\n> ".to_string()); |
| 163 | res!(r.print("part")); |
| 164 | res!(r.print("ly\n")); |
| 165 | req!(res!(screen.take()), "\r\x1b[Kpartly\n> ".to_string(), |
| 166 | "The prompt waits for the output's line to end."); |
| 167 | |
| 168 | res!(wr.write_all(b"first \\\n")); |
| 169 | res!(poll_until(&mut r, &screen, "\r\x1b[K. ")); |
| 170 | res!(wr.write_all(b"second\n")); |
| 171 | req!(res!(r.next().await), LineEvent::Line("first \nsecond".to_string())); |
| 172 | |
| 173 | req!(r.midline(), false); |
| 174 | res!(r.print("after")); |
| 175 | req!(r.midline(), true); |
| 176 | req!(res!(screen.take()), "\r\x1b[Kafter".to_string(), |
| 177 | "A pipe echoes nothing, so the entry left the prompt on its line."); |
| 178 | res!(r.prompt()); |
| 179 | req!(res!(screen.take()), "\n> ".to_string(), |
| 180 | "Once an entry is made the prompt is down until asked for."); |
| 181 | res!(r.print("more")); |
| 182 | res!(r.print_fresh("whole\n")); |
| 183 | req!(res!(screen.take()), "\r\x1b[Kmore\nwhole\n> ".to_string(), |
| 184 | "A fresh line ends the one left part way."); |
| 185 | res!(r.print_fresh("again\n")); |
| 186 | res!(r.print_fresh("")); |
| 187 | req!(res!(screen.take()), "\r\x1b[Kagain\n> ".to_string(), "Nothing is ended twice."); |
| 188 | res!(r.hide()); |
| 189 | req!(res!(screen.take()), "\r\x1b[K".to_string()); |
| 190 | |
| 191 | drop(wr); |
| 192 | req!(res!(r.next().await), LineEvent::End); |
| 193 | Ok(()) |
| 194 | } |
| 195 | |
| 196 | #[tokio::test] |
| 197 | async fn a_changed_prompt_replaces_one_that_is_up_and_waits_when_it_is_down() -> Outcome<()> { |
| 198 | let (rd, wr) = res!(std::io::pipe()); |
| 199 | let screen = Screen::default(); |
| 200 | let mut r = res!(LineReader::new(BufReader::new(rd), screen.clone(), "> ", LIMITS)); |
| 201 | |
| 202 | res!(r.set_prompt("a> ")); |
| 203 | req!(res!(screen.take()), String::new(), "A prompt that is down is not drawn by a change."); |
| 204 | res!(r.prompt()); |
| 205 | req!(res!(screen.take()), "a> ".to_string()); |
| 206 | res!(r.set_prompt("b> ")); |
| 207 | req!(res!(screen.take()), "\r\x1b[Kb> ".to_string(), "The prompt that is up is drawn again."); |
| 208 | res!(r.set_prompt("b> ")); |
| 209 | req!(res!(screen.take()), String::new(), "The same prompt is not drawn twice."); |
| 210 | res!(r.print("news\n")); |
| 211 | req!(res!(screen.take()), "\r\x1b[Knews\nb> ".to_string()); |
| 212 | |
| 213 | drop(wr); |
| 214 | req!(res!(r.next().await), LineEvent::End); |
| 215 | Ok(()) |
| 216 | } |
| 217 | |
| 218 | #[cfg(unix)] |
| 219 | #[tokio::test] |
| 220 | async fn ctrl_c_is_an_event_and_discards_the_entry_being_made() -> Outcome<()> { |
| 221 | let (rd, mut wr) = res!(std::io::pipe()); |
| 222 | let screen = Screen::default(); |
| 223 | let _turn = lock_mutex!(SIGNALS); |
| 224 | let mut r = res!(res!(LineReader::new(BufReader::new(rd), screen.clone(), "> ", LIMITS)) |
| 225 | .continuation(". ") |
| 226 | .hear_interrupts()); |
| 227 | res!(r.prompt()); |
| 228 | req!(res!(screen.take()), "> ".to_string()); |
| 229 | res!(wr.write_all(b"begun \\\n")); |
| 230 | res!(poll_until(&mut r, &screen, "\r\x1b[K. ")); |
| 231 | res!(kill_int(std::process::id())); |
| 232 | req!(res!(r.next().await), LineEvent::Interrupt); |
| 233 | res!(wr.write_all(b"fresh\n")); |
| 234 | req!(res!(r.next().await), LineEvent::Line("fresh".to_string()), |
| 235 | "The entry begun before Ctrl-C is gone."); |
| 236 | drop(wr); |
| 237 | req!(res!(r.next().await), LineEvent::End); |
| 238 | Ok(()) |
| 239 | } |
| 240 | |
| 241 | #[cfg(unix)] |
| 242 | #[tokio::test] |
| 243 | async fn ctrl_c_is_heard_while_input_is_held_and_comes_before_the_lines_that_wait() -> Outcome<()> { |
| 244 | let (rd, mut wr) = res!(std::io::pipe()); |
| 245 | let count = Arc::new(AtomicUsize::new(0)); |
| 246 | let _turn = lock_mutex!(SIGNALS); |
| 247 | let mut r = res!(res!(LineReader::new(BufReader::new(Counted(rd, count.clone())), |
| 248 | Screen::default(), "", LIMITS)).hear_interrupts()); |
| 249 | // Told after `r`, so once it has heard the interrupt `r` holds one too. |
| 250 | let mut after = res!(res!(reader("")).hear_interrupts()); |
| 251 | let deaf = res!(reader("")).interrupt().await.is_err(); |
| 252 | req!(deaf, true, "Nothing is heard unasked."); |
| 253 | |
| 254 | res!(wr.write_all(b"whole\nbegun \\\n")); |
| 255 | res!(taken(&count, 14)); |
| 256 | res!(kill_int(std::process::id())); |
| 257 | res!(after.interrupt().await); |
| 258 | res!(wr.write_all(b"fresh\n")); |
| 259 | res!(r.interrupt().await); |
| 260 | req!(res!(r.next().await), LineEvent::Line("whole".to_string()), |
| 261 | "An entry made while input was held is kept."); |
| 262 | req!(res!(r.next().await), LineEvent::Line("fresh".to_string()), |
| 263 | "The entry begun before Ctrl-C is gone, though it is taken after."); |
| 264 | |
| 265 | res!(wr.write_all(b"waiting\n")); |
| 266 | res!(taken(&count, 28)); |
| 267 | res!(kill_int(std::process::id())); |
| 268 | res!(after.interrupt().await); |
| 269 | req!(res!(r.next().await), LineEvent::Interrupt, "The interrupt passes the line that waits."); |
| 270 | req!(res!(r.next().await), LineEvent::Line("waiting".to_string())); |
| 271 | Ok(()) |
| 272 | } |
| 273 | |
| 274 | /// An entry begun before Ctrl-C and finished by a line read before it, though not yet taken, is |
| 275 | /// whole when it is taken; one still open at Ctrl-C is discarded however late it is taken. |
| 276 | #[cfg(unix)] |
| 277 | #[tokio::test] |
| 278 | async fn ctrl_c_keeps_an_entry_finished_before_it_and_taken_after() -> Outcome<()> { |
| 279 | for (rest, later, want) in [ |
| 280 | ("b\n", "", "a \nb"), |
| 281 | ("b \\\n", "c\n", "c"), |
| 282 | ] { |
| 283 | let (rd, mut wr) = res!(std::io::pipe()); |
| 284 | let count = Arc::new(AtomicUsize::new(0)); |
| 285 | let screen = Screen::default(); |
| 286 | let _turn = lock_mutex!(SIGNALS); |
| 287 | let mut r = res!(res!(LineReader::new(BufReader::new(Counted(rd, count.clone())), |
| 288 | screen.clone(), "> ", LIMITS)).continuation(". ").hear_interrupts()); |
| 289 | // Told after `r`, so once it has heard the interrupt `r` holds one too. |
| 290 | let mut after = res!(res!(reader("")).hear_interrupts()); |
| 291 | res!(r.prompt()); |
| 292 | req!(res!(screen.take()), "> ".to_string()); |
| 293 | res!(wr.write_all(b"a \\\n")); |
| 294 | res!(poll_until(&mut r, &screen, "\r\x1b[K. ")); |
| 295 | res!(wr.write_all(rest.as_bytes())); |
| 296 | res!(taken(&count, 4 + rest.len())); |
| 297 | res!(kill_int(std::process::id())); |
| 298 | res!(after.interrupt().await); |
| 299 | res!(r.interrupt().await); |
| 300 | res!(wr.write_all(later.as_bytes())); |
| 301 | // Taken once, since req! evaluates its operands again to report a mismatch. |
| 302 | let got = res!(r.next().await); |
| 303 | req!(got, LineEvent::Line(want.to_string()), "After {:?}.", rest); |
| 304 | drop(wr); |
| 305 | req!(res!(r.next().await), LineEvent::End); |
| 306 | } |
| 307 | Ok(()) |
| 308 | } |
| 309 | |
| 310 | /// Lines without end, each `LEN` bytes with its ending. |
| 311 | struct Endless; |
| 312 | |
| 313 | const LEN: usize = 16; |
| 314 | |
| 315 | impl Read for Endless { |
| 316 | fn read(&mut self, b: &mut [u8]) -> std::io::Result<usize> { |
| 317 | let n = b.len().min(LEN); |
| 318 | b[..n].fill(b'x'); |
| 319 | if n == LEN { |
| 320 | b[LEN - 1] = b'\n'; |
| 321 | } |
| 322 | Ok(n) |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | #[tokio::test] |
| 327 | async fn input_the_caller_does_not_take_is_not_read_past_the_limits() -> Outcome<()> { |
| 328 | let limits = LineLimits { ahead: 4, len: 64 }; |
| 329 | let count = Arc::new(AtomicUsize::new(0)); |
| 330 | let input = BufReader::with_capacity(LEN, Counted(Endless, count.clone())); |
| 331 | let mut r = res!(LineReader::new(input, Screen::default(), "", limits)); |
| 332 | // The channel holds `ahead` lines and the thread one more, which it waits to send. |
| 333 | res!(taken(&count, (limits.ahead + 1) * LEN)); |
| 334 | std::thread::sleep(Duration::from_millis(100)); |
| 335 | req!(count.load(Ordering::SeqCst), (limits.ahead + 1) * LEN, "The thread waits for the caller."); |
| 336 | req!(res!(r.next().await), LineEvent::Line("x".repeat(LEN - 1))); |
| 337 | |
| 338 | let count = Arc::new(AtomicUsize::new(0)); |
| 339 | let input = BufReader::with_capacity(LEN, Counted(std::io::repeat(b'x'), count.clone())); |
| 340 | let mut r = res!(LineReader::new(input, Screen::default(), "", limits)); |
| 341 | let e = match r.next().await { |
| 342 | Ok(ev) => return Err(err!("A line without end gave {:?}.", ev; Test, Unexpected)), |
| 343 | Err(e) => e, |
| 344 | }; |
| 345 | req!(e.tags().contains(&ErrTag::TooBig), true); |
| 346 | let took = count.load(Ordering::SeqCst); |
| 347 | req!(took > limits.len && took <= limits.len + 2 * LEN, true, |
| 348 | "The line is given up at its limit, not {} bytes on.", took); |
| 349 | req!(res!(r.next().await), LineEvent::End, "A failed read is the end of the input."); |
| 350 | Ok(()) |
| 351 | } |
| 352 | |
| 353 | /// A reader that heard interrupts and has gone must not leave the process deaf to Ctrl-C. The |
| 354 | /// process under signal is this binary again, running only this test, with `CHILD` set. |
| 355 | #[cfg(unix)] |
| 356 | #[tokio::test] |
| 357 | async fn ctrl_c_ends_the_process_once_no_reader_hears() -> Outcome<()> { |
| 358 | const CHILD: &str = "FE2O3_TERM_LINE_CHILD"; |
| 359 | const SAID: &str = "no reader hears"; |
| 360 | if std::env::var_os(CHILD).is_some() { |
| 361 | drop(res!(res!(reader("")).hear_interrupts())); |
| 362 | println!("{}", SAID); |
| 363 | std::thread::sleep(Duration::from_secs(10)); |
| 364 | return Err(err!("Ctrl-C did not end the process."; Test, Timeout)); |
| 365 | } |
| 366 | let mut child = res!(Command::new(res!(std::env::current_exe())) |
| 367 | .args(["--exact", "ctrl_c_ends_the_process_once_no_reader_hears", "--nocapture"]) |
| 368 | .env(CHILD, "1") |
| 369 | .stdout(Stdio::piped()) |
| 370 | .stderr(Stdio::null()) |
| 371 | .spawn()); |
| 372 | let out = res!(child.stdout.take().ok_or_else(|| err!("The child has no output."; Test, Missing))); |
| 373 | let mut said = false; |
| 374 | for line in BufReader::new(out).lines() { |
| 375 | if res!(line).contains(SAID) { |
| 376 | said = true; |
| 377 | break; |
| 378 | } |
| 379 | } |
| 380 | req!(said, true, "The child ended before its reader was dropped."); |
| 381 | res!(kill_int(child.id())); |
| 382 | req!(res!(child.wait()).code(), Some(130), "128 + SIGINT, as the default action reports."); |
| 383 | Ok(()) |
| 384 | } |
| 385 | |
| 386 | /// With a stop listener installed, before the reader or after it, Ctrl-C with no hearing reader |
| 387 | /// left is the stop listener's alone to answer: the line listener stands down rather than end the |
| 388 | /// process. |
| 389 | #[cfg(unix)] |
| 390 | #[tokio::test] |
| 391 | async fn ctrl_c_with_no_reader_is_left_to_the_stop_listener() -> Outcome<()> { |
| 392 | const CHILD: &str = "FE2O3_TERM_LINE_STOP_CHILD"; |
| 393 | const SAID: &str = "no reader hears"; |
| 394 | const STOPPED: i32 = 7; |
| 395 | let stop = || oxedyne_fe2o3_core::stop::on_stop_request(|_| std::process::exit(STOPPED)); |
| 396 | if let Some(order) = std::env::var_os(CHILD) { |
| 397 | let before = order == "before"; |
| 398 | if before { |
| 399 | res!(stop()); |
| 400 | } |
| 401 | drop(res!(res!(reader("")).hear_interrupts())); |
| 402 | if !before { |
| 403 | res!(stop()); |
| 404 | } |
| 405 | println!("{}", SAID); |
| 406 | std::thread::sleep(Duration::from_secs(10)); |
| 407 | return Err(err!("Ctrl-C did not end the process."; Test, Timeout)); |
| 408 | } |
| 409 | for order in ["before", "after"] { |
| 410 | let mut child = res!(Command::new(res!(std::env::current_exe())) |
| 411 | .args(["--exact", "ctrl_c_with_no_reader_is_left_to_the_stop_listener", "--nocapture"]) |
| 412 | .env(CHILD, order) |
| 413 | .stdout(Stdio::piped()) |
| 414 | .stderr(Stdio::null()) |
| 415 | .spawn()); |
| 416 | let out = res!(child.stdout.take().ok_or_else(|| err!("The child has no output."; Test, Missing))); |
| 417 | let mut said = false; |
| 418 | for line in BufReader::new(out).lines() { |
| 419 | if res!(line).contains(SAID) { |
| 420 | said = true; |
| 421 | break; |
| 422 | } |
| 423 | } |
| 424 | req!(said, true, "The child ended before its reader was dropped."); |
| 425 | res!(kill_int(child.id())); |
| 426 | req!(res!(child.wait()).code(), Some(STOPPED), "Stop listener installed {} the reader.", order); |
| 427 | } |
| 428 | Ok(()) |
| 429 | } |