-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_utils.py
More file actions
295 lines (241 loc) · 8.78 KB
/
test_utils.py
File metadata and controls
295 lines (241 loc) · 8.78 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
"""
This module provides a set of utilities for testing NanoDash applications
"""
import threading
import time
import pytest
import requests
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.support.ui import Select
from selenium.common.exceptions import TimeoutException, NoSuchElementException
@pytest.fixture
def selenium_webdriver():
"""
Pytest fixture for launching and quitting a Selenium WebDriver instance.
Yields:
Selenium WebDriver instance connected to the running app
Usage:
text_input = selenium_webdriver.find_element(By.ID, "element-id")
"""
driver = None
try:
driver = create_webdriver()
yield driver
except Exception as e:
raise e
finally:
if driver:
driver.quit()
def create_webdriver(headless: bool = False):
"""
Returns a new Selenium WebDriver instance pointed at 127.0.0.1:5000.
Args:
headless: If True, run the browser in headless mode (no GUI).
Returns:
Selenium WebDriver instance
"""
options = webdriver.ChromeOptions()
if headless:
options.add_argument("--headless=new")
driver = webdriver.Chrome(options=options)
driver.get("http://127.0.0.1:5000")
return driver
def start_app(app_object):
"""
Start the provided Flask app in a daemon thread.
"""
app = app_object
def run_app():
app.run(threaded=True, use_reloader=False, port=5000)
app_thread = threading.Thread(
target=run_app,
daemon=True,
)
app_thread.start()
# Wait for the app to start
driver = create_webdriver(headless=True)
WebDriverWait(driver, timeout=10).until(
EC.presence_of_element_located((By.TAG_NAME, "html"))
)
driver.quit()
return app_thread
def wait_for_graph_render(driver, graph_id, timeout=10):
"""Wait for a Plotly graph to render and return the SVG element.
Args:
driver: Selenium WebDriver instance
graph_id: ID of the graph component to wait for
timeout: Maximum time to wait in seconds
Returns:
True if graph rendered within timeout, False otherwise
"""
try:
WebDriverWait(driver, timeout).until(
EC.presence_of_element_located((By.CSS_SELECTOR, f"#{graph_id} .main-svg"))
)
return True
except TimeoutException:
return False
def setup_fetch_interceptor(driver, url_path="/handle-change"):
"""Setup JavaScript to intercept fetch requests and store payloads/responses.
Args:
driver: Selenium WebDriver instance
url_path: URL path to intercept (default: '/handle-change')
"""
driver.execute_script(f"""
window.lastPayload = null;
window.lastResponse = null;
const originalFetch = window.fetch;
window.fetch = function(url, options) {{
if (url === '{url_path}' && options && options.body) {{
window.lastPayload = JSON.parse(options.body);
}}
return originalFetch(url, options).then(response => {{
if (url === '{url_path}') {{
return response.clone().json().then(data => {{
window.lastResponse = data;
return response;
}});
}}
return response;
}});
}};
""")
def check_component_exists(driver, component_id):
"""Check if a component exists in the DOM.
Args:
driver: Selenium WebDriver instance
component_id: ID of the component to check
Returns:
True if the component exists, False otherwise
"""
try:
driver.find_element(By.ID, component_id)
return True
except NoSuchElementException:
return False
def get_graph_data(driver, graph_id):
"""Get the data from a Plotly graph.
Args:
driver: Selenium WebDriver instance
graph_id: ID of the graph component
Returns:
Dictionary with graph data or None if not found
"""
return driver.execute_script(f"""
const graphDiv = document.getElementById('{graph_id}');
if (graphDiv && graphDiv.data) {{
return graphDiv.data;
}}
return null;
""")
def set_component_value(driver, component_id, value):
"""Set the value of a component.
Args:
driver: Selenium WebDriver instance
component_id: ID of the component
value: Value to set
Returns:
True if successful, False otherwise
"""
try:
element = driver.find_element(By.ID, component_id)
element_type = element.tag_name.lower()
if element_type == "input":
input_type = element.get_attribute("type")
if input_type == "text":
element.clear()
for char in value:
element.send_keys(char)
time.sleep(0.05)
elif element_type == "select":
select = Select(element)
select.select_by_value(value)
return True
except Exception as e:
print("Exception while setting component value: ", e)
return False
def get_component_value(driver, component_id):
"""Get the value of a component.
Args:
driver: Selenium WebDriver instance
component_id: ID of the component
Returns:
Value of the component or None if component doesn't exist
"""
try:
element = driver.find_element(By.ID, component_id)
element_type = element.tag_name.lower()
if element_type == "input":
return element.get_attribute("value")
elif element_type == "select":
return element.get_attribute("value")
elif element_type == "div":
# For components that might store their value in innerHTML
return element.text
return None
except:
return None
def wait_for_callback_completion(driver, timeout=5):
"""Wait for all pending callbacks to complete.
Args:
driver: Selenium WebDriver instance
timeout: Maximum time to wait in seconds
Returns:
True if callbacks completed within timeout, False otherwise
"""
try:
start_time = time.time()
while time.time() - start_time < timeout:
# Check if the fetch interceptor has recorded a response
has_response = driver.execute_script("return window.lastResponse !== null;")
if has_response:
# Give a small additional time for UI updates
time.sleep(0.5)
return True
time.sleep(0.1)
return False
except:
return False
def verify_request_contents(request_contents, expected_trigger_id, expected_state):
"""Verify that the request contains the expected trigger ID and state."""
assert "trigger_id" in request_contents, "Request should contain `trigger_id` key"
assert "state" in request_contents, "Request should contain `state` key"
state = request_contents["state"]
assert request_contents["trigger_id"] == expected_trigger_id, (
f"trigger_id should be `{expected_trigger_id}`"
)
for component_id in expected_state:
assert component_id in state, (
f"State should include component with ID `{component_id}`"
)
assert state[component_id] == expected_state[component_id], (
f"State for `{component_id}` should be `{expected_state[component_id]}`"
)
def post_callback_request(payload):
response = requests.post(
"http://127.0.0.1:5000/handle-change",
json=payload,
headers={"Content-Type": "application/json"},
)
assert response.status_code == 200, "Callback request should return status code 200"
return response.json()
def verify_response_contents(response_contents, expected_response_contents):
"""Verify that the response contains the expected contents."""
assert response_contents, "Response should not be empty"
assert isinstance(response_contents, dict), "Response should be a dictionary"
# Check that all expected keys are in the response
for key in expected_response_contents:
assert key in response_contents, f"Key '{key}' should be in the response"
# Check that no unexpected keys are in the response
for key in response_contents:
assert key in expected_response_contents, (
f"Key '{key}' should not be in the response"
)
# Check that all keys have the expected values
for key, value in expected_response_contents.items():
assert value in str(response_contents[key]), (
f"Value '{value}' should be in the response for key '{key}'"
)