Promise vere e await: la coda dei microtask viene svuotata
Il difetto: Boa le Promise le ha, ma nessuno chiamava run_jobs(), quindi ogni .then restava in coda per sempre e la pagina non si aggiornava — senza un solo errore da leggere. - fetch restituisce una Promise costruita dal motore (new Promise + resolve/reject tenuti nella richiesta), non più un oggetto con un then finto - text() e json() restituiscono Promise anche loro, come nel browser: senza, "await r.text()" riceveva la stringa e chi si aspettava una Promise si rompeva - run_jobs() dopo ogni ingresso di JavaScript: script, eventi, timer, consegna delle risposte di fetch - il guscio desktop serve le fetch anche nel percorso senza finestra: con --aspetta l'attesa non serviva a niente e la pagina restava sulla scritta iniziale - 7 test nuovi (tests/promise.rs): then, await, fetch+text, fetch+json, catch, Promise.all, Promise accesa dentro un gestore di clic - aggiornato il test che si aspettava r.text() sincrona: codificava la vecchia semplificazione, non il comportamento giusto Verifica end-to-end su HTTP vero: una pagina con await fetch e await r.json() mostra "ricevuto: Mosaic (200)". Wikipedia, che usa async/await ovunque, si carica senza panic.
This commit is contained in:
1 parent
71f45d8967
commit
6a14853d0d
6 files changed
+241
-18
No files matched your search
@@ -0,0 +1,192 @@
|
||||
//! Promise vere, `await` e `fetch` (M2.5, residuo chiuso).
|
||||
//!
|
||||
//! Il difetto che questi test difendono: le Promise di Boa esistevano già, ma
|
||||
//! nessuno svuotava la coda dei microtask, quindi ogni `.then` restava in coda
|
||||
//! per sempre e la pagina non si aggiornava — senza nessun errore da leggere.
|
||||
|
||||
use engine::dom::NodeKind;
|
||||
use engine::script::Macchina;
|
||||
use engine::ContenutoPagina;
|
||||
|
||||
/// Testo visibile dentro l'elemento con quell'id.
|
||||
fn testo_di(contenuto: &ContenutoPagina, id: &str) -> String {
|
||||
let mut nodo = None;
|
||||
for (i, n) in contenuto.doc.nodes.iter().enumerate() {
|
||||
if let NodeKind::Element(e) = &n.kind {
|
||||
if e.attr("id") == Some(id) {
|
||||
nodo = Some(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(nodo) = nodo else {
|
||||
return String::new();
|
||||
};
|
||||
let mut out = String::new();
|
||||
for figlio in &contenuto.doc.node(nodo).children {
|
||||
if let NodeKind::Text(t) = &contenuto.doc.node(*figlio).kind {
|
||||
out.push_str(t);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn esegui(html: &str) -> (ContenutoPagina, Macchina) {
|
||||
let mut contenuto = ContenutoPagina::da_html(html);
|
||||
let mut macchina = Macchina::nuova().expect("interprete");
|
||||
let errori = contenuto.esegui_script(&mut macchina);
|
||||
assert!(errori.is_empty(), "errori negli script: {:?}", errori);
|
||||
(contenuto, macchina)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn then_di_una_promise_modifica_la_pagina() {
|
||||
let (contenuto, _) = esegui(
|
||||
"<html><body><div id=\"a\">prima</div><script>\
|
||||
Promise.resolve('dopo').then(function (v) {\
|
||||
document.getElementById('a').textContent = v; });\
|
||||
</script></body></html>",
|
||||
);
|
||||
assert_eq!(
|
||||
testo_di(&contenuto, "a"),
|
||||
"dopo",
|
||||
"il .then non è mai girato: la coda dei microtask non viene svuotata"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn await_in_una_funzione_async() {
|
||||
let (contenuto, _) = esegui(
|
||||
"<html><body><div id=\"a\">prima</div><script>\
|
||||
async function vai() {\
|
||||
var uno = await Promise.resolve('uno');\
|
||||
var due = await Promise.resolve('due');\
|
||||
document.getElementById('a').textContent = uno + '-' + due;\
|
||||
}\
|
||||
vai();\
|
||||
</script></body></html>",
|
||||
);
|
||||
assert_eq!(
|
||||
testo_di(&contenuto, "a"),
|
||||
"uno-due",
|
||||
"await non prosegue: mancano i microtask o le Promise non sono vere"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_e_una_promise_e_await_ne_legge_il_corpo() {
|
||||
let html = "<html><body><div id=\"a\">vuoto</div><script>\
|
||||
async function vai() {\
|
||||
var r = await fetch('/dati');\
|
||||
var testo = await r.text();\
|
||||
document.getElementById('a').textContent = r.status + ':' + testo;\
|
||||
}\
|
||||
vai();\
|
||||
</script></body></html>";
|
||||
|
||||
let (mut contenuto, mut macchina) = esegui(html);
|
||||
|
||||
// la richiesta è in coda: la esegue il guscio, non il motore
|
||||
let richieste = macchina.richieste_pendenti();
|
||||
assert_eq!(richieste.len(), 1, "la fetch non si è accodata");
|
||||
assert_eq!(richieste[0].1, "/dati");
|
||||
assert_eq!(richieste[0].2, "GET");
|
||||
|
||||
// nulla è ancora cambiato: la Promise non è risolta
|
||||
assert_eq!(testo_di(&contenuto, "a"), "vuoto");
|
||||
|
||||
let id = richieste[0].0;
|
||||
assert_eq!(
|
||||
macchina.consegna_risposta(&mut contenuto.doc, id, 200, "corpo vero"),
|
||||
1,
|
||||
"la consegna deve sbloccare la Promise"
|
||||
);
|
||||
assert_eq!(
|
||||
testo_di(&contenuto, "a"),
|
||||
"200:corpo vero",
|
||||
"await r.text() non ha ripreso dopo la consegna"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_rifiutata_finisce_nel_catch() {
|
||||
let html = "<html><body><div id=\"a\">vuoto</div><script>\
|
||||
fetch('/rotto').then(function () {\
|
||||
document.getElementById('a').textContent = 'non doveva riuscire';\
|
||||
}).catch(function (e) {\
|
||||
document.getElementById('a').textContent = 'errore: ' + e.message;\
|
||||
});\
|
||||
</script></body></html>";
|
||||
|
||||
let (mut contenuto, mut macchina) = esegui(html);
|
||||
let richieste = macchina.richieste_pendenti();
|
||||
let id = richieste[0].0;
|
||||
// stato negativo: richiesta fallita
|
||||
macchina.consegna_risposta(&mut contenuto.doc, id, -1, "");
|
||||
assert_eq!(
|
||||
testo_di(&contenuto, "a"),
|
||||
"errore: richiesta fallita",
|
||||
"una fetch fallita deve passare dal catch, non lasciare la pagina muta"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_e_promise_all() {
|
||||
let html = "<html><body><div id=\"a\">vuoto</div><script>\
|
||||
Promise.all([Promise.resolve(1), Promise.resolve(2)]).then(function (v) {\
|
||||
document.getElementById('a').textContent = 'somma ' + (v[0] + v[1]);\
|
||||
});\
|
||||
</script></body></html>";
|
||||
let (contenuto, _) = esegui(html);
|
||||
assert_eq!(
|
||||
testo_di(&contenuto, "a"),
|
||||
"somma 3",
|
||||
"Promise.all non funziona: le Promise non sono quelle del motore"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_di_fetch_legge_il_corpo_come_oggetto() {
|
||||
let html = "<html><body><div id=\"a\">vuoto</div><script>\
|
||||
async function vai() {\
|
||||
var r = await fetch('/json');\
|
||||
var dati = await r.json();\
|
||||
document.getElementById('a').textContent = 'nome=' + dati.nome;\
|
||||
}\
|
||||
vai();\
|
||||
</script></body></html>";
|
||||
let (mut contenuto, mut macchina) = esegui(html);
|
||||
let id = macchina.richieste_pendenti()[0].0;
|
||||
macchina.consegna_risposta(&mut contenuto.doc, id, 200, "{\"nome\":\"Mosaic\"}");
|
||||
assert_eq!(testo_di(&contenuto, "a"), "nome=Mosaic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn then_dentro_un_gestore_di_clic() {
|
||||
// il caso che rompeva il desktop: una Promise accesa da un evento
|
||||
let html = concat!(
|
||||
"<html><body><div id=\"riquadro\" style=\"width:60px;height:40px;background:#0000ff\">",
|
||||
"<span id=\"a\">prima</span></div><script>",
|
||||
"document.getElementById('riquadro').addEventListener('click', function () {",
|
||||
" Promise.resolve().then(function () {",
|
||||
" document.getElementById('a').textContent = 'dopo il clic';",
|
||||
" });",
|
||||
"});",
|
||||
"</script></body></html>"
|
||||
);
|
||||
let (mut contenuto, mut macchina) = esegui(html);
|
||||
let nodo = {
|
||||
let mut trovato = 0;
|
||||
for (i, n) in contenuto.doc.nodes.iter().enumerate() {
|
||||
if let NodeKind::Element(e) = &n.kind {
|
||||
if e.attr("id") == Some("riquadro") {
|
||||
trovato = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
trovato
|
||||
};
|
||||
let rami = engine::layout::catena_antenati(&contenuto.doc, nodo);
|
||||
macchina.clic(&mut contenuto.doc, &rami, 5.0, 5.0);
|
||||
assert_eq!(testo_di(&contenuto, "a"), "dopo il clic");
|
||||
}
|
||||
Reference in new issue
Block a user