Files
2026-11-27 06:03:56 +00:00

441 lines
15 KiB
Rust

//! CLI 必须实际执行用例、隔离 fake 与数据,并在失败或超时后继续。
use super::*;
#[test]
fn workflow_examples_use_real_models_and_explicit_external_fakes() {
let example = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../examples/next/workflows")
.canonicalize()
.unwrap();
let root = directory("workflow-examples");
let project = Project::load(&example).unwrap();
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
for source in &project.sources {
if let Ok(relative) = source.path.strip_prefix(&example) {
let target = root.join(relative);
fs::create_dir_all(target.parent().unwrap()).unwrap();
fs::copy(&source.path, target).unwrap();
}
}
// 仅测试副本补齐外部合同;不会往正式样例写入假支付、通知或身份。
fs::write(root.join("module/demo/order/adapter.dever"),
"port.pay(key:Uuid,amount:Decimal) (receipt:Text) {receipt=uuid.toText(key)}\nport.notify(key:Uuid,receipt:Text) () {}").unwrap();
fs::write(
root.join("module/demo/selection/adapter.dever"),
"port.accept(value:Text) (accepted:Bool) {accepted=value==\"yes\"}",
)
.unwrap();
for (domain, source) in [
(
"approval",
r#"
flow behavior() ()
| step | kind | do |
| request | flow | app.create(" approval ") |
| - | calc | assertEq(request.title,"approval") |
| - | calc | assertEq(request.status,data.request.Status.Pending) |
| - | flow | app.review(request.id,true) |
| updated | data | data.request.get(request.id) |
| - | calc | assertEq(updated.status,data.request.Status.Approved) |
"#,
),
(
"catalog",
r#"
flow behavior() ()
| step | kind | do |
| category | data | data.category.create({name="News"}) |
| - | data | data.item.create({title="First",category_id=category.id,supplier_cost=1.25}) |
| - | data | data.item.create({title="Second",category_id=null,supplier_cost=2.50}) |
| page | flow | app.list(1) |
| - | calc | assertEq(page.total,2) |
| first | calc | get(page.items,0) |
| second | calc | get(page.items,1) |
| - | check | first!=null else Invalid |
| - | check | second!=null else Invalid |
| - | calc | assertEq(first.category,"News") |
| - | calc | assertEq(second.category,null) |
| titles | flow | app.titles(1) |
| - | calc | assertEq(length(titles),1) |
| title | calc | get(titles,0) |
| - | check | title!=null else Invalid |
| - | calc | assertEq(title.title,"First") |
"#,
),
(
"selection",
r#"
flow behavior() ()
| step | kind | do |
| found | loop | app.find(["no","yes","fail"]) |
| - | calc | assertEq(found,"yes") |
| selected | loop | app.select(["no","yes","yes"]) |
| - | calc | assertEq(selected,["yes","yes"]) |
flow port.accept(value:Text) (accepted:Bool)
| step | kind | do |
| - | check | value!="fail" else dever.process.Error.Failed("test external failure") |
| accepted | calc | value=="yes" |
"#,
),
] {
let tests = root.join(format!("test/demo/{domain}"));
fs::create_dir_all(&tests).unwrap();
fs::write(tests.join("behavior.dever"), source).unwrap();
}
success(cli(&["fmt", root.to_str().unwrap()]));
success(cli(&["check", root.to_str().unwrap()]));
let output = success(cli(&["test", root.to_str().unwrap()]));
for domain in ["approval", "catalog", "selection"] {
assert!(
output.contains(&format!("PASS demo.{domain}.behavior")),
"{output}"
);
}
}
#[test]
fn test_command_runs_isolated_cases_and_checks_production_contract() {
let root = directory("test-runner");
let domain = root.join("module/demo/value");
let tests = root.join("test/demo/value");
fs::create_dir_all(&domain).unwrap();
fs::create_dir_all(&tests).unwrap();
write_source(domain.join("data/main.dever"), "type Value {name:Text}").unwrap();
fs::write(domain.join("port.dever"), "read(value:Int) (out:Int)").unwrap();
let adapter = "port.read(value:Int) (out:Int) {out=value}";
fs::write(domain.join("adapter.dever"), adapter).unwrap();
write_source(
domain.join("app/main.dever"),
r#"
read(value:Int) (out:Int) {out=port.read(value)}
rule sign(value:Int) (out:Int)
| name | value | out |
| negative | < 0 | -1 |
| zero | 0 | 0 |
| positive | > 0 | 1 |
flow write() (out:Int)
| step | kind | do |
| - | data | data.create({name="isolated"}) |
| out | data | data.count() |
rule record(value:Bool) (out:Int)
| name | value | out |
| written | true | app.write() |
| skipped | false | 0 |
rule nested(value:Int) (out:Int)
| name | value | out |
| all | - | app.sign(value) |
"#,
)
.unwrap();
for (name, source) in [
(
"a_fake",
"aFake() () {assertEq(app.read(4),5)}\nport.read(value:Int) (out:Int) {out=value+1}",
),
(
"b_database",
"flow bDatabase() ()\n| step | kind | do |\n| count | flow | app.write() |\n| - | calc | assertEq(count,1) |",
),
(
"c_database",
"flow cDatabase() ()\n| step | kind | do |\n| count | flow | app.write() |\n| - | calc | assertEq(count,1) |",
),
(
"c_rows",
r#"cRows() () {assertRow(app.sign(-1),"negative")
assertRow(app.sign(0),"zero")
assertRow(app.sign(1),"positive")
assertEq(app.sign(1),1)}"#,
),
(
"c_once",
r#"flow cOnce() ()
| step | kind | do |
| - | calc | assertRow(app.record(true),"written") |
| count | data | data.count() |
| - | calc | assertEq(count,1) |
| - | calc | assertRow(app.nested(-1),"all") |
| task | calc | run(app.sign(1)) |
| value | calc | wait(task) |
| - | calc | assertEq(value,1) |"#,
),
(
"c_clock",
r#"flow cClock() ()
| step | kind | do |
| before | flow | dever.time.now() |
| - | calc | dever.test.advanceClock(86400000) |
| after | flow | dever.time.now() |
| - | calc | assertEq(dever.time.difference(after,before),dever.time.duration(86400000)) |
| task | calc | run(dever.time.now()) |
| shared | calc | wait(task) |
| - | calc | assertEq(after,shared) |"#,
),
("d_failure", "dFailure() () {assert(false)}"),
(
"d_missing_fake",
"dMissingFake() () {assertEq(app.read(1),1)}",
),
(
"d_wrong_row",
"dWrongRow() () {assertRow(app.sign(-1),\"positive\")}",
),
(
"e_timeout",
"flow eTimeout() ()\n| step | kind | do |\n| - | flow | dever.time.sleep(500) |",
),
(
"f_secret",
"fSecret() () {key=secret(\"test-only\")\nassertEq(length(dever.crypto.hmacSha256(key,dever.bytes.fromText(\"x\"))),32)}",
),
] {
fs::write(tests.join(format!("{name}.dever")), source).unwrap();
}
let source = root.to_str().unwrap();
success(cli(&["fmt", source]));
let adapter = fs::read_to_string(domain.join("adapter.dever")).unwrap();
let output = cli(&["test", source, "--timeout-ms", "150"]);
assert!(!output.status.success());
let stdout = String::from_utf8(output.stdout).unwrap();
let stderr = String::from_utf8(output.stderr).unwrap();
for name in [
"a_fake",
"b_database",
"c_database",
"c_rows",
"c_once",
"f_secret",
] {
assert!(
stdout.contains(&format!("PASS demo.value.{name}")),
"{stdout}\n{stderr}"
);
}
assert!(stderr.contains("d_failure.dever"), "{stderr}");
assert!(stderr.contains("assert failed"), "{stderr}");
assert!(stderr.contains("assertRow failed"), "{stderr}");
assert!(stderr.contains("complete case-local fake"), "{stderr}");
assert!(stderr.contains("test timed out"), "{stderr}");
assert!(!root.join("data").exists());
assert_eq!(
fs::read_to_string(domain.join("adapter.dever")).unwrap(),
adapter
);
let filtered = success(cli(&["test", source, "--filter", "demo.value.a_fake"]));
assert!(filtered.contains("PASS demo.value.a_fake"));
assert!(!filtered.contains("b_database"));
fs::write(tests.join("d_failure.dever"), "invalid unselected source").unwrap();
success(cli(&["test", source, "--filter", "demo.value.a_fake"]));
assert!(
!cli(&["test", source, "--filter", "demo.valu"])
.status
.success()
);
fs::write(root.join("dever.api"), "dever-api 6\n").unwrap();
assert!(String::from_utf8_lossy(&cli(&["test", source]).stderr).contains("public API differs"));
}
#[test]
fn production_rejects_test_primitives() {
let root = directory("test-primitives-boundary");
let source = root.join("main.dever");
for body in [
"assert(true)",
"dever.test.advanceClock(1)",
"value=dever.test.drainJobs(1)",
"assertEq(1,1)",
"assertRow(1,\"row\")",
"value=secret(\"fixture\")",
] {
fs::write(&source, format!("main() () {{{body}}}")).unwrap();
let loaded = Project::load(&source).unwrap();
let error = program::check(&loaded.declarations, &loaded.modules)
.err()
.unwrap();
assert!(error.message.contains("test operations"), "{error:?}");
}
}
#[test]
fn assert_row_rejects_non_rules_and_unknown_or_dynamic_names() {
let root = directory("test-rule-diagnostics");
let domain = root.join("module/demo/value");
let test = root.join("test/demo/value/rows.dever");
fs::create_dir_all(&domain).unwrap();
fs::create_dir_all(test.parent().unwrap()).unwrap();
write_source(domain.join("app/main.dever"),
"read(value:Int) (out:Int) {out=value}\nrule sign(value:Int) (out:Int)\n| name | value | out |\n| negative | < 0 | -1 |\n| zero | 0 | 0 |\n| positive | > 0 | 1 |").unwrap();
success(cli(&["fmt", root.to_str().unwrap()]));
for (body, message) in [
("assertRow(app.read(1),\"positive\")", "requires a rule"),
("assertRow(1,\"positive\")", "direct rule call"),
("assertRow(app.sign(1),\"missing\")", "unknown rule row"),
(
"row=\"positive\"\nassertRow(app.sign(1),row)",
"literal row name",
),
] {
fs::write(&test, format!("rows() () {{{body}}}")).unwrap();
success(cli(&["fmt", root.to_str().unwrap()]));
let output = cli(&["test", root.to_str().unwrap()]);
assert!(!output.status.success());
let error = String::from_utf8_lossy(&output.stderr);
assert!(error.contains(message), "{body}: {error}");
}
}
#[test]
fn test_configuration_is_explicit_and_cannot_replace_isolated_resources() {
let root = directory("test-settings");
let domain = root.join("module/demo/value");
let cases = root.join("test/demo/value");
fs::create_dir_all(&domain).unwrap();
fs::create_dir_all(&cases).unwrap();
fs::create_dir_all(root.join("config")).unwrap();
write_source(
domain.join("app/main.dever"),
"setting label:Text\nread() (out:Text) {out=label}",
)
.unwrap();
fs::write(
cases.join("settings.dever"),
"settings() () {assertEq(app.read(),\"fixture\")}",
)
.unwrap();
fs::write(
root.join("config/setting.json"),
r#"{"module":{"demo":{"value":{"label":"production"}}}}"#,
)
.unwrap();
success(cli(&["fmt", root.to_str().unwrap()]));
assert!(!cli(&["test", root.to_str().unwrap()]).status.success());
let path = root.join("test/setting.json");
fs::write(
&path,
r#"{"module":{"demo":{"value":{"label":"fixture"}}}}"#,
)
.unwrap();
success(cli(&["test", root.to_str().unwrap()]));
fs::write(
&path,
r#"{"database":{"default":{"type":"sqlite","path":"data/business.sqlite"}}}"#,
)
.unwrap();
let denied = cli(&["test", root.to_str().unwrap()]);
assert!(!denied.status.success());
assert!(String::from_utf8_lossy(&denied.stderr).contains("unknown field `database`"));
fs::write(
&path,
r#"{"module":{"demo":{"value":{"label":"fixture","label":"duplicate"}}}}"#,
)
.unwrap();
assert!(!cli(&["test", root.to_str().unwrap()]).status.success());
assert!(!root.join("data").exists());
}
#[test]
fn test_clock_and_drain_report_invalid_limits_and_keep_running() {
let root = directory("test-time-bounds");
let domain = root.join("module/demo/value");
let cases = root.join("test/demo/value");
fs::create_dir_all(&domain).unwrap();
fs::create_dir_all(&cases).unwrap();
write_source(domain.join("app/main.dever"), "read() (out:Int) {out=1}").unwrap();
for (name, source) in [
(
"a_empty",
"aEmpty() () {assertEq(dever.test.drainJobs(1),0)}",
),
(
"b_invalid",
"bInvalid() () {assertEq(dever.test.drainJobs(0),0)}",
),
(
"c_negative",
"flow cNegative() ()\n| step | kind | do |\n| - | calc | dever.test.advanceClock(-1) |",
),
(
"d_overflow",
"flow dOverflow() ()\n| step | kind | do |\n| - | calc | dever.test.advanceClock(9223372036854775807) |",
),
("z_valid", "zValid() () {assertEq(app.read(),1)}"),
] {
fs::write(cases.join(format!("{name}.dever")), source).unwrap();
}
success(cli(&["fmt", root.to_str().unwrap()]));
let result = cli(&["test", root.to_str().unwrap()]);
assert!(!result.status.success());
let stdout = String::from_utf8_lossy(&result.stdout);
let stderr = String::from_utf8_lossy(&result.stderr);
assert!(
stdout.contains("PASS demo.value.a_empty"),
"{stdout}{stderr}"
);
assert!(
stdout.contains("PASS demo.value.z_valid"),
"{stdout}{stderr}"
);
for error in [
"Job drain limit must be 1..10000",
"must be nonnegative",
"advance overflows",
] {
assert!(stderr.contains(error), "{stderr}");
}
success(cli(&[
"test",
root.to_str().unwrap(),
"--filter",
"demo.value.a_empty",
"--profile",
"release",
]));
}
#[test]
fn dv_directories_load_and_execute_together() {
let root = directory("dv-directories");
for (path, source) in [
("module/demo/cart/data/cart.dv", "type Cart {amount:Int}"),
(
"module/demo/cart/port/pricing.dv",
"price(value:Int) (out:Int)",
),
(
"module/demo/cart/adapter/cart.dv",
"port.price(value:Int) (out:Int) {out=value+1}",
),
(
"module/demo/cart/rule/price.dv",
"rule price(active:Bool, value:Int) (out:Int) active {true => port.price(value)
false => 0}",
),
(
"module/demo/cart/loop/cart.dv",
"loop total(values:List<Int>) (out:Int) value in values {sum value}",
),
(
"module/demo/cart/flow/cart.dv",
"flow add(values:List<Int>) (out:Int) {amount=price(true,total(values))
row=data.create({amount=amount})
out=row.amount}",
),
(
"test/demo/cart/checkout.dv",
"flow checkout() () {amount=app.add([2,3])
assertEq(amount,6)
count=data.count()
assertEq(count,1)}
port.price(value:Int) (out:Int) {out=value+1}",
),
] {
write_source(root.join(path), source).unwrap();
}
let path = root.to_str().unwrap();
success(cli(&["fmt", path]));
success(cli(&["fmt", path, "--check"]));
success(cli(&["check", path]));
assert!(success(cli(&["test", path])).contains("PASS demo.cart.checkout"));
}