github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/avatars/upload_test.go (about) 1 package avatars 2 3 import ( 4 "io" 5 "mime" 6 "mime/multipart" 7 "os" 8 "testing" 9 10 "github.com/keybase/client/go/kbtest" 11 "github.com/keybase/client/go/libkb" 12 "github.com/keybase/client/go/protocol/keybase1" 13 "github.com/stretchr/testify/require" 14 ) 15 16 type uploadAvatarMockAPI struct { 17 libkb.API 18 Func func(map[string]string) error 19 } 20 21 func (a *uploadAvatarMockAPI) PostRaw(mctx libkb.MetaContext, arg libkb.APIArg, contentType string, r io.Reader) (*libkb.APIRes, error) { 22 _, params, err := mime.ParseMediaType(contentType) 23 if err != nil { 24 return nil, err 25 } 26 27 postForm := make(map[string]string) 28 29 mr := multipart.NewReader(r, params["boundary"]) 30 for { 31 p, err := mr.NextPart() 32 if err == io.EOF { 33 break 34 } 35 if err != nil { 36 return nil, err 37 } 38 slurp, err := io.ReadAll(p) 39 if err != nil { 40 return nil, err 41 } 42 postForm[p.Header.Get("Content-Disposition")] = string(slurp) 43 } 44 45 err = a.Func(postForm) 46 return nil, err 47 } 48 49 func TestUploadAvatar(t *testing.T) { 50 tc := libkb.SetupTest(t, "TestUploadAvatar", 1) 51 defer tc.Cleanup() 52 53 _, err := kbtest.CreateAndSignupFakeUser("avtr", tc.G) 54 require.NoError(t, err) 55 56 // Prepare test avatar file 57 tmpfile, err := os.CreateTemp(os.TempDir(), "kbtest_avatar.png") 58 require.NoError(t, err) 59 tmpFileStr := "\x89PNGa somewhat goofy picture of a cat" 60 _, err = tmpfile.WriteString(tmpFileStr) 61 require.NoError(t, err) 62 tmpfile.Close() 63 t.Logf("Created a test avatar file: %s", tmpfile.Name()) 64 defer os.Remove(tmpfile.Name()) 65 66 mock := uploadAvatarMockAPI{} 67 mock.Func = func(post map[string]string) error { 68 require.Len(t, post, 5) 69 require.Equal(t, "1", post["form-data; name=\"x0\""]) 70 require.Equal(t, "2", post["form-data; name=\"y0\""]) 71 require.Equal(t, "3", post["form-data; name=\"x1\""]) 72 require.Equal(t, "4", post["form-data; name=\"y1\""]) 73 require.Equal(t, tmpFileStr, post["form-data; name=\"avatar\"; filename=\"image\""]) 74 return nil 75 } 76 tc.G.API = &mock 77 78 crop := keybase1.ImageCropRect{ 79 X0: 1, Y0: 2, X1: 3, Y1: 4, 80 } 81 82 mctx := libkb.NewMetaContextBackground(tc.G) 83 err = UploadImage(mctx, tmpfile.Name(), nil, &crop) 84 require.NoError(t, err) 85 }