Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathtest_harness.py
More file actions
executable file
·3203 lines (2977 loc) · 133 KB
/
Copy pathtest_harness.py
File metadata and controls
executable file
·3203 lines (2977 loc) · 133 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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
pup integration test harness
Builds the release binary, injects DD_API_*/DD_APP_KEY credentials from dd-auth,
ensures a valid OAuth2 token (status → refresh → login), executes all read commands,
checks for output defects and visual regressions, then generates an HTML report.
Usage:
python3 scripts/test_harness.py [options]
Options:
--update-snapshots Accept current output as the new baseline
--no-build Skip cargo build (use existing binary)
--no-auth Skip auth checks and dd-auth credential injection
--dd-auth-domain DOMAIN dd-auth domain to use (default: app.datadoghq.com)
--output FILE Path for the HTML report (default: /tmp/pup-dev/harness_report.html)
--filter PATTERN Only run tests whose label contains PATTERN
--timeout SECS Per-command timeout in seconds (default: 30)
"""
import argparse
import difflib
import json
import os
import re
import signal
import subprocess
import sys
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
# ── paths ─────────────────────────────────────────────────────────────────────
REPO_ROOT = Path(__file__).parent.parent.resolve()
BINARY = REPO_ROOT / "target" / "release" / "pup"
SNAPSHOT_DIR = REPO_ROOT / "tests" / "snapshots"
LAST_OUTPUT_DIR = Path("/tmp/pup-dev")
DEFAULT_REPORT = LAST_OUTPUT_DIR / "harness_report.html"
# ── snapshot value normalization ──────────────────────────────────────────────
#
# Before computing the structural schema we normalize "stable-but-opaque" values
# so snapshots don't regress on rotating IDs, timestamps, or counts.
#
# Rules are applied in order; the first matching pattern wins for each string.
# Patterns that, when a dict's KEYS all match, collapse the whole dict to
# {"*": <value_schema>} so we don't snapshot individual service/metric/tag names.
DYNAMIC_KEY_PATTERNS: list[re.Pattern] = [
re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I), # UUID
re.compile(r"^[a-z0-9]([a-z0-9\-\.]*[a-z0-9])?:[^:]+$"), # tag (env:prod, host:web-01)
re.compile(r"^\d+$"), # pure numeric id
re.compile(r"^[a-z][a-z0-9_\-\.]+\.[a-z][a-z0-9_\-\.]+"), # dotted.metric.name
re.compile(r"^[a-z][a-z0-9_]*(-[a-z0-9_]+)+$"), # hyphenated service names (apm-service, account-config)
]
# Minimum number of keys before auto-detecting a "dynamic keys" dict.
DYNAMIC_KEY_MIN = 4
# Explicit path patterns (dot-joined key path, regex) that force "dynamic keys"
# treatment regardless of key content. Add entries here when you encounter a
# command whose top-level or nested dict uses caller-defined string keys.
FORCE_DYNAMIC_KEY_PATHS: list[re.Pattern] = [
re.compile(r".*\.tags$"),
re.compile(r".*\.meta$"),
re.compile(r".*\.attributes$"),
re.compile(r".*\.attributes\.\*$"), # inner log/event attribute dicts (CN, action, client_ip …)
re.compile(r".*\.metrics$"),
# Relationships dicts (on cases, incidents, etc.) have resource-specific optional
# keys (assignee, project, created_by, …) that vary per item. Collapse to {*: …}.
re.compile(r".*\.relationships$"),
re.compile(r".*\.usage$"),
# Infrastructure hosts: tags_by_source keys are cloud provider names ("Amazon Web
# Services", "Google Cloud Platform", …) that vary depending on which hosts
# the API returns on a given run — collapse to {"*": …} so snapshots are stable.
re.compile(r".*\.tags_by_source$"),
# Any path already two levels deep in dynamic-key territory (.*.*) will vary
# too much across API calls to snapshot reliably — collapse it.
re.compile(r".*\.\*\.\*.*"),
]
# String value normalization: replace with a stable placeholder.
# Applied to leaf string values before schema extraction so that rotating
# IDs/timestamps don't cause false positives.
VALUE_NORMALIZERS: list[tuple[re.Pattern, str]] = [
(re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I), "<uuid>"),
(re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}"), "<timestamp>"),
(re.compile(r"^\d{10,13}$"), "<unix_ts>"),
(re.compile(r"^https?://"), "<url>"),
(re.compile(r"^[0-9a-f]{32,64}$", re.I), "<hash>"),
]
# All possible normalized placeholder values. When both the baseline and
# the current value are placeholders, the actual content is just "some string"
# in both cases — no structural regression.
_NORMALIZED_PLACEHOLDERS = {"str", "<uuid>", "<timestamp>", "<unix_ts>", "<url>", "<hash>"}
# Schema paths that are known-optional: pup emits them only when non-default
# (e.g. truncated=false is skipped, next_action=None is skipped). Treat their
# absence in the current output as non-regressing.
_OPTIONAL_SCHEMA_PATHS: frozenset[str] = frozenset({
".metadata.next_action",
".metadata.truncated",
})
def _all_keys_dynamic(keys: list[str]) -> bool:
"""Return True when every key in a dict looks like a dynamic identifier."""
if len(keys) < DYNAMIC_KEY_MIN:
return False
return all(
any(p.fullmatch(k) for p in DYNAMIC_KEY_PATTERNS)
for k in keys
)
def _path_forces_dynamic(path: str) -> bool:
return any(p.fullmatch(path) for p in FORCE_DYNAMIC_KEY_PATHS)
def normalize_value(val: str) -> str:
for pattern, placeholder in VALUE_NORMALIZERS:
if pattern.search(val):
return placeholder
return val
def extract_json_schema(data: Any, max_depth: int = 6, path: str = "") -> Any:
"""
Recursively extract the structural schema of a JSON value.
- dict → {"key": child_schema, ...}
OR {"*": child_schema} when keys are detected as dynamic
- list → ["<list>", first_element_schema] or ["<empty_list>"]
- str → normalized placeholder or "str"
- other → type name string
"""
if max_depth == 0:
return "<...>"
if isinstance(data, dict):
keys = list(data.keys())
if not keys:
return {}
if _path_forces_dynamic(path) or _all_keys_dynamic(keys):
child_path = f"{path}.*"
# Short-circuit: if the child path would also be forced dynamic, don't
# recurse further — the values are too variable to snapshot reliably.
if _path_forces_dynamic(child_path):
return {"*": "<...>"}
# Merge ALL value schemas into a union so the result is stable across
# API calls that return different subsets of optional fields.
merged: Any = None
for v in data.values():
child = extract_json_schema(v, max_depth - 1, child_path)
if merged is None:
merged = child
elif isinstance(merged, dict) and isinstance(child, dict):
for k, cv in child.items():
if k not in merged:
merged[k] = cv
return {"*": merged if merged is not None else "<empty>"}
return {k: extract_json_schema(v, max_depth - 1, f"{path}.{k}") for k, v in sorted(data.items())}
if isinstance(data, list):
if not data:
return ["<empty_list>"]
# Merge schemas from ALL elements so the snapshot is a stable union of
# optional fields rather than an unstable sample of whichever element
# happens to appear first on this particular API call.
child_path = f"{path}[]"
merged = extract_json_schema(data[0], max_depth - 1, child_path)
for item in data[1:]:
child = extract_json_schema(item, max_depth - 1, child_path)
if isinstance(merged, dict) and isinstance(child, dict):
for k, cv in child.items():
if k not in merged:
merged[k] = cv
return ["<list>", merged]
if isinstance(data, str):
normalized = normalize_value(data)
if normalized != data:
return normalized
return "str"
if isinstance(data, bool):
return "bool"
return type(data).__name__
# ── snapshot / visual regression ──────────────────────────────────────────────
def snapshot_path(label: str, mode: str = "human") -> Path:
safe = re.sub(r"[^a-zA-Z0-9_-]", "_", label)
suffix = f"__{mode}" if mode else ""
return SNAPSHOT_DIR / f"{safe}{suffix}.json"
def _last_output_path(label: str, mode: str) -> Path:
"""Path for the raw stdout from the previous run — used for per-row diffs."""
safe = re.sub(r"[^a-zA-Z0-9_-]", "_", label)
return LAST_OUTPUT_DIR / f"{safe}__{mode}.last"
def load_last_output(label: str, mode: str) -> str | None:
p = _last_output_path(label, mode)
if p.exists():
try:
return p.read_text()
except Exception:
return None
return None
def save_last_output(label: str, mode: str, text: str) -> None:
LAST_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
_last_output_path(label, mode).write_text(text)
def load_snapshot(label: str, mode: str = "human") -> Any:
p = snapshot_path(label, mode)
if p.exists():
try:
return json.loads(p.read_text())
except Exception:
return None
return None
def save_snapshot(label: str, schema: Any, mode: str = "human") -> None:
SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
p = snapshot_path(label, mode)
p.write_text(json.dumps(schema, indent=2))
def diff_schemas(old: Any, new: Any, path: str = "") -> tuple[list[str], list[str]]:
"""
Compare two schemas. Returns (regressions, additions).
regressions — keys removed or types changed: these are real failures.
additions — keys present in new but absent from old: these are auto-merged
into the snapshot so future runs include them.
"""
regressions: list[str] = []
additions: list[str] = []
if type(old) != type(new):
regressions.append(f"{path or 'root'}: type changed {type(old).__name__} → {type(new).__name__}")
return regressions, additions
if isinstance(old, dict):
old_keys = set(old)
new_keys = set(new)
for k in sorted(old_keys - new_keys):
full_path = f"{path}.{k}"
if full_path in _OPTIONAL_SCHEMA_PATHS:
continue # known optional field — its absence is not a regression
regressions.append(f"{full_path}: key removed")
for k in sorted(new_keys - old_keys):
additions.append(f"{path}.{k}: key added")
for k in sorted(old_keys & new_keys):
r, a = diff_schemas(old[k], new[k], f"{path}.{k}")
regressions.extend(r)
additions.extend(a)
elif isinstance(old, list):
old_inner = old[1] if len(old) > 1 else None
new_inner = new[1] if len(new) > 1 else None
if old[0] != new[0]:
# Treat any transition between empty and populated list as additive.
# "<empty_list>" → "<list>": baseline had no data; API now returns items.
# "<list>" → "<empty_list>": baseline had items; this run happens to be
# empty (no outages, no results, etc.) — keep the richer baseline schema.
# Both directions are non-regressing: list emptiness is a runtime condition,
# not a structural change in the API or pup's output format.
empty_to_list = (old[0] == "<empty_list>" and new[0] == "<list>")
list_to_empty = (old[0] == "<list>" and new[0] == "<empty_list>")
if empty_to_list or list_to_empty:
additions.append(f"{path}: list emptiness changed '{old[0]}' → '{new[0]}'")
else:
regressions.append(f"{path}: list structure changed '{old[0]}' → '{new[0]}'")
elif old_inner is not None and new_inner is not None:
r, a = diff_schemas(old_inner, new_inner, f"{path}[]")
regressions.extend(r)
additions.extend(a)
elif old != new:
# If both values are normalized placeholders they represent the same
# thing ("some string") — the content merely changed category, which
# is not a structural regression worth failing on.
if old in _NORMALIZED_PLACEHOLDERS and new in _NORMALIZED_PLACEHOLDERS:
additions.append(f"{path or 'root'}: placeholder changed '{old}' → '{new}'")
else:
regressions.append(f"{path or 'root'}: value changed '{old}' → '{new}'")
return regressions, additions
def _truncate_schema(schema: Any, depth: int) -> Any:
"""
Collapse schema nodes below `depth` levels to "<...>".
Used by check_regression when a catalog entry sets max_regression_depth.
Both the stored baseline and the current schema are truncated identically
before diff_schemas runs, so volatility below the threshold never triggers
a regression while structural changes above it still do.
depth=1 checks that top-level keys exist and their immediate types match.
depth=2 checks one level of nesting beneath the root, etc.
"""
if depth <= 0:
return "<...>"
if isinstance(schema, dict):
return {k: _truncate_schema(v, depth - 1) for k, v in schema.items()}
if isinstance(schema, list):
if not schema:
return schema
result: list = [schema[0]]
if len(schema) > 1:
result.append(_truncate_schema(schema[1], depth - 1))
return result
return schema # scalar leaf — keep as-is
def _merge_schemas(base: Any, new: Any) -> Any:
"""Merge new schema into base, adding any keys present in new but absent from base."""
if isinstance(base, dict) and isinstance(new, dict):
merged = dict(base)
for k, v in new.items():
if k in merged:
merged[k] = _merge_schemas(merged[k], v)
else:
merged[k] = v
return merged
if isinstance(base, list) and isinstance(new, list):
# Upgrade ["<empty_list>"] → ["<list>", schema] when the API finally
# returns data for a list that was previously empty.
if base and base[0] == "<empty_list>" and new and new[0] == "<list>":
return new
# Merge list element schemas (keep the richer union)
if base and new and base[0] == new[0] == "<list>":
merged_inner = _merge_schemas(base[1], new[1]) if len(base) > 1 and len(new) > 1 else (base[1] if len(base) > 1 else new[1] if len(new) > 1 else None)
return ["<list>", merged_inner] if merged_inner is not None else base
return base # for scalars keep the base
def check_regression(
result: "TestResult",
update_snapshots: bool,
max_regression_depth: int = 0,
) -> tuple[str | None, bool]:
"""
Returns (regression_description | None, snapshot_was_created_or_updated).
Regression policy:
- Removed keys or type changes → FAIL (real regression)
- New keys in current output → auto-merge into snapshot (additive update, no failure)
This makes the baseline a stable "floor schema" that only grows over time.
max_regression_depth (0 = unlimited):
When set, both the stored baseline and the current schema are truncated to
this many levels before comparison. Nodes deeper than the limit become
"<...>" on both sides, so volatility in deeply-nested optional fields never
produces false-positive regressions. The snapshot itself is still saved at
full depth so future runs benefit from a richer baseline.
"""
if result.exit_code != 0 or not result.stdout.strip():
return None, False
try:
data = json.loads(result.stdout.strip())
except (json.JSONDecodeError, ValueError):
return None, False
current_schema = extract_json_schema(data)
existing = load_snapshot(result.label, result.mode)
if existing is None:
save_snapshot(result.label, current_schema, result.mode)
return None, True
if update_snapshots:
save_snapshot(result.label, current_schema, result.mode)
return None, False
# Apply depth truncation when requested. Both schemas are truncated
# identically so structural changes above the threshold still register.
if max_regression_depth > 0:
cmp_existing = _truncate_schema(existing, max_regression_depth)
cmp_current = _truncate_schema(current_schema, max_regression_depth)
else:
cmp_existing = existing
cmp_current = current_schema
regressions, additions = diff_schemas(cmp_existing, cmp_current)
# Auto-merge new keys into the snapshot so they're included in future baselines.
if additions:
merged = _merge_schemas(existing, current_schema)
save_snapshot(result.label, merged, result.mode)
if regressions:
return "\n".join(regressions), bool(additions)
return None, bool(additions)
# ── defect detection ──────────────────────────────────────────────────────────
# Match both Linux "thread '...' panicked at "
# and macOS "thread '...' (tid) panicked at "
PANIC_PATTERN = re.compile(r"panicked at ", re.IGNORECASE)
UNWRAP_PATTERN = re.compile(r"called `Option::unwrap\(\)` on a `None` value", re.IGNORECASE)
STACK_TRACE_PATTERN = re.compile(r"^\s+\d+:\s+0x[0-9a-f]", re.MULTILINE)
BACKTRACE_PATTERN = re.compile(r"stack backtrace:", re.IGNORECASE)
INTERNAL_ERROR_PATTERN = re.compile(r"internal error:|RUST_BACKTRACE", re.IGNORECASE)
AUTH_FAILURE_PATTERNS = [
re.compile(p, re.IGNORECASE) for p in [
r"401",
r"403",
r"authentication",
r"not authenticated",
r"no credentials",
r"run `pup auth login`",
r"invalid api key",
r"forbidden",
r"unauthorized",
r"DD_API_KEY",
r"DD_APP_KEY",
]
]
def is_auth_failure(text: str) -> bool:
return any(p.search(text) for p in AUTH_FAILURE_PATTERNS)
# HTTP 4xx semantics used to classify auth_fail results.
_HTTP_STATUS_REASONS: list[tuple[re.Pattern, str]] = [
(re.compile(r"\b400\b"), "400 Bad Request"),
(re.compile(r"\b401\b"), "401 Unauthorized"),
(re.compile(r"\b403\b"), "403 Forbidden"),
(re.compile(r"\b404\b"), "404 Not Found"),
(re.compile(r"\b429\b"), "429 Too Many Requests"),
(re.compile(r"\b5\d\d\b"), "5xx Server Error"),
]
def classify_auth_reason(stdout: str, stderr: str) -> str:
"""
Return a short human-readable reason for an auth/4xx failure.
Scans stderr first (where pup prints API error messages), then stdout,
and returns the first HTTP status match or a generic label.
"""
combined = stderr + "\n" + stdout
for pat, label in _HTTP_STATUS_REASONS:
if pat.search(combined):
return label
# Fallback: generic auth description from pup's error text
if re.search(r"no credentials|authentication required|set DD_API_KEY", combined, re.I):
return "no credentials configured"
if re.search(r"forbidden", combined, re.I):
return "403 Forbidden"
if re.search(r"unauthorized", combined, re.I):
return "401 Unauthorized"
return "auth error"
def check_defects(
result: "TestResult",
expect_json: bool,
expect_exit: int | None = None,
) -> list[str]:
defects = []
# Rust runtime signals (panics, backtraces, internal errors) go to stderr.
# Checking stdout for these patterns produces false positives when API
# responses contain phrases like "internal error:" in their payload text
# (e.g. events list describing a monitored system error).
stderr_only = result.stderr
combined = result.stdout + "\n" + result.stderr
if PANIC_PATTERN.search(stderr_only):
defects.append("PANIC detected in output")
if UNWRAP_PATTERN.search(stderr_only):
defects.append("unwrap() on None detected")
if BACKTRACE_PATTERN.search(stderr_only) and STACK_TRACE_PATTERN.search(combined):
defects.append("Rust stack trace in output")
if INTERNAL_ERROR_PATTERN.search(stderr_only):
defects.append("Internal error message in output")
if expect_exit is not None and result.exit_code != expect_exit:
defects.append(f"Unexpected exit code: got {result.exit_code}, expected {expect_exit}")
if expect_json and result.exit_code == 0 and result.stdout.strip():
try:
parsed = json.loads(result.stdout.strip())
if parsed is None:
defects.append("JSON output is null on success")
except json.JSONDecodeError as exc:
if not is_auth_failure(result.stdout) and not is_auth_failure(result.stderr):
defects.append(f"Invalid JSON output: {exc}")
if (expect_exit is None or expect_exit == 0) and \
result.exit_code == 0 and \
not result.stdout.strip() and not result.stderr.strip():
defects.append("Empty output on successful exit")
return defects
# ── result dataclass ──────────────────────────────────────────────────────────
@dataclass
class TestResult:
label: str
args: list[str]
category: str
exit_code: int
stdout: str
stderr: str
duration_ms: float
expect_exit: int | None = None
note: str = ""
defects: list[str] = field(default_factory=list)
regression: str | None = None
snapshot_created: bool = False
skipped: bool = False
skip_reason: str = ""
# Override computed status (used for synthetic untested/write rows)
status_override: str | None = None
# "human" | "agent" | "" (synthetic rows that were not run)
mode: str = "human"
# HTTP status classification when auth_fail (e.g. "401 Unauthorized")
auth_reason: str = ""
# Per-row diff: current stdout vs previous run's stdout (same mode)
row_diff: tuple[str, str] = field(default_factory=lambda: ("", ""))
@property
def test_id(self) -> str:
"""Stable slug derived from the label and mode, usable as an HTML anchor."""
base = re.sub(r"[^a-z0-9]+", "-", self.label.lower()).strip("-")
return f"{base}-{self.mode}" if self.mode else base
@property
def status(self) -> str:
if self.status_override:
return self.status_override
if self.skipped:
return "skipped"
if self.defects or self.regression:
return "fail"
if self.expect_exit is not None:
return "pass" if self.exit_code == self.expect_exit else "fail"
if self.exit_code != 0:
return "auth_fail"
return "pass"
# ── test catalog ──────────────────────────────────────────────────────────────
READ_COMMANDS: list[dict] = [
# ── no-auth commands ──────────────────────────────────────────────────
{
"label": "version",
"args": ["version"],
"category": "no_auth",
"expect_json": False,
},
{
"label": "test",
"args": ["test"],
"category": "no_auth",
"expect_json": False,
"note": "Diagnostic command: shows configured site, API host, key presence, and output format.",
},
{
"label": "agent schema",
"args": ["agent", "schema"],
"category": "no_auth",
"expect_json": True,
},
{
"label": "agent schema --compact",
"args": ["agent", "schema", "--compact"],
"category": "no_auth",
"expect_json": True,
},
{
"label": "agent guide",
"args": ["agent", "guide"],
"category": "no_auth",
"expect_json": False,
},
{
"label": "misc ip-ranges",
"args": ["misc", "ip-ranges"],
"category": "no_auth",
"expect_json": True,
},
{
"label": "misc status",
"args": ["misc", "status"],
"category": "no_auth",
"expect_json": True,
},
{
"label": "completions bash",
"args": ["completions", "bash"],
"category": "no_auth",
"expect_json": False,
"note": "BUG (debug build only): panics with clap debug_assert — "
"'type_id' referenced in conflicts_with* does not exist. "
"Release builds suppress debug_asserts and generate completions normally.",
},
{
"label": "completions zsh",
"args": ["completions", "zsh"],
"category": "no_auth",
"expect_json": False,
"note": "BUG (debug build only): same clap debug_assert panic as 'completions bash'.",
},
# ── --help smoke tests ────────────────────────────────────────────────
{
"label": "help (root)",
"args": ["--help"],
"category": "no_auth",
"expect_json": False,
"expect_exit": 0,
},
{
"label": "monitors --help",
"args": ["monitors", "--help"],
"category": "no_auth",
"expect_json": False,
"expect_exit": 0,
},
{
"label": "logs --help",
"args": ["logs", "--help"],
"category": "no_auth",
"expect_json": False,
"expect_exit": 0,
},
# ── auth status ───────────────────────────────────────────────────────
{
"label": "auth status",
"args": ["auth", "status"],
"category": "auth_status",
"expect_json": False,
},
# ── api-keys ──────────────────────────────────────────────────────────
{
"label": "api-keys list",
"args": ["api-keys", "list"],
"category": "auth_required",
"expect_json": True,
},
# ── app-keys ──────────────────────────────────────────────────────────
{
"label": "app-keys list",
"args": ["app-keys", "list"],
"category": "auth_required",
"expect_json": True,
},
# ── apm ───────────────────────────────────────────────────────────────
{
"label": "apm services list",
"args": ["apm", "services", "list", "--env=prod", "--from=1h"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "apm services stats",
"args": ["apm", "services", "stats", "--env=prod", "--from=1h"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "apm entities list",
"args": ["apm", "entities", "list", "--env=prod", "--from=1h"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "apm dependencies list",
"args": ["apm", "dependencies", "list", "--env=prod", "--from=1h"],
"category": "auth_required",
"expect_json": True,
"skip_regression": True,
# The service dependency map has 6000+ service names as top-level dict keys.
# They are a mix of hyphenated, underscore_separated, dotted, and single-word
# names — DYNAMIC_KEY_PATTERNS cannot collapse them all because _all_keys_dynamic
# requires EVERY key to match at least one pattern, and single-word names like
# "abacus" don't match any. Service names appear/disappear between API calls,
# making the snapshot inherently volatile. skip_regression is required.
},
{
"label": "apm flow-map",
"args": ["apm", "flow-map", "--env=prod", "--query=*", "--from=1h"],
"category": "auth_required",
"expect_json": True,
"note": "pup bug: --from is not propagated into the API query body; API returns 400 'missing parameter from in query'.",
},
# ── audit-logs ────────────────────────────────────────────────────────
{
"label": "audit-logs list",
"args": ["audit-logs", "list", "--from=1h"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "audit-logs search",
"args": ["audit-logs", "search", "--from=1h", "--query=*"],
"category": "auth_required",
"expect_json": True,
},
# ── cases ─────────────────────────────────────────────────────────────
{
"label": "cases projects list",
"args": ["cases", "projects", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "cases search",
"args": ["cases", "search", "--query=*"],
"category": "auth_required",
"expect_json": True,
},
# ── cicd ──────────────────────────────────────────────────────────────
{
"label": "cicd pipelines list",
"args": ["cicd", "pipelines", "list", "--from=1h"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "cicd events search",
"args": ["cicd", "events", "search", "--from=1h", "--query=*"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "cicd tests list",
"args": ["cicd", "tests", "list", "--from=1h"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "cicd tests search",
"args": ["cicd", "tests", "search", "--from=1h", "--query=*"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "cicd flaky-tests search",
"args": ["cicd", "flaky-tests", "search", "--query=*"],
"category": "auth_required",
"expect_json": True,
},
# ── cloud ─────────────────────────────────────────────────────────────
{
"label": "cloud aws list",
"args": ["cloud", "aws", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "cloud azure list",
"args": ["cloud", "azure", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "cloud gcp list",
"args": ["cloud", "gcp", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "cloud oci tenancies list",
"args": ["cloud", "oci", "tenancies", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "cloud oci products list",
"args": ["cloud", "oci", "products", "list"],
"category": "auth_required",
"expect_json": True,
},
# ── dashboards ────────────────────────────────────────────────────────
{
"label": "dashboards list",
"args": ["dashboards", "list"],
"category": "auth_required",
"expect_json": True,
},
# ── data-governance ───────────────────────────────────────────────────
{
"label": "data-governance scanner rules list",
"args": ["data-governance", "scanner", "rules"],
"category": "auth_required",
"expect_json": True,
},
# ── downtime ──────────────────────────────────────────────────────────
{
"label": "downtime list",
"args": ["downtime", "list"],
"category": "auth_required",
"expect_json": True,
},
# ── error-tracking ────────────────────────────────────────────────────
{
"label": "error-tracking issues search",
"args": ["error-tracking", "issues", "search", "--from=1h", "--query=*"],
"category": "auth_required",
"expect_json": True,
},
# ── events ────────────────────────────────────────────────────────────
{
"label": "events list",
"args": ["events", "list", "--from=1h"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "events search",
"args": ["events", "search", "--from=1h", "--query=*"],
"category": "auth_required",
"expect_json": True,
},
# ── fleet ─────────────────────────────────────────────────────────────
{
"label": "fleet agents list",
"args": ["fleet", "agents", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "fleet agents versions",
"args": ["fleet", "agents", "versions"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "fleet deployments list",
"args": ["fleet", "deployments", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "fleet schedules list",
"args": ["fleet", "schedules", "list"],
"category": "auth_required",
"expect_json": True,
},
# ── incidents ─────────────────────────────────────────────────────────
{
"label": "incidents list",
"args": ["incidents", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "incidents handles list",
"args": ["incidents", "handles", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "incidents postmortem-templates list",
"args": ["incidents", "postmortem-templates", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "incidents settings get",
"args": ["incidents", "settings", "get"],
"category": "auth_required",
"expect_json": True,
"note": "pup bug: serde deserialization error — missing field `analytics_dashboard_id` in API response model.",
},
# ── infrastructure ────────────────────────────────────────────────────
{
"label": "infrastructure hosts list",
"args": ["infrastructure", "hosts", "list"],
"category": "auth_required",
"expect_json": True,
"max_regression_depth": 2,
"note": "Per-host fields like aws_id/aws_name are optional (only on AWS hosts) and vary per run; depth-2 checks root envelope and that host_list is a populated list without inspecting per-host fields.",
},
# ── integrations ──────────────────────────────────────────────────────
{
"label": "integrations jira accounts",
"args": ["integrations", "jira", "accounts"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "integrations jira accounts list",
"args": ["integrations", "jira", "accounts", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "integrations jira templates list",
"args": ["integrations", "jira", "templates", "list"],
"category": "auth_required",
"expect_json": True,
"note": "pup bug: serde deserialization error — missing field `attributes` in Jira template response model.",
},
{
"label": "integrations pagerduty list",
"args": ["integrations", "pagerduty", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "integrations servicenow assignment-groups list",
"args": ["integrations", "servicenow", "assignment-groups", "list"],
"category": "auth_required",
"expect_json": True,
"note": "pup bug: validates INSTANCE_NAME positional arg as UUID; real instance names like 'dev186409' are rejected.",
},
{
"label": "integrations servicenow business-services list",
"args": ["integrations", "servicenow", "business-services", "list"],
"category": "auth_required",
"expect_json": True,
"note": "pup bug: same UUID validation bug as assignment-groups list.",
},
{
"label": "integrations servicenow instances list",
"args": ["integrations", "servicenow", "instances", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "integrations servicenow templates list",
"args": ["integrations", "servicenow", "templates", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "integrations servicenow users list",
"args": ["integrations", "servicenow", "users", "list"],
"category": "auth_required",
"expect_json": True,
"note": "pup bug: same UUID validation bug as assignment-groups list.",
},
{
"label": "integrations slack list",
"args": ["integrations", "slack", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "integrations webhooks list",
"args": ["integrations", "webhooks", "list"],
"category": "auth_required",
"expect_json": True,
},
# ── hamr ──────────────────────────────────────────────────────────────
{
"label": "hamr connections get",
"args": ["hamr", "connections", "get"],
"category": "auth_required",
"expect_json": True,
"note": "pup bug: serde error 'invalid type: null, expected a mapping' — HAMR API may return null for connection config.",
},
# ── investigations ────────────────────────────────────────────────────
{
"label": "investigations list",
"args": ["investigations", "list"],
"category": "auth_required",
"expect_json": True,
},
# ── logs ──────────────────────────────────────────────────────────────
{
"label": "logs archives list",
"args": ["logs", "archives", "list"],
"category": "auth_required",
"expect_json": True,
},
{
"label": "logs custom-destinations list",
You can’t perform that action at this time.
