use std::{path::Path, process::Command};
use serde_json::Value;
struct Run {
code: i32,
stdout: String,
stderr: String,
}
fn spock(dir: &Path, args: &[&str]) -> Run {
let output = Command::new(env!("CARGO_BIN_EXE_spock"))
.current_dir(dir)
.env("SPOCK_CACHE_DIR", dir.join("cache"))
.env("NO_COLOR", "1")
.args(args)
.output()
.expect("spock runs");
Run {
code: output.status.code().unwrap_or(-1),
stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
}
}
fn json(dir: &Path, args: &[&str]) -> (i32, Value) {
let run = spock(dir, &[args, &["--json"]].concat());
let report =
serde_json::from_str(&run.stdout).unwrap_or_else(|e| panic!("{e}: {}", run.stdout));
(run.code, report)
}
const SPECS: &str = r#"
type Proc;
struct State {
x: Int,
done: Set<Proc>,
}
impl State {
action init() -> State {
State { x: 0, done: {} }
}
action incr(self, p: Proc) -> State {
require !(p in self.done);
Self { ..self, x: self.x + 1, done: self.done | {p} }
}
action next(self) -> State {
any p: Proc { self.incr(p) }
}
}
model two {
type Proc = {a, b};
init = State::init;
next = State::next;
deadlock = false;
}
"#;
const CHANNEL: &str = r#"
struct State {
inbox: Set<Int>,
got: Set<Int>,
}
impl State {
action init() -> State {
State { inbox: {}, got: {} }
}
action send(self, m: Int) -> State {
require !(m in self.inbox) && !(m in self.got);
Self { ..self, inbox: self.inbox | {m} }
}
action recv(self, m: Int) -> State {
require m in self.inbox;
Self { ..self, inbox: self.inbox - {m}, got: self.got | {m} }
}
action lose(self, m: Int) -> State {
require m in self.inbox;
Self { ..self, inbox: self.inbox - {m} }
}
action next(self) -> State {
any m in 0..3 { any { self.send(m), self.recv(m), self.lose(m) } }
}
}
model lossy {
init = State::init;
next = State::next;
deadlock = false;
}
model unlogged_losses {
init = State::init;
next = State::next;
deadlock = false;
hidden = [State::lose];
}
"#;
fn dir(files: &[(&str, &str)]) -> tempfile::TempDir {
let dir = tempfile::tempdir().expect("a temporary directory");
std::fs::write(dir.path().join("counter.spock"), SPECS).unwrap();
std::fs::write(dir.path().join("channel.spock"), CHANNEL).unwrap();
for (name, text) in files {
std::fs::write(dir.path().join(name), text).unwrap();
}
dir
}
const LOST_UPDATE: &str = r#"{"state":{"x":0,"done":[]}}
{"action":"incr","args":["a"],"state":{"x":1}}
{"action":"incr","args":["b"],"state":{"x":1}}
"#;
#[test]
fn a_run_the_spec_allows_matches() {
let good = r#"{"state":{"x":0,"done":[]}}
{"action":"incr","args":["a"],"state":{"x":1}}
{"action":"incr","args":["b"],"state":{"x":2}}
"#;
let dir = dir(&[("run.jsonl", good)]);
let run = spock(dir.path(), &["trace", "counter.spock", "run.jsonl"]);
assert_eq!(run.code, 0, "{}{}", run.stdout, run.stderr);
assert!(
run.stdout.starts_with(
"two: ok, a behavior matches all 3 states of run.jsonl (at most 1 candidate state, "
),
"{}",
run.stdout
);
}
#[test]
fn a_run_no_behavior_explains_diverges_at_its_line() {
let dir = dir(&[("run.jsonl", LOST_UPDATE)]);
let run = spock(dir.path(), &["trace", "counter.spock", "run.jsonl"]);
assert_eq!(run.code, 14, "{}", run.stderr);
let expected = r#"error: no behavior of two matches line 3 of run.jsonl
--> run.jsonl:3:1
|
3 | {"action":"incr","args":["b"],"state":{"x":1}}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
the spec's State::incr(b) gives x = 2, and the line says x = 1
a behavior that matches lines 1 to 2, 2 states:
1 State::init // line 1
x = 0
done = {}
2 State::incr(a) // line 2
x = 1
done = {a}
two: a behavior matches 2 of 3 states of run.jsonl (at most 1 candidate state, "#;
assert!(run.stdout.starts_with(expected), "{}", run.stdout);
let (code, report) = json(dir.path(), &["trace", "counter.spock", "run.jsonl"]);
assert_eq!(code, 14);
assert_eq!(report["version"], 1);
assert_eq!(report["model"], "two");
assert_eq!(report["trace"], "run.jsonl");
assert_eq!((report["states"].as_u64(), report["matched"].as_u64()), (Some(3), Some(2)));
let outcome = &report["outcome"];
assert_eq!(outcome["kind"], "diverges");
assert_eq!(outcome["line"], 3);
let miss = &outcome["misses"][0];
assert_eq!(miss["from"]["state"], serde_json::json!({"x": 1, "done": ["a"]}));
assert_eq!(miss["why"]["kind"], "differs");
assert_eq!(miss["why"]["step"]["args"], serde_json::json!(["b"]));
assert_eq!(
miss["why"]["differences"],
serde_json::json!([{"path": "x", "seen": 1, "spec": 2}])
);
let lines: Vec<&Value> =
report["behavior"].as_array().unwrap().iter().map(|s| &s["line"]).collect();
assert_eq!(lines, [1, 2]);
}
#[test]
fn a_step_the_spec_takes_only_with_other_arguments_says_which() {
let trace = "{\"state\":{\"x\":0}}\n{\"action\":\"incr\",\"args\":[\"a\"]}\n\
{\"action\":\"incr\",\"args\":[\"a\"]}\n";
let dir = dir(&[("run.jsonl", trace)]);
let run = spock(dir.path(), &["trace", "counter.spock", "run.jsonl"]);
assert_eq!(run.code, 14);
assert!(
run.stdout.contains("\nthe spec takes State::incr here only as State::incr(b)\n"),
"{}",
run.stdout
);
let (_, report) = json(dir.path(), &["trace", "counter.spock", "run.jsonl"]);
let why = &report["outcome"]["misses"][0]["why"];
assert_eq!(why, &serde_json::json!({"kind": "arguments", "arguments": [["b"]]}));
}
#[test]
fn hidden_steps_come_between_the_lines_of_a_trace() {
let trace = "State::init\nState::send(1)\nState::send(2)\nState::recv(2)\n inbox = {}\n";
let dir = dir(&[("run.trace", trace)]);
let run = spock(dir.path(), &["trace", "channel.spock", "run.trace", "--model", "lossy"]);
assert_eq!(run.code, 14);
assert!(
run.stdout.contains(
"\nthe spec's State::recv(2) gives inbox = {1}, and the line says inbox = {}\n"
),
"{}",
run.stdout
);
let args = ["trace", "channel.spock", "run.trace", "--model", "unlogged_losses"];
let run = spock(dir.path(), &args);
assert_eq!(run.code, 0, "{}", run.stdout);
let (code, report) = json(dir.path(), &args);
assert_eq!(code, 0);
assert_eq!(report["outcome"]["kind"], "matches");
let steps: Vec<(Value, Value)> = report["behavior"]
.as_array()
.unwrap()
.iter()
.map(|s| (s["line"].clone(), s["action"].clone()))
.collect();
assert_eq!(
steps,
[
(1.into(), Value::Null),
(2.into(), "State::send".into()),
(Value::Null, "State::lose".into()),
(3.into(), "State::send".into()),
(4.into(), "State::recv".into()),
]
);
}
#[test]
fn a_bad_trace_is_an_error_in_it() {
let dir = dir(&[("run.trace", "State::init\nState::send(1)\n got = {x}\n")]);
let args = ["trace", "channel.spock", "run.trace", "--model", "lossy"];
let run = spock(dir.path(), &args);
assert_eq!(run.code, 150);
assert_eq!(run.stdout, "");
let expected = "\
error: expected a value of Int, found `x`
--> run.trace:3:10
|
3 | got = {x}
| ^
";
assert!(run.stderr.starts_with(expected), "{}", run.stderr);
let (code, report) = json(dir.path(), &args);
assert_eq!(code, 150);
assert_eq!(report["outcome"]["kind"], "error");
assert_eq!(
report["outcome"]["location"],
serde_json::json!({"file": "run.trace", "line": 3, "column": 10})
);
let run = spock(dir.path(), &["trace", "channel.spock", "missing.trace", "--model", "lossy"]);
assert_eq!(run.code, 150);
assert!(run.stderr.starts_with("missing.trace: "), "{}", run.stderr);
}
fn behavior(printed: &str) -> String {
let lines = printed.lines().skip_while(|l| !l.starts_with("a shortest behavior"));
let lines = lines.skip(1).take_while(|l| l.starts_with(" "));
lines.map(|l| format!("{l}\n")).collect()
}
#[test]
fn a_behavior_spock_check_printed_reads_back_as_a_trace() {
let specs = concat!(env!("CARGO_MANIFEST_DIR"), "/../../specs");
let dir = dir(&[]);
for (spec, model) in [
("lost_update.spock", "two_procs"),
("die_hard.spock", "die_hard"),
("hanoi.spock", "three_disks"),
("missionaries_and_cannibals.spock", "three_each"),
] {
let path = format!("{specs}/{spec}");
let checked = spock(dir.path(), &["check", &path, "--model", model]);
assert!([11, 12, 13].contains(&checked.code), "{spec}: {}", checked.stdout);
let printed = behavior(&checked.stdout);
assert!(!printed.is_empty(), "{spec}: {}", checked.stdout);
std::fs::write(dir.path().join("run.trace"), &printed).unwrap();
let run = spock(dir.path(), &["trace", &path, "run.trace", "--model", model]);
assert_eq!(run.code, checked.code, "{spec}: {}{}\n{printed}", run.stdout, run.stderr);
let (_, report) = json(dir.path(), &["check", &path, "--model", model]);
let steps: Vec<String> =
report["trace"].as_array().unwrap().iter().map(|step| format!("{step}\n")).collect();
std::fs::write(dir.path().join("run.jsonl"), steps.concat()).unwrap();
let run = spock(dir.path(), &["trace", &path, "run.jsonl", "--model", model]);
assert_eq!(run.code, checked.code, "{spec}: {}{}", run.stdout, run.stderr);
}
}
#[test]
fn a_trace_that_violates_an_invariant_or_step_property_exits_12_or_13() {
let spec = r#"
struct State { x: Int }
impl State {
action init() -> State { State { x: 0 } }
action step(self, d: Int) -> State { Self { ..self, x: self.x + d } }
action next(self) -> State { any d in {-1, 1} { self.step(d) } }
fn small(self) -> Bool { self.x < 2 }
fn non_decreasing(self, next: State) -> Bool { next.x >= self.x }
}
model m {
init = State::init;
next = State::next;
invariants = [State::small];
step_properties = [State::non_decreasing];
}
"#;
let inv_trace = "{\"state\":{\"x\":0}}\n{\"state\":{\"x\":1}}\n{\"state\":{\"x\":2}}\n";
let step_trace = "{\"state\":{\"x\":0}}\n{\"state\":{\"x\":-1}}\n";
let d = dir(&[("s.spock", spec), ("inv.jsonl", inv_trace), ("step.jsonl", step_trace)]);
let run = spock(d.path(), &["trace", "s.spock", "inv.jsonl"]);
assert_eq!(run.code, 12, "{}", run.stdout);
assert!(
run.stdout.contains("invariant State::small is violated at line 3 of inv.jsonl"),
"{}",
run.stdout
);
assert!(run.stdout.contains("a behavior to the violating state, 3 states:"), "{}", run.stdout);
assert!(run.stdout.contains("— Spock"), "{}", run.stdout);
let (code, report) = json(d.path(), &["trace", "s.spock", "inv.jsonl"]);
assert_eq!(code, 12);
assert_eq!(
report["outcome"],
serde_json::json!({ "kind": "invariant", "name": "State::small", "line": 3 })
);
let run = spock(d.path(), &["trace", "s.spock", "step.jsonl"]);
assert_eq!(run.code, 13, "{}", run.stdout);
assert!(
run.stdout
.contains("step property State::non_decreasing is violated at line 2 of step.jsonl"),
"{}",
run.stdout
);
assert!(run.stdout.contains("— Spock"), "{}", run.stdout);
let (code, report) = json(d.path(), &["trace", "s.spock", "step.jsonl"]);
assert_eq!(code, 13);
assert_eq!(
report["outcome"],
serde_json::json!({ "kind": "step_property", "name": "State::non_decreasing", "line": 2 })
);
}