1
use super::*;
2
use crate::login::LoginTemplate;
3
use askama::Template;
4
use axum::{
5
    body::Body,
6
    http::{Request, StatusCode},
7
    routing::get,
8
};
9
use std::fs;
10
use std::path::Path;
11
use tower::ServiceExt;
12

            
13
const SEPARATE: &str = "{{ crate::assets::BUILD_ID }}/";
14

            
15
166
fn static_urls(text: &str) -> Vec<&str> {
16
166
    text.match_indices("/static/")
17
150
        .map(|(start, _)| &text[start..])
18
        .collect()
19
166
}
20

            
21
42
fn template_files(dir: &Path, found: &mut Vec<std::path::PathBuf>) {
22
42
    for entry in fs::read_dir(dir).unwrap() {
23
204
        let path = entry.unwrap().path();
24
204
        match path.is_dir() {
25
40
            true => template_files(&path, found),
26
164
            false => found.push(path),
27
        }
28
    }
29
42
}
30

            
31
#[test]
32
2
fn every_template_static_url_carries_the_build_id() {
33
2
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("templates");
34
2
    let mut files = Vec::new();
35
2
    template_files(&root, &mut files);
36
2
    let mut urls = 0;
37
2
    for file in files {
38
164
        let text = fs::read_to_string(&file).unwrap();
39
164
        for url in static_urls(&text) {
40
136
            urls += 1;
41
136
            assert!(
42
136
                url["/static/".len()..].starts_with(SEPARATE),
43
                "{} has an unversioned asset: {}",
44
                file.display(),
45
                url.lines().next().unwrap_or_default()
46
            );
47
        }
48
    }
49
2
    assert!(urls > 0);
50
2
}
51

            
52
#[test]
53
2
fn a_rendered_page_references_only_versioned_assets() {
54
2
    let html = LoginTemplate::default().render().unwrap();
55
2
    let urls = static_urls(&html);
56
2
    assert!(urls.len() >= 4, "{urls:?}");
57
2
    let prefix = versioned_prefix();
58
2
    for url in urls {
59
14
        assert!(url.starts_with(&prefix), "{url}");
60
    }
61
2
    assert!(html.contains(&format!("{prefix}wasm/nomisync_frontend.js")));
62
2
}
63

            
64
2
fn app(dir: &Path) -> Router {
65
2
    let router = Router::new()
66
4
        .route("/page", get(|| async { "html" }))
67
2
        .merge(static_files(dir.to_str().unwrap()));
68
2
    with_cache_policy(router)
69
2
}
70

            
71
8
async fn get_status_and_cache(app: &Router, path: &str) -> (StatusCode, Option<String>) {
72
8
    let response = app
73
8
        .clone()
74
8
        .oneshot(Request::get(path).body(Body::empty()).unwrap())
75
8
        .await
76
        .unwrap();
77
8
    let cache = response
78
8
        .headers()
79
8
        .get(CACHE_CONTROL)
80
8
        .map(|v| v.to_str().unwrap().to_owned());
81
8
    (response.status(), cache)
82
8
}
83

            
84
#[tokio::test]
85
2
async fn versioned_assets_are_cached_forever_and_the_rest_revalidated() {
86
2
    let dir = std::env::temp_dir().join(format!("nomi-assets-{}", std::process::id()));
87
2
    fs::create_dir_all(&dir).unwrap();
88
2
    fs::write(dir.join("a.css"), "a{}").unwrap();
89
2
    let app = app(&dir);
90
2
    let versioned = format!("/static/{BUILD_ID}/a.css");
91

            
92
2
    let found = get_status_and_cache(&app, &versioned).await;
93
2
    assert_eq!(found, (StatusCode::OK, Some(IMMUTABLE.to_owned())));
94
2
    let bare = get_status_and_cache(&app, "/static/a.css").await;
95
2
    assert_eq!(bare, (StatusCode::OK, Some(REVALIDATE.to_owned())));
96
2
    let page = get_status_and_cache(&app, "/page").await;
97
2
    assert_eq!(page, (StatusCode::OK, Some(REVALIDATE.to_owned())));
98
2
    let missing = get_status_and_cache(&app, &format!("/static/{BUILD_ID}/none.css")).await;
99
2
    assert_eq!(
100
2
        missing,
101
2
        (StatusCode::NOT_FOUND, Some(REVALIDATE.to_owned()))
102
    );
103
2
    fs::remove_dir_all(&dir).unwrap();
104
2
}