pub use crate::imp::playwright::DeviceDescriptor;
use crate::{
api::{browser_type::BrowserType, selectors::Selectors},
imp::{core::*, playwright::Playwright as Impl, prelude::*},
Error
};
use std::{io, process::Command};
pub struct Playwright {
driver: Driver,
_conn: Connection,
inner: Weak<Impl>
}
fn run(driver: &Driver, args: &'static [&'static str]) -> io::Result<()> {
let status = Command::new(driver.executable()).args(args).status()?;
if !status.success() {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Exit with {}", status)
));
}
Ok(())
}
impl Playwright {
pub async fn initialize() -> Result<Playwright, Error> {
let driver = Driver::install()?;
Self::with_driver(driver).await
}
pub async fn with_driver(driver: Driver) -> Result<Playwright, Error> {
let conn = Connection::run(&driver.executable())?;
let p = Impl::wait_initial_object(&conn).await?;
Ok(Self {
driver,
_conn: conn,
inner: p
})
}
pub fn prepare(&self) -> io::Result<()> { run(&self.driver, &["install"]) }
pub fn install_chromium(&self) -> io::Result<()> { run(&self.driver, &["install", "chromium"]) }
pub fn install_firefox(&self) -> io::Result<()> { run(&self.driver, &["install", "firefox"]) }
pub fn install_webkit(&self) -> io::Result<()> { run(&self.driver, &["install", "webkit"]) }
pub fn chromium(&self) -> BrowserType {
let inner = weak_and_then(&self.inner, |rc| rc.chromium());
BrowserType::new(inner)
}
pub fn firefox(&self) -> BrowserType {
let inner = weak_and_then(&self.inner, |rc| rc.firefox());
BrowserType::new(inner)
}
pub fn webkit(&self) -> BrowserType {
let inner = weak_and_then(&self.inner, |rc| rc.webkit());
BrowserType::new(inner)
}
pub fn driver(&mut self) -> &mut Driver { &mut self.driver }
pub fn selectors(&self) -> Selectors {
let inner = weak_and_then(&self.inner, |rc| rc.selectors());
Selectors::new(inner)
}
pub fn devices(&self) -> Vec<DeviceDescriptor> {
upgrade(&self.inner)
.map(|x| x.devices().to_vec())
.unwrap_or_default()
}
pub fn device(&self, name: &str) -> Option<DeviceDescriptor> {
let inner = self.inner.upgrade()?;
let device = inner.device(name)?;
Some(device.to_owned())
}
}
#[cfg(test)]
mod tests {
use super::*;
crate::runtime_test!(failure_status_code, {
let mut p = Playwright::initialize().await.unwrap();
let err = run(p.driver(), &["nonExistentArg"]);
assert!(err.is_err());
if let Some(e) = err.err() {
assert_eq!(e.kind(), io::ErrorKind::Other);
}
});
}