MCPcopy Index your code
hub / github.com/jetify-com/devbox / TestSudoDevbox

Function TestSudoDevbox

internal/setup/setup_test.go:141–197  ·  view source on GitHub ↗

TestSudoDevbox uses sudo on the current test binary to recursively call itself as root. This test can only be run manually (because it needs sudo) but is still useful for testing after making any changes to the sudo code. - Within the test we check if os.Getuid() == 0 to act differently depending o

(t *testing.T)

Source from the content-addressed store, hash-verified

139// - The non-sudo version of the test looks for the same file to know if the
140// sudo worked.
141func TestSudoDevbox(t *testing.T) {
142 t.Skip("this test must be run manually because it requires sudo")
143
144 ctx := t.Context()
145 key := "test-sudo-devbox"
146 resultFile := key + "-result"
147
148 // Non-sudo process cleans up the result file.
149 os.Remove(resultFile)
150 t.Cleanup(func() {
151 if os.Getuid() != 0 {
152 os.Remove(resultFile)
153 }
154 })
155
156 task := &testTask{}
157 task.RunFunc = func(ctx context.Context) error {
158 ran, err := SudoDevbox(ctx, "-test.run", "^"+t.Name()+"$")
159 if ran || err != nil {
160 return err
161 }
162
163 // Create a result file to indicate to the non-sudo process that
164 // we ran as root successfully.
165 if os.Getuid() == 0 {
166 return os.WriteFile(resultFile, nil, 0o666)
167 }
168 err = fmt.Errorf("task.NeedsRun not running as root after calling SudoDevbox")
169 t.Error(err)
170 return err
171 }
172 task.NeedsRunFunc = func(ctx context.Context, lastRun RunInfo) bool {
173 if os.Getuid() == 0 {
174 t.Error("task.NeedsRun called in sudo process, but should only be called in user process")
175 }
176 return true
177 }
178
179 old := defaultPrompt
180 t.Cleanup(func() { defaultPrompt = old })
181 defaultPrompt = func(msg string) (response any, err error) {
182 if os.Getuid() == 0 {
183 err = fmt.Errorf("user prompted again while already running as sudo")
184 t.Error(err)
185 return false, err
186 }
187 return true, nil
188 }
189
190 err := ConfirmRun(ctx, key, task, "Allow sudo to run Devbox as root?")
191 if err != nil {
192 t.Error("got ConfirmRun error:", err)
193 }
194 if _, err := os.Stat(resultFile); err != nil {
195 t.Error("got missing sudo result file:", err)
196 }
197}
198

Callers

nothing calls this directly

Calls 4

SudoDevboxFunction · 0.85
ConfirmRunFunction · 0.85
RemoveMethod · 0.45
ErrorMethod · 0.45

Tested by

no test coverage detected