How to use assertSessionMetricsEmitted method of ws Package

Best K6 code snippet using ws.assertSessionMetricsEmitted

ws_test.go

Source:ws_test.go Github

copy

Full Screen

...35 "github.com/luckybroman5/http-log-reconstructor/k6/lib/testutils/httpmultibin"36 "github.com/luckybroman5/http-log-reconstructor/k6/stats"37 "github.com/stretchr/testify/assert"38)39func assertSessionMetricsEmitted(t *testing.T, sampleContainers []stats.SampleContainer, subprotocol, url string, status int, group string) {40 seenSessions := false41 seenSessionDuration := false42 seenConnecting := false43 for _, sampleContainer := range sampleContainers {44 for _, sample := range sampleContainer.GetSamples() {45 tags := sample.Tags.CloneTags()46 if tags["url"] == url {47 switch sample.Metric {48 case metrics.WSConnecting:49 seenConnecting = true50 case metrics.WSSessionDuration:51 seenSessionDuration = true52 case metrics.WSSessions:53 seenSessions = true54 }55 assert.Equal(t, strconv.Itoa(status), tags["status"])56 assert.Equal(t, subprotocol, tags["subproto"])57 assert.Equal(t, group, tags["group"])58 }59 }60 }61 assert.True(t, seenConnecting, "url %s didn't emit Connecting", url)62 assert.True(t, seenSessions, "url %s didn't emit Sessions", url)63 assert.True(t, seenSessionDuration, "url %s didn't emit SessionDuration", url)64}65func assertMetricEmitted(t *testing.T, metric *stats.Metric, sampleContainers []stats.SampleContainer, url string) {66 seenMetric := false67 for _, sampleContainer := range sampleContainers {68 for _, sample := range sampleContainer.GetSamples() {69 surl, ok := sample.Tags.Get("url")70 assert.True(t, ok)71 if surl == url {72 if sample.Metric == metric {73 seenMetric = true74 }75 }76 }77 }78 assert.True(t, seenMetric, "url %s didn't emit %s", url, metric.Name)79}80func TestSession(t *testing.T) {81 //TODO: split and paralelize tests82 t.Parallel()83 tb := httpmultibin.NewHTTPMultiBin(t)84 defer tb.Cleanup()85 sr := tb.Replacer.Replace86 root, err := lib.NewGroup("", nil)87 assert.NoError(t, err)88 rt := goja.New()89 rt.SetFieldNameMapper(common.FieldNameMapper{})90 samples := make(chan stats.SampleContainer, 1000)91 state := &lib.State{92 Group: root,93 Dialer: tb.Dialer,94 Options: lib.Options{95 SystemTags: stats.NewSystemTagSet(96 stats.TagURL,97 stats.TagProto,98 stats.TagStatus,99 stats.TagSubproto,100 ),101 },102 Samples: samples,103 TLSConfig: tb.TLSClientConfig,104 }105 ctx := context.Background()106 ctx = lib.WithState(ctx, state)107 ctx = common.WithRuntime(ctx, rt)108 rt.Set("ws", common.Bind(rt, New(), &ctx))109 t.Run("connect_ws", func(t *testing.T) {110 _, err := common.RunString(rt, sr(`111 let res = ws.connect("WSBIN_URL/ws-echo", function(socket){112 socket.close()113 });114 if (res.status != 101) { throw new Error("connection failed with status: " + res.status); }115 `))116 assert.NoError(t, err)117 })118 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", sr("WSBIN_URL/ws-echo"), 101, "")119 t.Run("connect_wss", func(t *testing.T) {120 _, err := common.RunString(rt, sr(`121 let res = ws.connect("WSSBIN_URL/ws-echo", function(socket){122 socket.close()123 });124 if (res.status != 101) { throw new Error("TLS connection failed with status: " + res.status); }125 `))126 assert.NoError(t, err)127 })128 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", sr("WSSBIN_URL/ws-echo"), 101, "")129 t.Run("open", func(t *testing.T) {130 _, err := common.RunString(rt, sr(`131 let opened = false;132 let res = ws.connect("WSBIN_URL/ws-echo", function(socket){133 socket.on("open", function() {134 opened = true;135 socket.close()136 })137 });138 if (!opened) { throw new Error ("open event not fired"); }139 `))140 assert.NoError(t, err)141 })142 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", sr("WSBIN_URL/ws-echo"), 101, "")143 t.Run("send_receive", func(t *testing.T) {144 _, err := common.RunString(rt, sr(`145 let res = ws.connect("WSBIN_URL/ws-echo", function(socket){146 socket.on("open", function() {147 socket.send("test")148 })149 socket.on("message", function (data){150 if (!data=="test") {151 throw new Error ("echo'd data doesn't match our message!");152 }153 socket.close()154 });155 });156 `))157 assert.NoError(t, err)158 })159 samplesBuf := stats.GetBufferedSamples(samples)160 assertSessionMetricsEmitted(t, samplesBuf, "", sr("WSBIN_URL/ws-echo"), 101, "")161 assertMetricEmitted(t, metrics.WSMessagesSent, samplesBuf, sr("WSBIN_URL/ws-echo"))162 assertMetricEmitted(t, metrics.WSMessagesReceived, samplesBuf, sr("WSBIN_URL/ws-echo"))163 t.Run("interval", func(t *testing.T) {164 _, err := common.RunString(rt, sr(`165 let counter = 0;166 let res = ws.connect("WSBIN_URL/ws-echo", function(socket){167 socket.setInterval(function () {168 counter += 1;169 if (counter > 2) { socket.close(); }170 }, 100);171 });172 if (counter < 3) {throw new Error ("setInterval should have been called at least 3 times, counter=" + counter);}173 `))174 assert.NoError(t, err)175 })176 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", sr("WSBIN_URL/ws-echo"), 101, "")177 t.Run("timeout", func(t *testing.T) {178 _, err := common.RunString(rt, sr(`179 let start = new Date().getTime();180 let ellapsed = new Date().getTime() - start;181 let res = ws.connect("WSBIN_URL/ws-echo", function(socket){182 socket.setTimeout(function () {183 ellapsed = new Date().getTime() - start;184 socket.close();185 }, 500);186 });187 if (ellapsed > 3000 || ellapsed < 500) {188 throw new Error ("setTimeout occurred after " + ellapsed + "ms, expected 500<T<3000");189 }190 `))191 assert.NoError(t, err)192 })193 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", sr("WSBIN_URL/ws-echo"), 101, "")194 t.Run("ping", func(t *testing.T) {195 _, err := common.RunString(rt, sr(`196 let pongReceived = false;197 let res = ws.connect("WSBIN_URL/ws-echo", function(socket){198 socket.on("open", function(data) {199 socket.ping();200 });201 socket.on("pong", function() {202 pongReceived = true;203 socket.close();204 });205 socket.setTimeout(function (){socket.close();}, 3000);206 });207 if (!pongReceived) {208 throw new Error ("sent ping but didn't get pong back");209 }210 `))211 assert.NoError(t, err)212 })213 samplesBuf = stats.GetBufferedSamples(samples)214 assertSessionMetricsEmitted(t, samplesBuf, "", sr("WSBIN_URL/ws-echo"), 101, "")215 assertMetricEmitted(t, metrics.WSPing, samplesBuf, sr("WSBIN_URL/ws-echo"))216 t.Run("multiple_handlers", func(t *testing.T) {217 _, err := common.RunString(rt, sr(`218 let pongReceived = false;219 let otherPongReceived = false;220 let res = ws.connect("WSBIN_URL/ws-echo", function(socket){221 socket.on("open", function(data) {222 socket.ping();223 });224 socket.on("pong", function() {225 pongReceived = true;226 if (otherPongReceived) {227 socket.close();228 }229 });230 socket.on("pong", function() {231 otherPongReceived = true;232 if (pongReceived) {233 socket.close();234 }235 });236 socket.setTimeout(function (){socket.close();}, 3000);237 });238 if (!pongReceived || !otherPongReceived) {239 throw new Error ("sent ping but didn't get pong back");240 }241 `))242 assert.NoError(t, err)243 })244 samplesBuf = stats.GetBufferedSamples(samples)245 assertSessionMetricsEmitted(t, samplesBuf, "", sr("WSBIN_URL/ws-echo"), 101, "")246 assertMetricEmitted(t, metrics.WSPing, samplesBuf, sr("WSBIN_URL/ws-echo"))247 t.Run("client_close", func(t *testing.T) {248 _, err := common.RunString(rt, sr(`249 let closed = false;250 let res = ws.connect("WSBIN_URL/ws-echo", function(socket){251 socket.on("open", function() {252 socket.close()253 })254 socket.on("close", function() {255 closed = true;256 })257 });258 if (!closed) { throw new Error ("close event not fired"); }259 `))260 assert.NoError(t, err)261 })262 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", sr("WSBIN_URL/ws-echo"), 101, "")263 serverCloseTests := []struct {264 name string265 endpoint string266 }{267 {"server_close_ok", "/ws-echo"},268 // Ensure we correctly handle invalid WS server269 // implementations that close the connection prematurely270 // without sending a close control frame first.271 {"server_close_invalid", "/ws-close-invalid"},272 }273 for _, tc := range serverCloseTests {274 tc := tc275 t.Run(tc.name, func(t *testing.T) {276 _, err := common.RunString(rt, sr(fmt.Sprintf(`277 let closed = false;278 let res = ws.connect("WSBIN_URL%s", function(socket){279 socket.on("open", function() {280 socket.send("test");281 })282 socket.on("close", function() {283 closed = true;284 })285 });286 if (!closed) { throw new Error ("close event not fired"); }287 `, tc.endpoint)))288 assert.NoError(t, err)289 })290 }291}292func TestErrors(t *testing.T) {293 t.Parallel()294 tb := httpmultibin.NewHTTPMultiBin(t)295 defer tb.Cleanup()296 sr := tb.Replacer.Replace297 root, err := lib.NewGroup("", nil)298 assert.NoError(t, err)299 rt := goja.New()300 rt.SetFieldNameMapper(common.FieldNameMapper{})301 samples := make(chan stats.SampleContainer, 1000)302 state := &lib.State{303 Group: root,304 Dialer: tb.Dialer,305 Options: lib.Options{306 SystemTags: &stats.DefaultSystemTagSet,307 },308 Samples: samples,309 }310 ctx := context.Background()311 ctx = lib.WithState(ctx, state)312 ctx = common.WithRuntime(ctx, rt)313 rt.Set("ws", common.Bind(rt, New(), &ctx))314 t.Run("invalid_url", func(t *testing.T) {315 _, err := common.RunString(rt, `316 let res = ws.connect("INVALID", function(socket){317 socket.on("open", function() {318 socket.close();319 });320 });321 `)322 assert.Error(t, err)323 })324 t.Run("invalid_url_message_panic", func(t *testing.T) {325 // Attempting to send a message to a non-existent socket shouldn't panic326 _, err := common.RunString(rt, `327 let res = ws.connect("INVALID", function(socket){328 socket.send("new message");329 });330 `)331 assert.Error(t, err)332 })333 t.Run("error_in_setup", func(t *testing.T) {334 _, err := common.RunString(rt, sr(`335 let res = ws.connect("WSBIN_URL/ws-echo-invalid", function(socket){336 throw new Error("error in setup");337 });338 `))339 assert.Error(t, err)340 })341 t.Run("send_after_close", func(t *testing.T) {342 _, err := common.RunString(rt, sr(`343 let hasError = false;344 let res = ws.connect("WSBIN_URL/ws-echo-invalid", function(socket){345 socket.on("open", function() {346 socket.close();347 socket.send("test");348 });349 socket.on("error", function(errorEvent) {350 hasError = true;351 });352 });353 if (!hasError) {354 throw new Error ("no error emitted for send after close");355 }356 `))357 assert.NoError(t, err)358 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", sr("WSBIN_URL/ws-echo-invalid"), 101, "")359 })360 t.Run("error on close", func(t *testing.T) {361 _, err := common.RunString(rt, sr(`362 var closed = false;363 let res = ws.connect("WSBIN_URL/ws-close", function(socket){364 socket.on('open', function open() {365 socket.setInterval(function timeout() {366 socket.ping();367 }, 1000);368 });369 socket.on("ping", function() {370 socket.close();371 });372 socket.on("error", function(errorEvent) {373 if (errorEvent == null) {374 throw new Error(JSON.stringify(errorEvent));375 }376 if (!closed) {377 closed = true;378 socket.close();379 }380 });381 });382 `))383 assert.NoError(t, err)384 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", sr("WSBIN_URL/ws-close"), 101, "")385 })386}387func TestSystemTags(t *testing.T) {388 tb := httpmultibin.NewHTTPMultiBin(t)389 defer tb.Cleanup()390 sr := tb.Replacer.Replace391 root, err := lib.NewGroup("", nil)392 assert.NoError(t, err)393 rt := goja.New()394 rt.SetFieldNameMapper(common.FieldNameMapper{})395 //TODO: test for actual tag values after removing the dependency on the396 // external service demos.kaazing.com (https://github.com/luckybroman5/http-log-reconstructor/k6/issues/537)397 testedSystemTags := []string{"group", "status", "subproto", "url", "ip"}398 samples := make(chan stats.SampleContainer, 1000)399 state := &lib.State{400 Group: root,401 Dialer: tb.Dialer,402 Options: lib.Options{SystemTags: stats.ToSystemTagSet(testedSystemTags)},403 Samples: samples,404 TLSConfig: tb.TLSClientConfig,405 }406 ctx := context.Background()407 ctx = lib.WithState(ctx, state)408 ctx = common.WithRuntime(ctx, rt)409 rt.Set("ws", common.Bind(rt, New(), &ctx))410 for _, expectedTag := range testedSystemTags {411 expectedTag := expectedTag412 t.Run("only "+expectedTag, func(t *testing.T) {413 state.Options.SystemTags = stats.ToSystemTagSet([]string{expectedTag})414 _, err := common.RunString(rt, sr(`415 let res = ws.connect("WSBIN_URL/ws-echo", function(socket){416 socket.on("open", function() {417 socket.send("test")418 })419 socket.on("message", function (data){420 if (!data=="test") {421 throw new Error ("echo'd data doesn't match our message!");422 }423 socket.close()424 });425 });426 `))427 assert.NoError(t, err)428 for _, sampleContainer := range stats.GetBufferedSamples(samples) {429 for _, sample := range sampleContainer.GetSamples() {430 for emittedTag := range sample.Tags.CloneTags() {431 assert.Equal(t, expectedTag, emittedTag)432 }433 }434 }435 })436 }437}438func TestTLSConfig(t *testing.T) {439 root, err := lib.NewGroup("", nil)440 assert.NoError(t, err)441 tb := httpmultibin.NewHTTPMultiBin(t)442 defer tb.Cleanup()443 sr := tb.Replacer.Replace444 rt := goja.New()445 rt.SetFieldNameMapper(common.FieldNameMapper{})446 samples := make(chan stats.SampleContainer, 1000)447 state := &lib.State{448 Group: root,449 Dialer: tb.Dialer,450 Options: lib.Options{451 SystemTags: stats.NewSystemTagSet(452 stats.TagURL,453 stats.TagProto,454 stats.TagStatus,455 stats.TagSubproto,456 stats.TagIP,457 ),458 },459 Samples: samples,460 }461 ctx := context.Background()462 ctx = lib.WithState(ctx, state)463 ctx = common.WithRuntime(ctx, rt)464 rt.Set("ws", common.Bind(rt, New(), &ctx))465 t.Run("insecure skip verify", func(t *testing.T) {466 state.TLSConfig = &tls.Config{467 InsecureSkipVerify: true,468 }469 _, err := common.RunString(rt, sr(`470 let res = ws.connect("WSSBIN_URL/ws-close", function(socket){471 socket.close()472 });473 if (res.status != 101) { throw new Error("TLS connection failed with status: " + res.status); }474 `))475 assert.NoError(t, err)476 })477 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", sr("WSSBIN_URL/ws-close"), 101, "")478 t.Run("custom certificates", func(t *testing.T) {479 state.TLSConfig = tb.TLSClientConfig480 _, err := common.RunString(rt, sr(`481 let res = ws.connect("WSSBIN_URL/ws-close", function(socket){482 socket.close()483 });484 if (res.status != 101) {485 throw new Error("TLS connection failed with status: " + res.status);486 }487 `))488 assert.NoError(t, err)489 })490 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", sr("WSSBIN_URL/ws-close"), 101, "")491}492func TestReadPump(t *testing.T) {493 var closeCode int494 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {495 conn, err := (&websocket.Upgrader{}).Upgrade(w, r, w.Header())496 assert.NoError(t, err)497 closeMsg := websocket.FormatCloseMessage(closeCode, "")498 _ = conn.WriteControl(websocket.CloseMessage, closeMsg, time.Now().Add(time.Second))499 }))500 defer srv.Close()501 closeCodes := []int{websocket.CloseNormalClosure, websocket.CloseGoingAway, websocket.CloseInternalServerErr}502 numAsserts := 0503 srvURL := "ws://" + srv.Listener.Addr().String()504 // Ensure readPump returns the response close code sent by the server...

Full Screen

Full Screen

assertSessionMetricsEmitted

Using AI Code Generation

copy

Full Screen

1import (2var (3func TestMain(m *testing.M) {4 service, err = selenium.NewChromeDriverService("/home/abhishek/Desktop/chromedriver", port)5 if err != nil {6 log.Fatal(err)7 }8 defer service.Stop()9 caps := selenium.Capabilities{"browserName": "chrome"}10 if err != nil {11 log.Fatal(err)12 }13 defer wd.Quit()14 code := m.Run()15 os.Exit(code)16}17func TestWeb(t *testing.T) {18 t.Fatal(err)19 }20 elem, err := wd.FindElement(selenium.ByCSSSelector, "#lst-ib")21 if err != nil {22 t.Fatal(err)23 }24 if err := elem.SendKeys("selenium"); err != nil {25 t.Fatal(err)26 }27 if err := elem.Submit(); err != nil {28 t.Fatal(err)29 }30 if err := wd.WaitWithTimeout(selenium.Condition("selenium != null"), 10*time.Second); err != nil {31 t.Fatal(err)32 }33 title, err := wd.Title()34 if err != nil {35 t.Fatal(err)36 }37 if !strings.HasPrefix(title, "selenium") {38 t.Fatalf("got title %q, want %q", title, "selenium")

Full Screen

Full Screen

assertSessionMetricsEmitted

Using AI Code Generation

copy

Full Screen

1import (2func TestGet(t *testing.T) {3 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {4 fmt.Fprintln(w, "Hello, client")5 }))6 defer ts.Close()7 res, err := http.Get(ts.URL)8 if err != nil {9 t.Fatal(err)10 }11 defer res.Body.Close()12 if res.StatusCode != http.StatusOK {13 t.Fatalf("status code error: %d %s", res.StatusCode, res.Status)14 }15 body, err := ioutil.ReadAll(res.Body)16 if err != nil {17 t.Fatal(err)18 }19 fmt.Printf("%s20}

Full Screen

Full Screen

assertSessionMetricsEmitted

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {4 conn, err := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}).Upgrade(w, r, nil)5 if err != nil {6 log.Println(err)7 }8 defer conn.Close()9 for {10 _, message, err := conn.ReadMessage()11 if err != nil {12 log.Println(err)13 }14 log.Printf("recv: %s", message)15 }16 })17 go http.ListenAndServe(addr, nil)18 time.Sleep(time.Second)19 log.Printf("connecting to %s", u)20 c, _, err := websocket.DefaultDialer.Dial(u, nil)21 if err != nil {22 log.Fatal("dial:", err)23 }24 defer c.Close()25 err = c.WriteMessage(websocket.TextMessage, []byte("hello"))26 if err != nil {27 log.Println("write:", err)28 }29 _, message, err := c.ReadMessage()30 if err != nil {31 log.Println("read:", err)32 }33 log.Printf("recv: %s", message)34}35import (36func main() {37 http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {38 conn, err := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}).Upgrade(w, r, nil)39 if err != nil {40 log.Println(err)41 }42 defer conn.Close()43 for {44 _, message, err := conn.ReadMessage()45 if err != nil {46 log.Println(err)47 }48 log.Printf("recv: %s", message)49 }50 })51 go http.ListenAndServe(addr, nil)52 time.Sleep(time.Second

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