use crate::Cmd;
use crate::Route;
use crate::executor::CommandExecutor;
use crate::{ValkeyResult, ValkeyValue};
use async_trait::async_trait;
use std::sync::Mutex;
type CapturedCommand = (Vec<Vec<u8>>, Option<Route>);
pub(crate) struct Mock {
response: Mutex<ValkeyValue>,
captured: Mutex<Option<CapturedCommand>>,
}
impl Mock {
pub(crate) fn new(response: ValkeyValue) -> Self {
Mock {
response: Mutex::new(response),
captured: Mutex::new(None),
}
}
pub(crate) fn ok() -> Self {
Mock::new(ValkeyValue::Okay)
}
pub(crate) fn int(n: i64) -> Self {
Mock::new(ValkeyValue::Int(n))
}
pub(crate) fn bulk(s: impl AsRef<[u8]>) -> Self {
Mock::new(ValkeyValue::BulkString(s.as_ref().to_vec().into()))
}
pub(crate) fn simple(s: &str) -> Self {
Mock::new(ValkeyValue::SimpleString(s.to_string()))
}
pub(crate) fn nil() -> Self {
Mock::new(ValkeyValue::Nil)
}
pub(crate) fn array(items: Vec<ValkeyValue>) -> Self {
Mock::new(ValkeyValue::Array(items))
}
pub(crate) fn args(&self) -> Vec<String> {
self.captured
.lock()
.unwrap()
.as_ref()
.expect("no command was captured")
.0
.iter()
.map(|a| String::from_utf8_lossy(a).into_owned())
.collect()
}
pub(crate) fn assert_args(&self, expected: &[&str]) {
let got = self.args();
let exp: Vec<String> = expected.iter().map(|s| s.to_string()).collect();
assert_eq!(got, exp, "command encoding mismatch");
}
pub(crate) fn routing(&self) -> Option<Route> {
self.captured
.lock()
.unwrap()
.as_mut()
.expect("no command was captured")
.1
.take()
}
}
#[async_trait]
impl CommandExecutor for Mock {
async fn execute_command(&self, cmd: Cmd, route: Option<Route>) -> ValkeyResult<ValkeyValue> {
let args: Vec<Vec<u8>> = cmd
.as_redis()
.args_iter()
.map(|a| match a {
redis::Arg::Simple(bytes) => bytes.to_vec(),
redis::Arg::Cursor => b"0".to_vec(),
})
.collect();
*self.captured.lock().unwrap() = Some((args, route));
Ok(self.response.lock().unwrap().clone())
}
}
mod bitmap;
mod connection_management;
mod generic;
mod geo;
mod hash;
mod json;
mod pubsub;
mod scripting;
mod server_management;
mod set;
mod sorted_set;
mod stream;
mod string;