glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! HTML assertions by CSS selector, as Rails' `assert_select` and
//! Phoenix's `has_element?`: what a page shows, without matching its
//! markup as text.
//!
//! ```glacier
//! res = get "/books"
//! assert_select(res, "ul.books li", count: 3)
//! assert_select(res, "h1", text: "Books")
//! assert_select(res, "form[action='/books'] input[name='title']")
//! refute_select(res, ".alert")
//! ```

use scraper::{Html, Selector};

/// Something holding HTML: a test response, or text.
pub trait HtmlBody {
    fn html(&self) -> &str;
}

impl HtmlBody for super::TestResponse {
    fn html(&self) -> &str {
        &self.body
    }
}

impl HtmlBody for str {
    fn html(&self) -> &str {
        self
    }
}

impl HtmlBody for String {
    fn html(&self) -> &str {
        self
    }
}

impl<T: HtmlBody + ?Sized> HtmlBody for &T {
    fn html(&self) -> &str {
        (**self).html()
    }
}

#[track_caller]
fn selector(css: &str) -> Selector {
    Selector::parse(css).unwrap_or_else(|e| panic!("`{css}` isn't a CSS selector: {e}"))
}

/// The text of each element `css` selects, whitespace squished.
#[track_caller]
pub fn select_text(body: impl HtmlBody, css: &str) -> Vec<String> {
    let document = Html::parse_document(body.html());
    document
        .select(&selector(css))
        .map(|element| {
            element
                .text()
                .collect::<String>()
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" ")
        })
        .collect()
}

/// A short look at the page, for a failure message.
fn outline(body: &str) -> String {
    let text = body.trim();
    if text.chars().count() > 600 {
        format!("{}…", text.chars().take(600).collect::<String>())
    } else {
        text.to_owned()
    }
}

/// Asserts `css` selects at least one element.
///
/// # Panics
///
/// When it selects none.
#[track_caller]
pub fn assert_select(body: impl HtmlBody, css: &str) {
    let found = select_text(&body, css);
    assert!(
        !found.is_empty(),
        "expected the page to have `{css}`, but it has none:\n{}",
        outline(body.html())
    );
}

/// Asserts `css` selects exactly `count` elements.
///
/// # Panics
///
/// When it selects another number.
#[track_caller]
pub fn assert_select_count(body: impl HtmlBody, css: &str, count: usize) {
    let found = select_text(&body, css);
    assert!(
        found.len() == count,
        "expected {count} of `{css}`, found {}:\n{}",
        found.len(),
        outline(body.html())
    );
}

/// Asserts some element `css` selects has `text` in its text.
///
/// # Panics
///
/// When none does.
#[track_caller]
pub fn assert_select_text(body: impl HtmlBody, css: &str, text: &str) {
    let found = select_text(&body, css);
    assert!(
        found.iter().any(|t| t.contains(text)),
        "expected `{css}` with the text {text:?}; found {}",
        if found.is_empty() {
            format!("no `{css}` at all:\n{}", outline(body.html()))
        } else {
            format!("{found:?}")
        }
    );
}

/// Asserts `css` selects nothing.
///
/// # Panics
///
/// When it selects something.
#[track_caller]
pub fn refute_select(body: impl HtmlBody, css: &str) {
    let found = select_text(&body, css);
    assert!(
        found.is_empty(),
        "expected no `{css}`, found {}: {found:?}",
        found.len()
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    const PAGE: &str = r#"<html><body><h1>Books</h1><ul class="books"><li>Dune</li><li>Emma
    </li></ul><form action="/books"><input name="title"></form></body></html>"#;

    #[test]
    fn selects_by_css() {
        assert_select(PAGE, "h1");
        assert_select_count(PAGE, "ul.books li", 2);
        assert_select_text(PAGE, "li", "Emma");
        assert_select(PAGE, "form[action='/books'] input[name='title']");
        refute_select(PAGE, ".alert");
        assert_eq!(select_text(PAGE, "li"), ["Dune", "Emma"]);
        let missing = std::panic::catch_unwind(|| assert_select_count(PAGE, "li", 3));
        let message = missing.unwrap_err();
        assert!(
            message
                .downcast_ref::<String>()
                .unwrap()
                .starts_with("expected 3 of `li`, found 2")
        );
    }
}