1use std::fmt;
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
5
6use navree_contracts::{BoxError, BoxFuture, Dispatcher, Job, JobEnvelope};
7
8use crate::batch::BatchRow;
9use crate::store::Store;
10use crate::{JobBatch, Queue, QueueOptions};
11
12#[derive(Clone, Default)]
57pub struct QueueFake {
58 recorded: Arc<Mutex<Vec<JobEnvelope>>>,
59 batches: Arc<Mutex<Vec<FakeBatch>>>,
60}
61
62#[derive(Clone, Debug)]
65pub struct RecordedBatch {
66 pub batch: JobBatch,
68 pub jobs: Vec<JobEnvelope>,
70 pub then: Option<JobEnvelope>,
72 pub catch: Option<JobEnvelope>,
74 pub finally: Option<JobEnvelope>,
76}
77
78impl RecordedBatch {
79 pub fn name(&self) -> &str {
81 &self.batch.name
82 }
83
84 pub fn jobs_of<J: Job>(&self) -> Vec<J> {
90 decode_all::<J>(&self.jobs)
91 }
92
93 pub fn then_of<J: Job>(&self) -> Option<J> {
95 self.then.as_ref().and_then(decode::<J>)
96 }
97
98 pub fn catch_of<J: Job>(&self) -> Option<J> {
100 self.catch.as_ref().and_then(decode::<J>)
101 }
102
103 pub fn finally_of<J: Job>(&self) -> Option<J> {
105 self.finally.as_ref().and_then(decode::<J>)
106 }
107}
108
109#[derive(Clone, Debug)]
111struct FakeBatch {
112 row: BatchRow,
113 jobs: Vec<JobEnvelope>,
114}
115
116fn decode<J: Job>(envelope: &JobEnvelope) -> Option<J> {
117 (envelope.job_type == J::NAME)
118 .then(|| serde_json::from_value(envelope.payload.clone()).ok())
119 .flatten()
120}
121
122fn decode_all<J: Job>(envelopes: &[JobEnvelope]) -> Vec<J> {
123 envelopes
124 .iter()
125 .filter(|e| e.job_type == J::NAME)
126 .map(|e| {
127 serde_json::from_value(e.payload.clone()).unwrap_or_else(|error| {
128 panic!("a recorded `{}` job does not deserialize: {error}", J::NAME)
129 })
130 })
131 .collect()
132}
133
134impl QueueFake {
135 pub fn batches(&self) -> Vec<RecordedBatch> {
137 self.batch_lock()
138 .iter()
139 .map(|fake| RecordedBatch {
140 batch: fake.row.to_batch(),
141 jobs: fake.jobs.clone(),
142 then: fake.row.callbacks.then.clone(),
143 catch: fake.row.callbacks.catch.clone(),
144 finally: fake.row.callbacks.finally.clone(),
145 })
146 .collect()
147 }
148
149 pub fn assert_batched(&self, pred: impl Fn(&RecordedBatch) -> bool) {
155 let batches = self.batches();
156 assert!(
157 batches.iter().any(pred),
158 "expected a matching batch to be dispatched; these were: {:?}",
159 batches.iter().map(RecordedBatch::name).collect::<Vec<_>>()
160 );
161 }
162
163 pub fn assert_nothing_batched(&self) {
169 let batches = self.batches();
170 assert!(
171 batches.is_empty(),
172 "expected no batch to be dispatched, these were: {:?}",
173 batches.iter().map(RecordedBatch::name).collect::<Vec<_>>()
174 );
175 }
176
177 pub(crate) fn record_batch(&self, row: BatchRow, jobs: Vec<JobEnvelope>) {
179 self.batch_lock().push(FakeBatch { row, jobs });
180 }
181
182 pub(crate) fn find_batch(&self, id: &str) -> Option<BatchRow> {
183 self.batch_lock()
184 .iter()
185 .find(|fake| fake.row.id == id)
186 .map(|fake| fake.row.clone())
187 }
188
189 pub(crate) fn batch_rows(&self, limit: usize) -> Vec<BatchRow> {
190 let mut rows: Vec<BatchRow> = self.batch_lock().iter().map(|f| f.row.clone()).collect();
191 rows.reverse();
192 rows.truncate(limit);
193 rows
194 }
195
196 pub(crate) fn cancel_batch(&self, id: &str, now: i64) -> Option<BatchRow> {
197 let mut batches = self.batch_lock();
198 let fake = batches.iter_mut().find(|fake| fake.row.id == id)?;
199 fake.row.cancel(now);
200 Some(fake.row.clone())
201 }
202
203 fn batch_lock(&self) -> MutexGuard<'_, Vec<FakeBatch>> {
204 self.batches.lock().unwrap_or_else(PoisonError::into_inner)
205 }
206 pub fn new() -> Self {
208 Self::default()
209 }
210
211 pub fn queue(&self) -> Queue {
214 Queue::new(
215 Store::Fake(self.clone()),
216 QueueOptions::default(),
217 None,
218 Vec::new(),
219 None,
220 )
221 }
222
223 pub fn dispatcher(&self) -> Arc<dyn Dispatcher> {
225 Arc::new(self.clone())
226 }
227
228 pub fn envelopes(&self) -> Vec<JobEnvelope> {
230 self.lock().clone()
231 }
232
233 pub fn dispatched<J: Job>(&self) -> Vec<J> {
239 self.lock()
240 .iter()
241 .filter(|e| e.job_type == J::NAME)
242 .map(|e| {
243 serde_json::from_value(e.payload.clone()).unwrap_or_else(|error| {
244 panic!("a recorded `{}` job does not deserialize: {error}", J::NAME)
245 })
246 })
247 .collect()
248 }
249
250 pub fn assert_dispatched<J: Job>(&self, pred: impl Fn(&J) -> bool) {
256 let jobs = self.dispatched::<J>();
257 assert!(
258 jobs.iter().any(pred),
259 "expected a matching `{}` job to be dispatched; {} `{}` job(s) were, and these job types: {:?}",
260 J::NAME,
261 jobs.len(),
262 J::NAME,
263 self.job_types()
264 );
265 }
266
267 pub fn assert_dispatched_times<J: Job>(&self, times: usize) {
273 let count = self.dispatched::<J>().len();
274 assert_eq!(
275 count,
276 times,
277 "expected `{}` to be dispatched {times} time(s), it was {count} time(s)",
278 J::NAME
279 );
280 }
281
282 pub fn assert_not_dispatched<J: Job>(&self) {
288 let count = self.dispatched::<J>().len();
289 assert_eq!(
290 count,
291 0,
292 "expected no `{}` job to be dispatched, {count} were",
293 J::NAME
294 );
295 }
296
297 pub fn assert_nothing_dispatched(&self) {
303 let types = self.job_types();
304 assert!(
305 types.is_empty(),
306 "expected no jobs to be dispatched, these were: {types:?}"
307 );
308 }
309
310 pub fn clear(&self) {
312 self.lock().clear();
313 self.batch_lock().clear();
314 }
315
316 pub(crate) fn record(&self, envelope: JobEnvelope) {
318 self.lock().push(envelope);
319 }
320
321 pub(crate) fn count_on(&self, queue: &str) -> u64 {
323 self.lock()
324 .iter()
325 .filter(|e| e.options.queue == queue)
326 .count() as u64
327 }
328
329 fn job_types(&self) -> Vec<String> {
330 self.lock().iter().map(|e| e.job_type.clone()).collect()
331 }
332
333 fn lock(&self) -> MutexGuard<'_, Vec<JobEnvelope>> {
334 self.recorded.lock().unwrap_or_else(PoisonError::into_inner)
335 }
336}
337
338impl Dispatcher for QueueFake {
339 fn dispatch_envelope(&self, env: JobEnvelope) -> BoxFuture<'_, Result<String, BoxError>> {
340 Box::pin(async move { Ok(self.queue().push(env).await?) })
341 }
342}
343
344impl fmt::Debug for QueueFake {
345 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346 f.debug_struct("QueueFake")
347 .field("dispatched", &self.job_types())
348 .finish()
349 }
350}