package main
import (
"fmt"
"io/ioutil"
"local/notes-server/config"
"local/notes-server/server"
"log"
"net/http"
"net/http/httptest"
"os"
"path"
"regexp"
"strings"
"testing"
)
func TestAll(t *testing.T) {
makeFiles(t)
defer os.RemoveAll(config.Root)
s := makeServer(t)
defer s.Close()
testServer(t, s.URL)
}
func makeFiles(t *testing.T) {
d, err := ioutil.TempDir(os.TempDir(), "pattern*")
if err != nil {
t.Fatal(err)
}
config.Root = d
for _, dir := range []string{"dirA", "dirB"} {
if err := os.MkdirAll(path.Join(d, dir), os.ModePerm); err != nil {
t.Fatal(err)
}
for _, file := range []string{"fileA", "fileB"} {
content := fmt.Sprintf("hello from %s/%s/%s", d, dir, file)
err := ioutil.WriteFile(
path.Join(d, dir, file),
[]byte(content),
os.ModePerm,
)
if err != nil {
t.Fatal(err)
}
}
}
}
func makeServer(t *testing.T) *httptest.Server {
s := server.New()
if err := s.Routes(); err != nil {
t.Fatal(err)
}
return httptest.NewServer(s)
}
func testServer(t *testing.T, url string) {
testCreate(t, url)
testEdit(t, url)
testDir(t, url)
testFile(t, url)
testNavRootDir(t, url)
testNavRootFile(t, url)
testNavDirDir(t, url)
testNavDirFile(t, url)
}
func testCreate(t *testing.T, url string) {
for _, path := range []string{"dirX/fileX", "fileX"} {
resp, err := http.Get(url + "/create/" + path)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatal(resp.StatusCode)
}
b, _ := ioutil.ReadAll(resp.Body)
s := string(b)
log.Println(string(s))
if ok := assertHasMultilink(s, path); !ok {
t.Error(err)
}
if ok := assertHasForm(s, "/submit/"+path); !ok {
t.Error(err)
}
if ok := assertHasTextArea(s); !ok {
t.Error(err)
}
if ok := assertHasSubmit(s); !ok {
t.Error(err)
}
}
}
func testEdit(t *testing.T, url string) {
for _, path := range []string{"dirX/fileX", "fileX"} {
resp, err := http.Get(url + "/edit/" + path)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatal(resp.StatusCode)
}
b, _ := ioutil.ReadAll(resp.Body)
s := string(b)
if ok := assertHasMultilink(s, path); !ok {
t.Error(err)
}
if ok := assertHasForm(s); !ok {
t.Error(err)
}
if ok := assertHasTextArea(s); !ok {
t.Error(err)
}
if ok := assertHasSubmit(s); !ok {
t.Error(err)
}
}
}
func testDir(t *testing.T, url string) {
t.Error("not impl")
}
func testFile(t *testing.T, url string) {
t.Error("not impl")
}
func testNavRootDir(t *testing.T, url string) {
t.Error("not impl")
}
func testNavRootFile(t *testing.T, url string) {
t.Error("not impl")
}
func testNavDirDir(t *testing.T, url string) {
t.Error("not impl")
}
func testNavDirFile(t *testing.T, url string) {
t.Error("not impl")
}
func assertHasMultilink(body string, segments ...string) bool {
if !strings.Contains(body, `/notes/`) {
return false
}
for _, segment := range segments {
regexp := regexp.MustCompile(``)
if !regexp.MatchString(body) {
return false
}
}
return true
}
func assertHasForm(body string, action ...string) bool {
return strings.Contains(body, `