dndex/server/dump_test.go

94 lines
2.2 KiB
Go

package server
import (
"bytes"
"encoding/json"
"fmt"
"local/dndex/storage/entity"
"net/http"
"net/http/httptest"
"testing"
)
func TestDump(t *testing.T) {
cases := map[string]func(*testing.T, *REST, func(*http.Request)){
"dump out": func(t *testing.T, rest *REST, scope func(r *http.Request)) {
r := httptest.NewRequest(http.MethodGet, "/dump", nil)
w := httptest.NewRecorder()
scope(r)
rest.dump(w, r)
if w.Code != http.StatusOK {
t.Fatal(w.Code)
}
var dump map[string][]entity.One
if err := json.Unmarshal(w.Body.Bytes(), &dump); err != nil {
t.Fatal(err)
}
if len(dump) == 0 {
t.Fatal(dump)
}
for _, ones := range dump {
for _, one := range ones {
if fmt.Sprint(one) == fmt.Sprint(entity.One{}) {
t.Fatal(one)
}
if len(one.Attachments) == 0 {
t.Fatal(one)
}
}
}
t.Logf("%d: %s: %+v", w.Code, w.Body.Bytes(), dump)
},
"dump in": func(t *testing.T, rest *REST, scope func(r *http.Request)) {
oneA := randomOne()
oneB := randomOne()
b, err := json.MarshalIndent(
map[string][]entity.One{testNamespace: []entity.One{oneA, oneB}},
"",
" ",
)
if err != nil {
t.Fatal(err)
}
t.Logf("dumping in %s", b)
r := httptest.NewRequest(http.MethodPost, "/dump", bytes.NewReader(b))
w := httptest.NewRecorder()
scope(r)
rest.dump(w, r)
if w.Code != http.StatusOK {
t.Fatal(w.Code)
}
foundA := false
foundB := false
b = w.Body.Bytes()
testEntitiesGetNResponse(t, w.Body, func(one shortEntity) bool {
foundA = foundA || one.ID == oneA.ID
foundB = foundB || one.ID == oneB.ID
return foundA && foundB
})
for _, one := range []entity.One{oneA, oneB} {
t.Logf("looking for %s", one.Name)
w = testEntitiesMethod(t, scope, rest, http.MethodGet, "/"+one.ID, ``)
if w.Code != http.StatusOK {
t.Fatal(w.Code, ":", string(w.Body.Bytes()))
}
testEntitiesGetOneResponse(t, w.Body, func(got entity.One) bool {
got.Modified = 0
one.Modified = 0
return fmt.Sprint(one) == fmt.Sprint(got)
})
}
},
}
for name, foo := range cases {
bar := foo
t.Run(name, func(t *testing.T) {
rest, scope, clean := testREST(t)
bar(t, rest, scope)
defer clean()
})
}
}