use scraper::{Html, Selector};
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}"))
}
#[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()
}
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()
}
}
#[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())
);
}
#[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())
);
}
#[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:?}")
}
);
}
#[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")
);
}
}