Best K6 code snippet using core.getMetricMax
engine_test.go
Source:engine_test.go
...335 }336 }337 return338}339func getMetricMax(mo *mockoutput.MockOutput, name string) (result float64) {340 for _, sc := range mo.SampleContainers {341 for _, s := range sc.GetSamples() {342 if s.Metric.Name == name && s.Value > result {343 result = s.Value344 }345 }346 }347 return348}349const expectedHeaderMaxLength = 500350// FIXME: This test is too brittle, consider simplifying.351func TestSentReceivedMetrics(t *testing.T) {352 t.Parallel()353 tb := httpmultibin.NewHTTPMultiBin(t)354 tr := tb.Replacer.Replace355 type testScript struct {356 Code string357 NumRequests int64358 ExpectedDataSent int64359 ExpectedDataReceived int64360 }361 testScripts := []testScript{362 {tr(`import http from "k6/http";363 export default function() {364 http.get("HTTPBIN_URL/bytes/15000");365 }`), 1, 0, 15000},366 {tr(`import http from "k6/http";367 export default function() {368 http.get("HTTPBIN_URL/bytes/5000");369 http.get("HTTPSBIN_URL/bytes/5000");370 http.batch(["HTTPBIN_URL/bytes/10000", "HTTPBIN_URL/bytes/20000", "HTTPSBIN_URL/bytes/10000"]);371 }`), 5, 0, 50000},372 {tr(`import http from "k6/http";373 let data = "0123456789".repeat(100);374 export default function() {375 http.post("HTTPBIN_URL/ip", {376 file: http.file(data, "test.txt")377 });378 }`), 1, 1000, 100},379 // NOTE(imiric): This needs to keep testing against /ws-echo-invalid because380 // this test is highly sensitive to metric data, and slightly differing381 // WS server implementations might introduce flakiness.382 // See https://github.com/k6io/k6/pull/1149383 {tr(`import ws from "k6/ws";384 let data = "0123456789".repeat(100);385 export default function() {386 ws.connect("WSBIN_URL/ws-echo-invalid", null, function (socket) {387 socket.on('open', function open() {388 socket.send(data);389 });390 socket.on('message', function (message) {391 socket.close();392 });393 });394 }`), 2, 1000, 1000},395 }396 type testCase struct{ Iterations, VUs int64 }397 testCases := []testCase{398 {1, 1}, {2, 2}, {2, 1}, {5, 2}, {25, 2}, {50, 5},399 }400 runTest := func(t *testing.T, ts testScript, tc testCase, noConnReuse bool) (float64, float64) {401 r, err := js.New(402 testutils.NewLogger(t),403 &loader.SourceData{URL: &url.URL{Path: "/script.js"}, Data: []byte(ts.Code)},404 nil,405 lib.RuntimeOptions{},406 )407 require.NoError(t, err)408 mockOutput := mockoutput.New()409 _, run, wait := newTestEngine(t, nil, r, []output.Output{mockOutput}, lib.Options{410 Iterations: null.IntFrom(tc.Iterations),411 VUs: null.IntFrom(tc.VUs),412 Hosts: tb.Dialer.Hosts,413 InsecureSkipTLSVerify: null.BoolFrom(true),414 NoVUConnectionReuse: null.BoolFrom(noConnReuse),415 Batch: null.IntFrom(20),416 })417 errC := make(chan error)418 go func() { errC <- run() }()419 select {420 case <-time.After(10 * time.Second):421 t.Fatal("Test timed out")422 case err := <-errC:423 require.NoError(t, err)424 }425 wait()426 checkData := func(name string, expected int64) float64 {427 data := getMetricSum(mockOutput, name)428 expectedDataMin := float64(expected * tc.Iterations)429 expectedDataMax := float64((expected + ts.NumRequests*expectedHeaderMaxLength) * tc.Iterations)430 if data < expectedDataMin || data > expectedDataMax {431 t.Errorf(432 "The %s sum should be in the interval [%f, %f] but was %f",433 name, expectedDataMin, expectedDataMax, data,434 )435 }436 return data437 }438 return checkData(metrics.DataSent.Name, ts.ExpectedDataSent),439 checkData(metrics.DataReceived.Name, ts.ExpectedDataReceived)440 }441 getTestCase := func(t *testing.T, ts testScript, tc testCase) func(t *testing.T) {442 return func(t *testing.T) {443 t.Parallel()444 noReuseSent, noReuseReceived := runTest(t, ts, tc, true)445 reuseSent, reuseReceived := runTest(t, ts, tc, false)446 if noReuseSent < reuseSent {447 t.Errorf("reuseSent=%f is greater than noReuseSent=%f", reuseSent, noReuseSent)448 }449 if noReuseReceived < reuseReceived {450 t.Errorf("reuseReceived=%f is greater than noReuseReceived=%f", reuseReceived, noReuseReceived)451 }452 }453 }454 // This Run will not return until the parallel subtests complete.455 t.Run("group", func(t *testing.T) {456 t.Parallel()457 for tsNum, ts := range testScripts {458 for tcNum, tc := range testCases {459 t.Run(460 fmt.Sprintf("SentReceivedMetrics_script[%d]_case[%d](%d,%d)", tsNum, tcNum, tc.Iterations, tc.VUs),461 getTestCase(t, ts, tc),462 )463 }464 }465 })466}467func TestRunTags(t *testing.T) {468 t.Parallel()469 tb := httpmultibin.NewHTTPMultiBin(t)470 runTagsMap := map[string]string{"foo": "bar", "test": "mest", "over": "written"}471 runTags := stats.NewSampleTags(runTagsMap)472 script := []byte(tb.Replacer.Replace(`473 import http from "k6/http";474 import ws from "k6/ws";475 import { Counter } from "k6/metrics";476 import { group, check, fail } from "k6";477 let customTags = { "over": "the rainbow" };478 let params = { "tags": customTags};479 let statusCheck = { "status is 200": (r) => r.status === 200 }480 let myCounter = new Counter("mycounter");481 export default function() {482 group("http", function() {483 check(http.get("HTTPSBIN_URL", params), statusCheck, customTags);484 check(http.get("HTTPBIN_URL/status/418", params), statusCheck, customTags);485 })486 group("websockets", function() {487 var response = ws.connect("WSBIN_URL/ws-echo", params, function (socket) {488 socket.on('open', function open() {489 console.log('ws open and say hello');490 socket.send("hello");491 });492 socket.on('message', function (message) {493 console.log('ws got message ' + message);494 if (message != "hello") {495 fail("Expected to receive 'hello' but got '" + message + "' instead !");496 }497 console.log('ws closing socket...');498 socket.close();499 });500 socket.on('close', function () {501 console.log('ws close');502 });503 socket.on('error', function (e) {504 console.log('ws error: ' + e.error());505 });506 });507 console.log('connect returned');508 check(response, { "status is 101": (r) => r && r.status === 101 }, customTags);509 })510 myCounter.add(1, customTags);511 }512 `))513 r, err := js.New(514 testutils.NewLogger(t),515 &loader.SourceData{URL: &url.URL{Path: "/script.js"}, Data: script},516 nil,517 lib.RuntimeOptions{},518 )519 require.NoError(t, err)520 mockOutput := mockoutput.New()521 _, run, wait := newTestEngine(t, nil, r, []output.Output{mockOutput}, lib.Options{522 Iterations: null.IntFrom(3),523 VUs: null.IntFrom(2),524 Hosts: tb.Dialer.Hosts,525 RunTags: runTags,526 SystemTags: &stats.DefaultSystemTagSet,527 InsecureSkipTLSVerify: null.BoolFrom(true),528 })529 errC := make(chan error)530 go func() { errC <- run() }()531 select {532 case <-time.After(10 * time.Second):533 t.Fatal("Test timed out")534 case err := <-errC:535 require.NoError(t, err)536 }537 wait()538 systemMetrics := []*stats.Metric{539 metrics.VUs, metrics.VUsMax, metrics.Iterations, metrics.IterationDuration,540 metrics.GroupDuration, metrics.DataSent, metrics.DataReceived,541 }542 getExpectedOverVal := func(metricName string) string {543 for _, sysMetric := range systemMetrics {544 if sysMetric.Name == metricName {545 return runTagsMap["over"]546 }547 }548 return "the rainbow"549 }550 for _, s := range mockOutput.Samples {551 for key, expVal := range runTagsMap {552 val, ok := s.Tags.Get(key)553 if key == "over" {554 expVal = getExpectedOverVal(s.Metric.Name)555 }556 assert.True(t, ok)557 assert.Equalf(t, expVal, val, "Wrong tag value in sample for metric %#v", s.Metric)558 }559 }560}561func TestSetupTeardownThresholds(t *testing.T) {562 t.Parallel()563 tb := httpmultibin.NewHTTPMultiBin(t)564 script := []byte(tb.Replacer.Replace(`565 import http from "k6/http";566 import { check } from "k6";567 import { Counter } from "k6/metrics";568 let statusCheck = { "status is 200": (r) => r.status === 200 }569 let myCounter = new Counter("setup_teardown");570 export let options = {571 iterations: 5,572 thresholds: {573 "setup_teardown": ["count == 2"],574 "iterations": ["count == 5"],575 "http_reqs": ["count == 7"],576 },577 };578 export function setup() {579 check(http.get("HTTPBIN_IP_URL"), statusCheck) && myCounter.add(1);580 };581 export default function () {582 check(http.get("HTTPBIN_IP_URL"), statusCheck);583 };584 export function teardown() {585 check(http.get("HTTPBIN_IP_URL"), statusCheck) && myCounter.add(1);586 };587 `))588 runner, err := js.New(589 testutils.NewLogger(t),590 &loader.SourceData{URL: &url.URL{Path: "/script.js"}, Data: script},591 nil,592 lib.RuntimeOptions{},593 )594 require.NoError(t, err)595 engine, run, wait := newTestEngine(t, nil, runner, nil, lib.Options{596 SystemTags: &stats.DefaultSystemTagSet,597 SetupTimeout: types.NullDurationFrom(3 * time.Second),598 TeardownTimeout: types.NullDurationFrom(3 * time.Second),599 VUs: null.IntFrom(3),600 })601 defer wait()602 errC := make(chan error)603 go func() { errC <- run() }()604 select {605 case <-time.After(10 * time.Second):606 t.Fatal("Test timed out")607 case err := <-errC:608 require.NoError(t, err)609 require.False(t, engine.IsTainted())610 }611}612func TestSetupException(t *testing.T) {613 t.Parallel()614 script := []byte(`615 import bar from "./bar.js";616 export function setup() {617 bar();618 };619 export default function() {620 };621 `)622 memfs := afero.NewMemMapFs()623 require.NoError(t, afero.WriteFile(memfs, "/bar.js", []byte(`624 export default function () {625 baz();626 }627 function baz() {628 throw new Error("baz");629 }630 `), 0x666))631 runner, err := js.New(632 testutils.NewLogger(t),633 &loader.SourceData{URL: &url.URL{Scheme: "file", Path: "/script.js"}, Data: script},634 map[string]afero.Fs{"file": memfs},635 lib.RuntimeOptions{},636 )637 require.NoError(t, err)638 _, run, wait := newTestEngine(t, nil, runner, nil, lib.Options{639 SystemTags: &stats.DefaultSystemTagSet,640 SetupTimeout: types.NullDurationFrom(3 * time.Second),641 TeardownTimeout: types.NullDurationFrom(3 * time.Second),642 VUs: null.IntFrom(3),643 })644 defer wait()645 errC := make(chan error)646 go func() { errC <- run() }()647 select {648 case <-time.After(10 * time.Second):649 t.Fatal("Test timed out")650 case err := <-errC:651 require.Error(t, err)652 var exception errext.Exception653 require.ErrorAs(t, err, &exception)654 require.Equal(t, "Error: baz\n\tat baz (file:///bar.js:7:8(4))\n"+655 "\tat file:///bar.js:4:5(3)\n\tat setup (file:///script.js:7:204(4))\n",656 err.Error())657 }658}659func TestVuInitException(t *testing.T) {660 t.Parallel()661 script := []byte(`662 export let options = {663 vus: 3,664 iterations: 5,665 };666 export default function() {};667 if (__VU == 2) {668 throw new Error('oops in ' + __VU);669 }670 `)671 logger := testutils.NewLogger(t)672 runner, err := js.New(673 logger,674 &loader.SourceData{URL: &url.URL{Scheme: "file", Path: "/script.js"}, Data: script},675 nil, lib.RuntimeOptions{},676 )677 require.NoError(t, err)678 opts, err := executor.DeriveScenariosFromShortcuts(runner.GetOptions())679 require.NoError(t, err)680 require.Empty(t, opts.Validate())681 require.NoError(t, runner.SetOptions(opts))682 execScheduler, err := local.NewExecutionScheduler(runner, logger)683 require.NoError(t, err)684 engine, err := NewEngine(execScheduler, opts, lib.RuntimeOptions{}, nil, logger)685 require.NoError(t, err)686 ctx, cancel := context.WithCancel(context.Background())687 defer cancel()688 _, _, err = engine.Init(ctx, ctx) // no need for 2 different contexts689 require.Error(t, err)690 var exception errext.Exception691 require.ErrorAs(t, err, &exception)692 assert.Equal(t, "Error: oops in 2\n\tat file:///script.js:10:8(32)\n", err.Error())693 var errWithHint errext.HasHint694 require.ErrorAs(t, err, &errWithHint)695 assert.Equal(t, "error while initializing VU #2 (script exception)", errWithHint.Hint())696}697func TestEmittedMetricsWhenScalingDown(t *testing.T) {698 t.Parallel()699 tb := httpmultibin.NewHTTPMultiBin(t)700 script := []byte(tb.Replacer.Replace(`701 import http from "k6/http";702 import { sleep } from "k6";703 export let options = {704 systemTags: ["iter", "vu", "url"],705 scenarios: {706 we_need_hard_stop_and_ramp_down: {707 executor: "ramping-vus",708 // Start with 2 VUs for 4 seconds and then quickly scale down to 1 for the next 4s and then quit709 startVUs: 2,710 stages: [711 { duration: "4s", target: 2 },712 { duration: "0s", target: 1 },713 { duration: "4s", target: 1 },714 ],715 gracefulStop: "0s",716 gracefulRampDown: "0s",717 },718 },719 };720 export default function () {721 console.log("VU " + __VU + " starting iteration #" + __ITER);722 http.get("HTTPBIN_IP_URL/bytes/15000");723 sleep(3.1);724 http.get("HTTPBIN_IP_URL/bytes/15000");725 console.log("VU " + __VU + " ending iteration #" + __ITER);726 };727 `))728 runner, err := js.New(729 testutils.NewLogger(t),730 &loader.SourceData{URL: &url.URL{Path: "/script.js"}, Data: script},731 nil,732 lib.RuntimeOptions{},733 )734 require.NoError(t, err)735 mockOutput := mockoutput.New()736 engine, run, wait := newTestEngine(t, nil, runner, []output.Output{mockOutput}, lib.Options{})737 errC := make(chan error)738 go func() { errC <- run() }()739 select {740 case <-time.After(12 * time.Second):741 t.Fatal("Test timed out")742 case err := <-errC:743 require.NoError(t, err)744 wait()745 require.False(t, engine.IsTainted())746 }747 // The 3.1 sleep in the default function would cause the first VU to complete 2 full iterations748 // and stat executing its third one, while the second VU will only fully complete 1 iteration749 // and will be canceled in the middle of its second one.750 assert.Equal(t, 3.0, getMetricSum(mockOutput, metrics.Iterations.Name))751 // That means that we expect to see 8 HTTP requests in total, 3*2=6 from the complete iterations752 // and one each from the two iterations that would be canceled in the middle of their execution753 assert.Equal(t, 8.0, getMetricSum(mockOutput, metrics.HTTPReqs.Name))754 // And we expect to see the data_received for all 8 of those requests. Previously, the data for755 // the 8th request (the 3rd one in the first VU before the test ends) was cut off by the engine756 // because it was emitted after the test officially ended. But that was mostly an unintended757 // consequence of the fact that those metrics were emitted only after an iteration ended when758 // it was interrupted.759 dataReceivedExpectedMin := 15000.0 * 8760 dataReceivedExpectedMax := (15000.0 + expectedHeaderMaxLength) * 8761 dataReceivedActual := getMetricSum(mockOutput, metrics.DataReceived.Name)762 if dataReceivedActual < dataReceivedExpectedMin || dataReceivedActual > dataReceivedExpectedMax {763 t.Errorf(764 "The data_received sum should be in the interval [%f, %f] but was %f",765 dataReceivedExpectedMin, dataReceivedExpectedMax, dataReceivedActual,766 )767 }768 // Also, the interrupted iterations shouldn't affect the average iteration_duration in any way, only769 // complete iterations should be taken into account770 durationCount := float64(getMetricCount(mockOutput, metrics.IterationDuration.Name))771 assert.Equal(t, 3.0, durationCount)772 durationSum := getMetricSum(mockOutput, metrics.IterationDuration.Name)773 assert.InDelta(t, 3.35, durationSum/(1000*durationCount), 0.25)774}775func TestMetricsEmission(t *testing.T) {776 if !isWindows {777 t.Parallel()778 }779 testCases := []struct {780 method string781 minIterDuration string782 defaultBody string783 expCount, expIters float64784 }{785 // Since emission of Iterations happens before the minIterationDuration786 // sleep is done, we expect to receive metrics for all executions of787 // the `default` function, despite of the lower overall duration setting.788 {"minIterationDuration", `"300ms"`, "testCounter.add(1);", 16.0, 16.0},789 // With the manual sleep method and no minIterationDuration, the last790 // `default` execution will be cutoff by the duration setting, so only791 // 3 sets of metrics are expected.792 {"sleepBeforeCounterAdd", "null", "sleep(0.3); testCounter.add(1); ", 12.0, 12.0},793 // The counter should be sent, but the last iteration will be incomplete794 {"sleepAfterCounterAdd", "null", "testCounter.add(1); sleep(0.3); ", 16.0, 12.0},795 }796 for _, tc := range testCases {797 tc := tc798 t.Run(tc.method, func(t *testing.T) {799 if !isWindows {800 t.Parallel()801 }802 runner, err := js.New(803 testutils.NewLogger(t),804 &loader.SourceData{URL: &url.URL{Path: "/script.js"}, Data: []byte(fmt.Sprintf(`805 import { sleep } from "k6";806 import { Counter } from "k6/metrics";807 let testCounter = new Counter("testcounter");808 export let options = {809 scenarios: {810 we_need_hard_stop: {811 executor: "constant-vus",812 vus: 4,813 duration: "1s",814 gracefulStop: "0s",815 },816 },817 minIterationDuration: %s,818 };819 export default function() {820 %s821 }822 `, tc.minIterDuration, tc.defaultBody))},823 nil,824 lib.RuntimeOptions{},825 )826 require.NoError(t, err)827 mockOutput := mockoutput.New()828 engine, run, wait := newTestEngine(t, nil, runner, []output.Output{mockOutput}, runner.GetOptions())829 errC := make(chan error)830 go func() { errC <- run() }()831 select {832 case <-time.After(10 * time.Second):833 t.Fatal("Test timed out")834 case err := <-errC:835 require.NoError(t, err)836 wait()837 require.False(t, engine.IsTainted())838 }839 assert.Equal(t, tc.expIters, getMetricSum(mockOutput, metrics.Iterations.Name))840 assert.Equal(t, tc.expCount, getMetricSum(mockOutput, "testcounter"))841 })842 }843}844//nolint: funlen845func TestMinIterationDurationInSetupTeardownStage(t *testing.T) {846 t.Parallel()847 setupScript := `848 import { sleep } from "k6";849 export function setup() {850 sleep(1);851 }852 export let options = {853 minIterationDuration: "2s",854 scenarios: {855 we_need_hard_stop: {856 executor: "constant-vus",857 vus: 2,858 duration: "1.9s",859 gracefulStop: "0s",860 },861 },862 setupTimeout: "3s",863 };864 export default function () {865 };`866 teardownScript := `867 import { sleep } from "k6";868 export let options = {869 minIterationDuration: "2s",870 scenarios: {871 we_need_hard_stop: {872 executor: "constant-vus",873 vus: 2,874 duration: "1.9s",875 gracefulStop: "0s",876 },877 },878 teardownTimeout: "3s",879 };880 export default function () {881 };882 export function teardown() {883 sleep(1);884 }885`886 tests := []struct {887 name, script string888 }{889 {"Test setup", setupScript},890 {"Test teardown", teardownScript},891 }892 for _, tc := range tests {893 tc := tc894 t.Run(tc.name, func(t *testing.T) {895 t.Parallel()896 runner, err := js.New(897 testutils.NewLogger(t),898 &loader.SourceData{URL: &url.URL{Path: "/script.js"}, Data: []byte(tc.script)},899 nil,900 lib.RuntimeOptions{},901 )902 require.NoError(t, err)903 engine, run, wait := newTestEngine(t, nil, runner, nil, runner.GetOptions())904 errC := make(chan error)905 go func() { errC <- run() }()906 select {907 case <-time.After(10 * time.Second):908 t.Fatal("Test timed out")909 case err := <-errC:910 require.NoError(t, err)911 wait()912 require.False(t, engine.IsTainted())913 }914 })915 }916}917func TestEngineRunsTeardownEvenAfterTestRunIsAborted(t *testing.T) {918 t.Parallel()919 testMetric := stats.New("teardown_metric", stats.Counter)920 ctx, cancel := context.WithCancel(context.Background())921 runner := &minirunner.MiniRunner{922 Fn: func(ctx context.Context, out chan<- stats.SampleContainer) error {923 cancel() // we cancel the runCtx immediately after the test starts924 return nil925 },926 TeardownFn: func(ctx context.Context, out chan<- stats.SampleContainer) error {927 out <- stats.Sample{Metric: testMetric, Value: 1}928 return nil929 },930 }931 mockOutput := mockoutput.New()932 _, run, wait := newTestEngine(t, ctx, runner, []output.Output{mockOutput}, lib.Options{933 VUs: null.IntFrom(1), Iterations: null.IntFrom(1),934 })935 assert.NoError(t, run())936 wait()937 var count float64938 for _, sample := range mockOutput.Samples {939 if sample.Metric == testMetric {940 count += sample.Value941 }942 }943 assert.Equal(t, 1.0, count)944}945func TestActiveVUsCount(t *testing.T) {946 t.Parallel()947 script := []byte(`948 var sleep = require('k6').sleep;949 exports.options = {950 scenarios: {951 carr1: {952 executor: 'constant-arrival-rate',953 rate: 10,954 preAllocatedVUs: 1,955 maxVUs: 10,956 startTime: '0s',957 duration: '3s',958 gracefulStop: '0s',959 },960 carr2: {961 executor: 'constant-arrival-rate',962 rate: 10,963 preAllocatedVUs: 1,964 maxVUs: 10,965 duration: '3s',966 startTime: '3s',967 gracefulStop: '0s',968 },969 rarr: {970 executor: 'ramping-arrival-rate',971 startRate: 5,972 stages: [973 { target: 10, duration: '2s' },974 { target: 0, duration: '2s' },975 ],976 preAllocatedVUs: 1,977 maxVUs: 10,978 startTime: '6s',979 gracefulStop: '0s',980 },981 }982 }983 exports.default = function () {984 sleep(5);985 }986 `)987 logger := testutils.NewLogger(t)988 logHook := testutils.SimpleLogrusHook{HookedLevels: logrus.AllLevels}989 logger.AddHook(&logHook)990 rtOpts := lib.RuntimeOptions{CompatibilityMode: null.StringFrom("base")}991 runner, err := js.New(logger, &loader.SourceData{URL: &url.URL{Path: "/script.js"}, Data: script}, nil, rtOpts)992 require.NoError(t, err)993 mockOutput := mockoutput.New()994 ctx, cancel := context.WithCancel(context.Background())995 defer cancel()996 opts, err := executor.DeriveScenariosFromShortcuts(lib.Options{997 MetricSamplesBufferSize: null.NewInt(200, false),998 }.Apply(runner.GetOptions()))999 require.NoError(t, err)1000 require.Empty(t, opts.Validate())1001 require.NoError(t, runner.SetOptions(opts))1002 execScheduler, err := local.NewExecutionScheduler(runner, logger)1003 require.NoError(t, err)1004 engine, err := NewEngine(execScheduler, opts, rtOpts, []output.Output{mockOutput}, logger)1005 require.NoError(t, err)1006 run, waitFn, err := engine.Init(ctx, ctx) // no need for 2 different contexts1007 require.NoError(t, err)1008 errC := make(chan error)1009 go func() { errC <- run() }()1010 select {1011 case <-time.After(15 * time.Second):1012 t.Fatal("Test timed out")1013 case err := <-errC:1014 require.NoError(t, err)1015 cancel()1016 waitFn()1017 require.False(t, engine.IsTainted())1018 }1019 assert.Equal(t, 10.0, getMetricMax(mockOutput, metrics.VUs.Name))1020 assert.Equal(t, 10.0, getMetricMax(mockOutput, metrics.VUsMax.Name))1021 logEntries := logHook.Drain()1022 assert.Len(t, logEntries, 3)1023 for _, logEntry := range logEntries {1024 assert.Equal(t, logrus.WarnLevel, logEntry.Level)1025 assert.Equal(t, "Insufficient VUs, reached 10 active VUs and cannot initialize more", logEntry.Message)1026 }1027}...
getMetricMax
Using AI Code Generation
1func main() {2 core := new(Core)3 core.getMetricMax()4}5func main() {6 core := new(Core)7 core.getMetricMax()8}9func main() {10 core := new(Core)11 core.getMetricMax()12}13func main() {14 core := new(Core)15 core.getMetricMax()16}17func main() {18 core := new(Core)19 core.getMetricMax()20}21func main() {22 core := new(Core)23 core.getMetricMax()24}25func main() {26 core := new(Core)27 core.getMetricMax()28}29func main() {30 core := new(Core)31 core.getMetricMax()32}33func main() {34 core := new(Core)35 core.getMetricMax()36}37func main() {38 core := new(Core)39 core.getMetricMax()40}41func main() {42 core := new(Core)43 core.getMetricMax()44}45func main() {46 core := new(Core)47 core.getMetricMax()48}49func main() {50 core := new(Core)51 core.getMetricMax()52}53func main() {54 core := new(Core)55 core.getMetricMax()56}
getMetricMax
Using AI Code Generation
1import (2func main() {3 metric := core.Metric{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}4 fmt.Println("Max value of metric is", metric.GetMetricMax())5}6import "fmt"7type Metric struct {8}9func (metric Metric) GetMetricMax() int {10 for _, value := range metric.Values {11 if value > max {12 }13 }14}
getMetricMax
Using AI Code Generation
1import (2func main() {3 fmt.Printf(stringutil.Reverse("!oG ,olleH"))4}5import (6func main() {7 fmt.Printf(stringutil.Reverse("!oG ,olleH"))8}9import (10func main() {11 fmt.Printf(stringutil.Reverse("!oG ,olleH"))12}13import (14func main() {15 fmt.Printf(stringutil.Reverse("!oG ,olleH"))16}17import (18func main() {19 fmt.Printf(stringutil.Reverse("!oG ,olleH"))20}21import (22func main() {23 fmt.Printf(stringutil.Reverse("!oG ,olleH"))24}25import (26func main() {27 fmt.Printf(stringutil.Reverse("!oG ,olleH"))28}29import (30func main() {31 fmt.Printf(stringutil.Reverse("!oG ,olleH"))32}33import (34func main() {35 fmt.Printf(stringutil.Reverse("!oG ,olleH"))36}37import (
getMetricMax
Using AI Code Generation
1import (2func main() {3 core := metrics.New()4 core.Add("somekey", 12)5 core.Add("somekey", 13)6 core.Add("somekey", 14)7 core.Add("somekey", 15)8 core.Add("somekey", 16)9 fmt.Println(core.GetMetricMax("somekey"))10}
getMetricMax
Using AI Code Generation
1import (2func main() {3 core := metrics.New()4 core.Metrics = make(map[string]float64)5 fmt.Println(core.GetMetricMax())6}7import (8type core struct {9}10func New() *core {11 return &core{}12}13func (c *core) GetMetricMax() float64 {14 max := math.Inf(-1)15 for _, v := range c.Metrics {16 if v > max {17 }18 }19 fmt.Println("GetMetricMax")20}21import (22func main() {23 core := metrics.New()24 core.Metrics = make(map[string]float64)25 fmt.Println(core.GetMetricMax())26}27import (28type Core struct {29}30func New() *Core {31 return &Core{}32}33func (c *Core) GetMetricMax() float64 {34 max := math.Inf(-1)35 for _, v := range c.Metrics {36 if v > max {37 }38 }39 fmt.Println("GetMetricMax")40}41import (
getMetricMax
Using AI Code Generation
1import (2func main() {3 var arr [5]int = [5]int{10, 20, 30, 40, 50}4 fmt.Println(core.GetMetricMax(arr))5}6import (7func GetMetricMax(arr [5]int) int {8 for i := 1; i < 5; i++ {9 if arr[i] > max {10 }11 }12}
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!!