-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathhelper.py
More file actions
334 lines (256 loc) · 9.86 KB
/
helper.py
File metadata and controls
334 lines (256 loc) · 9.86 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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
"""
Helper utilities for platform tests.
Provides:
- Lightweight REST wrappers (no SDK abstraction where raw status codes matter)
- Polling helpers (compilation, generic condition)
- Simple selector/object helpers
No automatic cleanup; pipelines are left in place for inspection after failures.
"""
from __future__ import annotations
import json
import time
import pytest
import requests
import logging
from typing import Any, Dict, Iterable
from http import HTTPStatus
from urllib.parse import quote, quote_plus
from feldera.testutils_oidc import get_oidc_test_helper
from tests import (
FELDERA_REQUESTS_VERIFY,
API_KEY,
BASE_URL,
TEST_CLIENT,
unique_pipeline_name,
)
from feldera.testutils import FELDERA_TEST_NUM_WORKERS, FELDERA_TEST_NUM_HOSTS
API_PREFIX = "/v0"
def _base_headers() -> Dict[str, str]:
headers = {
"Accept": "application/json",
}
# Try OIDC authentication first, then fall back to API_KEY
oidc_helper = get_oidc_test_helper()
if oidc_helper is not None:
token = oidc_helper.obtain_access_token()
headers["Authorization"] = f"Bearer {token}"
elif API_KEY:
headers["Authorization"] = f"Bearer {API_KEY}"
return headers
def api_url(fragment: str) -> str:
if not fragment.startswith("/"):
fragment = "/" + fragment
return f"{API_PREFIX}{fragment}"
def http_request(method: str, path: str, **kwargs) -> requests.Response:
"""
Low-level request wrapper (no retries). Raises only on network errors.
Args:
method: HTTP method (GET, POST, etc.)
path: URL path
base_headers: Optional override for base headers. If None (default), uses _base_headers().
If empty dict {}, no base headers are applied (for testing unauthenticated requests).
**kwargs: Additional arguments passed to requests.request()
"""
if not path.startswith("/"):
path = "/" + path
url = BASE_URL.rstrip("/") + path
# Allow override of base headers for testing unauthenticated requests
base_headers_arg = kwargs.pop("base_headers", None)
if base_headers_arg is None:
base_headers = _base_headers() # Default: include auth headers
else:
base_headers = base_headers_arg # Override: could be {} for no auth
custom_headers = kwargs.pop("headers", None) or {}
headers = {
**base_headers,
**custom_headers,
} # Merge, with custom headers taking precedence
# Provide a default timeout to avoid hanging tests.
timeout = kwargs.pop("timeout", 30)
kwargs["verify"] = FELDERA_REQUESTS_VERIFY
resp = requests.request(
method.upper(), url, headers=headers, timeout=timeout, **kwargs
)
return resp
def get(path: str, **kw) -> requests.Response:
return http_request("GET", path, **kw)
def get_pipeline(name: str, selector: str) -> requests.Response:
return get(f"{API_PREFIX}/pipelines/{name}?selector={selector}")
def post_no_body(path: str, **kw):
return http_request("POST", path, **kw)
def post_json(path: str, body: Dict[str, Any], **kw) -> requests.Response:
return http_request("POST", path, json=body, **kw)
def put_json(path: str, body: Dict[str, Any], **kw) -> requests.Response:
return http_request("PUT", path, json=body, **kw)
def patch_json(path: str, body: Dict[str, Any], **kw) -> requests.Response:
return http_request("PATCH", path, json=body, **kw)
def delete(path: str, **kw) -> requests.Response:
return http_request("DELETE", path, **kw)
def create_pipeline(name: str, sql: str):
r = post_json(
api_url("/pipelines"),
{
"name": name,
"program_code": sql,
"runtime_config": {
"workers": FELDERA_TEST_NUM_WORKERS,
"hosts": FELDERA_TEST_NUM_HOSTS,
"logging": "debug",
},
},
)
assert r.status_code == HTTPStatus.CREATED, r.text
wait_for_program_success(name, 1)
def start_pipeline(name: str, wait: bool = True):
TEST_CLIENT.start_pipeline(name, wait=wait)
def resume_pipeline(name: str, wait: bool = True):
TEST_CLIENT.resume_pipeline(name, wait=wait)
def start_pipeline_as_paused(name: str, wait: bool = True):
TEST_CLIENT.start_pipeline_as_paused(name, wait=wait)
def pause_pipeline(name: str, wait: bool = True):
TEST_CLIENT.pause_pipeline(name, wait=wait)
def stop_pipeline(name: str, force: bool = True, wait: bool = True):
TEST_CLIENT.stop_pipeline(name, force=force, wait=wait)
def clear_pipeline(name: str, wait: bool = True):
r = post_no_body(f"{API_PREFIX}/pipelines/{name}/clear")
if wait and r.status_code == HTTPStatus.ACCEPTED:
TEST_CLIENT.clear_storage(name)
return r
def reset_pipeline(name: str):
if get_pipeline(name, "status").status_code != HTTPStatus.OK:
return
stop_pipeline(name, force=True)
clear_pipeline(name)
def delete_pipeline(name: str):
return delete(api_url(f"pipelines/{name}"))
def cleanup_pipeline(name: str):
reset_pipeline(name)
delete_pipeline(name)
def connector_action(pipeline: str, table: str, connector: str, action: str):
table_enc = quote(table, safe="")
r = post_no_body(
api_url(
f"/pipelines/{pipeline}/tables/{table_enc}/connectors/{connector}/{action}"
)
)
return r
def adhoc_query_json(pipeline: str, sql: str):
"Runs a SQL query, returns results as list of dicts (JSON lines format)."
path = api_url(f"/pipelines/{pipeline}/query?sql={quote_plus(sql)}&format=json")
resp = get(path)
assert resp.status_code == HTTPStatus.OK, (
f"Adhoc query failed: status={resp.status_code}, body={resp.text}"
)
raw = resp.text.strip()
if not raw:
return []
lines = raw.split("\n")
return [json.loads(line) for line in lines if line]
def pipeline_stats(pipeline: str):
r = get(api_url(f"/pipelines/{pipeline}/stats"))
assert r.status_code == HTTPStatus.OK, (r.status_code, r.text)
return r.json()
def connector_stats(pipeline: str, table: str, connector: str):
table_enc = quote(table, safe="")
res = get(
api_url(
f"/pipelines/{pipeline}/tables/{table_enc}/connectors/{connector}/stats"
)
)
assert res.status_code == HTTPStatus.OK, (res.status_code, res.text)
return res.json()
def connector_paused(pipeline, table: str, connector: str) -> bool:
return connector_stats(pipeline, table, connector)["paused"]
def wait_for_program_success(
pipeline_name: str,
expected_program_version: int,
timeout_s: float = 1800.0,
poll_interval_s: float = 0.5,
) -> None:
"""
Wait until the pipeline's program has compiled successfully and reached
`expected_program_version`.
"""
TEST_CLIENT._wait_for_compilation(
pipeline_name,
expected_program_version=expected_program_version,
timeout_s=timeout_s,
poll_interval_s=poll_interval_s,
)
def wait_for_condition(
description: str,
predicate_func,
timeout_s: float | None,
poll_interval_s: float,
) -> None:
"""
Waits until the condition is met by regularly checking if `predicate_func()` returns `True`.
:param description: Human-readable description used in timeout/errors.
:param predicate_func: Callable function (taking `this` pipeline as argument) returning `True` when condition is met.
:param timeout_s: Maximum wait time in seconds. `None` means there is no timeout.
:param poll_interval_s: Poll interval in seconds. The timeout is enforced at this granularity.
:raises TimeoutError: If the condition is not met within the specified timeout.
"""
# Polling interval should not exceed the timeout
if timeout_s is not None and poll_interval_s > timeout_s:
raise ValueError(
f"poll interval ({poll_interval_s}s) cannot be larger than"
f" timeout ({timeout_s}s)"
)
# Waiting constant variables
timestamp_start_s = time.monotonic()
timestamp_deadline_s = timestamp_start_s + timeout_s
if timeout_s is None:
timeout_info = "no timeout is enforced"
else:
timeout_info = f"timeout: {timeout_s:.1}s"
# Waiting loop: exits either if the predicate function returns a value which evaluates to `True`
# or a timeout (if enforced) -- whichever occurs first.
attempt = 0
while True:
timestamp_now_s = time.monotonic()
if timestamp_now_s > timestamp_deadline_s:
raise TimeoutError(
f"timeout ({timeout_s:.1}s) waiting for condition '{description}'"
)
attempt += 1
if predicate_func():
logging.debug(
f"condition '{description}' has been met after {timestamp_now_s - timestamp_start_s:.1}s"
)
return
else:
logging.debug(
f"condition '{description}' is not yet met (attempt: {attempt}); {timestamp_now_s - timestamp_start_s:.1}s have passed ({timeout_info})"
)
time.sleep(poll_interval_s)
def extract_object_by_name(
collection: Iterable[Dict[str, Any]], name: str
) -> Dict[str, Any]:
for obj in collection:
if obj.get("name") == name:
return obj
raise KeyError(f"Object with name '{name}' not found in collection")
def gen_pipeline_name(func):
"""
Decorator for pytest functions that automatically generates a unique pipeline name.
The decorated function will receive a 'pipeline_name' parameter.
After the test completes, attempts to delete the pipeline but ignores any errors.
"""
return pytest.mark.usefixtures("pipeline_name")(func)
__all__ = [
"API_PREFIX",
"HTTPStatus",
"http_request",
"get",
"post_json",
"put_json",
"patch_json",
"delete",
"wait_for_program_success",
"wait_for_condition",
"unique_pipeline_name",
"extract_object_by_name",
"gen_pipeline_name",
"connector_action",
]