#![expect(
missing_docs,
reason = "the test binary's tool fixtures are public by the derive's rule"
)]
#![expect(
clippy::missing_errors_doc,
reason = "a tool's doc comment is its Flow declaration's text, which the tests read back"
)]
use flow_abi_testing::crossing::{bytes, crossed, read};
use flow_start::Spawn as _;
use flow_toolkit::{Flow, Int, ToolProblem, tool};
type Note = Option<String>;
#[derive(Flow, Clone, Debug, PartialEq)]
pub struct Record {
pub amount: Int,
pub note: Note,
pub next: Option<Box<Record>>,
}
#[derive(Flow, Debug, PartialEq)]
pub enum Error {
Empty,
Detail(String),
Pair(Int, String),
Named { value: Int, note: Note },
}
#[tool]
pub fn exact(amount: Int) -> Result<Record, Error> {
Ok(Record {
amount,
note: None,
next: None,
})
}
#[tool]
pub async fn asynchronous(value: String) -> Result<String, ToolProblem> {
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
Ok(value)
}
#[tool]
#[expect(
clippy::too_many_arguments,
clippy::fn_params_excessive_bools,
reason = "one parameter for each kind of default"
)]
pub fn find(
query: String,
#[flow(default = 20)] limit: Int,
#[flow(default = -1)] offset: Int,
#[flow(default = true)] exact: bool,
#[flow(default = "a \"b\" ${x}")] label: String,
#[flow(default = None)] owner: Option<String>,
#[flow(default = Some(2))] page: Option<Int>,
#[flow(default = "any")] tag: Option<String>,
) -> Vec<String> {
let _ = (limit, offset, exact, label, owner, page, tag);
vec![query]
}
#[derive(Flow, Debug, PartialEq)]
pub enum Tone {
Plain,
Loud,
}
#[tool]
pub fn say(text: String, #[flow(default = Plain)] tone: Tone) -> String {
match tone {
Tone::Plain => text,
Tone::Loud => text.to_uppercase(),
}
}
#[tool]
pub fn contextual(
context: &flow_toolkit::Context,
value: String,
) -> Result<String, std::convert::Infallible> {
if context.cancelled() {
return Ok("cancelled".into());
}
Ok(value)
}
fn extract(functions: Vec<flow_toolkit::__bridge::Function>) -> Result<String, String> {
let placed = functions
.into_iter()
.map(|function| flow_toolkit::__bridge::at("", "tests/functions.rs", 1, function))
.collect::<Vec<_>>();
common::extract("functions", None, &placed)
.map(|modules| modules.into_values().collect::<Vec<_>>().join("\n"))
.map_err(|error| error.to_string())
}
#[test]
fn a_parameter_default_is_written_after_its_type_as_a_flow_literal() {
let source = extract(vec![__flow_tool_find()]).unwrap();
assert!(
source.contains(
r#"pub flow find(query: Text, limit: Int = 20, offset: Int = -1, exact: Bool = true, label: Text = "a \"b\" \${x}", owner: Option<Text> = None, page: Option<Int> = Some(2), tag: Option<Text> = Some("any")) -> List<Text>"#
),
"{source}"
);
assert_eq!(
find(
"q".into(),
Int::from(1),
Int::from(0),
false,
String::new(),
None,
None,
None
),
["q"],
"the Rust function is still called with every argument"
);
}
#[test]
fn a_constructor_default_is_written_bare_after_its_enum_type() {
let source = extract(vec![__flow_tool_say()]).unwrap();
assert!(
source.contains("pub flow say(text: Text, tone: Tone = Plain) -> Text\n"),
"{source}"
);
assert_eq!(say("hi".into(), Tone::Loud), "HI");
assert_eq!(say("hi".into(), Tone::Plain), "hi");
}
#[test]
fn a_result_of_problem_declares_its_value_type_and_any_other_return_is_declared_whole() {
let source = extract(vec![__flow_tool_asynchronous(), __flow_tool_exact()]).unwrap();
assert!(
source.contains("pub flow asynchronous(value: Text) -> Text\n"),
"{source}"
);
assert!(
source.contains("pub flow exact(amount: Int) -> Result<Record, Error>\n"),
"{source}"
);
}
#[test]
fn invocation_context_is_injected_without_becoming_a_flow_parameter() {
let source = extract(vec![__flow_tool_contextual()]).unwrap();
assert!(source.contains("contextual(value: Text)"));
assert!(!source.contains("context:"));
}
#[test]
fn extracted_source_has_exact_types_recursive_records_and_typed_errors() {
let source = extract(vec![__flow_tool_exact(), __flow_tool_asynchronous()]).unwrap();
assert!(source.contains(
"pub type Record {\n pub amount: Int,\n pub note: Option<Text>,\n pub next: Option<Record>,\n}\n"
), "{source}");
assert!(source.contains("pub flow exact(amount: Int) -> Result<Record, Error>"));
assert!(source.contains(" Pair(Int, Text),\n"));
assert!(
source.contains(" Named {\n value: Int,\n note: Option<Text>,\n },\n"),
"{source}"
);
assert_eq!(source.matches("pub type Record").count(), 1);
}
#[test]
fn derived_values_preserve_large_integers_optional_fields_and_every_enum_payload() {
let number = Int::parse("999999999999999999999999999999999999999999").unwrap();
let record = exact(number.clone()).unwrap();
assert_eq!(record.amount, number);
assert_eq!(crossed(&record).0, record);
for error in [
Error::Empty,
Error::Detail("details".into()),
Error::Pair(number.clone(), "pair".into()),
Error::Named {
value: number,
note: None,
},
] {
assert_eq!(crossed(&error).0, error);
}
}
#[test]
fn a_named_variant_may_have_a_field_called_fields() {
#[derive(Flow, Clone, Debug, PartialEq)]
enum Form {
Listed { fields: Vec<String> },
}
let form = Form::Listed {
fields: vec!["a".into()],
};
assert_eq!(crossed(&form), (form.clone(), vec![0, 1, 1, b'a']));
}
#[test]
fn derived_records_and_enums_write_fields_in_declaration_order_and_constructors_by_number() {
let record = Record {
amount: Int::from(3),
note: None,
next: Some(Box::new(Record {
amount: Int::from(-1),
note: Some("n".into()),
next: None,
})),
};
assert_eq!(
crossed(&record),
(record.clone(), vec![6, 0, 1, 1, 1, 1, b'n', 0])
);
let number = Int::parse("999999999999999999999999999999999999999999").unwrap();
for (error, head) in [
(Error::Empty, 0),
(Error::Detail("details".into()), 1),
(Error::Pair(number.clone(), "pair".into()), 2),
(
Error::Named {
value: number,
note: None,
},
3,
),
] {
let (crossed, bytes) = crossed(&error);
assert_eq!(bytes[0], head, "{error:?}");
assert_eq!(crossed, error);
}
assert_eq!(bytes(&Session("abc".into())), [3, b'a', b'b', b'c']);
}
#[test]
fn async_functions_remain_directly_callable_with_a_real_runtime() {
assert_eq!(
flow_toolkit::__bridge::block_on(asynchronous("ready".into())).unwrap(),
"ready"
);
}
#[test]
fn duplicate_exported_names_are_refused() {
assert!(
extract(vec![__flow_tool_exact(), __flow_tool_exact()])
.unwrap_err()
.contains("duplicate Tool name")
);
}
mod common;
#[test]
fn a_launcher_whose_contract_cannot_be_written_fails_with_the_cause() {
let files = tempfile::TempDir::with_prefix("flow-function-extract").unwrap();
std::fs::write(files.path().join("file"), "").unwrap();
let out = files.path().join("file").join("out");
let output = std::process::Command::new(env!("CARGO_BIN_EXE_flow-toolkit-functions-sample"))
.args(["extract", "--library", env!("CARGO_MANIFEST_DIR"), "--out"])
.arg(&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 generated_function_process_preserves_logging_exact_values_and_all_failure_modes() {
use tempfile::TempDir;
let files = TempDir::with_prefix("flow-function-process").unwrap();
let executable = env!("CARGO_BIN_EXE_flow-toolkit-functions-sample");
let project = flow_testing::Project::new(common::outside(), &[], &[]);
common::stage_contract(
project.path(),
&sample_contract(files.path(), &[]),
&format!("\"{executable}\" serve"),
"pub flow main(mode: Text) -> Result<Result<lib.Value, lib.Error>, ToolProblem> = lib.answer(mode, 9007199254740993)\n",
);
for (mode, expected, code) in [
("ok", "Ok(Ok(Value { value: 9007199254740993 }))", 0),
("rejected", r#"Ok(Err(Rejected("no")))"#, 0),
(
"not-started",
r#"Err(NotStarted("the queue is closed"))"#,
1,
),
(
"interrupted",
r#"Err(Interrupted("the worker stopped"))"#,
1,
),
(
"network",
r#"Err(NetworkError { sent: true, reason: "the reply was lost" })"#,
1,
),
] {
let output = project.flow(&["run", "main.flow", &format!("mode={mode}")]);
assert_eq!(
output.status.code(),
Some(code),
"{mode}: {}",
common::said(&output)
);
assert_eq!(
String::from_utf8_lossy(&output.stdout),
format!("{expected}\n"),
"{mode}"
);
}
let output = project.flow(&["run", "main.flow", "mode=panic"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.code(),
Some(3),
"the run stays open: {stderr}"
);
assert!(
stderr.contains("the implementation stopped: stopped unexpectedly")
&& stderr.contains("open root#1\n"),
"{stderr}"
);
}
fn sample_contract(
dir: &std::path::Path,
environment: &[(&str, &std::path::Path)],
) -> std::collections::BTreeMap<flow_types::Segments, String> {
let out = dir.join("extracted");
let extracted = std::process::Command::new(env!("CARGO_BIN_EXE_flow-toolkit-functions-sample"))
.args(["extract", "--library", env!("CARGO_MANIFEST_DIR"), "--out"])
.arg(&out)
.envs(environment.iter().copied())
.locked_output()
.expect("the fixture step succeeds");
assert!(
extracted.status.success(),
"{}",
String::from_utf8_lossy(&extracted.stderr)
);
assert!(
extracted.stdout.is_empty(),
"the contract is written to files"
);
let modules = common::modules(&out);
let [(module, text)] = Vec::from_iter(&modules)[..] else {
panic!("one contract module: {modules:?}")
};
assert_eq!(
module, "",
"the sample's Tools and types are in its root module"
);
assert!(
text.starts_with("// Generated by flow build from rust module flow_toolkit_functions_sample. Do not edit.\n"),
"{text}"
);
assert!(
text.contains("// from tests/functions/tool.rs: Value\n"),
"{text}"
);
modules
}
#[test]
fn a_refusal_answers_its_own_error_inside_the_declared_result_and_the_rest_as_problems() {
use tempfile::TempDir;
let files = TempDir::with_prefix("flow-function-refusal").unwrap();
let executable = env!("CARGO_BIN_EXE_flow-toolkit-functions-sample");
let contract = sample_contract(files.path(), &[]);
let text = contract.values().next().expect("the root module");
assert!(
text.contains("pub flow refuse(mode: Text, value: Int) -> Result<Value, Error>\n"),
"{text}"
);
let project = flow_testing::Project::new(common::outside(), &[], &[]);
common::stage_contract(
project.path(),
&contract,
&format!("\"{executable}\" serve"),
"pub flow main(mode: Text) -> Result<Result<lib.Value, lib.Error>, ToolProblem> = lib.refuse(mode, 9007199254740993)\n",
);
for (mode, expected, code) in [
("ok", "Ok(Ok(Value { value: 9007199254740993 }))", 0),
("rejected", r#"Ok(Err(Rejected("no")))"#, 0),
(
"not-started",
r#"Err(NotStarted("the queue is closed"))"#,
1,
),
(
"interrupted",
r#"Err(Interrupted("the worker stopped"))"#,
1,
),
] {
let output = project.flow(&["run", "main.flow", &format!("mode={mode}")]);
assert_eq!(
output.status.code(),
Some(code),
"{mode}: {}",
common::said(&output)
);
assert_eq!(
String::from_utf8_lossy(&output.stdout),
format!("{expected}\n"),
"{mode}"
);
}
}
fn answer_listing(contracts: &std::collections::BTreeMap<flow_types::Segments, String>) -> Vec<u8> {
common::listing(contracts, &common::referring(&["lib.answer"]))
}
fn answer_index(listing: &[u8]) -> u64 {
let programs = flow_abi::read_listing(listing).expect("the compiler's contract file");
programs[0]
.tools
.iter()
.position(|(identity, _)| identity.name == "answer")
.and_then(|at| u64::try_from(at).ok())
.expect("the sample serves answer")
}
#[test]
fn function_toolkit_binary_explains_a_missing_command() {
assert!(
flow_toolkit::__bridge::run("functions", &[], None)
.unwrap_err()
.contains("; usage: serve --contract FILE")
);
let output = std::process::Command::new(common::rust_toolkit())
.locked_output()
.unwrap();
assert_eq!(output.status.code(), Some(2));
assert!(
String::from_utf8(output.stderr)
.unwrap()
.contains("no command; usage: serve --contract FILE")
);
}
#[cfg(unix)]
#[test]
#[expect(
clippy::too_many_lines,
reason = "one process is described, called twice, read frame by frame and started twice more"
)]
fn asynchronous_process_resource_opens_once_and_closes_after_two_calls_without_metadata_effects() {
use std::io::Write as _;
use std::process::{Command, Stdio};
let files = tempfile::TempDir::with_prefix("flow-resource-process").unwrap();
let events = files.path().join("events");
let executable = env!("CARGO_BIN_EXE_flow-toolkit-functions-sample");
let contracts = sample_contract(files.path(), &[("FLOW_RESOURCE_EVENTS", &events)]);
assert!(!events.exists());
let contract = files.path().join("contract");
let listing = answer_listing(&contracts);
std::fs::write(&contract, &listing).unwrap();
let mut child = Command::new(executable)
.args(["serve", "--contract"])
.arg(&contract)
.env("FLOW_RESOURCE_EVENTS", &events)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.locked_spawn()
.unwrap();
let mut input = child.stdin.take().unwrap();
let value = Int::parse("9007199254740993").unwrap();
let mut args = bytes(&"ok".to_owned());
args.extend(bytes(&value));
input
.write_all(
&flow_tool_protocol::Message::Describe {
version: flow_abi::DATA_VERSION,
reply_limit: 16 << 20,
}
.frame(),
)
.unwrap();
let run = flow_span::RunId::parse("7f3a91c04be2d5e6f708192a3b4c5d6e").unwrap();
for call in ["root#1", "root#2"] {
let call = flow_tool_protocol::Message::Call(flow_tool_protocol::Call::new(
run,
flow_span::CallRef::parse(call).unwrap(),
answer_index(&listing),
None,
&args,
));
input.write_all(&call.frame()).unwrap();
}
drop(input);
let output = child.wait_with_output().unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let mut frames = Vec::new();
let mut stdout = std::io::Cursor::new(output.stdout);
while let Some(flow_tool_protocol::Frame::Body(body)) =
flow_tool_protocol::read_frame(&mut stdout, usize::MAX).unwrap()
{
frames.push(
flow_tool_protocol::Message::parse(flow_tool_protocol::Route::Process, &body).unwrap(),
);
}
assert!(
matches!(
frames.first(),
Some(flow_tool_protocol::Message::Described { .. })
),
"{frames:?}"
);
let (logs, replies): (Vec<_>, Vec<_>) = frames
.into_iter()
.skip(1)
.partition(|frame| matches!(frame, flow_tool_protocol::Message::Log(_)));
let mut logged = logs
.into_iter()
.map(|log| {
let flow_tool_protocol::Message::Log(log) = log else {
unreachable!()
};
assert_eq!(log.run, Some(run), "the call's log line names its run");
assert_eq!(
(log.level, log.message.as_str()),
(flow_toolkit::Level::Info, "function fixture answer"),
"the call's log line carries its typed level"
);
log.call
.expect("the call's log line names its call")
.to_string()
})
.collect::<Vec<_>>();
logged.sort();
assert_eq!(logged, ["root#1", "root#2"]);
assert_eq!(replies.len(), 2);
for reply in replies {
let flow_tool_protocol::Message::Reply(reply) = reply else {
panic!("a reply: {reply:?}")
};
let flow_abi::Outcome::Ok(bytes) = reply.outcome else {
panic!("{:?}", reply.outcome)
};
assert_eq!(read::<Result<Int, String>>(&bytes.0), Ok(value.clone()));
}
assert_eq!(std::fs::read_to_string(events).unwrap(), "start\nclose:2\n");
assert!(
String::from_utf8(output.stderr)
.unwrap()
.contains("ordinary function logging without a newline"),
"ordinary output goes to standard error, beside the protocol"
);
for (mode, message, expected) in [
(
"init-error",
"initialization failed: fixture startup refused: the pool is closed for the test",
"start\n",
),
("close-error", "cleanup failed", "start\nclose:0\n"),
] {
let event_file = files.path().join(mode);
let output = Command::new(executable)
.args(["serve", "--contract"])
.arg(&contract)
.env("FLOW_RESOURCE_EVENTS", &event_file)
.env("FLOW_RESOURCE_MODE", mode)
.stdin(Stdio::null())
.locked_output()
.unwrap();
assert_eq!(output.status.code(), Some(2));
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(stderr.contains(message), "{stderr}");
assert_eq!(std::fs::read_to_string(event_file).unwrap(), expected);
assert_eq!(output.stdout, <[u8; 0]>::default());
}
}
#[test]
#[expect(
clippy::too_many_lines,
reason = "one real library is built, reused, served and made stale in sequence"
)]
fn native_preparation_uses_cargo_artifact_path_for_an_explicit_host_target() {
use std::fs;
use std::process::Command;
let version = Command::new("rustc").arg("-vV").locked_output().unwrap();
assert!(version.status.success());
let version = String::from_utf8(version.stdout).unwrap();
let target = version
.lines()
.find_map(|line| line.strip_prefix("host: "))
.unwrap();
let files = tempfile::TempDir::with_prefix("flow-native-target").unwrap();
let root = files.path().canonicalize().unwrap();
fs::create_dir(root.join("src")).unwrap();
let sdk = common::own("");
fs::write(
root.join("flow.toml"),
"[process]\ncommand = \"flow-toolkit-rust serve\"\nextract = \"flow-toolkit-rust extract\"\n",
)
.unwrap();
fs::write(root.join("src/lib.rs"),r#"
pub mod imported;
#[flow_toolkit::lifespan]
pub fn resources()->Result<flow_toolkit::Resource<()>,String>{
if std::env::var_os("FLOW_TEST_SERVING").is_none() { panic!("extraction must not initialize resources") }
Ok(flow_toolkit::Resource::sync((), |_| Ok(())))
}
"#).unwrap();
let imported = root.join("src/imported.rs");
fs::write(
&imported,
"#[flow_toolkit::tool] pub fn echo(value:String)->String{value}",
)
.unwrap();
let manifest = root.join("Cargo.toml");
common::toolkit_consumer(&root, "native-target-fixture", "");
fs::create_dir(root.join("target")).unwrap();
let out = root.join("target/contract");
let prepared = native_extract(&root, target, &out, &root.join("target/deps"))
.locked_output()
.unwrap();
assert!(
prepared.status.success(),
"{}",
String::from_utf8_lossy(&prepared.stderr)
);
assert!(
prepared.stdout.is_empty(),
"the contract is written to files"
);
let modules = common::modules(&out);
let Some(contract) = modules.get("imported") else {
panic!("the module imported has a contract: {modules:?}")
};
assert_eq!(
contract,
"// Generated by flow build from rust module native_target_fixture::imported. Do not edit.\n\n// from src/imported.rs: echo\npub flow echo(value: Text) -> Text\n"
);
assert_eq!(
modules.get(""),
None,
"a module without Tools has no contract"
);
let cache = common::launcher_cache(&root);
let executable = fs::read_to_string(cache.join("executable")).unwrap();
assert_eq!(std::path::Path::new(&executable), cache.join("launcher"));
let compiled = common::cache_home()
.join("flow-toolkit-rust/target")
.join(format!("{target}/release/flow-function-launcher"));
assert_eq!(
fs::read(&executable).unwrap(),
fs::read(&compiled).unwrap(),
"the cached launcher copies Cargo's artifact for the explicit target"
);
let relocated = root.join("target").join(format!(
"relocated-launcher{}",
std::env::consts::EXE_SUFFIX
));
fs::copy(&executable, &relocated).unwrap();
let relocated_out = root.join("target/relocated-contract");
let relocated = Command::new(relocated)
.args(["extract", "--library"])
.arg(&root)
.arg("--out")
.arg(&relocated_out)
.locked_output()
.unwrap();
assert!(relocated.status.success());
assert_eq!(common::modules(&relocated_out), modules);
let depfile = root.join("target/native-deps");
let cached_out = root.join("target/cached-contract");
let cached = native_extract(&root, target, &cached_out, &depfile)
.env("PATH", "")
.locked_output()
.unwrap();
assert!(
cached.status.success(),
"{}",
String::from_utf8_lossy(&cached.stderr)
);
assert_eq!(common::modules(&cached_out), modules);
let deps = common::depfile(&depfile);
assert!(deps.iter().all(|path| path.is_absolute()));
assert!(deps.contains(&fs::canonicalize(&imported).unwrap()));
assert!(deps.contains(&fs::canonicalize(&manifest).unwrap()));
assert!(
!deps.contains(&root.join("flow.toml")),
"flow.toml is no build input; the host watches it itself"
);
assert!(deps.contains(&fs::canonicalize(sdk.join("src/function.rs")).unwrap()));
assert!(!deps.contains(&std::path::PathBuf::from(&executable)));
fs::create_dir(root.join("contract")).unwrap();
fs::write(root.join("contract/imported.flow"), contract).unwrap();
assert_eq!(
serve_echo(
&native_extract(&root, target, &out, &depfile),
&root,
contract
),
"served",
"the crate launcher serves the module's Tool from the compiler's listing"
);
let written = native_extract(&root, target, &out, &depfile)
.env("PATH", "")
.locked_output()
.unwrap();
assert!(
written.status.success(),
"a written contract leaves the launcher current: {}",
String::from_utf8_lossy(&written.stderr)
);
fs::write(
&imported,
"#[flow_toolkit::tool] pub fn echo(value:String)->String{value}\ncompile_error!(\"must not compile without cargo\");",
)
.unwrap();
let stale_depfile = root.join("target/stale-deps");
let stale = native_extract(&root, target, &out, &stale_depfile)
.env("PATH", "")
.locked_output()
.unwrap();
assert_eq!(
stale.status.code(),
Some(2),
"a missing toolchain is a refusal: {}",
String::from_utf8_lossy(&stale.stderr)
);
assert!(String::from_utf8_lossy(&stale.stderr).contains("cargo was not found"));
assert!(
common::depfile(&stale_depfile).contains(&fs::canonicalize(&imported).unwrap()),
"a failed extraction still names the paths it read"
);
}
fn serve_echo(like: &std::process::Command, root: &std::path::Path, contract: &str) -> String {
use std::io::Write as _;
let staged =
tempfile::TempDir::with_prefix("flow-native-serve").expect("the fixture step succeeds");
let listing = staged.path().join("contract");
std::fs::write(
&listing,
common::listing(
&std::collections::BTreeMap::from([(
"imported".parse().expect("a test path is a path"),
contract.to_owned(),
)]),
&common::referring(&["imported.echo"]),
),
)
.expect("the fixture step succeeds");
let mut child = common::toolkit(common::rust_toolkit())
.envs(
like.get_envs()
.filter_map(|(key, value)| Some((key, value?))),
)
.args(["serve", "--contract"])
.arg(&listing)
.current_dir(root)
.env("PATH", "")
.env("FLOW_TEST_SERVING", "1")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.locked_spawn()
.expect("the fixture step succeeds");
let mut input = child.stdin.take().expect("the fixture step succeeds");
let call = flow_tool_protocol::Message::Call(flow_tool_protocol::Call::new(
flow_span::RunId::parse("7f3a91c04be2d5e6f708192a3b4c5d6e")
.expect("the fixture step succeeds"),
flow_span::CallRef::parse("root#1").expect("the fixture step succeeds"),
0,
None,
&bytes(&"served".to_owned()),
));
input
.write_all(
&flow_tool_protocol::Message::Describe {
version: flow_abi::DATA_VERSION,
reply_limit: 16 << 20,
}
.frame(),
)
.expect("the fixture step succeeds");
input
.write_all(&call.frame())
.expect("the fixture step succeeds");
drop(input);
let output = child.wait_with_output().expect("the fixture step succeeds");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let mut stdout = std::io::Cursor::new(output.stdout);
let mut replies = Vec::new();
while let Some(flow_tool_protocol::Frame::Body(body)) =
flow_tool_protocol::read_frame(&mut stdout, usize::MAX).expect("the fixture step succeeds")
{
replies.push(
flow_tool_protocol::Message::parse(flow_tool_protocol::Route::Process, &body)
.expect("the fixture step succeeds"),
);
}
assert!(
matches!(
replies.first(),
Some(flow_tool_protocol::Message::Described { .. })
),
"{replies:?}"
);
let Some(flow_tool_protocol::Message::Reply(reply)) = replies.get(1) else {
panic!("a reply: {replies:?}")
};
let flow_abi::Outcome::Ok(bytes) = &reply.outcome else {
panic!("{:?}", reply.outcome)
};
read::<String>(&bytes.0)
}
fn native_extract(
root: &std::path::Path,
target: &str,
out: &std::path::Path,
depfile: &std::path::Path,
) -> std::process::Command {
let mut command = common::toolkit(common::rust_toolkit());
command
.args(["extract", "--library"])
.arg(root)
.arg("--out")
.arg(out)
.arg("--depfile")
.arg(depfile)
.env("CARGO_BUILD_TARGET", target)
.env("CARGO_NET_OFFLINE", "true");
command
}
mod first {
use flow_toolkit::Flow;
#[derive(Flow, Debug)]
pub struct Shared {
pub text: String,
}
}
mod second {
use flow_toolkit::Flow;
#[derive(Flow, Debug)]
pub struct Shared {
pub number: Int,
}
use flow_toolkit::Int;
}
#[derive(Flow, Debug)]
pub struct Colliding {
pub first: first::Shared,
pub second: second::Shared,
}
#[tool]
pub fn collision_in_one_function(value: Colliding) -> Result<Colliding, Error> {
Ok(value)
}
#[expect(
unreachable_pub,
reason = "#[tool] and its types are public, here inside function bodies"
)]
mod scopes {
use flow_toolkit::__bridge::Function;
use flow_toolkit::{Flow, Int, tool};
pub fn first() -> Function {
#[derive(Flow, Debug)]
pub struct Shared {
pub text: String,
}
#[tool]
pub fn collision_first(value: Shared) -> Result<Shared, String> {
Ok(value)
}
__flow_tool_collision_first()
}
pub fn second() -> Function {
#[derive(Flow, Debug)]
pub struct Shared {
pub number: Int,
}
#[tool]
pub fn collision_second(value: Shared) -> Result<Shared, String> {
Ok(value)
}
__flow_tool_collision_second()
}
}
#[derive(Flow, Debug)]
pub struct Containers {
pub list: Vec<Int>,
pub set: std::collections::BTreeSet<String>,
pub dict: std::collections::BTreeMap<String, Int>,
pub pair: (Int, String),
pub triple: (Int, String, bool),
pub quad: (Int, String, bool, ()),
pub raw: flow_toolkit::JsonValue,
}
#[tool]
pub fn containers(value: Containers) -> Result<Containers, Error> {
Ok(value)
}
#[test]
fn metadata_preserves_collection_shapes_docs_json_import_and_rejects_type_name_collisions() {
let source = extract(vec![__flow_tool_containers()]).unwrap();
for text in [
"List<Int>",
"Set<Text>",
"Dict<Text, Int>",
"(Int, Text)",
"(Int, Text, Bool)",
"(Int, Text, Bool, Unit)",
"use \"std@v1/json\"",
"/// Keeps collection shapes",
] {
assert!(source.contains(text), "{text}: {source}");
}
let modules = extract(vec![__flow_tool_collision_in_one_function()]).unwrap();
assert!(
modules.contains("use \"./first\"\nuse \"./second\"\n")
&& modules.contains(" pub first: first.Shared,\n pub second: second.Shared,\n"),
"two modules' types of one name are each imported: {modules}"
);
assert!(
extract(vec![scopes::first(), scopes::second()])
.unwrap_err()
.contains("distinct Rust types share the Flow name Shared in one module")
);
let value = Record {
amount: Int::from(3),
note: Some("present".into()),
next: Some(Box::new(Record {
amount: Int::from(4),
note: None,
next: None,
})),
};
assert_eq!(crossed(&value).0, value);
}
#[derive(Flow, Debug, PartialEq)]
pub struct GenericRecord<T> {
pub value: T,
pub note: Option<T>,
}
#[derive(flow_toolkit::Handle, Debug, PartialEq)]
pub struct Session(pub String);
#[tool]
pub fn identity<T: flow_toolkit::Shaped>(value: T) -> Result<T, String> {
Ok(value)
}
#[tool]
pub fn wrap_generic<T: flow_toolkit::Shaped>(value: T) -> Result<GenericRecord<T>, String> {
Ok(GenericRecord { value, note: None })
}
#[test]
fn ordinary_generic_functions_and_host_types_own_their_declarations() {
assert_eq!(identity(Int::from(7)).unwrap(), Int::from(7));
let source = extract(vec![__flow_tool_identity(), __flow_tool_wrap_generic()]).unwrap();
assert!(
source.contains(
"pub type GenericRecord<T> {\n pub value: T,\n pub note: Option<T>,\n}\n"
),
"{source}"
);
assert!(
source.contains("identity<T>(value: T) -> Result<T, Text>"),
"{source}"
);
let mut types = flow_toolkit::__bridge::Types::default();
assert_eq!(
types.form(<GenericRecord<Int> as flow_toolkit::Shaped>::FORM),
flow_toolkit::__bridge::TypeRef::Named {
module: Some(flow_toolkit::__bridge::Owner::Rust("functions")),
name: "GenericRecord".to_owned(),
args: vec![flow_toolkit::__bridge::TypeRef::named("Int")],
}
);
assert_eq!(crossed(&Session("tab-1".into())).0, Session("tab-1".into()));
}
#[test]
fn retired_rust_authoring_apis_are_absent_in_an_otherwise_working_native_project() {
let project = tempfile::TempDir::with_prefix("flow-retired-rust-api").unwrap();
std::fs::create_dir(project.path().join("src")).unwrap();
let source = project.path().join("src/lib.rs");
std::fs::write(&source,"use flow_toolkit::{tool,Int}; #[tool] pub fn echo(value:Int)->Result<Int,String>{Ok(value)}\n#[tool] pub fn page(query:String, #[flow(default = 20)] limit:Int, #[flow(default = None)] owner:Option<String>)->Vec<String>{let _ = (limit, owner); vec![query]}").unwrap();
common::toolkit_consumer(project.path(), "flow-removal-consumer", "");
let positive = check_consumer(project.path());
assert!(
positive.status.success(),
"{}",
String::from_utf8_lossy(&positive.stderr)
);
for (old, expected) in [
(
"use flow_toolkit::{Server, Declaration, Args};",
"unresolved imports",
),
("use flow_toolkit::generate;", "unresolved import"),
("use flow_toolkit::TypeSpec;", "unresolved import"),
("use flow_toolkit::lifecycle;", "unresolved import"),
("use flow_toolkit::function;", "private"),
(
"pub fn obsolete(){ let _ = flow_toolkit::__bridge::Function::new; }",
"private",
),
(
"pub fn obsolete(){ let _ = flow_toolkit::data::parse_type_spec; }",
"cannot find",
),
(
"pub fn obsolete(){ flow_toolkit::function::serve(&[],\"{}\",None).unwrap(); }",
"private",
),
] {
std::fs::write(&source, old).unwrap();
let rejected = check_consumer(project.path());
assert!(
!rejected.status.success(),
"retired API still compiles: {old}"
);
assert!(
String::from_utf8_lossy(&rejected.stderr).contains(expected),
"{}",
String::from_utf8_lossy(&rejected.stderr)
);
}
}
#[tool]
pub fn r#fn(r#ref: String) -> Result<String, String> {
Ok(r#ref)
}
#[test]
fn native_rust_keyword_spelling_is_absent_from_the_flow_contract() {
let source = extract(vec![__flow_tool_fn()]).unwrap();
assert!(source.contains("flow fn(ref: Text)"), "{source}");
}
#[test]
fn generic_native_collections_reject_values_from_a_different_concrete_call() {
use flow_toolkit::Encoded;
use flow_types::Type;
use std::collections::BTreeMap;
let number = common::bound_call(Type::Int, Vec::new())
.decode::<Encoded>("9007199254740993")
.unwrap();
let values = vec![number.clone()];
assert_eq!(
common::written_at(&values, &Type::list(Type::Int), Vec::new()).unwrap(),
bytes(&vec![Int::parse("9007199254740993").unwrap()])
);
assert!(
common::written_at(&values, &Type::list(Type::Text), Vec::new()).is_none(),
"the target call's concrete type must be checked again"
);
let mapping = BTreeMap::from([("n".to_owned(), number)]);
assert!(
common::written_at(&mapping, &Type::dict(Type::Text, Type::Text), Vec::new()).is_none(),
"an admitted integer cannot become a Text value"
);
}
#[test]
fn generic_text_dictionaries_roundtrip_native_optional_values_and_validate_every_entry() {
use flow_types::Type;
use std::collections::{BTreeMap, BTreeSet};
let call = common::bound_call(Type::dict(Type::Text, Type::option(Type::Int)), Vec::new());
let native = BTreeMap::from([("b".to_owned(), Some(Int::from(9))), ("a".to_owned(), None)]);
let encoded = call.to_json(&native).unwrap();
assert_eq!(encoded, r#"{"a":"None","b":{"Some":9}}"#);
assert_eq!(
call.decode::<BTreeMap<String, Option<Int>>>(&encoded)
.unwrap(),
native
);
assert!(
call.decode::<BTreeMap<String, Option<Int>>>(r#"{"a":{"Some":"wrong"}}"#)
.is_err()
);
let list = common::bound_call(Type::list(Type::Int), Vec::new());
let set = common::bound_call(Type::set(Type::Int), Vec::new());
assert!(list.decode::<Vec<Int>>(r#""not a list""#).is_err());
assert!(set.decode::<BTreeSet<Int>>(r#"[1,"wrong"]"#).is_err());
}
fn check_consumer(project: &std::path::Path) -> std::process::Output {
std::process::Command::new("cargo")
.args([
"check",
"--offline",
"--locked",
"--quiet",
"--manifest-path",
])
.arg(project.join("Cargo.toml"))
.arg("--target-dir")
.arg(flow_testing::repository_root().join("target/rust-toolkit-removal-consumer"))
.locked_output()
.expect("cargo runs")
}
#[test]
fn a_constructor_default_the_enum_cannot_spell_as_a_unit_pattern_is_a_compile_error() {
let project = tempfile::TempDir::with_prefix("flow-constructor-default-consumer").unwrap();
std::fs::create_dir(project.path().join("src")).unwrap();
let source = project.path().join("src/lib.rs");
let declared = |name: &str| {
format!(
"#[derive(flow_toolkit::Flow)] pub enum Level {{ Info, Detail(String), Named {{ note: String }} }}\n#[flow_toolkit::tool] pub fn note(#[flow(default = {name})] level:Level){{let _ = level;}}"
)
};
std::fs::write(&source, declared("Info")).unwrap();
common::toolkit_consumer(project.path(), "flow-constructor-default-consumer", "");
let positive = check_consumer(project.path());
assert!(
positive.status.success(),
"{}",
String::from_utf8_lossy(&positive.stderr)
);
for (name, expected) in [
("Warning", "constant named `Warning` found for enum `Level`"),
(
"Detail",
"expected unit struct, unit variant or constant, found tuple variant",
),
(
"Named",
"expected unit struct, unit variant or constant, found struct variant",
),
] {
std::fs::write(&source, declared(name)).unwrap();
let rejected = check_consumer(project.path());
let diagnostic = String::from_utf8_lossy(&rejected.stderr);
assert!(!rejected.status.success(), "{name} was accepted");
assert!(
diagnostic.contains(expected),
"expected {expected:?} for {name}\n{diagnostic}"
);
assert!(
diagnostic.contains(&format!("#[flow(default = {name})]")),
"the error points at the attribute: {diagnostic}"
);
}
}
#[test]
fn malformed_native_markers_report_their_own_errors_in_a_working_consumer() {
let project = tempfile::TempDir::with_prefix("flow-malformed-native-consumer").unwrap();
std::fs::create_dir(project.path().join("src")).unwrap();
let source = project.path().join("src/lib.rs");
std::fs::write(&source,"use flow_toolkit::{tool,Int}; #[tool] pub fn echo(value:Int)->Result<Int,String>{Ok(value)}\n#[tool] pub fn page(query:String, #[flow(default = 20)] limit:Int, #[flow(default = None)] owner:Option<String>)->Vec<String>{let _ = (limit, owner); vec![query]}").unwrap();
common::toolkit_consumer(project.path(), "flow-malformed-consumer", "");
let positive = check_consumer(project.path());
assert!(
positive.status.success(),
"{}",
String::from_utf8_lossy(&positive.stderr)
);
for (declaration, expected) in [
(
"#[flow_toolkit::tool(unexpected)] pub fn invalid()->Result<(),String>{Ok(())}",
"#[tool] takes no arguments",
),
(
"#[flow_toolkit::tool] pub fn invalid<'a>()->Result<(),String>{Ok(())}",
"lifetimes and const parameters are unsupported",
),
(
"#[flow_toolkit::tool] pub fn invalid()->Result<(),flow_toolkit::ToolProblem<String>>{Ok(())}",
"ToolProblem and NoAnswer take no type argument",
),
(
"#[flow_toolkit::tool] pub fn invalid()->Result<(),flow_toolkit::Refusal>{Ok(())}",
"Refusal takes the Tool's own error type",
),
(
"#[flow_toolkit::tool] pub fn invalid(#[flow(default = \"twenty\")] limit:flow_toolkit::Int)->bool{let _ = limit; true}",
"DefaultText",
),
(
"#[flow_toolkit::tool] pub fn invalid(#[flow(default = None)] limit:flow_toolkit::Int)->bool{let _ = limit; true}",
"DefaultOption",
),
(
"#[flow_toolkit::tool] pub fn invalid<T: flow_toolkit::Shaped>(#[flow(default = 0)] value:T)->bool{let _ = value; true}",
"DefaultInt",
),
(
"#[derive(flow_toolkit::Flow)] #[flow(opaque)] pub struct Invalid(String);",
"expected #[flow(std = \"module.Name\")], naming a std declaration; a host type derives Handle",
),
(
"#[derive(flow_toolkit::Flow)] #[flow(std = \"code\")] pub struct Invalid(flow_toolkit::Encoded);",
"`code` names no std declaration",
),
(
"#[derive(flow_toolkit::Handle)] pub struct Invalid { handle:String }",
"a host type is a nongeneric tuple struct with one String field",
),
(
"#[derive(flow_toolkit::Handle)] pub struct Invalid<T>(T);",
"a host type is a nongeneric tuple struct with one String field",
),
(
"#[derive(flow_toolkit::Handle)] pub struct Invalid(String,String);",
"a host type is a nongeneric tuple struct with one String field",
),
(
"mod ids { #[derive(flow_toolkit::Flow)] pub struct Token(pub(crate) String); }\n#[flow_toolkit::tool] pub fn invalid(#[flow(default = ids::Token(\"t\"))] token: ids::Token) { let _ = token; }",
"this default needs a newtype's private constructor from another module, which the contract cannot write",
),
(
"mod ids { #[derive(flow_toolkit::Flow)] pub struct Token(String); }\n#[flow_toolkit::tool] pub fn invalid(#[flow(default = ids::Token(\"t\"))] token: ids::Token) { let _ = token; }",
"private",
),
(
"#[flow_toolkit::lifespan] pub fn invalid(value:String)->Result<flow_toolkit::Resource<()>,String>{unreachable!()}",
"#[lifespan] requires a public safe nongeneric zero-argument Rust function",
),
] {
std::fs::write(&source, declaration).unwrap();
let rejected = check_consumer(project.path());
let diagnostic = String::from_utf8_lossy(&rejected.stderr);
assert!(
!rejected.status.success(),
"invalid declaration was accepted: {declaration}"
);
assert!(
diagnostic.contains(expected),
"expected {expected:?} for {declaration}\n{diagnostic}"
);
assert!(
!diagnostic.contains("failed to get"),
"dependency failure is not a declaration refusal: {diagnostic}"
);
assert!(
!diagnostic.contains("error[E0412]") && !diagnostic.contains("error[E0433]"),
"a name the fixture uses resolves, so the refusal is the declaration's: {diagnostic}"
);
}
}
#[tool]
pub fn positional_failure() -> Result<(), (String, String)> {
Err(("left".into(), "right".into()))
}
#[test]
fn native_tuple_failures_keep_their_payload_without_a_problem_wrapper() {
assert_eq!(positional_failure(), Err(("left".into(), "right".into())));
let source = extract(vec![__flow_tool_positional_failure()]).unwrap();
assert!(
source.contains("positional_failure() -> Result<Unit, (Text, Text)>"),
"{source}"
);
}
#[cfg(unix)]
#[test]
fn a_corrupt_native_contract_refuses_before_resource_initialization() {
use std::process::{Command, Stdio};
let files = tempfile::TempDir::with_prefix("flow-native-corrupt-contract").unwrap();
let executable = env!("CARGO_BIN_EXE_flow-toolkit-functions-sample");
let mut listing = answer_listing(&sample_contract(files.path(), &[]));
listing.pop().expect("a contract file is not empty");
let contract = files.path().join("corrupt");
std::fs::write(&contract, listing).unwrap();
let events = files.path().join("resource-events");
let refused = Command::new(executable)
.args(["serve", "--contract"])
.arg(contract)
.env("FLOW_RESOURCE_EVENTS", &events)
.stdin(Stdio::null())
.locked_output()
.unwrap();
assert_eq!(refused.status.code(), Some(2));
assert!(String::from_utf8_lossy(&refused.stderr).contains("the contract file is invalid"));
assert_eq!(refused.stdout, <[u8; 0]>::default());
assert!(
!events.exists(),
"corrupt metadata must refuse before initializing an application resource"
);
}
#[derive(Flow, Debug)]
pub struct FrameInner<T> {
pub value: T,
}
#[derive(Flow, Debug)]
pub struct FrameOuter<A, B> {
pub inner: FrameInner<A>,
pub tail: B,
}
#[tool]
pub fn nested_frame() -> Result<FrameOuter<Int, String>, String> {
Ok(FrameOuter {
inner: FrameInner {
value: Int::from(1),
},
tail: "ok".into(),
})
}
#[test]
fn nested_generic_declarations_restore_the_enclosing_parameter_names() {
let source = extract(vec![__flow_tool_nested_frame()]).unwrap();
assert!(
source.contains(
"pub type FrameOuter<A, B> {\n pub inner: FrameInner<A>,\n pub tail: B,\n}\n"
),
"{source}"
);
assert!(
source.contains("pub type FrameInner<T> {\n pub value: T,\n}\n"),
"{source}"
);
}
#[tool]
pub fn nested_result_data() -> Result<Vec<Result<Int, String>>, String> {
Ok(vec![Ok(Int::from(42)), Err("invalid field".into())])
}
#[test]
fn nested_result_type_metadata_keeps_tool_completion_separate() {
let source = extract(vec![__flow_tool_nested_result_data()]).unwrap();
assert!(
source.contains("nested_result_data() -> Result<List<Result<Int, Text>>, Text>"),
"{source}"
);
let nested = nested_result_data().unwrap();
assert_eq!(crossed(&nested).0, nested);
}
#[test]
fn generic_results_select_each_concrete_payload_without_erasing_generic_values() {
use flow_toolkit::Encoded;
use flow_types::{DeclId, Type};
let call = common::bound_call(
Type::Named(DeclId(0), vec![Type::Int, Type::Text]),
vec![common::std_result()],
);
for source in [
r#"{"Ok":9007199254740993}"#,
r#"{"Err":"malformed decimal"}"#,
] {
let decoded = call.decode::<Result<Encoded, Encoded>>(source).unwrap();
assert_eq!(call.to_json(&decoded).unwrap(), source);
}
for source in [
r#""Ok""#,
r#"{"Unknown":1}"#,
r#"{"Ok":"wrong"}"#,
r#"{"Err":17}"#,
] {
assert!(
call.decode::<Result<Encoded, Encoded>>(source).is_err(),
"accepted {source}"
);
}
let wrong = Ok::<String, String>("wrong".into());
assert!(call.to_json(&wrong).is_err());
let integer = common::bound_call(Type::Int, Vec::new());
assert!(integer.to_json(&Ok::<Int, String>(Int::from(1))).is_err());
}
#[test]
fn a_generic_value_is_written_only_at_its_calls_types() {
let value = common::bound_call(flow_types::Type::Int, Vec::new())
.decode::<flow_toolkit::Encoded>("1")
.unwrap();
assert_eq!(
common::written_at(&value, &flow_types::Type::Int, Vec::new()).unwrap(),
bytes(&Int::from(1))
);
}
#[test]
fn a_launcher_whose_contract_path_is_a_directory_fails_with_the_cause() {
let files = tempfile::TempDir::with_prefix("flow-function-module").unwrap();
let out = files.path().join("out");
std::fs::create_dir_all(&out).unwrap();
let output = std::process::Command::new(env!("CARGO_BIN_EXE_flow-toolkit-functions-sample"))
.args(["extract", "--library", env!("CARGO_MANIFEST_DIR"), "--out"])
.arg(&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_launcher_whose_contract_cannot_be_read_fails_with_the_cause() {
let files = tempfile::TempDir::with_prefix("flow-function-unread-contract").unwrap();
let contract = files.path().join("missing-contract");
let output = std::process::Command::new(env!("CARGO_BIN_EXE_flow-toolkit-functions-sample"))
.args(["serve", "--contract"])
.arg(&contract)
.locked_output()
.unwrap();
assert_eq!(output.status.code(), Some(2));
assert_eq!(output.stdout, Vec::<u8>::new());
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains(&contract.display().to_string()), "{stderr}");
assert_eq!(std::fs::read_dir(files.path()).unwrap().count(), 0);
}
#[cfg(unix)]
#[test]
fn a_launcher_whose_host_stops_reading_ends_failed() {
use std::io::Write as _;
use std::process::{Command, Stdio};
let files = tempfile::TempDir::with_prefix("flow-function-unread").unwrap();
let contract = files.path().join("contract");
std::fs::write(
&contract,
answer_listing(&sample_contract(files.path(), &[])),
)
.unwrap();
let mut child = Command::new(env!("CARGO_BIN_EXE_flow-toolkit-functions-sample"))
.args(["serve", "--contract"])
.arg(&contract)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.locked_spawn()
.unwrap();
drop(child.stdout.take());
let mut input = child.stdin.take().unwrap();
input
.write_all(
&flow_tool_protocol::Message::Describe {
version: flow_abi::DATA_VERSION,
reply_limit: 16 << 20,
}
.frame(),
)
.unwrap();
drop(input);
assert_eq!(
child.wait().unwrap().code(),
Some(2),
"an answer no one reads cannot be written"
);
}