use std::sync::{Arc, Mutex, MutexGuard};
use serde_json::Value;
use crate::api::{Error, Result, TmfRequest, TmfResponse, Transport};
use crate::server::{Listener, MemoryStore, Notifier, TmfHandler};
pub const DEFAULT_BASE_URL: &str = "http://mock.tmforum.test/tmf-api/v5";
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Notification {
pub hub_id: String,
pub callback: String,
pub event_type: String,
pub event: Value,
}
impl Notification {
#[must_use]
pub fn delivery_url(&self) -> String {
Listener {
hub_id: self.hub_id.clone(),
callback: self.callback.clone(),
}
.delivery_url(&self.event_type)
}
}
#[derive(Debug, Clone)]
struct Recorder(Arc<Mutex<Vec<Notification>>>);
#[async_trait::async_trait]
impl Notifier for Recorder {
async fn notify(&self, listener: &Listener, event_type: &str, event: &Value) {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(Notification {
hub_id: listener.hub_id.clone(),
callback: listener.callback.clone(),
event_type: event_type.to_owned(),
event: event.clone(),
});
}
}
#[derive(Debug, Clone)]
pub struct MockTmfServer {
handler: Arc<TmfHandler<MemoryStore>>,
notifications: Arc<Mutex<Vec<Notification>>>,
}
impl Default for MockTmfServer {
fn default() -> Self {
Self::new()
}
}
impl MockTmfServer {
#[must_use]
pub fn new() -> Self {
Self::with_base_url(DEFAULT_BASE_URL)
}
#[must_use]
pub fn with_base_url(base_url: impl Into<String>) -> Self {
let notifications = Arc::new(Mutex::new(Vec::new()));
Self {
handler: Arc::new(
TmfHandler::new(base_url, MemoryStore::new())
.with_notifier(Recorder(Arc::clone(¬ifications))),
),
notifications,
}
}
#[must_use]
pub fn base_url(&self) -> &str {
self.handler.base_url()
}
#[must_use]
pub fn url_for(&self, path: &str) -> String {
format!("{}/{}", self.base_url(), path.trim_start_matches('/'))
}
#[must_use]
pub fn store(&self) -> &MemoryStore {
self.handler.store()
}
pub fn seed(&self, collection: &str, resource: Value) {
self.store().seed(collection, resource);
}
pub fn seed_all(&self, collection: &str, resources: impl IntoIterator<Item = Value>) {
self.store().seed_all(collection, resources);
}
#[must_use]
pub fn collection(&self, collection: &str) -> Vec<Value> {
self.store().collection(collection)
}
pub fn clear(&self) {
self.store().clear();
self.lock().clear();
}
#[must_use]
pub fn notifications(&self) -> Vec<Notification> {
self.lock().clone()
}
pub fn emit(&self, event: &Value) -> usize {
let event_type = event
.get("eventType")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
let matched: Vec<Notification> =
crate::server::matching_listeners(&self.collection("hub"), event)
.into_iter()
.map(|listener| Notification {
hub_id: listener.hub_id,
callback: listener.callback,
event_type: event_type.clone(),
event: event.clone(),
})
.collect();
let count = matched.len();
self.lock().extend(matched);
count
}
#[must_use]
pub fn transport(&self) -> MockTransport {
MockTransport {
server: self.clone(),
}
}
pub async fn expect_error(&self, request: &TmfRequest) -> Error {
let response = self.handler.handle(request).await;
assert!(!response.status.is_success(), "expected a failure response");
crate::api::interpret_failure(&response)
}
fn lock(&self) -> MutexGuard<'_, Vec<Notification>> {
self.notifications
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
#[derive(Debug, Clone)]
pub struct MockTransport {
server: MockTmfServer,
}
#[async_trait::async_trait]
impl Transport for MockTransport {
async fn execute(&self, request: TmfRequest) -> Result<TmfResponse> {
Ok(self.server.handler.handle(&request).await)
}
}
#[cfg(test)]
mod tests;