How to use GetTime method of netext Package

Best K6 code snippet using netext.GetTime

ws_test.go

Source:ws_test.go Github

copy

Full Screen

1/*2 *3 * k6 - a next-generation load testing tool4 * Copyright (C) 2017 Load Impact5 *6 * This program is free software: you can redistribute it and/or modify7 * it under the terms of the GNU Affero General Public License as8 * published by the Free Software Foundation, either version 3 of the9 * License, or (at your option) any later version.10 *11 * This program is distributed in the hope that it will be useful,12 * but WITHOUT ANY WARRANTY; without even the implied warranty of13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14 * GNU Affero General Public License for more details.15 *16 * You should have received a copy of the GNU Affero General Public License17 * along with this program. If not, see <http://www.gnu.org/licenses/>.18 *19 */20package ws21import (22 "context"23 "crypto/tls"24 "fmt"25 "net"26 "strconv"27 "strings"28 "testing"29 "time"30 "github.com/dop251/goja"31 "github.com/loadimpact/k6/js/common"32 "github.com/loadimpact/k6/lib"33 "github.com/loadimpact/k6/lib/metrics"34 "github.com/loadimpact/k6/lib/netext"35 "github.com/loadimpact/k6/lib/testutils"36 "github.com/loadimpact/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 makeWsProto(s string) string {81 return "ws" + strings.TrimPrefix(s, "http")82}83func TestSession(t *testing.T) {84 //TODO: split and paralelize tests85 root, err := lib.NewGroup("", nil)86 assert.NoError(t, err)87 rt := goja.New()88 rt.SetFieldNameMapper(common.FieldNameMapper{})89 dialer := netext.NewDialer(net.Dialer{90 Timeout: 10 * time.Second,91 KeepAlive: 60 * time.Second,92 DualStack: true,93 })94 samples := make(chan stats.SampleContainer, 1000)95 state := &lib.State{96 Group: root,97 Dialer: dialer,98 Options: lib.Options{99 SystemTags: lib.GetTagSet("url", "proto", "status", "subproto"),100 },101 Samples: samples,102 }103 ctx := context.Background()104 ctx = lib.WithState(ctx, state)105 ctx = common.WithRuntime(ctx, rt)106 rt.Set("ws", common.Bind(rt, New(), &ctx))107 t.Run("connect_ws", func(t *testing.T) {108 _, err := common.RunString(rt, `109 let res = ws.connect("ws://demos.kaazing.com/echo", function(socket){110 socket.close()111 });112 if (res.status != 101) { throw new Error("connection failed with status: " + res.status); }113 `)114 assert.NoError(t, err)115 })116 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", "ws://demos.kaazing.com/echo", 101, "")117 t.Run("connect_wss", func(t *testing.T) {118 _, err := common.RunString(rt, `119 let res = ws.connect("wss://demos.kaazing.com/echo", function(socket){120 socket.close()121 });122 if (res.status != 101) { throw new Error("TLS connection failed with status: " + res.status); }123 `)124 assert.NoError(t, err)125 })126 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", "wss://demos.kaazing.com/echo", 101, "")127 t.Run("open", func(t *testing.T) {128 _, err := common.RunString(rt, `129 let opened = false;130 let res = ws.connect("ws://demos.kaazing.com/echo", function(socket){131 socket.on("open", function() {132 opened = true;133 socket.close()134 })135 });136 if (!opened) { throw new Error ("open event not fired"); }137 `)138 assert.NoError(t, err)139 })140 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", "ws://demos.kaazing.com/echo", 101, "")141 t.Run("send_receive", func(t *testing.T) {142 _, err := common.RunString(rt, `143 let res = ws.connect("ws://demos.kaazing.com/echo", function(socket){144 socket.on("open", function() {145 socket.send("test")146 })147 socket.on("message", function (data){148 if (!data=="test") {149 throw new Error ("echo'd data doesn't match our message!");150 }151 socket.close()152 });153 });154 `)155 assert.NoError(t, err)156 })157 samplesBuf := stats.GetBufferedSamples(samples)158 assertSessionMetricsEmitted(t, samplesBuf, "", "ws://demos.kaazing.com/echo", 101, "")159 assertMetricEmitted(t, metrics.WSMessagesSent, samplesBuf, "ws://demos.kaazing.com/echo")160 assertMetricEmitted(t, metrics.WSMessagesReceived, samplesBuf, "ws://demos.kaazing.com/echo")161 t.Run("interval", func(t *testing.T) {162 _, err := common.RunString(rt, `163 let counter = 0;164 let res = ws.connect("ws://demos.kaazing.com/echo", function(socket){165 socket.setInterval(function () {166 counter += 1;167 if (counter > 2) { socket.close(); }168 }, 100);169 });170 if (counter < 3) {throw new Error ("setInterval should have been called at least 3 times, counter=" + counter);}171 `)172 assert.NoError(t, err)173 })174 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", "ws://demos.kaazing.com/echo", 101, "")175 t.Run("timeout", func(t *testing.T) {176 _, err := common.RunString(rt, `177 let start = new Date().getTime();178 let ellapsed = new Date().getTime() - start;179 let res = ws.connect("ws://demos.kaazing.com/echo", function(socket){180 socket.setTimeout(function () {181 ellapsed = new Date().getTime() - start;182 socket.close();183 }, 500);184 });185 if (ellapsed > 3000 || ellapsed < 500) {186 throw new Error ("setTimeout occurred after " + ellapsed + "ms, expected 500<T<3000");187 }188 `)189 assert.NoError(t, err)190 })191 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", "ws://demos.kaazing.com/echo", 101, "")192 t.Run("ping", func(t *testing.T) {193 _, err := common.RunString(rt, `194 let pongReceived = false;195 let res = ws.connect("ws://demos.kaazing.com/echo", function(socket){196 socket.on("open", function(data) {197 socket.ping();198 });199 socket.on("pong", function() {200 pongReceived = true;201 socket.close();202 });203 socket.setTimeout(function (){socket.close();}, 3000);204 });205 if (!pongReceived) {206 throw new Error ("sent ping but didn't get pong back");207 }208 `)209 assert.NoError(t, err)210 })211 samplesBuf = stats.GetBufferedSamples(samples)212 assertSessionMetricsEmitted(t, samplesBuf, "", "ws://demos.kaazing.com/echo", 101, "")213 assertMetricEmitted(t, metrics.WSPing, samplesBuf, "ws://demos.kaazing.com/echo")214 t.Run("multiple_handlers", func(t *testing.T) {215 _, err := common.RunString(rt, `216 let pongReceived = false;217 let otherPongReceived = false;218 let res = ws.connect("ws://demos.kaazing.com/echo", function(socket){219 socket.on("open", function(data) {220 socket.ping();221 });222 socket.on("pong", function() {223 pongReceived = true;224 if (otherPongReceived) {225 socket.close();226 }227 });228 socket.on("pong", function() {229 otherPongReceived = true;230 if (pongReceived) {231 socket.close();232 }233 });234 socket.setTimeout(function (){socket.close();}, 3000);235 });236 if (!pongReceived || !otherPongReceived) {237 throw new Error ("sent ping but didn't get pong back");238 }239 `)240 assert.NoError(t, err)241 })242 samplesBuf = stats.GetBufferedSamples(samples)243 assertSessionMetricsEmitted(t, samplesBuf, "", "ws://demos.kaazing.com/echo", 101, "")244 assertMetricEmitted(t, metrics.WSPing, samplesBuf, "ws://demos.kaazing.com/echo")245 t.Run("close", func(t *testing.T) {246 _, err := common.RunString(rt, `247 let closed = false;248 let res = ws.connect("ws://demos.kaazing.com/echo", function(socket){249 socket.on("open", function() {250 socket.close()251 })252 socket.on("close", function() {253 closed = true;254 })255 });256 if (!closed) { throw new Error ("close event not fired"); }257 `)258 assert.NoError(t, err)259 })260 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", "ws://demos.kaazing.com/echo", 101, "")261}262func TestErrors(t *testing.T) {263 root, err := lib.NewGroup("", nil)264 assert.NoError(t, err)265 rt := goja.New()266 rt.SetFieldNameMapper(common.FieldNameMapper{})267 dialer := netext.NewDialer(net.Dialer{268 Timeout: 10 * time.Second,269 KeepAlive: 60 * time.Second,270 DualStack: true,271 })272 samples := make(chan stats.SampleContainer, 1000)273 state := &lib.State{274 Group: root,275 Dialer: dialer,276 Options: lib.Options{277 SystemTags: lib.GetTagSet(lib.DefaultSystemTagList...),278 },279 Samples: samples,280 }281 ctx := context.Background()282 ctx = lib.WithState(ctx, state)283 ctx = common.WithRuntime(ctx, rt)284 rt.Set("ws", common.Bind(rt, New(), &ctx))285 t.Run("invalid_url", func(t *testing.T) {286 _, err := common.RunString(rt, `287 let res = ws.connect("INVALID", function(socket){288 socket.on("open", function() {289 socket.close();290 });291 });292 `)293 assert.Error(t, err)294 })295 t.Run("send_after_close", func(t *testing.T) {296 _, err := common.RunString(rt, `297 let hasError = false;298 let res = ws.connect("ws://demos.kaazing.com/echo", function(socket){299 socket.on("open", function() {300 socket.close();301 socket.send("test");302 });303 socket.on("error", function(errorEvent) {304 hasError = true;305 });306 });307 if (!hasError) {308 throw new Error ("no error emitted for send after close");309 }310 `)311 assert.NoError(t, err)312 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", "ws://demos.kaazing.com/echo", 101, "")313 })314}315func TestSystemTags(t *testing.T) {316 root, err := lib.NewGroup("", nil)317 assert.NoError(t, err)318 rt := goja.New()319 rt.SetFieldNameMapper(common.FieldNameMapper{})320 dialer := netext.NewDialer(net.Dialer{321 Timeout: 10 * time.Second,322 KeepAlive: 60 * time.Second,323 DualStack: true,324 })325 //TODO: test for actual tag values after removing the dependency on the326 // external service demos.kaazing.com (https://github.com/loadimpact/k6/issues/537)327 testedSystemTags := []string{"group", "status", "subproto", "url", "ip"}328 samples := make(chan stats.SampleContainer, 1000)329 state := &lib.State{330 Group: root,331 Dialer: dialer,332 Options: lib.Options{SystemTags: lib.GetTagSet(testedSystemTags...)},333 Samples: samples,334 }335 ctx := context.Background()336 ctx = lib.WithState(ctx, state)337 ctx = common.WithRuntime(ctx, rt)338 rt.Set("ws", common.Bind(rt, New(), &ctx))339 for _, expectedTag := range testedSystemTags {340 t.Run("only "+expectedTag, func(t *testing.T) {341 state.Options.SystemTags = map[string]bool{342 expectedTag: true,343 }344 _, err := common.RunString(rt, `345 let res = ws.connect("ws://demos.kaazing.com/echo", function(socket){346 socket.on("open", function() {347 socket.send("test")348 })349 socket.on("message", function (data){350 if (!data=="test") {351 throw new Error ("echo'd data doesn't match our message!");352 }353 socket.close()354 });355 });356 `)357 assert.NoError(t, err)358 for _, sampleContainer := range stats.GetBufferedSamples(samples) {359 for _, sample := range sampleContainer.GetSamples() {360 for emittedTag := range sample.Tags.CloneTags() {361 assert.Equal(t, expectedTag, emittedTag)362 }363 }364 }365 })366 }367}368func TestTLSConfig(t *testing.T) {369 root, err := lib.NewGroup("", nil)370 assert.NoError(t, err)371 rt := goja.New()372 rt.SetFieldNameMapper(common.FieldNameMapper{})373 dialer := netext.NewDialer(net.Dialer{374 Timeout: 10 * time.Second,375 KeepAlive: 60 * time.Second,376 DualStack: true,377 })378 samples := make(chan stats.SampleContainer, 1000)379 state := &lib.State{380 Group: root,381 Dialer: dialer,382 Options: lib.Options{383 SystemTags: lib.GetTagSet("url", "proto", "status", "subproto", "ip"),384 },385 Samples: samples,386 }387 ctx := context.Background()388 ctx = lib.WithState(ctx, state)389 ctx = common.WithRuntime(ctx, rt)390 rt.Set("ws", common.Bind(rt, New(), &ctx))391 tb := testutils.NewHTTPMultiBin(t)392 defer tb.Cleanup()393 url := makeWsProto(tb.ServerHTTPS.URL) + "/ws-close"394 t.Run("insecure skip verify", func(t *testing.T) {395 state.TLSConfig = &tls.Config{396 InsecureSkipVerify: true,397 }398 _, err := common.RunString(rt, fmt.Sprintf(`399 let res = ws.connect("%s", function(socket){400 socket.close()401 });402 if (res.status != 101) { throw new Error("TLS connection failed with status: " + res.status); }403 `, url))404 assert.NoError(t, err)405 })406 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", url, 101, "")407 t.Run("custom certificates", func(t *testing.T) {408 state.TLSConfig = tb.TLSClientConfig409 _, err := common.RunString(rt, fmt.Sprintf(`410 let res = ws.connect("%s", function(socket){411 socket.close()412 });413 if (res.status != 101) { throw new Error("TLS connection failed with status: " + res.status); }414 `, url))415 assert.NoError(t, err)416 })417 assertSessionMetricsEmitted(t, stats.GetBufferedSamples(samples), "", url, 101, "")418}...

Full Screen

Full Screen

dialer.go

Source:dialer.go Github

copy

Full Screen

...153// GetTags implements the stats.ConnectedSampleContainer interface.154func (ntr *NetTrail) GetTags() *stats.SampleTags {155 return ntr.Tags156}157// GetTime implements the stats.ConnectedSampleContainer interface.158func (ntr *NetTrail) GetTime() time.Time {159 return ntr.EndTime160}161// Conn wraps net.Conn and keeps track of sent and received data size162type Conn struct {163 net.Conn164 BytesRead, BytesWritten *int64165}166func (c *Conn) Read(b []byte) (int, error) {167 n, err := c.Conn.Read(b)168 if n > 0 {169 atomic.AddInt64(c.BytesRead, int64(n))170 }171 return n, err172}...

Full Screen

Full Screen

GetTime

Using AI Code Generation

copy

Full Screen

1import (2func main() {3vm := otto.New()4netext.Require(vm)5modules.Require(vm)6vm.Run(`7var http = require("k6/http");8var net = require("k6/net");9console.log(res.status);10console.log("Current time is "+net.GetTime());11}

Full Screen

Full Screen

GetTime

Using AI Code Generation

copy

Full Screen

1import (2func main() {3vm := otto.New()4underscore.Enable(vm)5modules.Register(vm)6common.Bind(vm, map[string]interface{}{}, map[string]*common.BindData{})7vm.Run(`8var net = require("k6/netext");9var res = net.GetTime();10console.log(res);11}

Full Screen

Full Screen

GetTime

Using AI Code Generation

copy

Full Screen

1import (2func main() {3fmt.Println(netext.GetTime())4}5import (6func main() {7fmt.Println(netext.GetTime())8}9.\1.go:7: undefined: netext in netext.GetTime()

Full Screen

Full Screen

GetTime

Using AI Code Generation

copy

Full Screen

1import (2func TestGetTime(t *testing.T) {3req, err := http.NewRequest("GET", "/", nil)4if err != nil {5t.Fatal(err)6}7rr := httptest.NewRecorder()8handler := http.HandlerFunc(GetTime)9handler.ServeHTTP(rr, req)10if status := rr.Code; status != http.StatusOK {11t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)12}13expected := `{"time":"2019-09-07T18:30:37.227Z"}`14if rr.Body.String() != expected {15t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected)16}17}18import (19func TestGetTime(t *testing.T) {20req, err := http.NewRequest("GET", "/", nil)21if err != nil {22t.Fatal(err)23}24rr := httptest.NewRecorder()25handler := http.HandlerFunc(GetTime)26handler.ServeHTTP(rr, req)27if status := rr.Code; status != http.StatusOK {28t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)29}30expected := `{"time":"2019-09-07T18:30:37.227Z"}`31if rr.Body.String() != expected {32t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), expected)33}34}

Full Screen

Full Screen

GetTime

Using AI Code Generation

copy

Full Screen

1import (2type MainController struct {3}4func (this *MainController) Get() {5}6func main() {7 beego.Router("/", &MainController{})8 beego.Run()9}10{{.time}}11import (12type MainController struct {13}14func (this *MainController) Get() {15}16func main() {17 beego.Router("/", &MainController{})18 beego.Run()19}20{{.time}}21import (22type MainController struct {23}24func (this *MainController) Get() {25}26func main() {27 beego.Router("/", &MainController{})28 beego.Run()29}30{{.time}}31import (32type MainController struct {33}34func (this *MainController) Get() {35}36func main() {37 beego.Router("/", &MainController{})38 beego.Run()39}40{{

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