80 lines
2.4 KiB
Go
80 lines
2.4 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"syscall"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
var testPort = "39231"
|
|
|
|
func Test_Server(t *testing.T) {
|
|
server := httptest.NewUnstartedServer(nil)
|
|
server.Close()
|
|
testPort = strings.Split(server.Listener.Addr().String(), ":")[1]
|
|
|
|
var err error
|
|
s, err := New(testPort, func(string, string, string, []string, time.Duration) {}, func(string, int) (string, error) { return "", nil }, func(string) (string, error) { return "", nil }, func(string) (string, error) { return "", nil })
|
|
if err != nil {
|
|
t.Errorf("failed to create server: %v", err)
|
|
}
|
|
go s.Serve()
|
|
time.Sleep(time.Second * 1)
|
|
if err := checkStatus("GET", "", http.StatusNotFound); err != nil {
|
|
t.Errorf(err.Error())
|
|
}
|
|
if err := checkStatus("GET", "api", http.StatusNotFound); err != nil {
|
|
t.Errorf(err.Error())
|
|
}
|
|
if err := checkStatus("GET", "api/feed", http.StatusBadRequest); err != nil {
|
|
t.Errorf(err.Error())
|
|
}
|
|
if err := checkStatus("POST", "api/feed", http.StatusBadRequest); err != nil {
|
|
t.Errorf(err.Error())
|
|
}
|
|
if err := checkStatus("PUT", "api/feed", http.StatusBadRequest, "invalid json"); err != nil {
|
|
t.Errorf(err.Error())
|
|
}
|
|
if err := checkStatus("POST", "api/feed", http.StatusBadRequest, `{"url":"hello/world", "refresh":"1m"}`); err != nil {
|
|
t.Errorf(err.Error())
|
|
}
|
|
if err := checkStatus("PUT", "api/feed", http.StatusOK, `{"url":"localhost:1234", "refresh":"1m", "tags":["a", "b"]}`); err != nil {
|
|
t.Errorf(err.Error())
|
|
}
|
|
if err := checkStatus("GET", "api/feed/localhost_1234", http.StatusOK); err != nil {
|
|
t.Errorf(err.Error())
|
|
}
|
|
if err := checkStatus("GET", "api/feed/1:localhost_1234", http.StatusOK); err != nil {
|
|
t.Errorf(err.Error())
|
|
}
|
|
if err := checkStatus("GET", "api/feed/item/localhost_1234", http.StatusOK); err != nil {
|
|
t.Errorf(err.Error())
|
|
}
|
|
if err := checkStatus("GET", "api/feed/tag/b", http.StatusOK); err != nil {
|
|
t.Errorf(err.Error())
|
|
}
|
|
syscall.Kill(syscall.Getpid(), syscall.SIGINT)
|
|
}
|
|
|
|
func checkStatus(method, path string, code int, body ...string) error {
|
|
b := bytes.NewBuffer(nil)
|
|
if len(body) > 0 {
|
|
b = bytes.NewBufferString(body[0])
|
|
}
|
|
client := &http.Client{}
|
|
r, _ := http.NewRequest(method, "http://localhost:"+testPort+"/"+path, b)
|
|
resp, err := client.Do(r)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to %v server: %v", method, err)
|
|
}
|
|
if resp.StatusCode != code {
|
|
return fmt.Errorf("%s %q did not return %v: %v", method, path, code, resp.StatusCode)
|
|
}
|
|
return nil
|
|
}
|