Skip to content

Commit f1c7144

Browse files
committed
test(cli): replace httptest.NewServer with RoundTripper mock in download tests
Avoids localhost port binding so tests pass in network-restricted sandboxes.
1 parent c3fdf55 commit f1c7144

1 file changed

Lines changed: 17 additions & 6 deletions

File tree

internal/cli/output_test.go

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,19 @@ import (
2222
syncpkg "github.com/openbootdotdev/openboot/internal/sync"
2323
)
2424

25+
// mockRoundTripper lets tests intercept HTTP calls without binding to any port.
26+
type mockRoundTripper struct{ handler http.Handler }
27+
28+
func (m *mockRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
29+
rec := httptest.NewRecorder()
30+
m.handler.ServeHTTP(rec, req)
31+
return rec.Result(), nil
32+
}
33+
34+
func mockHTTPClient(handler http.Handler) *http.Client {
35+
return &http.Client{Transport: &mockRoundTripper{handler: handler}}
36+
}
37+
2538
// captureStdout redirects os.Stdout, runs f, then restores it and returns
2639
// everything that was written.
2740
func captureStdout(t *testing.T, f func()) string {
@@ -713,24 +726,22 @@ func TestShowRestoreInfo_NoGitInfo_NoGitLine(t *testing.T) {
713726

714727
func TestDownloadSnapshotBytes_Success(t *testing.T) {
715728
payload := []byte(`{"version":1,"captured_at":"2025-01-01T00:00:00Z"}`)
716-
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
729+
client := mockHTTPClient(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
717730
w.WriteHeader(http.StatusOK)
718731
_, _ = w.Write(payload)
719732
}))
720-
defer srv.Close()
721733

722-
data, err := downloadSnapshotBytes(srv.URL, &http.Client{})
734+
data, err := downloadSnapshotBytes("https://openboot.dev/snap.json", client)
723735
require.NoError(t, err)
724736
assert.Equal(t, payload, data)
725737
}
726738

727739
func TestDownloadSnapshotBytes_Non200_ReturnsError(t *testing.T) {
728-
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
740+
client := mockHTTPClient(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
729741
w.WriteHeader(http.StatusNotFound)
730742
}))
731-
defer srv.Close()
732743

733-
_, err := downloadSnapshotBytes(srv.URL, &http.Client{})
744+
_, err := downloadSnapshotBytes("https://openboot.dev/snap.json", client)
734745
require.Error(t, err)
735746
assert.Contains(t, err.Error(), "HTTP 404")
736747
}

0 commit comments

Comments
 (0)