use rustis::{
ClientError, ErrorKind, Result,
client::Client,
commands::{GenericCommands, HashCommands, StringCommands},
};
use serde_json::{Value, json};
use uuid::Uuid;
async fn connect() -> Result<Client> {
Client::connect("127.0.0.1:6379").await
}
fn is_arity_error(error: &rustis::Error, command: &str) -> bool {
matches!(
error.kind(),
ErrorKind::Client(ClientError::InvalidKeyArity { command: named, .. }) if named == command
)
}
#[tokio::test]
async fn a_uuid_is_a_valid_key() -> Result<()> {
let client = connect().await?;
let key = Uuid::new_v4();
client.set(key, "value").await?;
let value: String = client.get(key).await?;
assert_eq!("value", value);
let value: String = client.get(key.to_string()).await?;
assert_eq!("value", value);
client.del(key).await?;
client.close().await?;
Ok(())
}
#[tokio::test]
async fn a_json_value_is_a_key_or_not_depending_on_its_variant() -> Result<()> {
let client = connect().await?;
for accepted in [json!("a_string_key"), json!(42)] {
client.set(accepted.clone(), "value").await?;
let value: String = client.get(accepted.clone()).await?;
assert_eq!("value", value, "{accepted} writes one argument");
client.del(accepted).await?;
}
for rejected in [Value::Null, json!(["a", "b"]), json!({"tenant": "acme"})] {
let result: Result<String> = client.get(rejected.clone()).await;
let error = result.unwrap_err();
assert!(
is_arity_error(&error, "GET"),
"{rejected} is not a single key, got {error:?}"
);
}
client.close().await?;
Ok(())
}
#[tokio::test]
async fn a_json_object_is_a_valid_set_of_field_values() -> Result<()> {
let client = connect().await?;
let key = Uuid::new_v4();
client
.hset(key, json!({"tenant": "acme", "id": "42"}))
.await?;
let tenant: String = client.hget(key, "tenant").await?;
assert_eq!("acme", tenant);
client.del(key).await?;
client.close().await?;
Ok(())
}
#[tokio::test]
async fn a_collection_of_foreign_keys_is_accepted_but_not_an_empty_one() -> Result<()> {
let client = connect().await?;
let keys = [Uuid::new_v4(), Uuid::new_v4()];
for key in keys {
client.set(key, "value").await?;
}
assert_eq!(2, client.del(keys).await?);
let error = client.del(Vec::<Uuid>::new()).await.unwrap_err();
assert!(
is_arity_error(&error, "DEL"),
"an empty key list is refused, got {error:?}"
);
client.close().await?;
Ok(())
}