Commit b5a8e689 authored by Lukas Böhm's avatar Lukas Böhm 🎱
Browse files

FIX TESTING

parent 983e3b80
......@@ -25,7 +25,6 @@ type endpointREST func(http.ResponseWriter, *http.Request) *HTTPError
func (fn endpointREST) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if e := fn(w, r); e != nil { // e is *HTTPError, not os.Error.
//fmt.Printf("Error (%s): %s - %i", e.Error.Error(), e.Message, e.Code)
if e.Code == 401 {
w.Header().Set("WWW-Authenticate", `Basic realm="Please enter the password"`)
}
......@@ -54,22 +53,19 @@ func AllShares(w http.ResponseWriter, _ *http.Request) *HTTPError {
func GetShare(w http.ResponseWriter, r *http.Request) *HTTPError {
fmt.Println("Get Share")
vars := mux.Vars(r)
if vars["id"] == "" {
shareID, err := uuid.Parse(vars["id"])
if err != nil {
return &HTTPError{ errors.New("invalid URL"), "invalid URL param", 400 }
}
db, err := GetDatabase()
if err != nil {
return &HTTPError{err, "Can't get database", 500}
}
var share Share
err = db.Preload("Attachments").Where("ID = ?", vars["id"]).First(&share).Error
err = db.Preload("Attachments").Where("ID = ?", shareID).First(&share).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return &HTTPError{err, "Record not found", 404}
}
......@@ -166,12 +162,6 @@ func OpenShare(w http.ResponseWriter, r *http.Request) *HTTPError {
return &HTTPError{err, "Can't create data", 500}
}
// create temporary dir
err = os.MkdirAll(filepath.Join(config.mediaDir, "temp", newShare.ID.String()), os.ModePerm)
if err != nil {
return &HTTPError{err, "Can't create directory", 500}
}
return SendJSON(w, newShare)
}
......@@ -271,11 +261,12 @@ func UploadAttachment(w http.ResponseWriter, r *http.Request) *HTTPError {
return SendJSON(w, att)
}
/////////////////////////////////
////////// functions ////////////
/////////////////////////////////
func ConfigureRoutes() {
fmt.Println("ConfigureRoutes")
router := mux.NewRouter().StrictSlash(true)
handler := cors.Default().Handler(router)
......
......@@ -3,12 +3,12 @@ package main
import (
"encoding/json"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
......@@ -21,6 +21,16 @@ var shares = []Share {
IsPublic: false,
IsTemporary: false,
Password: "test123",
Attachments: []Attachment {
{
ID: uuid.MustParse("913134c0-894f-4c4d-b545-92ec373168b1"),
Filename: "kekw.txt",
Filesize: 123456,
IsEncrypted: false,
ShareID: uuid.MustParse("5713d228-a042-446d-a5e4-183b19fa832a"),
},
},
},
{
ID: uuid.MustParse("f43b0e48-13cc-4c6c-8a23-3a18a670effd"),
......@@ -36,15 +46,6 @@ var shares = []Share {
IsTemporary: true,
},
}
var attachments = []Attachment {
{
ID: uuid.MustParse("913134c0-894f-4c4d-b545-92ec373168b1"),
Filename: "kekw.txt",
Filesize: 123456,
IsEncrypted: false,
ShareID: uuid.MustParse("5713d228-a042-446d-a5e4-183b19fa832a"),
},
}
func Reset() {
db, err := GetDatabase()
......@@ -60,22 +61,6 @@ func Reset() {
for _, sh := range shares {
db.Create(&sh)
}
for _, att := range attachments {
db.Create(&att)
}
}
func DoRequest(t *testing.T, method string, url string, body io.Reader, handle func(w http.ResponseWriter, r *http.Request) *HTTPError, header map[string][]string) *httptest.ResponseRecorder {
req, err := http.NewRequest(method, url, body)
if header != nil {
req.Header = header
}
if err != nil {
t.Fatal(err)
}
res := httptest.NewRecorder()
handle(res, req)
return res
}
/////////////////////////////////////
......@@ -83,63 +68,90 @@ func DoRequest(t *testing.T, method string, url string, body io.Reader, handle f
/////////////////////////////////////
func TestAllShares(t *testing.T) {
Reset()
r := mux.NewRouter()
r.Handle("/shares", endpointREST(AllShares)).Methods("GET")
ts := httptest.NewServer(r)
defer ts.Close()
t.Run("happy path", func(t *testing.T) {
res := DoRequest(t, "GET", "http://localhost:6969/shares", nil, AllShares, nil)
req, _ := http.NewRequest("GET", ts.URL + "/shares", nil)
res, _ := http.DefaultClient.Do(req)
body, _ := ioutil.ReadAll(res.Body)
var erg []Share
json.Unmarshal(res.Body.Bytes(), &erg)
assert.Equal(t, http.StatusOK, res.Code)
//assert.Equal(t, shares[1], erg[0])
json.Unmarshal(body, &erg)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, shares[1], erg[0])
})
}
func TestGetShare(t *testing.T) {
Reset()
router := mux.NewRouter()
ts := httptest.NewServer(router)
router.Handle("/share/{id}", endpointREST(GetShare)).Methods("GET")
defer ts.Close()
t.Run("happy path", func(t *testing.T) {
header := map[string][]string{
"Authorization": { "Basic NTcxM2QyMjgtYTA0Mi00NDZkLWE1ZTQtMTgzYjE5ZmE4MzJhOnRlc3QxMjM=" },
}
res := DoRequest(t, "GET", "http://localhost:6969/share/5713d228-a042-446d-a5e4-183b19fa832a", nil, GetShare, header)
assert.Equal(t, http.StatusOK, res.Code)
req, _ := http.NewRequest("GET", ts.URL + "/share/5713d228-a042-446d-a5e4-183b19fa832a", nil)
req.Header = header
res, _ := http.DefaultClient.Do(req)
body, _ := ioutil.ReadAll(res.Body)
var actual Share
var expected Share
json.Unmarshal(body, &actual)
ex, _ := json.Marshal(shares[0])
json.Unmarshal(ex, &expected)
assert.Equal(t, http.StatusOK, res.StatusCode)
assert.Equal(t, expected, actual)
})
t.Run("unauthorized", func(t *testing.T) {
res := DoRequest(t, "GET", "http://localhost:6969/share/5713d228-a042-446d-a5e4-183b19fa832a", nil, GetShare, nil)
assert.Equal(t, http.StatusUnauthorized, res.Code)
req, _ := http.NewRequest("GET", ts.URL + "/share/5713d228-a042-446d-a5e4-183b19fa832a", nil)
res, _ := http.DefaultClient.Do(req)
assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
})
t.Run("not found", func(t *testing.T) {
res := DoRequest(t, "GET", "http://localhost:6969/share/4015a76b-09d0-402b-814f-bd9fa48ce8e1", nil, GetShare, nil)
assert.Equal(t, http.StatusNotFound, res.Code)
req, _ := http.NewRequest("GET", ts.URL + "/share/4015a76b-09d0-402b-814f-bd9fa48ce8e1", nil)
res, _ := http.DefaultClient.Do(req)
assert.Equal(t, http.StatusNotFound, res.StatusCode)
})
t.Run("not ready", func(t *testing.T) {
res := DoRequest(t, "GET", "http://localhost:6969/share/a558aca3-fb40-400b-8dc6-ae49c705c791", nil, GetShare, nil)
assert.Equal(t, http.StatusFailedDependency, res.Code)
req, _ := http.NewRequest("GET", ts.URL + "/share/a558aca3-fb40-400b-8dc6-ae49c705c791", nil)
res, _ := http.DefaultClient.Do(req)
assert.Equal(t, http.StatusForbidden, res.StatusCode)
})
}
func TestDownloadFile(t *testing.T) {
t.Run("happy path", func(t *testing.T) {
}
func TestOpenShare(t *testing.T) {
// Created
b, _ := json.Marshal(Share {
//ID: uuid.MustParse("e5134044-2704-4864-85be-318fb158009f"),
Name: "TopKek",
})
read := strings.NewReader(string(b))
// Sucessfully created
res := DoRequest(t, "POST", "http://localhost:6969/shares", read, OpenShare, nil)
assert.Equal(t, http.StatusCreated, res.Code)
// Bad request
res = DoRequest(t, "POST", "http://localhost:6969/shares", nil, OpenShare, nil)
assert.Equal(t, http.StatusBadRequest, res.Code)
}
//func TestOpenShare(t *testing.T) {
// t.Run("happy path", func(t *testing.T) {
// b, _ := json.Marshal(Share {
// ID: uuid.MustParse("e5134044-2704-4864-85be-318fb158009f"),
// Name: "TopKek",
// })
// read := strings.NewReader(string(b))
// res := DoRequest(t, "POST", "http://localhost:6969/shares", read, OpenShare, nil)
// assert.Equal(t, http.StatusCreated, res.Code)
// })
//
// t.Run("bad request", func(t *testing.T) {
// res := DoRequest(t, "POST", "http://localhost:6969/shares", nil, OpenShare, nil)
// assert.Equal(t, http.StatusBadRequest, res.Code)
// })
//}
func TestCloseShare(t *testing.T) {
t.Run("happy path", func(t *testing.T) {
......
......@@ -9,16 +9,6 @@ import (
"time"
)
const nuid = "00000000-0000-0000-0000-000000000000"
//type Base struct {
// ID uuid.UUID `json:"id" gorm:"type:uuid; primary_key"`
// CreatedAt time.Time `json:"-"`
// UpdatedAt time.Time `json:"-"`
// DeletedAt *time.Time `json:"-" sql:"index"`
//}
// Share has many Attachments, ShareID is the foreign key
type Share struct {
ID uuid.UUID `json:"id" gorm:"type:uuid; primary_key"`
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment