How to use traverseMaps method of har Package

Best K6 code snippet using har.traverseMaps

converter.go

Source:converter.go Github

copy

Full Screen

...175 if err := json.Unmarshal([]byte(escapedPostdata), &requestMap); err != nil {176 return "", err177 }178 if len(previousResponse) != 0 {179 traverseMaps(requestMap, previousResponse, nil)180 }181 requestText, err := json.Marshal(requestMap)182 if err == nil {183 prettyJSONString := string(pretty.PrettyOptions(requestText, &pretty.Options{Width: 999999, Prefix: "\t\t\t", Indent: "\t", SortKeys: true})[:])184 fprintf(w, ",\n\t\t\t`%s`", strings.TrimSpace(prettyJSONString))185 } else {186 return "", err187 }188 } else {189 fprintf(w, ",\n\t\t%q", body)190 }191 }192 if len(params) > 0 {193 fprintf(w, ",\n\t\t\t{\n\t\t\t\t%s\n\t\t\t}", strings.Join(params, ",\n\t\t\t"))194 }195 fprintf(w, "\n\t\t)\n")196 if e.Response != nil {197 // the response is nil if there is a failed request in the recording, or if responses were not recorded198 if enableChecks {199 if e.Response.Status > 0 {200 if returnOnFailedCheck {201 fprintf(w, "\t\tif (!check(res, {\"status is %v\": (r) => r.status === %v })) { return };\n", e.Response.Status, e.Response.Status)202 } else {203 fprintf(w, "\t\tcheck(res, {\"status is %v\": (r) => r.status === %v });\n", e.Response.Status, e.Response.Status)204 }205 }206 }207 if e.Response.Headers != nil {208 for _, header := range e.Response.Headers {209 if header.Name == "Location" {210 fprintf(w, "\t\tredirectUrl = res.headers.Location;\n")211 recordedRedirectURL = header.Value212 break213 }214 }215 }216 responseMimeType := e.Response.Content.MimeType217 if correlate &&218 strings.Index(responseMimeType, "application/") == 0 &&219 strings.Index(responseMimeType, "json") == len(responseMimeType)-4 {220 if err := json.Unmarshal([]byte(e.Response.Content.Text), &previousResponse); err != nil {221 return "", err222 }223 fprint(w, "\t\tjson = JSON.parse(res.body);\n")224 }225 }226 }227 } else {228 batches := SplitEntriesInBatches(entries, batchTime)229 fprint(w, "\t\tlet req, res;\n")230 for j, batchEntries := range batches {231 fprint(w, "\t\treq = [")232 for k, e := range batchEntries {233 r, err := buildK6RequestObject(e.Request)234 if err != nil {235 return "", err236 }237 fprintf(w, "%v", r)238 if k != len(batchEntries)-1 {239 fprint(w, ",")240 }241 }242 fprint(w, "];\n")243 fprint(w, "\t\tres = http.batch(req);\n")244 if enableChecks {245 for k, e := range batchEntries {246 if e.Response.Status > 0 {247 if returnOnFailedCheck {248 fprintf(w, "\t\tif (!check(res, {\"status is %v\": (r) => r.status === %v })) { return };\n", e.Response.Status, e.Response.Status)249 } else {250 fprintf(w, "\t\tcheck(res[%v], {\"status is %v\": (r) => r.status === %v });\n", k, e.Response.Status, e.Response.Status)251 }252 }253 }254 }255 if j != len(batches)-1 {256 lastBatchEntry := batchEntries[len(batchEntries)-1]257 firstBatchEntry := batches[j+1][0]258 t := firstBatchEntry.StartedDateTime.Sub(lastBatchEntry.StartedDateTime).Seconds()259 fprintf(w, "\t\tsleep(%.2f);\n", t)260 }261 }262 if i == len(pages)-1 {263 // Last page; add random sleep time at the group completion264 fprintf(w, "\t\t// Random sleep between %ds and %ds\n", minSleep, maxSleep)265 fprintf(w, "\t\tsleep(Math.floor(Math.random()*%d+%d));\n", maxSleep-minSleep, minSleep)266 } else {267 // Add sleep time at the end of the group268 nextPage := pages[i+1]269 sleepTime := 0.5270 if len(entries) > 0 {271 lastEntry := entries[len(entries)-1]272 t := nextPage.StartedDateTime.Sub(lastEntry.StartedDateTime).Seconds()273 if t >= 0.01 {274 sleepTime = t275 }276 }277 fprintf(w, "\t\tsleep(%.2f);\n", sleepTime)278 }279 }280 fprint(w, "\t});\n")281 }282 fprint(w, "\n}\n")283 if err := w.Flush(); err != nil {284 return "", err285 }286 return b.String(), nil287}288func buildK6RequestObject(req *Request) (string, error) {289 var b bytes.Buffer290 w := bufio.NewWriter(&b)291 fprint(w, "{\n")292 method := strings.ToLower(req.Method)293 if method == "delete" {294 method = "del"295 }296 fprintf(w, `"method": %q, "url": %q`, method, req.URL)297 if req.PostData != nil && method != "get" {298 postParams, plainText, err := buildK6Body(req)299 if err != nil {300 return "", err301 } else if len(postParams) > 0 {302 fprintf(w, `, "body": { %s }`, strings.Join(postParams, ", "))303 } else if plainText != "" {304 fprintf(w, `, "body": %q`, plainText)305 }306 }307 var params []string308 var cookies []string309 for _, c := range req.Cookies {310 cookies = append(cookies, fmt.Sprintf(`%q: %q`, c.Name, c.Value))311 }312 if len(cookies) > 0 {313 params = append(params, fmt.Sprintf(`"cookies": { %s }`, strings.Join(cookies, ", ")))314 }315 if headers := buildK6Headers(req.Headers); len(headers) > 0 {316 params = append(params, fmt.Sprintf(`"headers": { %s }`, strings.Join(headers, ", ")))317 }318 if len(params) > 0 {319 fprintf(w, `, "params": { %s }`, strings.Join(params, ", "))320 }321 fprint(w, "}")322 if err := w.Flush(); err != nil {323 return "", err324 }325 var buffer bytes.Buffer326 err := json.Indent(&buffer, b.Bytes(), "\t\t", "\t")327 if err != nil {328 return "", err329 }330 return buffer.String(), nil331}332func buildK6Headers(headers []Header) []string {333 var h []string334 if len(headers) > 0 {335 ignored := map[string]bool{"cookie": true, "content-length": true}336 for _, header := range headers {337 name := strings.ToLower(header.Name)338 _, isIgnored := ignored[name]339 // Avoid SPDY's, duplicated or ignored headers340 if !isIgnored && name[0] != ':' {341 ignored[name] = true342 h = append(h, fmt.Sprintf("%q: %q", header.Name, header.Value))343 }344 }345 }346 return h347}348func buildK6Body(req *Request) ([]string, string, error) {349 var postParams []string350 if req.PostData.MimeType == "application/x-www-form-urlencoded" && len(req.PostData.Params) > 0 {351 for _, p := range req.PostData.Params {352 n, err := url.QueryUnescape(p.Name)353 if err != nil {354 return postParams, "", err355 }356 v, err := url.QueryUnescape(p.Value)357 if err != nil {358 return postParams, "", err359 }360 postParams = append(postParams, fmt.Sprintf(`%q: %q`, n, v))361 }362 return postParams, "", nil363 }364 return postParams, req.PostData.Text, nil365}366func traverseMaps(request map[string]interface{}, response map[string]interface{}, path []interface{}) {367 if response == nil {368 // previous call reached a leaf in the response map so there's no point continuing369 return370 }371 for key, val := range request {372 responseVal := response[key]373 if responseVal == nil {374 // no corresponding value in response map (and the type conversion below would fail so we need an early exit)375 continue376 }377 newPath := append(path, key)378 switch concreteVal := val.(type) {379 case map[string]interface{}:380 traverseMaps(concreteVal, responseVal.(map[string]interface{}), newPath)381 case []interface{}:382 traverseArrays(concreteVal, responseVal.([]interface{}), newPath)383 default:384 if responseVal == val {385 request[key] = jsObjectPath(newPath)386 }387 }388 }389}390func traverseArrays(requestArray []interface{}, responseArray []interface{}, path []interface{}) {391 for i, val := range requestArray {392 newPath := append(path, i)393 if len(responseArray) <= i {394 // requestArray had more entries than responseArray395 break396 }397 responseVal := responseArray[i]398 switch concreteVal := val.(type) {399 case map[string]interface{}:400 traverseMaps(concreteVal, responseVal.(map[string]interface{}), newPath)401 case []interface{}:402 traverseArrays(concreteVal, responseVal.([]interface{}), newPath)403 case string:404 if responseVal == val {405 requestArray[i] = jsObjectPath(newPath)406 }407 default:408 panic(jsObjectPath(newPath))409 }410 }411}412func jsObjectPath(path []interface{}) string {413 s := "${json"414 for _, val := range path {...

Full Screen

Full Screen

traverseMaps

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 jsonFile, err := os.Open("1.har")4 if err != nil {5 fmt.Println(err)6 }7 fmt.Println("Successfully Opened 1.har")8 defer jsonFile.Close()9 byteValue, _ := ioutil.ReadAll(jsonFile)10 json.Unmarshal(byteValue, &har)11 har.traverseMaps(har.Log.Entries)12}13import (14type har struct {15}16type log struct {17}18type entries struct {19}20type request struct {21}22func (h har) traverseMaps(maps []entries) {23 for _, item := range maps {24 fmt.Println(item.Request.Url)25 }26}

Full Screen

Full Screen

traverseMaps

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 h := har{}4 h.traverseMaps()5}6import (7type har struct {

Full Screen

Full Screen

traverseMaps

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 json := []byte(`{4 "menu": {5 "popup": {6 {"value": "New", "onclick": "CreateNewDoc()"},7 {"value": "Open", "onclick": "OpenDoc()"},8 {"value": "Close", "onclick": "CloseDoc()"}9 }10 }11 }`)12 jsonparser.ObjectEach(json, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {13 fmt.Println(string(key), string(value), dataType, offset)14 })15}16menu {"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}} Object 917popup {"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]} Object 4118menuitem [{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}] Array 54190 {"value":"New","onclick":"CreateNewDoc()"} Object 5920onclick CreateNewDoc() String 79211 {"value":"Open","onclick":"OpenDoc()"} Object 10022onclick OpenDoc() String 118232 {"value":"Close","onclick":"CloseDoc()"} Object 13724onclick CloseDoc() String 15725Example 2: Using jsonparser.ArrayEach() method26import

Full Screen

Full Screen

traverseMaps

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 har := Har{}4 har.Parse("sample.har")5 har.traverseMaps(har.Har)6}7import (8func main() {9 har := Har{}10 har.Parse("sample.har")11 har.traverseMaps(har.Har)12}13import (14func main() {15 har := Har{}16 har.Parse("sample.har")17 har.traverseMaps(har.Har)18}19import (20func main() {21 har := Har{}22 har.Parse("sample.har")23 har.traverseMaps(har.Har)24}25import (26func main() {27 har := Har{}28 har.Parse("sample.har")29 har.traverseMaps(har.Har)30}31import (32func main() {

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