How to use State method of modulestest Package

Best K6 code snippet using modulestest.State

k6_test.go

Source:k6_test.go Github

copy

Full Screen

...38 &modulestest.VU{39 RuntimeField: rt,40 InitEnvField: &common.InitEnvironment{},41 CtxField: context.Background(),42 StateField: nil,43 },44 ).(*K6)45 require.True(t, ok)46 require.NoError(t, rt.Set("k6", m.Exports().Named))47 _, err := rt.RunString(`k6.fail("blah")`)48 assert.Contains(t, err.Error(), "blah")49}50func TestSleep(t *testing.T) {51 t.Parallel()52 testdata := map[string]time.Duration{53 "1": 1 * time.Second,54 "1.0": 1 * time.Second,55 "0.5": 500 * time.Millisecond,56 }57 for name, d := range testdata {58 d := d59 t.Run(name, func(t *testing.T) {60 t.Parallel()61 rt := goja.New()62 m, ok := New().NewModuleInstance(63 &modulestest.VU{64 RuntimeField: rt,65 InitEnvField: &common.InitEnvironment{},66 CtxField: context.Background(),67 StateField: nil,68 },69 ).(*K6)70 require.True(t, ok)71 require.NoError(t, rt.Set("k6", m.Exports().Named))72 startTime := time.Now()73 _, err := rt.RunString(`k6.sleep(1)`)74 endTime := time.Now()75 assert.NoError(t, err)76 assert.True(t, endTime.Sub(startTime) > d, "did not sleep long enough")77 })78 }79 t.Run("Cancel", func(t *testing.T) {80 t.Parallel()81 rt := goja.New()82 ctx, cancel := context.WithCancel(context.Background())83 m, ok := New().NewModuleInstance(84 &modulestest.VU{85 RuntimeField: rt,86 InitEnvField: &common.InitEnvironment{},87 CtxField: ctx,88 StateField: nil,89 },90 ).(*K6)91 require.True(t, ok)92 require.NoError(t, rt.Set("k6", m.Exports().Named))93 dch := make(chan time.Duration)94 go func() {95 startTime := time.Now()96 _, err := rt.RunString(`k6.sleep(10)`)97 endTime := time.Now()98 assert.NoError(t, err)99 dch <- endTime.Sub(startTime)100 }()101 time.Sleep(1 * time.Second)102 cancel()103 d := <-dch104 assert.True(t, d > 500*time.Millisecond, "did not sleep long enough")105 assert.True(t, d < 2*time.Second, "slept for too long!!")106 })107}108func TestRandSeed(t *testing.T) {109 t.Parallel()110 rt := goja.New()111 m, ok := New().NewModuleInstance(112 &modulestest.VU{113 RuntimeField: rt,114 InitEnvField: &common.InitEnvironment{},115 CtxField: context.Background(),116 StateField: nil,117 },118 ).(*K6)119 require.True(t, ok)120 require.NoError(t, rt.Set("k6", m.Exports().Named))121 rand := 0.8487305991992138122 _, err := rt.RunString(fmt.Sprintf(`123 var rnd = Math.random();124 if (rnd == %.16f) { throw new Error("wrong random: " + rnd); }125 `, rand))126 assert.NoError(t, err)127 _, err = rt.RunString(fmt.Sprintf(`128 k6.randomSeed(12345)129 var rnd = Math.random();130 if (rnd != %.16f) { throw new Error("wrong random: " + rnd); }131 `, rand))132 assert.NoError(t, err)133}134func TestGroup(t *testing.T) {135 t.Parallel()136 setupGroupTest := func() (*goja.Runtime, *lib.State, *lib.Group) {137 root, err := lib.NewGroup("", nil)138 assert.NoError(t, err)139 rt := goja.New()140 state := &lib.State{141 Group: root,142 Samples: make(chan metrics.SampleContainer, 1000),143 Tags: lib.NewTagMap(nil),144 Options: lib.Options{145 SystemTags: metrics.NewSystemTagSet(metrics.TagGroup),146 },147 }148 state.BuiltinMetrics = metrics.RegisterBuiltinMetrics(metrics.NewRegistry())149 m, ok := New().NewModuleInstance(150 &modulestest.VU{151 RuntimeField: rt,152 InitEnvField: &common.InitEnvironment{},153 CtxField: context.Background(),154 StateField: state,155 },156 ).(*K6)157 require.True(t, ok)158 require.NoError(t, rt.Set("k6", m.Exports().Named))159 return rt, state, root160 }161 t.Run("Valid", func(t *testing.T) {162 t.Parallel()163 rt, state, root := setupGroupTest()164 assert.Equal(t, state.Group, root)165 require.NoError(t, rt.Set("fn", func() {166 groupTag, ok := state.Tags.Get("group")167 require.True(t, ok)168 assert.Equal(t, groupTag, "::my group")169 assert.Equal(t, state.Group.Name, "my group")170 assert.Equal(t, state.Group.Parent, root)171 }))172 _, err := rt.RunString(`k6.group("my group", fn)`)173 assert.NoError(t, err)174 assert.Equal(t, state.Group, root)175 groupTag, ok := state.Tags.Get("group")176 require.True(t, ok)177 assert.Equal(t, groupTag, root.Name)178 })179 t.Run("Invalid", func(t *testing.T) {180 t.Parallel()181 rt, _, _ := setupGroupTest()182 _, err := rt.RunString(`k6.group("::", function() { throw new Error("nooo") })`)183 assert.Contains(t, err.Error(), "group and check names may not contain '::'")184 })185}186func checkTestRuntime(t testing.TB) (*goja.Runtime, chan metrics.SampleContainer, *metrics.BuiltinMetrics) {187 rt := goja.New()188 root, err := lib.NewGroup("", nil)189 assert.NoError(t, err)190 samples := make(chan metrics.SampleContainer, 1000)191 state := &lib.State{192 Group: root,193 Options: lib.Options{194 SystemTags: &metrics.DefaultSystemTagSet,195 },196 Samples: samples,197 Tags: lib.NewTagMap(map[string]string{198 "group": root.Path,199 }),200 }201 state.BuiltinMetrics = metrics.RegisterBuiltinMetrics(metrics.NewRegistry())202 m, ok := New().NewModuleInstance(203 &modulestest.VU{204 RuntimeField: rt,205 InitEnvField: &common.InitEnvironment{},206 CtxField: context.Background(),207 StateField: state,208 },209 ).(*K6)210 require.True(t, ok)211 require.NoError(t, rt.Set("k6", m.Exports().Named))212 return rt, samples, state.BuiltinMetrics213}214func TestCheckObject(t *testing.T) {215 t.Parallel()216 rt, samples, builtinMetrics := checkTestRuntime(t)217 _, err := rt.RunString(`k6.check(null, { "check": true })`)218 assert.NoError(t, err)219 bufSamples := metrics.GetBufferedSamples(samples)220 if assert.Len(t, bufSamples, 1) {221 sample, ok := bufSamples[0].(metrics.Sample)222 require.True(t, ok)223 assert.NotZero(t, sample.Time)224 assert.Equal(t, builtinMetrics.Checks, sample.Metric)225 assert.Equal(t, float64(1), sample.Value)226 assert.Equal(t, map[string]string{227 "group": "",228 "check": "check",229 }, sample.Tags.CloneTags())230 }231 t.Run("Multiple", func(t *testing.T) {232 t.Parallel()233 rt, samples, _ := checkTestRuntime(t)234 _, err := rt.RunString(`k6.check(null, { "a": true, "b": false })`)235 assert.NoError(t, err)236 bufSamples := metrics.GetBufferedSamples(samples)237 assert.Len(t, bufSamples, 2)238 var foundA, foundB bool239 for _, sampleC := range bufSamples {240 for _, sample := range sampleC.GetSamples() {241 name, ok := sample.Tags.Get("check")242 assert.True(t, ok)243 switch name {244 case "a":245 assert.False(t, foundA, "duplicate 'a'")246 foundA = true247 case "b":248 assert.False(t, foundB, "duplicate 'b'")249 foundB = true250 default:251 assert.Fail(t, name)252 }253 }254 }255 assert.True(t, foundA, "missing 'a'")256 assert.True(t, foundB, "missing 'b'")257 })258 t.Run("Invalid", func(t *testing.T) {259 t.Parallel()260 rt, _, _ := checkTestRuntime(t)261 _, err := rt.RunString(`k6.check(null, { "::": true })`)262 assert.Contains(t, err.Error(), "group and check names may not contain '::'")263 })264}265func TestCheckArray(t *testing.T) {266 t.Parallel()267 rt, samples, builtinMetrics := checkTestRuntime(t)268 _, err := rt.RunString(`k6.check(null, [ true ])`)269 assert.NoError(t, err)270 bufSamples := metrics.GetBufferedSamples(samples)271 if assert.Len(t, bufSamples, 1) {272 sample, ok := bufSamples[0].(metrics.Sample)273 require.True(t, ok)274 assert.NotZero(t, sample.Time)275 assert.Equal(t, builtinMetrics.Checks, sample.Metric)276 assert.Equal(t, float64(1), sample.Value)277 assert.Equal(t, map[string]string{278 "group": "",279 "check": "0",280 }, sample.Tags.CloneTags())281 }282}283func TestCheckLiteral(t *testing.T) {284 t.Parallel()285 rt, samples, _ := checkTestRuntime(t)286 _, err := rt.RunString(`k6.check(null, 12345)`)287 assert.NoError(t, err)288 assert.Len(t, metrics.GetBufferedSamples(samples), 0)289}290func TestCheckNull(t *testing.T) {291 t.Parallel()292 rt, samples, _ := checkTestRuntime(t)293 _, err := rt.RunString(`k6.check(5)`)294 require.Error(t, err)295 assert.Contains(t, err.Error(), "no checks provided")296 assert.Len(t, metrics.GetBufferedSamples(samples), 0)297}298func TestCheckThrows(t *testing.T) {299 t.Parallel()300 rt, samples, builtinMetrics := checkTestRuntime(t)301 _, err := rt.RunString(`302 k6.check(null, {303 "a": function() { throw new Error("error A") },304 "b": function() { throw new Error("error B") },305 })306 `)307 assert.EqualError(t, err, "Error: error A at a (<eval>:3:28(3))")308 bufSamples := metrics.GetBufferedSamples(samples)309 if assert.Len(t, bufSamples, 1) {310 sample, ok := bufSamples[0].(metrics.Sample)311 require.True(t, ok)312 assert.NotZero(t, sample.Time)313 assert.Equal(t, builtinMetrics.Checks, sample.Metric)314 assert.Equal(t, float64(0), sample.Value)315 assert.Equal(t, map[string]string{316 "group": "",317 "check": "a",318 }, sample.Tags.CloneTags())319 }320}321func TestCheckTypes(t *testing.T) {322 t.Parallel()323 templates := map[string]string{324 "Literal": `k6.check(null,{"check": %s})`,325 "Callable": `k6.check(null,{"check": function() { return %s; }})`,326 "Callable/Arg": `k6.check(%s,{"check": function(v) {return v; }})`,327 }328 testdata := map[string]bool{329 `0`: false,330 `1`: true,331 `-1`: true,332 `""`: false,333 `"true"`: true,334 `"false"`: true,335 `true`: true,336 `false`: false,337 `null`: false,338 `undefined`: false,339 }340 for name, tpl := range templates {341 name, tpl := name, tpl342 t.Run(name, func(t *testing.T) {343 t.Parallel()344 for value, succ := range testdata {345 value, succ := value, succ346 t.Run(value, func(t *testing.T) {347 t.Parallel()348 rt, samples, builtinMetrics := checkTestRuntime(t)349 v, err := rt.RunString(fmt.Sprintf(tpl, value))350 if assert.NoError(t, err) {351 assert.Equal(t, succ, v.Export())352 }353 bufSamples := metrics.GetBufferedSamples(samples)354 if assert.Len(t, bufSamples, 1) {355 sample, ok := bufSamples[0].(metrics.Sample)356 require.True(t, ok)357 assert.NotZero(t, sample.Time)358 assert.Equal(t, builtinMetrics.Checks, sample.Metric)359 if succ {360 assert.Equal(t, float64(1), sample.Value)361 } else {362 assert.Equal(t, float64(0), sample.Value)363 }364 assert.Equal(t, map[string]string{365 "group": "",366 "check": "check",367 }, sample.Tags.CloneTags())368 }369 })370 }371 })372 }373}374func TestCheckContextExpiry(t *testing.T) {375 t.Parallel()376 rt := goja.New()377 ctx, cancel := context.WithCancel(context.Background())378 root, err := lib.NewGroup("", nil)379 require.NoError(t, err)380 samples := make(chan metrics.SampleContainer, 1000)381 state := &lib.State{382 Group: root,383 Options: lib.Options{384 SystemTags: &metrics.DefaultSystemTagSet,385 },386 Samples: samples,387 Tags: lib.NewTagMap(map[string]string{388 "group": root.Path,389 }),390 }391 state.BuiltinMetrics = metrics.RegisterBuiltinMetrics(metrics.NewRegistry())392 m, ok := New().NewModuleInstance(393 &modulestest.VU{394 RuntimeField: rt,395 InitEnvField: &common.InitEnvironment{},396 CtxField: ctx,397 StateField: state,398 },399 ).(*K6)400 require.True(t, ok)401 require.NoError(t, rt.Set("k6", m.Exports().Named))402 v, err := rt.RunString(`k6.check(null, { "check": true })`)403 if assert.NoError(t, err) {404 assert.Equal(t, true, v.Export())405 }406 check, _ := root.Check("check")407 assert.Equal(t, int64(1), check.Passes)408 assert.Equal(t, int64(0), check.Fails)409 cancel()410 v, err = rt.RunString(`k6.check(null, { "check": true })`)411 require.NoError(t, err)...

Full Screen

Full Screen

bench_test.go

Source:bench_test.go Github

copy

Full Screen

...76 ts.server.Close()77 close(ch) // this might need to be elsewhere78 })79 ts.vu = new(modulestest.VU)80 ts.vu.StateField = new(lib.State)81 ts.vu.CtxField = context.Background()82 ts.vu.StateField.Tags = lib.NewTagMap(nil)83 ts.vu.StateField.Transport = ts.server.Client().Transport84 ts.vu.StateField.BPool = bpool.NewBufferPool(123)85 ts.vu.StateField.Samples = ch86 ts.vu.StateField.BuiltinMetrics = metrics.RegisterBuiltinMetrics(metrics.NewRegistry())87 go func() {88 for range ch {89 }90 }()91 return ts92}93func BenchmarkStoreFromPrecompiledTemplates(b *testing.B) {94 s := newTestServer(b)95 c := &Client{96 client: &http.Client{},97 cfg: &Config{98 Url: s.server.URL,99 Timeout: "100s",100 },...

Full Screen

Full Screen

batch_test.go

Source:batch_test.go Github

copy

Full Screen

...8 "go.k6.io/k6/metrics"9)10func BenchmarkNewBatch(b *testing.B) {11 samples := make(chan metrics.SampleContainer)12 state := &lib.State{13 Samples: samples,14 VUID: 15,15 }16 ctx, cancel := context.WithCancel(context.Background())17 vu := &modulestest.VU{18 CtxField: ctx,19 StateField: state,20 }21 defer cancel()22 defer close(samples)23 go func() { // this is so that we read the send samples24 for range samples {25 }26 }()27 faker := gofakeit.New(12345)28 cardinalities := map[string]int{29 "app": 5,30 "namespace": 10,31 "pod": 100,32 }33 streams, minBatchSize, maxBatchSize := 5, 500, 100034 labels := newLabelPool(faker, cardinalities)35 c := Client{36 vu: vu,37 }38 b.ResetTimer()39 b.ReportAllocs()40 for i := 0; i < b.N; i++ {41 _ = c.newBatch(labels, streams, minBatchSize, maxBatchSize)42 }43}44func BenchmarkEncode(b *testing.B) {45 samples := make(chan metrics.SampleContainer)46 state := &lib.State{47 Samples: samples,48 VUID: 15,49 }50 ctx, cancel := context.WithCancel(context.Background())51 vu := &modulestest.VU{52 CtxField: ctx,53 StateField: state,54 }55 defer cancel()56 defer close(samples)57 go func() { // this is so that we read the send samples58 for range samples {59 }60 }()61 faker := gofakeit.New(12345)62 cardinalities := map[string]int{63 "app": 5,64 "namespace": 10,65 "pod": 100,66 }67 streams, minBatchSize, maxBatchSize := 5, 500, 1000...

Full Screen

Full Screen

State

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 modulestest.State()4 fmt.Println("main")5}6import (7func main() {8 modulestest.State()9 fmt.Println("main")10}11import (12func main() {13 modulestest.State()14 fmt.Println("main")15}16import (17func main() {18 modulestest.State()19 fmt.Println("main")20}21import (22func main() {23 modulestest.State()24 fmt.Println("main")25}26import (27func main() {28 modulestest.State()29 fmt.Println("main")30}31import (32func main() {33 modulestest.State()34 fmt.Println("main")35}36import (37func main() {38 modulestest.State()39 fmt.Println("main")40}41import (42func main() {43 modulestest.State()44 fmt.Println("main")45}46import (47func main() {48 modulestest.State()49 fmt.Println("main")50}51import (

Full Screen

Full Screen

State

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 modulestest.State()5}6import (7func State() {8 fmt.Println("This is a test")9}

Full Screen

Full Screen

State

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("modulestest.State():", modulestest.State())4}5import (6func State() string {7 return fmt.Sprintf("modulestest.State(): %s", modules.State())8}9import (10func State() string {11 return fmt.Sprintf("modules.State(): %s", "ok")12}13import (14func main() {15 fmt.Println("modulestest.State():", modulestest.State())16 fmt.Println("modules.State():", modules.State())17}18import (19func State() string {20 return fmt.Sprintf("modulestest.State(): %s", modules.State())21}22import (23func main() {24 fmt.Println("modulestest.State():", modulestest.State())25}

Full Screen

Full Screen

State

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m := modulestest{}4 m.State()5}6import (7func main() {8 m := modulestest{}9 m.State()10}11import (

Full Screen

Full Screen

State

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 modulestest := testing.Modulestest{}5 modulestest.State()6}

Full Screen

Full Screen

State

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4 modulestest.State()5}6import (7func main() {8 fmt.Println("Hello World!")9 modulestest.State()10}11import (12func main() {13 fmt.Println("Hello World!")14 modulestest.State()15}16import (17func main() {18 fmt.Println("Hello World!")19 modulestest.State()20}21import (22func main() {23 fmt.Println("Hello World!")24 modulestest.State()25}26import (27func main() {28 fmt.Println("Hello World!")29 modulestest.State()30}31import (32func main() {33 fmt.Println("Hello World!")34 modulestest.State()35}36import (37func main() {38 fmt.Println("Hello World!")39 modulestest.State()40}41import (

Full Screen

Full Screen

State

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "github.com/udhos/gobus/modules"3func main() {4 mod := modules.New()5 fmt.Println(mod.State())6}7import "fmt"8import "github.com/udhos/gobus/modules"9func main() {10 mod := modules.New()11 fmt.Println(mod.State())12}13import "fmt"14import "github.com/udhos/gobus/modules"15func main() {16 mod := modules.New()17 fmt.Println(mod.State())18}19import "fmt"20import "github.com/udhos/gobus/modules"21func main() {22 mod := modules.New()23 fmt.Println(mod.State())24}25import "fmt"26import "github.com/udhos/gobus/modules"27func main() {28 mod := modules.New()29 fmt.Println(mod.State())30}31import "fmt"32import "github.com/udhos/gobus/modules"33func main() {34 mod := modules.New()35 fmt.Println(mod.State())36}37import "fmt"38import "github.com/udhos/gobus/modules"39func main() {40 mod := modules.New()41 fmt.Println(mod.State())42}43import "fmt"44import "github.com/udhos/gobus/modules"45func main() {46 mod := modules.New()47 fmt.Println(mod.State())48}49import "fmt"50import "github.com/udhos/gobus/modules"51func main() {52 mod := modules.New()53 fmt.Println(mod.State())54}

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.

Run K6 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful