#![cfg(unix)]
mod common;
use flow_start::Spawn as _;
use flow_toolkit::Json;
use std::collections::BTreeMap;
use std::fs;
use std::os::unix::fs::PermissionsExt as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use tempfile::TempDir;
struct Fixture {
files: TempDir,
source: PathBuf,
executable: PathBuf,
bin: PathBuf,
}
fn quoted(text: &str) -> String {
format!("'{}'", text.replace('\'', "'\"'\"'"))
}
fn script(path: &Path, source: &str) {
flow_testing::write_executable(path, source, 0o755).expect("the fixture script is written");
}
fn object(fields: Vec<(&str, Json)>) -> Json {
Json::Object(
fields
.into_iter()
.map(|(key, value)| (key.into(), value))
.collect(),
)
}
fn text(path: &Path) -> Json {
Json::String(path.to_str().expect("fixture paths are UTF-8").into())
}
const CONTRACT: &str = "// Generated by flow build from rust module fixture. Do not edit.\n\npub flow echo(value: Text) -> Result<Text, Text>\n";
fn descriptor_command(case: &str, source: &Path) -> String {
if case == "descriptor-exit" {
"printf '%s\\n' 'fixture descriptor failed' >&2; exit 8".into()
} else if case == "source-race" {
format!(
"printf '%s\\n' '#[tool] pub fn echo() {{}} // changed during build' > {}; printf '{}' > \"$5\"",
quoted(source.to_str().expect("fixture paths are UTF-8")),
common::printf_format(&common::echo_contract())
)
} else {
format!(
"if [ \"$1\" = serve ]; then printf 'serving %s\\n' \"$3\"; exit 0; fi; printf '{}' > \"$5\"",
common::printf_format(&common::echo_contract())
)
}
}
fn cargo_script(case: &str, metadata: &str, artifact: &str, dependencies: &str) -> String {
let metadata_command = if case == "metadata-exit" {
"printf '%s\\n' 'fixture metadata failed' >&2; exit 7".into()
} else {
format!("printf '%s\\n' {}", quoted(metadata))
};
let metadata_command = if case == "cargo-disappears-after-metadata" {
format!("{metadata_command}\n/bin/rm -- \"$0\"")
} else {
metadata_command
};
let build_command = if case == "build-exit" {
"printf '%s\\n' 'fixture build failed' >&2; exit 9".into()
} else {
format!("{dependencies}\nprintf '%s\\n' {}", quoted(artifact))
};
format!(
"#!/bin/sh\nif [ \"$1\" = metadata ]; then\n{metadata_command}\nelse\n{build_command}\nfi\n"
)
}
fn metadata_package(id: &str, manifest: Option<&Path>) -> Json {
let (name, version) = id
.rsplit_once('#')
.expect("the id has the form name#package@version")
.1
.rsplit_once('@')
.expect("the id has the form name#package@version");
let mut fields = vec![
("id", Json::String(id.into())),
("name", Json::String(name.into())),
("version", Json::String(version.into())),
("source", Json::Null),
];
if let Some(manifest) = manifest {
fields.push(("manifest_path", text(manifest)));
}
object(fields)
}
fn metadata_node(id: &str, dependencies: &[&str]) -> Json {
let dependencies = dependencies
.iter()
.map(|id| {
object(vec![
("pkg", Json::String((*id).into())),
(
"dep_kinds",
Json::Array(vec![object(vec![
("kind", Json::Null),
("target", Json::Null),
])]),
),
])
})
.collect();
object(vec![
("id", Json::String(id.into())),
("deps", Json::Array(dependencies)),
])
}
fn resolved_sdk_metadata(root: &Path, sdk: &Path, source: Json, identity: Option<&str>) -> String {
let selected = format!("path+file://{}#fault-fixture@0.0.0", root.display());
let source_identity =
identity.map_or_else(|| format!("path+file://{}", sdk.display()), str::to_owned);
let dependency = format!(
"{source_identity}#flow-toolkit@{}",
env!("CARGO_PKG_VERSION")
);
let mut toolkit = metadata_package(&dependency, Some(&sdk.join("Cargo.toml")));
let Json::Object(members) = &mut toolkit else {
unreachable!("the fixture package is an object")
};
members
.iter_mut()
.find(|(key, _)| key == "source")
.expect("the fixture package has a source")
.1 = source;
object(vec![
(
"packages",
Json::Array(vec![
metadata_package(&selected, Some(&root.join("Cargo.toml"))),
toolkit,
]),
),
(
"resolve",
object(vec![(
"nodes",
Json::Array(vec![
metadata_node(&selected, &[&dependency]),
metadata_node(&dependency, &[]),
]),
)]),
),
("workspace_root", text(root)),
])
.canonical()
}
fn metadata(case: &str, root: &Path, manifest: &Path) -> String {
let malformed_sdk_source = match case {
"metadata-sdk-source" => Some("directory+file:///unsupported"),
"metadata-sdk-git-commit" => Some("git+https://example.invalid/toolkit"),
"metadata-sdk-git-reference" => {
Some("git+https://example.invalid/toolkit?unsupported=topic#0123456789abcdef")
}
_ => None,
};
if let Some(source) = malformed_sdk_source {
return resolved_sdk_metadata(
root,
&common::own("").canonicalize().expect("the path exists"),
Json::String(source.into()),
None,
);
}
match case {
"metadata-malformed" => return "not JSON".into(),
"metadata-no-packages" => return "{}".into(),
_ => {}
}
let selected = format!("path+file://{}#fault-fixture@0.0.0", root.display());
let sdk = common::own("")
.canonicalize()
.expect("the toolkit source exists");
let toolkit = format!(
"path+file://{}#flow-toolkit@{}",
sdk.display(),
env!("CARGO_PKG_VERSION")
);
let dependency = "path+file:///fixture-dependency#dependency@0.0.0";
let malformed_dependency = matches!(case, "metadata-no-manifest" | "metadata-newline");
let mut packages = vec![
metadata_package(&selected, Some(manifest)),
metadata_package(&toolkit, Some(&sdk.join("Cargo.toml"))),
];
let mut dependencies = vec![toolkit.as_str()];
if malformed_dependency {
dependencies.push(dependency);
}
let mut nodes = vec![
metadata_node(&selected, &dependencies),
metadata_node(&toolkit, &[]),
];
if malformed_dependency {
let manifest = if case == "metadata-newline" {
let directory = root.join("target/line\nbreak");
fs::create_dir(&directory).expect("the fixture directory is created");
let manifest = directory.join("Cargo.toml");
fs::write(
&manifest,
"[package]\nname=\"dependency\"\nversion=\"0.0.0\"\n",
)
.expect("the fixture file is written");
Some(manifest)
} else {
None
};
packages.push(metadata_package(dependency, manifest.as_deref()));
nodes.push(metadata_node(dependency, &[]));
}
let workspace = if case == "metadata-invalid-workspace" {
fs::create_dir(root.join("target/workspace")).expect("the fixture directory is created");
fs::write(root.join("target/workspace/Cargo.toml"), "not toml!!!")
.expect("the fixture file is written");
root.join("target/workspace")
} else {
root.to_owned()
};
object(vec![
("packages", Json::Array(packages)),
("resolve", object(vec![("nodes", Json::Array(nodes))])),
("workspace_root", text(&workspace)),
])
.canonical()
}
impl Fixture {
fn new(case: &str) -> Self {
let files = TempDir::with_prefix("rust-native-faults").expect("a temporary directory");
let root = files.path();
fs::create_dir(root.join("src")).expect("the fixture directory is created");
fs::create_dir_all(root.join("target/bin")).expect("the fixture directory is created");
fs::write(
root.join("Cargo.toml"),
format!("[package]\nname=\"fault-fixture\"\nversion=\"0.0.0\"\n[profile.dev]\ndebug=1\n[dependencies]\nflow-toolkit={{path={}}}\n", toml::Value::String(common::own("").canonicalize().expect("the toolkit source exists").to_str().expect("the toolkit path is UTF-8").into())),
)
.expect("the fixture file is written");
fs::write(root.join("Cargo.lock"), "version = 4\n").expect("the fixture file is written");
fs::write(
root.join("flow.toml"),
"[process]\ncommand = \"flow-toolkit-rust serve\"\nextract = \"flow-toolkit-rust extract\"\n",
)
.expect("the fixture file is written");
let source = root.join("src/lib.rs");
fs::write(
&source,
"#[tool] pub fn echo(value:String)->Result<String,String>{Ok(value)}",
)
.expect("the fixture file is written");
let executable = root.join("target/launcher");
let bin = root.join("target/bin");
let manifest = root.join("Cargo.toml");
let metadata = metadata(case, root, &manifest);
let artifact = object(vec![
("reason", Json::String("compiler-artifact".into())),
(
"target",
object(vec![(
"name",
Json::String("flow-function-launcher".into()),
)]),
),
("executable", text(&executable)),
])
.canonical();
let dependencies = format!(
"{{ printf '%s:' {launcher}; /usr/bin/find {src} -name '*.rs' | while read -r f; do printf ' %s' \"$f\"; done; echo; }} > {information}",
launcher = quoted(executable.to_str().expect("fixture paths are UTF-8")),
src = quoted(root.join("src").to_str().expect("fixture paths are UTF-8")),
information = quoted(
executable
.with_extension("d")
.to_str()
.expect("fixture paths are UTF-8")
),
);
script(
&bin.join("cargo"),
&cargo_script(case, &metadata, &artifact, &dependencies),
);
let descriptor = descriptor_command(case, &source);
script(&executable, &format!("#!/bin/sh\n{descriptor}\n"));
if case == "descriptor-unexecutable" {
fs::set_permissions(&executable, fs::Permissions::from_mode(0o644))
.expect("the fixture permissions change");
}
Self {
files,
source,
executable,
bin,
}
}
fn cache(&self) -> PathBuf {
common::launcher_cache(self.files.path())
}
fn out(&self) -> PathBuf {
self.files.path().join("target/contract-out")
}
fn extract_with(&self, toolkit: &Path, out: &Path) -> Command {
let mut command = common::toolkit(toolkit.to_str().expect("fixture paths are UTF-8"));
command
.args(["extract", "--library"])
.arg(self.files.path())
.arg("--out")
.arg(out)
.arg("--depfile")
.arg(self.files.path().join("target/deps"))
.env("PATH", &self.bin);
command
}
fn extract(&self) -> Command {
self.extract_with(common::rust_toolkit().as_ref(), &self.out())
}
fn assert_extracted(&self) {
assert_eq!(
common::modules(&self.out()),
BTreeMap::from([(flow_types::Segments::root(), CONTRACT.to_owned())]),
"extract writes the launcher's one root module"
);
}
fn prepare(&self) -> Output {
self.extract().locked_output().expect("the command runs")
}
fn prepare_resolved_sdk(&self, sdk: &Path, source: Json, identity: Option<&str>) -> Output {
let resolved = resolved_sdk_metadata(self.files.path(), sdk, source, identity);
let cargo = self.bin.join("cargo");
let original = fs::read_to_string(&cargo).expect("the fixture file is readable");
let previous = metadata(
"success",
self.files.path(),
&self.files.path().join("Cargo.toml"),
);
script(
&cargo,
&original.replace("ed(&previous), "ed(&resolved)),
);
self.extract().locked_output().expect("the command runs")
}
fn assert_sdk_identity(&self, sdk: &Path, dependency: &str, output: &Output) -> PathBuf {
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let cache = self.cache();
let manifest = fs::read_to_string(cache.join("Cargo.toml")).expect("the launcher manifest");
assert!(
manifest.contains("[profile.dev]"),
"the launcher keeps the package's profiles: {manifest}"
);
assert_eq!(
fs::read_to_string(cache.join("Cargo.lock")).expect("the launcher lockfile"),
"version = 4\n",
"the launcher's lockfile is the one Cargo wrote"
);
assert!(
self.source.is_file() && self.executable.is_file(),
"preparation leaves the source and builds the launcher"
);
assert_eq!(
fs::read_to_string(cache.join("sdk")).expect("the recorded toolkit"),
sdk.to_str().expect("a UTF-8 path"),
"the cache records the toolkit it was built with"
);
assert_eq!(
fs::read_to_string(cache.join("sdk-dependency")).expect("the recorded dependency"),
dependency,
"the cache records the toolkit dependency"
);
assert!(
manifest.contains(&format!("flow-toolkit = {dependency}")),
"the launcher depends on that toolkit: {manifest}"
);
let isolated = self.files.path().join("target/isolated-toolkit");
let copied = Command::new("/bin/cp")
.arg(common::rust_toolkit())
.arg(&isolated)
.locked_output()
.expect("the command runs");
assert!(
copied.status.success(),
"{}",
String::from_utf8_lossy(&copied.stderr)
);
let reused_out = self.files.path().join("target/reused-contract");
let reused = self
.extract_with(&isolated, &reused_out)
.locked_output()
.expect("the command runs");
assert!(
reused.status.success(),
"{}",
String::from_utf8_lossy(&reused.stderr)
);
assert_eq!(
common::modules(&reused_out),
common::modules(&self.out()),
"a copied toolkit binary reuses the preparation"
);
isolated
}
}
#[test]
fn malformed_cargo_metadata_build_failures_and_descriptor_failures_never_publish_a_fresh_cache() {
for (case, message) in [
("metadata-exit", "fixture metadata failed"),
("metadata-malformed", "JSON"),
("metadata-no-packages", "no packages"),
("metadata-no-manifest", "Cargo metadata needs manifest_path"),
("metadata-newline", "not one line of UTF-8"),
("metadata-invalid-workspace", "TOML parse error"),
("metadata-sdk-source", "Cargo toolkit source is unsupported"),
(
"metadata-sdk-git-commit",
"Cargo Git source has no commit identity",
),
(
"metadata-sdk-git-reference",
"Cargo Git reference kind is unsupported",
),
("build-exit", "compilation failed"),
("descriptor-exit", "fixture descriptor failed"),
("descriptor-unexecutable", "native Cargo build target"),
("source-race", "changed during the build"),
] {
let fixture = Fixture::new(case);
let output = fixture.prepare();
assert_eq!(
output.status.code(),
Some(2),
"{case}: {}",
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(message), "{case}: {stderr}");
assert!(!fixture.cache().join("fingerprint").exists(), "{case}");
}
}
#[test]
fn a_declared_toolkit_dependency_does_not_depend_on_the_cargo_target_location() {
let fixture = Fixture::new("success");
let target = TempDir::with_prefix("external-cargo-target").unwrap();
let executable = target.path().join("flow-toolkit-rust");
let copied = Command::new("/bin/cp")
.arg(common::rust_toolkit())
.arg(&executable)
.locked_output()
.unwrap();
assert!(copied.status.success());
let output = fixture
.extract_with(&executable, &fixture.out())
.env("CARGO_TARGET_DIR", target.path())
.locked_output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
fixture.assert_extracted();
assert_eq!(
fs::read_to_string(fixture.cache().join("sdk")).unwrap(),
common::own("").canonicalize().unwrap().to_str().unwrap()
);
}
#[test]
fn workspace_profiles_and_lock_are_preserved_and_sdk_failures_are_actionable_without_recompiling() {
let sdk = common::own("").canonicalize().unwrap();
let version = env!("CARGO_PKG_VERSION");
let mut path_fixture = None;
for (source, identity, dependency) in [
(Json::Null, None, format!("{{ path = {:?} }}", sdk.to_str().unwrap())),
(
Json::String("registry+https://example.invalid/index".into()),
Some("registry+https://example.invalid/index"),
format!("{{ version = \"={version}\", registry-index = \"https://example.invalid/index\" }}"),
),
(
Json::String("git+https://example.invalid/flow-toolkit?branch=release/%25proof#0123456789abcdef0123456789abcdef01234567".into()),
Some("git+https://example.invalid/flow-toolkit?branch=release%2F%2525proof"),
"{ git = \"https://example.invalid/flow-toolkit\", branch = \"release/%25proof\" }".into(),
),
] {
let is_path = source == Json::Null;
let fixture = Fixture::new("success");
let output = fixture.prepare_resolved_sdk(&sdk, source, identity);
let isolated = fixture.assert_sdk_identity(&sdk, &dependency, &output);
if is_path {
path_fixture = Some((fixture, isolated));
}
}
let (fixture, isolated) = path_fixture.unwrap();
let cache = fixture.cache();
fs::remove_file(cache.join("sdk")).unwrap();
fs::remove_file(cache.join("sdk-dependency")).unwrap();
let absent = fixture
.extract_with(&isolated, &fixture.out())
.locked_output()
.unwrap();
assert_eq!(absent.status.code(), Some(2));
assert!(
String::from_utf8_lossy(&absent.stderr).contains("depends on no flow-toolkit crate"),
"{}",
String::from_utf8_lossy(&absent.stderr)
);
}
#[test]
fn corrupt_cache_artifact_kinds_refuse_without_publishing_and_recover_after_repair() {
for name in [
"prepare.lock",
"inputs",
"executable",
"fingerprint",
"Cargo.toml",
] {
let fixture = Fixture::new("success");
let cache = fixture.cache();
fs::create_dir_all(cache.join(name)).unwrap();
let refused = fixture.prepare();
assert_eq!(
refused.status.code(),
Some(2),
"{name}: {}",
String::from_utf8_lossy(&refused.stderr)
);
assert!(
refused.stdout.is_empty() && !fixture.out().exists(),
"{name}: refused preparation published a contract"
);
assert!(
String::from_utf8_lossy(&refused.stderr)
.to_lowercase()
.contains("directory"),
"{name}: {}",
String::from_utf8_lossy(&refused.stderr)
);
assert!(
!cache.join("fingerprint").is_file(),
"{name}: failed preparation acquired a success stamp"
);
fs::remove_dir(cache.join(name)).unwrap();
let repaired = fixture.prepare();
assert!(
repaired.status.success(),
"{name}: {}",
String::from_utf8_lossy(&repaired.stderr)
);
fixture.assert_extracted();
assert!(cache.join("fingerprint").is_file());
let metadata_only = fixture.extract().locked_output().unwrap();
assert!(
metadata_only.status.success(),
"{name}: repaired preparation was not reusable"
);
}
}
#[test]
fn a_launcher_cargo_reports_but_never_wrote_fails_naming_both_paths_and_recovers_once_built() {
let fixture = Fixture::new("success");
let launcher = fs::read(&fixture.executable).unwrap();
fs::remove_file(&fixture.executable).unwrap();
let refused = fixture.prepare();
let stderr = String::from_utf8_lossy(&refused.stderr);
assert_eq!(refused.status.code(), Some(2), "{stderr}");
assert!(
stderr.contains(&format!(
"{} -> {}: ",
fixture.executable.display(),
fixture.cache().join("launcher").display()
)),
"the refusal names Cargo's artifact and the cache's launcher: {stderr}"
);
assert!(
refused.stdout.is_empty() && !fixture.out().exists(),
"a launcher that was never copied publishes no contract"
);
assert!(
!fixture.cache().join("fingerprint").exists(),
"a launcher that was never copied acquires no success stamp"
);
flow_testing::write_executable(&fixture.executable, launcher, 0o755).unwrap();
let repaired = fixture.prepare();
assert!(
repaired.status.success(),
"{}",
String::from_utf8_lossy(&repaired.stderr)
);
fixture.assert_extracted();
}
#[test]
fn a_prepared_contract_that_cannot_be_written_fails_with_the_cause() {
let fixture = Fixture::new("success");
assert!(fixture.prepare().status.success());
fs::write(fixture.files.path().join("target/file"), "").unwrap();
let out = fixture.files.path().join("target/file/contract");
let output = fixture
.extract_with(common::rust_toolkit().as_ref(), &out)
.locked_output()
.unwrap();
assert_eq!(output.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(&out.display().to_string()), "{stderr}");
}
#[test]
fn a_missing_cargo_is_a_missing_toolchain_and_a_directory_without_a_cargo_package_is_no_library() {
let fixture = Fixture::new("success");
let cargo = fixture.bin.join("cargo");
let saved = fs::read(&cargo).unwrap();
fs::remove_file(&cargo).unwrap();
let refused = fixture.prepare();
assert_eq!(
refused.status.code(),
Some(2),
"{}",
String::from_utf8_lossy(&refused.stderr)
);
assert!(String::from_utf8_lossy(&refused.stderr).contains("cargo was not found on PATH"));
assert_eq!(refused.stdout, <[u8; 0]>::default());
assert!(!fixture.cache().join("fingerprint").exists());
flow_testing::write_executable(&cargo, saved, 0o755).unwrap();
assert!(fixture.prepare().status.success());
let invalid = fixture
.extract_with(common::rust_toolkit().as_ref(), &fixture.out())
.args(["--library"])
.locked_output()
.unwrap();
assert_eq!(invalid.status.code(), Some(2), "--library is given twice");
let invalid = common::toolkit(common::rust_toolkit())
.args(["extract", "--library"])
.arg(fixture.files.path().join("src"))
.arg("--out")
.arg(fixture.out())
.arg("--depfile")
.arg(fixture.files.path().join("target/deps"))
.locked_output()
.unwrap();
assert_eq!(invalid.status.code(), Some(2));
assert!(
String::from_utf8_lossy(&invalid.stderr)
.contains("a Rust library's root is the root of its Cargo package"),
"{}",
String::from_utf8_lossy(&invalid.stderr)
);
assert_eq!(invalid.stdout, <[u8; 0]>::default());
}
#[test]
fn a_missing_exported_rust_module_is_located_and_recoverable_before_any_build() {
let fixture = Fixture::new("success");
fs::write(
&fixture.source,
"pub mod actions;\n#[tool] pub fn root() {}\n",
)
.unwrap();
let refused = fixture.prepare();
assert_eq!(refused.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&refused.stderr);
assert!(stderr.contains("actions/mod.rs"), "{stderr}");
assert!(stderr.contains("No such file"), "{stderr}");
assert!(!fixture.cache().join("fingerprint").exists());
fs::write(
fixture.source.parent().unwrap().join("actions.rs"),
"#[flow_toolkit::tool] pub fn echo(value:String)->Result<String,String>{Ok(value)}\n",
)
.unwrap();
let repaired = fixture.prepare();
assert!(
repaired.status.success(),
"{}",
String::from_utf8_lossy(&repaired.stderr)
);
}
#[test]
fn serve_with_a_missing_contract_starts_nothing_and_leaves_the_launcher_current() {
let fixture = Fixture::new("success");
assert!(fixture.prepare().status.success());
let contract = fixture.files.path().join("missing-contract");
let output = common::toolkit(common::rust_toolkit())
.args(["serve", "--contract"])
.arg(contract)
.current_dir(fixture.files.path())
.env("PATH", &fixture.bin)
.locked_output()
.unwrap();
assert_eq!(output.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("No such file"), "{stderr}");
assert!(
output.stdout.is_empty(),
"the launcher must not start without its contract"
);
let cached = fixture.extract().locked_output().unwrap();
assert!(cached.status.success(), "the launcher remains current");
}
#[test]
fn one_launcher_registers_every_module_and_a_stale_one_is_built_again_before_it_serves() {
let fixture = Fixture::new("success");
fs::write(&fixture.source, "pub mod left; pub mod right;\n").unwrap();
let left = fixture.source.parent().unwrap().join("left.rs");
let right = fixture.source.parent().unwrap().join("right.rs");
fs::write(&left, "// café 🌊\n#[tool] pub fn answer() {}\n").unwrap();
fs::write(&right, "#[tool] pub fn other() {}\n").unwrap();
let output = fixture.prepare();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let launcher = fs::read_to_string(fixture.cache().join("src/main.rs")).unwrap();
for registered in [
r#"flow_toolkit::__bridge::at("left", "src/left.rs", 2, tool_impl::left::__flow_tool_answer())"#,
r#"flow_toolkit::__bridge::at("right", "src/right.rs", 1, tool_impl::right::__flow_tool_other())"#,
] {
assert!(launcher.contains(registered), "{launcher}");
}
assert!(
launcher.contains(r#"flow_toolkit::__bridge::run("fault_fixture","#),
"{launcher}"
);
fs::write(&left, "#[tool] pub fn changed() {}\n").unwrap();
let serve = |contract: &Path| {
common::toolkit(common::rust_toolkit())
.args(["serve", "--contract"])
.arg(contract)
.current_dir(fixture.files.path())
.env("PATH", &fixture.bin)
.locked_output()
.unwrap()
};
let invalid = fixture.files.path().join("target/other-version");
fs::write(&invalid, "{}").unwrap();
let refused = serve(&invalid);
assert_eq!(refused.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&refused.stderr);
assert!(
stderr.contains(&format!(
"data version 123.125, not {}",
flow_abi::DATA_VERSION
)),
"a contract file of another data version is refused naming both: {stderr}"
);
assert_eq!(refused.stdout, <[u8; 0]>::default());
let main = fixture.cache().join("src/main.rs");
assert!(
fs::read_to_string(&main)
.unwrap()
.contains("__flow_tool_answer"),
"a refused contract builds nothing"
);
let contract = fixture.files.path().join("target/contract");
let mut listing = Vec::new();
flow_abi::primitives::write_uint(&mut listing, flow_abi::DATA_VERSION.major);
flow_abi::primitives::write_uint(&mut listing, flow_abi::DATA_VERSION.minor);
flow_abi::primitives::write_uint(&mut listing, 0);
fs::write(&contract, listing).unwrap();
let served = serve(&contract);
assert!(
served.status.success(),
"{}",
String::from_utf8_lossy(&served.stderr)
);
assert_eq!(
String::from_utf8_lossy(&served.stdout),
format!("serving {}\n", contract.canonicalize().unwrap().display()),
"the launcher is started with --contract FILE"
);
assert!(
fs::read_to_string(&main)
.unwrap()
.contains("__flow_tool_changed"),
"the stale launcher is built again before it serves"
);
}
#[test]
fn missing_native_inputs_and_incomplete_toolchains_refuse_without_accepted_outputs() {
let fixture = Fixture::new("success");
let missing = fixture.files.path().join("missing-library");
let output = common::toolkit(common::rust_toolkit())
.args(["extract", "--library"])
.arg(&missing)
.arg("--out")
.arg(fixture.out())
.arg("--depfile")
.arg(fixture.files.path().join("target/deps"))
.locked_output()
.unwrap();
assert!(!output.status.success());
assert!(String::from_utf8_lossy(&output.stderr).contains("missing-library"));
assert_eq!(output.stdout, <[u8; 0]>::default());
let repaired = fixture.prepare();
assert!(
repaired.status.success(),
"{}",
String::from_utf8_lossy(&repaired.stderr)
);
assert!(fixture.cache().join("fingerprint").is_file());
}
#[test]
fn cargo_disappearing_after_metadata_refuses_then_recovers_with_the_same_source() {
let fixture = Fixture::new("cargo-disappears-after-metadata");
let cargo = fixture.bin.join("cargo");
let program = fs::read(&cargo).unwrap();
let output = fixture.prepare();
assert_eq!(
output.status.code(),
Some(2),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert!(String::from_utf8_lossy(&output.stderr).contains("cargo was not found"));
assert!(output.stdout.is_empty() && !fixture.cache().join("fingerprint").exists());
let repaired = String::from_utf8(program)
.unwrap()
.replace("/bin/rm -- \"$0\"", "");
script(&cargo, &repaired);
let output = fixture.prepare();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert!(fixture.cache().join("fingerprint").is_file());
}
#[test]
fn a_blocked_resolved_sdk_sidecar_cannot_publish_preparation_and_repair_preserves_identity() {
let sdk = common::own("").canonicalize().unwrap();
let dependency = format!("{{ path = {:?} }}", sdk.to_str().unwrap());
for name in ["sdk", "sdk-dependency"] {
let fixture = Fixture::new("success");
let cache = fixture.cache();
fs::create_dir_all(cache.join(name)).unwrap();
let refused = fixture.prepare_resolved_sdk(&sdk, Json::Null, None);
assert_eq!(refused.status.code(), Some(2));
assert!(
String::from_utf8_lossy(&refused.stderr)
.to_lowercase()
.contains("directory")
);
assert_eq!(refused.stdout, <[u8; 0]>::default());
assert!(!cache.join("fingerprint").exists());
fs::remove_dir(cache.join(name)).unwrap();
let repaired = fixture.prepare_resolved_sdk(&sdk, Json::Null, None);
fixture.assert_sdk_identity(&sdk, &dependency, &repaired);
}
}