askrobots / dbbasic Public

Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.

0 downloads

dbbasic/tests/e2e/test_with_selenium.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add DBBasic crate engine logo and update README 0d628db 1 year, 2 months ago History
test_with_selenium.py · 10.2 KB · 293 lines
1#!/usr/bin/env python3
2"""
3Selenium-based automated testing for web interfaces
4Supports headless Chrome/Firefox for CI/CD environments
5"""
6
7import sys
8import time
9from selenium import webdriver
10from selenium.webdriver.common.by import By
11from selenium.webdriver.support.ui import WebDriverWait
12from selenium.webdriver.support import expected_conditions as EC
13from selenium.webdriver.chrome.service import Service
14from selenium.webdriver.chrome.options import Options as ChromeOptions
15from selenium.webdriver.firefox.options import Options as FirefoxOptions
16from selenium.common.exceptions import TimeoutException, NoSuchElementException
17
18class WebUITester:
19 def __init__(self, browser="chrome", headless=True, url="http://localhost:8003"):
20 self.url = url
21 self.browser_type = browser
22 self.headless = headless
23 self.driver = None
24 self.setup_driver()
25
26 def setup_driver(self):
27 """Initialize the web driver with appropriate options"""
28 if self.browser_type.lower() == "chrome":
29 options = ChromeOptions()
30 if self.headless:
31 options.add_argument('--headless=new') # New headless mode
32 options.add_argument('--no-sandbox')
33 options.add_argument('--disable-dev-shm-usage')
34 options.add_argument('--disable-gpu')
35 options.add_argument('--window-size=1920,1080')
36
37 try:
38 self.driver = webdriver.Chrome(options=options)
39 except Exception as e:
40 print(f"Chrome driver failed: {e}")
41 print("Trying with Firefox...")
42 self.browser_type = "firefox"
43 self.setup_firefox()
44 else:
45 self.setup_firefox()
46
47 def setup_firefox(self):
48 """Fallback to Firefox if Chrome isn't available"""
49 options = FirefoxOptions()
50 if self.headless:
51 options.add_argument('--headless')
52 options.add_argument('--width=1920')
53 options.add_argument('--height=1080')
54
55 try:
56 self.driver = webdriver.Firefox(options=options)
57 except Exception as e:
58 print(f"Firefox driver also failed: {e}")
59 sys.exit(1)
60
61 def test_syntax_highlighting(self):
62 """Test that YAML syntax highlighting works correctly"""
63 print("Testing syntax highlighting on config browser...")
64
65 # Navigate to config page
66 self.driver.get(f"{self.url}/config")
67
68 # Wait for config cards to load
69 wait = WebDriverWait(self.driver, 10)
70
71 try:
72 # Find and click first config card
73 config_card = wait.until(
74 EC.element_to_be_clickable((By.CLASS_NAME, "config-card"))
75 )
76 config_card.click()
77
78 # Wait for modal to appear
79 modal = wait.until(
80 EC.visibility_of_element_located((By.ID, "configModal"))
81 )
82
83 # Get the config content
84 config_content = self.driver.find_element(By.ID, "configContent")
85
86 # Check HTML content for proper highlighting
87 inner_html = config_content.get_attribute('innerHTML')
88 text_content = config_content.text
89
90 # Test 1: No raw style attributes should appear in text
91 if 'style=' in text_content or 'color:' in text_content:
92 print("❌ FAILED: Style attributes appearing as text!")
93 print(f"Found: {text_content[:200]}...")
94 return False
95
96 # Test 2: Should have span elements with style attributes in HTML
97 if '<span style' not in inner_html:
98 print("❌ FAILED: No syntax highlighting spans found!")
99 return False
100
101 # Test 3: Check for specific color codes (hex or rgb format)
102 # Chrome converts hex to rgb, so check for both formats
103 expected_colors = [
104 ('6a9955', 'rgb(106, 153, 85)'), # Comments green
105 ('9cdcfe', 'rgb(156, 220, 254)'), # Keys blue
106 ('ce9178', 'rgb(206, 145, 120)'), # Strings orange
107 ('569cd6', 'rgb(86, 156, 214)'), # Booleans light blue
108 ('b5cea8', 'rgb(181, 206, 168)') # Numbers green
109 ]
110
111 colors_found = 0
112 for hex_color, rgb_color in expected_colors:
113 if hex_color in inner_html or rgb_color in inner_html:
114 colors_found += 1
115
116 if colors_found == 0:
117 print("❌ FAILED: No expected color codes found in HTML!")
118 print(f"HTML sample: {inner_html[:500]}...")
119 return False
120
121 print(f"✅ PASSED: Syntax highlighting working correctly!")
122 print(f" - No style attributes in visible text")
123 print(f" - Found {colors_found}/{len(expected_colors)} expected colors")
124 print(f" - HTML structure is correct")
125
126 # Take screenshot for debugging
127 self.driver.save_screenshot("syntax_highlight_test.png")
128
129 return True
130
131 except TimeoutException:
132 print("❌ FAILED: Timeout waiting for elements")
133 return False
134 except Exception as e:
135 print(f"❌ FAILED: Unexpected error: {e}")
136 return False
137
138 def test_dashboard_links(self):
139 """Test that dashboard has links to other services"""
140 print("\nTesting dashboard links...")
141
142 self.driver.get(self.url)
143
144 try:
145 # Check for service links
146 links_to_check = [
147 ("Real-time Monitor", "http://localhost:8004"),
148 ("Test Runner", "http://localhost:8006")
149 ]
150
151 for link_text, expected_href in links_to_check:
152 try:
153 # Find link by partial text
154 elements = self.driver.find_elements(By.PARTIAL_LINK_TEXT, link_text)
155 if not elements:
156 # Try finding by href
157 elements = self.driver.find_elements(By.CSS_SELECTOR, f'a[href="{expected_href}"]')
158
159 if elements:
160 print(f"✅ Found link: {link_text} -> {expected_href}")
161 else:
162 print(f"❌ Missing link: {link_text}")
163 return False
164 except:
165 print(f"❌ Error finding link: {link_text}")
166 return False
167
168 print("✅ PASSED: All dashboard links present")
169 return True
170
171 except Exception as e:
172 print(f"❌ FAILED: {e}")
173 return False
174
175 def test_config_count(self):
176 """Test that expected number of configs are displayed"""
177 print("\nTesting config count...")
178
179 self.driver.get(f"{self.url}/config")
180 time.sleep(2) # Give time for JS to load
181
182 try:
183 # Count config cards
184 config_cards = self.driver.find_elements(By.CLASS_NAME, "config-card")
185 count = len(config_cards)
186
187 if count >= 11: # We expect at least 11 configs
188 print(f"✅ PASSED: Found {count} config files")
189
190 # List the configs found
191 for card in config_cards[:5]: # Show first 5
192 name = card.find_element(By.CLASS_NAME, "config-name").text
193 print(f" - {name}")
194 if count > 5:
195 print(f" ... and {count - 5} more")
196
197 return True
198 else:
199 print(f"❌ FAILED: Only found {count} configs (expected 11+)")
200 return False
201
202 except Exception as e:
203 print(f"❌ FAILED: {e}")
204 return False
205
206 def run_all_tests(self):
207 """Run all tests and report results"""
208 print(f"\n{'='*50}")
209 print(f"Running automated tests with {self.browser_type}")
210 print(f"Target: {self.url}")
211 print(f"Headless: {self.headless}")
212 print(f"{'='*50}")
213
214 results = []
215
216 # Run each test
217 tests = [
218 ("Dashboard Links", self.test_dashboard_links),
219 ("Config Count", self.test_config_count),
220 ("Syntax Highlighting", self.test_syntax_highlighting)
221 ]
222
223 for test_name, test_func in tests:
224 try:
225 result = test_func()
226 results.append((test_name, result))
227 except Exception as e:
228 print(f"❌ Test '{test_name}' crashed: {e}")
229 results.append((test_name, False))
230
231 # Summary
232 print(f"\n{'='*50}")
233 print("TEST SUMMARY")
234 print(f"{'='*50}")
235
236 passed = sum(1 for _, result in results if result)
237 total = len(results)
238
239 for test_name, result in results:
240 status = "✅ PASS" if result else "❌ FAIL"
241 print(f"{status}: {test_name}")
242
243 print(f"\nTotal: {passed}/{total} tests passed")
244
245 return passed == total
246
247 def cleanup(self):
248 """Close the browser"""
249 if self.driver:
250 self.driver.quit()
251
252def main():
253 """Main test runner"""
254 import argparse
255
256 parser = argparse.ArgumentParser(description='Test DBBasic web UI with Selenium')
257 parser.add_argument('--browser', default='chrome', choices=['chrome', 'firefox'],
258 help='Browser to use for testing')
259 parser.add_argument('--show-browser', action='store_true',
260 help='Run with visible browser (not headless)')
261 parser.add_argument('--url', default='http://localhost:8003',
262 help='URL to test')
263 parser.add_argument('--test', help='Run specific test only')
264
265 args = parser.parse_args()
266
267 # Create tester
268 tester = WebUITester(
269 browser=args.browser,
270 headless=not args.show_browser,
271 url=args.url
272 )
273
274 try:
275 if args.test:
276 # Run specific test
277 test_method = getattr(tester, f"test_{args.test}", None)
278 if test_method:
279 success = test_method()
280 else:
281 print(f"Unknown test: {args.test}")
282 success = False
283 else:
284 # Run all tests
285 success = tester.run_all_tests()
286
287 return 0 if success else 1
288
289 finally:
290 tester.cleanup()
291
292if __name__ == "__main__":
293 sys.exit(main())