1use crate::error::Result;
8use crate::protocol::{Locator, Page};
9use std::path::Path;
10use std::time::Duration;
11
12const DEFAULT_ASSERTION_TIMEOUT: Duration = Duration::from_secs(5);
14
15const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(100);
17
18pub fn expect(locator: Locator) -> Expectation {
88 Expectation::new(locator)
89}
90
91pub struct Expectation {
93 locator: Locator,
94 timeout: Duration,
95 poll_interval: Duration,
96 negate: bool,
97}
98
99#[allow(clippy::wrong_self_convention)]
102impl Expectation {
103 pub(crate) fn new(locator: Locator) -> Self {
105 Self {
106 locator,
107 timeout: DEFAULT_ASSERTION_TIMEOUT,
108 poll_interval: DEFAULT_POLL_INTERVAL,
109 negate: false,
110 }
111 }
112
113 pub fn with_timeout(mut self, timeout: Duration) -> Self {
116 self.timeout = timeout;
117 self
118 }
119
120 pub fn with_poll_interval(mut self, interval: Duration) -> Self {
124 self.poll_interval = interval;
125 self
126 }
127
128 #[allow(clippy::should_implement_trait)]
133 pub fn not(mut self) -> Self {
134 self.negate = true;
135 self
136 }
137
138 pub async fn to_be_visible(self) -> Result<()> {
144 let start = std::time::Instant::now();
145 let selector = self.locator.selector().to_string();
146
147 loop {
148 let is_visible = self.locator.is_visible().await?;
149
150 let matches = if self.negate { !is_visible } else { is_visible };
152
153 if matches {
154 return Ok(());
155 }
156
157 if start.elapsed() >= self.timeout {
159 let message = if self.negate {
160 format!(
161 "Expected element '{}' NOT to be visible, but it was visible after {:?}",
162 selector, self.timeout
163 )
164 } else {
165 format!(
166 "Expected element '{}' to be visible, but it was not visible after {:?}",
167 selector, self.timeout
168 )
169 };
170 return Err(crate::error::Error::AssertionTimeout(message));
171 }
172
173 tokio::time::sleep(self.poll_interval).await;
175 }
176 }
177
178 pub async fn to_be_hidden(self) -> Result<()> {
184 let negated = Expectation {
187 negate: !self.negate, ..self
189 };
190 negated.to_be_visible().await
191 }
192
193 pub async fn to_have_text(self, expected: &str) -> Result<()> {
200 let start = std::time::Instant::now();
201 let selector = self.locator.selector().to_string();
202 let expected = expected.trim();
203
204 loop {
205 let actual_text = self.locator.inner_text().await?;
207 let actual = actual_text.trim();
208
209 let matches = if self.negate {
211 actual != expected
212 } else {
213 actual == expected
214 };
215
216 if matches {
217 return Ok(());
218 }
219
220 if start.elapsed() >= self.timeout {
222 let message = if self.negate {
223 format!(
224 "Expected element '{}' NOT to have text '{}', but it did after {:?}",
225 selector, expected, self.timeout
226 )
227 } else {
228 format!(
229 "Expected element '{}' to have text '{}', but had '{}' after {:?}",
230 selector, expected, actual, self.timeout
231 )
232 };
233 return Err(crate::error::Error::AssertionTimeout(message));
234 }
235
236 tokio::time::sleep(self.poll_interval).await;
238 }
239 }
240
241 pub async fn to_have_text_regex(self, pattern: &str) -> Result<()> {
245 let start = std::time::Instant::now();
246 let selector = self.locator.selector().to_string();
247 let re = regex::Regex::new(pattern)
248 .map_err(|e| crate::error::Error::InvalidArgument(format!("Invalid regex: {}", e)))?;
249
250 loop {
251 let actual_text = self.locator.inner_text().await?;
252 let actual = actual_text.trim();
253
254 let matches = if self.negate {
256 !re.is_match(actual)
257 } else {
258 re.is_match(actual)
259 };
260
261 if matches {
262 return Ok(());
263 }
264
265 if start.elapsed() >= self.timeout {
267 let message = if self.negate {
268 format!(
269 "Expected element '{}' NOT to match pattern '{}', but it did after {:?}",
270 selector, pattern, self.timeout
271 )
272 } else {
273 format!(
274 "Expected element '{}' to match pattern '{}', but had '{}' after {:?}",
275 selector, pattern, actual, self.timeout
276 )
277 };
278 return Err(crate::error::Error::AssertionTimeout(message));
279 }
280
281 tokio::time::sleep(self.poll_interval).await;
283 }
284 }
285
286 pub async fn to_contain_text(self, expected: &str) -> Result<()> {
292 let start = std::time::Instant::now();
293 let selector = self.locator.selector().to_string();
294
295 loop {
296 let actual_text = self.locator.inner_text().await?;
297 let actual = actual_text.trim();
298
299 let matches = if self.negate {
301 !actual.contains(expected)
302 } else {
303 actual.contains(expected)
304 };
305
306 if matches {
307 return Ok(());
308 }
309
310 if start.elapsed() >= self.timeout {
312 let message = if self.negate {
313 format!(
314 "Expected element '{}' NOT to contain text '{}', but it did after {:?}",
315 selector, expected, self.timeout
316 )
317 } else {
318 format!(
319 "Expected element '{}' to contain text '{}', but had '{}' after {:?}",
320 selector, expected, actual, self.timeout
321 )
322 };
323 return Err(crate::error::Error::AssertionTimeout(message));
324 }
325
326 tokio::time::sleep(self.poll_interval).await;
328 }
329 }
330
331 pub async fn to_contain_text_regex(self, pattern: &str) -> Result<()> {
335 let start = std::time::Instant::now();
336 let selector = self.locator.selector().to_string();
337 let re = regex::Regex::new(pattern)
338 .map_err(|e| crate::error::Error::InvalidArgument(format!("Invalid regex: {}", e)))?;
339
340 loop {
341 let actual_text = self.locator.inner_text().await?;
342 let actual = actual_text.trim();
343
344 let matches = if self.negate {
346 !re.is_match(actual)
347 } else {
348 re.is_match(actual)
349 };
350
351 if matches {
352 return Ok(());
353 }
354
355 if start.elapsed() >= self.timeout {
357 let message = if self.negate {
358 format!(
359 "Expected element '{}' NOT to contain pattern '{}', but it did after {:?}",
360 selector, pattern, self.timeout
361 )
362 } else {
363 format!(
364 "Expected element '{}' to contain pattern '{}', but had '{}' after {:?}",
365 selector, pattern, actual, self.timeout
366 )
367 };
368 return Err(crate::error::Error::AssertionTimeout(message));
369 }
370
371 tokio::time::sleep(self.poll_interval).await;
373 }
374 }
375
376 pub async fn to_have_value(self, expected: &str) -> Result<()> {
382 let start = std::time::Instant::now();
383 let selector = self.locator.selector().to_string();
384
385 loop {
386 let actual = self.locator.input_value(None).await?;
387
388 let matches = if self.negate {
390 actual != expected
391 } else {
392 actual == expected
393 };
394
395 if matches {
396 return Ok(());
397 }
398
399 if start.elapsed() >= self.timeout {
401 let message = if self.negate {
402 format!(
403 "Expected input '{}' NOT to have value '{}', but it did after {:?}",
404 selector, expected, self.timeout
405 )
406 } else {
407 format!(
408 "Expected input '{}' to have value '{}', but had '{}' after {:?}",
409 selector, expected, actual, self.timeout
410 )
411 };
412 return Err(crate::error::Error::AssertionTimeout(message));
413 }
414
415 tokio::time::sleep(self.poll_interval).await;
417 }
418 }
419
420 pub async fn to_have_value_regex(self, pattern: &str) -> Result<()> {
424 let start = std::time::Instant::now();
425 let selector = self.locator.selector().to_string();
426 let re = regex::Regex::new(pattern)
427 .map_err(|e| crate::error::Error::InvalidArgument(format!("Invalid regex: {}", e)))?;
428
429 loop {
430 let actual = self.locator.input_value(None).await?;
431
432 let matches = if self.negate {
434 !re.is_match(&actual)
435 } else {
436 re.is_match(&actual)
437 };
438
439 if matches {
440 return Ok(());
441 }
442
443 if start.elapsed() >= self.timeout {
445 let message = if self.negate {
446 format!(
447 "Expected input '{}' NOT to match pattern '{}', but it did after {:?}",
448 selector, pattern, self.timeout
449 )
450 } else {
451 format!(
452 "Expected input '{}' to match pattern '{}', but had '{}' after {:?}",
453 selector, pattern, actual, self.timeout
454 )
455 };
456 return Err(crate::error::Error::AssertionTimeout(message));
457 }
458
459 tokio::time::sleep(self.poll_interval).await;
461 }
462 }
463
464 pub async fn to_be_enabled(self) -> Result<()> {
471 let start = std::time::Instant::now();
472 let selector = self.locator.selector().to_string();
473
474 loop {
475 let is_enabled = self.locator.is_enabled().await?;
476
477 let matches = if self.negate { !is_enabled } else { is_enabled };
479
480 if matches {
481 return Ok(());
482 }
483
484 if start.elapsed() >= self.timeout {
486 let message = if self.negate {
487 format!(
488 "Expected element '{}' NOT to be enabled, but it was enabled after {:?}",
489 selector, self.timeout
490 )
491 } else {
492 format!(
493 "Expected element '{}' to be enabled, but it was not enabled after {:?}",
494 selector, self.timeout
495 )
496 };
497 return Err(crate::error::Error::AssertionTimeout(message));
498 }
499
500 tokio::time::sleep(self.poll_interval).await;
502 }
503 }
504
505 pub async fn to_be_disabled(self) -> Result<()> {
512 let negated = Expectation {
515 negate: !self.negate, ..self
517 };
518 negated.to_be_enabled().await
519 }
520
521 pub async fn to_be_checked(self) -> Result<()> {
527 let start = std::time::Instant::now();
528 let selector = self.locator.selector().to_string();
529
530 loop {
531 let is_checked = self.locator.is_checked().await?;
532
533 let matches = if self.negate { !is_checked } else { is_checked };
535
536 if matches {
537 return Ok(());
538 }
539
540 if start.elapsed() >= self.timeout {
542 let message = if self.negate {
543 format!(
544 "Expected element '{}' NOT to be checked, but it was checked after {:?}",
545 selector, self.timeout
546 )
547 } else {
548 format!(
549 "Expected element '{}' to be checked, but it was not checked after {:?}",
550 selector, self.timeout
551 )
552 };
553 return Err(crate::error::Error::AssertionTimeout(message));
554 }
555
556 tokio::time::sleep(self.poll_interval).await;
558 }
559 }
560
561 pub async fn to_be_unchecked(self) -> Result<()> {
567 let negated = Expectation {
570 negate: !self.negate, ..self
572 };
573 negated.to_be_checked().await
574 }
575
576 pub async fn to_be_editable(self) -> Result<()> {
583 let start = std::time::Instant::now();
584 let selector = self.locator.selector().to_string();
585
586 loop {
587 let is_editable = self.locator.is_editable().await?;
588
589 let matches = if self.negate {
591 !is_editable
592 } else {
593 is_editable
594 };
595
596 if matches {
597 return Ok(());
598 }
599
600 if start.elapsed() >= self.timeout {
602 let message = if self.negate {
603 format!(
604 "Expected element '{}' NOT to be editable, but it was editable after {:?}",
605 selector, self.timeout
606 )
607 } else {
608 format!(
609 "Expected element '{}' to be editable, but it was not editable after {:?}",
610 selector, self.timeout
611 )
612 };
613 return Err(crate::error::Error::AssertionTimeout(message));
614 }
615
616 tokio::time::sleep(self.poll_interval).await;
618 }
619 }
620
621 pub async fn to_be_focused(self) -> Result<()> {
627 let start = std::time::Instant::now();
628 let selector = self.locator.selector().to_string();
629
630 loop {
631 let is_focused = self.locator.is_focused().await?;
632
633 let matches = if self.negate { !is_focused } else { is_focused };
635
636 if matches {
637 return Ok(());
638 }
639
640 if start.elapsed() >= self.timeout {
642 let message = if self.negate {
643 format!(
644 "Expected element '{}' NOT to be focused, but it was focused after {:?}",
645 selector, self.timeout
646 )
647 } else {
648 format!(
649 "Expected element '{}' to be focused, but it was not focused after {:?}",
650 selector, self.timeout
651 )
652 };
653 return Err(crate::error::Error::AssertionTimeout(message));
654 }
655
656 tokio::time::sleep(self.poll_interval).await;
658 }
659 }
660
661 pub async fn to_have_screenshot(
668 self,
669 baseline_path: impl AsRef<Path>,
670 options: Option<ScreenshotAssertionOptions>,
671 ) -> Result<()> {
672 let opts = options.unwrap_or_default();
673 let baseline_path = baseline_path.as_ref();
674
675 if opts.animations == Some(Animations::Disabled) {
677 let _ = self
678 .locator
679 .evaluate_js(DISABLE_ANIMATIONS_JS, None::<&()>)
680 .await;
681 }
682
683 let screenshot_opts = if let Some(ref mask_locators) = opts.mask {
685 let mask_js = build_mask_js(mask_locators);
687 let _ = self.locator.evaluate_js(&mask_js, None::<&()>).await;
688 None
689 } else {
690 None
691 };
692
693 compare_screenshot(
694 &opts,
695 baseline_path,
696 self.timeout,
697 self.poll_interval,
698 self.negate,
699 || async { self.locator.screenshot(screenshot_opts.clone()).await },
700 )
701 .await
702 }
703}
704
705const DISABLE_ANIMATIONS_JS: &str = r#"
707(() => {
708 const style = document.createElement('style');
709 style.textContent = '*, *::before, *::after { animation-duration: 0s !important; animation-delay: 0s !important; transition-duration: 0s !important; transition-delay: 0s !important; }';
710 style.setAttribute('data-playwright-no-animations', '');
711 document.head.appendChild(style);
712})()
713"#;
714
715fn build_mask_js(locators: &[Locator]) -> String {
717 let selectors: Vec<String> = locators
718 .iter()
719 .map(|l| {
720 let sel = l.selector().replace('\'', "\\'");
721 format!(
722 r#"
723 (function() {{
724 var els = document.querySelectorAll('{}');
725 els.forEach(function(el) {{
726 var rect = el.getBoundingClientRect();
727 var overlay = document.createElement('div');
728 overlay.setAttribute('data-playwright-mask', '');
729 overlay.style.cssText = 'position:fixed;z-index:2147483647;background:#FF00FF;pointer-events:none;'
730 + 'left:' + rect.left + 'px;top:' + rect.top + 'px;width:' + rect.width + 'px;height:' + rect.height + 'px;';
731 document.body.appendChild(overlay);
732 }});
733 }})();
734 "#,
735 sel
736 )
737 })
738 .collect();
739 selectors.join("\n")
740}
741
742#[derive(Debug, Clone, Copy, PartialEq, Eq)]
746pub enum Animations {
747 Allow,
749 Disabled,
751}
752
753#[derive(Debug, Clone, Default)]
757pub struct ScreenshotAssertionOptions {
758 pub max_diff_pixels: Option<u32>,
760 pub max_diff_pixel_ratio: Option<f64>,
762 pub threshold: Option<f64>,
764 pub animations: Option<Animations>,
766 pub mask: Option<Vec<Locator>>,
768 pub update_snapshots: Option<bool>,
770}
771
772impl ScreenshotAssertionOptions {
773 pub fn builder() -> ScreenshotAssertionOptionsBuilder {
775 ScreenshotAssertionOptionsBuilder::default()
776 }
777}
778
779#[derive(Debug, Clone, Default)]
781pub struct ScreenshotAssertionOptionsBuilder {
782 max_diff_pixels: Option<u32>,
783 max_diff_pixel_ratio: Option<f64>,
784 threshold: Option<f64>,
785 animations: Option<Animations>,
786 mask: Option<Vec<Locator>>,
787 update_snapshots: Option<bool>,
788}
789
790impl ScreenshotAssertionOptionsBuilder {
791 pub fn max_diff_pixels(mut self, pixels: u32) -> Self {
793 self.max_diff_pixels = Some(pixels);
794 self
795 }
796
797 pub fn max_diff_pixel_ratio(mut self, ratio: f64) -> Self {
799 self.max_diff_pixel_ratio = Some(ratio);
800 self
801 }
802
803 pub fn threshold(mut self, threshold: f64) -> Self {
805 self.threshold = Some(threshold);
806 self
807 }
808
809 pub fn animations(mut self, animations: Animations) -> Self {
811 self.animations = Some(animations);
812 self
813 }
814
815 pub fn mask(mut self, locators: Vec<Locator>) -> Self {
817 self.mask = Some(locators);
818 self
819 }
820
821 pub fn update_snapshots(mut self, update: bool) -> Self {
823 self.update_snapshots = Some(update);
824 self
825 }
826
827 pub fn build(self) -> ScreenshotAssertionOptions {
829 ScreenshotAssertionOptions {
830 max_diff_pixels: self.max_diff_pixels,
831 max_diff_pixel_ratio: self.max_diff_pixel_ratio,
832 threshold: self.threshold,
833 animations: self.animations,
834 mask: self.mask,
835 update_snapshots: self.update_snapshots,
836 }
837 }
838}
839
840pub fn expect_page(page: &Page) -> PageExpectation {
844 PageExpectation::new(page.clone())
845}
846
847#[allow(clippy::wrong_self_convention)]
849pub struct PageExpectation {
850 page: Page,
851 timeout: Duration,
852 poll_interval: Duration,
853 negate: bool,
854}
855
856impl PageExpectation {
857 fn new(page: Page) -> Self {
858 Self {
859 page,
860 timeout: DEFAULT_ASSERTION_TIMEOUT,
861 poll_interval: DEFAULT_POLL_INTERVAL,
862 negate: false,
863 }
864 }
865
866 pub fn with_timeout(mut self, timeout: Duration) -> Self {
868 self.timeout = timeout;
869 self
870 }
871
872 #[allow(clippy::should_implement_trait)]
874 pub fn not(mut self) -> Self {
875 self.negate = true;
876 self
877 }
878
879 pub async fn to_have_title(self, expected: &str) -> Result<()> {
885 let start = std::time::Instant::now();
886 let expected = expected.trim();
887
888 loop {
889 let actual = self.page.title().await?;
890 let actual = actual.trim();
891
892 let matches = if self.negate {
893 actual != expected
894 } else {
895 actual == expected
896 };
897
898 if matches {
899 return Ok(());
900 }
901
902 if start.elapsed() >= self.timeout {
903 let message = if self.negate {
904 format!(
905 "Expected page NOT to have title '{}', but it did after {:?}",
906 expected, self.timeout,
907 )
908 } else {
909 format!(
910 "Expected page to have title '{}', but got '{}' after {:?}",
911 expected, actual, self.timeout,
912 )
913 };
914 return Err(crate::error::Error::AssertionTimeout(message));
915 }
916
917 tokio::time::sleep(self.poll_interval).await;
918 }
919 }
920
921 pub async fn to_have_title_regex(self, pattern: &str) -> Result<()> {
927 let start = std::time::Instant::now();
928 let re = regex::Regex::new(pattern)
929 .map_err(|e| crate::error::Error::InvalidArgument(format!("Invalid regex: {}", e)))?;
930
931 loop {
932 let actual = self.page.title().await?;
933
934 let matches = if self.negate {
935 !re.is_match(&actual)
936 } else {
937 re.is_match(&actual)
938 };
939
940 if matches {
941 return Ok(());
942 }
943
944 if start.elapsed() >= self.timeout {
945 let message = if self.negate {
946 format!(
947 "Expected page title NOT to match '{}', but '{}' matched after {:?}",
948 pattern, actual, self.timeout,
949 )
950 } else {
951 format!(
952 "Expected page title to match '{}', but got '{}' after {:?}",
953 pattern, actual, self.timeout,
954 )
955 };
956 return Err(crate::error::Error::AssertionTimeout(message));
957 }
958
959 tokio::time::sleep(self.poll_interval).await;
960 }
961 }
962
963 pub async fn to_have_url(self, expected: &str) -> Result<()> {
969 let start = std::time::Instant::now();
970
971 loop {
972 let actual = self.page.url();
973
974 let matches = if self.negate {
975 actual != expected
976 } else {
977 actual == expected
978 };
979
980 if matches {
981 return Ok(());
982 }
983
984 if start.elapsed() >= self.timeout {
985 let message = if self.negate {
986 format!(
987 "Expected page NOT to have URL '{}', but it did after {:?}",
988 expected, self.timeout,
989 )
990 } else {
991 format!(
992 "Expected page to have URL '{}', but got '{}' after {:?}",
993 expected, actual, self.timeout,
994 )
995 };
996 return Err(crate::error::Error::AssertionTimeout(message));
997 }
998
999 tokio::time::sleep(self.poll_interval).await;
1000 }
1001 }
1002
1003 pub async fn to_have_url_regex(self, pattern: &str) -> Result<()> {
1009 let start = std::time::Instant::now();
1010 let re = regex::Regex::new(pattern)
1011 .map_err(|e| crate::error::Error::InvalidArgument(format!("Invalid regex: {}", e)))?;
1012
1013 loop {
1014 let actual = self.page.url();
1015
1016 let matches = if self.negate {
1017 !re.is_match(&actual)
1018 } else {
1019 re.is_match(&actual)
1020 };
1021
1022 if matches {
1023 return Ok(());
1024 }
1025
1026 if start.elapsed() >= self.timeout {
1027 let message = if self.negate {
1028 format!(
1029 "Expected page URL NOT to match '{}', but '{}' matched after {:?}",
1030 pattern, actual, self.timeout,
1031 )
1032 } else {
1033 format!(
1034 "Expected page URL to match '{}', but got '{}' after {:?}",
1035 pattern, actual, self.timeout,
1036 )
1037 };
1038 return Err(crate::error::Error::AssertionTimeout(message));
1039 }
1040
1041 tokio::time::sleep(self.poll_interval).await;
1042 }
1043 }
1044
1045 pub async fn to_have_screenshot(
1049 self,
1050 baseline_path: impl AsRef<Path>,
1051 options: Option<ScreenshotAssertionOptions>,
1052 ) -> Result<()> {
1053 let opts = options.unwrap_or_default();
1054 let baseline_path = baseline_path.as_ref();
1055
1056 if opts.animations == Some(Animations::Disabled) {
1058 let _ = self.page.evaluate_expression(DISABLE_ANIMATIONS_JS).await;
1059 }
1060
1061 if let Some(ref mask_locators) = opts.mask {
1063 let mask_js = build_mask_js(mask_locators);
1064 let _ = self.page.evaluate_expression(&mask_js).await;
1065 }
1066
1067 compare_screenshot(
1068 &opts,
1069 baseline_path,
1070 self.timeout,
1071 self.poll_interval,
1072 self.negate,
1073 || async { self.page.screenshot(None).await },
1074 )
1075 .await
1076 }
1077}
1078
1079async fn compare_screenshot<F, Fut>(
1081 opts: &ScreenshotAssertionOptions,
1082 baseline_path: &Path,
1083 timeout: Duration,
1084 poll_interval: Duration,
1085 negate: bool,
1086 take_screenshot: F,
1087) -> Result<()>
1088where
1089 F: Fn() -> Fut,
1090 Fut: std::future::Future<Output = Result<Vec<u8>>>,
1091{
1092 let threshold = opts.threshold.unwrap_or(0.2);
1093 let max_diff_pixels = opts.max_diff_pixels;
1094 let max_diff_pixel_ratio = opts.max_diff_pixel_ratio;
1095 let update_snapshots = opts.update_snapshots.unwrap_or(false);
1096
1097 let actual_bytes = take_screenshot().await?;
1099
1100 if !baseline_path.exists() || update_snapshots {
1102 if let Some(parent) = baseline_path.parent() {
1103 tokio::fs::create_dir_all(parent).await.map_err(|e| {
1104 crate::error::Error::ProtocolError(format!(
1105 "Failed to create baseline directory: {}",
1106 e
1107 ))
1108 })?;
1109 }
1110 tokio::fs::write(baseline_path, &actual_bytes)
1111 .await
1112 .map_err(|e| {
1113 crate::error::Error::ProtocolError(format!(
1114 "Failed to write baseline screenshot: {}",
1115 e
1116 ))
1117 })?;
1118 return Ok(());
1119 }
1120
1121 let baseline_bytes = tokio::fs::read(baseline_path).await.map_err(|e| {
1123 crate::error::Error::ProtocolError(format!("Failed to read baseline screenshot: {}", e))
1124 })?;
1125
1126 let start = std::time::Instant::now();
1127
1128 loop {
1129 let screenshot_bytes = if start.elapsed().is_zero() {
1130 actual_bytes.clone()
1131 } else {
1132 take_screenshot().await?
1133 };
1134
1135 let comparison = compare_images(&baseline_bytes, &screenshot_bytes, threshold)?;
1136
1137 let within_tolerance =
1138 is_within_tolerance(&comparison, max_diff_pixels, max_diff_pixel_ratio);
1139
1140 let matches = if negate {
1141 !within_tolerance
1142 } else {
1143 within_tolerance
1144 };
1145
1146 if matches {
1147 return Ok(());
1148 }
1149
1150 if start.elapsed() >= timeout {
1151 if negate {
1152 return Err(crate::error::Error::AssertionTimeout(format!(
1153 "Expected screenshots NOT to match, but they matched after {:?}",
1154 timeout
1155 )));
1156 }
1157
1158 let baseline_stem = baseline_path
1160 .file_stem()
1161 .and_then(|s| s.to_str())
1162 .unwrap_or("screenshot");
1163 let baseline_ext = baseline_path
1164 .extension()
1165 .and_then(|s| s.to_str())
1166 .unwrap_or("png");
1167 let baseline_dir = baseline_path.parent().unwrap_or(Path::new("."));
1168
1169 let actual_path =
1170 baseline_dir.join(format!("{}-actual.{}", baseline_stem, baseline_ext));
1171 let diff_path = baseline_dir.join(format!("{}-diff.{}", baseline_stem, baseline_ext));
1172
1173 let _ = tokio::fs::write(&actual_path, &screenshot_bytes).await;
1174
1175 if let Ok(diff_bytes) =
1176 generate_diff_image(&baseline_bytes, &screenshot_bytes, threshold)
1177 {
1178 let _ = tokio::fs::write(&diff_path, diff_bytes).await;
1179 }
1180
1181 return Err(crate::error::Error::AssertionTimeout(format!(
1182 "Screenshot mismatch: {} pixels differ ({:.2}% of total). \
1183 Max allowed: {}. Threshold: {:.2}. \
1184 Actual saved to: {}. Diff saved to: {}. \
1185 Timed out after {:?}",
1186 comparison.diff_count,
1187 comparison.diff_ratio * 100.0,
1188 max_diff_pixels
1189 .map(|p| p.to_string())
1190 .or_else(|| max_diff_pixel_ratio.map(|r| format!("{:.2}%", r * 100.0)))
1191 .unwrap_or_else(|| "0".to_string()),
1192 threshold,
1193 actual_path.display(),
1194 diff_path.display(),
1195 timeout,
1196 )));
1197 }
1198
1199 tokio::time::sleep(poll_interval).await;
1200 }
1201}
1202
1203struct ImageComparison {
1205 diff_count: u32,
1206 diff_ratio: f64,
1207}
1208
1209fn is_within_tolerance(
1210 comparison: &ImageComparison,
1211 max_diff_pixels: Option<u32>,
1212 max_diff_pixel_ratio: Option<f64>,
1213) -> bool {
1214 if let Some(max_pixels) = max_diff_pixels {
1215 if comparison.diff_count > max_pixels {
1216 return false;
1217 }
1218 } else if let Some(max_ratio) = max_diff_pixel_ratio {
1219 if comparison.diff_ratio > max_ratio {
1220 return false;
1221 }
1222 } else {
1223 if comparison.diff_count > 0 {
1225 return false;
1226 }
1227 }
1228 true
1229}
1230
1231fn compare_images(
1233 baseline_bytes: &[u8],
1234 actual_bytes: &[u8],
1235 threshold: f64,
1236) -> Result<ImageComparison> {
1237 use image::GenericImageView;
1238
1239 let baseline_img = image::load_from_memory(baseline_bytes).map_err(|e| {
1240 crate::error::Error::ProtocolError(format!("Failed to decode baseline image: {}", e))
1241 })?;
1242 let actual_img = image::load_from_memory(actual_bytes).map_err(|e| {
1243 crate::error::Error::ProtocolError(format!("Failed to decode actual image: {}", e))
1244 })?;
1245
1246 let (bw, bh) = baseline_img.dimensions();
1247 let (aw, ah) = actual_img.dimensions();
1248
1249 if bw != aw || bh != ah {
1251 let total = bw.max(aw) * bh.max(ah);
1252 return Ok(ImageComparison {
1253 diff_count: total,
1254 diff_ratio: 1.0,
1255 });
1256 }
1257
1258 let total_pixels = bw * bh;
1259 if total_pixels == 0 {
1260 return Ok(ImageComparison {
1261 diff_count: 0,
1262 diff_ratio: 0.0,
1263 });
1264 }
1265
1266 let threshold_sq = threshold * threshold;
1267 let mut diff_count: u32 = 0;
1268
1269 for y in 0..bh {
1270 for x in 0..bw {
1271 let bp = baseline_img.get_pixel(x, y);
1272 let ap = actual_img.get_pixel(x, y);
1273
1274 let dr = (bp[0] as f64 - ap[0] as f64) / 255.0;
1276 let dg = (bp[1] as f64 - ap[1] as f64) / 255.0;
1277 let db = (bp[2] as f64 - ap[2] as f64) / 255.0;
1278 let da = (bp[3] as f64 - ap[3] as f64) / 255.0;
1279
1280 let dist_sq = (dr * dr + dg * dg + db * db + da * da) / 4.0;
1281
1282 if dist_sq > threshold_sq {
1283 diff_count += 1;
1284 }
1285 }
1286 }
1287
1288 Ok(ImageComparison {
1289 diff_count,
1290 diff_ratio: diff_count as f64 / total_pixels as f64,
1291 })
1292}
1293
1294fn generate_diff_image(
1296 baseline_bytes: &[u8],
1297 actual_bytes: &[u8],
1298 threshold: f64,
1299) -> Result<Vec<u8>> {
1300 use image::{GenericImageView, ImageBuffer, Rgba};
1301
1302 let baseline_img = image::load_from_memory(baseline_bytes).map_err(|e| {
1303 crate::error::Error::ProtocolError(format!("Failed to decode baseline image: {}", e))
1304 })?;
1305 let actual_img = image::load_from_memory(actual_bytes).map_err(|e| {
1306 crate::error::Error::ProtocolError(format!("Failed to decode actual image: {}", e))
1307 })?;
1308
1309 let (bw, bh) = baseline_img.dimensions();
1310 let (aw, ah) = actual_img.dimensions();
1311 let width = bw.max(aw);
1312 let height = bh.max(ah);
1313
1314 let threshold_sq = threshold * threshold;
1315
1316 let mut diff_img: ImageBuffer<Rgba<u8>, Vec<u8>> = ImageBuffer::new(width, height);
1317
1318 for y in 0..height {
1319 for x in 0..width {
1320 if x >= bw || y >= bh || x >= aw || y >= ah {
1321 diff_img.put_pixel(x, y, Rgba([255, 0, 0, 255]));
1323 continue;
1324 }
1325
1326 let bp = baseline_img.get_pixel(x, y);
1327 let ap = actual_img.get_pixel(x, y);
1328
1329 let dr = (bp[0] as f64 - ap[0] as f64) / 255.0;
1330 let dg = (bp[1] as f64 - ap[1] as f64) / 255.0;
1331 let db = (bp[2] as f64 - ap[2] as f64) / 255.0;
1332 let da = (bp[3] as f64 - ap[3] as f64) / 255.0;
1333
1334 let dist_sq = (dr * dr + dg * dg + db * db + da * da) / 4.0;
1335
1336 if dist_sq > threshold_sq {
1337 diff_img.put_pixel(x, y, Rgba([255, 0, 0, 255]));
1339 } else {
1340 let gray = ((ap[0] as u16 + ap[1] as u16 + ap[2] as u16) / 3) as u8;
1342 diff_img.put_pixel(x, y, Rgba([gray, gray, gray, 100]));
1343 }
1344 }
1345 }
1346
1347 let mut output = std::io::Cursor::new(Vec::new());
1348 diff_img
1349 .write_to(&mut output, image::ImageFormat::Png)
1350 .map_err(|e| {
1351 crate::error::Error::ProtocolError(format!("Failed to encode diff image: {}", e))
1352 })?;
1353
1354 Ok(output.into_inner())
1355}
1356
1357#[cfg(test)]
1358mod tests {
1359 use super::*;
1360
1361 #[test]
1362 fn test_expectation_defaults() {
1363 assert_eq!(DEFAULT_ASSERTION_TIMEOUT, Duration::from_secs(5));
1365 assert_eq!(DEFAULT_POLL_INTERVAL, Duration::from_millis(100));
1366 }
1367}