1use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::sync::{Arc, Mutex};
9use std::time::{Duration, Instant};
10use trustformers_core::error::{CoreError, Result};
11use trustformers_core::TrustformersError;
12
13use crate::{device_info::MobileDeviceInfo, MobilePlatform};
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct UITestingConfig {
18 pub enabled: bool,
20 pub automation_config: TestAutomationConfig,
22 pub visual_regression_config: VisualRegressionConfig,
24 pub interaction_config: InteractionTestingConfig,
26 pub performance_config: UIPerformanceConfig,
28 pub accessibility_config: AccessibilityTestingConfig,
30 pub reporting_config: UITestReportingConfig,
32 pub output_directory: String,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct TestAutomationConfig {
39 pub frameworks: Vec<UITestFramework>,
41 pub execution_timeout: Duration,
43 pub retry_policy: RetryPolicy,
45 pub parallel_execution: bool,
47 pub max_concurrent_tests: usize,
49 pub test_data_management: TestDataManagement,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
55pub enum UITestFramework {
56 XCUITest,
58 Espresso,
60 UIAutomator,
62 FlutterIntegrationTest,
64 ReactNativeTestingLibrary,
66 UnityUITesting,
68 Appium,
70 Detox,
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct RetryPolicy {
77 pub max_retries: usize,
79 pub retry_delay: Duration,
81 pub backoff_factor: f32,
83 pub retry_conditions: Vec<RetryCondition>,
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89pub enum RetryCondition {
90 Timeout,
92 ElementNotFound,
94 NetworkError,
96 AssertionFailure,
98 AnyFailure,
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct TestDataManagement {
105 pub data_sources: Vec<TestDataSource>,
107 pub cleanup_strategy: DataCleanupStrategy,
109 pub isolation_enabled: bool,
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct TestDataSource {
116 pub source_type: DataSourceType,
118 pub location: String,
120 pub format: DataFormat,
122 pub credentials: Option<String>,
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
128pub enum DataSourceType {
129 Local,
131 Remote,
133 Database,
135 CloudStorage,
137 MockGenerator,
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
143pub enum DataFormat {
144 JSON,
145 CSV,
146 XML,
147 Binary,
148 Image,
149 Video,
150 Audio,
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
155pub enum DataCleanupStrategy {
156 PerTest,
158 PerSuite,
160 Manual,
162 Never,
164}
165
166#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct VisualRegressionConfig {
169 pub enabled: bool,
171 pub screenshot_config: ScreenshotConfig,
173 pub baseline_config: BaselineConfig,
175 pub comparison_config: ImageComparisonConfig,
177}
178
179#[derive(Debug, Clone, Serialize, Deserialize)]
181pub struct ScreenshotConfig {
182 pub format: ImageFormat,
184 pub quality: f32,
186 pub resolution: Option<(u32, u32)>,
188 pub exclude_areas: Vec<ScreenArea>,
190 pub capture_delay: Duration,
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
196pub enum ImageFormat {
197 PNG,
198 JPEG,
199 WebP,
200 TIFF,
201}
202
203#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct ScreenArea {
206 pub x: u32,
208 pub y: u32,
210 pub width: u32,
212 pub height: u32,
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize)]
218pub struct BaselineConfig {
219 pub storage_location: String,
221 pub update_strategy: BaselineUpdateStrategy,
223 pub versioning_enabled: bool,
225 pub platform_specific: bool,
227}
228
229#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
231pub enum BaselineUpdateStrategy {
232 Manual,
234 AutoOnFailure,
236 AutoOnChange,
238 ReviewRequired,
240}
241
242#[derive(Debug, Clone, Serialize, Deserialize)]
244pub struct ImageComparisonConfig {
245 pub algorithm: ComparisonAlgorithm,
247 pub threshold: f32,
249 pub pixel_tolerance: u8,
251 pub anti_aliasing_tolerance: bool,
253 pub color_tolerance: ColorTolerance,
255}
256
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
259pub enum ComparisonAlgorithm {
260 PixelByPixel,
262 SSIM,
264 PHash,
266 DHash,
268 AHash,
270}
271
272#[derive(Debug, Clone, Serialize, Deserialize)]
274pub struct ColorTolerance {
275 pub red: u8,
277 pub green: u8,
279 pub blue: u8,
281 pub alpha: u8,
283}
284
285#[derive(Debug, Clone, Serialize, Deserialize)]
287pub struct InteractionTestingConfig {
288 pub enabled: bool,
290 pub gesture_config: GestureTestingConfig,
292 pub input_config: InputTestingConfig,
294 pub navigation_config: NavigationTestingConfig,
296 pub performance_monitoring: bool,
298}
299
300#[derive(Debug, Clone, Serialize, Deserialize)]
302pub struct GestureTestingConfig {
303 pub supported_gestures: Vec<GestureType>,
305 pub timing_config: GestureTimingConfig,
307 pub validation_config: GestureValidationConfig,
309}
310
311#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
313pub enum GestureType {
314 Tap,
316 DoubleTap,
318 LongPress,
320 Swipe,
322 Pinch,
324 Pan,
326 Rotate,
328 MultiTouch,
330}
331
332#[derive(Debug, Clone, Serialize, Deserialize)]
334pub struct GestureTimingConfig {
335 pub tap_duration: Duration,
337 pub double_tap_interval: Duration,
339 pub long_press_duration: Duration,
341 pub swipe_duration: Duration,
343 pub gesture_delay: Duration,
345}
346
347#[derive(Debug, Clone, Serialize, Deserialize)]
349pub struct GestureValidationConfig {
350 pub validate_recognition: bool,
352 pub validate_response: bool,
354 pub response_timeout: Duration,
356 pub validation_criteria: Vec<ValidationCriterion>,
358}
359
360#[derive(Debug, Clone, Serialize, Deserialize)]
362pub struct ValidationCriterion {
363 pub criterion_type: CriterionType,
365 pub expected_value: String,
367 pub tolerance: f32,
369}
370
371#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
373pub enum CriterionType {
374 ElementState,
376 ResponseTime,
378 AnimationCompletion,
380 ValueChange,
382 EventTrigger,
384}
385
386#[derive(Debug, Clone, Serialize, Deserialize, Default)]
388pub struct InputTestingConfig {
389 pub text_input_config: TextInputConfig,
391 pub voice_input_config: VoiceInputConfig,
393 pub hardware_input_config: HardwareInputConfig,
395}
396
397#[derive(Debug, Clone, Serialize, Deserialize)]
399pub struct TextInputConfig {
400 pub test_input_methods: Vec<InputMethod>,
402 pub test_special_characters: bool,
404 pub test_languages: Vec<String>,
406 pub test_validation: bool,
408}
409
410#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
412pub enum InputMethod {
413 VirtualKeyboard,
415 HardwareKeyboard,
417 VoiceInput,
419 Handwriting,
421 Dictation,
423}
424
425#[derive(Debug, Clone, Serialize, Deserialize)]
427pub struct VoiceInputConfig {
428 pub enabled: bool,
430 pub test_languages: Vec<String>,
432 pub test_noise_conditions: bool,
434 pub test_voice_commands: Vec<String>,
436}
437
438#[derive(Debug, Clone, Serialize, Deserialize)]
440pub struct HardwareInputConfig {
441 pub test_volume_buttons: bool,
443 pub test_power_button: bool,
445 pub test_home_button: bool,
447 pub test_back_button: bool,
449 pub test_external_accessories: bool,
451}
452
453#[derive(Debug, Clone, Serialize, Deserialize)]
455pub struct NavigationTestingConfig {
456 pub enabled: bool,
458 pub test_flows: Vec<NavigationFlow>,
460 pub test_deep_linking: bool,
462 pub test_back_navigation: bool,
464 pub test_state_restoration: bool,
466}
467
468#[derive(Debug, Clone, Serialize, Deserialize)]
470pub struct NavigationFlow {
471 pub name: String,
473 pub steps: Vec<NavigationStep>,
475 pub expected_outcomes: Vec<String>,
477}
478
479#[derive(Debug, Clone, Serialize, Deserialize)]
481pub struct NavigationStep {
482 pub step_type: NavigationStepType,
484 pub target_element: String,
486 pub parameters: HashMap<String, String>,
488}
489
490#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
492pub enum NavigationStepType {
493 Tap,
495 Navigate,
497 Wait,
499 Verify,
501 Input,
503 Swipe,
505}
506
507#[derive(Debug, Clone, Serialize, Deserialize)]
509pub struct UIPerformanceConfig {
510 pub enabled: bool,
512 pub frame_rate_monitoring: bool,
514 pub memory_monitoring: bool,
516 pub cpu_monitoring: bool,
518 pub network_monitoring: bool,
520 pub performance_thresholds: PerformanceThresholds,
522}
523
524#[derive(Debug, Clone, Serialize, Deserialize)]
526pub struct PerformanceThresholds {
527 pub min_frame_rate: f32,
529 pub max_memory_usage: usize,
531 pub max_cpu_usage: f32,
533 pub max_response_time: Duration,
535 pub max_network_latency: Duration,
537}
538
539#[derive(Debug, Clone, Serialize, Deserialize)]
541pub struct AccessibilityTestingConfig {
542 pub enabled: bool,
544 pub test_screen_reader: bool,
546 pub test_keyboard_navigation: bool,
548 pub test_color_contrast: bool,
550 pub test_text_scaling: bool,
552 pub test_voice_control: bool,
554 pub standards: Vec<AccessibilityStandard>,
556}
557
558#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
560pub enum AccessibilityStandard {
561 WCAG21AA,
563 WCAG21AAA,
565 Section508,
567 ADA,
569 IOsAccessibility,
571 AndroidAccessibility,
573}
574
575#[derive(Debug, Clone, Serialize, Deserialize)]
577pub struct UITestReportingConfig {
578 pub formats: Vec<ReportFormat>,
580 pub include_screenshots: bool,
582 pub include_videos: bool,
584 pub include_performance_metrics: bool,
586 pub include_accessibility_results: bool,
588 pub template: Option<String>,
590}
591
592#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
594pub enum ReportFormat {
595 HTML,
596 JSON,
597 XML,
598 JUnit,
599 Allure,
600 PDF,
601}
602
603#[derive(Debug, Clone, Serialize, Deserialize)]
605pub struct UITestResult {
606 pub test_id: String,
608 pub test_name: String,
610 pub test_type: UITestType,
612 pub status: TestStatus,
614 pub start_time: u64,
616 pub end_time: u64,
618 pub duration: Duration,
620 pub device_info: MobileDeviceInfo,
622 pub test_steps: Vec<UITestStep>,
624 pub screenshots: Vec<Screenshot>,
626 pub performance_metrics: Option<UIPerformanceMetrics>,
628 pub accessibility_results: Option<AccessibilityTestResults>,
630 pub error_details: Option<String>,
632 pub artifacts: Vec<TestArtifact>,
634}
635
636#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
638pub enum UITestType {
639 Functional,
641 VisualRegression,
643 Interaction,
645 Performance,
647 Accessibility,
649 EndToEnd,
651}
652
653#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
655pub enum TestStatus {
656 Passed,
658 Failed,
660 Skipped,
662 Timeout,
664 Error,
666}
667
668#[derive(Debug, Clone, Serialize, Deserialize)]
670pub struct UITestStep {
671 pub step_id: String,
673 pub step_name: String,
675 pub action: UITestAction,
677 pub status: TestStatus,
679 pub duration: Duration,
681 pub screenshot: Option<String>,
683 pub error: Option<String>,
685}
686
687#[derive(Debug, Clone, Serialize, Deserialize)]
689pub struct UITestAction {
690 pub action_type: ActionType,
692 pub target_element: String,
694 pub parameters: HashMap<String, String>,
696}
697
698#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
700pub enum ActionType {
701 Tap,
703 Type,
705 Swipe,
707 Wait,
709 Verify,
711 Navigate,
713 Scroll,
715 Pinch,
717 Screenshot,
719}
720
721#[derive(Debug, Clone, Serialize, Deserialize)]
723pub struct Screenshot {
724 pub id: String,
726 pub file_path: String,
728 pub timestamp: u64,
730 pub dimensions: (u32, u32),
732 pub format: ImageFormat,
734}
735
736#[derive(Debug, Clone, Serialize, Deserialize)]
738pub struct UIPerformanceMetrics {
739 pub avg_frame_rate: f32,
741 pub frame_drops: usize,
743 pub memory_usage: MemoryUsage,
745 pub cpu_usage: f32,
747 pub response_times: Vec<Duration>,
749 pub network_metrics: Option<NetworkMetrics>,
751}
752
753#[derive(Debug, Clone, Serialize, Deserialize)]
755pub struct MemoryUsage {
756 pub peak_mb: usize,
758 pub avg_mb: usize,
760 pub leaks_detected: usize,
762}
763
764#[derive(Debug, Clone, Serialize, Deserialize)]
766pub struct NetworkMetrics {
767 pub total_requests: usize,
769 pub failed_requests: usize,
771 pub avg_latency: Duration,
773 pub data_transferred: usize,
775}
776
777#[derive(Debug, Clone, Serialize, Deserialize)]
779pub struct AccessibilityTestResults {
780 pub overall_score: f32,
782 pub standards_compliance: HashMap<AccessibilityStandard, f32>,
784 pub issues: Vec<AccessibilityIssue>,
786 pub recommendations: Vec<String>,
788}
789
790#[derive(Debug, Clone, Serialize, Deserialize)]
792pub struct AccessibilityIssue {
793 pub issue_type: AccessibilityIssueType,
795 pub severity: SeverityLevel,
797 pub element_id: String,
799 pub description: String,
801 pub recommendation: String,
803}
804
805#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
807pub enum AccessibilityIssueType {
808 MissingLabel,
810 ColorContrast,
812 KeyboardNavigation,
814 ScreenReaderIncompatible,
816 TouchTargetTooSmall,
818 MissingFocusIndicator,
820}
821
822#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
824pub enum SeverityLevel {
825 Low,
827 Medium,
829 High,
831 Critical,
833}
834
835#[derive(Debug, Clone, Serialize, Deserialize)]
837pub struct TestArtifact {
838 pub artifact_type: ArtifactType,
840 pub file_path: String,
842 pub file_size: usize,
844 pub description: String,
846}
847
848#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
850pub enum ArtifactType {
851 Screenshot,
853 Video,
855 Log,
857 PerformanceProfile,
859 AccessibilityReport,
861 NetworkTrace,
863}
864
865pub struct UITestingFramework {
867 config: UITestingConfig,
868 device_info: MobileDeviceInfo,
869 test_runners: HashMap<UITestFramework, Box<dyn UITestRunner + Send + Sync>>,
870 test_results: Arc<Mutex<Vec<UITestResult>>>,
871 screenshot_manager: Arc<Mutex<ScreenshotManager>>,
872 performance_monitor: Arc<Mutex<PerformanceMonitor>>,
873}
874
875pub trait UITestRunner {
877 fn run_test(&self, test_config: &UITestConfig) -> Result<UITestResult>;
878 fn capture_screenshot(&self, path: &str) -> Result<Screenshot>;
879 fn find_element(&self, selector: &str) -> Result<UIElement>;
880 fn perform_action(&self, action: &UITestAction) -> Result<()>;
881 fn wait_for_element(&self, selector: &str, timeout: Duration) -> Result<UIElement>;
882}
883
884#[derive(Debug, Clone, Serialize, Deserialize)]
886pub struct UITestConfig {
887 pub test_name: String,
889 pub test_type: UITestType,
891 pub test_steps: Vec<UITestStep>,
893 pub timeout: Duration,
895 pub test_data: HashMap<String, String>,
897}
898
899#[derive(Debug, Clone, Serialize, Deserialize)]
901pub struct UIElement {
902 pub id: String,
904 pub element_type: String,
906 pub text: Option<String>,
908 pub bounds: ScreenArea,
910 pub properties: HashMap<String, String>,
912}
913
914pub struct ScreenshotManager {
916 config: ScreenshotConfig,
917 baseline_store: HashMap<String, String>,
918 comparison_engine: ImageComparisonEngine,
919}
920
921pub struct ImageComparisonEngine {
923 config: ImageComparisonConfig,
924}
925
926pub struct PerformanceMonitor {
928 config: UIPerformanceConfig,
929 metrics_collector: MetricsCollector,
930}
931
932pub struct MetricsCollector {
934 frame_rate_samples: Vec<f32>,
935 memory_samples: Vec<usize>,
936 cpu_samples: Vec<f32>,
937 response_times: Vec<Duration>,
938}
939
940impl Default for UITestingConfig {
941 fn default() -> Self {
942 Self {
943 enabled: true,
944 automation_config: TestAutomationConfig::default(),
945 visual_regression_config: VisualRegressionConfig::default(),
946 interaction_config: InteractionTestingConfig::default(),
947 performance_config: UIPerformanceConfig::default(),
948 accessibility_config: AccessibilityTestingConfig::default(),
949 reporting_config: UITestReportingConfig::default(),
950 output_directory: "/tmp/ui_tests".to_string(),
951 }
952 }
953}
954
955impl Default for TestAutomationConfig {
956 fn default() -> Self {
957 Self {
958 frameworks: vec![UITestFramework::Appium],
959 execution_timeout: Duration::from_secs(300),
960 retry_policy: RetryPolicy::default(),
961 parallel_execution: true,
962 max_concurrent_tests: 4,
963 test_data_management: TestDataManagement::default(),
964 }
965 }
966}
967
968impl Default for RetryPolicy {
969 fn default() -> Self {
970 Self {
971 max_retries: 3,
972 retry_delay: Duration::from_secs(1),
973 backoff_factor: 2.0,
974 retry_conditions: vec![
975 RetryCondition::Timeout,
976 RetryCondition::ElementNotFound,
977 RetryCondition::NetworkError,
978 ],
979 }
980 }
981}
982
983impl Default for TestDataManagement {
984 fn default() -> Self {
985 Self {
986 data_sources: vec![TestDataSource {
987 source_type: DataSourceType::Local,
988 location: "/tmp/test_data".to_string(),
989 format: DataFormat::JSON,
990 credentials: None,
991 }],
992 cleanup_strategy: DataCleanupStrategy::PerTest,
993 isolation_enabled: true,
994 }
995 }
996}
997
998impl Default for VisualRegressionConfig {
999 fn default() -> Self {
1000 Self {
1001 enabled: true,
1002 screenshot_config: ScreenshotConfig::default(),
1003 baseline_config: BaselineConfig::default(),
1004 comparison_config: ImageComparisonConfig::default(),
1005 }
1006 }
1007}
1008
1009impl Default for ScreenshotConfig {
1010 fn default() -> Self {
1011 Self {
1012 format: ImageFormat::PNG,
1013 quality: 1.0,
1014 resolution: None,
1015 exclude_areas: Vec::new(),
1016 capture_delay: Duration::from_millis(500),
1017 }
1018 }
1019}
1020
1021impl Default for BaselineConfig {
1022 fn default() -> Self {
1023 Self {
1024 storage_location: "/tmp/baselines".to_string(),
1025 update_strategy: BaselineUpdateStrategy::Manual,
1026 versioning_enabled: true,
1027 platform_specific: true,
1028 }
1029 }
1030}
1031
1032impl Default for ImageComparisonConfig {
1033 fn default() -> Self {
1034 Self {
1035 algorithm: ComparisonAlgorithm::PixelByPixel,
1036 threshold: 0.95,
1037 pixel_tolerance: 5,
1038 anti_aliasing_tolerance: true,
1039 color_tolerance: ColorTolerance {
1040 red: 10,
1041 green: 10,
1042 blue: 10,
1043 alpha: 10,
1044 },
1045 }
1046 }
1047}
1048
1049impl Default for InteractionTestingConfig {
1050 fn default() -> Self {
1051 Self {
1052 enabled: true,
1053 gesture_config: GestureTestingConfig::default(),
1054 input_config: InputTestingConfig::default(),
1055 navigation_config: NavigationTestingConfig::default(),
1056 performance_monitoring: true,
1057 }
1058 }
1059}
1060
1061impl Default for GestureTestingConfig {
1062 fn default() -> Self {
1063 Self {
1064 supported_gestures: vec![
1065 GestureType::Tap,
1066 GestureType::DoubleTap,
1067 GestureType::LongPress,
1068 GestureType::Swipe,
1069 GestureType::Pinch,
1070 ],
1071 timing_config: GestureTimingConfig::default(),
1072 validation_config: GestureValidationConfig::default(),
1073 }
1074 }
1075}
1076
1077impl Default for GestureTimingConfig {
1078 fn default() -> Self {
1079 Self {
1080 tap_duration: Duration::from_millis(100),
1081 double_tap_interval: Duration::from_millis(300),
1082 long_press_duration: Duration::from_millis(1000),
1083 swipe_duration: Duration::from_millis(500),
1084 gesture_delay: Duration::from_millis(100),
1085 }
1086 }
1087}
1088
1089impl Default for GestureValidationConfig {
1090 fn default() -> Self {
1091 Self {
1092 validate_recognition: true,
1093 validate_response: true,
1094 response_timeout: Duration::from_secs(5),
1095 validation_criteria: Vec::new(),
1096 }
1097 }
1098}
1099
1100impl Default for TextInputConfig {
1101 fn default() -> Self {
1102 Self {
1103 test_input_methods: vec![InputMethod::VirtualKeyboard],
1104 test_special_characters: true,
1105 test_languages: vec!["en".to_string()],
1106 test_validation: true,
1107 }
1108 }
1109}
1110
1111impl Default for VoiceInputConfig {
1112 fn default() -> Self {
1113 Self {
1114 enabled: false,
1115 test_languages: vec!["en".to_string()],
1116 test_noise_conditions: false,
1117 test_voice_commands: Vec::new(),
1118 }
1119 }
1120}
1121
1122impl Default for HardwareInputConfig {
1123 fn default() -> Self {
1124 Self {
1125 test_volume_buttons: true,
1126 test_power_button: false,
1127 test_home_button: true,
1128 test_back_button: true,
1129 test_external_accessories: false,
1130 }
1131 }
1132}
1133
1134impl Default for NavigationTestingConfig {
1135 fn default() -> Self {
1136 Self {
1137 enabled: true,
1138 test_flows: Vec::new(),
1139 test_deep_linking: true,
1140 test_back_navigation: true,
1141 test_state_restoration: true,
1142 }
1143 }
1144}
1145
1146impl Default for UIPerformanceConfig {
1147 fn default() -> Self {
1148 Self {
1149 enabled: true,
1150 frame_rate_monitoring: true,
1151 memory_monitoring: true,
1152 cpu_monitoring: true,
1153 network_monitoring: true,
1154 performance_thresholds: PerformanceThresholds::default(),
1155 }
1156 }
1157}
1158
1159impl Default for PerformanceThresholds {
1160 fn default() -> Self {
1161 Self {
1162 min_frame_rate: 30.0,
1163 max_memory_usage: 512, max_cpu_usage: 80.0, max_response_time: Duration::from_millis(1000),
1166 max_network_latency: Duration::from_millis(500),
1167 }
1168 }
1169}
1170
1171impl Default for AccessibilityTestingConfig {
1172 fn default() -> Self {
1173 Self {
1174 enabled: true,
1175 test_screen_reader: true,
1176 test_keyboard_navigation: true,
1177 test_color_contrast: true,
1178 test_text_scaling: true,
1179 test_voice_control: false,
1180 standards: vec![AccessibilityStandard::WCAG21AA],
1181 }
1182 }
1183}
1184
1185impl Default for UITestReportingConfig {
1186 fn default() -> Self {
1187 Self {
1188 formats: vec![ReportFormat::HTML, ReportFormat::JSON],
1189 include_screenshots: true,
1190 include_videos: false,
1191 include_performance_metrics: true,
1192 include_accessibility_results: true,
1193 template: None,
1194 }
1195 }
1196}
1197
1198impl UITestingFramework {
1199 pub fn new(config: UITestingConfig, device_info: MobileDeviceInfo) -> Result<Self> {
1201 let mut test_runners = HashMap::new();
1202
1203 for framework in &config.automation_config.frameworks {
1205 let runner = Self::create_test_runner(*framework, &device_info)?;
1206 test_runners.insert(*framework, runner);
1207 }
1208
1209 let screenshot_config = config.visual_regression_config.screenshot_config.clone();
1211 let performance_config = config.performance_config.clone();
1212
1213 Ok(Self {
1214 config,
1215 device_info,
1216 test_runners,
1217 test_results: Arc::new(Mutex::new(Vec::new())),
1218 screenshot_manager: Arc::new(Mutex::new(ScreenshotManager::new(screenshot_config))),
1219 performance_monitor: Arc::new(Mutex::new(PerformanceMonitor::new(performance_config))),
1220 })
1221 }
1222
1223 pub fn run_test_suite(&self, test_configs: Vec<UITestConfig>) -> Result<Vec<UITestResult>> {
1225 println!("Running UI test suite with {} tests", test_configs.len());
1226
1227 let mut results = Vec::new();
1228
1229 for test_config in test_configs {
1230 let result = self.run_single_test(&test_config)?;
1231 results.push(result);
1232 }
1233
1234 if let Ok(mut test_results) = self.test_results.lock() {
1236 test_results.extend(results.clone());
1237 }
1238
1239 Ok(results)
1240 }
1241
1242 pub fn run_single_test(&self, test_config: &UITestConfig) -> Result<UITestResult> {
1244 let start_time = std::time::SystemTime::now()
1245 .duration_since(std::time::UNIX_EPOCH)
1246 .unwrap_or_default()
1247 .as_secs();
1248
1249 println!("Running UI test: {}", test_config.test_name);
1250
1251 let framework = self.select_test_framework(&test_config.test_type)?;
1253 let runner = self.test_runners.get(&framework).ok_or_else(|| {
1254 TrustformersError::runtime_error(format!("No runner for framework: {:?}", framework))
1255 })?;
1256
1257 let mut attempts = 0;
1259 let max_attempts = self.config.automation_config.retry_policy.max_retries + 1;
1260 let mut last_error = None;
1261
1262 while attempts < max_attempts {
1263 match runner.run_test(test_config) {
1264 Ok(result) => {
1265 println!("UI test passed: {}", test_config.test_name);
1266 return Ok(result);
1267 },
1268 Err(e) => {
1269 last_error = Some(e);
1270 attempts += 1;
1271
1272 if attempts < max_attempts
1273 && last_error.as_ref().is_some_and(|e| self.should_retry(e))
1274 {
1275 println!(
1276 "Retrying UI test: {} (attempt {}/{})",
1277 test_config.test_name,
1278 attempts + 1,
1279 max_attempts
1280 );
1281 std::thread::sleep(self.config.automation_config.retry_policy.retry_delay);
1282 }
1283 },
1284 }
1285 }
1286
1287 let end_time = std::time::SystemTime::now()
1289 .duration_since(std::time::UNIX_EPOCH)
1290 .unwrap_or_default()
1291 .as_secs();
1292
1293 Ok(UITestResult {
1294 test_id: format!("test_{}", start_time),
1295 test_name: test_config.test_name.clone(),
1296 test_type: test_config.test_type,
1297 status: TestStatus::Failed,
1298 start_time,
1299 end_time,
1300 duration: Duration::from_secs(end_time - start_time),
1301 device_info: self.device_info.clone(),
1302 test_steps: Vec::new(),
1303 screenshots: Vec::new(),
1304 performance_metrics: None,
1305 accessibility_results: None,
1306 error_details: last_error.map(|e| format!("{:?}", e)),
1307 artifacts: Vec::new(),
1308 })
1309 }
1310
1311 pub fn generate_report(&self, results: &[UITestResult]) -> Result<String> {
1313 let mut report = String::new();
1314
1315 let total_tests = results.len();
1317 let passed_tests = results.iter().filter(|r| r.status == TestStatus::Passed).count();
1318 let failed_tests = results.iter().filter(|r| r.status == TestStatus::Failed).count();
1319 let skipped_tests = results.iter().filter(|r| r.status == TestStatus::Skipped).count();
1320
1321 report.push_str("# UI Test Report\n\n");
1322 report.push_str("## Summary\n");
1323 report.push_str(&format!("- Total Tests: {}\n", total_tests));
1324 report.push_str(&format!("- Passed: {}\n", passed_tests));
1325 report.push_str(&format!("- Failed: {}\n", failed_tests));
1326 report.push_str(&format!("- Skipped: {}\n", skipped_tests));
1327 report.push_str(&format!(
1328 "- Success Rate: {:.2}%\n\n",
1329 (passed_tests as f32 / total_tests as f32) * 100.0
1330 ));
1331
1332 report.push_str("## Test Details\n\n");
1334 for result in results {
1335 report.push_str(&format!("### {}\n", result.test_name));
1336 report.push_str(&format!("- Status: {:?}\n", result.status));
1337 report.push_str(&format!("- Duration: {:?}\n", result.duration));
1338 report.push_str(&format!("- Type: {:?}\n", result.test_type));
1339
1340 if let Some(error) = &result.error_details {
1341 report.push_str(&format!("- Error: {}\n", error));
1342 }
1343
1344 report.push('\n');
1345 }
1346
1347 Ok(report)
1348 }
1349
1350 fn create_test_runner(
1353 framework: UITestFramework,
1354 device_info: &MobileDeviceInfo,
1355 ) -> Result<Box<dyn UITestRunner + Send + Sync>> {
1356 match framework {
1357 UITestFramework::Appium => Ok(Box::new(AppiumTestRunner::new(device_info.clone())?)),
1358 UITestFramework::XCUITest | UITestFramework::Espresso => {
1369 Err(TrustformersError::runtime_error(format!(
1370 "{:?} test framework is not available: it requires a real on-device \
1371 automation bridge (Xcode/xcodebuild for XCUITest, the Android test \
1372 orchestrator for Espresso) that is not attached in this environment",
1373 framework
1374 ))
1375 .into())
1376 },
1377 _ => Err(TrustformersError::runtime_error(format!(
1378 "Unsupported test framework: {:?}",
1379 framework
1380 ))
1381 .into()),
1382 }
1383 }
1384
1385 fn select_test_framework(&self, test_type: &UITestType) -> Result<UITestFramework> {
1386 match self.device_info.platform {
1388 MobilePlatform::Ios => {
1389 if self.config.automation_config.frameworks.contains(&UITestFramework::XCUITest) {
1390 Ok(UITestFramework::XCUITest)
1391 } else {
1392 Ok(UITestFramework::Appium)
1393 }
1394 },
1395 MobilePlatform::Android => {
1396 if self.config.automation_config.frameworks.contains(&UITestFramework::Espresso) {
1397 Ok(UITestFramework::Espresso)
1398 } else {
1399 Ok(UITestFramework::Appium)
1400 }
1401 },
1402 _ => Ok(UITestFramework::Appium),
1403 }
1404 }
1405
1406 fn should_retry(&self, error: &CoreError) -> bool {
1407 for condition in &self.config.automation_config.retry_policy.retry_conditions {
1409 match condition {
1410 RetryCondition::AnyFailure => return true,
1411 RetryCondition::Timeout => {
1412 let msg = error.to_string();
1413 if msg.contains("timeout") {
1414 return true;
1415 }
1416 },
1417 RetryCondition::ElementNotFound => {
1418 let msg = error.to_string();
1419 if msg.contains("element not found") {
1420 return true;
1421 }
1422 },
1423 RetryCondition::NetworkError => {
1424 let msg = error.to_string();
1425 if msg.contains("network") {
1426 return true;
1427 }
1428 },
1429 RetryCondition::AssertionFailure => {
1430 let msg = error.to_string();
1431 if msg.contains("assertion") {
1432 return true;
1433 }
1434 },
1435 }
1436 }
1437 false
1438 }
1439}
1440
1441impl ScreenshotManager {
1442 fn new(config: ScreenshotConfig) -> Self {
1443 Self {
1444 config,
1445 baseline_store: HashMap::new(),
1446 comparison_engine: ImageComparisonEngine::new(ImageComparisonConfig::default()),
1447 }
1448 }
1449
1450 fn capture_screenshot(&self, path: &str) -> Result<Screenshot> {
1451 let timestamp = std::time::SystemTime::now()
1453 .duration_since(std::time::UNIX_EPOCH)
1454 .unwrap_or_default()
1455 .as_secs();
1456
1457 Ok(Screenshot {
1458 id: format!("screenshot_{}", timestamp),
1459 file_path: path.to_string(),
1460 timestamp,
1461 dimensions: (1080, 1920), format: self.config.format,
1463 })
1464 }
1465
1466 fn compare_screenshots(&self, baseline_path: &str, current_path: &str) -> Result<f32> {
1467 self.comparison_engine.compare_images(baseline_path, current_path)
1469 }
1470}
1471
1472impl ImageComparisonEngine {
1473 fn new(config: ImageComparisonConfig) -> Self {
1474 Self { config }
1475 }
1476
1477 fn compare_images(&self, baseline_path: &str, current_path: &str) -> Result<f32> {
1478 println!("Comparing images: {} vs {}", baseline_path, current_path);
1481 Ok(0.95) }
1483}
1484
1485impl PerformanceMonitor {
1486 fn new(config: UIPerformanceConfig) -> Self {
1487 Self {
1488 config,
1489 metrics_collector: MetricsCollector::new(),
1490 }
1491 }
1492
1493 fn start_monitoring(&mut self) -> Result<()> {
1494 self.metrics_collector.start_collection()
1495 }
1496
1497 fn stop_monitoring(&mut self) -> Result<UIPerformanceMetrics> {
1498 self.metrics_collector.stop_collection()
1499 }
1500}
1501
1502impl MetricsCollector {
1503 fn new() -> Self {
1504 Self {
1505 frame_rate_samples: Vec::new(),
1506 memory_samples: Vec::new(),
1507 cpu_samples: Vec::new(),
1508 response_times: Vec::new(),
1509 }
1510 }
1511
1512 fn start_collection(&mut self) -> Result<()> {
1513 Ok(())
1515 }
1516
1517 fn stop_collection(&mut self) -> Result<UIPerformanceMetrics> {
1518 let avg_frame_rate = if !self.frame_rate_samples.is_empty() {
1520 self.frame_rate_samples.iter().sum::<f32>() / self.frame_rate_samples.len() as f32
1521 } else {
1522 60.0
1523 };
1524
1525 let avg_memory = if !self.memory_samples.is_empty() {
1526 self.memory_samples.iter().sum::<usize>() / self.memory_samples.len()
1527 } else {
1528 100
1529 };
1530
1531 let avg_cpu = if !self.cpu_samples.is_empty() {
1532 self.cpu_samples.iter().sum::<f32>() / self.cpu_samples.len() as f32
1533 } else {
1534 50.0
1535 };
1536
1537 Ok(UIPerformanceMetrics {
1538 avg_frame_rate,
1539 frame_drops: 0,
1540 memory_usage: MemoryUsage {
1541 peak_mb: avg_memory,
1542 avg_mb: avg_memory,
1543 leaks_detected: 0,
1544 },
1545 cpu_usage: avg_cpu,
1546 response_times: self.response_times.clone(),
1547 network_metrics: None,
1548 })
1549 }
1550}
1551
1552pub struct AppiumTestRunner {
1556 device_info: MobileDeviceInfo,
1557}
1558
1559impl AppiumTestRunner {
1560 fn new(device_info: MobileDeviceInfo) -> Result<Self> {
1561 Ok(Self { device_info })
1562 }
1563}
1564
1565impl UITestRunner for AppiumTestRunner {
1566 fn run_test(&self, test_config: &UITestConfig) -> Result<UITestResult> {
1567 let start_time = std::time::SystemTime::now()
1568 .duration_since(std::time::UNIX_EPOCH)
1569 .unwrap_or_default()
1570 .as_secs();
1571
1572 let mut test_steps = Vec::new();
1574 for step in &test_config.test_steps {
1575 let step_result = self.execute_step(step)?;
1576 test_steps.push(step_result);
1577 }
1578
1579 let end_time = std::time::SystemTime::now()
1580 .duration_since(std::time::UNIX_EPOCH)
1581 .unwrap_or_default()
1582 .as_secs();
1583
1584 let status = if test_steps.iter().any(|s| s.status == TestStatus::Failed) {
1593 TestStatus::Failed
1594 } else {
1595 TestStatus::Passed
1596 };
1597
1598 Ok(UITestResult {
1599 test_id: format!("appium_test_{}", start_time),
1600 test_name: test_config.test_name.clone(),
1601 test_type: test_config.test_type,
1602 status,
1603 start_time,
1604 end_time,
1605 duration: Duration::from_secs(end_time - start_time),
1606 device_info: self.device_info.clone(),
1607 test_steps,
1608 screenshots: Vec::new(),
1609 performance_metrics: None,
1610 accessibility_results: None,
1611 error_details: None,
1612 artifacts: Vec::new(),
1613 })
1614 }
1615
1616 fn capture_screenshot(&self, _path: &str) -> Result<Screenshot> {
1625 Err(TrustformersError::runtime_error(
1626 "Appium screenshot capture is not available: this crate does not implement a real \
1627 Appium WebDriver client, so no screenshot was actually captured."
1628 .to_string(),
1629 )
1630 .into())
1631 }
1632
1633 fn find_element(&self, _selector: &str) -> Result<UIElement> {
1640 Err(TrustformersError::runtime_error(
1641 "Appium element lookup is not available: this crate does not implement a real \
1642 Appium WebDriver client, so no element was actually located."
1643 .to_string(),
1644 )
1645 .into())
1646 }
1647
1648 fn perform_action(&self, action: &UITestAction) -> Result<()> {
1655 Err(TrustformersError::runtime_error(format!(
1656 "Appium action execution ({:?} on '{}') is not available: this crate does not \
1657 implement a real Appium WebDriver client, so no action was actually performed.",
1658 action.action_type, action.target_element
1659 ))
1660 .into())
1661 }
1662
1663 fn wait_for_element(&self, selector: &str, _timeout: Duration) -> Result<UIElement> {
1664 self.find_element(selector)
1670 }
1671}
1672
1673impl AppiumTestRunner {
1674 fn execute_step(&self, step: &UITestStep) -> Result<UITestStep> {
1675 let start_time = Instant::now();
1676
1677 match self.perform_action(&step.action) {
1679 Ok(()) => Ok(UITestStep {
1680 step_id: step.step_id.clone(),
1681 step_name: step.step_name.clone(),
1682 action: step.action.clone(),
1683 status: TestStatus::Passed,
1684 duration: start_time.elapsed(),
1685 screenshot: None,
1686 error: None,
1687 }),
1688 Err(e) => Ok(UITestStep {
1689 step_id: step.step_id.clone(),
1690 step_name: step.step_name.clone(),
1691 action: step.action.clone(),
1692 status: TestStatus::Failed,
1693 duration: start_time.elapsed(),
1694 screenshot: None,
1695 error: Some(format!("{:?}", e)),
1696 }),
1697 }
1698 }
1699}
1700
1701pub struct XCUITestRunner {
1703 device_info: MobileDeviceInfo,
1704}
1705
1706impl XCUITestRunner {
1707 fn new(device_info: MobileDeviceInfo) -> Result<Self> {
1708 Ok(Self { device_info })
1709 }
1710}
1711
1712impl UITestRunner for XCUITestRunner {
1713 fn run_test(&self, test_config: &UITestConfig) -> Result<UITestResult> {
1714 Err(TrustformersError::runtime_error("XCUITest runner not implemented".into()).into())
1716 }
1717
1718 fn capture_screenshot(&self, path: &str) -> Result<Screenshot> {
1719 Err(TrustformersError::runtime_error("XCUITest screenshot not implemented".into()).into())
1721 }
1722
1723 fn find_element(&self, selector: &str) -> Result<UIElement> {
1724 Err(
1726 TrustformersError::runtime_error("XCUITest element finding not implemented".into())
1727 .into(),
1728 )
1729 }
1730
1731 fn perform_action(&self, action: &UITestAction) -> Result<()> {
1732 Err(
1734 TrustformersError::runtime_error("XCUITest action execution not implemented".into())
1735 .into(),
1736 )
1737 }
1738
1739 fn wait_for_element(&self, selector: &str, timeout: Duration) -> Result<UIElement> {
1740 Err(
1742 TrustformersError::runtime_error("XCUITest element waiting not implemented".into())
1743 .into(),
1744 )
1745 }
1746}
1747
1748pub struct EspressoTestRunner {
1750 device_info: MobileDeviceInfo,
1751}
1752
1753impl EspressoTestRunner {
1754 fn new(device_info: MobileDeviceInfo) -> Result<Self> {
1755 Ok(Self { device_info })
1756 }
1757}
1758
1759impl UITestRunner for EspressoTestRunner {
1760 fn run_test(&self, test_config: &UITestConfig) -> Result<UITestResult> {
1761 Err(TrustformersError::runtime_error("Espresso runner not implemented".into()).into())
1763 }
1764
1765 fn capture_screenshot(&self, path: &str) -> Result<Screenshot> {
1766 Err(TrustformersError::runtime_error("Espresso screenshot not implemented".into()).into())
1768 }
1769
1770 fn find_element(&self, selector: &str) -> Result<UIElement> {
1771 Err(
1773 TrustformersError::runtime_error("Espresso element finding not implemented".into())
1774 .into(),
1775 )
1776 }
1777
1778 fn perform_action(&self, action: &UITestAction) -> Result<()> {
1779 Err(
1781 TrustformersError::runtime_error("Espresso action execution not implemented".into())
1782 .into(),
1783 )
1784 }
1785
1786 fn wait_for_element(&self, selector: &str, timeout: Duration) -> Result<UIElement> {
1787 Err(
1789 TrustformersError::runtime_error("Espresso element waiting not implemented".into())
1790 .into(),
1791 )
1792 }
1793}
1794
1795#[cfg(test)]
1796mod tests {
1797 use super::*;
1798
1799 #[test]
1800 fn test_ui_testing_config_default() {
1801 let config = UITestingConfig::default();
1802 assert!(config.enabled);
1803 assert!(!config.automation_config.frameworks.is_empty());
1804 assert!(config.visual_regression_config.enabled);
1805 }
1806
1807 #[test]
1808 fn test_retry_policy_default() {
1809 let policy = RetryPolicy::default();
1810 assert_eq!(policy.max_retries, 3);
1811 assert_eq!(policy.backoff_factor, 2.0);
1812 assert!(!policy.retry_conditions.is_empty());
1813 }
1814
1815 #[test]
1816 fn test_screenshot_config_default() {
1817 let config = ScreenshotConfig::default();
1818 assert_eq!(config.format, ImageFormat::PNG);
1819 assert_eq!(config.quality, 1.0);
1820 }
1821
1822 #[test]
1823 fn test_performance_thresholds_default() {
1824 let thresholds = PerformanceThresholds::default();
1825 assert_eq!(thresholds.min_frame_rate, 30.0);
1826 assert_eq!(thresholds.max_memory_usage, 512);
1827 assert_eq!(thresholds.max_cpu_usage, 80.0);
1828 }
1829
1830 #[test]
1838 fn test_xcuitest_and_espresso_are_not_falsely_advertised_as_available() {
1839 for framework in [UITestFramework::XCUITest, UITestFramework::Espresso] {
1840 let mut config = UITestingConfig::default();
1841 config.automation_config.frameworks = vec![framework];
1842
1843 let result = UITestingFramework::new(config, MobileDeviceInfo::default());
1844 assert!(
1845 result.is_err(),
1846 "{:?} must not construct a usable test runner in this environment",
1847 framework
1848 );
1849 }
1850 }
1851
1852 #[test]
1863 fn test_appium_framework_still_constructs() {
1864 let mut config = UITestingConfig::default();
1865 config.automation_config.frameworks = vec![UITestFramework::Appium];
1866
1867 let result = UITestingFramework::new(config, MobileDeviceInfo::default());
1868 assert!(result.is_ok());
1869 }
1870
1871 fn single_step_test_config() -> UITestConfig {
1872 UITestConfig {
1873 test_name: "probe".to_string(),
1874 test_type: UITestType::Functional,
1875 test_steps: vec![UITestStep {
1876 step_id: "step-1".to_string(),
1877 step_name: "tap button".to_string(),
1878 action: UITestAction {
1879 action_type: ActionType::Tap,
1880 target_element: "submit_button".to_string(),
1881 parameters: HashMap::new(),
1882 },
1883 status: TestStatus::Passed,
1884 duration: Duration::from_secs(0),
1885 screenshot: None,
1886 error: None,
1887 }],
1888 timeout: Duration::from_secs(30),
1889 test_data: HashMap::new(),
1890 }
1891 }
1892
1893 #[test]
1902 fn test_appium_runner_reports_honest_errors_not_fabricated_ui_data() {
1903 let runner = AppiumTestRunner::new(MobileDeviceInfo::default()).expect("runner creation");
1904
1905 let screenshot_path = std::env::temp_dir().join("trustformers_mobile_appium_test.png");
1906 assert!(runner
1907 .capture_screenshot(screenshot_path.to_str().expect("valid utf8 path"))
1908 .is_err());
1909 assert!(runner.find_element("#submit_button").is_err());
1910 assert!(runner
1911 .perform_action(&UITestAction {
1912 action_type: ActionType::Tap,
1913 target_element: "submit_button".to_string(),
1914 parameters: HashMap::new(),
1915 })
1916 .is_err());
1917 }
1918
1919 #[test]
1926 fn test_appium_run_test_status_reflects_real_step_failures() {
1927 let runner = AppiumTestRunner::new(MobileDeviceInfo::default()).expect("runner creation");
1928 let result = runner.run_test(&single_step_test_config()).expect("run_test itself succeeds");
1929
1930 assert_eq!(result.test_steps.len(), 1);
1931 assert_eq!(result.test_steps[0].status, TestStatus::Failed);
1932 assert_eq!(
1933 result.status,
1934 TestStatus::Failed,
1935 "the overall result must reflect that its one step actually failed, not a hardcoded \
1936 Passed"
1937 );
1938 }
1939}