Skip to content

Commit

Permalink
Merge pull request #17 from alphagov/add-status-code-check
Browse files Browse the repository at this point in the history
Add error message for non-200 status codes
  • Loading branch information
theseanything authored Jun 27, 2024
2 parents 6c696ac + 8e4e72e commit fe9262a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
5 changes: 5 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"fmt"
"net/http"
"os"
"time"
Expand Down Expand Up @@ -59,6 +60,10 @@ func fetchMirrorFreshnessMetric(backend string, url string) (float64, error) {
return -1, err
}

if resp.StatusCode != http.StatusOK {
return -1, fmt.Errorf("request failed with status code: %s", resp.Status)
}

lastModified := resp.Header.Get("Last-Modified")

t, err := time.Parse(time.RFC1123, lastModified)
Expand Down
17 changes: 14 additions & 3 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func setup() (*metrics, *Config) {
return m, cfg
}

func createTestServer(lastModified time.Time) *httptest.Server {
func createTestServer(lastModified time.Time, statusCode int) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
backend := r.Header.Get("Backend-Override")
if backend == "backend1" || backend == "backend2" {
Expand All @@ -31,6 +31,7 @@ func createTestServer(lastModified time.Time) *httptest.Server {
}

w.Header().Set("Last-Modified", lastModified.Format(http.TimeFormat))
w.WriteHeader(statusCode)
} else {
http.Error(w, "Backend-Override header not set to backend1 or backend2", http.StatusBadRequest)
}
Expand All @@ -39,7 +40,7 @@ func createTestServer(lastModified time.Time) *httptest.Server {

func TestFetchMirrorFreshnessMetric(t *testing.T) {
timestamp := time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)
ts := createTestServer(timestamp)
ts := createTestServer(timestamp, http.StatusOK)
defer ts.Close()

freshness, err := fetchMirrorFreshnessMetric("backend1", ts.URL)
Expand All @@ -49,11 +50,21 @@ func TestFetchMirrorFreshnessMetric(t *testing.T) {
assert.Equal(t, expectedFreshness, freshness)
}

func TestFetchMirrorFreshnessMetric500StatusCode(t *testing.T) {
timestamp := time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)
ts := createTestServer(timestamp, http.StatusInternalServerError)
defer ts.Close()

_, err := fetchMirrorFreshnessMetric("backend1", ts.URL)
assert.Error(t, err)
assert.Contains(t, err.Error(), "request failed with status code")
}

func TestUpdateMetrics(t *testing.T) {
m, cfg := setup()

timestamp := time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)
ts := createTestServer(timestamp)
ts := createTestServer(timestamp, http.StatusOK)
defer ts.Close()

cfg.MirrorFreshnessUrl = ts.URL
Expand Down

0 comments on commit fe9262a

Please sign in to comment.