Best K6 code snippet using http.assertRequestMetricsEmittedSingle
response_callback_test.go
Source:response_callback_test.go
...269 }270 }271 require.Equal(t, len(testCase.expectedSamples), reqsCount)272 for i, expectedSample := range testCase.expectedSamples {273 assertRequestMetricsEmittedSingle(t, bufSamples[i], expectedSample.tags, expectedSample.metrics, nil)274 }275 })276 }277}278func TestResponseCallbackBatch(t *testing.T) {279 t.Parallel()280 tb, _, samples, rt, mii := newRuntime(t)281 sr := tb.Replacer.Replace282 HTTPMetricsWithoutFailed := []string{283 metrics.HTTPReqsName,284 metrics.HTTPReqBlockedName,285 metrics.HTTPReqConnectingName,286 metrics.HTTPReqDurationName,287 metrics.HTTPReqReceivingName,288 metrics.HTTPReqWaitingName,289 metrics.HTTPReqSendingName,290 metrics.HTTPReqTLSHandshakingName,291 }292 allHTTPMetrics := append(HTTPMetricsWithoutFailed, metrics.HTTPReqFailedName)293 // IMPORTANT: the tests here depend on the fact that the url they hit can be ordered in the same294 // order as the expectedSamples even if they are made concurrently295 testCases := map[string]struct {296 code string297 expectedSamples []expectedSample298 }{299 "basic": {300 code: `301 http.batch([["GET", "HTTPBIN_URL/status/200", null, {responseCallback: null}],302 ["GET", "HTTPBIN_URL/status/201"],303 ["GET", "HTTPBIN_URL/status/202", null, {responseCallback: http.expectedStatuses(4)}],304 ["GET", "HTTPBIN_URL/status/405", null, {responseCallback: http.expectedStatuses(405)}],305 ]);`,306 expectedSamples: []expectedSample{307 {308 tags: map[string]string{309 "method": "GET",310 "url": sr("HTTPBIN_URL/status/200"),311 "name": sr("HTTPBIN_URL/status/200"),312 "status": "200",313 "group": "",314 "proto": "HTTP/1.1",315 },316 metrics: HTTPMetricsWithoutFailed,317 },318 {319 tags: map[string]string{320 "method": "GET",321 "url": sr("HTTPBIN_URL/status/201"),322 "name": sr("HTTPBIN_URL/status/201"),323 "status": "201",324 "group": "",325 "expected_response": "true",326 "proto": "HTTP/1.1",327 },328 metrics: allHTTPMetrics,329 },330 {331 tags: map[string]string{332 "method": "GET",333 "url": sr("HTTPBIN_URL/status/202"),334 "name": sr("HTTPBIN_URL/status/202"),335 "status": "202",336 "group": "",337 "expected_response": "false",338 "proto": "HTTP/1.1",339 },340 metrics: allHTTPMetrics,341 },342 {343 tags: map[string]string{344 "method": "GET",345 "url": sr("HTTPBIN_URL/status/405"),346 "name": sr("HTTPBIN_URL/status/405"),347 "status": "405",348 "error_code": "1405",349 "group": "",350 "expected_response": "true",351 "proto": "HTTP/1.1",352 },353 metrics: allHTTPMetrics,354 },355 },356 },357 }358 for name, testCase := range testCases {359 testCase := testCase360 t.Run(name, func(t *testing.T) {361 mii.defaultClient.responseCallback = defaultExpectedStatuses.match362 _, err := rt.RunString(sr(testCase.code))363 assert.NoError(t, err)364 bufSamples := metrics.GetBufferedSamples(samples)365 reqsCount := 0366 for _, container := range bufSamples {367 for _, sample := range container.GetSamples() {368 if sample.Metric.Name == "http_reqs" {369 reqsCount++370 }371 }372 }373 sort.Slice(bufSamples, func(i, j int) bool {374 iURL, _ := bufSamples[i].GetSamples()[0].Tags.Get("url")375 jURL, _ := bufSamples[j].GetSamples()[0].Tags.Get("url")376 return iURL < jURL377 })378 require.Equal(t, len(testCase.expectedSamples), reqsCount)379 for i, expectedSample := range testCase.expectedSamples {380 assertRequestMetricsEmittedSingle(t, bufSamples[i], expectedSample.tags, expectedSample.metrics, nil)381 }382 })383 }384}385func TestResponseCallbackInActionWithoutPassedTag(t *testing.T) {386 t.Parallel()387 tb, state, samples, rt, _ := newRuntime(t)388 sr := tb.Replacer.Replace389 allHTTPMetrics := []string{390 metrics.HTTPReqsName,391 metrics.HTTPReqFailedName,392 metrics.HTTPReqBlockedName,393 metrics.HTTPReqConnectingName,394 metrics.HTTPReqDurationName,395 metrics.HTTPReqReceivingName,396 metrics.HTTPReqSendingName,397 metrics.HTTPReqWaitingName,398 metrics.HTTPReqTLSHandshakingName,399 }400 deleteSystemTag(state, metrics.TagExpectedResponse.String())401 _, err := rt.RunString(sr(`http.request("GET", "HTTPBIN_URL/redirect/1", null, {responseCallback: http.expectedStatuses(200)});`))402 assert.NoError(t, err)403 bufSamples := metrics.GetBufferedSamples(samples)404 reqsCount := 0405 for _, container := range bufSamples {406 for _, sample := range container.GetSamples() {407 if sample.Metric.Name == "http_reqs" {408 reqsCount++409 }410 }411 }412 require.Equal(t, 2, reqsCount)413 tags := map[string]string{414 "method": "GET",415 "url": sr("HTTPBIN_URL/redirect/1"),416 "name": sr("HTTPBIN_URL/redirect/1"),417 "status": "302",418 "group": "",419 "proto": "HTTP/1.1",420 }421 assertRequestMetricsEmittedSingle(t, bufSamples[0], tags, allHTTPMetrics, func(sample metrics.Sample) {422 if sample.Metric.Name == metrics.HTTPReqFailedName {423 require.EqualValues(t, sample.Value, 1)424 }425 })426 tags["url"] = sr("HTTPBIN_URL/get")427 tags["name"] = tags["url"]428 tags["status"] = "200"429 assertRequestMetricsEmittedSingle(t, bufSamples[1], tags, allHTTPMetrics, func(sample metrics.Sample) {430 if sample.Metric.Name == metrics.HTTPReqFailedName {431 require.EqualValues(t, sample.Value, 0)432 }433 })434}435func TestDigestWithResponseCallback(t *testing.T) {436 t.Parallel()437 tb, _, samples, rt, _ := newRuntime(t)438 urlWithCreds := tb.Replacer.Replace(439 "http://testuser:testpwd@HTTPBIN_IP:HTTPBIN_PORT/digest-auth/auth/testuser/testpwd",440 )441 allHTTPMetrics := []string{442 metrics.HTTPReqsName,443 metrics.HTTPReqFailedName,444 metrics.HTTPReqBlockedName,445 metrics.HTTPReqConnectingName,446 metrics.HTTPReqDurationName,447 metrics.HTTPReqReceivingName,448 metrics.HTTPReqSendingName,449 metrics.HTTPReqWaitingName,450 metrics.HTTPReqTLSHandshakingName,451 }452 _, err := rt.RunString(fmt.Sprintf(`453 var res = http.get(%q, { auth: "digest" });454 if (res.status !== 200) { throw new Error("wrong status: " + res.status); }455 if (res.error_code !== 0) { throw new Error("wrong error code: " + res.error_code); }456 `, urlWithCreds))457 require.NoError(t, err)458 bufSamples := metrics.GetBufferedSamples(samples)459 reqsCount := 0460 for _, container := range bufSamples {461 for _, sample := range container.GetSamples() {462 if sample.Metric.Name == "http_reqs" {463 reqsCount++464 }465 }466 }467 require.Equal(t, 2, reqsCount)468 urlRaw := tb.Replacer.Replace(469 "http://HTTPBIN_IP:HTTPBIN_PORT/digest-auth/auth/testuser/testpwd")470 tags := map[string]string{471 "method": "GET",472 "url": urlRaw,473 "name": urlRaw,474 "status": "401",475 "group": "",476 "proto": "HTTP/1.1",477 "expected_response": "true",478 "error_code": "1401",479 }480 assertRequestMetricsEmittedSingle(t, bufSamples[0], tags, allHTTPMetrics, func(sample metrics.Sample) {481 if sample.Metric.Name == metrics.HTTPReqFailedName {482 require.EqualValues(t, sample.Value, 0)483 }484 })485 tags["status"] = "200"486 delete(tags, "error_code")487 assertRequestMetricsEmittedSingle(t, bufSamples[1], tags, allHTTPMetrics, func(sample metrics.Sample) {488 if sample.Metric.Name == metrics.HTTPReqFailedName {489 require.EqualValues(t, sample.Value, 0)490 }491 })492}493func deleteSystemTag(state *lib.State, tag string) {494 enabledTags := state.Options.SystemTags.Map()495 delete(enabledTags, tag)496 tagsList := make([]string, 0, len(enabledTags))497 for k := range enabledTags {498 tagsList = append(tagsList, k)499 }500 state.Options.SystemTags = metrics.ToSystemTagSet(tagsList)501}...
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!!