chore(linters): Fix findings found by `testifylint`: `go-require` for handlers for `plugins/inputs/[a-m]` (#16076)

This commit is contained in:
Paweł Żak 2024-10-28 13:58:03 +01:00 committed by GitHub
parent 13d053f917
commit 7c9d5e52b0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
26 changed files with 653 additions and 214 deletions

View File

@ -149,16 +149,25 @@ func TestURLs(t *testing.T) {
switch r.URL.Path { switch r.URL.Path {
case "/admin/xml/queues.jsp": case "/admin/xml/queues.jsp":
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("<queues></queues>")) if _, err := w.Write([]byte("<queues></queues>")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case "/admin/xml/topics.jsp": case "/admin/xml/topics.jsp":
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("<topics></topics>")) if _, err := w.Write([]byte("<topics></topics>")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case "/admin/xml/subscribers.jsp": case "/admin/xml/subscribers.jsp":
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("<subscribers></subscribers>")) if _, err := w.Write([]byte("<subscribers></subscribers>")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
default: default:
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
t.Fatalf("unexpected path: %s", r.URL.Path) t.Fatalf("unexpected path: %s", r.URL.Path)

View File

@ -32,8 +32,11 @@ Scoreboard: WW_____W_RW_R_W__RRR____WR_W___WW________W_WW_W_____R__R_WR__WRWR_RR
func TestHTTPApache(t *testing.T) { func TestHTTPApache(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := fmt.Fprintln(w, apacheStatus) if _, err := fmt.Fprintln(w, apacheStatus); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
defer ts.Close() defer ts.Close()

View File

@ -248,11 +248,22 @@ func TestBasicAuth(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, _ := r.BasicAuth() username, password, _ := r.BasicAuth()
require.Equal(t, tt.username, username) if username != tt.username {
require.Equal(t, tt.password, password) w.WriteHeader(http.StatusInternalServerError)
t.Errorf("Not equal, expected: %q, actual: %q", tt.username, username)
return
}
if password != tt.password {
w.WriteHeader(http.StatusInternalServerError)
t.Errorf("Not equal, expected: %q, actual: %q", tt.password, password)
return
}
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("{}")) if _, err := w.Write([]byte("{}")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
}) })
var acc testutil.Accumulator var acc testutil.Accumulator

View File

@ -29,13 +29,22 @@ func Test_BeatStats(t *testing.T) {
case suffixStats: case suffixStats:
jsonFilePath = "beat6_stats.json" jsonFilePath = "beat6_stats.json"
default: default:
require.FailNow(t, "cannot handle request") w.WriteHeader(http.StatusInternalServerError)
t.Errorf("Cannot handle request")
return
} }
data, err := os.ReadFile(jsonFilePath) data, err := os.ReadFile(jsonFilePath)
require.NoErrorf(t, err, "could not read from data file %s", jsonFilePath) if err != nil {
_, err = w.Write(data) w.WriteHeader(http.StatusInternalServerError)
require.NoError(t, err, "could not write data") t.Errorf("Could not read from data file %q: %v", jsonFilePath, err)
return
}
if _, err = w.Write(data); err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
requestURL, err := url.Parse(beatTest.URL) requestURL, err := url.Parse(beatTest.URL)
require.NoErrorf(t, err, "can't parse URL %s", beatTest.URL) require.NoErrorf(t, err, "can't parse URL %s", beatTest.URL)
@ -173,18 +182,42 @@ func Test_BeatRequest(t *testing.T) {
case suffixStats: case suffixStats:
jsonFilePath = "beat6_stats.json" jsonFilePath = "beat6_stats.json"
default: default:
require.FailNow(t, "cannot handle request") w.WriteHeader(http.StatusInternalServerError)
t.Errorf("Cannot handle request")
return
} }
data, err := os.ReadFile(jsonFilePath) data, err := os.ReadFile(jsonFilePath)
require.NoErrorf(t, err, "could not read from data file %s", jsonFilePath) if err != nil {
require.Equal(t, "beat.test.local", request.Host) w.WriteHeader(http.StatusInternalServerError)
require.Equal(t, "POST", request.Method) t.Errorf("Could not read from data file %q: %v", jsonFilePath, err)
require.Equal(t, "Basic YWRtaW46UFdE", request.Header.Get("Authorization")) return
require.Equal(t, "test-value", request.Header.Get("X-Test")) }
if request.Host != "beat.test.local" {
_, err = w.Write(data) w.WriteHeader(http.StatusInternalServerError)
require.NoError(t, err, "could not write data") t.Errorf("Not equal, expected: %q, actual: %q", "beat.test.local", request.Host)
return
}
if request.Method != "POST" {
w.WriteHeader(http.StatusInternalServerError)
t.Errorf("Not equal, expected: %q, actual: %q", "POST", request.Method)
return
}
if request.Header.Get("Authorization") != "Basic YWRtaW46UFdE" {
w.WriteHeader(http.StatusInternalServerError)
t.Errorf("Not equal, expected: %q, actual: %q", "Basic YWRtaW46UFdE", request.Header.Get("Authorization"))
return
}
if request.Header.Get("X-Test") != "test-value" {
w.WriteHeader(http.StatusInternalServerError)
t.Errorf("Not equal, expected: %q, actual: %q", "test-value", request.Header.Get("X-Test"))
return
}
if _, err = w.Write(data); err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
requestURL, err := url.Parse(beatTest.URL) requestURL, err := url.Parse(beatTest.URL)

View File

@ -74,7 +74,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "system.events"): case strings.Contains(query, "system.events"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -91,7 +95,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "system.metrics"): case strings.Contains(query, "system.metrics"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -108,7 +116,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "system.asynchronous_metrics"): case strings.Contains(query, "system.asynchronous_metrics"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -125,7 +137,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "zk_exists"): case strings.Contains(query, "zk_exists"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -136,7 +152,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "zk_root_nodes"): case strings.Contains(query, "zk_root_nodes"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -147,7 +167,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "replication_queue_exists"): case strings.Contains(query, "replication_queue_exists"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -158,7 +182,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "replication_too_many_tries_replicas"): case strings.Contains(query, "replication_too_many_tries_replicas"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -171,7 +199,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "system.detached_parts"): case strings.Contains(query, "system.detached_parts"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -182,7 +214,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "system.dictionaries"): case strings.Contains(query, "system.dictionaries"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -197,7 +233,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "system.mutations"): case strings.Contains(query, "system.mutations"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -212,7 +252,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "system.disks"): case strings.Contains(query, "system.disks"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -229,7 +273,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "system.processes"): case strings.Contains(query, "system.processes"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -258,7 +306,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "text_log_exists"): case strings.Contains(query, "text_log_exists"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -269,7 +321,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "system.text_log"): case strings.Contains(query, "system.text_log"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -298,7 +354,11 @@ func TestGather(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} }
})) }))
ch = &ClickHouse{ ch = &ClickHouse{
@ -451,7 +511,11 @@ func TestGatherWithSomeTablesNotExists(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "replication_queue_exists"): case strings.Contains(query, "replication_queue_exists"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -462,7 +526,11 @@ func TestGatherWithSomeTablesNotExists(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "text_log_exists"): case strings.Contains(query, "text_log_exists"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -473,7 +541,11 @@ func TestGatherWithSomeTablesNotExists(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} }
})) }))
ch = &ClickHouse{ ch = &ClickHouse{
@ -509,7 +581,11 @@ func TestGatherClickhouseCloud(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case strings.Contains(query, "zk_root_nodes"): case strings.Contains(query, "zk_root_nodes"):
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct { Data: []struct {
@ -520,7 +596,11 @@ func TestGatherClickhouseCloud(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} }
})) }))
defer ts.Close() defer ts.Close()
@ -545,7 +625,11 @@ func TestWrongJSONMarshalling(t *testing.T) {
err := enc.Encode(result{ err := enc.Encode(result{
Data: []struct{}{}, Data: []struct{}{},
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
ch = &ClickHouse{ ch = &ClickHouse{
Servers: []string{ Servers: []string{
@ -631,7 +715,11 @@ func TestAutoDiscovery(t *testing.T) {
}, },
}, },
}) })
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} }
})) }))
ch = &ClickHouse{ ch = &ClickHouse{

View File

@ -75,9 +75,16 @@ func TestConsulStats(t *testing.T) {
if r.RequestURI == "/v1/agent/metrics" { if r.RequestURI == "/v1/agent/metrics" {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
responseKeyMetrics, err := os.ReadFile("testdata/response_key_metrics.json") responseKeyMetrics, err := os.ReadFile("testdata/response_key_metrics.json")
require.NoError(t, err) if err != nil {
_, err = fmt.Fprintln(w, string(responseKeyMetrics)) w.WriteHeader(http.StatusInternalServerError)
require.NoError(t, err) t.Error(err)
return
}
if _, err = fmt.Fprintln(w, string(responseKeyMetrics)); err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} }
})) }))
defer ts.Close() defer ts.Close()

View File

@ -17,17 +17,29 @@ func TestGatherServer(t *testing.T) {
bucket := "blastro-df" bucket := "blastro-df"
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/pools" { if r.URL.Path == "/pools" {
_, err := w.Write(readJSON(t, "testdata/pools_response.json")) if _, err := w.Write(readJSON(t, "testdata/pools_response.json")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else if r.URL.Path == "/pools/default" { } else if r.URL.Path == "/pools/default" {
_, err := w.Write(readJSON(t, "testdata/pools_default_response.json")) if _, err := w.Write(readJSON(t, "testdata/pools_default_response.json")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else if r.URL.Path == "/pools/default/buckets" { } else if r.URL.Path == "/pools/default/buckets" {
_, err := w.Write(readJSON(t, "testdata/bucket_response.json")) if _, err := w.Write(readJSON(t, "testdata/bucket_response.json")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else if r.URL.Path == "/pools/default/buckets/"+bucket+"/stats" { } else if r.URL.Path == "/pools/default/buckets/"+bucket+"/stats" {
_, err := w.Write(readJSON(t, "testdata/bucket_stats_response.json")) if _, err := w.Write(readJSON(t, "testdata/bucket_stats_response.json")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
@ -116,8 +128,11 @@ func TestGatherDetailedBucketMetrics(t *testing.T) {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/pools/default/buckets/"+bucket+"/stats" || r.URL.Path == "/pools/default/buckets/"+bucket+"/nodes/"+node+"/stats" { if r.URL.Path == "/pools/default/buckets/"+bucket+"/stats" || r.URL.Path == "/pools/default/buckets/"+bucket+"/nodes/"+node+"/stats" {
_, err := w.Write(test.response) if _, err := w.Write(test.response); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
@ -153,14 +168,23 @@ func TestGatherDetailedBucketMetrics(t *testing.T) {
func TestGatherNodeOnly(t *testing.T) { func TestGatherNodeOnly(t *testing.T) {
faker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { faker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/pools" { if r.URL.Path == "/pools" {
_, err := w.Write(readJSON(t, "testdata/pools_response.json")) if _, err := w.Write(readJSON(t, "testdata/pools_response.json")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else if r.URL.Path == "/pools/default" { } else if r.URL.Path == "/pools/default" {
_, err := w.Write(readJSON(t, "testdata/pools_default_response.json")) if _, err := w.Write(readJSON(t, "testdata/pools_default_response.json")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else if r.URL.Path == "/pools/default/buckets" { } else if r.URL.Path == "/pools/default/buckets" {
_, err := w.Write(readJSON(t, "testdata/bucket_response.json")) if _, err := w.Write(readJSON(t, "testdata/bucket_response.json")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
@ -183,17 +207,29 @@ func TestGatherFailover(t *testing.T) {
faker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { faker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path { switch r.URL.Path {
case "/pools": case "/pools":
_, err := w.Write(readJSON(t, "testdata/pools_response.json")) if _, err := w.Write(readJSON(t, "testdata/pools_response.json")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case "/pools/default": case "/pools/default":
_, err := w.Write(readJSON(t, "testdata/pools_default_response.json")) if _, err := w.Write(readJSON(t, "testdata/pools_default_response.json")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case "/pools/default/buckets": case "/pools/default/buckets":
_, err := w.Write(readJSON(t, "testdata/bucket_response.json")) if _, err := w.Write(readJSON(t, "testdata/bucket_response.json")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case "/settings/autoFailover": case "/settings/autoFailover":
_, err := w.Write(readJSON(t, "testdata/settings_autofailover.json")) if _, err := w.Write(readJSON(t, "testdata/settings_autofailover.json")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
default: default:
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }

View File

@ -305,8 +305,11 @@ func TestBasic(t *testing.T) {
` `
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/_stats" { if r.URL.Path == "/_stats" {
_, err := w.Write([]byte(js)) if _, err := w.Write([]byte(js)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }

View File

@ -36,8 +36,11 @@ func getMultiEntries() bool {
func TestCtrlXCreateSubscriptionBasic(t *testing.T) { func TestCtrlXCreateSubscriptionBasic(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusCreated) w.WriteHeader(http.StatusCreated)
_, err := w.Write([]byte("201 created")) if _, err := w.Write([]byte("201 created")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
defer server.Close() defer server.Close()
@ -80,8 +83,11 @@ func TestCtrlXCreateSubscriptionDriven(t *testing.T) {
t.Run(test.res, func(t *testing.T) { t.Run(test.res, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(test.status) w.WriteHeader(test.status)
_, err := w.Write([]byte(test.res)) if _, err := w.Write([]byte(test.res)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
defer server.Close() defer server.Close()
subs := make([]subscription, 0) subs := make([]subscription, 0)
@ -118,45 +124,75 @@ func newServer(t *testing.T) *httptest.Server {
mux := http.NewServeMux() mux := http.NewServeMux()
// Handle request to fetch token // Handle request to fetch token
mux.HandleFunc("/identity-manager/api/v2/auth/token", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/identity-manager/api/v2/auth/token", func(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write([]byte("{\"access_token\": \"eyJhbGciOiJIU.xxx.xxx\", \"token_type\":\"Bearer\"}")) if _, err := w.Write([]byte("{\"access_token\": \"eyJhbGciOiJIU.xxx.xxx\", \"token_type\":\"Bearer\"}")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
}) })
// Handle request to validate token // Handle request to validate token
mux.HandleFunc("/identity-manager/api/v2/auth/token/validity", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/identity-manager/api/v2/auth/token/validity", func(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write([]byte("{\"valid\": \"true\"}")) if _, err := w.Write([]byte("{\"valid\": \"true\"}")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
}) })
// Handle request to create subscription // Handle request to create subscription
mux.HandleFunc(path, func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc(path, func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusCreated) w.WriteHeader(http.StatusCreated)
_, err := w.Write([]byte("201 created")) if _, err := w.Write([]byte("201 created")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
}) })
// Handle request to fetch sse data // Handle request to fetch sse data
mux.HandleFunc(path+"/", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc(path+"/", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet { if r.Method == http.MethodGet {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("event: update\n")) if _, err := w.Write([]byte("event: update\n")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
_, err = w.Write([]byte("id: 12345\n")) t.Error(err)
require.NoError(t, err) return
}
if _, err := w.Write([]byte("id: 12345\n")); err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
if getMultiEntries() { if getMultiEntries() {
data := "data: {\n" data := "data: {\n"
_, err = w.Write([]byte(data)) if _, err := w.Write([]byte(data)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
data = "data: \"node\":\"plc/app/Application/sym/PLC_PRG/counter\", \"timestamp\":132669450604571037,\"type\":\"double\",\"value\":44.0\n" data = "data: \"node\":\"plc/app/Application/sym/PLC_PRG/counter\", \"timestamp\":132669450604571037,\"type\":\"double\",\"value\":44.0\n"
_, err = w.Write([]byte(data)) if _, err := w.Write([]byte(data)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
data = "data: }\n" data = "data: }\n"
_, err = w.Write([]byte(data)) if _, err := w.Write([]byte(data)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
data := "data: {\"node\":\"plc/app/Application/sym/PLC_PRG/counter\", \"timestamp\":132669450604571037,\"type\":\"double\",\"value\":43.0}\n" data := "data: {\"node\":\"plc/app/Application/sym/PLC_PRG/counter\", \"timestamp\":132669450604571037,\"type\":\"double\",\"value\":43.0}\n"
_, err = w.Write([]byte(data)) if _, err := w.Write([]byte(data)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
}
if _, err := w.Write([]byte("\n")); err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
} }
_, err = w.Write([]byte("\n"))
require.NoError(t, err)
} }
}) })
return httptest.NewServer(mux) return httptest.NewServer(mux)

View File

@ -42,20 +42,35 @@ func TestJSONSuccess(t *testing.T) {
switch r.URL.Path { switch r.URL.Path {
case "/api/sections": case "/api/sections":
content, err := os.ReadFile(path.Join("testdata", "sections.json")) content, err := os.ReadFile(path.Join("testdata", "sections.json"))
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
payload = string(content) payload = string(content)
case "/api/rooms": case "/api/rooms":
content, err := os.ReadFile(path.Join("testdata", "rooms.json")) content, err := os.ReadFile(path.Join("testdata", "rooms.json"))
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
payload = string(content) payload = string(content)
case "/api/devices": case "/api/devices":
content, err := os.ReadFile(path.Join("testdata", "device_hc2.json")) content, err := os.ReadFile(path.Join("testdata", "device_hc2.json"))
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
payload = string(content) payload = string(content)
} }
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := fmt.Fprintln(w, payload) if _, err := fmt.Fprintln(w, payload); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
defer ts.Close() defer ts.Close()
@ -158,20 +173,35 @@ func TestHC3JSON(t *testing.T) {
switch r.URL.Path { switch r.URL.Path {
case "/api/sections": case "/api/sections":
content, err := os.ReadFile(path.Join("testdata", "sections.json")) content, err := os.ReadFile(path.Join("testdata", "sections.json"))
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
payload = string(content) payload = string(content)
case "/api/rooms": case "/api/rooms":
content, err := os.ReadFile(path.Join("testdata", "rooms.json")) content, err := os.ReadFile(path.Join("testdata", "rooms.json"))
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
payload = string(content) payload = string(content)
case "/api/devices": case "/api/devices":
content, err := os.ReadFile(path.Join("testdata", "device_hc3.json")) content, err := os.ReadFile(path.Join("testdata", "device_hc3.json"))
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
payload = string(content) payload = string(content)
} }
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := fmt.Fprintln(w, payload) if _, err := fmt.Fprintln(w, payload); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
defer ts.Close() defer ts.Close()

View File

@ -17,8 +17,11 @@ func TestFireboard(t *testing.T) {
// Create a test server with the const response JSON // Create a test server with the const response JSON
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := fmt.Fprintln(w, response) if _, err := fmt.Fprintln(w, response); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
defer ts.Close() defer ts.Close()

View File

@ -171,8 +171,11 @@ func Test_Gather(t *testing.T) {
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, err := fmt.Fprintf(w, "%s", string(sampleJSON)) if _, err := fmt.Fprintf(w, "%s", sampleJSON); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
requestURL, err := url.Parse(fluentdTest.Endpoint) requestURL, err := url.Parse(fluentdTest.Endpoint)

View File

@ -204,12 +204,18 @@ func startGCSServer(t *testing.T) *httptest.Server {
switch r.URL.Path { switch r.URL.Path {
case "/test-bucket/prefix/offset.json": case "/test-bucket/prefix/offset.json":
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte(currentOffSetKey)) if _, err := w.Write([]byte(currentOffSetKey)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
case "/test-bucket/prefix/offset-key.json": case "/test-bucket/prefix/offset-key.json":
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("{\"offSet\":\"offsetfile\"}")) if _, err := w.Write([]byte("{\"offSet\":\"offsetfile\"}")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
default: default:
failPath(r.URL.Path, t, w) failPath(r.URL.Path, t, w)
} }
@ -265,8 +271,11 @@ func startMultipleItemGCSServer(t *testing.T) *httptest.Server {
if data, err := json.Marshal(objListing); err == nil { if data, err := json.Marshal(objListing); err == nil {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := w.Write(data) if _, err := w.Write(data); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
t.Fatalf("unexpected path: %s", r.URL.Path) t.Fatalf("unexpected path: %s", r.URL.Path)
@ -314,17 +323,28 @@ func stateFullGCSServer(t *testing.T) *httptest.Server {
if data, err := json.Marshal(objListing); err == nil { if data, err := json.Marshal(objListing); err == nil {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := w.Write(data) if _, err := w.Write(data); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
failPath(r.URL.Path, t, w) failPath(r.URL.Path, t, w)
} }
case "/upload/storage/v1/b/test-iteration-bucket/o": case "/upload/storage/v1/b/test-iteration-bucket/o":
_, params, err := mime.ParseMediaType(r.Header["Content-Type"][0]) _, params, err := mime.ParseMediaType(r.Header["Content-Type"][0])
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
boundary := params["boundary"] boundary := params["boundary"]
currentOffSetKey, err = fetchJSON(t, boundary, r.Body) currentOffSetKey, err = fetchJSON(t, boundary, r.Body)
require.NoError(t, err) if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
default: default:
serveBlobs(t, w, r.URL.Path, currentOffSetKey) serveBlobs(t, w, r.URL.Path, currentOffSetKey)
} }

View File

@ -49,18 +49,27 @@ func TestHaproxyGeneratesMetricsWithAuthentication(t *testing.T) {
username, password, ok := r.BasicAuth() username, password, ok := r.BasicAuth()
if !ok { if !ok {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
_, err := fmt.Fprint(w, "Unauthorized") if _, err := fmt.Fprint(w, "Unauthorized"); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
return return
} }
if username == "user" && password == "password" { if username == "user" && password == "password" {
_, err := fmt.Fprint(w, string(csvOutputSample)) if _, err := fmt.Fprint(w, string(csvOutputSample)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
_, err := fmt.Fprint(w, "Unauthorized") if _, err := fmt.Fprint(w, "Unauthorized"); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} }
})) }))
defer ts.Close() defer ts.Close()
@ -96,8 +105,11 @@ func TestHaproxyGeneratesMetricsWithAuthentication(t *testing.T) {
func TestHaproxyGeneratesMetricsWithoutAuthentication(t *testing.T) { func TestHaproxyGeneratesMetricsWithoutAuthentication(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, err := fmt.Fprint(w, string(csvOutputSample)) if _, err := fmt.Fprint(w, string(csvOutputSample)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
defer ts.Close() defer ts.Close()
@ -217,8 +229,11 @@ func TestHaproxyDefaultGetFromLocalhost(t *testing.T) {
func TestHaproxyKeepFieldNames(t *testing.T) { func TestHaproxyKeepFieldNames(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, err := fmt.Fprint(w, string(csvOutputSample)) if _, err := fmt.Fprint(w, string(csvOutputSample)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
defer ts.Close() defer ts.Close()

View File

@ -32,8 +32,11 @@ import (
func TestHTTPWithJSONFormat(t *testing.T) { func TestHTTPWithJSONFormat(t *testing.T) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" { if r.URL.Path == "/endpoint" {
_, err := w.Write([]byte(simpleJSON)) if _, err := w.Write([]byte(simpleJSON)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
@ -73,8 +76,11 @@ func TestHTTPHeaders(t *testing.T) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" { if r.URL.Path == "/endpoint" {
if r.Header.Get(header) == headerValue { if r.Header.Get(header) == headerValue {
_, err := w.Write([]byte(simpleJSON)) if _, err := w.Write([]byte(simpleJSON)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusForbidden) w.WriteHeader(http.StatusForbidden)
} }
@ -107,8 +113,11 @@ func TestHTTPContentLengthHeader(t *testing.T) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" { if r.URL.Path == "/endpoint" {
if r.Header.Get("Content-Length") != "" { if r.Header.Get("Content-Length") != "" {
_, err := w.Write([]byte(simpleJSON)) if _, err := w.Write([]byte(simpleJSON)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusForbidden) w.WriteHeader(http.StatusForbidden)
} }
@ -408,8 +417,11 @@ func TestOAuthClientCredentialsGrant(t *testing.T) {
func TestHTTPWithCSVFormat(t *testing.T) { func TestHTTPWithCSVFormat(t *testing.T) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" { if r.URL.Path == "/endpoint" {
_, err := w.Write([]byte(simpleCSVWithHeader)) if _, err := w.Write([]byte(simpleCSVWithHeader)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
@ -466,8 +478,11 @@ func TestConnectionOverUnixSocket(t *testing.T) {
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/data" { if r.URL.Path == "/data" {
w.Header().Set("Content-Type", "text/csv") w.Header().Set("Content-Type", "text/csv")
_, err := w.Write([]byte(simpleCSVWithHeader)) if _, err := w.Write([]byte(simpleCSVWithHeader)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }

View File

@ -170,11 +170,21 @@ func checkOutput(t *testing.T, acc *testutil.Accumulator, presentFields, present
func TestHeaders(t *testing.T) { func TestHeaders(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cHeader := r.Header.Get("Content-Type") if r.Host != "Hello" {
uaHeader := r.Header.Get("User-Agent") w.WriteHeader(http.StatusInternalServerError)
require.Equal(t, "Hello", r.Host) t.Errorf("Not equal, expected: %q, actual: %q", "Hello", r.Host)
require.Equal(t, "application/json", cHeader) return
require.Equal(t, internal.ProductToken(), uaHeader) }
if cHeader := r.Header.Get("Content-Type"); cHeader != "application/json" {
w.WriteHeader(http.StatusInternalServerError)
t.Errorf("Not equal, expected: %q, actual: %q", "application/json", cHeader)
return
}
if uaHeader := r.Header.Get("User-Agent"); uaHeader != internal.ProductToken() {
w.WriteHeader(http.StatusInternalServerError)
t.Errorf("Not equal, expected: %q, actual: %q", internal.ProductToken(), uaHeader)
return
}
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
})) }))
defer ts.Close() defer ts.Close()
@ -1115,8 +1125,11 @@ func TestRedirect(t *testing.T) {
ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Add("Location", "http://example.org") w.Header().Add("Location", "http://example.org")
w.WriteHeader(http.StatusMovedPermanently) w.WriteHeader(http.StatusMovedPermanently)
_, err := w.Write([]byte("test")) if _, err := w.Write([]byte("test")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
}) })
h := &HTTPResponse{ h := &HTTPResponse{
@ -1158,8 +1171,11 @@ func TestRedirect(t *testing.T) {
func TestBasicAuth(t *testing.T) { func TestBasicAuth(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
aHeader := r.Header.Get("Authorization") if aHeader := r.Header.Get("Authorization"); aHeader != "Basic bWU6bXlwYXNzd29yZA==" {
require.Equal(t, "Basic bWU6bXlwYXNzd29yZA==", aHeader) w.WriteHeader(http.StatusInternalServerError)
t.Errorf("Not equal, expected: %q, actual: %q", "Basic bWU6bXlwYXNzd29yZA==", aHeader)
return
}
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
})) }))
defer ts.Close() defer ts.Close()
@ -1336,7 +1352,11 @@ func TestStatusCodeAndStringMatchFail(t *testing.T) {
func TestSNI(t *testing.T) { func TestSNI(t *testing.T) {
ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, "super-special-hostname.example.com", r.TLS.ServerName) if r.TLS.ServerName != "super-special-hostname.example.com" {
w.WriteHeader(http.StatusInternalServerError)
t.Errorf("Not equal, expected: %q, actual: %q", "super-special-hostname.example.com", r.TLS.ServerName)
return
}
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
})) }))
defer ts.Close() defer ts.Close()

View File

@ -70,8 +70,11 @@ func TestGatherServicesStatus(t *testing.T) {
if r.URL.Path == "/v1/objects/services" { if r.URL.Path == "/v1/objects/services" {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, err := w.Write([]byte(icinga2ServiceResponse)) if _, err := w.Write([]byte(icinga2ServiceResponse)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
t.Logf("Req: %s %s\n", r.Host, r.URL.Path) t.Logf("Req: %s %s\n", r.Host, r.URL.Path)
@ -133,8 +136,11 @@ func TestGatherHostsStatus(t *testing.T) {
if r.URL.Path == "/v1/objects/hosts" { if r.URL.Path == "/v1/objects/hosts" {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, err := w.Write([]byte(icinga2HostResponse)) if _, err := w.Write([]byte(icinga2HostResponse)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
t.Logf("Req: %s %s\n", r.Host, r.URL.Path) t.Logf("Req: %s %s\n", r.Host, r.URL.Path)
@ -192,8 +198,11 @@ func TestGatherStatusCIB(t *testing.T) {
if r.URL.Path == "/v1/status/CIB" { if r.URL.Path == "/v1/status/CIB" {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, err := w.Write([]byte(icinga2StatusCIB)) if _, err := w.Write([]byte(icinga2StatusCIB)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
t.Logf("Req: %s %s\n", r.Host, r.URL.Path) t.Logf("Req: %s %s\n", r.Host, r.URL.Path)
@ -262,8 +271,11 @@ func TestGatherStatusPgsql(t *testing.T) {
if r.URL.Path == "/v1/status/IdoPgsqlConnection" { if r.URL.Path == "/v1/status/IdoPgsqlConnection" {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, err := w.Write([]byte(icinga2StatusPgsql)) if _, err := w.Write([]byte(icinga2StatusPgsql)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
t.Logf("Req: %s %s\n", r.Host, r.URL.Path) t.Logf("Req: %s %s\n", r.Host, r.URL.Path)

View File

@ -17,8 +17,11 @@ import (
func TestBasic(t *testing.T) { func TestBasic(t *testing.T) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" { if r.URL.Path == "/endpoint" {
_, err := w.Write([]byte(basicJSON)) if _, err := w.Write([]byte(basicJSON)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
@ -68,8 +71,11 @@ func TestInfluxDB(t *testing.T) {
fakeInfluxServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fakeInfluxServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" { if r.URL.Path == "/endpoint" {
_, err := w.Write(influxReturn) if _, err := w.Write(influxReturn); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
@ -140,8 +146,11 @@ func TestInfluxDB2(t *testing.T) {
fakeInfluxServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fakeInfluxServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" { if r.URL.Path == "/endpoint" {
_, err := w.Write(influxReturn2) if _, err := w.Write(influxReturn2); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
@ -180,8 +189,11 @@ func TestCloud1(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" { if r.URL.Path == "/endpoint" {
_, err := w.Write(input) if _, err := w.Write(input); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
@ -215,8 +227,11 @@ func TestCloud1(t *testing.T) {
func TestErrorHandling(t *testing.T) { func TestErrorHandling(t *testing.T) {
badServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { badServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" { if r.URL.Path == "/endpoint" {
_, err := w.Write([]byte("not json")) if _, err := w.Write([]byte("not json")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
@ -234,8 +249,11 @@ func TestErrorHandling(t *testing.T) {
func TestErrorHandling404(t *testing.T) { func TestErrorHandling404(t *testing.T) {
badServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { badServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" { if r.URL.Path == "/endpoint" {
_, err := w.Write([]byte(basicJSON)) if _, err := w.Write([]byte(basicJSON)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
@ -253,8 +271,11 @@ func TestErrorHandling404(t *testing.T) {
func TestErrorResponse(t *testing.T) { func TestErrorResponse(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
_, err := w.Write([]byte(`{"error": "unable to parse authentication credentials"}`)) if _, err := w.Write([]byte(`{"error": "unable to parse authentication credentials"}`)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
defer ts.Close() defer ts.Close()

View File

@ -628,8 +628,16 @@ func TestJolokia2_ClientAuthRequest(t *testing.T) {
username, password, _ = r.BasicAuth() username, password, _ = r.BasicAuth()
body, err := io.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
require.NoError(t, err) if err != nil {
require.NoError(t, json.Unmarshal(body, &requests)) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
if err := json.Unmarshal(body, &requests); err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
})) }))

View File

@ -85,11 +85,24 @@ func TestJolokia2_ClientProxyAuthRequest(t *testing.T) {
username, password, _ = r.BasicAuth() username, password, _ = r.BasicAuth()
body, err := io.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
require.NoError(t, err) if err != nil {
require.NoError(t, json.Unmarshal(body, &requests)) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
if err := json.Unmarshal(body, &requests); err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err = fmt.Fprintf(w, "[]") if _, err = fmt.Fprintf(w, "[]"); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
defer server.Close() defer server.Close()

View File

@ -18,8 +18,11 @@ func TestKapacitor(t *testing.T) {
fakeInfluxServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fakeInfluxServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" { if r.URL.Path == "/endpoint" {
_, err := w.Write(kapacitorReturn) if _, err := w.Write(kapacitorReturn); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
@ -80,8 +83,11 @@ func TestKapacitor(t *testing.T) {
func TestMissingStats(t *testing.T) { func TestMissingStats(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write([]byte(`{}`)) if _, err := w.Write([]byte(`{}`)); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
defer server.Close() defer server.Close()
@ -99,8 +105,11 @@ func TestMissingStats(t *testing.T) {
func TestErrorHandling(t *testing.T) { func TestErrorHandling(t *testing.T) {
badServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { badServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" { if r.URL.Path == "/endpoint" {
_, err := w.Write([]byte("not json")) if _, err := w.Write([]byte("not json")); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }

View File

@ -15,13 +15,19 @@ func TestKubernetesStats(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.RequestURI == "/stats/summary" { if r.RequestURI == "/stats/summary" {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := fmt.Fprintln(w, responseStatsSummery) if _, err := fmt.Fprintln(w, responseStatsSummery); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} }
if r.RequestURI == "/pods" { if r.RequestURI == "/pods" {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := fmt.Fprintln(w, responsePods) if _, err := fmt.Fprintln(w, responsePods); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} }
})) }))
defer ts.Close() defer ts.Close()

View File

@ -28,8 +28,11 @@ var (
func Test_Logstash5GatherProcessStats(test *testing.T) { func Test_Logstash5GatherProcessStats(test *testing.T) {
fakeServer := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { fakeServer := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
writer.Header().Set("Content-Type", "application/json") writer.Header().Set("Content-Type", "application/json")
_, err := fmt.Fprintf(writer, "%s", string(logstash5ProcessJSON)) if _, err := fmt.Fprintf(writer, "%s", logstash5ProcessJSON); err != nil {
require.NoError(test, err) writer.WriteHeader(http.StatusInternalServerError)
test.Error(err)
return
}
})) }))
requestURL, err := url.Parse(logstashTest.URL) requestURL, err := url.Parse(logstashTest.URL)
require.NoErrorf(test, err, "Can't connect to: %s", logstashTest.URL) require.NoErrorf(test, err, "Can't connect to: %s", logstashTest.URL)
@ -73,8 +76,11 @@ func Test_Logstash5GatherProcessStats(test *testing.T) {
func Test_Logstash6GatherProcessStats(test *testing.T) { func Test_Logstash6GatherProcessStats(test *testing.T) {
fakeServer := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { fakeServer := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
writer.Header().Set("Content-Type", "application/json") writer.Header().Set("Content-Type", "application/json")
_, err := fmt.Fprintf(writer, "%s", string(logstash6ProcessJSON)) if _, err := fmt.Fprintf(writer, "%s", logstash6ProcessJSON); err != nil {
require.NoError(test, err) writer.WriteHeader(http.StatusInternalServerError)
test.Error(err)
return
}
})) }))
requestURL, err := url.Parse(logstashTest.URL) requestURL, err := url.Parse(logstashTest.URL)
require.NoErrorf(test, err, "Can't connect to: %s", logstashTest.URL) require.NoErrorf(test, err, "Can't connect to: %s", logstashTest.URL)
@ -119,8 +125,11 @@ func Test_Logstash5GatherPipelineStats(test *testing.T) {
logstash5accPipelineStats.SetDebug(true) logstash5accPipelineStats.SetDebug(true)
fakeServer := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { fakeServer := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
writer.Header().Set("Content-Type", "application/json") writer.Header().Set("Content-Type", "application/json")
_, err := fmt.Fprintf(writer, "%s", string(logstash5PipelineJSON)) if _, err := fmt.Fprintf(writer, "%s", logstash5PipelineJSON); err != nil {
require.NoError(test, err) writer.WriteHeader(http.StatusInternalServerError)
test.Error(err)
return
}
})) }))
requestURL, err := url.Parse(logstashTest.URL) requestURL, err := url.Parse(logstashTest.URL)
require.NoErrorf(test, err, "Can't connect to: %s", logstashTest.URL) require.NoErrorf(test, err, "Can't connect to: %s", logstashTest.URL)
@ -217,8 +226,11 @@ func Test_Logstash6GatherPipelinesStats(test *testing.T) {
logstash6accPipelinesStats.SetDebug(true) logstash6accPipelinesStats.SetDebug(true)
fakeServer := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { fakeServer := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
writer.Header().Set("Content-Type", "application/json") writer.Header().Set("Content-Type", "application/json")
_, err := fmt.Fprintf(writer, "%s", string(logstash6PipelinesJSON)) if _, err := fmt.Fprintf(writer, "%s", logstash6PipelinesJSON); err != nil {
require.NoError(test, err) writer.WriteHeader(http.StatusInternalServerError)
test.Error(err)
return
}
})) }))
requestURL, err := url.Parse(logstashTest.URL) requestURL, err := url.Parse(logstashTest.URL)
require.NoErrorf(test, err, "Can't connect to: %s", logstashTest.URL) require.NoErrorf(test, err, "Can't connect to: %s", logstashTest.URL)
@ -559,8 +571,11 @@ func Test_Logstash6GatherPipelinesStats(test *testing.T) {
func Test_Logstash5GatherJVMStats(test *testing.T) { func Test_Logstash5GatherJVMStats(test *testing.T) {
fakeServer := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { fakeServer := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
writer.Header().Set("Content-Type", "application/json") writer.Header().Set("Content-Type", "application/json")
_, err := fmt.Fprintf(writer, "%s", string(logstash5JvmJSON)) if _, err := fmt.Fprintf(writer, "%s", logstash5JvmJSON); err != nil {
require.NoError(test, err) writer.WriteHeader(http.StatusInternalServerError)
test.Error(err)
return
}
})) }))
requestURL, err := url.Parse(logstashTest.URL) requestURL, err := url.Parse(logstashTest.URL)
require.NoErrorf(test, err, "Can't connect to: %s", logstashTest.URL) require.NoErrorf(test, err, "Can't connect to: %s", logstashTest.URL)
@ -623,8 +638,11 @@ func Test_Logstash5GatherJVMStats(test *testing.T) {
func Test_Logstash6GatherJVMStats(test *testing.T) { func Test_Logstash6GatherJVMStats(test *testing.T) {
fakeServer := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { fakeServer := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
writer.Header().Set("Content-Type", "application/json") writer.Header().Set("Content-Type", "application/json")
_, err := fmt.Fprintf(writer, "%s", string(logstash6JvmJSON)) if _, err := fmt.Fprintf(writer, "%s", logstash6JvmJSON); err != nil {
require.NoError(test, err) writer.WriteHeader(http.StatusInternalServerError)
test.Error(err)
return
}
})) }))
requestURL, err := url.Parse(logstashTest.URL) requestURL, err := url.Parse(logstashTest.URL)
require.NoErrorf(test, err, "Can't connect to: %s", logstashTest.URL) require.NoErrorf(test, err, "Can't connect to: %s", logstashTest.URL)

View File

@ -17,8 +17,11 @@ func TestMailChimpGatherReports(t *testing.T) {
http.HandlerFunc( http.HandlerFunc(
func(w http.ResponseWriter, _ *http.Request) { func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := fmt.Fprintln(w, sampleReports) if _, err := fmt.Fprintln(w, sampleReports); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
}, },
)) ))
defer ts.Close() defer ts.Close()
@ -82,8 +85,11 @@ func TestMailChimpGatherReport(t *testing.T) {
http.HandlerFunc( http.HandlerFunc(
func(w http.ResponseWriter, _ *http.Request) { func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := fmt.Fprintln(w, sampleReport) if _, err := fmt.Fprintln(w, sampleReport); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
}, },
)) ))
defer ts.Close() defer ts.Close()
@ -148,8 +154,11 @@ func TestMailChimpGatherError(t *testing.T) {
http.HandlerFunc( http.HandlerFunc(
func(w http.ResponseWriter, _ *http.Request) { func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := fmt.Fprintln(w, sampleError) if _, err := fmt.Fprintln(w, sampleError); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
}, },
)) ))
defer ts.Close() defer ts.Close()

View File

@ -16,8 +16,11 @@ func TestMarklogic(t *testing.T) {
// Create a test server with the const response JSON // Create a test server with the const response JSON
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := fmt.Fprintln(w, response) if _, err := fmt.Fprintln(w, response); err != nil {
require.NoError(t, err) w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
})) }))
defer ts.Close() defer ts.Close()

View File

@ -591,7 +591,11 @@ func TestInvalidUsernameOrPassword(t *testing.T) {
return return
} }
require.Equal(t, "/_status", r.URL.Path, "Cannot handle request") if r.URL.Path != "/_status" {
w.WriteHeader(http.StatusInternalServerError)
t.Errorf("Not equal, expected: %q, actual: %q", "/_status", r.URL.Path)
return
}
http.ServeFile(w, r, "testdata/response_servicetype_0.xml") http.ServeFile(w, r, "testdata/response_servicetype_0.xml")
})) }))
@ -618,7 +622,11 @@ func TestNoUsernameOrPasswordConfiguration(t *testing.T) {
return return
} }
require.Equal(t, "/_status", r.URL.Path, "Cannot handle request") if r.URL.Path != "/_status" {
w.WriteHeader(http.StatusInternalServerError)
t.Errorf("Not equal, expected: %q, actual: %q", "/_status", r.URL.Path)
return
}
http.ServeFile(w, r, "testdata/response_servicetype_0.xml") http.ServeFile(w, r, "testdata/response_servicetype_0.xml")
})) }))