Skip to content

Commit 111bc1e

Browse files
committed
Fix tests for the containers we're running them in
1 parent 90e88d3 commit 111bc1e

File tree

1 file changed

+13
-24
lines changed

1 file changed

+13
-24
lines changed

hostname1/dbus_test.go

Lines changed: 13 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ func TestStaticHostname(t *testing.T) {
6161
if err != nil && err != io.EOF {
6262
t.Fatal(err)
6363
}
64-
// Close the file so that systemd-hostnamed can use it.
64+
// Close the file so that hostnamed can use it.
6565
hostnameFile.Close()
6666
expectedHostname := strings.TrimSuffix(string(expectedHostnameBytes[:n]), "\n")
6767

@@ -75,44 +75,33 @@ func TestStaticHostname(t *testing.T) {
7575
} else if hostname != expectedHostname {
7676
t.Fatalf("expected %q, got %q", expectedHostname, hostname)
7777
}
78-
}
79-
80-
func TestSetStaticHostname(t *testing.T) {
81-
hostnameFile, err := os.Open("/etc/hostname")
82-
if err != nil {
83-
t.Fatal(err)
84-
}
85-
defer hostnameFile.Close()
86-
87-
originalHostnameBytes := make([]byte, 256)
88-
n, err := hostnameFile.Read(originalHostnameBytes)
89-
if err != nil && err != io.EOF {
90-
t.Fatal(err)
91-
}
92-
// Close the file so that systemd-hostnamed can use it.
93-
hostnameFile.Close()
94-
originalHostname := strings.TrimSuffix(string(originalHostnameBytes[:n]), "\n")
9578

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

102-
h, err := New()
89+
hostnameFile, err = os.OpenFile("/etc/hostname", os.O_WRONLY|os.O_TRUNC, 0644)
10390
if err != nil {
10491
t.Fatal(err)
10592
}
106-
107-
if err := h.SetStaticHostname(randomHostname, false); err != nil {
108-
t.Fatal(err)
109-
}
93+
defer hostnameFile.Close()
94+
// Restore the original hostname.
11095
defer func() {
111-
if err := h.SetStaticHostname(string(originalHostname), false); err != nil {
96+
if _, err := hostnameFile.WriteString(expectedHostname); err != nil {
11297
t.Fatal(err)
11398
}
11499
}()
115100

101+
if _, err := hostnameFile.WriteString(randomHostname); err != nil {
102+
t.Fatal(err)
103+
}
104+
116105
if hostname, err := h.StaticHostname(); err != nil {
117106
t.Fatal(err)
118107
} else if hostname != randomHostname {

0 commit comments

Comments
 (0)