Skip to content

Commit

Permalink
Fix randRange panic (#107)
Browse files Browse the repository at this point in the history
  • Loading branch information
sunshineplan authored Jan 17, 2024
1 parent b727596 commit 757220a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
3 changes: 3 additions & 0 deletions watermark.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ func (w *WatermarkOption) do(base image.Image) image.Image {
}

func randRange(min, max int) int {
if max < min {
min, max = max, min
}
return rand.Intn(max-min+1) + min
}

Expand Down
23 changes: 23 additions & 0 deletions watermark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package imgconv
import (
"image"
"reflect"
"slices"
"testing"
"time"

Expand Down Expand Up @@ -60,3 +61,25 @@ func TestCalcResizeXY(t *testing.T) {
}
}
}

func TestRandRange(t *testing.T) {
testCase := []struct {
min, max int
res []int
}{
{1, 5, []int{1, 2, 3, 4, 5}},
{5, 1, []int{1, 2, 3, 4, 5}},
{-1, 5, []int{-1, 0, 1, 2, 3, 4, 5}},
{5, -1, []int{-1, 0, 1, 2, 3, 4, 5}},
{-5, -1, []int{-5, -4, -3, -2, -1}},
{-1, -5, []int{-5, -4, -3, -2, -1}},
}

for i := 0; i < 100; i++ {
for i, tc := range testCase {
if res := randRange(tc.min, tc.max); !slices.Contains(tc.res, res) {
t.Errorf("#%d: got %d, not in range %v", i, res, tc.res)
}
}
}
}

0 comments on commit 757220a

Please sign in to comment.