feat: tests for docker cmd and env vars

This commit is contained in:
Aravinth Manivannan 2023-09-20 21:54:23 +05:30
parent 061e4c51d5
commit c2ac9689d8
Signed by: realaravinth
GPG key ID: F8F50389936984FF
4 changed files with 67 additions and 3 deletions

View file

@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::process::Command;
pub struct Docker;
@ -13,11 +14,22 @@ impl Docker {
x.get(1).unwrap().trim().to_string()
}
pub fn run_container(name: &str, img: &str) {
Command::new("docker")
.args(["run", "--name", name, img])
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 {
@ -40,3 +52,33 @@ impl Docker {
.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);
}
}

View file

@ -0,0 +1,10 @@
FROM debian:latest
LABEL org.opencontainers.image.source https://git.batsense.net/ForgeFlux/ftest
RUN mkdir /sr/
WORKDIR /src/
COPY . .
RUN find .
RUN ls .
CMD ["/src/scripts/run.sh"]

View file

@ -0,0 +1,4 @@
default:
docker buildx build -t forgeflux/ftest-dev-docker-cmd --load .
run:
docker run forgeflux/ftest-dev-test-docker-cmd

View file

@ -0,0 +1,8 @@
#!/bin/bash
echo "running"
echo "env:"
printenv $@
sleep 10
echo "exiting"
exit 0