1package http
2
3import (
4 "bytes"
5 "image"
6 "image/png"
7 "mime/multipart"
8 "net/http"
9 "net/http/httptest"
10 "testing"
11
12 "github.com/gorilla/mux"
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
15
16 "github.com/MichaelMure/git-bug/api/auth"
17 "github.com/MichaelMure/git-bug/cache"
18 "github.com/MichaelMure/git-bug/repository"
19)
20
21func TestGitFileHandlers(t *testing.T) {
22 repo := repository.CreateGoGitTestRepo(t, false)
23
24 mrc := cache.NewMultiRepoCache()
25 repoCache, err := mrc.RegisterDefaultRepository(repo)
26 require.NoError(t, err)
27
28 author, err := repoCache.NewIdentity("test identity", "test@test.org")
29 require.NoError(t, err)
30
31 err = repoCache.SetUserIdentity(author)
32 require.NoError(t, err)
33
34 // UPLOAD
35
36 uploadHandler := NewGitUploadFileHandler(mrc)
37
38 img := image.NewNRGBA(image.Rect(0, 0, 50, 50))
39 data := &bytes.Buffer{}
40 err = png.Encode(data, img)
41 require.NoError(t, err)
42
43 body := &bytes.Buffer{}
44 writer := multipart.NewWriter(body)
45 part, err := writer.CreateFormFile("uploadfile", "noname")
46 assert.NoError(t, err)
47
48 _, err = part.Write(data.Bytes())
49 assert.NoError(t, err)
50
51 err = writer.Close()
52 assert.NoError(t, err)
53
54 w := httptest.NewRecorder()
55 r, _ := http.NewRequest("GET", "/", body)
56 r.Header.Add("Content-Type", writer.FormDataContentType())
57
58 // Simulate auth
59 r = r.WithContext(auth.CtxWithUser(r.Context(), author.Id()))
60
61 // Handler's params
62 r = mux.SetURLVars(r, map[string]string{
63 "repo": "",
64 })
65
66 uploadHandler.ServeHTTP(w, r)
67
68 assert.Equal(t, http.StatusOK, w.Code)
69 assert.Equal(t, `{"hash":"3426a1488292d8f3f3c59ca679681336542b986f"}`, w.Body.String())
70 // DOWNLOAD
71
72 downloadHandler := NewGitFileHandler(mrc)
73
74 w = httptest.NewRecorder()
75 r, _ = http.NewRequest("GET", "/", nil)
76
77 // Simulate auth
78 r = r.WithContext(auth.CtxWithUser(r.Context(), author.Id()))
79
80 // Handler's params
81 r = mux.SetURLVars(r, map[string]string{
82 "repo": "",
83 "hash": "3426a1488292d8f3f3c59ca679681336542b986f",
84 })
85
86 downloadHandler.ServeHTTP(w, r)
87 assert.Equal(t, http.StatusOK, w.Code)
88
89 assert.Equal(t, data.Bytes(), w.Body.Bytes())
90}