Skip to main content

pact_plugin_driver/
test_context.rs

1//! Thread-local test run ID for log correlation across driver and plugin log entries
2
3use std::cell::RefCell;
4
5thread_local! {
6  static CURRENT_TEST_RUN_ID: RefCell<Option<String>> = const { RefCell::new(None) };
7}
8
9/// Set the test run ID for the current thread. Pass `None` to clear it.
10///
11/// Should be called by the test framework (pact_consumer, pact_ffi) before any plugin
12/// calls, so that the ID is included in `testContext` of outgoing gRPC requests and can
13/// be used to correlate plugin log entries with a specific test.
14pub fn set_test_run_id(id: Option<String>) {
15  CURRENT_TEST_RUN_ID.with(|cell| *cell.borrow_mut() = id);
16}
17
18/// Return the test run ID set for the current thread, if any.
19pub fn current_test_run_id() -> Option<String> {
20  CURRENT_TEST_RUN_ID.with(|cell| cell.borrow().clone())
21}
22
23/// Build a `prost_types::Struct` containing `{ "testRunId": "<id>" }` when a test run ID
24/// is set on the current thread, or return `None` if none is set.
25pub(crate) fn current_test_context() -> Option<prost_types::Struct> {
26  current_test_run_id().map(|id| {
27    let mut fields = ::std::collections::BTreeMap::new();
28    fields.insert(
29      "testRunId".to_string(),
30      prost_types::Value {
31        kind: Some(prost_types::value::Kind::StringValue(id)),
32      },
33    );
34    prost_types::Struct { fields }
35  })
36}