github.com/k0marov/go-socnet@v0.0.0-20220715154813-90d07867c782/features/profiles/domain/validators/validators_test.go (about) 1 package validators_test 2 3 import ( 4 "fmt" 5 "github.com/k0marov/go-socnet/core/general/client_errors" 6 "github.com/k0marov/go-socnet/core/general/core_values/ref" 7 "github.com/k0marov/go-socnet/core/general/image_decoder" 8 . "github.com/k0marov/go-socnet/core/helpers/test_helpers" 9 "reflect" 10 "strings" 11 "testing" 12 13 "github.com/k0marov/go-socnet/features/profiles/domain/validators" 14 "github.com/k0marov/go-socnet/features/profiles/domain/values" 15 ) 16 17 func TestProfileUpdateValidator(t *testing.T) { 18 cases := []struct { 19 profileUpdate values.ProfileUpdateData 20 ok bool 21 err client_errors.ClientError 22 }{ 23 {values.ProfileUpdateData{About: "abcdfeg"}, true, client_errors.ClientError{}}, 24 {values.ProfileUpdateData{About: ""}, true, client_errors.ClientError{}}, 25 {values.ProfileUpdateData{About: strings.Repeat("abc", 100)}, false, client_errors.AboutTooLong}, 26 } 27 sut := validators.NewProfileUpdateValidator() 28 for _, c := range cases { 29 t.Run(c.profileUpdate.About, func(t *testing.T) { 30 gotErr, gotOk := sut(c.profileUpdate) 31 Assert(t, gotOk, c.ok, "validation result") 32 AssertError(t, gotErr, c.err) 33 }) 34 } 35 } 36 37 func makeRefWithoutCheck(data *[]byte) ref.Ref[[]byte] { 38 ref, err := ref.NewRef(data) 39 if err != nil { 40 panic("ref data was nil") 41 } 42 return ref 43 } 44 45 func TestAvatarValidator(t *testing.T) { 46 goodAvatar := []byte(RandomString()) 47 nonSquareAvatar := []byte(RandomString()) 48 jsInjectionAvatar := []byte(RandomString()) 49 50 imageDecoder := func(fileContents []byte) (image_decoder.Image, error) { 51 if reflect.DeepEqual(fileContents, goodAvatar) { 52 return image_decoder.Image{Width: 10, Height: 10}, nil 53 } else if reflect.DeepEqual(fileContents, nonSquareAvatar) { 54 return image_decoder.Image{Width: 10, Height: 20}, nil 55 } else if reflect.DeepEqual(fileContents, jsInjectionAvatar) { 56 return image_decoder.Image{}, RandomError() 57 } 58 panic(fmt.Sprintf("called with unexpected arguments, fileContents=%v", fileContents)) 59 } 60 sut := validators.NewAvatarValidator(imageDecoder) 61 62 cases := []struct { 63 avatar values.AvatarData 64 ok bool 65 err client_errors.ClientError 66 }{ 67 {values.AvatarData{Data: makeRefWithoutCheck(&goodAvatar)}, true, client_errors.ClientError{}}, 68 {values.AvatarData{Data: makeRefWithoutCheck(&nonSquareAvatar)}, false, client_errors.NonSquareAvatar}, 69 {values.AvatarData{Data: makeRefWithoutCheck(&jsInjectionAvatar)}, false, client_errors.InvalidImage}, 70 } 71 72 for _, c := range cases { 73 gotErr, gotOk := sut(c.avatar) 74 Assert(t, gotOk, c.ok, "result of validation") 75 AssertError(t, gotErr, c.err) 76 } 77 }