From 2a92929c2024c72a904bdc84eac1fabeadd4bcab Mon Sep 17 00:00:00 2001 From: Winni Neessen Date: Sat, 1 Oct 2022 16:06:56 +0200 Subject: [PATCH] Better test coverage for breaches API --- breach_test.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/breach_test.go b/breach_test.go index 8e02fdd..602cd84 100644 --- a/breach_test.go +++ b/breach_test.go @@ -1,11 +1,19 @@ package hibp import ( + "encoding/json" "fmt" "os" "testing" ) +const ( + validDateJSON = `{"date": "2022-10-01"}` + validNullDateJSON = `{"date": "null""}` + invalidJSON = `{"date": '2022-10-01'}` + invalidDateJSON = `{"date": "202299-10-01"}` +) + // TestBreaches tests the Breaches() method of the breaches API func TestBreaches(t *testing.T) { hc := New() @@ -238,6 +246,44 @@ func TestBreachedAccountWithoutTruncate(t *testing.T) { } } +// TestApiDate_UnmarshalJSON_Time tests the ApiDate type JSON unmarshalling +func TestApiDate_UnmarshalJSON_Time(t *testing.T) { + type testData struct { + Date *ApiDate `json:"date"` + } + tt := []struct { + n string + j []byte + d string + nil bool + sf bool + }{ + {"valid Date JSON", []byte(validDateJSON), "2022-10-01", false, false}, + {"valid Null Date JSON", []byte(validNullDateJSON), "", true, false}, + {"invalid JSON", []byte(invalidJSON), "", true, true}, + {"invalid Date", []byte(invalidDateJSON), "", true, true}, + } + + for _, tc := range tt { + t.Run(tc.n, func(t *testing.T) { + var td testData + if err := json.Unmarshal(tc.j, &td); err != nil && !tc.sf { + t.Errorf("failed to unmarshal test JSON: %s", err) + } + if td.Date == nil && !tc.nil { + t.Errorf("unmarshal on ApiDate type failed. Expected data but got nil") + return + } + if !tc.nil { + tdd := td.Date.Time().Format("2006-01-02") + if tdd != tc.d && !tc.sf { + t.Errorf(`unmarshal of ApiDate type failed. Expected: %q, got %q"`, tc.d, tdd) + } + } + }) + } +} + // ExampleBreachApi_Breaches_getAllBreaches is a code example to show how to fetch all breaches from the // HIBP breaches API func ExampleBreachApi_Breaches_getAllBreaches() {