How to use parseAssertions method of venom Package

Best Venom code snippet using venom.parseAssertions

assertion.go

Source:assertion.go Github

copy

Full Screen

...74 Func assertions.AssertFunc75 Args []interface{}76 Required bool77}78func parseAssertions(ctx context.Context, s string, input interface{}) (*assertion, error) {79 dump, err := Dump(input)80 if err != nil {81 return nil, errors.New("assertion syntax error")82 }83 assert := splitAssertion(s)84 if len(assert) < 2 {85 return nil, errors.New("assertion syntax error")86 }87 actual := dump[assert[0]]88 // "Must" assertions use same tests as "Should" ones, only the flag changes89 required := false90 if strings.HasPrefix(assert[1], "Must") {91 required = true92 assert[1] = strings.Replace(assert[1], "Must", "Should", 1)93 }94 f, ok := assertions.Get(assert[1])95 if !ok {96 return nil, errors.New("assertion not supported")97 }98 args := make([]interface{}, len(assert[2:]))99 for i, v := range assert[2:] {100 var err error101 args[i], err = stringToType(v, actual)102 if err != nil {103 return nil, fmt.Errorf("mismatched type between '%v' and '%v': %v", assert[0], v, err)104 }105 }106 return &assertion{107 Actual: actual,108 Func: f,109 Args: args,110 Required: required,111 }, nil112}113// check selects the correct assertion function to call depending on typing provided by user114func check(ctx context.Context, tc TestCase, stepNumber int, rangedIndex int, assertion Assertion, r interface{}) *Failure {115 var errs *Failure116 switch t := assertion.(type) {117 case string:118 errs = checkString(ctx, tc, stepNumber, rangedIndex, assertion.(string), r)119 case map[string]interface{}:120 errs = checkBranch(ctx, tc, stepNumber, rangedIndex, assertion.(map[string]interface{}), r)121 default:122 errs = newFailure(ctx, tc, stepNumber, rangedIndex, "", fmt.Errorf("unsupported assertion format: %v", t))123 }124 return errs125}126// checkString evaluate a complex assertion containing logical operators127// it recursively calls checkAssertion for each operand128func checkBranch(ctx context.Context, tc TestCase, stepNumber int, rangedIndex int, branch map[string]interface{}, r interface{}) *Failure {129 // Extract logical operator130 if len(branch) != 1 {131 return newFailure(ctx, tc, stepNumber, rangedIndex, "", fmt.Errorf("expected exactly 1 logical operator but %d were provided", len(branch)))132 }133 var operator string134 for k := range branch {135 operator = k136 }137 // Extract logical operands138 var operands []interface{}139 switch t := branch[operator].(type) {140 case []interface{}:141 operands = branch[operator].([]interface{})142 default:143 return newFailure(ctx, tc, stepNumber, rangedIndex, "", fmt.Errorf("expected %s operands to be an []interface{}, got %v", operator, t))144 }145 if len(operands) == 0 {146 return nil147 }148 // Evaluate assertions (operands)149 var results []string150 assertionsCount := len(operands)151 assertionsSuccess := 0152 for _, assertion := range operands {153 errs := check(ctx, tc, stepNumber, rangedIndex, assertion, r)154 if errs != nil {155 results = append(results, fmt.Sprintf(" - fail: %s", assertion))156 }157 if errs == nil {158 assertionsSuccess++159 results = append(results, fmt.Sprintf(" - pass: %s", assertion))160 }161 }162 // Evaluate operator behaviour163 var err error164 switch operator {165 case "and":166 if assertionsSuccess != assertionsCount {167 err = fmt.Errorf("%d/%d assertions succeeded:\n%s\n", assertionsSuccess, assertionsCount, strings.Join(results, "\n"))168 }169 case "or":170 if assertionsSuccess == 0 {171 err = fmt.Errorf("no assertions succeeded:\n%s\n", strings.Join(results, "\n"))172 }173 case "xor":174 if assertionsSuccess == 0 {175 err = fmt.Errorf("no assertions succeeded:\n%s\n", strings.Join(results, "\n"))176 }177 if assertionsSuccess > 1 {178 err = fmt.Errorf("multiple assertions succeeded but expected only one to suceed:\n%s\n", strings.Join(results, "\n"))179 }180 case "not":181 if assertionsSuccess > 0 {182 err = fmt.Errorf("some assertions succeeded but expected none to suceed:\n%s\n", strings.Join(results, "\n"))183 }184 default:185 return newFailure(ctx, tc, stepNumber, rangedIndex, "", fmt.Errorf("unsupported assertion operator %s", operator))186 }187 if err != nil {188 return newFailure(ctx, tc, stepNumber, rangedIndex, "", err)189 }190 return nil191}192// checkString evaluate a single string assertion193func checkString(ctx context.Context, tc TestCase, stepNumber int, rangedIndex int, assertion string, r interface{}) *Failure {194 assert, err := parseAssertions(context.Background(), assertion, r)195 if err != nil {196 return newFailure(ctx, tc, stepNumber, rangedIndex, assertion, err)197 }198 if err := assert.Func(assert.Actual, assert.Args...); err != nil {199 failure := newFailure(ctx, tc, stepNumber, rangedIndex, assertion, err)200 failure.AssertionRequired = assert.Required201 return failure202 }203 return nil204}205// splitAssertion splits the assertion string a, with support206// for quoted arguments.207func splitAssertion(a string) []string {208 lastQuote := rune(0)209 f := func(c rune) bool {210 switch {211 case c == lastQuote:212 lastQuote = rune(0)213 return false214 case lastQuote != rune(0):215 return false216 case unicode.In(c, unicode.Quotation_Mark):217 lastQuote = c218 return false219 default:220 return unicode.IsSpace(c)221 }222 }223 m := strings.FieldsFunc(a, f)224 for i, e := range m {225 first, _ := utf8.DecodeRuneInString(e)226 last, _ := utf8.DecodeLastRuneInString(e)227 if unicode.In(first, unicode.Quotation_Mark) && first == last {228 m[i] = string([]rune(e)[1 : utf8.RuneCountInString(e)-1])229 }230 }231 return m232}233func stringToType(val string, valType interface{}) (interface{}, error) {234 switch valType.(type) {235 case bool:236 return strconv.ParseBool(val)237 case string:238 return val, nil239 case int:240 return strconv.Atoi(val)241 case int8:242 return strconv.ParseInt(val, 10, 8)243 case int16:244 return strconv.ParseInt(val, 10, 16)245 case int32:246 return strconv.ParseInt(val, 10, 32)247 case int64:248 return strconv.ParseInt(val, 10, 64)249 case uint:250 newVal, err := strconv.Atoi(val)251 return uint(newVal), err252 case uint8:253 return strconv.ParseUint(val, 10, 8)254 case uint16:255 return strconv.ParseUint(val, 10, 16)256 case uint32:257 return strconv.ParseUint(val, 10, 32)258 case uint64:259 return strconv.ParseUint(val, 10, 64)260 case float32:261 iVal, err := strconv.ParseFloat(val, 32)262 return float32(iVal), err263 case float64:264 iVal, err := strconv.ParseFloat(val, 64)265 return iVal, err266 case time.Time:267 return time.Parse(time.RFC3339, val)268 case time.Duration:269 return time.ParseDuration(val)270 }271 return val, nil272}273func findLineNumber(filename, testcase string, stepNumber int, assertion string, infoNumber int) int {274 countLine := 0275 file, err := os.Open(filename)276 if err != nil {277 return countLine278 }279 defer file.Close()280 lineFound := false281 testcaseFound := false282 commentBlock := false283 countStep := 0284 countInfo := 0285 scanner := bufio.NewScanner(file)286 for scanner.Scan() {287 countLine++288 line := strings.Trim(scanner.Text(), " ")289 if strings.HasPrefix(line, "/*") {290 commentBlock = true291 continue292 }293 if strings.HasPrefix(line, "*/") {294 commentBlock = false295 continue296 }297 if strings.HasPrefix(line, "#") || strings.HasPrefix(line, "//") || commentBlock {298 continue299 }300 if !testcaseFound && strings.Contains(line, testcase) {301 testcaseFound = true302 continue303 }304 if testcaseFound && countStep <= stepNumber && (strings.Contains(line, "type") || strings.Contains(line, "script")) {305 countStep++306 continue307 }308 if testcaseFound && countStep > stepNumber {309 if strings.Contains(line, assertion) {310 lineFound = true311 break312 } else if strings.Contains(strings.ReplaceAll(line, " ", ""), "info:") {313 countInfo++314 if infoNumber == countInfo {315 lineFound = true316 break317 }318 }319 }320 }321 if err := scanner.Err(); err != nil {322 return countLine323 }324 if !lineFound {325 return 0326 }327 return countLine328}329// This evaluates a string of assertions with a given vars scope, and returns a slice of failures (i.e. empty slice = all pass)330func testConditionalStatement(ctx context.Context, tc *TestCase, assertions []string, vars H, text string) ([]string, error) {331 var failures []string332 for _, assertion := range assertions {333 Debug(ctx, "evaluating %s", assertion)334 assert, err := parseAssertions(ctx, assertion, vars)335 if err != nil {336 Error(ctx, "unable to parse assertion: %v", err)337 return failures, err338 }339 if err := assert.Func(assert.Actual, assert.Args...); err != nil {340 s := fmt.Sprintf(text, tc.originalName, err)341 failures = append(failures, s)342 }343 }344 return failures, nil345}...

Full Screen

Full Screen

parseAssertions

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 v := venom.New()4 v.RegisterExecutor(ssh.Name, ssh.New())5 v.RegisterExecutor(http.Name, http.New())6 v.RegisterExecutor(imap.Name, imap.New())7 v.RegisterExecutor(tcp.Name, tcp.New())8 v.RegisterExecutor(udp.Name, udp.New())9 v.RegisterExecutor(golang.Name, golang.New())10 v.RegisterExecutor(vars.Name, vars.New())11 v.RegisterExecutor(web.Name, web.New())12 v.RegisterExecutor(executors.Name, executors.New())13 fmt.Println(v.ParseAssertions(`{14 {15 "result": {16 },17 "expected": {18 },19 }20 }`))21}

Full Screen

Full Screen

parseAssertions

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 venom := venom.New()4 venom.ParseAssertions("assertions1.yml")5 fmt.Println(venom.Assertions)6}

Full Screen

Full Screen

parseAssertions

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 t.Vars = map[string]string{"a": "b"}4 t.Steps = []venom.TestStep{5 {6 map[string]string{"a": "b"},7 []venom.TestStep{{"step2", "action", "type", "input", map[string]string{"a": "b"

Full Screen

Full Screen

parseAssertions

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 venom.ParseAssertions("1.yaml")4 fmt.Println(venom)5}6import (7func main() {8 venom.ParseAssertions("2.yaml")9 fmt.Println(venom)10}11import (12func main() {13 venom.ParseAssertions("3.yaml")14 fmt.Println(venom)15}16import (17func main() {18 venom.ParseAssertions("4.yaml")19 fmt.Println(venom)20}21import (22func main() {23 venom.ParseAssertions("5.yaml")24 fmt.Println(venom)25}26import (27func main() {28 venom.ParseAssertions("6.yaml")29 fmt.Println(venom)30}31import (32func main() {33 venom.ParseAssertions("7.yaml")34 fmt.Println(venom)35}36import (37func main() {38 venom.ParseAssertions("8.yaml")39 fmt.Println(venom)40}41import (

Full Screen

Full Screen

parseAssertions

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 venomInstance.Init()4 assertions = venom.Assertions{5 {6 },7 }8 err = venomInstance.ParseAssertions(&test, assertions)9 if err != nil {10 fmt.Println(err)11 }12}

Full Screen

Full Screen

parseAssertions

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var folderPath = flag.String("path", "", "path of the folder containing the test cases")4 flag.Parse()5 if *folderPath == "" {6 }7 if !isDirectory(*folderPath) {8 fmt.Println("error: path provided is not a directory")9 os.Exit(1)10 }11 v := venom.NewVenom()12 err := v.ParseAssertions(*folderPath)13 if err != nil {14 fmt.Println(err)15 os.Exit(1)16 }17 os.Exit(0)18}19func isDirectory(path string) bool {20 fileInfo, err := os.Stat(path)21 if err != nil {22 }23 return fileInfo.IsDir()24}25func getFilesInDirectory(path string) ([]string, error) {26 err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {27 if info.IsDir() {28 }29 if filepath.Ext(path) != ".yaml" {30 }31 files = append(files, path)32 })33 if err != nil {34 }35}

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 Venom 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