Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Sketch] Two ways to test for errors in a more semantic way #13

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion internal/runner/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package runner

import (
"encoding/json"
"fmt"
"os"
)

Expand All @@ -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)
Expand Down
45 changes: 45 additions & 0 deletions internal/runner/file_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
}