Rustfmt net crate

This commit is contained in:
Pyfisch 2018-11-03 15:28:48 +01:00
parent ba1ed11ced
commit 2481ad25f8
30 changed files with 4957 additions and 2870 deletions

View file

@ -118,11 +118,13 @@ fn test_cookie_secure_prefix() {
assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none());
let url = &ServoUrl::parse("http://example.com").unwrap();
let cookie = cookie_rs::Cookie::parse("__Secure-SID=12345; Secure; Domain=example.com").unwrap();
let cookie =
cookie_rs::Cookie::parse("__Secure-SID=12345; Secure; Domain=example.com").unwrap();
assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none());
let url = &ServoUrl::parse("https://example.com").unwrap();
let cookie = cookie_rs::Cookie::parse("__Secure-SID=12345; Secure; Domain=example.com").unwrap();
let cookie =
cookie_rs::Cookie::parse("__Secure-SID=12345; Secure; Domain=example.com").unwrap();
assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_some());
}
@ -157,7 +159,8 @@ fn test_cookie_host_prefix() {
assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none());
let url = &ServoUrl::parse("https://example.com").unwrap();
let cookie = cookie_rs::Cookie::parse("__Host-SID=12345; Secure; Domain=example.com; Path=/").unwrap();
let cookie =
cookie_rs::Cookie::parse("__Host-SID=12345; Secure; Domain=example.com; Path=/").unwrap();
assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none());
let url = &ServoUrl::parse("https://example.com").unwrap();
@ -193,13 +196,18 @@ fn test_sort_order() {
assert!(b.cookie.path().as_ref().unwrap().len() > a.cookie.path().as_ref().unwrap().len());
assert_eq!(CookieStorage::cookie_comparator(&a, &b), Ordering::Greater);
assert_eq!(CookieStorage::cookie_comparator(&b, &a), Ordering::Less);
assert_eq!(CookieStorage::cookie_comparator(&a, &a_prime), Ordering::Less);
assert_eq!(CookieStorage::cookie_comparator(&a_prime, &a), Ordering::Greater);
assert_eq!(
CookieStorage::cookie_comparator(&a, &a_prime),
Ordering::Less
);
assert_eq!(
CookieStorage::cookie_comparator(&a_prime, &a),
Ordering::Greater
);
assert_eq!(CookieStorage::cookie_comparator(&a, &a), Ordering::Equal);
}
fn add_cookie_to_storage(storage: &mut CookieStorage, url: &ServoUrl, cookie_str: &str)
{
fn add_cookie_to_storage(storage: &mut CookieStorage, url: &ServoUrl, cookie_str: &str) {
let source = CookieSource::HTTP;
let cookie = cookie_rs::Cookie::parse(cookie_str.to_owned()).unwrap();
let cookie = Cookie::new_wrapped(cookie, url, source).unwrap();
@ -225,21 +233,40 @@ fn test_insecure_cookies_cannot_evict_secure_cookie() {
let insecure_url = ServoUrl::parse("http://home.example.org:8888/cookie-parser?0001").unwrap();
add_cookie_to_storage(&mut storage, &insecure_url, "foo=value; Domain=home.example.org");
add_cookie_to_storage(&mut storage, &insecure_url, "foo2=value; Domain=.example.org");
add_cookie_to_storage(
&mut storage,
&insecure_url,
"foo=value; Domain=home.example.org",
);
add_cookie_to_storage(
&mut storage,
&insecure_url,
"foo2=value; Domain=.example.org",
);
add_cookie_to_storage(&mut storage, &insecure_url, "foo3=value; Path=/foo/bar");
add_cookie_to_storage(&mut storage, &insecure_url, "foo4=value; Path=/foo");
let source = CookieSource::HTTP;
assert_eq!(storage.cookies_for_url(&secure_url, source).unwrap(), "foo=bar; foo2=bar");
assert_eq!(
storage.cookies_for_url(&secure_url, source).unwrap(),
"foo=bar; foo2=bar"
);
let url = ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap();
let url =
ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap();
let source = CookieSource::HTTP;
assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo3=bar; foo4=value; foo=bar; foo2=bar");
assert_eq!(
storage.cookies_for_url(&url, source).unwrap(),
"foo3=bar; foo4=value; foo=bar; foo2=bar"
);
let url = ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap();
let url =
ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap();
let source = CookieSource::HTTP;
assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo4=bar; foo3=bar; foo4=value; foo=bar; foo2=bar");
assert_eq!(
storage.cookies_for_url(&url, source).unwrap(),
"foo4=bar; foo3=bar; foo4=value; foo=bar; foo2=bar"
);
}
#[test]
@ -267,14 +294,21 @@ fn test_secure_cookies_eviction() {
let source = CookieSource::HTTP;
assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo2=value");
let url = ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap();
let url =
ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap();
let source = CookieSource::HTTP;
assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo3=bar; foo4=value; foo2=value");
assert_eq!(
storage.cookies_for_url(&url, source).unwrap(),
"foo3=bar; foo4=value; foo2=value"
);
let url = ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap();
let url =
ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap();
let source = CookieSource::HTTP;
assert_eq!(storage.cookies_for_url(&url, source).unwrap(),
"foo4=bar; foo3=value; foo3=bar; foo4=value; foo2=value");
assert_eq!(
storage.cookies_for_url(&url, source).unwrap(),
"foo4=bar; foo3=value; foo3=bar; foo4=value; foo2=value"
);
}
#[test]
@ -302,21 +336,28 @@ fn test_secure_cookies_eviction_non_http_source() {
let source = CookieSource::HTTP;
assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo2=value");
let url = ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap();
let url =
ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap();
let source = CookieSource::HTTP;
assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo3=bar; foo4=value; foo2=value");
assert_eq!(
storage.cookies_for_url(&url, source).unwrap(),
"foo3=bar; foo4=value; foo2=value"
);
let url = ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap();
let url =
ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap();
let source = CookieSource::HTTP;
assert_eq!(storage.cookies_for_url(&url, source).unwrap(),
"foo4=bar; foo3=value; foo3=bar; foo4=value; foo2=value");
assert_eq!(
storage.cookies_for_url(&url, source).unwrap(),
"foo4=bar; foo3=value; foo3=bar; foo4=value; foo2=value"
);
}
fn add_retrieve_cookies(set_location: &str,
set_cookies: &[String],
final_location: &str)
-> String {
fn add_retrieve_cookies(
set_location: &str,
set_cookies: &[String],
final_location: &str,
) -> String {
let mut storage = CookieStorage::new(5);
let url = ServoUrl::parse(set_location).unwrap();
let source = CookieSource::HTTP;
@ -329,56 +370,75 @@ fn add_retrieve_cookies(set_location: &str,
// Get cookies for the test location
let url = ServoUrl::parse(final_location).unwrap();
storage.cookies_for_url(&url, source).unwrap_or("".to_string())
storage
.cookies_for_url(&url, source)
.unwrap_or("".to_string())
}
#[test]
fn test_cookie_eviction_expired() {
let mut vec = Vec::new();
for i in 1..6 {
let st = format!("extra{}=bar; Secure; expires=Sun, 18-Apr-2000 21:06:29 GMT",
i);
let st = format!(
"extra{}=bar; Secure; expires=Sun, 18-Apr-2000 21:06:29 GMT",
i
);
vec.push(st);
}
vec.push("foo=bar; Secure; expires=Sun, 18-Apr-2027 21:06:29 GMT".to_owned());
let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001",
&vec, "https://home.example.org:8888/cookie-parser-result?0001");
let r = add_retrieve_cookies(
"https://home.example.org:8888/cookie-parser?0001",
&vec,
"https://home.example.org:8888/cookie-parser-result?0001",
);
assert_eq!(&r, "foo=bar");
}
#[test]
fn test_cookie_eviction_all_secure_one_nonsecure() {
let mut vec = Vec::new();
for i in 1..5 {
let st = format!("extra{}=bar; Secure; expires=Sun, 18-Apr-2026 21:06:29 GMT",
i);
let st = format!(
"extra{}=bar; Secure; expires=Sun, 18-Apr-2026 21:06:29 GMT",
i
);
vec.push(st);
}
vec.push("foo=bar; expires=Sun, 18-Apr-2026 21:06:29 GMT".to_owned());
vec.push("foo2=bar; Secure; expires=Sun, 18-Apr-2028 21:06:29 GMT".to_owned());
let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001",
&vec, "https://home.example.org:8888/cookie-parser-result?0001");
assert_eq!(&r, "extra1=bar; extra2=bar; extra3=bar; extra4=bar; foo2=bar");
let r = add_retrieve_cookies(
"https://home.example.org:8888/cookie-parser?0001",
&vec,
"https://home.example.org:8888/cookie-parser-result?0001",
);
assert_eq!(
&r,
"extra1=bar; extra2=bar; extra3=bar; extra4=bar; foo2=bar"
);
}
#[test]
fn test_cookie_eviction_all_secure_new_nonsecure() {
let mut vec = Vec::new();
for i in 1..6 {
let st = format!("extra{}=bar; Secure; expires=Sun, 18-Apr-2026 21:06:29 GMT",
i);
let st = format!(
"extra{}=bar; Secure; expires=Sun, 18-Apr-2026 21:06:29 GMT",
i
);
vec.push(st);
}
vec.push("foo=bar; expires=Sun, 18-Apr-2077 21:06:29 GMT".to_owned());
let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001",
&vec, "https://home.example.org:8888/cookie-parser-result?0001");
assert_eq!(&r, "extra1=bar; extra2=bar; extra3=bar; extra4=bar; extra5=bar");
let r = add_retrieve_cookies(
"https://home.example.org:8888/cookie-parser?0001",
&vec,
"https://home.example.org:8888/cookie-parser-result?0001",
);
assert_eq!(
&r,
"extra1=bar; extra2=bar; extra3=bar; extra4=bar; extra5=bar"
);
}
#[test]
fn test_cookie_eviction_all_nonsecure_new_secure() {
let mut vec = Vec::new();
@ -387,12 +447,17 @@ fn test_cookie_eviction_all_nonsecure_new_secure() {
vec.push(st);
}
vec.push("foo=bar; Secure; expires=Sun, 18-Apr-2077 21:06:29 GMT".to_owned());
let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001",
&vec, "https://home.example.org:8888/cookie-parser-result?0001");
assert_eq!(&r, "extra2=bar; extra3=bar; extra4=bar; extra5=bar; foo=bar");
let r = add_retrieve_cookies(
"https://home.example.org:8888/cookie-parser?0001",
&vec,
"https://home.example.org:8888/cookie-parser-result?0001",
);
assert_eq!(
&r,
"extra2=bar; extra3=bar; extra4=bar; extra5=bar; foo=bar"
);
}
#[test]
fn test_cookie_eviction_all_nonsecure_new_nonsecure() {
let mut vec = Vec::new();
@ -401,7 +466,13 @@ fn test_cookie_eviction_all_nonsecure_new_nonsecure() {
vec.push(st);
}
vec.push("foo=bar; expires=Sun, 18-Apr-2077 21:06:29 GMT".to_owned());
let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001",
&vec, "https://home.example.org:8888/cookie-parser-result?0001");
assert_eq!(&r, "extra2=bar; extra3=bar; extra4=bar; extra5=bar; foo=bar");
let r = add_retrieve_cookies(
"https://home.example.org:8888/cookie-parser?0001",
&vec,
"https://home.example.org:8888/cookie-parser-result?0001",
);
assert_eq!(
&r,
"extra2=bar; extra3=bar; extra4=bar; extra5=bar; foo=bar"
);
}

File diff suppressed because it is too large Load diff

View file

@ -14,10 +14,12 @@ use servo_url::ServoUrl;
use std::ops::Deref;
#[cfg(test)]
fn assert_parse(url: &'static str,
content_type: Option<ContentType>,
charset: Option<&str>,
data: Option<&[u8]>) {
fn assert_parse(
url: &'static str,
content_type: Option<ContentType>,
charset: Option<&str>,
data: Option<&[u8]>,
) {
let url = ServoUrl::parse(url).unwrap();
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -33,7 +35,10 @@ fn assert_parse(url: &'static str,
assert_eq!(header_content_type, content_type);
let metadata = match response.metadata() {
Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Basic(m), .. }) => m,
Ok(FetchMetadata::Filtered {
filtered: FilteredMetadata::Basic(m),
..
}) => m,
result => panic!(result),
};
assert_eq!(metadata.content_type.map(Serde::into_inner), content_type);
@ -49,7 +54,12 @@ fn assert_parse(url: &'static str,
},
None => {
assert!(response.is_network_error());
assert_eq!(response.metadata().err(), Some(NetworkError::Internal("Decoding data URL failed".to_owned())));
assert_eq!(
response.metadata().err(),
Some(NetworkError::Internal(
"Decoding data URL failed".to_owned()
))
);
},
}
}
@ -63,9 +73,12 @@ fn empty_invalid() {
fn plain() {
assert_parse(
"data:,hello%20world",
Some(ContentType::from("text/plain; charset=US-ASCII".parse::<Mime>().unwrap())),
Some(ContentType::from(
"text/plain; charset=US-ASCII".parse::<Mime>().unwrap(),
)),
Some("us-ascii"),
Some(b"hello world"));
Some(b"hello world"),
);
}
#[test]
@ -74,7 +87,8 @@ fn plain_ct() {
"data:text/plain,hello",
Some(ContentType::from(mime::TEXT_PLAIN)),
None,
Some(b"hello"));
Some(b"hello"),
);
}
#[test]
@ -83,16 +97,20 @@ fn plain_html() {
"data:text/html,<p>Servo</p>",
Some(ContentType::from(mime::TEXT_HTML)),
None,
Some(b"<p>Servo</p>"));
Some(b"<p>Servo</p>"),
);
}
#[test]
fn plain_charset() {
assert_parse(
"data:text/plain;charset=latin1,hello",
Some(ContentType::from("text/plain; charset=latin1".parse::<Mime>().unwrap())),
Some(ContentType::from(
"text/plain; charset=latin1".parse::<Mime>().unwrap(),
)),
Some("latin1"),
Some(b"hello"));
Some(b"hello"),
);
}
#[test]
@ -101,16 +119,20 @@ fn plain_only_charset() {
"data:;charset=utf-8,hello",
Some(ContentType::from(mime::TEXT_PLAIN_UTF_8)),
Some("utf-8"),
Some(b"hello"));
Some(b"hello"),
);
}
#[test]
fn base64() {
assert_parse(
"data:;base64,C62+7w==",
Some(ContentType::from("text/plain; charset=US-ASCII".parse::<Mime>().unwrap())),
Some(ContentType::from(
"text/plain; charset=US-ASCII".parse::<Mime>().unwrap(),
)),
Some("us-ascii"),
Some(&[0x0B, 0xAD, 0xBE, 0xEF]));
Some(&[0x0B, 0xAD, 0xBE, 0xEF]),
);
}
#[test]
@ -119,14 +141,20 @@ fn base64_ct() {
"data:application/octet-stream;base64,C62+7w==",
Some(ContentType::from(mime::APPLICATION_OCTET_STREAM)),
None,
Some(&[0x0B, 0xAD, 0xBE, 0xEF]));
Some(&[0x0B, 0xAD, 0xBE, 0xEF]),
);
}
#[test]
fn base64_charset() {
assert_parse(
"data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==",
Some(ContentType::from("text/plain; charset=koi8-r".parse::<Mime>().unwrap())),
Some(ContentType::from(
"text/plain; charset=koi8-r".parse::<Mime>().unwrap(),
)),
Some("koi8-r"),
Some(&[0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4]));
Some(&[
0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4,
]),
);
}

View file

@ -70,7 +70,10 @@ fn test_fetch_on_bad_port_is_network_error() {
let fetch_response = fetch(&mut request, None);
assert!(fetch_response.is_network_error());
let fetch_error = fetch_response.get_network_error().unwrap();
assert_eq!(fetch_error, &NetworkError::Internal("Request attempted on bad port".into()))
assert_eq!(
fetch_error,
&NetworkError::Internal("Request attempted on bad port".into())
)
}
#[test]
@ -94,7 +97,7 @@ fn test_fetch_response_body_matches_const_message() {
ResponseBody::Done(ref body) => {
assert_eq!(&**body, MESSAGE);
},
_ => panic!()
_ => panic!(),
};
}
@ -106,7 +109,10 @@ fn test_fetch_aboutblank() {
request.referrer = Referrer::NoReferrer;
let fetch_response = fetch(&mut request, None);
assert!(!fetch_response.is_network_error());
assert_eq!(*fetch_response.body.lock().unwrap(), ResponseBody::Done(vec![]));
assert_eq!(
*fetch_response.body.lock().unwrap(),
ResponseBody::Done(vec![])
);
}
#[test]
@ -127,11 +133,12 @@ fn test_fetch_blob() {
let origin = ServoUrl::parse("http://www.example.org/").unwrap();
let (sender, receiver) = ipc::channel().unwrap();
context.filemanager.promote_memory(blob_buf, true, sender, "http://www.example.org".into());
context
.filemanager
.promote_memory(blob_buf, true, sender, "http://www.example.org".into());
let id = receiver.recv().unwrap().unwrap();
let url = ServoUrl::parse(&format!("blob:{}{}", origin.as_str(), id.simple())).unwrap();
let mut request = Request::new(url, Some(Origin::Origin(origin.origin())), None);
let fetch_response = fetch_with_context(&mut request, &context);
@ -139,19 +146,27 @@ fn test_fetch_blob() {
assert_eq!(fetch_response.headers.len(), 2);
let content_type: Mime = fetch_response.headers.typed_get::<ContentType>().unwrap().into();
let content_type: Mime = fetch_response
.headers
.typed_get::<ContentType>()
.unwrap()
.into();
assert_eq!(content_type, mime::TEXT_PLAIN);
let content_length: ContentLength = fetch_response.headers.typed_get().unwrap();
assert_eq!(content_length.0, bytes.len() as u64);
assert_eq!(*fetch_response.body.lock().unwrap(),
ResponseBody::Done(bytes.to_vec()));
assert_eq!(
*fetch_response.body.lock().unwrap(),
ResponseBody::Done(bytes.to_vec())
);
}
#[test]
fn test_fetch_file() {
let path = Path::new("../../resources/servo.css").canonicalize().unwrap();
let path = Path::new("../../resources/servo.css")
.canonicalize()
.unwrap();
let url = ServoUrl::from_file_path(path.clone()).unwrap();
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -159,7 +174,11 @@ fn test_fetch_file() {
let fetch_response = fetch(&mut request, None);
assert!(!fetch_response.is_network_error());
assert_eq!(fetch_response.headers.len(), 1);
let content_type: Mime = fetch_response.headers.typed_get::<ContentType>().unwrap().into();
let content_type: Mime = fetch_response
.headers
.typed_get::<ContentType>()
.unwrap()
.into();
assert_eq!(content_type, mime::TEXT_CSS);
let resp_body = fetch_response.body.lock().unwrap();
@ -171,7 +190,7 @@ fn test_fetch_file() {
ResponseBody::Done(ref val) => {
assert_eq!(val, &bytes);
},
_ => panic!()
_ => panic!(),
}
}
@ -200,15 +219,34 @@ fn test_cors_preflight_fetch() {
static ACK: &'static [u8] = b"ACK";
let state = Arc::new(AtomicUsize::new(0));
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0 {
assert!(request.headers().contains_key(header::ACCESS_CONTROL_REQUEST_METHOD));
assert!(!request.headers().contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS));
assert!(!request.headers().get(header::REFERER).unwrap().to_str().unwrap().contains("a.html"));
response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY);
response.headers_mut().typed_insert(AccessControlAllowCredentials);
response.headers_mut().typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET]));
if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0
{
assert!(request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_METHOD));
assert!(!request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS));
assert!(!request
.headers()
.get(header::REFERER)
.unwrap()
.to_str()
.unwrap()
.contains("a.html"));
response
.headers_mut()
.typed_insert(AccessControlAllowOrigin::ANY);
response
.headers_mut()
.typed_insert(AccessControlAllowCredentials);
response
.headers_mut()
.typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET]));
} else {
response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY);
response
.headers_mut()
.typed_insert(AccessControlAllowOrigin::ANY);
*response.body_mut() = ACK.to_vec().into();
}
};
@ -228,7 +266,7 @@ fn test_cors_preflight_fetch() {
assert!(!fetch_response.is_network_error());
match *fetch_response.body.lock().unwrap() {
ResponseBody::Done(ref body) => assert_eq!(&**body, ACK),
_ => panic!()
_ => panic!(),
};
}
@ -239,15 +277,30 @@ fn test_cors_preflight_cache_fetch() {
let counter = state.clone();
let mut cache = CorsCache::new();
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0 {
assert!(request.headers().contains_key(header::ACCESS_CONTROL_REQUEST_METHOD));
assert!(!request.headers().contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS));
response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY);
response.headers_mut().typed_insert(AccessControlAllowCredentials);
response.headers_mut().typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET]));
response.headers_mut().typed_insert(AccessControlMaxAge::from(Duration::new(6000, 0)));
if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0
{
assert!(request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_METHOD));
assert!(!request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS));
response
.headers_mut()
.typed_insert(AccessControlAllowOrigin::ANY);
response
.headers_mut()
.typed_insert(AccessControlAllowCredentials);
response
.headers_mut()
.typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET]));
response
.headers_mut()
.typed_insert(AccessControlMaxAge::from(Duration::new(6000, 0)));
} else {
response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY);
response
.headers_mut()
.typed_insert(AccessControlAllowOrigin::ANY);
*response.body_mut() = ACK.to_vec().into();
}
};
@ -276,11 +329,11 @@ fn test_cors_preflight_cache_fetch() {
match *fetch_response0.body.lock().unwrap() {
ResponseBody::Done(ref body) => assert_eq!(&**body, ACK),
_ => panic!()
_ => panic!(),
};
match *fetch_response1.body.lock().unwrap() {
ResponseBody::Done(ref body) => assert_eq!(&**body, ACK),
_ => panic!()
_ => panic!(),
};
}
@ -289,14 +342,27 @@ fn test_cors_preflight_fetch_network_error() {
static ACK: &'static [u8] = b"ACK";
let state = Arc::new(AtomicUsize::new(0));
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0 {
assert!(request.headers().contains_key(header::ACCESS_CONTROL_REQUEST_METHOD));
assert!(!request.headers().contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS));
response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY);
response.headers_mut().typed_insert(AccessControlAllowCredentials);
response.headers_mut().typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET]));
if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0
{
assert!(request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_METHOD));
assert!(!request
.headers()
.contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS));
response
.headers_mut()
.typed_insert(AccessControlAllowOrigin::ANY);
response
.headers_mut()
.typed_insert(AccessControlAllowCredentials);
response
.headers_mut()
.typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET]));
} else {
response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY);
response
.headers_mut()
.typed_insert(AccessControlAllowOrigin::ANY);
*response.body_mut() = ACK.to_vec().into();
}
};
@ -318,11 +384,13 @@ fn test_cors_preflight_fetch_network_error() {
fn test_fetch_response_is_basic_filtered() {
static MESSAGE: &'static [u8] = b"";
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
response.headers_mut().insert(header::SET_COOKIE, HeaderValue::from_static(""));
response
.headers_mut()
.insert(header::SET_COOKIE, HeaderValue::from_static(""));
// this header is obsoleted, so hyper doesn't implement it, but it's still covered by the spec
response.headers_mut().insert(
HeaderName::from_static("set-cookie2"),
HeaderValue::from_bytes(&vec![]).unwrap()
HeaderValue::from_bytes(&vec![]).unwrap(),
);
*response.body_mut() = MESSAGE.to_vec().into();
@ -340,7 +408,9 @@ fn test_fetch_response_is_basic_filtered() {
let headers = fetch_response.headers;
assert!(!headers.contains_key(header::SET_COOKIE));
assert!(headers.get(HeaderName::from_static("set-cookie2")).is_none());
assert!(headers
.get(HeaderName::from_static("set-cookie2"))
.is_none());
}
#[test]
@ -349,28 +419,41 @@ fn test_fetch_response_is_cors_filtered() {
let handler = move |_: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
// this is mandatory for the Cors Check to pass
// TODO test using different url encodings with this value ie. punycode
response.headers_mut().typed_insert(AccessControlAllowOrigin::ANY);
response
.headers_mut()
.typed_insert(AccessControlAllowOrigin::ANY);
// these are the headers that should be kept after filtering
response.headers_mut().typed_insert(CacheControl::new());
response.headers_mut().insert(header::CONTENT_LANGUAGE, HeaderValue::from_bytes(&vec![]).unwrap());
response.headers_mut().typed_insert(ContentType::from(mime::TEXT_HTML));
response.headers_mut().typed_insert(Expires::from(SystemTime::now() + Duration::new(86400, 0)));
response.headers_mut().typed_insert(LastModified::from(SystemTime::now()));
response.headers_mut().insert(
header::CONTENT_LANGUAGE,
HeaderValue::from_bytes(&vec![]).unwrap(),
);
response
.headers_mut()
.typed_insert(ContentType::from(mime::TEXT_HTML));
response
.headers_mut()
.typed_insert(Expires::from(SystemTime::now() + Duration::new(86400, 0)));
response
.headers_mut()
.typed_insert(LastModified::from(SystemTime::now()));
response.headers_mut().typed_insert(Pragma::no_cache());
// these headers should not be kept after filtering, even though they are given a pass
response.headers_mut().insert(header::SET_COOKIE, HeaderValue::from_static(""));
response
.headers_mut()
.insert(header::SET_COOKIE, HeaderValue::from_static(""));
response.headers_mut().insert(
HeaderName::from_static("set-cookie2"),
HeaderValue::from_bytes(&vec![]).unwrap()
HeaderValue::from_bytes(&vec![]).unwrap(),
);
response.headers_mut().typed_insert(
AccessControlAllowHeaders::from_iter(vec![
response
.headers_mut()
.typed_insert(AccessControlAllowHeaders::from_iter(vec![
HeaderName::from_static("set-cookie"),
HeaderName::from_static("set-cookie2")
])
);
HeaderName::from_static("set-cookie2"),
]));
*response.body_mut() = MESSAGE.to_vec().into();
};
@ -397,7 +480,9 @@ fn test_fetch_response_is_cors_filtered() {
assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN));
assert!(!headers.contains_key(header::SET_COOKIE));
assert!(headers.get(HeaderName::from_static("set-cookie2")).is_none());
assert!(headers
.get(HeaderName::from_static("set-cookie2"))
.is_none());
}
#[test]
@ -424,12 +509,12 @@ fn test_fetch_response_is_opaque_filtered() {
assert!(fetch_response.status.is_none());
assert_eq!(fetch_response.headers, HeaderMap::new());
match *fetch_response.body.lock().unwrap() {
ResponseBody::Empty => { },
_ => panic!()
ResponseBody::Empty => {},
_ => panic!(),
}
match fetch_response.cache_state {
CacheState::None => { },
_ => panic!()
CacheState::None => {},
_ => panic!(),
}
}
@ -437,13 +522,21 @@ fn test_fetch_response_is_opaque_filtered() {
fn test_fetch_response_is_opaque_redirect_filtered() {
static MESSAGE: &'static [u8] = b"";
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
let redirects = request.uri().path().split("/").collect::<String>().parse::<u32>().unwrap_or(0);
let redirects = request
.uri()
.path()
.split("/")
.collect::<String>()
.parse::<u32>()
.unwrap_or(0);
if redirects == 1 {
*response.body_mut() = MESSAGE.to_vec().into();
} else {
*response.status_mut() = StatusCode::FOUND;
response.headers_mut().insert(header::LOCATION, HeaderValue::from_static("1"));
response
.headers_mut()
.insert(header::LOCATION, HeaderValue::from_static("1"));
}
};
@ -463,12 +556,12 @@ fn test_fetch_response_is_opaque_redirect_filtered() {
assert!(fetch_response.status.is_none());
assert_eq!(fetch_response.headers, HeaderMap::new());
match *fetch_response.body.lock().unwrap() {
ResponseBody::Empty => { },
_ => panic!()
ResponseBody::Empty => {},
_ => panic!(),
}
match fetch_response.cache_state {
CacheState::None => { },
_ => panic!()
CacheState::None => {},
_ => panic!(),
}
}
@ -516,12 +609,19 @@ fn test_fetch_with_hsts() {
*response.body_mut() = MESSAGE.to_vec().into();
};
let cert_path = Path::new("../../resources/self_signed_certificate_for_testing.crt").canonicalize().unwrap();
let key_path = Path::new("../../resources/privatekey_for_testing.key").canonicalize().unwrap();
let cert_path = Path::new("../../resources/self_signed_certificate_for_testing.crt")
.canonicalize()
.unwrap();
let key_path = Path::new("../../resources/privatekey_for_testing.key")
.canonicalize()
.unwrap();
let (server, url) = make_ssl_server(handler, cert_path.clone(), key_path.clone());
let mut ca_content = String::new();
File::open(cert_path).unwrap().read_to_string(&mut ca_content).unwrap();
File::open(cert_path)
.unwrap()
.read_to_string(&mut ca_content)
.unwrap();
let ssl_client = create_ssl_connector_builder(&ca_content);
let context = FetchContext {
@ -534,8 +634,9 @@ fn test_fetch_with_hsts() {
{
let mut list = context.state.hsts_list.write().unwrap();
list.push(HstsEntry::new("localhost".to_owned(), IncludeSubdomains::NotIncluded, None)
.unwrap());
list.push(
HstsEntry::new("localhost".to_owned(), IncludeSubdomains::NotIncluded, None).unwrap(),
);
}
let origin = Origin::Origin(url.origin());
let mut request = Request::new(url, Some(origin), None);
@ -544,8 +645,10 @@ fn test_fetch_with_hsts() {
request.local_urls_only = false;
let response = fetch_with_context(&mut request, &context);
server.close();
assert_eq!(response.internal_response.unwrap().url().unwrap().scheme(),
"https");
assert_eq!(
response.internal_response.unwrap().url().unwrap().scheme(),
"https"
);
}
#[test]
@ -562,7 +665,7 @@ fn test_fetch_with_sri_network_error() {
// To calulate hash use :
// echo -n "alert('Hello, Network Error');" | openssl dgst -sha384 -binary | openssl base64 -A
request.integrity_metadata =
"sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO".to_owned();
"sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO".to_owned();
// Set the flag.
request.local_urls_only = false;
@ -586,7 +689,7 @@ fn test_fetch_with_sri_sucess() {
// To calulate hash use :
// echo -n "alert('Hello, Network Error');" | openssl dgst -sha384 -binary | openssl base64 -A
request.integrity_metadata =
"sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO".to_owned();
"sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO".to_owned();
// Set the flag.
request.local_urls_only = false;
@ -600,9 +703,7 @@ fn test_fetch_with_sri_sucess() {
#[test]
fn test_fetch_blocked_nosniff() {
#[inline]
fn test_nosniff_request(destination: Destination,
mime: Mime,
should_error: bool) {
fn test_nosniff_request(destination: Destination, mime: Mime, should_error: bool) {
const MESSAGE: &'static [u8] = b"";
const HEADER: &'static str = "x-content-type-options";
const VALUE: &'static [u8] = b"nosniff";
@ -612,7 +713,10 @@ fn test_fetch_blocked_nosniff() {
response.headers_mut().typed_insert(mime_header);
assert!(response.headers().contains_key(header::CONTENT_TYPE));
// Add the nosniff header
response.headers_mut().insert(HeaderName::from_static(HEADER), HeaderValue::from_bytes(VALUE).unwrap());
response.headers_mut().insert(
HeaderName::from_static(HEADER),
HeaderValue::from_bytes(VALUE).unwrap(),
);
*response.body_mut() = MESSAGE.to_vec().into();
};
@ -631,7 +735,7 @@ fn test_fetch_blocked_nosniff() {
let tests = vec![
(Destination::Script, mime::TEXT_JAVASCRIPT, false),
(Destination::Script, mime::TEXT_CSS, true),
(Destination::Style, mime::TEXT_CSS, false),
(Destination::Style, mime::TEXT_CSS, false),
];
for test in tests {
@ -642,14 +746,22 @@ fn test_fetch_blocked_nosniff() {
fn setup_server_and_fetch(message: &'static [u8], redirect_cap: u32) -> Response {
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
let redirects = request.uri().path().split("/").collect::<String>().parse::<u32>().unwrap_or(0);
let redirects = request
.uri()
.path()
.split("/")
.collect::<String>()
.parse::<u32>()
.unwrap_or(0);
if redirects >= redirect_cap {
*response.body_mut() = message.to_vec().into();
} else {
*response.status_mut() = StatusCode::FOUND;
let url = format!("{redirects}", redirects = redirects + 1);
response.headers_mut().insert(header::LOCATION, HeaderValue::from_str(&url).unwrap());
response
.headers_mut()
.insert(header::LOCATION, HeaderValue::from_str(&url).unwrap());
}
};
@ -678,7 +790,7 @@ fn test_fetch_redirect_count_ceiling() {
ResponseBody::Done(ref body) => {
assert_eq!(&**body, MESSAGE);
},
_ => panic!()
_ => panic!(),
};
}
@ -694,31 +806,43 @@ fn test_fetch_redirect_count_failure() {
match *fetch_response.body.lock().unwrap() {
ResponseBody::Done(_) | ResponseBody::Receiving(_) => panic!(),
_ => { }
_ => {},
};
}
fn test_fetch_redirect_updates_method_runner(tx: Sender<bool>, status_code: StatusCode, method: Method) {
fn test_fetch_redirect_updates_method_runner(
tx: Sender<bool>,
status_code: StatusCode,
method: Method,
) {
let handler_method = method.clone();
let handler_tx = Arc::new(Mutex::new(tx));
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
let redirects = request.uri().path().split("/").collect::<String>().parse::<u32>().unwrap_or(0);
let redirects = request
.uri()
.path()
.split("/")
.collect::<String>()
.parse::<u32>()
.unwrap_or(0);
let mut test_pass = true;
if redirects == 0 {
*response.status_mut() = StatusCode::TEMPORARY_REDIRECT;
response.headers_mut().insert(header::LOCATION, HeaderValue::from_static("1"));
response
.headers_mut()
.insert(header::LOCATION, HeaderValue::from_static("1"));
} else if redirects == 1 {
// this makes sure that the request method does't change from the wrong status code
if handler_method != Method::GET && request.method() == Method::GET {
test_pass = false;
}
*response.status_mut() = status_code;
response.headers_mut().insert(header::LOCATION, HeaderValue::from_static("2"));
response
.headers_mut()
.insert(header::LOCATION, HeaderValue::from_static("2"));
} else if request.method() != Method::GET {
test_pass = false;
}
@ -727,7 +851,6 @@ fn test_fetch_redirect_updates_method_runner(tx: Sender<bool>, status_code: Stat
if redirects > 0 {
handler_tx.lock().unwrap().send(test_pass).unwrap();
}
};
let (server, url) = make_server(handler);
@ -745,7 +868,11 @@ fn test_fetch_redirect_updates_method_runner(tx: Sender<bool>, status_code: Stat
fn test_fetch_redirect_updates_method() {
let (tx, rx) = channel();
test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::MOVED_PERMANENTLY, Method::POST);
test_fetch_redirect_updates_method_runner(
tx.clone(),
StatusCode::MOVED_PERMANENTLY,
Method::POST,
);
assert_eq!(rx.recv().unwrap(), true);
assert_eq!(rx.recv().unwrap(), true);
// make sure the test doesn't send more data than expected
@ -763,7 +890,11 @@ fn test_fetch_redirect_updates_method() {
let extension = Method::from_bytes(b"FOO").unwrap();
test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::MOVED_PERMANENTLY, extension.clone());
test_fetch_redirect_updates_method_runner(
tx.clone(),
StatusCode::MOVED_PERMANENTLY,
extension.clone(),
);
assert_eq!(rx.recv().unwrap(), true);
// for MovedPermanently and Found, Method should only be changed if it was Post
assert_eq!(rx.recv().unwrap(), false);
@ -785,9 +916,9 @@ fn response_is_done(response: &Response) -> bool {
let response_complete = match response.response_type {
ResponseType::Default | ResponseType::Basic | ResponseType::Cors => {
(*response.body.lock().unwrap()).is_done()
}
},
// if the internal response cannot have a body, it shouldn't block the "done" state
ResponseType::Opaque | ResponseType::OpaqueRedirect | ResponseType::Error(..) => true
ResponseType::Opaque | ResponseType::OpaqueRedirect | ResponseType::Error(..) => true,
};
let internal_complete = if let Some(ref res) = response.internal_response {
@ -842,13 +973,21 @@ fn test_opaque_filtered_fetch_async_returns_complete_response() {
fn test_opaque_redirect_filtered_fetch_async_returns_complete_response() {
static MESSAGE: &'static [u8] = b"";
let handler = move |request: HyperRequest<Body>, response: &mut HyperResponse<Body>| {
let redirects = request.uri().path().split("/").collect::<String>().parse::<u32>().unwrap_or(0);
let redirects = request
.uri()
.path()
.split("/")
.collect::<String>()
.parse::<u32>()
.unwrap_or(0);
if redirects == 1 {
*response.body_mut() = MESSAGE.to_vec().into();
} else {
*response.status_mut() = StatusCode::FOUND;
response.headers_mut().insert(header::LOCATION, HeaderValue::from_static("1"));
response
.headers_mut()
.insert(header::LOCATION, HeaderValue::from_static("1"));
}
};
@ -892,13 +1031,22 @@ fn test_fetch_with_devtools() {
//Creating default headers for request
let mut headers = HeaderMap::new();
headers.insert(header::ACCEPT_ENCODING, HeaderValue::from_static("gzip, deflate, br"));
headers.typed_insert(
Host::from(format!("{}:{}", url.host_str().unwrap(), url.port().unwrap()).parse::<Authority>().unwrap()));
headers.insert(
header::ACCEPT_ENCODING,
HeaderValue::from_static("gzip, deflate, br"),
);
headers.typed_insert(Host::from(
format!("{}:{}", url.host_str().unwrap(), url.port().unwrap())
.parse::<Authority>()
.unwrap(),
));
headers.insert(header::ACCEPT, HeaderValue::from_static("*/*"));
headers.insert(header::ACCEPT_LANGUAGE, HeaderValue::from_static("en-US, en; q=0.5"));
headers.insert(
header::ACCEPT_LANGUAGE,
HeaderValue::from_static("en-US, en; q=0.5"),
);
headers.typed_insert::<UserAgent>(DEFAULT_USER_AGENT.parse().unwrap());
@ -918,7 +1066,11 @@ fn test_fetch_with_devtools() {
let content = "Yay!";
let mut response_headers = HeaderMap::new();
response_headers.typed_insert(ContentLength(content.len() as u64));
devhttpresponse.headers.as_mut().unwrap().remove(header::DATE);
devhttpresponse
.headers
.as_mut()
.unwrap()
.remove(header::DATE);
let httpresponse = DevtoolsHttpResponse {
headers: Some(response_headers),

View file

@ -16,14 +16,18 @@ use std::path::PathBuf;
#[test]
fn test_filemanager() {
let filemanager = FileManager::new(create_embedder_proxy());
PREFS.set("dom.testing.htmlinputelement.select_files.enabled", PrefValue::Boolean(true));
PREFS.set(
"dom.testing.htmlinputelement.select_files.enabled",
PrefValue::Boolean(true),
);
// Try to open a dummy file "components/net/tests/test.jpeg" in tree
let mut handler = File::open("tests/test.jpeg").expect("test.jpeg is stolen");
let mut test_file_content = vec![];
handler.read_to_end(&mut test_file_content)
.expect("Read components/net/tests/test.jpeg error");
handler
.read_to_end(&mut test_file_content)
.expect("Read components/net/tests/test.jpeg error");
let patterns = vec![FilterPattern(".txt".to_string())];
let origin = "test.com".to_string();
@ -31,10 +35,16 @@ fn test_filemanager() {
{
// Try to select a dummy file "components/net/tests/test.jpeg"
let (tx, rx) = ipc::channel().unwrap();
filemanager.handle(FileManagerThreadMsg::SelectFile(patterns.clone(), tx, origin.clone(),
Some("tests/test.jpeg".to_string())));
let selected = rx.recv().expect("Broken channel")
.expect("The file manager failed to find test.jpeg");
filemanager.handle(FileManagerThreadMsg::SelectFile(
patterns.clone(),
tx,
origin.clone(),
Some("tests/test.jpeg".to_string()),
));
let selected = rx
.recv()
.expect("Broken channel")
.expect("The file manager failed to find test.jpeg");
// Expecting attributes conforming the spec
assert_eq!(selected.filename, PathBuf::from("test.jpeg"));
@ -43,24 +53,35 @@ fn test_filemanager() {
// Test by reading, expecting same content
{
let (tx2, rx2) = ipc::channel().unwrap();
filemanager.handle(FileManagerThreadMsg::ReadFile(tx2, selected.id.clone(), false, origin.clone()));
filemanager.handle(FileManagerThreadMsg::ReadFile(
tx2,
selected.id.clone(),
false,
origin.clone(),
));
let msg = rx2.recv().expect("Broken channel");
if let ReadFileProgress::Meta(blob_buf) = msg.expect("File manager reading failure is unexpected") {
if let ReadFileProgress::Meta(blob_buf) =
msg.expect("File manager reading failure is unexpected")
{
let mut bytes = blob_buf.bytes;
loop {
match rx2.recv().expect("Broken channel").expect("File manager reading failure is unexpected") {
match rx2
.recv()
.expect("Broken channel")
.expect("File manager reading failure is unexpected")
{
ReadFileProgress::Meta(_) => {
panic!("Invalid FileManager reply");
}
},
ReadFileProgress::Partial(mut bytes_in) => {
bytes.append(&mut bytes_in);
}
},
ReadFileProgress::EOF => {
break;
}
},
}
}
@ -73,7 +94,11 @@ fn test_filemanager() {
// Delete the id
{
let (tx2, rx2) = ipc::channel().unwrap();
filemanager.handle(FileManagerThreadMsg::DecRef(selected.id.clone(), origin.clone(), tx2));
filemanager.handle(FileManagerThreadMsg::DecRef(
selected.id.clone(),
origin.clone(),
tx2,
));
let ret = rx2.recv().expect("Broken channel");
assert!(ret.is_ok(), "DecRef is not okay");
@ -82,15 +107,26 @@ fn test_filemanager() {
// Test by reading again, expecting read error because we invalidated the id
{
let (tx2, rx2) = ipc::channel().unwrap();
filemanager.handle(FileManagerThreadMsg::ReadFile(tx2, selected.id.clone(), false, origin.clone()));
filemanager.handle(FileManagerThreadMsg::ReadFile(
tx2,
selected.id.clone(),
false,
origin.clone(),
));
let msg = rx2.recv().expect("Broken channel");
match msg {
Err(FileManagerThreadError::BlobURLStoreError(BlobURLStoreError::InvalidFileID)) => {},
Err(FileManagerThreadError::BlobURLStoreError(
BlobURLStoreError::InvalidFileID,
)) => {},
other => {
assert!(false, "Get unexpected response after deleting the id: {:?}", other);
}
assert!(
false,
"Get unexpected response after deleting the id: {:?}",
other
);
},
}
}
}

View file

@ -13,7 +13,7 @@ fn test_hsts_entry_is_not_expired_when_it_has_no_timestamp() {
host: "mozilla.org".to_owned(),
include_subdomains: false,
max_age: Some(20),
timestamp: None
timestamp: None,
};
assert!(!entry.is_expired());
@ -25,7 +25,7 @@ fn test_hsts_entry_is_not_expired_when_it_has_no_max_age() {
host: "mozilla.org".to_owned(),
include_subdomains: false,
max_age: None,
timestamp: Some(time::get_time().sec as u64)
timestamp: Some(time::get_time().sec as u64),
};
assert!(!entry.is_expired());
@ -37,7 +37,7 @@ fn test_hsts_entry_is_expired_when_it_has_reached_its_max_age() {
host: "mozilla.org".to_owned(),
include_subdomains: false,
max_age: Some(10),
timestamp: Some(time::get_time().sec as u64 - 20u64)
timestamp: Some(time::get_time().sec as u64 - 20u64),
};
assert!(entry.is_expired());
@ -46,7 +46,9 @@ fn test_hsts_entry_is_expired_when_it_has_reached_its_max_age() {
#[test]
fn test_hsts_entry_cant_be_created_with_ipv6_address_as_host() {
let entry = HstsEntry::new(
"2001:0db8:0000:0000:0000:ff00:0042:8329".to_owned(), IncludeSubdomains::NotIncluded, None
"2001:0db8:0000:0000:0000:ff00:0042:8329".to_owned(),
IncludeSubdomains::NotIncluded,
None,
);
assert!(entry.is_none(), "able to create HstsEntry with IPv6 host");
@ -54,9 +56,7 @@ fn test_hsts_entry_cant_be_created_with_ipv6_address_as_host() {
#[test]
fn test_hsts_entry_cant_be_created_with_ipv4_address_as_host() {
let entry = HstsEntry::new(
"4.4.4.4".to_owned(), IncludeSubdomains::NotIncluded, None
);
let entry = HstsEntry::new("4.4.4.4".to_owned(), IncludeSubdomains::NotIncluded, None);
assert!(entry.is_none(), "able to create HstsEntry with IPv4 host");
}
@ -66,15 +66,33 @@ fn test_base_domain_in_entries_map() {
let entries_map = HashMap::new();
let mut list = HstsList {
entries_map: entries_map
entries_map: entries_map,
};
list.push(HstsEntry::new("servo.mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded, None).unwrap());
list.push(HstsEntry::new("firefox.mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded, None).unwrap());
list.push(HstsEntry::new("bugzilla.org".to_owned(),
IncludeSubdomains::NotIncluded, None).unwrap());
list.push(
HstsEntry::new(
"servo.mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap(),
);
list.push(
HstsEntry::new(
"firefox.mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap(),
);
list.push(
HstsEntry::new(
"bugzilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap(),
);
assert_eq!(list.entries_map.len(), 2);
assert_eq!(list.entries_map.get("mozilla.org").unwrap().len(), 2);
@ -83,14 +101,27 @@ fn test_base_domain_in_entries_map() {
#[test]
fn test_push_entry_with_0_max_age_evicts_entry_from_list() {
let mut entries_map = HashMap::new();
entries_map.insert("mozilla.org".to_owned(), vec!(HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded, Some(500000u64)).unwrap()));
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
Some(500000u64),
)
.unwrap()],
);
let mut list = HstsList {
entries_map: entries_map
entries_map: entries_map,
};
list.push(HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded, Some(0)).unwrap());
list.push(
HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
Some(0),
)
.unwrap(),
);
assert_eq!(list.is_host_secure("mozilla.org"), false)
}
@ -98,14 +129,22 @@ fn test_push_entry_with_0_max_age_evicts_entry_from_list() {
#[test]
fn test_push_entry_to_hsts_list_should_not_add_subdomains_whose_superdomain_is_already_matched() {
let mut entries_map = HashMap::new();
entries_map.insert("mozilla.org".to_owned(), vec!(HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::Included, None).unwrap()));
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()],
);
let mut list = HstsList {
entries_map: entries_map
entries_map: entries_map,
};
list.push(HstsEntry::new("servo.mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded, None).unwrap());
list.push(
HstsEntry::new(
"servo.mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap(),
);
assert_eq!(list.entries_map.get("mozilla.org").unwrap().len(), 1)
}
@ -113,16 +152,24 @@ fn test_push_entry_to_hsts_list_should_not_add_subdomains_whose_superdomain_is_a
#[test]
fn test_push_entry_to_hsts_list_should_update_existing_domain_entrys_include_subdomains() {
let mut entries_map = HashMap::new();
entries_map.insert("mozilla.org".to_owned(), vec!(HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::Included, None).unwrap()));
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()],
);
let mut list = HstsList {
entries_map: entries_map
entries_map: entries_map,
};
assert!(list.is_host_secure("servo.mozilla.org"));
list.push(HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded, None).unwrap());
list.push(
HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap(),
);
assert!(!list.is_host_secure("servo.mozilla.org"))
}
@ -130,14 +177,27 @@ fn test_push_entry_to_hsts_list_should_update_existing_domain_entrys_include_sub
#[test]
fn test_push_entry_to_hsts_list_should_not_create_duplicate_entry() {
let mut entries_map = HashMap::new();
entries_map.insert("mozilla.org".to_owned(), vec!(HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded, None).unwrap()));
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap()],
);
let mut list = HstsList {
entries_map: entries_map
entries_map: entries_map,
};
list.push(HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded, None).unwrap());
list.push(
HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap(),
);
assert_eq!(list.entries_map.get("mozilla.org").unwrap().len(), 1)
}
@ -145,16 +205,16 @@ fn test_push_entry_to_hsts_list_should_not_create_duplicate_entry() {
#[test]
fn test_push_multiple_entrie_to_hsts_list_should_add_them_all() {
let mut list = HstsList {
entries_map: HashMap::new()
entries_map: HashMap::new(),
};
assert!(!list.is_host_secure("mozilla.org"));
assert!(!list.is_host_secure("bugzilla.org"));
list.push(HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::Included, None).unwrap());
list.push(HstsEntry::new("bugzilla.org".to_owned(),
IncludeSubdomains::Included, None).unwrap());
list.push(HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap());
list.push(
HstsEntry::new("bugzilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap(),
);
assert!(list.is_host_secure("mozilla.org"));
assert!(list.is_host_secure("bugzilla.org"));
@ -163,13 +223,12 @@ fn test_push_multiple_entrie_to_hsts_list_should_add_them_all() {
#[test]
fn test_push_entry_to_hsts_list_should_add_an_entry() {
let mut list = HstsList {
entries_map: HashMap::new()
entries_map: HashMap::new(),
};
assert!(!list.is_host_secure("mozilla.org"));
list.push(HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::Included, None).unwrap());
list.push(HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap());
assert!(list.is_host_secure("mozilla.org"));
}
@ -177,34 +236,43 @@ fn test_push_entry_to_hsts_list_should_add_an_entry() {
#[test]
fn test_parse_hsts_preload_should_return_none_when_json_invalid() {
let mock_preload_content = "derp";
assert!(HstsList::from_preload(mock_preload_content).is_none(), "invalid preload list should not have parsed")
assert!(
HstsList::from_preload(mock_preload_content).is_none(),
"invalid preload list should not have parsed"
)
}
#[test]
fn test_parse_hsts_preload_should_return_none_when_json_contains_no_entries_map_key() {
let mock_preload_content = "{\"nothing\": \"to see here\"}";
assert!(HstsList::from_preload(mock_preload_content).is_none(), "invalid preload list should not have parsed")
assert!(
HstsList::from_preload(mock_preload_content).is_none(),
"invalid preload list should not have parsed"
)
}
#[test]
fn test_parse_hsts_preload_should_decode_host_and_includes_subdomains() {
let mock_preload_content = "{\
\"entries\": [\
{\"host\": \"mozilla.org\",\
\"include_subdomains\": false}\
]\
\"entries\": [\
{\"host\": \"mozilla.org\",\
\"include_subdomains\": false}\
]\
}";
let hsts_list = HstsList::from_preload(mock_preload_content);
let entries_map = hsts_list.unwrap().entries_map;
assert_eq!(entries_map.get("mozilla.org").unwrap()[0].host, "mozilla.org");
assert_eq!(
entries_map.get("mozilla.org").unwrap()[0].host,
"mozilla.org"
);
assert!(!entries_map.get("mozilla.org").unwrap()[0].include_subdomains);
}
#[test]
fn test_hsts_list_with_no_entries_map_does_not_is_host_secure() {
let hsts_list = HstsList {
entries_map: HashMap::new()
entries_map: HashMap::new(),
};
assert!(!hsts_list.is_host_secure("mozilla.org"));
@ -213,11 +281,18 @@ fn test_hsts_list_with_no_entries_map_does_not_is_host_secure() {
#[test]
fn test_hsts_list_with_exact_domain_entry_is_is_host_secure() {
let mut entries_map = HashMap::new();
entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded, None).unwrap()]);
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap()],
);
let hsts_list = HstsList {
entries_map: entries_map
entries_map: entries_map,
};
assert!(hsts_list.is_host_secure("mozilla.org"));
@ -226,10 +301,12 @@ fn test_hsts_list_with_exact_domain_entry_is_is_host_secure() {
#[test]
fn test_hsts_list_with_subdomain_when_include_subdomains_is_true_is_is_host_secure() {
let mut entries_map = HashMap::new();
entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::Included, None).unwrap()]);
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()],
);
let hsts_list = HstsList {
entries_map: entries_map
entries_map: entries_map,
};
assert!(hsts_list.is_host_secure("servo.mozilla.org"));
@ -238,10 +315,17 @@ fn test_hsts_list_with_subdomain_when_include_subdomains_is_true_is_is_host_secu
#[test]
fn test_hsts_list_with_subdomain_when_include_subdomains_is_false_is_not_is_host_secure() {
let mut entries_map = HashMap::new();
entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded, None).unwrap()]);
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
None,
)
.unwrap()],
);
let hsts_list = HstsList {
entries_map: entries_map
entries_map: entries_map,
};
assert!(!hsts_list.is_host_secure("servo.mozilla.org"));
@ -250,10 +334,12 @@ fn test_hsts_list_with_subdomain_when_include_subdomains_is_false_is_not_is_host
#[test]
fn test_hsts_list_with_subdomain_when_host_is_not_a_subdomain_is_not_is_host_secure() {
let mut entries_map = HashMap::new();
entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::Included, None).unwrap()]);
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()],
);
let hsts_list = HstsList {
entries_map: entries_map
entries_map: entries_map,
};
assert!(!hsts_list.is_host_secure("servo-mozilla.org"));
@ -262,10 +348,12 @@ fn test_hsts_list_with_subdomain_when_host_is_not_a_subdomain_is_not_is_host_sec
#[test]
fn test_hsts_list_with_subdomain_when_host_is_exact_match_is_is_host_secure() {
let mut entries_map = HashMap::new();
entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(),
IncludeSubdomains::Included, None).unwrap()]);
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()],
);
let hsts_list = HstsList {
entries_map: entries_map
entries_map: entries_map,
};
assert!(hsts_list.is_host_secure("mozilla.org"));
@ -274,14 +362,17 @@ fn test_hsts_list_with_subdomain_when_host_is_exact_match_is_is_host_secure() {
#[test]
fn test_hsts_list_with_expired_entry_is_not_is_host_secure() {
let mut entries_map = HashMap::new();
entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry {
entries_map.insert(
"mozilla.org".to_owned(),
vec![HstsEntry {
host: "mozilla.org".to_owned(),
include_subdomains: false,
max_age: Some(20),
timestamp: Some(time::get_time().sec as u64 - 100u64)
}]);
timestamp: Some(time::get_time().sec as u64 - 100u64),
}],
);
let hsts_list = HstsList {
entries_map: entries_map
entries_map: entries_map,
};
assert!(!hsts_list.is_host_secure("mozilla.org"));

File diff suppressed because it is too large Load diff

View file

@ -70,9 +70,7 @@ use tokio::runtime::Runtime;
use tokio_openssl::SslAcceptorExt;
lazy_static! {
pub static ref HANDLE: Mutex<Runtime> = {
Mutex::new(Runtime::new().unwrap())
};
pub static ref HANDLE: Mutex<Runtime> = { Mutex::new(Runtime::new().unwrap()) };
}
const DEFAULT_USER_AGENT: &'static str = "Such Browser. Very Layout. Wow.";
@ -83,18 +81,17 @@ struct FetchResponseCollector {
fn create_embedder_proxy() -> EmbedderProxy {
let (sender, _) = channel();
let event_loop_waker = | | {
struct DummyEventLoopWaker {
}
let event_loop_waker = || {
struct DummyEventLoopWaker {}
impl DummyEventLoopWaker {
fn new() -> DummyEventLoopWaker {
DummyEventLoopWaker { }
DummyEventLoopWaker {}
}
}
impl EventLoopWaker for DummyEventLoopWaker {
fn wake(&self) { }
fn wake(&self) {}
fn clone(&self) -> Box<EventLoopWaker + Send> {
Box::new(DummyEventLoopWaker { })
Box::new(DummyEventLoopWaker {})
}
}
@ -103,12 +100,16 @@ fn create_embedder_proxy() -> EmbedderProxy {
EmbedderProxy {
sender: sender,
event_loop_waker: event_loop_waker()
event_loop_waker: event_loop_waker(),
}
}
fn new_fetch_context(dc: Option<Sender<DevtoolsControlMsg>>, fc: Option<EmbedderProxy>) -> FetchContext {
let ssl_connector = create_ssl_connector_builder(&resources::read_string(Resource::SSLCertificates));
fn new_fetch_context(
dc: Option<Sender<DevtoolsControlMsg>>,
fc: Option<EmbedderProxy>,
) -> FetchContext {
let ssl_connector =
create_ssl_connector_builder(&resources::read_string(Resource::SSLCertificates));
let sender = fc.unwrap_or_else(|| create_embedder_proxy());
FetchContext {
state: Arc::new(HttpState::new(ssl_connector)),
@ -135,9 +136,7 @@ fn fetch(request: &mut Request, dc: Option<Sender<DevtoolsControlMsg>>) -> Respo
fn fetch_with_context(request: &mut Request, context: &FetchContext) -> Response {
let (sender, receiver) = channel();
let mut target = FetchResponseCollector {
sender: sender,
};
let mut target = FetchResponseCollector { sender: sender };
methods::fetch(request, &mut target, context);
@ -146,9 +145,7 @@ fn fetch_with_context(request: &mut Request, context: &FetchContext) -> Response
fn fetch_with_cors_cache(request: &mut Request, cache: &mut CorsCache) -> Response {
let (sender, receiver) = channel();
let mut target = FetchResponseCollector {
sender: sender,
};
let mut target = FetchResponseCollector { sender: sender };
methods::fetch_with_cors_cache(request, cache, &mut target, &new_fetch_context(None, None));
@ -166,7 +163,7 @@ impl Server {
}
fn make_server<H>(handler: H) -> (Server, ServoUrl)
where
where
H: Fn(HyperRequest<Body>, &mut HyperResponse<Body>) + Send + Sync + 'static,
{
let handler = Arc::new(handler);
@ -174,18 +171,18 @@ fn make_server<H>(handler: H) -> (Server, ServoUrl)
let url_string = format!("http://localhost:{}", listener.local_addr().unwrap().port());
let url = ServoUrl::parse(&url_string).unwrap();
let (tx, rx) = futures::sync::oneshot::channel::<()>();
let server = HyperServer::from_tcp(listener).unwrap().serve(
move || {
let server = HyperServer::from_tcp(listener)
.unwrap()
.serve(move || {
let handler = handler.clone();
service_fn_ok(move |req: HyperRequest<Body>| {
let mut response = HyperResponse::new(Vec::<u8>::new().into());
handler(req, &mut response);
response
})
}
)
.with_graceful_shutdown(rx)
.map_err(|_|());
})
.with_graceful_shutdown(rx)
.map_err(|_| ());
HANDLE.lock().unwrap().spawn(server);
let server = Server { close_channel: tx };
@ -193,7 +190,7 @@ fn make_server<H>(handler: H) -> (Server, ServoUrl)
}
fn make_ssl_server<H>(handler: H, cert_path: PathBuf, key_path: PathBuf) -> (Server, ServoUrl)
where
where
H: Fn(HyperRequest<Body>, &mut HyperResponse<Body>) + Send + Sync + 'static,
{
let handler = Arc::new(handler);
@ -202,28 +199,39 @@ fn make_ssl_server<H>(handler: H, cert_path: PathBuf, key_path: PathBuf) -> (Ser
let url_string = format!("http://localhost:{}", listener.local_addr().unwrap().port());
let url = ServoUrl::parse(&url_string).unwrap();
let server = listener.incoming()
.map_err(|_| ())
.for_each(move |sock| {
let mut ssl_builder = SslAcceptor::mozilla_modern(SslMethod::tls()).unwrap();
ssl_builder.set_certificate_file(&cert_path, SslFiletype::PEM).unwrap();
ssl_builder.set_private_key_file(&key_path, SslFiletype::PEM).unwrap();
let server = listener.incoming().map_err(|_| ()).for_each(move |sock| {
let mut ssl_builder = SslAcceptor::mozilla_modern(SslMethod::tls()).unwrap();
ssl_builder
.set_certificate_file(&cert_path, SslFiletype::PEM)
.unwrap();
ssl_builder
.set_private_key_file(&key_path, SslFiletype::PEM)
.unwrap();
let handler = handler.clone();
ssl_builder.build().accept_async(sock).map_err(|_| ()).and_then(move |ssl| {
Http::new().serve_connection(ssl,
let handler = handler.clone();
ssl_builder
.build()
.accept_async(sock)
.map_err(|_| ())
.and_then(move |ssl| {
Http::new()
.serve_connection(
ssl,
service_fn_ok(move |req: HyperRequest<Body>| {
let mut response = HyperResponse::new(Vec::<u8>::new().into());
handler(req, &mut response);
response
})
)
.map_err(|_|())
}),
)
.map_err(|_| ())
})
});
});
let (tx, rx) = futures::sync::oneshot::channel::<()>();
let server = server.select(rx.map_err(|_| ())).map(|_| ()).map_err(|_| ());
let server = server
.select(rx.map_err(|_| ()))
.map(|_| ())
.map_err(|_| ());
HANDLE.lock().unwrap().spawn(server);

View file

@ -33,7 +33,7 @@ fn test_sniff_mp4_matcher() {
panic!("Didn't read mime type")
}
},
Err(e) => panic!("Couldn't read from file with error {}", e)
Err(e) => panic!("Couldn't read from file with error {}", e),
}
}
@ -43,9 +43,9 @@ fn test_sniff_mp4_matcher_long() {
let matcher = Mp4Matcher;
let mut data: [u8; 260] = [0; 260];
&data[.. 11].clone_from_slice(
&[0x00, 0x00, 0x01, 0x04, 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34]
);
&data[..11].clone_from_slice(&[
0x00, 0x00, 0x01, 0x04, 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34,
]);
assert!(matcher.matches(&data));
}
@ -57,13 +57,18 @@ fn test_validate_classifier() {
}
#[cfg(test)]
fn test_sniff_with_flags(filename_orig: &path::Path,
expected_mime: Mime,
supplied_type: Option<Mime>,
no_sniff_flag: NoSniffFlag,
apache_bug_flag: ApacheBugFlag) {
fn test_sniff_with_flags(
filename_orig: &path::Path,
expected_mime: Mime,
supplied_type: Option<Mime>,
no_sniff_flag: NoSniffFlag,
apache_bug_flag: ApacheBugFlag,
) {
let current_working_directory = env::current_dir().unwrap();
println!("The current directory is {}", current_working_directory.display());
println!(
"The current directory is {}",
current_working_directory.display()
);
let mut filename = PathBuf::from("tests/parsable_mime/");
filename.push(filename_orig);
@ -74,30 +79,35 @@ fn test_sniff_with_flags(filename_orig: &path::Path,
match read_result {
Ok(data) => {
let parsed_mime = classifier.classify(LoadContext::Browsing,
no_sniff_flag,
apache_bug_flag,
&supplied_type,
&data);
let parsed_mime = classifier.classify(
LoadContext::Browsing,
no_sniff_flag,
apache_bug_flag,
&supplied_type,
&data,
);
if (parsed_mime.type_() != expected_mime.type_()) ||
(parsed_mime.subtype() != expected_mime.subtype()) {
panic!("File {:?} parsed incorrectly should be {:?}, parsed as {:?}",
filename, expected_mime, parsed_mime);
(parsed_mime.subtype() != expected_mime.subtype())
{
panic!(
"File {:?} parsed incorrectly should be {:?}, parsed as {:?}",
filename, expected_mime, parsed_mime
);
}
}
Err(e) => panic!("Couldn't read from file {:?} with error {}",
filename, e),
},
Err(e) => panic!("Couldn't read from file {:?} with error {}", filename, e),
}
}
#[cfg(test)]
fn test_sniff_full(filename_orig: &path::Path, expected_mime: Mime,
supplied_type: Option<Mime>) {
test_sniff_with_flags(filename_orig,
expected_mime,
supplied_type,
NoSniffFlag::Off,
ApacheBugFlag::Off)
fn test_sniff_full(filename_orig: &path::Path, expected_mime: Mime, supplied_type: Option<Mime>) {
test_sniff_with_flags(
filename_orig,
expected_mime,
supplied_type,
NoSniffFlag::Off,
ApacheBugFlag::Off,
)
}
#[cfg(test)]
@ -198,32 +208,50 @@ fn test_sniff_wave() {
#[test]
fn test_sniff_ogg() {
test_sniff_classification("small.ogg", "application/ogg".parse().unwrap(), None);
test_sniff_classification("small.ogg", "application/ogg".parse().unwrap(), Some("audio/".parse().unwrap()));
test_sniff_classification(
"small.ogg",
"application/ogg".parse().unwrap(),
Some("audio/".parse().unwrap()),
);
}
#[test]
#[should_panic]
fn test_sniff_vsn_ms_fontobject() {
test_sniff_classification_sup("vnd.ms-fontobject", "application/vnd.ms-fontobject".parse().unwrap());
test_sniff_classification_sup(
"vnd.ms-fontobject",
"application/vnd.ms-fontobject".parse().unwrap(),
);
}
#[test]
#[should_panic]
fn test_sniff_true_type() {
test_sniff_full(&PathBuf::from("unknown/true_type.ttf"), "(TrueType)/".parse().unwrap(), None);
test_sniff_full(
&PathBuf::from("unknown/true_type.ttf"),
"(TrueType)/".parse().unwrap(),
None,
);
}
#[test]
#[should_panic]
fn test_sniff_open_type() {
test_sniff_full(&PathBuf::from("unknown/open_type"), "(OpenType)/".parse().unwrap(), None);
test_sniff_full(
&PathBuf::from("unknown/open_type"),
"(OpenType)/".parse().unwrap(),
None,
);
}
#[test]
#[should_panic]
fn test_sniff_true_type_collection() {
test_sniff_full(&PathBuf::from("unknown/true_type_collection.ttc"), "(TrueType Collection)/".parse().unwrap(),
None);
test_sniff_full(
&PathBuf::from("unknown/true_type_collection.ttc"),
"(TrueType Collection)/".parse().unwrap(),
None,
);
}
#[test]
@ -244,7 +272,11 @@ fn test_sniff_zip() {
#[test]
fn test_sniff_rar() {
test_sniff_classification("test.rar", "application/x-rar-compressed".parse().unwrap(), None);
test_sniff_classification(
"test.rar",
"application/x-rar-compressed".parse().unwrap(),
None,
);
}
#[test]
@ -466,86 +498,130 @@ fn test_sniff_utf_8_bom() {
#[test]
fn test_sniff_rss_feed() {
// RSS feeds
test_sniff_full(&PathBuf::from("text/xml/feed.rss"), "application/rss+xml".parse().unwrap(), Some(mime::TEXT_HTML));
test_sniff_full(&PathBuf::from("text/xml/rdf_rss.xml"), "application/rss+xml".parse().unwrap(),
Some(mime::TEXT_HTML));
test_sniff_full(
&PathBuf::from("text/xml/feed.rss"),
"application/rss+xml".parse().unwrap(),
Some(mime::TEXT_HTML),
);
test_sniff_full(
&PathBuf::from("text/xml/rdf_rss.xml"),
"application/rss+xml".parse().unwrap(),
Some(mime::TEXT_HTML),
);
// Not RSS feeds
test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_1.xml"), mime::TEXT_HTML, Some(mime::TEXT_HTML));
test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_2.xml"), mime::TEXT_HTML, Some(mime::TEXT_HTML));
test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_3.xml"), mime::TEXT_HTML, Some(mime::TEXT_HTML));
test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_4.xml"), mime::TEXT_HTML, Some(mime::TEXT_HTML));
test_sniff_full(
&PathBuf::from("text/xml/rdf_rss_ko_1.xml"),
mime::TEXT_HTML,
Some(mime::TEXT_HTML),
);
test_sniff_full(
&PathBuf::from("text/xml/rdf_rss_ko_2.xml"),
mime::TEXT_HTML,
Some(mime::TEXT_HTML),
);
test_sniff_full(
&PathBuf::from("text/xml/rdf_rss_ko_3.xml"),
mime::TEXT_HTML,
Some(mime::TEXT_HTML),
);
test_sniff_full(
&PathBuf::from("text/xml/rdf_rss_ko_4.xml"),
mime::TEXT_HTML,
Some(mime::TEXT_HTML),
);
}
#[test]
fn test_sniff_atom_feed() {
test_sniff_full(&PathBuf::from("text/xml/feed.atom"), "application/atom+xml".parse().unwrap(),
Some(mime::TEXT_HTML));
test_sniff_full(
&PathBuf::from("text/xml/feed.atom"),
"application/atom+xml".parse().unwrap(),
Some(mime::TEXT_HTML),
);
}
#[test]
fn test_sniff_binary_file() {
test_sniff_full(&PathBuf::from("unknown/binary_file"), mime::APPLICATION_OCTET_STREAM, None);
test_sniff_full(
&PathBuf::from("unknown/binary_file"),
mime::APPLICATION_OCTET_STREAM,
None,
);
}
#[test]
fn test_sniff_atom_feed_with_no_sniff_flag_on() {
test_sniff_with_flags(&PathBuf::from("text/xml/feed.atom"),
mime::TEXT_HTML,
Some(mime::TEXT_HTML),
NoSniffFlag::On,
ApacheBugFlag::Off);
test_sniff_with_flags(
&PathBuf::from("text/xml/feed.atom"),
mime::TEXT_HTML,
Some(mime::TEXT_HTML),
NoSniffFlag::On,
ApacheBugFlag::Off,
);
}
#[test]
fn test_sniff_with_no_sniff_flag_on_and_apache_flag_on() {
test_sniff_with_flags(&PathBuf::from("text/xml/feed.atom"),
mime::TEXT_HTML,
Some(mime::TEXT_HTML),
NoSniffFlag::On,
ApacheBugFlag::On);
test_sniff_with_flags(
&PathBuf::from("text/xml/feed.atom"),
mime::TEXT_HTML,
Some(mime::TEXT_HTML),
NoSniffFlag::On,
ApacheBugFlag::On,
);
}
#[test]
fn test_sniff_utf_8_bom_with_apache_flag_on() {
test_sniff_with_flags(&PathBuf::from("text/plain/utf8bom.txt"),
mime::TEXT_PLAIN,
Some("dummy/text".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On);
test_sniff_with_flags(
&PathBuf::from("text/plain/utf8bom.txt"),
mime::TEXT_PLAIN,
Some("dummy/text".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On,
);
}
#[test]
fn test_sniff_utf_16be_bom_with_apache_flag_on() {
test_sniff_with_flags(&PathBuf::from("text/plain/utf16bebom.txt"),
mime::TEXT_PLAIN,
Some("dummy/text".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On);
test_sniff_with_flags(
&PathBuf::from("text/plain/utf16bebom.txt"),
mime::TEXT_PLAIN,
Some("dummy/text".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On,
);
}
#[test]
fn test_sniff_utf_16le_bom_with_apache_flag_on() {
test_sniff_with_flags(&PathBuf::from("text/plain/utf16lebom.txt"),
mime::TEXT_PLAIN,
Some("dummy/text".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On);
test_sniff_with_flags(
&PathBuf::from("text/plain/utf16lebom.txt"),
mime::TEXT_PLAIN,
Some("dummy/text".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On,
);
}
#[test]
fn test_sniff_octet_stream_apache_flag_on() {
test_sniff_with_flags(&PathBuf::from("unknown/binary_file"),
mime::APPLICATION_OCTET_STREAM,
Some("dummy/binary".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On);
test_sniff_with_flags(
&PathBuf::from("unknown/binary_file"),
mime::APPLICATION_OCTET_STREAM,
Some("dummy/binary".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On,
);
}
#[test]
fn test_sniff_mp4_video_apache_flag_on() {
test_sniff_with_flags(&PathBuf::from("video/mp4/test.mp4"),
mime::APPLICATION_OCTET_STREAM,
Some("video/mp4".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On);
test_sniff_with_flags(
&PathBuf::from("video/mp4/test.mp4"),
mime::APPLICATION_OCTET_STREAM,
Some("video/mp4".parse().unwrap()),
NoSniffFlag::Off,
ApacheBugFlag::On,
);
}

View file

@ -21,7 +21,13 @@ fn test_exit() {
let (mtx, _mrx) = ipc::channel().unwrap();
let (sender, receiver) = ipc::channel().unwrap();
let (resource_thread, _private_resource_thread) = new_core_resource_thread(
"".into(), None, ProfilerChan(tx), MemProfilerChan(mtx), create_embedder_proxy(), None);
"".into(),
None,
ProfilerChan(tx),
MemProfilerChan(mtx),
create_embedder_proxy(),
None,
);
resource_thread.send(CoreResourceMsg::Exit(sender)).unwrap();
receiver.recv().unwrap();
}
@ -32,12 +38,16 @@ fn test_parse_hostsfile() {
let hosts_table = parse_hostsfile(mock_hosts_file_content);
assert_eq!(2, hosts_table.len());
assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap());
assert_eq!(ip("127.0.0.2"), *hosts_table.get("servo.test.server").unwrap());
assert_eq!(
ip("127.0.0.2"),
*hosts_table.get("servo.test.server").unwrap()
);
}
#[test]
fn test_parse_malformed_hostsfile() {
let mock_hosts_file_content = "malformed file\n127.0.0.1 foo.bar.com\nservo.test.server 127.0.0.1";
let mock_hosts_file_content =
"malformed file\n127.0.0.1 foo.bar.com\nservo.test.server 127.0.0.1";
let hosts_table = parse_hostsfile(mock_hosts_file_content);
assert_eq!(1, hosts_table.len());
assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap());
@ -45,7 +55,8 @@ fn test_parse_malformed_hostsfile() {
#[test]
fn test_parse_hostsfile_with_line_comment() {
let mock_hosts_file_content = "# this is a line comment\n127.0.0.1 foo.bar.com\n# anothercomment";
let mock_hosts_file_content =
"# this is a line comment\n127.0.0.1 foo.bar.com\n# anothercomment";
let hosts_table = parse_hostsfile(mock_hosts_file_content);
assert_eq!(1, hosts_table.len());
assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap());
@ -53,11 +64,15 @@ fn test_parse_hostsfile_with_line_comment() {
#[test]
fn test_parse_hostsfile_with_end_of_line_comment() {
let mock_hosts_file_content = "127.0.0.1 foo.bar.com # line ending comment\n127.0.0.2 servo.test.server #comment";
let mock_hosts_file_content =
"127.0.0.1 foo.bar.com # line ending comment\n127.0.0.2 servo.test.server #comment";
let hosts_table = parse_hostsfile(mock_hosts_file_content);
assert_eq!(2, hosts_table.len());
assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap());
assert_eq!(ip("127.0.0.2"), *hosts_table.get("servo.test.server").unwrap());
assert_eq!(
ip("127.0.0.2"),
*hosts_table.get("servo.test.server").unwrap()
);
}
#[test]
@ -86,12 +101,14 @@ fn test_parse_hostsfile_with_tabs_instead_spaces() {
let hosts_table = parse_hostsfile(mock_hosts_file_content);
assert_eq!(2, hosts_table.len());
assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap());
assert_eq!(ip("127.0.0.2"), *hosts_table.get("servo.test.server").unwrap());
assert_eq!(
ip("127.0.0.2"),
*hosts_table.get("servo.test.server").unwrap()
);
}
#[test]
fn test_parse_hostsfile_with_valid_ipv4_addresses()
{
fn test_parse_hostsfile_with_valid_ipv4_addresses() {
let mock_hosts_file_content =
"255.255.255.255 foo.bar.com\n169.0.1.201 servo.test.server\n192.168.5.0 servo.foo.com";
let hosts_table = parse_hostsfile(mock_hosts_file_content);
@ -99,8 +116,7 @@ fn test_parse_hostsfile_with_valid_ipv4_addresses()
}
#[test]
fn test_parse_hostsfile_with_invalid_ipv4_addresses()
{
fn test_parse_hostsfile_with_invalid_ipv4_addresses() {
let mock_hosts_file_content = "256.255.255.255 foo.bar.com\n169.0.1000.201 servo.test.server \
\n192.168.5.500 servo.foo.com\n192.abc.100.2 test.servo.com";
let hosts_table = parse_hostsfile(mock_hosts_file_content);
@ -108,8 +124,7 @@ fn test_parse_hostsfile_with_invalid_ipv4_addresses()
}
#[test]
fn test_parse_hostsfile_with_valid_ipv6_addresses()
{
fn test_parse_hostsfile_with_valid_ipv6_addresses() {
let mock_hosts_file_content = "2001:0db8:0000:0000:0000:ff00:0042:8329 foo.bar.com\n\
2001:db8:0:0:0:ff00:42:8329 moz.foo.com\n\
2001:db8::ff00:42:8329 foo.moz.com moz.moz.com\n\
@ -122,8 +137,7 @@ fn test_parse_hostsfile_with_valid_ipv6_addresses()
}
#[test]
fn test_parse_hostsfile_with_invalid_ipv6_addresses()
{
fn test_parse_hostsfile_with_invalid_ipv6_addresses() {
let mock_hosts_file_content = "12001:0db8:0000:0000:0000:ff00:0042:8329 foo.bar.com\n\
2001:zdb8:0:0:0:gg00:42:t329 moz.foo.com\n\
2002:0DB8:85A3:0042:1000:8A2E:0370:7334/1289 baz3.bar.moz";
@ -132,14 +146,19 @@ fn test_parse_hostsfile_with_invalid_ipv6_addresses()
}
#[test]
fn test_parse_hostsfile_with_end_of_line_whitespace()
{
fn test_parse_hostsfile_with_end_of_line_whitespace() {
let mock_hosts_file_content = "127.0.0.1 foo.bar.com \n\
2001:db8:0:0:0:ff00:42:8329 moz.foo.com\n \
127.0.0.2 servo.test.server ";
let hosts_table = parse_hostsfile(mock_hosts_file_content);
assert_eq!(3, hosts_table.len());
assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap());
assert_eq!(ip("2001:db8:0:0:0:ff00:42:8329"), *hosts_table.get("moz.foo.com").unwrap());
assert_eq!(ip("127.0.0.2"), *hosts_table.get("servo.test.server").unwrap());
assert_eq!(
ip("2001:db8:0:0:0:ff00:42:8329"),
*hosts_table.get("moz.foo.com").unwrap()
);
assert_eq!(
ip("127.0.0.2"),
*hosts_table.get("servo.test.server").unwrap()
);
}

View file

@ -72,7 +72,8 @@ fn test_response_integrity_valid() {
let url: ServoUrl = ServoUrl::parse("http://servo.org").unwrap();
let response: Response = Response::new(url);
let integrity_metadata = "sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO";
let integrity_metadata =
"sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO";
let response_body = "alert('Hello, world.');".to_owned().into_bytes();
*response.body.lock().unwrap() = ResponseBody::Done(response_body);
@ -84,7 +85,8 @@ fn test_response_integrity_invalid() {
let url: ServoUrl = ServoUrl::parse("http://servo.org").unwrap();
let response: Response = Response::new(url);
let integrity_metadata = "sha256-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO";
let integrity_metadata =
"sha256-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO";
let response_body = "alert('Hello, world.');".to_owned().into_bytes();
*response.body.lock().unwrap() = ResponseBody::Done(response_body);