RuleStack

Configs

Stacks

Compare

Diff

RuleStack

Configs

Stacks

Compare

Diff

Read API

RuleStack

Configs

Stacks

Compare

Diff

Read API

Configs/Cursor rules/tugkanboz/awesome-cursorrules

Cursor rule

example-structures/selenium-python/.cursor/rules/test-patterns.mdc

Selenium 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 blocks

Repository

18

— · pushed 0 days ago

Last changed

2 days ago

First indexed 2 days ago.
tugkanboz/awesome-cursorrules/example-structures/selenium-python/.cursor/rules/test-patterns.mdcRawGitHub
1---
2description: Selenium pytest test patterns — data-driven tests, fixtures, error handling, and performance checks
3globs: **/test_*.py,**/*_test.py,**/tests/**/*.py
4alwaysApply: false
5---
6# Selenium Python Test Patterns
7 
8## Advanced Test Structure
9- **Arrange-Act-Assert Pattern**: Clear test structure with setup, action, and verification
10- **Data-Driven Testing**: Parametrized tests with comprehensive data coverage
11- **Test Categorization**: Smart use of pytest markers for test organization
12- **Robust Error Handling**: Graceful failure management and recovery
13 
14## Data-Driven Test Excellence
15```python
16import pytest
17from pages.login_page import LoginPage
18from pages.dashboard_page import DashboardPage
19 
20class TestUserAuthentication:
21 """Comprehensive user authentication test suite."""
22
23 @pytest.mark.smoke
24 @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 # Arrange
33 user_credentials = test_data.get_user_credentials(user_type)
34 login_page = LoginPage(driver)
35
36 # Act
37 dashboard_page = login_page.navigate() \
38 .login(user_credentials['email'], user_credentials['password'])
39
40 # Assert
41 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"
46
47 @pytest.mark.regression
48 @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 # Arrange
58 login_page = LoginPage(driver)
59
60 # Act
61 result_page = login_page.navigate() \
62 .login(invalid_credential['email'], invalid_credential['password'])
63
64 # Assert
65 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```
70 
71## Advanced Test Fixtures
72```python
73import pytest
74import json
75from typing import Dict, Any
76from selenium.webdriver.support.ui import WebDriverWait
77 
78@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")
85
86 def _load_json(self, file_path: str) -> Dict[str, Any]:
87 with open(file_path, 'r') as f:
88 return json.load(f)
89
90 def get_user_credentials(self, user_type: str) -> Dict[str, str]:
91 return self.users_data.get(user_type, {})
92
93 def get_test_scenario(self, scenario_name: str) -> Dict[str, Any]:
94 return self.test_scenarios.get(scenario_name, {})
95
96 return TestDataManager()
97 
98@pytest.fixture(scope="function")
99def clean_environment(driver):
100 """Ensure clean test environment before each test."""
101 # Clear browser data
102 driver.delete_all_cookies()
103 driver.execute_script("localStorage.clear();")
104 driver.execute_script("sessionStorage.clear();")
105
106 # Navigate to base URL
107 driver.get("https://app.example.com")
108
109 yield
110
111 # Cleanup after test
112 try:
113 # Take screenshot if test failed
114 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)}")
119 
120@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 = driver
126 self.wait = WebDriverWait(driver, default_timeout)
127
128 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 )
134
135 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 )
141
142 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 )
148
149 return WaitHelper(driver)
150```
151 
152## Error Handling and Recovery
153```python
154class TestErrorHandling:
155 """Test error scenarios and recovery mechanisms."""
156
157 @pytest.mark.error_handling
158 def test_network_error_recovery(self, driver, mock_network_error):
159 """Test application behavior during network errors."""
160 # Arrange
161 login_page = LoginPage(driver)
162
163 # Act - Simulate network error during login
164 with mock_network_error:
165 result = login_page.navigate().attempt_login("user@example.com", "password123")
166
167 # Assert
168 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"
170
171 # Test recovery
172 login_page.click_retry_button()
173 dashboard = login_page.wait_for_successful_login()
174 assert dashboard.is_loaded(), "Should successfully login after retry"
175
176 @pytest.mark.error_handling
177 def test_session_timeout_handling(self, driver, simulate_session_timeout):
178 """Test session timeout detection and handling."""
179 # Arrange
180 dashboard = DashboardPage(driver)
181 dashboard.navigate_and_login()
182
183 # Act - Simulate session timeout
184 simulate_session_timeout()
185 dashboard.perform_action_requiring_auth()
186
187 # Assert
188 assert dashboard.is_session_expired_modal_visible(), "Session expired modal should appear"
189
190 # Test re-authentication
191 dashboard.click_reauth_button()
192 login_page = LoginPage(driver)
193 assert login_page.is_loaded(), "Should redirect to login page"
194
195 @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()
200
201 # This operation might fail due to timing issues
202 success = dashboard.perform_complex_operation_with_retry(max_attempts=3)
203 assert success, "Complex operation should eventually succeed with retries"
204```
205 
206## Performance Testing
207```python
208import time
209from datetime import datetime
210 
211class TestPerformance:
212 """Performance-focused test scenarios."""
213
214 @pytest.mark.performance
215 def test_page_load_performance(self, driver):
216 """Test page load times meet performance requirements."""
217 # Measure navigation time
218 start_time = time.time()
219
220 login_page = LoginPage(driver)
221 login_page.navigate()
222
223 # Wait for page to be fully loaded
224 driver.execute_script("return document.readyState") == "complete"
225
226 load_time = time.time() - start_time
227
228 # Assert performance requirement
229 assert load_time < 3.0, f"Page load time {load_time:.2f}s exceeds 3s requirement"
230
231 # Log performance metrics
232 logger.info(f"Login page load time: {load_time:.2f}s")
233
234 @pytest.mark.performance
235 def test_form_submission_performance(self, driver, performance_monitor):
236 """Test form submission response times."""
237 login_page = LoginPage(driver)
238 login_page.navigate()
239
240 # Measure login submission time
241 with performance_monitor.measure("login_submission"):
242 dashboard = login_page.login("user@example.com", "password123")
243
244 submission_time = performance_monitor.get_last_measurement("login_submission")
245
246 assert submission_time < 2.0, f"Login submission {submission_time:.2f}s exceeds 2s requirement"
247 assert dashboard.is_loaded(), "Dashboard should load successfully"
248
249 @pytest.mark.performance
250 def test_concurrent_user_simulation(self, driver_pool):
251 """Simulate multiple concurrent users."""
252 import concurrent.futures
253
254 def simulate_user_session(driver_instance):
255 login_page = LoginPage(driver_instance)
256 dashboard = login_page.navigate().login("user@example.com", "password123")
257
258 # Simulate user actions
259 dashboard.perform_typical_user_workflow()
260 return dashboard.is_workflow_completed()
261
262 # Run concurrent sessions
263 with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
264 futures = [executor.submit(simulate_user_session, driver)
265 for driver in driver_pool]
266
267 results = [future.result() for future in concurrent.futures.as_completed(futures)]
268
269 # All sessions should complete successfully
270 assert all(results), "All concurrent user sessions should complete successfully"
271 
272```

Sections

  • Selenium Python Test Patterns
  • Advanced Test Structure
  • Data-Driven Test Excellence
  • Advanced Test Fixtures
  • Error Handling and Recovery
  • Performance Testing

What it covers

testcode-stylearchitecturetesting-strategyperformance

Glob targeting

  • **/test_*.py
  • **/*_test.py
  • **/tests/**/*.py

Format

Cursor rules

The most expressive format here. Many small .mdc files, each with frontmatter declaring when it should load, so a rule about migrations only enters context when a migration is open. Costs the most to maintain and only one editor reads it.

What the corpus says about it

Repository

Owner
tugkanboz
Language
—
License
—
Archived
no

All configs in this repo

Also in tugkanboz/awesome-cursorrules

Diff this repo’s formats

One 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?

The other instruction files in this repository
RepositoryFormatStackCoversScoreChanged
tugkanboz/awesome-cursorrulesexample-structures/cypress/.cursor/rules/api-testing.mdc · 18Cursor rulesunclassifiedtesttesting-strategyapi58/1002 days ago
tugkanboz/awesome-cursorrulesexample-structures/cypress/.cursor/rules/testing-fundamentals.mdc · 18Cursor rulesunclassifiedtestarchtesting-strategysecurity+262/1002 days ago
tugkanboz/awesome-cursorrulesrules/appium-mobile-test-automation-framework/.cursorrules · 18.cursorrulesunclassifiedteststylearchperformance+256/1002 days ago
tugkanboz/awesome-cursorrulesrules/cypress-javascript-test-automation-framework/.cursorrules · 18.cursorrulesunclassifiedtestlint-formatstylearch+459/1002 days ago
tugkanboz/awesome-cursorrulesrules/k6-performance-test-framework/.cursorrules · 18.cursorrulesunclassifiedsetupteststylearch+256/1002 days ago
tugkanboz/awesome-cursorrulesrules/restassured-java-framework/.cursorrules · 18.cursorrulesunclassifiedteststylearchsecurity+456/1002 days ago
tugkanboz/awesome-cursorrulesrules/selenium-net-test-automation-framework/.cursorrules · 18.cursorrulesunclassifiedteststylearchdeployment+156/1002 days ago
tugkanboz/awesome-cursorrulesrules/selenium-python-test-automation-framework/.cursorrules · 18.cursorrulesunclassifiedtestlint-formatstylearch+359/1002 days ago
tugkanboz/awesome-cursorrulesrules/webdriverio-javascript-test-automation-framework/.cursorrules · 18.cursorrulesunclassifiedtestlint-formatstylearch+469/1002 days ago
tugkanboz/awesome-cursorrulesexample-structures/next-js/.cursor/rules/app-router-patterns.mdc · 18Cursor rulesunclassifiedstyleapido-not65/1002 days ago
tugkanboz/awesome-cursorrulesexample-structures/react-typescript/.cursor/rules/component-development.mdc · 18Cursor rulesunclassifiedteststylearchtypes+158/1002 days ago
tugkanboz/awesome-cursorrulesexample-structures/selenium-python/.cursor/rules/framework-architecture.mdc · 18Cursor rulesunclassifiedsetuptestlint-formatstyle+393/1002 days ago
tugkanboz/awesome-cursorrulesexample-structures/selenium-python/.cursor/rules/page-object-patterns.mdc · 18Cursor rulesunclassifiedui54/1002 days ago
tugkanboz/awesome-cursorrulesframeworks/cypress/.cursor/rules/cypress-excellence.mdc · 18Cursor rulesunclassifiedtesttesting-strategysecurityperformance+158/1002 days ago
tugkanboz/awesome-cursorrulesrules/playwright-javascript-test-automation-framework/.cursorrules · 18.cursorrulesunclassifiedtestlint-formatstylearch+359/1002 days ago
tugkanboz/awesome-cursorrulesrules/vitest-javascript-unit-test-framework/.cursorrules · 18.cursorrulesunclassifiedsetupteststylearch+560/1002 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
RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack

RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack

RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack