Skip to main content

glacier/testing/
select.rs

1//! HTML assertions by CSS selector, as Rails' `assert_select` and
2//! Phoenix's `has_element?`: what a page shows, without matching its
3//! markup as text.
4//!
5//! ```glacier
6//! res = get "/books"
7//! assert_select(res, "ul.books li", count: 3)
8//! assert_select(res, "h1", text: "Books")
9//! assert_select(res, "form[action='/books'] input[name='title']")
10//! refute_select(res, ".alert")
11//! ```
12
13use scraper::{Html, Selector};
14
15/// Something holding HTML: a test response, or text.
16pub trait HtmlBody {
17    fn html(&self) -> &str;
18}
19
20impl HtmlBody for super::TestResponse {
21    fn html(&self) -> &str {
22        &self.body
23    }
24}
25
26impl HtmlBody for str {
27    fn html(&self) -> &str {
28        self
29    }
30}
31
32impl HtmlBody for String {
33    fn html(&self) -> &str {
34        self
35    }
36}
37
38impl<T: HtmlBody + ?Sized> HtmlBody for &T {
39    fn html(&self) -> &str {
40        (**self).html()
41    }
42}
43
44#[track_caller]
45fn selector(css: &str) -> Selector {
46    Selector::parse(css).unwrap_or_else(|e| panic!("`{css}` isn't a CSS selector: {e}"))
47}
48
49/// The text of each element `css` selects, whitespace squished.
50#[track_caller]
51pub fn select_text(body: impl HtmlBody, css: &str) -> Vec<String> {
52    let document = Html::parse_document(body.html());
53    document
54        .select(&selector(css))
55        .map(|element| {
56            element
57                .text()
58                .collect::<String>()
59                .split_whitespace()
60                .collect::<Vec<_>>()
61                .join(" ")
62        })
63        .collect()
64}
65
66/// A short look at the page, for a failure message.
67fn outline(body: &str) -> String {
68    let text = body.trim();
69    if text.chars().count() > 600 {
70        format!("{}…", text.chars().take(600).collect::<String>())
71    } else {
72        text.to_owned()
73    }
74}
75
76/// Asserts `css` selects at least one element.
77///
78/// # Panics
79///
80/// When it selects none.
81#[track_caller]
82pub fn assert_select(body: impl HtmlBody, css: &str) {
83    let found = select_text(&body, css);
84    assert!(
85        !found.is_empty(),
86        "expected the page to have `{css}`, but it has none:\n{}",
87        outline(body.html())
88    );
89}
90
91/// Asserts `css` selects exactly `count` elements.
92///
93/// # Panics
94///
95/// When it selects another number.
96#[track_caller]
97pub fn assert_select_count(body: impl HtmlBody, css: &str, count: usize) {
98    let found = select_text(&body, css);
99    assert!(
100        found.len() == count,
101        "expected {count} of `{css}`, found {}:\n{}",
102        found.len(),
103        outline(body.html())
104    );
105}
106
107/// Asserts some element `css` selects has `text` in its text.
108///
109/// # Panics
110///
111/// When none does.
112#[track_caller]
113pub fn assert_select_text(body: impl HtmlBody, css: &str, text: &str) {
114    let found = select_text(&body, css);
115    assert!(
116        found.iter().any(|t| t.contains(text)),
117        "expected `{css}` with the text {text:?}; found {}",
118        if found.is_empty() {
119            format!("no `{css}` at all:\n{}", outline(body.html()))
120        } else {
121            format!("{found:?}")
122        }
123    );
124}
125
126/// Asserts `css` selects nothing.
127///
128/// # Panics
129///
130/// When it selects something.
131#[track_caller]
132pub fn refute_select(body: impl HtmlBody, css: &str) {
133    let found = select_text(&body, css);
134    assert!(
135        found.is_empty(),
136        "expected no `{css}`, found {}: {found:?}",
137        found.len()
138    );
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    const PAGE: &str = r#"<html><body><h1>Books</h1><ul class="books"><li>Dune</li><li>Emma
146    </li></ul><form action="/books"><input name="title"></form></body></html>"#;
147
148    #[test]
149    fn selects_by_css() {
150        assert_select(PAGE, "h1");
151        assert_select_count(PAGE, "ul.books li", 2);
152        assert_select_text(PAGE, "li", "Emma");
153        assert_select(PAGE, "form[action='/books'] input[name='title']");
154        refute_select(PAGE, ".alert");
155        assert_eq!(select_text(PAGE, "li"), ["Dune", "Emma"]);
156        let missing = std::panic::catch_unwind(|| assert_select_count(PAGE, "li", 3));
157        let message = missing.unwrap_err();
158        assert!(
159            message
160                .downcast_ref::<String>()
161                .unwrap()
162                .starts_with("expected 3 of `li`, found 2")
163        );
164    }
165}