Best Venom code snippet using venom.Retry
venom.go
Source:venom.go
1package venom2import (3 "bytes"4 "context"5 "encoding/json"6 "fmt"7 "io"8 "os"9 "path"10 "path/filepath"11 "plugin"12 "sort"13 "strings"14 "github.com/confluentinc/bincover"15 "github.com/fatih/color"16 "github.com/ovh/cds/sdk/interpolate"17 "github.com/pkg/errors"18 "github.com/rockbears/yaml"19 log "github.com/sirupsen/logrus"20 "github.com/spf13/cast"21)22var (23 //Version is set with -ldflags "-X github.com/ovh/venom/venom.Version=$(VERSION)"24 Version = "snapshot"25 IsTest = ""26)27func OSExit(exitCode int) {28 if IsTest != "" {29 bincover.ExitCode = exitCode30 } else {31 os.Exit(exitCode)32 }33}34// ContextKey can be added in context to store contextual infos. Also used by logger.35type ContextKey string36// New instanciates a new venom on venom run cmd37func New() *Venom {38 v := &Venom{39 LogOutput: os.Stdout,40 PrintFunc: fmt.Printf,41 executorsBuiltin: map[string]Executor{},42 executorsPlugin: map[string]Executor{},43 executorsUser: map[string]Executor{},44 executorFileCache: map[string][]byte{},45 variables: map[string]interface{}{},46 OutputFormat: "xml",47 }48 return v49}50type Venom struct {51 LogOutput io.Writer52 PrintFunc func(format string, a ...interface{}) (n int, err error)53 executorsBuiltin map[string]Executor54 executorsPlugin map[string]Executor55 executorsUser map[string]Executor56 executorFileCache map[string][]byte57 Tests Tests58 variables H59 LibDir string60 OutputFormat string61 OutputDir string62 StopOnFailure bool63 HtmlReport bool64 Verbose int65}66var trace = color.New(color.Attribute(90)).SprintFunc()67func (v *Venom) Print(format string, a ...interface{}) {68 v.PrintFunc(format, a...) // nolint69}70func (v *Venom) Println(format string, a ...interface{}) {71 v.PrintFunc(format+"\n", a...) // nolint72}73func (v *Venom) PrintlnTrace(s string) {74 v.PrintlnIndentedTrace(s, "")75}76func (v *Venom) PrintlnIndentedTrace(s string, indent string) {77 v.Println("\t %s%s %s", indent, trace("[trac]"), trace(s)) // nolint78}79func (v *Venom) AddVariables(variables map[string]interface{}) {80 for k, variable := range variables {81 v.variables[k] = variable82 }83}84// RegisterExecutorBuiltin register builtin executors85func (v *Venom) RegisterExecutorBuiltin(name string, e Executor) {86 v.executorsBuiltin[name] = e87}88// RegisterExecutorPlugin register plugin executors89func (v *Venom) RegisterExecutorPlugin(name string, e Executor) {90 v.executorsPlugin[name] = e91}92// RegisterExecutorUser register User sxecutors93func (v *Venom) RegisterExecutorUser(name string, e Executor) {94 v.executorsUser[name] = e95}96// GetExecutorRunner initializes a test by name97// no type -> exec is default98func (v *Venom) GetExecutorRunner(ctx context.Context, ts TestStep, h H) (context.Context, ExecutorRunner, error) {99 name, _ := ts.StringValue("type")100 script, _ := ts.StringValue("script")101 if name == "" && script != "" {102 name = "exec"103 }104 retry, err := ts.IntValue("retry")105 if err != nil {106 return nil, nil, err107 }108 retryIf, err := ts.StringSliceValue("retry_if")109 if err != nil {110 return nil, nil, err111 }112 delay, err := ts.IntValue("delay")113 if err != nil {114 return nil, nil, err115 }116 timeout, err := ts.IntValue("timeout")117 if err != nil {118 return nil, nil, err119 }120 info, _ := ts.StringSliceValue("info")121 vars, err := DumpStringPreserveCase(h)122 if err != nil {123 return ctx, nil, err124 }125 allKeys := []string{}126 for k, v := range vars {127 ctx = context.WithValue(ctx, ContextKey("var."+k), v)128 allKeys = append(allKeys, k)129 }130 ctx = context.WithValue(ctx, ContextKey("vars"), allKeys)131 if name == "" {132 return ctx, newExecutorRunner(nil, name, "builtin", retry, retryIf, delay, timeout, info), nil133 }134 if ex, ok := v.executorsBuiltin[name]; ok {135 return ctx, newExecutorRunner(ex, name, "builtin", retry, retryIf, delay, timeout, info), nil136 }137 if err := v.registerUserExecutors(ctx, name, vars); err != nil {138 Debug(ctx, "executor %q is not implemented as user executor - err:%v", name, err)139 }140 if ex, ok := v.executorsUser[name]; ok {141 return ctx, newExecutorRunner(ex, name, "user", retry, retryIf, delay, timeout, info), nil142 }143 if err := v.registerPlugin(ctx, name, vars); err != nil {144 Debug(ctx, "executor %q is not implemented as plugin - err:%v", name, err)145 }146 // then add the executor plugin to the map to not have to load it on each step147 if ex, ok := v.executorsUser[name]; ok {148 return ctx, newExecutorRunner(ex, name, "plugin", retry, retryIf, delay, timeout, info), nil149 }150 return ctx, nil, fmt.Errorf("executor %q is not implemented", name)151}152func (v *Venom) getUserExecutorFilesPath(vars map[string]string) (filePaths []string, err error) {153 var libpaths []string154 if v.LibDir != "" {155 p := strings.Split(v.LibDir, string(os.PathListSeparator))156 libpaths = append(libpaths, p...)157 }158 libpaths = append(libpaths, path.Join(vars["venom.testsuite.workdir"], "lib"))159 for _, p := range libpaths {160 p = strings.TrimSpace(p)161 err = filepath.Walk(p, func(fp string, f os.FileInfo, err error) error {162 switch ext := filepath.Ext(fp); ext {163 case ".yml", ".yaml":164 filePaths = append(filePaths, fp)165 }166 return nil167 })168 if err != nil {169 return nil, err170 }171 }172 sort.Strings(filePaths)173 if len(filePaths) == 0 {174 return nil, fmt.Errorf("no user executor yml file selected")175 }176 return filePaths, nil177}178func (v *Venom) registerUserExecutors(ctx context.Context, name string, vars map[string]string) error {179 executorsPath, err := v.getUserExecutorFilesPath(vars)180 if err != nil {181 return err182 }183 for _, f := range executorsPath {184 log.Info("Reading ", f)185 btes, ok := v.executorFileCache[f]186 if !ok {187 btes, err = os.ReadFile(f)188 if err != nil {189 return errors.Wrapf(err, "unable to read file %q", f)190 }191 v.executorFileCache[f] = btes192 }193 varsFromInput, err := getUserExecutorInputYML(ctx, btes)194 if err != nil {195 return err196 }197 // varsFromInput contains the default vars from the executor198 var varsFromInputMap map[string]string199 if len(varsFromInput) > 0 {200 varsFromInputMap, err = DumpStringPreserveCase(varsFromInput)201 if err != nil {202 return errors.Wrapf(err, "unable to parse variables")203 }204 }205 varsComputed := map[string]string{}206 for k, v := range vars {207 varsComputed[k] = v208 }209 for k, v := range varsFromInputMap {210 // we only take vars from varsFromInputMap if it's not already exist in vars from teststep vars211 if _, ok := vars[k]; !ok {212 varsComputed[k] = v213 }214 }215 content, err := interpolate.Do(string(btes), varsComputed)216 if err != nil {217 return err218 }219 ux := UserExecutor{Filename: f}220 if err := yaml.Unmarshal([]byte(content), &ux); err != nil {221 return errors.Wrapf(err, "unable to parse file %q with content %v", f, content)222 }223 log.Debugf("User executor %q revolved with content %v", f, content)224 for k, vr := range varsComputed {225 ux.Input.Add(k, vr)226 }227 v.RegisterExecutorUser(ux.Executor, ux)228 }229 return nil230}231func (v *Venom) registerPlugin(ctx context.Context, name string, vars map[string]string) error {232 workdir := vars["venom.testsuite.workdir"]233 // try to load from testsuite path234 p, err := plugin.Open(path.Join(workdir, "lib", name+".so"))235 if err != nil {236 // try to load from venom binary path237 p, err = plugin.Open(path.Join("lib", name+".so"))238 if err != nil {239 return fmt.Errorf("unable to load plugin %q.so", name)240 }241 }242 symbolExecutor, err := p.Lookup("Plugin")243 if err != nil {244 return err245 }246 executor := symbolExecutor.(Executor)247 v.RegisterExecutorPlugin(name, executor)248 return nil249}250func VarFromCtx(ctx context.Context, varname string) interface{} {251 i := ctx.Value(ContextKey("var." + varname))252 return i253}254func StringVarFromCtx(ctx context.Context, varname string) string {255 i := ctx.Value(ContextKey("var." + varname))256 return cast.ToString(i)257}258func StringSliceVarFromCtx(ctx context.Context, varname string) []string {259 i := ctx.Value(ContextKey("var." + varname))260 return cast.ToStringSlice(i)261}262func IntVarFromCtx(ctx context.Context, varname string) int {263 i := ctx.Value(ContextKey("var." + varname))264 return cast.ToInt(i)265}266func BoolVarFromCtx(ctx context.Context, varname string) bool {267 i := ctx.Value(ContextKey("var." + varname))268 return cast.ToBool(i)269}270func StringMapInterfaceVarFromCtx(ctx context.Context, varname string) map[string]interface{} {271 i := ctx.Value(ContextKey("var." + varname))272 return cast.ToStringMap(i)273}274func StringMapStringVarFromCtx(ctx context.Context, varname string) map[string]string {275 i := ctx.Value(ContextKey("var." + varname))276 return cast.ToStringMapString(i)277}278func AllVarsFromCtx(ctx context.Context) H {279 i := ctx.Value(ContextKey("vars"))280 allKeys := cast.ToStringSlice(i)281 res := H{}282 for _, k := range allKeys {283 res.Add(k, VarFromCtx(ctx, k))284 }285 return res286}287func JSONUnmarshal(btes []byte, i interface{}) error {288 var d = json.NewDecoder(bytes.NewReader(btes))289 d.UseNumber()290 return d.Decode(i)291}...
types_executor.go
Source:types_executor.go
...20 executorWithDefaultAssertions21 executorWithZeroValueResult22 ExecutorWithSetup23 Name() string24 Retry() int25 RetryIf() []string26 Delay() int27 Timeout() int28 Info() []string29 Type() string30 GetExecutor() Executor31}32var _ Executor = new(executor)33// ExecutorWrap contains an executor implementation and some attributes34type executor struct {35 Executor36 name string37 retry int // nb retry a test case if it is in failure.38 retryIf []string // retry conditions to check before performing any retries39 delay int // delay between two retries40 timeout int // timeout on executor41 info []string // info to display after the run and before the assertion42 stype string // builtin, plugin, user43}44func (e executor) Name() string {45 return e.name46}47func (e executor) Type() string {48 return e.stype49}50func (e executor) Retry() int {51 return e.retry52}53func (e executor) RetryIf() []string {54 return e.retryIf55}56func (e executor) Delay() int {57 return e.delay58}59func (e executor) Timeout() int {60 return e.timeout61}62func (e executor) Info() []string {63 return e.info64}65func (e executor) GetExecutor() Executor {66 return e.Executor67}...
process_teststep.go
Source:process_teststep.go
...19 ctx = context.WithValue(ctx, ContextKey("executor"), e.Name())20 var assertRes AssertionsApplied21 var retry int22 var result interface{}23 for retry = 0; retry <= e.Retry() && !assertRes.OK; retry++ {24 if retry > 1 && !assertRes.OK {25 Debug(ctx, "Sleep %d, it's %d attempt", e.Delay(), retry)26 time.Sleep(time.Duration(e.Delay()) * time.Second)27 }28 var err error29 result, err = v.runTestStepExecutor(ctx, e, tc, tsResult, step)30 if err != nil {31 // we save the failure only if it's the last attempt32 if retry == e.Retry() {33 failure := newFailure(ctx, *tc, stepNumber, rangedIndex, "", err)34 tsResult.appendFailure(*failure)35 }36 continue37 }38 Debug(ctx, "result of runTestStepExecutor: %+v", result)39 mapResult := GetExecutorResult(result)40 mapResultString, _ := DumpString(result)41 if v.Verbose >= 2 {42 fdump := dumpFile{43 Result: result,44 TestStep: step,45 Variables: AllVarsFromCtx(ctx),46 }47 output, err := json.MarshalIndent(fdump, "", " ")48 if err != nil {49 Error(ctx, "unable to marshal result: %v", err)50 }51 oDir := v.OutputDir52 if oDir == "" {53 oDir = "."54 }55 filename := path.Join(oDir, fmt.Sprintf("%s.%s.step.%d.%d.dump.json", slug.Make(StringVarFromCtx(ctx, "venom.testsuite.shortName")), slug.Make(tc.Name), stepNumber, rangedIndex))56 if err := os.WriteFile(filename, []byte(output), 0644); err != nil {57 return fmt.Errorf("Error while creating file %s: %v", filename, err)58 }59 tc.computedVerbose = append(tc.computedVerbose, fmt.Sprintf("writing %s", filename))60 }61 for ninfo, i := range e.Info() {62 info, err := interpolate.Do(i, mapResultString)63 if err != nil {64 Error(ctx, "unable to parse %q: %v", i, err)65 continue66 }67 if info == "" {68 continue69 }70 filename := StringVarFromCtx(ctx, "venom.testsuite.filename")71 lineNumber := findLineNumber(filename, tc.originalName, stepNumber, i, ninfo+1)72 if lineNumber > 0 {73 info += fmt.Sprintf(" (%s:%d)", filename, lineNumber)74 } else if tc.IsExecutor {75 filename = StringVarFromCtx(ctx, "venom.executor.filename")76 originalName := StringVarFromCtx(ctx, "venom.executor.name")77 lineNumber = findLineNumber(filename, originalName, stepNumber, i, ninfo+1)78 if lineNumber > 0 {79 info += fmt.Sprintf(" (%s:%d)", filename, lineNumber)80 }81 }82 Info(ctx, info)83 tc.computedInfo = append(tc.computedInfo, info)84 tsResult.ComputedInfo = append(tsResult.ComputedInfo, info)85 }86 if result == nil {87 Debug(ctx, "empty testcase, applying assertions on variables: %v", AllVarsFromCtx(ctx))88 assertRes = applyAssertions(ctx, AllVarsFromCtx(ctx), *tc, stepNumber, rangedIndex, step, nil)89 } else {90 if h, ok := e.(executorWithDefaultAssertions); ok {91 assertRes = applyAssertions(ctx, result, *tc, stepNumber, rangedIndex, step, h.GetDefaultAssertions())92 } else {93 assertRes = applyAssertions(ctx, result, *tc, stepNumber, rangedIndex, step, nil)94 }95 }96 tsResult.AssertionsApplied = assertRes97 tc.computedVars.AddAll(H(mapResult))98 if assertRes.OK {99 break100 }101 failures, err := testConditionalStatement(ctx, tc, e.RetryIf(), tc.computedVars, "")102 if err != nil {103 tsResult.appendError(fmt.Errorf("Error while evaluating retry condition: %v", err))104 break105 }106 if len(failures) > 0 {107 failure := newFailure(ctx, *tc, stepNumber, rangedIndex, "", fmt.Errorf("retry conditions not fulfilled, skipping %d remaining retries", e.Retry()-retry))108 tsResult.Errors = append(tsResult.Errors, *failure)109 break110 }111 }112 if retry > 1 && len(assertRes.errors) > 0 {113 tsResult.appendFailure(Failure{Value: fmt.Sprintf("It's a failure after %d attempts", retry)})114 } else if len(assertRes.errors) > 0 {115 tsResult.appendFailure(assertRes.errors...)116 }117 tsResult.Systemerr += assertRes.systemerr + "\n"118 tsResult.Systemout += assertRes.systemout + "\n"119 return result120}121func (v *Venom) runTestStepExecutor(ctx context.Context, e ExecutorRunner, tc *TestCase, ts *TestStepResult, step TestStep) (interface{}, error) {...
Retry
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Hello, World!")4}5import "fmt"6func main() {7 fmt.Println("Hello, World!")8}9import "fmt"10func main() {11 fmt.Println("Hello, World!")12}13import "fmt"14func main() {15 fmt.Println("Hello, World!")16}17import "fmt"18func main() {19 fmt.Println("Hello, World!")20}21import "fmt"22func main() {23 fmt.Println("Hello, World!")24}25import "fmt"26func main() {27 fmt.Println("Hello, World!")28}29import "fmt"30func main() {31 fmt.Println("Hello, World!")32}33import "fmt"34func main() {35 fmt.Println("Hello, World!")36}37import "fmt"38func main() {39 fmt.Println("Hello, World!")40}41import "fmt"42func main() {43 fmt.Println("Hello, World!")44}45import "fmt"46func main() {47 fmt.Println("Hello, World!")48}49import "fmt"50func main() {51 fmt.Println("Hello, World!")52}53import "fmt"54func main() {55 fmt.Println("Hello,
Retry
Using AI Code Generation
1import (2func main() {3 vektra.Retry(func() error {4 fmt.Println("Hello World")5 return errors.New("Error")6 }, 5, time.Second)7}8import (9func main() {10 vektra.Retry(func() error {11 fmt.Println("Hello World")12 return errors.New("Error")13 }, 5, time.Second)14}15import (16func main() {17 vektra.Retry(func() error {18 fmt.Println("Hello World")19 return errors.New("Error")20 }, 5, time.Second)21}22import (23func main() {24 vektra.Retry(func() error {25 fmt.Println("Hello World")26 return errors.New("Error")27 }, 5, time.Second)28}29import (30func main() {31 vektra.Retry(func() error {32 fmt.Println("Hello World")33 return errors.New("Error")34 }, 5, time.Second)35}36import (
Retry
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, World!")4 venom.Retry(3)5}6import (7func main() {8 fmt.Println("Hello, World!")9 venom.Retry(3)10}11import (12func main() {13 fmt.Println("Hello, World!")14 venom.Retry(3)15}16import (17func main() {18 fmt.Println("Hello, World!")19 venom.Retry(3)20}21import (22func main() {23 fmt.Println("Hello, World!")24 venom.Retry(3)25}26import (27func main() {28 fmt.Println("Hello, World!")29 venom.Retry(3)30}31import (32func main() {33 fmt.Println("Hello, World!")34 venom.Retry(3)35}36import (37func main() {38 fmt.Println("Hello, World!")39 venom.Retry(3)40}41import (42func main() {43 fmt.Println("Hello, World!")44 venom.Retry(3)45}46import (47func main() {48 fmt.Println("Hello, World!")49 venom.Retry(3)50}
Retry
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 venom := &Venom{}5 venom.Retry(10, 1*time.Second, func() error {6 fmt.Println("Hello, world!")7 })8}9import (10func main() {11 fmt.Println("Hello, playground")12 venom := &Venom{}13 venom.Retry(10, 1*time.Second, func() error {14 fmt.Println("Hello, world!")15 return fmt.Errorf("Error")16 })17}
Retry
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, world.")4 v := venom.NewVenom()5 v.Retry(5, 2, func() error {6 return fmt.Errorf("Test")7 })8}
Retry
Using AI Code Generation
1import (2func main() {3 venom := &fixtures.Venom{}4 err := venom.Retry(3, 1, func() error {5 })6 if err != nil {7 fmt.Println("Error")8 }9}10import (11func main() {12 venom := &fixtures.Venom{}13 err := venom.Retry(3, 1, func() error {14 })15 if err != nil {16 fmt.Println("Error")17 }18}19import (20func main() {21 venom := &fixtures.Venom{}22 err := venom.Retry(3, 1, func() error {23 })24 if err != nil {25 fmt.Println("Error")26 }27}28import (29func main() {30 venom := &fixtures.Venom{}31 err := venom.Retry(3, 1, func() error {32 })33 if err != nil {34 fmt.Println("Error")35 }36}37import (38func main() {39 venom := &fixtures.Venom{}40 err := venom.Retry(3, 1, func() error {41 })42 if err != nil {43 fmt.Println("Error")44 }45}46import (47func main() {48 venom := &fixtures.Venom{}49 err := venom.Retry(3, 1, func() error {
Retry
Using AI Code Generation
1import "fmt"2func main() {3 venom.Retry()4 fmt.Println("Retry method of Venom class called")5}6import "fmt"7type Venom struct {}8func (venom Venom) Retry() {9 fmt.Println("Retry method of Venom class called")10}11import "fmt"12type Venom struct {}13func (venom Venom) Retry() {14 fmt.Println("Retry method of Venom class called")15}16import "fmt"17type Venom struct {}18func (venom Venom) Retry() {19 fmt.Println("Retry method of Venom class called")20}21import "fmt"22type Venom struct {}23func (venom Venom) Retry() {24 fmt.Println("Retry method of Venom class called")25}26import "fmt"27type Venom struct {}28func (venom Venom) Retry() {29 fmt.Println("Retry method of Venom class called")30}31import "fmt"32type Venom struct {}33func (venom Venom) Retry() {34 fmt.Println("Retry method of Venom class called")35}36import "fmt"37type Venom struct {}38func (venom Venom) Retry() {39 fmt.Println("Retry method of Venom class called")40}41import "fmt"42type Venom struct {}43func (venom Venom) Retry() {44 fmt.Println("Retry method of Venom class called")45}46import "fmt"47type Venom struct {}48func (venom Venom) Retry() {49 fmt.Println("Retry method of Venom class called")50}51import "fmt"52type Venom struct {}53func (venom Venom) Retry() {54 fmt.Println("Retry method of Venom class called")55}
Retry
Using AI Code Generation
1import "fmt"2import "github.com/venom"3func main() {4 v.Retry(5, 1000, func() bool {5 fmt.Println("Hello World!")6 })7}8import "fmt"9import "github.com/venom"10func main() {11 v.Retry(5, 1000, func() bool {12 fmt.Println("Hello World!")13 })14}15import "fmt"16import "github.com/venom"17func main() {18 v.Retry(5, 1000, func() bool {19 fmt.Println("Hello World!")20 })21}22import "fmt"23import "github.com/venom"24func main() {25 v.Retry(5, 1000, func() bool {26 fmt.Println("Hello World!")27 })28}29import "fmt"30import "github.com/venom"31func main() {32 v.Retry(5, 1000, func() bool {33 fmt.Println("Hello World!")34 })35}36import "fmt"37import "github.com/venom"38func main() {39 v.Retry(5, 1000, func() bool {40 fmt.Println("Hello World!")41 })42}43import "fmt"44import "github.com/venom"45func main() {46 v.Retry(5, 1000, func() bool {47 fmt.Println("Hello World!")48 })49}
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!!