pdk_unit/backends/trace.rs
1// Copyright (c) 2026, Salesforce, Inc.,
2// All rights reserved.
3// For full license text, see the LICENSE.txt file
4
5use crate::{Backend, UnitHttpRequest, UnitHttpResponse};
6use std::cell::RefCell;
7use std::collections::VecDeque;
8
9/// A [Backend] that stores the incoming requests to be later retrieved by the test.
10/// Delegates the response generation to the function provided in the constructor.
11/// This classes uses the interior mutability pattern to allow the test to retrieve the requests.
12///
13/// # Example
14///
15/// ```ignore
16/// let back = Rc::new(TraceBackend::new(echo_backend));
17///
18/// let mut tester = UnitTestBuilder::default()
19/// .with_config(config)
20/// .with_backend(Rc::clone(&back))
21/// .with_entrypoint(crate::configure);
22///
23/// let response = tester.request(req.clone());
24/// let request = back.next().unwrap();
25/// ```
26pub struct TraceBackend<B: Backend> {
27 response: B,
28 calls: RefCell<VecDeque<UnitHttpRequest>>,
29}
30
31impl<B: Backend> TraceBackend<B> {
32 /// Creates a new instance with the provided backend for response generation.
33 pub fn new(response: B) -> Self {
34 Self {
35 response,
36 calls: Default::default(),
37 }
38 }
39
40 /// Removes and returns the next request that reached the backend.
41 pub fn next(&self) -> Option<UnitHttpRequest> {
42 self.calls.borrow_mut().pop_front()
43 }
44}
45
46impl<B: Backend> Backend for TraceBackend<B> {
47 fn call(&self, req: UnitHttpRequest) -> UnitHttpResponse {
48 self.calls.borrow_mut().push_back(req.clone());
49 self.response.call(req)
50 }
51}