A - ciò che rende viva una pagina vera: - <script src="...">: sequenza ordinata di script inline ed esterni, caricati dalla rete o dal disco secondo il contesto del documento - querySelector/querySelectorAll su documento ed elemento: tag, #id, .classe, [attributo] e discendenza - attributi onclick (e ogni on<evento>) eseguiti con new Function, con 'this' legato all'elemento - innerHTML in scrittura ora analizza l'HTML, invece di mostrare i tag B - completamenti: - navigazione: parentNode, children, firstChild, nextSibling, remove, insertBefore - stopPropagation: ferma davvero la risalita agli antenati - element.value anche in scrittura, riportato allo stato dei moduli dal guscio - console.log raccolto e stampato con MOSAIC_JS_LOG=1 - style.prop = '' toglie la dichiarazione, come in HTML Corretti: nome con accento sbagliato tra preludio e Rust (remove non funzionava); albero dei selettori costruito solo per gli elementi, quindi la radice non aveva figli e ogni query restituiva vuoto; flag di ridisegno azzerato subito dopo il render, che annullava i valori impostati dagli script al caricamento.
223 lines
7.6 KiB
Rust
223 lines
7.6 KiB
Rust
//! Sotto-risorse dalla rete (M2.6), provate sul serio: un server locale serve la
|
|
//! pagina, il foglio di stile e l'immagine separatamente, e il test guarda i
|
|
//! pixel che ne risultano. Niente internet: la CI resta deterministica.
|
|
|
|
use std::io::{Read, Write};
|
|
use std::net::TcpListener;
|
|
use std::path::PathBuf;
|
|
use std::thread;
|
|
|
|
use engine::{render_with_form, FormState, RenderOptions};
|
|
|
|
const PAGINA: &str = concat!(
|
|
"<!doctype html><html><head><meta charset=\"utf-8\">",
|
|
"<link rel=\"stylesheet\" href=\"stile.css\">",
|
|
"</head><body><h1>Titolo</h1><p>testo</p>",
|
|
"<img src=\"img/quadrato.png\" width=\"40\" height=\"40\">",
|
|
"</body></html>"
|
|
);
|
|
|
|
const STILE: &str = "body{margin:0;padding:4px}h1{color:#cc0000;font-size:24px;margin:0}\
|
|
p{margin:0;font-size:12px}";
|
|
|
|
fn font() -> PathBuf {
|
|
let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
|
p.push("cases/mono.ttf");
|
|
p
|
|
}
|
|
|
|
fn immagine() -> Vec<u8> {
|
|
let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
|
p.push("cases/quadrato-blu.png");
|
|
std::fs::read(p).expect("quadrato di prova")
|
|
}
|
|
|
|
/// Server usa-e-getta: risponde con l'elenco dato e chiude. `404` per il resto.
|
|
fn server(risposte: Vec<(String, String, Vec<u8>)>) -> u16 {
|
|
let ascolto = TcpListener::bind("127.0.0.1:0").expect("porta libera");
|
|
let porta = ascolto.local_addr().unwrap().port();
|
|
thread::spawn(move || {
|
|
for flusso in ascolto.incoming().flatten() {
|
|
let mut flusso = flusso;
|
|
let mut buf = [0u8; 4096];
|
|
let n = flusso.read(&mut buf).unwrap_or(0);
|
|
let richiesta = String::from_utf8_lossy(&buf[..n]).to_string();
|
|
let percorso = richiesta
|
|
.split_whitespace()
|
|
.nth(1)
|
|
.unwrap_or("/")
|
|
.to_string();
|
|
let trovato = risposte.iter().find(|(p, _, _)| *p == percorso);
|
|
let (codice, tipo, corpo) = match trovato {
|
|
Some((_, tipo, corpo)) => ("200 OK", tipo.clone(), corpo.clone()),
|
|
None => (
|
|
"404 Not Found",
|
|
"text/plain".to_string(),
|
|
b"non c'e'".to_vec(),
|
|
),
|
|
};
|
|
let testa = format!(
|
|
"HTTP/1.1 {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
|
|
codice,
|
|
tipo,
|
|
corpo.len()
|
|
);
|
|
let _ = flusso.write_all(testa.as_bytes());
|
|
let _ = flusso.write_all(&corpo);
|
|
}
|
|
});
|
|
porta
|
|
}
|
|
|
|
fn opzioni(porta: u16) -> RenderOptions {
|
|
RenderOptions {
|
|
viewport: (300, 200),
|
|
dpi_scale: 1.0,
|
|
font_path: font(),
|
|
auto_height: true,
|
|
base_dir: PathBuf::from("."),
|
|
base_url: Some(format!("http://127.0.0.1:{}/pagina.html", porta)),
|
|
}
|
|
}
|
|
|
|
fn conta(res: &engine::RenderResult, rgb: [u8; 3]) -> usize {
|
|
res.rgba
|
|
.chunks_exact(4)
|
|
.filter(|p| p[0] == rgb[0] && p[1] == rgb[1] && p[2] == rgb[2])
|
|
.count()
|
|
}
|
|
|
|
#[test]
|
|
fn stile_esterno_e_immagine_arrivano_dalla_rete() {
|
|
let porta = server(vec![
|
|
(
|
|
"/pagina.html".to_string(),
|
|
"text/html".to_string(),
|
|
PAGINA.as_bytes().to_vec(),
|
|
),
|
|
(
|
|
"/stile.css".to_string(),
|
|
"text/css".to_string(),
|
|
STILE.as_bytes().to_vec(),
|
|
),
|
|
(
|
|
"/img/quadrato.png".to_string(),
|
|
"image/png".to_string(),
|
|
immagine(),
|
|
),
|
|
]);
|
|
let res = render_with_form(PAGINA, "", &opzioni(porta), &FormState::default()).expect("render");
|
|
|
|
assert!(
|
|
res.resource_errors.is_empty(),
|
|
"sotto-risorse fallite: {:?}",
|
|
res.resource_errors
|
|
);
|
|
// il colore del titolo viene dal foglio esterno
|
|
assert!(
|
|
conta(&res, [0xcc, 0x00, 0x00]) > 50,
|
|
"il foglio esterno non è stato applicato"
|
|
);
|
|
// l'immagine: 40x40 px tutti blu
|
|
assert!(
|
|
conta(&res, [0x00, 0x00, 0xff]) >= 40 * 40,
|
|
"l'immagine non è stata scaricata e disegnata"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn risorsa_mancante_e_un_errore_riportato_non_un_render_rotto() {
|
|
let html = "<html><head><link rel=\"stylesheet\" href=\"manca.css\"></head>\
|
|
<body><p>testo comunque impaginato</p></body></html>";
|
|
let porta = server(vec![(
|
|
"/pagina.html".to_string(),
|
|
"text/html".to_string(),
|
|
html.as_bytes().to_vec(),
|
|
)]);
|
|
let res = render_with_form(html, "", &opzioni(porta), &FormState::default())
|
|
.expect("il render non deve fallire per una sotto-risorsa mancante");
|
|
assert_eq!(res.resource_errors.len(), 1, "{:?}", res.resource_errors);
|
|
assert!(
|
|
res.resource_errors[0].contains("404"),
|
|
"{:?}",
|
|
res.resource_errors
|
|
);
|
|
assert!(res.layout.rect.h > 0.0, "la pagina è comunque impaginata");
|
|
}
|
|
|
|
#[test]
|
|
fn documenti_locali_non_escono_in_rete() {
|
|
// senza base_url nessuna richiesta: la pagina resta quella di sempre
|
|
let opts = RenderOptions {
|
|
viewport: (200, 120),
|
|
dpi_scale: 1.0,
|
|
font_path: font(),
|
|
auto_height: true,
|
|
base_dir: PathBuf::from("."),
|
|
base_url: None,
|
|
};
|
|
let html = "<html><head><link rel=\"stylesheet\" href=\"http://127.0.0.1:1/x.css\">\
|
|
</head><body><p>solo locale</p></body></html>";
|
|
let res = render_with_form(html, "", &opts, &FormState::default()).expect("render");
|
|
assert!(res.resource_errors.is_empty(), "{:?}", res.resource_errors);
|
|
}
|
|
|
|
#[test]
|
|
fn script_esterno_viene_scaricato_ed_eseguito() {
|
|
let html = "<html><body><div id=\"esito\">fermo</div>\
|
|
<script src=\"app.js\"></script></body></html>";
|
|
let js = "document.getElementById('esito').textContent = 'script esterno eseguito';";
|
|
let porta = server(vec![
|
|
(
|
|
"/pagina.html".to_string(),
|
|
"text/html".to_string(),
|
|
html.as_bytes().to_vec(),
|
|
),
|
|
(
|
|
"/app.js".to_string(),
|
|
"text/javascript".to_string(),
|
|
js.as_bytes().to_vec(),
|
|
),
|
|
]);
|
|
let base = format!("http://127.0.0.1:{}/pagina.html", porta);
|
|
let mut contenuto = engine::ContenutoPagina::da_html(html);
|
|
let mut macchina = engine::script::Macchina::nuova().expect("interprete");
|
|
let caricatore = |src: &str| -> Option<String> {
|
|
let url = engine::resource::risolvi_url(Some(&base), src)?;
|
|
let r = engine::net::get(&url, &engine::net::Limiti::default()).ok()?;
|
|
r.text().ok()
|
|
};
|
|
let errori = contenuto.esegui_script_con(&mut macchina, &caricatore);
|
|
assert!(errori.is_empty(), "errori: {:?}", errori);
|
|
|
|
// il codice dello script esterno ha davvero modificato il documento
|
|
let esito = contenuto
|
|
.doc
|
|
.nodes
|
|
.iter()
|
|
.enumerate()
|
|
.find(|(_, n)| match &n.kind {
|
|
engine::dom::NodeKind::Element(e) => e.attr("id") == Some("esito"),
|
|
_ => false,
|
|
})
|
|
.map(|(i, _)| i)
|
|
.expect("nodo esito");
|
|
assert_eq!(contenuto.doc.text_content(esito), "script esterno eseguito");
|
|
}
|
|
|
|
#[test]
|
|
fn risoluzione_dei_riferimenti() {
|
|
use engine::resource::risolvi_url;
|
|
assert_eq!(
|
|
risolvi_url(Some("https://a.test/d/p.html"), "../i/a.png").as_deref(),
|
|
Some("https://a.test/i/a.png")
|
|
);
|
|
assert_eq!(
|
|
risolvi_url(Some("https://a.test/d/p.html"), "s.css").as_deref(),
|
|
Some("https://a.test/d/s.css")
|
|
);
|
|
assert_eq!(risolvi_url(None, "s.css"), None);
|
|
// il client HTTP accetta solo http/https: gli altri schemi non si risolvono
|
|
assert_eq!(risolvi_url(Some("ftp://a.test/"), "s.css"), None);
|
|
}
|