git_file_handlers_test.go

 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(false)
23	defer repository.CleanupTestRepos(repo)
24
25	mrc := cache.NewMultiRepoCache()
26	repoCache, err := mrc.RegisterDefaultRepository(repo)
27	require.NoError(t, err)
28
29	author, err := repoCache.NewIdentity("test identity", "test@test.org")
30	require.NoError(t, err)
31
32	err = repoCache.SetUserIdentity(author)
33	require.NoError(t, err)
34
35	// UPLOAD
36
37	uploadHandler := NewGitUploadFileHandler(mrc)
38
39	img := image.NewNRGBA(image.Rect(0, 0, 50, 50))
40	data := &bytes.Buffer{}
41	err = png.Encode(data, img)
42	require.NoError(t, err)
43
44	body := &bytes.Buffer{}
45	writer := multipart.NewWriter(body)
46	part, err := writer.CreateFormFile("uploadfile", "noname")
47	assert.NoError(t, err)
48
49	_, err = part.Write(data.Bytes())
50	assert.NoError(t, err)
51
52	err = writer.Close()
53	assert.NoError(t, err)
54
55	w := httptest.NewRecorder()
56	r, _ := http.NewRequest("GET", "/", body)
57	r.Header.Add("Content-Type", writer.FormDataContentType())
58
59	// Simulate auth
60	r = r.WithContext(auth.CtxWithUser(r.Context(), author.Id()))
61
62	// Handler's params
63	r = mux.SetURLVars(r, map[string]string{
64		"repo": "",
65	})
66
67	uploadHandler.ServeHTTP(w, r)
68
69	assert.Equal(t, http.StatusOK, w.Code)
70	assert.Equal(t, `{"hash":"3426a1488292d8f3f3c59ca679681336542b986f"}`, w.Body.String())
71	// DOWNLOAD
72
73	downloadHandler := NewGitFileHandler(mrc)
74
75	w = httptest.NewRecorder()
76	r, _ = http.NewRequest("GET", "/", nil)
77
78	// Simulate auth
79	r = r.WithContext(auth.CtxWithUser(r.Context(), author.Id()))
80
81	// Handler's params
82	r = mux.SetURLVars(r, map[string]string{
83		"repo": "",
84		"hash": "3426a1488292d8f3f3c59ca679681336542b986f",
85	})
86
87	downloadHandler.ServeHTTP(w, r)
88	assert.Equal(t, http.StatusOK, w.Code)
89
90	assert.Equal(t, data.Bytes(), w.Body.Bytes())
91}