1
//! Unit tests for the introspection / test-framework special forms.
2

            
3
use crate::ast::{Expr, Fraction, Number};
4
use crate::error::Error;
5
use crate::runtime::{Symbol, SymbolKind, SymbolTable};
6

            
7
use super::apropos::apropos;
8
use super::describe_pp::pp;
9
use super::folded::{folded_eval_form, folded_form, folded_symbol};
10
use super::test_framework::{assert_equal, deftest, run_tests};
11

            
12
29
fn syms() -> SymbolTable {
13
29
    SymbolTable::with_builtins()
14
29
}
15

            
16
#[test]
17
1
fn pp_constant_number_returns_string() {
18
1
    let result = pp(&mut syms(), &[Expr::Number(Number::Index(42))]).unwrap();
19
1
    assert_eq!(result, Expr::String("42".to_string()));
20
1
}
21

            
22
#[test]
23
1
fn pp_string_literal_round_trips() {
24
1
    let result = pp(&mut syms(), &[Expr::String("hi".into())]).unwrap();
25
    // format_expr prints strings with their content (no quoting)
26
    // — matches DESCRIBE's value-line convention.
27
1
    assert_eq!(result, Expr::String("hi".to_string()));
28
1
}
29

            
30
#[test]
31
1
fn pp_nil_returns_nil_text() {
32
1
    let result = pp(&mut syms(), &[Expr::Nil]).unwrap();
33
1
    assert_eq!(result, Expr::String("nil".to_string()));
34
1
}
35

            
36
#[test]
37
1
fn pp_arity_zero_errors() {
38
1
    assert!(pp(&mut syms(), &[]).is_err());
39
1
}
40

            
41
#[test]
42
1
fn pp_arity_two_errors() {
43
1
    assert!(pp(&mut syms(), &[Expr::Nil, Expr::Nil]).is_err());
44
1
}
45

            
46
#[test]
47
1
fn apropos_finds_entity_count() {
48
1
    let result = apropos(&mut syms(), &[Expr::String("entity-count".into())]).unwrap();
49
1
    let Expr::Datum(inner) = result else {
50
        panic!("apropos must return a quoted list, got {result:?}");
51
    };
52
1
    let Expr::List(elems) = *inner else {
53
        panic!("apropos must return a quoted list");
54
    };
55
1
    assert!(
56
1
        elems
57
1
            .iter()
58
1
            .any(|e| matches!(e, Expr::Symbol(s) if s == "ENTITY-COUNT")),
59
        "missing ENTITY-COUNT in {elems:?}",
60
    );
61
1
}
62

            
63
#[test]
64
1
fn apropos_folds_a_quoted_symbol_argument() {
65
1
    let result = apropos(&mut syms(), &[Expr::quoted(Expr::Symbol("mapcar".into()))]).unwrap();
66
1
    assert_eq!(
67
1
        result,
68
1
        Expr::quoted_list(vec![Expr::Symbol("MAPCAR".into())])
69
    );
70
1
}
71

            
72
#[test]
73
1
fn apropos_rejects_a_non_constant_argument() {
74
1
    let err = apropos(&mut syms(), &[Expr::Symbol("unbound-needle".into())]).unwrap_err();
75
1
    assert!(err.to_string().contains("APROPOS"), "got: {err}");
76
1
}
77

            
78
#[test]
79
1
fn apropos_is_case_insensitive() {
80
1
    let result = apropos(&mut syms(), &[Expr::String("entity-COUNT".into())]).unwrap();
81
1
    let Expr::Datum(inner) = result else {
82
        panic!("expected quoted list");
83
    };
84
1
    let Expr::List(elems) = *inner else {
85
        panic!("expected list");
86
    };
87
1
    assert!(
88
1
        elems
89
1
            .iter()
90
1
            .any(|e| matches!(e, Expr::Symbol(s) if s == "ENTITY-COUNT"))
91
    );
92
1
}
93

            
94
#[test]
95
1
fn apropos_results_are_sorted() {
96
1
    let result = apropos(&mut syms(), &[Expr::String("entity".into())]).unwrap();
97
1
    let Expr::Datum(inner) = result else {
98
        panic!("expected quoted list");
99
    };
100
1
    let Expr::List(elems) = *inner else {
101
        panic!("expected list");
102
    };
103
1
    let names: Vec<&str> = elems
104
1
        .iter()
105
15
        .filter_map(|e| match e {
106
15
            Expr::Symbol(s) => Some(s.as_str()),
107
            _ => None,
108
15
        })
109
        .collect();
110
1
    let mut sorted = names.clone();
111
1
    sorted.sort();
112
1
    assert_eq!(names, sorted, "apropos must return sorted names");
113
1
}
114

            
115
#[test]
116
1
fn apropos_no_match_returns_nil() {
117
1
    let result = apropos(&mut syms(), &[Expr::String("nonexistent-xyz-12345".into())]).unwrap();
118
1
    assert_eq!(result, Expr::Nil);
119
1
}
120

            
121
#[test]
122
1
fn apropos_rejects_number_arg() {
123
    let err =
124
1
        apropos(&mut syms(), &[Expr::Number(Number::Index(1))]).expect_err("number should error");
125
1
    assert!(err.to_string().contains("APROPOS"));
126
1
}
127

            
128
#[test]
129
1
fn deftest_registers_named_test() {
130
1
    let mut s = syms();
131
1
    let name = Expr::Symbol("smoke".to_string());
132
1
    let body = Expr::Number(Number::Index(1));
133
1
    let result = deftest(&mut s, &[name, body.clone()]).unwrap();
134
1
    assert_eq!(result, Expr::Datum(Box::new(Expr::Symbol("smoke".into()))));
135
1
    assert_eq!(s.tests(), vec![("smoke".to_string(), body)]);
136
1
}
137

            
138
#[test]
139
1
fn deftest_wraps_multi_form_body_in_progn() {
140
1
    let mut s = syms();
141
1
    let _ = deftest(
142
1
        &mut s,
143
1
        &[
144
1
            Expr::Symbol("multi".into()),
145
1
            Expr::Number(Number::Index(1)),
146
1
            Expr::Number(Number::Index(2)),
147
1
        ],
148
1
    )
149
1
    .unwrap();
150
1
    let (_, body) = s.tests().into_iter().next().unwrap();
151
1
    let Expr::List(elems) = body else {
152
        panic!("multi-form body must be wrapped in a PROGN list");
153
    };
154
1
    assert_eq!(elems[0], Expr::symbol("PROGN"));
155
1
    assert_eq!(elems.len(), 3);
156
1
}
157

            
158
#[test]
159
1
fn deftest_rejects_non_symbol_name() {
160
1
    let err = deftest(&mut syms(), &[Expr::String("not-a-sym".into()), Expr::Nil])
161
1
        .expect_err("string name must error");
162
1
    assert!(err.to_string().contains("DEFTEST"));
163
1
}
164

            
165
/// Re-registering a test name overwrites in place instead of appending, so the
166
/// two-surface compile (a DEFTEST evaluated on both the eval and codegen pass)
167
/// can't double-register and double-run a test. The latest body wins.
168
#[test]
169
1
fn deftest_reregistration_is_idempotent() {
170
1
    let mut s = syms();
171
1
    let name = Expr::Symbol("dup".to_string());
172
1
    let first = Expr::Number(Number::Index(1));
173
1
    let second = Expr::Number(Number::Index(2));
174
1
    deftest(&mut s, &[name.clone(), first]).unwrap();
175
1
    deftest(&mut s, &[name, second.clone()]).unwrap();
176
1
    assert_eq!(s.tests(), vec![("dup".to_string(), second)]);
177
1
}
178

            
179
#[test]
180
1
fn assert_equal_passes_for_equal_numbers() {
181
1
    let one = Expr::Number(Number::Index(1));
182
1
    let result = assert_equal(&mut syms(), &[one.clone(), one]).unwrap();
183
1
    assert_eq!(result, Expr::Nil);
184
1
}
185

            
186
#[test]
187
1
fn assert_equal_fails_for_unequal() {
188
1
    let err = assert_equal(
189
1
        &mut syms(),
190
1
        &[
191
1
            Expr::Number(Number::Index(1)),
192
1
            Expr::Number(Number::Index(2)),
193
1
        ],
194
1
    )
195
1
    .expect_err("1 != 2");
196
1
    assert!(err.to_string().contains("assertion failed"));
197
1
}
198

            
199
#[test]
200
1
fn run_tests_empty_registry_reports_zero() {
201
1
    let result = run_tests(&mut syms(), &[]).unwrap();
202
1
    let Expr::String(s) = result else {
203
        panic!("expected String summary");
204
    };
205
1
    assert!(s.contains("0 tests"));
206
1
    assert!(s.contains("0 passed"));
207
1
    assert!(s.contains("0 failed"));
208
1
}
209

            
210
#[test]
211
1
fn run_tests_counts_one_pass_one_fail() {
212
1
    let mut s = syms();
213
1
    s.register_test(
214
1
        "ok",
215
1
        Expr::List(vec![
216
1
            Expr::Symbol("ASSERT-EQUAL".into()),
217
1
            Expr::Number(Number::Index(1)),
218
1
            Expr::Number(Number::Index(1)),
219
1
        ]),
220
1
    );
221
1
    s.register_test(
222
1
        "bad",
223
1
        Expr::List(vec![
224
1
            Expr::Symbol("ASSERT-EQUAL".into()),
225
1
            Expr::Number(Number::Index(1)),
226
1
            Expr::Number(Number::Index(2)),
227
1
        ]),
228
1
    );
229
1
    let result = run_tests(&mut s, &[]).unwrap();
230
1
    let Expr::String(summary) = result else {
231
        panic!("expected summary string");
232
    };
233
1
    assert!(summary.contains("2 tests"));
234
1
    assert!(summary.contains("1 passed"));
235
1
    assert!(summary.contains("1 failed"));
236
1
    assert!(summary.contains("bad"));
237
1
}
238

            
239
#[test]
240
1
fn run_tests_rejects_args() {
241
    let err =
242
1
        run_tests(&mut syms(), &[Expr::Number(Number::Index(1))]).expect_err("args must error");
243
1
    assert!(err.to_string().contains("RUN-TESTS"));
244
1
}
245

            
246
5
fn quoted_sum() -> Expr {
247
5
    Expr::List(vec![
248
5
        Expr::Symbol("+".into()),
249
5
        Expr::Number(Number::Index(1)),
250
5
        Expr::Number(Number::Index(2)),
251
5
    ])
252
5
}
253

            
254
#[test]
255
1
fn folded_form_unwraps_a_quoted_datum() {
256
1
    let operand = Expr::Quote(Box::new(quoted_sum()));
257
1
    assert_eq!(
258
1
        folded_form(&mut syms(), "EVAL", &operand).unwrap(),
259
1
        quoted_sum()
260
    );
261
1
}
262

            
263
#[test]
264
1
fn folded_form_folds_a_constructed_form() {
265
1
    let operand = Expr::List(vec![
266
1
        Expr::Symbol("LIST".into()),
267
1
        Expr::Quote(Box::new(Expr::Symbol("+".into()))),
268
1
        Expr::Number(Number::Index(1)),
269
1
        Expr::Number(Number::Index(2)),
270
1
    ]);
271
1
    assert_eq!(
272
1
        folded_form(&mut syms(), "EVAL", &operand).unwrap(),
273
1
        quoted_sum()
274
    );
275
1
}
276

            
277
#[test]
278
1
fn folded_form_rejects_a_non_constant_operand() {
279
1
    let err = folded_form(&mut syms(), "EVAL", &Expr::Symbol("unbound-var".into())).unwrap_err();
280
1
    assert_eq!(
281
1
        err.to_string(),
282
1
        "Compile error: EVAL: the form is not a compile-time constant"
283
    );
284
1
}
285

            
286
#[test]
287
1
fn folded_symbol_reads_a_quoted_symbol() {
288
1
    let operand = Expr::Quote(Box::new(Expr::Symbol("CAR".into())));
289
1
    assert_eq!(
290
1
        folded_symbol(&mut syms(), "COMPILE", &operand).unwrap(),
291
1
        "CAR"
292
    );
293
1
}
294

            
295
#[test]
296
1
fn folded_symbol_rejects_a_non_symbol() {
297
1
    let err = folded_symbol(&mut syms(), "COMPILE", &Expr::Number(Number::Index(42))).unwrap_err();
298
1
    assert_eq!(
299
1
        err.to_string(),
300
1
        "Compile error: COMPILE: argument must be a quoted symbol"
301
    );
302
1
}
303

            
304
1
fn bound_sum_of(name: &str) -> Expr {
305
1
    Expr::Quote(Box::new(Expr::List(vec![
306
1
        Expr::Symbol("+".into()),
307
1
        Expr::Symbol(name.into()),
308
1
        Expr::Number(Number::Index(1)),
309
1
    ])))
310
1
}
311

            
312
2
fn bind_locally(symbols: &mut SymbolTable, name: &str) {
313
2
    symbols
314
2
        .define(Symbol::new(name, SymbolKind::Variable).with_value(Expr::Number(Number::Index(1))));
315
2
}
316

            
317
#[test]
318
1
fn folded_eval_form_rejects_a_locally_bound_name() {
319
1
    let mut symbols = syms();
320
1
    bind_locally(&mut symbols, "A");
321
1
    let err = folded_eval_form(&mut symbols, &bound_sum_of("A")).unwrap_err();
322
1
    assert_eq!(
323
1
        err.to_string(),
324
1
        "Compile error: EVAL: A is bound locally here; EVAL sees only global definitions"
325
    );
326
1
}
327

            
328
#[test]
329
1
fn folded_eval_form_accepts_a_global_and_ignores_other_locals() {
330
1
    let mut symbols = syms();
331
1
    bind_locally(&mut symbols, "B");
332
1
    assert_eq!(
333
1
        folded_eval_form(&mut symbols, &Expr::Quote(Box::new(quoted_sum()))).unwrap(),
334
1
        quoted_sum()
335
    );
336
1
}
337

            
338
#[test]
339
1
fn assert_equal_refuses_two_numeric_kinds() {
340
1
    let err = assert_equal(
341
1
        &mut syms(),
342
1
        &[
343
1
            Expr::Number(Number::Index(1)),
344
1
            Expr::Number(Number::Scalar(Fraction::new(1, 1))),
345
1
        ],
346
1
    )
347
1
    .expect_err("index against scalar");
348
1
    assert!(matches!(err, Error::Dimension(_)), "{err}");
349
1
}