use crate::tester::unit_test::{Backends, UnitTest, UnitTestConfig, IDENTITY_MANAGEMENT_SVC};
use crate::{Backend, GrpcBackend, TraceBackend, UnitHttpResponse};
use classy::Entrypoint;
use pdk_core::client::service_name;
use std::rc::Rc;
pub struct UnitTestBuilder {
backend: Backends,
config: UnitTestConfig,
}
impl Default for UnitTestBuilder {
fn default() -> Self {
Self {
backend: Backends {
backend: Box::new(TraceBackend::new(UnitHttpResponse::new(200))),
upstreams: Default::default(),
grpc_upstreams: Default::default(),
},
config: Default::default(),
}
}
}
impl UnitTestBuilder {
pub fn with_config<S: Into<String>>(mut self, config: S) -> Self {
self.config.policy_config = config.into();
self
}
pub fn with_backend<B: Backend + 'static>(mut self, backend: B) -> Self {
self.backend.backend = Box::new(backend);
self
}
pub fn with_http_upstream_from_authority<K: AsRef<str>, B: Backend + 'static>(
self,
authority: K,
backend: B,
) -> Self {
let upstream = self.upstream(authority.as_ref());
self.with_http_upstream(upstream, backend)
}
pub fn with_http_upstream<K: Into<String>, B: Backend + 'static>(
mut self,
upstream: K,
backend: B,
) -> Self {
self.backend
.upstreams
.insert(upstream.into(), Rc::new(backend));
self
}
pub fn with_grpc_upstream_from_authority<K: AsRef<str>, B: GrpcBackend + 'static>(
self,
authority: K,
backend: B,
) -> Self {
let upstream = self.upstream(authority.as_ref());
self.with_grpc_upstream(upstream, backend)
}
pub fn with_grpc_upstream<K: Into<String>, B: GrpcBackend + 'static>(
mut self,
upstream: K,
backend: B,
) -> Self {
self.backend
.grpc_upstreams
.insert(upstream.into(), Rc::new(backend));
self
}
pub fn metadata<F: FnOnce(&mut pdk_core::policy_context::api::Metadata)>(
mut self,
function: F,
) -> Self {
function(&mut self.config.metadata);
self
}
pub fn with_identity_management<K: Into<String>, B: Backend + 'static>(
mut self,
url: K,
backend: B,
) -> Self {
self.config.identity_management = Some(url.into());
self.with_http_upstream(IDENTITY_MANAGEMENT_SVC, backend)
}
pub fn with_entrypoint<C, T, E: Entrypoint<C, T> + Clone + 'static>(
self,
entrypoint: E,
) -> UnitTest {
UnitTest::new(entrypoint, self.config, self.backend)
}
fn upstream(&self, authority: &str) -> String {
format!(
"{}.{}.svc",
service_name(
self.config.metadata.policy_metadata.policy_name.as_str(),
authority
),
self.config
.metadata
.policy_metadata
.policy_namespace
.as_str(),
)
}
}