Cursor rule
example-structures/selenium-python/.cursor/rules/test-patterns.mdcSelenium pytest test patterns — data-driven tests, fixtures, error handling, and performance checks
Cursor rules
Quality
66/100
Scores the file, not the repository.Length
822 words
6 headings · 3 code blocksRepository
18
— · pushed 0 days agoLast changed
2 days ago
First indexed 2 days ago.123456# Selenium Python Test Patterns78## Advanced Test Structure9- **Arrange-Act-Assert Pattern**: Clear test structure with setup, action, and verification10- **Data-Driven Testing**: Parametrized tests with comprehensive data coverage11- **Test Categorization**: Smart use of pytest markers for test organization12- **Robust Error Handling**: Graceful failure management and recovery1314## Data-Driven Test Excellence15```python16import pytest17from pages.login_page import LoginPage18from pages.dashboard_page import DashboardPage1920class TestUserAuthentication:21 """Comprehensive user authentication test suite."""2223 @pytest.mark.smoke24 @pytest.mark.parametrize("user_type,expected_dashboard", [25 ("admin", "admin-dashboard"),26 ("manager", "manager-dashboard"),27 ("employee", "employee-dashboard"),28 ("guest", "guest-dashboard")29 ])30 def test_role_based_dashboard_access(self, driver, test_data, user_type, expected_dashboard):31 """Test that users see appropriate dashboard based on their role."""32 # Arrange33 user_credentials = test_data.get_user_credentials(user_type)34 login_page = LoginPage(driver)3536 # Act37 dashboard_page = login_page.navigate() \38 .login(user_credentials['email'], user_credentials['password'])3940 # Assert41 assert dashboard_page.is_loaded(), f"Dashboard not loaded for {user_type}"42 assert dashboard_page.get_dashboard_type() == expected_dashboard, \43 f"Wrong dashboard type for {user_type}"44 assert dashboard_page.get_user_role() == user_type.upper(), \45 f"User role not displayed correctly"4647 @pytest.mark.regression48 @pytest.mark.parametrize("invalid_credential", [49 {"email": "invalid@example.com", "password": "validPassword123", "error": "Invalid email"},50 {"email": "valid@example.com", "password": "wrongPassword", "error": "Invalid password"},51 {"email": "", "password": "validPassword123", "error": "Email is required"},52 {"email": "valid@example.com", "password": "", "error": "Password is required"},53 {"email": "notanemail", "password": "validPassword123", "error": "Invalid email format"}54 ])55 def test_login_validation_errors(self, driver, invalid_credential):56 """Test comprehensive login validation error scenarios."""57 # Arrange58 login_page = LoginPage(driver)5960 # Act61 result_page = login_page.navigate() \62 .login(invalid_credential['email'], invalid_credential['password'])6364 # Assert65 assert isinstance(result_page, LoginPage), "Should remain on login page for invalid credentials"66 assert result_page.get_error_message() == invalid_credential['error'], \67 f"Expected error: {invalid_credential['error']}"68 assert result_page.is_password_field_cleared(), "Password field should be cleared after error"69```7071## Advanced Test Fixtures72```python73import pytest74import json75from typing import Dict, Any76from selenium.webdriver.support.ui import WebDriverWait7778@pytest.fixture(scope="session")79def test_data():80 """Load test data from JSON files."""81 class TestDataManager:82 def __init__(self):83 self.users_data = self._load_json("test_data/users.json")84 self.test_scenarios = self._load_json("test_data/scenarios.json")8586 def _load_json(self, file_path: str) -> Dict[str, Any]:87 with open(file_path, 'r') as f:88 return json.load(f)8990 def get_user_credentials(self, user_type: str) -> Dict[str, str]:91 return self.users_data.get(user_type, {})9293 def get_test_scenario(self, scenario_name: str) -> Dict[str, Any]:94 return self.test_scenarios.get(scenario_name, {})9596 return TestDataManager()9798@pytest.fixture(scope="function")99def clean_environment(driver):100 """Ensure clean test environment before each test."""101 # Clear browser data102 driver.delete_all_cookies()103 driver.execute_script("localStorage.clear();")104 driver.execute_script("sessionStorage.clear();")105106 # Navigate to base URL107 driver.get("https://app.example.com")108109 yield110111 # Cleanup after test112 try:113 # Take screenshot if test failed114 if hasattr(driver, '_test_failed') and driver._test_failed:115 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")116 driver.save_screenshot(f"screenshots/failed_test_{timestamp}.png")117 except Exception as e:118 logger.warning(f"Cleanup failed: {str(e)}")119120@pytest.fixture(scope="function")121def wait_helper(driver):122 """Provide advanced waiting utilities."""123 class WaitHelper:124 def __init__(self, driver, default_timeout=10):125 self.driver = driver126 self.wait = WebDriverWait(driver, default_timeout)127128 def wait_for_page_transition(self, expected_url_contains: str, timeout: int = 15):129 """Wait for page URL to change to expected pattern."""130 return self.wait.until(131 lambda d: expected_url_contains in d.current_url,132 message=f"Page did not transition to URL containing: {expected_url_contains}"133 )134135 def wait_for_ajax_complete(self, timeout: int = 30):136 """Wait for all AJAX requests to complete."""137 return self.wait.until(138 lambda d: d.execute_script("return jQuery.active == 0"),139 message="AJAX requests did not complete"140 )141142 def wait_for_custom_condition(self, condition_script: str, timeout: int = 10):143 """Wait for custom JavaScript condition to be true."""144 return self.wait.until(145 lambda d: d.execute_script(f"return {condition_script}"),146 message=f"Custom condition not met: {condition_script}"147 )148149 return WaitHelper(driver)150```151152## Error Handling and Recovery153```python154class TestErrorHandling:155 """Test error scenarios and recovery mechanisms."""156157 @pytest.mark.error_handling158 def test_network_error_recovery(self, driver, mock_network_error):159 """Test application behavior during network errors."""160 # Arrange161 login_page = LoginPage(driver)162163 # Act - Simulate network error during login164 with mock_network_error:165 result = login_page.navigate().attempt_login("user@example.com", "password123")166167 # Assert168 assert login_page.is_network_error_displayed(), "Network error message should be visible"169 assert login_page.is_retry_button_visible(), "Retry button should be available"170171 # Test recovery172 login_page.click_retry_button()173 dashboard = login_page.wait_for_successful_login()174 assert dashboard.is_loaded(), "Should successfully login after retry"175176 @pytest.mark.error_handling177 def test_session_timeout_handling(self, driver, simulate_session_timeout):178 """Test session timeout detection and handling."""179 # Arrange180 dashboard = DashboardPage(driver)181 dashboard.navigate_and_login()182183 # Act - Simulate session timeout184 simulate_session_timeout()185 dashboard.perform_action_requiring_auth()186187 # Assert188 assert dashboard.is_session_expired_modal_visible(), "Session expired modal should appear"189190 # Test re-authentication191 dashboard.click_reauth_button()192 login_page = LoginPage(driver)193 assert login_page.is_loaded(), "Should redirect to login page"194195 @pytest.mark.flaky(reruns=3, reruns_delay=2)196 def test_flaky_operation_with_retry(self, driver):197 """Test flaky operations with automatic retry mechanism."""198 dashboard = DashboardPage(driver)199 dashboard.navigate_and_login()200201 # This operation might fail due to timing issues202 success = dashboard.perform_complex_operation_with_retry(max_attempts=3)203 assert success, "Complex operation should eventually succeed with retries"204```205206## Performance Testing207```python208import time209from datetime import datetime210211class TestPerformance:212 """Performance-focused test scenarios."""213214 @pytest.mark.performance215 def test_page_load_performance(self, driver):216 """Test page load times meet performance requirements."""217 # Measure navigation time218 start_time = time.time()219220 login_page = LoginPage(driver)221 login_page.navigate()222223 # Wait for page to be fully loaded224 driver.execute_script("return document.readyState") == "complete"225226 load_time = time.time() - start_time227228 # Assert performance requirement229 assert load_time < 3.0, f"Page load time {load_time:.2f}s exceeds 3s requirement"230231 # Log performance metrics232 logger.info(f"Login page load time: {load_time:.2f}s")233234 @pytest.mark.performance235 def test_form_submission_performance(self, driver, performance_monitor):236 """Test form submission response times."""237 login_page = LoginPage(driver)238 login_page.navigate()239240 # Measure login submission time241 with performance_monitor.measure("login_submission"):242 dashboard = login_page.login("user@example.com", "password123")243244 submission_time = performance_monitor.get_last_measurement("login_submission")245246 assert submission_time < 2.0, f"Login submission {submission_time:.2f}s exceeds 2s requirement"247 assert dashboard.is_loaded(), "Dashboard should load successfully"248249 @pytest.mark.performance250 def test_concurrent_user_simulation(self, driver_pool):251 """Simulate multiple concurrent users."""252 import concurrent.futures253254 def simulate_user_session(driver_instance):255 login_page = LoginPage(driver_instance)256 dashboard = login_page.navigate().login("user@example.com", "password123")257258 # Simulate user actions259 dashboard.perform_typical_user_workflow()260 return dashboard.is_workflow_completed()261262 # Run concurrent sessions263 with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:264 futures = [executor.submit(simulate_user_session, driver)265 for driver in driver_pool]266267 results = [future.result() for future in concurrent.futures.as_completed(futures)]268269 # All sessions should complete successfully270 assert all(results), "All concurrent user sessions should complete successfully"271272```
Also in tugkanboz/awesome-cursorrules
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| tugkanboz/awesome-cursorrulesexample-structures/cypress/.cursor/rules/api-testing.mdc · 18 | Cursor rules | testtesting-strategyapi | 58/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesexample-structures/cypress/.cursor/rules/testing-fundamentals.mdc · 18 | Cursor rules | testarchtesting-strategysecurity+2 | 62/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesrules/appium-mobile-test-automation-framework/.cursorrules · 18 | .cursorrules | teststylearchperformance+2 | 56/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesrules/cypress-javascript-test-automation-framework/.cursorrules · 18 | .cursorrules | testlint-formatstylearch+4 | 59/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesrules/k6-performance-test-framework/.cursorrules · 18 | .cursorrules | setupteststylearch+2 | 56/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesrules/restassured-java-framework/.cursorrules · 18 | .cursorrules | teststylearchsecurity+4 | 56/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesrules/selenium-net-test-automation-framework/.cursorrules · 18 | .cursorrules | teststylearchdeployment+1 | 56/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesrules/selenium-python-test-automation-framework/.cursorrules · 18 | .cursorrules | testlint-formatstylearch+3 | 59/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesrules/webdriverio-javascript-test-automation-framework/.cursorrules · 18 | .cursorrules | testlint-formatstylearch+4 | 69/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesexample-structures/next-js/.cursor/rules/app-router-patterns.mdc · 18 | Cursor rules | styleapido-not | 65/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesexample-structures/react-typescript/.cursor/rules/component-development.mdc · 18 | Cursor rules | teststylearchtypes+1 | 58/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesexample-structures/selenium-python/.cursor/rules/framework-architecture.mdc · 18 | Cursor rules | setuptestlint-formatstyle+3 | 93/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesexample-structures/selenium-python/.cursor/rules/page-object-patterns.mdc · 18 | Cursor rules | ui | 54/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesframeworks/cypress/.cursor/rules/cypress-excellence.mdc · 18 | Cursor rules | testtesting-strategysecurityperformance+1 | 58/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesrules/playwright-javascript-test-automation-framework/.cursorrules · 18 | .cursorrules | testlint-formatstylearch+3 | 59/100 | 2 days ago | |
| tugkanboz/awesome-cursorrulesrules/vitest-javascript-unit-test-framework/.cursorrules · 18 | .cursorrules | setupteststylearch+5 | 60/100 | 2 days ago |
Diff against example-structures/cypress/.cursor/rules/api-testing.mdc Diff against example-structures/cypress/.cursor/rules/testing-fundamentals.mdc Diff against rules/appium-mobile-test-automation-framework/.cursorrules Diff against rules/cypress-javascript-test-automation-framework/.cursorrules Diff against rules/k6-performance-test-framework/.cursorrules Diff against rules/restassured-java-framework/.cursorrules Diff against rules/selenium-net-test-automation-framework/.cursorrules Diff against rules/selenium-python-test-automation-framework/.cursorrules Diff against rules/webdriverio-javascript-test-automation-framework/.cursorrules Diff against example-structures/next-js/.cursor/rules/app-router-patterns.mdc Diff against example-structures/react-typescript/.cursor/rules/component-development.mdc Diff against example-structures/selenium-python/.cursor/rules/framework-architecture.mdc Diff against example-structures/selenium-python/.cursor/rules/page-object-patterns.mdc Diff against frameworks/cypress/.cursor/rules/cypress-excellence.mdc Diff against rules/playwright-javascript-test-automation-framework/.cursorrules Diff against rules/vitest-javascript-unit-test-framework/.cursorrules
