How to use assertMetricEmittedCount method of ws Package

Best K6 code snippet using ws.assertMetricEmittedCount

ws_test.go

Source:ws_test.go Github

copy

Full Screen

...68 assert.True(t, seenConnecting, "url %s didn't emit Connecting", url)69 assert.True(t, seenSessions, "url %s didn't emit Sessions", url)70 assert.True(t, seenSessionDuration, "url %s didn't emit SessionDuration", url)71}72func assertMetricEmittedCount(t *testing.T, metricName string, sampleContainers []metrics.SampleContainer, url string, count int) {73 t.Helper()74 actualCount := 075 for _, sampleContainer := range sampleContainers {76 for _, sample := range sampleContainer.GetSamples() {77 surl, ok := sample.Tags.Get("url")78 assert.True(t, ok)79 if surl == url && sample.Metric.Name == metricName {80 actualCount++81 }82 }83 }84 assert.Equal(t, count, actualCount, "url %s emitted %s %d times, expected was %d times", url, metricName, actualCount, count)85}86type testState struct {87 ctxPtr *context.Context88 rt *goja.Runtime89 tb *httpmultibin.HTTPMultiBin90 state *lib.State91 samples chan metrics.SampleContainer92}93func newTestState(t testing.TB) testState {94 tb := httpmultibin.NewHTTPMultiBin(t)95 root, err := lib.NewGroup("", nil)96 require.NoError(t, err)97 rt := goja.New()98 rt.SetFieldNameMapper(common.FieldNameMapper{})99 samples := make(chan metrics.SampleContainer, 1000)100 state := &lib.State{101 Group: root,102 Dialer: tb.Dialer,103 Options: lib.Options{104 SystemTags: metrics.NewSystemTagSet(105 metrics.TagURL,106 metrics.TagProto,107 metrics.TagStatus,108 metrics.TagSubproto,109 ),110 UserAgent: null.StringFrom("TestUserAgent"),111 },112 Samples: samples,113 TLSConfig: tb.TLSClientConfig,114 BuiltinMetrics: metrics.RegisterBuiltinMetrics(metrics.NewRegistry()),115 Tags: lib.NewTagMap(nil),116 }117 m := New().NewModuleInstance(&modulestest.VU{118 CtxField: tb.Context,119 InitEnvField: &common.InitEnvironment{},120 RuntimeField: rt,121 StateField: state,122 })123 require.NoError(t, rt.Set("ws", m.Exports().Default))124 return testState{125 rt: rt,126 tb: tb,127 state: state,128 samples: samples,129 }130}131func TestSession(t *testing.T) {132 // TODO: split and paralelize tests133 t.Parallel()134 tb := httpmultibin.NewHTTPMultiBin(t)135 sr := tb.Replacer.Replace136 root, err := lib.NewGroup("", nil)137 require.NoError(t, err)138 rt := goja.New()139 rt.SetFieldNameMapper(common.FieldNameMapper{})140 samples := make(chan metrics.SampleContainer, 1000)141 state := &lib.State{142 Group: root,143 Dialer: tb.Dialer,144 Options: lib.Options{145 SystemTags: metrics.NewSystemTagSet(146 metrics.TagURL,147 metrics.TagProto,148 metrics.TagStatus,149 metrics.TagSubproto,150 ),151 },152 Samples: samples,153 TLSConfig: tb.TLSClientConfig,154 BuiltinMetrics: metrics.RegisterBuiltinMetrics(metrics.NewRegistry()),155 Tags: lib.NewTagMap(nil),156 }157 m := New().NewModuleInstance(&modulestest.VU{158 CtxField: context.Background(),159 InitEnvField: &common.InitEnvironment{},160 RuntimeField: rt,161 StateField: state,162 })163 require.NoError(t, rt.Set("ws", m.Exports().Default))164 t.Run("connect_ws", func(t *testing.T) {165 _, err := rt.RunString(sr(`166 var res = ws.connect("WSBIN_URL/ws-echo", function(socket){167 socket.close()168 });169 if (res.status != 101) { throw new Error("connection failed with status: " + res.status); }170 `))171 require.NoError(t, err)172 })173 assertSessionMetricsEmitted(t, metrics.GetBufferedSamples(samples), "", sr("WSBIN_URL/ws-echo"), statusProtocolSwitch, "")174 t.Run("connect_wss", func(t *testing.T) {175 _, err := rt.RunString(sr(`176 var res = ws.connect("WSSBIN_URL/ws-echo", function(socket){177 socket.close()178 });179 if (res.status != 101) { throw new Error("TLS connection failed with status: " + res.status); }180 `))181 require.NoError(t, err)182 })183 assertSessionMetricsEmitted(t, metrics.GetBufferedSamples(samples), "", sr("WSSBIN_URL/ws-echo"), statusProtocolSwitch, "")184 t.Run("open", func(t *testing.T) {185 _, err := rt.RunString(sr(`186 var opened = false;187 var res = ws.connect("WSBIN_URL/ws-echo", function(socket){188 socket.on("open", function() {189 opened = true;190 socket.close()191 })192 });193 if (!opened) { throw new Error ("open event not fired"); }194 `))195 require.NoError(t, err)196 })197 assertSessionMetricsEmitted(t, metrics.GetBufferedSamples(samples), "", sr("WSBIN_URL/ws-echo"), statusProtocolSwitch, "")198 t.Run("send_receive", func(t *testing.T) {199 _, err := rt.RunString(sr(`200 var res = ws.connect("WSBIN_URL/ws-echo", function(socket){201 socket.on("open", function() {202 socket.send("test")203 })204 socket.on("message", function (data) {205 if (!data=="test") {206 throw new Error ("echo'd data doesn't match our message!");207 }208 socket.close()209 });210 });211 `))212 require.NoError(t, err)213 })214 samplesBuf := metrics.GetBufferedSamples(samples)215 assertSessionMetricsEmitted(t, samplesBuf, "", sr("WSBIN_URL/ws-echo"), statusProtocolSwitch, "")216 assertMetricEmittedCount(t, metrics.WSMessagesSentName, samplesBuf, sr("WSBIN_URL/ws-echo"), 1)217 assertMetricEmittedCount(t, metrics.WSMessagesReceivedName, samplesBuf, sr("WSBIN_URL/ws-echo"), 1)218 t.Run("interval", func(t *testing.T) {219 _, err := rt.RunString(sr(`220 var counter = 0;221 var res = ws.connect("WSBIN_URL/ws-echo", function(socket){222 socket.setInterval(function () {223 counter += 1;224 if (counter > 2) { socket.close(); }225 }, 100);226 });227 if (counter < 3) {throw new Error ("setInterval should have been called at least 3 times, counter=" + counter);}228 `))229 require.NoError(t, err)230 })231 assertSessionMetricsEmitted(t, metrics.GetBufferedSamples(samples), "", sr("WSBIN_URL/ws-echo"), statusProtocolSwitch, "")232 t.Run("bad interval", func(t *testing.T) {233 _, err := rt.RunString(sr(`234 var counter = 0;235 var res = ws.connect("WSBIN_URL/ws-echo", function(socket){236 socket.setInterval(function () {237 counter += 1;238 if (counter > 2) { socket.close(); }239 }, -1.23);240 });241 `))242 require.Error(t, err)243 require.Contains(t, err.Error(), "setInterval requires a >0 timeout parameter, received -1.23 ")244 })245 t.Run("timeout", func(t *testing.T) {246 _, err := rt.RunString(sr(`247 var start = new Date().getTime();248 var ellapsed = new Date().getTime() - start;249 var res = ws.connect("WSBIN_URL/ws-echo", function(socket){250 socket.setTimeout(function () {251 ellapsed = new Date().getTime() - start;252 socket.close();253 }, 500);254 });255 if (ellapsed > 3000 || ellapsed < 500) {256 throw new Error ("setTimeout occurred after " + ellapsed + "ms, expected 500<T<3000");257 }258 `))259 require.NoError(t, err)260 })261 t.Run("bad timeout", func(t *testing.T) {262 _, err := rt.RunString(sr(`263 var start = new Date().getTime();264 var ellapsed = new Date().getTime() - start;265 var res = ws.connect("WSBIN_URL/ws-echo", function(socket){266 socket.setTimeout(function () {267 ellapsed = new Date().getTime() - start;268 socket.close();269 }, 0);270 });271 `))272 require.Error(t, err)273 require.Contains(t, err.Error(), "setTimeout requires a >0 timeout parameter, received 0.00 ")274 })275 assertSessionMetricsEmitted(t, metrics.GetBufferedSamples(samples), "", sr("WSBIN_URL/ws-echo"), statusProtocolSwitch, "")276 t.Run("ping", func(t *testing.T) {277 _, err := rt.RunString(sr(`278 var pongReceived = false;279 var res = ws.connect("WSBIN_URL/ws-echo", function(socket){280 socket.on("open", function(data) {281 socket.ping();282 });283 socket.on("pong", function() {284 pongReceived = true;285 socket.close();286 });287 socket.setTimeout(function (){socket.close();}, 3000);288 });289 if (!pongReceived) {290 throw new Error ("sent ping but didn't get pong back");291 }292 `))293 require.NoError(t, err)294 })295 samplesBuf = metrics.GetBufferedSamples(samples)296 assertSessionMetricsEmitted(t, samplesBuf, "", sr("WSBIN_URL/ws-echo"), statusProtocolSwitch, "")297 assertMetricEmittedCount(t, metrics.WSPingName, samplesBuf, sr("WSBIN_URL/ws-echo"), 1)298 t.Run("multiple_handlers", func(t *testing.T) {299 _, err := rt.RunString(sr(`300 var pongReceived = false;301 var otherPongReceived = false;302 var res = ws.connect("WSBIN_URL/ws-echo", function(socket){303 socket.on("open", function(data) {304 socket.ping();305 });306 socket.on("pong", function() {307 pongReceived = true;308 if (otherPongReceived) {309 socket.close();310 }311 });312 socket.on("pong", function() {313 otherPongReceived = true;314 if (pongReceived) {315 socket.close();316 }317 });318 socket.setTimeout(function (){socket.close();}, 3000);319 });320 if (!pongReceived || !otherPongReceived) {321 throw new Error ("sent ping but didn't get pong back");322 }323 `))324 require.NoError(t, err)325 })326 samplesBuf = metrics.GetBufferedSamples(samples)327 assertSessionMetricsEmitted(t, samplesBuf, "", sr("WSBIN_URL/ws-echo"), statusProtocolSwitch, "")328 assertMetricEmittedCount(t, metrics.WSPingName, samplesBuf, sr("WSBIN_URL/ws-echo"), 1)329 t.Run("client_close", func(t *testing.T) {330 _, err := rt.RunString(sr(`331 var closed = false;332 var res = ws.connect("WSBIN_URL/ws-echo", function(socket){333 socket.on("open", function() {334 socket.close()335 })336 socket.on("close", function() {337 closed = true;338 })339 });340 if (!closed) { throw new Error ("close event not fired"); }341 `))342 require.NoError(t, err)343 })344 assertSessionMetricsEmitted(t, metrics.GetBufferedSamples(samples), "", sr("WSBIN_URL/ws-echo"), statusProtocolSwitch, "")345 serverCloseTests := []struct {346 name string347 endpoint string348 }{349 {"server_close_ok", "/ws-echo"},350 // Ensure we correctly handle invalid WS server351 // implementations that close the connection prematurely352 // without sending a close control frame first.353 {"server_close_invalid", "/ws-close-invalid"},354 }355 for _, tc := range serverCloseTests {356 tc := tc357 t.Run(tc.name, func(t *testing.T) {358 _, err := rt.RunString(sr(fmt.Sprintf(`359 var closed = false;360 var res = ws.connect("WSBIN_URL%s", function(socket){361 socket.on("open", function() {362 socket.send("test");363 })364 socket.on("close", function() {365 closed = true;366 })367 });368 if (!closed) { throw new Error ("close event not fired"); }369 `, tc.endpoint)))370 require.NoError(t, err)371 })372 }373 t.Run("multi_message", func(t *testing.T) {374 t.Parallel()375 tb.Mux.HandleFunc("/ws-echo-multi", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {376 conn, err := (&websocket.Upgrader{}).Upgrade(w, req, w.Header())377 if err != nil {378 return379 }380 for {381 messageType, r, e := conn.NextReader()382 if e != nil {383 return384 }385 var wc io.WriteCloser386 wc, err = conn.NextWriter(messageType)387 if err != nil {388 return389 }390 if _, err = io.Copy(wc, r); err != nil {391 return392 }393 if err = wc.Close(); err != nil {394 return395 }396 }397 }))398 t.Run("send_receive_multiple_ws", func(t *testing.T) {399 _, err := rt.RunString(sr(`400 var msg1 = "test1"401 var msg2 = "test2"402 var msg3 = "test3"403 var allMsgsRecvd = false404 var res = ws.connect("WSBIN_URL/ws-echo-multi", (socket) => {405 socket.on("open", () => {406 socket.send(msg1)407 })408 socket.on("message", (data) => {409 if (data == msg1){410 socket.send(msg2)411 }412 if (data == msg2){413 socket.send(msg3)414 }415 if (data == msg3){416 allMsgsRecvd = true417 socket.close()418 }419 });420 });421 if (!allMsgsRecvd) {422 throw new Error ("messages 1,2,3 in sequence, was not received from server");423 }424 `))425 require.NoError(t, err)426 })427 samplesBuf = metrics.GetBufferedSamples(samples)428 assertSessionMetricsEmitted(t, samplesBuf, "", sr("WSBIN_URL/ws-echo-multi"), statusProtocolSwitch, "")429 assertMetricEmittedCount(t, metrics.WSMessagesSentName, samplesBuf, sr("WSBIN_URL/ws-echo-multi"), 3)430 assertMetricEmittedCount(t, metrics.WSMessagesReceivedName, samplesBuf, sr("WSBIN_URL/ws-echo-multi"), 3)431 t.Run("send_receive_multiple_wss", func(t *testing.T) {432 _, err := rt.RunString(sr(`433 var msg1 = "test1"434 var msg2 = "test2"435 var secondMsgReceived = false436 var res = ws.connect("WSSBIN_URL/ws-echo-multi", (socket) => {437 socket.on("open", () => {438 socket.send(msg1)439 })440 socket.on("message", (data) => {441 if (data == msg1){442 socket.send(msg2)443 }444 if (data == msg2){445 secondMsgReceived = true446 socket.close()447 }448 });449 });450 if (!secondMsgReceived) {451 throw new Error ("second test message was not received from server!");452 }453 `))454 require.NoError(t, err)455 })456 samplesBuf = metrics.GetBufferedSamples(samples)457 assertSessionMetricsEmitted(t, samplesBuf, "", sr("WSSBIN_URL/ws-echo-multi"), statusProtocolSwitch, "")458 assertMetricEmittedCount(t, metrics.WSMessagesSentName, samplesBuf, sr("WSSBIN_URL/ws-echo-multi"), 2)459 assertMetricEmittedCount(t, metrics.WSMessagesReceivedName, samplesBuf, sr("WSSBIN_URL/ws-echo-multi"), 2)460 t.Run("send_receive_text_binary", func(t *testing.T) {461 _, err := rt.RunString(sr(`462 var msg1 = "test1"463 var msg2 = new Uint8Array([116, 101, 115, 116, 50]); // 'test2'464 var secondMsgReceived = false465 var res = ws.connect("WSBIN_URL/ws-echo-multi", (socket) => {466 socket.on("open", () => {467 socket.send(msg1)468 })469 socket.on("message", (data) => {470 if (data == msg1){471 socket.sendBinary(msg2.buffer)472 }473 });474 socket.on("binaryMessage", (data) => {475 let data2 = new Uint8Array(data)476 if(JSON.stringify(msg2) == JSON.stringify(data2)){477 secondMsgReceived = true478 }479 socket.close()480 })481 });482 if (!secondMsgReceived) {483 throw new Error ("second test message was not received from server!");484 }485 `))486 require.NoError(t, err)487 })488 samplesBuf = metrics.GetBufferedSamples(samples)489 assertSessionMetricsEmitted(t, samplesBuf, "", sr("WSBIN_URL/ws-echo-multi"), statusProtocolSwitch, "")490 assertMetricEmittedCount(t, metrics.WSMessagesSentName, samplesBuf, sr("WSBIN_URL/ws-echo-multi"), 2)491 assertMetricEmittedCount(t, metrics.WSMessagesReceivedName, samplesBuf, sr("WSBIN_URL/ws-echo-multi"), 2)492 })493}494func TestSocketSendBinary(t *testing.T) { //nolint: tparallel495 t.Parallel()496 tb := httpmultibin.NewHTTPMultiBin(t)497 sr := tb.Replacer.Replace498 root, err := lib.NewGroup("", nil)499 require.NoError(t, err)500 rt := goja.New()501 rt.SetFieldNameMapper(common.FieldNameMapper{})502 samples := make(chan metrics.SampleContainer, 1000)503 state := &lib.State{ //nolint: exhaustivestruct504 Group: root,505 Dialer: tb.Dialer,...

Full Screen

Full Screen

assertMetricEmittedCount

Using AI Code Generation

copy

Full Screen

1ws.assertMetricEmittedCount("metricName", 1)2ws.assertMetricEmittedCount("metricName", 1)3ws.assertMetricEmittedCount("metricName", 1)4ws.assertMetricEmittedCount("metricName", 1)5ws.assertMetricEmittedCount("metricName", 1)6ws.assertMetricEmittedCount("metricName", 1)7ws.assertMetricEmittedCount("metricName", 1)8ws.assertMetricEmittedCount("metricName", 1)9ws.assertMetricEmittedCount("metricName", 1)10ws.assertMetricEmittedCount("metricName", 1)11ws.assertMetricEmittedCount("metricName", 1)12ws.assertMetricEmittedCount("metricName", 1)13ws.assertMetricEmittedCount("metricName", 1)14ws.assertMetricEmittedCount("metricName", 1)15ws.assertMetricEmittedCount("metricName", 1)

Full Screen

Full Screen

assertMetricEmittedCount

Using AI Code Generation

copy

Full Screen

1import (2func TestFoo(t *testing.T) {3 ctrl := gomock.NewController(t)4 defer ctrl.Finish()5 mockW := mock.NewMockWorkspace(ctrl)6 mockW.EXPECT().assertMetricEmittedCount("foo", "bar", 1).Return(nil).Times(1)7 foo(mockW)8}9import (10func TestFoo(t *testing.T) {11 ctrl := gomock.NewController(t)12 defer ctrl.Finish()13 mockW := mock.NewMockWorkspace(ctrl)14 mockW.EXPECT().assertMetricEmittedCount("foo", "bar", 1).Return(nil).Times(1)15 foo(mockW)16}17import (18func TestFoo(t *testing.T) {19 ctrl := gomock.NewController(t)20 defer ctrl.Finish()21 mockW := mock.NewMockWorkspace(ctrl)22 mockW.EXPECT().assertMetricEmittedCount("foo", "bar", 1).Return(nil).Times(1)23 foo(mockW)24}25import (

Full Screen

Full Screen

assertMetricEmittedCount

Using AI Code Generation

copy

Full Screen

1import (2var (3func TestMain(m *testing.M) {4 exitCode := m.Run()5 os.Exit(exitCode)6}7type TestSuite struct {8}9func (s *TestSuite) SetupSuite() {10 s.T().Parallel()11 s.T().SetDefaultEventuallyTimeout(defaultTimeout)12}13type TestSuite struct {14}15func (s *TestSuite) SetupSuite() {16 s.T().Parallel()17 s.T().SetDefaultEventuallyTimeout(defaultTimeout)18}19type TestSuite struct {20}21func (s *TestSuite) SetupSuite() {22 s.T().Parallel()23 s.T().SetDefaultEventuallyTimeout(defaultTimeout)24}25type TestSuite struct {26}27func (s *TestSuite) SetupSuite() {28 s.T().Parallel()29 s.T().SetDefaultEventuallyTimeout(defaultTimeout)30}31type TestSuite struct {32}33func (s *TestSuite) SetupSuite() {34 s.T().Parallel()35 s.T().SetDefaultEventuallyTimeout(defaultTimeout)36}37type TestSuite struct {38}39func (s *TestSuite) SetupSuite() {40 s.T().Parallel()41 s.T().SetDefaultEventuallyTimeout(defaultTimeout)42}

Full Screen

Full Screen

assertMetricEmittedCount

Using AI Code Generation

copy

Full Screen

1import (2func TestKafka(t *testing.T) {3 config := cluster.NewConfig()4 brokers := []string{"localhost:9092"}5 topics := []string{"test"}6 consumer, err := cluster.NewConsumer(brokers, "group", topics, config)7 if err != nil {8 panic(err)9 }10 defer consumer.Close()11 go func() {12 for err := range consumer.Errors() {13 fmt.Println(err)14 }15 }()16 go func() {17 for ntf := range consumer.Notifications() {18 fmt.Println(ntf)19 }20 }()21 for {22 select {23 case msg, ok := <-consumer.Messages():24 if ok {25 fmt.Println(string(msg.Value))26 consumer.MarkOffset(msg, "")27 }28 }29 }30 assert.Equal(t, 1, count, "Count of messages should be 1")31}32import (33func TestKafka(t *testing.T) {34 config := cluster.NewConfig()35 brokers := []string{"localhost:9092"}36 topics := []string{"test"}37 consumer, err := cluster.NewConsumer(brokers, "group", topics, config)38 if err != nil {39 panic(err)40 }41 defer consumer.Close()42 go func() {43 for err := range consumer.Errors() {44 fmt.Println(err)45 }46 }()47 go func() {48 for ntf := range consumer.Notifications() {49 fmt.Println(ntf)50 }51 }()52 for {53 select {

Full Screen

Full Screen

assertMetricEmittedCount

Using AI Code Generation

copy

Full Screen

1func TestMain(m *testing.M) {2 ws := new(Ws)3 ws.Run()4 os.Exit(m.Run())5}6func TestWs(t *testing.T) {7 ws := new(Ws)8 ws.Run()9 assertMetricEmittedCount(t, ws, "count", 1)10}11type Ws struct {12}13func (ws *Ws) Run() {14 ws.MetricEmittedCount = testutil.NewMetricEmittedCount(ws.T)15}16func (ws *Ws) Test() {17 ws.EmitMetric("count", 1)18}19func (ws *Ws) Assert() {20 assertMetricEmittedCount(ws.T, ws, "count", 1)21}22func (ws *Ws) Run(t *testing.T) {23 ws.MetricEmittedCount = testutil.NewMetricEmittedCount(ws.T)24}25func (ws *Ws) Test() {26 ws.EmitMetric("count", 1)27}28func (ws *Ws) Assert() {29 assertMetricEmittedCount(ws.T, ws, "count", 1)30}

Full Screen

Full Screen

assertMetricEmittedCount

Using AI Code Generation

copy

Full Screen

1func assertMetricEmittedCount ( t * testing . T , ws * Workspace , metricName string , count int ) { 2 metricCount , err := ws . GetMetricCount ( metricName ) 3 if err != nil { 4 t . Fatalf ( "failed to get metric count for metric %s: %v" , metricName , err ) 5 } 6 if metricCount != count { 7 t . Fatalf ( "expected metric %s to be emitted %d times, but got %d" , metricName , count , metricCount ) 8 } 9 }10func TestMetricEmittedCount ( t * testing . T ) { 11 ws , err := NewWorkspace ( ) 12 if err != nil { 13 t . Fatalf ( "failed to create workspace: %v" , err ) 14 } 15 defer ws . Destroy ( ) 16 metric , err := NewMetric ( metricName , "test metric" ) 17 if err != nil { 18 t . Fatalf ( "failed to create metric %s: %v" , metricName , err ) 19 } 20 err = ws . RegisterMetric ( metric ) 21 if err != nil { 22 t . Fatalf ( "failed to register metric %s: %v" , metricName , err ) 23 } 24 err = metric . Emit ( ) 25 if err != nil { 26 t . Fatalf ( "failed to emit metric %s: %v" , metricName , err ) 27 } 28 assertMetricEmittedCount ( t , ws , metric

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