Skip to main content

portaki_test_utils/
lib.rs

1//! In-process test harness for Portaki module unit tests.
2//!
3//! # Role in the SDK stack
4//!
5//! `portaki-test-utils` complements [`portaki_sdk`] for **dev-dependencies** in
6//! module crates. Production Wasm modules call host functions through
7//! [`portaki_sdk::host`] (KV, i18n, connectors, repo, …). This crate supplies
8//! [`MockHostFunctions`], a [`portaki_sdk::host::HostBackend`] that runs entirely
9//! in memory on the test thread.
10//!
11//! Typical test flow:
12//!
13//! 1. Build a [`portaki_sdk::Context`] with [`MockContextBuilder::guest`] or
14//!    [`MockContextBuilder::host`].
15//! 2. Seed translations, KV bytes, and connector JSON stubs.
16//! 3. Call [`MockContextBuilder::run`] to install the mock backend via
17//!    [`portaki_sdk::host::with_host`] and execute module code.
18//! 4. Assert rendered SDUI with [`SurfaceAssertions`]. It walks every primitive of the
19//!    contract, so a module needs no `contains_component_type` helper of its own:
20//!
21//! ```
22//! use portaki_sdk::sdui::primitives::{Card, EmptyState, Stack};
23//! use portaki_sdk::sdui::surface::Surface;
24//! use portaki_test_utils::SurfaceAssertions;
25//!
26//! let surface = Surface::new(Stack::new().child(Card::new()));
27//! let tree = SurfaceAssertions::new(&surface);
28//!
29//! // Was: assert!(contains_component_type(&surface, "Card"));
30//! assert!(tree.contains_type("Card"));
31//! assert!(!tree.contains_primitive::<EmptyState>());
32//! ```
33//!
34//! # Relationship to `portaki-connectors`
35//!
36//! When module code calls `portaki_connectors::OpenWeather::current`, the mock
37//! host returns JSON registered with
38//! [`MockContextBuilder::with_connector_response`]. No network or gateway
39//! process is required.
40//!
41//! # Example
42//!
43//! ```
44//! use portaki_sdk::capability::{core, external};
45//! use portaki_test_utils::{MockContext, Property};
46//!
47//! MockContext::guest()
48//!     .with_property(Property::default())
49//!     .with_capabilities(&[core::STORAGE, external::OPEN_WEATHER_POOL])
50//!     .with_connector_response(
51//!         "open-weather",
52//!         "current",
53//!         r#"{"main":{"temp":21.5,"humidity":55},"weather":[{"main":"Clear"}]}"#,
54//!     )
55//!     .run(|_ctx| {
56//!         // Module code calling portaki_connectors::OpenWeather::current reads the stub.
57//!     });
58//! ```
59//!
60//! # Layout
61//!
62//! - [`MockContextBuilder`] / [`MockHostFunctions`] — mock host installation
63//! - [`Property`], [`Booking`], [`GuestIdentityFixture`] — default fixtures
64//! - [`SurfaceAssertions`], [`PrimitiveTag`] — SDUI tree queries over every primitive
65//! - [`assert_refused`], [`assert_declared_error`] — a handler refused with a declared code
66//! - [`mod@scenarios`] — the seven pathological cases of the sandbox, for `tests/scenarios.rs`
67//! - [`conformance!`] / [`mod@conformance`] — the battery every module runs: manifest, listing,
68//!   surfaces, operations, i18n, emails, contracts
69
70#![deny(missing_docs)]
71
72mod assertions;
73pub mod conformance;
74mod fixtures;
75mod mock_host;
76pub mod scenarios;
77
78/// Links the module's library into this integration test, so its `#[surface]`s are declared —
79/// for a test that names nothing of it, like one that only asserts on the battery's findings.
80///
81/// `link_module!()` reads the package's library name; `link_module!(my_module)` names it.
82#[macro_export]
83macro_rules! link_module {
84    ($($lib:ident)?) => {
85        $crate::__private::portaki_sdk::__link_module_crate!($($lib)?);
86    };
87}
88
89#[doc(hidden)]
90pub mod __private {
91    pub use portaki_sdk;
92}
93
94/// Asserts that `code` is declared by `portaki_module!(error = "…")` in a module linked into this
95/// test binary.
96///
97/// `portaki_sdk::refuse!` checks that at compile time; a `PortakiError::Refused` built by hand
98/// does not — the platform would then drop the refusal and show the host a generic failure. An
99/// integration test that names nothing of the module links it with [`link_module!`] first.
100///
101/// # Panics
102///
103/// When no linked module declares `code`.
104#[track_caller]
105pub fn assert_declared_error(code: &str) {
106    let declared: Vec<&str> = portaki_sdk::error::declared_errors().collect();
107    assert!(
108        declared.contains(&code),
109        "refusal code `{code}` is not declared — add error = \"{code}\" to portaki_module! \
110         (declared: {declared:?}; none at all? link the module with link_module!())"
111    );
112}
113
114/// Asserts that `result` is the refusal `code`, and that the module declares it.
115///
116/// ```ignore
117/// let result = MockContext::guest().run(|ctx| report(ctx, Report { photo: None }));
118/// portaki_test_utils::assert_refused(&result, "photo_required");
119/// ```
120///
121/// # Panics
122///
123/// When `result` is anything but `Err(PortakiError::Refused(code))`, or `code` is undeclared.
124#[track_caller]
125pub fn assert_refused<T: std::fmt::Debug>(result: &portaki_sdk::Result<T>, code: &str) {
126    match result {
127        Err(portaki_sdk::PortakiError::Refused(refused)) if *refused == code => {}
128        other => panic!("expected Err(Refused({code:?})), got {other:?}"),
129    }
130    assert_declared_error(code);
131}
132
133pub use assertions::{PrimitiveTag, SurfaceAssertions};
134pub use fixtures::{Booking, GuestIdentityFixture, Property};
135pub use mock_host::{ConnectorCall, LogLine, MockContext, MockContextBuilder, MockHostFunctions};