Skip to content
This repository was archived by the owner on Sep 2, 2024. It is now read-only.

Commit 1fd11ff

Browse files
committed
added file storage tests fix #7
1 parent 4e398c0 commit 1fd11ff

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

storage_test.go

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,87 @@
11
package staticbackend
22

33
import (
4+
"fmt"
5+
"io"
6+
"mime/multipart"
7+
"net/http"
8+
"net/http/httptest"
9+
"os"
10+
"path"
11+
"strings"
412
"testing"
513

14+
"github.com/staticbackendhq/core/backend"
615
"github.com/staticbackendhq/core/internal"
16+
"github.com/staticbackendhq/core/middleware"
717
)
818

19+
func TestFileUpload(t *testing.T) {
20+
pr, pw := io.Pipe()
21+
22+
writer := multipart.NewWriter(pw)
23+
24+
go func() {
25+
defer writer.Close()
26+
27+
part, err := writer.CreateFormFile("file", "upload.test")
28+
if err != nil {
29+
t.Error(err)
30+
}
31+
32+
if _, err := part.Write([]byte("testing file upload")); err != nil {
33+
t.Error(err)
34+
}
35+
}()
36+
37+
req := httptest.NewRequest("POST", "/storage/upload", pr)
38+
req.Header.Add("Content-Type", writer.FormDataContentType())
39+
req.Header.Set("SB-PUBLIC-KEY", pubKey)
40+
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", adminToken))
41+
42+
stdAuth := []middleware.Middleware{
43+
middleware.WithDB(backend.DB, backend.Cache, getStripePortalURL),
44+
middleware.RequireAuth(backend.DB, backend.Cache),
45+
}
46+
47+
w := httptest.NewRecorder()
48+
h := middleware.Chain(http.HandlerFunc(upload), stdAuth...)
49+
h.ServeHTTP(w, req)
50+
51+
if w.Code != 200 {
52+
t.Errorf("Expected 200, got %d", w.Code)
53+
}
54+
55+
var data backend.SavedFile
56+
if err := parseBody(w.Result().Body, &data); err != nil {
57+
t.Error(err)
58+
}
59+
defer w.Result().Body.Close()
60+
61+
t.Log(data)
62+
63+
// let's remove the web-based prefix to test if file was saved
64+
localFilePath := strings.Replace(data.URL, "http://localhost:8099/localfs", "", -1)
65+
66+
localFilePath = path.Join(os.TempDir(), localFilePath)
67+
68+
if _, err := os.Stat(localFilePath); os.IsNotExist(err) {
69+
t.Errorf("Expected file %s to exists", localFilePath)
70+
}
71+
72+
// test the delete file endpoint
73+
delPath := fmt.Sprintf("/sudostorage/delete?id=%s", data.ID)
74+
resp := dbReq(t, deleteFile, "DELETE", delPath, nil)
75+
if resp.StatusCode != 200 {
76+
t.Errorf("Expected 200, go %d", resp.StatusCode)
77+
}
78+
79+
// the file should not exists anymore
80+
if _, err := os.Stat(localFilePath); !os.IsNotExist(err) {
81+
t.Errorf("Expected file %s to not exists", localFilePath)
82+
}
83+
}
84+
985
func TestCleanUpFileName(t *testing.T) {
1086
fakeNames := make(map[string]string)
1187
fakeNames[""] = ""

0 commit comments

Comments
 (0)