| 1 | package logo |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "image" |
| 6 | "image/color" |
| 7 | "image/png" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | ) |
| 11 | |
| 12 | func TestScaleKeepsAspect(t *testing.T) { |
| 13 | wide := solid(800, 400, color.NRGBA{R: 20, G: 80, B: 200, A: 255}) |
| 14 | out, mime, err := Normalize(wide) |
| 15 | if err != nil { |
| 16 | t.Fatal(err) |
| 17 | } |
| 18 | if mime != "image/png" { |
| 19 | t.Fatal(mime) |
| 20 | } |
| 21 | w, h, err := SizeOf(out) |
| 22 | if err != nil { |
| 23 | t.Fatal(err) |
| 24 | } |
| 25 | if w != 512 || h != 256 { |
| 26 | t.Fatalf("wide %dx%d", w, h) |
| 27 | } |
| 28 | tall := solid(100, 600, color.NRGBA{G: 180, A: 255}) |
| 29 | out, _, err = Normalize(tall) |
| 30 | if err != nil { |
| 31 | t.Fatal(err) |
| 32 | } |
| 33 | w, h, err = SizeOf(out) |
| 34 | if err != nil { |
| 35 | t.Fatal(err) |
| 36 | } |
| 37 | if h != 512 || w > 512 || w < 80 { |
| 38 | t.Fatalf("tall %dx%d", w, h) |
| 39 | } |
| 40 | small := solid(40, 40, color.NRGBA{B: 255, A: 255}) |
| 41 | out, _, err = Normalize(small) |
| 42 | if err != nil { |
| 43 | t.Fatal(err) |
| 44 | } |
| 45 | w, h, _ = SizeOf(out) |
| 46 | if w != 40 || h != 40 { |
| 47 | t.Fatalf("small %dx%d", w, h) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | func TestSVG(t *testing.T) { |
| 52 | ok := []byte(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><circle cx="5" cy="5" r="4" fill="#1f6feb"/></svg>`) |
| 53 | out, mime, err := Normalize(ok) |
| 54 | if err != nil || mime != "image/svg+xml" || !bytes.Equal(out, ok) { |
| 55 | t.Fatalf("%s %v %d", mime, err, len(out)) |
| 56 | } |
| 57 | bad := []byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`) |
| 58 | if _, _, err := Normalize(bad); err == nil { |
| 59 | t.Fatal("script svg") |
| 60 | } |
| 61 | huge := []byte("<svg xmlns=\"http://www.w3.org/2000/svg\">" + strings.Repeat("a", MaxSVG) + "</svg>") |
| 62 | if _, _, err := Normalize(huge); err == nil { |
| 63 | t.Fatal("grote svg") |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | func solid(w, h int, c color.NRGBA) []byte { |
| 68 | img := image.NewNRGBA(image.Rect(0, 0, w, h)) |
| 69 | for y := 0; y < h; y++ { |
| 70 | for x := 0; x < w; x++ { |
| 71 | img.SetNRGBA(x, y, c) |
| 72 | } |
| 73 | } |
| 74 | var buf bytes.Buffer |
| 75 | _ = png.Encode(&buf, img) |
| 76 | return buf.Bytes() |
| 77 | } |