-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_browser_automation.py
More file actions
250 lines (195 loc) · 7.91 KB
/
test_browser_automation.py
File metadata and controls
250 lines (195 loc) · 7.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#!/usr/bin/env python3
"""
Real Browser Automation Test for Browser Controller
This test demonstrates actual browser automation capabilities:
- Opening a browser
- Navigating to websites
- Interacting with page elements
- Taking screenshots
- Proper cleanup
Prerequisites:
- Internet connection
- Browser drivers (handled automatically by webdriver-manager)
"""
import asyncio
import os
import sys
from pathlib import Path
# Add src to path
sys.path.insert(0, str(Path(__file__).parent / "src"))
from src.core.browser_controller import BrowserController
from src.config.browser_config import BrowserConfig
from src.types.browser_types import BrowserType
async def test_basic_navigation():
"""Test basic browser navigation and page interaction"""
print("🌐 Testing basic navigation and interaction...")
# Create configuration for headless testing
config = BrowserConfig(
browser_type=BrowserType.CHROME,
headless=True, # Run in headless mode for CI/automated testing
window_size=(1280, 720),
page_load_timeout=30,
implicit_wait=10
)
async with BrowserController(config) as controller:
# Create a session
session = await controller.create_session()
try:
# Navigate to a simple test page
await session.navigate_to("https://httpbin.org/html")
print("✓ Successfully navigated to test page")
# Try to find an element
title_element = await session.find_element("h1")
if title_element:
print("✓ Found title element on page")
# Take a screenshot
screenshot_path = "test_screenshot.png"
success = await session.take_screenshot(screenshot_path)
if success and os.path.exists(screenshot_path):
print(f"✓ Screenshot saved to {screenshot_path}")
# Clean up screenshot
os.remove(screenshot_path)
except Exception as e:
print(f"❌ Error during navigation test: {e}")
return False
finally:
await controller.close_session(session.session_id)
return True
async def test_form_interaction():
"""Test form interaction capabilities"""
print("📝 Testing form interaction...")
config = BrowserConfig(
browser_type=BrowserType.CHROME,
headless=True,
window_size=(1280, 720)
)
async with BrowserController(config) as controller:
session = await controller.create_session()
try:
# Navigate to httpbin forms page
await session.navigate_to("https://httpbin.org/forms/post")
print("✓ Navigated to forms test page")
# Try to interact with form elements
# Find input field by name
custname_input = await session.find_element("input[name='custname']")
if custname_input:
await session.type_text("input[name='custname']", "Test User")
print("✓ Successfully typed in form field")
# Find and interact with radio button
size_radio = await session.find_element("input[value='medium']")
if size_radio:
await session.click_element("input[value='medium']")
print("✓ Successfully clicked radio button")
except Exception as e:
print(f"❌ Error during form interaction test: {e}")
return False
finally:
await controller.close_session(session.session_id)
return True
async def test_multiple_sessions():
"""Test managing multiple browser sessions"""
print("🔄 Testing multiple sessions...")
config = BrowserConfig(
browser_type=BrowserType.CHROME,
headless=True,
window_size=(1280, 720)
)
async with BrowserController(config) as controller:
sessions = []
try:
# Create multiple sessions
for i in range(3):
session = await controller.create_session()
sessions.append(session)
await session.navigate_to("https://httpbin.org/html")
print(f"✓ Successfully created and navigated {len(sessions)} sessions")
# Verify all sessions are active
active_sessions = controller.get_active_sessions()
if len(active_sessions) == 3:
print("✓ All sessions are properly tracked")
except Exception as e:
print(f"❌ Error during multiple sessions test: {e}")
return False
finally:
# Clean up all sessions
for session in sessions:
await controller.close_session(session.session_id)
return True
async def test_error_handling():
"""Test error handling and recovery"""
print("⚠️ Testing error handling...")
config = BrowserConfig(
browser_type=BrowserType.CHROME,
headless=True,
page_load_timeout=5 # Short timeout to test timeout handling
)
async with BrowserController(config) as controller:
session = await controller.create_session()
try:
# Test invalid URL handling
try:
await session.navigate_to("http://this-domain-should-not-exist-12345.com")
print("❌ Should have failed on invalid URL")
return False
except Exception:
print("✓ Properly handled invalid URL")
# Test element not found handling
await session.navigate_to("https://httpbin.org/html")
element = await session.find_element("non-existent-element")
if element is None:
print("✓ Properly handled element not found")
except Exception as e:
print(f"❌ Unexpected error during error handling test: {e}")
return False
finally:
await controller.close_session(session.session_id)
return True
async def main():
"""Run all browser automation tests"""
print("=" * 60)
print("Browser Controller - Real Browser Automation Tests")
print("=" * 60)
print()
tests = [
("Basic Navigation", test_basic_navigation),
("Form Interaction", test_form_interaction),
("Multiple Sessions", test_multiple_sessions),
("Error Handling", test_error_handling)
]
passed = 0
failed = 0
for test_name, test_func in tests:
print(f"--- Running {test_name} Test ---")
try:
success = await test_func()
if success:
print(f"✓ {test_name} test PASSED")
passed += 1
else:
print(f"❌ {test_name} test FAILED")
failed += 1
except Exception as e:
print(f"❌ {test_name} test FAILED with exception: {e}")
failed += 1
print()
print("=" * 60)
print(f"Test Results: {passed} PASSED, {failed} FAILED")
if failed == 0:
print("🎉 All browser automation tests passed!")
print()
print("Your Browser Controller is ready for:")
print("• Web scraping and data extraction")
print("• Automated testing and form submission")
print("• UI interaction and screenshot capture")
print("• Integration with other LAM components")
else:
print("❌ Some tests failed. Check your setup:")
print("• Internet connection")
print("• Browser installation (Chrome recommended)")
print("• Firewall/antivirus settings")
print("=" * 60)
return failed == 0
if __name__ == "__main__":
# Run the tests
success = asyncio.run(main())
sys.exit(0 if success else 1)