How to use Close method of toxics Package

Best Toxiproxy code snippet using toxics.Close

toxic_test.go

Source:toxic_test.go Github

copy

Full Screen

...27 ln, err := net.Listen("tcp", "localhost:0")28 if err != nil {29 t.Fatal("Failed to create TCP server", err)30 }31 defer ln.Close()32 response := make(chan []byte, 1)33 tomb := tomb.Tomb{}34 go func() {35 defer tomb.Done()36 src, err := ln.Accept()37 if err != nil {38 select {39 case <-tomb.Dying():40 default:41 t.Fatal("Failed to accept client")42 }43 return44 }45 ln.Close()46 scan := bufio.NewScanner(src)47 if scan.Scan() {48 received := append(scan.Bytes(), '\n')49 response <- received50 src.Write(received)51 }52 }()53 f(ln.Addr().String(), response)54 tomb.Killf("Function body finished")55 ln.Close()56 tomb.Wait()57 close(response)58}59func WithEchoProxy(t *testing.T, f func(proxy net.Conn, response chan []byte, proxyServer *toxiproxy.Proxy)) {60 WithEchoServer(t, func(upstream string, response chan []byte) {61 proxy := NewTestProxy("test", upstream)62 proxy.Start()63 conn, err := net.Dial("tcp", proxy.Listen)64 if err != nil {65 t.Error("Unable to dial TCP server", err)66 }67 f(conn, response, proxy)68 proxy.Stop()69 })70}71func ToxicToJson(t *testing.T, name, typeName, stream string, toxic toxics.Toxic) io.Reader {72 data := map[string]interface{}{73 "name": name,74 "type": typeName,75 "stream": stream,76 "attributes": toxic,77 }78 request, err := json.Marshal(data)79 if err != nil {80 t.Errorf("Failed to marshal toxic for api (1): %v", toxic)81 }82 return bytes.NewReader(request)83}84func AssertEchoResponse(t *testing.T, client, server net.Conn) {85 msg := []byte("hello world\n")86 _, err := client.Write(msg)87 if err != nil {88 t.Error("Failed writing to TCP server", err)89 }90 scan := bufio.NewScanner(server)91 if !scan.Scan() {92 t.Error("Client unexpectedly closed connection")93 }94 resp := append(scan.Bytes(), '\n')95 if !bytes.Equal(resp, msg) {96 t.Error("Server didn't read correct bytes from client:", string(resp))97 }98 _, err = server.Write(resp)99 if err != nil {100 t.Error("Failed writing to TCP client", err)101 }102 scan = bufio.NewScanner(client)103 if !scan.Scan() {104 t.Error("Server unexpectedly closed connection")105 }106 resp = append(scan.Bytes(), '\n')107 if !bytes.Equal(resp, msg) {108 t.Error("Client didn't read correct bytes from server:", string(resp))109 }110}111func TestPersistentConnections(t *testing.T) {112 ln, err := net.Listen("tcp", "localhost:0")113 if err != nil {114 t.Fatal("Failed to create TCP server", err)115 }116 defer ln.Close()117 proxy := NewTestProxy("test", ln.Addr().String())118 proxy.Start()119 defer proxy.Stop()120 serverConnRecv := make(chan net.Conn)121 go func() {122 conn, err := ln.Accept()123 if err != nil {124 t.Error("Unable to accept TCP connection", err)125 }126 serverConnRecv <- conn127 }()128 conn, err := net.Dial("tcp", proxy.Listen)129 if err != nil {130 t.Error("Unable to dial TCP server", err)131 }132 serverConn := <-serverConnRecv133 proxy.Toxics.AddToxicJson(ToxicToJson(t, "noop_up", "noop", "upstream", &toxics.NoopToxic{}))134 proxy.Toxics.AddToxicJson(ToxicToJson(t, "noop_down", "noop", "downstream", &toxics.NoopToxic{}))135 AssertEchoResponse(t, conn, serverConn)136 proxy.Toxics.ResetToxics()137 AssertEchoResponse(t, conn, serverConn)138 proxy.Toxics.ResetToxics()139 AssertEchoResponse(t, conn, serverConn)140 err = conn.Close()141 if err != nil {142 t.Error("Failed to close TCP connection", err)143 }144}145func TestToxicAddRemove(t *testing.T) {146 ln, err := net.Listen("tcp", "localhost:0")147 if err != nil {148 t.Fatal("Failed to create TCP server", err)149 }150 defer ln.Close()151 proxy := NewTestProxy("test", ln.Addr().String())152 proxy.Start()153 defer proxy.Stop()154 serverConnRecv := make(chan net.Conn)155 go func() {156 conn, err := ln.Accept()157 if err != nil {158 t.Error("Unable to accept TCP connection", err)159 }160 serverConnRecv <- conn161 }()162 conn, err := net.Dial("tcp", proxy.Listen)163 if err != nil {164 t.Error("Unable to dial TCP server", err)165 }166 serverConn := <-serverConnRecv167 running := make(chan struct{})168 go func() {169 enabled := false170 for {171 select {172 case <-running:173 return174 default:175 if enabled {176 proxy.Toxics.AddToxicJson(ToxicToJson(t, "noop_up", "noop", "upstream", &toxics.NoopToxic{}))177 proxy.Toxics.RemoveToxic("noop_down")178 } else {179 proxy.Toxics.RemoveToxic("noop_up")180 proxy.Toxics.AddToxicJson(ToxicToJson(t, "noop_down", "noop", "downstream", &toxics.NoopToxic{}))181 }182 enabled = !enabled183 }184 }185 }()186 for i := 0; i < 100; i++ {187 AssertEchoResponse(t, conn, serverConn)188 }189 close(running)190 err = conn.Close()191 if err != nil {192 t.Error("Failed to close TCP connection", err)193 }194}195func TestProxyLatency(t *testing.T) {196 ln, err := net.Listen("tcp", "localhost:0")197 if err != nil {198 t.Fatal("Failed to create TCP server", err)199 }200 defer ln.Close()201 proxy := NewTestProxy("test", ln.Addr().String())202 proxy.Start()203 defer proxy.Stop()204 serverConnRecv := make(chan net.Conn)205 go func() {206 conn, err := ln.Accept()207 if err != nil {208 t.Error("Unable to accept TCP connection", err)209 }210 serverConnRecv <- conn211 }()212 conn, err := net.Dial("tcp", proxy.Listen)213 if err != nil {214 t.Error("Unable to dial TCP server", err)215 }216 serverConn := <-serverConnRecv217 start := time.Now()218 for i := 0; i < 100; i++ {219 AssertEchoResponse(t, conn, serverConn)220 }221 latency := time.Since(start) / 200222 if latency > 300*time.Microsecond {223 t.Errorf("Average proxy latency > 300µs (%v)", latency)224 } else {225 t.Logf("Average proxy latency: %v", latency)226 }227 err = conn.Close()228 if err != nil {229 t.Error("Failed to close TCP connection", err)230 }231}232func BenchmarkProxyBandwidth(b *testing.B) {233 ln, err := net.Listen("tcp", "localhost:0")234 if err != nil {235 b.Fatal("Failed to create TCP server", err)236 }237 defer ln.Close()238 proxy := NewTestProxy("test", ln.Addr().String())239 proxy.Start()240 defer proxy.Stop()241 buf := []byte(strings.Repeat("hello world ", 1000))242 go func() {243 conn, err := ln.Accept()244 if err != nil {245 b.Error("Unable to accept TCP connection", err)246 }247 buf2 := make([]byte, len(buf))248 for err == nil {249 _, err = conn.Read(buf2)250 }251 }()252 conn, err := net.Dial("tcp", proxy.Listen)253 if err != nil {254 b.Error("Unable to dial TCP server", err)255 }256 b.SetBytes(int64(len(buf)))257 b.ReportAllocs()258 b.ResetTimer()259 for i := 0; i < b.N; i++ {260 n, err := conn.Write(buf)261 if err != nil || n != len(buf) {262 b.Errorf("%v, %d == %d", err, n, len(buf))263 break264 }265 }266 err = conn.Close()267 if err != nil {268 b.Error("Failed to close TCP connection", err)269 }270}...

Full Screen

Full Screen

latency_test.go

Source:latency_test.go Github

copy

Full Screen

...78 time.Duration(upLatency.Jitter+downLatency.Jitter+20)*time.Millisecond,79 )80 proxy.Toxics.RemoveToxic("latency_up")81 proxy.Toxics.RemoveToxic("latency_down")82 err = conn.Close()83 if err != nil {84 t.Error("Failed to close TCP connection", err)85 }86 })87}88func TestUpstreamLatency(t *testing.T) {89 DoLatencyTest(t, &toxics.LatencyToxic{Latency: 100}, nil)90}91func TestDownstreamLatency(t *testing.T) {92 DoLatencyTest(t, nil, &toxics.LatencyToxic{Latency: 100})93}94func TestFullstreamLatencyEven(t *testing.T) {95 DoLatencyTest(t, &toxics.LatencyToxic{Latency: 100}, &toxics.LatencyToxic{Latency: 100})96}97func TestFullstreamLatencyBiasUp(t *testing.T) {98 DoLatencyTest(t, &toxics.LatencyToxic{Latency: 1000}, &toxics.LatencyToxic{Latency: 100})99}100func TestFullstreamLatencyBiasDown(t *testing.T) {101 DoLatencyTest(t, &toxics.LatencyToxic{Latency: 100}, &toxics.LatencyToxic{Latency: 1000})102}103func TestZeroLatency(t *testing.T) {104 DoLatencyTest(t, &toxics.LatencyToxic{Latency: 0}, &toxics.LatencyToxic{Latency: 0})105}106func TestLatencyToxicCloseRace(t *testing.T) {107 ln, err := net.Listen("tcp", "localhost:0")108 if err != nil {109 t.Fatal("Failed to create TCP server", err)110 }111 defer ln.Close()112 proxy := NewTestProxy("test", ln.Addr().String())113 proxy.Start()114 defer proxy.Stop()115 go func() {116 for {117 _, err := ln.Accept()118 if err != nil {119 return120 }121 }122 }()123 // Check for potential race conditions when interrupting toxics124 for i := 0; i < 1000; i++ {125 proxy.Toxics.AddToxicJson(ToxicToJson(t, "", "latency", "upstream", &toxics.LatencyToxic{Latency: 10}))126 conn, err := net.Dial("tcp", proxy.Listen)127 if err != nil {128 t.Error("Unable to dial TCP server", err)129 }130 conn.Write([]byte("hello"))131 conn.Close()132 proxy.Toxics.RemoveToxic("latency")133 }134}135func TestTwoLatencyToxics(t *testing.T) {136 WithEchoProxy(t, func(conn net.Conn, response chan []byte, proxy *toxiproxy.Proxy) {137 toxics := []*toxics.LatencyToxic{&toxics.LatencyToxic{Latency: 500}, &toxics.LatencyToxic{Latency: 500}}138 for i, toxic := range toxics {139 _, err := proxy.Toxics.AddToxicJson(ToxicToJson(t, "latency_"+strconv.Itoa(i), "latency", "upstream", toxic))140 if err != nil {141 t.Error("AddToxicJson returned error:", err)142 }143 }144 msg := []byte("hello world " + strings.Repeat("a", 32*1024) + "\n")145 timer := time.Now()146 _, err := conn.Write(msg)147 if err != nil {148 t.Error("Failed writing to TCP server", err)149 }150 resp := <-response151 if !bytes.Equal(resp, msg) {152 t.Error("Server didn't read correct bytes from client:", string(resp))153 }154 AssertDeltaTime(t,155 "Upstream two latency toxics",156 time.Since(timer),157 time.Duration(1000)*time.Millisecond,158 time.Duration(10)*time.Millisecond,159 )160 for i := range toxics {161 proxy.Toxics.RemoveToxic("latency_" + strconv.Itoa(i))162 }163 err = conn.Close()164 if err != nil {165 t.Error("Failed to close TCP connection", err)166 }167 })168}169func TestLatencyToxicBandwidth(t *testing.T) {170 ln, err := net.Listen("tcp", "localhost:0")171 if err != nil {172 t.Fatal("Failed to create TCP server", err)173 }174 defer ln.Close()175 proxy := NewTestProxy("test", ln.Addr().String())176 proxy.Start()177 defer proxy.Stop()178 buf := []byte(strings.Repeat("hello world ", 1000))179 go func() {180 conn, err := ln.Accept()181 if err != nil {182 t.Error("Unable to accept TCP connection", err)183 }184 for err == nil {185 _, err = conn.Write(buf)186 }187 }()188 conn, err := net.Dial("tcp", proxy.Listen)189 if err != nil {190 t.Error("Unable to dial TCP server", err)191 }192 proxy.Toxics.AddToxicJson(ToxicToJson(t, "", "latency", "", &toxics.LatencyToxic{Latency: 100}))193 time.Sleep(150 * time.Millisecond) // Wait for latency toxic194 buf2 := make([]byte, len(buf))195 start := time.Now()196 count := 0197 for i := 0; i < 100; i++ {198 n, err := io.ReadFull(conn, buf2)199 count += n200 if err != nil {201 t.Error(err)202 break203 }204 }205 // Assert the transfer was at least 100MB/s206 AssertDeltaTime(t, "Latency toxic bandwidth", time.Since(start), 0, time.Duration(count/100000)*time.Millisecond)207 err = conn.Close()208 if err != nil {209 t.Error("Failed to close TCP connection", err)210 }211}...

Full Screen

Full Screen

link.go

Source:link.go Github

copy

Full Screen

...45 link.output = stream.NewChanReader(last)46 return link47}48// Start the link with the specified toxics49func (link *ToxicLink) Start(name string, source io.Reader, dest io.WriteCloser) {50 go func() {51 bytes, err := io.Copy(link.input, source)52 if err != nil {53 logrus.WithFields(logrus.Fields{54 "name": link.proxy.Name,55 "bytes": bytes,56 "err": err,57 }).Warn("Source terminated")58 }59 link.input.Close()60 }()61 for i, toxic := range link.toxics.chain[link.direction] {62 if stateful, ok := toxic.Toxic.(toxics.StatefulToxic); ok {63 link.stubs[i].State = stateful.NewState()64 }65 go link.stubs[i].Run(toxic)66 }67 go func() {68 bytes, err := io.Copy(dest, link.output)69 if err != nil {70 logrus.WithFields(logrus.Fields{71 "name": link.proxy.Name,72 "bytes": bytes,73 "err": err,74 }).Warn("Destination terminated")75 }76 dest.Close()77 link.toxics.RemoveLink(name)78 link.proxy.RemoveConnection(name)79 }()80}81// Add a toxic to the end of the chain.82func (link *ToxicLink) AddToxic(toxic *toxics.ToxicWrapper) {83 i := len(link.stubs)84 newin := make(chan *stream.StreamChunk, toxic.BufferSize)85 link.stubs = append(link.stubs, toxics.NewToxicStub(newin, link.stubs[i-1].Output))86 // Interrupt the last toxic so that we don't have a race when moving channels87 if link.stubs[i-1].InterruptToxic() {88 link.stubs[i-1].Output = newin89 if stateful, ok := toxic.Toxic.(toxics.StatefulToxic); ok {90 link.stubs[i].State = stateful.NewState()91 }92 go link.stubs[i].Run(toxic)93 go link.stubs[i-1].Run(link.toxics.chain[link.direction][i-1])94 } else {95 // This link is already closed, make sure the new toxic matches96 link.stubs[i].Output = newin // The real output is already closed, close this instead97 link.stubs[i].Close()98 }99}100// Update an existing toxic in the chain.101func (link *ToxicLink) UpdateToxic(toxic *toxics.ToxicWrapper) {102 if link.stubs[toxic.Index].InterruptToxic() {103 go link.stubs[toxic.Index].Run(toxic)104 }105}106// Remove an existing toxic from the chain.107func (link *ToxicLink) RemoveToxic(toxic *toxics.ToxicWrapper) {108 i := toxic.Index109 if link.stubs[i].InterruptToxic() {110 cleanup, ok := toxic.Toxic.(toxics.CleanupToxic)111 if ok {112 cleanup.Cleanup(link.stubs[i])113 // Cleanup could have closed the stub.114 if link.stubs[i].Closed() {115 return116 }117 }118 stop := make(chan bool)119 // Interrupt the previous toxic to update its output120 go func() {121 stop <- link.stubs[i-1].InterruptToxic()122 }()123 // Unblock the previous toxic if it is trying to flush124 // If the previous toxic is closed, continue flusing until we reach the end.125 interrupted := false126 stopped := false127 for !interrupted {128 select {129 case interrupted = <-stop:130 stopped = true131 case tmp := <-link.stubs[i].Input:132 if tmp == nil {133 link.stubs[i].Close()134 if !stopped {135 <-stop136 }137 return138 }139 link.stubs[i].Output <- tmp140 }141 }142 // Empty the toxic's buffer if necessary143 for len(link.stubs[i].Input) > 0 {144 tmp := <-link.stubs[i].Input145 if tmp == nil {146 link.stubs[i].Close()147 return148 }149 link.stubs[i].Output <- tmp150 }151 link.stubs[i-1].Output = link.stubs[i].Output152 link.stubs = append(link.stubs[:i], link.stubs[i+1:]...)153 go link.stubs[i-1].Run(link.toxics.chain[link.direction][i-1])154 }155}...

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 toxic := client.Toxic{4 Attributes: client.ToxicAttributes{5 },6 }7 toxicClient := client.NewToxic("localhost:8474", "test", "latency")8 err := toxicClient.Create(&toxic)9 if err != nil {10 fmt.Println(err)11 }12 err = toxicClient.Close()13 if err != nil {14 fmt.Println(err)15 }16}

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1toxics.Close()2toxics.Close()3toxics.Close()4toxics.Close()5toxicsChannel := make(chan *toxiproxy.Toxics)6go func() {7 toxics.Close()8 toxics.Close()9}()10toxics.Close()11toxics.Close()

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 toxics := client.NewToxics("localhost:8474", "test")4 toxics.Close()5 fmt.Println("Closed")6}7import (8func main() {9 toxics := client.NewToxics("localhost:8474", "test")10 toxic := client.Toxic{11 Attributes: client.Attributes{12 },13 }14 toxics.Create(&toxic)15 fmt.Println("Created")16}17import (18func main() {19 toxics := client.NewToxics("localhost:8474", "test")20 toxics.Delete("latency_downstream")21 fmt.Println("Deleted")22}23import (24func main() {25 toxics := client.NewToxics("localhost:8474", "test")26 toxic := toxics.Get("latency_downstream")27 fmt.Println("Toxic: ", toxic)28}29Toxic: &{latency_downstream downstream latency 1 map[latency:1000 jitter:100]}30import (31func main() {32 toxics := client.NewToxics("localhost:8474", "test")

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 toxics := client.NewToxics("localhost:8474")4 toxics.Close("proxy1", "latency")5 fmt.Println("Toxic Closed")6}7import (8func main() {9 toxics := client.NewToxics("localhost:8474")10 toxics.Close("proxy1", "latency")11 fmt.Println("Toxic Closed")12}13import (14func main() {15 toxics := client.NewToxics("localhost:8474")16 toxics.Close("proxy1", "latency")17 fmt.Println("Toxic Closed")18}19import (20func main() {21 toxics := client.NewToxics("localhost:8474")22 toxics.Close("proxy1", "latency")23 fmt.Println("Toxic Closed")24}25import (26func main() {

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 toxics := toxiproxy.NewClient("localhost:8474").Toxics("redis")4 toxic := toxics.Create("timeout", "downstream", 1.0, toxiproxy.Attributes{"timeout": "5000"})5 fmt.Println(toxic.Name)6 toxic.Close()7}

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 toxics := toxiproxyClient.Toxics("redis")4 toxics.Close()5}6import (7func main() {8 toxics := toxiproxyClient.Toxics("redis")9 toxics.Down()10}11import (12func main() {13 toxics := toxiproxyClient.Toxics("redis")14 toxics.Latency("upstream", 5000)15}16import (17func main() {18 toxics := toxiproxyClient.Toxics("redis")19 toxics.LatencyJitter("upstream", 5000, 1000)20}21import (22func main() {23 toxics := toxiproxyClient.Toxics("redis")24 toxics.LimitData("upstream", 100)25}26import (27func main() {28 toxics := toxiproxyClient.Toxics("redis")29 toxics.Slicer("upstream", 100, 100)30}31import (32func main() {33 toxics := toxiproxyClient.Toxics("redis")34 toxics.SlowClose("upstream", 5000)35}

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1toxics := toxiproxyClient.Toxics("proxyName")2toxics.Close()3toxic := toxiproxyClient.Toxic("proxyName", "toxicName")4toxic.Close()5toxics := toxiproxyClient.Toxics("proxyName")6toxics.Close()7toxic := toxiproxyClient.Toxic("proxyName", "toxicName")8toxic.Close()9toxics := toxiproxyClient.Toxics("proxyName")10toxics.Close()11toxic := toxiproxyClient.Toxic("proxyName", "toxicName")12toxic.Close()13toxics := toxiproxyClient.Toxics("proxyName")14toxics.Close()15toxic := toxiproxyClient.Toxic("proxyName", "toxicName")16toxic.Close()17toxics := toxiproxyClient.Toxics("proxyName")18toxics.Close()19toxic := toxiproxyClient.Toxic("proxyName", "toxicName")20toxic.Close()21toxics := toxiproxyClient.Toxics("proxyName")22toxics.Close()23toxic := toxiproxyClient.Toxic("proxyName", "toxicName")24toxic.Close()25toxics := toxiproxyClient.Toxics("proxyName")26toxics.Close()27toxic := toxiproxyClient.Toxic("proxyName", "toxicName")28toxic.Close()

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c, err := client.NewDefaultClient()4 if err != nil {5 log.Fatal(err)6 }7 proxy, err := c.CreateProxy("my_proxy", "localhost:1234", "localhost:5678")8 if err != nil {9 log.Fatal(err)10 }11 _, err = proxy.AddToxic("latency", "downstream", 1, client.ToxicAttributes{12 })13 if err != nil {14 log.Fatal(err)15 }16 c.Close()17}18import (19func main() {20 c, err := client.NewDefaultClient()21 if err != nil {22 log.Fatal(err)23 }24 proxy, err := c.CreateProxy("my_proxy", "localhost:1234", "localhost:5678")25 if err != nil {26 log.Fatal(err)27 }28 toxic, err := proxy.AddToxic("latency", "downstream", 1, client.ToxicAttributes{29 })30 if err != nil {31 log.Fatal(err)32 }33 toxic.Close()34}35import (36func main() {37 c, err := client.NewDefaultClient()38 if err != nil {39 log.Fatal(err)40 }41 proxy, err := c.CreateProxy("my_proxy", "localhost:1234", "localhost:5678")42 if err != nil {43 log.Fatal(err)44 }

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Toxiproxy automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful