use crate::finding::{Citation, Finding, Property, Rule, RuleId};
use crate::model::TestModel;
use crate::node::{Node, Unit, Visit, walk};
use crate::role::Role;
pub const RULE: Rule = Rule {
id: RuleId::new("test-logic"),
property: Property::Precision,
summary: "a test computes its own expectations instead of stating them",
instruction: "Do not put loops or conditionals in a test body. A test is a \
concrete input/output pair: state the values directly rather \
than computing them, and split the cases into separate tests.",
citation: Citation {
title: "Testing on the Toilet: Don't Put Logic in Tests",
url: "https://testing.googleblog.com/2014/07/testing-on-toilet-dont-put-logic-in.html",
date: "2014-07-31",
},
};
pub fn check<'t, N: Node<'t>>(unit: &Unit<'t, N>, model: &TestModel, out: &mut Vec<Finding>) {
walk(unit.root, &mut |node| {
if !model.is_test(node) {
return Visit::Descend;
}
check_body(node, model, out);
Visit::Skip
});
}
fn check_body<'t, N: Node<'t>>(test: N, model: &TestModel, out: &mut Vec<Finding>) {
let mut first = true;
walk(test, &mut |node| {
if first {
first = false;
return Visit::Descend;
}
let Some(kind) = Logic::of(node, model) else {
return Visit::Descend;
};
let label = model.iteration_method(node).unwrap_or_else(|| node.kind());
out.push(
Finding::new(&RULE, node.span(), kind.message(label))
.with_help(kind.help().to_string()),
);
Visit::Skip
});
}
#[derive(Clone, Copy)]
enum Logic {
Loop,
Branch,
}
impl Logic {
fn of<'t, N: Node<'t>>(node: N, model: &TestModel) -> Option<Logic> {
if node.has_role(Role::Loop) || model.is_iteration(node) {
Some(Logic::Loop)
} else if node.has_role(Role::Branch) {
Some(Logic::Branch)
} else {
None
}
}
fn message(self, kind: &str) -> String {
match self {
Logic::Loop => format!("loop (`{kind}`) in a test body"),
Logic::Branch => format!("conditional (`{kind}`) in a test body"),
}
}
fn help(self) -> &'static str {
match self {
Logic::Loop => {
"state each case directly instead of looping, so a failure \
names the case that failed"
}
Logic::Branch => {
"split the branches into separate tests, so each one states \
the scenario it covers"
}
}
}
}