k8s_test_framework/
test_pod.rs

1//! Manage test pods.
2
3use std::process::{Command, Stdio};
4
5use k8s_openapi::api::core::v1::Pod;
6
7use super::{resource_file::ResourceFile, Result};
8use crate::up_down;
9
10/// A config that holds a test `Pod` resource file.
11#[derive(Debug)]
12pub struct Config {
13    test_pod_resource_file: ResourceFile,
14}
15
16impl Config {
17    /// Create a [`Config`] using a structured [`Pod`] object.
18    pub fn from_pod(pod: &Pod) -> Result<Self> {
19        Self::from_resource_string(serde_json::to_string(pod)?.as_str())
20    }
21
22    /// Create a [`Config`] using an unstructured resource string.
23    pub fn from_resource_string(resource: &str) -> Result<Self> {
24        let test_pod_resource_file = ResourceFile::new(resource)?;
25        Ok(Self {
26            test_pod_resource_file,
27        })
28    }
29}
30
31/// Parameters required to build a `kubectl` command to manage the test `Pod`.
32#[derive(Debug)]
33pub struct CommandBuilder {
34    kubectl_command: String,
35    config: Config,
36}
37
38impl up_down::CommandBuilder for CommandBuilder {
39    fn build(&self, command_to_build: up_down::CommandToBuild) -> Command {
40        let mut command = Command::new(&self.kubectl_command);
41        command
42            .arg(match command_to_build {
43                up_down::CommandToBuild::Up => "create",
44                up_down::CommandToBuild::Down => "delete",
45            })
46            .arg("-f")
47            .arg(self.config.test_pod_resource_file.path());
48
49        if matches!(command_to_build, up_down::CommandToBuild::Down) {
50            // We don't need a graceful shutdown
51            command.arg("--force=true");
52            command.arg("--grace-period=0");
53            command.arg("--wait=false");
54        }
55
56        command.stdin(Stdio::null());
57        command
58    }
59}
60
61/// Create a new [`up_down::Manager`] with the specified `config` and using
62/// the specified `kubectl_command`.
63pub fn manager(kubectl_command: &str, config: Config) -> up_down::Manager<CommandBuilder> {
64    up_down::Manager::new(CommandBuilder {
65        kubectl_command: kubectl_command.to_owned(),
66        config,
67    })
68}