Skip to content

Commit 98cfc58

Browse files
committed
refactor(parametric): simplify telemetry readiness
1 parent 0b90762 commit 98cfc58

3 files changed

Lines changed: 98 additions & 181 deletions

File tree

‎tests/parametric/conftest.py‎

Lines changed: 14 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
import base64
2-
from collections.abc import Generator, Mapping
2+
from collections.abc import Generator
33
import json
44
from pathlib import Path
55
import shutil
66
import subprocess
7-
from typing import Any
87
import uuid
98

109
import pytest
@@ -189,42 +188,31 @@ def nodejs_telemetry_value(test_agent: TestAgentAPI, dd_key: str) -> str | int |
189188
return entries[0].get("value")
190189

191190

192-
def _nodejs_telemetry_config_matches(
193-
configurations: dict[str, list[dict[str, Any]]], expected: Mapping[str, object]
194-
) -> bool:
191+
def assert_nodejs_telemetry_config(test_agent: TestAgentAPI, expected: dict, *, runtime_id: str | None = None) -> None:
192+
"""Assert expected dd_* config values against the nodejs telemetry configuration."""
193+
if runtime_id is None:
194+
runtime_id = test_agent.wait_for_telemetry_runtime_id()
195+
configurations = test_agent.wait_for_telemetry_configurations(runtime_id=runtime_id)
195196
for dd_key, expected_value in expected.items():
196-
entries = configurations.get(_telemetry_name(dd_key))
197-
if not entries:
198-
return False
197+
name = _telemetry_name(dd_key)
198+
entries = configurations.get(name)
199+
assert entries, f"No telemetry configuration '{name}' for runtime '{runtime_id}'"
199200
actual = entries[0].get("value")
200201
if dd_key == "dd_tags":
201202
actual_tags = "" if actual is None else str(actual)
202203
expected_tags = expected_value if isinstance(expected_value, list) else str(expected_value).split(",")
203-
if any(tag not in actual_tags for tag in expected_tags):
204-
return False
205-
elif str(actual).lower() != str(expected_value).lower():
206-
return False
207-
return True
208-
209-
210-
def assert_nodejs_telemetry_config(
211-
test_agent: TestAgentAPI, expected: Mapping[str, object], *, runtime_id: str | None = None
212-
) -> None:
213-
"""Assert expected dd_* config values against the nodejs telemetry configuration."""
214-
if runtime_id is None:
215-
runtime_id = test_agent.wait_for_telemetry_runtime_id()
216-
test_agent.wait_for_telemetry_configurations(
217-
runtime_id=runtime_id,
218-
validator=lambda configurations: _nodejs_telemetry_config_matches(configurations, expected),
219-
)
204+
for tag in expected_tags:
205+
assert tag in actual_tags, f"Expected tag '{tag}' not found in telemetry tags: {actual_tags}"
206+
else:
207+
assert str(actual).lower() == str(expected_value).lower(), f"Expected {name}={expected_value}, got {actual}"
220208

221209

222210
def restart_and_get_runtime_id(test_agent: TestAgentAPI, test_library: APMLibrary) -> str | None:
223211
previous_runtime_id = test_agent.wait_for_telemetry_runtime_id() if test_library.lang == "nodejs" else None
224212
test_library.container_restart()
225213
if previous_runtime_id is None:
226214
return None
227-
return test_agent.wait_for_telemetry_runtime_id(exclude={previous_runtime_id})
215+
return test_agent.wait_for_telemetry_runtime_id(exclude=previous_runtime_id)
228216

229217

230218
def nodejs_startup_config(test_library: APMLibrary) -> dict:
Lines changed: 49 additions & 111 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from collections.abc import Callable
2-
31
import pytest
42

53
from tests.parametric.conftest import assert_nodejs_telemetry_config
@@ -14,27 +12,24 @@ def _configuration_event(
1412
"request_type": "app-started",
1513
"runtime_id": runtime_id,
1614
"tracer_time": tracer_time,
17-
"application": {
18-
"language_name": "nodejs",
19-
"language_version": "24.4.1",
20-
"service_name": "parametric",
21-
"tracer_version": "5.62.0",
22-
},
2315
"payload": {"configuration": configurations},
24-
"seq_id": 1,
2516
}
2617

2718

2819
def _config(name: str, value: str, *, seq_id: int = 0) -> dict[str, object]:
29-
return {"name": name, "origin": "local_stable_config", "seq_id": seq_id, "value": value}
20+
return {"name": name, "seq_id": seq_id, "value": value}
21+
3022

23+
def _test_agent(monkeypatch: pytest.MonkeyPatch, responses: list[list[dict[str, object]]]) -> TestAgentAPI:
24+
test_agent = object.__new__(TestAgentAPI)
3125

32-
def _telemetry(events: list[dict[str, object]]) -> Callable[..., list[dict[str, object]]]:
33-
def get_events(*, clear: bool = False) -> list[dict[str, object]]:
26+
def telemetry(*, clear: bool = False) -> list[dict[str, object]]:
3427
assert clear is False
35-
return events
28+
return responses.pop(0) if len(responses) > 1 else responses[0]
3629

37-
return get_events
30+
monkeypatch.setattr(test_agent, "telemetry", telemetry)
31+
monkeypatch.setattr("utils.docker_fixtures._test_agent.time.sleep", lambda _seconds: None)
32+
return test_agent
3833

3934

4035
@scenarios.test_the_test
@@ -49,114 +44,57 @@ def test_nodejs_telemetry_assertion_waits_for_post_restart_runtime(monkeypatch:
4944
tracer_time=2,
5045
configurations=[_config("DD_TRACE_PROPAGATION_STYLE", "tracecontext")],
5146
)
52-
telemetry_responses = [[stale_event], [stale_event, current_event]]
53-
54-
test_agent = object.__new__(TestAgentAPI)
55-
56-
def telemetry(*, clear: bool = False) -> list[dict[str, object]]:
57-
assert clear is False
58-
if len(telemetry_responses) > 1:
59-
return telemetry_responses.pop(0)
60-
return telemetry_responses[0]
61-
62-
monkeypatch.setattr(test_agent, "telemetry", telemetry)
47+
test_agent = _test_agent(monkeypatch, [[stale_event], [stale_event, current_event]])
48+
runtime_id = test_agent.wait_for_telemetry_runtime_id(exclude="before-restart")
6349

6450
assert_nodejs_telemetry_config(
6551
test_agent,
6652
{"dd_trace_propagation_style": "tracecontext"},
67-
runtime_id="after-restart",
53+
runtime_id=runtime_id,
6854
)
6955

7056

7157
@scenarios.test_the_test
72-
def test_nodejs_telemetry_assertion_rejects_stale_matching_value(monkeypatch: pytest.MonkeyPatch) -> None:
73-
events = [
74-
_configuration_event(
75-
runtime_id="before-restart",
76-
tracer_time=1,
77-
configurations=[_config("DD_TRACE_PROPAGATION_STYLE", "tracecontext")],
58+
@pytest.mark.parametrize(
59+
("events", "expected"),
60+
[
61+
(
62+
[
63+
_configuration_event(
64+
runtime_id="before-restart",
65+
tracer_time=1,
66+
configurations=[_config("DD_TRACE_PROPAGATION_STYLE", "tracecontext")],
67+
),
68+
_configuration_event(
69+
runtime_id="after-restart",
70+
tracer_time=2,
71+
configurations=[_config("DD_TRACE_PROPAGATION_STYLE", "datadog")],
72+
),
73+
],
74+
{"dd_trace_propagation_style": "tracecontext"},
7875
),
79-
_configuration_event(
80-
runtime_id="after-restart",
81-
tracer_time=2,
82-
configurations=[_config("DD_TRACE_PROPAGATION_STYLE", "datadog")],
76+
(
77+
[
78+
_configuration_event(
79+
runtime_id="after-restart",
80+
tracer_time=2,
81+
configurations=[
82+
_config("DD_SERVICE", "expected", seq_id=0),
83+
_config("DD_SERVICE", "wrong", seq_id=1),
84+
],
85+
)
86+
],
87+
{"dd_service": "expected"},
8388
),
84-
]
85-
test_agent = object.__new__(TestAgentAPI)
86-
monkeypatch.setattr(test_agent, "telemetry", _telemetry(events))
87-
monkeypatch.setattr("utils.docker_fixtures._test_agent.time.sleep", lambda _seconds: None)
88-
89-
with pytest.raises(AssertionError):
90-
assert_nodejs_telemetry_config(
91-
test_agent,
92-
{"dd_trace_propagation_style": "tracecontext"},
93-
runtime_id="after-restart",
94-
)
95-
96-
97-
@scenarios.test_the_test
98-
def test_nodejs_telemetry_assertion_requires_one_runtime_to_match_all_values(
89+
],
90+
ids=["stale-match", "superseded-sequence"],
91+
)
92+
def test_nodejs_telemetry_assertion_rejects_invalid_runtime_snapshot(
9993
monkeypatch: pytest.MonkeyPatch,
94+
events: list[dict[str, object]],
95+
expected: dict[str, object],
10096
) -> None:
101-
events = [
102-
_configuration_event(
103-
runtime_id="before-restart",
104-
tracer_time=1,
105-
configurations=[_config("DD_SERVICE", "expected"), _config("DD_ENV", "wrong")],
106-
),
107-
_configuration_event(
108-
runtime_id="after-restart",
109-
tracer_time=2,
110-
configurations=[_config("DD_SERVICE", "wrong"), _config("DD_ENV", "expected")],
111-
),
112-
]
113-
test_agent = object.__new__(TestAgentAPI)
114-
monkeypatch.setattr(test_agent, "telemetry", _telemetry(events))
115-
monkeypatch.setattr("utils.docker_fixtures._test_agent.time.sleep", lambda _seconds: None)
116-
117-
with pytest.raises(AssertionError):
118-
assert_nodejs_telemetry_config(
119-
test_agent,
120-
{"dd_service": "expected", "dd_env": "expected"},
121-
runtime_id="after-restart",
122-
)
123-
124-
125-
@scenarios.test_the_test
126-
def test_nodejs_telemetry_assertion_uses_latest_configuration_sequence(monkeypatch: pytest.MonkeyPatch) -> None:
127-
events = [
128-
_configuration_event(
129-
runtime_id="after-restart",
130-
tracer_time=2,
131-
configurations=[
132-
_config("DD_SERVICE", "expected", seq_id=0),
133-
_config("DD_SERVICE", "wrong", seq_id=1),
134-
],
135-
)
136-
]
137-
test_agent = object.__new__(TestAgentAPI)
138-
monkeypatch.setattr(test_agent, "telemetry", _telemetry(events))
139-
monkeypatch.setattr("utils.docker_fixtures._test_agent.time.sleep", lambda _seconds: None)
97+
test_agent = _test_agent(monkeypatch, [events])
14098

14199
with pytest.raises(AssertionError):
142-
assert_nodejs_telemetry_config(test_agent, {"dd_service": "expected"}, runtime_id="after-restart")
143-
144-
145-
@scenarios.test_the_test
146-
def test_wait_for_telemetry_runtime_id_ignores_excluded_runtime(monkeypatch: pytest.MonkeyPatch) -> None:
147-
stale_event = _configuration_event(runtime_id="before-restart", tracer_time=1, configurations=[])
148-
current_event = _configuration_event(runtime_id="after-restart", tracer_time=2, configurations=[])
149-
telemetry_responses = [[stale_event], [stale_event, current_event]]
150-
test_agent = object.__new__(TestAgentAPI)
151-
152-
def telemetry(*, clear: bool = False) -> list[dict[str, object]]:
153-
assert clear is False
154-
if len(telemetry_responses) > 1:
155-
return telemetry_responses.pop(0)
156-
return telemetry_responses[0]
157-
158-
monkeypatch.setattr(test_agent, "telemetry", telemetry)
159-
160-
runtime_id = test_agent.wait_for_telemetry_runtime_id(exclude={"before-restart"})
161-
162-
assert runtime_id == "after-restart"
100+
assert_nodejs_telemetry_config(test_agent, expected, runtime_id="after-restart")

‎utils/docker_fixtures/_test_agent.py‎

Lines changed: 35 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import base64
2-
from collections.abc import Callable, Generator
2+
from collections.abc import Generator
33
import contextlib
44
import datetime
55
import gzip
@@ -709,14 +709,12 @@ def wait_for_telemetry_configurations(
709709
*,
710710
service: str | None = None,
711711
runtime_id: str | None = None,
712-
validator: Callable[[dict[str, list[dict[str, Any]]]], bool] | None = None,
713712
clear: bool = False,
714713
wait_loops: int = 100,
715714
) -> dict[str, list[dict[str, Any]]]:
716715
"""Waits for and returns configurations captured in telemetry events.
717716
718717
Telemetry events can be found in `app-started` or `app-client-configuration-change` events.
719-
When provided, runtime_id filters events and validator defines the readiness condition.
720718
Returns a dictionary where keys are configuration names and values are lists of
721719
configuration dictionaries, allowing for multiple entries per configuration name
722720
with different origins.
@@ -727,54 +725,47 @@ def wait_for_telemetry_configurations(
727725
with contextlib.suppress(requests.exceptions.RequestException):
728726
events = self.telemetry(clear=False)
729727
if events:
730-
configurations = {}
731-
events.sort(key=lambda event: event["tracer_time"])
732-
for event in events:
733-
if runtime_id is not None and event.get("runtime_id") != runtime_id:
734-
continue
735-
if service is not None and event["application"]["service_name"] != service:
736-
continue
737-
for event_type in ["app-started", "app-client-configuration-change"]:
738-
telemetry_event = self._get_telemetry_event(event, event_type)
739-
if telemetry_event:
740-
for config in telemetry_event.get("payload", {}).get("configuration", []):
741-
configurations.setdefault(config["name"], []).append(config)
742-
for payload in configurations.values():
743-
payload.sort(key=lambda item: item.get("seq_id") or 0, reverse=True)
744-
if validator is None or validator(configurations):
745-
if clear:
746-
self.clear()
747-
return configurations
728+
break
748729
time.sleep(0.05)
749-
750-
if not events:
730+
else:
751731
raise AssertionError("No telemetry events were found. Ensure the application is sending telemetry events.")
752-
raise AssertionError(f"No telemetry configurations matched the validator. Last observed: {configurations}")
753732

754-
def wait_for_telemetry_runtime_id(self, *, exclude: set[str] | None = None, wait_loops: int = 200) -> str:
755-
excluded_runtime_ids = exclude or set()
733+
events.sort(key=lambda event: event["tracer_time"])
734+
for event in events:
735+
if runtime_id is not None and event.get("runtime_id") != runtime_id:
736+
continue
737+
if service is not None and event["application"]["service_name"] != service:
738+
continue
739+
for event_type in ["app-started", "app-client-configuration-change"]:
740+
telemetry_event = self._get_telemetry_event(event, event_type)
741+
if telemetry_event:
742+
for config in telemetry_event.get("payload", {}).get("configuration", []):
743+
configurations.setdefault(config["name"], []).append(config)
744+
for payload in configurations.values():
745+
payload.sort(key=lambda item: item.get("seq_id") or 0, reverse=True)
746+
if clear:
747+
self.clear()
748+
return configurations
749+
750+
def wait_for_telemetry_runtime_id(self, *, exclude: str | None = None, wait_loops: int = 200) -> str:
756751
observed_runtime_ids: set[str] = set()
757752
for _ in range(wait_loops):
758-
try:
753+
events: list[dict[str, Any]] = []
754+
with contextlib.suppress(requests.exceptions.RequestException):
759755
events = self.telemetry(clear=False)
760-
except requests.exceptions.RequestException:
761-
events = []
762-
else:
763-
events.sort(key=lambda event: event["tracer_time"], reverse=True)
764-
for event in events:
765-
telemetry_event = self._get_telemetry_event(event, "app-started")
766-
if telemetry_event is None:
767-
continue
768-
runtime_id = telemetry_event.get("runtime_id") or event.get("runtime_id")
769-
if runtime_id is None:
770-
continue
771-
observed_runtime_ids.add(runtime_id)
772-
if runtime_id not in excluded_runtime_ids:
773-
return runtime_id
756+
events.sort(key=lambda event: event["tracer_time"], reverse=True)
757+
for event in events:
758+
telemetry_event = self._get_telemetry_event(event, "app-started")
759+
if telemetry_event is None:
760+
continue
761+
runtime_id = telemetry_event.get("runtime_id") or event.get("runtime_id")
762+
if runtime_id is None:
763+
continue
764+
observed_runtime_ids.add(runtime_id)
765+
if runtime_id != exclude:
766+
return runtime_id
774767
time.sleep(0.01)
775-
raise AssertionError(
776-
f"No telemetry runtime ID found excluding {excluded_runtime_ids}. Observed: {observed_runtime_ids}"
777-
)
768+
raise AssertionError(f"No telemetry runtime ID found excluding {exclude}. Observed: {observed_runtime_ids}")
778769

779770
def get_telemetry_config_by_origin(
780771
self,

0 commit comments

Comments
 (0)