Best K6 code snippet using metrics.GetSamples
promql_test.go
Source:promql_test.go
...202 Query: `metric{source_id="some-id"}`,203 },204 )205 Expect(err).NotTo(HaveOccurred())206 Expect(r.GetVector().GetSamples()).To(HaveLen(3))207 Eventually(spyDataReader.ReadSourceIDs).Should(208 ConsistOf("some-id"),209 )210 Expect(spyDataReader.ReadEnvelopeTypes()).To(HaveLen(1))211 Expect(spyDataReader.ReadEnvelopeTypes()[0]).To(Equal(212 []logcache_v1.EnvelopeType{213 logcache_v1.EnvelopeType_GAUGE,214 logcache_v1.EnvelopeType_COUNTER,215 logcache_v1.EnvelopeType_TIMER,216 },217 ),218 )219 })220 Context("when metric names contain unsupported characters", func() {221 It("converts counter metric names to proper promql format", func() {222 now := time.Now()223 spyDataReader.readResults = [][]*loggregator_v2.Envelope{224 {225 {226 SourceId: "some-id-1",227 Timestamp: now.UnixNano(),228 Message: &loggregator_v2.Envelope_Counter{229 Counter: &loggregator_v2.Counter{230 Name: "some-metric$count",231 Total: 104,232 },233 },234 Tags: map[string]string{235 "a": "tag-a",236 "b": "tag-b",237 },238 },239 },240 {241 {242 SourceId: "some-id-2",243 Timestamp: now.UnixNano(),244 Message: &loggregator_v2.Envelope_Counter{245 Counter: &loggregator_v2.Counter{246 Name: "some|metric#count",247 Total: 100,248 },249 },250 Tags: map[string]string{251 "a": "tag-a",252 "b": "tag-b",253 },254 },255 },256 }257 for range spyDataReader.readResults {258 spyDataReader.readErrs = append(spyDataReader.readErrs, nil)259 }260 r, err := q.InstantQuery(261 context.Background(),262 &logcache_v1.PromQL_InstantQueryRequest{263 Query: `some_metric_count{source_id="some-id-1"} + ignoring (source_id) some_metric_count{source_id="some-id-2"}`,264 },265 )266 Expect(err).NotTo(HaveOccurred())267 Expect(r.GetVector().GetSamples()).To(HaveLen(1))268 Expect(r.GetVector().GetSamples()[0].Point.Value).To(Equal(204.0))269 Eventually(spyDataReader.ReadSourceIDs).Should(270 ConsistOf("some-id-1", "some-id-2"),271 )272 })273 It("converts timer metric names to proper promql format", func() {274 hourAgo := time.Now().Add(-time.Hour)275 spyDataReader.readResults = [][]*loggregator_v2.Envelope{276 {277 {278 SourceId: "some-id-1",279 Timestamp: hourAgo.UnixNano(),280 Message: &loggregator_v2.Envelope_Timer{281 Timer: &loggregator_v2.Timer{282 Name: "some-metric$time",283 Start: 199,284 Stop: 201,285 },286 },287 Tags: map[string]string{288 "a": "tag-a",289 "b": "tag-b",290 },291 },292 },293 {294 {295 SourceId: "some-id-2",296 Timestamp: hourAgo.UnixNano(),297 Message: &loggregator_v2.Envelope_Timer{298 Timer: &loggregator_v2.Timer{299 Name: "some|metric#time",300 Start: 299,301 Stop: 302,302 },303 },304 Tags: map[string]string{305 "a": "tag-a",306 "b": "tag-b",307 },308 },309 },310 }311 for range spyDataReader.readResults {312 spyDataReader.readErrs = append(spyDataReader.readErrs, nil)313 }314 r, err := q.InstantQuery(315 context.Background(),316 &logcache_v1.PromQL_InstantQueryRequest{317 Query: `some_metric_time{source_id="some-id-1"} + ignoring(source_id) some_metric_time{source_id="some-id-2"}`,318 Time: testing.FormatTimeWithDecimalMillis(hourAgo),319 },320 )321 Expect(err).NotTo(HaveOccurred())322 Expect(r.GetVector().GetSamples()).To(HaveLen(1))323 Expect(r.GetVector().GetSamples()[0].Point.Value).To(Equal(5.0))324 Eventually(spyDataReader.ReadSourceIDs).Should(325 ConsistOf("some-id-1", "some-id-2"),326 )327 })328 It("converts gauge metric names to proper promql format", func() {329 now := time.Now()330 // hourAgo := time.Now().Add(-time.Hour)331 spyDataReader.readResults = [][]*loggregator_v2.Envelope{332 {333 {334 SourceId: "some-id-1",335 Timestamp: now.UnixNano(),336 Message: &loggregator_v2.Envelope_Gauge{337 Gauge: &loggregator_v2.Gauge{338 Metrics: map[string]*loggregator_v2.GaugeValue{339 "some-metric$value": {Unit: "thing", Value: 99},340 },341 },342 },343 Tags: map[string]string{344 "a": "tag-a",345 "b": "tag-b",346 },347 },348 },349 {350 {351 SourceId: "some-id-2",352 Timestamp: now.UnixNano(),353 Message: &loggregator_v2.Envelope_Gauge{354 Gauge: &loggregator_v2.Gauge{355 Metrics: map[string]*loggregator_v2.GaugeValue{356 "some|metric#value": {Unit: "thing", Value: 199},357 },358 },359 },360 Tags: map[string]string{361 "a": "tag-a",362 "b": "tag-b",363 },364 },365 },366 {367 {368 SourceId: "some-id-3",369 Timestamp: now.UnixNano(),370 Message: &loggregator_v2.Envelope_Gauge{371 Gauge: &loggregator_v2.Gauge{372 Metrics: map[string]*loggregator_v2.GaugeValue{373 "some.metric+value": {Unit: "thing", Value: 299},374 },375 },376 },377 Tags: map[string]string{378 "a": "tag-a",379 "b": "tag-b",380 },381 },382 },383 }384 for range spyDataReader.readResults {385 spyDataReader.readErrs = append(spyDataReader.readErrs, nil)386 }387 r, err := q.InstantQuery(388 context.Background(),389 &logcache_v1.PromQL_InstantQueryRequest{390 Query: `some_metric_value{source_id="some-id-1"} + ignoring (source_id) some_metric_value{source_id="some-id-2"} + ignoring (source_id) some_metric_value{source_id="some-id-3"}`,391 Time: testing.FormatTimeWithDecimalMillis(now),392 },393 )394 Expect(err).ToNot(HaveOccurred())395 Expect(r.GetVector().GetSamples()).To(HaveLen(1))396 Expect(r.GetVector().GetSamples()[0].Point.Value).To(Equal(597.0))397 })398 })399 Context("When using an InstantQuery", func() {400 It("returns a scalar", func() {401 r, err := q.InstantQuery(context.Background(), &logcache_v1.PromQL_InstantQueryRequest{Query: `7*9`})402 Expect(err).ToNot(HaveOccurred())403 Expect(testing.ParseTimeWithDecimalMillis(r.GetScalar().GetTime())).To(404 BeTemporally("~", time.Now(), time.Second),405 )406 Expect(r.GetScalar().GetValue()).To(Equal(63.0))407 })408 It("returns a vector", func() {409 hourAgo := time.Now().Add(-time.Hour)410 spyDataReader.readErrs = []error{nil, nil}411 spyDataReader.readResults = [][]*loggregator_v2.Envelope{412 {{413 SourceId: "some-id-1",414 Timestamp: hourAgo.UnixNano(),415 Message: &loggregator_v2.Envelope_Counter{416 Counter: &loggregator_v2.Counter{417 Name: "metric",418 Total: 99,419 },420 },421 Tags: map[string]string{422 "a": "tag-a",423 "b": "tag-b",424 },425 }},426 {{427 SourceId: "some-id-2",428 Timestamp: hourAgo.UnixNano(),429 Message: &loggregator_v2.Envelope_Counter{430 Counter: &loggregator_v2.Counter{431 Name: "metric",432 Total: 101,433 },434 },435 Tags: map[string]string{436 "a": "tag-a",437 "b": "tag-b",438 },439 }},440 }441 r, err := q.InstantQuery(442 context.Background(),443 &logcache_v1.PromQL_InstantQueryRequest{444 Time: testing.FormatTimeWithDecimalMillis(hourAgo),445 Query: `metric{source_id="some-id-1"} + ignoring (source_id) metric{source_id="some-id-2"}`,446 },447 )448 Expect(err).ToNot(HaveOccurred())449 Expect(r.GetVector().GetSamples()).To(HaveLen(1))450 actualTime := r.GetVector().GetSamples()[0].Point.Time451 Expect(testing.ParseTimeWithDecimalMillis(actualTime)).To(BeTemporally("~", hourAgo, time.Second))452 Expect(r.GetVector().GetSamples()).To(Equal([]*logcache_v1.PromQL_Sample{453 {454 Metric: map[string]string{455 "a": "tag-a",456 "b": "tag-b",457 },458 Point: &logcache_v1.PromQL_Point{459 Time: actualTime,460 Value: 200,461 },462 },463 }))464 Eventually(spyDataReader.ReadSourceIDs).Should(465 ConsistOf("some-id-1", "some-id-2"),466 )467 Expect(testing.ParseTimeWithDecimalMillis(actualTime)).To(BeTemporally("~", spyDataReader.readEnds[0]))468 Expect(469 spyDataReader.readEnds[0].Sub(spyDataReader.readStarts[0]),470 ).To(Equal(time.Minute*5 + time.Second))471 })472 It("returns a matrix", func() {473 now := time.Now()474 spyDataReader.readErrs = []error{nil}475 spyDataReader.readResults = [][]*loggregator_v2.Envelope{476 {{477 SourceId: "some-id-1",478 InstanceId: "0",479 Timestamp: now.UnixNano(),480 Message: &loggregator_v2.Envelope_Counter{481 Counter: &loggregator_v2.Counter{482 Name: "metric",483 Total: 99,484 },485 },486 Tags: map[string]string{487 "a": "tag-a",488 "b": "tag-b",489 },490 }},491 }492 r, err := q.InstantQuery(493 context.Background(),494 &logcache_v1.PromQL_InstantQueryRequest{Query: `metric{source_id="some-id-1"}[5m]`},495 )496 Expect(err).ToNot(HaveOccurred())497 Expect(r.GetMatrix().GetSeries()).To(Equal([]*logcache_v1.PromQL_Series{498 {499 Metric: map[string]string{500 "a": "tag-a",501 "b": "tag-b",502 "source_id": "some-id-1",503 "instance_id": "0",504 },505 Points: []*logcache_v1.PromQL_Point{{506 Time: testing.FormatTimeWithDecimalMillis(now.Truncate(time.Second)),507 Value: 99,508 }},509 },510 }))511 Eventually(spyDataReader.ReadSourceIDs).Should(512 ConsistOf("some-id-1"),513 )514 })515 It("filters for correct counter metric name and label", func() {516 now := time.Now()517 spyDataReader.readErrs = []error{nil}518 spyDataReader.readResults = [][]*loggregator_v2.Envelope{519 {520 {521 SourceId: "some-id-1",522 Timestamp: now.UnixNano(),523 Message: &loggregator_v2.Envelope_Counter{524 Counter: &loggregator_v2.Counter{525 Name: "metric",526 Total: 99,527 },528 },529 Tags: map[string]string{530 "a": "tag-a",531 "b": "tag-b",532 },533 },534 {535 SourceId: "some-id-1",536 Timestamp: now.UnixNano(),537 Message: &loggregator_v2.Envelope_Counter{538 Counter: &loggregator_v2.Counter{539 Name: "wrongname",540 Total: 101,541 },542 },543 Tags: map[string]string{544 "a": "tag-a",545 "b": "tag-b",546 },547 },548 {549 SourceId: "some-id-1",550 Timestamp: now.UnixNano(),551 Message: &loggregator_v2.Envelope_Counter{552 Counter: &loggregator_v2.Counter{553 Name: "metric",554 Total: 103,555 },556 },557 Tags: map[string]string{558 "a": "wrong-tag",559 "b": "tag-b",560 },561 },562 },563 }564 r, err := q.InstantQuery(565 context.Background(),566 &logcache_v1.PromQL_InstantQueryRequest{Query: `metric{source_id="some-id-1",a="tag-a"}`},567 )568 Expect(err).ToNot(HaveOccurred())569 Expect(r.GetVector().GetSamples()).To(HaveLen(1))570 Expect(r.GetVector().GetSamples()[0].Point.Value).To(Equal(99.0))571 })572 It("filters for correct timer metric name", func() {573 now := time.Now()574 spyDataReader.readErrs = []error{nil}575 spyDataReader.readResults = [][]*loggregator_v2.Envelope{576 {577 {578 SourceId: "some-id-1",579 Timestamp: now.UnixNano(),580 Message: &loggregator_v2.Envelope_Timer{581 Timer: &loggregator_v2.Timer{582 Name: "metric",583 Start: 99,584 Stop: 101,585 },586 },587 Tags: map[string]string{588 "a": "tag-a",589 "b": "tag-b",590 },591 },592 {593 SourceId: "some-id-1",594 Timestamp: now.UnixNano(),595 Message: &loggregator_v2.Envelope_Timer{596 Timer: &loggregator_v2.Timer{597 Name: "wrongname",598 Start: 99,599 Stop: 101,600 },601 },602 Tags: map[string]string{603 "a": "tag-a",604 "b": "tag-b",605 },606 },607 },608 }609 r, err := q.InstantQuery(610 context.Background(),611 &logcache_v1.PromQL_InstantQueryRequest{Query: `metric{source_id="some-id-1"}`},612 )613 Expect(err).ToNot(HaveOccurred())614 Expect(r.GetVector().GetSamples()).To(HaveLen(1))615 Expect(r.GetVector().GetSamples()[0].Point.Value).To(Equal(2.0))616 })617 It("filters for correct gauge metric name", func() {618 now := time.Now()619 spyDataReader.readErrs = []error{nil}620 spyDataReader.readResults = [][]*loggregator_v2.Envelope{621 {622 {623 SourceId: "some-id-1",624 Timestamp: now.UnixNano(),625 Message: &loggregator_v2.Envelope_Gauge{626 Gauge: &loggregator_v2.Gauge{627 Metrics: map[string]*loggregator_v2.GaugeValue{628 "metric": {Unit: "thing", Value: 99},629 "othermetric": {Unit: "thing", Value: 103},630 },631 },632 },633 Tags: map[string]string{634 "a": "tag-a",635 "b": "tag-b",636 },637 },638 {639 SourceId: "some-id-1",640 Timestamp: now.UnixNano(),641 Message: &loggregator_v2.Envelope_Gauge{642 Gauge: &loggregator_v2.Gauge{643 Metrics: map[string]*loggregator_v2.GaugeValue{644 "wrongname": {Unit: "thing", Value: 101},645 },646 },647 },648 Tags: map[string]string{649 "a": "tag-a",650 "b": "tag-b",651 },652 },653 },654 }655 r, err := q.InstantQuery(656 context.Background(),657 &logcache_v1.PromQL_InstantQueryRequest{Query: `metric{source_id="some-id-1"}`},658 )659 Expect(err).ToNot(HaveOccurred())660 Expect(r.GetVector().GetSamples()).To(HaveLen(1))661 Expect(r.GetVector().GetSamples()[0].Point.Value).To(Equal(99.0))662 })663 It("captures the query time as a metric", func() {664 _, err := q.InstantQuery(665 context.Background(),666 &logcache_v1.PromQL_InstantQueryRequest{Query: `metric{source_id="some-id-1"}`},667 )668 Expect(err).ToNot(HaveOccurred())669 Eventually(func() float64 {670 return spyMetrics.GetMetricValue("log_cache_promql_instant_query_time", nil)671 }).ShouldNot(BeZero())672 })673 It("expands requests filtered for multiple source IDs", func() {674 now := time.Now()675 spyDataReader.readErrs = []error{nil, nil}676 spyDataReader.readResults = [][]*loggregator_v2.Envelope{677 {678 {679 SourceId: "some-id-1",680 Timestamp: now.UnixNano(),681 Message: &loggregator_v2.Envelope_Gauge{682 Gauge: &loggregator_v2.Gauge{683 Metrics: map[string]*loggregator_v2.GaugeValue{684 "metric": {Unit: "thing", Value: 99},685 },686 },687 },688 },689 },690 {691 {692 SourceId: "some-id-2",693 Timestamp: now.UnixNano(),694 Message: &loggregator_v2.Envelope_Gauge{695 Gauge: &loggregator_v2.Gauge{696 Metrics: map[string]*loggregator_v2.GaugeValue{697 "metric": {Unit: "thing", Value: 101},698 },699 },700 },701 },702 },703 }704 result, err := q.InstantQuery(705 context.Background(),706 &logcache_v1.PromQL_InstantQueryRequest{Query: `metric{source_id=~"some-id-1|some-id-2"}`},707 )708 Expect(err).ToNot(HaveOccurred())709 Eventually(spyDataReader.ReadSourceIDs).Should(ConsistOf("some-id-1", "some-id-2"))710 Expect(func() []map[string]string {711 var metrics []map[string]string712 for _, sample := range result.GetVector().GetSamples() {713 metrics = append(metrics, sample.GetMetric())714 }715 return metrics716 }()).To(ConsistOf(717 HaveKeyWithValue("source_id", "some-id-1"),718 HaveKeyWithValue("source_id", "some-id-2"),719 ))720 })721 It("returns an error for an invalid query", func() {722 _, err := q.InstantQuery(723 context.Background(),724 &logcache_v1.PromQL_InstantQueryRequest{Query: `invalid.query`},725 )726 Expect(err).To(HaveOccurred())...
response_callback_test.go
Source:response_callback_test.go
...270 assert.NoError(t, err)271 bufSamples := stats.GetBufferedSamples(samples)272 reqsCount := 0273 for _, container := range bufSamples {274 for _, sample := range container.GetSamples() {275 if sample.Metric.Name == "http_reqs" {276 reqsCount++277 }278 }279 }280 require.Equal(t, len(testCase.expectedSamples), reqsCount)281 for i, expectedSample := range testCase.expectedSamples {282 assertRequestMetricsEmittedSingle(t, bufSamples[i], expectedSample.tags, expectedSample.metrics, nil)283 }284 })285 }286}287func TestResponseCallbackBatch(t *testing.T) {288 t.Parallel()289 tb, _, samples, rt, ctx := newRuntime(t)290 sr := tb.Replacer.Replace291 httpModule := new(GlobalHTTP).NewModuleInstancePerVU().(*HTTP)292 rt.Set("http", common.Bind(rt, httpModule, ctx))293 HTTPMetricsWithoutFailed := []string{294 metrics.HTTPReqsName,295 metrics.HTTPReqBlockedName,296 metrics.HTTPReqConnectingName,297 metrics.HTTPReqDurationName,298 metrics.HTTPReqReceivingName,299 metrics.HTTPReqWaitingName,300 metrics.HTTPReqSendingName,301 metrics.HTTPReqTLSHandshakingName,302 }303 allHTTPMetrics := append(HTTPMetricsWithoutFailed, metrics.HTTPReqFailedName)304 // IMPORTANT: the tests here depend on the fact that the url they hit can be ordered in the same305 // order as the expectedSamples even if they are made concurrently306 testCases := map[string]struct {307 code string308 expectedSamples []expectedSample309 }{310 "basic": {311 code: `312 http.batch([["GET", "HTTPBIN_URL/status/200", null, {responseCallback: null}],313 ["GET", "HTTPBIN_URL/status/201"],314 ["GET", "HTTPBIN_URL/status/202", null, {responseCallback: http.expectedStatuses(4)}],315 ["GET", "HTTPBIN_URL/status/405", null, {responseCallback: http.expectedStatuses(405)}],316 ]);`,317 expectedSamples: []expectedSample{318 {319 tags: map[string]string{320 "method": "GET",321 "url": sr("HTTPBIN_URL/status/200"),322 "name": sr("HTTPBIN_URL/status/200"),323 "status": "200",324 "group": "",325 "proto": "HTTP/1.1",326 },327 metrics: HTTPMetricsWithoutFailed,328 },329 {330 tags: map[string]string{331 "method": "GET",332 "url": sr("HTTPBIN_URL/status/201"),333 "name": sr("HTTPBIN_URL/status/201"),334 "status": "201",335 "group": "",336 "expected_response": "true",337 "proto": "HTTP/1.1",338 },339 metrics: allHTTPMetrics,340 },341 {342 tags: map[string]string{343 "method": "GET",344 "url": sr("HTTPBIN_URL/status/202"),345 "name": sr("HTTPBIN_URL/status/202"),346 "status": "202",347 "group": "",348 "expected_response": "false",349 "proto": "HTTP/1.1",350 },351 metrics: allHTTPMetrics,352 },353 {354 tags: map[string]string{355 "method": "GET",356 "url": sr("HTTPBIN_URL/status/405"),357 "name": sr("HTTPBIN_URL/status/405"),358 "status": "405",359 "error_code": "1405",360 "group": "",361 "expected_response": "true",362 "proto": "HTTP/1.1",363 },364 metrics: allHTTPMetrics,365 },366 },367 },368 }369 for name, testCase := range testCases {370 testCase := testCase371 t.Run(name, func(t *testing.T) {372 httpModule.responseCallback = defaultExpectedStatuses.match373 _, err := rt.RunString(sr(testCase.code))374 assert.NoError(t, err)375 bufSamples := stats.GetBufferedSamples(samples)376 reqsCount := 0377 for _, container := range bufSamples {378 for _, sample := range container.GetSamples() {379 if sample.Metric.Name == "http_reqs" {380 reqsCount++381 }382 }383 }384 sort.Slice(bufSamples, func(i, j int) bool {385 iURL, _ := bufSamples[i].GetSamples()[0].Tags.Get("url")386 jURL, _ := bufSamples[j].GetSamples()[0].Tags.Get("url")387 return iURL < jURL388 })389 require.Equal(t, len(testCase.expectedSamples), reqsCount)390 for i, expectedSample := range testCase.expectedSamples {391 assertRequestMetricsEmittedSingle(t, bufSamples[i], expectedSample.tags, expectedSample.metrics, nil)392 }393 })394 }395}396func TestResponseCallbackInActionWithoutPassedTag(t *testing.T) {397 t.Parallel()398 tb, state, samples, rt, ctx := newRuntime(t)399 sr := tb.Replacer.Replace400 allHTTPMetrics := []string{401 metrics.HTTPReqsName,402 metrics.HTTPReqFailedName,403 metrics.HTTPReqBlockedName,404 metrics.HTTPReqConnectingName,405 metrics.HTTPReqDurationName,406 metrics.HTTPReqReceivingName,407 metrics.HTTPReqSendingName,408 metrics.HTTPReqWaitingName,409 metrics.HTTPReqTLSHandshakingName,410 }411 deleteSystemTag(state, stats.TagExpectedResponse.String())412 httpModule := new(GlobalHTTP).NewModuleInstancePerVU().(*HTTP)413 rt.Set("http", common.Bind(rt, httpModule, ctx))414 _, err := rt.RunString(sr(`http.request("GET", "HTTPBIN_URL/redirect/1", null, {responseCallback: http.expectedStatuses(200)});`))415 assert.NoError(t, err)416 bufSamples := stats.GetBufferedSamples(samples)417 reqsCount := 0418 for _, container := range bufSamples {419 for _, sample := range container.GetSamples() {420 if sample.Metric.Name == "http_reqs" {421 reqsCount++422 }423 }424 }425 require.Equal(t, 2, reqsCount)426 tags := map[string]string{427 "method": "GET",428 "url": sr("HTTPBIN_URL/redirect/1"),429 "name": sr("HTTPBIN_URL/redirect/1"),430 "status": "302",431 "group": "",432 "proto": "HTTP/1.1",433 }434 assertRequestMetricsEmittedSingle(t, bufSamples[0], tags, allHTTPMetrics, func(sample stats.Sample) {435 if sample.Metric.Name == metrics.HTTPReqFailedName {436 require.EqualValues(t, sample.Value, 1)437 }438 })439 tags["url"] = sr("HTTPBIN_URL/get")440 tags["name"] = tags["url"]441 tags["status"] = "200"442 assertRequestMetricsEmittedSingle(t, bufSamples[1], tags, allHTTPMetrics, func(sample stats.Sample) {443 if sample.Metric.Name == metrics.HTTPReqFailedName {444 require.EqualValues(t, sample.Value, 0)445 }446 })447}448func TestDigestWithResponseCallback(t *testing.T) {449 t.Parallel()450 tb, _, samples, rt, ctx := newRuntime(t)451 httpModule := new(GlobalHTTP).NewModuleInstancePerVU().(*HTTP)452 rt.Set("http", common.Bind(rt, httpModule, ctx))453 urlWithCreds := tb.Replacer.Replace(454 "http://testuser:testpwd@HTTPBIN_IP:HTTPBIN_PORT/digest-auth/auth/testuser/testpwd",455 )456 allHTTPMetrics := []string{457 metrics.HTTPReqsName,458 metrics.HTTPReqFailedName,459 metrics.HTTPReqBlockedName,460 metrics.HTTPReqConnectingName,461 metrics.HTTPReqDurationName,462 metrics.HTTPReqReceivingName,463 metrics.HTTPReqSendingName,464 metrics.HTTPReqWaitingName,465 metrics.HTTPReqTLSHandshakingName,466 }467 _, err := rt.RunString(fmt.Sprintf(`468 var res = http.get(%q, { auth: "digest" });469 if (res.status !== 200) { throw new Error("wrong status: " + res.status); }470 if (res.error_code !== 0) { throw new Error("wrong error code: " + res.error_code); }471 `, urlWithCreds))472 require.NoError(t, err)473 bufSamples := stats.GetBufferedSamples(samples)474 reqsCount := 0475 for _, container := range bufSamples {476 for _, sample := range container.GetSamples() {477 if sample.Metric.Name == "http_reqs" {478 reqsCount++479 }480 }481 }482 require.Equal(t, 2, reqsCount)483 urlRaw := tb.Replacer.Replace(484 "http://HTTPBIN_IP:HTTPBIN_PORT/digest-auth/auth/testuser/testpwd")485 tags := map[string]string{486 "method": "GET",487 "url": urlRaw,488 "name": urlRaw,489 "status": "401",490 "group": "",...
GetSamples
Using AI Code Generation
1import (2func main() {3 histogram := promauto.NewHistogram(prometheus.HistogramOpts{4 })5 counter := promauto.NewCounter(prometheus.CounterOpts{6 })7 for i := 0; i < 100; i++ {8 counter.Inc()9 }10 for i := 0; i < 100; i++ {11 histogram.Observe(float64(i))12 }13 http.Handle("/metrics", promhttp.Handler())14 fmt.Println("Beginning to serve on port :2112")15 http.ListenAndServe(":2112", nil)16}17import (18func main() {19 histogram := promauto.NewHistogram(prometheus.HistogramOpts{20 })21 counter := promauto.NewCounter(prometheus.CounterOpts{22 })23 for i := 0; i < 100; i++ {24 counter.Inc()25 }26 for i := 0; i < 100; i++ {27 histogram.Observe(float64(i))28 }29 http.Handle("/metrics",
GetSamples
Using AI Code Generation
1import (2func main() {3 http.Handle("/metrics", promhttp.Handler())4 go func() {5 http.ListenAndServe(":8080", nil)6 }()7 opsProcessed := promauto.NewGauge(prometheus.GaugeOpts{8 })9 opsProcessed.Inc()10 fmt.Println("Data:", opsProcessed.GetSamples())11}12Data: map[{}:{2019-10-01 09:20:51.489 +0000 UTC 1}]13import (14func main() {15 http.Handle("/metrics", promhttp.Handler())16 go func() {17 http.ListenAndServe(":8080", nil)18 }()19 opsProcessed := promauto.NewGauge(prometheus.GaugeOpts{20 })21 opsProcessed.Inc()22 fmt.Println("Data:", opsProcessed.GetSamples())23}24Data: map[{}:{2019-10-01 09:20:51.489 +0000 UTC 1}]25import (26func main() {27 http.Handle("/metrics", promhttp.Handler())28 go func() {29 http.ListenAndServe(":8080", nil)30 }()
GetSamples
Using AI Code Generation
1import (2var (3 testCounter = promauto.NewCounter(prometheus.CounterOpts{4 })5func main() {6 go func() {7 for {8 testCounter.Inc()9 time.Sleep(time.Second)10 }11 }()12 http.Handle("/metrics", promhttp.Handler())13 http.ListenAndServe(":8080", nil)14}15import (16var (17 testCounter = promauto.NewCounter(prometheus.CounterOpts{18 })19func main() {20 go func() {21 for {22 testCounter.Inc()23 time.Sleep(time.Second)24 }25 }()26 http.Handle("/metrics", promhttp.Handler())27 http.ListenAndServe(":8080", nil)28}29import (30var (31 testCounter = promauto.NewCounter(prometheus.CounterOpts{32 })33func main() {34 go func() {
GetSamples
Using AI Code Generation
1import (2var (3 registry = prometheus.NewRegistry()4 counter = promauto.With(registry).NewCounter(prometheus.CounterOpts{5 })6func main() {7 registry.MustRegister(prometheus.NewBuildInfoCollector())8 registry.MustRegister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))9 registry.MustRegister(prometheus.NewGoCollector())10 http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))11 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {12 counter.Inc()13 })14 log.Fatal(http.ListenAndServe(":8080", nil))15}16import (17var (18 registry = prometheus.NewRegistry()19 counter = promauto.With(registry).NewCounter(prometheus.CounterOpts{20 })21func main() {22 registry.MustRegister(prometheus.NewBuildInfoCollector())23 registry.MustRegister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))24 registry.MustRegister(prometheus.NewGoCollector())25 http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))
GetSamples
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, world.")4}5import (6func main() {7 fmt.Println("Hello, world.")8}9import (10func main() {11 fmt.Println("Hello, world.")12}13import (14func main() {15 fmt.Println("Hello, world.")16}17import (18func main() {19 fmt.Println("Hello, world.")20}21import (22func main() {23 fmt.Println("Hello, world.")24}25import (26func main() {27 fmt.Println("Hello, world.")28}29import (30func main() {31 fmt.Println("Hello, world.")32}33import (34func main() {35 fmt.Println("Hello, world.")36}37import (38func main() {39 fmt.Println("Hello, world.")40}41import (42func main() {43 fmt.Println("Hello, world.")44}
GetSamples
Using AI Code Generation
1import (2func main() {3 m := metrics.New()4 m.AddSample(1, 1)5 samples := m.GetSamples()6 fmt.Println(samples)7}8[{1 1}]
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!!