Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
164 changes: 164 additions & 0 deletions feature_integration_tests/test_cases/tests/time/test_clock_now.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
# *******************************************************************************
# Copyright (c) 2026 Contributors to the Eclipse Foundation
#
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# This program and the accompanying materials are made available under the
# terms of the Apache License Version 2.0 which is available at
# https://www.apache.org/licenses/LICENSE-2.0
#
# SPDX-License-Identifier: Apache-2.0
# *******************************************************************************

from typing import Any

import pytest
from fit_scenario import FitScenario, ResultCode
from test_properties import add_test_properties
from testing_utils import LogContainer, ScenarioResult

# score_time is C++ only; there is no Rust variant of the clock library.
pytestmark = pytest.mark.parametrize("version", ["cpp"], scope="class")


class ClockScenario(FitScenario):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

redundant? should be possible to use FitScenario directly

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropped the build_tools override — FitScenario.build_tools already resolves the parametrized version via request.getfixturevalue. ClockScenario is kept as a thin base only to provide test_config, which is abstract on Scenario and not implemented by FitScenario.

"""Common base for score_time clock scenarios.

``build_tools`` is inherited from ``FitScenario``. The ``version`` parameter
is declared on ``test_config`` so it appears in the fixture dependency chain;
``FitScenario.build_tools`` then resolves it dynamically via
``request.getfixturevalue("version")`` and selects the C++ target.
"""

@pytest.fixture(scope="class")
def test_config(self, version: str) -> dict[str, Any]:
return {}


@add_test_properties(
partially_verifies=["FR-9"],
test_type="requirements-based",
derivation_technique="requirements-analysis",
)
class TestSystemClockNow(ClockScenario):
"""
Verify SystemClock::Now() returns a live reading through the public Clock API.

The C++ scenario compares the reading against the host system clock within
tolerance and fails the process otherwise. Python confirms the process
succeeded and that the reading was emitted. Partially verifies FR-9
(Absolute Time Base API): a live, non-zero reading through the public API.
"""

@pytest.fixture(scope="class")
def scenario_name(self) -> str:
return "time.system_clock_now"

def test_returns_success(self, results: ScenarioResult) -> None:
assert results.return_code == ResultCode.SUCCESS

def test_reading_logged(self, logs_info_level: LogContainer) -> None:
log = logs_info_level.find_log("clock", value="system")
assert log is not None
assert log.value_ns > 0


@add_test_properties(
partially_verifies=["FR-14"],
test_type="requirements-based",
derivation_technique="requirements-analysis",
)
class TestSteadyClockNow(ClockScenario):
"""
Verify SteadyClock::Now() is monotonic across two consecutive readings.

The C++ scenario fails the process if the second reading precedes the first.
Python confirms success and that the logged readings are non-decreasing.
Partially verifies FR-14 (Monotonic Clock API): non-decreasing readings.
"""

@pytest.fixture(scope="class")
def scenario_name(self) -> str:
return "time.steady_clock_now"

def test_returns_success(self, results: ScenarioResult) -> None:
assert results.return_code == ResultCode.SUCCESS

def test_readings_monotonic(self, logs_info_level: LogContainer) -> None:
log = logs_info_level.find_log("clock", value="steady")
assert log is not None
assert log.second_ns >= log.first_ns


@add_test_properties(
partially_verifies=["FR-13"],
test_type="requirements-based",
derivation_technique="requirements-analysis",
)
class TestHighResSteadyClockNow(ClockScenario):
"""
Verify HighResSteadyClock::Now() is live and monotonic.

The C++ scenario fails the process on a zero or non-monotonic reading.
Python confirms success and that the logged readings are non-zero and
non-decreasing. Partially verifies FR-13 (High Precision Clock API): a
non-zero, non-decreasing high-resolution reading.
"""

@pytest.fixture(scope="class")
def scenario_name(self) -> str:
return "time.high_res_steady_clock_now"

def test_returns_success(self, results: ScenarioResult) -> None:
assert results.return_code == ResultCode.SUCCESS

def test_readings_monotonic(self, logs_info_level: LogContainer) -> None:
log = logs_info_level.find_log("clock", value="high_res_steady")
assert log is not None
assert log.first_ns > 0
assert log.second_ns >= log.first_ns


@add_test_properties(
partially_verifies=["FR-14"],
test_type="requirements-based",
derivation_technique="requirements-analysis",
)
class TestSteadyClockProgression(ClockScenario):
"""
Verify SteadyClock::Now() stays monotonic across a burst of ticks and
progresses by roughly a known sleep duration.

The C++ scenario takes several readings, asserts the sequence is
non-decreasing, sleeps for a known duration, takes a final reading and
asserts it does not precede the last pre-sleep reading. Python confirms
success and that the post-sleep reading advanced by roughly the sleep
duration. Partially verifies FR-14 (Monotonic Clock API) / TC-FR14-001:
repeated Now() calls are non-decreasing and the clock progresses over time.
"""

@pytest.fixture(scope="class")
def scenario_name(self) -> str:
return "time.steady_clock_progression"

@pytest.fixture(scope="class")
def test_config(self, version: str) -> dict[str, Any]:
return {"tick_count": 5, "sleep_ms": 100}

def test_returns_success(self, results: ScenarioResult) -> None:
assert results.return_code == ResultCode.SUCCESS

def test_readings_monotonic(self, logs_info_level: LogContainer) -> None:
log = logs_info_level.find_log("clock", value="steady")
assert log is not None
assert log.last_ns >= log.first_ns
assert log.final_ns >= log.last_ns

def test_clock_progressed_during_sleep(self, logs_info_level: LogContainer) -> None:
log = logs_info_level.find_log("clock", value="steady")
assert log is not None
expected_ns = log.sleep_ms * 1_000_000
# Allow generous scheduling jitter: the clock must have advanced by at
# least half the sleep, proving the elapsed time is observable.
assert log.final_ns - log.last_ns >= expected_ns // 2
3 changes: 3 additions & 0 deletions feature_integration_tests/test_scenarios/cpp/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,8 @@ cc_binary(
"@score_baselibs//score/mw/log:backend_stub_testutil",
"@score_persistency//:kvs_cpp",
"@score_test_scenarios//test_scenarios_cpp",
"@score_time//score/time/high_res_steady_time",
"@score_time//score/time/steady_time",
"@score_time//score/time/system_time",
],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/********************************************************************************
* Copyright (c) 2026 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/

#ifndef INTERNALS_TIME_CLOCK_LOG_H_
#define INTERNALS_TIME_CLOCK_LOG_H_

#include <chrono>
#include <cstdint>
#include <iostream>
#include <string>

namespace time_log {

/**
* @brief Return the current UNIX timestamp in microseconds.
*
* The FIT LogContainer parses the "timestamp" field as microseconds, so the
* C++ scenarios emit microseconds to keep log ordering consistent with the
* Rust tracing JSON shape.
*
* @return Microseconds since the UNIX epoch.
*/
inline std::int64_t unix_micros() {
const auto now = std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count();
}

/**
* @brief Emit a structured JSON INFO log line to stdout.
*
* Matches the Rust tracing JSON format expected by the FIT LogContainer so
* that Python test assertions can use find_log() uniformly for both Rust and
* C++ scenarios.
*
* Example output:
* @code
* {"timestamp":"1700000000000000","level":"INFO","fields":{"clock":"system","value_ns":1700000000000000000},
* "target":"cpp_test_scenarios::scenarios::time::system_clock_now","threadId":"ThreadId(1)"}
* @endcode
*
* @param fields JSON fragment for the "fields" object, e.g. @c "\"clock\":\"system\",\"value_ns\":1"
* @param target Module target string embedded in the log line.
*/
inline void log_info(const std::string& fields, const std::string& target) {
std::cout << "{\"timestamp\":\"" << unix_micros()
<< "\",\"level\":\"INFO\",\"fields\":{" << fields
<< "},\"target\":\"" << target
<< "\",\"threadId\":\"ThreadId(1)\"}\n";
}

} // namespace time_log

#endif // INTERNALS_TIME_CLOCK_LOG_H_
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Scenario::Ptr make_utf8_default_value_get_scenario();
Scenario::Ptr make_multi_instance_isolation_scenario();
ScenarioGroup::Ptr supported_datatypes_group();
ScenarioGroup::Ptr default_values_group();
ScenarioGroup::Ptr time_scenario_group();

ScenarioGroup::Ptr persistency_scenario_group() {
return std::make_shared<ScenarioGroupImpl>(
Expand All @@ -42,5 +43,5 @@ ScenarioGroup::Ptr root_scenario_group() {
return std::make_shared<ScenarioGroupImpl>(
"root",
std::vector<Scenario::Ptr>{},
std::vector<ScenarioGroup::Ptr>{persistency_scenario_group()});
std::vector<ScenarioGroup::Ptr>{persistency_scenario_group(), time_scenario_group()});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/********************************************************************************
* Copyright (c) 2026 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/

#include "../../internals/time/clock_log.h"

#include "score/time/high_res_steady_time/src/high_res_steady_clock.h"

#include <scenario.hpp>

#include <cstdint>
#include <memory>
#include <stdexcept>
#include <string>

namespace {

/// Read the HighResSteadyClock twice via the public Clock API and verify it is
/// live and monotonic.
///
/// The high-resolution steady clock must return a non-zero reading and never
/// move backwards. This proves the high-resolution backend (system-clock based
/// on Linux) links and behaves monotonically in the reference integration build.
class HighResSteadyClockNow final : public Scenario {
public:
/**
* @brief Return the scenario name used to identify this scenario in the runner.
* @return Scenario name string.
*/
std::string name() const final { return "high_res_steady_clock_now"; }

/**
* @brief Execute the high-resolution steady-clock scenario.
*
* Takes two consecutive snapshots and verifies the first is non-zero and the
* second is not earlier than the first, then logs both readings for Python
* inspection.
*
* @param input Unused; this scenario takes no configuration.
* @throws std::runtime_error if the reading is zero or non-monotonic.
*/
void run(const std::string& /*input*/) const final {
const auto clock = score::time::HighResSteadyClock::GetInstance();
const std::int64_t first_ns = clock.Now().TimePointNs().count();
const std::int64_t second_ns = clock.Now().TimePointNs().count();

if (first_ns == 0) {
throw std::runtime_error("HighResSteadyClock::Now() returned a zero reading");
}
if (second_ns < first_ns) {
throw std::runtime_error(
"HighResSteadyClock::Now() is not monotonic: second reading precedes the first");
}

time_log::log_info(
"\"clock\":\"high_res_steady\",\"first_ns\":" + std::to_string(first_ns) +
",\"second_ns\":" + std::to_string(second_ns),
"cpp_test_scenarios::scenarios::time::high_res_steady_clock_now");
}
};

} // namespace

/**
* @brief Factory function for the HighResSteadyClockNow scenario.
* @return Shared pointer to the constructed scenario.
*/
Scenario::Ptr make_high_res_steady_clock_now_scenario() {
return std::make_shared<HighResSteadyClockNow>();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/********************************************************************************
* Copyright (c) 2026 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/

#include <scenario.hpp>

#include <vector>

Scenario::Ptr make_system_clock_now_scenario();
Scenario::Ptr make_steady_clock_now_scenario();
Scenario::Ptr make_high_res_steady_clock_now_scenario();
Scenario::Ptr make_steady_clock_progression_scenario();

ScenarioGroup::Ptr time_scenario_group() {
return std::make_shared<ScenarioGroupImpl>(
"time",
std::vector<Scenario::Ptr>{
make_system_clock_now_scenario(),
make_steady_clock_now_scenario(),
make_high_res_steady_clock_now_scenario(),
make_steady_clock_progression_scenario(),
},
std::vector<ScenarioGroup::Ptr>{});
}
Loading
Loading