Skip to main content

react_auditor/rules/testing/
assert_includes_message.rs

1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4
5use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
6
7pub struct AssertIncludesMessage;
8
9const RULE_META: RuleMeta = RuleMeta {
10    id: "assert-includes-message",
11    default_severity: Severity::Warning,
12    category: "testing",
13    description: "Assertions should include a descriptive message",
14};
15
16const ASSERT_METHODS: &[(&str, usize)] = &[
17    ("assert", 1),
18    ("assert.ok", 1),
19    ("assert.strictEqual", 2),
20    ("assert.deepEqual", 2),
21    ("assert.equal", 2),
22    ("assert.notStrictEqual", 2),
23    ("assert.notEqual", 2),
24    ("assert.deepStrictEqual", 2),
25    ("assert.notDeepStrictEqual", 2),
26    ("assert.throws", 1),
27    ("assert.doesNotThrow", 1),
28    ("assert.rejects", 1),
29    ("assert.doesNotReject", 1),
30];
31
32impl Rule for AssertIncludesMessage {
33    fn meta(&self) -> &RuleMeta {
34        &RULE_META
35    }
36
37    fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
38        let mut collector = AssertCollector {
39            findings: Vec::new(),
40            source: source_text,
41        };
42        collector.visit_program(program);
43        collector.findings
44    }
45}
46
47struct AssertCollector<'a> {
48    findings: Vec<RuleFinding>,
49    source: &'a str,
50}
51
52impl<'a> AssertCollector<'a> {
53    fn push_finding(&mut self, start: usize, msg: String) {
54        let line = self.source[..start].lines().count().max(1);
55        let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
56        self.findings.push(RuleFinding {
57            line,
58            column: col + 1,
59            message: msg,
60        });
61    }
62}
63
64impl<'a> Visit<'a> for AssertCollector<'a> {
65    fn visit_call_expression(&mut self, expr: &oxc_ast::ast::CallExpression<'a>) {
66        let callee_str = match &expr.callee {
67            oxc_ast::ast::Expression::Identifier(ident) if ident.name.as_str() == "assert" => {
68                "assert".to_string()
69            }
70            oxc_ast::ast::Expression::StaticMemberExpression(member) => {
71                if let oxc_ast::ast::Expression::Identifier(obj) = &member.object {
72                    if obj.name.as_str() == "assert" {
73                        format!("assert.{}", member.property.name.as_str())
74                    } else {
75                        return;
76                    }
77                } else {
78                    return;
79                }
80            }
81            _ => return,
82        };
83
84        let Some(&(_, required_args)) = ASSERT_METHODS.iter().find(|(name, _)| *name == callee_str)
85        else {
86            return;
87        };
88
89        if expr.arguments.len() <= required_args {
90            let last_arg_has_msg = expr
91                .arguments
92                .last()
93                .and_then(|arg| arg.as_expression())
94                .is_some_and(|e| matches!(e, oxc_ast::ast::Expression::StringLiteral(_)));
95
96            if !last_arg_has_msg {
97                let method_name = if callee_str == "assert" {
98                    "assert(condition)".to_string()
99                } else {
100                    format!("{callee_str}(…)")
101                };
102                self.push_finding(
103                    expr.span.start as usize,
104                    format!(
105                        "`{method_name}` is missing a descriptive message — add a string argument explaining the assertion"
106                    ),
107                );
108            }
109        }
110    }
111}