Skip to content

Commit

Permalink
test: update transpiler test
Browse files Browse the repository at this point in the history
  • Loading branch information
mtshiba committed Aug 24, 2023
1 parent 2035824 commit 1b04cbe
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
44 changes: 44 additions & 0 deletions crates/erg_common/python_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -893,3 +893,47 @@ pub fn exec_py_code(code: &str, args: &[&str], output: Output) -> std::io::Resul
};
out.wait()
}

pub fn exec_py_code_with_output(
code: &str,
args: &[&str],
) -> std::io::Result<std::process::Output> {
let out = if cfg!(windows) {
let fallback = |err: std::io::Error| {
// if the filename or extension is too long
// create a temporary file and execute it
if err.raw_os_error() == Some(206) {
let tmp_dir = env::temp_dir();
let tmp_file = tmp_dir.join("tmp.py");
File::create(&tmp_file)
.unwrap()
.write_all(code.as_bytes())
.unwrap();
Command::new(which_python())
.arg(tmp_file)
.args(args)
.stdout(Stdio::piped())
.spawn()
} else {
Err(err)
}
};
Command::new(which_python())
.arg("-c")
.arg(code)
.args(args)
.stdout(Stdio::piped())
.spawn()
.or_else(fallback)
.expect("cannot execute python")
} else {
let exec_command = format!("{} -c \"{code}\" {}", which_python(), args.join(" "));
Command::new("sh")
.arg("-c")
.arg(exec_command)
.stdout(Stdio::piped())
.spawn()
.expect("cannot execute python")
};
out.wait_with_output()
}
9 changes: 7 additions & 2 deletions tests/embed.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use erg::DummyVM;
use erg_common::config::ErgConfig;
use erg_common::error::MultiErrorDisplay;
use erg_common::python_util::exec_py_code_with_output;
use erg_compiler::artifact::Buildable;
use erg_compiler::module::SharedCompilerResource;
use erg_compiler::HIRBuilder;
Expand All @@ -21,11 +22,15 @@ fn test_vm_embedding() -> Result<(), ()> {
fn test_transpiler_embedding() -> Result<(), ()> {
let mut trans = Transpiler::default();
let res = trans
.transpile("print!(\"\")".into(), "exec")
.transpile("print!(\"hello\")".into(), "exec")
.map_err(|es| {
es.errors.write_all_stderr();
})?;
assert!(res.object.code().ends_with("(print)(Str(\"\"),)\n"));
assert!(res.object.code().ends_with("(print)(Str(\"hello\"),)\n"));
let code = res.object.code().replace('"', "\\\"").replace('`', "\\`");
let res = exec_py_code_with_output(&code, &[]).map_err(|_| ())?;
assert!(res.status.success());
assert_eq!(res.stdout, b"hello\n");
Ok(())
}

Expand Down

0 comments on commit 1b04cbe

Please sign in to comment.