bluebell/upload/upload_test.go

82 lines
2.1 KiB
Go
Raw Normal View History

2023-07-22 00:59:45 +01:00
package upload
import (
"bytes"
_ "embed"
2024-08-10 13:28:30 +01:00
"github.com/1f349/bluebell/conf"
2023-07-22 00:59:45 +01:00
"github.com/julienschmidt/httprouter"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"testing"
)
2023-08-21 00:27:54 +01:00
var (
//go:embed test-archive.tar.gz
testArchiveTarGz []byte
//go:embed test-sites.yml
testSitesYml []byte
)
2023-07-22 00:59:45 +01:00
func assertUploadedFile(t *testing.T, fs afero.Fs) {
// check uploaded file exists
stat, err := fs.Stat("example.com/main/test.txt")
assert.NoError(t, err)
assert.False(t, stat.IsDir())
assert.Equal(t, int64(13), stat.Size())
// check contents
o, err := fs.Open("example.com/main/test.txt")
assert.NoError(t, err)
all, err := io.ReadAll(o)
assert.NoError(t, err)
assert.Equal(t, "Hello world!\n", string(all))
}
func TestHandler_Handle(t *testing.T) {
2023-08-21 00:27:54 +01:00
f := afero.NewMemMapFs()
2024-08-10 13:28:30 +01:00
conf := conf.New(f)
2023-08-21 00:27:54 +01:00
h := &Handler{f, conf}
create, err := f.Create("sites.yml")
assert.NoError(t, err)
_, err = create.Write(testSitesYml)
assert.NoError(t, err)
assert.NoError(t, create.Close())
assert.NoError(t, conf.Load())
2023-07-22 00:59:45 +01:00
mpBuf := new(bytes.Buffer)
mp := multipart.NewWriter(mpBuf)
file, err := mp.CreateFormFile("upload", "test-archive.tar.gz")
assert.NoError(t, err)
_, err = file.Write(testArchiveTarGz)
assert.NoError(t, err)
assert.NoError(t, mp.Close())
2023-08-21 00:27:54 +01:00
req, err := http.NewRequest(http.MethodPost, "https://example.com/u?site=example.com&branch=main", mpBuf)
2023-07-22 00:59:45 +01:00
assert.NoError(t, err)
2023-08-21 00:27:54 +01:00
req.Header.Set("Authorization", "Bearer abcd1234")
2023-07-22 00:59:45 +01:00
req.Header.Set("Content-Type", mp.FormDataContentType())
rec := httptest.NewRecorder()
2023-08-21 00:27:54 +01:00
h.Handle(rec, req, httprouter.Params{})
2023-07-22 00:59:45 +01:00
res := rec.Result()
assert.Equal(t, http.StatusAccepted, res.StatusCode)
assert.NotNil(t, res.Body)
all, err := io.ReadAll(res.Body)
assert.NoError(t, err)
assert.Equal(t, "", string(all))
2023-08-21 00:27:54 +01:00
assertUploadedFile(t, f)
2023-07-22 00:59:45 +01:00
}
func TestHandler_extractTarGzUpload(t *testing.T) {
fs := afero.NewMemMapFs()
2024-08-10 13:28:30 +01:00
conf := conf.New(fs)
2023-08-21 00:27:54 +01:00
h := &Handler{fs, conf}
2023-07-22 00:59:45 +01:00
buffer := bytes.NewBuffer(testArchiveTarGz)
assert.NoError(t, h.extractTarGzUpload(buffer, "example.com", "main"))
assertUploadedFile(t, fs)
}