Fuzz ParseColor.

This commit is contained in:
Nuno Cruces 2022-03-26 15:36:53 +00:00
parent 05bce67856
commit ea8c939434
3 changed files with 68 additions and 3 deletions

View file

@ -18,7 +18,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
go-version: 1.18
- name: Build
run: go build -v ./...

View file

@ -27,7 +27,7 @@ func ParseColor(s string) color.Color {
}
}
if len(s) >= 10 {
if len(s) >= 10 && "rgb" == s[:3] {
c := color.NRGBA{A: 0xff}
if _, err := fmt.Sscanf(s, "rgb(%d,%d,%d)", &c.R, &c.G, &c.B); err == nil {
return c

View file

@ -67,9 +67,26 @@ func TestColor_strings(t *testing.T) {
{"#8888", color.NRGBA{0x88, 0x88, 0x88, 0x88}},
{"#80808080", color.NRGBA{0x80, 0x80, 0x80, 0x80}},
{"rgb(128,128,128)", color.NRGBA{0x80, 0x80, 0x80, 0xff}},
{"rgba(128,128,128,0.5)", color.NRGBA{0x80, 0x80, 0x80, 0x80}},
{"rgba(128,128,128,0)", color.NRGBA{0x80, 0x80, 0x80, 0x00}},
{"rgba(128,128,128,1)", color.NRGBA{0x80, 0x80, 0x80, 0xff}},
{"rgba(128,128,128,0.0)", color.NRGBA{0x80, 0x80, 0x80, 0x00}},
{"rgba(128,128,128,1.0)", color.NRGBA{0x80, 0x80, 0x80, 0xff}},
{"not a color", nil},
{"#0", nil},
{"#00", nil},
{"#000", color.Black},
{"#0000", color.Transparent},
{"#00000", nil},
{"#000000", color.Black},
{"#0000000", nil},
{"#00000000", color.Transparent},
{"#000000000", nil},
{"rgb(-1,-1,-1)", nil},
{"rgb(256,256,256)", nil},
{"rgb(128,128,128,0.5)", nil},
{"rgb(127.5,127.5,127.5)", nil},
{"rgba(127.5,127.5,127.5,0.5)", nil},
{"rgba(128,128,128)", nil},
}
for _, test := range tests {
c := ParseColor(test.data)
@ -78,3 +95,51 @@ func TestColor_strings(t *testing.T) {
}
}
}
func FuzzParseColor(f *testing.F) {
f.Add("#000")
f.Add("#000f")
f.Add("#000000")
f.Add("#000000ff")
f.Add("#fff")
f.Add("#ffff")
f.Add("#ffffff")
f.Add("#ffffffff")
f.Add("#FFF")
f.Add("#FFFF")
f.Add("#FFFFFF")
f.Add("#FFFFFFFF")
f.Add("#0")
f.Add("#00")
f.Add("#000")
f.Add("#0000")
f.Add("#00000")
f.Add("#000000")
f.Add("#0000000")
f.Add("#00000000")
f.Add("#000000000")
f.Add("#8888")
f.Add("#80808080")
f.Add("rgb(-1,-1,-1)")
f.Add("rgb(128,128,128)")
f.Add("rgb(256,256,256)")
f.Add("rgb(128,128,128,0.5)")
f.Add("rgb(127.5,127.5,127.5)")
f.Add("rgba(128,128,128)")
f.Add("rgba(128,128,128,0)")
f.Add("rgba(128,128,128,1)")
f.Add("rgba(128,128,128,0.0)")
f.Add("rgba(128,128,128,0.5)")
f.Add("rgba(128,128,128,1.0)")
f.Add("rgba(127.5,127.5,127.5,0.5)")
f.Add("not a color")
f.Add("")
for _, name := range colornames.Names {
f.Add(name)
}
f.Fuzz(func(t *testing.T, s string) {
ParseColor(s)
})
}