Bug 1396821 - [geckodriver] Apply rustfmt on other webdriver modules. r=ato

MozReview-Commit-ID: LLLVkRvL08O

--HG--
extra : rebase_source : a8fc7b929c8005470394de5df14a0d8e67ff95a0
This commit is contained in:
Henrik Skupin 2018-08-17 14:56:05 +02:00
Родитель 1cf0042ddf
Коммит e565b85469
3 изменённых файлов: 323 добавлений и 156 удалений

Просмотреть файл

@ -1,78 +1,228 @@
use regex::{Regex, Captures};
use regex::{Captures, Regex};
use hyper::method::Method;
use hyper::method::Method::{Get, Post, Delete};
use hyper::method::Method::{Delete, Get, Post};
use serde_json::Value;
use command::{WebDriverCommand, WebDriverMessage, WebDriverExtensionCommand,
VoidWebDriverExtensionCommand};
use error::{WebDriverResult, WebDriverError, ErrorStatus};
use command::{VoidWebDriverExtensionCommand, WebDriverCommand, WebDriverExtensionCommand,
WebDriverMessage};
use error::{ErrorStatus, WebDriverError, WebDriverResult};
fn standard_routes<U:WebDriverExtensionRoute>() -> Vec<(Method, &'static str, Route<U>)> {
return vec![(Post, "/session", Route::NewSession),
(Delete, "/session/{sessionId}", Route::DeleteSession),
(Post, "/session/{sessionId}/url", Route::Get),
(Get, "/session/{sessionId}/url", Route::GetCurrentUrl),
(Post, "/session/{sessionId}/back", Route::GoBack),
(Post, "/session/{sessionId}/forward", Route::GoForward),
(Post, "/session/{sessionId}/refresh", Route::Refresh),
(Get, "/session/{sessionId}/title", Route::GetTitle),
(Get, "/session/{sessionId}/source", Route::GetPageSource),
(Get, "/session/{sessionId}/window", Route::GetWindowHandle),
(Get, "/session/{sessionId}/window/handles", Route::GetWindowHandles),
(Delete, "/session/{sessionId}/window", Route::CloseWindow),
(Get, "/session/{sessionId}/window/size", Route::GetWindowSize),
(Post, "/session/{sessionId}/window/size", Route::SetWindowSize),
(Get, "/session/{sessionId}/window/position", Route::GetWindowPosition),
(Post, "/session/{sessionId}/window/position", Route::SetWindowPosition),
(Get, "/session/{sessionId}/window/rect", Route::GetWindowRect),
(Post, "/session/{sessionId}/window/rect", Route::SetWindowRect),
(Post, "/session/{sessionId}/window/minimize", Route::MinimizeWindow),
(Post, "/session/{sessionId}/window/maximize", Route::MaximizeWindow),
(Post, "/session/{sessionId}/window/fullscreen", Route::FullscreenWindow),
(Post, "/session/{sessionId}/window", Route::SwitchToWindow),
(Post, "/session/{sessionId}/frame", Route::SwitchToFrame),
(Post, "/session/{sessionId}/frame/parent", Route::SwitchToParentFrame),
(Post, "/session/{sessionId}/element", Route::FindElement),
(Post, "/session/{sessionId}/elements", Route::FindElements),
(Post, "/session/{sessionId}/element/{elementId}/element", Route::FindElementElement),
(Post, "/session/{sessionId}/element/{elementId}/elements", Route::FindElementElements),
(Get, "/session/{sessionId}/element/active", Route::GetActiveElement),
(Get, "/session/{sessionId}/element/{elementId}/displayed", Route::IsDisplayed),
(Get, "/session/{sessionId}/element/{elementId}/selected", Route::IsSelected),
(Get, "/session/{sessionId}/element/{elementId}/attribute/{name}", Route::GetElementAttribute),
(Get, "/session/{sessionId}/element/{elementId}/property/{name}", Route::GetElementProperty),
(Get, "/session/{sessionId}/element/{elementId}/css/{propertyName}", Route::GetCSSValue),
(Get, "/session/{sessionId}/element/{elementId}/text", Route::GetElementText),
(Get, "/session/{sessionId}/element/{elementId}/name", Route::GetElementTagName),
(Get, "/session/{sessionId}/element/{elementId}/rect", Route::GetElementRect),
(Get, "/session/{sessionId}/element/{elementId}/enabled", Route::IsEnabled),
(Post, "/session/{sessionId}/execute/sync", Route::ExecuteScript),
(Post, "/session/{sessionId}/execute/async", Route::ExecuteAsyncScript),
(Get, "/session/{sessionId}/cookie", Route::GetCookies),
(Get, "/session/{sessionId}/cookie/{name}", Route::GetNamedCookie),
(Post, "/session/{sessionId}/cookie", Route::AddCookie),
(Delete, "/session/{sessionId}/cookie", Route::DeleteCookies),
(Delete, "/session/{sessionId}/cookie/{name}", Route::DeleteCookie),
(Get, "/session/{sessionId}/timeouts", Route::GetTimeouts),
(Post, "/session/{sessionId}/timeouts", Route::SetTimeouts),
(Post, "/session/{sessionId}/element/{elementId}/click", Route::ElementClick),
(Post, "/session/{sessionId}/element/{elementId}/tap", Route::ElementTap),
(Post, "/session/{sessionId}/element/{elementId}/clear", Route::ElementClear),
(Post, "/session/{sessionId}/element/{elementId}/value", Route::ElementSendKeys),
(Post, "/session/{sessionId}/alert/dismiss", Route::DismissAlert),
(Post, "/session/{sessionId}/alert/accept", Route::AcceptAlert),
(Get, "/session/{sessionId}/alert/text", Route::GetAlertText),
(Post, "/session/{sessionId}/alert/text", Route::SendAlertText),
(Get, "/session/{sessionId}/screenshot", Route::TakeScreenshot),
(Get, "/session/{sessionId}/element/{elementId}/screenshot", Route::TakeElementScreenshot),
(Post, "/session/{sessionId}/actions", Route::PerformActions),
(Delete, "/session/{sessionId}/actions", Route::ReleaseActions),
(Get, "/status", Route::Status),]
fn standard_routes<U: WebDriverExtensionRoute>() -> Vec<(Method, &'static str, Route<U>)> {
return vec![
(Post, "/session", Route::NewSession),
(Delete, "/session/{sessionId}", Route::DeleteSession),
(Post, "/session/{sessionId}/url", Route::Get),
(Get, "/session/{sessionId}/url", Route::GetCurrentUrl),
(Post, "/session/{sessionId}/back", Route::GoBack),
(Post, "/session/{sessionId}/forward", Route::GoForward),
(Post, "/session/{sessionId}/refresh", Route::Refresh),
(Get, "/session/{sessionId}/title", Route::GetTitle),
(Get, "/session/{sessionId}/source", Route::GetPageSource),
(Get, "/session/{sessionId}/window", Route::GetWindowHandle),
(
Get,
"/session/{sessionId}/window/handles",
Route::GetWindowHandles,
),
(Delete, "/session/{sessionId}/window", Route::CloseWindow),
(
Get,
"/session/{sessionId}/window/size",
Route::GetWindowSize,
),
(
Post,
"/session/{sessionId}/window/size",
Route::SetWindowSize,
),
(
Get,
"/session/{sessionId}/window/position",
Route::GetWindowPosition,
),
(
Post,
"/session/{sessionId}/window/position",
Route::SetWindowPosition,
),
(
Get,
"/session/{sessionId}/window/rect",
Route::GetWindowRect,
),
(
Post,
"/session/{sessionId}/window/rect",
Route::SetWindowRect,
),
(
Post,
"/session/{sessionId}/window/minimize",
Route::MinimizeWindow,
),
(
Post,
"/session/{sessionId}/window/maximize",
Route::MaximizeWindow,
),
(
Post,
"/session/{sessionId}/window/fullscreen",
Route::FullscreenWindow,
),
(Post, "/session/{sessionId}/window", Route::SwitchToWindow),
(Post, "/session/{sessionId}/frame", Route::SwitchToFrame),
(
Post,
"/session/{sessionId}/frame/parent",
Route::SwitchToParentFrame,
),
(Post, "/session/{sessionId}/element", Route::FindElement),
(Post, "/session/{sessionId}/elements", Route::FindElements),
(
Post,
"/session/{sessionId}/element/{elementId}/element",
Route::FindElementElement,
),
(
Post,
"/session/{sessionId}/element/{elementId}/elements",
Route::FindElementElements,
),
(
Get,
"/session/{sessionId}/element/active",
Route::GetActiveElement,
),
(
Get,
"/session/{sessionId}/element/{elementId}/displayed",
Route::IsDisplayed,
),
(
Get,
"/session/{sessionId}/element/{elementId}/selected",
Route::IsSelected,
),
(
Get,
"/session/{sessionId}/element/{elementId}/attribute/{name}",
Route::GetElementAttribute,
),
(
Get,
"/session/{sessionId}/element/{elementId}/property/{name}",
Route::GetElementProperty,
),
(
Get,
"/session/{sessionId}/element/{elementId}/css/{propertyName}",
Route::GetCSSValue,
),
(
Get,
"/session/{sessionId}/element/{elementId}/text",
Route::GetElementText,
),
(
Get,
"/session/{sessionId}/element/{elementId}/name",
Route::GetElementTagName,
),
(
Get,
"/session/{sessionId}/element/{elementId}/rect",
Route::GetElementRect,
),
(
Get,
"/session/{sessionId}/element/{elementId}/enabled",
Route::IsEnabled,
),
(
Post,
"/session/{sessionId}/execute/sync",
Route::ExecuteScript,
),
(
Post,
"/session/{sessionId}/execute/async",
Route::ExecuteAsyncScript,
),
(Get, "/session/{sessionId}/cookie", Route::GetCookies),
(
Get,
"/session/{sessionId}/cookie/{name}",
Route::GetNamedCookie,
),
(Post, "/session/{sessionId}/cookie", Route::AddCookie),
(Delete, "/session/{sessionId}/cookie", Route::DeleteCookies),
(
Delete,
"/session/{sessionId}/cookie/{name}",
Route::DeleteCookie,
),
(Get, "/session/{sessionId}/timeouts", Route::GetTimeouts),
(Post, "/session/{sessionId}/timeouts", Route::SetTimeouts),
(
Post,
"/session/{sessionId}/element/{elementId}/click",
Route::ElementClick,
),
(
Post,
"/session/{sessionId}/element/{elementId}/tap",
Route::ElementTap,
),
(
Post,
"/session/{sessionId}/element/{elementId}/clear",
Route::ElementClear,
),
(
Post,
"/session/{sessionId}/element/{elementId}/value",
Route::ElementSendKeys,
),
(
Post,
"/session/{sessionId}/alert/dismiss",
Route::DismissAlert,
),
(
Post,
"/session/{sessionId}/alert/accept",
Route::AcceptAlert,
),
(Get, "/session/{sessionId}/alert/text", Route::GetAlertText),
(
Post,
"/session/{sessionId}/alert/text",
Route::SendAlertText,
),
(
Get,
"/session/{sessionId}/screenshot",
Route::TakeScreenshot,
),
(
Get,
"/session/{sessionId}/element/{elementId}/screenshot",
Route::TakeElementScreenshot,
),
(Post, "/session/{sessionId}/actions", Route::PerformActions),
(
Delete,
"/session/{sessionId}/actions",
Route::ReleaseActions,
),
(Get, "/status", Route::Status),
];
}
#[derive(Clone, Copy, Debug)]
pub enum Route<U:WebDriverExtensionRoute> {
pub enum Route<U: WebDriverExtensionRoute> {
NewSession,
DeleteSession,
Get,
@ -85,10 +235,10 @@ pub enum Route<U:WebDriverExtensionRoute> {
GetWindowHandle,
GetWindowHandles,
CloseWindow,
GetWindowSize, // deprecated
SetWindowSize, // deprecated
GetWindowPosition, // deprecated
SetWindowPosition, // deprecated
GetWindowSize, // deprecated
SetWindowSize, // deprecated
GetWindowPosition, // deprecated
SetWindowPosition, // deprecated
GetWindowRect,
SetWindowRect,
MinimizeWindow,
@ -136,7 +286,7 @@ pub enum Route<U:WebDriverExtensionRoute> {
Extension(U),
}
pub trait WebDriverExtensionRoute : Clone + Send + PartialEq {
pub trait WebDriverExtensionRoute: Clone + Send + PartialEq {
type Command: WebDriverExtensionCommand + 'static;
fn command(&self, &Captures, &Value) -> WebDriverResult<WebDriverCommand<Self::Command>>;
@ -148,7 +298,11 @@ pub struct VoidWebDriverExtensionRoute;
impl WebDriverExtensionRoute for VoidWebDriverExtensionRoute {
type Command = VoidWebDriverExtensionCommand;
fn command(&self, _:&Captures, _:&Value) -> WebDriverResult<WebDriverCommand<VoidWebDriverExtensionCommand>> {
fn command(
&self,
_: &Captures,
_: &Value,
) -> WebDriverResult<WebDriverCommand<VoidWebDriverExtensionCommand>> {
panic!("No extensions implemented");
}
}
@ -157,16 +311,16 @@ impl WebDriverExtensionRoute for VoidWebDriverExtensionRoute {
struct RequestMatcher<U: WebDriverExtensionRoute> {
method: Method,
path_regexp: Regex,
match_type: Route<U>
match_type: Route<U>,
}
impl <U: WebDriverExtensionRoute> RequestMatcher<U> {
impl<U: WebDriverExtensionRoute> RequestMatcher<U> {
pub fn new(method: Method, path: &str, match_type: Route<U>) -> RequestMatcher<U> {
let path_regexp = RequestMatcher::<U>::compile_path(path);
RequestMatcher {
method: method,
path_regexp: path_regexp,
match_type: match_type
match_type: match_type,
}
}
@ -184,7 +338,7 @@ impl <U: WebDriverExtensionRoute> RequestMatcher<U> {
if !component.ends_with("}") {
panic!("Invalid url pattern")
}
rv.push_str(&format!("(?P<{}>[^/]+)/", &component[1..component.len()-1])[..]);
rv.push_str(&format!("(?P<{}>[^/]+)/", &component[1..component.len() - 1])[..]);
} else {
rv.push_str(&format!("{}/", component)[..]);
}
@ -202,18 +356,20 @@ pub struct WebDriverHttpApi<U: WebDriverExtensionRoute> {
routes: Vec<(Method, RequestMatcher<U>)>,
}
impl <U: WebDriverExtensionRoute> WebDriverHttpApi<U> {
impl<U: WebDriverExtensionRoute> WebDriverHttpApi<U> {
pub fn new(extension_routes: &[(Method, &str, U)]) -> WebDriverHttpApi<U> {
let mut rv = WebDriverHttpApi::<U> {
routes: vec![],
};
let mut rv = WebDriverHttpApi::<U> { routes: vec![] };
debug!("Creating routes");
for &(ref method, ref url, ref match_type) in standard_routes::<U>().iter() {
rv.add(method.clone(), *url, (*match_type).clone());
};
}
for &(ref method, ref url, ref extension_route) in extension_routes.iter() {
rv.add(method.clone(), *url, Route::Extension(extension_route.clone()));
};
rv.add(
method.clone(),
*url,
Route::Extension(extension_route.clone()),
);
}
rv
}
@ -222,24 +378,33 @@ impl <U: WebDriverExtensionRoute> WebDriverHttpApi<U> {
self.routes.push((method, http_matcher));
}
pub fn decode_request(&self, method: Method, path: &str, body: &str) -> WebDriverResult<WebDriverMessage<U>> {
pub fn decode_request(
&self,
method: Method,
path: &str,
body: &str,
) -> WebDriverResult<WebDriverMessage<U>> {
let mut error = ErrorStatus::UnknownPath;
for &(ref match_method, ref matcher) in self.routes.iter() {
if method == *match_method {
let (method_match, captures) = matcher.get_match(method.clone(), path);
if captures.is_some() {
if method_match {
return WebDriverMessage::from_http(matcher.match_type.clone(),
&captures.unwrap(),
body,
method == Post)
return WebDriverMessage::from_http(
matcher.match_type.clone(),
&captures.unwrap(),
body,
method == Post,
);
} else {
error = ErrorStatus::UnknownMethod;
}
}
}
}
Err(WebDriverError::new(error,
format!("{} {} did not match a known command", method, path)))
Err(WebDriverError::new(
error,
format!("{} {} did not match a known command", method, path),
))
}
}

Просмотреть файл

@ -1,7 +1,7 @@
#![allow(non_snake_case)]
extern crate cookie;
extern crate base64;
extern crate cookie;
#[macro_use]
extern crate lazy_static;
#[macro_use]
@ -13,18 +13,19 @@ extern crate serde;
extern crate serde_derive;
extern crate serde_json;
extern crate time;
extern crate url;
extern crate unicode_segmentation;
extern crate url;
#[macro_use] pub mod macros;
#[macro_use]
pub mod macros;
pub mod actions;
pub mod httpapi;
pub mod capabilities;
pub mod command;
pub mod common;
pub mod error;
pub mod server;
pub mod httpapi;
pub mod response;
pub mod server;
#[cfg(test)]
pub mod test;

Просмотреть файл

@ -7,45 +7,49 @@ use std::sync::Mutex;
use std::thread;
use std::time::Duration;
use hyper::header::{ContentType, CacheControl, CacheDirective};
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
use hyper::header::{CacheControl, CacheDirective, ContentType};
use hyper::method::Method;
use hyper::Result;
use hyper::mime::{Attr, Mime, SubLevel, TopLevel, Value};
use hyper::server::{Handler, Listening, Request, Response, Server};
use hyper::status::StatusCode;
use hyper::uri::RequestUri::AbsolutePath;
use hyper::Result;
use command::{WebDriverMessage, WebDriverCommand};
use error::{WebDriverResult, WebDriverError, ErrorStatus};
use httpapi::{WebDriverHttpApi, WebDriverExtensionRoute, VoidWebDriverExtensionRoute};
use command::{WebDriverCommand, WebDriverMessage};
use error::{ErrorStatus, WebDriverError, WebDriverResult};
use httpapi::{VoidWebDriverExtensionRoute, WebDriverExtensionRoute, WebDriverHttpApi};
use response::{CloseWindowResponse, WebDriverResponse};
enum DispatchMessage<U: WebDriverExtensionRoute> {
HandleWebDriver(WebDriverMessage<U>, Sender<WebDriverResult<WebDriverResponse>>),
Quit
HandleWebDriver(
WebDriverMessage<U>,
Sender<WebDriverResult<WebDriverResponse>>,
),
Quit,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Session {
pub id: String
pub id: String,
}
impl Session {
fn new(id: String) -> Session {
Session {
id: id
}
Session { id: id }
}
}
pub trait WebDriverHandler<U: WebDriverExtensionRoute=VoidWebDriverExtensionRoute> : Send {
fn handle_command(&mut self, session: &Option<Session>, msg: WebDriverMessage<U>) -> WebDriverResult<WebDriverResponse>;
pub trait WebDriverHandler<U: WebDriverExtensionRoute = VoidWebDriverExtensionRoute>: Send {
fn handle_command(
&mut self,
session: &Option<Session>,
msg: WebDriverMessage<U>,
) -> WebDriverResult<WebDriverResponse>;
fn delete_session(&mut self, session: &Option<Session>);
}
#[derive(Debug)]
struct Dispatcher<T: WebDriverHandler<U>,
U: WebDriverExtensionRoute> {
struct Dispatcher<T: WebDriverHandler<U>, U: WebDriverExtensionRoute> {
handler: T,
session: Option<Session>,
extension_type: PhantomData<U>,
@ -102,49 +106,46 @@ impl<T: WebDriverHandler<U>, U: WebDriverExtensionRoute> Dispatcher<T, U> {
fn check_session(&self, msg: &WebDriverMessage<U>) -> WebDriverResult<()> {
match msg.session_id {
Some(ref msg_session_id) => {
match self.session {
Some(ref existing_session) => {
if existing_session.id != *msg_session_id {
Err(WebDriverError::new(
ErrorStatus::InvalidSessionId,
format!("Got unexpected session id {}",
msg_session_id)))
} else {
Ok(())
}
},
None => Ok(())
Some(ref msg_session_id) => match self.session {
Some(ref existing_session) => {
if existing_session.id != *msg_session_id {
Err(WebDriverError::new(
ErrorStatus::InvalidSessionId,
format!("Got unexpected session id {}", msg_session_id),
))
} else {
Ok(())
}
}
None => Ok(()),
},
None => {
match self.session {
Some(_) => {
match msg.command {
WebDriverCommand::Status => Ok(()),
WebDriverCommand::NewSession(_) => {
Err(WebDriverError::new(
ErrorStatus::SessionNotCreated,
"Session is already started"))
},
WebDriverCommand::NewSession(_) => Err(WebDriverError::new(
ErrorStatus::SessionNotCreated,
"Session is already started",
)),
_ => {
//This should be impossible
error!("Got a message with no session id");
Err(WebDriverError::new(
ErrorStatus::UnknownError,
"Got a command with no session?!"))
"Got a command with no session?!",
))
}
}
},
None => {
match msg.command {
WebDriverCommand::NewSession(_) => Ok(()),
WebDriverCommand::Status => Ok(()),
_ => Err(WebDriverError::new(
ErrorStatus::InvalidSessionId,
"Tried to run a command before creating a session"))
}
}
None => match msg.command {
WebDriverCommand::NewSession(_) => Ok(()),
WebDriverCommand::Status => Ok(()),
_ => Err(WebDriverError::new(
ErrorStatus::InvalidSessionId,
"Tried to run a command before creating a session",
)),
},
}
}
}
@ -154,14 +155,14 @@ impl<T: WebDriverHandler<U>, U: WebDriverExtensionRoute> Dispatcher<T, U> {
#[derive(Debug)]
struct HttpHandler<U: WebDriverExtensionRoute> {
chan: Mutex<Sender<DispatchMessage<U>>>,
api: Mutex<WebDriverHttpApi<U>>
api: Mutex<WebDriverHttpApi<U>>,
}
impl <U: WebDriverExtensionRoute> HttpHandler<U> {
impl<U: WebDriverExtensionRoute> HttpHandler<U> {
fn new(api: WebDriverHttpApi<U>, chan: Sender<DispatchMessage<U>>) -> HttpHandler<U> {
HttpHandler {
chan: Mutex::new(chan),
api: Mutex::new(api)
api: Mutex::new(api),
}
}
}
@ -209,19 +210,18 @@ impl<U: WebDriverExtensionRoute> Handler for HttpHandler<U> {
}
}
match recv_res.recv() {
Ok(data) => {
match data {
Ok(response) => (StatusCode::Ok,
serde_json::to_string(&response).unwrap()),
Err(err) => (err.http_status(),
serde_json::to_string(&err).unwrap()),
Ok(data) => match data {
Ok(response) => {
(StatusCode::Ok, serde_json::to_string(&response).unwrap())
}
}
Err(err) => {
(err.http_status(), serde_json::to_string(&err).unwrap())
}
},
Err(e) => panic!("Error reading response: {:?}", e),
}
}
Err(err) => (err.http_status(),
serde_json::to_string(&err).unwrap()),
Err(err) => (err.http_status(), serde_json::to_string(&err).unwrap()),
};
debug!("<- {} {}", status, resp_body);
@ -230,10 +230,11 @@ impl<U: WebDriverExtensionRoute> Handler for HttpHandler<U> {
let resp_status = res.status_mut();
*resp_status = status;
}
res.headers_mut()
.set(ContentType(Mime(TopLevel::Application,
SubLevel::Json,
vec![(Attr::Charset, Value::Utf8)])));
res.headers_mut().set(ContentType(Mime(
TopLevel::Application,
SubLevel::Json,
vec![(Attr::Charset, Value::Utf8)],
)));
res.headers_mut()
.set(CacheControl(vec![CacheDirective::NoCache]));