use super::*;
use pretty_assertions::assert_eq;
use rho_browser::cdp::target::CreateBrowserContext;
use rho_browser::cdp::BackendNodeId;
use rho_browser::tab::Tab;
use rho_browser::{Browser, LaunchOptions, PageSession};
use std::time::Duration;
const SLOW: Duration = Duration::from_millis(500);
const NEEDS_BROWSER: &str = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE";
struct Fixture {
browser: Browser,
_profile: tempfile::TempDir,
open: OpenTab,
page: PageSession,
start: String,
}
impl Fixture {
async fn new(page: &'static str) -> Self {
let profile = tempfile::tempdir().unwrap();
let executable = std::env::var_os("RHO_BROWSER_EXECUTABLE").expect(NEEDS_BROWSER);
let browser = Browser::launch(&LaunchOptions::new(executable, profile.path()))
.await
.expect("the browser should start");
let connection = browser.connection();
let context = connection
.call(&CreateBrowserContext {})
.await
.unwrap()
.browser_context_id;
let tab = Tab::open(connection, &context, VIEWPORT).await.unwrap();
let server = serve(page).await;
Self {
browser,
_profile: profile,
page: tab.page().clone(),
open: OpenTab::new("tab-1".to_owned(), tab, VIEWPORT),
start: format!("http://{server}/"),
}
}
async fn reload(&mut self) {
self.open.load(&self.start).await.unwrap();
}
async fn refer(&mut self, selector: &str) -> String {
let page = &self.page;
let document = page
.call_raw("DOM.getDocument", json!({ "depth": 0 }))
.await
.unwrap();
let found = page
.call_raw(
"DOM.querySelector",
json!({ "nodeId": document["root"]["nodeId"], "selector": selector }),
)
.await
.unwrap();
let node = page
.call_raw("DOM.describeNode", json!({ "nodeId": found["nodeId"] }))
.await
.unwrap()["node"]["backendNodeId"]
.as_i64()
.unwrap();
self.open.document().await.unwrap();
self.open.refs.name(BackendNodeId(node))
}
async fn read(&mut self, expression: &str) -> Value {
self.open.evaluate(expression).await.unwrap()
}
async fn close(self) {
tokio::time::timeout(Duration::from_secs(30), self.browser.close())
.await
.expect("the browser should close")
.expect("the exit status");
}
}
async fn serve(page: &'static str) -> std::net::SocketAddr {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
while let Ok((mut stream, _)) = listener.accept().await {
tokio::spawn(async move {
let mut request = vec![0; 4096];
let read = stream.read(&mut request).await.unwrap_or(0);
let request = String::from_utf8_lossy(&request[..read]).into_owned();
let body = match request.split_whitespace().nth(1) {
Some("/") => page,
Some("/slow") => {
tokio::time::sleep(SLOW).await;
"<title>slow</title>"
}
_ => "<title>next</title>",
};
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: text/html; charset=utf-8\r\ncontent-length: {}\r\n\r\n{body}",
body.len()
);
let _ = stream.write_all(response.as_bytes()).await;
});
}
});
address
}
const CLICKS: &str = r##"<title>start</title>
<button id="plain" onclick="document.title = 'plain ' + event.detail + (event.shiftKey ? ' shift' : '')">plain</button>
<button id="right" oncontextmenu="document.title = 'right'; return false">right</button>
<button id="hover" onmouseover="document.title = 'hovered'">hover</button>
<a id="link" href="/next">next</a>
<span id="wrapped"><a href="#" onclick="document.title = 'inner'"><b id="bold">bold</b></a></span>
<button id="hidden" style="display: none" onclick="document.title = 'hidden'">hidden</button>
<button id="under" style="position: absolute; left: 10px; top: 220px" onclick="document.title = 'under'">under</button>
<div style="position: absolute; left: 0; top: 200px; width: 300px; height: 100px"></div>
<button style="position: absolute; left: 500px; top: 20px; width: 100px; height: 30px" onclick="document.title = 'point'">point</button>
<div style="height: 3000px"></div>
<button id="far" onclick="document.title = 'far'">far</button>"##;
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn a_click_lands_on_its_target_or_fails() {
let mut fixture = Fixture::new(CLICKS).await;
let cases = [
("#plain", Pointer::Left, Modifiers::NONE, true, "plain 1"),
("#plain", Pointer::Double, Modifiers::NONE, true, "plain 2"),
(
"#plain",
Pointer::Left,
Modifiers::SHIFT,
true,
"plain 1 shift",
),
("#right", Pointer::Right, Modifiers::NONE, true, "right"),
("#hover", Pointer::Hover, Modifiers::NONE, true, "hovered"),
("#bold", Pointer::Left, Modifiers::NONE, true, "inner"),
("#far", Pointer::Left, Modifiers::NONE, true, "far"),
("#link", Pointer::Left, Modifiers::NONE, true, "next"),
("#under", Pointer::Left, Modifiers::NONE, false, "start"),
("#hidden", Pointer::Left, Modifiers::NONE, false, "start"),
];
let mut outcomes = Vec::new();
for (selector, pointer, modifiers, _, _) in &cases {
fixture.reload().await;
let element = fixture.refer(selector).await;
let clicked = point(
&mut fixture.open,
*pointer,
&Target::Ref(element),
*modifiers,
)
.await;
let title = fixture.read("document.title").await;
outcomes.push((*selector, clicked.is_ok(), title));
}
fixture.reload().await;
let at = Target::Point { x: 550, y: 35 };
let clicked = point(&mut fixture.open, Pointer::Left, &at, Modifiers::NONE).await;
outcomes.push((
"(550, 35)",
clicked.is_ok(),
fixture.read("document.title").await,
));
let expected: Vec<_> = cases
.iter()
.map(|(selector, _, _, clicked, title)| (*selector, *clicked, json!(title)))
.chain([("(550, 35)", true, json!("point"))])
.collect();
assert_eq!(outcomes, expected);
fixture.close().await;
}
const PLACES: &str = r##"<title>start</title>
<style>button { position: absolute; box-sizing: border-box; border: 0; padding: 0; }</style>
<button id="at" style="left: 10.5px; top: 20.25px; width: 100px; height: 30px">at</button>
<button id="far" style="left: 40px; top: 2000px; width: 50px; height: 20px">far</button>
<button id="edge" style="position: fixed; left: 1200px; top: 100px; width: 200px; height: 40px">edge</button>"##;
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn a_click_by_ref_says_where_its_element_was() {
let mut fixture = Fixture::new(PLACES).await;
let mut refs = Vec::new();
let mut placed = Vec::new();
let mut far = [0.0, 0.0];
for (selector, pointer) in [
("#at", Pointer::Left),
("#at", Pointer::Hover),
("#far", Pointer::Left),
("#edge", Pointer::Left),
] {
fixture.reload().await;
let element = fixture.refer(selector).await;
let target = Target::Ref(element.clone());
let done = point(&mut fixture.open, pointer, &target, Modifiers::NONE)
.await
.unwrap();
refs.push(element);
placed.push(done.placed);
if selector == "#far" {
let at = fixture
.read("(r => [r.left, r.top])(document.getElementById('far').getBoundingClientRect())")
.await;
far = serde_json::from_value(at).unwrap();
}
}
fixture.reload().await;
let at = Target::Point { x: 20, y: 30 };
let by_point = point(&mut fixture.open, Pointer::Left, &at, Modifiers::NONE)
.await
.unwrap()
.placed;
let expected = [
BrowserRect::new(10, 20, 101, 31),
BrowserRect::new(10, 20, 101, 31),
BrowserRect::new(far[0] as u32, far[1] as u32, 50, 20),
BrowserRect::new(1200, 100, 80, 40),
]
.into_iter()
.zip(refs)
.map(|(rect, element)| {
Some(Placed {
element,
rect,
viewport: BrowserViewport::new(VIEWPORT.width, VIEWPORT.height),
})
})
.collect::<Vec<_>>();
assert_eq!((placed, by_point), (expected, None));
fixture.close().await;
}
const FIELDS: &str = r##"<title>start</title>
<form action="/next"><input id="field" name="q"></form>"##;
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn typed_text_and_keys_reach_the_focused_field() {
let mut fixture = Fixture::new(FIELDS).await;
fixture.reload().await;
let field = fixture.refer("#field").await;
point(
&mut fixture.open,
Pointer::Left,
&Target::Ref(field),
Modifiers::NONE,
)
.await
.unwrap();
let value = "document.querySelector('#field')?.value ?? document.title";
let mut seen = Vec::new();
type_text(&mut fixture.open, "héllo wörld 👋")
.await
.unwrap();
seen.push(fixture.read(value).await);
for keys in ["alt+a", "meta+a", "ctrl+a", "x", "BackSpace"] {
let chords = keys::sequence(keys).unwrap();
press_keys(&mut fixture.open, keys, &chords, 1)
.await
.unwrap();
seen.push(fixture.read(value).await);
}
type_text(&mut fixture.open, "ab").await.unwrap();
let left = keys::sequence("Left").unwrap();
press_keys(&mut fixture.open, "Left", &left, 2)
.await
.unwrap();
type_text(&mut fixture.open, "c\n").await.unwrap();
seen.push(fixture.read(value).await);
assert_eq!(
seen,
[
json!("héllo wörld 👋"),
json!("héllo wörld 👋"),
json!("héllo wörld 👋"),
json!("héllo wörld 👋"),
json!("x"),
json!(""),
json!("next"),
]
);
fixture.close().await;
}
const FORM: &str = r##"<title>start</title>
<input id="text" oninput="document.title = 'input ' + this.value">
<input id="tracked">
<input id="number" type="number">
<input id="box" type="checkbox" onchange="document.title = 'box ' + this.checked">
<input id="first" type="radio" name="choice" checked>
<input id="second" type="radio" name="choice">
<select id="pick" onchange="document.title = 'pick ' + this.value">
<option value="a">Apple</option><option value="b">Banana</option>
<option value="c" disabled>Cherry</option>
</select>
<textarea id="area"></textarea>
<input id="off" disabled>
<input id="locked" readonly>
<input id="file" type="file">
<input id="filled" type="number" value="5">
<fieldset disabled><input id="fenced"></fieldset>
<div id="plain">plain</div>
<script>
// As React does: it remembers the value it last set through the
// element's own setter, and reports a change only when the field's value
// differs from it.
const tracked = document.getElementById("tracked");
const native = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");
let remembered = "";
Object.defineProperty(tracked, "value", {
get() { return native.get.call(this); },
set(value) { remembered = value; native.set.call(this, value); },
});
tracked.addEventListener("input", () => {
document.title = tracked.value !== remembered ? "changed" : "unchanged";
});
</script>"##;
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn form_input_sets_fields_as_a_user_would() {
let mut fixture = Fixture::new(FORM).await;
let state = "[document.title, ...[...document.querySelectorAll('input, select, textarea')]
.map(el => el.type === 'checkbox' || el.type === 'radio' ? el.checked : el.value)]";
fixture.reload().await;
let untouched = fixture.read(state).await;
let after = |title: &str, changes: &[(usize, Value)]| {
let mut state = untouched.as_array().unwrap().clone();
state[0] = json!(title);
for (index, value) in changes {
state[*index] = value.clone();
}
Value::Array(state)
};
let cases = [
(
"#text",
json!("hello"),
true,
after("input hello", &[(1, json!("hello"))]),
),
(
"#tracked",
json!("hello"),
true,
after("changed", &[(2, json!("hello"))]),
),
(
"#number",
json!(42),
true,
after("start", &[(3, json!("42"))]),
),
("#number", json!("abc"), false, untouched.clone()),
(
"#box",
json!(true),
true,
after("box true", &[(4, json!(true))]),
),
("#box", json!(false), true, untouched.clone()),
("#box", json!("yes"), false, untouched.clone()),
(
"#second",
json!(true),
true,
after("start", &[(5, json!(false)), (6, json!(true))]),
),
("#first", json!(false), false, untouched.clone()),
(
"#pick",
json!("Banana"),
true,
after("pick b", &[(7, json!("b"))]),
),
(
"#pick",
json!("b"),
true,
after("pick b", &[(7, json!("b"))]),
),
("#pick", json!("Durian"), false, untouched.clone()),
("#pick", json!("Cherry"), false, untouched.clone()),
(
"#area",
json!("two\nlines"),
true,
after("start", &[(8, json!("two\nlines"))]),
),
("#off", json!("x"), false, untouched.clone()),
("#locked", json!("x"), false, untouched.clone()),
("#file", json!("x"), false, untouched.clone()),
("#filled", json!("abc"), false, untouched.clone()),
("#fenced", json!("x"), false, untouched.clone()),
("#plain", json!("x"), false, untouched.clone()),
];
let mut outcomes = Vec::new();
for (selector, value, _, _) in &cases {
fixture.reload().await;
let element = fixture.refer(selector).await;
let set = form_input(&mut fixture.open, &element, value).await;
outcomes.push((*selector, set.is_ok(), fixture.read(state).await));
}
let expected: Vec<_> = cases
.into_iter()
.map(|(selector, _, set, state)| (selector, set, state))
.collect();
assert_eq!(outcomes, expected);
fixture.close().await;
}
const SCRIPTED: &str = r##"<title>start</title>
<script>var secret = 42;</script>
<a id="link" href="/next">next</a>"##;
fn script_outcome(done: Result<String, ToolError>) -> Result<String, ()> {
done.map(|text| {
text.split_once('\n')
.map(|(_, body)| body.to_owned())
.unwrap_or(text)
})
.map_err(drop)
}
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn a_script_runs_in_the_page_and_says_what_it_returned() {
let mut fixture = Fixture::new(SCRIPTED).await;
fixture.reload().await;
let cases = [
("secret", Ok("42")),
(
"({ title: document.title, n: [1, 2] })",
Ok(r#"{"title":"start","n":[1,2]}"#),
),
("document.getElementById('link')", Ok("a#link")),
("throw new Error('boom')", Err(())),
("while (true) {}", Err(())),
("document.title", Ok("start")),
("location.href = '/slow'; 'going'", Ok("going")),
("document.title", Ok("slow")),
];
let mut outcomes = Vec::new();
for (script, _) in &cases {
let done = run(&mut fixture.open, &Act::Script((*script).to_owned())).await;
outcomes.push((*script, script_outcome(done.map(|done| done.text))));
}
let expected: Vec<_> = cases
.iter()
.map(|(script, outcome)| (*script, outcome.map(str::to_owned)))
.collect();
assert_eq!(outcomes, expected);
fixture.close().await;
}
#[derive(Debug, Clone, PartialEq)]
enum Refused {
Stale,
Kept,
}
const FILE_INPUTS: &str = r##"<title>start</title>
<input id="one" type="file" onchange="document.title = 'changed'">
<input id="many" type="file" multiple>
<input id="text">"##;
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn a_file_input_takes_the_files_it_can_hold() {
let mut fixture = Fixture::new(FILE_INPUTS).await;
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.txt"), "a").unwrap();
std::fs::write(dir.path().join("b.txt"), "b").unwrap();
let files = |names: &[&str]| {
let paths: Vec<std::path::PathBuf> = names.iter().map(Into::into).collect();
super::super::opt_in::uploads(dir.path(), &paths).unwrap()
};
let cases = [
("#one", vec!["a.txt"], Ok(json!(["a.txt"]))),
(
"#many",
vec!["a.txt", "b.txt"],
Ok(json!(["a.txt", "b.txt"])),
),
("#one", vec!["a.txt", "b.txt"], Err(Refused::Kept)),
("#text", vec!["a.txt"], Err(Refused::Kept)),
];
let mut outcomes = Vec::new();
for (selector, names, _) in &cases {
fixture.reload().await;
let element = fixture.refer(selector).await;
let stale = super::super::refs::StaleRef(element.clone()).to_string();
let done = run(
&mut fixture.open,
&Act::Upload {
element,
files: files(names),
},
)
.await;
let held = fixture
.read(&format!(
"Array.from(document.querySelector('{selector}').files || []).map(f => f.name)"
))
.await;
let outcome = match done {
Ok(_) => Ok(held),
Err(error) if error.message() == stale => Err(Refused::Stale),
Err(_) => Err(Refused::Kept),
};
outcomes.push((*selector, outcome));
}
fixture.reload().await;
let element = fixture.refer("#one").await;
let upload = Act::Upload {
element,
files: files(&["a.txt"]),
};
run(&mut fixture.open, &upload).await.unwrap();
let changed = fixture.read("document.title").await;
let expected: Vec<_> = cases
.iter()
.map(|(selector, _, held)| (*selector, held.clone()))
.collect();
assert_eq!((outcomes, changed), (expected, json!("changed")));
fixture.close().await;
}