add avatar proxy tests

This commit is contained in:
Umputun
2018-02-14 21:19:30 -06:00
parent 5fe810db41
commit fd726395ff
2 changed files with 74 additions and 14 deletions
+12 -14
View File
@@ -3,24 +3,20 @@
package avatar
import (
"net/http"
"time"
"os"
"path"
"io"
"log"
"fmt"
"hash/crc64"
"io"
"log"
"net/http"
"os"
"path"
"strings"
"time"
"github.com/go-chi/chi"
"github.com/go-chi/render"
"github.com/pkg/errors"
"github.com/umputun/remark/app/rest/common"
"github.com/umputun/remark/app/store"
)
@@ -32,7 +28,7 @@ type Proxy struct {
RoutePath string
}
// Put gets original avatar url from user info and returns proxied
// Put gets original avatar url from user info and returns proxied url
func (p *Proxy) Put(u store.User) (avatarURL string, err error) {
if u.Picture == "" {
@@ -114,8 +110,10 @@ func (p *Proxy) Routes() chi.Router {
return router
}
// get location for user id by adding partion to final path
// the end result is a full path like this - /tmp/avatars.test/992
func (p *Proxy) location(id string) string {
checksum64 := crc64.Checksum([]byte(id), crc64.MakeTable(crc64.ECMA))
partition := checksum64 % 1000
return path.Join(p.StorePath, fmt.Sprintf("%03d", partition))
partition := checksum64 % 100
return path.Join(p.StorePath, fmt.Sprintf("%02d", partition))
}
+62
View File
@@ -0,0 +1,62 @@
package avatar
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/umputun/remark/app/store"
)
func TestPut(t *testing.T) {
p := Proxy{StorePath: "/tmp/avatars.test", RoutePath: "/avatar"}
os.MkdirAll("/tmp/avatars.test", 0700)
defer os.RemoveAll("/tmp/avatars.test")
u := store.User{ID: "user1", Name: "user1 name", Picture: "https://friends.radio-t.com/resources/images/rt_logo_64.png"}
res, err := p.Put(u)
assert.NoError(t, err)
assert.Equal(t, "/avatar/user1.image", res)
fi, err := os.Stat("/tmp/avatars.test/20/user1.image")
assert.NoError(t, err)
assert.Equal(t, int64(8432), fi.Size())
u.ID = "user2"
res, err = p.Put(u)
assert.NoError(t, err)
assert.Equal(t, "/avatar/user2.image", res)
fi, err = os.Stat("/tmp/avatars.test/92/user2.image")
assert.NoError(t, err)
assert.Equal(t, int64(8432), fi.Size())
}
func TestRoutes(t *testing.T) {
p := Proxy{StorePath: "/tmp/avatars.test", RoutePath: "/avatar"}
os.MkdirAll("/tmp/avatars.test", 0700)
defer os.RemoveAll("/tmp/avatars.test")
u := store.User{ID: "user1", Name: "user1 name", Picture: "https://friends.radio-t.com/resources/images/rt_logo_64.png"}
_, err := p.Put(u)
assert.NoError(t, err)
req, err := http.NewRequest("GET", "/user1.image", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.Handler(p.Routes())
handler.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Code)
assert.Equal(t, http.Header{"Content-Type": []string{"image/*"}}, rr.HeaderMap)
bb := bytes.Buffer{}
sz, err := io.Copy(&bb, rr.Body)
assert.NoError(t, err)
assert.Equal(t, int64(8432), sz)
}