Best Toxiproxy code snippet using toxiproxy.handler
network_test.go
Source:network_test.go
1package ws2import (3 "fmt"4 "net"5 "net/url"6 "os"7 "strings"8 "syscall"9 "testing"10 "time"11 "github.com/gorilla/websocket"12 "github.com/stretchr/testify/assert"13 "github.com/stretchr/testify/require"14 "github.com/stretchr/testify/suite"15 toxiproxy "github.com/Shopify/toxiproxy/client"16)17type NetworkTestSuite struct {18 suite.Suite19 proxy *toxiproxy.Proxy20 proxyPort int21 server *Server22 client *Client23}24func (s *NetworkTestSuite) SetupSuite() {25 client := toxiproxy.NewClient("localhost:8474")26 s.proxyPort = 888627 // Proxy listens on 8886 and upstreams to 8887 (where ocpp server is actually listening)28 oldProxy, err := client.Proxy("ocpp")29 if oldProxy != nil {30 oldProxy.Delete()31 }32 p, err := client.CreateProxy("ocpp", "localhost:8886", fmt.Sprintf("localhost:%v", serverPort))33 require.NoError(s.T(), err)34 s.proxy = p35}36func (s *NetworkTestSuite) TearDownSuite() {37 s.proxy.Delete()38}39func (s *NetworkTestSuite) SetupTest() {40 s.server = newWebsocketServer(s.T(), nil)41 s.client = newWebsocketClient(s.T(), nil)42}43func (s *NetworkTestSuite) TearDownTest() {44 s.server = nil45 s.client = nil46}47func (s *NetworkTestSuite) TestClientConnectionFailed() {48 t := s.T()49 s.server = newWebsocketServer(t, nil)50 s.server.SetNewClientHandler(func(ws Channel) {51 assert.Fail(t, "should not accept new clients")52 })53 go s.server.Start(serverPort, serverPath)54 time.Sleep(500 * time.Millisecond)55 // Test client56 host := s.proxy.Listen57 u := url.URL{Scheme: "ws", Host: host, Path: testPath}58 // Disable network59 _ = s.proxy.Disable()60 defer s.proxy.Enable()61 // Attempt connection62 err := s.client.Start(u.String())63 require.Error(t, err)64 netError, ok := err.(*net.OpError)65 require.True(t, ok)66 require.NotNil(t, netError.Err)67 sysError, ok := netError.Err.(*os.SyscallError)68 require.True(t, ok)69 assert.Equal(t, "connect", sysError.Syscall)70 assert.Equal(t, syscall.ECONNREFUSED, sysError.Err)71 // Cleanup72 s.server.Stop()73}74func (s *NetworkTestSuite) TestClientConnectionFailedTimeout() {75 t := s.T()76 // Set timeouts for test77 s.client.timeoutConfig.HandshakeTimeout = 2 * time.Second78 // Setup79 s.server = newWebsocketServer(t, nil)80 s.server.SetNewClientHandler(func(ws Channel) {81 assert.Fail(t, "should not accept new clients")82 })83 go s.server.Start(serverPort, serverPath)84 time.Sleep(500 * time.Millisecond)85 // Test client86 host := s.proxy.Listen87 u := url.URL{Scheme: "ws", Host: host, Path: testPath}88 // Add connection timeout89 _, err := s.proxy.AddToxic("connectTimeout", "timeout", "upstream", 1, toxiproxy.Attributes{90 "timeout": 3000, // 3 seconds91 })92 defer s.proxy.RemoveToxic("connectTimeout")93 require.NoError(t, err)94 // Attempt connection95 err = s.client.Start(u.String())96 require.Error(t, err)97 netError, ok := err.(*net.OpError)98 require.True(t, ok)99 require.NotNil(t, netError.Err)100 assert.True(t, strings.Contains(netError.Error(), "timeout"))101 assert.True(t, netError.Timeout())102 // Cleanup103 s.server.Stop()104}105func (s *NetworkTestSuite) TestClientAutoReconnect() {106 t := s.T()107 // Set timeouts for test108 s.client.timeoutConfig.ReconnectBackoff = 1 * time.Second109 // Setup110 serverOnDisconnected := make(chan bool, 1)111 clientOnDisconnected := make(chan bool, 1)112 reconnected := make(chan bool, 1)113 s.server = newWebsocketServer(t, nil)114 s.server.SetNewClientHandler(func(ws Channel) {115 assert.NotNil(t, ws)116 conn := s.server.connections[ws.ID()]117 require.NotNil(t, conn)118 })119 s.server.SetDisconnectedClientHandler(func(ws Channel) {120 serverOnDisconnected <- true121 })122 go s.server.Start(serverPort, serverPath)123 time.Sleep(500 * time.Millisecond)124 // Test bench125 s.client.SetDisconnectedHandler(func(err error) {126 assert.NotNil(t, err)127 closeError, ok := err.(*websocket.CloseError)128 require.True(t, ok)129 assert.Equal(t, websocket.CloseAbnormalClosure, closeError.Code)130 assert.False(t, s.client.IsConnected())131 clientOnDisconnected <- true132 })133 s.client.SetReconnectedHandler(func() {134 time.Sleep(50 * time.Millisecond) // Make sure we reconnected after backoff135 reconnected <- true136 })137 // Connect client138 host := s.proxy.Listen139 u := url.URL{Scheme: "ws", Host: host, Path: testPath}140 err := s.client.Start(u.String())141 require.Nil(t, err)142 // Close all connection from server side143 time.Sleep(500 * time.Millisecond)144 for _, s := range s.server.connections {145 err = s.connection.Close()146 require.Nil(t, err)147 }148 // Wait for disconnect to propagate149 result := <-serverOnDisconnected150 require.True(t, result)151 result = <-clientOnDisconnected152 require.True(t, result)153 start := time.Now()154 // Wait for reconnection155 result = <-reconnected156 elapsed := time.Since(start)157 assert.True(t, result)158 assert.True(t, s.client.IsConnected())159 assert.GreaterOrEqual(t, elapsed.Milliseconds(), s.client.timeoutConfig.ReconnectBackoff.Milliseconds())160 // Cleanup161 s.client.SetDisconnectedHandler(func(err error) {162 assert.Nil(t, err)163 clientOnDisconnected <- true164 })165 s.client.Stop()166 result = <-clientOnDisconnected167 require.True(t, result)168 s.server.Stop()169}170func (s *NetworkTestSuite) TestClientPongTimeout() {171 t := s.T()172 // Set timeouts for test173 // Will attempt to send ping after 1 second, and server expects ping within 1.4 seconds174 // Server will close connection175 s.client.timeoutConfig.PongWait = 2 * time.Second176 s.client.timeoutConfig.PingPeriod = (s.client.timeoutConfig.PongWait * 5) / 10177 s.client.timeoutConfig.ReconnectBackoff = 1 * time.Second178 s.server.timeoutConfig.PingWait = (s.client.timeoutConfig.PongWait * 7) / 10179 // Setup180 serverOnDisconnected := make(chan bool, 1)181 clientOnDisconnected := make(chan bool, 1)182 reconnected := make(chan bool, 1)183 s.server.SetNewClientHandler(func(ws Channel) {184 assert.NotNil(t, ws)185 })186 s.server.SetDisconnectedClientHandler(func(ws Channel) {187 serverOnDisconnected <- true188 })189 s.server.SetMessageHandler(func(ws Channel, data []byte) error {190 assert.Fail(t, "unexpected message received")191 return fmt.Errorf("unexpected message received")192 })193 go s.server.Start(serverPort, serverPath)194 time.Sleep(500 * time.Millisecond)195 // Test client196 s.client.SetDisconnectedHandler(func(err error) {197 defer func() {198 clientOnDisconnected <- true199 }()200 require.Error(t, err)201 closeError, ok := err.(*websocket.CloseError)202 require.True(t, ok)203 assert.Equal(t, websocket.CloseAbnormalClosure, closeError.Code)204 })205 s.client.SetReconnectedHandler(func() {206 time.Sleep(50 * time.Millisecond) // Make sure we reconnected after backoff207 reconnected <- true208 })209 host := s.proxy.Listen210 u := url.URL{Scheme: "ws", Host: host, Path: testPath}211 // Attempt connection212 err := s.client.Start(u.String())213 require.NoError(t, err)214 // Slow upstream network -> ping won't get through and server-side close will be triggered215 _, err = s.proxy.AddToxic("readTimeout", "timeout", "upstream", 1, toxiproxy.Attributes{216 "timeout": 5000, // 5 seconds217 })218 require.NoError(t, err)219 // Attempt to send message220 result := <-clientOnDisconnected221 require.True(t, result)222 result = <-serverOnDisconnected223 require.True(t, result)224 // Reconnect time starts225 _ = s.proxy.RemoveToxic("readTimeout")226 startTimeout := time.Now()227 result = <-reconnected228 require.True(t, result)229 elapsed := time.Since(startTimeout)230 assert.GreaterOrEqual(t, elapsed.Milliseconds(), s.client.timeoutConfig.ReconnectBackoff.Milliseconds())231 // Cleanup232 s.client.SetDisconnectedHandler(nil)233 s.client.Stop()234 s.server.Stop()235}236func (s *NetworkTestSuite) TestClientReadTimeout() {237 t := s.T()238 // Set timeouts for test239 s.client.timeoutConfig.PongWait = 2 * time.Second240 s.client.timeoutConfig.PingPeriod = (s.client.timeoutConfig.PongWait * 7) / 10241 s.client.timeoutConfig.ReconnectBackoff = 1 * time.Second242 s.server.timeoutConfig.PingWait = s.client.timeoutConfig.PongWait243 // Setup244 serverOnDisconnected := make(chan bool, 1)245 clientOnDisconnected := make(chan bool, 1)246 reconnected := make(chan bool, 1)247 s.server.SetNewClientHandler(func(ws Channel) {248 assert.NotNil(t, ws)249 })250 s.server.SetDisconnectedClientHandler(func(ws Channel) {251 serverOnDisconnected <- true252 })253 s.server.SetMessageHandler(func(ws Channel, data []byte) error {254 assert.Fail(t, "unexpected message received")255 return fmt.Errorf("unexpected message received")256 })257 go s.server.Start(serverPort, serverPath)258 time.Sleep(500 * time.Millisecond)259 // Test client260 s.client.SetDisconnectedHandler(func(err error) {261 defer func() {262 clientOnDisconnected <- true263 }()264 require.Error(t, err)265 errMsg := err.Error()266 c := strings.Contains(errMsg, "timeout")267 if !c {268 fmt.Println(errMsg)269 }270 assert.True(t, c)271 })272 s.client.SetReconnectedHandler(func() {273 time.Sleep(50 * time.Millisecond) // Make sure we reconnected after backoff274 reconnected <- true275 })276 host := s.proxy.Listen277 u := url.URL{Scheme: "ws", Host: host, Path: testPath}278 // Attempt connection279 err := s.client.Start(u.String())280 require.NoError(t, err)281 // Slow down network. Ping will be received but pong won't go through282 _, err = s.proxy.AddToxic("writeTimeout", "timeout", "downstream", 1, toxiproxy.Attributes{283 "timeout": 5000, // 5 seconds284 })285 require.NoError(t, err)286 // Attempt to send message287 require.NoError(t, err)288 result := <-serverOnDisconnected289 require.True(t, result)290 result = <-clientOnDisconnected291 require.True(t, result)292 // Reconnect time starts293 s.proxy.RemoveToxic("writeTimeout")294 startTimeout := time.Now()295 result = <-reconnected296 require.True(t, result)297 elapsed := time.Since(startTimeout)298 assert.GreaterOrEqual(t, elapsed.Milliseconds(), s.client.timeoutConfig.ReconnectBackoff.Milliseconds())299 // Cleanup300 s.client.SetDisconnectedHandler(nil)301 s.client.Stop()302 s.server.Stop()303}304//TODO: test error channel from websocket305func TestNetworkErrors(t *testing.T) {306 suite.Run(t, new(NetworkTestSuite))307}...
routines.go
Source:routines.go
...71 u := (uint64(u1) << 32) | uint64(u2)72 return fmt.Sprintf("%016x", u)73}74//Generates span for each request which is sent to :8000 server75func (S *Stub) wrapHandler(path string, exceptype string, handler func(http.ResponseWriter, *http.Request)) (string, func(http.ResponseWriter, *http.Request)) {76 return path, func(rw http.ResponseWriter, req *http.Request) {77 s := S.h.MetricAggregator().Summary("service.responseTime", map[string]interface{}{78 "name": path,79 "http.method": req.Method,80 "isWeb": true,81 "service.instance.id": "New relic trial metric",82 })83 before := time.Now()84 handler(rw, req)85 s.RecordDuration(time.Since(before))86 S.h.RecordSpan(telemetry.Span{87 ID: randomID(),88 TraceID: randomID(),89 Name: "service.responseTime",90 Timestamp: before,91 Duration: time.Since(before),92 ServiceName: "NR assignment exp 1 Stub",93 Attributes: map[string]interface{}{94 "name": path,95 "http.method": req.Method,96 "isWeb": true,97 "service.instance.id": "New relic trial span",98 },...
helper_test.go
Source:helper_test.go
1package goomerang_test2import (3 "context"4 "crypto/tls"5 "fmt"6 "net"7 "strings"8 "testing"9 "time"10 "github.com/Shopify/toxiproxy"11 toxiClient "github.com/Shopify/toxiproxy/client"12 "go.eloylp.dev/kit/pki"13 kitTest "go.eloylp.dev/kit/test"14 "go.eloylp.dev/goomerang/client"15 "go.eloylp.dev/goomerang/example/protos"16 "go.eloylp.dev/goomerang/internal/test"17 "go.eloylp.dev/goomerang/message"18 "go.eloylp.dev/goomerang/server"19 "go.eloylp.dev/goomerang/ws"20)21const (22 proxyAddr = "127.0.0.1:8474"23 kernelDefinedPort = "127.0.0.1:0"24)25var (26 proxyServer *toxiproxy.ApiServer27 proxyClient *toxiClient.Client28 defaultCtx = context.Background()29 defaultMsg = message.New().30 SetPayload(&protos.MessageV1{31 Message: "a message!",32 })33 echoHandler = message.HandlerFunc(func(s message.Sender, msg *message.Message) {34 s.Send(msg)35 })36 nilHandler = message.HandlerFunc(func(s message.Sender, msg *message.Message) {})37)38func init() {39 proxyServer = toxiproxy.NewServer()40 proxyAddrParts := strings.Split(proxyAddr, ":")41 go proxyServer.Listen(proxyAddrParts[0], proxyAddrParts[1])42 mustWaitTCPService("localhost:8474", time.Millisecond, time.Second)43 proxyClient = toxiClient.NewClient(proxyAddr)44}45func mustWaitTCPService(addr string, interval, maxWait time.Duration) {46 ctx, cancl := context.WithTimeout(context.Background(), maxWait)47 defer cancl()48 for {49 select {50 case <-ctx.Done():51 panic(ctx.Err())52 default:53 con, conErr := net.Dial("tcp", addr)54 if conErr == nil {55 _ = con.Close()56 return57 }58 time.Sleep(interval)59 }60 }61}62func PrepareServer(t *testing.T, opts ...server.Option) (s *server.Server, run func()) {63 t.Helper()64 is := configureServer(t, opts)65 return is, func() {66 go is.Run()67 waitForServer(t, is)68 }69}70func waitForServer(t *testing.T, is *server.Server) {71 ctx, cancl := context.WithTimeout(defaultCtx, time.Second)72 defer cancl()73 var serverAddr string74 for {75 select {76 case <-ctx.Done():77 t.Fatal(fmt.Errorf("error waiting for server addr: %v", ctx.Err()))78 default:79 serverAddr = is.Addr()80 if serverAddr == "" {81 continue82 }83 kitTest.WaitTCPService(t, serverAddr, 50*time.Millisecond, 2*time.Second)84 return85 }86 }87}88func configureServer(t *testing.T, opts []server.Option) *server.Server {89 allOpts := []server.Option{server.WithListenAddr(kernelDefinedPort)}90 allOpts = append(allOpts, opts...)91 s, err := server.New(allOpts...)92 if err != nil {93 t.Fatal(err)94 }95 return s96}97func PrepareTLSServer(t *testing.T, opts ...server.Option) (s *server.Server, run func()) {98 t.Helper()99 is := configureServer(t, opts)100 return is, func() {101 go is.Run()102 waitForServer(t, is)103 }104}105func PrepareClient(t *testing.T, opts ...client.Option) (c *client.Client, connect func()) {106 c, err := client.New(opts...)107 if err != nil {108 t.Fatal(err)109 }110 ctx := context.Background()111 return c, func() {112 err = c.Connect(ctx)113 if err != nil {114 t.Fatal(err)115 }116 }117}118func SelfSignedCert(t *testing.T) tls.Certificate {119 crt, err := pki.SelfSignedCert(pki.WithCertSerialNumber(1),120 pki.WithCertCommonName("127.0.0.1"),121 pki.WithCertOrganization([]string{"goomerang"}),122 pki.WithCertIpAddresses([]string{"127.0.0.1"}),123 pki.WithCertNotBefore(time.Now()),124 pki.WithCertNotAfter(time.Now().Add(time.Hour*24*365)),125 )126 if err != nil {127 t.Fatal(err)128 }129 return crt130}131func statusChangesHook(a *test.Arbiter, side string) func(status uint32) {132 side = strings.ToUpper(side)133 return func(status uint32) {134 switch status {135 case ws.StatusNew:136 a.ItsAFactThat(side + "_WAS_NEW")137 case ws.StatusRunning:138 a.ItsAFactThat(side + "_WAS_RUNNING")139 case ws.StatusClosing:140 a.ItsAFactThat(side + "_WAS_CLOSING")141 case ws.StatusClosed:142 a.ItsAFactThat(side + "_WAS_CLOSED")143 }144 }145}146func noErrorHook(a *test.Arbiter) func(err error) {147 return func(err error) {148 a.ErrorHappened(err)149 }150}151func failIfErr(t *testing.T, err error) {152 if err != nil {153 t.Fatal(err)154 }155}...
handler
Using AI Code Generation
1import (2func main() {3 proxy, _ := client.CreateProxy("my_proxy", "localhost:5000", "localhost:5001")4 fmt.Println(proxy.Name)5 fmt.Println(proxy.Listen)6 fmt.Println(proxy.Upstream)7 proxy.Toxics.Add("latency", "latency", 2.0, 0.0)8 proxy.Toxics.Add("bandwidth", "bandwidth", 0.0, 1024.0)9 proxy.Toxics.Add("slow_close", "slow_close", 0.0, 0.0)10 proxy.Toxics.Add("timeout", "timeout", 0.0, 0.0)11 proxy.Toxics.Add("slicer", "slicer", 0.0, 0.0)12 proxy.Toxics.Add("limit_data", "limit_data", 0.0, 0.0)13 proxy.Toxics.Add("down", "down", 0.0, 0.0)14 proxy.Toxics.Add("latency_up", "latency", 2.0, 0.0)15 proxy.Toxics.Add("bandwidth_up", "bandwidth", 0.0, 1024.0)16 proxy.Toxics.Add("slow_close_up", "slow_close", 0.0, 0.0)17 proxy.Toxics.Add("timeout_up", "timeout", 0.0, 0.0)18 proxy.Toxics.Add("slicer_up", "slicer", 0.0, 0.0)19 proxy.Toxics.Add("limit_data_up", "limit_data", 0.0, 0.0)20 proxy.Toxics.Add("down_up", "down", 0.0, 0.0)21 proxy.Toxics.Add("latency_down", "latency", 2.0, 0.0)22 proxy.Toxics.Add("bandwidth_down", "bandwidth", 0.0, 1024.0)23 proxy.Toxics.Add("slow_close_down", "slow_close", 0.0, 0.0)
handler
Using AI Code Generation
1import (2func main() {3 proxy := toxiproxy.NewProxy()4 if err := proxy.Start(); err != nil {5 log.Fatalln(err)6 }7 client := &http.Client{8 Transport: &http.Transport{9 },10 }11 proxyServer := httputil.NewSingleHostReverseProxy(remote)12 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {13 res, err := client.Do(req)14 if err != nil {15 log.Fatalln(err)16 }17 proxyServer.ServeHTTP(w, r)18 res.Body.Close()19 })20 go func() {21 log.Fatal(http.ListenAndServe(":8080", nil))22 }()23 ch := make(chan os.Signal)24 signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)25 if err := proxy.Stop(); err != nil {26 log.Fatalln(err)27 }28 fmt.Println("proxy stopped")29}30import (31func main() {32 proxy := toxiproxy.NewProxy()
handler
Using AI Code Generation
1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 proxy := httputil.NewSingleHostReverseProxy(proxyURL)7 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {8 fmt.Println("request received")9 proxy.ServeHTTP(w, r)10 })11 log.Fatal(http.ListenAndServe(":8080", nil))12}13import (14func main() {15 client := &http.Client{16 }17 if err != nil {18 log.Fatal(err)19 }20 res, err := client.Do(req)21 if err != nil {22 log.Fatal(err)23 }24 defer res.Body.Close()25 body, err := ioutil.ReadAll(res.Body)26 if err != nil {27 log.Fatal(err)28 }29 sb := string(body)30 fmt.Println(sb)31}32import (33func main() {34 client := &http.Client{35 }36 if err != nil {37 log.Fatal(err)38 }
handler
Using AI Code Generation
1func (t *Toxiproxy) Handler(w http.ResponseWriter, r *http.Request) {2}3func (t *Toxiproxy) Handler(w http.ResponseWriter, r *http.Request) {4}5func (t *Toxiproxy) Handler(w http.ResponseWriter, r *http.Request) {6}7func (t *Toxiproxy) Handler(w http.ResponseWriter, r *http.Request) {8}9func (t *Toxiproxy) Handler(w http.ResponseWriter, r *http.Request) {10}11func (t *Toxiproxy) Handler(w http.ResponseWriter, r *http.Request) {12}13func (t *Toxiproxy) Handler(w http.ResponseWriter, r *http.Request) {14}15func (t *Toxiproxy) Handler(w http.ResponseWriter, r *http.Request) {16}17func (t *Toxiproxy) Handler(w http.ResponseWriter, r *http.Request) {18}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!