Skip to content

Commit

Permalink
sudo-test: add API to set container hostname
Browse files Browse the repository at this point in the history
  • Loading branch information
japaric committed Mar 24, 2023
1 parent 8d44fc9 commit 6c338df
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
15 changes: 11 additions & 4 deletions test-framework/sudo-test/src/docker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,18 @@ pub struct Container {
}

impl Container {
pub fn new(image: &str) -> Result<Self> {
#[cfg(test)]
fn new(image: &str) -> Result<Self> {
Self::new_with_hostname(image, None)
}

pub fn new_with_hostname(image: &str, hostname: Option<&str>) -> Result<Self> {
let mut docker_run = StdCommand::new("docker");
docker_run
.args(["run", "-d", "--rm", image])
.args(DOCKER_RUN_COMMAND);
docker_run.args(["run", "--detach"]);
if let Some(hostname) = hostname {
docker_run.args(["--hostname", hostname]);
}
docker_run.args(["--rm", image]).args(DOCKER_RUN_COMMAND);
let id = run(&mut docker_run, None)?.stdout()?;
validate_docker_id(&id, &docker_run)?;

Expand Down
21 changes: 20 additions & 1 deletion test-framework/sudo-test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ impl Command {
pub struct EnvBuilder {
files: HashMap<AbsolutePath, TextFile>,
groups: HashMap<Groupname, Group>,
hostname: Option<String>,
users: HashMap<Username, User>,
}

Expand Down Expand Up @@ -158,6 +159,12 @@ impl EnvBuilder {
self
}

/// Sets the hostname of the container to the specified string
pub fn hostname(&mut self, hostname: impl AsRef<str>) -> &mut Self {
self.hostname = Some(hostname.as_ref().to_string());
self
}

/// builds the test environment
///
/// # Panics
Expand All @@ -172,7 +179,7 @@ impl EnvBuilder {
docker::build_base_image().expect("fatal error: could not build the base Docker image")
});

let container = Container::new(BASE_IMAGE)?;
let container = Container::new_with_hostname(BASE_IMAGE, self.hostname.as_deref())?;

let (mut usernames, user_ids) = getent_passwd(&container)?;

Expand Down Expand Up @@ -688,4 +695,16 @@ mod tests {

Ok(())
}

#[test]
fn setting_hostname_works() -> Result<()> {
let expected = "container";

let env = EnvBuilder::default().hostname(expected).build()?;

let actual = Command::new("hostname").exec(&env)?.stdout()?;
assert_eq!(expected, actual);

Ok(())
}
}

0 comments on commit 6c338df

Please sign in to comment.