You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
115 lines
2.5 KiB
115 lines
2.5 KiB
package main |
|
|
|
import ( |
|
"fmt" |
|
"net/http" |
|
"net/http/httptest" |
|
"reflect" |
|
"testing" |
|
) |
|
|
|
func TestScraper(t *testing.T) { |
|
|
|
tests := []struct { |
|
json string |
|
expected *AppStats |
|
ok bool |
|
}{ |
|
{ |
|
json: ` |
|
{ |
|
"requestCounters": { |
|
"200": 65221, |
|
"404": 14066, |
|
"500": 12618 |
|
}, |
|
"requestRates": { |
|
"200": 100, |
|
"404": 1 |
|
}, |
|
"duration": { |
|
"count": 91905, |
|
"sum": 4484.3037570333245, |
|
"average": 0.024613801985478054 |
|
} |
|
} |
|
`, |
|
expected: &AppStats{ |
|
RequestCounters: map[string]int{ |
|
"200": 65221, |
|
"404": 14066, |
|
"500": 12618, |
|
}, |
|
RequestRates: map[string]int{ |
|
"200": 100, |
|
"404": 1, |
|
}, |
|
Duration: &AppDuration{ |
|
Count: 91905, |
|
Sum: 4484.3037570333245, |
|
Average: 0.024613801985478054, |
|
}, |
|
}, |
|
ok: true, |
|
}, |
|
{ |
|
json: "invalid", |
|
ok: false, |
|
}, |
|
} |
|
|
|
for i, test := range tests { |
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
|
w.Header().Set("Content-Type", "application/json") |
|
fmt.Fprintln(w, test.json) |
|
})) |
|
defer server.Close() |
|
|
|
scraper := appScraper{ |
|
endpoint: server.URL, |
|
client: http.DefaultClient, |
|
} |
|
stats, err := scraper.stats() |
|
|
|
if err != nil { |
|
if !test.ok { |
|
continue |
|
} |
|
t.Fatalf("Test %v: http.Get(%q) unexpected error: %v", i, server.URL, err) |
|
} |
|
|
|
if !reflect.DeepEqual(*test.expected.Duration, *stats.Duration) { |
|
t.Fatalf("Test %v: Duration expected %v, got %v", i, *test.expected.Duration, *stats.Duration) |
|
} |
|
if !reflect.DeepEqual(test.expected.RequestCounters, stats.RequestCounters) { |
|
t.Fatalf("Test %v: RequestCounters expected %v, got %v", i, test.expected.RequestCounters, stats.RequestCounters) |
|
} |
|
if !reflect.DeepEqual(test.expected.RequestRates, stats.RequestRates) { |
|
t.Fatalf("Test %v: RequestRates expected %v, got %v", i, test.expected.RequestRates, stats.RequestRates) |
|
} |
|
} |
|
} |
|
|
|
// Yes, this is stolen from the consul_exporter, but why reinvent the wheel? ;-) |
|
func TestNewExporter(t *testing.T) { |
|
cases := []struct { |
|
uri string |
|
ok bool |
|
}{ |
|
{uri: "", ok: false}, |
|
{uri: "localhost:8500", ok: true}, |
|
{uri: "https://localhost:8500", ok: true}, |
|
{uri: "http://some.where:8500", ok: true}, |
|
{uri: "fuuuu://localhost:8500", ok: false}, |
|
} |
|
|
|
for _, test := range cases { |
|
_, err := NewExporter(test.uri) |
|
if test.ok && err != nil { |
|
t.Errorf("expected no error w/ %q, but got %q", test.uri, err) |
|
} |
|
if !test.ok && err == nil { |
|
t.Errorf("expected error w/ %q, but got %q", test.uri, err) |
|
} |
|
} |
|
}
|
|
|