use std::fmt;
use indexmap::IndexMap;
use regex::{Regex, RegexBuilder};
use serde::Deserialize;
use crate::node::NodeError;
use crate::pool::{Selector, VariablePool};
use crate::value::Value;
const PATTERN_SIZE_LIMIT: usize = 1 << 20;
pub const MAX_ISSUES: usize = 200;
const FOUND_CHARS: usize = 160;
const EMAIL: &str = r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}";
const PHONE: &str = r"\+\d(?:[ .\-]?\(?\d\)?){7,14}";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Issue {
pub field: String,
pub rule: String,
pub message: String,
pub found: Option<String>,
}
impl Issue {
pub fn to_value(&self) -> Value {
let mut entries = vec![
("field", Value::from(self.field.as_str())),
("rule", Value::from(self.rule.as_str())),
("message", Value::from(self.message.as_str())),
];
if let Some(found) = &self.found {
entries.push(("found", Value::from(found.as_str())));
}
Value::object(entries)
}
}
impl fmt::Display for Issue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if !self.field.is_empty() {
write!(f, "{}: ", self.field)?;
}
f.write_str(&self.message)?;
if let Some(found) = &self.found {
write!(f, " (\"{found}\")")?;
}
Ok(())
}
}
pub fn notes(issues: &[Issue]) -> String {
issues.iter().map(|issue| format!("- {issue}")).collect::<Vec<_>>().join("\n")
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub struct RuleError(pub String);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Detector {
Email,
Phone,
}
impl Detector {
fn name(self) -> &'static str {
match self {
Detector::Email => "email",
Detector::Phone => "phone",
}
}
fn pattern(self) -> &'static str {
match self {
Detector::Email => EMAIL,
Detector::Phone => PHONE,
}
}
fn message(self) -> &'static str {
match self {
Detector::Email => "contains an email address",
Detector::Phone => "contains a phone number",
}
}
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ForbidSpec {
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub text: Option<String>,
#[serde(default)]
pub pattern: Option<String>,
#[serde(default)]
pub detect: Option<Detector>,
#[serde(default)]
pub message: Option<String>,
#[serde(default)]
pub fields: Vec<String>,
#[serde(default)]
pub replace: Option<String>,
#[serde(default)]
pub redact: Option<bool>,
}
impl ForbidSpec {
pub fn compile(&self) -> Result<Forbid, RuleError> {
let (pattern, name, message) = match (&self.text, &self.pattern, self.detect) {
(Some(text), None, None) => {
if text.trim().is_empty() {
return Err(RuleError("a forbid `text` must not be empty".into()));
}
(phrase_pattern(text), "forbid".to_owned(), format!("remove \"{}\"", text.trim()))
}
(None, Some(pattern), None) => {
if pattern.is_empty() {
return Err(RuleError("a forbid `pattern` must not be empty".into()));
}
(pattern.clone(), "forbid".to_owned(), "matches a forbidden pattern".to_owned())
}
(None, None, Some(detector)) => {
(detector.pattern().to_owned(), detector.name().to_owned(), detector.message().to_owned())
}
_ => return Err(RuleError("a forbid rule needs exactly one of `text`, `pattern` and `detect`".into())),
};
let regex = RegexBuilder::new(&pattern)
.size_limit(PATTERN_SIZE_LIMIT)
.build()
.map_err(|e| RuleError(format!("forbid pattern `{pattern}`: {e}")))?;
for field in &self.fields {
check_field_pattern(field)?;
}
Ok(Forbid {
name: self.name.clone().filter(|name| !name.trim().is_empty()).unwrap_or(name),
regex,
message: self.message.clone().filter(|message| !message.trim().is_empty()).unwrap_or(message),
fields: self.fields.clone(),
replace: self.replace.clone(),
redact: self.redact.unwrap_or(self.detect.is_some()),
})
}
}
#[derive(Clone, Debug)]
pub struct Forbid {
name: String,
regex: Regex,
message: String,
fields: Vec<String>,
replace: Option<String>,
redact: bool,
}
impl Forbid {
fn applies_to(&self, field: &str) -> bool {
self.fields.is_empty() || self.fields.iter().any(|pattern| covers(pattern, field))
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Require {
pub field: String,
pub text: String,
#[serde(default)]
pub message: Option<String>,
}
#[derive(Clone, Debug, Default)]
pub struct Rules {
pub forbid: Vec<Forbid>,
pub require: Vec<Require>,
pub paragraphs: IndexMap<String, usize>,
pub ignore: Vec<String>,
}
#[derive(Clone, Debug, Default)]
pub struct Texts {
leaves: Vec<(String, String)>,
lists: IndexMap<String, usize>,
}
impl Texts {
pub fn of(value: &Value, prefix: &str) -> Self {
let mut texts = Texts::default();
texts.add(value, prefix);
texts
}
pub fn add(&mut self, value: &Value, prefix: &str) {
let root =
if prefix.is_empty() && !matches!(value, Value::Object(_) | Value::Array(_)) { "text" } else { prefix };
self.walk(value, root.to_owned());
}
fn walk(&mut self, value: &Value, path: String) {
match value {
Value::String(text) => self.leaves.push((path, text.to_string())),
Value::Int(_) | Value::Float(_) => self.leaves.push((path, value.to_text())),
Value::Array(items) => {
for (index, item) in items.iter().enumerate() {
self.walk(item, format!("{path}[{index}]"));
}
self.lists.insert(path, items.len());
}
Value::Object(map) => {
for (key, item) in map.iter() {
let child = if path.is_empty() { key.clone() } else { format!("{path}.{key}") };
self.walk(item, child);
}
}
Value::Null | Value::Bool(_) | Value::Secret(_) | Value::File(_) => {}
}
}
fn joined(&self, field: &str) -> Option<String> {
let parts: Vec<&str> =
self.leaves.iter().filter(|(path, _)| covers(field, path)).map(|(_, text)| text.as_str()).collect();
if parts.is_empty() { None } else { Some(parts.join("\n")) }
}
fn paragraphs(&self, field: &str) -> Option<usize> {
if let Some(count) = self.lists.get(field) {
return Some(*count);
}
let (_, text) = self.leaves.iter().find(|(path, _)| path == field)?;
Some(paragraph_count(text))
}
}
fn paragraph_count(text: &str) -> usize {
let mut count = 0;
let mut in_paragraph = false;
for line in text.lines() {
if line.trim().is_empty() {
in_paragraph = false;
} else if !in_paragraph {
in_paragraph = true;
count += 1;
}
}
count
}
pub fn check(texts: &Texts, rules: &Rules) -> Vec<Issue> {
let mut issues = Vec::new();
for rule in &rules.forbid {
for (field, text) in texts.leaves.iter().filter(|(field, _)| rule.applies_to(field)) {
for found in rule.regex.find_iter(text) {
if issues.len() >= MAX_ISSUES {
return issues;
}
issues.push(Issue {
field: field.clone(),
rule: rule.name.clone(),
message: rule.message.clone(),
found: (!rule.redact).then(|| shorten(found.as_str())),
});
}
}
}
let ignored = |text: &str| rules.ignore.iter().any(|ignore| ignore.trim() == text.trim());
for rule in &rules.require {
let Some(text) = texts.joined(&rule.field) else { continue };
if ignored(&text) || text.contains(rule.text.as_str()) {
continue;
}
if issues.len() >= MAX_ISSUES {
return issues;
}
issues.push(Issue {
field: rule.field.clone(),
rule: "require".into(),
message: rule.message.clone().unwrap_or_else(|| format!("must state \"{}\"", rule.text)),
found: None,
});
}
for (field, expected) in &rules.paragraphs {
let Some(count) = texts.paragraphs(field) else { continue };
if count == *expected || texts.joined(field).is_some_and(|text| ignored(&text)) {
continue;
}
if issues.len() >= MAX_ISSUES {
return issues;
}
issues.push(Issue {
field: field.clone(),
rule: "paragraphs".into(),
message: format!(
"write exactly {expected} paragraph{}, not {count}",
if *expected == 1 { "" } else { "s" }
),
found: None,
});
}
issues
}
pub fn fix(value: &Value, prefix: &str, forbid: &[Forbid]) -> Value {
if !forbid.iter().any(|rule| rule.replace.is_some()) {
return value.clone();
}
let root = if prefix.is_empty() && !matches!(value, Value::Object(_) | Value::Array(_)) { "text" } else { prefix };
fix_at(value, root, forbid)
}
fn fix_at(value: &Value, path: &str, forbid: &[Forbid]) -> Value {
match value {
Value::String(text) => {
let mut fixed = text.to_string();
for rule in forbid.iter().filter(|rule| rule.applies_to(path)) {
if let Some(replace) = &rule.replace {
fixed = rule.regex.replace_all(&fixed, replace.as_str()).into_owned();
}
}
Value::from(fixed)
}
Value::Array(items) => Value::array(
items.iter().enumerate().map(|(index, item)| fix_at(item, &format!("{path}[{index}]"), forbid)),
),
Value::Object(map) => Value::object(map.iter().map(|(key, item)| {
let child = if path.is_empty() { key.clone() } else { format!("{path}.{key}") };
let fixed = fix_at(item, &child, forbid);
(key.clone(), fixed)
})),
other => other.clone(),
}
}
pub fn issues_from(value: &Value) -> Result<Vec<Issue>, RuleError> {
let items = match value {
Value::Null => return Ok(Vec::new()),
Value::Array(items) => items,
other => return Err(RuleError(format!("issues must be a list, got {}", other.type_name()))),
};
let mut issues = Vec::with_capacity(items.len());
for item in items.iter() {
let Some(map) = item.as_object() else {
issues.push(Issue { field: String::new(), rule: "issue".into(), message: item.to_text(), found: None });
continue;
};
let text = |key: &str| map.get(key).map(Value::to_text).filter(|text| !text.trim().is_empty());
let reason = text("rule").or_else(|| text("reason")).unwrap_or_else(|| "issue".to_owned());
let number = text("number");
let message = match (text("message"), reason.as_str(), &number) {
(Some(message), _, _) => message,
(None, "attribution", Some(number)) => {
let owners = match map.get("owners") {
Some(Value::Array(owners)) => owners.iter().map(Value::to_text).collect::<Vec<_>>().join(" / "),
_ => "another entity".to_owned(),
};
let named = text("named").unwrap_or_else(|| "the entity named next to it".to_owned());
format!("{number} belongs to {owners}, not {named}")
}
(None, _, Some(number)) => format!("{number} is not in the facts"),
(None, _, None) => reason.clone(),
};
let found = text("found").or_else(|| text("sentence")).map(|found| shorten(&found));
issues.push(Issue { field: text("field").unwrap_or_default(), rule: reason, message, found });
}
Ok(issues)
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RulesConfig {
#[serde(default)]
pub forbid: Option<serde_json::Value>,
#[serde(default)]
pub require: Option<serde_json::Value>,
#[serde(default)]
pub paragraphs: Option<serde_json::Value>,
#[serde(default)]
pub ignore: Vec<String>,
}
#[derive(Clone, Debug)]
enum Given<T> {
Inline(T),
From(Selector),
}
impl<T: Clone> Given<T> {
fn parse<F>(value: &serde_json::Value, parse: F) -> Result<Self, RuleError>
where
F: FnOnce(&serde_json::Value) -> Result<T, RuleError>,
{
let is_selector = match value {
serde_json::Value::String(_) => true,
serde_json::Value::Array(items) => !items.is_empty() && items.iter().all(serde_json::Value::is_string),
_ => false,
};
if is_selector {
return serde_json::from_value::<Selector>(value.clone())
.map(Given::From)
.map_err(|e| RuleError(e.to_string()));
}
parse(value).map(Given::Inline)
}
fn selector(&self) -> Option<&Selector> {
match self {
Given::From(selector) => Some(selector),
Given::Inline(_) => None,
}
}
fn resolve<F>(&self, pool: &VariablePool, empty: T, parse: F) -> Result<T, NodeError>
where
F: FnOnce(&serde_json::Value) -> Result<T, RuleError>,
{
match self {
Given::Inline(rules) => Ok(rules.clone()),
Given::From(selector) => match pool.get_or_null(selector) {
Value::Null => Ok(empty),
value => parse(&value.to_json()).map_err(|e| NodeError::invalid_input(format!("`{selector}`: {e}"))),
},
}
}
}
#[derive(Clone, Debug, Default)]
pub struct RuleSources {
forbid: Option<Given<Vec<Forbid>>>,
require: Option<Given<Vec<Require>>>,
paragraphs: Option<Given<IndexMap<String, usize>>>,
ignore: Vec<String>,
}
impl RuleSources {
pub fn parse(config: &RulesConfig) -> Result<Self, (&'static str, RuleError)> {
let forbid = config
.forbid
.as_ref()
.map(|value| Given::parse(value, parse_forbid))
.transpose()
.map_err(|e| ("forbid", e))?;
let require = config
.require
.as_ref()
.map(|value| Given::parse(value, parse_require))
.transpose()
.map_err(|e| ("require", e))?;
let paragraphs = config
.paragraphs
.as_ref()
.map(|value| Given::parse(value, parse_paragraphs))
.transpose()
.map_err(|e| ("paragraphs", e))?;
Ok(Self { forbid, require, paragraphs, ignore: config.ignore.clone() })
}
pub fn is_empty(&self) -> bool {
self.forbid.is_none() && self.require.is_none() && self.paragraphs.is_none()
}
pub fn resolve(&self, pool: &VariablePool) -> Result<Rules, NodeError> {
let forbid = match &self.forbid {
Some(given) => given.resolve(pool, Vec::new(), parse_forbid)?,
None => Vec::new(),
};
let require = match &self.require {
Some(given) => given.resolve(pool, Vec::new(), parse_require)?,
None => Vec::new(),
};
let paragraphs = match &self.paragraphs {
Some(given) => given.resolve(pool, IndexMap::new(), parse_paragraphs)?,
None => IndexMap::new(),
};
Ok(Rules { forbid, require, paragraphs, ignore: self.ignore.clone() })
}
pub fn selectors(&self) -> Vec<Selector> {
let mut out = Vec::new();
out.extend(self.forbid.as_ref().and_then(Given::selector).cloned());
out.extend(self.require.as_ref().and_then(Given::selector).cloned());
out.extend(self.paragraphs.as_ref().and_then(Given::selector).cloned());
out
}
}
fn objects(value: &serde_json::Value, what: &str) -> Result<(), RuleError> {
match value {
serde_json::Value::Array(items) if items.iter().all(serde_json::Value::is_object) => Ok(()),
_ => Err(RuleError(format!("{what} must be a list of rules (objects)"))),
}
}
fn parse_forbid(value: &serde_json::Value) -> Result<Vec<Forbid>, RuleError> {
objects(value, "forbid")?;
let specs: Vec<ForbidSpec> =
serde_json::from_value(value.clone()).map_err(|e| RuleError(format!("forbid must be a list of rules: {e}")))?;
specs.iter().map(ForbidSpec::compile).collect()
}
fn parse_require(value: &serde_json::Value) -> Result<Vec<Require>, RuleError> {
objects(value, "require")?;
let rules: Vec<Require> = serde_json::from_value(value.clone())
.map_err(|e| RuleError(format!("require must be a list of `{{field, text}}`: {e}")))?;
for rule in &rules {
check_field_pattern(&rule.field)?;
if rule.text.is_empty() {
return Err(RuleError(format!("require of `{}`: `text` must not be empty", rule.field)));
}
}
Ok(rules)
}
fn parse_paragraphs(value: &serde_json::Value) -> Result<IndexMap<String, usize>, RuleError> {
let counts: IndexMap<String, usize> = serde_json::from_value(value.clone())
.map_err(|e| RuleError(format!("paragraphs must map fields to counts: {e}")))?;
for field in counts.keys() {
check_field_pattern(field)?;
}
Ok(counts)
}
pub fn rules_schema() -> serde_json::Value {
use serde_json::json;
use crate::catalog::schema::selector;
let field = json!({ "type": "string", "minLength": 1, "description": "Field path (`summary`, `items[*].note`); it covers the fields inside it" });
let forbid_rule = json!({
"type": "object",
"properties": {
"name": { "type": "string", "description": "Name of the rule in the issues" },
"text": { "type": "string", "minLength": 1, "description": "A phrase: any case, any spacing, whole words" },
"pattern": { "type": "string", "minLength": 1, "description": "A regular expression (no look-around; `(?i)` for any case)" },
"detect": { "type": "string", "enum": ["email", "phone"], "description": "A built-in detector" },
"message": { "type": "string", "description": "The message of its issues" },
"fields": { "type": "array", "items": field.clone(), "description": "Fields the rule applies to (default: all)" },
"replace": { "type": "string", "description": "What `fixed` writes instead of a match (`$1` for a group)" },
"redact": { "type": "boolean", "description": "Leave the matched text out of the issues (default: on for detectors)" }
},
"additionalProperties": false
});
let require_rule = json!({
"type": "object",
"properties": {
"field": field.clone(),
"text": { "type": "string", "minLength": 1, "description": "The text the field must contain, as written" },
"message": { "type": "string" }
},
"required": ["field", "text"],
"additionalProperties": false
});
let or_selector = |inline: serde_json::Value, description: &str| json!({ "description": description, "anyOf": [inline, selector()] });
json!({
"forbid": or_selector(json!({ "type": "array", "items": forbid_rule }), "Texts that must not appear, or a selector of such rules"),
"require": or_selector(json!({ "type": "array", "items": require_rule }), "Texts a field must state, or a selector of such rules"),
"paragraphs": or_selector(
json!({ "type": "object", "additionalProperties": { "type": "integer", "minimum": 0 } }),
"Paragraphs per field (`{field: count}`), or a selector of such an object"
),
"ignore": { "type": "array", "items": { "type": "string" }, "description": "Whole texts (`N/A`) that `require` and `paragraphs` skip" }
})
}
pub fn check_field_pattern(pattern: &str) -> Result<(), RuleError> {
if pattern.trim().is_empty() {
return Err(RuleError("a field must not be empty".into()));
}
Ok(())
}
pub fn covers(pattern: &str, field: &str) -> bool {
let (mut pattern, mut field) = (pattern, field);
while let Some(next) = pattern.chars().next() {
if let Some(rest) = pattern.strip_prefix("[*]") {
let Some(index) = field.strip_prefix('[') else { return false };
let digits = index.bytes().take_while(u8::is_ascii_digit).count();
let Some(after) = index.get(digits..).and_then(|after| after.strip_prefix(']')) else { return false };
if digits == 0 {
return false;
}
(pattern, field) = (rest, after);
} else {
let Some(after) = field.strip_prefix(next) else { return false };
(pattern, field) = (pattern.get(next.len_utf8()..).unwrap_or_default(), after);
}
}
field.is_empty() || field.starts_with('.') || field.starts_with('[')
}
fn phrase_pattern(text: &str) -> String {
let text = text.trim();
let words: Vec<String> = text.split_whitespace().map(regex::escape).collect();
let mut pattern = String::from("(?i)");
let is_word = |c: Option<char>| c.is_some_and(|c| c.is_alphanumeric() || c == '_');
if is_word(text.chars().next()) {
pattern.push_str(r"\b");
}
pattern.push_str(&words.join(r"\s+"));
if is_word(text.chars().last()) {
pattern.push_str(r"\b");
}
pattern
}
fn shorten(text: &str) -> String {
let text = text.trim();
match text.char_indices().nth(FOUND_CHARS).and_then(|(cut, _)| text.get(..cut)) {
Some(head) => format!("{head}…"),
None => text.to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn json(value: serde_json::Value) -> Value {
Value::from_json(value)
}
fn forbid(spec: serde_json::Value) -> Forbid {
serde_json::from_value::<ForbidSpec>(spec).unwrap().compile().unwrap()
}
fn rules_with_forbid(specs: Vec<serde_json::Value>) -> Rules {
Rules { forbid: specs.into_iter().map(forbid).collect(), ..Rules::default() }
}
#[test]
fn fields_cover_the_fields_inside_them() {
assert!(covers("notes", "notes"));
assert!(covers("notes", "notes[2]"));
assert!(covers("notes", "notes.title"));
assert!(!covers("notes", "notes_extra"));
assert!(covers("stores[*].note", "stores[12].note"));
assert!(!covers("stores[*].note", "stores.note"));
assert!(covers("stores[1]", "stores[1].note"));
assert!(!covers("stores[1]", "stores[10].note"));
}
#[test]
fn texts_have_field_paths_and_list_counts() {
let texts = Texts::of(&json(serde_json::json!({"a": ["x", "y"], "b": {"c": 12.5, "d": true}})), "");
assert_eq!(
texts.leaves,
vec![("a[0]".into(), "x".into()), ("a[1]".into(), "y".into()), ("b.c".into(), "12.5".into())]
);
assert_eq!(texts.lists.get("a"), Some(&2));
assert_eq!(Texts::of(&Value::from("plain"), "").leaves, vec![("text".into(), "plain".into())]);
assert_eq!(Texts::of(&Value::from("plain"), "draft.text").leaves[0].0, "draft.text");
}
#[test]
fn a_phrase_matches_in_any_case_and_spacing_as_whole_words() {
let rules = rules_with_forbid(vec![serde_json::json!({"text": "Spring Sale", "message": "not running"})]);
let texts = Texts::of(
&json(serde_json::json!({"a": "The spring sale ended.", "b": "Springsale", "c": "SPRING\nSALE!"})),
"",
);
let issues = check(&texts, &rules);
assert_eq!(issues.iter().map(|i| i.field.as_str()).collect::<Vec<_>>(), vec!["a", "c"]);
assert_eq!(issues[0].message, "not running");
assert_eq!(issues[0].found.as_deref(), Some("spring sale"));
}
#[test]
fn a_mark_is_found_wherever_it_stands() {
let rules = rules_with_forbid(vec![serde_json::json!({"name": "semicolon", "text": ";", "replace": "."})]);
let value = json(serde_json::json!({"a": "One; two;three"}));
let issues = check(&Texts::of(&value, ""), &rules);
assert_eq!(issues.len(), 2);
assert_eq!(issues[0].rule, "semicolon");
assert_eq!(issues[0].message, "remove \";\"");
assert_eq!(fix(&value, "", &rules.forbid).to_json(), serde_json::json!({"a": "One. two.three"}));
}
#[test]
fn a_pattern_may_be_limited_to_fields_and_fixed_with_groups() {
let rules = rules_with_forbid(vec![serde_json::json!({
"pattern": r"(?i)\b(fell|declined)\s+(by\s+)?-(\d)",
"message": "no minus after a falling verb",
"fields": ["notes[*]"],
"replace": "$1 $2$3"
})]);
let value = json(serde_json::json!({"notes": ["Sales fell by -5%."], "title": "Sales fell -5%"}));
let issues = check(&Texts::of(&value, ""), &rules);
assert_eq!(issues.len(), 1);
assert_eq!(issues[0].field, "notes[0]");
assert_eq!(issues[0].found.as_deref(), Some("fell by -5"));
let fixed = fix(&value, "", &rules.forbid).to_json();
assert_eq!(fixed, serde_json::json!({"notes": ["Sales fell by 5%."], "title": "Sales fell -5%"}));
}
#[test]
fn detectors_find_contacts_and_hide_them() {
let rules =
rules_with_forbid(vec![serde_json::json!({"detect": "email"}), serde_json::json!({"detect": "phone"})]);
let value = json(serde_json::json!({
"rows": [{"note": "write to jane.doe@example.co.uk"}, {"note": "call +62 812-3456-7890"}],
"fine": "growth of +12.5% in 2026-10, 1,234,567 visits, version 1.2.3"
}));
let issues = check(&Texts::of(&value, ""), &rules);
assert_eq!(issues.len(), 2, "{issues:?}");
assert_eq!((issues[0].rule.as_str(), issues[0].field.as_str()), ("email", "rows[0].note"));
assert_eq!((issues[1].rule.as_str(), issues[1].field.as_str()), ("phone", "rows[1].note"));
assert!(issues.iter().all(|issue| issue.found.is_none()));
assert_eq!(issues[0].to_string(), "rows[0].note: contains an email address");
}
#[test]
fn numbers_are_text_too() {
let rules = rules_with_forbid(vec![serde_json::json!({"name": "id", "pattern": r"^\d{12,}$"})]);
let issues = check(&Texts::of(&json(serde_json::json!({"id": 6281234567890_i64})), ""), &rules);
assert_eq!(issues.len(), 1);
}
#[test]
fn wrong_rules_are_refused() {
let compile = |spec: serde_json::Value| serde_json::from_value::<ForbidSpec>(spec).unwrap().compile();
assert!(compile(serde_json::json!({})).is_err());
assert!(compile(serde_json::json!({"text": ";", "pattern": ";"})).is_err());
assert!(compile(serde_json::json!({"text": " "})).is_err());
let error = compile(serde_json::json!({"pattern": "(?<!x)y"})).unwrap_err();
assert!(error.0.contains("forbid pattern"), "{error}");
assert!(serde_json::from_value::<ForbidSpec>(serde_json::json!({"txt": ";"})).is_err());
}
#[test]
fn required_texts_are_looked_for_in_the_whole_field() {
let rules = Rules {
require: vec![
Require { field: "notes".into(), text: "12.5%".into(), message: None },
Require { field: "notes".into(), text: "Spring".into(), message: Some("name the campaign".into()) },
Require { field: "missing".into(), text: "x".into(), message: None },
Require { field: "empty".into(), text: "x".into(), message: None },
],
ignore: vec!["N/A".into()],
..Rules::default()
};
let value = json(serde_json::json!({"notes": ["Sales rose.", "Up 12.5% on May."], "empty": " N/A "}));
let issues = check(&Texts::of(&value, ""), &rules);
assert_eq!(issues.len(), 1, "{issues:?}");
assert_eq!(issues[0].to_string(), "notes: name the campaign");
}
#[test]
fn paragraphs_count_list_items_or_text_blocks() {
let rules = Rules {
paragraphs: IndexMap::from([("list".into(), 2), ("text".into(), 2), ("one".into(), 1), ("na".into(), 3)]),
ignore: vec!["N/A".into()],
..Rules::default()
};
let value = json(serde_json::json!({
"list": ["a", "b", "c"], "text": "First.\n\n\nSecond\nstill second.", "one": "a\n\nb", "na": ["N/A"]
}));
let issues = check(&Texts::of(&value, ""), &rules);
assert_eq!(
notes(&issues),
"- list: write exactly 2 paragraphs, not 3\n- one: write exactly 1 paragraph, not 2"
);
}
#[test]
fn issues_of_other_checks_read_as_notes() {
let unsupported = json(serde_json::json!([
{"field": "summary", "number": "31%", "sentence": "Toys took 31%.", "reason": "attribution",
"named": "Toys", "owners": ["Electronics"]},
{"field": "notes[1]", "number": "48", "sentence": "We sold 48.", "reason": "value"},
{"field": "x", "rule": "custom", "message": "say it plainly"},
"free text"
]));
let issues = issues_from(&unsupported).unwrap();
assert_eq!(
notes(&issues),
"- summary: 31% belongs to Electronics, not Toys (\"Toys took 31%.\")\n\
- notes[1]: 48 is not in the facts (\"We sold 48.\")\n\
- x: say it plainly\n\
- free text"
);
assert!(issues_from(&Value::Null).unwrap().is_empty());
assert!(issues_from(&Value::from("x")).is_err());
}
#[test]
fn issues_are_capped() {
let rules = rules_with_forbid(vec![serde_json::json!({"text": ";"})]);
let issues = check(&Texts::of(&Value::from(";".repeat(MAX_ISSUES + 50)), ""), &rules);
assert_eq!(issues.len(), MAX_ISSUES);
}
}