101 lines
2.4 KiB
Go
101 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"os"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func Test_Core(t *testing.T) {
|
|
server := httptest.NewUnstartedServer(nil)
|
|
server.Close()
|
|
wasDBPath := os.Getenv("DBPATH")
|
|
wasPort := os.Getenv("PORT")
|
|
defer os.Setenv("DBPATH", wasDBPath)
|
|
defer os.Setenv("PORT", wasPort)
|
|
tmpf, err := ioutil.TempFile("", "testdb.db")
|
|
if err != nil {
|
|
t.Fatalf("cannot create temp db file: %v", err)
|
|
}
|
|
defer os.Remove(tmpf.Name())
|
|
os.Setenv("DBPATH", tmpf.Name())
|
|
os.Setenv("PORT", ":"+strings.Split(server.Listener.Addr().String(), ":")[1])
|
|
go core()
|
|
time.Sleep(time.Second * 5)
|
|
|
|
client := &http.Client{
|
|
Timeout: time.Second * 5,
|
|
}
|
|
testhost := "http://localhost" + os.Getenv("PORT")
|
|
|
|
cases := []struct {
|
|
method string
|
|
path string
|
|
body string
|
|
status int
|
|
pre func()
|
|
post func()
|
|
}{
|
|
{
|
|
method: "post",
|
|
path: "api/feed",
|
|
body: `{"url":"https://utw.me/feed/", "refresh":"1m", "items":"Fate", "content":"25"}`,
|
|
status: 200,
|
|
post: func() { time.Sleep(time.Second * 10) },
|
|
},
|
|
{
|
|
method: "get",
|
|
path: "api/feed",
|
|
body: "https://utw.me/feed/",
|
|
status: 200,
|
|
},
|
|
{
|
|
method: "get",
|
|
path: "api/feed/item",
|
|
body: "https___utw_me_feed_.20180108_https___utw_me_2018_01_08_fate_apocrypha_25_",
|
|
status: 200,
|
|
},
|
|
}
|
|
for _, c := range cases {
|
|
c.method = strings.ToUpper(c.method)
|
|
if c.pre != nil {
|
|
c.pre()
|
|
}
|
|
loc, err := url.Parse(testhost + "/" + c.path)
|
|
if err != nil {
|
|
t.Errorf("cannot create loc %s+%s: %v", testhost, c.path, err)
|
|
}
|
|
var body io.Reader = nil
|
|
if c.method == "GET" && c.body != "" {
|
|
v := url.Values{}
|
|
v.Add("url", c.body)
|
|
loc.RawQuery = v.Encode()
|
|
} else if c.body != "" {
|
|
body = bytes.NewBuffer([]byte(c.body))
|
|
}
|
|
req, err := http.NewRequest(c.method, loc.String(), body)
|
|
if err != nil {
|
|
t.Errorf("cannot create request %s:%s: %v", c.method, loc.String(), err)
|
|
}
|
|
if resp, err := client.Do(req); err != nil {
|
|
t.Errorf("cannot %s to %s: %v", c.method, loc.String(), err)
|
|
} else if resp.StatusCode != c.status {
|
|
t.Errorf("wrong %s status to %s: %v, expected %v", c.method, loc.String(), resp.StatusCode, c.status)
|
|
} else if b, err := ioutil.ReadAll(resp.Body); err != nil {
|
|
t.Errorf("cannot read body on %s to %s: %v", c.method, loc.String(), err)
|
|
} else {
|
|
t.Logf("resp body: %s", b)
|
|
}
|
|
if c.post != nil {
|
|
c.post()
|
|
}
|
|
}
|
|
}
|