From bd528ed11eb372a8591a1746fd5ed708d87e9346 Mon Sep 17 00:00:00 2001 From: Josh Deprez Date: Wed, 7 Feb 2024 14:51:41 +1100 Subject: [PATCH] [Sketch] Two ways to test for errors in a more semantic way --- internal/runner/file.go | 4 +++- internal/runner/file_test.go | 45 ++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 internal/runner/file_test.go diff --git a/internal/runner/file.go b/internal/runner/file.go index ae89b4d4..dfdb0e49 100644 --- a/internal/runner/file.go +++ b/internal/runner/file.go @@ -2,6 +2,7 @@ package runner import ( "encoding/json" + "fmt" "os" ) @@ -12,7 +13,8 @@ import ( func readJsonFile(filename string, v any) error { content, err := os.ReadFile(filename) if err != nil { - return err + //return err + return fmt.Errorf("reading file: %w", err) } return json.Unmarshal(content, v) diff --git a/internal/runner/file_test.go b/internal/runner/file_test.go new file mode 100644 index 00000000..6062ef4e --- /dev/null +++ b/internal/runner/file_test.go @@ -0,0 +1,45 @@ +package runner + +import ( + "errors" + "io/fs" + "syscall" + "testing" +) + +type Report struct { + Result string `json:"result"` +} + +func TestReadJsonFile_Errors(t *testing.T) { + var report Report + + testCases := []struct { + fileName string + wantErrorAs any + wantErrorIs error + }{ + { + fileName: "file_not_exist", + wantErrorAs: new(*fs.PathError), + }, + { + fileName: "file_not_exist", + wantErrorIs: syscall.ENOENT, + }, + } + + for _, tc := range testCases { + gotError := readJsonFile(tc.fileName, &report) + if tc.wantErrorAs != nil { + if !errors.As(gotError, tc.wantErrorAs) { + t.Errorf("readJsonFile(%q, &report) = %v, want %T", tc.fileName, gotError, tc.wantErrorAs) + } + } + if tc.wantErrorIs != nil { + if !errors.Is(gotError, tc.wantErrorIs) { + t.Errorf("readJsonFile(%q, &report) = %v, want %v", tc.fileName, gotError, tc.wantErrorIs) + } + } + } +}