ftest/src/docker.rs

84 lines
2.7 KiB
Rust

use std::collections::HashMap;
use std::process::Command;
pub struct Docker;
impl Docker {
pub fn version() -> String {
let version = Command::new("docker")
.arg("--version")
.output()
.expect("unable to obtain Docker version");
let x = String::from_utf8(version.stdout).unwrap();
let x: Vec<&str> = x.split("Docker version ").collect();
x.get(1).unwrap().trim().to_string()
}
pub fn run_container(name: &str, img: &str, env: &HashMap<String, String>) {
let mut env_args = Vec::with_capacity(env.len() * 2 + 6);
env_args.push("run".to_string());
env_args.push("-d".to_string());
env_args.push("--name".to_string());
env_args.push(name.to_string());
for (k, v) in env.iter() {
env_args.push("-e".to_string());
env_args.push(format!("{k}={v}"));
}
env_args.push(img.to_string());
let mut child = Command::new("docker")
.args(&env_args)
.spawn()
.expect("unable to obtain Docker version");
child.wait().unwrap();
}
pub fn get_logs(name: &str) -> String {
let output = Command::new("docker")
.args(["logs", name])
.output()
.expect("unable to get logs");
String::from_utf8(output.stdout).unwrap()
}
pub fn rm_container(name: &str, force: bool) {
let args = if force {
vec!["rm", name]
} else {
vec!["rm", "--force", name]
};
Command::new("docker")
.args(args)
.spawn()
.expect(&format!("unable to remove docker container {name}"));
}
}
#[cfg(test)]
mod tests {
use crate::utils::get_random;
use super::*;
#[test]
fn test_docker() {
Docker::version();
let name = format!("test_sleep__{}", get_random(4));
let mut env = HashMap::new();
env.insert("FOO".to_string(), "BAR".to_string());
env.insert("BAZ".to_string(), "BOO".to_string());
Docker::run_container(&name, "forgeflux/ftest-dev-docker-cmd", &env);
let out = Command::new("docker")
.args(["container", "inspect", "-f", "'{{.State.Running}}'", &name])
.output()
.unwrap();
let out = String::from_utf8(out.stdout).unwrap();
assert!(out.contains("true"));
std::thread::sleep(std::time::Duration::new(10, 0));
let logs = Docker::get_logs(&name);
println!("{logs}");
assert!(logs.contains("running"));
assert!(logs.contains("FOO=BAR"));
assert!(logs.contains("BAZ=BOO"));
Docker::rm_container(&name, true);
}
}