Skip to content

Commit c68bf12

Browse files
fix: edit test so that mock server creation is in a separate helper function
1 parent 21463a1 commit c68bf12

File tree

1 file changed

+30
-25
lines changed

1 file changed

+30
-25
lines changed

pkg/client_test.go

+30-25
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,35 @@ func assertEquality(t *testing.T, obj1 any, obj2 any) {
2222
}
2323
}
2424

25+
func mockServer(t *testing.T) *httptest.Server {
26+
t.Helper()
27+
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
28+
currentTime := time.Now()
29+
formattedTime := currentTime.Format(time.ANSIC)
30+
31+
if strings.Contains(r.Header.Get("content-type"), "text/plain") {
32+
33+
w.Header().Set("Content-Type", "text/plain")
34+
fmt.Fprint(w, formattedTime)
35+
36+
} else if strings.Contains(r.Header.Get("content-type"), "application/json") {
37+
38+
w.Header().Set("Content-Type", "application/json")
39+
40+
timeJson, err := json.Marshal(formattedTime)
41+
if err != nil {
42+
log.Fatalf("error converting to json: %v", err)
43+
}
44+
_, err = w.Write(timeJson)
45+
if err != nil {
46+
log.Fatalf("error writing data to response: %v", err)
47+
}
48+
} else {
49+
http.Error(w, http.StatusText(http.StatusUnsupportedMediaType), http.StatusUnsupportedMediaType)
50+
}
51+
}))
52+
}
53+
2554
func TestGetTime(t *testing.T) {
2655
formattedTime := time.Now().Format(time.ANSIC)
2756
expectedTime, err := time.Parse(time.ANSIC, formattedTime)
@@ -141,31 +170,7 @@ func TestGetTimeMock(t *testing.T) {
141170
}
142171
for _, testcase := range testcases {
143172
t.Run(testcase.name, func(t *testing.T) {
144-
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
145-
currentTime := time.Now()
146-
formattedTime := currentTime.Format(time.ANSIC)
147-
148-
if strings.Contains(r.Header.Get("content-type"), "text/plain") {
149-
150-
w.Header().Set("Content-Type", "text/plain")
151-
fmt.Fprint(w, formattedTime)
152-
153-
} else if strings.Contains(r.Header.Get("content-type"), "application/json") {
154-
155-
w.Header().Set("Content-Type", "application/json")
156-
157-
timeJson, err := json.Marshal(formattedTime)
158-
if err != nil {
159-
log.Fatalf("error converting to json: %v", err)
160-
}
161-
_, err = w.Write(timeJson)
162-
if err != nil {
163-
log.Fatalf("error writing data to response: %v", err)
164-
}
165-
} else {
166-
http.Error(w, http.StatusText(http.StatusUnsupportedMediaType), http.StatusUnsupportedMediaType)
167-
}
168-
}))
173+
mockServer := mockServer(t)
169174

170175
defer mockServer.Close()
171176

0 commit comments

Comments
 (0)