@@ -61,7 +61,7 @@ func TestStaticHostname(t *testing.T) {
61
61
if err != nil && err != io .EOF {
62
62
t .Fatal (err )
63
63
}
64
- // Close the file so that systemd- hostnamed can use it.
64
+ // Close the file so that hostnamed can use it.
65
65
hostnameFile .Close ()
66
66
expectedHostname := strings .TrimSuffix (string (expectedHostnameBytes [:n ]), "\n " )
67
67
@@ -75,44 +75,33 @@ func TestStaticHostname(t *testing.T) {
75
75
} else if hostname != expectedHostname {
76
76
t .Fatalf ("expected %q, got %q" , expectedHostname , hostname )
77
77
}
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 " )
95
78
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.
96
83
var randomBytes [5 ]byte
97
84
if _ , err := rand .Read (randomBytes [:]); err != nil {
98
85
t .Fatal (err )
99
86
}
100
87
randomHostname := "newhostname" + hex .EncodeToString (randomBytes [:])
101
88
102
- h , err := New ( )
89
+ hostnameFile , err = os . OpenFile ( "/etc/hostname" , os . O_WRONLY | os . O_TRUNC , 0644 )
103
90
if err != nil {
104
91
t .Fatal (err )
105
92
}
106
-
107
- if err := h .SetStaticHostname (randomHostname , false ); err != nil {
108
- t .Fatal (err )
109
- }
93
+ defer hostnameFile .Close ()
94
+ // Restore the original hostname.
110
95
defer func () {
111
- if err := h . SetStaticHostname ( string ( originalHostname ), false ); err != nil {
96
+ if _ , err := hostnameFile . WriteString ( expectedHostname ); err != nil {
112
97
t .Fatal (err )
113
98
}
114
99
}()
115
100
101
+ if _ , err := hostnameFile .WriteString (randomHostname ); err != nil {
102
+ t .Fatal (err )
103
+ }
104
+
116
105
if hostname , err := h .StaticHostname (); err != nil {
117
106
t .Fatal (err )
118
107
} else if hostname != randomHostname {
0 commit comments