Skip to content

Commit

Permalink
Handle error when reading user input
Browse files Browse the repository at this point in the history
  • Loading branch information
rockstaedt committed Oct 24, 2023
1 parent 77d1624 commit 91a2fd4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
7 changes: 3 additions & 4 deletions cmd/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"
"github.com/TwiN/go-color"
"github.com/rockstaedt/txtreader"
"log"
"rockstaedt/commit-message-check/internal/model"
)

Expand All @@ -31,9 +30,9 @@ func (h *Handler) validate() int {
h.notify("Subject line too long. Do you want to abort? (y/n)", "red")

var decision string
_, err := fmt.Fscanln(h.Reader, &decision)
if err != nil {
log.Fatal(err)
if _, err := fmt.Fscanln(h.Reader, &decision); err != nil {
h.notify("Could not read user input.", "red")
return 1
}

if decision == "y" {
Expand Down
15 changes: 13 additions & 2 deletions cmd/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func TestValidate(t *testing.T) {
handler := NewHandler(model.Config{CommitMsgFile: testFile})
handler.Writer = buffer

t.Run("user confirms abort", func(t *testing.T) {
t.Run("user confirms abort returns 1", func(t *testing.T) {
buffer.Reset()
handler.Reader = bytes.NewReader([]byte("y"))

Expand All @@ -58,14 +58,25 @@ func TestValidate(t *testing.T) {
assert.Contains(t, buffer.String(), color.Red+"Subject line too long. Do you want to abort? (y/n)")
assert.Equal(t, 1, status)
})
t.Run("user declines abort", func(t *testing.T) {

t.Run("user declines abort returns 0", func(t *testing.T) {
buffer.Reset()
handler.Reader = bytes.NewReader([]byte("n"))

status := handler.Run("validate")

assert.Equal(t, 0, status)
})

t.Run("error at reading user input returns 1", func(t *testing.T) {
buffer.Reset()
handler.Reader = bytes.NewReader([]byte(""))

status := handler.Run("validate")

assert.Equal(t, 1, status)
assert.Contains(t, buffer.String(), color.Red+"Could not read user input.")
})
})

t.Run("returns 1 when error at reading file", func(t *testing.T) {
Expand Down

0 comments on commit 91a2fd4

Please sign in to comment.