aboutsummaryrefslogtreecommitdiffstats
path: root/tests
diff options
context:
space:
mode:
authorPyfisch <pyfisch@gmail.com>2018-11-06 13:01:35 +0100
committerPyfisch <pyfisch@gmail.com>2018-11-06 22:30:31 +0100
commitcb07debcb6f3d3561177ce536c320986720791b7 (patch)
treeccac4d5a48b3112230f3fc2e873753dd7263e9fb /tests
parentbf47f90da667e95eaffc8fee36ca8a88e72e276c (diff)
downloadservo-cb07debcb6f3d3561177ce536c320986720791b7.tar.gz
servo-cb07debcb6f3d3561177ce536c320986720791b7.zip
Format remaining files
Diffstat (limited to 'tests')
-rw-r--r--tests/unit/malloc_size_of/lib.rs28
-rw-r--r--tests/unit/metrics/interactive_time.rs27
-rw-r--r--tests/unit/metrics/paint_time.rs2
-rw-r--r--tests/unit/profile/time.rs22
-rw-r--r--tests/unit/script/headers.rs18
-rw-r--r--tests/unit/script/htmlareaelement.rs140
-rw-r--r--tests/unit/script/htmlimageelement.rs134
-rw-r--r--tests/unit/script/lib.rs34
-rw-r--r--tests/unit/script/origin.rs54
-rw-r--r--tests/unit/script/textinput.rs102
-rw-r--r--tests/unit/script_plugins/lib.rs22
-rw-r--r--tests/unit/style/animated_properties.rs172
-rw-r--r--tests/unit/style/attr.rs26
-rw-r--r--tests/unit/style/custom_properties.rs29
-rw-r--r--tests/unit/style/lib.rs9
-rw-r--r--tests/unit/style/parsing/animation.rs24
-rw-r--r--tests/unit/style/parsing/background.rs215
-rw-r--r--tests/unit/style/parsing/border.rs59
-rw-r--r--tests/unit/style/parsing/effects.rs38
-rw-r--r--tests/unit/style/parsing/image.rs162
-rw-r--r--tests/unit/style/parsing/inherited_text.rs10
-rw-r--r--tests/unit/style/parsing/mod.rs92
-rw-r--r--tests/unit/style/parsing/position.rs1
-rw-r--r--tests/unit/style/parsing/selectors.rs9
-rw-r--r--tests/unit/style/parsing/supports.rs5
-rw-r--r--tests/unit/style/parsing/transition_timing_function.rs45
-rw-r--r--tests/unit/style/properties/mod.rs42
-rw-r--r--tests/unit/style/properties/scaffolding.rs40
-rw-r--r--tests/unit/style/properties/serialization.rs405
-rw-r--r--tests/unit/style/rule_tree/bench.rs115
-rw-r--r--tests/unit/style/size_of.rs42
-rw-r--r--tests/unit/style/str.rs6
-rw-r--r--tests/unit/style/stylesheets.rs565
-rw-r--r--tests/unit/style/stylist.rs145
-rw-r--r--tests/unit/style/viewport.rs594
35 files changed, 2282 insertions, 1151 deletions
diff --git a/tests/unit/malloc_size_of/lib.rs b/tests/unit/malloc_size_of/lib.rs
index 8aae5a40310..dd933402623 100644
--- a/tests/unit/malloc_size_of/lib.rs
+++ b/tests/unit/malloc_size_of/lib.rs
@@ -25,9 +25,9 @@ pub mod does_not_impl_malloc_size_of {
```compile_fail,E0277
extern crate malloc_size_of;
extern crate servo_arc;
-
+
fn sizeable<T: malloc_size_of::MallocSizeOf>() {}
-
+
fn main() {
sizeable::<servo_arc::Arc<i32>>();
}
@@ -35,13 +35,12 @@ pub mod does_not_impl_malloc_size_of {
*/
pub fn servo_arc() {}
-
/**
```compile_fail,E0277
extern crate malloc_size_of;
-
+
fn sizeable<T: malloc_size_of::MallocSizeOf>() {}
-
+
fn main() {
sizeable::<std::sync::Arc<i32>>();
}
@@ -49,13 +48,12 @@ pub mod does_not_impl_malloc_size_of {
*/
pub fn std_arc() {}
-
/**
```compile_fail,E0277
extern crate malloc_size_of;
-
+
fn sizeable<T: malloc_size_of::MallocSizeOf>() {}
-
+
fn main() {
sizeable::<std::rc::Rc<i32>>();
}
@@ -69,9 +67,9 @@ pub mod does_not_impl_malloc_shallow_size_of {
```compile_fail,E0277
extern crate malloc_size_of;
extern crate servo_arc;
-
+
fn shallow_sizeable<T: malloc_size_of::MallocShallowSizeOf>() {}
-
+
fn main() {
shallow_sizeable::<servo_arc::Arc<i32>>();
}
@@ -79,13 +77,12 @@ pub mod does_not_impl_malloc_shallow_size_of {
*/
pub fn servo_arc() {}
-
/**
```compile_fail,E0277
extern crate malloc_size_of;
-
+
fn shallow_sizeable<T: malloc_size_of::MallocShallowSizeOf>() {}
-
+
fn main() {
shallow_sizeable::<std::sync::Arc<i32>>();
}
@@ -93,13 +90,12 @@ pub mod does_not_impl_malloc_shallow_size_of {
*/
pub fn std_arc() {}
-
/**
```compile_fail,E0277
extern crate malloc_size_of;
-
+
fn shallow_sizeable<T: malloc_size_of::MallocShallowSizeOf>() {}
-
+
fn main() {
shallow_sizeable::<std::rc::Rc<i32>>();
}
diff --git a/tests/unit/metrics/interactive_time.rs b/tests/unit/metrics/interactive_time.rs
index c8999df4b3b..c525ccdfc2c 100644
--- a/tests/unit/metrics/interactive_time.rs
+++ b/tests/unit/metrics/interactive_time.rs
@@ -16,14 +16,11 @@ impl ProfilerMetadataFactory for DummyProfilerMetadataFactory {
}
}
-
fn test_interactive() -> InteractiveMetrics {
let (sender, _) = ipc::channel().unwrap();
let profiler_chan = ProfilerChan(sender);
- let mut interactive = InteractiveMetrics::new(
- profiler_chan,
- ServoUrl::parse("about:blank").unwrap(),
- );
+ let mut interactive =
+ InteractiveMetrics::new(profiler_chan, ServoUrl::parse("about:blank").unwrap());
assert_eq!((&interactive).get_navigation_start(), None);
assert_eq!(interactive.get_tti(), None);
@@ -38,12 +35,18 @@ fn test_set_dcl() {
let profiler_metadata_factory = DummyProfilerMetadataFactory {};
let interactive = test_interactive();
- interactive.maybe_set_tti(&profiler_metadata_factory, InteractiveFlag::DOMContentLoaded);
+ interactive.maybe_set_tti(
+ &profiler_metadata_factory,
+ InteractiveFlag::DOMContentLoaded,
+ );
let dcl = interactive.get_dom_content_loaded();
assert!(dcl.is_some());
//try to overwrite
- interactive.maybe_set_tti(&profiler_metadata_factory, InteractiveFlag::DOMContentLoaded);
+ interactive.maybe_set_tti(
+ &profiler_metadata_factory,
+ InteractiveFlag::DOMContentLoaded,
+ );
assert_eq!(interactive.get_dom_content_loaded(), dcl);
assert_eq!(interactive.get_tti(), None);
}
@@ -84,7 +87,10 @@ fn test_set_tti_dcl() {
let mta = interactive.get_main_thread_available();
assert!(mta.is_some());
- interactive.maybe_set_tti(&profiler_metadata_factory, InteractiveFlag::DOMContentLoaded);
+ interactive.maybe_set_tti(
+ &profiler_metadata_factory,
+ InteractiveFlag::DOMContentLoaded,
+ );
let dcl = interactive.get_dom_content_loaded();
assert!(dcl.is_some());
@@ -97,7 +103,10 @@ fn test_set_tti_mta() {
let profiler_metadata_factory = DummyProfilerMetadataFactory {};
let interactive = test_interactive();
- interactive.maybe_set_tti(&profiler_metadata_factory, InteractiveFlag::DOMContentLoaded);
+ interactive.maybe_set_tti(
+ &profiler_metadata_factory,
+ InteractiveFlag::DOMContentLoaded,
+ );
let dcl = interactive.get_dom_content_loaded();
assert!(dcl.is_some());
diff --git a/tests/unit/metrics/paint_time.rs b/tests/unit/metrics/paint_time.rs
index 0207324a9c2..9112570fe7f 100644
--- a/tests/unit/metrics/paint_time.rs
+++ b/tests/unit/metrics/paint_time.rs
@@ -125,7 +125,7 @@ fn test_first_contentful_paint_setter() {
image_rendering: ImageRendering::Auto,
alpha_type: AlphaType::PremultipliedAlpha,
color: ColorF::WHITE,
- }
+ },
));
let display_list = DisplayList {
list: vec![image],
diff --git a/tests/unit/profile/time.rs b/tests/unit/profile/time.rs
index 0cd41086065..6377256b937 100644
--- a/tests/unit/profile/time.rs
+++ b/tests/unit/profile/time.rs
@@ -22,8 +22,9 @@ fn time_profiler_smoke_test() {
#[test]
fn time_profiler_stats_test() {
- let even_data = vec![1.234, 3.24567, 3.54578, 5.0, 5.324, 7.345,
- 9.2345, 10.2342345, 13.2599, 15.0];
+ let even_data = vec![
+ 1.234, 3.24567, 3.54578, 5.0, 5.324, 7.345, 9.2345, 10.2342345, 13.2599, 15.0,
+ ];
let (even_mean, even_median, even_min, even_max) = time::Profiler::get_statistics(&even_data);
assert_eq!(7.34230845, even_mean);
@@ -31,8 +32,9 @@ fn time_profiler_stats_test() {
assert_eq!(1.234, even_min);
assert_eq!(15.0, even_max);
- let odd_data = vec![1.234, 3.24567, 3.54578, 5.0, 5.324, 7.345,
- 9.2345, 10.2342345, 13.2599];
+ let odd_data = vec![
+ 1.234, 3.24567, 3.54578, 5.0, 5.324, 7.345, 9.2345, 10.2342345, 13.2599,
+ ];
let (odd_mean, odd_median, odd_min, odd_max) = time::Profiler::get_statistics(&odd_data);
assert_eq!(6.491453833333334, odd_mean);
@@ -54,14 +56,16 @@ fn channel_profiler_test() {
assert_eq!(val_profile_receiver, 43);
let (sender, receiver) = ipc::channel().unwrap();
- chan.send(ProfilerMsg::Get((ProfilerCategory::IpcReceiver, None), sender.clone()));
+ chan.send(ProfilerMsg::Get(
+ (ProfilerCategory::IpcReceiver, None),
+ sender.clone(),
+ ));
match receiver.recv().unwrap() {
// asserts that the time spent in the sleeping thread is more than 1500 milliseconds
ProfilerData::Record(time_data) => assert!(time_data[0] > 1.5e3),
ProfilerData::NoRecords => assert!(false),
};
-
}
#[test]
@@ -77,14 +81,16 @@ fn bytes_channel_profiler_test() {
assert_eq!(val_profile_receiver, [1, 2, 3]);
let (sender, receiver) = ipc::channel().unwrap();
- chan.send(ProfilerMsg::Get((ProfilerCategory::IpcBytesReceiver, None), sender.clone()));
+ chan.send(ProfilerMsg::Get(
+ (ProfilerCategory::IpcBytesReceiver, None),
+ sender.clone(),
+ ));
match receiver.recv().unwrap() {
// asserts that the time spent in the sleeping thread is more than 1500 milliseconds
ProfilerData::Record(time_data) => assert!(time_data[0] > 1.5e3),
ProfilerData::NoRecords => assert!(false),
};
-
}
#[cfg(debug_assertions)]
diff --git a/tests/unit/script/headers.rs b/tests/unit/script/headers.rs
index e990b706cdd..a08b82b5dfa 100644
--- a/tests/unit/script/headers.rs
+++ b/tests/unit/script/headers.rs
@@ -34,7 +34,8 @@ fn test_normalize_non_empty_no_whitespace_bytestring() {
#[test]
fn test_normalize_non_empty_leading_whitespace_bytestring() {
// Non-empty, leading whitespace, no trailing whitespace ByteString test
- let leading_whitespace_bytestring = ByteString::new(vec![b'\t', b'\n', b' ', b'\r', b'S', b'!']);
+ let leading_whitespace_bytestring =
+ ByteString::new(vec![b'\t', b'\n', b' ', b'\r', b'S', b'!']);
let actual = normalize_value(leading_whitespace_bytestring);
let expected = ByteString::new(vec![b'S', b'!']);
assert_eq!(actual, expected);
@@ -43,7 +44,8 @@ fn test_normalize_non_empty_leading_whitespace_bytestring() {
#[test]
fn test_normalize_non_empty_no_leading_whitespace_trailing_whitespace_bytestring() {
// Non-empty, no leading whitespace, but with trailing whitespace ByteString test
- let trailing_whitespace_bytestring = ByteString::new(vec![b'S', b'!', b'\t', b'\n', b' ', b'\r']);
+ let trailing_whitespace_bytestring =
+ ByteString::new(vec![b'S', b'!', b'\t', b'\n', b' ', b'\r']);
let actual = normalize_value(trailing_whitespace_bytestring);
let expected = ByteString::new(vec![b'S', b'!']);
assert_eq!(actual, expected);
@@ -52,8 +54,9 @@ fn test_normalize_non_empty_no_leading_whitespace_trailing_whitespace_bytestring
#[test]
fn test_normalize_non_empty_leading_and_trailing_whitespace_bytestring() {
// Non-empty, leading whitespace, and trailing whitespace ByteString test
- let whitespace_sandwich_bytestring =
- ByteString::new(vec![b'\t', b'\n', b' ', b'\r', b'S', b'!', b'\t', b'\n', b' ', b'\r']);
+ let whitespace_sandwich_bytestring = ByteString::new(vec![
+ b'\t', b'\n', b' ', b'\r', b'S', b'!', b'\t', b'\n', b' ', b'\r',
+ ]);
let actual = normalize_value(whitespace_sandwich_bytestring);
let expected = ByteString::new(vec![b'S', b'!']);
assert_eq!(actual, expected);
@@ -63,10 +66,9 @@ fn test_normalize_non_empty_leading_and_trailing_whitespace_bytestring() {
fn test_normalize_non_empty_leading_trailing_and_internal_whitespace_bytestring() {
// Non-empty, leading whitespace, trailing whitespace,
// and internal whitespace ByteString test
- let whitespace_bigmac_bytestring =
- ByteString::new(vec![b'\t', b'\n', b' ', b'\r', b'S',
- b'\t', b'\n', b' ', b'\r', b'!',
- b'\t', b'\n', b' ', b'\r']);
+ let whitespace_bigmac_bytestring = ByteString::new(vec![
+ b'\t', b'\n', b' ', b'\r', b'S', b'\t', b'\n', b' ', b'\r', b'!', b'\t', b'\n', b' ', b'\r',
+ ]);
let actual = normalize_value(whitespace_bigmac_bytestring);
let expected = ByteString::new(vec![b'S', b'\t', b'\n', b' ', b'\r', b'!']);
assert_eq!(actual, expected);
diff --git a/tests/unit/script/htmlareaelement.rs b/tests/unit/script/htmlareaelement.rs
index c2a98fd8681..be4cb12c0cc 100644
--- a/tests/unit/script/htmlareaelement.rs
+++ b/tests/unit/script/htmlareaelement.rs
@@ -28,14 +28,26 @@ fn delimiter_input() {
// Area::Circle tests
#[test]
fn valid_circle_inputs() {
- assert_eq!(Area::parse("10.2, 3.4, 5.2", Shape::Circle),
- Some(Area::Circle { left: 10.2, top: 3.4, radius: 5.2 }));
+ assert_eq!(
+ Area::parse("10.2, 3.4, 5.2", Shape::Circle),
+ Some(Area::Circle {
+ left: 10.2,
+ top: 3.4,
+ radius: 5.2
+ })
+ );
}
#[test]
fn valid_negative_circle_inputs() {
- assert_eq!(Area::parse("-10.2, -3.4, 5.2", Shape::Circle),
- Some(Area::Circle { left: -10.2, top: -3.4, radius: 5.2 }));
+ assert_eq!(
+ Area::parse("-10.2, -3.4, 5.2", Shape::Circle),
+ Some(Area::Circle {
+ left: -10.2,
+ top: -3.4,
+ radius: 5.2
+ })
+ );
}
#[test]
@@ -46,77 +58,133 @@ fn invalid_negative_circle_radius() {
// Area::Rectangle tests
#[test]
fn rectangle_valid_input() {
- assert_eq!(Area::parse("5.2, 1.1, 10.2, 3.4", Shape::Rectangle),
- Some(Area::Rectangle { top_left: (5.2, 1.1),
- bottom_right: (10.2, 3.4) }));
+ assert_eq!(
+ Area::parse("5.2, 1.1, 10.2, 3.4", Shape::Rectangle),
+ Some(Area::Rectangle {
+ top_left: (5.2, 1.1),
+ bottom_right: (10.2, 3.4)
+ })
+ );
}
#[test]
fn rectangle_valid_negative_input() {
- assert_eq!(Area::parse("-10.2, -3.4, -5.2, -1.1", Shape::Rectangle),
- Some(Area::Rectangle { top_left: (-10.2, -3.4),
- bottom_right: (-5.2, -1.1) }));
+ assert_eq!(
+ Area::parse("-10.2, -3.4, -5.2, -1.1", Shape::Rectangle),
+ Some(Area::Rectangle {
+ top_left: (-10.2, -3.4),
+ bottom_right: (-5.2, -1.1)
+ })
+ );
}
#[test]
fn rectangle_invalid_input() {
- assert_eq!(Area::parse("5.2, 4.3, 10.2, 1.1.2", Shape::Rectangle),
- Some(Area::Rectangle { top_left: (5.2, 0.0),
- bottom_right: (10.2, 4.3) }));
+ assert_eq!(
+ Area::parse("5.2, 4.3, 10.2, 1.1.2", Shape::Rectangle),
+ Some(Area::Rectangle {
+ top_left: (5.2, 0.0),
+ bottom_right: (10.2, 4.3)
+ })
+ );
}
#[test]
fn rectangle_unordered_input() {
- assert_eq!(Area::parse("5.2, 1.1, 10.2, 4.3", Shape::Rectangle),
- Some(Area::Rectangle { top_left: (5.2, 1.1),
- bottom_right: (10.2, 4.3) }));
+ assert_eq!(
+ Area::parse("5.2, 1.1, 10.2, 4.3", Shape::Rectangle),
+ Some(Area::Rectangle {
+ top_left: (5.2, 1.1),
+ bottom_right: (10.2, 4.3)
+ })
+ );
}
// Area::Polygon tests
#[test]
fn polygon_six_points_valid_input() {
- assert_eq!(Area::parse("1.1, 1.1, 6.1, 1.1, 3.1, 3.1", Shape::Polygon),
- Some(Area::Polygon { points: vec![1.1, 1.1, 6.1, 1.1, 3.1, 3.1] }));
+ assert_eq!(
+ Area::parse("1.1, 1.1, 6.1, 1.1, 3.1, 3.1", Shape::Polygon),
+ Some(Area::Polygon {
+ points: vec![1.1, 1.1, 6.1, 1.1, 3.1, 3.1]
+ })
+ );
}
#[test]
fn polygon_six_points_valid_negative_input() {
- assert_eq!(Area::parse("1.1, -1.1, 6.1, -1.1, 3.1, -3.1", Shape::Polygon),
- Some(Area::Polygon { points: vec![1.1, -1.1, 6.1, -1.1, 3.1, -3.1] }));
+ assert_eq!(
+ Area::parse("1.1, -1.1, 6.1, -1.1, 3.1, -3.1", Shape::Polygon),
+ Some(Area::Polygon {
+ points: vec![1.1, -1.1, 6.1, -1.1, 3.1, -3.1]
+ })
+ );
}
#[test]
fn polygon_six_points_invalid_input() {
- assert_eq!(Area::parse(";1.1, 1.1,'; 6.1,(*^() 1.1, 3.1, 3.1, 100.1 %$,;", Shape::Polygon),
- Some(Area::Polygon { points: vec![1.1, 1.1, 6.1, 1.1, 3.1, 3.1] }));
+ assert_eq!(
+ Area::parse(
+ ";1.1, 1.1,'; 6.1,(*^() 1.1, 3.1, 3.1, 100.1 %$,;",
+ Shape::Polygon
+ ),
+ Some(Area::Polygon {
+ points: vec![1.1, 1.1, 6.1, 1.1, 3.1, 3.1]
+ })
+ );
}
#[test]
fn polygon_eight_points_invalid_input() {
- assert_eq!(Area::parse("1.1, -1.1, 6.1, -1.1, 1.1, -3.1, 6.1, -3.1.2, 12.1", Shape::Polygon),
- Some(Area::Polygon { points: vec![1.1, -1.1, 6.1, -1.1, 1.1, -3.1, 6.1, 0.0] }));
+ assert_eq!(
+ Area::parse(
+ "1.1, -1.1, 6.1, -1.1, 1.1, -3.1, 6.1, -3.1.2, 12.1",
+ Shape::Polygon
+ ),
+ Some(Area::Polygon {
+ points: vec![1.1, -1.1, 6.1, -1.1, 1.1, -3.1, 6.1, 0.0]
+ })
+ );
}
#[test]
fn test_hit_test_circle() {
- let circ1 = Area::Circle { left: 20.0, top: 10.0, radius: 5.0 };
- assert!(!circ1.hit_test(&Point2D::new(10.0, 20.0)));
- let circ2 = Area::Circle { left: 10.0, top: 10.0, radius: 5.0 };
- assert!(circ2.hit_test(&Point2D::new(10.0, 12.0)));
+ let circ1 = Area::Circle {
+ left: 20.0,
+ top: 10.0,
+ radius: 5.0,
+ };
+ assert!(!circ1.hit_test(&Point2D::new(10.0, 20.0)));
+ let circ2 = Area::Circle {
+ left: 10.0,
+ top: 10.0,
+ radius: 5.0,
+ };
+ assert!(circ2.hit_test(&Point2D::new(10.0, 12.0)));
}
#[test]
fn test_hit_test_rectangle() {
- let rect1 = Area::Rectangle { top_left: (1.0, 7.0), bottom_right: (15.0, 10.0) };
- assert!(!rect1.hit_test(&Point2D::new(10.0, 5.0)));
- let rect2 = Area::Rectangle { top_left: (8.0, 10.0), bottom_right: (20.0, 12.0) };
- assert!(rect2.hit_test(&Point2D::new(10.0, 12.0)));
+ let rect1 = Area::Rectangle {
+ top_left: (1.0, 7.0),
+ bottom_right: (15.0, 10.0),
+ };
+ assert!(!rect1.hit_test(&Point2D::new(10.0, 5.0)));
+ let rect2 = Area::Rectangle {
+ top_left: (8.0, 10.0),
+ bottom_right: (20.0, 12.0),
+ };
+ assert!(rect2.hit_test(&Point2D::new(10.0, 12.0)));
}
#[test]
fn test_hit_test_polygon() {
- let poly1 = Area::Polygon { points: vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0] };
- assert!(!poly1.hit_test(&Point2D::new(10.0, 5.0)));
- let poly2 = Area::Polygon { points: vec![7.0, 7.5, 8.2, 9.0, 11.0, 12.0] };
- assert!(!poly2.hit_test(&Point2D::new(10.0, 5.0)));
+ let poly1 = Area::Polygon {
+ points: vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
+ };
+ assert!(!poly1.hit_test(&Point2D::new(10.0, 5.0)));
+ let poly2 = Area::Polygon {
+ points: vec![7.0, 7.5, 8.2, 9.0, 11.0, 12.0],
+ };
+ assert!(!poly2.hit_test(&Point2D::new(10.0, 5.0)));
}
diff --git a/tests/unit/script/htmlimageelement.rs b/tests/unit/script/htmlimageelement.rs
index 796e63c2e2b..6c38bfa83e2 100644
--- a/tests/unit/script/htmlimageelement.rs
+++ b/tests/unit/script/htmlimageelement.rs
@@ -12,48 +12,104 @@ fn no_value() {
#[test]
fn width_one_value() {
- let first_descriptor = Descriptor { wid: Some(320), den: None };
- let first_imagesource = ImageSource { url: "small-image.jpg".to_string(), descriptor: first_descriptor };
+ let first_descriptor = Descriptor {
+ wid: Some(320),
+ den: None,
+ };
+ let first_imagesource = ImageSource {
+ url: "small-image.jpg".to_string(),
+ descriptor: first_descriptor,
+ };
let sources = &[first_imagesource];
assert_eq!(parse_a_srcset_attribute("small-image.jpg, 320w"), sources);
}
#[test]
fn width_two_value() {
- let first_descriptor = Descriptor { wid: Some(320), den: None };
- let first_imagesource = ImageSource { url: "small-image.jpg".to_string(), descriptor: first_descriptor };
- let second_descriptor = Descriptor { wid: Some(480), den: None };
- let second_imagesource = ImageSource { url: "medium-image.jpg".to_string(), descriptor: second_descriptor };
+ let first_descriptor = Descriptor {
+ wid: Some(320),
+ den: None,
+ };
+ let first_imagesource = ImageSource {
+ url: "small-image.jpg".to_string(),
+ descriptor: first_descriptor,
+ };
+ let second_descriptor = Descriptor {
+ wid: Some(480),
+ den: None,
+ };
+ let second_imagesource = ImageSource {
+ url: "medium-image.jpg".to_string(),
+ descriptor: second_descriptor,
+ };
let sources = &[first_imagesource, second_imagesource];
- assert_eq!(parse_a_srcset_attribute("small-image.jpg 320w, medium-image.jpg 480w"), sources);
+ assert_eq!(
+ parse_a_srcset_attribute("small-image.jpg 320w, medium-image.jpg 480w"),
+ sources
+ );
}
#[test]
fn width_three_value() {
- let first_descriptor = Descriptor { wid: Some(320), den: None };
- let first_imagesource = ImageSource { url: "smallImage.jpg".to_string(), descriptor: first_descriptor };
- let second_descriptor = Descriptor { wid: Some(480), den: None };
- let second_imagesource = ImageSource { url: "mediumImage.jpg".to_string(), descriptor: second_descriptor };
- let third_descriptor = Descriptor { wid: Some(800), den: None };
- let third_imagesource = ImageSource { url: "largeImage.jpg".to_string(), descriptor: third_descriptor };
+ let first_descriptor = Descriptor {
+ wid: Some(320),
+ den: None,
+ };
+ let first_imagesource = ImageSource {
+ url: "smallImage.jpg".to_string(),
+ descriptor: first_descriptor,
+ };
+ let second_descriptor = Descriptor {
+ wid: Some(480),
+ den: None,
+ };
+ let second_imagesource = ImageSource {
+ url: "mediumImage.jpg".to_string(),
+ descriptor: second_descriptor,
+ };
+ let third_descriptor = Descriptor {
+ wid: Some(800),
+ den: None,
+ };
+ let third_imagesource = ImageSource {
+ url: "largeImage.jpg".to_string(),
+ descriptor: third_descriptor,
+ };
let sources = &[first_imagesource, second_imagesource, third_imagesource];
- assert_eq!(parse_a_srcset_attribute("smallImage.jpg 320w,
+ assert_eq!(
+ parse_a_srcset_attribute(
+ "smallImage.jpg 320w,
mediumImage.jpg 480w,
- largeImage.jpg 800w"), sources);
+ largeImage.jpg 800w"
+ ),
+ sources
+ );
}
#[test]
fn density_value() {
- let first_descriptor = Descriptor { wid: None, den: Some(1.0) };
- let first_imagesource = ImageSource { url: "small-image.jpg".to_string(), descriptor: first_descriptor };
+ let first_descriptor = Descriptor {
+ wid: None,
+ den: Some(1.0),
+ };
+ let first_imagesource = ImageSource {
+ url: "small-image.jpg".to_string(),
+ descriptor: first_descriptor,
+ };
let sources = &[first_imagesource];
assert_eq!(parse_a_srcset_attribute("small-image.jpg 1x"), sources);
}
#[test]
fn without_descriptor() {
- let first_descriptor = Descriptor { wid: None, den: None };
- let first_imagesource = ImageSource { url: "small-image.jpg".to_string(), descriptor: first_descriptor };
+ let first_descriptor = Descriptor {
+ wid: None,
+ den: None,
+ };
+ let first_imagesource = ImageSource {
+ url: "small-image.jpg".to_string(),
+ descriptor: first_descriptor,
+ };
let sources = &[first_imagesource];
assert_eq!(parse_a_srcset_attribute("small-image.jpg"), sources);
}
@@ -62,23 +118,47 @@ fn without_descriptor() {
#[test]
fn two_descriptor() {
let empty_vec = Vec::new();
- assert_eq!(parse_a_srcset_attribute("small-image.jpg 320w 1.1x"), empty_vec);
+ assert_eq!(
+ parse_a_srcset_attribute("small-image.jpg 320w 1.1x"),
+ empty_vec
+ );
}
#[test]
fn decimal_descriptor() {
- let first_descriptor = Descriptor { wid: None, den: Some(2.2) };
- let first_imagesource = ImageSource { url: "small-image.jpg".to_string(), descriptor: first_descriptor };
+ let first_descriptor = Descriptor {
+ wid: None,
+ den: Some(2.2),
+ };
+ let first_imagesource = ImageSource {
+ url: "small-image.jpg".to_string(),
+ descriptor: first_descriptor,
+ };
let sources = &[first_imagesource];
assert_eq!(parse_a_srcset_attribute("small-image.jpg 2.2x"), sources);
}
#[test]
fn different_descriptor() {
- let first_descriptor = Descriptor { wid: Some(320), den: None };
- let first_imagesource = ImageSource { url: "small-image.jpg".to_string(), descriptor: first_descriptor };
- let second_descriptor = Descriptor { wid: None, den: Some(2.2) };
- let second_imagesource = ImageSource { url: "medium-image.jpg".to_string(), descriptor: second_descriptor };
+ let first_descriptor = Descriptor {
+ wid: Some(320),
+ den: None,
+ };
+ let first_imagesource = ImageSource {
+ url: "small-image.jpg".to_string(),
+ descriptor: first_descriptor,
+ };
+ let second_descriptor = Descriptor {
+ wid: None,
+ den: Some(2.2),
+ };
+ let second_imagesource = ImageSource {
+ url: "medium-image.jpg".to_string(),
+ descriptor: second_descriptor,
+ };
let sources = &[first_imagesource, second_imagesource];
- assert_eq!(parse_a_srcset_attribute("small-image.jpg 320w, medium-image.jpg 2.2x"), sources);
+ assert_eq!(
+ parse_a_srcset_attribute("small-image.jpg 320w, medium-image.jpg 2.2x"),
+ sources
+ );
}
diff --git a/tests/unit/script/lib.rs b/tests/unit/script/lib.rs
index 157531474d4..0251144dd30 100644
--- a/tests/unit/script/lib.rs
+++ b/tests/unit/script/lib.rs
@@ -2,19 +2,29 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-#[cfg(test)] extern crate euclid;
-#[cfg(test)] extern crate keyboard_types;
-#[cfg(test)] extern crate script;
-#[cfg(test)] extern crate servo_url;
-
-#[cfg(test)] mod origin;
-#[cfg(all(test, target_pointer_width = "64"))] mod size_of;
-#[cfg(test)] mod textinput;
-#[cfg(test)] mod headers;
-#[cfg(test)] mod htmlareaelement;
-#[cfg(test)] mod htmlimageelement;
-#[cfg(test)] mod timeranges;
+#[cfg(test)]
+extern crate euclid;
+#[cfg(test)]
+extern crate keyboard_types;
+#[cfg(test)]
+extern crate script;
+#[cfg(test)]
+extern crate servo_url;
+#[cfg(test)]
+mod headers;
+#[cfg(test)]
+mod htmlareaelement;
+#[cfg(test)]
+mod htmlimageelement;
+#[cfg(test)]
+mod origin;
+#[cfg(all(test, target_pointer_width = "64"))]
+mod size_of;
+#[cfg(test)]
+mod textinput;
+#[cfg(test)]
+mod timeranges;
/**
```compile_fail,E0277
diff --git a/tests/unit/script/origin.rs b/tests/unit/script/origin.rs
index 526b12bf0f9..dc19a984774 100644
--- a/tests/unit/script/origin.rs
+++ b/tests/unit/script/origin.rs
@@ -6,29 +6,57 @@ use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
#[test]
fn same_origin() {
- let a = MutableOrigin::new(ServoUrl::parse("http://example.com/a.html").unwrap().origin());
- let b = MutableOrigin::new(ServoUrl::parse("http://example.com/b.html").unwrap().origin());
+ let a = MutableOrigin::new(
+ ServoUrl::parse("http://example.com/a.html")
+ .unwrap()
+ .origin(),
+ );
+ let b = MutableOrigin::new(
+ ServoUrl::parse("http://example.com/b.html")
+ .unwrap()
+ .origin(),
+ );
assert!(a.same_origin(&b));
assert_eq!(a.is_tuple(), true);
}
#[test]
fn identical_origin() {
- let a = MutableOrigin::new(ServoUrl::parse("http://example.com/a.html").unwrap().origin());
+ let a = MutableOrigin::new(
+ ServoUrl::parse("http://example.com/a.html")
+ .unwrap()
+ .origin(),
+ );
assert!(a.same_origin(&a));
}
#[test]
fn cross_origin() {
- let a = MutableOrigin::new(ServoUrl::parse("http://example.com/a.html").unwrap().origin());
- let b = MutableOrigin::new(ServoUrl::parse("http://example.org/b.html").unwrap().origin());
+ let a = MutableOrigin::new(
+ ServoUrl::parse("http://example.com/a.html")
+ .unwrap()
+ .origin(),
+ );
+ let b = MutableOrigin::new(
+ ServoUrl::parse("http://example.org/b.html")
+ .unwrap()
+ .origin(),
+ );
assert!(!a.same_origin(&b));
}
#[test]
fn clone_same_origin() {
- let a = MutableOrigin::new(ServoUrl::parse("http://example.com/a.html").unwrap().origin());
- let b = MutableOrigin::new(ServoUrl::parse("http://example.com/b.html").unwrap().origin());
+ let a = MutableOrigin::new(
+ ServoUrl::parse("http://example.com/a.html")
+ .unwrap()
+ .origin(),
+ );
+ let b = MutableOrigin::new(
+ ServoUrl::parse("http://example.com/b.html")
+ .unwrap()
+ .origin(),
+ );
let c = b.clone();
assert!(a.same_origin(&c));
assert!(b.same_origin(&b));
@@ -38,8 +66,16 @@ fn clone_same_origin() {
#[test]
fn clone_cross_origin() {
- let a = MutableOrigin::new(ServoUrl::parse("http://example.com/a.html").unwrap().origin());
- let b = MutableOrigin::new(ServoUrl::parse("http://example.org/b.html").unwrap().origin());
+ let a = MutableOrigin::new(
+ ServoUrl::parse("http://example.com/a.html")
+ .unwrap()
+ .origin(),
+ );
+ let b = MutableOrigin::new(
+ ServoUrl::parse("http://example.org/b.html")
+ .unwrap()
+ .origin(),
+ );
let c = b.clone();
assert!(!a.same_origin(&c));
assert!(b.same_origin(&c));
diff --git a/tests/unit/script/textinput.rs b/tests/unit/script/textinput.rs
index 0f4467d81ca..6488542269b 100644
--- a/tests/unit/script/textinput.rs
+++ b/tests/unit/script/textinput.rs
@@ -13,18 +13,25 @@ use script::test::DOMString;
use script::textinput::{TextInput, TextPoint, Selection, Lines, Direction, SelectionDirection};
fn text_input(lines: Lines, s: &str) -> TextInput<DummyClipboardContext> {
- TextInput::new(lines,
- DOMString::from(s),
- DummyClipboardContext::new(""),
- None,
- None,
- SelectionDirection::None)
+ TextInput::new(
+ lines,
+ DOMString::from(s),
+ DummyClipboardContext::new(""),
+ None,
+ None,
+ SelectionDirection::None,
+ )
}
#[test]
fn test_set_content_ignores_max_length() {
let mut textinput = TextInput::new(
- Lines::Single, DOMString::from(""), DummyClipboardContext::new(""), Some(1), None, SelectionDirection::None
+ Lines::Single,
+ DOMString::from(""),
+ DummyClipboardContext::new(""),
+ Some(1),
+ None,
+ SelectionDirection::None,
);
textinput.set_content(DOMString::from("mozilla rocks"));
@@ -64,7 +71,7 @@ fn test_textinput_when_inserting_multiple_lines_still_respects_max_length() {
DummyClipboardContext::new(""),
Some(17),
None,
- SelectionDirection::None
+ SelectionDirection::None,
);
textinput.adjust_vertical(1, Selection::NotSelected);
@@ -74,7 +81,8 @@ fn test_textinput_when_inserting_multiple_lines_still_respects_max_length() {
}
#[test]
-fn test_textinput_when_content_is_already_longer_than_max_length_and_theres_no_selection_dont_insert_anything() {
+fn test_textinput_when_content_is_already_longer_than_max_length_and_theres_no_selection_dont_insert_anything(
+) {
let mut textinput = TextInput::new(
Lines::Single,
DOMString::from("abc"),
@@ -90,7 +98,8 @@ fn test_textinput_when_content_is_already_longer_than_max_length_and_theres_no_s
}
#[test]
-fn test_multi_line_textinput_with_maxlength_doesnt_allow_appending_characters_when_input_spans_lines() {
+fn test_multi_line_textinput_with_maxlength_doesnt_allow_appending_characters_when_input_spans_lines(
+) {
let mut textinput = TextInput::new(
Lines::Multiple,
DOMString::from("abc\nd"),
@@ -106,7 +115,8 @@ fn test_multi_line_textinput_with_maxlength_doesnt_allow_appending_characters_wh
}
#[test]
-fn test_single_line_textinput_with_max_length_doesnt_allow_appending_characters_when_replacing_a_selection() {
+fn test_single_line_textinput_with_max_length_doesnt_allow_appending_characters_when_replacing_a_selection(
+) {
let mut textinput = TextInput::new(
Lines::Single,
DOMString::from("abcde"),
@@ -183,7 +193,8 @@ fn test_single_line_textinput_with_max_length_inside_char() {
}
#[test]
-fn test_single_line_textinput_with_max_length_doesnt_allow_appending_characters_after_max_length_is_reached() {
+fn test_single_line_textinput_with_max_length_doesnt_allow_appending_characters_after_max_length_is_reached(
+) {
let mut textinput = TextInput::new(
Lines::Single,
DOMString::from("a"),
@@ -430,23 +441,39 @@ fn test_navigation_keyboard_shortcuts() {
textinput.handle_keydown_aux(Key::ArrowLeft, Modifiers::META, true);
assert_eq!(textinput.edit_point().index, 0);
// Test that CTRL + ALT + E moves to the end of the current line also.
- textinput.handle_keydown_aux(Key::Character("e".to_owned()), Modifiers::CONTROL | Modifiers::ALT, true);
+ textinput.handle_keydown_aux(
+ Key::Character("e".to_owned()),
+ Modifiers::CONTROL | Modifiers::ALT,
+ true,
+ );
assert_eq!(textinput.edit_point().index, 11);
// Test that CTRL + ALT + A moves to the beginning of the current line also.
- textinput.handle_keydown_aux(Key::Character("a".to_owned()), Modifiers::CONTROL | Modifiers::ALT, true);
+ textinput.handle_keydown_aux(
+ Key::Character("a".to_owned()),
+ Modifiers::CONTROL | Modifiers::ALT,
+ true,
+ );
assert_eq!(textinput.edit_point().index, 0);
// Test that ALT + Right moves to the end of the word.
textinput.handle_keydown_aux(Key::ArrowRight, Modifiers::ALT, true);
assert_eq!(textinput.edit_point().index, 5);
// Test that CTRL + ALT + F moves to the end of the word also.
- textinput.handle_keydown_aux(Key::Character("f".to_owned()), Modifiers::CONTROL | Modifiers::ALT, true);
+ textinput.handle_keydown_aux(
+ Key::Character("f".to_owned()),
+ Modifiers::CONTROL | Modifiers::ALT,
+ true,
+ );
assert_eq!(textinput.edit_point().index, 11);
// Test that ALT + Left moves to the end of the word.
textinput.handle_keydown_aux(Key::ArrowLeft, Modifiers::ALT, true);
assert_eq!(textinput.edit_point().index, 6);
// Test that CTRL + ALT + B moves to the end of the word also.
- textinput.handle_keydown_aux(Key::Character("b".to_owned()), Modifiers::CONTROL | Modifiers::ALT, true);
+ textinput.handle_keydown_aux(
+ Key::Character("b".to_owned()),
+ Modifiers::CONTROL | Modifiers::ALT,
+ true,
+ );
assert_eq!(textinput.edit_point().index, 0);
}
@@ -510,12 +537,14 @@ fn test_clipboard_paste() {
#[cfg(not(target_os = "macos"))]
const MODIFIERS: Modifiers = Modifiers::CONTROL;
- let mut textinput = TextInput::new(Lines::Single,
- DOMString::from("defg"),
- DummyClipboardContext::new("abc"),
- None,
- None,
- SelectionDirection::None);
+ let mut textinput = TextInput::new(
+ Lines::Single,
+ DOMString::from("defg"),
+ DummyClipboardContext::new("abc"),
+ None,
+ None,
+ SelectionDirection::None,
+ );
assert_eq!(textinput.get_content(), "defg");
assert_eq!(textinput.edit_point().index, 0);
textinput.handle_keydown_aux(Key::Character("v".to_owned()), MODIFIERS, false);
@@ -547,7 +576,6 @@ fn test_textinput_cursor_position_correct_after_clearing_selection() {
textinput.adjust_horizontal_by_one(Direction::Backward, Selection::NotSelected);
assert_eq!(textinput.edit_point().index, 0);
-
let mut textinput = text_input(Lines::Multiple, "abc\nde\nf");
// Multiline - Forward
@@ -576,7 +604,6 @@ fn test_textinput_cursor_position_correct_after_clearing_selection() {
assert_eq!(textinput.edit_point().line, 0);
}
-
#[test]
fn test_textinput_set_selection_with_direction() {
let mut textinput = text_input(Lines::Single, "abcdef");
@@ -592,7 +619,10 @@ fn test_textinput_set_selection_with_direction() {
textinput.set_selection_range(2, 6, SelectionDirection::Backward);
assert_eq!(textinput.edit_point().line, 0);
assert_eq!(textinput.edit_point().index, 2);
- assert_eq!(textinput.selection_direction(), SelectionDirection::Backward);
+ assert_eq!(
+ textinput.selection_direction(),
+ SelectionDirection::Backward
+ );
assert!(textinput.selection_origin().is_some());
assert_eq!(textinput.selection_origin().unwrap().line, 0);
@@ -617,7 +647,6 @@ fn test_textinput_set_selection_with_direction() {
assert!(textinput.selection_origin().is_some());
assert_eq!(textinput.selection_origin().unwrap().line, 0);
assert_eq!(textinput.selection_origin().unwrap().index, 0);
-
}
#[test]
@@ -634,19 +663,28 @@ fn test_textinput_unicode_handling() {
fn test_selection_bounds() {
let mut textinput = text_input(Lines::Single, "abcdef");
- assert_eq!(TextPoint { line: 0, index: 0 }, textinput.selection_origin_or_edit_point());
+ assert_eq!(
+ TextPoint { line: 0, index: 0 },
+ textinput.selection_origin_or_edit_point()
+ );
assert_eq!(TextPoint { line: 0, index: 0 }, textinput.selection_start());
assert_eq!(TextPoint { line: 0, index: 0 }, textinput.selection_end());
textinput.set_selection_range(2, 5, SelectionDirection::Forward);
- assert_eq!(TextPoint { line: 0, index: 2 }, textinput.selection_origin_or_edit_point());
+ assert_eq!(
+ TextPoint { line: 0, index: 2 },
+ textinput.selection_origin_or_edit_point()
+ );
assert_eq!(TextPoint { line: 0, index: 2 }, textinput.selection_start());
assert_eq!(TextPoint { line: 0, index: 5 }, textinput.selection_end());
assert_eq!(2, textinput.selection_start_offset());
assert_eq!(5, textinput.selection_end_offset());
textinput.set_selection_range(3, 6, SelectionDirection::Backward);
- assert_eq!(TextPoint { line: 0, index: 6 }, textinput.selection_origin_or_edit_point());
+ assert_eq!(
+ TextPoint { line: 0, index: 6 },
+ textinput.selection_origin_or_edit_point()
+ );
assert_eq!(TextPoint { line: 0, index: 3 }, textinput.selection_start());
assert_eq!(TextPoint { line: 0, index: 6 }, textinput.selection_end());
assert_eq!(3, textinput.selection_start_offset());
@@ -654,8 +692,10 @@ fn test_selection_bounds() {
textinput = text_input(Lines::Multiple, "\n\n");
textinput.set_selection_range(0, 1, SelectionDirection::Forward);
- assert_eq!(TextPoint { line: 0, index: 0 }, textinput.selection_origin_or_edit_point());
+ assert_eq!(
+ TextPoint { line: 0, index: 0 },
+ textinput.selection_origin_or_edit_point()
+ );
assert_eq!(TextPoint { line: 0, index: 0 }, textinput.selection_start());
assert_eq!(TextPoint { line: 1, index: 0 }, textinput.selection_end());
-
}
diff --git a/tests/unit/script_plugins/lib.rs b/tests/unit/script_plugins/lib.rs
index 35a1c0dff11..f27a16f2e32 100644
--- a/tests/unit/script_plugins/lib.rs
+++ b/tests/unit/script_plugins/lib.rs
@@ -7,13 +7,13 @@ pub mod unrooted_must_root {
```
#![feature(plugin)]
#![plugin(script_plugins)]
-
+
#[must_root] struct Foo(i32);
#[must_root] struct Bar(Foo);
-
+
fn foo1(_: &Foo) {}
fn foo2(_: &()) -> &Foo { unimplemented!() }
-
+
fn main() {}
```
*/
@@ -23,10 +23,10 @@ pub mod unrooted_must_root {
```compile_fail
#![feature(plugin)]
#![plugin(script_plugins)]
-
+
#[must_root] struct Foo(i32);
struct Bar(Foo);
-
+
fn main() {}
```
*/
@@ -36,11 +36,11 @@ pub mod unrooted_must_root {
```compile_fail
#![feature(plugin)]
#![plugin(script_plugins)]
-
+
#[must_root] struct Foo(i32);
-
+
fn foo1(_: Foo) {}
-
+
fn main() {}
```
*/
@@ -50,11 +50,11 @@ pub mod unrooted_must_root {
```compile_fail
#![feature(plugin)]
#![plugin(script_plugins)]
-
+
#[must_root] struct Foo(i32);
-
+
fn foo2() -> Foo { unimplemented!() }
-
+
fn main() {}
```
*/
diff --git a/tests/unit/style/animated_properties.rs b/tests/unit/style/animated_properties.rs
index a884321369f..5eae2be7273 100644
--- a/tests/unit/style/animated_properties.rs
+++ b/tests/unit/style/animated_properties.rs
@@ -11,53 +11,76 @@ fn interpolate_rgba(from: RGBA, to: RGBA, progress: f64) -> RGBA {
let from = from.to_animated_value();
let to = to.to_animated_value();
RGBA::from_animated_value(
- from.animate(&to, Procedure::Interpolate { progress }).unwrap(),
+ from.animate(&to, Procedure::Interpolate { progress })
+ .unwrap(),
)
}
// Color
#[test]
fn test_rgba_color_interepolation_preserves_transparent() {
- assert_eq!(interpolate_rgba(RGBA::transparent(),
- RGBA::transparent(), 0.5),
- RGBA::transparent());
+ assert_eq!(
+ interpolate_rgba(RGBA::transparent(), RGBA::transparent(), 0.5),
+ RGBA::transparent()
+ );
}
#[test]
fn test_rgba_color_interepolation_alpha() {
- assert_eq!(interpolate_rgba(RGBA::new(200, 0, 0, 100),
- RGBA::new(0, 200, 0, 200), 0.5),
- RGBA::new(67, 133, 0, 150));
+ assert_eq!(
+ interpolate_rgba(RGBA::new(200, 0, 0, 100), RGBA::new(0, 200, 0, 200), 0.5),
+ RGBA::new(67, 133, 0, 150)
+ );
}
#[test]
fn test_rgba_color_interepolation_out_of_range_1() {
// Some cubic-bezier functions produce values that are out of range [0, 1].
// Unclamped cases.
- assert_eq!(interpolate_rgba(RGBA::from_floats(0.3, 0.0, 0.0, 0.4),
- RGBA::from_floats(0.0, 1.0, 0.0, 0.6), -0.5),
- RGBA::new(154, 0, 0, 77));
+ assert_eq!(
+ interpolate_rgba(
+ RGBA::from_floats(0.3, 0.0, 0.0, 0.4),
+ RGBA::from_floats(0.0, 1.0, 0.0, 0.6),
+ -0.5
+ ),
+ RGBA::new(154, 0, 0, 77)
+ );
}
#[test]
fn test_rgba_color_interepolation_out_of_range_2() {
- assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.6),
- RGBA::from_floats(0.0, 0.3, 0.0, 0.4), 1.5),
- RGBA::new(0, 154, 0, 77));
+ assert_eq!(
+ interpolate_rgba(
+ RGBA::from_floats(1.0, 0.0, 0.0, 0.6),
+ RGBA::from_floats(0.0, 0.3, 0.0, 0.4),
+ 1.5
+ ),
+ RGBA::new(0, 154, 0, 77)
+ );
}
#[test]
fn test_rgba_color_interepolation_out_of_range_clamped_1() {
- assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.8),
- RGBA::from_floats(0.0, 1.0, 0.0, 0.2), -0.5),
- RGBA::from_floats(1.0, 0.0, 0.0, 1.0));
+ assert_eq!(
+ interpolate_rgba(
+ RGBA::from_floats(1.0, 0.0, 0.0, 0.8),
+ RGBA::from_floats(0.0, 1.0, 0.0, 0.2),
+ -0.5
+ ),
+ RGBA::from_floats(1.0, 0.0, 0.0, 1.0)
+ );
}
#[test]
fn test_rgba_color_interepolation_out_of_range_clamped_2() {
- assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.8),
- RGBA::from_floats(0.0, 1.0, 0.0, 0.2), 1.5),
- RGBA::from_floats(0.0, 0.0, 0.0, 0.0));
+ assert_eq!(
+ interpolate_rgba(
+ RGBA::from_floats(1.0, 0.0, 0.0, 0.8),
+ RGBA::from_floats(0.0, 1.0, 0.0, 0.2),
+ 1.5
+ ),
+ RGBA::from_floats(0.0, 0.0, 0.0, 0.0)
+ );
}
// Transform
@@ -65,16 +88,19 @@ fn test_rgba_color_interepolation_out_of_range_clamped_2() {
fn test_transform_interpolation_on_translate() {
use style::values::computed::{CalcLengthOrPercentage, Length, LengthOrPercentage};
- let from = Transform(vec![
- TransformOperation::Translate3D(LengthOrPercentage::Length(Length::new(0.)),
- LengthOrPercentage::Length(Length::new(100.)),
- Length::new(25.))]);
- let to = Transform(vec![
- TransformOperation::Translate3D(LengthOrPercentage::Length(Length::new(100.)),
- LengthOrPercentage::Length(Length::new(0.)),
- Length::new(75.))]);
+ let from = Transform(vec![TransformOperation::Translate3D(
+ LengthOrPercentage::Length(Length::new(0.)),
+ LengthOrPercentage::Length(Length::new(100.)),
+ Length::new(25.),
+ )]);
+ let to = Transform(vec![TransformOperation::Translate3D(
+ LengthOrPercentage::Length(Length::new(100.)),
+ LengthOrPercentage::Length(Length::new(0.)),
+ Length::new(75.),
+ )]);
assert_eq!(
- from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(),
+ from.animate(&to, Procedure::Interpolate { progress: 0.5 })
+ .unwrap(),
Transform(vec![TransformOperation::Translate3D(
LengthOrPercentage::Length(Length::new(50.)),
LengthOrPercentage::Length(Length::new(50.)),
@@ -87,19 +113,25 @@ fn test_transform_interpolation_on_translate() {
LengthOrPercentage::Percentage(Percentage(1.0)),
Length::new(25.),
)]);
- let to = Transform(vec![
- TransformOperation::Translate3D(LengthOrPercentage::Length(Length::new(100.)),
- LengthOrPercentage::Length(Length::new(50.)),
- Length::new(75.))]);
+ let to = Transform(vec![TransformOperation::Translate3D(
+ LengthOrPercentage::Length(Length::new(100.)),
+ LengthOrPercentage::Length(Length::new(50.)),
+ Length::new(75.),
+ )]);
assert_eq!(
- from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(),
+ from.animate(&to, Procedure::Interpolate { progress: 0.5 })
+ .unwrap(),
Transform(vec![TransformOperation::Translate3D(
// calc(50px + 25%)
- LengthOrPercentage::Calc(CalcLengthOrPercentage::new(Length::new(50.),
- Some(Percentage(0.25)))),
+ LengthOrPercentage::Calc(CalcLengthOrPercentage::new(
+ Length::new(50.),
+ Some(Percentage(0.25))
+ )),
// calc(25px + 50%)
- LengthOrPercentage::Calc(CalcLengthOrPercentage::new(Length::new(25.),
- Some(Percentage(0.5)))),
+ LengthOrPercentage::Calc(CalcLengthOrPercentage::new(
+ Length::new(25.),
+ Some(Percentage(0.5))
+ )),
Length::new(50.),
)])
);
@@ -110,7 +142,8 @@ fn test_transform_interpolation_on_scale() {
let from = Transform(vec![TransformOperation::Scale3D(1.0, 2.0, 1.0)]);
let to = Transform(vec![TransformOperation::Scale3D(2.0, 4.0, 2.0)]);
assert_eq!(
- from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(),
+ from.animate(&to, Procedure::Interpolate { progress: 0.5 })
+ .unwrap(),
Transform(vec![TransformOperation::Scale3D(1.5, 3.0, 1.5)])
);
}
@@ -119,15 +152,27 @@ fn test_transform_interpolation_on_scale() {
fn test_transform_interpolation_on_rotate() {
use style::values::computed::Angle;
- let from = Transform(vec![TransformOperation::Rotate3D(0.0, 0.0, 1.0,
- Angle::from_radians(0.0))]);
- let to = Transform(vec![TransformOperation::Rotate3D(0.0, 0.0, 1.0,
- Angle::from_radians(100.0))]);
+ let from = Transform(vec![TransformOperation::Rotate3D(
+ 0.0,
+ 0.0,
+ 1.0,
+ Angle::from_radians(0.0),
+ )]);
+ let to = Transform(vec![TransformOperation::Rotate3D(
+ 0.0,
+ 0.0,
+ 1.0,
+ Angle::from_radians(100.0),
+ )]);
assert_eq!(
- from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(),
- Transform(vec![
- TransformOperation::Rotate3D(0.0, 0.0, 1.0, Angle::from_radians(50.0)),
- ])
+ from.animate(&to, Procedure::Interpolate { progress: 0.5 })
+ .unwrap(),
+ Transform(vec![TransformOperation::Rotate3D(
+ 0.0,
+ 0.0,
+ 1.0,
+ Angle::from_radians(50.0)
+ )])
);
}
@@ -135,12 +180,17 @@ fn test_transform_interpolation_on_rotate() {
fn test_transform_interpolation_on_skew() {
use style::values::computed::Angle;
- let from = Transform(vec![TransformOperation::Skew(Angle::from_radians(0.0),
- Some(Angle::from_radians(100.0)))]);
- let to = Transform(vec![TransformOperation::Skew(Angle::from_radians(100.0),
- Some(Angle::from_radians(0.0)))]);
+ let from = Transform(vec![TransformOperation::Skew(
+ Angle::from_radians(0.0),
+ Some(Angle::from_radians(100.0)),
+ )]);
+ let to = Transform(vec![TransformOperation::Skew(
+ Angle::from_radians(100.0),
+ Some(Angle::from_radians(0.0)),
+ )]);
assert_eq!(
- from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(),
+ from.animate(&to, Procedure::Interpolate { progress: 0.5 })
+ .unwrap(),
Transform(vec![TransformOperation::Skew(
Angle::from_radians(50.0),
Some(Angle::from_radians(50.0)),
@@ -152,14 +202,20 @@ fn test_transform_interpolation_on_skew() {
fn test_transform_interpolation_on_mismatched_lists() {
use style::values::computed::{Angle, Length, LengthOrPercentage};
- let from = Transform(vec![TransformOperation::Rotate3D(0.0, 0.0, 1.0,
- Angle::from_radians(100.0))]);
- let to = Transform(vec![
- TransformOperation::Translate3D(LengthOrPercentage::Length(Length::new(100.)),
- LengthOrPercentage::Length(Length::new(0.)),
- Length::new(0.))]);
+ let from = Transform(vec![TransformOperation::Rotate3D(
+ 0.0,
+ 0.0,
+ 1.0,
+ Angle::from_radians(100.0),
+ )]);
+ let to = Transform(vec![TransformOperation::Translate3D(
+ LengthOrPercentage::Length(Length::new(100.)),
+ LengthOrPercentage::Length(Length::new(0.)),
+ Length::new(0.),
+ )]);
assert_eq!(
- from.animate(&to, Procedure::Interpolate { progress: 0.5 }).unwrap(),
+ from.animate(&to, Procedure::Interpolate { progress: 0.5 })
+ .unwrap(),
Transform(vec![TransformOperation::InterpolateMatrix {
from_list: from.clone(),
to_list: to.clone(),
diff --git a/tests/unit/style/attr.rs b/tests/unit/style/attr.rs
index 9fc56ff82bb..c0bcc87d28f 100644
--- a/tests/unit/style/attr.rs
+++ b/tests/unit/style/attr.rs
@@ -23,7 +23,7 @@ fn test_parse_double() {
let value = String::from("432.5e2");
match AttrValue::from_double(value, 0.0) {
AttrValue::Double(_, num) => assert_eq!(num, 43250f64),
- _ => panic!("expected a double value")
+ _ => panic!("expected a double value"),
}
}
@@ -32,7 +32,7 @@ fn test_parse_double_negative_prefix() {
let value = String::from("-5.6");
match AttrValue::from_double(value, 0.0) {
AttrValue::Double(_, num) => assert_eq!(num, -5.6f64),
- _ => panic!("expected a double value")
+ _ => panic!("expected a double value"),
}
}
@@ -41,7 +41,7 @@ fn test_parse_double_positive_prefix() {
let value = String::from("+5.6");
match AttrValue::from_double(value, 0.0) {
AttrValue::Double(_, num) => assert_eq!(num, 5.6f64),
- _ => panic!("expected a double value")
+ _ => panic!("expected a double value"),
}
}
@@ -50,7 +50,7 @@ fn test_from_limited_i32_should_be_default_when_less_than_0() {
let value = String::from("-1");
match AttrValue::from_limited_i32(value, 0) {
AttrValue::Int(_, 0) => (),
- _ => panic!("expected an IndexSize error")
+ _ => panic!("expected an IndexSize error"),
}
}
@@ -58,17 +58,15 @@ fn test_from_limited_i32_should_be_default_when_less_than_0() {
fn test_from_limited_i32_should_parse_a_uint_when_value_is_0_or_greater() {
match AttrValue::from_limited_i32(String::from("1"), 0) {
AttrValue::Int(_, 1) => (),
- _ => panic!("expected an successful parsing")
+ _ => panic!("expected an successful parsing"),
}
}
#[test]
fn test_from_limited_i32_should_keep_parsed_value_when_not_an_int() {
match AttrValue::from_limited_i32(String::from("parsed-value"), 0) {
- AttrValue::Int(p, 0) => {
- assert_eq!(p, String::from("parsed-value"))
- },
- _ => panic!("expected an successful parsing")
+ AttrValue::Int(p, 0) => assert_eq!(p, String::from("parsed-value")),
+ _ => panic!("expected an successful parsing"),
}
}
@@ -82,7 +80,13 @@ pub fn test_parse_length() {
check("0", LengthOrPercentageOrAuto::Length(Au::from_px(0)));
check("0.000%", LengthOrPercentageOrAuto::Percentage(0.0));
check("+5.82%", LengthOrPercentageOrAuto::Percentage(0.0582));
- check("5.82", LengthOrPercentageOrAuto::Length(Au::from_f64_px(5.82)));
+ check(
+ "5.82",
+ LengthOrPercentageOrAuto::Length(Au::from_f64_px(5.82)),
+ );
check("invalid", LengthOrPercentageOrAuto::Auto);
- check("12 followed by invalid", LengthOrPercentageOrAuto::Length(Au::from_px(12)));
+ check(
+ "12 followed by invalid",
+ LengthOrPercentageOrAuto::Length(Au::from_px(12)),
+ );
}
diff --git a/tests/unit/style/custom_properties.rs b/tests/unit/style/custom_properties.rs
index aeefe6e19b9..e9b4399b1b7 100644
--- a/tests/unit/style/custom_properties.rs
+++ b/tests/unit/style/custom_properties.rs
@@ -12,11 +12,17 @@ fn cascade(
name_and_value: &[(&str, &str)],
inherited: Option<&Arc<CustomPropertiesMap>>,
) -> Option<Arc<CustomPropertiesMap>> {
- let values = name_and_value.iter().map(|&(name, value)| {
- let mut input = ParserInput::new(value);
- let mut parser = Parser::new(&mut input);
- (Name::from(name), SpecifiedValue::parse(&mut parser).unwrap())
- }).collect::<Vec<_>>();
+ let values = name_and_value
+ .iter()
+ .map(|&(name, value)| {
+ let mut input = ParserInput::new(value);
+ let mut parser = Parser::new(&mut input);
+ (
+ Name::from(name),
+ SpecifiedValue::parse(&mut parser).unwrap(),
+ )
+ })
+ .collect::<Vec<_>>();
let env = CssEnvironment;
let mut builder = CustomPropertiesBuilder::new(inherited, &env);
@@ -31,14 +37,11 @@ fn cascade(
#[bench]
fn cascade_custom_simple(b: &mut Bencher) {
b.iter(|| {
- let parent = cascade(&[
- ("foo", "10px"),
- ("bar", "100px"),
- ], None);
+ let parent = cascade(&[("foo", "10px"), ("bar", "100px")], None);
- test::black_box(cascade(&[
- ("baz", "calc(40em + 4px)"),
- ("bazz", "calc(30em + 4px)"),
- ], parent.as_ref()))
+ test::black_box(cascade(
+ &[("baz", "calc(40em + 4px)"), ("bazz", "calc(30em + 4px)")],
+ parent.as_ref(),
+ ))
})
}
diff --git a/tests/unit/style/lib.rs b/tests/unit/style/lib.rs
index f9fe10dbaae..a48fc9826ce 100644
--- a/tests/unit/style/lib.rs
+++ b/tests/unit/style/lib.rs
@@ -8,7 +8,8 @@
extern crate app_units;
extern crate cssparser;
extern crate euclid;
-#[macro_use] extern crate html5ever;
+#[macro_use]
+extern crate html5ever;
extern crate parking_lot;
extern crate rayon;
extern crate selectors;
@@ -17,8 +18,10 @@ extern crate servo_arc;
extern crate servo_atoms;
extern crate servo_config;
extern crate servo_url;
-#[macro_use] extern crate size_of_test;
-#[macro_use] extern crate style;
+#[macro_use]
+extern crate size_of_test;
+#[macro_use]
+extern crate style;
extern crate style_traits;
extern crate test;
diff --git a/tests/unit/style/parsing/animation.rs b/tests/unit/style/parsing/animation.rs
index 4984e2035a9..c138a51a1c4 100644
--- a/tests/unit/style/parsing/animation.rs
+++ b/tests/unit/style/parsing/animation.rs
@@ -14,14 +14,22 @@ use style_traits::ToCss;
fn test_animation_name() {
use self::animation_name::single_value::SpecifiedValue as SingleValue;
let other_name = Atom::from("other-name");
- assert_eq!(parse_longhand!(animation_name, "none"),
- animation_name::SpecifiedValue(vec![SingleValue(None)]));
- assert_eq!(parse_longhand!(animation_name, "other-name, none, 'other-name', \"other-name\""),
- animation_name::SpecifiedValue(
- vec![SingleValue(Some(KeyframesName::Ident(CustomIdent(other_name.clone())))),
- SingleValue(None),
- SingleValue(Some(KeyframesName::QuotedString(other_name.clone()))),
- SingleValue(Some(KeyframesName::QuotedString(other_name.clone())))]));
+ assert_eq!(
+ parse_longhand!(animation_name, "none"),
+ animation_name::SpecifiedValue(vec![SingleValue(None)])
+ );
+ assert_eq!(
+ parse_longhand!(
+ animation_name,
+ "other-name, none, 'other-name', \"other-name\""
+ ),
+ animation_name::SpecifiedValue(vec![
+ SingleValue(Some(KeyframesName::Ident(CustomIdent(other_name.clone())))),
+ SingleValue(None),
+ SingleValue(Some(KeyframesName::QuotedString(other_name.clone()))),
+ SingleValue(Some(KeyframesName::QuotedString(other_name.clone())))
+ ])
+ );
}
#[test]
diff --git a/tests/unit/style/parsing/background.rs b/tests/unit/style/parsing/background.rs
index dd47e4d1a9e..2afb894ecf8 100644
--- a/tests/unit/style/parsing/background.rs
+++ b/tests/unit/style/parsing/background.rs
@@ -13,72 +13,179 @@ fn background_shorthand_should_parse_all_available_properties_when_specified() {
let input = "url(\"http://servo/test.png\") top center / 200px 200px repeat-x fixed padding-box content-box red";
let result = parse(background::parse_value, input).unwrap();
- assert_eq!(result.background_image, parse_longhand!(background_image, "url(\"http://servo/test.png\")"));
- assert_eq!(result.background_position_x, parse_longhand!(background_position_x, "center"));
- assert_eq!(result.background_position_y, parse_longhand!(background_position_y, "top"));
- assert_eq!(result.background_size, parse_longhand!(background_size, "200px 200px"));
- assert_eq!(result.background_repeat, parse_longhand!(background_repeat, "repeat-x"));
- assert_eq!(result.background_attachment, parse_longhand!(background_attachment, "fixed"));
- assert_eq!(result.background_origin, parse_longhand!(background_origin, "padding-box"));
- assert_eq!(result.background_clip, parse_longhand!(background_clip, "content-box"));
- assert_eq!(result.background_color, parse_longhand!(background_color, "red"));
+ assert_eq!(
+ result.background_image,
+ parse_longhand!(background_image, "url(\"http://servo/test.png\")")
+ );
+ assert_eq!(
+ result.background_position_x,
+ parse_longhand!(background_position_x, "center")
+ );
+ assert_eq!(
+ result.background_position_y,
+ parse_longhand!(background_position_y, "top")
+ );
+ assert_eq!(
+ result.background_size,
+ parse_longhand!(background_size, "200px 200px")
+ );
+ assert_eq!(
+ result.background_repeat,
+ parse_longhand!(background_repeat, "repeat-x")
+ );
+ assert_eq!(
+ result.background_attachment,
+ parse_longhand!(background_attachment, "fixed")
+ );
+ assert_eq!(
+ result.background_origin,
+ parse_longhand!(background_origin, "padding-box")
+ );
+ assert_eq!(
+ result.background_clip,
+ parse_longhand!(background_clip, "content-box")
+ );
+ assert_eq!(
+ result.background_color,
+ parse_longhand!(background_color, "red")
+ );
}
#[test]
fn background_shorthand_should_parse_when_some_fields_set() {
let result = parse(background::parse_value, "14px 40px repeat-y").unwrap();
- assert_eq!(result.background_position_x, parse_longhand!(background_position_x, "14px"));
- assert_eq!(result.background_position_y, parse_longhand!(background_position_y, "40px"));
- assert_eq!(result.background_repeat, parse_longhand!(background_repeat, "repeat-y"));
-
- let result = parse(background::parse_value, "url(\"http://servo/test.png\") repeat blue").unwrap();
-
- assert_eq!(result.background_image, parse_longhand!(background_image, "url(\"http://servo/test.png\")"));
- assert_eq!(result.background_repeat, parse_longhand!(background_repeat, "repeat"));
- assert_eq!(result.background_color, parse_longhand!(background_color, "blue"));
+ assert_eq!(
+ result.background_position_x,
+ parse_longhand!(background_position_x, "14px")
+ );
+ assert_eq!(
+ result.background_position_y,
+ parse_longhand!(background_position_y, "40px")
+ );
+ assert_eq!(
+ result.background_repeat,
+ parse_longhand!(background_repeat, "repeat-y")
+ );
+
+ let result = parse(
+ background::parse_value,
+ "url(\"http://servo/test.png\") repeat blue",
+ )
+ .unwrap();
+
+ assert_eq!(
+ result.background_image,
+ parse_longhand!(background_image, "url(\"http://servo/test.png\")")
+ );
+ assert_eq!(
+ result.background_repeat,
+ parse_longhand!(background_repeat, "repeat")
+ );
+ assert_eq!(
+ result.background_color,
+ parse_longhand!(background_color, "blue")
+ );
let result = parse(background::parse_value, "padding-box").unwrap();
- assert_eq!(result.background_origin, parse_longhand!(background_origin, "padding-box"));
- assert_eq!(result.background_clip, parse_longhand!(background_clip, "padding-box"));
+ assert_eq!(
+ result.background_origin,
+ parse_longhand!(background_origin, "padding-box")
+ );
+ assert_eq!(
+ result.background_clip,
+ parse_longhand!(background_clip, "padding-box")
+ );
let result = parse(background::parse_value, "url(\"http://servo/test.png\")").unwrap();
- assert_eq!(result.background_image, parse_longhand!(background_image, "url(\"http://servo/test.png\")"));
+ assert_eq!(
+ result.background_image,
+ parse_longhand!(background_image, "url(\"http://servo/test.png\")")
+ );
}
#[test]
fn background_shorthand_should_parse_comma_separated_declarations() {
- let input = "url(\"http://servo/test.png\") top left no-repeat, url(\"http://servo/test.png\") \
- center / 100% 100% no-repeat, white";
+ let input =
+ "url(\"http://servo/test.png\") top left no-repeat, url(\"http://servo/test.png\") \
+ center / 100% 100% no-repeat, white";
let result = parse(background::parse_value, input).unwrap();
- assert_eq!(result.background_image, parse_longhand!(background_image, "url(\"http://servo/test.png\"), \
- url(\"http://servo/test.png\"), none"));
- assert_eq!(result.background_position_x, parse_longhand!(background_position_x, "left, center, 0%"));
- assert_eq!(result.background_position_y, parse_longhand!(background_position_y, "top, center, 0%"));
- assert_eq!(result.background_repeat, parse_longhand!(background_repeat, "no-repeat, no-repeat, repeat"));
- assert_eq!(result.background_clip, parse_longhand!(background_clip, "border-box, border-box, border-box"));
- assert_eq!(result.background_origin, parse_longhand!(background_origin, "padding-box, padding-box, \
- padding-box"));
- assert_eq!(result.background_size, parse_longhand!(background_size, "auto auto, 100% 100%, auto auto"));
- assert_eq!(result.background_attachment, parse_longhand!(background_attachment, "scroll, scroll, scroll"));
- assert_eq!(result.background_color, parse_longhand!(background_color, "white"));
+ assert_eq!(
+ result.background_image,
+ parse_longhand!(
+ background_image,
+ "url(\"http://servo/test.png\"), \
+ url(\"http://servo/test.png\"), none"
+ )
+ );
+ assert_eq!(
+ result.background_position_x,
+ parse_longhand!(background_position_x, "left, center, 0%")
+ );
+ assert_eq!(
+ result.background_position_y,
+ parse_longhand!(background_position_y, "top, center, 0%")
+ );
+ assert_eq!(
+ result.background_repeat,
+ parse_longhand!(background_repeat, "no-repeat, no-repeat, repeat")
+ );
+ assert_eq!(
+ result.background_clip,
+ parse_longhand!(background_clip, "border-box, border-box, border-box")
+ );
+ assert_eq!(
+ result.background_origin,
+ parse_longhand!(
+ background_origin,
+ "padding-box, padding-box, \
+ padding-box"
+ )
+ );
+ assert_eq!(
+ result.background_size,
+ parse_longhand!(background_size, "auto auto, 100% 100%, auto auto")
+ );
+ assert_eq!(
+ result.background_attachment,
+ parse_longhand!(background_attachment, "scroll, scroll, scroll")
+ );
+ assert_eq!(
+ result.background_color,
+ parse_longhand!(background_color, "white")
+ );
}
#[test]
fn background_shorthand_should_parse_position_and_size_correctly() {
let result = parse(background::parse_value, "7px 4px").unwrap();
- assert_eq!(result.background_position_x, parse_longhand!(background_position_x, "7px"));
- assert_eq!(result.background_position_y, parse_longhand!(background_position_y, "4px"));
+ assert_eq!(
+ result.background_position_x,
+ parse_longhand!(background_position_x, "7px")
+ );
+ assert_eq!(
+ result.background_position_y,
+ parse_longhand!(background_position_y, "4px")
+ );
let result = parse(background::parse_value, "7px 4px / 30px 20px").unwrap();
- assert_eq!(result.background_position_x, parse_longhand!(background_position_x, "7px"));
- assert_eq!(result.background_position_y, parse_longhand!(background_position_y, "4px"));
- assert_eq!(result.background_size, parse_longhand!(background_size, "30px 20px"));
+ assert_eq!(
+ result.background_position_x,
+ parse_longhand!(background_position_x, "7px")
+ );
+ assert_eq!(
+ result.background_position_y,
+ parse_longhand!(background_position_y, "4px")
+ );
+ assert_eq!(
+ result.background_size,
+ parse_longhand!(background_size, "30px 20px")
+ );
assert!(parse(background::parse_value, "/ 30px 20px").is_err());
@@ -89,16 +196,34 @@ fn background_shorthand_should_parse_position_and_size_correctly() {
fn background_shorthand_should_parse_origin_and_clip_correctly() {
let result = parse(background::parse_value, "padding-box content-box").unwrap();
- assert_eq!(result.background_origin, parse_longhand!(background_origin, "padding-box"));
- assert_eq!(result.background_clip, parse_longhand!(background_clip, "content-box"));
+ assert_eq!(
+ result.background_origin,
+ parse_longhand!(background_origin, "padding-box")
+ );
+ assert_eq!(
+ result.background_clip,
+ parse_longhand!(background_clip, "content-box")
+ );
let result = parse(background::parse_value, "padding-box padding-box").unwrap();
- assert_eq!(result.background_origin, parse_longhand!(background_origin, "padding-box"));
- assert_eq!(result.background_clip, parse_longhand!(background_clip, "padding-box"));
+ assert_eq!(
+ result.background_origin,
+ parse_longhand!(background_origin, "padding-box")
+ );
+ assert_eq!(
+ result.background_clip,
+ parse_longhand!(background_clip, "padding-box")
+ );
let result = parse(background::parse_value, "padding-box").unwrap();
- assert_eq!(result.background_origin, parse_longhand!(background_origin, "padding-box"));
- assert_eq!(result.background_clip, parse_longhand!(background_clip, "padding-box"));
+ assert_eq!(
+ result.background_origin,
+ parse_longhand!(background_origin, "padding-box")
+ );
+ assert_eq!(
+ result.background_clip,
+ parse_longhand!(background_clip, "padding-box")
+ );
}
diff --git a/tests/unit/style/parsing/border.rs b/tests/unit/style/parsing/border.rs
index 0eadbec4f31..635e3c60a71 100644
--- a/tests/unit/style/parsing/border.rs
+++ b/tests/unit/style/parsing/border.rs
@@ -13,31 +13,60 @@ use style_traits::ToCss;
macro_rules! assert_longhand {
($parsed_shorthand: expr, $prop: ident, $value_string: expr) => {
- assert_eq!($parsed_shorthand.$prop, parse_longhand!($prop, $value_string).maybe_boxed())
- }
+ assert_eq!(
+ $parsed_shorthand.$prop,
+ parse_longhand!($prop, $value_string).maybe_boxed()
+ )
+ };
}
macro_rules! assert_initial {
($parsed_shorthand: expr, $prop: ident) => {
- assert_eq!($parsed_shorthand.$prop, $prop::get_initial_specified_value().maybe_boxed())
- }
+ assert_eq!(
+ $parsed_shorthand.$prop,
+ $prop::get_initial_specified_value().maybe_boxed()
+ )
+ };
}
macro_rules! assert_border_radius_values {
($input:expr; $tlw:expr, $trw:expr, $brw:expr, $blw:expr ;
$tlh:expr, $trh:expr, $brh:expr, $blh:expr) => {
let input = parse(BorderRadius::parse, $input)
- .expect(&format!("Failed parsing {} as border radius",
- $input));
- assert_eq!(::style_traits::ToCss::to_css_string(&input.top_left.0.width()), $tlw);
- assert_eq!(::style_traits::ToCss::to_css_string(&input.top_right.0.width()), $trw);
- assert_eq!(::style_traits::ToCss::to_css_string(&input.bottom_right.0.width()), $brw);
- assert_eq!(::style_traits::ToCss::to_css_string(&input.bottom_left.0.width()), $blw);
- assert_eq!(::style_traits::ToCss::to_css_string(&input.top_left.0.height()), $tlh);
- assert_eq!(::style_traits::ToCss::to_css_string(&input.top_right.0.height()), $trh);
- assert_eq!(::style_traits::ToCss::to_css_string(&input.bottom_right.0.height()), $brh);
- assert_eq!(::style_traits::ToCss::to_css_string(&input.bottom_left.0.height()), $blh);
- }
+ .expect(&format!("Failed parsing {} as border radius", $input));
+ assert_eq!(
+ ::style_traits::ToCss::to_css_string(&input.top_left.0.width()),
+ $tlw
+ );
+ assert_eq!(
+ ::style_traits::ToCss::to_css_string(&input.top_right.0.width()),
+ $trw
+ );
+ assert_eq!(
+ ::style_traits::ToCss::to_css_string(&input.bottom_right.0.width()),
+ $brw
+ );
+ assert_eq!(
+ ::style_traits::ToCss::to_css_string(&input.bottom_left.0.width()),
+ $blw
+ );
+ assert_eq!(
+ ::style_traits::ToCss::to_css_string(&input.top_left.0.height()),
+ $tlh
+ );
+ assert_eq!(
+ ::style_traits::ToCss::to_css_string(&input.top_right.0.height()),
+ $trh
+ );
+ assert_eq!(
+ ::style_traits::ToCss::to_css_string(&input.bottom_right.0.height()),
+ $brh
+ );
+ assert_eq!(
+ ::style_traits::ToCss::to_css_string(&input.bottom_left.0.height()),
+ $blh
+ );
+ };
}
#[test]
diff --git a/tests/unit/style/parsing/effects.rs b/tests/unit/style/parsing/effects.rs
index 79fd1937e52..9e1836d6667 100644
--- a/tests/unit/style/parsing/effects.rs
+++ b/tests/unit/style/parsing/effects.rs
@@ -16,18 +16,26 @@ fn test_clip() {
assert_roundtrip_with_context!(clip::parse, "rect(auto, auto, auto, auto)");
// Non-standard syntax
- assert_roundtrip_with_context!(clip::parse,
- "rect(1px 2px 3px 4px)",
- "rect(1px, 2px, 3px, 4px)");
- assert_roundtrip_with_context!(clip::parse,
- "rect(auto 2px 3px auto)",
- "rect(auto, 2px, 3px, auto)");
- assert_roundtrip_with_context!(clip::parse,
- "rect(1px auto auto 4px)",
- "rect(1px, auto, auto, 4px)");
- assert_roundtrip_with_context!(clip::parse,
- "rect(auto auto auto auto)",
- "rect(auto, auto, auto, auto)");
+ assert_roundtrip_with_context!(
+ clip::parse,
+ "rect(1px 2px 3px 4px)",
+ "rect(1px, 2px, 3px, 4px)"
+ );
+ assert_roundtrip_with_context!(
+ clip::parse,
+ "rect(auto 2px 3px auto)",
+ "rect(auto, 2px, 3px, auto)"
+ );
+ assert_roundtrip_with_context!(
+ clip::parse,
+ "rect(1px auto auto 4px)",
+ "rect(1px, auto, auto, 4px)"
+ );
+ assert_roundtrip_with_context!(
+ clip::parse,
+ "rect(auto auto auto auto)",
+ "rect(auto, auto, auto, auto)"
+ );
}
#[test]
@@ -85,7 +93,7 @@ fn test_parse_factor() {
#[test]
fn blur_radius_should_not_accept_negavite_values() {
use style::properties::longhands::box_shadow;
- assert!(parse(box_shadow::parse, "1px 1px -1px").is_err());// for -ve values
- assert!(parse(box_shadow::parse, "1px 1px 0").is_ok());// for zero
- assert!(parse(box_shadow::parse, "1px 1px 1px").is_ok());// for +ve value
+ assert!(parse(box_shadow::parse, "1px 1px -1px").is_err()); // for -ve values
+ assert!(parse(box_shadow::parse, "1px 1px 0").is_ok()); // for zero
+ assert!(parse(box_shadow::parse, "1px 1px 1px").is_ok()); // for +ve value
}
diff --git a/tests/unit/style/parsing/image.rs b/tests/unit/style/parsing/image.rs
index e171cd29ca8..bbc83b5e070 100644
--- a/tests/unit/style/parsing/image.rs
+++ b/tests/unit/style/parsing/image.rs
@@ -33,72 +33,122 @@ fn test_linear_gradient() {
#[test]
fn test_radial_gradient() {
// Parsing with all values
- assert_roundtrip_with_context!(Image::parse, "radial-gradient(circle closest-side at 20px 30px, red, green)");
- assert_roundtrip_with_context!(Image::parse, "radial-gradient(ellipse closest-side at 20px 30px, red, green)",
- "radial-gradient(closest-side at 20px 30px, red, green)");
- assert_roundtrip_with_context!(Image::parse, "radial-gradient(closest-side circle at 20px 30px, red, green)",
- "radial-gradient(circle closest-side at 20px 30px, red, green)");
- assert_roundtrip_with_context!(Image::parse, "radial-gradient(closest-side ellipse at 20px 30px, red, green)",
- "radial-gradient(closest-side at 20px 30px, red, green)");
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(circle closest-side at 20px 30px, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(ellipse closest-side at 20px 30px, red, green)",
+ "radial-gradient(closest-side at 20px 30px, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(closest-side circle at 20px 30px, red, green)",
+ "radial-gradient(circle closest-side at 20px 30px, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(closest-side ellipse at 20px 30px, red, green)",
+ "radial-gradient(closest-side at 20px 30px, red, green)"
+ );
// Parsing with <shape-keyword> and <size> reversed
- assert_roundtrip_with_context!(Image::parse, "radial-gradient(closest-side circle at 20px 30px, red, green)",
- "radial-gradient(circle closest-side at 20px 30px, red, green)");
- assert_roundtrip_with_context!(Image::parse, "radial-gradient(closest-corner ellipse at 20px 30px, red, green)",
- "radial-gradient(closest-corner at 20px 30px, red, green)");
- assert_roundtrip_with_context!(Image::parse, "radial-gradient(30px circle, red, green)",
- "radial-gradient(30px at center center, red, green)");
- assert_roundtrip_with_context!(Image::parse, "radial-gradient(30px 40px ellipse, red, green)",
- "radial-gradient(30px 40px at center center, red, green)");
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(closest-side circle at 20px 30px, red, green)",
+ "radial-gradient(circle closest-side at 20px 30px, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(closest-corner ellipse at 20px 30px, red, green)",
+ "radial-gradient(closest-corner at 20px 30px, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(30px circle, red, green)",
+ "radial-gradient(30px at center center, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(30px 40px ellipse, red, green)",
+ "radial-gradient(30px 40px at center center, red, green)"
+ );
// Parsing without <size>
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(circle, red, green)",
- "radial-gradient(circle at center center, red, green)");
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(ellipse, red, green)",
- "radial-gradient(at center center, red, green)");
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(circle at 20px 30px, red, green)");
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(ellipse at 20px 30px, red, green)",
- "radial-gradient(at 20px 30px, red, green)");
-
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(circle, red, green)",
+ "radial-gradient(circle at center center, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(ellipse, red, green)",
+ "radial-gradient(at center center, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(circle at 20px 30px, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(ellipse at 20px 30px, red, green)",
+ "radial-gradient(at 20px 30px, red, green)"
+ );
// Parsing without <shape-keyword>
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(20px at 20px 30px, red, green)");
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(20px 30px at left center, red, green)");
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(closest-side at center, red, green)",
- "radial-gradient(closest-side at center center, red, green)");
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(20px, red, green)",
- "radial-gradient(20px at center center, red, green)");
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(20px 30px, red, green)",
- "radial-gradient(20px 30px at center center, red, green)");
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(closest-side, red, green)",
- "radial-gradient(closest-side at center center, red, green)");
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(20px at 20px 30px, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(20px 30px at left center, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(closest-side at center, red, green)",
+ "radial-gradient(closest-side at center center, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(20px, red, green)",
+ "radial-gradient(20px at center center, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(20px 30px, red, green)",
+ "radial-gradient(20px 30px at center center, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(closest-side, red, green)",
+ "radial-gradient(closest-side at center center, red, green)"
+ );
// Parsing without <shape-keyword> and <size>
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(at center, red, green)",
- "radial-gradient(at center center, red, green)");
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(at center bottom, red, green)");
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(at 40px 50px, red, green)");
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(at center, red, green)",
+ "radial-gradient(at center center, red, green)"
+ );
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(at center bottom, red, green)"
+ );
+ assert_roundtrip_with_context!(Image::parse, "radial-gradient(at 40px 50px, red, green)");
// Parsing with just color stops
- assert_roundtrip_with_context!(Image::parse,
- "radial-gradient(red, green)",
- "radial-gradient(at center center, red, green)");
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "radial-gradient(red, green)",
+ "radial-gradient(at center center, red, green)"
+ );
// Parsing repeating radial gradient
- assert_roundtrip_with_context!(Image::parse,
- "repeating-radial-gradient(red, green)",
- "repeating-radial-gradient(at center center, red, green)");
+ assert_roundtrip_with_context!(
+ Image::parse,
+ "repeating-radial-gradient(red, green)",
+ "repeating-radial-gradient(at center center, red, green)"
+ );
}
diff --git a/tests/unit/style/parsing/inherited_text.rs b/tests/unit/style/parsing/inherited_text.rs
index 85b99a85fc7..6f923887c4d 100644
--- a/tests/unit/style/parsing/inherited_text.rs
+++ b/tests/unit/style/parsing/inherited_text.rs
@@ -11,7 +11,9 @@ fn negative_letter_spacing_should_parse_properly() {
use style::values::specified::length::{Length, NoCalcLength, FontRelativeLength};
let negative_value = parse_longhand!(letter_spacing, "-0.5em");
- let expected = Spacing::Value(Length::NoCalc(NoCalcLength::FontRelative(FontRelativeLength::Em(-0.5))));
+ let expected = Spacing::Value(Length::NoCalc(NoCalcLength::FontRelative(
+ FontRelativeLength::Em(-0.5),
+ )));
assert_eq!(negative_value, expected);
}
@@ -21,9 +23,9 @@ fn negative_word_spacing_should_parse_properly() {
use style::values::specified::length::{NoCalcLength, LengthOrPercentage, FontRelativeLength};
let negative_value = parse_longhand!(word_spacing, "-0.5em");
- let expected = Spacing::Value(LengthOrPercentage::Length(
- NoCalcLength::FontRelative(FontRelativeLength::Em(-0.5))
- ));
+ let expected = Spacing::Value(LengthOrPercentage::Length(NoCalcLength::FontRelative(
+ FontRelativeLength::Em(-0.5),
+ )));
assert_eq!(negative_value, expected);
}
diff --git a/tests/unit/style/parsing/mod.rs b/tests/unit/style/parsing/mod.rs
index 6f76b2efea6..a801b3d6605 100644
--- a/tests/unit/style/parsing/mod.rs
+++ b/tests/unit/style/parsing/mod.rs
@@ -11,13 +11,17 @@ use style::stylesheets::{CssRuleType, Origin};
use style_traits::{ParsingMode, ParseError};
fn parse<T, F>(f: F, s: &'static str) -> Result<T, ParseError<'static>>
-where F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>> {
+where
+ F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>>,
+{
let mut input = ParserInput::new(s);
parse_input(f, &mut input)
}
fn parse_input<'i: 't, 't, T, F>(f: F, input: &'t mut ParserInput<'i>) -> Result<T, ParseError<'i>>
-where F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>> {
+where
+ F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>>,
+{
let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap();
let context = ParserContext::new(
Origin::Author,
@@ -33,14 +37,24 @@ where F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>> {
}
fn parse_entirely<T, F>(f: F, s: &'static str) -> Result<T, ParseError<'static>>
-where F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>> {
+where
+ F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>>,
+{
let mut input = ParserInput::new(s);
parse_entirely_input(f, &mut input)
}
-fn parse_entirely_input<'i: 't, 't, T, F>(f: F, input: &'t mut ParserInput<'i>) -> Result<T, ParseError<'i>>
-where F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>> {
- parse_input(|context, parser| parser.parse_entirely(|p| f(context, p)), input)
+fn parse_entirely_input<'i: 't, 't, T, F>(
+ f: F,
+ input: &'t mut ParserInput<'i>,
+) -> Result<T, ParseError<'i>>
+where
+ F: Fn(&ParserContext, &mut Parser<'i, 't>) -> Result<T, ParseError<'i>>,
+{
+ parse_input(
+ |context, parser| parser.parse_entirely(|p| f(context, p)),
+ input,
+ )
}
// This is a macro so that the file/line information
@@ -51,24 +65,31 @@ macro_rules! assert_roundtrip_with_context {
};
($fun:expr, $input:expr, $output:expr) => {{
let mut input = ::cssparser::ParserInput::new($input);
- let serialized = super::parse_input(|context, i| {
- let parsed = $fun(context, i)
- .expect(&format!("Failed to parse {}", $input));
- let serialized = ToCss::to_css_string(&parsed);
- assert_eq!(serialized, $output);
- Ok(serialized)
- }, &mut input).unwrap();
+ let serialized = super::parse_input(
+ |context, i| {
+ let parsed = $fun(context, i).expect(&format!("Failed to parse {}", $input));
+ let serialized = ToCss::to_css_string(&parsed);
+ assert_eq!(serialized, $output);
+ Ok(serialized)
+ },
+ &mut input,
+ )
+ .unwrap();
let mut input = ::cssparser::ParserInput::new(&serialized);
- let unwrapped = super::parse_input(|context, i| {
- let re_parsed = $fun(context, i)
- .expect(&format!("Failed to parse serialization {}", $input));
- let re_serialized = ToCss::to_css_string(&re_parsed);
- assert_eq!(serialized, re_serialized);
- Ok(())
- }, &mut input).unwrap();
+ let unwrapped = super::parse_input(
+ |context, i| {
+ let re_parsed =
+ $fun(context, i).expect(&format!("Failed to parse serialization {}", $input));
+ let re_serialized = ToCss::to_css_string(&re_parsed);
+ assert_eq!(serialized, re_serialized);
+ Ok(())
+ },
+ &mut input,
+ )
+ .unwrap();
unwrapped
- }}
+ }};
}
macro_rules! assert_roundtrip {
@@ -78,34 +99,37 @@ macro_rules! assert_roundtrip {
($fun:expr, $input:expr, $output:expr) => {
let mut input = ParserInput::new($input);
let mut parser = Parser::new(&mut input);
- let parsed = $fun(&mut parser)
- .expect(&format!("Failed to parse {}", $input));
+ let parsed = $fun(&mut parser).expect(&format!("Failed to parse {}", $input));
let serialized = ToCss::to_css_string(&parsed);
assert_eq!(serialized, $output);
let mut input = ParserInput::new(&serialized);
let mut parser = Parser::new(&mut input);
- let re_parsed = $fun(&mut parser)
- .expect(&format!("Failed to parse serialization {}", $input));
+ let re_parsed =
+ $fun(&mut parser).expect(&format!("Failed to parse serialization {}", $input));
let re_serialized = ToCss::to_css_string(&re_parsed);
assert_eq!(serialized, re_serialized)
- }
+ };
}
macro_rules! assert_parser_exhausted {
($fun:expr, $string:expr, $should_exhausted:expr) => {{
- parse(|context, input| {
- let parsed = $fun(context, input);
- assert_eq!(parsed.is_ok(), true);
- assert_eq!(input.is_exhausted(), $should_exhausted);
- Ok(())
- }, $string).unwrap()
- }}
+ parse(
+ |context, input| {
+ let parsed = $fun(context, input);
+ assert_eq!(parsed.is_ok(), true);
+ assert_eq!(input.is_exhausted(), $should_exhausted);
+ Ok(())
+ },
+ $string,
+ )
+ .unwrap()
+ }};
}
macro_rules! parse_longhand {
($name:ident, $s:expr) => {
- parse($name::parse, $s).unwrap()
+ parse($name::parse, $s).unwrap()
};
}
diff --git a/tests/unit/style/parsing/position.rs b/tests/unit/style/parsing/position.rs
index 5494f6c9c12..d97e79cbc64 100644
--- a/tests/unit/style/parsing/position.rs
+++ b/tests/unit/style/parsing/position.rs
@@ -143,4 +143,3 @@ fn test_vertical_position() {
assert!(parse(VerticalPosition::parse, "y-start").is_err());
assert!(parse(VerticalPosition::parse, "y-end").is_err());
}
-
diff --git a/tests/unit/style/parsing/selectors.rs b/tests/unit/style/parsing/selectors.rs
index 5ace20370d4..8fbfbfc4f24 100644
--- a/tests/unit/style/parsing/selectors.rs
+++ b/tests/unit/style/parsing/selectors.rs
@@ -8,7 +8,9 @@ use style::selector_parser::{SelectorImpl, SelectorParser};
use style::stylesheets::{Origin, Namespaces};
use style_traits::ParseError;
-fn parse_selector<'i, 't>(input: &mut Parser<'i, 't>) -> Result<SelectorList<SelectorImpl>, ParseError<'i>> {
+fn parse_selector<'i, 't>(
+ input: &mut Parser<'i, 't>,
+) -> Result<SelectorList<SelectorImpl>, ParseError<'i>> {
let mut ns = Namespaces::default();
ns.prefixes.insert("svg".into(), ns!(svg));
let parser = SelectorParser {
@@ -24,7 +26,10 @@ fn test_selectors() {
assert_roundtrip!(parse_selector, "div");
assert_roundtrip!(parse_selector, "svg|circle");
assert_roundtrip!(parse_selector, "p:before", "p::before");
- assert_roundtrip!(parse_selector, "[border=\"0\"]:-servo-nonzero-border ~ ::-servo-details-summary");
+ assert_roundtrip!(
+ parse_selector,
+ "[border=\"0\"]:-servo-nonzero-border ~ ::-servo-details-summary"
+ );
assert_roundtrip!(parse_selector, "* > *");
assert_roundtrip!(parse_selector, "*|* + *", "* + *");
}
diff --git a/tests/unit/style/parsing/supports.rs b/tests/unit/style/parsing/supports.rs
index 573be52d767..285db477af1 100644
--- a/tests/unit/style/parsing/supports.rs
+++ b/tests/unit/style/parsing/supports.rs
@@ -10,7 +10,10 @@ use style_traits::ToCss;
fn test_supports_condition() {
assert_roundtrip!(SupportsCondition::parse, "(margin: 1px)");
assert_roundtrip!(SupportsCondition::parse, "not (--be: to be)");
- assert_roundtrip!(SupportsCondition::parse, "(color: blue) and future-extension(4)");
+ assert_roundtrip!(
+ SupportsCondition::parse,
+ "(color: blue) and future-extension(4)"
+ );
assert_roundtrip!(SupportsCondition::parse, "future-\\1 extension(4)");
assert_roundtrip!(SupportsCondition::parse, "((test))");
}
diff --git a/tests/unit/style/parsing/transition_timing_function.rs b/tests/unit/style/parsing/transition_timing_function.rs
index dab50b34275..46af0a5f7c3 100644
--- a/tests/unit/style/parsing/transition_timing_function.rs
+++ b/tests/unit/style/parsing/transition_timing_function.rs
@@ -8,14 +8,41 @@ use style_traits::ToCss;
#[test]
fn test_cubic_bezier() {
- assert_roundtrip_with_context!(transition_timing_function::parse, "cubic-bezier(0, 0, 0, 0)");
- assert_roundtrip_with_context!(transition_timing_function::parse, "cubic-bezier(0.25, 0, 0.5, 0)");
- assert_roundtrip_with_context!(transition_timing_function::parse, "cubic-bezier(1, 1, 1, 1)");
+ assert_roundtrip_with_context!(
+ transition_timing_function::parse,
+ "cubic-bezier(0, 0, 0, 0)"
+ );
+ assert_roundtrip_with_context!(
+ transition_timing_function::parse,
+ "cubic-bezier(0.25, 0, 0.5, 0)"
+ );
+ assert_roundtrip_with_context!(
+ transition_timing_function::parse,
+ "cubic-bezier(1, 1, 1, 1)"
+ );
// p1x and p2x values must be in range [0, 1]
- assert!(parse(transition_timing_function::parse, "cubic-bezier(-1, 0, 0, 0").is_err());
- assert!(parse(transition_timing_function::parse, "cubic-bezier(0, 0, -1, 0").is_err());
- assert!(parse(transition_timing_function::parse, "cubic-bezier(-1, 0, -1, 0").is_err());
+ assert!(
+ parse(
+ transition_timing_function::parse,
+ "cubic-bezier(-1, 0, 0, 0"
+ )
+ .is_err()
+ );
+ assert!(
+ parse(
+ transition_timing_function::parse,
+ "cubic-bezier(0, 0, -1, 0"
+ )
+ .is_err()
+ );
+ assert!(
+ parse(
+ transition_timing_function::parse,
+ "cubic-bezier(-1, 0, -1, 0"
+ )
+ .is_err()
+ );
assert!(parse(transition_timing_function::parse, "cubic-bezier(2, 0, 0, 0").is_err());
assert!(parse(transition_timing_function::parse, "cubic-bezier(0, 0, 2, 0").is_err());
@@ -27,7 +54,11 @@ fn test_steps() {
assert_roundtrip_with_context!(transition_timing_function::parse, "steps(1)");
assert_roundtrip_with_context!(transition_timing_function::parse, "steps( 1)", "steps(1)");
assert_roundtrip_with_context!(transition_timing_function::parse, "steps(1, start)");
- assert_roundtrip_with_context!(transition_timing_function::parse, "steps(2, end) ", "steps(2)");
+ assert_roundtrip_with_context!(
+ transition_timing_function::parse,
+ "steps(2, end) ",
+ "steps(2)"
+ );
// Step interval value must be an integer greater than 0
assert!(parse(transition_timing_function::parse, "steps(0)").is_err());
diff --git a/tests/unit/style/properties/mod.rs b/tests/unit/style/properties/mod.rs
index 5210b663168..0ceaf7c02e5 100644
--- a/tests/unit/style/properties/mod.rs
+++ b/tests/unit/style/properties/mod.rs
@@ -10,10 +10,7 @@ use style_traits::{ParsingMode, ParseError};
fn parse<T, F>(f: F, s: &'static str) -> Result<T, ParseError<'static>>
where
- F: for<'t> Fn(
- &ParserContext,
- &mut Parser<'static, 't>,
- ) -> Result<T, ParseError<'static>>
+ F: for<'t> Fn(&ParserContext, &mut Parser<'static, 't>) -> Result<T, ParseError<'static>>,
{
let mut input = ParserInput::new(s);
parse_input(f, &mut input)
@@ -42,24 +39,31 @@ macro_rules! assert_roundtrip_with_context {
assert_roundtrip_with_context!($fun, $string, $string);
};
($fun:expr, $input:expr, $output:expr) => {{
- let serialized = parse(|context, i| {
- let parsed = $fun(context, i)
- .expect(&format!("Failed to parse {}", $input));
- let serialized = ToCss::to_css_string(&parsed);
- assert_eq!(serialized, $output);
- Ok(serialized)
- }, $input).unwrap();
+ let serialized = parse(
+ |context, i| {
+ let parsed = $fun(context, i).expect(&format!("Failed to parse {}", $input));
+ let serialized = ToCss::to_css_string(&parsed);
+ assert_eq!(serialized, $output);
+ Ok(serialized)
+ },
+ $input,
+ )
+ .unwrap();
let mut input = ::cssparser::ParserInput::new(&serialized);
- let unwrapped = parse_input(|context, i| {
- let re_parsed = $fun(context, i)
- .expect(&format!("Failed to parse serialization {}", $input));
- let re_serialized = ToCss::to_css_string(&re_parsed);
- assert_eq!(serialized, re_serialized);
- Ok(())
- }, &mut input).unwrap();
+ let unwrapped = parse_input(
+ |context, i| {
+ let re_parsed =
+ $fun(context, i).expect(&format!("Failed to parse serialization {}", $input));
+ let re_serialized = ToCss::to_css_string(&re_parsed);
+ assert_eq!(serialized, re_serialized);
+ Ok(())
+ },
+ &mut input,
+ )
+ .unwrap();
unwrapped
- }}
+ }};
}
mod scaffolding;
diff --git a/tests/unit/style/properties/scaffolding.rs b/tests/unit/style/properties/scaffolding.rs
index faa727ff613..56fa88165ef 100644
--- a/tests/unit/style/properties/scaffolding.rs
+++ b/tests/unit/style/properties/scaffolding.rs
@@ -10,13 +10,24 @@ use std::process::Command;
#[test]
fn properties_list_json() {
- let top = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap()).join("..").join("..").join("..");
- let json = top.join("target").join("doc").join("servo").join("css-properties.json");
+ let top = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap())
+ .join("..")
+ .join("..")
+ .join("..");
+ let json = top
+ .join("target")
+ .join("doc")
+ .join("servo")
+ .join("css-properties.json");
if json.exists() {
remove_file(&json).unwrap()
}
let python = env::var("PYTHON").ok().unwrap_or_else(find_python);
- let script = top.join("components").join("style").join("properties").join("build.py");
+ let script = top
+ .join("components")
+ .join("style")
+ .join("properties")
+ .join("build.py");
let status = Command::new(python)
.arg(&script)
.arg("servo")
@@ -34,11 +45,19 @@ fn properties_list_json() {
#[cfg(windows)]
fn find_python() -> String {
- if Command::new("python2.7.exe").arg("--version").output().is_ok() {
+ if Command::new("python2.7.exe")
+ .arg("--version")
+ .output()
+ .is_ok()
+ {
return "python2.7.exe".to_owned();
}
- if Command::new("python27.exe").arg("--version").output().is_ok() {
+ if Command::new("python27.exe")
+ .arg("--version")
+ .output()
+ .is_ok()
+ {
return "python27.exe".to_owned();
}
@@ -51,9 +70,16 @@ fn find_python() -> String {
#[cfg(not(windows))]
fn find_python() -> String {
- if Command::new("python2.7").arg("--version").output().unwrap().status.success() {
+ if Command::new("python2.7")
+ .arg("--version")
+ .output()
+ .unwrap()
+ .status
+ .success()
+ {
"python2.7"
} else {
"python"
- }.to_owned()
+ }
+ .to_owned()
}
diff --git a/tests/unit/style/properties/serialization.rs b/tests/unit/style/properties/serialization.rs
index 5c520ccc79d..cf37bcc0ca9 100644
--- a/tests/unit/style/properties/serialization.rs
+++ b/tests/unit/style/properties/serialization.rs
@@ -32,28 +32,36 @@ fn property_declaration_block_should_serialize_correctly() {
use style::properties::longhands::overflow_x::SpecifiedValue as OverflowValue;
let declarations = vec![
- (PropertyDeclaration::Width(
- LengthOrPercentageOrAuto::Length(NoCalcLength::from_px(70f32))),
- Importance::Normal),
-
- (PropertyDeclaration::MinHeight(
- LengthOrPercentage::Length(NoCalcLength::from_px(20f32))),
- Importance::Normal),
-
- (PropertyDeclaration::Height(
- LengthOrPercentageOrAuto::Length(NoCalcLength::from_px(20f32))),
- Importance::Important),
-
- (PropertyDeclaration::Display(Display::InlineBlock),
- Importance::Normal),
-
- (PropertyDeclaration::OverflowX(
- OverflowValue::Auto),
- Importance::Normal),
-
- (PropertyDeclaration::OverflowY(
- OverflowValue::Auto),
- Importance::Normal),
+ (
+ PropertyDeclaration::Width(LengthOrPercentageOrAuto::Length(NoCalcLength::from_px(
+ 70f32,
+ ))),
+ Importance::Normal,
+ ),
+ (
+ PropertyDeclaration::MinHeight(LengthOrPercentage::Length(NoCalcLength::from_px(
+ 20f32,
+ ))),
+ Importance::Normal,
+ ),
+ (
+ PropertyDeclaration::Height(LengthOrPercentageOrAuto::Length(NoCalcLength::from_px(
+ 20f32,
+ ))),
+ Importance::Important,
+ ),
+ (
+ PropertyDeclaration::Display(Display::InlineBlock),
+ Importance::Normal,
+ ),
+ (
+ PropertyDeclaration::OverflowX(OverflowValue::Auto),
+ Importance::Normal,
+ ),
+ (
+ PropertyDeclaration::OverflowY(OverflowValue::Auto),
+ Importance::Normal,
+ ),
];
let block = block_from(declarations);
@@ -147,62 +155,65 @@ mod shorthand_serialization {
#[test]
fn different_longhands_should_serialize_to_long_form() {
- let mut properties = Vec::new();
+ let mut properties = Vec::new();
- let solid = BorderStyle::Solid;
+ let solid = BorderStyle::Solid;
- properties.push(PropertyDeclaration::BorderTopStyle(solid.clone()));
- properties.push(PropertyDeclaration::BorderRightStyle(solid.clone()));
- properties.push(PropertyDeclaration::BorderBottomStyle(solid.clone()));
- properties.push(PropertyDeclaration::BorderLeftStyle(solid.clone()));
+ properties.push(PropertyDeclaration::BorderTopStyle(solid.clone()));
+ properties.push(PropertyDeclaration::BorderRightStyle(solid.clone()));
+ properties.push(PropertyDeclaration::BorderBottomStyle(solid.clone()));
+ properties.push(PropertyDeclaration::BorderLeftStyle(solid.clone()));
- let px_30 = BorderSideWidth::Length(Length::from_px(30f32));
- let px_10 = BorderSideWidth::Length(Length::from_px(10f32));
+ let px_30 = BorderSideWidth::Length(Length::from_px(30f32));
+ let px_10 = BorderSideWidth::Length(Length::from_px(10f32));
- properties.push(PropertyDeclaration::BorderTopWidth(px_30.clone()));
- properties.push(PropertyDeclaration::BorderRightWidth(px_30.clone()));
- properties.push(PropertyDeclaration::BorderBottomWidth(px_30.clone()));
- properties.push(PropertyDeclaration::BorderLeftWidth(px_10.clone()));
+ properties.push(PropertyDeclaration::BorderTopWidth(px_30.clone()));
+ properties.push(PropertyDeclaration::BorderRightWidth(px_30.clone()));
+ properties.push(PropertyDeclaration::BorderBottomWidth(px_30.clone()));
+ properties.push(PropertyDeclaration::BorderLeftWidth(px_10.clone()));
- let blue = Color::rgba(RGBA::new(0, 0, 255, 255));
+ let blue = Color::rgba(RGBA::new(0, 0, 255, 255));
- properties.push(PropertyDeclaration::BorderTopColor(blue.clone()));
- properties.push(PropertyDeclaration::BorderRightColor(blue.clone()));
- properties.push(PropertyDeclaration::BorderBottomColor(blue.clone()));
- properties.push(PropertyDeclaration::BorderLeftColor(blue.clone()));
+ properties.push(PropertyDeclaration::BorderTopColor(blue.clone()));
+ properties.push(PropertyDeclaration::BorderRightColor(blue.clone()));
+ properties.push(PropertyDeclaration::BorderBottomColor(blue.clone()));
+ properties.push(PropertyDeclaration::BorderLeftColor(blue.clone()));
- let serialization = shorthand_properties_to_string(properties);
- assert_eq!(serialization,
+ let serialization = shorthand_properties_to_string(properties);
+ assert_eq!(serialization,
"border-style: solid; border-width: 30px 30px 30px 10px; border-color: rgb(0, 0, 255);");
}
#[test]
fn same_longhands_should_serialize_correctly() {
- let mut properties = Vec::new();
+ let mut properties = Vec::new();
- let solid = BorderStyle::Solid;
+ let solid = BorderStyle::Solid;
- properties.push(PropertyDeclaration::BorderTopStyle(solid.clone()));
- properties.push(PropertyDeclaration::BorderRightStyle(solid.clone()));
- properties.push(PropertyDeclaration::BorderBottomStyle(solid.clone()));
- properties.push(PropertyDeclaration::BorderLeftStyle(solid.clone()));
+ properties.push(PropertyDeclaration::BorderTopStyle(solid.clone()));
+ properties.push(PropertyDeclaration::BorderRightStyle(solid.clone()));
+ properties.push(PropertyDeclaration::BorderBottomStyle(solid.clone()));
+ properties.push(PropertyDeclaration::BorderLeftStyle(solid.clone()));
- let px_30 = BorderSideWidth::Length(Length::from_px(30f32));
+ let px_30 = BorderSideWidth::Length(Length::from_px(30f32));
- properties.push(PropertyDeclaration::BorderTopWidth(px_30.clone()));
- properties.push(PropertyDeclaration::BorderRightWidth(px_30.clone()));
- properties.push(PropertyDeclaration::BorderBottomWidth(px_30.clone()));
- properties.push(PropertyDeclaration::BorderLeftWidth(px_30.clone()));
+ properties.push(PropertyDeclaration::BorderTopWidth(px_30.clone()));
+ properties.push(PropertyDeclaration::BorderRightWidth(px_30.clone()));
+ properties.push(PropertyDeclaration::BorderBottomWidth(px_30.clone()));
+ properties.push(PropertyDeclaration::BorderLeftWidth(px_30.clone()));
- let blue = Color::rgba(RGBA::new(0, 0, 255, 255));
+ let blue = Color::rgba(RGBA::new(0, 0, 255, 255));
- properties.push(PropertyDeclaration::BorderTopColor(blue.clone()));
- properties.push(PropertyDeclaration::BorderRightColor(blue.clone()));
- properties.push(PropertyDeclaration::BorderBottomColor(blue.clone()));
- properties.push(PropertyDeclaration::BorderLeftColor(blue.clone()));
+ properties.push(PropertyDeclaration::BorderTopColor(blue.clone()));
+ properties.push(PropertyDeclaration::BorderRightColor(blue.clone()));
+ properties.push(PropertyDeclaration::BorderBottomColor(blue.clone()));
+ properties.push(PropertyDeclaration::BorderLeftColor(blue.clone()));
- let serialization = shorthand_properties_to_string(properties);
- assert_eq!(serialization, "border-style: solid; border-width: 30px; border-color: rgb(0, 0, 255);");
+ let serialization = shorthand_properties_to_string(properties);
+ assert_eq!(
+ serialization,
+ "border-style: solid; border-width: 30px; border-color: rgb(0, 0, 255);"
+ );
}
#[test]
@@ -274,7 +285,10 @@ mod shorthand_serialization {
let serialization = shorthand_properties_to_string(properties);
// TODO: Make the rgb test show border-color as blue red instead of below tuples
- assert_eq!(serialization, "border-color: rgb(0, 0, 255) rgb(255, 0, 0);");
+ assert_eq!(
+ serialization,
+ "border-color: rgb(0, 0, 255) rgb(255, 0, 0);"
+ );
}
#[test]
@@ -297,41 +311,42 @@ mod shorthand_serialization {
#[test]
fn border_radius_should_serialize_correctly() {
let mut properties = Vec::new();
- properties.push(PropertyDeclaration::BorderTopLeftRadius(Box::new(BorderCornerRadius::new(
- Percentage::new(0.01).into(), Percentage::new(0.05).into()
- ))));
- properties.push(PropertyDeclaration::BorderTopRightRadius(Box::new(BorderCornerRadius::new(
- Percentage::new(0.02).into(), Percentage::new(0.06).into()
- ))));
- properties.push(PropertyDeclaration::BorderBottomRightRadius(Box::new(BorderCornerRadius::new(
- Percentage::new(0.03).into(), Percentage::new(0.07).into()
- ))));
- properties.push(PropertyDeclaration::BorderBottomLeftRadius(Box::new(BorderCornerRadius::new(
- Percentage::new(0.04).into(), Percentage::new(0.08).into()
- ))));
+ properties.push(PropertyDeclaration::BorderTopLeftRadius(Box::new(
+ BorderCornerRadius::new(Percentage::new(0.01).into(), Percentage::new(0.05).into()),
+ )));
+ properties.push(PropertyDeclaration::BorderTopRightRadius(Box::new(
+ BorderCornerRadius::new(Percentage::new(0.02).into(), Percentage::new(0.06).into()),
+ )));
+ properties.push(PropertyDeclaration::BorderBottomRightRadius(Box::new(
+ BorderCornerRadius::new(Percentage::new(0.03).into(), Percentage::new(0.07).into()),
+ )));
+ properties.push(PropertyDeclaration::BorderBottomLeftRadius(Box::new(
+ BorderCornerRadius::new(Percentage::new(0.04).into(), Percentage::new(0.08).into()),
+ )));
let serialization = shorthand_properties_to_string(properties);
assert_eq!(serialization, "border-radius: 1% 2% 3% 4% / 5% 6% 7% 8%;");
}
}
-
mod border_shorthands {
use super::*;
#[test]
fn border_top_and_color() {
let mut properties = Vec::new();
- properties.push(PropertyDeclaration::BorderTopWidth(BorderSideWidth::Length(Length::from_px(1.))));
+ properties.push(PropertyDeclaration::BorderTopWidth(
+ BorderSideWidth::Length(Length::from_px(1.)),
+ ));
properties.push(PropertyDeclaration::BorderTopStyle(BorderStyle::Solid));
let c = Color::Numeric {
parsed: RGBA::new(255, 0, 0, 255),
- authored: Some("green".to_string().into_boxed_str())
+ authored: Some("green".to_string().into_boxed_str()),
};
properties.push(PropertyDeclaration::BorderTopColor(c));
let c = Color::Numeric {
parsed: RGBA::new(0, 255, 0, 255),
- authored: Some("red".to_string().into_boxed_str())
+ authored: Some("red".to_string().into_boxed_str()),
};
properties.push(PropertyDeclaration::BorderTopColor(c.clone()));
properties.push(PropertyDeclaration::BorderBottomColor(c.clone()));
@@ -339,31 +354,39 @@ mod shorthand_serialization {
properties.push(PropertyDeclaration::BorderRightColor(c.clone()));
let serialization = shorthand_properties_to_string(properties);
- assert_eq!(serialization, "border-top: 1px solid red; border-color: red;");
+ assert_eq!(
+ serialization,
+ "border-top: 1px solid red; border-color: red;"
+ );
}
#[test]
fn border_color_and_top() {
let mut properties = Vec::new();
- let c = Color::Numeric {
+ let c = Color::Numeric {
parsed: RGBA::new(0, 255, 0, 255),
- authored: Some("red".to_string().into_boxed_str())
+ authored: Some("red".to_string().into_boxed_str()),
};
properties.push(PropertyDeclaration::BorderTopColor(c.clone()));
properties.push(PropertyDeclaration::BorderBottomColor(c.clone()));
properties.push(PropertyDeclaration::BorderLeftColor(c.clone()));
properties.push(PropertyDeclaration::BorderRightColor(c.clone()));
- properties.push(PropertyDeclaration::BorderTopWidth(BorderSideWidth::Length(Length::from_px(1.))));
+ properties.push(PropertyDeclaration::BorderTopWidth(
+ BorderSideWidth::Length(Length::from_px(1.)),
+ ));
properties.push(PropertyDeclaration::BorderTopStyle(BorderStyle::Solid));
let c = Color::Numeric {
parsed: RGBA::new(255, 0, 0, 255),
- authored: Some("green".to_string().into_boxed_str())
+ authored: Some("green".to_string().into_boxed_str()),
};
properties.push(PropertyDeclaration::BorderTopColor(c));
let serialization = shorthand_properties_to_string(properties);
- assert_eq!(serialization, "border-color: green red red; border-top: 1px solid green;");
+ assert_eq!(
+ serialization,
+ "border-color: green red red; border-top: 1px solid green;"
+ );
}
// we can use border-top as a base to test out the different combinations
@@ -386,9 +409,11 @@ mod shorthand_serialization {
}
fn get_border_property_values() -> (BorderSideWidth, BorderStyle, Color) {
- (BorderSideWidth::Length(Length::from_px(4f32)),
- BorderStyle::Solid,
- Color::currentcolor())
+ (
+ BorderSideWidth::Length(Length::from_px(4f32)),
+ BorderStyle::Solid,
+ Color::currentcolor(),
+ )
}
#[test]
@@ -445,13 +470,14 @@ mod shorthand_serialization {
// the ‘border’ shorthand resets ‘border-image’ to its initial value. To verify the
// serialization of 'border' shorthand, we need to set 'border-image' as well.
let block_text = "\
- border-top: 4px solid; \
- border-right: 4px solid; \
- border-bottom: 4px solid; \
- border-left: 4px solid; \
- border-image: none;";
+ border-top: 4px solid; \
+ border-right: 4px solid; \
+ border-bottom: 4px solid; \
+ border-left: 4px solid; \
+ border-image: none;";
- let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
+ let block =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
let serialization = block.to_css_string();
@@ -483,7 +509,10 @@ mod shorthand_serialization {
properties.push(PropertyDeclaration::ListStyleType(style_type));
let serialization = shorthand_properties_to_string(properties);
- assert_eq!(serialization, "list-style: inside url(\"http://servo/test.png\") disc;");
+ assert_eq!(
+ serialization,
+ "list-style: inside url(\"http://servo/test.png\") disc;"
+ );
}
}
@@ -493,65 +522,68 @@ mod shorthand_serialization {
#[test]
fn background_should_serialize_all_available_properties_when_specified() {
let block_text = "\
- background-color: rgb(255, 0, 0); \
- background-image: url(\"http://servo/test.png\"); \
- background-repeat: repeat-x; \
- background-attachment: scroll; \
- background-size: 70px 50px; \
- background-position-x: 7px; \
- background-position-y: bottom 4px; \
- background-origin: border-box; \
- background-clip: padding-box;";
-
- let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
+ background-color: rgb(255, 0, 0); \
+ background-image: url(\"http://servo/test.png\"); \
+ background-repeat: repeat-x; \
+ background-attachment: scroll; \
+ background-size: 70px 50px; \
+ background-position-x: 7px; \
+ background-position-y: bottom 4px; \
+ background-origin: border-box; \
+ background-clip: padding-box;";
+
+ let block =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
let serialization = block.to_css_string();
assert_eq!(
serialization,
"background: rgb(255, 0, 0) url(\"http://servo/test.png\") repeat-x \
- scroll left 7px bottom 4px / 70px 50px border-box padding-box;"
+ scroll left 7px bottom 4px / 70px 50px border-box padding-box;"
);
}
#[test]
fn background_should_combine_origin_and_clip_properties_when_equal() {
let block_text = "\
- background-color: rgb(255, 0, 0); \
- background-image: url(\"http://servo/test.png\"); \
- background-repeat: repeat-x; \
- background-attachment: scroll; \
- background-size: 70px 50px; \
- background-position-x: 7px; \
- background-position-y: 4px; \
- background-origin: padding-box; \
- background-clip: padding-box;";
-
- let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
+ background-color: rgb(255, 0, 0); \
+ background-image: url(\"http://servo/test.png\"); \
+ background-repeat: repeat-x; \
+ background-attachment: scroll; \
+ background-size: 70px 50px; \
+ background-position-x: 7px; \
+ background-position-y: 4px; \
+ background-origin: padding-box; \
+ background-clip: padding-box;";
+
+ let block =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
let serialization = block.to_css_string();
assert_eq!(
serialization,
"background: rgb(255, 0, 0) url(\"http://servo/test.png\") repeat-x \
- scroll 7px 4px / 70px 50px padding-box;"
+ scroll 7px 4px / 70px 50px padding-box;"
);
}
#[test]
fn serialize_multiple_backgrounds() {
let block_text = "\
- background-color: rgb(0, 0, 255); \
- background-image: url(\"http://servo/test.png\"), none; \
- background-repeat: repeat-x, repeat-y; \
- background-attachment: scroll, scroll; \
- background-size: 70px 50px, 20px 30px; \
- background-position-x: 7px, 70px; \
- background-position-y: 4px, 40px; \
- background-origin: border-box, padding-box; \
- background-clip: padding-box, padding-box;";
-
- let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
+ background-color: rgb(0, 0, 255); \
+ background-image: url(\"http://servo/test.png\"), none; \
+ background-repeat: repeat-x, repeat-y; \
+ background-attachment: scroll, scroll; \
+ background-size: 70px 50px, 20px 30px; \
+ background-position-x: 7px, 70px; \
+ background-position-y: 4px, 40px; \
+ background-origin: border-box, padding-box; \
+ background-clip: padding-box, padding-box;";
+
+ let block =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
let serialization = block.to_css_string();
@@ -573,16 +605,17 @@ mod shorthand_serialization {
// multiple backgrounds.
// Below background-origin only has one value.
let block_text = "\
- background-color: rgb(0, 0, 255); \
- background-image: url(\"http://servo/test.png\"), none; \
- background-repeat: repeat-x, repeat-y; \
- background-attachment: scroll, scroll; \
- background-size: 70px 50px, 20px 30px; \
- background-position: 7px 4px, 5px 6px; \
- background-origin: border-box; \
- background-clip: padding-box, padding-box;";
-
- let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
+ background-color: rgb(0, 0, 255); \
+ background-image: url(\"http://servo/test.png\"), none; \
+ background-repeat: repeat-x, repeat-y; \
+ background-attachment: scroll, scroll; \
+ background-size: 70px 50px, 20px 30px; \
+ background-position: 7px 4px, 5px 6px; \
+ background-origin: border-box; \
+ background-clip: padding-box, padding-box;";
+
+ let block =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
let serialization = block.to_css_string();
@@ -594,18 +627,20 @@ mod shorthand_serialization {
// If there is any longhand consisted of both keyword and position,
// the shorthand result should be the 4-value format.
let block_text = "\
- background-position-x: 30px;\
- background-position-y: bottom 20px;";
- let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
+ background-position-x: 30px;\
+ background-position-y: bottom 20px;";
+ let block =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
let serialization = block.to_css_string();
assert_eq!(serialization, "background-position: left 30px bottom 20px;");
// If there is no longhand consisted of both keyword and position,
// the shorthand result should be the 2-value format.
let block_text = "\
- background-position-x: center;\
- background-position-y: 20px;";
- let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
+ background-position-x: center;\
+ background-position-y: 20px;";
+ let block =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
let serialization = block.to_css_string();
assert_eq!(serialization, "background-position: center 20px;");
}
@@ -628,41 +663,48 @@ mod shorthand_serialization {
#[test]
fn serialize_single_animation() {
let block_text = "\
- animation-name: bounce;\
- animation-duration: 1s;\
- animation-timing-function: ease-in;\
- animation-delay: 0s;\
- animation-direction: normal;\
- animation-fill-mode: forwards;\
- animation-iteration-count: infinite;\
- animation-play-state: paused;";
-
- let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
+ animation-name: bounce;\
+ animation-duration: 1s;\
+ animation-timing-function: ease-in;\
+ animation-delay: 0s;\
+ animation-direction: normal;\
+ animation-fill-mode: forwards;\
+ animation-iteration-count: infinite;\
+ animation-play-state: paused;";
+
+ let block =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
let serialization = block.to_css_string();
- assert_eq!(serialization, "animation: 1s ease-in 0s infinite normal forwards paused bounce;")
+ assert_eq!(
+ serialization,
+ "animation: 1s ease-in 0s infinite normal forwards paused bounce;"
+ )
}
#[test]
fn serialize_multiple_animations() {
let block_text = "\
- animation-name: bounce, roll;\
- animation-duration: 1s, 0.2s;\
- animation-timing-function: ease-in, linear;\
- animation-delay: 0s, 1s;\
- animation-direction: normal, reverse;\
- animation-fill-mode: forwards, backwards;\
- animation-iteration-count: infinite, 2;\
- animation-play-state: paused, running;";
+ animation-name: bounce, roll;\
+ animation-duration: 1s, 0.2s;\
+ animation-timing-function: ease-in, linear;\
+ animation-delay: 0s, 1s;\
+ animation-direction: normal, reverse;\
+ animation-fill-mode: forwards, backwards;\
+ animation-iteration-count: infinite, 2;\
+ animation-play-state: paused, running;";
- let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
+ let block =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
let serialization = block.to_css_string();
- assert_eq!(serialization,
- "animation: 1s ease-in 0s infinite normal forwards paused bounce, \
- 0.2s linear 1s 2 reverse backwards running roll;");
+ assert_eq!(
+ serialization,
+ "animation: 1s ease-in 0s infinite normal forwards paused bounce, \
+ 0.2s linear 1s 2 reverse backwards running roll;"
+ );
}
#[test]
@@ -673,16 +715,17 @@ mod shorthand_serialization {
// lists have the same length (this affects background, transition and animation).
// https://github.com/servo/servo/issues/15398 )
let block_text = "\
- animation-name: bounce, roll, flip, jump; \
- animation-duration: 1s, 0.2s; \
- animation-timing-function: ease-in, linear; \
- animation-delay: 0s, 1s, 0.5s; \
- animation-direction: normal; \
- animation-fill-mode: forwards, backwards; \
- animation-iteration-count: infinite, 2; \
- animation-play-state: paused, running;";
+ animation-name: bounce, roll, flip, jump; \
+ animation-duration: 1s, 0.2s; \
+ animation-timing-function: ease-in, linear; \
+ animation-delay: 0s, 1s, 0.5s; \
+ animation-direction: normal; \
+ animation-fill-mode: forwards, backwards; \
+ animation-iteration-count: infinite, 2; \
+ animation-play-state: paused, running;";
- let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
+ let block =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
let serialization = block.to_css_string();
@@ -699,7 +742,8 @@ mod shorthand_serialization {
animation-iteration-count: infinite, 2; \
animation-play-state: paused, running;";
- let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
+ let block =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
let serialization = block.to_css_string();
@@ -712,7 +756,8 @@ mod shorthand_serialization {
#[test]
fn css_wide_keywords_should_be_parsed() {
let block_text = "--a:inherit;";
- let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
+ let block =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
let serialization = block.to_css_string();
assert_eq!(serialization, "--a: inherit;");
@@ -721,7 +766,8 @@ mod shorthand_serialization {
#[test]
fn non_keyword_custom_property_should_be_unparsed() {
let block_text = "--main-color: #06c;";
- let block = parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
+ let block =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), block_text).unwrap();
let serialization = block.to_css_string();
assert_eq!(serialization, block_text);
@@ -751,7 +797,8 @@ mod shorthand_serialization {
let shadow_decl = BoxShadowList(vec![shadow_val]);
properties.push(PropertyDeclaration::BoxShadow(shadow_decl));
let shadow_css = "box-shadow: 1px 2px 3px 4px;";
- let shadow = parse(|c, i| Ok(parse_property_declaration_list(c, i)), shadow_css).unwrap();
+ let shadow =
+ parse(|c, i| Ok(parse_property_declaration_list(c, i)), shadow_css).unwrap();
assert_eq!(shadow.to_css_string(), shadow_css);
}
diff --git a/tests/unit/style/rule_tree/bench.rs b/tests/unit/style/rule_tree/bench.rs
index c1ea58f5248..4172431356e 100644
--- a/tests/unit/style/rule_tree/bench.rs
+++ b/tests/unit/style/rule_tree/bench.rs
@@ -18,11 +18,14 @@ use test::{self, Bencher};
struct ErrorringErrorReporter;
impl ParseErrorReporter for ErrorringErrorReporter {
- fn report_error(&self,
- url: &ServoUrl,
- location: SourceLocation,
- error: ContextualParseError) {
- panic!("CSS error: {}\t\n{}:{} {}", url.as_str(), location.line, location.column, error);
+ fn report_error(&self, url: &ServoUrl, location: SourceLocation, error: ContextualParseError) {
+ panic!(
+ "CSS error: {}\t\n{}:{} {}",
+ url.as_str(),
+ location.line,
+ location.column,
+ error
+ );
}
}
@@ -38,9 +41,10 @@ impl<'a> Drop for AutoGCRuleTree<'a> {
fn drop(&mut self) {
unsafe {
self.0.gc();
- assert!(::std::thread::panicking() ||
- !self.0.root().has_children_for_testing(),
- "No rule nodes other than the root shall remain!");
+ assert!(
+ ::std::thread::panicking() || !self.0.root().has_children_for_testing(),
+ "No rule nodes other than the root shall remain!"
+ );
}
}
}
@@ -49,41 +53,51 @@ fn parse_rules(css: &str) -> Vec<(StyleSource, CascadeLevel)> {
let lock = SharedRwLock::new();
let media = Arc::new(lock.wrap(MediaList::empty()));
- let s = Stylesheet::from_str(css,
- ServoUrl::parse("http://localhost").unwrap(),
- Origin::Author,
- media,
- lock,
- None,
- Some(&ErrorringErrorReporter),
- QuirksMode::NoQuirks,
- 0);
+ let s = Stylesheet::from_str(
+ css,
+ ServoUrl::parse("http://localhost").unwrap(),
+ Origin::Author,
+ media,
+ lock,
+ None,
+ Some(&ErrorringErrorReporter),
+ QuirksMode::NoQuirks,
+ 0,
+ );
let guard = s.shared_lock.read();
let rules = s.contents.rules.read_with(&guard);
- rules.0.iter().filter_map(|rule| {
- match *rule {
+ rules
+ .0
+ .iter()
+ .filter_map(|rule| match *rule {
CssRule::Style(ref style_rule) => Some((
StyleSource::from_rule(style_rule.clone()),
CascadeLevel::UserNormal,
)),
_ => None,
- }
- }).collect()
+ })
+ .collect()
}
fn test_insertion(rule_tree: &RuleTree, rules: Vec<(StyleSource, CascadeLevel)>) -> StrongRuleNode {
rule_tree.insert_ordered_rules(rules.into_iter())
}
-fn test_insertion_style_attribute(rule_tree: &RuleTree, rules: &[(StyleSource, CascadeLevel)],
- shared_lock: &SharedRwLock)
- -> StrongRuleNode {
+fn test_insertion_style_attribute(
+ rule_tree: &RuleTree,
+ rules: &[(StyleSource, CascadeLevel)],
+ shared_lock: &SharedRwLock,
+) -> StrongRuleNode {
let mut rules = rules.to_vec();
- rules.push((StyleSource::from_declarations(Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one(
- PropertyDeclaration::Display(
- longhands::display::SpecifiedValue::Block),
- Importance::Normal
- )))), CascadeLevel::UserNormal));
+ rules.push((
+ StyleSource::from_declarations(Arc::new(shared_lock.wrap(
+ PropertyDeclarationBlock::with_one(
+ PropertyDeclaration::Display(longhands::display::SpecifiedValue::Block),
+ Importance::Normal,
+ ),
+ ))),
+ CascadeLevel::UserNormal,
+ ));
test_insertion(rule_tree, rules)
}
@@ -95,7 +109,8 @@ fn bench_insertion_basic(b: &mut Bencher) {
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
- .baz { display: block; }");
+ .baz { display: block; }",
+ );
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
@@ -114,7 +129,8 @@ fn bench_insertion_basic_per_element(b: &mut Bencher) {
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
- .baz { display: block; }");
+ .baz { display: block; }",
+ );
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
@@ -134,14 +150,19 @@ fn bench_expensive_insertion(b: &mut Bencher) {
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
- .baz { display: block; }");
+ .baz { display: block; }",
+ );
let shared_lock = SharedRwLock::new();
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
for _ in 0..(4000 + 400) {
- test::black_box(test_insertion_style_attribute(&r, &rules_matched, &shared_lock));
+ test::black_box(test_insertion_style_attribute(
+ &r,
+ &rules_matched,
+ &shared_lock,
+ ));
}
});
}
@@ -154,7 +175,8 @@ fn bench_insertion_basic_parallel(b: &mut Bencher) {
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
- .baz { display: block; }");
+ .baz { display: block; }",
+ );
b.iter(|| {
let _gc = AutoGCRuleTree::new(&r);
@@ -163,13 +185,11 @@ fn bench_insertion_basic_parallel(b: &mut Bencher) {
for _ in 0..4 {
s.spawn(|s| {
for _ in 0..1000 {
- test::black_box(test_insertion(&r,
- rules_matched.clone()));
+ test::black_box(test_insertion(&r, rules_matched.clone()));
}
s.spawn(|_| {
for _ in 0..100 {
- test::black_box(test_insertion(&r,
- rules_matched.clone()));
+ test::black_box(test_insertion(&r, rules_matched.clone()));
}
})
})
@@ -186,7 +206,8 @@ fn bench_expensive_insertion_parallel(b: &mut Bencher) {
let rules_matched = parse_rules(
".foo { width: 200px; } \
.bar { height: 500px; } \
- .baz { display: block; }");
+ .baz { display: block; }",
+ );
let shared_lock = SharedRwLock::new();
b.iter(|| {
@@ -196,15 +217,19 @@ fn bench_expensive_insertion_parallel(b: &mut Bencher) {
for _ in 0..4 {
s.spawn(|s| {
for _ in 0..1000 {
- test::black_box(test_insertion_style_attribute(&r,
- &rules_matched,
- &shared_lock));
+ test::black_box(test_insertion_style_attribute(
+ &r,
+ &rules_matched,
+ &shared_lock,
+ ));
}
s.spawn(|_| {
for _ in 0..100 {
- test::black_box(test_insertion_style_attribute(&r,
- &rules_matched,
- &shared_lock));
+ test::black_box(test_insertion_style_attribute(
+ &r,
+ &rules_matched,
+ &shared_lock,
+ ));
}
})
})
diff --git a/tests/unit/style/size_of.rs b/tests/unit/style/size_of.rs
index 1078074fa58..60c0b1c75e4 100644
--- a/tests/unit/style/size_of.rs
+++ b/tests/unit/style/size_of.rs
@@ -8,16 +8,44 @@ use style::properties;
size_of_test!(test_size_of_dependency, Dependency, 16);
-size_of_test!(test_size_of_property_declaration, properties::PropertyDeclaration, 32);
+size_of_test!(
+ test_size_of_property_declaration,
+ properties::PropertyDeclaration,
+ 32
+);
// This is huge, but we allocate it on the stack and then never move it,
// we only pass `&mut SourcePropertyDeclaration` references around.
-size_of_test!(test_size_of_parsed_declaration, properties::SourcePropertyDeclaration, 568);
+size_of_test!(
+ test_size_of_parsed_declaration,
+ properties::SourcePropertyDeclaration,
+ 568
+);
-size_of_test!(test_size_of_selector_parse_error_kind, SelectorParseErrorKind, 40);
-size_of_test!(test_size_of_style_parse_error_kind, ::style_traits::StyleParseErrorKind, 56);
-size_of_test!(test_size_of_value_parse_error_kind, ::style_traits::ValueParseErrorKind, 40);
+size_of_test!(
+ test_size_of_selector_parse_error_kind,
+ SelectorParseErrorKind,
+ 40
+);
+size_of_test!(
+ test_size_of_style_parse_error_kind,
+ ::style_traits::StyleParseErrorKind,
+ 56
+);
+size_of_test!(
+ test_size_of_value_parse_error_kind,
+ ::style_traits::ValueParseErrorKind,
+ 40
+);
size_of_test!(test_size_of_selector_parse_error, SelectorParseError, 56);
-size_of_test!(test_size_of_style_traits_parse_error, ::style_traits::ParseError, 72);
-size_of_test!(test_size_of_value_parse_error, ::style_traits::ValueParseError, 56);
+size_of_test!(
+ test_size_of_style_traits_parse_error,
+ ::style_traits::ParseError,
+ 72
+);
+size_of_test!(
+ test_size_of_value_parse_error,
+ ::style_traits::ValueParseError,
+ 56
+);
diff --git a/tests/unit/style/str.rs b/tests/unit/style/str.rs
index 154cf894158..78a870dced0 100644
--- a/tests/unit/style/str.rs
+++ b/tests/unit/style/str.rs
@@ -7,7 +7,11 @@ use style::str::{split_html_space_chars, str_join, starts_with_ignore_ascii_case
#[test]
pub fn split_html_space_chars_whitespace() {
assert!(split_html_space_chars("").collect::<Vec<_>>().is_empty());
- assert!(split_html_space_chars("\u{0020}\u{0009}\u{000a}\u{000c}\u{000d}").collect::<Vec<_>>().is_empty());
+ assert!(
+ split_html_space_chars("\u{0020}\u{0009}\u{000a}\u{000c}\u{000d}")
+ .collect::<Vec<_>>()
+ .is_empty()
+ );
}
#[test]
diff --git a/tests/unit/style/stylesheets.rs b/tests/unit/style/stylesheets.rs
index 17c6e493db6..74a2c18e94b 100644
--- a/tests/unit/style/stylesheets.rs
+++ b/tests/unit/style/stylesheets.rs
@@ -31,7 +31,9 @@ use style::values::specified::{LengthOrPercentageOrAuto, PositionComponent};
use style::values::specified::TimingFunction;
pub fn block_from<I>(iterable: I) -> PropertyDeclarationBlock
-where I: IntoIterator<Item=(PropertyDeclaration, Importance)> {
+where
+ I: IntoIterator<Item = (PropertyDeclaration, Importance)>,
+{
let mut block = PropertyDeclarationBlock::new();
for (d, i) in iterable {
block.push(d, i);
@@ -69,8 +71,17 @@ fn test_parse_stylesheet() {
let url = ServoUrl::parse("about::test").unwrap();
let lock = SharedRwLock::new();
let media = Arc::new(lock.wrap(MediaList::empty()));
- let stylesheet = Stylesheet::from_str(css, url.clone(), Origin::UserAgent, media, lock,
- None, None, QuirksMode::NoQuirks, 0);
+ let stylesheet = Stylesheet::from_str(
+ css,
+ url.clone(),
+ Origin::UserAgent,
+ media,
+ lock,
+ None,
+ None,
+ QuirksMode::NoQuirks,
+ 0,
+ );
let mut namespaces = Namespaces::default();
namespaces.default = Some(ns!(html));
let expected = Stylesheet {
@@ -79,180 +90,245 @@ fn test_parse_stylesheet() {
namespaces: RwLock::new(namespaces),
url_data: RwLock::new(url),
quirks_mode: QuirksMode::NoQuirks,
- rules: CssRules::new(vec![
- CssRule::Namespace(Arc::new(stylesheet.shared_lock.wrap(NamespaceRule {
- prefix: None,
- url: NsAtom::from("http://www.w3.org/1999/xhtml"),
- source_location: SourceLocation {
- line: 1,
- column: 19,
- },
- }))),
- CssRule::Style(Arc::new(stylesheet.shared_lock.wrap(StyleRule {
- selectors: SelectorList::from_vec(vec!(
- Selector::from_vec(vec!(
- Component::DefaultNamespace(NsAtom::from("http://www.w3.org/1999/xhtml")),
- Component::LocalName(LocalName {
- name: local_name!("input"),
- lower_name: local_name!("input"),
- }),
- Component::AttributeInNoNamespace {
- local_name: local_name!("type"),
- operator: AttrSelectorOperator::Equal,
- value: "hidden".to_owned(),
- case_sensitivity: ParsedCaseSensitivity::AsciiCaseInsensitive,
- never_matches: false,
- }
- ), (0 << 20) + (1 << 10) + (1 << 0))
- )),
- block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![
- (
- PropertyDeclaration::Display(longhands::display::SpecifiedValue::None),
- Importance::Important,
- ),
- (
- PropertyDeclaration::Custom(CustomDeclaration {
- name: Atom::from("a"),
- value: CustomDeclarationValue::CSSWideKeyword(CSSWideKeyword::Inherit),
- }),
- Importance::Important,
- ),
- ]))),
- source_location: SourceLocation {
- line: 3,
- column: 9,
- },
- }))),
- CssRule::Style(Arc::new(stylesheet.shared_lock.wrap(StyleRule {
- selectors: SelectorList::from_vec(vec!(
- Selector::from_vec(vec!(
- Component::DefaultNamespace(NsAtom::from("http://www.w3.org/1999/xhtml")),
+ rules: CssRules::new(
+ vec![
+ CssRule::Namespace(Arc::new(stylesheet.shared_lock.wrap(NamespaceRule {
+ prefix: None,
+ url: NsAtom::from("http://www.w3.org/1999/xhtml"),
+ source_location: SourceLocation {
+ line: 1,
+ column: 19,
+ },
+ }))),
+ CssRule::Style(Arc::new(stylesheet.shared_lock.wrap(StyleRule {
+ selectors: SelectorList::from_vec(vec![Selector::from_vec(
+ vec![
+ Component::DefaultNamespace(NsAtom::from(
+ "http://www.w3.org/1999/xhtml",
+ )),
Component::LocalName(LocalName {
- name: local_name!("html"),
- lower_name: local_name!("html"),
+ name: local_name!("input"),
+ lower_name: local_name!("input"),
}),
- ), (0 << 20) + (0 << 10) + (1 << 0)),
- Selector::from_vec(vec!(
- Component::DefaultNamespace(NsAtom::from("http://www.w3.org/1999/xhtml")),
- Component::LocalName(LocalName {
- name: local_name!("body"),
- lower_name: local_name!("body"),
- })
- ), (0 << 20) + (0 << 10) + (1 << 0)
- ),
- )),
- block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![
- (PropertyDeclaration::Display(longhands::display::SpecifiedValue::Block),
- Importance::Normal),
- ]))),
- source_location: SourceLocation {
- line: 11,
- column: 9,
- },
- }))),
- CssRule::Style(Arc::new(stylesheet.shared_lock.wrap(StyleRule {
- selectors: SelectorList::from_vec(vec!(
- Selector::from_vec(vec!(
- Component::DefaultNamespace(NsAtom::from("http://www.w3.org/1999/xhtml")),
- Component::ID(Atom::from("d1")),
- Component::Combinator(Combinator::Child),
- Component::DefaultNamespace(NsAtom::from("http://www.w3.org/1999/xhtml")),
- Component::Class(Atom::from("ok"))
- ), (1 << 20) + (1 << 10) + (0 << 0))
- )),
- block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![
- (PropertyDeclaration::BackgroundColor(
- longhands::background_color::SpecifiedValue::Numeric {
- authored: Some("blue".to_owned().into_boxed_str()),
- parsed: cssparser::RGBA::new(0, 0, 255, 255),
- }
- ),
- Importance::Normal),
- (PropertyDeclaration::BackgroundPositionX(
- longhands::background_position_x::SpecifiedValue(
- vec![PositionComponent::zero()])),
- Importance::Normal),
- (PropertyDeclaration::BackgroundPositionY(
- longhands::background_position_y::SpecifiedValue(
- vec![PositionComponent::zero()])),
- Importance::Normal),
- (PropertyDeclaration::BackgroundRepeat(
- longhands::background_repeat::SpecifiedValue(
- vec![longhands::background_repeat::single_value
- ::get_initial_specified_value()])),
- Importance::Normal),
- (PropertyDeclaration::BackgroundAttachment(
- longhands::background_attachment::SpecifiedValue(
- vec![longhands::background_attachment::single_value
- ::get_initial_specified_value()])),
- Importance::Normal),
- (PropertyDeclaration::BackgroundImage(
- longhands::background_image::SpecifiedValue(
- vec![longhands::background_image::single_value
- ::get_initial_specified_value()])),
- Importance::Normal),
- (PropertyDeclaration::BackgroundSize(
- longhands::background_size::SpecifiedValue(
- vec![longhands::background_size::single_value
- ::get_initial_specified_value()])),
- Importance::Normal),
- (PropertyDeclaration::BackgroundOrigin(
- longhands::background_origin::SpecifiedValue(
- vec![longhands::background_origin::single_value
- ::get_initial_specified_value()])),
- Importance::Normal),
- (PropertyDeclaration::BackgroundClip(
- longhands::background_clip::SpecifiedValue(
- vec![longhands::background_clip::single_value
- ::get_initial_specified_value()])),
- Importance::Normal),
- ]))),
- source_location: SourceLocation {
- line: 15,
- column: 9,
- },
- }))),
- CssRule::Keyframes(Arc::new(stylesheet.shared_lock.wrap(KeyframesRule {
- name: KeyframesName::Ident(CustomIdent("foo".into())),
- keyframes: vec![
- Arc::new(stylesheet.shared_lock.wrap(Keyframe {
- selector: KeyframeSelector::new_for_unit_testing(
- vec![KeyframePercentage::new(0.)]),
- block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![
- (PropertyDeclaration::Width(
- LengthOrPercentageOrAuto::Percentage(Percentage(0.))),
- Importance::Normal),
- ]))),
- source_location: SourceLocation {
- line: 17,
- column: 13,
- },
- })),
- Arc::new(stylesheet.shared_lock.wrap(Keyframe {
- selector: KeyframeSelector::new_for_unit_testing(
- vec![KeyframePercentage::new(1.)]),
- block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![
- (PropertyDeclaration::Width(
- LengthOrPercentageOrAuto::Percentage(Percentage(1.))),
- Importance::Normal),
- (PropertyDeclaration::AnimationTimingFunction(
- animation_timing_function::SpecifiedValue(
- vec![TimingFunction::ease()])),
- Importance::Normal),
- ]))),
- source_location: SourceLocation {
- line: 18,
- column: 13,
- },
- })),
- ],
- vendor_prefix: None,
- source_location: SourceLocation {
- line: 16,
- column: 19,
- },
- })))
- ], &stylesheet.shared_lock),
+ Component::AttributeInNoNamespace {
+ local_name: local_name!("type"),
+ operator: AttrSelectorOperator::Equal,
+ value: "hidden".to_owned(),
+ case_sensitivity: ParsedCaseSensitivity::AsciiCaseInsensitive,
+ never_matches: false,
+ },
+ ],
+ (0 << 20) + (1 << 10) + (1 << 0),
+ )]),
+ block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![
+ (
+ PropertyDeclaration::Display(
+ longhands::display::SpecifiedValue::None,
+ ),
+ Importance::Important,
+ ),
+ (
+ PropertyDeclaration::Custom(CustomDeclaration {
+ name: Atom::from("a"),
+ value: CustomDeclarationValue::CSSWideKeyword(
+ CSSWideKeyword::Inherit,
+ ),
+ }),
+ Importance::Important,
+ ),
+ ]))),
+ source_location: SourceLocation { line: 3, column: 9 },
+ }))),
+ CssRule::Style(Arc::new(stylesheet.shared_lock.wrap(StyleRule {
+ selectors: SelectorList::from_vec(vec![
+ Selector::from_vec(
+ vec![
+ Component::DefaultNamespace(NsAtom::from(
+ "http://www.w3.org/1999/xhtml",
+ )),
+ Component::LocalName(LocalName {
+ name: local_name!("html"),
+ lower_name: local_name!("html"),
+ }),
+ ],
+ (0 << 20) + (0 << 10) + (1 << 0),
+ ),
+ Selector::from_vec(
+ vec![
+ Component::DefaultNamespace(NsAtom::from(
+ "http://www.w3.org/1999/xhtml",
+ )),
+ Component::LocalName(LocalName {
+ name: local_name!("body"),
+ lower_name: local_name!("body"),
+ }),
+ ],
+ (0 << 20) + (0 << 10) + (1 << 0),
+ ),
+ ]),
+ block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![(
+ PropertyDeclaration::Display(longhands::display::SpecifiedValue::Block),
+ Importance::Normal,
+ )]))),
+ source_location: SourceLocation {
+ line: 11,
+ column: 9,
+ },
+ }))),
+ CssRule::Style(Arc::new(stylesheet.shared_lock.wrap(StyleRule {
+ selectors: SelectorList::from_vec(vec![Selector::from_vec(
+ vec![
+ Component::DefaultNamespace(NsAtom::from(
+ "http://www.w3.org/1999/xhtml",
+ )),
+ Component::ID(Atom::from("d1")),
+ Component::Combinator(Combinator::Child),
+ Component::DefaultNamespace(NsAtom::from(
+ "http://www.w3.org/1999/xhtml",
+ )),
+ Component::Class(Atom::from("ok")),
+ ],
+ (1 << 20) + (1 << 10) + (0 << 0),
+ )]),
+ block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![
+ (
+ PropertyDeclaration::BackgroundColor(
+ longhands::background_color::SpecifiedValue::Numeric {
+ authored: Some("blue".to_owned().into_boxed_str()),
+ parsed: cssparser::RGBA::new(0, 0, 255, 255),
+ },
+ ),
+ Importance::Normal,
+ ),
+ (
+ PropertyDeclaration::BackgroundPositionX(
+ longhands::background_position_x::SpecifiedValue(vec![
+ PositionComponent::zero(),
+ ]),
+ ),
+ Importance::Normal,
+ ),
+ (
+ PropertyDeclaration::BackgroundPositionY(
+ longhands::background_position_y::SpecifiedValue(vec![
+ PositionComponent::zero(),
+ ]),
+ ),
+ Importance::Normal,
+ ),
+ (
+ PropertyDeclaration::BackgroundRepeat(
+ longhands::background_repeat::SpecifiedValue(
+ vec![longhands::background_repeat::single_value
+ ::get_initial_specified_value()],
+ ),
+ ),
+ Importance::Normal,
+ ),
+ (
+ PropertyDeclaration::BackgroundAttachment(
+ longhands::background_attachment::SpecifiedValue(
+ vec![longhands::background_attachment::single_value
+ ::get_initial_specified_value()],
+ ),
+ ),
+ Importance::Normal,
+ ),
+ (
+ PropertyDeclaration::BackgroundImage(
+ longhands::background_image::SpecifiedValue(
+ vec![longhands::background_image::single_value
+ ::get_initial_specified_value()],
+ ),
+ ),
+ Importance::Normal,
+ ),
+ (
+ PropertyDeclaration::BackgroundSize(
+ longhands::background_size::SpecifiedValue(
+ vec![longhands::background_size::single_value
+ ::get_initial_specified_value()],
+ ),
+ ),
+ Importance::Normal,
+ ),
+ (
+ PropertyDeclaration::BackgroundOrigin(
+ longhands::background_origin::SpecifiedValue(
+ vec![longhands::background_origin::single_value
+ ::get_initial_specified_value()],
+ ),
+ ),
+ Importance::Normal,
+ ),
+ (
+ PropertyDeclaration::BackgroundClip(
+ longhands::background_clip::SpecifiedValue(
+ vec![longhands::background_clip::single_value
+ ::get_initial_specified_value()],
+ ),
+ ),
+ Importance::Normal,
+ ),
+ ]))),
+ source_location: SourceLocation {
+ line: 15,
+ column: 9,
+ },
+ }))),
+ CssRule::Keyframes(Arc::new(stylesheet.shared_lock.wrap(KeyframesRule {
+ name: KeyframesName::Ident(CustomIdent("foo".into())),
+ keyframes: vec![
+ Arc::new(stylesheet.shared_lock.wrap(Keyframe {
+ selector: KeyframeSelector::new_for_unit_testing(vec![
+ KeyframePercentage::new(0.),
+ ]),
+ block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![(
+ PropertyDeclaration::Width(
+ LengthOrPercentageOrAuto::Percentage(Percentage(0.)),
+ ),
+ Importance::Normal,
+ )]))),
+ source_location: SourceLocation {
+ line: 17,
+ column: 13,
+ },
+ })),
+ Arc::new(stylesheet.shared_lock.wrap(Keyframe {
+ selector: KeyframeSelector::new_for_unit_testing(vec![
+ KeyframePercentage::new(1.),
+ ]),
+ block: Arc::new(stylesheet.shared_lock.wrap(block_from(vec![
+ (
+ PropertyDeclaration::Width(
+ LengthOrPercentageOrAuto::Percentage(Percentage(1.)),
+ ),
+ Importance::Normal,
+ ),
+ (
+ PropertyDeclaration::AnimationTimingFunction(
+ animation_timing_function::SpecifiedValue(vec![
+ TimingFunction::ease(),
+ ]),
+ ),
+ Importance::Normal,
+ ),
+ ]))),
+ source_location: SourceLocation {
+ line: 18,
+ column: 13,
+ },
+ })),
+ ],
+ vendor_prefix: None,
+ source_location: SourceLocation {
+ line: 16,
+ column: 19,
+ },
+ }))),
+ ],
+ &stylesheet.shared_lock,
+ ),
source_map_url: RwLock::new(None),
source_url: RwLock::new(None),
},
@@ -266,10 +342,10 @@ fn test_parse_stylesheet() {
#[derive(Debug)]
struct CSSError {
- pub url : ServoUrl,
+ pub url: ServoUrl,
pub line: u32,
pub column: u32,
- pub message: String
+ pub message: String,
}
struct TestingErrorReporter {
@@ -285,11 +361,21 @@ impl TestingErrorReporter {
fn assert_messages_contain(&self, expected_errors: &[(u32, u32, &str)]) {
let errors = self.errors.borrow();
- for (i, (error, &(line, column, message))) in errors.iter().zip(expected_errors).enumerate() {
- assert_eq!((error.line, error.column), (line, column),
- "line/column numbers of the {}th error: {:?}", i + 1, error.message);
- assert!(error.message.contains(message),
- "{:?} does not contain {:?}", error.message, message);
+ for (i, (error, &(line, column, message))) in errors.iter().zip(expected_errors).enumerate()
+ {
+ assert_eq!(
+ (error.line, error.column),
+ (line, column),
+ "line/column numbers of the {}th error: {:?}",
+ i + 1,
+ error.message
+ );
+ assert!(
+ error.message.contains(message),
+ "{:?} does not contain {:?}",
+ error.message,
+ message
+ );
}
if errors.len() < expected_errors.len() {
panic!("Missing errors: {:#?}", &expected_errors[errors.len()..]);
@@ -301,22 +387,16 @@ impl TestingErrorReporter {
}
impl ParseErrorReporter for TestingErrorReporter {
- fn report_error(&self,
- url: &ServoUrl,
- location: SourceLocation,
- error: ContextualParseError) {
- self.errors.borrow_mut().push(
- CSSError{
- url: url.clone(),
- line: location.line,
- column: location.column,
- message: error.to_string(),
- }
- )
+ fn report_error(&self, url: &ServoUrl, location: SourceLocation, error: ContextualParseError) {
+ self.errors.borrow_mut().push(CSSError {
+ url: url.clone(),
+ line: location.line,
+ column: location.column,
+ message: error.to_string(),
+ })
}
}
-
#[test]
fn test_report_error_stylesheet() {
PREFS.set("layout.viewport.enabled", PrefValue::Boolean(true));
@@ -342,29 +422,50 @@ fn test_report_error_stylesheet() {
let lock = SharedRwLock::new();
let media = Arc::new(lock.wrap(MediaList::empty()));
- Stylesheet::from_str(css, url.clone(), Origin::UserAgent, media, lock,
- None, Some(&error_reporter), QuirksMode::NoQuirks, 5);
+ Stylesheet::from_str(
+ css,
+ url.clone(),
+ Origin::UserAgent,
+ media,
+ lock,
+ None,
+ Some(&error_reporter),
+ QuirksMode::NoQuirks,
+ 5,
+ );
error_reporter.assert_messages_contain(&[
- (8, 18, "Unsupported property declaration: 'display: invalid;'"),
- (9, 27, "Unsupported property declaration: 'background-image:"), // FIXME: column should be around 56
+ (
+ 8,
+ 18,
+ "Unsupported property declaration: 'display: invalid;'",
+ ),
+ (
+ 9,
+ 27,
+ "Unsupported property declaration: 'background-image:",
+ ), // FIXME: column should be around 56
(10, 17, "Unsupported property declaration: 'invalid: true;'"),
(12, 28, "Invalid media rule"),
(13, 30, "Unsupported @font-face descriptor declaration"),
-
// When @counter-style is supported, this should be replaced with two errors
(14, 19, "Invalid rule: '@counter-style "),
-
// When @font-feature-values is supported, this should be replaced with two errors
(15, 25, "Invalid rule: '@font-feature-values "),
-
(16, 13, "Invalid rule: '@invalid'"),
(17, 29, "Invalid rule: '@invalid'"),
-
(18, 34, "Invalid rule: '@supports "),
(19, 26, "Invalid keyframe rule: 'from invalid '"),
- (19, 52, "Unsupported keyframe property declaration: 'margin: 0 invalid 0;'"),
- (20, 29, "Unsupported @viewport descriptor declaration: 'width: 320px invalid auto;'"),
+ (
+ 19,
+ 52,
+ "Unsupported keyframe property declaration: 'margin: 0 invalid 0;'",
+ ),
+ (
+ 20,
+ 29,
+ "Unsupported @viewport descriptor declaration: 'width: 320px invalid auto;'",
+ ),
]);
assert_eq!(error_reporter.errors.borrow()[0].url, url);
@@ -384,28 +485,50 @@ fn test_no_report_unrecognized_vendor_properties() {
let lock = SharedRwLock::new();
let media = Arc::new(lock.wrap(MediaList::empty()));
- Stylesheet::from_str(css, url, Origin::UserAgent, media, lock,
- None, Some(&error_reporter), QuirksMode::NoQuirks, 0);
+ Stylesheet::from_str(
+ css,
+ url,
+ Origin::UserAgent,
+ media,
+ lock,
+ None,
+ Some(&error_reporter),
+ QuirksMode::NoQuirks,
+ 0,
+ );
- error_reporter.assert_messages_contain(&[
- (4, 31, "Unsupported property declaration: '-moz-background-color: red;'"),
- ]);
+ error_reporter.assert_messages_contain(&[(
+ 4,
+ 31,
+ "Unsupported property declaration: '-moz-background-color: red;'",
+ )]);
}
#[test]
fn test_source_map_url() {
let tests = vec![
("", None),
- ("/*# sourceMappingURL=something */", Some("something".to_string())),
+ (
+ "/*# sourceMappingURL=something */",
+ Some("something".to_string()),
+ ),
];
for test in tests {
let url = ServoUrl::parse("about::test").unwrap();
let lock = SharedRwLock::new();
let media = Arc::new(lock.wrap(MediaList::empty()));
- let stylesheet = Stylesheet::from_str(test.0, url.clone(), Origin::UserAgent, media, lock,
- None, None, QuirksMode::NoQuirks,
- 0);
+ let stylesheet = Stylesheet::from_str(
+ test.0,
+ url.clone(),
+ Origin::UserAgent,
+ media,
+ lock,
+ None,
+ None,
+ QuirksMode::NoQuirks,
+ 0,
+ );
let url_opt = stylesheet.contents.source_map_url.read();
assert_eq!(*url_opt, test.1);
}
@@ -422,9 +545,17 @@ fn test_source_url() {
let url = ServoUrl::parse("about::test").unwrap();
let lock = SharedRwLock::new();
let media = Arc::new(lock.wrap(MediaList::empty()));
- let stylesheet = Stylesheet::from_str(test.0, url.clone(), Origin::UserAgent, media, lock,
- None, None, QuirksMode::NoQuirks,
- 0);
+ let stylesheet = Stylesheet::from_str(
+ test.0,
+ url.clone(),
+ Origin::UserAgent,
+ media,
+ lock,
+ None,
+ None,
+ QuirksMode::NoQuirks,
+ 0,
+ );
let url_opt = stylesheet.contents.source_url.read();
assert_eq!(*url_opt, test.1);
}
diff --git a/tests/unit/style/stylist.rs b/tests/unit/style/stylist.rs
index 01446cddcc1..80d017611b7 100644
--- a/tests/unit/style/stylist.rs
+++ b/tests/unit/style/stylist.rs
@@ -24,37 +24,55 @@ use style::thread_state::{self, ThreadState};
/// Each sublist of the result contains the Rules for one StyleRule.
fn get_mock_rules(css_selectors: &[&str]) -> (Vec<Vec<Rule>>, SharedRwLock) {
let shared_lock = SharedRwLock::new();
- (css_selectors.iter().enumerate().map(|(i, selectors)| {
- let selectors = SelectorParser::parse_author_origin_no_namespace(selectors).unwrap();
-
- let locked = Arc::new(shared_lock.wrap(StyleRule {
- selectors: selectors,
- block: Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one(
- PropertyDeclaration::Display(
- longhands::display::SpecifiedValue::Block),
- Importance::Normal
- ))),
- source_location: SourceLocation {
- line: 0,
- column: 0,
- },
- }));
-
- let guard = shared_lock.read();
- let rule = locked.read_with(&guard);
- rule.selectors.0.iter().map(|s| {
- Rule::new(s.clone(), AncestorHashes::new(s, QuirksMode::NoQuirks), locked.clone(), i as u32)
- }).collect()
- }).collect(), shared_lock)
+ (
+ css_selectors
+ .iter()
+ .enumerate()
+ .map(|(i, selectors)| {
+ let selectors =
+ SelectorParser::parse_author_origin_no_namespace(selectors).unwrap();
+
+ let locked = Arc::new(shared_lock.wrap(StyleRule {
+ selectors: selectors,
+ block: Arc::new(shared_lock.wrap(PropertyDeclarationBlock::with_one(
+ PropertyDeclaration::Display(longhands::display::SpecifiedValue::Block),
+ Importance::Normal,
+ ))),
+ source_location: SourceLocation { line: 0, column: 0 },
+ }));
+
+ let guard = shared_lock.read();
+ let rule = locked.read_with(&guard);
+ rule.selectors
+ .0
+ .iter()
+ .map(|s| {
+ Rule::new(
+ s.clone(),
+ AncestorHashes::new(s, QuirksMode::NoQuirks),
+ locked.clone(),
+ i as u32,
+ )
+ })
+ .collect()
+ })
+ .collect(),
+ shared_lock,
+ )
}
fn parse_selectors(selectors: &[&str]) -> Vec<Selector<SelectorImpl>> {
- selectors.iter()
- .map(|x| SelectorParser::parse_author_origin_no_namespace(x).unwrap().0
- .into_iter()
- .nth(0)
- .unwrap())
- .collect()
+ selectors
+ .iter()
+ .map(|x| {
+ SelectorParser::parse_author_origin_no_namespace(x)
+ .unwrap()
+ .0
+ .into_iter()
+ .nth(0)
+ .unwrap()
+ })
+ .collect()
}
#[test]
@@ -65,14 +83,13 @@ fn test_revalidation_selectors() {
"div:not(.foo)",
"div span",
"div > span",
-
// ID selectors.
"#foo1",
"#foo2::before",
"#foo3 > span",
"#foo1 > span", // FIXME(bz): This one should not be a
- // revalidation selector, since #foo1 should be in the
- // rule hash.
+ // revalidation selector, since #foo1 should be in the
+ // rule hash.
// Attribute selectors.
"div[foo]",
@@ -84,7 +101,6 @@ fn test_revalidation_selectors() {
"div[foo $= \"bar\"]",
"div[foo *= \"bar\"]",
"*|div[foo][bar = \"baz\"]",
-
// Non-state-based pseudo-classes.
"div:empty",
"div:first-child",
@@ -97,7 +113,6 @@ fn test_revalidation_selectors() {
"div:first-of-type",
"div:last-of-type",
"div:only-of-type",
-
// Note: it would be nice to test :moz-any and the various other non-TS
// pseudo classes supported by gecko, but we don't have access to those
// in these unit tests. :-(
@@ -105,18 +120,17 @@ fn test_revalidation_selectors() {
// Sibling combinators.
"span + div",
"span ~ div",
-
// Selectors in the ancestor chain (needed for cousin sharing).
"p:first-child span",
- ]).into_iter()
- .filter(|s| needs_revalidation_for_testing(&s))
- .collect::<Vec<_>>();
+ ])
+ .into_iter()
+ .filter(|s| needs_revalidation_for_testing(&s))
+ .collect::<Vec<_>>();
let reference = parse_selectors(&[
// ID selectors.
"#foo3 > span",
"#foo1 > span",
-
// Attribute selectors.
"div[foo]",
"div:not([foo])",
@@ -127,7 +141,6 @@ fn test_revalidation_selectors() {
"div[foo $= \"bar\"]",
"div[foo *= \"bar\"]",
"*|div[foo][bar = \"baz\"]",
-
// Non-state-based pseudo-classes.
"div:empty",
"div:first-child",
@@ -140,15 +153,14 @@ fn test_revalidation_selectors() {
"div:first-of-type",
"div:last-of-type",
"div:only-of-type",
-
// Sibling combinators.
"span + div",
"span ~ div",
-
// Selectors in the ancestor chain (needed for cousin sharing).
"p:first-child span",
- ]).into_iter()
- .collect::<Vec<_>>();
+ ])
+ .into_iter()
+ .collect::<Vec<_>>();
assert_eq!(test.len(), reference.len());
for (t, r) in test.into_iter().zip(reference.into_iter()) {
@@ -161,25 +173,52 @@ fn test_rule_ordering_same_specificity() {
let (rules_list, _) = get_mock_rules(&["a.intro", "img.sidebar"]);
let a = &rules_list[0][0];
let b = &rules_list[1][0];
- assert!((a.specificity(), a.source_order) < ((b.specificity(), b.source_order)),
- "The rule that comes later should win.");
+ assert!(
+ (a.specificity(), a.source_order) < ((b.specificity(), b.source_order)),
+ "The rule that comes later should win."
+ );
}
#[test]
fn test_insert() {
let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]);
let mut selector_map = SelectorMap::new();
- selector_map.insert(rules_list[1][0].clone(), QuirksMode::NoQuirks)
- .expect("OOM");
- assert_eq!(1, selector_map.id_hash.get(&Atom::from("top"), QuirksMode::NoQuirks).unwrap()[0].source_order);
- selector_map.insert(rules_list[0][0].clone(), QuirksMode::NoQuirks)
- .expect("OOM");
- assert_eq!(0, selector_map.class_hash.get(&Atom::from("foo"), QuirksMode::NoQuirks).unwrap()[0].source_order);
- assert!(selector_map.class_hash.get(&Atom::from("intro"), QuirksMode::NoQuirks).is_none());
+ selector_map
+ .insert(rules_list[1][0].clone(), QuirksMode::NoQuirks)
+ .expect("OOM");
+ assert_eq!(
+ 1,
+ selector_map
+ .id_hash
+ .get(&Atom::from("top"), QuirksMode::NoQuirks)
+ .unwrap()[0]
+ .source_order
+ );
+ selector_map
+ .insert(rules_list[0][0].clone(), QuirksMode::NoQuirks)
+ .expect("OOM");
+ assert_eq!(
+ 0,
+ selector_map
+ .class_hash
+ .get(&Atom::from("foo"), QuirksMode::NoQuirks)
+ .unwrap()[0]
+ .source_order
+ );
+ assert!(
+ selector_map
+ .class_hash
+ .get(&Atom::from("intro"), QuirksMode::NoQuirks)
+ .is_none()
+ );
}
fn mock_stylist() -> Stylist {
- let device = Device::new(MediaType::screen(), TypedSize2D::new(0f32, 0f32), TypedScale::new(1.0));
+ let device = Device::new(
+ MediaType::screen(),
+ TypedSize2D::new(0f32, 0f32),
+ TypedScale::new(1.0),
+ );
Stylist::new(device, QuirksMode::NoQuirks)
}
diff --git a/tests/unit/style/viewport.rs b/tests/unit/style/viewport.rs
index a8d01651c3d..2ad0c773c0a 100644
--- a/tests/unit/style/viewport.rs
+++ b/tests/unit/style/viewport.rs
@@ -34,15 +34,14 @@ macro_rules! stylesheet {
None,
None,
QuirksMode::NoQuirks,
- 0
+ 0,
))
- }
+ };
}
-fn test_viewport_rule<F>(css: &str,
- device: &Device,
- callback: F)
- where F: Fn(&Vec<ViewportDescriptorDeclaration>, &str)
+fn test_viewport_rule<F>(css: &str, device: &Device, callback: F)
+where
+ F: Fn(&Vec<ViewportDescriptorDeclaration>, &str),
{
PREFS.set("layout.viewport.enabled", PrefValue::Boolean(true));
let stylesheet = stylesheet!(css, Author);
@@ -55,7 +54,8 @@ fn test_viewport_rule<F>(css: &str,
}
fn test_meta_viewport<F>(meta: &str, callback: F)
- where F: Fn(&Vec<ViewportDescriptorDeclaration>, &str)
+where
+ F: Fn(&Vec<ViewportDescriptorDeclaration>, &str),
{
if let Some(mut rule) = ViewportRule::from_meta(meta) {
// from_meta uses a hash-map to collect the declarations, so we need to
@@ -74,29 +74,46 @@ fn test_meta_viewport<F>(meta: &str, callback: F)
macro_rules! assert_decl_len {
($declarations:ident == 1) => {
- assert_eq!($declarations.len(), 1,
- "expected 1 declaration; have {}: {:?})",
- $declarations.len(), $declarations)
+ assert_eq!(
+ $declarations.len(),
+ 1,
+ "expected 1 declaration; have {}: {:?})",
+ $declarations.len(),
+ $declarations
+ )
};
($declarations:ident == $len:expr) => {
- assert_eq!($declarations.len(), $len,
- "expected {} declarations; have {}: {:?})",
- $len, $declarations.len(), $declarations)
- }
+ assert_eq!(
+ $declarations.len(),
+ $len,
+ "expected {} declarations; have {}: {:?})",
+ $len,
+ $declarations.len(),
+ $declarations
+ )
+ };
}
macro_rules! viewport_length {
($value:expr, px) => {
- ViewportLength::Specified(LengthOrPercentageOrAuto::Length(NoCalcLength::from_px($value)))
+ ViewportLength::Specified(LengthOrPercentageOrAuto::Length(NoCalcLength::from_px(
+ $value,
+ )))
};
($value:expr, vw) => {
- ViewportLength::Specified(LengthOrPercentageOrAuto::Length(ViewportPercentage(Vw($value))))
- }
+ ViewportLength::Specified(LengthOrPercentageOrAuto::Length(ViewportPercentage(Vw(
+ $value,
+ ))))
+ };
}
#[test]
fn empty_viewport_rule() {
- let device = Device::new(MediaType::screen(), TypedSize2D::new(800., 600.), TypedScale::new(1.0));
+ let device = Device::new(
+ MediaType::screen(),
+ TypedSize2D::new(800., 600.),
+ TypedScale::new(1.0),
+ );
test_viewport_rule("@viewport {}", &device, |declarations, css| {
println!("{}", css);
@@ -119,35 +136,77 @@ macro_rules! assert_decl_eq {
#[test]
fn simple_viewport_rules() {
- let device = Device::new(MediaType::screen(), TypedSize2D::new(800., 600.), TypedScale::new(1.0));
+ let device = Device::new(
+ MediaType::screen(),
+ TypedSize2D::new(800., 600.),
+ TypedScale::new(1.0),
+ );
- test_viewport_rule("@viewport { width: auto; height: auto;\
- zoom: auto; min-zoom: 0; max-zoom: 200%;\
- user-zoom: zoom; orientation: auto; }",
- &device, |declarations, css| {
- println!("{}", css);
- assert_decl_len!(declarations == 9);
- assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto));
- assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::Specified(Auto));
- assert_decl_eq!(&declarations[2], Author, MinHeight: ViewportLength::Specified(Auto));
- assert_decl_eq!(&declarations[3], Author, MaxHeight: ViewportLength::Specified(Auto));
- assert_decl_eq!(&declarations[4], Author, Zoom: Zoom::Auto);
- assert_decl_eq!(&declarations[5], Author, MinZoom: Zoom::Number(0.));
- assert_decl_eq!(&declarations[6], Author, MaxZoom: Zoom::Percentage(2.));
- assert_decl_eq!(&declarations[7], Author, UserZoom: UserZoom::Zoom);
- assert_decl_eq!(&declarations[8], Author, Orientation: Orientation::Auto);
- });
+ test_viewport_rule(
+ "@viewport { width: auto; height: auto;\
+ zoom: auto; min-zoom: 0; max-zoom: 200%;\
+ user-zoom: zoom; orientation: auto; }",
+ &device,
+ |declarations, css| {
+ println!("{}", css);
+ assert_decl_len!(declarations == 9);
+ assert_decl_eq!(
+ &declarations[0],
+ Author,
+ MinWidth: ViewportLength::Specified(Auto)
+ );
+ assert_decl_eq!(
+ &declarations[1],
+ Author,
+ MaxWidth: ViewportLength::Specified(Auto)
+ );
+ assert_decl_eq!(
+ &declarations[2],
+ Author,
+ MinHeight: ViewportLength::Specified(Auto)
+ );
+ assert_decl_eq!(
+ &declarations[3],
+ Author,
+ MaxHeight: ViewportLength::Specified(Auto)
+ );
+ assert_decl_eq!(&declarations[4], Author, Zoom: Zoom::Auto);
+ assert_decl_eq!(&declarations[5], Author, MinZoom: Zoom::Number(0.));
+ assert_decl_eq!(&declarations[6], Author, MaxZoom: Zoom::Percentage(2.));
+ assert_decl_eq!(&declarations[7], Author, UserZoom: UserZoom::Zoom);
+ assert_decl_eq!(&declarations[8], Author, Orientation: Orientation::Auto);
+ },
+ );
- test_viewport_rule("@viewport { min-width: 200px; max-width: auto;\
- min-height: 200px; max-height: auto; }",
- &device, |declarations, css| {
- println!("{}", css);
- assert_decl_len!(declarations == 4);
- assert_decl_eq!(&declarations[0], Author, MinWidth: viewport_length!(200., px));
- assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::Specified(Auto));
- assert_decl_eq!(&declarations[2], Author, MinHeight: viewport_length!(200., px));
- assert_decl_eq!(&declarations[3], Author, MaxHeight: ViewportLength::Specified(Auto));
- });
+ test_viewport_rule(
+ "@viewport { min-width: 200px; max-width: auto;\
+ min-height: 200px; max-height: auto; }",
+ &device,
+ |declarations, css| {
+ println!("{}", css);
+ assert_decl_len!(declarations == 4);
+ assert_decl_eq!(
+ &declarations[0],
+ Author,
+ MinWidth: viewport_length!(200., px)
+ );
+ assert_decl_eq!(
+ &declarations[1],
+ Author,
+ MaxWidth: ViewportLength::Specified(Auto)
+ );
+ assert_decl_eq!(
+ &declarations[2],
+ Author,
+ MinHeight: viewport_length!(200., px)
+ );
+ assert_decl_eq!(
+ &declarations[3],
+ Author,
+ MaxHeight: ViewportLength::Specified(Auto)
+ );
+ },
+ );
}
#[test]
@@ -155,129 +214,278 @@ fn simple_meta_viewport_contents() {
test_meta_viewport("width=500, height=600", |declarations, meta| {
println!("{}", meta);
assert_decl_len!(declarations == 4);
- assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::ExtendToZoom);
- assert_decl_eq!(&declarations[1], Author, MaxWidth: viewport_length!(500., px));
- assert_decl_eq!(&declarations[2], Author, MinHeight: ViewportLength::ExtendToZoom);
- assert_decl_eq!(&declarations[3], Author, MaxHeight: viewport_length!(600., px));
+ assert_decl_eq!(
+ &declarations[0],
+ Author,
+ MinWidth: ViewportLength::ExtendToZoom
+ );
+ assert_decl_eq!(
+ &declarations[1],
+ Author,
+ MaxWidth: viewport_length!(500., px)
+ );
+ assert_decl_eq!(
+ &declarations[2],
+ Author,
+ MinHeight: ViewportLength::ExtendToZoom
+ );
+ assert_decl_eq!(
+ &declarations[3],
+ Author,
+ MaxHeight: viewport_length!(600., px)
+ );
});
test_meta_viewport("initial-scale=1.0", |declarations, meta| {
println!("{}", meta);
assert_decl_len!(declarations == 3);
- assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::ExtendToZoom);
- assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::ExtendToZoom);
+ assert_decl_eq!(
+ &declarations[0],
+ Author,
+ MinWidth: ViewportLength::ExtendToZoom
+ );
+ assert_decl_eq!(
+ &declarations[1],
+ Author,
+ MaxWidth: ViewportLength::ExtendToZoom
+ );
assert_decl_eq!(&declarations[2], Author, Zoom: Zoom::Number(1.));
});
- test_meta_viewport("initial-scale=2.0, height=device-width", |declarations, meta| {
- println!("{}", meta);
- assert_decl_len!(declarations == 5);
- assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto));
- assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::Specified(Auto));
- assert_decl_eq!(&declarations[2], Author, MinHeight: ViewportLength::ExtendToZoom);
- assert_decl_eq!(&declarations[3], Author, MaxHeight: viewport_length!(100., vw));
- assert_decl_eq!(&declarations[4], Author, Zoom: Zoom::Number(2.));
- });
+ test_meta_viewport(
+ "initial-scale=2.0, height=device-width",
+ |declarations, meta| {
+ println!("{}", meta);
+ assert_decl_len!(declarations == 5);
+ assert_decl_eq!(
+ &declarations[0],
+ Author,
+ MinWidth: ViewportLength::Specified(Auto)
+ );
+ assert_decl_eq!(
+ &declarations[1],
+ Author,
+ MaxWidth: ViewportLength::Specified(Auto)
+ );
+ assert_decl_eq!(
+ &declarations[2],
+ Author,
+ MinHeight: ViewportLength::ExtendToZoom
+ );
+ assert_decl_eq!(
+ &declarations[3],
+ Author,
+ MaxHeight: viewport_length!(100., vw)
+ );
+ assert_decl_eq!(&declarations[4], Author, Zoom: Zoom::Number(2.));
+ },
+ );
- test_meta_viewport("width=480, initial-scale=2.0, user-scalable=1", |declarations, meta| {
- println!("{}", meta);
- assert_decl_len!(declarations == 4);
- assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::ExtendToZoom);
- assert_decl_eq!(&declarations[1], Author, MaxWidth: viewport_length!(480., px));
- assert_decl_eq!(&declarations[2], Author, Zoom: Zoom::Number(2.));
- assert_decl_eq!(&declarations[3], Author, UserZoom: UserZoom::Zoom);
- });
+ test_meta_viewport(
+ "width=480, initial-scale=2.0, user-scalable=1",
+ |declarations, meta| {
+ println!("{}", meta);
+ assert_decl_len!(declarations == 4);
+ assert_decl_eq!(
+ &declarations[0],
+ Author,
+ MinWidth: ViewportLength::ExtendToZoom
+ );
+ assert_decl_eq!(
+ &declarations[1],
+ Author,
+ MaxWidth: viewport_length!(480., px)
+ );
+ assert_decl_eq!(&declarations[2], Author, Zoom: Zoom::Number(2.));
+ assert_decl_eq!(&declarations[3], Author, UserZoom: UserZoom::Zoom);
+ },
+ );
}
#[test]
fn cascading_within_viewport_rule() {
- let device = Device::new(MediaType::screen(), TypedSize2D::new(800., 600.), TypedScale::new(1.0));
+ let device = Device::new(
+ MediaType::screen(),
+ TypedSize2D::new(800., 600.),
+ TypedScale::new(1.0),
+ );
// normal order of appearance
- test_viewport_rule("@viewport { min-width: 200px; min-width: auto; }",
- &device, |declarations, css| {
- println!("{}", css);
- assert_decl_len!(declarations == 1);
- assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto));
- });
+ test_viewport_rule(
+ "@viewport { min-width: 200px; min-width: auto; }",
+ &device,
+ |declarations, css| {
+ println!("{}", css);
+ assert_decl_len!(declarations == 1);
+ assert_decl_eq!(
+ &declarations[0],
+ Author,
+ MinWidth: ViewportLength::Specified(Auto)
+ );
+ },
+ );
// !important order of appearance
- test_viewport_rule("@viewport { min-width: 200px !important; min-width: auto !important; }",
- &device, |declarations, css| {
- println!("{}", css);
- assert_decl_len!(declarations == 1);
- assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto), !important);
- });
+ test_viewport_rule(
+ "@viewport { min-width: 200px !important; min-width: auto !important; }",
+ &device,
+ |declarations, css| {
+ println!("{}", css);
+ assert_decl_len!(declarations == 1);
+ assert_decl_eq!(
+ &declarations[0],
+ Author,
+ MinWidth: ViewportLength::Specified(Auto),
+ !important
+ );
+ },
+ );
// !important vs normal
- test_viewport_rule("@viewport { min-width: auto !important; min-width: 200px; }",
- &device, |declarations, css| {
- println!("{}", css);
- assert_decl_len!(declarations == 1);
- assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto), !important);
- });
+ test_viewport_rule(
+ "@viewport { min-width: auto !important; min-width: 200px; }",
+ &device,
+ |declarations, css| {
+ println!("{}", css);
+ assert_decl_len!(declarations == 1);
+ assert_decl_eq!(
+ &declarations[0],
+ Author,
+ MinWidth: ViewportLength::Specified(Auto),
+ !important
+ );
+ },
+ );
// normal longhands vs normal shorthand
- test_viewport_rule("@viewport { min-width: 200px; max-width: 200px; width: auto; }",
- &device, |declarations, css| {
- println!("{}", css);
- assert_decl_len!(declarations == 2);
- assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto));
- assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::Specified(Auto));
- });
+ test_viewport_rule(
+ "@viewport { min-width: 200px; max-width: 200px; width: auto; }",
+ &device,
+ |declarations, css| {
+ println!("{}", css);
+ assert_decl_len!(declarations == 2);
+ assert_decl_eq!(
+ &declarations[0],
+ Author,
+ MinWidth: ViewportLength::Specified(Auto)
+ );
+ assert_decl_eq!(
+ &declarations[1],
+ Author,
+ MaxWidth: ViewportLength::Specified(Auto)
+ );
+ },
+ );
// normal shorthand vs normal longhands
- test_viewport_rule("@viewport { width: 200px; min-width: auto; max-width: auto; }",
- &device, |declarations, css| {
- println!("{}", css);
- assert_decl_len!(declarations == 2);
- assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto));
- assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::Specified(Auto));
- });
+ test_viewport_rule(
+ "@viewport { width: 200px; min-width: auto; max-width: auto; }",
+ &device,
+ |declarations, css| {
+ println!("{}", css);
+ assert_decl_len!(declarations == 2);
+ assert_decl_eq!(
+ &declarations[0],
+ Author,
+ MinWidth: ViewportLength::Specified(Auto)
+ );
+ assert_decl_eq!(
+ &declarations[1],
+ Author,
+ MaxWidth: ViewportLength::Specified(Auto)
+ );
+ },
+ );
// one !important longhand vs normal shorthand
- test_viewport_rule("@viewport { min-width: auto !important; width: 200px; }",
- &device, |declarations, css| {
- println!("{}", css);
- assert_decl_len!(declarations == 2);
- assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto), !important);
- assert_decl_eq!(&declarations[1], Author, MaxWidth: viewport_length!(200., px));
- });
+ test_viewport_rule(
+ "@viewport { min-width: auto !important; width: 200px; }",
+ &device,
+ |declarations, css| {
+ println!("{}", css);
+ assert_decl_len!(declarations == 2);
+ assert_decl_eq!(
+ &declarations[0],
+ Author,
+ MinWidth: ViewportLength::Specified(Auto),
+ !important
+ );
+ assert_decl_eq!(
+ &declarations[1],
+ Author,
+ MaxWidth: viewport_length!(200., px)
+ );
+ },
+ );
// both !important longhands vs normal shorthand
- test_viewport_rule("@viewport { min-width: auto !important; max-width: auto !important; width: 200px; }",
- &device, |declarations, css| {
- println!("{}", css);
- assert_decl_len!(declarations == 2);
- assert_decl_eq!(&declarations[0], Author, MinWidth: ViewportLength::Specified(Auto), !important);
- assert_decl_eq!(&declarations[1], Author, MaxWidth: ViewportLength::Specified(Auto), !important);
- });
+ test_viewport_rule(
+ "@viewport { min-width: auto !important; max-width: auto !important; width: 200px; }",
+ &device,
+ |declarations, css| {
+ println!("{}", css);
+ assert_decl_len!(declarations == 2);
+ assert_decl_eq!(
+ &declarations[0],
+ Author,
+ MinWidth: ViewportLength::Specified(Auto),
+ !important
+ );
+ assert_decl_eq!(
+ &declarations[1],
+ Author,
+ MaxWidth: ViewportLength::Specified(Auto),
+ !important
+ );
+ },
+ );
}
#[test]
fn multiple_stylesheets_cascading() {
PREFS.set("layout.viewport.enabled", PrefValue::Boolean(true));
- let device = Device::new(MediaType::screen(), TypedSize2D::new(800., 600.), TypedScale::new(1.0));
+ let device = Device::new(
+ MediaType::screen(),
+ TypedSize2D::new(800., 600.),
+ TypedScale::new(1.0),
+ );
let shared_lock = SharedRwLock::new();
let stylesheets = vec![
- stylesheet!("@viewport { min-width: 100px; min-height: 100px; zoom: 1; }",
- UserAgent,
- shared_lock.clone()),
- stylesheet!("@viewport { min-width: 200px; min-height: 200px; }",
- User, shared_lock.clone()),
- stylesheet!("@viewport { min-width: 300px; }",
- Author, shared_lock.clone())
+ stylesheet!(
+ "@viewport { min-width: 100px; min-height: 100px; zoom: 1; }",
+ UserAgent,
+ shared_lock.clone()
+ ),
+ stylesheet!(
+ "@viewport { min-width: 200px; min-height: 200px; }",
+ User,
+ shared_lock.clone()
+ ),
+ stylesheet!(
+ "@viewport { min-width: 300px; }",
+ Author,
+ shared_lock.clone()
+ ),
];
let declarations = Cascade::from_stylesheets(
stylesheets.iter().map(|s| (&**s, Origin::Author)),
&StylesheetGuards::same(&shared_lock.read()),
&device,
- ).finish();
+ )
+ .finish();
assert_decl_len!(declarations == 3);
assert_decl_eq!(&declarations[0], UserAgent, Zoom: Zoom::Number(1.));
- assert_decl_eq!(&declarations[1], User, MinHeight: viewport_length!(200., px));
- assert_decl_eq!(&declarations[2], Author, MinWidth: viewport_length!(300., px));
+ assert_decl_eq!(
+ &declarations[1],
+ User,
+ MinHeight: viewport_length!(200., px)
+ );
+ assert_decl_eq!(
+ &declarations[2],
+ Author,
+ MinWidth: viewport_length!(300., px)
+ );
let stylesheets = vec![
stylesheet!("@viewport { min-width: 100px !important; }",
@@ -291,10 +499,21 @@ fn multiple_stylesheets_cascading() {
stylesheets.iter().map(|s| (&**s, Origin::Author)),
&StylesheetGuards::same(&shared_lock.read()),
&device,
- ).finish();
+ )
+ .finish();
assert_decl_len!(declarations == 3);
- assert_decl_eq!(&declarations[0], UserAgent, MinWidth: viewport_length!(100., px), !important);
- assert_decl_eq!(&declarations[1], User, MinHeight: viewport_length!(200., px), !important);
+ assert_decl_eq!(
+ &declarations[0],
+ UserAgent,
+ MinWidth: viewport_length!(100., px),
+ !important
+ );
+ assert_decl_eq!(
+ &declarations[1],
+ User,
+ MinHeight: viewport_length!(200., px),
+ !important
+ );
assert_decl_eq!(&declarations[2], Author, Zoom: Zoom::Number(3.), !important);
}
@@ -314,70 +533,81 @@ fn constrain_viewport() {
macro_rules! from_css {
($css:expr) => {
&ViewportRule::parse(&context, &mut Parser::new(&mut $css)).unwrap()
- }
+ };
}
let initial_viewport = TypedSize2D::new(800., 600.);
let device = Device::new(MediaType::screen(), initial_viewport, TypedScale::new(1.0));
let mut input = ParserInput::new("");
- assert_eq!(ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks), None);
+ assert_eq!(
+ ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks),
+ None
+ );
let mut input = ParserInput::new("width: 320px auto");
- assert_eq!(ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks),
- Some(ViewportConstraints {
- size: initial_viewport,
-
- initial_zoom: PinchZoomFactor::new(1.),
- min_zoom: None,
- max_zoom: None,
-
- user_zoom: UserZoom::Zoom,
- orientation: Orientation::Auto
- }));
+ assert_eq!(
+ ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks),
+ Some(ViewportConstraints {
+ size: initial_viewport,
+
+ initial_zoom: PinchZoomFactor::new(1.),
+ min_zoom: None,
+ max_zoom: None,
+
+ user_zoom: UserZoom::Zoom,
+ orientation: Orientation::Auto
+ })
+ );
let mut input = ParserInput::new("width: 320px auto");
- assert_eq!(ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks),
- Some(ViewportConstraints {
- size: initial_viewport,
-
- initial_zoom: PinchZoomFactor::new(1.),
- min_zoom: None,
- max_zoom: None,
-
- user_zoom: UserZoom::Zoom,
- orientation: Orientation::Auto
- }));
-
- let mut input = ParserInput::new("width: 800px; height: 600px;\
- zoom: 1;\
- user-zoom: zoom;\
- orientation: auto;");
- assert_eq!(ViewportConstraints::maybe_new(&device,
- from_css!(input),
- QuirksMode::NoQuirks),
- Some(ViewportConstraints {
- size: initial_viewport,
-
- initial_zoom: PinchZoomFactor::new(1.),
- min_zoom: None,
- max_zoom: None,
-
- user_zoom: UserZoom::Zoom,
- orientation: Orientation::Auto
- }));
+ assert_eq!(
+ ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks),
+ Some(ViewportConstraints {
+ size: initial_viewport,
+
+ initial_zoom: PinchZoomFactor::new(1.),
+ min_zoom: None,
+ max_zoom: None,
+
+ user_zoom: UserZoom::Zoom,
+ orientation: Orientation::Auto
+ })
+ );
+
+ let mut input = ParserInput::new(
+ "width: 800px; height: 600px;\
+ zoom: 1;\
+ user-zoom: zoom;\
+ orientation: auto;",
+ );
+ assert_eq!(
+ ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks),
+ Some(ViewportConstraints {
+ size: initial_viewport,
+
+ initial_zoom: PinchZoomFactor::new(1.),
+ min_zoom: None,
+ max_zoom: None,
+
+ user_zoom: UserZoom::Zoom,
+ orientation: Orientation::Auto
+ })
+ );
let initial_viewport = TypedSize2D::new(200., 150.);
let device = Device::new(MediaType::screen(), initial_viewport, TypedScale::new(1.0));
let mut input = ParserInput::new("width: 320px auto");
- assert_eq!(ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks),
- Some(ViewportConstraints {
- size: TypedSize2D::new(320., 240.),
-
- initial_zoom: PinchZoomFactor::new(1.),
- min_zoom: None,
- max_zoom: None,
-
- user_zoom: UserZoom::Zoom,
- orientation: Orientation::Auto
- }));
+ assert_eq!(
+ ViewportConstraints::maybe_new(&device, from_css!(input), QuirksMode::NoQuirks),
+ Some(ViewportConstraints {
+ size: TypedSize2D::new(320., 240.),
+
+ initial_zoom: PinchZoomFactor::new(1.),
+ min_zoom: None,
+ max_zoom: None,
+
+ user_zoom: UserZoom::Zoom,
+ orientation: Orientation::Auto
+ })
+ );
}