testcontainers_modules/redis/standalone.rs
1use testcontainers::{core::WaitFor, Image};
2
3const NAME: &str = "redis";
4const TAG: &str = "5.0";
5
6/// Module to work with [`Redis`] inside of tests.
7///
8/// Starts an instance of Redis based on the official [`Redis docker image`].
9///
10/// By default Redis is exposed on Port 6379 ([`REDIS_PORT`]) and has no access control. Please refer to the [`Redis reference guide`] for more informations on how to interact with the API.
11///
12/// # Example
13/// ```
14/// use redis::Commands;
15/// use testcontainers_modules::{
16/// redis::{Redis, REDIS_PORT},
17/// testcontainers::runners::SyncRunner,
18/// };
19///
20/// let redis_instance = Redis::default().start().unwrap();
21/// let host_ip = redis_instance.get_host().unwrap();
22/// let host_port = redis_instance.get_host_port_ipv4(REDIS_PORT).unwrap();
23///
24/// let url = format!("redis://{host_ip}:{host_port}");
25/// let client = redis::Client::open(url.as_ref()).unwrap();
26/// let mut con = client.get_connection().unwrap();
27///
28/// con.set::<_, _, ()>("my_key", 42).unwrap();
29/// let result: i64 = con.get("my_key").unwrap();
30/// ```
31///
32/// [`Redis`]: https://redis.io/
33/// [`Redis docker image`]: https://hub.docker.com/_/redis
34/// [`Redis reference guide`]: https://redis.io/docs/interact/
35/// [`REDIS_PORT`]: super::REDIS_PORT
36#[derive(Debug, Default, Clone)]
37pub struct Redis {
38 /// (remove if there is another variable)
39 /// Field is included to prevent this struct to be a unit struct.
40 /// This allows extending functionality (and thus further variables) without breaking changes
41 _priv: (),
42}
43
44impl Image for Redis {
45 fn name(&self) -> &str {
46 NAME
47 }
48
49 fn tag(&self) -> &str {
50 TAG
51 }
52
53 fn ready_conditions(&self) -> Vec<WaitFor> {
54 vec![WaitFor::message_on_stdout("Ready to accept connections")]
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use redis::Commands;
61
62 use crate::{redis::Redis, testcontainers::runners::SyncRunner};
63
64 #[test]
65 fn redis_fetch_an_integer() -> Result<(), Box<dyn std::error::Error + 'static>> {
66 let _ = pretty_env_logger::try_init();
67 let node = Redis::default().start()?;
68 let host_ip = node.get_host()?;
69 let host_port = node.get_host_port_ipv4(6379)?;
70 let url = format!("redis://{host_ip}:{host_port}");
71
72 let client = redis::Client::open(url.as_ref()).unwrap();
73 let mut con = client.get_connection().unwrap();
74
75 con.set::<_, _, ()>("my_key", 42).unwrap();
76 let result: i64 = con.get("my_key").unwrap();
77 assert_eq!(42, result);
78 Ok(())
79 }
80}