use super::{MissingResourceError, Resources};
use crate::{AsyncResource, Shared};
struct Egemma(usize);
struct Whisper(&'static str);
struct Ecapa;
impl AsyncResource for Egemma {
type Error = core::convert::Infallible;
type Options = usize;
async fn build(_ctx: &Resources, dim: usize) -> Result<Self, Self::Error> {
Ok(Self(dim))
}
}
impl AsyncResource for Whisper {
type Error = core::convert::Infallible;
type Options = &'static str;
async fn build(_ctx: &Resources, model: &'static str) -> Result<Self, Self::Error> {
Ok(Self(model))
}
}
impl AsyncResource for Ecapa {
type Error = core::convert::Infallible;
type Options = ();
async fn build(_ctx: &Resources, (): ()) -> Result<Self, Self::Error> {
Ok(Self)
}
}
#[test]
fn a_typed_lookup_answers_at_the_type_it_was_asked_at() {
let ctx = Resources::new()
.with(Shared::new(Egemma(768)))
.with(Shared::new(Whisper("large-v3")));
assert_eq!(ctx.len(), 2);
assert_eq!(ctx.shared::<Egemma>().expect("it is in").0, 768);
assert_eq!(ctx.shared::<Whisper>().expect("it is in").0, "large-v3");
}
#[test]
fn a_resource_nothing_built_is_a_refusal_that_names_it() {
let ctx = Resources::new().with(Shared::new(Egemma(768)));
let refusal = ctx
.shared::<Ecapa>()
.expect_err("nothing ever built an `Ecapa`");
assert_eq!(refusal, MissingResourceError::of::<Ecapa>());
assert!(refusal.resource().as_str().contains("Ecapa"));
assert!(refusal.to_string().contains("Ecapa"), "{refusal}");
}
#[test]
fn holds_reads_membership_at_the_type() {
let mut ctx = Resources::new();
assert!(ctx.is_empty());
assert!(!ctx.holds::<Egemma>());
ctx.insert(Shared::new(Egemma(512)));
assert!(ctx.holds::<Egemma>());
assert!(!ctx.holds::<Whisper>());
assert!(!ctx.is_empty());
}
#[test]
fn a_lookup_clones_the_handle_rather_than_the_resource() {
let built = Shared::new(Egemma(768));
let ctx = Resources::new().with(built);
let first = ctx.shared::<Egemma>().expect("it is in");
let second = ctx.shared::<Egemma>().expect("it is in");
assert!(core::ptr::eq(first.get(), second.get()));
assert_eq!(first.holders(), 3);
}
#[test]
fn a_second_handle_for_one_type_replaces_the_first() {
let ctx = Resources::new()
.with(Shared::new(Egemma(768)))
.with(Shared::new(Egemma(1024)));
assert_eq!(ctx.len(), 1);
assert_eq!(ctx.shared::<Egemma>().expect("it is in").0, 1024);
}
#[test]
fn the_context_is_send_and_sync() {
const fn crosses<T: Send + Sync>() {}
crosses::<Resources>();
}
#[test]
fn the_debug_reports_how_many_were_built() {
let ctx = Resources::new()
.with(Shared::new(Egemma(768)))
.with(Shared::new(Whisper("large-v3")));
assert_eq!(
format!("{ctx:?}"),
"Resources { resources: 2, goodbyes: 0 }"
);
}