5.8 KiB · text History da3a685
//! Smoke test: every template under `templates/` parses, and the shared page
//! shell renders with a plausible context. Templates are data, not code, so a
//! typo in one is invisible to `cargo check` — this is what catches it.
use minijinja::{context, Environment};
use std::path::Path;

/// Mirror the environment the webservice builds in `src/main.rs`.
fn environment() -> Environment<'static> {
    let mut env = Environment::new();
    env.set_loader(minijinja::path_loader("templates"));
    env.add_function("avatar_color", |name: String| {
        recourse::avatar::avatar_color(&name).to_string()
    });
    env.add_global("require_email_verification", true);
    env.add_function("tier_name", |level: i32| recourse::trust::tier_name(level).to_string());
    env
}

fn collect(dir: &Path, root: &Path, out: &mut Vec<String>) {
    for entry in std::fs::read_dir(dir).unwrap() {
        let path = entry.unwrap().path();
        if path.is_dir() {
            collect(&path, root, out);
        } else if path.extension().is_some_and(|e| e == "html") {
            let rel = path.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
            out.push(rel);
        }
    }
}

#[test]
fn every_template_parses() {
    let env = environment();
    let root = Path::new("templates");
    let mut names = Vec::new();
    collect(root, root, &mut names);
    assert!(!names.is_empty());
    for name in names {
        env.get_template(&name)
            .unwrap_or_else(|e| panic!("template {name} failed to load: {e:#}"));
    }
}

#[test]
fn shell_renders_for_anonymous_and_signed_in() {
    let env = environment();
    let user = context! {
        id => "0198f0aa-0000-7000-8000-000000000000",
        username => "alice",
        email => "alice@example.com",
        is_active => true,
        is_staff => true,
        trust_level => 2,
        avatar_content_type => None::<String>,
    };
    for ctx in [
        context! { title => "OK", app_name => "recourse" },
        context! { title => "OK", app_name => "recourse", user => user },
    ] {
        let html = env.get_template("ok.html").unwrap().render(ctx).unwrap();
        assert!(html.contains("recourse"));
    }
}

fn tile(id: &str, title: &str) -> minijinja::Value {
    context! {
        id => id, title => title, is_pinned => false, is_closed => false,
        posts_count => 3, replies => 2, views => 9, bumped_at => "2h", bumped_at_abs => "2026-12-01 10:00",
        author => "alice", author_id => id, author_has_avatar => false,
        cat_widget_bg => "#0088CC", cat_name => "General", cat_slug => "general",
        tags => vec![context! { name => "rust", slug => "rust" }],
        posters => vec![context! { id => id, name => "alice", has_avatar => false }],
        reactions => vec![context! { emoji => "❤️", count => 2 }],
        is_new => true, unread => 0,
    }
}

#[test]
fn visual_mode_renders_rail_tiles_columns_and_reader() {
    let env = environment();
    let a = "0198f0aa-0000-7000-8000-00000000000a";
    let b = "0198f0aa-0000-7000-8000-00000000000b";
    let base = "/c/development?view=focus&sort=latest";
    let reader = context! {
        topic => context! { id => b, title => "Second", is_pinned => false, is_closed => false },
        author => "alice", cat_name => "Development", cat_slug => "development",
        posts => Vec::<minijinja::Value>::new(), index => 2, count => 2, prev => a, next => None::<String>,
        strip => vec![
            context! { id => a, title => "First", widget_bg => "#000", current => false, unread => true },
            context! { id => b, title => "Second", widget_bg => "#000", current => true, unread => false },
        ],
    };
    let page = |reader: Option<minijinja::Value>| {
        env.get_template("forum/focus.html").unwrap().render(context! {
            title => "Development", app_name => "recourse",
            category => context! { name => "Development", slug => "development", description => "Code" },
            category_widget_bg => "#25AAE2", slug => "development", watching => false, can_write => false,
            ancestors => Vec::<minijinja::Value>::new(),
            up => context! { name => "All categories", href => "/?view=focus" },
            rail => vec![
                context! { name => "Development", slug => "development", href => base, widget_bg => "#25AAE2", count => 4, current => true },
                context! { name => "General", slug => "general", href => "/c/general?view=focus&sort=latest", widget_bg => "#0088CC", count => 1, current => false },
            ],
            topics => vec![tile(a, "First")],
            columns => vec![context! {
                name => "Backend", slug => "backend", href => "/c/backend?view=focus&sort=latest",
                widget_bg => "#3AB54A", count => 1, topics => vec![tile(b, "Second")], more => 0,
            }],
            reader => reader, base => base, current_sort => "latest",
        }).unwrap()
    };
    let html = page(None);
    assert!(html.contains(r#"id="focus-rail-development" aria-current="true""#));
    assert!(html.contains(r#"aria-label="Focus on General""#));
    assert!(html.contains(r#"aria-label="Focus on Backend""#));
    assert!(html.contains(&format!(r#"id="tile-{a}""#)));
    assert!(html.contains(&format!(r#"id="square-{b}""#)));
    assert!(html.contains(r#"<div id="reader">"#) && !html.contains("data-reader"));
    let html = page(Some(reader.clone()));
    assert!(html.contains(&format!(r#"data-reader="{b}""#)));
    assert!(html.contains(r#"id="reader-prev""#) && !html.contains(r#"id="reader-next""#));
    assert!(html.contains("2 / 2"));

    // The fragment the reader's links swap in.
    let frag = env.get_template("forum/_reader.html").unwrap()
        .render(context! { reader => reader, base => base }).unwrap();
    assert!(frag.trim_start().starts_with(r#"<div id="reader">"#));
    assert!(frag.contains(r##"hx-target="#reader""##));
}