Replace flaky server for log level handler test. (#9822)

**What this PR does / why we need it**:
I've noticed that the `TestLevelHandler` were flaky because the code
wasn't waiting to the server to be running. Since the test is for a
handler it's much simpler to call it directly with a response recorder.

**Checklist**
- [x] Reviewed the
[`CONTRIBUTING.md`](https://github.com/grafana/loki/blob/main/CONTRIBUTING.md)
guide (**required**)
- [ ] Documentation added
- [x] Tests updated
- [ ] `CHANGELOG.md` updated
- [ ] If the change is worth mentioning in the release notes, add
`add-to-release-notes` label
- [ ] Changes that require user attention or interaction to upgrade are
documented in `docs/sources/upgrading/_index.md`
- [ ] For Helm chart changes bump the Helm chart version in
`production/helm/loki/Chart.yaml` and update
`production/helm/loki/CHANGELOG.md` and
`production/helm/loki/README.md`. [Example
PR](d10549e3ec)
pull/9823/head
Karsten Jeschkies 2 years ago committed by GitHub
parent 6a1f34f4f1
commit 125e168a91
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 28
      pkg/util/log/log_test.go

@ -3,6 +3,7 @@ package log
import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
@ -20,12 +21,6 @@ func TestLevelHandler(t *testing.T) {
baseLogger: log.NewLogfmtLogger(io.Discard),
}
// Start test http server
go func() {
err := http.ListenAndServe(":8080", LevelHandler(&lvl))
assert.NoError(t, err)
}()
testCases := []struct {
testName string
targetLogLevel string
@ -42,22 +37,25 @@ func TestLevelHandler(t *testing.T) {
for _, testCase := range testCases {
t.Run(testCase.testName, func(t *testing.T) {
var (
resp *http.Response
err error
req *http.Request
err error
)
if strings.HasPrefix(testCase.testName, "Get") {
resp, err = http.Get("http://localhost:8080/")
req, err = http.NewRequest("GET", "/", nil)
} else if strings.HasPrefix(testCase.testName, "Post") {
resp, err = http.PostForm("http://localhost:8080/", url.Values{"log_level": {testCase.targetLogLevel}})
form := url.Values{"log_level": {testCase.targetLogLevel}}
req, err = http.NewRequest("POST", "/", strings.NewReader(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
}
assert.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.JSONEq(t, testCase.expectedResponse, string(body))
assert.Equal(t, testCase.expectedStatusCode, resp.StatusCode)
rr := httptest.NewRecorder()
handler := LevelHandler(&lvl)
handler.ServeHTTP(rr, req)
assert.JSONEq(t, testCase.expectedResponse, rr.Body.String())
assert.Equal(t, testCase.expectedStatusCode, rr.Code)
assert.Equal(t, testCase.expectedLogLevel, lvl.String())
})
}

Loading…
Cancel
Save