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 the complete public adapter contract using canonical string fixtures.
30///
31/// This covers scalar and batch behavior, expiry, removal, and clear. Use the
32/// granular contract helpers when an adapter uses other key or value types.
33///
34/// # Panics
35///
36/// Panics when `ttl_ms` is not positive or the backend violates the public
37/// adapter contract.
38pub async fn assert_adapter_contract<B>(backend: &B, ttl_ms: i64)
39where
40    B: CacheBackend<String, String>,
41{
42    assert!(ttl_ms > 0, "contract TTL must be positive");
43    assert_backend_contract(backend, &"contract".to_owned(), String::new()).await;
44    assert_expiring_contract(backend, &"ttl".to_owned(), "value".to_owned(), ttl_ms).await;
45    assert_batch_contract(
46        backend,
47        &"batch-first".to_owned(),
48        &"batch-second".to_owned(),
49        &"batch-missing".to_owned(),
50        "first".to_owned(),
51        "second".to_owned(),
52    )
53    .await;
54    assert_clear_contract(
55        backend,
56        &"clear-first".to_owned(),
57        &"clear-second".to_owned(),
58        "first".to_owned(),
59        "second".to_owned(),
60    )
61    .await;
62}
63
64/// Checks scalar miss, immortal and zero-TTL writes, invalid TTL rejection,
65/// removal, and zero-value-safe hit semantics.
66///
67/// # Panics
68///
69/// Panics when the backend violates the public adapter contract.
70pub async fn assert_backend_contract<B, K, V>(backend: &B, key: &K, value: V)
71where
72    B: CacheBackend<K, V>,
73    K: Sync,
74    V: Debug + PartialEq + Send + Sync + 'static,
75{
76    backend
77        .remove(key)
78        .await
79        .expect("contract setup remove failed");
80    assert!(
81        backend
82            .get(key)
83            .await
84            .expect("contract miss read failed")
85            .is_none()
86    );
87
88    let expected = Arc::new(value);
89    backend
90        .set(key, Arc::clone(&expected), -1)
91        .await
92        .expect("contract immortal write failed");
93    assert!(matches!(
94        backend.get(key).await.expect("contract immortal read failed"),
95        Some(entry) if entry.value == expected && entry.remaining_ttl == -1
96    ));
97
98    assert!(matches!(
99        backend.set(key, Arc::clone(&expected), -2).await,
100        Err(KapeError::InvalidTtl(-2))
101    ));
102    assert!(matches!(
103        backend.get(key).await.expect("invalid TTL changed value"),
104        Some(entry) if entry.value == expected && entry.remaining_ttl == -1
105    ));
106
107    backend
108        .set(key, Arc::clone(&expected), 0)
109        .await
110        .expect("contract zero-TTL write failed");
111    assert!(
112        backend
113            .get(key)
114            .await
115            .expect("contract zero-TTL read failed")
116            .is_none()
117    );
118
119    backend
120        .set(key, expected, -1)
121        .await
122        .expect("contract rewrite failed");
123    backend.remove(key).await.expect("contract remove failed");
124    assert!(
125        backend
126            .get(key)
127            .await
128            .expect("contract post-remove read failed")
129            .is_none()
130    );
131}
132
133/// Checks positive millisecond TTL reporting and expiration.
134///
135/// # Panics
136///
137/// Panics when `ttl_ms` is not positive or the backend violates expiration.
138pub async fn assert_expiring_contract<B, K, V>(backend: &B, key: &K, value: V, ttl_ms: i64)
139where
140    B: CacheBackend<K, V>,
141    K: Sync,
142    V: Debug + PartialEq + Send + Sync + 'static,
143{
144    assert!(ttl_ms > 0, "contract TTL must be positive");
145    backend
146        .set(key, Arc::new(value), ttl_ms)
147        .await
148        .expect("contract expiring write failed");
149
150    match backend
151        .get(key)
152        .await
153        .expect("contract expiring read failed")
154    {
155        Some(entry) => {
156            assert!(entry.remaining_ttl > 0, "remaining TTL must be positive");
157            assert!(
158                entry.remaining_ttl <= ttl_ms,
159                "remaining TTL exceeds requested TTL"
160            );
161        }
162        None => panic!("expected expiring hit, got a miss"),
163    }
164
165    let wait_ms = u64::try_from(ttl_ms).expect("positive TTL must fit u64") + 25;
166    sleep(Duration::from_millis(wait_ms)).await;
167    assert!(
168        backend
169            .get(key)
170            .await
171            .expect("contract expired read failed")
172            .is_none()
173    );
174}
175
176/// Checks ordered batch reads, duplicate read positions, duplicate-write
177/// rejection, misses, pre-validation, and empty-batch behavior.
178///
179/// # Panics
180///
181/// Panics when a batch operation violates the public adapter contract.
182pub async fn assert_batch_contract<B, K, V>(
183    backend: &B,
184    first_key: &K,
185    second_key: &K,
186    missing_key: &K,
187    first_value: V,
188    second_value: V,
189) where
190    B: CacheBackend<K, V>,
191    K: Eq + Hash + Sync,
192    V: Debug + PartialEq + Send + Sync + 'static,
193{
194    backend
195        .remove_many(&[first_key, second_key, missing_key])
196        .await
197        .expect("batch contract setup remove failed");
198
199    let first_value = Arc::new(first_value);
200    let second_value = Arc::new(second_value);
201    backend
202        .set_many(&[
203            SetItem::new(first_key, Arc::clone(&first_value), -1),
204            SetItem::new(second_key, Arc::clone(&second_value), 10_000),
205        ])
206        .await
207        .expect("batch contract write failed");
208
209    let read_keys = [first_key, missing_key, first_key, second_key];
210    let results = backend
211        .get_many(&read_keys)
212        .await
213        .expect("batch contract read failed");
214    assert_eq!(results.len(), read_keys.len());
215    assert!(matches!(&results[0], Some(entry) if entry.value == first_value));
216    assert!(results[1].is_none());
217    assert!(matches!(&results[2], Some(entry) if entry.value == first_value));
218    assert!(matches!(&results[3], Some(entry) if entry.value == second_value));
219
220    assert!(matches!(
221        backend
222            .set_many(&[
223                SetItem::new(first_key, Arc::clone(&first_value), -1),
224                SetItem::new(second_key, Arc::clone(&second_value), -2),
225            ])
226            .await,
227        Err(KapeError::InvalidTtl(-2))
228    ));
229
230    assert!(matches!(
231        backend
232            .set_many(&[
233                SetItem::new(first_key, Arc::clone(&second_value), -1),
234                SetItem::new(first_key, Arc::clone(&first_value), -1),
235            ])
236            .await,
237        Err(KapeError::DuplicateBatchKey {
238            first_index: 0,
239            duplicate_index: 1,
240        })
241    ));
242    assert!(matches!(
243        backend
244            .get(first_key)
245            .await
246            .expect("duplicate batch write changed value"),
247        Some(entry) if entry.value == first_value
248    ));
249
250    backend
251        .set_many(&[SetItem::new(first_key, Arc::clone(&first_value), 0)])
252        .await
253        .expect("batch zero-TTL invalidation failed");
254    assert!(
255        backend
256            .get(first_key)
257            .await
258            .expect("batch zero-TTL read failed")
259            .is_none()
260    );
261    assert!(
262        backend
263            .get(second_key)
264            .await
265            .expect("batch zero-TTL changed another key")
266            .is_some()
267    );
268
269    backend
270        .remove_many(&[first_key, second_key])
271        .await
272        .expect("batch contract remove failed");
273    assert!(
274        backend
275            .get_many(&[first_key, second_key])
276            .await
277            .expect("batch contract post-remove read failed")
278            .iter()
279            .all(Option::is_none)
280    );
281
282    assert!(
283        backend
284            .get_many(&[])
285            .await
286            .expect("empty batch read failed")
287            .is_empty()
288    );
289    backend
290        .set_many(&[])
291        .await
292        .expect("empty batch write failed");
293    backend
294        .remove_many(&[])
295        .await
296        .expect("empty batch remove failed");
297}
298
299/// Checks that clear removes all entries visible to this backend.
300///
301/// # Panics
302///
303/// Panics when clear fails or leaves an entry behind.
304pub async fn assert_clear_contract<B, K, V>(
305    backend: &B,
306    first_key: &K,
307    second_key: &K,
308    first_value: V,
309    second_value: V,
310) where
311    B: CacheBackend<K, V>,
312    K: Eq + Hash + Sync,
313    V: Debug + PartialEq + Send + Sync + 'static,
314{
315    backend
316        .set_many(&[
317            SetItem::new(first_key, Arc::new(first_value), -1),
318            SetItem::new(second_key, Arc::new(second_value), 10_000),
319        ])
320        .await
321        .expect("clear contract write failed");
322
323    backend.clear().await.expect("contract clear failed");
324    assert!(
325        backend
326            .get_many(&[first_key, second_key])
327            .await
328            .expect("contract post-clear read failed")
329            .iter()
330            .all(Option::is_none)
331    );
332}