package avatar import ( "bytes" "encoding/hex" "image" "image/color" "image/jpeg" "os" "path/filepath" "testing" ) // Reference values from the previous implementation. They pin the identicon // algorithm, so existing users keep the same picture. func TestIdenticonMatchesReference(t *testing.T) { tests := []struct { name string bytes string rgb [3]uint8 }{ {"alice", "a554a5a173394418a17c66ae57445638", [3]uint8{156, 178, 31}}, {"admin", "7c212d2be8af0b70a0dd6542c4f55b32", [3]uint8{166, 33, 186}}, {"bob-42", "07c21f2cb96afe78a3f481297d2f9406", [3]uint8{197, 27, 53}}, {"ünïcode", "6f73f4fe71b1d1c57b611ae2556e8766", [3]uint8{219, 140, 57}}, } for _, tt := range tests { b := hashBytes(tt.name, 16) if got := hex.EncodeToString(b); got != tt.bytes { t.Errorf("hashBytes(%q) = %s, want %s", tt.name, got, tt.bytes) } r, g, bl := hslToRGB(float64((int(b[0])|int(b[1])<<8)%360), float64(int(b[2])%20+65), float64(int(b[3])%20+40)) if [3]uint8{r, g, bl} != tt.rgb { t.Errorf("color(%q) = %v, want %v", tt.name, [3]uint8{r, g, bl}, tt.rgb) } } } func TestIdenticonPixels(t *testing.T) { img := Identicon("alice") if img.Bounds() != image.Rect(0, 0, 128, 128) { t.Fatalf("bounds = %v", img.Bounds()) } // The padding area is always background. if got := img.NRGBAAt(0, 0); got != (color.NRGBA{240, 240, 240, 255}) { t.Errorf("corner = %v", got) } // Column 0 and column 4 mirror each other. for y := 24; y < 104; y++ { if img.NRGBAAt(24, y) != img.NRGBAAt(127-24, y) { t.Fatalf("identicon not symmetric at y=%d", y) } } } func TestSaveResizesAndRejectsNonImages(t *testing.T) { dir := t.TempDir() src := image.NewRGBA(image.Rect(0, 0, 400, 200)) var buf bytes.Buffer if err := jpeg.Encode(&buf, src, nil); err != nil { t.Fatal(err) } if err := Save(dir, 7, buf.Bytes()); err != nil { t.Fatal(err) } f, err := os.Open(filepath.Join(dir, "7.png")) if err != nil { t.Fatal(err) } defer f.Close() cfg, format, err := image.DecodeConfig(f) if err != nil { t.Fatal(err) } if format != "png" || cfg.Width != 128 || cfg.Height != 128 { t.Errorf("stored %s %dx%d", format, cfg.Width, cfg.Height) } if err := Save(dir, 8, []byte("not an image at all")); err == nil { t.Error("expected an error for a non-image upload") } } func TestPath(t *testing.T) { if got := Path("/data/avatars", 42); got != "/data/avatars/42.png" { t.Errorf("Path = %q", got) } }