Setting environment variables from the build script via cargo::rustc-env
#1787
-
Hi all, I have a crate with a C-API where I am using inline_c to test the C-API within the Rust test harness. In order for the tests to work, I need to set some flags for inline_c, which incline_c recommends to be done via I am aware that I could probably solve this with a setup script, but since setting the variables from the build script works for As a proof of concept, with this (admittedly hacky for now) change, my tests work. If this sounds like a feature worth having, I would be up for implementing it more nicely. diff --git a/nextest-runner/src/test_command.rs b/nextest-runner/src/test_command.rs
index 82955758..e3b6d90b 100644
--- a/nextest-runner/src/test_command.rs
+++ b/nextest-runner/src/test_command.rs
@@ -74,7 +74,22 @@ impl TestCommand {
{
// Convert the output directory to an absolute path.
let out_dir = lctx.rust_build_meta.target_directory.join(out_dir);
- cmd.env("OUT_DIR", out_dir);
+ cmd.env("OUT_DIR", out_dir.as_str());
+ // Set environment variables set via the `cargo::rustc-env` key
+ if let Ok(out_file) = std::fs::File::open(out_dir.parent().unwrap().join("output")) {
+ use std::io::BufRead;
+ for line in std::io::BufReader::new(out_file).lines() {
+ let line = line.unwrap();
+ let Some(key_val) = line
+ .strip_prefix("cargo:rustc-env=")
+ .or_else(|| line.strip_prefix("cargo::rustc-env="))
+ else {
+ continue;
+ };
+ let split = key_val.find('=').unwrap();
+ cmd.env(&key_val[..split], &key_val[split + 1..]);
+ }
+ }
}
// Expose paths to non-test binaries at runtime so that relocated paths work. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Thanks for the question. I agree that nextest should be doing this (it takes great pains to run tests in the same environment as cargo), and I'm surprised this is the first time someone's run into this! |
Beta Was this translation helpful? Give feedback.
-
Right, I was also surprised to not find anything on this yet. I'll write up a cleaner implementation and send a PR then. |
Beta Was this translation helpful? Give feedback.
Thanks for the question. I agree that nextest should be doing this (it takes great pains to run tests in the same environment as cargo), and I'm surprised this is the first time someone's run into this!