How to use Toxics method of toxiproxy Package

Best Toxiproxy code snippet using toxiproxy.Toxics

cli.go

Source:cli.go Github

copy

Full Screen

...27 return ""28 }29}30var toxicDescription = `31 Default Toxics:32 latency: delay all data +/- jitter33 latency=<ms>,jitter=<ms>34 bandwidth: limit to max kb/s35 rate=<KB/s>36 slow_close: delay from closing37 delay=<ms>38 timeout: stop all data and close after timeout39 timeout=<ms>40 slicer: slice data into bits with optional delay41 average_size=<bytes>,size_variation=<bytes>,delay=<microseconds>42 toxic add:43 usage: toxiproxy-cli toxic add <proxyName> --type <toxicType> --toxicName <toxicName> \44 --attribute <key=value> --upstream --downstream45 example: toxiproxy-cli toxic add myProxy -t latency -n myToxic -a latency=100 -a jitter=5046 toxic update:47 usage: toxiproxy-cli toxic update <proxyName> --toxicName <toxicName> \48 --attribute <key1=value1> --attribute <key2=value2>49 example: toxiproxy-cli toxic update myProxy -n myToxic -a jitter=2550 toxic delete:51 usage: toxiproxy-cli toxic delete <proxyName> --toxicName <toxicName>52 example: toxiproxy-cli toxic delete myProxy -n myToxic53`54var hostname string55var isTTY bool56func main() {57 app := cli.NewApp()58 app.Name = "toxiproxy-cli"59 app.Version = toxiproxyServer.Version60 app.Usage = "Simulate network and system conditions"61 app.Commands = []cli.Command{62 {63 Name: "list",64 Usage: "list all proxies\n\tusage: 'toxiproxy-cli list'\n",65 Aliases: []string{"l", "li", "ls"},66 Action: withToxi(list),67 },68 {69 Name: "inspect",70 Aliases: []string{"i", "ins"},71 Usage: "inspect a single proxy\n\tusage: 'toxiproxy-cli inspect <proxyName>'\n",72 Action: withToxi(inspectProxy),73 },74 {75 Name: "create",76 Usage: "create a new proxy\n\tusage: 'toxiproxy-cli create <proxyName> --listen <addr> --upstream <addr>'\n",77 Aliases: []string{"c", "new"},78 Flags: []cli.Flag{79 cli.StringFlag{80 Name: "listen, l",81 Usage: "proxy will listen on this address",82 },83 cli.StringFlag{84 Name: "upstream, u",85 Usage: "proxy will forward to this address",86 },87 },88 Action: withToxi(createProxy),89 },90 {91 Name: "toggle",92 Usage: "\ttoggle enabled status on a proxy\n\t\tusage: 'toxiproxy-cli toggle <proxyName>'\n",93 Aliases: []string{"tog"},94 Action: withToxi(toggleProxy),95 },96 {97 Name: "delete",98 Usage: "\tdelete a proxy\n\t\tusage: 'toxiproxy-cli delete <proxyName>'\n",99 Aliases: []string{"d"},100 Action: withToxi(deleteProxy),101 },102 {103 Name: "toxic",104 Aliases: []string{"t"},105 Usage: "\tadd, remove or update a toxic\n\t\tusage: see 'toxiproxy-cli toxic'\n",106 Description: toxicDescription,107 Subcommands: []cli.Command{108 {109 Name: "add",110 Aliases: []string{"a"},111 Usage: "add a new toxic",112 ArgsUsage: "<proxyName>",113 Flags: []cli.Flag{114 cli.StringFlag{115 Name: "toxicName, n",116 Usage: "name of the toxic",117 },118 cli.StringFlag{119 Name: "type, t",120 Usage: "type of toxic",121 },122 cli.StringFlag{123 Name: "toxicity, tox",124 Usage: "toxicity of toxic",125 },126 cli.StringSliceFlag{127 Name: "attribute, a",128 Usage: "toxic attribute in key=value format",129 },130 cli.BoolFlag{131 Name: "upstream, u",132 Usage: "add toxic to upstream",133 },134 cli.BoolFlag{135 Name: "downstream, d",136 Usage: "add toxic to downstream",137 },138 },139 Action: withToxi(addToxic),140 },141 {142 Name: "update",143 Aliases: []string{"u"},144 Usage: "update an enabled toxic",145 ArgsUsage: "<proxyName>",146 Flags: []cli.Flag{147 cli.StringFlag{148 Name: "toxicName, n",149 Usage: "name of the toxic",150 },151 cli.StringFlag{152 Name: "toxicity, tox",153 Usage: "toxicity of toxic",154 },155 cli.StringSliceFlag{156 Name: "attribute, a",157 Usage: "toxic attribute in key=value format",158 },159 },160 Action: withToxi(updateToxic),161 },162 {163 Name: "remove",164 Aliases: []string{"r", "delete", "d"},165 Usage: "remove an enabled toxic",166 ArgsUsage: "<proxyName>",167 Flags: []cli.Flag{168 cli.StringFlag{169 Name: "toxicName, n",170 Usage: "name of the toxic",171 },172 },173 Action: withToxi(removeToxic),174 },175 },176 },177 }178 cli.HelpFlag = cli.BoolFlag{179 Name: "help",180 Usage: "show help",181 }182 app.Flags = []cli.Flag{183 cli.StringFlag{184 Name: "host, h",185 Value: "http://localhost:8474",186 Usage: "toxiproxy host to connect to",187 Destination: &hostname,188 },189 }190 isTTY = terminal.IsTerminal(int(os.Stdout.Fd()))191 app.Run(os.Args)192}193type toxiAction func(*cli.Context, *toxiproxy.Client) error194func withToxi(f toxiAction) func(*cli.Context) error {195 return func(c *cli.Context) error {196 toxiproxyClient := toxiproxy.NewClient(hostname)197 return f(c, toxiproxyClient)198 }199}200func list(c *cli.Context, t *toxiproxy.Client) error {201 proxies, err := t.Proxies()202 if err != nil {203 return errorf("Failed to retrieve proxies: %s", err)204 }205 var proxyNames []string206 for proxyName := range proxies {207 proxyNames = append(proxyNames, proxyName)208 }209 sort.Strings(proxyNames)210 if isTTY {211 fmt.Printf("%sName\t\t\t%sListen\t\t%sUpstream\t\t%sEnabled\t\t%sToxics\n%s", color(GREEN), color(BLUE),212 color(YELLOW), color(PURPLE), color(RED), color(NONE))213 fmt.Printf("%s======================================================================================\n", color(NONE))214 if len(proxyNames) == 0 {215 fmt.Printf("%sno proxies\n%s", color(RED), color(NONE))216 hint("create a proxy with `toxiproxy-cli create`")217 return nil218 }219 }220 for _, proxyName := range proxyNames {221 proxy := proxies[proxyName]222 numToxics := strconv.Itoa(len(proxy.ActiveToxics))223 if numToxics == "0" && isTTY {224 numToxics = "None"225 }226 printWidth(color(colorEnabled(proxy.Enabled)), proxy.Name, 3)227 printWidth(BLUE, proxy.Listen, 2)228 printWidth(YELLOW, proxy.Upstream, 3)229 printWidth(PURPLE, enabledText(proxy.Enabled), 2)230 fmt.Printf("%s%s%s\n", color(RED), numToxics, color(NONE))231 }232 hint("inspect toxics with `toxiproxy-cli inspect <proxyName>`")233 return nil234}235func inspectProxy(c *cli.Context, t *toxiproxy.Client) error {236 proxyName := c.Args().First()237 if proxyName == "" {238 cli.ShowSubcommandHelp(c)239 return errorf("Proxy name is required as the first argument.\n")240 }241 proxy, err := t.Proxy(proxyName)242 if err != nil {243 return errorf("Failed to retrieve proxy %s: %s\n", proxyName, err.Error())244 }245 if isTTY {246 fmt.Printf("%sName: %s%s\t", color(PURPLE), color(NONE), proxy.Name)247 fmt.Printf("%sListen: %s%s\t", color(BLUE), color(NONE), proxy.Listen)248 fmt.Printf("%sUpstream: %s%s\n", color(YELLOW), color(NONE), proxy.Upstream)249 fmt.Printf("%s======================================================================\n", color(NONE))250 splitToxics := func(toxics toxiproxy.Toxics) (toxiproxy.Toxics, toxiproxy.Toxics) {251 upstream := make(toxiproxy.Toxics, 0)252 downstream := make(toxiproxy.Toxics, 0)253 for _, toxic := range toxics {254 if toxic.Stream == "upstream" {255 upstream = append(upstream, toxic)256 } else {257 downstream = append(downstream, toxic)258 }259 }260 return upstream, downstream261 }262 if len(proxy.ActiveToxics) == 0 {263 fmt.Printf("%sProxy has no toxics enabled.\n%s", color(RED), color(NONE))264 } else {265 up, down := splitToxics(proxy.ActiveToxics)266 listToxics(up, "Upstream")267 fmt.Println()268 listToxics(down, "Downstream")269 }270 hint("add a toxic with `toxiproxy-cli toxic add`")271 } else {272 listToxics(proxy.ActiveToxics, "")273 }274 return nil275}276func toggleProxy(c *cli.Context, t *toxiproxy.Client) error {277 proxyName := c.Args().First()278 if proxyName == "" {279 cli.ShowSubcommandHelp(c)280 return errorf("Proxy name is required as the first argument.\n")281 }282 proxy, err := t.Proxy(proxyName)283 if err != nil {284 return errorf("Failed to retrieve proxy %s: %s\n", proxyName, err.Error())285 }286 proxy.Enabled = !proxy.Enabled287 err = proxy.Save()288 if err != nil {289 return errorf("Failed to toggle proxy %s: %s\n", proxyName, err.Error())290 }291 fmt.Printf("Proxy %s%s%s is now %s%s%s\n", colorEnabled(proxy.Enabled), proxyName, color(NONE), colorEnabled(proxy.Enabled), enabledText(proxy.Enabled), color(NONE))292 return nil293}294func createProxy(c *cli.Context, t *toxiproxy.Client) error {295 proxyName := c.Args().First()296 if proxyName == "" {297 cli.ShowSubcommandHelp(c)298 return errorf("Proxy name is required as the first argument.\n")299 }300 listen, err := getArgOrFail(c, "listen")301 if err != nil {302 return err303 }304 upstream, err := getArgOrFail(c, "upstream")305 if err != nil {306 return err307 }308 _, err = t.CreateProxy(proxyName, listen, upstream)309 if err != nil {310 return errorf("Failed to create proxy: %s\n", err.Error())311 }312 fmt.Printf("Created new proxy %s\n", proxyName)313 return nil314}315func deleteProxy(c *cli.Context, t *toxiproxy.Client) error {316 proxyName := c.Args().First()317 if proxyName == "" {318 cli.ShowSubcommandHelp(c)319 return errorf("Proxy name is required as the first argument.\n")320 }321 p, err := t.Proxy(proxyName)322 if err != nil {323 return errorf("Failed to retrieve proxy %s: %s\n", proxyName, err.Error())324 }325 err = p.Delete()326 if err != nil {327 return errorf("Failed to delete proxy: %s\n", err.Error())328 }329 fmt.Printf("Deleted proxy %s\n", proxyName)330 return nil331}332func parseToxicity(c *cli.Context, defaultToxicity float32) (float32, error) {333 var toxicity = defaultToxicity334 toxicityString := c.String("toxicity")335 if toxicityString != "" {336 tox, err := strconv.ParseFloat(toxicityString, 32)337 if err != nil || tox > 1 || tox < 0 {338 return 0, errorf("toxicity should be a float between 0 and 1.\n")339 }340 toxicity = float32(tox)341 }342 return toxicity, nil343}344func addToxic(c *cli.Context, t *toxiproxy.Client) error {345 proxyName := c.Args().First()346 if proxyName == "" {347 cli.ShowSubcommandHelp(c)348 return errorf("Proxy name is required as the first argument.\n")349 }350 toxicName := c.String("toxicName")351 toxicType, err := getArgOrFail(c, "type")352 if err != nil {353 return err354 }355 upstream := c.Bool("upstream")356 downstream := c.Bool("downstream")357 toxicity, err := parseToxicity(c, 1.0)358 if err != nil {359 return err360 }361 attributes := parseAttributes(c, "attribute")362 p, err := t.Proxy(proxyName)363 if err != nil {364 return errorf("Failed to retrieve proxy %s: %s\n", proxyName, err.Error())365 }366 addToxic := func(stream string) error {367 t, err := p.AddToxic(toxicName, toxicType, stream, toxicity, attributes)368 if err != nil {369 return errorf("Failed to add toxic: %s\n", err.Error())370 }371 toxicName = t.Name372 fmt.Printf("Added %s %s toxic '%s' on proxy '%s'\n", stream, toxicType, toxicName, proxyName)373 return nil374 }375 if upstream {376 err := addToxic("upstream")377 if err != nil {378 return err379 }380 }381 // Default to downstream.382 if downstream || (!downstream && !upstream) {383 return addToxic("downstream")384 }385 return nil386}387func updateToxic(c *cli.Context, t *toxiproxy.Client) error {388 proxyName := c.Args().First()389 if proxyName == "" {390 cli.ShowSubcommandHelp(c)391 return errorf("Proxy name is required as the first argument.\n")392 }393 toxicName, err := getArgOrFail(c, "toxicName")394 if err != nil {395 return err396 }397 attributes := parseAttributes(c, "attribute")398 p, err := t.Proxy(proxyName)399 if err != nil {400 return errorf("Failed to retrieve proxy %s: %s\n", proxyName, err.Error())401 }402 toxicity, err := parseToxicity(c, -1)403 if err != nil {404 return nil405 }406 _, err = p.UpdateToxic(toxicName, toxicity, attributes)407 if err != nil {408 return errorf("Failed to update toxic: %s\n", err.Error())409 }410 fmt.Printf("Updated toxic '%s' on proxy '%s'\n", toxicName, proxyName)411 return nil412}413func removeToxic(c *cli.Context, t *toxiproxy.Client) error {414 proxyName := c.Args().First()415 if proxyName == "" {416 cli.ShowSubcommandHelp(c)417 return errorf("Proxy name is required as the first argument.\n")418 }419 toxicName, err := getArgOrFail(c, "toxicName")420 if err != nil {421 return err422 }423 p, err := t.Proxy(proxyName)424 if err != nil {425 return errorf("Failed to retrieve proxy %s: %s\n", proxyName, err.Error())426 }427 err = p.RemoveToxic(toxicName)428 if err != nil {429 return errorf("Failed to remove toxic: %s\n", err.Error())430 }431 fmt.Printf("Removed toxic '%s' on proxy '%s'\n", toxicName, proxyName)432 return nil433}434func parseAttributes(c *cli.Context, name string) toxiproxy.Attributes {435 parsed := map[string]interface{}{}436 args := c.StringSlice(name)437 for _, raw := range args {438 kv := strings.SplitN(raw, "=", 2)439 if len(kv) < 2 {440 continue441 }442 if float, err := strconv.ParseFloat(kv[1], 64); err == nil {443 parsed[kv[0]] = float444 } else {445 parsed[kv[0]] = kv[1]446 }447 }448 return parsed449}450func colorEnabled(enabled bool) string {451 if enabled {452 return color(GREEN)453 }454 return color(RED)455}456func enabledText(enabled bool) string {457 if enabled {458 return "enabled"459 }460 return "disabled"461}462type attribute struct {463 key string464 value interface{}465}466type attributeList []attribute467func (a attributeList) Len() int { return len(a) }468func (a attributeList) Less(i, j int) bool { return a[i].key < a[j].key }469func (a attributeList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }470func sortedAttributes(attrs toxiproxy.Attributes) attributeList {471 li := make(attributeList, 0, len(attrs))472 for k, v := range attrs {473 li = append(li, attribute{k, v.(float64)})474 }475 sort.Sort(li)476 return li477}478func listToxics(toxics toxiproxy.Toxics, stream string) {479 if isTTY {480 fmt.Printf("%s%s toxics:\n%s", color(GREEN), stream, color(NONE))481 if len(toxics) == 0 {482 fmt.Printf("%sProxy has no %s toxics enabled.\n%s", color(RED), stream, color(NONE))483 return484 }485 }486 for _, t := range toxics {487 if isTTY {488 fmt.Printf("%s%s:%s\t", color(BLUE), t.Name, color(NONE))489 } else {490 fmt.Printf("%s\t", t.Name)491 }492 fmt.Printf("type=%s\t", t.Type)...

Full Screen

Full Screen

client.go

Source:client.go Github

copy

Full Screen

...24 Stream string `json:"stream,omitempty"`25 Toxicity float32 `json:"toxicity"`26 Attributes Attributes `json:"attributes"`27}28type Toxics []Toxic29type Proxy struct {30 Name string `json:"name"` // The name of the proxy31 Listen string `json:"listen"` // The address the proxy listens on32 Upstream string `json:"upstream"` // The upstream address to proxy to33 Enabled bool `json:"enabled"` // Whether the proxy is enabled34 ActiveToxics Toxics `json:"toxics"` // The toxics active on this proxy35 client *Client36 created bool // True if this proxy exists on the server37}38// NewClient creates a new client which provides the base of all communication39// with Toxiproxy. Endpoint is the address to the proxy (e.g. localhost:8474 if40// not overriden)41func NewClient(endpoint string) *Client {42 if strings.HasPrefix(endpoint, "https://") {43 log.Fatal("the toxiproxy client does not support https")44 } else if !strings.HasPrefix(endpoint, "http://") {45 endpoint = "http://" + endpoint46 }47 return &Client{endpoint: endpoint}48}49// Proxies returns a map with all the proxies and their toxics.50func (client *Client) Proxies() (map[string]*Proxy, error) {51 resp, err := http.Get(client.endpoint + "/proxies")52 if err != nil {53 return nil, err54 }55 err = checkError(resp, http.StatusOK, "Proxies")56 if err != nil {57 return nil, err58 }59 proxies := make(map[string]*Proxy)60 err = json.NewDecoder(resp.Body).Decode(&proxies)61 if err != nil {62 return nil, err63 }64 for _, proxy := range proxies {65 proxy.client = client66 proxy.created = true67 }68 return proxies, nil69}70// Generates a new uncommitted proxy instance. In order to use the result, the71// proxy fields will need to be set and have `Save()` called.72func (client *Client) NewProxy() *Proxy {73 return &Proxy{74 client: client,75 }76}77// CreateProxy instantiates a new proxy and starts listening on the specified address.78// This is an alias for `NewProxy()` + `proxy.Save()`79func (client *Client) CreateProxy(name, listen, upstream string) (*Proxy, error) {80 proxy := &Proxy{81 Name: name,82 Listen: listen,83 Upstream: upstream,84 Enabled: true,85 client: client,86 }87 err := proxy.Save()88 if err != nil {89 return nil, err90 }91 return proxy, nil92}93// Proxy returns a proxy by name.94func (client *Client) Proxy(name string) (*Proxy, error) {95 // TODO url encode96 resp, err := http.Get(client.endpoint + "/proxies/" + name)97 if err != nil {98 return nil, err99 }100 err = checkError(resp, http.StatusOK, "Proxy")101 if err != nil {102 return nil, err103 }104 proxy := new(Proxy)105 err = json.NewDecoder(resp.Body).Decode(proxy)106 if err != nil {107 return nil, err108 }109 proxy.client = client110 proxy.created = true111 return proxy, nil112}113// Create a list of proxies using a configuration list. If a proxy already exists, it will be replaced114// with the specified configuration. For large amounts of proxies, `config` can be loaded from a file.115// Returns a list of the successfully created proxies.116func (client *Client) Populate(config []Proxy) ([]*Proxy, error) {117 proxies := struct {118 Proxies []*Proxy `json:"proxies"`119 }{}120 request, err := json.Marshal(config)121 if err != nil {122 return nil, err123 }124 resp, err := http.Post(client.endpoint+"/populate", "application/json", bytes.NewReader(request))125 if err != nil {126 return nil, err127 }128 // Response body may need to be read twice, we want to return both the proxy list and any errors129 var body bytes.Buffer130 tee := io.TeeReader(resp.Body, &body)131 err = json.NewDecoder(tee).Decode(&proxies)132 if err != nil {133 return nil, err134 }135 resp.Body = ioutil.NopCloser(&body)136 err = checkError(resp, http.StatusCreated, "Populate")137 return proxies.Proxies, err138}139// Save saves changes to a proxy such as its enabled status or upstream port.140func (proxy *Proxy) Save() error {141 request, err := json.Marshal(proxy)142 if err != nil {143 return err144 }145 var resp *http.Response146 if proxy.created {147 resp, err = http.Post(proxy.client.endpoint+"/proxies/"+proxy.Name, "text/plain", bytes.NewReader(request))148 } else {149 resp, err = http.Post(proxy.client.endpoint+"/proxies", "application/json", bytes.NewReader(request))150 }151 if err != nil {152 return err153 }154 if proxy.created {155 err = checkError(resp, http.StatusOK, "Save")156 } else {157 err = checkError(resp, http.StatusCreated, "Create")158 }159 if err != nil {160 return err161 }162 err = json.NewDecoder(resp.Body).Decode(proxy)163 if err != nil {164 return err165 }166 proxy.created = true167 return nil168}169// Enable a proxy again after it has been disabled.170func (proxy *Proxy) Enable() error {171 proxy.Enabled = true172 return proxy.Save()173}174// Disable a proxy so that no connections can pass through. This will drop all active connections.175func (proxy *Proxy) Disable() error {176 proxy.Enabled = false177 return proxy.Save()178}179// Delete a proxy complete and close all existing connections through it. All information about180// the proxy such as listen port and active toxics will be deleted as well. If you just wish to181// stop and later enable a proxy, use `Enable()` and `Disable()`.182func (proxy *Proxy) Delete() error {183 httpClient := &http.Client{}184 req, err := http.NewRequest("DELETE", proxy.client.endpoint+"/proxies/"+proxy.Name, nil)185 if err != nil {186 return err187 }188 resp, err := httpClient.Do(req)189 if err != nil {190 return err191 }192 return checkError(resp, http.StatusNoContent, "Delete")193}194// Toxics returns a map of all the active toxics and their attributes.195func (proxy *Proxy) Toxics() (Toxics, error) {196 resp, err := http.Get(proxy.client.endpoint + "/proxies/" + proxy.Name + "/toxics")197 if err != nil {198 return nil, err199 }200 err = checkError(resp, http.StatusOK, "Toxics")201 if err != nil {202 return nil, err203 }204 toxics := make(Toxics, 0)205 err = json.NewDecoder(resp.Body).Decode(&toxics)206 if err != nil {207 return nil, err208 }209 return toxics, nil210}211// AddToxic adds a toxic to the given stream direction.212// If a name is not specified, it will default to <type>_<stream>.213// If a stream is not specified, it will default to downstream.214// See https://github.com/Shopify/toxiproxy#toxics for a list of all Toxic types.215func (proxy *Proxy) AddToxic(name, typeName, stream string, toxicity float32, attrs Attributes) (*Toxic, error) {216 toxic := Toxic{name, typeName, stream, toxicity, attrs}217 if toxic.Toxicity == -1 {218 toxic.Toxicity = 1 // Just to be consistent with a toxicity of -1 using the default...

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

Toxics

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 toxics, err := c.Toxics("redis")4 if err != nil {5 fmt.Println("Error:", err)6 }7 fmt.Println(toxics)8}9import (10func main() {11 toxic, err := c.Toxic("redis", "latency")12 if err != nil {

Full Screen

Full Screen

Toxics

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 toxics, err := toxiproxyClient.Toxics("redis")4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println(toxics)8}

Full Screen

Full Screen

Toxics

Using AI Code Generation

copy

Full Screen

1func main() {2 toxics, err := toxiproxy.Toxics("redis")3 if err != nil {4 panic(err)5 }6 fmt.Println(toxics)7}8func main() {9 toxic := toxiproxy.Toxic{10 Attributes: toxiproxy.Attributes{11 },12 }13 err := toxiproxy.CreateToxic("redis", "latency", toxic)14 if err != nil {15 panic(err)16 }17}18func main() {19 toxic := toxiproxy.Toxic{20 Attributes: toxiproxy.Attributes{21 },22 }23 err := toxiproxy.UpdateToxic("redis", "latency", toxic)24 if err != nil {25 panic(err)26 }27}

Full Screen

Full Screen

Toxics

Using AI Code Generation

copy

Full Screen

1func main() {2 toxics, err := toxiproxy.Toxics("redis")3 if err != nil {4 fmt.Println(err)5 }6 for _, toxic := range toxics {7 fmt.Println(toxic.Name)8 }9}10func main() {11 toxic := &toxiproxy.Toxic{12 Attributes: map[string]interface{}{13 },14 }15 err := toxiproxy.CreateToxic("redis", toxic)16 if err != nil {17 fmt.Println(err)18 }19}20func main() {21 toxic, err := toxiproxy.GetToxic("redis", "latency")22 if err != nil {23 fmt.Println(err)24 }25 fmt.Println(toxic.Name)26}27func main() {28 toxic := &toxiproxy.Toxic{29 Attributes: map[string]interface{}{30 },31 }32 err := toxiproxy.UpdateToxic("redis", toxic)33 if err != nil {34 fmt.Println(err)35 }36}37func main() {38 err := toxiproxy.DeleteToxic("redis", "latency")39 if err != nil {40 fmt.Println(err)41 }42}

Full Screen

Full Screen

Toxics

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 toxics, err := client.Toxics("proxy1")4 if err != nil {5 fmt.Println("Error getting toxics:", err)6 } else {7 fmt.Println("Toxics:", toxics)8 }9}10import (11func main() {12 toxics, err := client.Toxics("proxy1")13 if err != nil {14 fmt.Println("Error getting toxics:", err)15 } else {16 fmt.Println("Toxics:", toxics)17 }18 toxic, err := client.Toxic("proxy1", "latency")19 if err != nil {20 fmt.Println("Error getting toxic:", err)21 } else {22 fmt.Println("Toxic:", toxic)23 }24}25Toxic: &{latency latency 0 0 0 0 0}26import (27func main() {28 toxics, err := client.Toxics("proxy1")29 if err != nil {30 fmt.Println("Error getting toxics:", err)31 } else {32 fmt.Println("Toxics:", toxics)33 }34 toxic, err := client.Toxic("proxy1", "latency")35 if err != nil {36 fmt.Println("Error getting toxic:", err)37 } else {38 fmt.Println("Toxic:", toxic)

Full Screen

Full Screen

Toxics

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 panic(err)5 }6 toxics, err := proxyClient.Toxics("redis-master")7 if err != nil {8 panic(err)9 }10 fmt.Println(toxics)11 toxic := client.Toxic{12 Attributes: map[string]interface{}{13 },14 }15 err = proxyClient.AddToxic("redis-master", toxic)16 if err != nil {17 panic(err)18 }19}20import (21func main() {22 if err != nil {23 panic(err)24 }25 toxic := client.Toxic{26 Attributes: map[string]interface{}{27 },28 }29 toxic, err = proxyClient.Toxics("redis-master").CreateToxic(toxic)30 if err != nil {31 panic(err)32 }33 fmt.Println(toxic)34}35import (36func main() {37 if err != nil {38 panic(err)39 }

Full Screen

Full Screen

Toxics

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 toxics := client.Toxics{4 }5 toxics, err := toxics.List()6 if err != nil {7 panic(err)8 }9 fmt.Println(toxics)10}11[{ProxyName:proxy1 Name:downstream Type:latency Stream:downstream Attributes:map[latency:1000 jitter:0 correlation:0]} {ProxyName:proxy1 Name:downstream Type:bandwidth Stream:downstream Attributes:map[rate:10000000]}]12import (13func main() {14 toxic := client.Toxic{15 Attributes: map[string]string{16 },17 }18 err := toxic.Create()19 if err != nil {20 panic(err)21 }22 fmt.Println(toxic)23}24{ProxyName:proxy1 Name:downstream Type:latency Stream:downstream Attributes:map[correlation:0 jitter:0 latency:1000]}

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