Skip to content

Commit 506fe19

Browse files
committed
🧪 Modify emission metrics test
Uses raw metrics names request to determine when emission metrics have sent to the server
1 parent aab9e24 commit 506fe19

File tree

5 files changed

+27
-13
lines changed

5 files changed

+27
-13
lines changed

‎pyproject.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,6 @@ testpaths = [
9797
markers = [
9898
"eco: tests for emission metrics",
9999
"client: tests of Simvue client",
100-
"converters: tests for Simvue object converters",
101100
"dispatch: test data dispatcher",
102101
"run: test the simvue Run class",
103102
"utilities: test simvue utilities module",

‎simvue/api/objects/base.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -477,7 +477,7 @@ def read_only(self, is_read_only: bool) -> None:
477477
if not self._read_only:
478478
self._staging = self._get_local_staged()
479479

480-
def commit(self) -> None:
480+
def commit(self) -> dict | None:
481481
"""Send updates to the server, or if offline, store locally."""
482482
if self._read_only:
483483
raise AttributeError("Cannot commit object in 'read-only' mode")
@@ -489,22 +489,26 @@ def commit(self) -> None:
489489
self._cache()
490490
return
491491

492+
_response: dict | None = None
493+
492494
# Initial commit is creation of object
493495
# if staging is empty then we do not need to use PUT
494496
if not self._identifier or self._identifier.startswith("offline_"):
495497
self._logger.debug(
496498
f"Posting from staged data for {self._label} '{self.id}': {self._staging}"
497499
)
498-
self._post(**self._staging)
500+
_response = self._post(**self._staging)
499501
elif self._staging:
500502
self._logger.debug(
501503
f"Pushing updates from staged data for {self._label} '{self.id}': {self._staging}"
502504
)
503-
self._put(**self._staging)
505+
_response = self._put(**self._staging)
504506

505507
# Clear staged changes
506508
self._clear_staging()
507509

510+
return _response
511+
508512
@property
509513
def id(self) -> str | None:
510514
"""The identifier for this object if applicable.

‎simvue/run.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -478,14 +478,14 @@ def _dispatch_callback(
478478
offline=self._user_config.run.mode == "offline",
479479
events=buffer,
480480
)
481-
_events.commit()
481+
return _events.commit()
482482
else:
483483
_metrics = Metrics.new(
484484
run=self.id,
485485
offline=self._user_config.run.mode == "offline",
486486
metrics=buffer,
487487
)
488-
_metrics.commit()
488+
return _metrics.commit()
489489

490490
return _dispatch_callback
491491

‎tests/conftest.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def clear_out_files() -> None:
5353
for file_obj in out_files:
5454
file_obj.unlink()
5555

56-
56+
5757
@pytest.fixture()
5858
def offline_cache_setup(monkeypatch: monkeypatch.MonkeyPatch):
5959
# Will be executed before test
@@ -63,7 +63,8 @@ def offline_cache_setup(monkeypatch: monkeypatch.MonkeyPatch):
6363
# Will be executed after test
6464
cache_dir.cleanup()
6565
monkeypatch.setenv("SIMVUE_OFFLINE_DIRECTORY", None)
66-
66+
67+
6768
@pytest.fixture
6869
def mock_co2_signal(monkeypatch: monkeypatch.MonkeyPatch) -> dict[str, dict | str]:
6970
_mock_data = {
@@ -100,7 +101,7 @@ def _mock_location_info(self) -> None:
100101

101102
monkeypatch.setattr(requests, "get", _mock_get)
102103
monkeypatch.setattr(sv_eco.APIClient, "_get_user_location_info", _mock_location_info)
103-
104+
104105
_fetch = sv_cfg.SimvueConfiguration.fetch
105106
@classmethod
106107
def _mock_fetch(cls, *args, **kwargs) -> sv_cfg.SimvueConfiguration:

‎tests/functional/test_run_class.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import logging
33
import os
44
import pytest
5+
import requests
56
import pytest_mock
67
import time
78
import typing
@@ -53,11 +54,20 @@ def test_check_run_initialised_decorator() -> None:
5354
@pytest.mark.run
5455
@pytest.mark.eco
5556
@pytest.mark.online
56-
def test_run_with_emissions_online(speedy_heartbeat, mock_co2_signal, create_plain_run) -> None:
57+
def test_run_with_emissions_online(speedy_heartbeat, mock_co2_signal, create_plain_run: tuple[sv_run.Run, ...], mocker) -> None:
5758
run_created, _ = create_plain_run
59+
metric_interval = 1
5860
run_created._user_config.eco.co2_signal_api_token = "test_token"
59-
run_created.config(enable_emission_metrics=True, system_metrics_interval=1)
60-
time.sleep(5)
61+
run_created.config(enable_emission_metrics=True, system_metrics_interval=metric_interval)
62+
spy = mocker.spy(run_created, "_get_internal_metrics")
63+
while (
64+
"sustainability.emissions.total" not in requests.get(
65+
url=f"{run_created._user_config.server.url}/metrics/names",
66+
headers=run_created._headers,
67+
params={"runs": json.dumps([run_created.id])}).json()
68+
and spy.call_count < 4
69+
):
70+
time.sleep(metric_interval)
6171
_run = RunObject(identifier=run_created.id)
6272
_metric_names = [item[0] for item in _run.metrics]
6373
client = sv_cl.Client()
@@ -75,7 +85,7 @@ def test_run_with_emissions_online(speedy_heartbeat, mock_co2_signal, create_pla
7585
# Check that total = previous total + latest delta
7686
_total_values = _metric_values[_total_metric_name].tolist()
7787
_delta_values = _metric_values[_delta_metric_name].tolist()
78-
assert len(_total_values) > 1
88+
assert len(_total_values) == spy.call_count
7989
for i in range(1, len(_total_values)):
8090
assert _total_values[i] == _total_values[i - 1] + _delta_values[i]
8191

0 commit comments

Comments
 (0)