Best Toxiproxy code snippet using toxiproxy.write
proxy_test.go
Source:proxy_test.go
1package toxiproxy_test2import (3 "bytes"4 "encoding/hex"5 "io"6 "io/ioutil"7 "net"8 "testing"9 "time"10 "github.com/Shopify/toxiproxy"11 "github.com/sirupsen/logrus"12 tomb "gopkg.in/tomb.v1"13)14func init() {15 logrus.SetLevel(logrus.FatalLevel)16}17func NewTestProxy(name, upstream string) *toxiproxy.Proxy {18 proxy := toxiproxy.NewProxy()19 proxy.Name = name20 proxy.Listen = "localhost:0"21 proxy.Upstream = upstream22 return proxy23}24func WithTCPServer(t *testing.T, f func(string, chan []byte)) {25 ln, err := net.Listen("tcp", "localhost:0")26 if err != nil {27 t.Fatal("Failed to create TCP server", err)28 }29 defer ln.Close()30 response := make(chan []byte, 1)31 tomb := tomb.Tomb{}32 go func() {33 defer tomb.Done()34 src, err := ln.Accept()35 if err != nil {36 select {37 case <-tomb.Dying():38 default:39 t.Fatal("Failed to accept client")40 }41 return42 }43 ln.Close()44 val, err := ioutil.ReadAll(src)45 if err != nil {46 t.Fatal("Failed to read from client")47 }48 response <- val49 }()50 f(ln.Addr().String(), response)51 tomb.Killf("Function body finished")52 ln.Close()53 tomb.Wait()54 close(response)55}56func TestSimpleServer(t *testing.T) {57 WithTCPServer(t, func(addr string, response chan []byte) {58 conn, err := net.Dial("tcp", addr)59 if err != nil {60 t.Error("Unable to dial TCP server", err)61 }62 msg := []byte("hello world")63 _, err = conn.Write(msg)64 if err != nil {65 t.Error("Failed writing to TCP server", err)66 }67 err = conn.Close()68 if err != nil {69 t.Error("Failed to close TCP connection", err)70 }71 resp := <-response72 if !bytes.Equal(resp, msg) {73 t.Error("Server didn't read bytes from client")74 }75 })76}77func WithTCPProxy(t *testing.T, f func(proxy net.Conn, response chan []byte, proxyServer *toxiproxy.Proxy)) {78 WithTCPServer(t, func(upstream string, response chan []byte) {79 proxy := NewTestProxy("test", upstream)80 proxy.Start()81 conn := AssertProxyUp(t, proxy.Listen, true)82 f(conn, response, proxy)83 proxy.Stop()84 })85}86func TestProxySimpleMessage(t *testing.T) {87 WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *toxiproxy.Proxy) {88 msg := []byte("hello world")89 _, err := conn.Write(msg)90 if err != nil {91 t.Error("Failed writing to TCP server", err)92 }93 err = conn.Close()94 if err != nil {95 t.Error("Failed to close TCP connection", err)96 }97 resp := <-response98 if !bytes.Equal(resp, msg) {99 t.Error("Server didn't read correct bytes from client", resp)100 }101 })102}103func TestProxyToDownUpstream(t *testing.T) {104 proxy := NewTestProxy("test", "localhost:20009")105 proxy.Start()106 conn := AssertProxyUp(t, proxy.Listen, true)107 // Check to make sure the connection is closed108 conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))109 _, err := conn.Read(make([]byte, 1))110 if err != io.EOF {111 t.Error("Proxy did not close connection when upstream down", err)112 }113 proxy.Stop()114}115func TestProxyBigMessage(t *testing.T) {116 WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *toxiproxy.Proxy) {117 buf := make([]byte, 32*1024)118 msg := make([]byte, len(buf)*2)119 hex.Encode(msg, buf)120 _, err := conn.Write(msg)121 if err != nil {122 t.Error("Failed writing to TCP server", err)123 }124 err = conn.Close()125 if err != nil {126 t.Error("Failed to close TCP connection", err)127 }128 resp := <-response129 if !bytes.Equal(resp, msg) {130 t.Error("Server didn't read correct bytes from client", resp)131 }132 })133}134func TestProxyTwoPartMessage(t *testing.T) {135 WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *toxiproxy.Proxy) {136 msg1 := []byte("hello world")137 msg2 := []byte("hello world")138 _, err := conn.Write(msg1)139 if err != nil {140 t.Error("Failed writing to TCP server", err)141 }142 _, err = conn.Write(msg2)143 if err != nil {144 t.Error("Failed writing to TCP server", err)145 }146 err = conn.Close()147 if err != nil {148 t.Error("Failed to close TCP connection", err)149 }150 msg1 = append(msg1, msg2...)151 resp := <-response152 if !bytes.Equal(resp, msg1) {153 t.Error("Server didn't read correct bytes from client", resp)154 }155 })156}157func TestClosingProxyMultipleTimes(t *testing.T) {158 WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *toxiproxy.Proxy) {159 proxy.Stop()160 proxy.Stop()161 proxy.Stop()162 })163}164func TestStartTwoProxiesOnSameAddress(t *testing.T) {165 WithTCPProxy(t, func(conn net.Conn, response chan []byte, proxy *toxiproxy.Proxy) {166 proxy2 := NewTestProxy("proxy_2", "localhost:3306")167 proxy2.Listen = proxy.Listen168 if err := proxy2.Start(); err == nil {169 t.Fatal("Expected an err back from start")170 }171 })172}173func TestStopProxyBeforeStarting(t *testing.T) {174 WithTCPServer(t, func(upstream string, response chan []byte) {175 proxy := NewTestProxy("test", upstream)176 AssertProxyUp(t, proxy.Listen, false)177 proxy.Stop()178 err := proxy.Start()179 if err != nil {180 t.Error("Proxy failed to start", err)181 }182 err = proxy.Start()183 if err != toxiproxy.ErrProxyAlreadyStarted {184 t.Error("Proxy did not fail to start when already started", err)185 }186 AssertProxyUp(t, proxy.Listen, true)187 proxy.Stop()188 AssertProxyUp(t, proxy.Listen, false)189 })190}191func TestProxyUpdate(t *testing.T) {192 WithTCPServer(t, func(upstream string, response chan []byte) {193 proxy := NewTestProxy("test", upstream)194 err := proxy.Start()195 if err != nil {196 t.Error("Proxy failed to start", err)197 }198 AssertProxyUp(t, proxy.Listen, true)199 before := proxy.Listen200 input := &toxiproxy.Proxy{Listen: "localhost:0", Upstream: proxy.Upstream, Enabled: true}201 err = proxy.Update(input)202 if err != nil {203 t.Error("Failed to update proxy", err)204 }205 if proxy.Listen == before || proxy.Listen == input.Listen {206 t.Errorf("Proxy update didn't change listen address: %s to %s", before, proxy.Listen)207 }208 AssertProxyUp(t, proxy.Listen, true)209 input.Listen = proxy.Listen210 err = proxy.Update(input)211 if err != nil {212 t.Error("Failed to update proxy", err)213 }214 AssertProxyUp(t, proxy.Listen, true)215 input.Enabled = false216 err = proxy.Update(input)217 if err != nil {218 t.Error("Failed to update proxy", err)219 }220 AssertProxyUp(t, proxy.Listen, false)221 })222}223func TestRestartFailedToStartProxy(t *testing.T) {224 WithTCPServer(t, func(upstream string, response chan []byte) {225 proxy := NewTestProxy("test", upstream)226 conflict := NewTestProxy("test2", upstream)227 err := conflict.Start()228 if err != nil {229 t.Error("Proxy failed to start", err)230 }231 AssertProxyUp(t, conflict.Listen, true)232 proxy.Listen = conflict.Listen233 err = proxy.Start()234 if err == nil || err == toxiproxy.ErrProxyAlreadyStarted {235 t.Error("Proxy started when it should have conflicted")236 }237 conflict.Stop()238 AssertProxyUp(t, conflict.Listen, false)239 err = proxy.Start()240 if err != nil {241 t.Error("Proxy failed to start after conflict went away", err)242 }243 AssertProxyUp(t, proxy.Listen, true)244 proxy.Stop()245 AssertProxyUp(t, proxy.Listen, false)246 })247}248func AssertProxyUp(t *testing.T, addr string, up bool) net.Conn {249 conn, err := net.Dial("tcp", addr)250 if err != nil && up {251 t.Error("Expected proxy to be up:", err)252 } else if err == nil && !up {253 t.Error("Expected proxy to be down")254 }255 return conn256}...
timeout_test.go
Source:timeout_test.go
...32 }33 defer conn.Close()34 serverConn := <-serverConnRecv35 defer serverConn.Close()36 writeAndReceive := func(from, to net.Conn) {37 data := []byte("foobar")38 _, err := from.Write(data)39 if err != nil {40 t.Fatal(err)41 }42 err = testhelper.TimeoutAfter(time.Second, func() {43 resp := make([]byte, len(data))44 to.Read(resp)45 if !bytes.Equal(resp, data) {46 t.Fatalf("expected '%s' but got '%s'", string(data), string(resp))47 }48 })49 if err != nil {50 t.Fatal(err)51 }52 }53 // Make sure we can send and receive data before continuing.54 writeAndReceive(conn, serverConn)55 writeAndReceive(serverConn, conn)56 f(conn, serverConn, proxy)57}58func TestTimeoutToxicDoesNotCauseHang(t *testing.T) {59 WithEstablishedProxy(t, func(conn, _ net.Conn, proxy *toxiproxy.Proxy) {60 proxy.Toxics.AddToxicJson(ToxicToJson(t, "might_block", "latency", "upstream", &toxics.LatencyToxic{Latency: 10}))61 proxy.Toxics.AddToxicJson(ToxicToJson(t, "timeout", "timeout", "upstream", &toxics.TimeoutToxic{Timeout: 0}))62 for i := 0; i < 5; i++ {63 _, err := conn.Write([]byte("hello"))64 if err != nil {65 t.Fatal("Unable to write to proxy", err)66 }67 time.Sleep(200 * time.Millisecond) // Shitty sync waiting for latency toxi to get data.68 }69 err := testhelper.TimeoutAfter(time.Second, func() {70 proxy.Toxics.RemoveToxic("might_block")71 })72 if err != nil {73 t.Fatal(err)74 }75 })76}77func TestTimeoutToxicClosesConnectionOnRemove(t *testing.T) {78 WithEstablishedProxy(t, func(conn, serverConn net.Conn, proxy *toxiproxy.Proxy) {79 proxy.Toxics.AddToxicJson(ToxicToJson(t, "to_delete", "timeout", "upstream", &toxics.TimeoutToxic{Timeout: 0}))...
write
Using AI Code Generation
1import (2func main() {3 toxiproxyClient := toxiproxy.NewClient("localhost:8474")4 toxiproxyClient.CreateProxy("redis", "localhost:6379", "localhost:16379")5 toxiproxyClient.CreateProxy("mysql", "localhost:3306", "localhost:13306")6 toxiproxyClient.CreateProxy("postgres", "localhost:5432", "localhost:15432")7 toxiproxyClient.CreateProxy("memcached", "localhost:11211", "localhost:11111")8 toxiproxyClient.CreateProxy("elasticsearch", "localhost:9200", "localhost:19200")9 toxiproxyClient.CreateProxy("mongodb", "localhost:27017", "localhost:127017")10 toxiproxyClient.CreateProxy("rabbitmq", "localhost:5672", "localhost:15672")11 toxiproxyClient.CreateProxy("cassandra", "localhost:9042", "localhost:19042")12 toxiproxyClient.CreateProxy("redis-cluster", "localhost:7000", "localhost:17000")13 toxiproxyClient.CreateProxy("redis-cluster", "localhost:7001", "localhost:17001")14 toxiproxyClient.CreateProxy("redis-cluster", "localhost:7002", "localhost:17002")15 toxiproxyClient.CreateProxy("redis-cluster", "localhost:7003", "localhost:17003")16 toxiproxyClient.CreateProxy("redis-cluster", "localhost:7004", "localhost:17004")17 toxiproxyClient.CreateProxy("redis-cluster", "localhost:7005", "localhost:17005")18 toxiproxyClient.CreateProxy("redis-cluster", "localhost:7006", "localhost:17006")19 toxiproxyClient.CreateProxy("redis-cluster", "localhost:7007", "localhost:17007")20 toxiproxyClient.CreateProxy("redis-cluster", "localhost:7008", "localhost:17008")21 toxiproxyClient.CreateProxy("redis-cluster", "localhost:7009", "localhost:17009")22 toxiproxyClient.CreateProxy("redis-cluster", "localhost:7010", "localhost:17010")23 toxiproxyClient.CreateProxy("redis-cluster", "localhost:7011", "localhost:17011
write
Using AI Code Generation
1import (2func main() {3 toxiproxyClient.CreateProxy("my_proxy", "localhost:5000", "localhost:5001")4 toxiproxyClient.EnableProxy("my_proxy")5 toxiproxyClient.WriteToxic("my_proxy", "latency", "downstream", toxiproxy.Toxic{6 Attributes: map[string]interface{}{"latency": 1000, "jitter": 200},7 })8 toxiproxyClient.WriteToxic("my_proxy", "latency", "upstream", toxiproxy.Toxic{9 Attributes: map[string]interface{}{"latency": 1000, "jitter": 200},10 })11 toxiproxyClient.DeleteProxy("my_proxy")12}13import (14func main() {15 toxiproxyClient.CreateProxy("my_proxy", "localhost:5000", "localhost:5001")16 toxiproxyClient.EnableProxy("my_proxy")17 toxiproxyClient.WriteToxic("my_proxy", "latency", "downstream", toxiproxy.Toxic{18 Attributes: map[string]interface{}{"latency": 1000, "jitter": 200},19 })20 toxiproxyClient.WriteToxic("my_proxy", "latency", "upstream", toxiproxy.Toxic{
write
Using AI Code Generation
1import (2func main() {3 toxiproxyClient.CreateProxy("myproxy", "localhost:6379", "localhost:6380")4 toxiproxyClient.AddToxic("myproxy", "latency", "downstream", 0, toxiproxy.Attributes{"latency": 500, "jitter": 200})5 toxiproxyClient.AddToxic("myproxy", "bandwidth", "downstream", 0, toxiproxy.Attributes{"rate": 102400})6 toxiproxyClient.AddToxic("myproxy", "slow_close", "downstream", 0, toxiproxy.Attributes{"delay": 500})7 toxiproxyClient.AddToxic("myproxy", "timeout", "downstream", 0, toxiproxy.Attributes{"timeout": 500})8 toxiproxyClient.AddToxic("myproxy", "slicer", "downstream", 0, toxiproxy.Attributes{"average_size": 1024, "size_variation": 10, "delay": 100})9 toxiproxyClient.AddToxic("myproxy", "limit_data", "downstream", 0, toxiproxy.Attributes{"bytes": 1024})10 toxiproxyClient.AddToxic("myproxy", "limit_data", "upstream", 0, toxiproxy.Attributes{"bytes": 1024})11 toxiproxyClient.AddToxic("myproxy", "limit_data", "downstream", 0, toxiproxy.Attributes{"bytes": 1024})12 toxiproxyClient.AddToxic("myproxy", "limit_data", "upstream", 0, toxiproxy.Attributes{"bytes": 1024})13 toxiproxyClient.AddToxic("myproxy", "limit_data", "downstream", 0, toxiproxy.Attributes{"bytes": 1024})14 toxiproxyClient.AddToxic("myproxy", "limit_data", "upstream", 0, toxiproxy.Attributes{"bytes": 1024})15 toxiproxyClient.AddToxic("myproxy", "limit_data", "downstream", 0, toxiproxy.Attributes{"bytes": 1024})
write
Using AI Code Generation
1import (2func main() {3 client, err := toxiproxy.NewClient("localhost:8474")4 if err != nil {5 fmt.Println("Error creating client:", err)6 }7 proxy, err := client.CreateProxy("redis", "localhost:6379", "localhost:16379")8 if err != nil {9 fmt.Println("Error creating proxy:", err)10 }11 fmt.Println("Proxy created:", proxy.Name)12 latencyToxic, err := proxy.Toxics().Create("latency", "downstream", -1, toxiproxy.Attributes{"latency": 1000, "jitter": 500})13 if err != nil {14 fmt.Println("Error creating latency toxic:", err)15 }16 fmt.Println("Latency toxic added:", latencyToxic.Name)17 bandwidthToxic, err := proxy.Toxics().Create("bandwidth", "downstream", -1, toxiproxy.Attributes{"rate": 1024})18 if err != nil {19 fmt.Println("Error creating bandwidth toxic:", err)20 }21 fmt.Println("Bandwidth toxic added:", bandwidthToxic.Name)22 toxics, err := proxy.Toxics().All()23 if err != nil {24 fmt.Println("Error listing toxics:", err)25 }26 fmt.Println("Toxics:")27 for _, toxic := range toxics {28 fmt.Println(" ", toxic.Name)29 }30 err = proxy.Toxics().Delete("latency")31 if err != nil {32 fmt.Println("Error deleting toxic:", err)33 }34 fmt.Println("Latency toxic deleted")35 err = client.DeleteProxy("redis")36 if err != nil {37 fmt.Println("Error deleting proxy:", err)38 }39 fmt.Println("Proxy deleted")40}
write
Using AI Code Generation
1import (2func main() {3 client := toxiproxy.NewClient("localhost:8474")4 toxics, err := client.Toxics("proxy1")5 if err != nil {6 panic(err)7 }8 toxic := toxiproxy.Toxic{9 Attributes: toxiproxy.Attributes{10 },11 }12 err = toxics.Create(&toxic)13 if err != nil {14 panic(err)15 }16}
write
Using AI Code Generation
1import (2func main() {3 c, err := client.NewClient("localhost:8474")4 if err != nil {5 fmt.Println(err)6 }7 err = c.Reset()8 if err != nil {9 fmt.Println(err)10 }11 proxy, err := c.CreateProxy("test", "localhost:12345", "localhost:8080")12 if err != nil {13 fmt.Println(err)14 }15 proxy.AddToxic("latency", "latency", "downstream", 1, client.Attributes{16 })17 proxy.AddToxic("slow_close", "slow_close", "downstream", 1, client.Attributes{18 })19 time.Sleep(1 * time.Second)20 proxy.RemoveToxic("latency")21 proxy.RemoveToxic("slow_close")22}
write
Using AI Code Generation
1import (2func main() {3 proxy, err := client.CreateProxy("my_proxy", "localhost:8080", "localhost:8081")4 if err != nil {5 panic(err)6 }7 fmt.Println("Proxy created")8 time.Sleep(5 * time.Second)9 err = proxy.Delete()10 if err != nil {11 panic(err)12 }13 fmt.Println("Proxy deleted")14}15import (16func main() {17 proxy, err := client.CreateProxy("my_proxy", "localhost:8080", "localhost:8081")18 if err != nil {19 panic(err)20 }21 fmt.Println("Proxy created")22 time.Sleep(5 * time.Second)23 err = proxy.Delete()24 if err != nil {25 panic(err)26 }27 fmt.Println("Proxy deleted")28}29import (30func main() {31 proxy, err := client.CreateProxy("my_proxy", "localhost:8080", "localhost:8081")32 if err != nil {33 panic(err)34 }35 fmt.Println("Proxy created")36 time.Sleep(5 * time.Second)37 err = proxy.Delete()38 if err != nil {39 panic(err)40 }41 fmt.Println("Proxy deleted")42}43import (44func main() {45 proxy, err := client.CreateProxy("my_proxy", "localhost:8080", "localhost:8081
write
Using AI Code Generation
1func main() {2 toxiproxy := toxiproxy.Toxiproxy{3 }4 err := client.AddProxy(toxiproxy)5 if err != nil {6 log.Fatal(err)7 }8 err = client.SetLatency("test", 2000)9 if err != nil {10 log.Fatal(err)11 }12 err = client.SetBandwidth("test", 1000000)13 if err != nil {14 log.Fatal(err)15 }16 err = client.SetSlowClose("test", 2000)17 if err != nil {18 log.Fatal(err)19 }20 err = client.SetTimeout("test", 2000)21 if err != nil {22 log.Fatal(err)23 }24 err = client.SetLatency("test", 2000)25 if err != nil {26 log.Fatal(err)27 }28 err = client.SetBandwidth("test", 1000000)29 if err != nil {30 log.Fatal(err)31 }32 err = client.SetSlowClose("test", 2000)33 if err != nil {34 log.Fatal(err)35 }36 err = client.SetTimeout("test", 2000)37 if err != nil {38 log.Fatal(err)39 }40 err = client.SetLatency("test", 2000)41 if err != nil {42 log.Fatal(err)43 }44 err = client.SetBandwidth("test", 1000000)45 if err != nil {46 log.Fatal(err)47 }48 err = client.SetSlowClose("
write
Using AI Code Generation
1proxy := client.Proxy("test")2err := proxy.Create()3if err != nil {4 panic(err)5}6proxy := client.Proxy("test")7err := proxy.Create()8if err != nil {9 panic(err)10}11proxy := client.Proxy("test")12err := proxy.Create()13if err != nil {14 panic(err)15}16proxy := client.Proxy("test")17err := proxy.Create()18if err != nil {19 panic(err)20}21proxy := client.Proxy("test")22err := proxy.Create()23if err != nil {24 panic(err)25}
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!!