Best K6 code snippet using k6.Group
k6_test.go
Source:k6_test.go
...101 if (rnd != %.16f) { throw new Error("wrong random: " + rnd); }102 `, rand))103 assert.NoError(t, err)104}105func TestGroup(t *testing.T) {106 t.Parallel()107 setupGroupTest := func() (*goja.Runtime, *lib.State, *lib.Group) {108 root, err := lib.NewGroup("", nil)109 assert.NoError(t, err)110 rt := goja.New()111 state := &lib.State{Group: root, Samples: make(chan stats.SampleContainer, 1000)}112 ctx := context.Background()113 ctx = lib.WithState(ctx, state)114 ctx = common.WithRuntime(ctx, rt)115 require.NoError(t, rt.Set("k6", common.Bind(rt, New(), &ctx)))116 return rt, state, root117 }118 t.Run("Valid", func(t *testing.T) {119 t.Parallel()120 rt, state, root := setupGroupTest()121 assert.Equal(t, state.Group, root)122 require.NoError(t, rt.Set("fn", func() {123 assert.Equal(t, state.Group.Name, "my group")124 assert.Equal(t, state.Group.Parent, root)125 }))126 _, err := rt.RunString(`k6.group("my group", fn)`)127 assert.NoError(t, err)128 assert.Equal(t, state.Group, root)129 })130 t.Run("Invalid", func(t *testing.T) {131 t.Parallel()132 rt, _, _ := setupGroupTest()133 _, err := rt.RunString(`k6.group("::", function() { throw new Error("nooo") })`)134 assert.Contains(t, err.Error(), "group and check names may not contain '::'")135 })136}137func checkTestRuntime(t testing.TB, ctxs ...*context.Context) (138 *goja.Runtime, chan stats.SampleContainer,139) {140 rt := goja.New()141 root, err := lib.NewGroup("", nil)142 assert.NoError(t, err)143 samples := make(chan stats.SampleContainer, 1000)144 state := &lib.State{145 Group: root,146 Options: lib.Options{147 SystemTags: &stats.DefaultSystemTagSet,148 },149 Samples: samples,150 Tags: map[string]string{"group": root.Path},151 }152 ctx := context.Background()153 if len(ctxs) == 1 { // hacks154 ctx = *ctxs[0]155 }156 ctx = common.WithRuntime(ctx, rt)157 ctx = lib.WithState(ctx, state)158 require.NoError(t, rt.Set("k6", common.Bind(rt, New(), &ctx)))159 if len(ctxs) == 1 { // hacks160 *ctxs[0] = ctx161 }162 return rt, samples163}164func TestCheckObject(t *testing.T) {165 t.Parallel()166 rt, samples := checkTestRuntime(t)167 _, err := rt.RunString(`k6.check(null, { "check": true })`)168 assert.NoError(t, err)169 bufSamples := stats.GetBufferedSamples(samples)170 if assert.Len(t, bufSamples, 1) {171 sample, ok := bufSamples[0].(stats.Sample)172 require.True(t, ok)173 assert.NotZero(t, sample.Time)174 assert.Equal(t, metrics.Checks, sample.Metric)175 assert.Equal(t, float64(1), sample.Value)176 assert.Equal(t, map[string]string{177 "group": "",178 "check": "check",179 }, sample.Tags.CloneTags())180 }181 t.Run("Multiple", func(t *testing.T) {182 t.Parallel()183 rt, samples := checkTestRuntime(t)184 _, err := rt.RunString(`k6.check(null, { "a": true, "b": false })`)185 assert.NoError(t, err)186 bufSamples := stats.GetBufferedSamples(samples)187 assert.Len(t, bufSamples, 2)188 var foundA, foundB bool189 for _, sampleC := range bufSamples {190 for _, sample := range sampleC.GetSamples() {191 name, ok := sample.Tags.Get("check")192 assert.True(t, ok)193 switch name {194 case "a":195 assert.False(t, foundA, "duplicate 'a'")196 foundA = true197 case "b":198 assert.False(t, foundB, "duplicate 'b'")199 foundB = true200 default:201 assert.Fail(t, name)202 }203 }204 }205 assert.True(t, foundA, "missing 'a'")206 assert.True(t, foundB, "missing 'b'")207 })208 t.Run("Invalid", func(t *testing.T) {209 t.Parallel()210 rt, _ := checkTestRuntime(t)211 _, err := rt.RunString(`k6.check(null, { "::": true })`)212 assert.Contains(t, err.Error(), "group and check names may not contain '::'")213 })214}215func TestCheckArray(t *testing.T) {216 t.Parallel()217 rt, samples := checkTestRuntime(t)218 _, err := rt.RunString(`k6.check(null, [ true ])`)219 assert.NoError(t, err)220 bufSamples := stats.GetBufferedSamples(samples)221 if assert.Len(t, bufSamples, 1) {222 sample, ok := bufSamples[0].(stats.Sample)223 require.True(t, ok)224 assert.NotZero(t, sample.Time)225 assert.Equal(t, metrics.Checks, sample.Metric)226 assert.Equal(t, float64(1), sample.Value)227 assert.Equal(t, map[string]string{228 "group": "",229 "check": "0",230 }, sample.Tags.CloneTags())231 }232}233func TestCheckLiteral(t *testing.T) {234 t.Parallel()235 rt, samples := checkTestRuntime(t)236 _, err := rt.RunString(`k6.check(null, 12345)`)237 assert.NoError(t, err)238 assert.Len(t, stats.GetBufferedSamples(samples), 0)239}240func TestCheckThrows(t *testing.T) {241 t.Parallel()242 rt, samples := checkTestRuntime(t)243 _, err := rt.RunString(`244 k6.check(null, {245 "a": function() { throw new Error("error A") },246 "b": function() { throw new Error("error B") },247 })248 `)249 assert.EqualError(t, err, "Error: error A at a (<eval>:3:28(4))")250 bufSamples := stats.GetBufferedSamples(samples)251 if assert.Len(t, bufSamples, 1) {252 sample, ok := bufSamples[0].(stats.Sample)253 require.True(t, ok)254 assert.NotZero(t, sample.Time)255 assert.Equal(t, metrics.Checks, sample.Metric)256 assert.Equal(t, float64(0), sample.Value)257 assert.Equal(t, map[string]string{258 "group": "",259 "check": "a",260 }, sample.Tags.CloneTags())261 }262}263func TestCheckTypes(t *testing.T) {264 t.Parallel()265 templates := map[string]string{266 "Literal": `k6.check(null,{"check": %s})`,267 "Callable": `k6.check(null,{"check": function() { return %s; }})`,268 "Callable/Arg": `k6.check(%s,{"check": function(v) {return v; }})`,269 }270 testdata := map[string]bool{271 `0`: false,272 `1`: true,273 `-1`: true,274 `""`: false,275 `"true"`: true,276 `"false"`: true,277 `true`: true,278 `false`: false,279 `null`: false,280 `undefined`: false,281 }282 for name, tpl := range templates {283 name, tpl := name, tpl284 t.Run(name, func(t *testing.T) {285 t.Parallel()286 for value, succ := range testdata {287 value, succ := value, succ288 t.Run(value, func(t *testing.T) {289 t.Parallel()290 rt, samples := checkTestRuntime(t)291 v, err := rt.RunString(fmt.Sprintf(tpl, value))292 if assert.NoError(t, err) {293 assert.Equal(t, succ, v.Export())294 }295 bufSamples := stats.GetBufferedSamples(samples)296 if assert.Len(t, bufSamples, 1) {297 sample, ok := bufSamples[0].(stats.Sample)298 require.True(t, ok)299 assert.NotZero(t, sample.Time)300 assert.Equal(t, metrics.Checks, sample.Metric)301 if succ {302 assert.Equal(t, float64(1), sample.Value)303 } else {304 assert.Equal(t, float64(0), sample.Value)305 }306 assert.Equal(t, map[string]string{307 "group": "",308 "check": "check",309 }, sample.Tags.CloneTags())310 }311 })312 }313 })314 }315}316func TestCheckContextExpiry(t *testing.T) {317 t.Parallel()318 ctx, cancel := context.WithCancel(context.Background())319 rt, _ := checkTestRuntime(t, &ctx)320 root := lib.GetState(ctx).Group321 v, err := rt.RunString(`k6.check(null, { "check": true })`)322 if assert.NoError(t, err) {323 assert.Equal(t, true, v.Export())324 }325 check, _ := root.Check("check")326 assert.Equal(t, int64(1), check.Passes)327 assert.Equal(t, int64(0), check.Fails)328 cancel()329 v, err = rt.RunString(`k6.check(null, { "check": true })`)330 if assert.NoError(t, err) {331 assert.Equal(t, true, v.Export())332 }333 assert.Equal(t, int64(1), check.Passes)334 assert.Equal(t, int64(0), check.Fails)...
k6.go
Source:k6.go
...32 "go.k6.io/k6/stats"33)34// K6 is just the module struct.35type K6 struct{}36// ErrGroupInInitContext is returned when group() are using in the init context.37var ErrGroupInInitContext = common.NewInitContextError("Using group() in the init context is not supported")38// ErrCheckInInitContext is returned when check() are using in the init context.39var ErrCheckInInitContext = common.NewInitContextError("Using check() in the init context is not supported")40// New returns a new module Struct.41func New() *K6 {42 return &K6{}43}44// Fail is a fancy way of saying `throw "something"`.45func (*K6) Fail(msg string) (goja.Value, error) {46 return goja.Undefined(), errors.New(msg)47}48// Sleep waits the provided seconds before continuing the execution.49func (*K6) Sleep(ctx context.Context, secs float64) {50 timer := time.NewTimer(time.Duration(secs * float64(time.Second)))51 select {52 case <-timer.C:53 case <-ctx.Done():54 timer.Stop()55 }56}57// RandomSeed sets the seed to the random generator used for this VU.58func (*K6) RandomSeed(ctx context.Context, seed int64) {59 randSource := rand.New(rand.NewSource(seed)).Float64 //nolint:gosec60 rt := common.GetRuntime(ctx)61 rt.SetRandSource(randSource)62}63// Group wraps a function call and executes it within the provided group name.64func (*K6) Group(ctx context.Context, name string, fn goja.Callable) (goja.Value, error) {65 state := lib.GetState(ctx)66 if state == nil {67 return nil, ErrGroupInInitContext68 }69 if fn == nil {70 return nil, errors.New("group() requires a callback as a second argument")71 }72 g, err := state.Group.Group(name)73 if err != nil {74 return goja.Undefined(), err75 }76 old := state.Group77 state.Group = g78 shouldUpdateTag := state.Options.SystemTags.Has(stats.TagGroup)79 if shouldUpdateTag {80 state.Tags["group"] = g.Path81 }82 defer func() {83 state.Group = old84 if shouldUpdateTag {85 state.Tags["group"] = old.Path86 }87 }()88 startTime := time.Now()89 ret, err := fn(goja.Undefined())90 t := time.Now()91 tags := state.CloneTags()92 stats.PushIfNotDone(ctx, state.Samples, stats.Sample{93 Time: t,94 Metric: metrics.GroupDuration,95 Tags: stats.IntoSampleTags(&tags),96 Value: stats.D(t.Sub(startTime)),97 })98 return ret, err99}100// Check will emit check metrics for the provided checks.101//nolint:cyclop102func (*K6) Check(ctx context.Context, arg0, checks goja.Value, extras ...goja.Value) (bool, error) {103 state := lib.GetState(ctx)104 if state == nil {105 return false, ErrCheckInInitContext106 }107 rt := common.GetRuntime(ctx)108 t := time.Now()109 // Prepare the metric tags110 commonTags := state.CloneTags()111 if len(extras) > 0 {112 obj := extras[0].ToObject(rt)113 for _, k := range obj.Keys() {114 commonTags[k] = obj.Get(k).String()115 }116 }117 succ := true118 var exc error119 obj := checks.ToObject(rt)120 for _, name := range obj.Keys() {121 val := obj.Get(name)122 tags := make(map[string]string, len(commonTags))123 for k, v := range commonTags {124 tags[k] = v125 }126 // Resolve the check record.127 check, err := state.Group.Check(name)128 if err != nil {129 return false, err130 }131 if state.Options.SystemTags.Has(stats.TagCheck) {132 tags["check"] = check.Name133 }134 // Resolve callables into values.135 fn, ok := goja.AssertFunction(val)136 if ok {137 tmpVal, err := fn(goja.Undefined(), arg0)138 val = tmpVal139 if err != nil {140 val = rt.ToValue(false)141 exc = err...
group_routes_test.go
Source:group_routes_test.go
...32 "go.k6.io/k6/lib"33 "go.k6.io/k6/lib/testutils"34 "go.k6.io/k6/lib/testutils/minirunner"35)36func TestGetGroups(t *testing.T) {37 g0, err := lib.NewGroup("", nil)38 assert.NoError(t, err)39 g1, err := g0.Group("group 1")40 assert.NoError(t, err)41 g2, err := g1.Group("group 2")42 assert.NoError(t, err)43 logger := logrus.New()44 logger.SetOutput(testutils.NewTestOutput(t))45 execScheduler, err := local.NewExecutionScheduler(&minirunner.MiniRunner{Group: g0}, logger)46 require.NoError(t, err)47 engine, err := core.NewEngine(execScheduler, lib.Options{}, lib.RuntimeOptions{}, nil, logger)48 require.NoError(t, err)49 t.Run("list", func(t *testing.T) {50 rw := httptest.NewRecorder()51 NewHandler().ServeHTTP(rw, newRequestWithEngine(engine, "GET", "/v1/groups", nil))52 res := rw.Result()53 body := rw.Body.Bytes()54 assert.Equal(t, http.StatusOK, res.StatusCode)55 assert.NotEmpty(t, body)56 t.Run("document", func(t *testing.T) {57 var doc jsonapi.Document58 assert.NoError(t, json.Unmarshal(body, &doc))59 assert.Nil(t, doc.Data.DataObject)60 if assert.NotEmpty(t, doc.Data.DataArray) {61 assert.Equal(t, "groups", doc.Data.DataArray[0].Type)62 }63 })64 t.Run("groups", func(t *testing.T) {65 var groups []Group66 require.NoError(t, jsonapi.Unmarshal(body, &groups))67 require.Len(t, groups, 3)68 for _, g := range groups {69 switch g.ID {70 case g0.ID:71 assert.Equal(t, "", g.Name)72 assert.Nil(t, g.Parent)73 assert.Equal(t, "", g.ParentID)74 assert.Len(t, g.GroupIDs, 1)75 assert.EqualValues(t, []string{g1.ID}, g.GroupIDs)76 case g1.ID:77 assert.Equal(t, "group 1", g.Name)78 assert.Nil(t, g.Parent)79 assert.Equal(t, g0.ID, g.ParentID)80 assert.EqualValues(t, []string{g2.ID}, g.GroupIDs)81 case g2.ID:82 assert.Equal(t, "group 2", g.Name)83 assert.Nil(t, g.Parent)84 assert.Equal(t, g1.ID, g.ParentID)85 assert.EqualValues(t, []string{}, g.GroupIDs)86 default:87 assert.Fail(t, "Unknown ID: "+g.ID)88 }89 }90 })91 })92 for _, gp := range []*lib.Group{g0, g1, g2} {93 t.Run(gp.Name, func(t *testing.T) {94 rw := httptest.NewRecorder()95 NewHandler().ServeHTTP(rw, newRequestWithEngine(engine, "GET", "/v1/groups/"+gp.ID, nil))96 res := rw.Result()97 assert.Equal(t, http.StatusOK, res.StatusCode)98 })99 }100}...
Group
Using AI Code Generation
1import (2func TestGroup(t *testing.T) {3 tb := testutils.NewHTTPMultiBin(t)4 defer tb.Cleanup()5 tb.Mux.HandleFunc("/v1", func(w http.ResponseWriter, r *http.Request) {6 w.WriteHeader(200)7 })8 tb.Mux.HandleFunc("/v2", func(w http.ResponseWriter, r *http.Request) {9 w.WriteHeader(200)10 })11 tb.Mux.HandleFunc("/v3", func(w http.ResponseWriter, r *http.Request) {12 w.WriteHeader(200)13 })14 tb.Mux.HandleFunc("/v4", func(w http.ResponseWriter, r *http.Request) {15 w.WriteHeader(200)16 })17 tb.Mux.HandleFunc("/v5", func(w http.ResponseWriter, r *http.Request) {18 w.WriteHeader(200)19 })20 tb.Mux.HandleFunc("/v6", func(w http.ResponseWriter, r *http.Request) {21 w.WriteHeader(200)22 })23 tb.Mux.HandleFunc("/v7", func(w http.ResponseWriter, r *http.Request) {24 w.WriteHeader(200)25 })26 tb.Mux.HandleFunc("/v8", func(w http.ResponseWriter, r *http.Request) {27 w.WriteHeader(200)28 })29 tb.Mux.HandleFunc("/v9", func(w http.ResponseWriter, r *http.Request) {30 w.WriteHeader(200)31 })32 tb.Mux.HandleFunc("/v10", func(w http.ResponseWriter, r *http.Request) {33 w.WriteHeader(200)34 })35 tb.Mux.HandleFunc("/v11", func(w http.ResponseWriter, r *http.Request) {36 w.WriteHeader(200)37 })38 tb.Mux.HandleFunc("/v12", func(w http.ResponseWriter, r *http.Request) {39 w.WriteHeader(200)40 })41 tb.Mux.HandleFunc("/v13", func(w http.ResponseWriter, r *http.Request) {42 w.WriteHeader(200)43 })44 tb.Mux.HandleFunc("/v14", func(w http.ResponseWriter, r *http.Request) {45 w.WriteHeader(200)46 })47 tb.Mux.HandleFunc("/v15", func(w http.ResponseWriter, r *http.Request)
Group
Using AI Code Generation
1import (2func init() {3 modules.Register("k6/x/execution", new(Execution))4}5type Execution struct{}6func (*Execution) VU() int64 {7 return int64(lib.GetState(lib.GetState(*lib.Options)).VU)8}9func (*Execution) Iteration() int64 {10 return int64(lib.GetState(lib.GetState(*lib.Options)).Iteration)11}12func (*Execution) Scenario() string {13 return lib.GetState(lib.GetState(*lib.Options)).Scenario.Name14}15import { group, sleep } from "k6";16import { Counter } from "k6/metrics";17import http from "k6/http";18import { check } from "k6";19import { vu, iteration, scenario } from "k6/x/execution";20export let options = {21};22export default function () {23 group("test", function () {24 console.log(`VU: ${vu()}`);25 console.log(`Iteration: ${iteration()}`);26 console.log(`Scenario: ${scenario()}`);27 });28}
Group
Using AI Code Generation
1func (k6 *K6) Group(name string, fn func()) {2 k6.group(name, fn)3}4func (k6 *K6) Group(name string, fn func()) {5 k6.group(name, fn)6}7func (k6 *K6) Group(name string, fn func()) {8 k6.group(name, fn)9}10func (k6 *K6) Group(name string, fn func()) {11 k6.group(name, fn)12}13func (k6 *K6) Group(name string, fn func()) {14 k6.group(name, fn)15}16func (k6 *K6) Group(name string, fn func()) {17 k6.group(name, fn)18}19func (k6 *K6) Group(name string, fn func()) {20 k6.group(name, fn)21}22func (k6 *K6) Group(name string, fn func()) {23 k6.group(name, fn)24}25func (k6 *K6) Group(name string, fn func()) {26 k6.group(name, fn)27}28func (k6 *K6) Group(name string, fn func()) {29 k6.group(name, fn)30}31func (k6 *K6) Group(name string, fn func()) {32 k6.group(name, fn)33}34func (k6 *K6) Group(name string, fn func()) {35 k6.group(name, fn)36}
Group
Using AI Code Generation
1import (2func TestGroup(t *testing.T) {3 rt := js.New()4 rt.Set("k6", modules.GetModules().Get("k6"))5 rt.Set("common", common.Bind(rt, nil))6 rt.Set("lib", lib.GetModules())7 rt.Set("http", modules.GetModules().Get("k6/http"))8 r := testutils.NewRunner(t, rt)9 r.SetOptions(lib.Options{10 VUs: null.IntFrom(1),11 Iterations: null.IntFrom(1),12 Duration: types.NullDurationFrom(100 * time.Millisecond),13 })14 r.SetOptions(lib.Options{15 VUs: null.IntFrom(1),16 Iterations: null.IntFrom(1),17 Duration: types.NullDurationFrom(100 * time.Millisecond),18 })19 _, err := r.RunString(`20 import { check, sleep, group } from "k6";21 import http from "k6/http";22 export let options = {23 };24 export default function() {25 group("test", function() {26 sleep(1);27 });28 };`)29 if err != nil {30 t.Fatal(err)31 }32}33import (
Group
Using AI Code Generation
1import "k6.io/k6/js/modules/k6"2export default function () {3 const group = k6.group("my group", function () {4 })5}6import k6 from "k6"7import { group } from "k6"8export default function () {9 const group = group("my group", function () {10 })11}12import { group } from "k6"13export default function () {14 const group = group("my group", function () {15 })16}17import { group } from "k6"18export default function () {19 const group = group("my group", function () {20 })21}22import { group } from "k6"23export default function () {24 const group = group("my group", function () {25 })26}27import { group } from "k6"28export default function () {29 const group = group("my group", function () {30 })31}32import { group } from "k6"33export default function () {34 const group = group("my group", function () {35 })36}37import { group } from "k6"38export default function () {39 const group = group("my group", function () {40 })41}
Group
Using AI Code Generation
1import (2func main() {3 k6 := modules.Get("k6")4 fmt.Println(k6)5}6{map[Group:0xc0000c7a80]}7import (8func main() {9 k6 := modules.Get("k6")10 fmt.Println(k6)11 k6.Group("group1", func() {12 fmt.Println("This is group1")13 })14}15{map[Group:0xc0000c7a80]}16Group(name, fn)17import (18func main() {19 k6 := modules.Get("k6")20 fmt.Println(k6)21 k6.Group("group1", func() {22 fmt.Println("This is group1")23 })24 k6.Group("group2", func() {25 fmt.Println("This is group2")26 })27}28{map[Group:0xc0000c7a80]}
Group
Using AI Code Generation
1func main() {2 group := k6.Group("Group1", func() {3 })4 group.Run()5}6func main() {7 group := k6.Group("Group2", func() {8 })9 group.Run()10}11func main() {12 group := k6.Group("Group3", func() {13 })14 group.Run()15}16func main() {17 group := k6.Group("Group4", func() {18 })19 group.Run()20}21func main() {22 group := k6.Group("Group5", func() {23 })24 group.Run()25}26func main() {27 group := k6.Group("Group6", func() {28 })29 group.Run()30}
Group
Using AI Code Generation
1group("Group 1", function() {2 check(response, {3 "status code is 200": (response) => response.status === 200,4 });5 });6});7sleep(1);8group("Group 2", function() {
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!!