tablo-test 0.9.0

In-memory HTTP test client for Tablo panels, re-exported as `tablo::testing`.
Documentation
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Semantic queries over rendered HTML for tests.
//!
//! The table and form renderers own their markup; tests assert the behavior
//! the markup carries. Each helper reads one stable hook:
//! `tr[id^="row-"]` for rows, `tr[data-group]` for group headers, `[aria-label]` links and buttons
//! for actions, `#{name}-error` and its `data-error` for field errors, `[data-filter-name]` for
//! filters, `[data-empty]` for the zero-rows message, `[data-sidebar=menu-item]` for sidebar
//! entries, `th[data-column]` for the shown columns and its `aria-sort` for the sortable ones, and
//! the `column` checkboxes for the column picker.
//!
//! The queries assume one table per document: rows never nest, and cells carry text rather than
//! nested tables.

use tablo_core::dom::{empty, error};

pub use self::rows::{CellEdit, Group, Row, RowActions, groups, row_actions, row_keys, rows};

pub(crate) type Attrs = Vec<(String, Option<String>)>;
pub(crate) type Element = (String, Attrs, String);

/// One `<option>` of a filter select, or one checkbox of a filter checklist.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilterOption {
    /// The submitted value.
    pub value: String,
    /// The shown label.
    pub label: String,
    /// Whether the request selected it, or checked it.
    pub selected: bool,
}

/// One toggleable column the column picker offers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PickerColumn {
    /// The column's name, which the picker posts.
    pub name: String,
    /// Whether the reader's choice shows it: its box is checked.
    pub shown: bool,
}

/// Why a table rendered no rows, and the links it offers out of that state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmptyTable {
    /// What emptied it.
    pub reason: EmptyReason,
    /// The link that clears the search or the filters, `None` when nothing narrowed the table.
    pub clear: Option<String>,
    /// The link back to the first page, `None` without a cursor.
    pub first_page: Option<String>,
}

/// What emptied a table, as its zero-rows message's `data-empty` names it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EmptyReason {
    /// The table holds no records.
    NoRecords,
    /// The request's search matched no record.
    Search,
    /// The request's filters matched no record.
    Filters,
}

/// The zero-rows message of `html`, or `None` when the table renders rows.
///
/// # Panics
///
/// When the message names no reason this version knows: a renderer that drops `data-empty`'s
/// value would otherwise read as any reason.
pub fn empty_table(html: &str) -> Option<EmptyTable> {
    let (_, attrs, inner) = tags_where(html, |_, attrs| attr_value(attrs, "data-empty").is_some())
        .into_iter()
        .next()?;
    let link = |kind: &str| {
        open_tags(&inner)
            .into_iter()
            .find(|(_, attrs, _)| attr_value(attrs, "data-empty-link").as_deref() == Some(kind))
            .and_then(|(_, attrs, _)| attr_value(&attrs, "href"))
    };
    let reason = match attr_value(&attrs, "data-empty").as_deref() {
        Some(empty::NONE) => EmptyReason::NoRecords,
        Some(empty::SEARCH) => EmptyReason::Search,
        Some(empty::FILTERS) => EmptyReason::Filters,
        other => panic!("the zero-rows message names no known reason: {other:?}"),
    };
    Some(EmptyTable {
        reason,
        clear: link(empty::CLEAR_LINK),
        first_page: link(empty::FIRST_PAGE_LINK),
    })
}

/// The names of the columns the table's header shows, in order, without the bulk and actions
/// columns.
pub fn columns(html: &str) -> Vec<String> {
    open_tags(html)
        .into_iter()
        .filter(|(tag, _, _)| tag == "th")
        .filter_map(|(_, attrs, _)| attr_value(&attrs, "data-column"))
        .collect()
}

/// The names of the columns whose header sorts the table, in order: those the header marks with
/// `aria-sort`.
pub fn sortable_columns(html: &str) -> Vec<String> {
    open_tags(html)
        .into_iter()
        .filter(|(tag, attrs, _)| tag == "th" && attr_value(attrs, "aria-sort").is_some())
        .filter_map(|(_, attrs, _)| attr_value(&attrs, "data-column"))
        .collect()
}

/// The toggleable columns the column picker offers, in order, or `None` when the table renders
/// no picker.
pub fn column_picker(html: &str) -> Option<Vec<PickerColumn>> {
    let columns: Vec<PickerColumn> = open_tags(html)
        .into_iter()
        .filter(|(tag, attrs, _)| {
            tag == "input"
                && attr_value(attrs, "type").as_deref() == Some("checkbox")
                && attr_value(attrs, "name").as_deref() == Some("column")
        })
        .map(|(_, attrs, _)| PickerColumn {
            name: attr_value(&attrs, "value").unwrap_or_default(),
            shown: attrs.iter().any(|(name, _)| name == "checked"),
        })
        .collect();
    (!columns.is_empty()).then_some(columns)
}

/// The first `href` in `html` that contains `needle`, its entities decoded.
pub fn find_href_with(html: &str, needle: &str) -> Option<String> {
    open_tags(html)
        .into_iter()
        .filter_map(|(_, attrs, _)| attr_value(&attrs, "href"))
        .find(|href| href.contains(needle))
}

/// Why a field renders an error, as its error slot's `data-error` names it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
    /// Posted empty, and the field has no blank answer.
    Required,
    /// Posted a value the field, the resource's validation or the uploader refused.
    Invalid,
    /// A choice whose options the user may not read.
    Unavailable,
}

/// Why the field posting `name` was refused, or `None` when it renders no error.
///
/// # Panics
///
/// When the slot names no kind this version knows: a renderer that drops `data-error` would
/// otherwise read as any refusal.
///
/// Assert on the kind rather than the sentence, which is wording; [`field_error_message`] reads
/// the sentence for a test whose subject is an app's own message.
pub fn field_error(html: &str, name: &str) -> Option<ErrorKind> {
    let (attrs, _) = error_slot(html, name)?;
    Some(match attr_value(&attrs, "data-error").as_deref() {
        Some(error::REQUIRED) => ErrorKind::Required,
        Some(error::INVALID) => ErrorKind::Invalid,
        Some(error::UNAVAILABLE) => ErrorKind::Unavailable,
        other => panic!("the error slot of `{name}` names no known kind: {other:?}"),
    })
}

/// The sentence rendered under the field posting `name`, or `None` when it renders no error.
pub fn field_error_message(html: &str, name: &str) -> Option<String> {
    error_slot(html, name).map(|(_, text)| text)
}

/// The attributes and text of the error slot `#{name}-error`, when it renders one.
fn error_slot(html: &str, name: &str) -> Option<(Attrs, String)> {
    let target = format!("{name}-error");
    let (_, attrs, inner) = tags_where(html, |_, attrs| {
        attr_value(attrs, "id").as_deref() == Some(target.as_str())
    })
    .into_iter()
    .next()?;
    let text = strip_text(&inner);
    (!text.is_empty()).then_some((attrs, text))
}

/// The options of the select or checklist filter `name`, or `None` when `name` names neither. A
/// checklist offering no option reads as an empty list, since its control still renders.
pub fn filter_options(html: &str, name: &str) -> Option<Vec<FilterOption>> {
    let (tag, _, inner) = tags_where(html, |_, attrs| {
        attr_value(attrs, "data-filter-name").as_deref() == Some(name)
    })
    .into_iter()
    .next()?;
    if tag != "select" {
        let options: Vec<FilterOption> = elements(&inner, "label")
            .into_iter()
            .filter_map(|(_, _, inner)| {
                let (_, attrs, _) = open_tags(&inner).into_iter().find(|(tag, attrs, _)| {
                    tag == "input" && attr_value(attrs, "type").as_deref() == Some("checkbox")
                })?;
                Some(FilterOption {
                    value: attr_value(&attrs, "value").unwrap_or_default(),
                    label: strip_text(&inner),
                    selected: attrs.iter().any(|(name, _)| name == "checked"),
                })
            })
            .collect();
        // A checklist renders the button that opens it, with or without an option; another
        // control's container, such as a date filter's, renders none.
        return inner.contains("<button").then_some(options);
    }
    let options = elements(&inner, "option")
        .into_iter()
        .map(|(_, attrs, inner)| FilterOption {
            value: attr_value(&attrs, "value").unwrap_or_default(),
            label: strip_text(&inner),
            selected: is_selected(&attrs),
        })
        .collect();
    Some(options)
}

pub(crate) fn is_selected(attrs: &Attrs) -> bool {
    attrs.iter().any(|(name, _)| name == "selected")
}

pub(crate) fn attr_value(attrs: &Attrs, name: &str) -> Option<String> {
    attrs
        .iter()
        .find(|(attr, _)| attr == name)
        .and_then(|(_, value)| value.clone())
}

/// The tags `keep` accepts, each with its inner HTML up to the first matching close tag.
///
/// Only an accepted tag's inner HTML is read, so a query over one element costs one scan of the
/// document rather than one per tag.
pub(crate) fn tags_where(html: &str, keep: impl Fn(&str, &Attrs) -> bool) -> Vec<Element> {
    open_tags(html)
        .into_iter()
        .filter(|(tag, attrs, _)| keep(tag, attrs))
        .map(|(tag, attrs, open_end)| {
            let inner = inner_html(html, &tag, open_end);
            (tag, attrs, inner)
        })
        .collect()
}

fn inner_html(html: &str, tag: &str, open_end: usize) -> String {
    if is_void(tag) {
        return String::new();
    }
    // Same-name elements nest (a `div` in a `div`), so the close is the one that returns the
    // depth to zero.
    let after = &html[open_end + 1..];
    let open = format!("<{tag}");
    let close = format!("</{tag}>");
    let mut depth = 1usize;
    let mut pos = 0;
    while let Some(at) = after[pos..].find('<') {
        let at = pos + at;
        let rest = &after[at..];
        if rest.starts_with(close.as_str()) {
            depth -= 1;
            if depth == 0 {
                return after[..at].to_string();
            }
            pos = at + close.len();
        } else if rest.starts_with(open.as_str())
            && rest[open.len()..].starts_with([' ', '>', '/', '\t', '\n'])
        {
            depth += 1;
            pos = at + open.len();
        } else {
            pos = at + 1;
        }
    }
    String::new()
}

pub(crate) fn elements(html: &str, tag: &str) -> Vec<Element> {
    tags_where(html, |name, _| name == tag)
}

pub(crate) fn open_tags(html: &str) -> Vec<(String, Attrs, usize)> {
    let mut out = Vec::new();
    let mut pos = 0;
    while let Some(start) = html[pos..].find('<') {
        let abs_start = pos + start;
        let Some(end) = tag_end(html, abs_start) else {
            break;
        };
        let raw = &html[abs_start + 1..end];
        pos = end + 1;
        if raw.starts_with('!') || raw.starts_with('?') || raw.starts_with('/') {
            continue;
        }
        let (tag, attrs) = parse_tag(raw);
        if tag.is_empty() {
            continue;
        }
        out.push((tag, attrs, end));
    }
    out
}

fn parse_tag(raw: &str) -> (String, Attrs) {
    let mut attrs = Vec::new();
    let bytes = raw.as_bytes();
    let mut pos = 0;
    while pos < bytes.len() && !bytes[pos].is_ascii_whitespace() && bytes[pos] != b'/' {
        pos += 1;
    }
    let tag = raw[..pos].to_ascii_lowercase();
    while pos < bytes.len() {
        while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
            pos += 1;
        }
        if pos >= bytes.len() || bytes[pos] == b'/' {
            break;
        }
        let name_start = pos;
        while pos < bytes.len()
            && (bytes[pos].is_ascii_alphanumeric()
                || matches!(bytes[pos], b'-' | b'_' | b':' | b'.' | b'@'))
        {
            pos += 1;
        }
        if name_start == pos {
            pos += 1;
            while pos < bytes.len() && !raw.is_char_boundary(pos) {
                pos += 1;
            }
            continue;
        }
        let name = raw[name_start..pos].to_ascii_lowercase();
        while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
            pos += 1;
        }
        if pos >= bytes.len() || bytes[pos] != b'=' {
            attrs.push((name, None));
            continue;
        }
        pos += 1;
        while pos < bytes.len() && bytes[pos].is_ascii_whitespace() {
            pos += 1;
        }
        if pos >= bytes.len() {
            attrs.push((name, Some(String::new())));
            break;
        }
        let quote = bytes[pos];
        if quote == b'"' || quote == b'\'' {
            pos += 1;
            let value_start = pos;
            while pos < bytes.len() && bytes[pos] != quote {
                pos += 1;
            }
            attrs.push((
                name,
                Some(decode_entities(&raw[value_start..pos.min(bytes.len())])),
            ));
            pos = (pos + 1).min(bytes.len());
        } else {
            let value_start = pos;
            while pos < bytes.len() && !bytes[pos].is_ascii_whitespace() {
                pos += 1;
            }
            attrs.push((name, Some(decode_entities(&raw[value_start..pos]))));
        }
    }
    (tag, attrs)
}

fn tag_end(html: &str, start: usize) -> Option<usize> {
    let bytes = html.as_bytes();
    let mut quote = None;
    let mut pos = start + 1;
    while pos < bytes.len() {
        let byte = bytes[pos];
        if let Some(q) = quote {
            if byte == q {
                quote = None;
            }
        } else if byte == b'"' || byte == b'\'' {
            quote = Some(byte);
        } else if byte == b'>' {
            return Some(pos);
        }
        pos += 1;
    }
    None
}

fn is_void(tag: &str) -> bool {
    matches!(
        tag,
        "area"
            | "base"
            | "br"
            | "col"
            | "embed"
            | "hr"
            | "img"
            | "input"
            | "link"
            | "meta"
            | "param"
            | "source"
            | "track"
            | "wbr"
    )
}

pub(crate) fn strip_text(fragment: &str) -> String {
    let mut text = String::new();
    let mut pos = 0;
    while pos < fragment.len() {
        if let Some(start) = fragment[pos..].find('<') {
            text.push_str(&fragment[pos..pos + start]);
            let abs = pos + start;
            match tag_end(fragment, abs) {
                Some(end) => pos = end + 1,
                None => break,
            }
        } else {
            text.push_str(&fragment[pos..]);
            break;
        }
    }
    decode_entities(&text).trim().to_string()
}

fn decode_entities(text: &str) -> String {
    text.replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", "\"")
        .replace("&#x27;", "'")
        .replace("&#39;", "'")
        .replace("&amp;", "&")
}

mod rows;
#[cfg(test)]
mod tests;