use rightsize::{Container, ContainerGuard, Result, Wait};
const AMQP_PORT: u16 = 5672;
const MANAGEMENT_PORT: u16 = 15672;
pub struct RabbitMqContainer {
container: Container,
username: String,
password: String,
}
impl RabbitMqContainer {
pub fn new() -> Self {
Self::with_image("rabbitmq:4-management-alpine")
}
pub fn with_image(image: &str) -> Self {
let username = "guest".to_string();
let password = "guest".to_string();
let container = Container::new(image)
.with_exposed_ports(&[AMQP_PORT, MANAGEMENT_PORT])
.with_env("RABBITMQ_DEFAULT_USER", &username)
.with_env("RABBITMQ_DEFAULT_PASS", &password)
.waiting_for(Wait::for_log_message(".*Server startup complete.*", 1));
Self {
container,
username,
password,
}
}
pub fn with_username(mut self, username: &str) -> Self {
self.username = username.to_string();
self.container = self.container.with_env("RABBITMQ_DEFAULT_USER", username);
self
}
pub fn with_password(mut self, password: &str) -> Self {
self.password = password.to_string();
self.container = self.container.with_env("RABBITMQ_DEFAULT_PASS", password);
self
}
pub async fn start(self) -> Result<RabbitMqGuard> {
crate::register_default_backends();
let guard = self.container.start().await?;
Ok(RabbitMqGuard {
guard,
username: self.username,
password: self.password,
})
}
}
impl Default for RabbitMqContainer {
fn default() -> Self {
Self::new()
}
}
pub struct RabbitMqGuard {
guard: ContainerGuard,
username: String,
password: String,
}
impl RabbitMqGuard {
pub fn username(&self) -> &str {
&self.username
}
pub fn password(&self) -> &str {
&self.password
}
pub fn amqp_url(&self) -> String {
format!(
"amqp://{}:{}@{}:{}",
self.username,
self.password,
self.guard.host(),
self.guard.get_mapped_port(AMQP_PORT).unwrap()
)
}
pub fn management_url(&self) -> String {
format!(
"http://{}:{}",
self.guard.host(),
self.guard.get_mapped_port(MANAGEMENT_PORT).unwrap()
)
}
pub async fn stop(self) -> Result<()> {
self.guard.stop().await
}
}
impl std::ops::Deref for RabbitMqGuard {
type Target = ContainerGuard;
fn deref(&self) -> &ContainerGuard {
&self.guard
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_are_the_guest_pair() {
let c = RabbitMqContainer::new();
assert_eq!(c.username, "guest");
assert_eq!(c.password, "guest");
}
#[test]
fn builders_override_the_defaults() {
let c = RabbitMqContainer::new()
.with_username("alice")
.with_password("s3cret");
assert_eq!(c.username, "alice");
assert_eq!(c.password, "s3cret");
}
}