/tests/repl.rs

https://github.com/lark-exploration/lark · Rust · 85 lines · 66 code · 17 blank · 2 comment · 3 complexity · 984af3e6d8bd895bac3ebcf3ac20378c MD5 · raw file

  1. #[cfg(test)]
  2. mod tests {
  3. use std::io::{Read, Write};
  4. use std::panic;
  5. use std::process::{Command, Stdio};
  6. struct ChildSession {
  7. child: std::process::Child,
  8. }
  9. impl Drop for ChildSession {
  10. fn drop(&mut self) {
  11. let _ = self.child.kill();
  12. }
  13. }
  14. impl ChildSession {
  15. fn spawn() -> ChildSession {
  16. let child = Command::new("cargo")
  17. .arg("run")
  18. .arg("--")
  19. .arg("repl")
  20. .stdin(Stdio::piped())
  21. .stdout(Stdio::piped())
  22. .spawn()
  23. .expect("Failed to spawn child process");
  24. ChildSession { child }
  25. }
  26. /// Helper function to do the work of sending a result back to the IDE
  27. fn send(&mut self, msg: &str) -> Result<(), Box<std::error::Error>> {
  28. let child_stdin = self.child.stdin.as_mut().ok_or(std::io::Error::new(
  29. std::io::ErrorKind::BrokenPipe,
  30. "can connect to child stdin",
  31. ))?;
  32. child_stdin
  33. .write_all(msg.as_bytes())
  34. .expect("Failed to write to stdin");
  35. //let _ = io::stdout().flush();
  36. Ok(())
  37. }
  38. fn receive(&mut self) -> Result<String, Box<std::error::Error>> {
  39. let child_stdout = self.child.stdout.as_mut().ok_or(std::io::Error::new(
  40. std::io::ErrorKind::BrokenPipe,
  41. "can connect to child stdout",
  42. ))?;
  43. let mut buffer = String::new();
  44. let mut character = [0; 1];
  45. loop {
  46. child_stdout.read(&mut character[..])?;
  47. let ch = character[0] as char;
  48. eprintln!("{}", ch);
  49. buffer.push(ch);
  50. if ch == '>' {
  51. eprintln!("break");
  52. break;
  53. }
  54. }
  55. Ok(buffer)
  56. }
  57. }
  58. #[test]
  59. fn repl_test_assignment() {
  60. let mut child_session = ChildSession::spawn();
  61. let _ = child_session.receive();
  62. child_session.send("let x = true\n").unwrap();
  63. let _result = child_session.receive().unwrap();
  64. child_session.send("debug(x)\n").unwrap();
  65. let result = child_session.receive().unwrap();
  66. assert_eq!(result, " true\n>");
  67. }
  68. }