aboutsummaryrefslogtreecommitdiffstats
path: root/api/http/git_file_handlers_test.go
blob: 7be4aff6d39b2116adf7dc5edc89ddecf38ebdab (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package http

import (
	"bytes"
	"image"
	"image/png"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gorilla/mux"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/MichaelMure/git-bug/api/auth"
	"github.com/MichaelMure/git-bug/cache"
	"github.com/MichaelMure/git-bug/repository"
)

func TestGitFileHandlers(t *testing.T) {
	repo := repository.CreateGoGitTestRepo(t, false)

	mrc := cache.NewMultiRepoCache()
	repoCache, events, err := mrc.RegisterDefaultRepository(repo)
	require.NoError(t, err)
	for event := range events {
		require.NoError(t, event.Err)
	}

	author, err := repoCache.Identities().New("test identity", "test@test.org")
	require.NoError(t, err)

	err = repoCache.SetUserIdentity(author)
	require.NoError(t, err)

	// UPLOAD

	uploadHandler := NewGitUploadFileHandler(mrc)

	img := image.NewNRGBA(image.Rect(0, 0, 50, 50))
	data := &bytes.Buffer{}
	err = png.Encode(data, img)
	require.NoError(t, err)

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile("uploadfile", "noname")
	assert.NoError(t, err)

	_, err = part.Write(data.Bytes())
	assert.NoError(t, err)

	err = writer.Close()
	assert.NoError(t, err)

	w := httptest.NewRecorder()
	r, _ := http.NewRequest("GET", "/", body)
	r.Header.Add("Content-Type", writer.FormDataContentType())

	// Simulate auth
	r = r.WithContext(auth.CtxWithUser(r.Context(), author.Id()))

	// Handler's params
	r = mux.SetURLVars(r, map[string]string{
		"repo": "",
	})

	uploadHandler.ServeHTTP(w, r)

	assert.Equal(t, http.StatusOK, w.Code)
	assert.Equal(t, `{"hash":"3426a1488292d8f3f3c59ca679681336542b986f"}`, w.Body.String())
	// DOWNLOAD

	downloadHandler := NewGitFileHandler(mrc)

	w = httptest.NewRecorder()
	r, _ = http.NewRequest("GET", "/", nil)

	// Simulate auth
	r = r.WithContext(auth.CtxWithUser(r.Context(), author.Id()))

	// Handler's params
	r = mux.SetURLVars(r, map[string]string{
		"repo": "",
		"hash": "3426a1488292d8f3f3c59ca679681336542b986f",
	})

	downloadHandler.ServeHTTP(w, r)
	assert.Equal(t, http.StatusOK, w.Code)

	assert.Equal(t, data.Bytes(), w.Body.Bytes())
}