Branchwell

Become a Pro / website · becomeapro.ai / tests / selenium / page_objects / ai_coach_page.py

Raw 24.2 KB on 6c7ce85c3441baadd17890ab9cc9bf8ed5112901
1from selenium.webdriver.common.by import By
2from selenium.webdriver.common.keys import Keys
3from selenium.webdriver.support.ui import WebDriverWait
4from selenium.webdriver.support import expected_conditions as EC
5from selenium.common.exceptions import TimeoutException, NoSuchElementException
6import time
7import os
8import sys
9
10# Import from utils module instead of test_ai_coach
11from utils import save_screenshot
12
13
14class AICoachPage:
15 """Page Object Model for the AI Coach page."""
16
17 # URL
18 URL_PATH = "/ai-coach"
19
20 # Locators
21 CHAT_CONTAINER = (By.CSS_SELECTOR, ".flex.flex-col.flex-1")
22 CHAT_INPUT = (By.CSS_SELECTOR, "input[placeholder='Type your response...']")
23 SEND_BUTTON = (By.CSS_SELECTOR, "button[type='submit']")
24 CHAT_MESSAGES = (By.CSS_SELECTOR, "div.whitespace-pre-line")
25 ASSISTANT_MESSAGES = (By.CSS_SELECTOR, "div.flex div.whitespace-pre-line")
26 USER_MESSAGES = (By.CSS_SELECTOR, "div.text-white")
27 CHOICE_BUTTONS = (By.CSS_SELECTOR, "div.flex.flex-wrap button")
28 GENERATE_ROADMAP_BUTTON = (By.XPATH, "//button[contains(text(), 'Generate') and contains(@class, 'w-full')]")
29 LOADING_SCREEN = (By.CSS_SELECTOR, "div.fixed")
30 BRAIN_ICON = (By.CSS_SELECTOR, "svg")
31 LOADING_INDICATOR = (By.CSS_SELECTOR, ".animate-spin")
32 LOADING_PROGRESS = (By.CSS_SELECTOR, "p.text-white")
33 ROADMAP_HEADING = (By.XPATH, "//h1[contains(text(), 'AI Roadmap') or contains(text(), 'Your Roadmap')]")
34
35 def __init__(self, driver, base_url):
36 """Initialize with WebDriver instance and base URL."""
37 self.driver = driver
38 self.base_url = base_url
39 self.wait = WebDriverWait(driver, 10)
40
41 def open(self):
42 """Navigate to the AI Coach page."""
43 self.driver.get(f"{self.base_url}{self.URL_PATH}")
44 return self
45
46 def is_loaded(self):
47 """Check if the page is loaded by verifying initial message is displayed."""
48 try:
49 # Reduce standard wait to 5 seconds for initial page load
50 WebDriverWait(self.driver, 5).until(EC.presence_of_element_located(self.ASSISTANT_MESSAGES))
51 return True
52 except TimeoutException:
53 return False
54
55 def send_message(self, message):
56 """Type and send a message in the chat input."""
57 try:
58 # Wait for input field to be visible and clickable with reduced timeout
59 input_field = WebDriverWait(self.driver, 10).until(
60 EC.element_to_be_clickable(self.CHAT_INPUT)
61 )
62
63 # Clear any existing text and type the message
64 input_field.clear()
65 input_field.send_keys(message)
66
67 # Find and click send button
68 send_button = WebDriverWait(self.driver, 5).until(
69 EC.element_to_be_clickable(self.SEND_BUTTON)
70 )
71
72 send_button.click()
73 return True
74 except Exception as e:
75 print(f"Error sending message: {e}")
76 return False
77
78 def get_latest_assistant_message(self):
79 """Get the latest message from the assistant."""
80 try:
81 # Wait for assistant response with a shorter timeout
82 WebDriverWait(self.driver, 3).until(lambda d: len(d.find_elements(*self.ASSISTANT_MESSAGES)) > 0)
83
84 # Get all assistant messages
85 messages = self.driver.find_elements(*self.ASSISTANT_MESSAGES)
86 if messages:
87 # Return the text of the latest message
88 return messages[-1].text
89 return None
90 except (TimeoutException, NoSuchElementException):
91 return None
92
93 def click_choice(self, choice_text):
94 """
95 Click a multiple choice button with the given text.
96 Will try to find a button that contains the specified text (case-insensitive, partial match).
97 """
98 try:
99 # Wait for choices to be displayed with a reduced timeout
100 WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(self.CHOICE_BUTTONS))
101
102 # Special handling for budget selection which often causes issues
103 if "$" in choice_text or "budget" in choice_text.lower():
104 print("Special handling for budget selection")
105 # Try specific XPath for budget buttons
106 budget_xpath = "//button[contains(text(), '$') or contains(text(), 'budget') or contains(text(), 'Budget')]"
107 budget_buttons = self.driver.find_elements(By.XPATH, budget_xpath)
108
109 if budget_buttons:
110 # Log all budget buttons found
111 button_texts = [btn.text.strip() for btn in budget_buttons if btn.text.strip()]
112 print(f"Budget buttons found: {button_texts}")
113
114 # Find the best matching button for the user's choice
115 selected_button = None
116
117 # First try exact match
118 for button in budget_buttons:
119 if button.text.strip().lower() == choice_text.lower():
120 selected_button = button
121 print(f"Found exact match for budget: '{button.text.strip()}'")
122 break
123
124 # If no exact match, try partial match with $ amount
125 if not selected_button and "$50" in choice_text:
126 for button in budget_buttons:
127 if "$50" in button.text:
128 selected_button = button
129 print(f"Found partial match for $50 budget: '{button.text.strip()}'")
130 break
131
132 # If still no match, try any button that contains the word "budget"
133 if not selected_button:
134 for button in budget_buttons:
135 if "$" in button.text:
136 selected_button = button
137 print(f"Found budget button with $ sign: '{button.text.strip()}'")
138 break
139
140 # If we found a button, click it
141 if selected_button:
142 # Scroll the button into view first
143 self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", selected_button)
144 time.sleep(1) # Give time for scrolling to complete
145
146 # Take screenshot before clicking
147 save_screenshot(self.driver, "before_budget_click.png")
148
149 # Click using JavaScript
150 self.driver.execute_script("arguments[0].click();", selected_button)
151 print(f"Clicked budget button: '{selected_button.text.strip()}'")
152
153 # Take screenshot after clicking
154 time.sleep(1)
155 save_screenshot(self.driver, "after_budget_click.png")
156 return True
157
158 # Find all choice buttons (standard approach if not budget)
159 choices = self.driver.find_elements(*self.CHOICE_BUTTONS)
160
161 # Print available choices for debugging
162 choice_texts = [btn.text.strip() for btn in choices]
163 print(f"Available choices: {choice_texts}")
164
165 # First try exact match
166 for button in choices:
167 button_text = button.text.strip()
168 if button_text.lower() == choice_text.lower():
169 print(f"Found exact match button: '{button_text}'")
170 # Scroll the button into view first
171 self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
172 time.sleep(0.5) # Give time for scrolling
173
174 # Click using JavaScript
175 self.driver.execute_script("arguments[0].click();", button)
176 print(f"Clicked button: '{button_text}'")
177 time.sleep(0.5) # Give time for UI to update
178 return True
179
180 # If no exact match, try partial match
181 for button in choices:
182 button_text = button.text.strip()
183 if choice_text.lower() in button_text.lower() or button_text.lower() in choice_text.lower():
184 print(f"Found partial match button: '{button_text}'")
185 # Scroll the button into view first
186 self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
187 time.sleep(0.5) # Give time for scrolling
188
189 # Click using JavaScript
190 self.driver.execute_script("arguments[0].click();", button)
191 print(f"Clicked button: '{button_text}'")
192 time.sleep(0.5) # Give time for UI to update
193 return True
194
195 # If still no match but buttons exist, try to find a button containing key terms
196 if choices:
197 # Terms to look for in buttons based on the user's input
198 key_terms = []
199 if "$" in choice_text:
200 key_terms.append("$")
201 if "beginner" in choice_text.lower():
202 key_terms.append("beginner")
203 if "hour" in choice_text.lower():
204 key_terms.append("hour")
205
206 # Check for buttons containing key terms
207 for term in key_terms:
208 for button in choices:
209 button_text = button.text.strip()
210 if term.lower() in button_text.lower():
211 print(f"Found button matching term '{term}': '{button_text}'")
212 # Scroll the button into view first
213 self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
214 time.sleep(0.5) # Give time for scrolling
215
216 # Click using JavaScript
217 self.driver.execute_script("arguments[0].click();", button)
218 print(f"Clicked button: '{button_text}'")
219 time.sleep(0.5) # Give time for UI to update
220 return True
221
222 # Last resort: click the first button as fallback
223 button = choices[0]
224 button_text = button.text.strip()
225 print(f"No match found, clicking first button as fallback: '{button_text}'")
226 # Scroll the button into view first
227 self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
228 time.sleep(0.5) # Give time for scrolling
229
230 # Click using JavaScript
231 self.driver.execute_script("arguments[0].click();", button)
232 print(f"Clicked button: '{button_text}'")
233 time.sleep(0.5) # Give time for UI to update
234 return True
235
236 print(f"No buttons found that match: '{choice_text}'")
237 return False # No buttons found
238 except Exception as e:
239 print(f"Error clicking choice: {e}")
240 import traceback
241 traceback.print_exc()
242 save_screenshot(self.driver, "error_clicking_choice.png")
243 return False
244
245 def generate_roadmap(self):
246 """Click the Generate Roadmap button."""
247 try:
248 print("Looking for the Generate Roadmap button...")
249
250 # Scroll to bottom of page
251 self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
252
253 # Try direct xpath first for better matching
254 generate_button_xpath = "//button[contains(text(), 'Generate') and contains(text(), 'Roadmap')]"
255 buttons = self.driver.find_elements(By.XPATH, generate_button_xpath)
256
257 if buttons:
258 print(f"Found Generate Roadmap button via XPath ({len(buttons)} matches)")
259 # Ensure button is in view
260 self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", buttons[0])
261
262 # Click the first matching button
263 self.driver.execute_script("arguments[0].click();", buttons[0])
264 print("Clicked Generate Roadmap button via XPath")
265 return True
266
267 # Try our class-based selector if the text-based selector fails
268 button = None
269 try:
270 # Try the specific button with our defined selector
271 button = WebDriverWait(self.driver, 5).until(
272 EC.element_to_be_clickable(self.GENERATE_ROADMAP_BUTTON)
273 )
274 print("Found button with Generate Roadmap class selector")
275 except (TimeoutException, NoSuchElementException):
276 # Fallback to finding any button that appears to be a submit/action button
277 print("Specific button not found, looking for any action button...")
278 buttons = self.driver.find_elements(By.CSS_SELECTOR, "button.w-full, button.bg-primary, button.bg-purple-600")
279 if buttons:
280 print(f"Found {len(buttons)} potential action buttons")
281 # Use the last one, as it's likely the generate button at the end of the chat
282 button = buttons[-1]
283
284 # Print button text for debugging
285 button_text = button.text.strip()
286 print(f"Using button with text: '{button_text}'")
287
288 # Ensure it's clickable
289 self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
290 else:
291 print("No potential action buttons found")
292 return False
293
294 # Scroll to the button to ensure it's in view
295 self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button)
296
297 # Click using JavaScript for reliability
298 self.driver.execute_script("arguments[0].click();", button)
299 print("Generate Roadmap button clicked")
300
301 # Wait for loading screen to appear with short timeout
302 try:
303 WebDriverWait(self.driver, 3).until(EC.presence_of_element_located(self.LOADING_SCREEN))
304 print("Loading screen appeared")
305 return True
306 except (TimeoutException, NoSuchElementException):
307 print("Loading screen did not appear, but button was clicked")
308 # Return true anyway, as the button was clicked
309 return True
310
311 except Exception as e:
312 print(f"Error generating roadmap: {e}")
313 import traceback
314 traceback.print_exc()
315 return False
316
317 def wait_for_loading_complete(self, timeout=60):
318 """Wait for the loading screen to complete and verify roadmap is displayed."""
319 try:
320 start_time = time.time()
321 print("Waiting for loading to start and complete...")
322
323 # Check if we're already on the roadmap page
324 try:
325 if self.driver.find_elements(*self.ROADMAP_HEADING):
326 print("Roadmap already loaded, no loading indicator detected")
327 return True
328 except:
329 pass
330
331 # Wait for loading screen or indicator to appear
332 try:
333 # Try to find either the loading screen or the loading indicator with short timeout
334 WebDriverWait(self.driver, 5).until(
335 lambda d: d.find_elements(*self.LOADING_SCREEN) or
336 d.find_elements(*self.LOADING_INDICATOR)
337 )
338 print("Loading started")
339
340 # Take a screenshot of the loading screen
341 save_screenshot(self.driver, "loading_screen_animated.png")
342 print("Screenshot taken of the loading animation")
343
344 except:
345 print("No loading screen or indicator found - checking if roadmap is already visible")
346 # If neither loading screen nor indicator is found, check again for roadmap
347 try:
348 WebDriverWait(self.driver, 2).until(
349 EC.visibility_of_element_located(self.ROADMAP_HEADING)
350 )
351 print("Roadmap already loaded, no loading detected")
352 return True
353 except:
354 print("Neither loading elements nor roadmap heading found")
355
356 # Wait for loading screen and loading indicator to disappear
357 # Use polling to check status periodically rather than waiting the full timeout
358 poll_interval = 2 # Check every 2 seconds
359 poll_count = int(timeout / poll_interval)
360
361 for i in range(poll_count):
362 if not self.driver.find_elements(*self.LOADING_SCREEN) and not self.driver.find_elements(*self.LOADING_INDICATOR):
363 print(f"Loading elements disappeared after {i * poll_interval} seconds")
364 break
365
366 # Check if progress has reached 100% (if progress element exists)
367 try:
368 progress_element = self.driver.find_element(*self.LOADING_PROGRESS)
369 progress_text = progress_element.text if progress_element else ""
370 if any(text in progress_text for text in ["100%", "Complete", "Done"]):
371 print(f"Progress reached 100% after {i * poll_interval} seconds")
372 break
373
374 # Take a mid-loading screenshot to capture progress indicators
375 # Only take one screenshot during the middle of loading (around 40-60% complete)
376 if progress_text and any(text in progress_text for text in ["40%", "50%", "60%"]):
377 save_screenshot(self.driver, "loading_screen_progress.png")
378 print(f"Screenshot taken of loading progress: {progress_text}")
379
380 except:
381 pass
382
383 # Check if URL changed to roadmap URL
384 if "/roadmap" in self.driver.current_url:
385 print(f"URL changed to roadmap after {i * poll_interval} seconds")
386 return True
387
388 time.sleep(poll_interval)
389
390 # Check for roadmap elements
391 roadmap_candidates = [
392 # Original roadmap heading selector
393 self.ROADMAP_HEADING,
394 # Alternative selectors that might indicate the roadmap is present
395 (By.XPATH, "//h1[contains(text(), 'Roadmap')]"),
396 (By.XPATH, "//div[contains(@class, 'roadmap')]"),
397 (By.XPATH, "//section[contains(@class, 'roadmap')]"),
398 (By.CSS_SELECTOR, ".roadmap-container"),
399 (By.CSS_SELECTOR, ".roadmap-section"),
400 # Any heading containing roadmap
401 (By.XPATH, "//*[self::h1 or self::h2 or self::h3][contains(text(), 'roadmap') or contains(text(), 'Roadmap')]")
402 ]
403
404 # Check URL first
405 if "/roadmap" in self.driver.current_url:
406 print(f"URL contains '/roadmap', assuming roadmap generated successfully: {self.driver.current_url}")
407 return True
408
409 # Try all selectors
410 found_selector = None
411 for selector in roadmap_candidates:
412 try:
413 elements = self.driver.find_elements(*selector)
414 if elements:
415 found_selector = selector
416 print(f"Found roadmap indicator with selector: {selector}")
417 break
418 except:
419 continue
420
421 if found_selector:
422 end_time = time.time()
423 print(f"Roadmap found after {end_time - start_time:.2f} seconds - roadmap generation successful!")
424 return True
425
426 # Final fallback - check page content
427 try:
428 body_text = self.driver.find_element(By.TAG_NAME, "body").text.lower()
429 if "roadmap" in body_text:
430 print("Found 'roadmap' in page content, assuming roadmap was generated")
431 return True
432 except:
433 pass
434
435 print("Could not find any roadmap indicators")
436 return False
437
438 except Exception as e:
439 print(f"Error waiting for loading to complete: {e}")
440 import traceback
441 traceback.print_exc()
442 return False
443
444 def get_all_messages(self):
445 """Get all messages in the chat (both user and assistant)."""
446 messages = self.driver.find_elements(*self.CHAT_CONTAINER)
447 return [msg.text for msg in messages]
448
449 def has_multiple_choice_buttons(self):
450 """Check if multiple choice buttons are currently displayed."""
451 try:
452 # First try with our defined selector
453 choices = self.driver.find_elements(*self.CHOICE_BUTTONS)
454 if choices and len(choices) > 0:
455 return True
456
457 # If no buttons found with the default selector, try alternative selectors
458 # Try any buttons that might be part of a multiple choice UI
459 alt_choices = self.driver.find_elements(By.CSS_SELECTOR, "button.bg-blue-gradient, button.bg-primary, button.rounded-lg")
460 if alt_choices and len(alt_choices) > 0:
461 # Check if these are likely choice buttons (not just random buttons)
462 visible_buttons = [btn for btn in alt_choices if btn.is_displayed()]
463 if len(visible_buttons) >= 2: # Multiple choice usually has at least 2 options
464 print(f"Found {len(visible_buttons)} potential choice buttons with alternative selector")
465 return True
466
467 # Special handling for budget buttons which sometimes have different classes
468 budget_buttons = self.driver.find_elements(By.XPATH, "//button[contains(text(), '$')]")
469 if budget_buttons and len(budget_buttons) > 0:
470 print(f"Found {len(budget_buttons)} budget buttons")
471 return True
472
473 return False
474 except (TimeoutException, NoSuchElementException):
475 return False
476
477 def send_response(self, message, fast_mode=True):
478 """
479 Send a response to the AI, either by clicking a choice button or typing a message.
480 This is a smart method that detects if multiple choice buttons are available.
481
482 Args:
483 message: Text to send or button text to click
484 fast_mode: If True, use faster testing mode with minimal waits and screenshots
485
486 Returns:
487 bool: True if message was sent successfully
488 """
489 # First check if multiple choice buttons are present
490 print("Checking for multiple choice buttons...")
491
492 # Take a screenshot only in debug mode
493 if not fast_mode:
494 save_screenshot(self.driver, "ui_state_before_response.png")
495
496 if self.has_multiple_choice_buttons():
497 print(f"Multiple choice buttons found, trying to click '{message}'")
498 return self.click_choice(message)
499 else:
500 print(f"No multiple choice buttons found, sending text message: '{message}'")
501 return self.send_message(message)