How to use AddToxicJson method of toxiproxy Package

Best Toxiproxy code snippet using toxiproxy.AddToxicJson

bidirectional_test.go

Source:bidirectional_test.go Github

copy

Full Screen

...69 proxy := NewTestProxy("test", upstream)70 proxy.Start()71 // Test the 2 different code paths for adding toxics to existing links vs adding them on link creation.72 if !existingLink {73 proxy.Toxics.AddToxicJson(ToxicToJson(t, "", "echo_test", "both", &EchoToxic{}))74 }75 conn, err := net.Dial("tcp", proxy.Listen)76 if err != nil {77 t.Error("Unable to dial TCP server", err)78 }79 if existingLink {80 proxy.Toxics.AddToxicJson(ToxicToJson(t, "", "echo_test", "both", &EchoToxic{}))81 }82 f(conn, response, proxy)83 proxy.Stop()84 })85}86func AssertToxicEchoResponse(t *testing.T, proxy net.Conn, serverResponse chan []byte, expectServer bool) {87 msg := []byte("hello " + strconv.Itoa(rand.Int()) + " world\n")88 _, err := proxy.Write(msg)89 if err != nil {90 t.Error("Failed writing to TCP server", err)91 }92 scan := bufio.NewScanner(proxy)93 if !scan.Scan() {94 t.Error("Server unexpectedly closed connection")95 }96 resp := append(scan.Bytes(), '\n')97 if !bytes.Equal(resp, msg) {98 t.Error("Client didn't read correct bytes from proxy:", string(resp), "!=", string(msg))99 }100 if expectServer {101 resp = <-serverResponse102 if !bytes.Equal(resp, msg) {103 t.Error("Server didn't read correct bytes from client:", string(resp), "!=", string(msg))104 }105 } else {106 select {107 case resp = <-serverResponse:108 t.Error("Server got unexpected data from client:", string(resp))109 default:110 }111 }112}113func TestAddUpdateRemoveBidirectionalToxic(t *testing.T) {114 for existing := 0; existing < 2; existing++ {115 WithEchoToxic(t, existing > 0, func(proxy net.Conn, response chan []byte, proxyServer *toxiproxy.Proxy) {116 AssertToxicEchoResponse(t, proxy, response, false)117 proxyServer.Toxics.UpdateToxicJson("echo_test", bytes.NewReader([]byte(`{"attributes": {"replace": true}}`)))118 _, err := proxy.Write([]byte("hello world\n"))119 if err != nil {120 t.Error("Failed writing to TCP server", err)121 }122 scan := bufio.NewScanner(proxy)123 if !scan.Scan() {124 t.Error("Server unexpectedly closed connection")125 }126 resp := scan.Bytes()127 if !bytes.Equal(resp, []byte("foobar")) {128 t.Error("Client didn't read correct bytes from proxy:", string(resp), "!= foobar")129 }130 proxyServer.Toxics.RemoveToxic("echo_test")131 AssertToxicEchoResponse(t, proxy, response, true)132 })133 }134}135func TestBidirectionalToxicOnlyShowsUpOnce(t *testing.T) {136 proxy := NewTestProxy("test", "localhost:20001")137 proxy.Start()138 toxic, _ := proxy.Toxics.AddToxicJson(ToxicToJson(t, "", "echo_test", "both", &EchoToxic{}))139 if toxic.PairedToxic == nil {140 t.Fatal("Expected bidirectional toxic to have a paired toxic.")141 } else if toxic.PairedToxic.Name != "" || toxic.PairedToxic.Direction != stream.Upstream || toxic.PairedToxic.PairedToxic != toxic {142 t.Fatalf("Paired toxic had incorrect values: %+v", toxic.PairedToxic)143 } else if toxic.Direction != stream.Downstream {144 t.Fatal("Expected toxic to have downstream direction set:", toxic.Direction)145 }146 toxics := proxy.Toxics.GetToxicArray()147 if len(toxics) != 1 {148 t.Fatalf("Wrong number of toxics returned: %d != 1", len(toxics))149 } else if toxics[0].Name != "echo_test" || toxics[0].Stream != "both" {150 t.Fatalf("Toxic was not stored as expected: %+v", toxics[0])151 }152 proxy.Stop()153}154func TestBidirectionalToxicDuplicateName(t *testing.T) {155 proxy := NewTestProxy("test", "localhost:20001")156 proxy.Start()157 // Test against regular toxics158 proxy.Toxics.AddToxicJson(ToxicToJson(t, "foo", "latency", "downstream", &toxics.LatencyToxic{}))159 _, err := proxy.Toxics.AddToxicJson(ToxicToJson(t, "foo", "echo_test", "both", &EchoToxic{}))160 if err != toxiproxy.ErrToxicAlreadyExists {161 t.Fatal("Expected adding toxic to fail due to existing toxic:", err)162 }163 // Test against other bidirection toxics164 proxy.Toxics.AddToxicJson(ToxicToJson(t, "bar", "echo_test", "both", &EchoToxic{}))165 _, err = proxy.Toxics.AddToxicJson(ToxicToJson(t, "bar", "echo_test", "both", &EchoToxic{}))166 if err != toxiproxy.ErrToxicAlreadyExists {167 t.Fatal("Expected adding toxic to fail due to existing bidirectional toxic:", err)168 }169 toxics := proxy.Toxics.GetToxicArray()170 if len(toxics) != 2 {171 t.Fatalf("Wrong number of toxics returned: %d != 2", len(toxics))172 } else if toxics[0].Name != "foo" || toxics[0].Type != "latency" || toxics[0].Stream != "downstream" {173 t.Fatalf("Latency toxic was not stored as expected: %+v", toxics[0])174 } else if toxics[1].Name != "bar" || toxics[1].Type != "echo_test" || toxics[1].Stream != "both" {175 t.Fatalf("Bidirectional toxic was not stored as expected: %+v", toxics[1])176 }177 proxy.Stop()178}179func TestBidirectionalToxicWithStartToxicity(t *testing.T) {180 for existing := 0; existing < 2; existing++ {181 WithEchoToxic(t, existing > 0, func(proxy net.Conn, response chan []byte, proxyServer *toxiproxy.Proxy) {182 proxyServer.Toxics.RemoveToxic("echo_test")183 AssertToxicEchoResponse(t, proxy, response, true)184 proxyServer.Toxics.AddToxicJson(bytes.NewReader([]byte(`{"type": "echo_test", "toxicity": 0.5}`)))185 _, err := proxy.Write([]byte("hello world\n"))186 if err != nil {187 t.Error("Failed writing to TCP server", err)188 }189 scan := bufio.NewScanner(proxy)190 if !scan.Scan() {191 t.Error("Server unexpectedly closed connection")192 }193 resp := scan.Bytes()194 if !bytes.Equal(resp, []byte("hello world")) {195 t.Error("Client didn't read correct bytes from proxy:", string(resp), "!= hello world")196 }197 // Clear out response, it's random if the request made it through or not198 select {...

Full Screen

Full Screen

helper_toxi_test.go

Source:helper_toxi_test.go Github

copy

Full Screen

...19// &toxics.BandwidthToxic{20// Rate: 100 * 1000,21// }))22//23// proxy.Toxics.AddToxicJson(reader)24//25func ToxicToJson(name, typeName, stream string, toxic toxics.Toxic) io.Reader {26 data := map[string]interface{}{27 "name": name,28 "type": typeName,29 "stream": stream,30 "attributes": toxic,31 }32 request, err := json.Marshal(data)33 if err != nil {34 msg := fmt.Sprintf("Failed to marshal toxic for api (1): %v", toxic)35 panic(msg)36 }37 return bytes.NewReader(request)38}39// Available type name40// - noop41// - slicer42// - timeout43// - bandwidth44// - latency45// - limit_data46func getToxicType(tx toxics.Toxic) string {47 switch tx.(type) {48 case *toxics.NoopToxic:49 return "noop"50 case *toxics.SlicerToxic:51 return "slicer"52 case *toxics.TimeoutToxic:53 return "timeout"54 case *toxics.BandwidthToxic:55 return "bandwidth"56 case *toxics.LatencyToxic:57 return "latency"58 case *toxics.LimitDataToxic:59 return "limit_data"60 default:61 panic("Unknown toxic type")62 }63}64func getStreamDirect(stream string) string {65 tmp := strings.ToLower(stream)66 if strings.HasPrefix(tmp, "down") {67 return "downstream"68 }69 return "upstream"70}71func NewTestProxy(name, upstream string) *toxiproxy.Proxy {72 proxy := toxiproxy.NewProxy()73 proxy.Name = name74 proxy.Listen = "localhost:0"75 proxy.Upstream = upstream76 return proxy77}78type ToxicOptions struct {79 Name string80 Stream string // upstream/downstream81 Toxic toxics.Toxic82}83func toxicToReader(opts ToxicOptions) io.Reader {84 toxicType := getToxicType(opts.Toxic)85 direct := getStreamDirect(opts.Stream)86 return ToxicToJson(opts.Name, toxicType, direct, opts.Toxic)87}88func newTestProxyWithToxic(name, upstream string, opts ToxicOptions) *toxiproxy.Proxy {89 proxy := NewTestProxy(name, upstream)90 proxy.Start()91 // defer proxy.Stop()92 if opts.Toxic == nil {93 return proxy94 }95 reader := toxicToReader(opts)96 _, err := proxy.Toxics.AddToxicJson(reader)97 if err != nil {98 panic(err)99 }100 return proxy101}102func newTestClientViaProxy(clientOpts ClientOptions, txOpts ToxicOptions) (*toxiproxy.Proxy, pulsar.Client) {103 proxy := newTestProxyWithToxic("pulsar-proxy",104 "localhost:6650", txOpts)105 client, err := pulsar.NewClient(pulsar.ClientOptions{106 URL: fmt.Sprintf("pulsar://%s", proxy.Listen),107 ConnectionTimeout: clientOpts.DialTimeout,108 OperationTimeout: clientOpts.OpTimeout,109 })110 if err != nil {111 panic(err)112 }113 return proxy, client114}115// update or add toxic116// FIXME: not work, only for same type117func updateProxyToxic(proxy *toxiproxy.Proxy, opts ToxicOptions) {118 var err error119 defer func() {120 if err != nil {121 panic(err)122 }123 }()124 reader := toxicToReader(opts)125 w := proxy.Toxics.GetToxic(opts.Name)126 if w == nil {127 _, err = proxy.Toxics.AddToxicJson(reader)128 return129 }130 if reflect.TypeOf(w.Toxic) == reflect.TypeOf(opts.Toxic) {131 _, err = proxy.Toxics.UpdateToxicJson(opts.Name, reader)132 return133 }134 // remove old and add new135 err = proxy.Toxics.RemoveToxic(opts.Name)136 if err != nil {137 return138 }139 _, err = proxy.Toxics.AddToxicJson(reader)140}141func removeProxyToxic(proxy *toxiproxy.Proxy, opts ToxicOptions) {142 err := proxy.Toxics.RemoveToxic(opts.Name)143 if err != nil {144 panic(err)145 }146}147func nopToxicOptions() ToxicOptions {148 return ToxicOptions{149 Name: "nop",150 Stream: "up",151 Toxic: nil,152 }153}...

Full Screen

Full Screen

timeout_test.go

Source:timeout_test.go Github

copy

Full Screen

...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}))80 proxy.Toxics.RemoveToxic("to_delete")81 err := testhelper.TimeoutAfter(time.Second, func() {82 buf := make([]byte, 1)83 _, err := conn.Read(buf)84 if err != io.EOF {85 t.Fatal("expected EOF from closed connetion")86 }87 _, err = serverConn.Read(buf)88 if err != io.EOF {89 t.Fatal("expected EOF from closed server connetion")90 }91 })92 if err != nil {93 t.Fatal(err)...

Full Screen

Full Screen

AddToxicJson

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 toxic := &client.Toxic{4 Attributes: map[string]string{5 },6 }7 _, err := toxiproxy.AddToxicJson("proxy1", toxic)8 if err != nil {9 fmt.Println(err)10 }11}12import (13func main() {14 toxic := &client.Toxic{15 Attributes: map[string]string{16 },17 }18 proxy, err := toxiproxy.Proxy("proxy1")19 if err != nil {20 fmt.Println(err)21 }22 _, err = proxy.AddToxic(toxic)23 if err != nil {24 fmt.Println(err)25 }26}27import (28func main() {29 toxic := &client.Toxic{30 Attributes: map[string]string{31 },32 }

Full Screen

Full Screen

AddToxicJson

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 proxy := toxiproxy.Proxy{4 }5 err := client.CreateProxy(&proxy)6 if err != nil {7 panic(err)8 }9 toxic := toxiproxy.Toxic{10 Attributes: map[string]string{11 },12 }13 err = client.AddToxicJson("test", toxic)14 if err != nil {15 panic(err)16 }17}18import (19func main() {20 proxy := toxiproxy.Proxy{21 }22 err := client.CreateProxy(&proxy)23 if err != nil {24 panic(err)25 }26 toxic := toxiproxy.Toxic{27 Attributes: map[string]string{28 },29 }30 err = proxy.AddToxic(toxic)31 if err != nil {32 panic(err)33 }34}

Full Screen

Full Screen

AddToxicJson

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 proxy, err := client.CreateProxy("test", "localhost:9000", "localhost:9001")4 if err != nil {5 fmt.Println(err)6 }7 toxic, err := proxy.AddToxic("latency", "downstream", 1.0, toxiproxy.Attributes{"latency": 1000, "jitter": 0})8 if err != nil {9 fmt.Println(err)10 }11 toxic, err = proxy.UpdateToxic(toxic)12 if err != nil {13 fmt.Println(err)14 }15 err = proxy.DeleteToxic(toxic)16 if err != nil {17 fmt.Println(err)18 }19 err = client.DeleteProxy(proxy)20 if err != nil {21 fmt.Println(err)22 }23}

Full Screen

Full Screen

AddToxicJson

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 proxy := client.NewClient("localhost:8474")4 proxy.AddToxicJson("proxy", "downstream", "latency", 1, `{"latency": 500, "jitter": 200}`)5}6import (7func main() {8 proxy := client.NewClient("localhost:8474")9 toxic := client.Toxic{Type: "latency", Stream: "downstream", Attributes: map[string]interface{}{"latency": 500, "jitter": 200}}10 proxy.AddToxic("proxy", toxic)11}12import (13func main() {14 proxy := client.NewClient("localhost:8474")15 proxy.Proxy("proxy").AddToxicJson("latency", 1, `{"latency": 500, "jitter": 200}`)16}17import (18func main() {19 proxy := client.NewClient("localhost:8474")20 toxic := client.Toxic{Type: "latency", Stream: "downstream", Attributes: map[string]interface{}{"latency": 500, "jitter": 200}}21 proxy.Proxy("proxy").AddToxic(toxic)22}23import (24func main() {25 proxy := client.NewClient("localhost:8474")26 proxy.Proxy("proxy").AddToxicJson("latency", 1, `{"latency": 500, "jitter": 200}`)27}28import (

Full Screen

Full Screen

AddToxicJson

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 _, err := proxy.CreateProxy("test", "localhost:80", "localhost:8080")4 if err != nil {5 fmt.Println(err)6 }7 toxic := client.Toxic{8 Attributes: client.Attributes{9 },10 }11 err = proxy.AddToxicJson("test", toxic)12 if err != nil {13 fmt.Println(err)14 }15}16* Connected to localhost (::1) port 8474 (#0)17{18 {19 "attributes": {20 },

Full Screen

Full Screen

AddToxicJson

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 proxy, err := toxiproxyClient.CreateProxy("test1", "localhost:3000", "localhost:3001")4 if err != nil {5 panic(err)6 }7 fmt.Printf("Proxy created: %v", proxy)8 toxic, err := toxiproxyClient.AddToxicJson(proxy.Name, &client.ToxicJson{9 Attributes: map[string]interface{}{10 },11 })12 if err != nil {13 panic(err)14 }15 fmt.Printf("Toxic created: %v", toxic)16 err = toxiproxyClient.RemoveToxicJson(proxy.Name, toxic.Name)17 if err != nil {18 panic(err)19 }20 fmt.Printf("Toxic removed: %v", toxic)21 toxics, err := toxiproxyClient.GetToxicsJson(proxy.Name)22 if err != nil {23 panic(err)24 }25 fmt.Printf("Toxics of a proxy: %v", toxics)26 toxic, err = toxiproxyClient.GetToxicJson(proxy.Name, toxic.Name)27 if err != nil {28 panic(err)29 }30 fmt.Printf("Toxic of a proxy: %v", toxic)31 toxic, err = toxiproxyClient.UpdateToxicJson(proxy.Name, toxic.Name, &client.ToxicJson

Full Screen

Full Screen

AddToxicJson

Using AI Code Generation

copy

Full Screen

1toxiproxy.AddToxicJson("proxyname", "downstream", "timeout", "timeout", 1, 1, 0, 0, 0)2toxiproxy.AddToxicJson("proxyname", "downstream", "timeout", "timeout", 1, 1, 0, 0, 0)3toxiproxy.AddToxicJson("proxyname", "downstream", "timeout", "timeout", 1, 1, 0, 0, 0)4toxiproxy.AddToxicJson("proxyname", "downstream", "timeout", "timeout", 1, 1, 0, 0, 0)5toxiproxy.AddToxicJson("proxyname", "downstream", "timeout", "timeout", 1, 1, 0, 0, 0)6toxiproxy.AddToxicJson("proxyname", "downstream", "timeout", "timeout", 1, 1, 0, 0, 0)7toxiproxy.AddToxicJson("proxyname", "downstream", "timeout", "timeout", 1, 1, 0, 0, 0)

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful