Skip to content

Commit

Permalink
Fix tests for the containers we're running them in
Browse files Browse the repository at this point in the history
  • Loading branch information
ananthb committed Apr 28, 2024
1 parent 90e88d3 commit 111bc1e
Showing 1 changed file with 13 additions and 24 deletions.
37 changes: 13 additions & 24 deletions hostname1/dbus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func TestStaticHostname(t *testing.T) {
if err != nil && err != io.EOF {
t.Fatal(err)
}
// Close the file so that systemd-hostnamed can use it.
// Close the file so that hostnamed can use it.
hostnameFile.Close()
expectedHostname := strings.TrimSuffix(string(expectedHostnameBytes[:n]), "\n")

Expand All @@ -75,44 +75,33 @@ func TestStaticHostname(t *testing.T) {
} else if hostname != expectedHostname {
t.Fatalf("expected %q, got %q", expectedHostname, hostname)
}
}

func TestSetStaticHostname(t *testing.T) {
hostnameFile, err := os.Open("/etc/hostname")
if err != nil {
t.Fatal(err)
}
defer hostnameFile.Close()

originalHostnameBytes := make([]byte, 256)
n, err := hostnameFile.Read(originalHostnameBytes)
if err != nil && err != io.EOF {
t.Fatal(err)
}
// Close the file so that systemd-hostnamed can use it.
hostnameFile.Close()
originalHostname := strings.TrimSuffix(string(originalHostnameBytes[:n]), "\n")

// hostnamed replaces the /etc/hostname entirely when the SetStaticHostname
// D-Bus method is called.
// This doesn't work with container bind mounts, so let's modify the file directly and
// see if the StaticHostname property changes.
var randomBytes [5]byte
if _, err := rand.Read(randomBytes[:]); err != nil {
t.Fatal(err)
}
randomHostname := "newhostname" + hex.EncodeToString(randomBytes[:])

h, err := New()
hostnameFile, err = os.OpenFile("/etc/hostname", os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
t.Fatal(err)
}

if err := h.SetStaticHostname(randomHostname, false); err != nil {
t.Fatal(err)
}
defer hostnameFile.Close()
// Restore the original hostname.
defer func() {
if err := h.SetStaticHostname(string(originalHostname), false); err != nil {
if _, err := hostnameFile.WriteString(expectedHostname); err != nil {
t.Fatal(err)
}
}()

if _, err := hostnameFile.WriteString(randomHostname); err != nil {
t.Fatal(err)
}

if hostname, err := h.StaticHostname(); err != nil {
t.Fatal(err)
} else if hostname != randomHostname {
Expand Down

0 comments on commit 111bc1e

Please sign in to comment.