How to use Unlock method of toxiproxy Package

Best Toxiproxy code snippet using toxiproxy.Unlock

loadbot.go

Source:loadbot.go Github

copy

Full Screen

...172 // also mining. https://github.com/zcash/zcash/issues/6045173 zecSendMtx.Lock()174 defer func() {175 time.Sleep(time.Second)176 zecSendMtx.Unlock()177 }()178 }179 return harnessCtl(ctx, symbol, fmt.Sprintf("./mine-%s", node), fmt.Sprintf("%d", n))180}181// harnessResult is the result of a harnessCtl command.182type harnessResult struct {183 err error184 output string185 cmd string186}187// String returns a result string for the harnessResult.188func (res *harnessResult) String() string {189 if res.err != nil {190 return fmt.Sprintf("error running harness command %q: %v", res.cmd, res.err)191 }192 return fmt.Sprintf("response from harness command %q: %s", res.cmd, res.output)193}194func harnessSymbol(symbol string) string {195 switch symbol {196 case dextt:197 return eth198 }199 return symbol200}201// harnessCtl will run the command from the harness-ctl directory for the202// specified symbol. ctx shadows the global context. The global context is not203// used because stopping some nodes will occur after it is canceled.204func harnessCtl(ctx context.Context, symbol, cmd string, args ...string) <-chan *harnessResult {205 dir := filepath.Join(dextestDir, harnessSymbol(symbol), "harness-ctl")206 c := make(chan *harnessResult)207 go func() {208 fullCmd := strings.Join(append([]string{cmd}, args...), " ")209 command := exec.CommandContext(ctx, cmd, args...)210 command.Dir = dir211 output, err := command.Output()212 if err != nil {213 var exitErr *exec.ExitError214 if errors.As(err, &exitErr) {215 log.Errorf("exec error (%s) %q: %v: %s", symbol, cmd, err, string(exitErr.Stderr))216 } else {217 log.Errorf("%s harnessCtl error running %q: %v", symbol, cmd, err)218 }219 }220 c <- &harnessResult{221 err: err,222 output: strings.TrimSpace(string(output)),223 cmd: fullCmd,224 }225 }()226 return c227}228// harnessProcessCtl will run the long running command from the harness-ctl229// directory for the specified symbol. The command and stop function are saved230// to a global slice for stopping later.231func harnessProcessCtl(symbol string, stopFn func(context.Context), cmd string, args ...string) error {232 processesMtx.Lock()233 defer processesMtx.Unlock()234 if err := ctx.Err(); err != nil {235 return err236 }237 dir := filepath.Join(dextestDir, harnessSymbol(symbol), "harness-ctl")238 // Killing the process with ctx or process.Kill *sometimes* does not239 // seem to stop the coin daemon. Kill later with an rpc "stop" command240 // contained in the stop function.241 command := exec.Command(cmd, args...)242 command.Dir = dir243 p := &process{244 cmd: command,245 stopFn: stopFn,246 }247 if err := command.Start(); err != nil {248 return fmt.Errorf("unable to start process: %v", err)249 }250 processes = append(processes, p)251 return nil252}253// nextAddr returns a new address, as well as the selected port, both as254// strings.255func nextAddr() (addrPort, port string, err error) {256 addrs, err := findOpenAddrs(1)257 if err != nil {258 return "", "", err259 }260 addrPort = addrs[0].String()261 _, port, err = net.SplitHostPort(addrPort)262 if err != nil {263 return "", "", err264 }265 return addrPort, port, nil266}267// shutdown stops some long running processes.268func shutdown() {269 processesMtx.Lock()270 defer processesMtx.Unlock()271 for _, p := range processes {272 ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)273 defer cancel()274 p.stopFn(ctx)275 if err := p.cmd.Wait(); err != nil {276 fmt.Printf("failed to wait for stopped process: %v\n", err)277 }278 }279}280func main() {281 // Catch ctrl+c for a clean shutdown.282 killChan := make(chan os.Signal, 1)283 signal.Notify(killChan, os.Interrupt)284 go func() {285 <-killChan286 quit()287 }()288 if err := run(); err != nil {289 println(err.Error())290 quit()291 os.Exit(1)292 }293 quit()294 os.Exit(0)295}296func run() error {297 defer shutdown()298 var programName string299 var debug, trace, latency500, shaky500, slow100, spotty20, registerWithQuote bool300 var m, n int301 flag.StringVar(&programName, "p", "", "the bot program to run")302 flag.StringVar(&market, "mkt", "dcr_btc", "the market to run on")303 flag.BoolVar(&registerWithQuote, "rwq", false, "pay the register fee with the quote asset (default is base)")304 flag.BoolVar(&keepMidGap, "kmg", false, "disallow mid gap drift")305 flag.BoolVar(&latency500, "latency500", false, "add 500 ms of latency to downstream comms for wallets and server")306 flag.BoolVar(&shaky500, "shaky500", false, "add 500 ms +/- 500ms of latency to downstream comms for wallets and server")307 flag.BoolVar(&slow100, "slow100", false, "limit bandwidth on all server and wallet connections to 100 kB/s")308 flag.BoolVar(&spotty20, "spotty20", false, "drop all connections every 20 seconds")309 flag.BoolVar(&debug, "debug", false, "use debug logging")310 flag.BoolVar(&trace, "trace", false, "use trace logging")311 flag.IntVar(&m, "m", 0, "for compound and sidestacker, m is the number of makers to stack before placing takers")312 flag.IntVar(&n, "n", 0, "for compound and sidestacker, n is the number of orders to place per epoch (default 3)")313 flag.Parse()314 if programName == "" {315 return errors.New("no program set. use `-p program-name` to set the bot's program")316 }317 // Parse the default log level and create initialize logging.318 logLevel := "info"319 if debug {320 logLevel = "debug"321 }322 if trace {323 logLevel = "trace"324 }325 symbols := strings.Split(market, "_")326 if len(symbols) != 2 {327 return fmt.Errorf("invalid market %q", market)328 }329 baseSymbol = strings.ToLower(symbols[0])330 quoteSymbol = strings.ToLower(symbols[1])331 var found bool332 baseID, found = dex.BipSymbolID(baseSymbol)333 if !found {334 return fmt.Errorf("base asset %q not found", baseSymbol)335 }336 quoteID, found = dex.BipSymbolID(quoteSymbol)337 if !found {338 return fmt.Errorf("quote asset %q not found", quoteSymbol)339 }340 regAsset = baseID341 if registerWithQuote {342 regAsset = quoteID343 }344 ui, err := asset.UnitInfo(baseID)345 if err != nil {346 return fmt.Errorf("cannot get base %q unit info: %v", baseSymbol, err)347 }348 conversionFactors[baseSymbol] = ui.Conventional.ConversionFactor349 ui, err = asset.UnitInfo(quoteID)350 if err != nil {351 return fmt.Errorf("cannot get quote %q unit info: %v", quoteSymbol, err)352 }353 conversionFactors[quoteSymbol] = ui.Conventional.ConversionFactor354 f, err := os.ReadFile(filepath.Join(dextestDir, "dcrdex", "markets.json"))355 if err != nil {356 return fmt.Errorf("error reading simnet dcrdex markets.json file: %v", err)357 }358 var mktsCfg marketsDotJSON359 err = json.Unmarshal(f, &mktsCfg)360 if err != nil {361 return fmt.Errorf("error unmarshaling markets.json: %v", err)362 }363 markets := make([]string, len(mktsCfg.Markets))364 for i, mkt := range mktsCfg.Markets {365 getSymbol := func(name string) (string, error) {366 asset, ok := mktsCfg.Assets[name]367 if !ok {368 return "", fmt.Errorf("config does not have an asset that matches %s", name)369 }370 return strings.ToLower(asset.Symbol), nil371 }372 bs, err := getSymbol(mkt.Base)373 if err != nil {374 return err375 }376 qs, err := getSymbol(mkt.Quote)377 if err != nil {378 return err379 }380 markets[i] = fmt.Sprintf("%s_%s", bs, qs)381 if qs != quoteSymbol || bs != baseSymbol {382 continue383 }384 lotSize = mkt.LotSize385 rateStep = mkt.RateStep386 epochDuration = mkt.Duration387 marketBuyBuffer = mkt.MBBuffer388 break389 }390 // Adjust to be comparable to the dcr_btc market.391 defaultMidGap = defaultBtcPerDcr * float64(rateStep) / 100392 if epochDuration == 0 {393 return fmt.Errorf("failed to find %q market in harness config. Available markets: %s", market, strings.Join(markets, ", "))394 }395 shortSymbol := func(s string) string {396 parts := strings.Split(s, ".")397 return parts[0]398 }399 baseAssetCfg = mktsCfg.Assets[fmt.Sprintf("%s_simnet", strings.ToUpper(shortSymbol(baseSymbol)))]400 quoteAssetCfg = mktsCfg.Assets[fmt.Sprintf("%s_simnet", strings.ToUpper(shortSymbol(quoteSymbol)))]401 if baseAssetCfg == nil || quoteAssetCfg == nil {402 return errors.New("asset configuration missing from markets.json")403 }404 // Load the asset node configs. We'll need the wallet RPC addresses.405 // Note that the RPC address may be modified if toxiproxy is used below.406 alphaCfgBase = loadNodeConfig(baseSymbol, alpha)407 betaCfgBase = loadNodeConfig(baseSymbol, beta)408 alphaCfgQuote = loadNodeConfig(quoteSymbol, alpha)409 betaCfgQuote = loadNodeConfig(quoteSymbol, beta)410 loggerMaker, err = dex.NewLoggerMaker(os.Stdout, logLevel)411 if err != nil {412 return fmt.Errorf("error creating LoggerMaker: %v", err)413 }414 log /* global */ = loggerMaker.NewLogger("LOADBOT", dex.LevelInfo)415 log.Infof("Running program %s", programName)416 getAddress := func(symbol, node string) (string, error) {417 var args []string418 switch symbol {419 case btc, ltc:420 args = []string{"getnewaddress", "''", "bech32"}421 case doge, bch, zec:422 args = []string{"getnewaddress"}423 case dcr:424 args = []string{"getnewaddress", "default", "ignore"}425 case eth, dextt:426 args = []string{"attach", `--exec eth.accounts[1]`}427 default:428 return "", fmt.Errorf("getAddress: unknown symbol %q", symbol)429 }430 res := <-harnessCtl(ctx, symbol, fmt.Sprintf("./%s", node), args...)431 if res.err != nil {432 return "", fmt.Errorf("error getting %s address: %v", symbol, res.err)433 }434 return strings.Trim(res.output, `"`), nil435 }436 if alphaAddrBase, err = getAddress(baseSymbol, alpha); err != nil {437 return err438 }439 if betaAddrBase, err = getAddress(baseSymbol, beta); err != nil {440 return err441 }442 if alphaAddrQuote, err = getAddress(quoteSymbol, alpha); err != nil {443 return err444 }445 if betaAddrQuote, err = getAddress(quoteSymbol, beta); err != nil {446 return err447 }448 unlockWallets := func(symbol string) error {449 switch symbol {450 case btc, ltc, doge, bch:451 <-harnessCtl(ctx, symbol, "./alpha", "walletpassphrase", "abc", "4294967295")452 <-harnessCtl(ctx, symbol, "./beta", "walletpassphrase", "abc", "4294967295")453 case dcr:454 <-harnessCtl(ctx, dcr, "./alpha", "walletpassphrase", "abc", "0")455 <-harnessCtl(ctx, dcr, "./beta", "walletpassphrase", "abc", "0") // creating new accounts requires wallet unlocked456 <-harnessCtl(ctx, dcr, "./beta", "unlockaccount", "default", "abc")457 case eth, zec, dextt:458 // eth unlocking for send, so no need to here. Mining459 // accounts are always unlocked. zec is unlocked already.460 default:461 return fmt.Errorf("unlockWallets: unknown symbol %q", symbol)462 }463 return nil464 }465 // Unlock wallets, since they may have been locked on a previous shutdown.466 if err = unlockWallets(baseSymbol); err != nil {467 return err468 }469 if err = unlockWallets(quoteSymbol); err != nil {470 return err471 }472 // Clean up the directory.473 os.RemoveAll(botDir)474 err = os.MkdirAll(botDir, 0700)475 if err != nil {476 return fmt.Errorf("error creating loadbot directory: %v", err)477 }478 // Run any specified network conditions.479 var toxics toxiproxy.Toxics...

Full Screen

Full Screen

lock_test.go

Source:lock_test.go Github

copy

Full Screen

...98 // Wait until we regain lock99 is = <-hasLockCh100 assert.True(t, is)101 assert.True(t, l.HasLock())102 // Unlock the key103 l.Unlock([]byte("this is a test"))104 printKeys("lock-test")105 // Ensure the key is NOT deleted106 list, _, err := c.KV().List("lock-test", nil)107 require.NoError(t, err)108 var found bool109 for _, i := range list {110 if i.Key == name {111 found = true112 assert.Equal(t, i.Value, []byte("this is a test"))113 }114 }115 assert.True(t, found)116 // Delete the key117 _, err = c.KV().Delete(name, nil)118 require.NoError(t, err)119 })120}121func TestBehaviorDeleteOnUnlock(t *testing.T) {122 logrus.SetLevel(logrus.DebugLevel)123 hasLockCh := make(chan bool, 5)124 defer cleanUp()125 WithToxiProxy(t, func(p *toxiproxy.Proxy, c *api.Client) {126 ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*500)127 defer cancel()128 name := fmt.Sprintf("lock-test-delete-%d", rand.Int())129 l, err := consul.SpawnLock(ctx, &consul.LockConfig{130 Client: c,131 LockOptions: &api.LockOptions{132 SessionOpts: &api.SessionEntry{133 Name: name,134 LockDelay: time.Second * 10,135 // When SessionBehavior is Delete136 Behavior: api.SessionBehaviorDelete,137 TTL: "10s",138 },139 Value: []byte("lock-value"),140 SessionName: name,141 Key: name,142 },143 OnChange: func(hasLock bool) {144 hasLockCh <- hasLock145 },146 })147 require.NoError(t, err)148 require.NotNil(t, l)149 // Should have lock150 require.True(t, l.HasLock())151 select {152 case is := <-hasLockCh:153 assert.True(t, is)154 default:155 }156 // Unlock the key157 l.Unlock(nil)158 printKeys("lock-test")159 // Ensure the key was deleted160 list, _, err := c.KV().List("lock-test", nil)161 require.NoError(t, err)162 var found bool163 for _, i := range list {164 if i.Key == name {165 found = true166 }167 }168 assert.False(t, found)169 })170}171func TestBehaviorDeleteOnDisconnect(t *testing.T) {172 logrus.SetLevel(logrus.DebugLevel)173 defer cleanUp()174 WithToxiProxy(t, func(p *toxiproxy.Proxy, c *api.Client) {175 printKeys("lock-test")176 ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*500)177 defer cancel()178 name := fmt.Sprintf("lock-test-disconnect%d", rand.Int())179 l, err := consul.SpawnLock(ctx, &consul.LockConfig{180 Client: c,181 LockOptions: &api.LockOptions{182 SessionOpts: &api.SessionEntry{183 Name: name,184 // When SessionBehavior is Delete185 Behavior: api.SessionBehaviorDelete,186 TTL: "10s",187 },188 Value: []byte("lock-value"),189 SessionName: name,190 Key: name,191 },192 })193 require.NoError(t, err)194 require.NotNil(t, l)195 // Should have lock196 printKeys("lock-test")197 require.True(t, l.HasLock())198 // Interrupt connectivity to consul199 p.Stop()200 // Wait for the lock file to disappear201 client, err := api.NewClient(api.DefaultConfig())202 testutil.UntilPass(t, 50, time.Second, func(t testutil.TestingT) {203 kv, _, err := client.KV().Get(name, nil)204 assert.NoError(t, err)205 assert.Nil(t, kv)206 })207 // Resume connectivity208 err = p.Start()209 require.NoError(t, err)210 // Wait until we regain lock211 testutil.UntilPass(t, 50, time.Second, func(t testutil.TestingT) {212 assert.True(t, l.HasLock())213 })214 // Unlock the key215 l.Unlock(nil)216 })217}...

Full Screen

Full Screen

proxy.go

Source:proxy.go Github

copy

Full Screen

...30}31func (c *ConnectionList) Lock() {32 c.lock.Lock()33}34func (c *ConnectionList) Unlock() {35 c.lock.Unlock()36}37var ErrProxyAlreadyStarted = errors.New("Proxy already started")38func NewProxy() *Proxy {39 proxy := &Proxy{40 started: make(chan error),41 connections: ConnectionList{list: make(map[string]net.Conn)},42 }43 proxy.Toxics = NewToxicCollection(proxy)44 return proxy45}46func (proxy *Proxy) Start() error {47 proxy.Lock()48 defer proxy.Unlock()49 return start(proxy)50}51func (proxy *Proxy) Update(input *Proxy) error {52 proxy.Lock()53 defer proxy.Unlock()54 if input.Listen != proxy.Listen || input.Upstream != proxy.Upstream {55 stop(proxy)56 proxy.Listen = input.Listen57 proxy.Upstream = input.Upstream58 }59 if input.Enabled != proxy.Enabled {60 if input.Enabled {61 return start(proxy)62 }63 stop(proxy)64 }65 return nil66}67func (proxy *Proxy) Stop() {68 proxy.Lock()69 defer proxy.Unlock()70 stop(proxy)71}72// server runs the Proxy server, accepting new clients and creating Links to73// connect them to upstreams.74func (proxy *Proxy) server() {75 ln, err := net.Listen("tcp", proxy.Listen)76 if err != nil {77 proxy.started <- err78 return79 }80 proxy.Listen = ln.Addr().String()81 proxy.started <- nil82 logrus.WithFields(logrus.Fields{83 "name": proxy.Name,84 "proxy": proxy.Listen,85 "upstream": proxy.Upstream,86 }).Info("Started proxy")87 acceptTomb := tomb.Tomb{}88 defer acceptTomb.Done()89 // This channel is to kill the blocking Accept() call below by closing the90 // net.Listener.91 go func() {92 <-proxy.tomb.Dying()93 // Notify ln.Accept() that the shutdown was safe94 acceptTomb.Killf("Shutting down from stop()")95 // Unblock ln.Accept()96 err := ln.Close()97 if err != nil {98 logrus.WithFields(logrus.Fields{99 "proxy": proxy.Name,100 "listen": proxy.Listen,101 "err": err,102 }).Warn("Attempted to close an already closed proxy server")103 }104 // Wait for the accept loop to finish processing105 acceptTomb.Wait()106 proxy.tomb.Done()107 }()108 for {109 client, err := ln.Accept()110 if err != nil {111 // This is to confirm we're being shut down in a legit way. Unfortunately,112 // Go doesn't export the error when it's closed from Close() so we have to113 // sync up with a channel here.114 //115 // See http://zhen.org/blog/graceful-shutdown-of-go-net-dot-listeners/116 select {117 case <-acceptTomb.Dying():118 default:119 logrus.WithFields(logrus.Fields{120 "proxy": proxy.Name,121 "listen": proxy.Listen,122 "err": err,123 }).Warn("Error while accepting client")124 }125 return126 }127 logrus.WithFields(logrus.Fields{128 "name": proxy.Name,129 "client": client.RemoteAddr(),130 "proxy": proxy.Listen,131 "upstream": proxy.Upstream,132 }).Info("Accepted client")133 upstream, err := net.Dial("tcp", proxy.Upstream)134 if err != nil {135 logrus.WithFields(logrus.Fields{136 "name": proxy.Name,137 "client": client.RemoteAddr(),138 "proxy": proxy.Listen,139 "upstream": proxy.Upstream,140 }).Error("Unable to open connection to upstream")141 client.Close()142 continue143 }144 name := client.RemoteAddr().String()145 proxy.connections.Lock()146 proxy.connections.list[name+"upstream"] = upstream147 proxy.connections.list[name+"downstream"] = client148 proxy.connections.Unlock()149 proxy.Toxics.StartLink(name+"upstream", client, upstream, stream.Upstream)150 proxy.Toxics.StartLink(name+"downstream", upstream, client, stream.Downstream)151 }152}153func (proxy *Proxy) RemoveConnection(name string) {154 proxy.connections.Lock()155 defer proxy.connections.Unlock()156 delete(proxy.connections.list, name)157}158// Starts a proxy, assumes the lock has already been taken159func start(proxy *Proxy) error {160 if proxy.Enabled {161 return ErrProxyAlreadyStarted162 }163 proxy.tomb = tomb.Tomb{} // Reset tomb, from previous starts/stops164 go proxy.server()165 err := <-proxy.started166 // Only enable the proxy if it successfully started167 proxy.Enabled = err == nil168 return err169}170// Stops a proxy, assumes the lock has already been taken171func stop(proxy *Proxy) {172 if !proxy.Enabled {173 return174 }175 proxy.Enabled = false176 proxy.tomb.Killf("Shutting down from stop()")177 proxy.tomb.Wait() // Wait until we stop accepting new connections178 proxy.connections.Lock()179 defer proxy.connections.Unlock()180 for _, conn := range proxy.connections.list {181 conn.Close()182 }183 logrus.WithFields(logrus.Fields{184 "name": proxy.Name,185 "proxy": proxy.Listen,186 "upstream": proxy.Upstream,187 }).Info("Terminated proxy")188}...

Full Screen

Full Screen

Unlock

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 toxiproxyClient, err := toxiproxy.NewClient("localhost:8474")4 if err != nil {5 fmt.Println("Error in connecting to toxiproxy server")6 }7 toxiproxyClient.Disable("redis_slave")8 fmt.Println("Toxiproxy disabled")9}10import (11func main() {12 toxiproxyClient, err := toxiproxy.NewClient("localhost:8474")13 if err != nil {14 fmt.Println("Error in connecting to toxiproxy server")15 }16 toxiproxyClient.Enable("redis_slave")17 fmt.Println("Toxiproxy enabled")18}19import (20func main() {21 toxiproxyClient, err := toxiproxy.NewClient("localhost:8474")22 if err != nil {23 fmt.Println("Error in connecting to toxiproxy server")24 }25 toxiproxyClient.Reset("redis_slave")26 fmt.Println("Toxiproxy reset")27}28import (29func main() {30 toxiproxyClient, err := toxiproxy.NewClient("localhost:8474")31 if err != nil {32 fmt.Println("Error in connecting to toxiproxy server")33 }34 toxiproxyClient.Create(&toxiproxy.Proxy{35 Toxics: toxiproxy.Toxics{},36 ToxicsMap: make(map[string]*toxiproxy.Toxic),37 })38 fmt.Println("Toxiproxy created")39}

Full Screen

Full Screen

Unlock

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 toxiproxyClient := toxiproxy.NewClient("localhost:8474")4 toxiproxyClient.CreateProxy("testProxy", "localhost:8000", "localhost:8001")5 toxiproxyClient.CreateToxic("testProxy", "latency", "downstream", 1, toxiproxy.Attributes{"latency": 1000})6 toxiproxyClient.CreateToxic("testProxy", "latency", "upstream", 1, toxiproxy.Attributes{"latency": 1000})7 toxiproxyClient.CreateToxic("testProxy", "bandwidth", "downstream", 1, toxiproxy.Attributes{"rate": 200000})8 toxiproxyClient.CreateToxic("testProxy", "bandwidth", "upstream", 1, toxiproxy.Attributes{"rate": 200000})9 toxiproxyClient.CreateToxic("testProxy", "slow_close", "downstream", 1, toxiproxy.Attributes{"delay": 1000})10 toxiproxyClient.CreateToxic("testProxy", "slow_close", "upstream", 1, toxiproxy.Attributes{"delay": 1000})11 toxiproxyClient.CreateToxic("testProxy", "timeout", "downstream", 1, toxiproxy.Attributes{"timeout": 1000})12 toxiproxyClient.CreateToxic("testProxy", "timeout", "upstream", 1, toxiproxy.Attributes{"timeout": 1000})13 toxiproxyClient.CreateToxic("testProxy", "slicer", "downstream", 1, toxiproxy.Attributes{"average_size": 100, "size_variation": 10, "delay": 10})14 toxiproxyClient.CreateToxic("testProxy", "slicer", "upstream", 1, toxiproxy.Attributes{"average_size": 100, "size_variation": 10, "delay": 10})15 toxiproxyClient.CreateToxic("testProxy", "limit_data", "downstream", 1, toxiproxy.Attributes

Full Screen

Full Screen

Unlock

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 proxy, err := client.Proxy("redis")7 if err != nil {8 log.Fatal(err)9 }10 toxics, err := proxy.Toxics()11 if err != nil {12 log.Fatal(err)13 }14 for _, toxic := range toxics {15 if toxic.Name == "latency" {16 err = toxic.Delete()17 if err != nil {18 log.Fatal(err)19 }20 }21 }22 toxic := stream.Toxic{23 Attributes: stream.Attributes{24 },25 }26 err = proxy.AddToxic(&toxic)27 if err != nil {28 log.Fatal(err)29 }30 time.Sleep(10 * time.Second)31 err = toxic.Delete()32 if err != nil {33 log.Fatal(err)34 }35}

Full Screen

Full Screen

Unlock

Using AI Code Generation

copy

Full Screen

1toxiproxy.Unlock()2toxiproxy.Lock()3toxiproxy.IsLocked()4toxiproxy.Enable()5toxiproxy.Disable()6toxiproxy.IsEnabled()7toxiproxy.Delete()8toxiproxy.Reset()9toxiproxy.All()10toxiproxy.Create()11toxiproxy.Update()12toxiproxy.Get()13toxiproxy.Toxics()14toxiproxy.Toxic()15toxiproxy.CreateToxic()16toxiproxy.UpdateToxic()

Full Screen

Full Screen

Unlock

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 proxy, err := client.Proxy("redis")7 if err != nil {8 fmt.Println(err)9 }10 toxic, err := proxy.CreateToxic("latency", "downstream", "latency", 1, toxiproxy.Attributes{"latency": 1000, "jitter": 0})11 if err != nil {12 fmt.Println(err)13 }14 time.Sleep(2 * time.Second)15 toxic.Disable()16 time.Sleep(2 * time.Second)17 toxic.Enable()18 time.Sleep(2 * time.Second)19 toxic.Delete()20}

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