How to use getMetricCount method of core Package

Best K6 code snippet using core.getMetricCount

engine_test.go

Source:engine_test.go Github

copy

Full Screen

...432 }433 }434 return435}436func getMetricCount(collector *dummy.Collector, name string) (result uint) {437 for _, sc := range collector.SampleContainers {438 for _, s := range sc.GetSamples() {439 if s.Metric.Name == name {440 result++441 }442 }443 }444 return445}446const expectedHeaderMaxLength = 500447func TestSentReceivedMetrics(t *testing.T) {448 t.Parallel()449 tb := testutils.NewHTTPMultiBin(t)450 defer tb.Cleanup()451 tr := tb.Replacer.Replace452 type testScript struct {453 Code string454 NumRequests int64455 ExpectedDataSent int64456 ExpectedDataReceived int64457 }458 testScripts := []testScript{459 {tr(`import http from "k6/http";460 export default function() {461 http.get("HTTPBIN_URL/bytes/15000");462 }`), 1, 0, 15000},463 {tr(`import http from "k6/http";464 export default function() {465 http.get("HTTPBIN_URL/bytes/5000");466 http.get("HTTPSBIN_URL/bytes/5000");467 http.batch(["HTTPBIN_URL/bytes/10000", "HTTPBIN_URL/bytes/20000", "HTTPSBIN_URL/bytes/10000"]);468 }`), 5, 0, 50000},469 {tr(`import http from "k6/http";470 let data = "0123456789".repeat(100);471 export default function() {472 http.post("HTTPBIN_URL/ip", {473 file: http.file(data, "test.txt")474 });475 }`), 1, 1000, 100},476 {tr(`import ws from "k6/ws";477 let data = "0123456789".repeat(100);478 export default function() {479 ws.connect("ws://HTTPBIN_IP:HTTPBIN_PORT/ws-echo", null, function (socket) {480 socket.on('open', function open() {481 socket.send(data);482 });483 socket.on('message', function (message) {484 socket.close();485 });486 });487 }`), 2, 1000, 1000},488 }489 type testCase struct{ Iterations, VUs int64 }490 testCases := []testCase{491 {1, 1}, {1, 2}, {2, 1}, {5, 2}, {25, 2}, {50, 5},492 }493 runTest := func(t *testing.T, ts testScript, tc testCase, noConnReuse bool) (float64, float64) {494 r, err := js.New(495 &lib.SourceData{Filename: "/script.js", Data: []byte(ts.Code)},496 afero.NewMemMapFs(),497 lib.RuntimeOptions{},498 )499 require.NoError(t, err)500 options := lib.Options{501 Iterations: null.IntFrom(tc.Iterations),502 VUs: null.IntFrom(tc.VUs),503 VUsMax: null.IntFrom(tc.VUs),504 Hosts: tb.Dialer.Hosts,505 InsecureSkipTLSVerify: null.BoolFrom(true),506 NoVUConnectionReuse: null.BoolFrom(noConnReuse),507 }508 r.SetOptions(options)509 engine, err := NewEngine(local.New(r), options)510 require.NoError(t, err)511 collector := &dummy.Collector{}512 engine.Collectors = []lib.Collector{collector}513 ctx, cancel := context.WithCancel(context.Background())514 errC := make(chan error)515 go func() { errC <- engine.Run(ctx) }()516 select {517 case <-time.After(10 * time.Second):518 cancel()519 t.Fatal("Test timed out")520 case err := <-errC:521 cancel()522 require.NoError(t, err)523 }524 checkData := func(name string, expected int64) float64 {525 data := getMetricSum(collector, name)526 expectedDataMin := float64(expected * tc.Iterations)527 expectedDataMax := float64((expected + ts.NumRequests*expectedHeaderMaxLength) * tc.Iterations)528 if data < expectedDataMin || data > expectedDataMax {529 t.Errorf(530 "The %s sum should be in the interval [%f, %f] but was %f",531 name, expectedDataMin, expectedDataMax, data,532 )533 }534 return data535 }536 return checkData(metrics.DataSent.Name, ts.ExpectedDataSent),537 checkData(metrics.DataReceived.Name, ts.ExpectedDataReceived)538 }539 getTestCase := func(t *testing.T, ts testScript, tc testCase) func(t *testing.T) {540 return func(t *testing.T) {541 t.Parallel()542 noReuseSent, noReuseReceived := runTest(t, ts, tc, true)543 reuseSent, reuseReceived := runTest(t, ts, tc, false)544 if noReuseSent < reuseSent {545 t.Errorf("noReuseSent=%f is greater than reuseSent=%f", noReuseSent, reuseSent)546 }547 if noReuseReceived < reuseReceived {548 t.Errorf("noReuseReceived=%f is greater than reuseReceived=%f", noReuseReceived, reuseReceived)549 }550 }551 }552 // This Run will not return until the parallel subtests complete.553 t.Run("group", func(t *testing.T) {554 for tsNum, ts := range testScripts {555 for tcNum, tc := range testCases {556 t.Run(557 fmt.Sprintf("SentReceivedMetrics_script[%d]_case[%d](%d,%d)", tsNum, tcNum, tc.Iterations, tc.VUs),558 getTestCase(t, ts, tc),559 )560 }561 }562 })563}564func TestRunTags(t *testing.T) {565 t.Parallel()566 tb := testutils.NewHTTPMultiBin(t)567 defer tb.Cleanup()568 runTagsMap := map[string]string{"foo": "bar", "test": "mest", "over": "written"}569 runTags := stats.NewSampleTags(runTagsMap)570 script := []byte(tb.Replacer.Replace(`571 import http from "k6/http";572 import ws from "k6/ws";573 import { Counter } from "k6/metrics";574 import { group, check, fail } from "k6";575 let customTags = { "over": "the rainbow" };576 let params = { "tags": customTags};577 let statusCheck = { "status is 200": (r) => r.status === 200 }578 let myCounter = new Counter("mycounter");579 export default function() {580 group("http", function() {581 check(http.get("HTTPSBIN_URL", params), statusCheck, customTags);582 check(http.get("HTTPBIN_URL/status/418", params), statusCheck, customTags);583 })584 group("websockets", function() {585 var response = ws.connect("wss://HTTPSBIN_IP:HTTPSBIN_PORT/ws-echo", params, function (socket) {586 socket.on('open', function open() {587 console.log('ws open and say hello');588 socket.send("hello");589 });590 socket.on('message', function (message) {591 console.log('ws got message ' + message);592 if (message != "hello") {593 fail("Expected to receive 'hello' but got '" + message + "' instead !");594 }595 console.log('ws closing socket...');596 socket.close();597 });598 socket.on('close', function () {599 console.log('ws close');600 });601 socket.on('error', function (e) {602 console.log('ws error: ' + e.error());603 });604 });605 console.log('connect returned');606 check(response, { "status is 101": (r) => r && r.status === 101 }, customTags);607 })608 myCounter.add(1, customTags);609 }610 `))611 r, err := js.New(612 &lib.SourceData{Filename: "/script.js", Data: script},613 afero.NewMemMapFs(),614 lib.RuntimeOptions{},615 )616 require.NoError(t, err)617 options := lib.Options{618 Iterations: null.IntFrom(3),619 VUs: null.IntFrom(2),620 VUsMax: null.IntFrom(2),621 Hosts: tb.Dialer.Hosts,622 RunTags: runTags,623 SystemTags: lib.GetTagSet(lib.DefaultSystemTagList...),624 InsecureSkipTLSVerify: null.BoolFrom(true),625 }626 r.SetOptions(options)627 engine, err := NewEngine(local.New(r), options)628 require.NoError(t, err)629 collector := &dummy.Collector{}630 engine.Collectors = []lib.Collector{collector}631 ctx, cancel := context.WithCancel(context.Background())632 errC := make(chan error)633 go func() { errC <- engine.Run(ctx) }()634 select {635 case <-time.After(10 * time.Second):636 cancel()637 t.Fatal("Test timed out")638 case err := <-errC:639 cancel()640 require.NoError(t, err)641 }642 systemMetrics := []*stats.Metric{643 metrics.VUs, metrics.VUsMax, metrics.Iterations, metrics.IterationDuration,644 metrics.GroupDuration, metrics.DataSent, metrics.DataReceived,645 }646 getExpectedOverVal := func(metricName string) string {647 for _, sysMetric := range systemMetrics {648 if sysMetric.Name == metricName {649 return runTagsMap["over"]650 }651 }652 return "the rainbow"653 }654 for _, s := range collector.Samples {655 for key, expVal := range runTagsMap {656 val, ok := s.Tags.Get(key)657 if key == "over" {658 expVal = getExpectedOverVal(s.Metric.Name)659 }660 assert.True(t, ok)661 assert.Equalf(t, expVal, val, "Wrong tag value in sample for metric %#v", s.Metric)662 }663 }664}665func TestSetupTeardownThresholds(t *testing.T) {666 t.Parallel()667 tb := testutils.NewHTTPMultiBin(t)668 defer tb.Cleanup()669 script := []byte(tb.Replacer.Replace(`670 import http from "k6/http";671 import { check } from "k6";672 import { Counter } from "k6/metrics";673 let statusCheck = { "status is 200": (r) => r.status === 200 }674 let myCounter = new Counter("setup_teardown");675 export let options = {676 iterations: 5,677 thresholds: {678 "setup_teardown": ["count == 2"],679 "iterations": ["count == 5"],680 "http_reqs": ["count == 7"],681 },682 };683 export function setup() {684 check(http.get("HTTPBIN_IP_URL"), statusCheck) && myCounter.add(1);685 };686 export default function () {687 check(http.get("HTTPBIN_IP_URL"), statusCheck);688 };689 export function teardown() {690 check(http.get("HTTPBIN_IP_URL"), statusCheck) && myCounter.add(1);691 };692 `))693 runner, err := js.New(694 &lib.SourceData{Filename: "/script.js", Data: script},695 afero.NewMemMapFs(),696 lib.RuntimeOptions{},697 )698 require.NoError(t, err)699 runner.SetOptions(runner.GetOptions().Apply(lib.Options{700 SystemTags: lib.GetTagSet(lib.DefaultSystemTagList...),701 SetupTimeout: types.NullDurationFrom(3 * time.Second),702 TeardownTimeout: types.NullDurationFrom(3 * time.Second),703 VUs: null.IntFrom(3),704 VUsMax: null.IntFrom(3),705 }))706 engine, err := NewEngine(local.New(runner), runner.GetOptions())707 require.NoError(t, err)708 ctx, cancel := context.WithCancel(context.Background())709 errC := make(chan error)710 go func() { errC <- engine.Run(ctx) }()711 select {712 case <-time.After(10 * time.Second):713 cancel()714 t.Fatal("Test timed out")715 case err := <-errC:716 cancel()717 require.NoError(t, err)718 require.False(t, engine.IsTainted())719 }720}721func TestEmittedMetricsWhenScalingDown(t *testing.T) {722 t.Parallel()723 tb := testutils.NewHTTPMultiBin(t)724 defer tb.Cleanup()725 script := []byte(tb.Replacer.Replace(`726 import http from "k6/http";727 import { sleep } from "k6";728 export let options = {729 systemTags: ["iter", "vu", "url"],730 // Start with 2 VUs for 4 seconds and then quickly scale down to 1 for the next 4s and then quit731 vus: 2,732 vusMax: 2,733 stages: [734 { duration: "4s", target: 2 },735 { duration: "1s", target: 1 },736 { duration: "3s", target: 1 },737 ],738 };739 export default function () {740 console.log("VU " + __VU + " starting iteration #" + __ITER);741 http.get("HTTPBIN_IP_URL/bytes/15000");742 sleep(3.1);743 http.get("HTTPBIN_IP_URL/bytes/15000");744 console.log("VU " + __VU + " ending iteration #" + __ITER);745 };746 `))747 runner, err := js.New(748 &lib.SourceData{Filename: "/script.js", Data: script},749 afero.NewMemMapFs(),750 lib.RuntimeOptions{},751 )752 require.NoError(t, err)753 engine, err := NewEngine(local.New(runner), runner.GetOptions())754 require.NoError(t, err)755 collector := &dummy.Collector{}756 engine.Collectors = []lib.Collector{collector}757 ctx, cancel := context.WithCancel(context.Background())758 errC := make(chan error)759 go func() { errC <- engine.Run(ctx) }()760 select {761 case <-time.After(10 * time.Second):762 cancel()763 t.Fatal("Test timed out")764 case err := <-errC:765 cancel()766 require.NoError(t, err)767 require.False(t, engine.IsTainted())768 }769 // The 1.7 sleep in the default function would cause the first VU to comlete 2 full iterations770 // and stat executing its third one, while the second VU will only fully complete 1 iteration771 // and will be canceled in the middle of its second one.772 assert.Equal(t, 3.0, getMetricSum(collector, metrics.Iterations.Name))773 // That means that we expect to see 8 HTTP requests in total, 3*2=6 from the complete iterations774 // and one each from the two iterations that would be canceled in the middle of their execution775 assert.Equal(t, 8.0, getMetricSum(collector, metrics.HTTPReqs.Name))776 // But we expect to only see the data_received for only 7 of those requests. The data for the 8th777 // request (the 3rd one in the first VU before the test ends) gets cut off by the engine because778 // it's emitted after the test officially ends779 dataReceivedExpectedMin := 15000.0 * 7780 dataReceivedExpectedMax := (15000.0 + expectedHeaderMaxLength) * 7781 dataReceivedActual := getMetricSum(collector, metrics.DataReceived.Name)782 if dataReceivedActual < dataReceivedExpectedMin || dataReceivedActual > dataReceivedExpectedMax {783 t.Errorf(784 "The data_received sum should be in the interval [%f, %f] but was %f",785 dataReceivedExpectedMin, dataReceivedExpectedMax, dataReceivedActual,786 )787 }788 // Also, the interrupted iterations shouldn't affect the average iteration_duration in any way, only789 // complete iterations should be taken into account790 durationCount := float64(getMetricCount(collector, metrics.IterationDuration.Name))791 assert.Equal(t, 3.0, durationCount)792 durationSum := getMetricSum(collector, metrics.IterationDuration.Name)793 assert.InDelta(t, 3.35, durationSum/(1000*durationCount), 0.25)794}795func TestMinIterationDuration(t *testing.T) {796 t.Parallel()797 runner, err := js.New(798 &lib.SourceData{Filename: "/script.js", Data: []byte(`799 import { Counter } from "k6/metrics";800 let testCounter = new Counter("testcounter");801 export let options = {802 minIterationDuration: "1s",803 vus: 2,804 vusMax: 2,...

Full Screen

Full Screen

metrics.go

Source:metrics.go Github

copy

Full Screen

...28}29// WithMetricCount is an option to get the histogram/summary count as metric value.30func WithMetricCount() MetricsOption {31 return func(o *metricsOptions) {32 o.getValue = getMetricCount33 }34}35// WithLabelMatchers is an option to filter only matching series.36func WithLabelMatchers(matchers ...*matchers.Matcher) MetricsOption {37 return func(o *metricsOptions) {38 o.labelMatchers = matchers39 }40}41// WaitMissingMetrics is an option to wait whenever an expected metric is missing. If this42// option is not enabled, will return error on missing metrics.43func WaitMissingMetrics() MetricsOption {44 return func(o *metricsOptions) {45 o.waitMissingMetrics = true46 }47}48// SkipMissingMetrics is an option to skip/ignore whenever an expected metric is missing.49func SkipMissingMetrics() MetricsOption {50 return func(o *metricsOptions) {51 o.skipMissingMetrics = true52 }53}54func buildMetricsOptions(opts []MetricsOption) metricsOptions {55 result := metricsOptions{56 getValue: getMetricValue,57 waitBackoff: &backoff.Config{58 Min: 300 * time.Millisecond,59 Max: 600 * time.Millisecond,60 MaxRetries: 50,61 },62 }63 for _, opt := range opts {64 opt(&result)65 }66 return result67}68func getMetricValue(m *io_prometheus_client.Metric) float64 {69 if m.GetGauge() != nil {70 return m.GetGauge().GetValue()71 } else if m.GetCounter() != nil {72 return m.GetCounter().GetValue()73 } else if m.GetHistogram() != nil {74 return m.GetHistogram().GetSampleSum()75 } else if m.GetSummary() != nil {76 return m.GetSummary().GetSampleSum()77 } else {78 return 079 }80}81func getMetricCount(m *io_prometheus_client.Metric) float64 {82 if m.GetHistogram() != nil {83 return float64(m.GetHistogram().GetSampleCount())84 } else if m.GetSummary() != nil {85 return float64(m.GetSummary().GetSampleCount())86 } else {87 return 088 }89}90func getValues(metrics []*io_prometheus_client.Metric, opts metricsOptions) []float64 {91 values := make([]float64, 0, len(metrics))92 for _, m := range metrics {93 values = append(values, opts.getValue(m))94 }95 return values...

Full Screen

Full Screen

engine.go

Source:engine.go Github

copy

Full Screen

1package aggregator2import (3 "os"4 "github.com/rs/zerolog"5)6var logger zerolog.Logger = zerolog.New(os.Stderr).With().7 Str("source", "ENG").8 Timestamp().9 Logger()10// Engine is the core calculcation engine for counting11type Engine struct {12 Nsm *NamespaceManager13}14// NewEngine creates a new engine15func NewEngine(nsm *NamespaceManager) Engine {16 e := Engine{Nsm: nsm}17 return e18}19// HandleRawEvent is the handler for any event. It checks whether the event is defined in config20// and updates the relevant metrics21func (e Engine) HandleRawEvent(rawEvent map[string]interface{}, namespace string) error {22 // Event must have an id to identify what event it is23 id, idExists := rawEvent["id"]24 if !idExists {25 return &InvalidEventIDError{}26 }27 // Id must be an int28 idTyped, isInt := id.(int)29 if !isInt {30 return &InvalidEventIDError{}31 }32 // Get the config for the event33 // TODO Add RW lock for events34 eventConfig, configExists := e.Nsm.EventConfigsByNamespace[namespace][idTyped]35 if !configExists {36 return &EventConfigNotFoundError{}37 }38 // Validate against the config39 event, err := eventConfig.validate(rawEvent)40 if err != nil {41 return err42 }43 // Check namespace44 e.Nsm.NsDataLck.RLock()45 defer e.Nsm.NsDataLck.RUnlock()46 if _, nsExists := e.Nsm.ActiveNamespaces[namespace]; !nsExists {47 return &NamespaceNotFoundError{}48 }49 res := e.handleEvent(*event, namespace)50 return res51}52func (e Engine) handleEvent(event event, namespace string) error {53 e.Nsm.namespaceRLock(namespace)54 defer e.Nsm.namespaceRUnlock(namespace)55 // Get the metric configs for this event56 metricConfigs := e.getMetricConfigs(event, namespace)57 if len(metricConfigs) == 0 {58 return &NoMetricsFoundError{}59 }60 // Handle this event for each of these metric configs61 for _, metricConfig := range metricConfigs {62 _, isNew := metricConfig.handleEvent(event, namespace)63 if isNew {64 e.Nsm.IncrementNumKeys(namespace, metricConfig.ID)65 }66 }67 return nil68}69func (e Engine) getMetricConfigs(event event, namespace string) []*metricConfig {70 configs := []*metricConfig{}71 e.Nsm.NsDataLck.RLock()72 // Get all configs in the specified namespace73 // Check if namespace active on this node74 if _, exists := e.Nsm.ActiveNamespaces[namespace]; exists {75 specificNamespace, namespaceExists := e.Nsm.EventToMetricMap[namespace]76 if namespaceExists {77 namespaceConfigs, namespaceConfigsExist := specificNamespace[event.ID]78 if namespaceConfigsExist {79 configs = append(configs, namespaceConfigs...)80 }81 }82 }83 e.Nsm.NsDataLck.RUnlock()84 return configs85}86// GetMetricCount gets the value for a given metric87func (e Engine) GetMetricCount(ns string, metricKey int, metricID int) MetricCountResult {88 mcs, namespaceExists := e.Nsm.MetricConfigsByNamespace[ns]89 if !namespaceExists {90 return MetricCountResult{91 Err: &NamespaceNotFoundError{},92 Count: 0,93 }94 }95 mc, mcExists := mcs[metricID]96 if !mcExists {97 return MetricCountResult{98 Err: &MetricConfigNotFoundError{},99 Count: 0,100 }101 }102 return mc.getCount(metricKey, ns)103}...

Full Screen

Full Screen

getMetricCount

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 urlClient := local.New(coredataUrl)4 coredataClient := coredata.NewCoreDataClient(5 types.EndpointParams{6 },7 count, err := coredataClient.EventCountForDeviceName(deviceName)8 if err != nil {9 fmt.Println(err)10 } else {11 fmt.Println("Count of metrics for device", deviceName, "is", count)12 }13}

Full Screen

Full Screen

getMetricCount

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 metric.Fields = common.MapStr{4 "cluster_uuid": common.MapStr{5 },6 "status": common.MapStr{7 },8 "indices": common.MapStr{9 "count": common.MapStr{10 },11 },12 "nodes": common.MapStr{13 "count": common.MapStr{14 },15 },16 }17 fmt.Println(metric.getMetricCount())18}

Full Screen

Full Screen

getMetricCount

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 core := metricdef.NewCore()4 metricDef := metricdef.New("test", 1, 1, "avg")5 core.Add(metricDef)6 count := core.GetMetricCount()7 fmt.Println("Metric Count: ", count)8 core.Remove(metricDef)9 count = core.GetMetricCount()10 fmt.Println("Metric Count: ", count)11}

Full Screen

Full Screen

getMetricCount

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(metrics.GetMetricCount())4}5import (6func main() {7 fmt.Println(metrics.GetMetricCount())8 metrics.ResetMetricCount()9 fmt.Println(metrics.GetMetricCount())10 metrics.ResetMetricCount(10)11 fmt.Println(metrics.GetMetricCount())12}13import (14func main() {15 fmt.Println(metrics.GetMetricCount())16}17import (18func main() {19 fmt.Println(metrics.GetMetricCount())20}

Full Screen

Full Screen

getMetricCount

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 var getMetricCountMethodSignature = "func() int"4 getMetricCountMethodPtr = GetMethodPtr(coreClass, getMetricCountMethod, getMetricCountMethodSignature)5 var getMetricCountMethodFunc = *(*func() int)(unsafe.Pointer(getMetricCountMethodPtr))6 metricCount = getMetricCountMethodFunc()7 fmt.Println(metricCount)8}9func GetMethodPtr(class string, method string, methodSignature string) uintptr {10 var classType = reflect.TypeOf(class)11 var methodValue = classType.MethodByName(method)12 var methodSignatureType = reflect.TypeOf(methodSignature)13 if methodType.String() == methodSignatureType.String() {14 var methodPtr = methodValue.Func.Pointer()15 }16}17import (18func main() {19 var getMetricCountMethodSignature = "func() int"20 getMetricCountMethodPtr = GetMethodPtr(coreClass, getMetricCountMethod, getMetricCountMethodSignature)21 var getMetricCountMethodFunc = *(*func() int)(

Full Screen

Full Screen

getMetricCount

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 core := core.NewCore()4 metricCount := core.GetMetricCount()5 fmt.Println(metricCount)6}7import (8func main() {9 core := core.NewCore()10 metricCount := core.GetMetricCount()11 fmt.Println(metricCount)12}13import (14func main() {15 core := core.NewCore()16 metricCount := core.GetMetricCount()17 fmt.Println(metricCount)18}19import (20func main() {21 core := core.NewCore()22 metricCount := core.GetMetricCount()23 fmt.Println(metricCount)24}25import (26func main() {27 core := core.NewCore()28 metricCount := core.GetMetricCount()29 fmt.Println(metricCount)30}31import (32func main() {33 core := core.NewCore()

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