use std::error::Error as StdError;
use std::future::{Future, IntoFuture};
use std::pin::Pin;
use jiff::ZonedDateTimeArithmetic;
use tracing::Instrument;
use crate::context::{Context, Internals};
use crate::queue::{
Batch, BatchId, Callback, Catch, EncodedCallback, EncodedJob, Finally, Job, JobList, JobTypes, Link, Outcome,
Payload, Place, Point, Ran, Then,
};
use crate::{Application, Error};
pub trait RunsJobs {
fn job<J: Job>(&self, job: J) -> TestJob<J>;
fn callback<C: Callback>(&self, callback: C) -> TestCallback<C>;
}
impl RunsJobs for Application {
fn job<J: Job>(&self, job: J) -> TestJob<J> {
TestJob {
application: self.clone(),
job,
attempt: 1,
batch: None,
}
}
fn callback<C: Callback>(&self, callback: C) -> TestCallback<C> {
TestCallback {
application: self.clone(),
callback,
batch: FakeBatch::default(),
}
}
}
#[derive(Debug)]
#[must_use = "a test job does nothing unless awaited"]
pub struct TestJob<J> {
application: Application,
job: J,
attempt: u32,
batch: Option<BatchId>,
}
impl<J: Job> TestJob<J> {
pub fn attempt(mut self, number: u32) -> Self {
self.attempt = number.max(1);
self
}
pub fn in_batch(mut self) -> Self {
self.batch = Some(BatchId::generate());
self
}
async fn run(self) -> TestJobResult {
let Self {
application,
job,
attempt,
batch,
} = self;
application
.scope(async move || {
let context = Context::expect("laravel::testing::RunsJobs::job()");
let connection = crate::queue::manager().default_connection().to_owned();
let queue = J::options().queue.unwrap_or("default");
let ran = match EncodedJob::new(job).map(|job| Payload::new(job, &context.values())) {
Ok(mut payload) => {
payload.debounce_id = None;
payload.batch = batch;
let place = Place {
connection: &connection,
queue,
number: attempt,
};
payload.run(place).instrument(payload.span(place)).await
}
Err(error) => Ran::failed(error),
};
TestJobResult {
job: J::NAME,
outcome: ran.outcome,
chain: JobList::new(ran.chain.jobs),
added_to_batch: JobList::new(
ran.batch
.added
.into_iter()
.filter_map(|chain| chain.jobs.into_iter().next())
.collect::<Vec<Link>>(),
),
cancelled_batch: ran.batch.cancel,
}
})
.await
}
}
impl<J: Job> IntoFuture for TestJob<J> {
type Output = TestJobResult;
type IntoFuture = Pin<Box<dyn Future<Output = TestJobResult> + Send>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.run())
}
}
#[derive(Debug)]
pub struct TestJobResult {
job: &'static str,
outcome: Outcome,
chain: JobList,
added_to_batch: JobList,
cancelled_batch: bool,
}
impl TestJobResult {
#[must_use]
pub const fn chain(&self) -> &JobList {
&self.chain
}
#[track_caller]
pub fn assert_chained<C: JobTypes>(&self) -> &Self {
let expected = C::names();
let actual = self.chain.names();
assert_eq!(
actual, expected,
"expected job `{}` to chain {expected:?}, but it chained {actual:?}",
self.job,
);
self
}
#[must_use]
pub const fn added_to_batch(&self) -> &JobList {
&self.added_to_batch
}
#[track_caller]
pub fn assert_batch_cancelled(&self) -> &Self {
assert!(
self.cancelled_batch,
"expected job `{}` to cancel its batch, but it {} without cancelling it",
self.job,
self.ended(),
);
self
}
#[must_use]
pub const fn error(&self) -> Option<&Error> {
match &self.outcome {
Outcome::Failed { error, .. } | Outcome::Settled(error) => Some(error),
Outcome::Succeeded
| Outcome::Released(_)
| Outcome::Deleted
| Outcome::Debounced
| Outcome::Skipped
| Outcome::MissingModels => None,
}
}
#[track_caller]
pub fn assert_succeeded(&self) -> &Self {
assert!(
matches!(self.outcome, Outcome::Succeeded),
"expected job `{}` to succeed, but it {}",
self.job,
self.ended(),
);
self
}
#[track_caller]
pub fn assert_released(&self) -> &Self {
assert!(
matches!(self.outcome, Outcome::Released(_)),
"expected job `{}` to be released, but it {}",
self.job,
self.ended(),
);
self
}
#[track_caller]
pub fn assert_released_after(&self, delay: impl Into<ZonedDateTimeArithmetic>) -> &Self {
let expected = crate::clock::exact_duration(delay);
assert!(
matches!(self.outcome, Outcome::Released(delay) if delay == expected),
"expected job `{}` to be released for {expected:?}, but it {}",
self.job,
self.ended(),
);
self
}
#[track_caller]
pub fn assert_deleted(&self) -> &Self {
assert!(
matches!(self.outcome, Outcome::Deleted | Outcome::MissingModels),
"expected job `{}` to be deleted, but it {}",
self.job,
self.ended(),
);
self
}
#[track_caller]
pub fn assert_failed(&self) -> &Self {
assert!(
self.error().is_some(),
"expected job `{}` to fail, but it {}",
self.job,
self.ended(),
);
self
}
#[track_caller]
pub fn assert_failed_with<E: StdError + Send + Sync + 'static>(&self) -> &Self {
assert!(
self.error().and_then(super::find_error::<E>).is_some(),
"expected job `{}` to fail with `{}`, but it {}",
self.job,
std::any::type_name::<E>(),
self.ended(),
);
self
}
fn ended(&self) -> String {
match &self.outcome {
Outcome::Succeeded => "succeeded".to_owned(),
Outcome::Released(delay) => format!("was released for {delay:?}"),
Outcome::Deleted | Outcome::MissingModels => "was deleted".to_owned(),
Outcome::Debounced => "was debounced".to_owned(),
Outcome::Skipped => "was skipped".to_owned(),
Outcome::Failed { error, .. } | Outcome::Settled(error) => format!("failed: {error}"),
}
}
}
#[derive(Debug)]
#[must_use = "a test callback does nothing until one of its methods is awaited"]
pub struct TestCallback<C> {
application: Application,
callback: C,
batch: FakeBatch,
}
#[derive(Debug, Default)]
struct FakeBatch {
name: Option<String>,
total: Option<u64>,
pending: Option<u64>,
failed: Option<u64>,
cancelled: bool,
}
impl<C: Callback> TestCallback<C> {
pub fn name(mut self, name: impl Into<String>) -> Self {
self.batch.name = Some(name.into());
self
}
pub const fn total_jobs(mut self, jobs: u64) -> Self {
self.batch.total = Some(jobs);
self
}
pub const fn pending_jobs(mut self, jobs: u64) -> Self {
self.batch.pending = Some(jobs);
self
}
pub const fn failed_jobs(mut self, jobs: u64) -> Self {
self.batch.failed = Some(jobs);
self
}
pub const fn cancelled(mut self) -> Self {
self.batch.cancelled = true;
self
}
async fn call(self, method: Method) -> crate::Result<()> {
let Self {
application,
callback,
batch,
} = self;
let failed = batch.failed.unwrap_or(u64::from(matches!(method, Method::Catch(_))));
let pending = batch.pending.unwrap_or(failed);
let total = batch.total.unwrap_or(1).max(pending).max(failed);
let callback = EncodedCallback::new(callback)?;
application
.scope(async move || {
let now = jiff::Timestamp::try_from(crate::clock::system_now()).unwrap_or(jiff::Timestamp::UNIX_EPOCH);
let batch = Batch::new(
BatchId::generate(),
batch.name,
(total, pending, failed),
now,
batch.cancelled.then_some(now),
(pending == failed).then_some(now),
);
let point = match &method {
Method::Then => Point::Then(&batch),
Method::Catch(error) => Point::Catch(Some(&batch), error),
Method::Finally => Point::Finally(&batch),
};
callback.run(point).await
})
.await
}
}
enum Method {
Then,
Catch(Error),
Finally,
}
impl<C: Then> TestCallback<C> {
pub fn then(self) -> impl Future<Output = crate::Result<()>> + Send {
self.call(Method::Then)
}
}
impl<C: Catch> TestCallback<C> {
pub fn catch(self, error: impl Into<Error>) -> impl Future<Output = crate::Result<()>> + Send {
self.call(Method::Catch(error.into()))
}
}
impl<C: Finally> TestCallback<C> {
pub fn finally(self) -> impl Future<Output = crate::Result<()>> + Send {
self.call(Method::Finally)
}
}