17.0 KiB · text History 263b40b
//! 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"));
    recourse::web::add_helpers(&mut env, true);
    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""##));
}

fn reader_ctx(a: &str, b: &str) -> minijinja::Value {
    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 },
        ],
    }
}

#[test]
fn focus_list_pages_render_with_and_without_reader() {
    let env = environment();
    let a = "0198f0aa-0000-7000-8000-00000000000a";
    let b = "0198f0aa-0000-7000-8000-00000000000b";
    let mut t = tile(a, "First");
    t = context! { notes => vec!["Bookmarked #2 · 1d"], ..t };
    for (page_id, base, search, rail) in [
        ("tag", "/tag/rust?view=focus", None, true),
        ("search", "/search?q=htmx&view=focus", Some("htmx"), false),
        ("bookmarks", "/bookmarks?view=focus", None, false),
        ("reactions", "/reactions?view=focus", None, false),
        ("notifications", "/notifications?view=focus", None, false),
    ] {
        for reader in [None, Some(reader_ctx(a, b))] {
            let mut ctx = context! {
                title => page_id, app_name => "recourse", page_id => page_id, heading => page_id,
                heading_icon => "fa-bell", crumbs => Vec::<minijinja::Value>::new(),
                toggle_base => base.replace("view=focus", "").trim_end_matches(['?', '&']).to_string(),
                base => base, empty => "Nothing", mark_all_read => page_id == "notifications",
                others => Vec::<minijinja::Value>::new(),
                topics => vec![t.clone(), tile(b, "Second")], reader => reader.clone(),
                up => context! { name => "All tags", href => "/tags" },
                rail => if rail { vec![context! { name => "rust", slug => "rust", href => "/tag/rust?view=focus", widget_bg => "", count => 2, current => true }] } else { vec![] },
                rail_label => "Other tags",
            };
            if let Some(q) = search {
                ctx = context! { search_q => q, ..ctx };
            }
            let html = env.get_template("forum/focus_list.html").unwrap().render(ctx)
                .unwrap_or_else(|e| panic!("{page_id}: {e:#}"));
            assert!(html.contains(&format!(r#"data-focus="{page_id}""#)), "{page_id}");
            assert!(html.contains(&format!(r#"id="tile-{a}""#)) && html.contains("Bookmarked #2"));
            assert!(html.contains(r#"aria-pressed="true" title="Focus layout""#));
            assert_eq!(html.contains(r#"id="focus-rail-rust" aria-current="true""#), rail, "{page_id}");
            assert_eq!(html.contains(r#"name="q" value="htmx""#), search.is_some());
            assert_eq!(html.contains(&format!(r#"data-reader="{b}""#)), reader.is_some(), "{page_id}");
            // (minijinja's HTML escaping writes `/` as `&#x2f;`.)
            let q = base.split('?').nth(1).unwrap().replace('&', "&amp;");
            assert!(html.contains(&format!("?{q}&amp;topic={a}")), "{page_id}");
        }
    }

    let html = env.get_template("tags_focus.html").unwrap().render(context! {
        title => "Tags", app_name => "recourse",
        tags => vec![context! { name => "rust", slug => "rust", href => "/tag/rust?view=focus", count => 1, topics => vec![tile(a, "First")] }],
    }).unwrap();
    assert!(html.contains(r#"id="tag-rust""#) && html.contains(&format!(r#"id="square-{a}""#)));
    assert!(html.contains(&format!("rust?view=focus&amp;topic={a}")));
}

#[test]
fn focus_topic_page_keeps_the_topic_controls() {
    let env = environment();
    let a = "0198f0aa-0000-7000-8000-00000000000a";
    let b = "0198f0aa-0000-7000-8000-00000000000b";
    let user = context! {
        id => a, username => "alice", email => "a@x.io", is_active => true, is_staff => false,
        trust_level => 3, email_verified_at => "2026-01-01", avatar_content_type => None::<String>,
    };
    let post = context! {
        id => a, post_number => 1, cooked => "<p>hi</p>", created_at => "1h", created_at_abs => "x",
        author => "alice", author_id => a, author_has_avatar => false, edited => false, deleted => false,
        deleted_by => None::<String>, can_edit => true, can_restore => false, bookmarked => false,
        reactions => Vec::<minijinja::Value>::new(), can_react => true, can_bookmark => true, can_flag => false,
        flagged => false, can_moderate => false, moderated => false, hidden => false, pending_flags => 0,
    };
    let caps = context! { signed_in => true, can_reply => true, can_react => true, locked => false };
    for strip in [true, false] {
        let html = env.get_template("forum/topic_focus.html").unwrap().render(context! {
            title => "Second", app_name => "recourse", user => user.clone(),
            category => context! { name => "Backend", slug => "backend" },
            topic => context! { id => b, title => "Second", is_closed => false, user_id => a },
            posts => vec![post.clone()], tags => vec![context! { name => "rust", slug => "rust" }],
            can_edit_tags => true, may_create_tags => true, min_trust => 3,
            participants => Vec::<minijinja::Value>::new(), topic_deleted => false,
            can_delete_topic => true, can_restore_topic => false, watching => false,
            up => context! { name => "Development", href => "/c/development?view=focus&sort=latest" },
            rail => vec![context! { name => "Backend", slug => "backend", href => "/c/backend?view=focus", widget_bg => "#000", count => 2, current => true }],
            rail_label => "Other categories",
            strip => if strip { reader_ctx(a, b).get_attr("strip").unwrap() } else { minijinja::Value::from(Vec::<i32>::new()) },
            position => if strip { context! { index => 2, count => 2, prev => a, next => None::<String> } } else { minijinja::Value::from(()) },
            ancestors => vec![context! { name => "Backend", href => "/c/backend?view=focus" }],
            close_href => "/c/backend?view=focus&sort=latest",
            caps => caps.clone(), flag_reasons => recourse::policy::FLAG_REASONS,
        }).unwrap();
        assert!(html.contains(&format!(r#"data-reader="{b}""#)));
        assert!(html.contains(r#"id="reply""#), "reply form");
        assert!(html.contains(&format!(r#"action="/t/{b}/delete""#)), "topic delete");
        assert!(html.contains(r#"/p/0198f0aa-0000-7000-8000-00000000000a/edit"#), "post edit");
        assert!(html.contains(r#"hx-post="/c/backend/watch""#), "watch");
        assert!(html.contains(r#"id="reader-close""#));
        assert_eq!(html.contains(r#"id="reader-prev""#), strip);
        assert!(html.contains(r#"aria-pressed="true" title="Focus layout""#));
    }
}

#[test]
fn moderation_states_render_in_the_topic_page() {
    let env = environment();
    let a = "0198f0aa-0000-7000-8000-00000000000a";
    let user = context! {
        id => a, username => "bob", email => "b@x.io", is_active => true, is_staff => false,
        trust_level => 2, email_verified_at => "2026-01-01", avatar_content_type => None::<String>,
    };
    let post = |n: i32, moderated: bool, hidden: bool| context! {
        id => format!("0198f0aa-0000-7000-8000-00000000000{n}"), post_number => n,
        cooked => if hidden { "" } else { "<p>note</p>" }, created_at => "1h", created_at_abs => "x",
        author => "alice", author_id => "0198f0aa-0000-7000-8000-0000000000ff", author_has_avatar => false,
        edited => moderated, deleted => false, deleted_by => None::<String>, can_edit => false, can_restore => false,
        bookmarked => false, reactions => Vec::<minijinja::Value>::new(), can_react => false, can_bookmark => true,
        can_flag => !moderated && !hidden, flagged => false, can_moderate => false, moderated => moderated,
        moderated_by => "mod", hidden => hidden, show_hidden => false, pending_flags => 0,
    };
    let html = env.get_template("forum/topic.html").unwrap().render(context! {
        title => "T", app_name => "recourse", user => user,
        category => context! { name => "Backend", slug => "backend" },
        topic => context! { id => a, title => "T", is_closed => true, user_id => a },
        posts => vec![post(1, true, false), post(2, false, true), post(3, false, false)],
        tags => Vec::<minijinja::Value>::new(), participants => Vec::<minijinja::Value>::new(),
        topic_deleted => false, can_delete_topic => false, can_restore_topic => false,
        caps => context! {
            signed_in => true, can_reply => false, can_react => false, locked => true, can_flag => true,
            lock_message => "Locked by staff: cooling off",
            reply_block => context! { code => "locked", message => "Locked by staff: cooling off" },
        },
        flag_reasons => recourse::policy::FLAG_REASONS,
    }).unwrap();
    assert!(html.contains("Locked by staff: cooling off"));
    assert!(!html.contains(r#"id="reply""#), "no reply form on a locked topic");
    assert!(html.contains("data-moderated") && html.contains("staff"), "the staff note");
    assert!(html.contains("Hidden pending staff review."));
    assert!(html.contains("/p/0198f0aa-0000-7000-8000-000000000003/flag"), "flag on an ordinary post");
    assert!(!html.contains("/p/0198f0aa-0000-7000-8000-000000000001/flag"));
    assert!(!html.contains("/react/"), "no reactions in a locked topic");
}

/// The shader script takes its default from the page (the server's
/// `handlers::shaders` constants), not from a constant of its own, so the
/// two can't drift: its only fallback is "off".
#[test]
fn the_shader_script_reads_the_default_from_the_page() {
    let js = std::fs::read_to_string("assets/f/js/shader_background.js").unwrap();
    assert!(js.contains("dataset.shaderDefault"), "reads <body data-shader-default>");
    assert!(js.contains(r#"pattern: "off", ...siteDefault(), ...saved"#), "page default over off, saved choice over both");
    for p in recourse::handlers::shaders::Shader::ALL {
        assert!(!js.contains(&format!(r#"pattern: "{}""#, p.value())), "a hard-coded {} default", p.value());
    }
    // Every pattern is one the field script draws: its own program, or a
    // layer of the moire field.
    let field = std::fs::read_to_string("assets/f/js/shader_field.js").unwrap();
    for p in recourse::handlers::shaders::Shader::ALL {
        let v = p.value();
        assert!(field.contains(&format!("\"{v}\"")) || field.contains(&format!("{v}: {}", v.to_uppercase())), "{v} unknown to shader_field.js");
    }
}

/// The body carries `hx-select="#content"` for boosted navigation, and htmx
/// inherits it: a request that swaps a fragment (the post's link block)
/// must say `hx-select="unset"`, or the fragment selects nothing and the
/// block empties.
#[test]
fn link_block_requests_do_not_inherit_the_page_select() {
    for name in ["templates/forum/_post_links.html", "templates/forum/_post.html"] {
        let src = std::fs::read_to_string(name).unwrap();
        let tags: Vec<&str> = src.split('<').filter(|t| t.contains("#links-") || t.contains("/links?open=1")).collect();
        assert!(!tags.is_empty(), "{name}");
        for tag in tags {
            if tag.contains("hx-get") || tag.contains("hx-post") {
                assert!(tag.contains(r#"hx-select="unset""#), "{name}: <{}", tag.lines().next().unwrap());
            }
        }
    }
}