ic-testkit 0.49.0

PocketIC-oriented test utilities for IC canister tests
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use std::{
    any::Any,
    panic::{AssertUnwindSafe, catch_unwind},
};

use pocket_ic::RejectResponse;

/// Captured PocketIC operation failure, retaining transport classification.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PocketIcOperationError {
    message: String,
    transport: bool,
}

impl PocketIcOperationError {
    /// Capture an upstream PocketIC panic message and classify its transport.
    #[must_use]
    pub fn new(message: impl Into<String>) -> Self {
        let message = message.into();
        let transport = is_dead_instance_transport_error(&message);
        Self { message, transport }
    }

    /// Read the original upstream message without contextual wrappers.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Whether the message matches a recognized PocketIC transport failure.
    #[must_use]
    pub const fn is_transport(&self) -> bool {
        self.transport
    }
}

// Only callers that intentionally capture every unwind use this boundary.
// Candid calls retain their separate policy of resuming unrelated panics.
pub(super) fn capture_operation<T>(
    operation: impl FnOnce() -> T,
) -> Result<T, PocketIcOperationError> {
    catch_unwind(AssertUnwindSafe(operation))
        .map_err(|payload| PocketIcOperationError::new(panic_payload_to_string(payload.as_ref())))
}

impl std::fmt::Display for PocketIcOperationError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for PocketIcOperationError {}

/// A rejected management call or a captured PocketIC operation panic.
#[non_exhaustive]
#[derive(Debug)]
pub enum PocketIcCallFailure {
    /// PocketIC returned a structured management-canister rejection.
    Rejected(RejectResponse),
    /// Captured PocketIC panic, retaining its original transport classification.
    Operation(PocketIcOperationError),
}

impl std::fmt::Display for PocketIcCallFailure {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Rejected(response) => write!(formatter, "rejected: {response:?}"),
            Self::Operation(source) if source.is_transport() => {
                write!(formatter, "PocketIC instance unavailable: {source}")
            }
            Self::Operation(source) => write!(formatter, "panicked: {source}"),
        }
    }
}

impl std::error::Error for PocketIcCallFailure {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Rejected(_) => None,
            Self::Operation(source) => Some(source),
        }
    }
}

pub(super) fn capture_call<T>(
    call: impl FnOnce() -> Result<T, RejectResponse>,
) -> Result<T, PocketIcCallFailure> {
    match capture_operation(call) {
        Ok(Ok(value)) => Ok(value),
        Ok(Err(response)) => Err(PocketIcCallFailure::Rejected(response)),
        Err(source) => Err(PocketIcCallFailure::Operation(source)),
    }
}

// Extract a stable string message from one panic payload.
pub(super) fn panic_payload_to_string(payload: &(dyn Any + Send)) -> String {
    if let Some(message) = payload.downcast_ref::<String>() {
        return message.clone();
    }
    if let Some(message) = payload.downcast_ref::<&'static str>() {
        return (*message).to_string();
    }

    "non-string panic payload".to_string()
}

/// Recognize PocketIC transport failures in typed causes and request-error text.
///
/// The complete error source chain is inspected so a recipe can classify its
/// own wrapper error as [`super::RebuildReason::DeadPocketIcTransport`]. This
/// preserves the classification already captured by testkit's structured errors.
/// Testkit [`super::CandidCallError`], [`super::PocketIcCallFailure`], and
/// [`PocketIcOperationError`] causes retain their transport classification through
/// contextual display wrappers, including nested [`std::io::Error`] values.
/// Snapshot and installation failures expose their operation cause through
/// the error source chain.
///
/// For other errors, message recognition requires a reqwest debug error with a
/// PocketIC instance URL and a recognized transport source, optionally prefixed
/// by PocketIC's HTTP panic context. Generic application messages and bare I/O
/// error kinds do not qualify.
/// Recognized sources include OS connection resets during an HTTP request.
///
/// Use this only for errors originating in a PocketIC operation. This is a
/// message-based heuristic, not proof that the server or instance has died;
/// another service or application can reproduce the same text. PocketIC does
/// not yet expose a structured transport error.
#[must_use]
pub fn is_dead_pocket_ic_transport_error(error: &(dyn std::error::Error + 'static)) -> bool {
    let mut current = Some(error);
    while let Some(candidate) = current {
        if candidate
            .downcast_ref::<PocketIcOperationError>()
            .is_some_and(PocketIcOperationError::is_transport)
        {
            return true;
        }
        if is_dead_instance_transport_error(&candidate.to_string()) {
            return true;
        }
        // io::Error::source delegates to the contained error's source, skipping
        // the contained error itself. Inspect it before following its causes so
        // contextual errors keep their own structured classification.
        current = if let Some(inner) = candidate
            .downcast_ref::<std::io::Error>()
            .and_then(std::io::Error::get_ref)
        {
            Some(inner)
        } else {
            candidate.source()
        };
    }
    false
}

// Recognize maintained PocketIC request-error shapes for restore recovery.
pub(super) fn is_dead_instance_transport_error(message: &str) -> bool {
    let message = message
        .strip_prefix("HTTP failure: ")
        .or_else(|| message.strip_prefix("called `Result::unwrap()` on an `Err` value: "))
        .unwrap_or(message);
    let Some(error) = message.strip_prefix("reqwest::Error { kind: ") else {
        return false;
    };
    let Some((kind, request)) = error.split_once(", url: \"") else {
        return false;
    };
    if !matches!(kind, "Request" | "Body" | "Decode") {
        return false;
    }
    let Some((url, source)) = request.split_once("\", source: ") else {
        return false;
    };
    let Some(source) = source.strip_suffix(" }") else {
        return false;
    };
    let Some(authority_and_path) = url
        .strip_prefix("http://")
        .or_else(|| url.strip_prefix("https://"))
    else {
        return false;
    };
    let Some((authority, path)) = authority_and_path.split_once('/') else {
        return false;
    };
    let Some(instance_path) = path.strip_prefix("instances/") else {
        return false;
    };
    let instance_id = instance_path.split('/').next().unwrap_or_default();
    if authority.is_empty()
        || instance_id.is_empty()
        || !instance_id.bytes().all(|byte| byte.is_ascii_digit())
    {
        return false;
    }
    let source = source
        .strip_prefix("hyper_util::client::legacy::Error(Connect, ")
        .or_else(|| source.strip_prefix("hyper_util::client::legacy::Error(SendRequest, "))
        .and_then(|source| source.strip_suffix(')'))
        .unwrap_or(source);
    let reset = source
        .strip_prefix("hyper::Error(Io, Os { code: ")
        .and_then(|source| source.split_once(", kind: ConnectionReset, message: \""))
        .is_some_and(|(code, message)| code.parse::<i32>().is_ok() && message.ends_with("\" })"));
    (source.starts_with("ConnectError(") && source.contains("kind: ConnectionRefused,"))
        || reset
        || matches!(
            source,
            "hyper::Error(IncompleteMessage)"
                | "hyper::Error(ChannelClosed)"
                | "hyper::Error(Canceled, \"connection closed before message completed\")"
        )
}

#[cfg(test)]
mod tests {
    use super::super::{CanisterInstallError, ControllerSnapshotError};
    use super::{
        PocketIcOperationError, capture_operation, is_dead_instance_transport_error,
        is_dead_pocket_ic_transport_error,
    };

    #[derive(Debug)]
    struct WrapperError(std::io::Error);

    const REFUSED: &str = "reqwest::Error { kind: Request, url: \"http://127.0.0.1:1234/instances/0/update/tick\", source: hyper_util::client::legacy::Error(Connect, ConnectError(\"tcp connect error\", 127.0.0.1:1234, Os { code: 111, kind: ConnectionRefused, message: \"Connection refused\" })) }";
    const INCOMPLETE: &str = "reqwest::Error { kind: Request, url: \"http://127.0.0.1:1234/instances/0/read/get_time\", source: hyper::Error(IncompleteMessage) }";
    const RESET: &str = "reqwest::Error { kind: Request, url: \"http://127.0.0.1:49238/instances/0/update/submit_ingress_message\", source: hyper_util::client::legacy::Error(SendRequest, hyper::Error(Io, Os { code: 54, kind: ConnectionReset, message: \"Connection reset by peer\" })) }";

    impl std::fmt::Display for WrapperError {
        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            formatter.write_str("wrapped PocketIC request failed")
        }
    }

    impl std::error::Error for WrapperError {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            Some(&self.0)
        }
    }

    #[test]
    fn dead_instance_transport_error_detects_connection_refused() {
        assert!(is_dead_instance_transport_error(REFUSED));
        assert!(is_dead_instance_transport_error(&format!(
            "HTTP failure: {REFUSED}"
        )));
    }

    #[test]
    fn dead_instance_transport_error_detects_incomplete_message() {
        assert!(is_dead_instance_transport_error(INCOMPLETE));
        assert!(is_dead_instance_transport_error(&format!(
            "called `Result::unwrap()` on an `Err` value: {INCOMPLETE}"
        )));
    }

    #[test]
    fn dead_instance_transport_error_detects_native_connection_reset() {
        for message in [RESET.to_owned(), RESET.replace("code: 54", "code: 104")] {
            assert!(is_dead_instance_transport_error(&message));
            assert!(PocketIcOperationError::new(format!("HTTP failure: {message}")).is_transport());
            assert!(is_dead_instance_transport_error(&format!(
                "called `Result::unwrap()` on an `Err` value: {message}"
            )));
        }
    }

    #[test]
    fn classify_pocket_ic_panic_marks_dead_instance_transport() {
        let classified = capture_operation::<()>(|| panic!("{INCOMPLETE}"))
            .expect_err("operation panic must be captured");

        assert_eq!(classified.message(), INCOMPLETE);
        assert!(classified.is_transport());
        let non_string = capture_operation::<()>(|| std::panic::panic_any(7_u8))
            .expect_err("non-string panic must be captured");
        assert_eq!(non_string.message(), "non-string panic payload");
        assert!(!non_string.is_transport());
    }

    #[test]
    fn public_classifier_inspects_the_error_source_chain() {
        let dead = WrapperError(std::io::Error::other(REFUSED));
        assert!(is_dead_pocket_ic_transport_error(&dead));

        let unrelated = WrapperError(std::io::Error::other("request rejected"));
        assert!(!is_dead_pocket_ic_transport_error(&unrelated));
    }

    #[test]
    fn snapshot_and_install_wrappers_preserve_transport_causes() {
        let canister_id = candid::Principal::anonymous();
        for message in [REFUSED, RESET, "unrelated application panic"] {
            let expected = message != "unrelated application panic";
            let capture = ControllerSnapshotError::CapturePanicked {
                canister_id,
                source: PocketIcOperationError::new(message),
                cleanup_failures: vec![],
            };
            let restore = ControllerSnapshotError::RestorePanicked {
                canister_id,
                source: PocketIcOperationError::new(message),
            };
            for snapshot in [capture, restore] {
                assert_eq!(is_dead_pocket_ic_transport_error(&snapshot), expected);
                let wrapper = WrapperError(std::io::Error::other(snapshot));
                assert_eq!(is_dead_pocket_ic_transport_error(&wrapper), expected);
            }
            for install in [
                CanisterInstallError::CreateCanister {
                    label: Some("fixture".into()),
                    source: PocketIcOperationError::new(message),
                },
                CanisterInstallError::AddCycles {
                    canister_id,
                    label: Some("fixture".into()),
                    source: PocketIcOperationError::new(message),
                },
                CanisterInstallError::InstallCode {
                    canister_id,
                    label: Some("fixture".into()),
                    source: PocketIcOperationError::new(message),
                },
            ] {
                assert_eq!(is_dead_pocket_ic_transport_error(&install), expected);
                let wrapper = WrapperError(std::io::Error::other(install));
                assert_eq!(is_dead_pocket_ic_transport_error(&wrapper), expected);
            }
        }
    }

    #[test]
    fn unrelated_and_quoted_transport_text_does_not_qualify() {
        for message in [
            "application worker channel closed",
            "fixture expected ConnectionRefused but observed another result",
            "tcp connect error",
            "connection closed before message completed",
            "IncompleteMessage",
            &format!("fixture quoted {REFUSED}"),
            &REFUSED.replace("/instances/0/update/tick", "/application/worker"),
            &REFUSED.replace("/instances/0/", "/instances/quoted/"),
            &INCOMPLETE.replace(
                "hyper::Error(IncompleteMessage)",
                "Custom(\"channel closed\")",
            ),
            &INCOMPLETE.replace(
                "hyper::Error(IncompleteMessage)",
                "Custom(\"hyper::Error(IncompleteMessage)\")",
            ),
            &format!("fixture quoted {RESET}"),
            &RESET.replace("/instances/0/", "/application/worker/"),
            &RESET.replace("/instances/0/", "/instances/quoted/"),
            &RESET.replace("kind: ConnectionReset,", "kind: ConnectionAborted,"),
            &RESET.replace("code: 54", "code: quoted"),
            &RESET.replace("hyper::Error(Io, Os {", "Custom(Os {"),
        ] {
            let error = WrapperError(std::io::Error::other(message.to_owned()));
            assert!(!is_dead_pocket_ic_transport_error(&error), "{message}");
            assert!(!PocketIcOperationError::new(message).is_transport());
        }
        let refused = std::io::Error::from(std::io::ErrorKind::ConnectionRefused);
        assert!(!is_dead_pocket_ic_transport_error(&refused));
        assert!(!is_dead_pocket_ic_transport_error(&WrapperError(refused)));
        let reset = std::io::Error::from(std::io::ErrorKind::ConnectionReset);
        assert!(!is_dead_pocket_ic_transport_error(&reset));
        assert!(!is_dead_pocket_ic_transport_error(&WrapperError(reset)));
    }

    #[test]
    fn structured_channel_closure_on_an_instance_request_qualifies() {
        let message = INCOMPLETE.replace("IncompleteMessage", "ChannelClosed");
        assert!(is_dead_instance_transport_error(&message));
    }

    #[test]
    fn contextual_call_errors_use_their_structured_kind() {
        let context = super::super::CandidCallContext::new(
            "query_call",
            candid::Principal::anonymous(),
            candid::Principal::anonymous(),
            "get",
        );
        let error = super::super::CandidCallError::Transport {
            context: Box::new(context.clone()),
            source: PocketIcOperationError::new(REFUSED),
        };
        assert!(is_dead_pocket_ic_transport_error(&error));
        let error = super::super::CandidCallError::Decode {
            context: Box::new(context),
            bytes: 0,
            message: "channel closed".into(),
        };
        assert!(!is_dead_pocket_ic_transport_error(&error));
    }

    #[test]
    fn io_wrappers_preserve_contextual_call_error_kinds() {
        let context = super::super::CandidCallContext::new(
            "query_call",
            candid::Principal::anonymous(),
            candid::Principal::anonymous(),
            "get",
        );
        for (error, expected) in [
            (
                super::super::CandidCallError::Transport {
                    context: Box::new(context.clone()),
                    source: PocketIcOperationError::new(REFUSED),
                },
                true,
            ),
            (
                super::super::CandidCallError::Decode {
                    context: Box::new(context),
                    bytes: 0,
                    message: REFUSED.into(),
                },
                false,
            ),
        ] {
            let inner = std::io::Error::other(error);
            assert_eq!(is_dead_pocket_ic_transport_error(&inner), expected);
            let wrapped = WrapperError(std::io::Error::other(inner));
            assert_eq!(is_dead_pocket_ic_transport_error(&wrapped), expected);
        }
    }
}