-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_progress_auto.py
More file actions
317 lines (275 loc) · 11.8 KB
/
test_progress_auto.py
File metadata and controls
317 lines (275 loc) · 11.8 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/env python3
"""
Automatic Progress Indicator Tester
This script will automatically navigate and test progress detection.
"""
import os
import time
import json
import logging
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
import sys
# Configure logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler("test_progress_auto.log", encoding="utf-8"),
],
)
logger = logging.getLogger(__name__)
def setup_chrome_driver(headless=False):
"""Setup Chrome driver with your profile"""
chrome_options = Options()
if headless:
chrome_options.add_argument("--headless=new")
# Chrome profile path for macOS
profile_dir = os.path.expanduser(
"~/Library/Application Support/Google/Chrome/SeleniumProfile"
)
os.makedirs(profile_dir, exist_ok=True)
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--start-maximized")
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option("useAutomationExtension", False)
chrome_options.add_argument(f"--user-data-dir={profile_dir}")
try:
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=chrome_options)
driver.implicitly_wait(10)
driver.execute_script(
"Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
)
logger.info("Chrome driver setup completed successfully")
logger.info(f"Using profile: {profile_dir}")
return driver
except Exception as e:
logger.error(f"Failed to setup Chrome driver: {e}")
sys.exit(1)
def analyze_progress_elements(driver):
"""Analyze progress indicator elements on current page"""
logger.info("=== Analyzing page for progress indicators ===")
results = []
# 1. Find elements with percentage characters
percentage_elements = driver.find_elements(By.XPATH, "//*[contains(text(), '%')]")
logger.debug(f"Found {len(percentage_elements)} elements with '%'")
for i, elem in enumerate(percentage_elements):
try:
if (
elem.is_displayed()
and elem.size["width"] > 0
and elem.size["height"] > 0
):
info = {
"type": "percentage_text",
"index": i,
"tag": elem.tag_name,
"text": elem.text.strip(),
"class": elem.get_attribute("class"),
"style": elem.get_attribute("style"),
"aria": elem.get_attribute("aria-valuenow"),
"visible": True,
}
results.append(info)
logger.debug(f"Valid percentage element: {info['text']}")
except Exception as e:
logger.debug(f"Error checking percentage element {i}: {e}")
# 2. Find progress bar elements
progress_selectors = [
"//*[@role='progressbar']",
"//*[contains(@class, 'progress')]",
"//*[contains(@class, 'progress-bar')]",
]
for selector in progress_selectors:
try:
elements = driver.find_elements(By.XPATH, selector)
logger.debug(f"Selector '{selector}' found {len(elements)} elements")
for i, elem in enumerate(elements):
try:
if elem.is_displayed():
info = {
"type": "progress_bar",
"index": i,
"tag": elem.tag_name,
"class": elem.get_attribute("class"),
"style": elem.get_attribute("style"),
"aria": elem.get_attribute("aria-valuenow"),
"text": elem.text.strip(),
"width": elem.size["width"],
"height": elem.size["height"],
"visible": True,
}
results.append(info)
logger.debug(f"Found progress bar: {info['class']}")
except Exception as e:
logger.debug(f"Error checking progress element {i}: {e}")
except Exception as e:
logger.debug(f"Error with selector '{selector}': {e}")
# 3. Find generation status elements
status_selectors = [
"//*[contains(text(), 'Generating')]",
"//*[contains(text(), 'Processing')]",
"//*[contains(@class, 'generating')]",
"//*[contains(@class, 'processing')]",
]
for selector in status_selectors:
try:
elements = driver.find_elements(By.XPATH, selector)
logger.debug(f"Selector '{selector}' found {len(elements)} elements")
for i, elem in enumerate(elements):
try:
if elem.is_displayed():
info = {
"type": "generation_status",
"index": i,
"tag": elem.tag_name,
"class": elem.get_attribute("class"),
"style": elem.get_attribute("style"),
"text": elem.text.strip(),
"visible": True,
}
results.append(info)
logger.debug(f"Found status: '{info['text']}'")
except Exception as e:
logger.debug(f"Error checking status element {i}: {e}")
except Exception as e:
logger.debug(f"Error with selector '{selector}': {e}")
# Save comprehensive analysis
output_file = "progress_analysis.json"
with open(output_file, "w", encoding="utf-8") as f:
json.dump(
{
"timestamp": time.time(),
"total_elements": len(results),
"url": driver.current_url,
"page_title": driver.title,
"window_size": driver.get_window_size(),
"analysis": results,
},
f,
indent=2,
ensure_ascii=False,
)
# Take screenshot
screenshot_file = "page_screenshot.png"
driver.save_screenshot(screenshot_file)
# Print summary
logger.info("=== Analysis Summary ===")
logger.info(f"Total elements found: {len(results)}")
logger.info(
f"Percentage text elements: {sum(1 for r in results if r['type'] == 'percentage_text')}"
)
logger.info(
f"Progress bar elements: {sum(1 for r in results if r['type'] == 'progress_bar')}"
)
logger.info(
f"Generation status elements: {sum(1 for r in results if r['type'] == 'generation_status')}"
)
# Print details of percentage elements
for i, r in enumerate([r for r in results if r["type"] == "percentage_text"]):
logger.info(f"\nPercentage Element {i}:")
logger.info(f" Text: '{r['text']}'")
logger.info(f" Tag: {r['tag']}")
logger.info(f" Class: {r['class']}")
logger.info(f" Style: '{r['style']}'")
print(f"\n✅ Analysis complete!")
print(f"📊 Results saved to: {output_file}")
print(f"📸 Screenshot saved to: {screenshot_file}")
return results
def main():
print("=== Google Flow Progress Indicator Test ===\n")
print("This test will automatically analyze the Flow tool's progress indicators.")
driver = setup_chrome_driver(headless=False)
try:
# Open Flow project
url = "https://labs.google/fx/tools/flow/project/0bdaaba0-dfa6-42ed-8a3c-e0d760d490b9"
driver.get(url)
WebDriverWait(driver, 30).until(
EC.presence_of_element_located((By.TAG_NAME, "body"))
)
logger.info(f"Opened Flow tool: {url}")
# Wait for page to load completely
print("\nWaiting for page to load completely...")
time.sleep(5)
# Analyze current state
print("\nAnalyzing current page state...")
results = analyze_progress_elements(driver)
if len(results) == 0:
print("\n⚠️ No progress indicator elements found on this page.")
print(
"\nPlease start an image generation manually and run this test again."
)
# Give time to see the results
print("\n")
for i in range(10, 0, -1):
sys.stdout.write(f"\rTest will continue in {i} seconds...")
sys.stdout.flush()
time.sleep(1)
# Try to find generation interface
print("\n\nLooking for generation interface elements...")
generation_elements = driver.find_elements(
By.CSS_SELECTOR, "button, input, textarea"
)
logger.debug(f"Found {len(generation_elements)} interactive elements")
# Check if we're on the generation page
has_prompt_input = False
has_generate_button = False
for elem in generation_elements:
try:
if (
elem.get_attribute("type") in ["text", "textarea"]
or "prompt" in (elem.get_attribute("class") or "").lower()
or "input" in (elem.get_attribute("class") or "").lower()
):
has_prompt_input = True
if elem.tag_name == "BUTTON" and (
"generate" in (elem.text.lower() or "")
or "generate" in (elem.get_attribute("class") or "").lower()
or "generate" in (elem.get_attribute("aria-label") or "").lower()
):
has_generate_button = True
except Exception as e:
logger.debug(f"Error checking element: {e}")
if has_prompt_input and has_generate_button:
logger.info("✅ Generation interface elements found!")
print("✅ Generation interface elements found!")
else:
logger.warning("⚠️ Generation interface not detected on this page")
print("⚠️ You may need to navigate to the generation page manually")
# Save complete page source for debugging
source_file = "page_source.html"
with open(source_file, "w", encoding="utf-8") as f:
f.write(driver.page_source)
logger.info(f"Page source saved to: {source_file}")
print(f"\n📄 Page source saved to: {source_file}")
print("🔍 Review this file to find progress indicator selectors")
# Simple user instructions
print("\n=== Next Steps ===")
print("1. If you see the generation interface, start a generation manually")
print("2. Run this script again to analyze the progress indicator")
print("3. Check test_progress_auto.log for detailed debugging info")
input("\nPress Enter to close the browser...")
except Exception as e:
logger.error(f"Test failed: {e}")
import traceback
logger.error(f"Stack trace: {traceback.format_exc()}")
print(f"\nError: {e}")
finally:
driver.quit()
logger.info("Browser closed")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nTest interrupted by user")
logger.info("Test interrupted")