Files
obipipeline/tests/errors.rs
T

274 lines
7.4 KiB
Rust
Raw Normal View History

//! Error semantics: the first error stops the pipeline and is returned by `finish()` / `run()`;
//! no failure may hang. Every test runs under a timeout guard.
use obipipeline::{
Pipeline, PipelineError, Throttle, WorkerPool, make_pipe, make_pipeline, throttle,
};
use std::io::{Error, ErrorKind};
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
// The `Text` payload is only built, never read back: it exists to trigger a runtime mismatch.
#[allow(dead_code)]
enum D {
Num(u64),
Text(String),
}
/// Runs `f` on a thread and fails the test if it does not finish in time (a hang is the bug to catch).
fn within<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let _ = tx.send(f());
});
rx.recv_timeout(Duration::from_secs(10))
.expect("the pipeline hung")
}
fn fails_on_5(x: u64) -> Result<u64, Error> {
if x == 5 {
Err(Error::new(ErrorKind::InvalidData, "boom on 5"))
} else {
Ok(x)
}
}
fn flat_fails_on_5(x: u64) -> Result<Vec<u64>, Error> {
fails_on_5(x).map(|v| vec![v, v])
}
fn panics_on_3(x: u64) -> u64 {
assert!(x != 3, "boom on 3");
x
}
fn to_text(x: u64) -> String {
x.to_string()
}
fn plus_one(x: u64) -> u64 {
x + 1
}
fn identity(x: u64) -> u64 {
x
}
fn triple(x: u64) -> Vec<u64> {
vec![x, x, x]
}
fn ignore(_x: u64) {}
fn message(e: &PipelineError) -> String {
e.to_string()
}
#[test]
fn fallible_stage_error_is_returned_and_does_not_hang() {
let (items, result) = within(|| {
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
let mut it = pipe.apply(1..=10u64, 2, 4);
let items: Vec<u64> = it.by_ref().collect();
(items, it.finish())
});
assert!(items.len() < 10, "the pipeline must stop early");
let err = result.expect_err("the stage error must be returned");
assert!(message(&err).contains("boom on 5"), "{err}");
}
#[test]
fn fallible_flat_stage_error_is_returned_and_does_not_hang() {
let result = within(|| {
let pipe = make_pipe! { D : u64 => u64, ||? flat_fails_on_5 : Num => Num, };
pipe.apply(1..=10u64, 2, 4).finish()
});
assert!(message(&result.unwrap_err()).contains("boom on 5"));
}
#[test]
fn runtime_type_mismatch_is_returned_and_does_not_hang() {
let result = within(|| {
// The first stage produces a Text, the second one reads a Num.
let pipe = make_pipe! {
D : u64 => u64,
| to_text : Num => Text,
| panics_on_3 : Num => Num,
};
pipe.apply(1..=10u64, 2, 4).finish()
});
assert!(matches!(result, Err(PipelineError::TypeMismatch)));
}
#[test]
fn worker_panic_is_returned_and_does_not_hang() {
let result = within(|| {
let pipe = make_pipe! { D : u64 => u64, | panics_on_3 : Num => Num, };
pipe.apply(1..=10u64, 2, 4).finish()
});
assert!(message(&result.unwrap_err()).contains("boom on 3"));
}
#[test]
fn finish_is_ok_when_everything_went_through() {
let (n, result) = within(|| {
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
let mut it = pipe.apply(6..=20u64, 3, 4);
let n = it.by_ref().count();
(n, it.finish())
});
assert_eq!(n, 15);
assert!(result.is_ok());
}
#[test]
fn capacity_one_works() {
let n = within(|| {
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
pipe.apply(6..=205u64, 2, 1).count()
});
assert_eq!(n, 200);
}
#[test]
#[should_panic(expected = "capacity of at least 1")]
fn zero_capacity_is_rejected() {
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
let _ = pipe.apply(0..3u64, 2, 0);
}
#[test]
#[should_panic(expected = "at least one worker")]
fn zero_workers_is_rejected() {
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
let _ = pipe.apply(0..3u64, 0, 4);
}
#[test]
#[should_panic(expected = "at least one slot")]
fn throttle_new_zero_is_rejected() {
let _ = Throttle::new(0);
}
#[test]
#[should_panic(expected = "at least one slot")]
fn throttle_zero_is_rejected() {
let _ = throttle(0..3u32, 0).count();
}
// ── Pipeline / WorkerPool (the lower-level runtime) ─────────────────────────────
fn pool_run(pipeline: Pipeline<D>) -> Result<(), PipelineError> {
WorkerPool::new(pipeline, 3, 4).run()
}
#[test]
fn pipeline_runs_and_reaches_the_sink() {
let (tx, rx) = mpsc::channel::<u64>();
let result = within(move || {
let collect = move |x: u64| tx.send(x).unwrap();
let pipeline = make_pipeline! {
D,
source 1..=50u64 => Num,
| plus_one : Num => Num,
sink collect @ Num,
};
pool_run(pipeline)
});
assert!(result.is_ok());
let mut got: Vec<u64> = rx.try_iter().collect();
got.sort_unstable();
assert_eq!(got, (2..=51).collect::<Vec<_>>());
}
#[test]
fn pipeline_returns_a_stage_error() {
let result = within(|| {
pool_run(make_pipeline! {
D,
source 1..=20u64 => Num,
|? fails_on_5 : Num => Num,
sink ignore @ Num,
})
});
assert!(message(&result.unwrap_err()).contains("boom on 5"));
}
fn fallible_source() -> Vec<Result<u64, Error>> {
vec![
Ok(1),
Ok(2),
Err(Error::new(ErrorKind::UnexpectedEof, "source broke")),
Ok(4),
]
}
#[test]
fn pipeline_returns_a_source_error() {
let result = within(|| {
pool_run(make_pipeline! {
D,
source? fallible_source() => Num,
| identity : Num => Num,
sink ignore @ Num,
})
});
assert!(message(&result.unwrap_err()).contains("source broke"));
}
fn failing_sink(x: u64) -> Result<(), Error> {
if x == 7 {
Err(Error::new(ErrorKind::BrokenPipe, "sink broke"))
} else {
Ok(())
}
}
#[test]
fn pipeline_returns_a_sink_error() {
let result = within(|| {
pool_run(make_pipeline! {
D,
source 1..=20u64 => Num,
| identity : Num => Num,
sink? failing_sink @ Num,
})
});
assert!(message(&result.unwrap_err()).contains("sink broke"));
}
#[test]
fn pipeline_with_a_flat_stage_counts_every_item() {
let (tx, rx) = mpsc::channel::<u64>();
let result = within(move || {
let collect = move |x: u64| tx.send(x).unwrap();
pool_run(make_pipeline! {
D,
source 1..=10u64 => Num,
|| triple : Num => Num,
sink collect @ Num,
})
});
assert!(result.is_ok());
assert_eq!(rx.try_iter().count(), 30);
}
// ── PipelineError ───────────────────────────────────────────────────────────────
#[test]
fn pipeline_error_display_and_source() {
use std::error::Error as _;
assert_eq!(
PipelineError::TypeMismatch.to_string(),
"data type mismatch in pipeline stage"
);
assert_eq!(
PipelineError::EndOfStream.to_string(),
"end of input stream"
);
assert!(PipelineError::TypeMismatch.source().is_none());
let inner = PipelineError::StepError(Box::new(Error::other("inner")));
assert!(inner.to_string().contains("inner"));
assert!(inner.source().is_some());
}