use std::collections::HashMap;
use std::fmt;
use std::future::IntoFuture;
use std::sync::{Mutex, MutexGuard, PoisonError};
use futures_util::future::BoxFuture;
use serde::Serialize;
use serde_json::Value;
use crate::Application;
use crate::context::{Context, Internals};
use crate::queue::__queueable::ModelRows;
use crate::queue::{QueueManager, QueueManagerInternals as _};
use crate::workflow::store::{Created, Delivery, EntryStatus, Kind, NewRun};
use crate::workflow::{Manager, RunId, RunInfo, Status, StepInfo, Token, Workflow};
pub trait RunsWorkflows {
fn workflow<W: Workflow>(&self, workflow: W) -> TestWorkflow<W>;
}
impl RunsWorkflows for Application {
fn workflow<W: Workflow>(&self, workflow: W) -> TestWorkflow<W> {
TestWorkflow {
application: self.clone(),
workflow,
replacements: HashMap::new(),
tokens: Vec::new(),
}
}
}
#[must_use = "a test workflow does nothing unless awaited"]
pub struct TestWorkflow<W> {
application: Application,
workflow: W,
replacements: HashMap<String, String>,
tokens: Vec<String>,
}
impl<W> fmt::Debug for TestWorkflow<W> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TestWorkflow").finish_non_exhaustive()
}
}
impl<W: Workflow> TestWorkflow<W> {
#[track_caller]
pub fn with_step(mut self, name: impl Into<String>, output: impl Serialize) -> Self {
let output = serde_json::to_string(&output)
.unwrap_or_else(|error| panic!("the replaced step's output doesn't serialize: {error}"));
self.replacements.insert(name.into(), output);
self
}
pub fn claim(mut self, token: impl AsRef<str>) -> Self {
self.tokens.push(token.as_ref().to_owned());
self
}
async fn start(self) -> TestRun {
let Self {
application,
workflow,
replacements,
tokens,
} = self;
let id = application
.scope(async move || {
let context = Context::expect("laravel::testing::RunsWorkflows::workflow()");
let (connection, queue) = QueueManager::of(context.services())
.route(None, W::queue())
.unwrap_or_else(|error| panic!("the workflow's queue isn't defined: {error}"));
let input = crate::queue::store_queueable("workflow", W::NAME, &workflow, &mut ModelRows::new())
.unwrap_or_else(|error| panic!("the workflow doesn't encode: {error}"));
let id = RunId::generate();
let now = crate::workflow::now();
let mut run = NewRun::__starting(
id,
W::NAME.to_owned(),
input.to_string(),
crate::workflow::encode_context(&context).unwrap_or_default(),
(connection, queue),
now,
);
run.tokens = tokens;
match store(&context).create(run).await {
Ok(Created::Saved) => {}
Ok(Created::Taken { token, owner }) => {
panic!("the token `{token}` is owned by the unfinished run {owner}")
}
Ok(other) => panic!("the run couldn't be saved: {other:?}"),
Err(error) => panic!("the run couldn't be saved: {error}"),
}
id
})
.await;
let run = TestRun {
application,
id,
replacements,
info: Mutex::new(None),
};
run.advance().await;
run
}
}
impl<W: Workflow> IntoFuture for TestWorkflow<W> {
type Output = TestRun;
type IntoFuture = BoxFuture<'static, TestRun>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.start())
}
}
fn store(context: &Context) -> std::sync::Arc<dyn crate::workflow::ErasedStore> {
Manager::of(context.services())
.store()
.unwrap_or_else(|error| panic!("the workflow store isn't available: {error}"))
}
pub struct TestRun {
application: Application,
id: RunId,
replacements: HashMap<String, String>,
info: Mutex<Option<RunInfo>>,
}
impl fmt::Debug for TestRun {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let state = self.state();
let Some(info) = state.as_ref() else {
return write!(f, "run {} is gone from its store", self.id);
};
write!(f, "run {} of `{}` is {}", info.id(), info.workflow(), info.status())?;
if let Some(error) = info.error() {
write!(f, ": {error}")?;
}
for step in info.steps() {
write!(
f,
"\n {} `{}` {}",
step.kind().as_str(),
step.name(),
step.status().as_str()
)?;
if step.kind() == Kind::Step {
write!(f, " after {} tries", step.tries())?;
}
if let Some(error) = step.error() {
write!(f, ": {error}")?;
}
}
Ok(())
}
}
impl TestRun {
#[must_use]
pub const fn id(&self) -> RunId {
self.id
}
#[must_use]
pub fn info(&self) -> Option<RunInfo> {
self.state().clone()
}
fn state(&self) -> MutexGuard<'_, Option<RunInfo>> {
self.info.lock().unwrap_or_else(PoisonError::into_inner)
}
pub async fn advance(&self) -> &Self {
let id = self.id;
let replacements = self.replacements.clone();
let info = self
.application
.scope(async move || {
if let Err(error) = crate::workflow::advance(id, replacements).await {
panic!("the workflow run couldn't advance: {error:#}");
}
crate::workflow::find(id).await
})
.await
.unwrap_or_else(|error| panic!("the workflow run couldn't be read: {error:#}"));
*self.state() = info;
self
}
pub async fn resume<T: Serialize>(&self, token: impl Into<Token<T>>, value: T) -> &Self {
let token = String::from(token.into());
let value =
serde_json::to_string(&value).unwrap_or_else(|error| panic!("the value doesn't serialize: {error}"));
let id = self.id;
self.application
.scope(async move || {
let context = Context::expect("laravel::testing::TestRun::resume()");
let delivery = store(&context)
.resume(&token, value)
.await
.unwrap_or_else(|error| panic!("the token couldn't be resumed: {error:#}"));
match delivery {
Delivery::Due(owner) | Delivery::Queued(owner) if owner == id => {}
Delivery::Due(owner) | Delivery::Queued(owner) => {
panic!("the token `{token}` is owned by run {owner}, not run {id}")
}
_ => panic!(
"run {id} doesn't own the token `{token}`: it hasn't reached a wait for the token, \
so claim the token at the start with `app.workflow(..).claim(..)`"
),
}
})
.await;
self.advance().await
}
fn read<T>(&self, read: impl FnOnce(&RunInfo) -> T) -> T {
let info = self.info();
let info = info
.as_ref()
.unwrap_or_else(|| panic!("the workflow run `{}` is gone from its store", self.id));
read(info)
}
fn status(&self) -> Status {
self.read(RunInfo::status)
}
fn step(&self, name: &str) -> Option<StepInfo> {
self.read(|info| {
info.steps()
.iter()
.find(|step| step.kind() == Kind::Step && step.name() == name)
.cloned()
})
}
#[track_caller]
pub fn assert_completed(&self) -> &Self {
assert_eq!(self.status(), Status::Completed, "the run didn't complete\n{self:?}");
self
}
#[track_caller]
pub fn assert_completed_with(&self, expected: impl Serialize) -> &Self {
self.assert_completed();
let expected = serde_json::to_value(expected).expect("the expected output serializes");
let output: Option<Value> = self.read(|info| info.output().expect("the output is JSON"));
assert_eq!(output, Some(expected), "the run returned something else");
self
}
#[track_caller]
pub fn assert_failed(&self) -> &Self {
assert_eq!(self.status(), Status::Failed, "the run didn't fail\n{self:?}");
self
}
#[track_caller]
pub fn assert_failed_with(&self, message: &str) -> &Self {
self.assert_failed();
let error = self.read(|info| info.error().unwrap_or_default().to_owned());
assert!(
error.contains(message),
"the run failed with `{error}`, not `{message}`"
);
self
}
#[track_caller]
pub fn assert_sleeping(&self) -> &Self {
let sleeping = self.read(|info| {
info.status() == Status::Waiting
&& info
.steps()
.iter()
.any(|step| step.kind() == Kind::Sleep && step.status() == EntryStatus::Pending)
});
assert!(sleeping, "the run isn't sleeping\n{self:?}");
self
}
#[track_caller]
pub fn assert_waiting_for(&self, token: impl AsRef<str>) -> &Self {
let token = token.as_ref();
let waiting =
self.read(|info| info.status() == Status::Waiting && info.waiting_for().any(|wait| wait == token));
assert!(waiting, "the run isn't waiting for `{token}`\n{self:?}");
self
}
#[track_caller]
pub fn assert_retrying(&self, name: &str) -> &Self {
let retrying = self.status() == Status::Waiting
&& self
.step(name)
.is_some_and(|step| step.status() == EntryStatus::Pending);
assert!(retrying, "the step `{name}` isn't waiting to try again\n{self:?}");
self
}
#[track_caller]
pub fn assert_step_ran(&self, name: &str) -> &Self {
let ran = self
.step(name)
.is_some_and(|step| step.status() == EntryStatus::Completed);
assert!(ran, "the step `{name}` didn't complete\n{self:?}");
self
}
#[track_caller]
pub fn assert_step_not_ran(&self, name: &str) -> &Self {
assert!(self.step(name).is_none(), "the step `{name}` was tried\n{self:?}");
self
}
#[track_caller]
pub fn assert_step_tries(&self, name: &str, count: u32) -> &Self {
let tries = self.step(name).map_or(0, |step| step.tries());
assert_eq!(
tries, count,
"the step `{name}` was tried {tries} times, not {count}: {self:?}"
);
self
}
}