Skip to content

Commit

Permalink
feat(exp): add mockutil.Server helper (#543)
Browse files Browse the repository at this point in the history
This helper ensures that the wrapped test server will be closed at the
end of each test.
  • Loading branch information
jooola authored Oct 31, 2024
1 parent 01392cc commit fa1069b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
11 changes: 11 additions & 0 deletions hcloud/exp/mockutil/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package mockutil
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -83,3 +84,13 @@ func Handler(t *testing.T, requests []Request) http.HandlerFunc {
index++
})
}

// Server is a [httptest.Server] wrapping a [Handler] that closes itself at the end of the test.
func Server(t *testing.T, requests []Request) *httptest.Server {
t.Helper()

server := httptest.NewServer(Handler(t, requests))
t.Cleanup(server.Close)

return server
}
6 changes: 2 additions & 4 deletions hcloud/exp/mockutil/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"io"
"math/rand"
"net/http"
"net/http/httptest"
"strings"
"testing"

Expand All @@ -14,7 +13,7 @@ import (
)

func TestHandler(t *testing.T) {
server := httptest.NewServer(Handler(t, []Request{
server := Server(t, []Request{
{
Method: "GET", Path: "/",
Status: 200,
Expand All @@ -40,8 +39,7 @@ func TestHandler(t *testing.T) {
},
Status: 200,
},
}))
defer server.Close()
})

// Request 1
resp, err := http.Get(server.URL)
Expand Down

0 comments on commit fa1069b

Please sign in to comment.