gpaste/api/http_test.go

281 lines
7.4 KiB
Go
Raw Normal View History

2022-01-20 02:44:33 +00:00
package api_test
2022-01-18 19:58:30 +00:00
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
2022-01-21 06:17:52 +00:00
"strings"
2022-01-18 19:58:30 +00:00
"testing"
2022-01-21 06:17:52 +00:00
"time"
2022-01-18 19:58:30 +00:00
"git.t-juice.club/torjus/gpaste"
2022-01-20 02:44:33 +00:00
"git.t-juice.club/torjus/gpaste/api"
2022-01-21 06:17:52 +00:00
"git.t-juice.club/torjus/gpaste/files"
2022-01-20 02:35:55 +00:00
"git.t-juice.club/torjus/gpaste/users"
2022-01-22 09:19:18 +00:00
"github.com/google/go-cmp/cmp"
2022-01-21 06:17:52 +00:00
"github.com/google/uuid"
2022-01-18 19:58:30 +00:00
)
func TestHandlers(t *testing.T) {
2022-01-23 16:22:16 +00:00
//cfg := &gpaste.ServerConfig{
// SigningSecret: "abc123",
// Store: &gpaste.ServerStoreConfig{
// Type: "memory",
// },
// URL: "http://localhost:8080",
//}
//hs := api.NewHTTPServer(cfg)
t.Run("index", func(t *testing.T) {
hs := newServer()
2022-01-18 19:58:30 +00:00
rr := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
hs.Handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("Returned unexpected status")
}
expectedBody := "index"
if body := rr.Body.String(); body != expectedBody {
t.Errorf("Body does not match expected. Got %s want %s", body, expectedBody)
}
})
2022-01-23 16:22:16 +00:00
t.Run("api", func(t *testing.T) {
t.Run("file", func(t *testing.T) {
// POST /api/file
t.Run("POST", func(t *testing.T) {
hs := newServer()
rr := httptest.NewRecorder()
buf := &bytes.Buffer{}
mw := multipart.NewWriter(buf)
fw, err := mw.CreateFormFile("test", "test.txt")
if err != nil {
t.Fatalf("Unable to create form file: %s", err)
}
expectedData := "Test OMEGALUL PLS."
if _, err := io.WriteString(fw, expectedData); err != nil {
t.Fatalf("Unable to write body to buffer: %s", err)
}
mw.Close()
req := httptest.NewRequest(http.MethodPost, "/api/file", buf)
req.Header.Add("Content-Type", mw.FormDataContentType())
hs.Handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusAccepted {
t.Errorf("Returned unexpected status. Got %d want %d", status, http.StatusAccepted)
}
var expectedResp []struct {
Message string `json:"message"`
ID string `json:"id"`
URL string `json:"url"`
}
decoder := json.NewDecoder(rr.Result().Body)
if err := decoder.Decode(&expectedResp); err != nil {
t.Fatalf("error decoding response: %s", err)
}
if l := len(expectedResp); l != 1 {
t.Errorf("Response has wrong length. Got %d want %d", l, 1)
}
uploadID := expectedResp[0].ID
if uploadID == "" {
t.Errorf("Response has empty id")
}
retrieved, err := hs.Files.Get(uploadID)
if err != nil {
t.Errorf("Error retrieving file: %s", err)
}
defer retrieved.Body.Close()
retBuf := new(bytes.Buffer)
io.Copy(retBuf, retrieved.Body)
if diff := cmp.Diff(retBuf.String(), expectedData); diff != "" {
t.Errorf("Retrieved file mismatch: %s", diff)
}
})
// GET /api/file/id
t.Run("GET", func(t *testing.T) {
hs := newServer()
fileData := "abc123456"
sr := io.NopCloser(strings.NewReader(fileData))
file := &files.File{
ID: uuid.NewString(),
OriginalFilename: "test-file.txt",
MaxViews: 99,
ExpiresOn: time.Now().Add(90 * time.Second),
Body: sr,
}
hs.Files.Store(file)
rr := httptest.NewRecorder()
url := fmt.Sprintf("/api/file/%s", file.ID)
req := httptest.NewRequest(http.MethodGet, url, nil)
hs.Handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("Returned unexpected status. Got %d want %d", status, http.StatusAccepted)
t.Logf(url)
}
if diff := cmp.Diff(rr.Body.String(), fileData); diff != "" {
t.Errorf("Returned body does not match expected: %s", diff)
}
})
// DELETE /api/file/id
t.Run("DELETE", func(t *testing.T) {
hs := newServer()
fileBody := io.NopCloser(strings.NewReader("roflcopter"))
file := &files.File{
ID: uuid.NewString(),
OriginalFilename: "testpls.txt",
MaxViews: 9,
ExpiresOn: time.Now().Add(10 * time.Hour),
Body: fileBody,
}
if err := hs.Files.Store(file); err != nil {
t.Fatalf("Error storing file: %s", err)
}
rr := httptest.NewRecorder()
url := fmt.Sprintf("/api/file/%s", file.ID)
req := httptest.NewRequest(http.MethodDelete, url, nil)
hs.Handler.ServeHTTP(rr, req)
if rr.Result().StatusCode != http.StatusOK {
t.Fatalf("Delete returned wrong status: %s", rr.Result().Status)
}
if _, err := hs.Files.Get(file.ID); err == nil {
t.Errorf("Getting after delete returned no error")
}
})
})
// /api/user
t.Run("user", func(t *testing.T) {
t.Run("POST", func(t *testing.T) {
hs := newServer()
adminPw := "admin"
admin := &users.User{
Username: "admin",
Role: users.RoleAdmin,
}
_ = admin.SetPassword(adminPw)
_ = hs.Users.Store(admin)
token, err := hs.Auth.Login(admin.Username, adminPw)
if err != nil {
t.Fatalf("error getting admin token: %s", err)
}
requestData := &api.RequestAPIUserCreate{
Username: "test",
Password: "test",
}
body := new(bytes.Buffer)
encoder := json.NewEncoder(body)
if err := encoder.Encode(requestData); err != nil {
t.Fatalf("Error encoding data: %s", err)
}
rr := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/user", body)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
hs.Handler.ServeHTTP(rr, req)
if rr.Result().StatusCode != http.StatusAccepted {
t.Fatalf("Create returned wrong status: %s", rr.Result().Status)
}
user, err := hs.Users.Get(requestData.Username)
if err != nil {
t.Fatalf("Unable to get user after create: %s", err)
}
expectedUser := &users.User{
Username: requestData.Username,
Role: users.RoleUser,
}
ignorePW := cmp.FilterPath(func(p cmp.Path) bool {
return p.String() == "HashedPassword"
}, cmp.Ignore())
if diff := cmp.Diff(user, expectedUser, ignorePW); diff != "" {
t.Errorf("User does not match expected: %s", diff)
}
})
2022-01-18 19:58:30 +00:00
})
2022-01-19 21:25:19 +00:00
2022-01-23 16:22:16 +00:00
// /api/login
t.Run("Login", func(t *testing.T) {
2022-01-22 09:19:18 +00:00
hs := newServer()
2022-01-23 16:22:16 +00:00
// TODO: Add test
username := "admin"
password := "admin"
user := &users.User{Username: username}
if err := user.SetPassword(password); err != nil {
t.Fatalf("Error setting user password: %s", err)
2022-01-22 09:19:18 +00:00
}
2022-01-23 16:22:16 +00:00
if err := hs.Users.Store(user); err != nil {
t.Fatalf("Error storing user: %s", err)
2022-01-22 09:19:18 +00:00
}
2022-01-23 16:22:16 +00:00
requestData := struct {
Username string `json:"username"`
Password string `json:"password"`
}{
Username: username,
Password: password,
2022-01-22 09:19:18 +00:00
}
2022-01-23 16:22:16 +00:00
2022-01-22 09:19:18 +00:00
body := new(bytes.Buffer)
encoder := json.NewEncoder(body)
2022-01-23 16:22:16 +00:00
if err := encoder.Encode(&requestData); err != nil {
t.Fatalf("Error encoding request body: %s", err)
2022-01-22 09:19:18 +00:00
}
rr := httptest.NewRecorder()
2022-01-23 16:22:16 +00:00
req := httptest.NewRequest(http.MethodPost, "/api/login", body)
2022-01-22 09:19:18 +00:00
2022-01-23 16:22:16 +00:00
hs.Handler.ServeHTTP(rr, req)
2022-01-22 09:19:18 +00:00
2022-01-23 16:22:16 +00:00
responseData := struct {
Token string `json:"token"`
}{}
2022-01-22 09:19:18 +00:00
2022-01-23 16:22:16 +00:00
decoder := json.NewDecoder(rr.Body)
if err := decoder.Decode(&responseData); err != nil {
t.Fatalf("Error decoding response: %s", err)
2022-01-22 09:19:18 +00:00
}
2022-01-23 16:22:16 +00:00
if _, err := hs.Auth.ValidateToken(responseData.Token); err != nil {
t.Fatalf("Unable to validate received token: %s", err)
2022-01-22 09:19:18 +00:00
}
})
})
2022-01-23 16:22:16 +00:00
2022-01-22 09:19:18 +00:00
}
func newServer() *api.HTTPServer {
cfg := &gpaste.ServerConfig{
SigningSecret: "abc123",
Store: &gpaste.ServerStoreConfig{
Type: "memory",
},
URL: "http://localhost:8080",
}
return api.NewHTTPServer(cfg)
2022-01-18 19:58:30 +00:00
}