Lines
100 %
Functions
Branches
use super::*;
use crate::login::LoginTemplate;
use askama::Template;
use axum::{
body::Body,
http::{Request, StatusCode},
routing::get,
};
use std::fs;
use std::path::Path;
use tower::ServiceExt;
const SEPARATE: &str = "{{ crate::assets::BUILD_ID }}/";
fn static_urls(text: &str) -> Vec<&str> {
text.match_indices("/static/")
.map(|(start, _)| &text[start..])
.collect()
}
fn template_files(dir: &Path, found: &mut Vec<std::path::PathBuf>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
match path.is_dir() {
true => template_files(&path, found),
false => found.push(path),
#[test]
fn every_template_static_url_carries_the_build_id() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("templates");
let mut files = Vec::new();
template_files(&root, &mut files);
let mut urls = 0;
for file in files {
let text = fs::read_to_string(&file).unwrap();
for url in static_urls(&text) {
urls += 1;
assert!(
url["/static/".len()..].starts_with(SEPARATE),
"{} has an unversioned asset: {}",
file.display(),
url.lines().next().unwrap_or_default()
);
assert!(urls > 0);
fn a_rendered_page_references_only_versioned_assets() {
let html = LoginTemplate::default().render().unwrap();
let urls = static_urls(&html);
assert!(urls.len() >= 4, "{urls:?}");
let prefix = versioned_prefix();
for url in urls {
assert!(url.starts_with(&prefix), "{url}");
assert!(html.contains(&format!("{prefix}wasm/nomisync_frontend.js")));
fn app(dir: &Path) -> Router {
let router = Router::new()
.route("/page", get(|| async { "html" }))
.merge(static_files(dir.to_str().unwrap()));
with_cache_policy(router)
async fn get_status_and_cache(app: &Router, path: &str) -> (StatusCode, Option<String>) {
let response = app
.clone()
.oneshot(Request::get(path).body(Body::empty()).unwrap())
.await
.unwrap();
let cache = response
.headers()
.get(CACHE_CONTROL)
.map(|v| v.to_str().unwrap().to_owned());
(response.status(), cache)
#[tokio::test]
async fn versioned_assets_are_cached_forever_and_the_rest_revalidated() {
let dir = std::env::temp_dir().join(format!("nomi-assets-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join("a.css"), "a{}").unwrap();
let app = app(&dir);
let versioned = format!("/static/{BUILD_ID}/a.css");
let found = get_status_and_cache(&app, &versioned).await;
assert_eq!(found, (StatusCode::OK, Some(IMMUTABLE.to_owned())));
let bare = get_status_and_cache(&app, "/static/a.css").await;
assert_eq!(bare, (StatusCode::OK, Some(REVALIDATE.to_owned())));
let page = get_status_and_cache(&app, "/page").await;
assert_eq!(page, (StatusCode::OK, Some(REVALIDATE.to_owned())));
let missing = get_status_and_cache(&app, &format!("/static/{BUILD_ID}/none.css")).await;
assert_eq!(
missing,
(StatusCode::NOT_FOUND, Some(REVALIDATE.to_owned()))
fs::remove_dir_all(&dir).unwrap();