mockservers.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package framework
  2. import (
  3. "fmt"
  4. "net/http"
  5. "os"
  6. "github.com/fatedier/frp/test/e2e/framework/consts"
  7. "github.com/fatedier/frp/test/e2e/mock/server"
  8. "github.com/fatedier/frp/test/e2e/mock/server/httpserver"
  9. "github.com/fatedier/frp/test/e2e/mock/server/streamserver"
  10. "github.com/fatedier/frp/test/e2e/pkg/port"
  11. )
  12. const (
  13. TCPEchoServerPort = "TCPEchoServerPort"
  14. UDPEchoServerPort = "UDPEchoServerPort"
  15. UDSEchoServerAddr = "UDSEchoServerAddr"
  16. HTTPSimpleServerPort = "HTTPSimpleServerPort"
  17. )
  18. type MockServers struct {
  19. tcpEchoServer server.Server
  20. udpEchoServer server.Server
  21. udsEchoServer server.Server
  22. httpSimpleServer server.Server
  23. }
  24. func NewMockServers(portAllocator *port.Allocator) *MockServers {
  25. s := &MockServers{}
  26. tcpPort := portAllocator.Get()
  27. udpPort := portAllocator.Get()
  28. httpPort := portAllocator.Get()
  29. s.tcpEchoServer = streamserver.New(streamserver.TCP, streamserver.WithBindPort(tcpPort))
  30. s.udpEchoServer = streamserver.New(streamserver.UDP, streamserver.WithBindPort(udpPort))
  31. s.httpSimpleServer = httpserver.New(httpserver.WithBindPort(httpPort),
  32. httpserver.WithHandler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  33. _, _ = w.Write([]byte(consts.TestString))
  34. })),
  35. )
  36. udsIndex := portAllocator.Get()
  37. udsAddr := fmt.Sprintf("%s/frp_echo_server_%d.sock", os.TempDir(), udsIndex)
  38. os.Remove(udsAddr)
  39. s.udsEchoServer = streamserver.New(streamserver.Unix, streamserver.WithBindAddr(udsAddr))
  40. return s
  41. }
  42. func (m *MockServers) Run() error {
  43. if err := m.tcpEchoServer.Run(); err != nil {
  44. return err
  45. }
  46. if err := m.udpEchoServer.Run(); err != nil {
  47. return err
  48. }
  49. if err := m.udsEchoServer.Run(); err != nil {
  50. return err
  51. }
  52. return m.httpSimpleServer.Run()
  53. }
  54. func (m *MockServers) Close() {
  55. m.tcpEchoServer.Close()
  56. m.udpEchoServer.Close()
  57. m.udsEchoServer.Close()
  58. m.httpSimpleServer.Close()
  59. os.Remove(m.udsEchoServer.BindAddr())
  60. }
  61. func (m *MockServers) GetTemplateParams() map[string]interface{} {
  62. ret := make(map[string]interface{})
  63. ret[TCPEchoServerPort] = m.tcpEchoServer.BindPort()
  64. ret[UDPEchoServerPort] = m.udpEchoServer.BindPort()
  65. ret[UDSEchoServerAddr] = m.udsEchoServer.BindAddr()
  66. ret[HTTPSimpleServerPort] = m.httpSimpleServer.BindPort()
  67. return ret
  68. }
  69. func (m *MockServers) GetParam(key string) interface{} {
  70. params := m.GetTemplateParams()
  71. if v, ok := params[key]; ok {
  72. return v
  73. }
  74. return nil
  75. }