plugins/tests/http_test.go

68 lines
1.7 KiB
Go
Raw Normal View History

package tests
import (
"apigo.cloud/git/apigo/gojs"
_ "apigo.cloud/git/apigo/plugins/http"
"github.com/ssgo/s"
2024-03-24 12:28:02 +08:00
"os"
"path/filepath"
"strings"
"testing"
)
2024-03-24 12:28:02 +08:00
func StartHttpServer(port string) *s.AsyncServer {
s.Register(0, "/echo", func(in map[string]interface{}) map[string]interface{} {
return in
}, "")
s.Register(0, "/jump", func(response *s.Response) {
response.Location("/echo?aaa=222")
}, "")
2024-03-24 12:28:02 +08:00
s.Config.Listen = port
return s.AsyncStart()
}
2024-03-24 12:28:02 +08:00
func TestHttp(t *testing.T) {
if files, err := os.ReadDir("http_tests"); err == nil {
for _, f := range files {
if !f.IsDir() && strings.HasSuffix(f.Name(), "_test.js") {
testName := f.Name()[0 : len(f.Name())-8]
r, err := gojs.RunFile(filepath.Join("http_tests", f.Name()), &gojs.RuntimeOption{
Globals: map[string]interface{}{
"startTestServer": StartHttpServer,
},
})
Test(t, testName, r == true && err == nil, err)
}
}
}
}
func TestH2C(t *testing.T) {
s.Register(0, "/echo", func(in map[string]interface{}) map[string]interface{} {
return in
}, "")
s.Config.Listen = ""
as := s.AsyncStart()
defer as.Stop()
2024-03-24 12:28:02 +08:00
rt := gojs.New(nil)
defer rt.Close()
rt.JsCtx.Globals().Set("server", rt.JsCtx.String(as.Addr))
2024-03-24 12:28:02 +08:00
_, err := rt.Run(`
import http from "apigo.cloud/git/apigo/plugins/http"
http.get('http://'+server+'/echo?aaa=111')
`)
2024-03-24 12:28:02 +08:00
//fmt.Println(u.BMagenta(err))
Test(t, "get for h2c", err != nil && strings.Contains(err.Error(), "transport connection broken"))
2024-03-24 12:28:02 +08:00
r, err := rt.Run(`
import http from "apigo.cloud/git/apigo/plugins/http"
let c = http.newH2C(10)
r = c.post('http://'+server+'/echo', {aaa:111})
if(r.aaa != 111) throw new Error('aaa is '+r.aaa+' not 111')
return true
`)
Test(t, "post for h2c", r == true && err == nil, r, err)
}