|
1 | | -//! Tests for `PrintWriter::CollectString` — the output capture mode used by |
2 | | -//! hosts that need to intercept `print()` rather than pass it through to |
3 | | -//! stdout. |
4 | | -//! |
5 | | -//! Expected output is asserted via [`insta::assert_snapshot!`] with inline |
6 | | -//! snapshots — multi-line print output renders naturally in the snapshot |
7 | | -//! literal, which is substantially clearer than an escaped `"a\nb\n"` string. |
8 | | -//! To update after an intentional change, run `cargo insta review` (or set |
9 | | -//! `INSTA_UPDATE=always`). |
| 1 | +//! Tests for captured print output and callback errors. |
| 2 | +
|
| 3 | +use std::{borrow::Cow, mem}; |
10 | 4 |
|
11 | 5 | use insta::assert_snapshot; |
12 | 6 | use monty::MontyRun; |
13 | | -use monty_types::{CollectedStreams, CompileOptions, PrintStream, PrintWriter, ResourceTracker}; |
| 7 | +use monty_types::{ |
| 8 | + CollectedStreams, CompileOptions, ExcType, MontyException, MontyObject, PrintStream, PrintWriter, |
| 9 | + PrintWriterCallback, ResourceTracker, |
| 10 | +}; |
| 11 | + |
| 12 | +/// Checkpoint errors must reach handlers inside a synchronously evaluated callback. |
| 13 | +#[test] |
| 14 | +fn checkpoint_error_caught_inside_synchronous_callback() { |
| 15 | + let code = r" |
| 16 | +seen = [] |
| 17 | +
|
| 18 | +def key(value): |
| 19 | + try: |
| 20 | + print('arm') |
| 21 | + for _ in range(1000): |
| 22 | + pass |
| 23 | + except ValueError as exc: |
| 24 | + assert str(exc) == 'checkpoint failed' |
| 25 | + seen.append(value) |
| 26 | + return -value |
| 27 | +
|
| 28 | +def outer(): |
| 29 | + result = sorted([1, 2], key=key) |
| 30 | + assert result == [2, 1] |
| 31 | + assert seen == [1] |
| 32 | + return 42 |
| 33 | +
|
| 34 | +outer() |
| 35 | +"; |
| 36 | + assert_eq!(run_with_checkpoint_failure(code), MontyObject::int(42)); |
| 37 | +} |
| 38 | + |
| 39 | +/// A checkpoint failure must unwind nested frames before a native caller returns to its outer handler. |
| 40 | +#[test] |
| 41 | +fn checkpoint_error_unwinds_synchronous_callback() { |
| 42 | + let code = r" |
| 43 | +def leaf(value): |
| 44 | + print('arm') |
| 45 | + for _ in range(1000): |
| 46 | + pass |
| 47 | + return value |
| 48 | +
|
| 49 | +def key(value): |
| 50 | + return sorted([value], key=leaf)[0] |
| 51 | +
|
| 52 | +def outer(): |
| 53 | + kept = ['alive'] |
| 54 | + try: |
| 55 | + sorted([1], key=key) |
| 56 | + assert False, 'expected checkpoint failure' |
| 57 | + except ValueError as exc: |
| 58 | + assert str(exc) == 'checkpoint failed' |
| 59 | + assert kept == ['alive'] |
| 60 | + assert sorted([3, 1, 2], key=lambda value: -value) == [3, 2, 1] |
| 61 | + return 42 |
| 62 | +
|
| 63 | +outer() |
| 64 | +"; |
| 65 | + assert_eq!(run_with_checkpoint_failure(code), MontyObject::int(42)); |
| 66 | +} |
| 67 | + |
| 68 | +/// Arms a single failure from Python so setup cannot consume it before synchronous re-entry. |
| 69 | +fn run_with_checkpoint_failure(code: &str) -> MontyObject { |
| 70 | + let mut runner = MontyRun::new(code.to_owned(), "test.py", vec![], CompileOptions::default()).unwrap(); |
| 71 | + let mut writer = FailCheckpoint::default(); |
| 72 | + let result = runner |
| 73 | + .run(vec![], ResourceTracker::default(), PrintWriter::Callback(&mut writer)) |
| 74 | + .unwrap(); |
| 75 | + assert_eq!(writer.failures, 1); |
| 76 | + result |
| 77 | +} |
| 78 | + |
| 79 | +/// Fails the first flush poll after `print('arm')`, without relying on elapsed time. |
| 80 | +#[derive(Default)] |
| 81 | +struct FailCheckpoint { |
| 82 | + armed: bool, |
| 83 | + failures: usize, |
| 84 | +} |
| 85 | + |
| 86 | +impl PrintWriterCallback for FailCheckpoint { |
| 87 | + fn stdout_write(&mut self, output: Cow<'_, str>) -> Result<(), MontyException> { |
| 88 | + assert_eq!(output, "arm"); |
| 89 | + self.armed = self.failures == 0; |
| 90 | + Ok(()) |
| 91 | + } |
| 92 | + |
| 93 | + fn stdout_push(&mut self, _end: char) -> Result<(), MontyException> { |
| 94 | + Ok(()) |
| 95 | + } |
| 96 | + |
| 97 | + fn poll_flush(&mut self) -> Result<(), MontyException> { |
| 98 | + if mem::take(&mut self.armed) { |
| 99 | + self.failures += 1; |
| 100 | + Err(MontyException::new( |
| 101 | + ExcType::ValueError, |
| 102 | + Some("checkpoint failed".to_owned()), |
| 103 | + )) |
| 104 | + } else { |
| 105 | + Ok(()) |
| 106 | + } |
| 107 | + } |
| 108 | +} |
14 | 109 |
|
15 | 110 | /// Run `code` under Monty with a string-collecting `PrintWriter` and return |
16 | 111 | /// whatever was printed. Panics on parse/runtime errors — callers only care |
|
0 commit comments