Skip to main content

yew_e2e/test_driver/
scripts.rs

1//! Scripts installed in the page: the clipboard, the WebSocket, the error
2//! watch and the mutation count.
3
4use std::sync::atomic::Ordering;
5
6use anyhow::{Context, Result, ensure};
7
8use crate::{TestDriver, TestElement};
9
10impl TestDriver {
11    /// Capture clipboard writes in this page without accessing the system clipboard.
12    ///
13    /// Replaces `navigator.clipboard.writeText` so the text it is handed is
14    /// kept on the page instead, where [`Self::wait_copied`] reads it. Lasts
15    /// until the page is next loaded.
16    pub async fn capture_clipboard(&self) -> Result<()> {
17        let function = "() => { \
18             navigator.clipboard.writeText = async text => { \
19                 document.body.setAttribute('data-copied', text); \
20             }; \
21         }";
22
23        self.inject(function, Vec::new()).await
24    }
25
26    /// Delay every `WebSocket` send in this page by `millis`, so what the page
27    /// shows while a request is in flight can be observed. Lasts until
28    /// [`Self::stop_delaying_websocket_sends`] or the page is next loaded.
29    ///
30    /// This defers the call into the real `WebSocket.send`, which means it
31    /// must not defer with the caller's own bytes: `send_with_u8_array` hands
32    /// JS a raw view over wasm linear memory, not a copy, and musli-web's
33    /// client reuses one scratch buffer for every request, clearing it the
34    /// moment `send` returns. A connection something else keeps sending on
35    /// (a poll on a timer, say) would otherwise overwrite
36    /// that memory before a long enough delay's deferred call ever reads it,
37    /// corrupting the frame it finally sends. `data.slice()` copies the
38    /// bytes out synchronously, before this function returns control to the
39    /// caller -- the same moment a real, un-shimmed `send()` would -- so the
40    /// delay only ever holds a snapshot, the way a slow network holds bytes
41    /// already handed off, never a live alias into memory the caller is free
42    /// to keep mutating.
43    pub async fn delay_websocket_sends(&self, millis: u64) -> Result<()> {
44        let function = "millis => { \
45             WebSocket.__e2eOriginalSend = WebSocket.__e2eOriginalSend \
46                 || WebSocket.prototype.send; \
47             const send = WebSocket.__e2eOriginalSend; \
48             WebSocket.prototype.send = function(data) { \
49                 const copy = data && typeof data.slice === 'function' \
50                     ? data.slice() : data; \
51                 setTimeout(() => { if (this.readyState === 1) send.call(this, copy); }, \
52                     millis); \
53             }; \
54         }";
55
56        self.inject(function, vec![serde_json::json!(millis)]).await
57    }
58
59    /// Undo [`Self::delay_websocket_sends`], now that whatever it was
60    /// installed to slow down has been observed. The patched `send` stays in
61    /// effect for the rest of the page's life otherwise, taxing every later
62    /// request on the same connection by the same delay -- fine for a test
63    /// that stops looking right after, a trap for one that keeps going and
64    /// pays it on every send from here to the next page load.
65    pub async fn stop_delaying_websocket_sends(&self) -> Result<()> {
66        let function = "() => { \
67             if (WebSocket.__e2eOriginalSend) { \
68                 WebSocket.prototype.send = WebSocket.__e2eOriginalSend; \
69                 delete WebSocket.__e2eOriginalSend; \
70             } \
71         }";
72
73        self.inject(function, Vec::new()).await
74    }
75
76    /// Wait until the text last written to the clipboard since
77    /// [`Self::capture_clipboard`] is exactly `text`.
78    pub async fn wait_copied(&self, text: &str) -> Result<()> {
79        self.wait_until("the full text to be copied", async || {
80            Ok(self.find_one_by("body").await?.attr("data-copied").await? == text)
81        })
82        .await
83    }
84
85    /// Start watching for anything the page throws.
86    ///
87    /// The listener is installed by a script that keeps its names to itself,
88    /// so it neither collides with the page's globals nor claims any the page
89    /// declares later. It marks the body `data-watching` once it is in place,
90    /// and this fails if that mark does not appear, since a watch that never
91    /// started would let every throw pass unheard.
92    ///
93    /// What it records for a thrown error is its message followed by its
94    /// stack, since some browsers (Firefox) keep only the frames in the stack.
95    ///
96    /// The watch is the test's from here on: [`Self::reload`],
97    /// [`Self::reopen_with`], [`Self::in_second_tab`] and
98    /// [`Self::in_second_window`] start it again on the page they arrive at,
99    /// and a test that never asked for it is left unwatched by them.
100    pub async fn watch_for_errors(&self) -> Result<()> {
101        self.watching.store(true, Ordering::Relaxed);
102        self.install_watch().await
103    }
104
105    /// Watch the page this has just navigated to, if the test is watching.
106    pub(super) async fn rewatch(&self) -> Result<()> {
107        if !self.watching.load(Ordering::Relaxed) {
108            return Ok(());
109        }
110
111        self.install_watch()
112            .await
113            .context("watching the page again after navigating")
114    }
115
116    async fn install_watch(&self) -> Result<()> {
117        tracing::trace!("Listening for uncaught errors in the page");
118
119        let function = "() => { \
120             if (document.body.hasAttribute('data-watching')) { return; } \
121             const say = what => document.body.setAttribute( \
122                 'data-threw', String(what).slice(0, 6000)); \
123             const told = (thrown, otherwise) => { \
124                 if (!(thrown instanceof Error)) { return otherwise; } \
125                 const head = String(thrown); \
126                 const stack = thrown.stack || ''; \
127                 return stack.startsWith(head) ? stack : head + '\\n' + stack; \
128             }; \
129             window.addEventListener('error', e => say(told(e.error, e.message))); \
130             window.addEventListener('unhandledrejection', \
131                 e => say(told(e.reason, e.reason))); \
132             const was = console.error; \
133             console.error = (...a) => { say(a.join(' ')); was(...a); }; \
134             document.body.setAttribute('data-watching', ''); \
135         }";
136
137        self.inject(function, Vec::new()).await?;
138
139        let watching = self
140            .inner
141            .execute(
142                "return document.body.hasAttribute('data-watching');",
143                Vec::new(),
144            )
145            .await?;
146
147        ensure!(
148            watching.json().as_bool() == Some(true),
149            "the script that watches the page for errors did not run"
150        );
151        Ok(())
152    }
153
154    /// What the page threw since [`Self::watch_for_errors`], if anything did.
155    pub async fn error_seen(&self) -> Result<Option<String>> {
156        let body = self.find_one_by("body").await?;
157        let seen = body.attr("data-threw").await?;
158
159        Ok((!seen.is_empty()).then_some(seen))
160    }
161
162    /// **Start counting what changes in the document under `element`**: every
163    /// node added or removed, attribute set and text changed there, and the
164    /// element itself taken out of the page (moving it does that), and every
165    /// canvas in it cleared to be drawn again, read back with
166    /// [`Self::mutations`]. Watching again starts the count over.
167    pub async fn watch_mutations(&self, element: &TestElement) -> Result<()> {
168        self.inner
169            .execute(
170                "if (window.__e2eMutations) { \
171                   window.__e2eMutations.observer.disconnect(); \
172                   window.__e2eMutations.outer.disconnect(); \
173                 } \
174                 const watch = { count: 0, kinds: [] }; \
175                 watch.observer = new MutationObserver(records => { \
176                   watch.count += records.length; \
177                   for (const r of records) watch.kinds.push(r.type + ':' + (r.attributeName || '') + ':' + (r.target.className || r.target.nodeName)); \
178                 }); \
179                 watch.observer.observe(arguments[0], \
180                   { subtree: true, childList: true, attributes: true, characterData: true }); \
181                 const node = arguments[0]; \
182                 watch.outer = new MutationObserver(records => { \
183                   for (const r of records) for (const n of r.removedNodes) \
184                     if (n === node || n.contains(node)) { watch.count += 1; watch.kinds.push('removed'); } \
185                 }); \
186                 watch.outer.observe(document.body, { subtree: true, childList: true }); \
187                 if (!window.__e2eClearRect) { \
188                   window.__e2eClearRect = CanvasRenderingContext2D.prototype.clearRect; \
189                   CanvasRenderingContext2D.prototype.clearRect = function (...args) { \
190                     const watch = window.__e2eMutations; \
191                     if (watch && watch.node.contains(this.canvas)) { watch.count += 1; watch.kinds.push('redrawn'); } \
192                     return window.__e2eClearRect.apply(this, args); \
193                   }; \
194                 } \
195                 watch.node = node; \
196                 window.__e2eMutations = watch;",
197                vec![element.inner.to_json()?],
198            )
199            .await?;
200        Ok(())
201    }
202
203    /// How many changes [`Self::watch_mutations`] has seen, and what each was:
204    /// its kind, the attribute where it was one, and the class of the node.
205    pub async fn mutations(&self) -> Result<(u64, Vec<String>)> {
206        let value = self
207            .inner
208            .execute(
209                "const watch = window.__e2eMutations; \
210                 return watch ? [watch.count, watch.kinds] : [0, []];",
211                Vec::new(),
212            )
213            .await?;
214        Ok(serde_json::from_value(value.json().clone())?)
215    }
216}