Skip to content

Commit

Permalink
Merge pull request #183 from Mido-sys/fix_division_zero_issue_182
Browse files Browse the repository at this point in the history
Gracefully handle division by zero using ints & floats
  • Loading branch information
paganotoni authored Jun 21, 2024
2 parents f6aa624 + e75a6c4 commit 8eb5406
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
6 changes: 6 additions & 0 deletions compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,9 @@ func (c *compiler) intsOperator(l int, r int, op string) (interface{}, error) {
case "-":
return l - r, nil
case "/":
if r == 0 {
return nil, fmt.Errorf("division by zero %v %s %v", l, op, r)
}
return l / r, nil
case "*":
return l * r, nil
Expand All @@ -556,6 +559,9 @@ func (c *compiler) floatsOperator(l float64, r float64, op string) (interface{},
case "-":
return l - r, nil
case "/":
if r == 0 {
return nil, fmt.Errorf("division by zero %v %s %v", l, op, r)
}
return l / r, nil
case "*":
return l * r, nil
Expand Down
18 changes: 18 additions & 0 deletions math_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,24 @@ import (
"github.com/stretchr/testify/require"
)

func Test_Render_Int_Math_Division_By_Zero(t *testing.T) {
r := require.New(t)
input := `<%= 10 / 0 %>`
s, err := plush.Render(input, plush.NewContext())
r.Error(err)
r.Empty(s)
r.Contains(err.Error(), "division by zero 10 / 0")
}

func Test_Render_Int_Float_Division_By_Zero(t *testing.T) {
r := require.New(t)
input := `<%= 10.5 / 0.0 %>`
s, err := plush.Render(input, plush.NewContext())
r.Error(err)
r.Empty(s)
r.Contains(err.Error(), "division by zero 10.5 / 0")
}

func Test_Render_Int_Math(t *testing.T) {
r := require.New(t)

Expand Down

0 comments on commit 8eb5406

Please sign in to comment.