Skip to main content

kape_testkit/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::{
4    fmt::Debug,
5    hash::{BuildHasher, Hash, RandomState},
6    sync::Arc,
7    time::Duration,
8};
9
10use kape::{CacheBackend, KapeError, SetItem};
11use tokio::time::sleep;
12
13/// Returns a 16-character alphanumeric string from OS-seeded hasher state.
14///
15/// Use this for example and test keys that should not collide across runs.
16#[must_use]
17pub fn get_random_string() -> String {
18    const ALPHANUMERIC: &[u8; 62] =
19        b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
20    let state = RandomState::new();
21    (0..16)
22        .map(|i| {
23            let index = (state.hash_one(i) % 62) as u8;
24            char::from(ALPHANUMERIC[usize::from(index)])
25        })
26        .collect()
27}
28
29/// Checks scalar miss, immortal and zero-TTL writes, invalid TTL rejection,
30/// removal, and zero-value-safe hit semantics.
31///
32/// # Panics
33///
34/// Panics when the backend violates the public adapter contract.
35pub async fn assert_backend_contract<B, K, V>(backend: &B, key: &K, value: V)
36where
37    B: CacheBackend<K, V>,
38    K: Sync,
39    V: Debug + PartialEq + Send + Sync + 'static,
40{
41    backend
42        .remove(key)
43        .await
44        .expect("contract setup remove failed");
45    assert!(
46        backend
47            .get(key)
48            .await
49            .expect("contract miss read failed")
50            .is_none()
51    );
52
53    let expected = Arc::new(value);
54    backend
55        .set(key, Arc::clone(&expected), -1)
56        .await
57        .expect("contract immortal write failed");
58    assert!(matches!(
59        backend.get(key).await.expect("contract immortal read failed"),
60        Some(entry) if entry.value == expected && entry.remaining_ttl == -1
61    ));
62
63    assert!(matches!(
64        backend.set(key, Arc::clone(&expected), -2).await,
65        Err(KapeError::InvalidTtl(-2))
66    ));
67    assert!(matches!(
68        backend.get(key).await.expect("invalid TTL changed value"),
69        Some(entry) if entry.value == expected && entry.remaining_ttl == -1
70    ));
71
72    backend
73        .set(key, Arc::clone(&expected), 0)
74        .await
75        .expect("contract zero-TTL write failed");
76    assert!(
77        backend
78            .get(key)
79            .await
80            .expect("contract zero-TTL read failed")
81            .is_none()
82    );
83
84    backend
85        .set(key, expected, -1)
86        .await
87        .expect("contract rewrite failed");
88    backend.remove(key).await.expect("contract remove failed");
89    assert!(
90        backend
91            .get(key)
92            .await
93            .expect("contract post-remove read failed")
94            .is_none()
95    );
96}
97
98/// Checks positive millisecond TTL reporting and expiration.
99///
100/// # Panics
101///
102/// Panics when `ttl_ms` is not positive or the backend violates expiration.
103pub async fn assert_expiring_contract<B, K, V>(backend: &B, key: &K, value: V, ttl_ms: i64)
104where
105    B: CacheBackend<K, V>,
106    K: Sync,
107    V: Debug + PartialEq + Send + Sync + 'static,
108{
109    assert!(ttl_ms > 0, "contract TTL must be positive");
110    backend
111        .set(key, Arc::new(value), ttl_ms)
112        .await
113        .expect("contract expiring write failed");
114
115    match backend
116        .get(key)
117        .await
118        .expect("contract expiring read failed")
119    {
120        Some(entry) => {
121            assert!(entry.remaining_ttl > 0, "remaining TTL must be positive");
122            assert!(
123                entry.remaining_ttl <= ttl_ms,
124                "remaining TTL exceeds requested TTL"
125            );
126        }
127        None => panic!("expected expiring hit, got a miss"),
128    }
129
130    let wait_ms = u64::try_from(ttl_ms).expect("positive TTL must fit u64") + 25;
131    sleep(Duration::from_millis(wait_ms)).await;
132    assert!(
133        backend
134            .get(key)
135            .await
136            .expect("contract expired read failed")
137            .is_none()
138    );
139}
140
141/// Checks ordered batch reads, duplicate read positions, duplicate-write
142/// rejection, misses, pre-validation, and empty-batch behavior.
143///
144/// # Panics
145///
146/// Panics when a batch operation violates the public adapter contract.
147pub async fn assert_batch_contract<B, K, V>(
148    backend: &B,
149    first_key: &K,
150    second_key: &K,
151    missing_key: &K,
152    first_value: V,
153    second_value: V,
154) where
155    B: CacheBackend<K, V>,
156    K: Eq + Hash + Sync,
157    V: Debug + PartialEq + Send + Sync + 'static,
158{
159    backend
160        .remove_many(&[first_key, second_key, missing_key])
161        .await
162        .expect("batch contract setup remove failed");
163
164    let first_value = Arc::new(first_value);
165    let second_value = Arc::new(second_value);
166    backend
167        .set_many(&[
168            SetItem::new(first_key, Arc::clone(&first_value), -1),
169            SetItem::new(second_key, Arc::clone(&second_value), 10_000),
170        ])
171        .await
172        .expect("batch contract write failed");
173
174    let read_keys = [first_key, missing_key, first_key, second_key];
175    let results = backend
176        .get_many(&read_keys)
177        .await
178        .expect("batch contract read failed");
179    assert_eq!(results.len(), read_keys.len());
180    assert!(matches!(&results[0], Some(entry) if entry.value == first_value));
181    assert!(results[1].is_none());
182    assert!(matches!(&results[2], Some(entry) if entry.value == first_value));
183    assert!(matches!(&results[3], Some(entry) if entry.value == second_value));
184
185    assert!(matches!(
186        backend
187            .set_many(&[
188                SetItem::new(first_key, Arc::clone(&first_value), -1),
189                SetItem::new(second_key, Arc::clone(&second_value), -2),
190            ])
191            .await,
192        Err(KapeError::InvalidTtl(-2))
193    ));
194
195    assert!(matches!(
196        backend
197            .set_many(&[
198                SetItem::new(first_key, Arc::clone(&second_value), -1),
199                SetItem::new(first_key, Arc::clone(&first_value), -1),
200            ])
201            .await,
202        Err(KapeError::DuplicateBatchKey {
203            first_index: 0,
204            duplicate_index: 1,
205        })
206    ));
207    assert!(matches!(
208        backend
209            .get(first_key)
210            .await
211            .expect("duplicate batch write changed value"),
212        Some(entry) if entry.value == first_value
213    ));
214
215    backend
216        .set_many(&[SetItem::new(first_key, Arc::clone(&first_value), 0)])
217        .await
218        .expect("batch zero-TTL invalidation failed");
219    assert!(
220        backend
221            .get(first_key)
222            .await
223            .expect("batch zero-TTL read failed")
224            .is_none()
225    );
226    assert!(
227        backend
228            .get(second_key)
229            .await
230            .expect("batch zero-TTL changed another key")
231            .is_some()
232    );
233
234    backend
235        .remove_many(&[first_key, second_key])
236        .await
237        .expect("batch contract remove failed");
238    assert!(
239        backend
240            .get_many(&[first_key, second_key])
241            .await
242            .expect("batch contract post-remove read failed")
243            .iter()
244            .all(Option::is_none)
245    );
246
247    assert!(
248        backend
249            .get_many(&[])
250            .await
251            .expect("empty batch read failed")
252            .is_empty()
253    );
254    backend
255        .set_many(&[])
256        .await
257        .expect("empty batch write failed");
258    backend
259        .remove_many(&[])
260        .await
261        .expect("empty batch remove failed");
262}
263
264/// Checks that clear removes all entries visible to this backend.
265///
266/// # Panics
267///
268/// Panics when clear fails or leaves an entry behind.
269pub async fn assert_clear_contract<B, K, V>(
270    backend: &B,
271    first_key: &K,
272    second_key: &K,
273    first_value: V,
274    second_value: V,
275) where
276    B: CacheBackend<K, V>,
277    K: Eq + Hash + Sync,
278    V: Debug + PartialEq + Send + Sync + 'static,
279{
280    backend
281        .set_many(&[
282            SetItem::new(first_key, Arc::new(first_value), -1),
283            SetItem::new(second_key, Arc::new(second_value), 10_000),
284        ])
285        .await
286        .expect("clear contract write failed");
287
288    backend.clear().await.expect("contract clear failed");
289    assert!(
290        backend
291            .get_many(&[first_key, second_key])
292            .await
293            .expect("contract post-clear read failed")
294            .iter()
295            .all(Option::is_none)
296    );
297}