1
0

func_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package tests
  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 init() {
  19. go StartEchoServer()
  20. go StartHttpServer()
  21. time.Sleep(500 * time.Millisecond)
  22. }
  23. func TestEchoServer(t *testing.T) {
  24. c, err := net.ConnectTcpServer(fmt.Sprintf("127.0.0.1:%d", ECHO_PORT))
  25. if err != nil {
  26. t.Fatalf("connect to echo server error: %v", err)
  27. }
  28. timer := time.Now().Add(time.Duration(5) * time.Second)
  29. c.SetDeadline(timer)
  30. c.Write([]byte(ECHO_TEST_STR + "\n"))
  31. br := bufio.NewReader(c)
  32. buf, err := br.ReadString('\n')
  33. if err != nil {
  34. t.Fatalf("read from echo server error: %v", err)
  35. }
  36. if ECHO_TEST_STR != buf {
  37. t.Fatalf("content error, send [%s], get [%s]", strings.Trim(ECHO_TEST_STR, "\n"), strings.Trim(buf, "\n"))
  38. }
  39. }
  40. func TestHttpServer(t *testing.T) {
  41. client := &http.Client{}
  42. req, _ := http.NewRequest("GET", fmt.Sprintf("http://127.0.0.1:%d", HTTP_PORT), nil)
  43. res, err := client.Do(req)
  44. if err != nil {
  45. t.Fatalf("do http request error: %v", err)
  46. }
  47. if res.StatusCode == 200 {
  48. body, err := ioutil.ReadAll(res.Body)
  49. if err != nil {
  50. t.Fatalf("read from http server error: %v", err)
  51. }
  52. bodystr := string(body)
  53. if bodystr != HTTP_RES_STR {
  54. t.Fatalf("content from http server error [%s], correct string is [%s]", bodystr, HTTP_RES_STR)
  55. }
  56. } else {
  57. t.Fatalf("http code from http server error [%d]", res.StatusCode)
  58. }
  59. }