types: Run tests as sub-tests.

This enables better reporting of test results/metrics, and removes the need to manually include test names in logs.
This commit is contained in:
jholdstock 2022-12-31 14:07:43 +00:00 committed by Jamie Holdstock
parent fb8c58c512
commit 33bb68c3df

View File

@ -12,42 +12,42 @@ import (
// TestAPIErrorAs ensures APIError can be unwrapped via errors.As. // TestAPIErrorAs ensures APIError can be unwrapped via errors.As.
func TestAPIErrorAs(t *testing.T) { func TestAPIErrorAs(t *testing.T) {
tests := []struct { tests := map[string]struct {
testName string
apiError error apiError error
expectedKind ErrorCode expectedKind ErrorCode
expectedMessage string expectedMessage string
}{{ }{
testName: "BadRequest error", "BadRequest error": {
apiError: ErrorResponse{Message: "something went wrong", Code: int64(ErrBadRequest)}, apiError: ErrorResponse{Message: "something went wrong", Code: int64(ErrBadRequest)},
expectedKind: ErrBadRequest, expectedKind: ErrBadRequest,
expectedMessage: "something went wrong", expectedMessage: "something went wrong",
}, },
{ "Unknown error": {
testName: "Unknown error",
apiError: ErrorResponse{Message: "something went wrong again", Code: int64(999)}, apiError: ErrorResponse{Message: "something went wrong again", Code: int64(999)},
expectedKind: 999, expectedKind: 999,
expectedMessage: "something went wrong again", expectedMessage: "something went wrong again",
}} },
}
for testName, test := range tests {
t.Run(testName, func(t *testing.T) {
for _, test := range tests {
// Ensure APIError can be unwrapped from error. // Ensure APIError can be unwrapped from error.
var parsedError ErrorResponse var parsedError ErrorResponse
if !errors.As(test.apiError, &parsedError) { if !errors.As(test.apiError, &parsedError) {
t.Errorf("%s: unable to unwrap error", test.testName) t.Fatalf("unable to unwrap error")
continue
} }
if parsedError.Code != int64(test.expectedKind) { if parsedError.Code != int64(test.expectedKind) {
t.Errorf("%s: error was wrong kind. expected: %d actual %d", t.Fatalf("error was wrong kind. expected: %d actual %d",
test.testName, test.expectedKind, parsedError.Code) test.expectedKind, parsedError.Code)
continue
} }
if parsedError.Message != test.expectedMessage { if parsedError.Message != test.expectedMessage {
t.Errorf("%s: error had wrong message. expected: %q actual %q", t.Fatalf("error had wrong message. expected: %q actual %q",
test.testName, test.expectedMessage, parsedError.Message) test.expectedMessage, parsedError.Message)
continue }
}
})
} }
} }