-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtest_collectors_base.py
More file actions
576 lines (402 loc) · 15.8 KB
/
Copy pathtest_collectors_base.py
File metadata and controls
576 lines (402 loc) · 15.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
"""Tests for core.collectors base types."""
from io import StringIO
from unittest.mock import patch
import pytest
from django.core.management.base import CommandError
import core.collectors.base_collector as collector_lifecycle
from core.collectors.base_collector import AbstractCollector
from core.collectors.command_base import BaseCollectorCommand
from core.tracker_result import GenericTrackerResult
_OK = GenericTrackerResult.ok()
class _CallCommandCollector(AbstractCollector):
"""Invokes ``call_command`` from :meth:`collect` (tests adapter-style collectors)."""
__slots__ = ("_command_name",)
def __init__(self, command_name: str) -> None:
self._command_name = command_name
@property
def name(self) -> str:
return "call_command_adapter"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
from django.core.management import call_command as _call_command
_call_command(self._command_name)
return _OK
def test_call_command_collector_collect_invokes_call_command():
with patch("django.core.management.call_command") as m:
c = _CallCommandCollector("run_boost_usage_tracker")
c.collect()
m.assert_called_once_with("run_boost_usage_tracker")
def test_call_command_collector_sync_pinecone_default_noop():
c = _CallCommandCollector("check")
assert c.sync_pinecone() is None
def test_base_collector_command_runs_then_sync_pinecone():
phases = []
class OkCollector(AbstractCollector):
@property
def name(self) -> str:
return "ok"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
phases.append("run")
return _OK
def sync_pinecone(self) -> None:
phases.append("sync")
class Cmd(BaseCollectorCommand):
help = "test"
def get_collector(self, **options):
return OkCollector()
Cmd(stdout=StringIO(), stderr=StringIO()).handle()
assert phases == ["run", "sync"]
def test_base_collector_command_propagates_command_error():
class BadCollector(AbstractCollector):
@property
def name(self) -> str:
return "bad"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
raise CommandError("planned", returncode=3)
class Cmd(BaseCollectorCommand):
help = "test"
def get_collector(self, **options):
return BadCollector()
with pytest.raises(CommandError, match="planned"):
Cmd(stdout=StringIO(), stderr=StringIO()).handle()
def test_abstract_collector_handle_error_logs_failure_category():
class PhaseCollector(AbstractCollector):
@property
def name(self) -> str:
return "phase"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
return _OK
collector = PhaseCollector()
collector._error_phase = "fetch"
with patch.object(collector_lifecycle.logger, "exception") as mock_exc:
collector.handle_error(RuntimeError("boom"))
mock_exc.assert_called_once()
assert "phase" in str(mock_exc.call_args)
def test_base_collector_command_logs_and_reraises_generic_exception():
class BadCollector(AbstractCollector):
@property
def name(self) -> str:
return "bad"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
raise RuntimeError("boom")
class Cmd(BaseCollectorCommand):
help = "test"
def get_collector(self, **options):
return BadCollector()
with patch.object(BadCollector, "handle_error") as mock_handle:
with pytest.raises(RuntimeError, match="boom"):
Cmd(stdout=StringIO(), stderr=StringIO()).handle()
mock_handle.assert_called_once()
assert isinstance(mock_handle.call_args[0][0], RuntimeError)
def test_base_collector_command_requires_get_collector_at_instantiation():
class IncompleteCmd(BaseCollectorCommand):
help = "test"
with pytest.raises(TypeError, match="get_collector"):
IncompleteCmd(stdout=StringIO(), stderr=StringIO())
def test_base_collector_command_failure_classifies_in_handle_error():
class BadCollector(AbstractCollector):
@property
def name(self) -> str:
return "bad"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
raise ValueError("bad input")
class Cmd(BaseCollectorCommand):
help = "test"
def get_collector(self, **options):
return BadCollector()
with patch.object(collector_lifecycle.logger, "exception") as mock_exc:
with pytest.raises(ValueError, match="bad input"):
Cmd(stdout=StringIO(), stderr=StringIO()).handle()
mock_exc.assert_called_once()
assert mock_exc.call_args[1]["extra"]["failure_category"] == "validation"
def test_base_collector_command_double_fault_clears_error_phase():
class BadCollector(AbstractCollector):
@property
def name(self) -> str:
return "bad"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
raise RuntimeError("primary")
held: dict[str, AbstractCollector] = {}
class Cmd(BaseCollectorCommand):
help = "test"
def get_collector(self, **options):
c = BadCollector()
held["c"] = c
return c
cmd = Cmd(stdout=StringIO(), stderr=StringIO())
with patch.object(
BadCollector,
"handle_error",
side_effect=AssertionError("secondary"),
):
with pytest.raises(AssertionError, match="secondary"):
cmd.handle()
assert not hasattr(held["c"], "_error_phase")
def test_abstract_collector_run_calls_hooks_in_order():
order = []
class AC(AbstractCollector):
@property
def name(self) -> str:
return "ac_test"
def pre_collect(self) -> None:
order.append("pre_collect")
def validate_config(self) -> None:
order.append("validate")
def collect(self) -> GenericTrackerResult:
order.append("collect")
return _OK
def post_collect(self) -> None:
order.append("post_collect")
AC().run()
assert order == ["pre_collect", "validate", "collect", "post_collect"]
def test_abstract_collector_run_default_hooks_are_no_ops():
class Minimal(AbstractCollector):
@property
def name(self) -> str:
return "minimal"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
return _OK
Minimal().run()
def test_abstract_collector_run_failure_in_pre_collect_skips_later_phases():
calls = []
class AC(AbstractCollector):
@property
def name(self) -> str:
return "ac"
def pre_collect(self) -> None:
calls.append("pre_collect")
raise RuntimeError("pre failed")
def validate_config(self) -> None:
calls.append("validate")
def collect(self) -> GenericTrackerResult:
calls.append("collect")
return _OK
def post_collect(self) -> None:
calls.append("post_collect")
def on_error(self, exc: BaseException) -> None:
calls.append(("on_error", exc))
with pytest.raises(RuntimeError, match="pre failed"):
AC().run()
assert calls == ["pre_collect", ("on_error", calls[1][1])]
assert isinstance(calls[1][1], RuntimeError)
def test_abstract_collector_run_failure_in_validate_skips_collect_and_post():
calls = []
class AC(AbstractCollector):
@property
def name(self) -> str:
return "ac"
def validate_config(self) -> None:
calls.append("validate")
raise ValueError("bad config")
def collect(self) -> GenericTrackerResult:
calls.append("collect")
return _OK
def post_collect(self) -> None:
calls.append("post_collect")
def on_error(self, exc: BaseException) -> None:
calls.append(("on_error", type(exc).__name__))
with pytest.raises(ValueError, match="bad config"):
AC().run()
assert calls == ["validate", ("on_error", "ValueError")]
def test_abstract_collector_run_failure_in_collect_skips_post_collect():
calls = []
class AC(AbstractCollector):
@property
def name(self) -> str:
return "ac"
def validate_config(self) -> None:
calls.append("validate")
def collect(self) -> GenericTrackerResult:
calls.append("collect")
raise RuntimeError("collect failed")
def post_collect(self) -> None:
calls.append("post_collect")
def on_error(self, exc: BaseException) -> None:
calls.append("on_error")
with pytest.raises(RuntimeError, match="collect failed"):
AC().run()
assert calls == ["validate", "collect", "on_error"]
def test_abstract_collector_run_failure_in_post_collect_calls_on_error():
calls = []
class AC(AbstractCollector):
@property
def name(self) -> str:
return "ac"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
calls.append("collect")
return _OK
def post_collect(self) -> None:
raise RuntimeError("post failed")
def on_error(self, exc: BaseException) -> None:
calls.append("on_error")
collector = AC()
with pytest.raises(RuntimeError, match="post failed"):
collector.run()
assert calls == ["collect", "on_error"]
assert collector.last_result is None
def test_abstract_collector_run_failure_in_persist_incremental_state_does_not_set_last_result():
from core.incremental_state import GenericIncrementalState
state_out = GenericIncrementalState(checkpoint_token="t", human_readable_marker="m")
class AC(AbstractCollector):
@property
def name(self) -> str:
return "ac"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
self._incremental_state_out = state_out
return _OK
def persist_incremental_state(self, state) -> None:
raise RuntimeError("persist failed")
collector = AC()
with pytest.raises(RuntimeError, match="persist failed"):
collector.run()
assert collector.last_result is None
def test_abstract_collector_run_on_error_does_not_swallow_exception():
class AC(AbstractCollector):
@property
def name(self) -> str:
return "ac"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
raise RuntimeError("primary")
def on_error(self, exc: BaseException) -> None:
pass
with pytest.raises(RuntimeError, match="primary"):
AC().run()
def test_abstract_collector_run_on_error_failure_still_reraises_original():
class AC(AbstractCollector):
@property
def name(self) -> str:
return "ac"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
raise RuntimeError("primary")
def on_error(self, exc: BaseException) -> None:
raise AssertionError("hook failed")
with pytest.raises(RuntimeError, match="primary"):
AC().run()
def test_abstract_collector_run_on_error_runs_before_command_handle_error():
order = []
class BadCollector(AbstractCollector):
@property
def name(self) -> str:
return "bad"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
raise RuntimeError("boom")
def on_error(self, exc: BaseException) -> None:
order.append("on_error")
def handle_error(self, exc: BaseException) -> None:
order.append("handle_error")
class Cmd(BaseCollectorCommand):
help = "test"
def get_collector(self, **options):
return BadCollector()
with pytest.raises(RuntimeError, match="boom"):
Cmd(stdout=StringIO(), stderr=StringIO()).handle()
assert order == ["on_error", "handle_error"]
def test_base_collector_command_command_error_skips_handle_error_still_calls_on_error():
order = []
class BadCollector(AbstractCollector):
@property
def name(self) -> str:
return "bad"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
raise CommandError("planned", returncode=3)
def on_error(self, exc: BaseException) -> None:
order.append("on_error")
def handle_error(self, exc: BaseException) -> None:
order.append("handle_error")
class Cmd(BaseCollectorCommand):
help = "test"
def get_collector(self, **options):
return BadCollector()
with pytest.raises(CommandError, match="planned"):
Cmd(stdout=StringIO(), stderr=StringIO()).handle()
assert order == ["on_error"]
def test_abstract_collector_handle_error_uses_name_in_log_extra():
class Named(AbstractCollector):
@property
def name(self) -> str:
return "named_slug"
def validate_config(self) -> None:
pass
def collect(self) -> GenericTrackerResult:
return _OK
c = Named()
c._error_phase = "collect"
with patch.object(collector_lifecycle.logger, "exception") as mock_exc:
c.handle_error(RuntimeError("x"))
mock_exc.assert_called_once()
assert "named_slug" in str(mock_exc.call_args)
def test_abstract_collector_run_rejects_non_protocol_return():
class BadReturn(AbstractCollector):
@property
def name(self) -> str:
return "bad_return"
def validate_config(self) -> None:
return None
def collect(self):
return {"success": True, "counts": {}}
with pytest.raises(TypeError, match="TrackerResult"):
BadReturn().run()
def test_abstract_collector_run_sets_duration_and_last_result():
class Counting(AbstractCollector):
@property
def name(self) -> str:
return "counting"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
return GenericTrackerResult.ok(items=3)
collector = Counting()
result = collector.run()
assert result.counts["items"] == 3
assert result.duration_seconds is not None
assert collector.last_result is result
def test_base_collector_command_logs_tracker_result_fields():
class OkCollector(AbstractCollector):
@property
def name(self) -> str:
return "logged_collector"
def validate_config(self) -> None:
return None
def collect(self) -> GenericTrackerResult:
return GenericTrackerResult.ok(messages=2)
class Cmd(BaseCollectorCommand):
help = "test"
def get_collector(self, **options):
return OkCollector()
import core.collectors.command_base as cmd_mod
with patch.object(cmd_mod.logger, "info") as mock_info:
Cmd(stdout=StringIO(), stderr=StringIO()).handle()
finished = [
c
for c in mock_info.call_args_list
if c.args and "Collector finished" in str(c.args[0])
]
assert finished
assert finished[0].kwargs["extra"]["records_collected"] == 2