From ef3bf0f4dd962250aa2700b71f753f36619915e1 Mon Sep 17 00:00:00 2001 From: sunshineplan Date: Wed, 17 Jan 2024 13:24:34 +0800 Subject: [PATCH] Fix randRange panic --- watermark.go | 3 +++ watermark_test.go | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/watermark.go b/watermark.go index d5326ef..dd14464 100644 --- a/watermark.go +++ b/watermark.go @@ -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 } diff --git a/watermark_test.go b/watermark_test.go index feb3d30..8fa1204 100644 --- a/watermark_test.go +++ b/watermark_test.go @@ -3,6 +3,7 @@ package imgconv import ( "image" "reflect" + "slices" "testing" "time" @@ -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) + } + } + } +}