1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
//! Fuzz-style robustness tests for the parser + editing paths.
//!
//! `cargo-fuzz` requires a nightly toolchain (libfuzzer-sys links
//! against compiler-rt's fuzzing runtime), which isn't a guaranteed
//! CI dependency. This suite drives the same parsers through
//! `proptest`-generated random inputs — not coverage-guided, so less
//! effective than libFuzzer at discovering deep branches, but
//! adequate for surfacing "parser panics on weird input" bugs and
//! for locking in the *no-panic* contract across the public API.
//!
//! Each property runs 1024 iterations (configurable via
//! `PROPTEST_CASES=<N>`). Shrinking on failure is via proptest's
//! built-in minimiser, so a crash reduces to the smallest input that
//! reproduces it.
//!
//! Invariants asserted (in addition to "does not panic"):
//!
//! * After `set_html(x)` / `set_markdown(x)` succeeds,
//! `to_plain_text()` must succeed and `character_count() >= 0`.
//! * `block_count()` is always at least 1 once plain text has been
//! initialised.
//! * A successful import round-trip through HTML or markdown
//! preserves the plain-text content modulo whitespace
//! normalisation.
use proptest::prelude::*;
use text_document::{MoveMode, MoveOperation, TextDocument};
// Bounded random bytes that contain a biased mix of ASCII, UTF-8
// multibyte, HTML-significant, and markdown-significant characters.
// Uniform random bytes would almost never produce valid HTML; this
// strategy skews toward "interesting" inputs.
fn arb_html_like() -> impl Strategy<Value = String> {
proptest::string::string_regex(r#"[a-zA-Z0-9 <>/&;!?.,\n\t\-="'#\[\]\(\)éà🌍]{0,200}"#).unwrap()
}
fn arb_markdown_like() -> impl Strategy<Value = String> {
proptest::string::string_regex(r"[a-zA-Z0-9 #*_`|\-\[\]\(\)!\n\t.,>:;éà🌍]{0,200}").unwrap()
}
// Small alphabet for edit-op sequences that drive the cursor API.
#[derive(Debug, Clone)]
enum Op {
InsertText(String),
InsertBlock,
DeleteChar,
DeletePrev,
MoveNext(u8),
MovePrev(u8),
SelectForward(u8),
SelectBackward(u8),
Undo,
Redo,
}
fn arb_op() -> impl Strategy<Value = Op> {
prop_oneof![
proptest::string::string_regex(r"[a-z ]{0,5}")
.unwrap()
.prop_map(Op::InsertText),
Just(Op::InsertBlock),
Just(Op::DeleteChar),
Just(Op::DeletePrev),
(0u8..6).prop_map(Op::MoveNext),
(0u8..6).prop_map(Op::MovePrev),
(0u8..6).prop_map(Op::SelectForward),
(0u8..6).prop_map(Op::SelectBackward),
Just(Op::Undo),
Just(Op::Redo),
]
}
// ── Property: HTML parser never panics ──────────────────────────────
proptest! {
#[test]
fn set_html_never_panics(input in arb_html_like()) {
// Priming with `set_plain_text("")` guarantees the document
// has an initial block; without it a fresh document can have
// `block_count == 0`, which is a valid construction state
// even though every edit path assumes ≥1 block. Callers
// (including the rich-text widget) always prime the doc, so
// the same contract applies here.
let doc = TextDocument::new();
doc.set_plain_text("").unwrap();
// We don't care whether set_html succeeds; we care that it
// doesn't panic. Error returns are a valid outcome.
let op = match doc.set_html(&input) {
Ok(o) => o,
Err(_) => return Ok(()),
};
// `set_html` returns an Operation that completes async on a
// background thread. Wait for it before querying: a panic there
// is the failure mode we're testing for, and querying mid-import
// races the still-mutating doc. An `Err` result is fine.
let _ = op.wait();
// Downstream queries must still be safe.
prop_assert!(doc.to_plain_text().is_ok());
prop_assert!(doc.block_count() >= 1);
}
}
// ── Property: markdown parser never panics ──────────────────────────
proptest! {
#[test]
fn set_markdown_never_panics(input in arb_markdown_like()) {
let doc = TextDocument::new();
doc.set_plain_text("").unwrap();
let op = match doc.set_markdown(&input) {
Ok(o) => o,
Err(_) => return Ok(()),
};
// `set_markdown` returns an Operation that completes async.
// `wait` blocks until done; panic there is the failure mode
// we're testing for. An `Err` result is fine.
let _ = op.wait();
prop_assert!(doc.to_plain_text().is_ok());
prop_assert!(doc.block_count() >= 1);
}
}
// ── Property: insert_html at arbitrary cursor positions ─────────────
proptest! {
#[test]
fn insert_html_at_arbitrary_position_never_panics(
seed in "[a-zA-Z ]{0,30}",
html in arb_html_like(),
pos_frac in 0.0f64..=1.0,
) {
let doc = TextDocument::new();
doc.set_plain_text(&seed).unwrap();
let pos = ((pos_frac * doc.character_count() as f64).floor() as usize)
.min(doc.character_count());
let cursor = doc.cursor_at(pos);
let _ = cursor.insert_html(&html);
// Any downstream query must still succeed.
prop_assert!(doc.to_plain_text().is_ok());
prop_assert!(doc.block_count() >= 1);
}
}
// ── Property: random edit sequences preserve invariants ─────────────
proptest! {
#[test]
fn random_edit_sequence_preserves_invariants(
seed in "[a-zA-Z ]{0,40}",
ops in prop::collection::vec(arb_op(), 0..20),
) {
let doc = TextDocument::new();
doc.set_plain_text(&seed).unwrap();
let cursor = doc.cursor_at(0);
for op in &ops {
match op {
Op::InsertText(t) => { let _ = cursor.insert_text(t); }
Op::InsertBlock => { let _ = cursor.insert_block(); }
Op::DeleteChar => { let _ = cursor.delete_char(); }
Op::DeletePrev => { let _ = cursor.delete_previous_char(); }
Op::MoveNext(n) => {
cursor.move_position(
MoveOperation::NextCharacter,
MoveMode::MoveAnchor,
*n as usize,
);
}
Op::MovePrev(n) => {
cursor.move_position(
MoveOperation::PreviousCharacter,
MoveMode::MoveAnchor,
*n as usize,
);
}
Op::SelectForward(n) => {
cursor.move_position(
MoveOperation::NextCharacter,
MoveMode::KeepAnchor,
*n as usize,
);
}
Op::SelectBackward(n) => {
cursor.move_position(
MoveOperation::PreviousCharacter,
MoveMode::KeepAnchor,
*n as usize,
);
}
Op::Undo => { let _ = doc.undo(); }
Op::Redo => { let _ = doc.redo(); }
}
// Core invariants after every op.
prop_assert!(doc.block_count() >= 1);
let plain = doc.to_plain_text().unwrap();
prop_assert_eq!(
doc.character_count() + doc.block_count() - 1,
plain.chars().count(),
"character_count + (block_count - 1) == plain.chars().count()"
);
// Cursor position never exceeds max.
let cc = doc.character_count();
let bc = doc.block_count();
let max = cc + bc.saturating_sub(1);
prop_assert!(cursor.position() <= max);
prop_assert!(cursor.anchor() <= max);
}
}
}
// ── Property: HTML → document → HTML round-trip stabilises ──────────
proptest! {
#[test]
fn html_roundtrip_stabilises(seed in arb_html_like()) {
// `set_html` is a long operation: it returns immediately with a
// handle while the import runs on a background thread. Querying
// the document before `wait()` races with the import and can see
// a still-empty doc — which is what made this property flaky on
// CI (commit transient: html1 had content, html2 raced and was
// empty, false-positive idempotency failure).
let doc1 = TextDocument::new();
let op1 = match doc1.set_html(&seed) {
Ok(o) => o,
Err(_) => return Ok(()),
};
if op1.wait().is_err() {
return Ok(());
}
let c = doc1.cursor_at(0);
c.move_position(MoveOperation::End, MoveMode::KeepAnchor, 1);
let html1 = c.selection().to_html();
// Second round-trip: parse the first output, reserialise, expect
// the same string. If the serialiser is idempotent (which it
// should be for internally-produced HTML), html1 == html2.
let doc2 = TextDocument::new();
let op2 = match doc2.set_html(&html1) {
Ok(o) => o,
Err(_) => return Ok(()),
};
if op2.wait().is_err() {
return Ok(());
}
let c2 = doc2.cursor_at(0);
c2.move_position(MoveOperation::End, MoveMode::KeepAnchor, 1);
let html2 = c2.selection().to_html();
prop_assert_eq!(
html1, html2,
"HTML serialiser must be idempotent on its own output"
);
}
}
// ── Seed corpus: hand-picked adversarial HTML inputs ────────────────
// These are the small set that would appear in a cargo-fuzz corpus
// directory. They're cheap to run and serve as a fast smoke test.
#[test]
fn seed_corpus_adversarial_html() {
let inputs: &[&str] = &[
"",
"<",
"<p>",
"</p>",
"<p><p><p><p><p>",
"<p>unterminated",
"<!DOCTYPE html><html></html>",
"<table><tr><td>",
"<script>alert(1)</script>",
"<p>&<></p>",
"<p style='x:y'>a</p>",
"<p><b><i><u></u></i></b></p>",
"<p>\0\x01\x02</p>",
"<p>café 日本語 🌍</p>",
"<p>e\u{0301}X</p>",
"<ul><li><ol><li><ul><li>deep</li></ul></li></ol></li></ul>",
];
for html in inputs {
let doc = TextDocument::new();
doc.set_plain_text("").unwrap();
if let Ok(op) = doc.set_html(html) {
let _ = op.wait();
}
// After any html import, queries must be safe.
let _ = doc.to_plain_text();
let _ = doc.character_count();
let _ = doc.block_count();
}
}
#[test]
fn seed_corpus_adversarial_markdown() {
let inputs: &[&str] = &[
"",
"#",
"##",
"# ",
"\n\n\n",
"| a | b |\n|---|---|",
"| a |\n| b\n| c",
"```\n```",
";
doc.set_plain_text("").unwrap();
if let Ok(op) = doc.set_markdown(md) {
let _ = op.wait();
}
let _ = doc.to_plain_text();
}
}