func_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package test
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/fatedier/frp/utils/net"
  11. )
  12. var (
  13. ECHO_PORT int64 = 10711
  14. HTTP_PORT int64 = 10710
  15. ECHO_TEST_STR string = "Hello World\n"
  16. HTTP_RES_STR string = "Hello World"
  17. )
  18. func TestEchoServer(t *testing.T) {
  19. c, err := net.ConnectTcpServer(fmt.Sprintf("127.0.0.1:%d", ECHO_PORT))
  20. if err != nil {
  21. t.Fatalf("connect to echo server error: %v", err)
  22. }
  23. timer := time.Now().Add(time.Duration(5) * time.Second)
  24. c.SetDeadline(timer)
  25. c.Write([]byte(ECHO_TEST_STR))
  26. c.Write('\n')
  27. br := bufio.NewReader(c)
  28. buf, err := br.ReadString('\n')
  29. if err != nil {
  30. t.Fatalf("read from echo server error: %v", err)
  31. }
  32. if ECHO_TEST_STR != buf {
  33. t.Fatalf("content error, send [%s], get [%s]", strings.Trim(ECHO_TEST_STR, "\n"), strings.Trim(buf, "\n"))
  34. }
  35. }
  36. func TestHttpServer(t *testing.T) {
  37. client := &http.Client{}
  38. req, _ := http.NewRequest("GET", fmt.Sprintf("http://127.0.0.1:%d", HTTP_PORT), nil)
  39. res, err := client.Do(req)
  40. if err != nil {
  41. t.Fatalf("do http request error: %v", err)
  42. }
  43. if res.StatusCode == 200 {
  44. body, err := ioutil.ReadAll(res.Body)
  45. if err != nil {
  46. t.Fatalf("read from http server error: %v", err)
  47. }
  48. bodystr := string(body)
  49. if bodystr != HTTP_RES_STR {
  50. t.Fatalf("content from http server error [%s], correct string is [%s]", bodystr, HTTP_RES_STR)
  51. }
  52. } else {
  53. t.Fatalf("http code from http server error [%d]", res.StatusCode)
  54. }
  55. }