Best K6 code snippet using k6.Check
k6_test.go
Source:k6_test.go
...160 *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)335}336func TestCheckTags(t *testing.T) {337 t.Parallel()338 rt, samples := checkTestRuntime(t)339 v, err := rt.RunString(`k6.check(null, {"check": true}, {a: 1, b: "2"})`)340 if assert.NoError(t, err) {341 assert.Equal(t, true, v.Export())342 }343 bufSamples := stats.GetBufferedSamples(samples)344 if assert.Len(t, bufSamples, 1) {345 sample, ok := bufSamples[0].(stats.Sample)346 require.True(t, ok)347 assert.NotZero(t, sample.Time)348 assert.Equal(t, metrics.Checks, sample.Metric)349 assert.Equal(t, float64(1), sample.Value)350 assert.Equal(t, map[string]string{351 "group": "",352 "check": "check",353 "a": "1",354 "b": "2",355 }, sample.Tags.CloneTags())356 }357}...
k6.go
Source:k6.go
...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 = err142 }143 }144 sampleTags := stats.IntoSampleTags(&tags)145 // Emit! (But only if we have a valid context.)146 select {147 case <-ctx.Done():148 default:149 if val.ToBoolean() {150 atomic.AddInt64(&check.Passes, 1)151 stats.PushIfNotDone(ctx, state.Samples, stats.Sample{Time: t, Metric: metrics.Checks, Tags: sampleTags, Value: 1})152 } else {153 atomic.AddInt64(&check.Fails, 1)154 stats.PushIfNotDone(ctx, state.Samples, stats.Sample{Time: t, Metric: metrics.Checks, Tags: sampleTags, Value: 0})155 // A single failure makes the return value false.156 succ = false157 }158 }159 if exc != nil {160 return succ, exc161 }162 }163 return succ, nil164}...
init_and_modules_test.go
Source:init_and_modules_test.go
...36 "go.k6.io/k6/lib/testutils"37 "go.k6.io/k6/loader"38 "go.k6.io/k6/stats"39)40type CheckModule struct {41 t testing.TB42 initCtxCalled int43 vuCtxCalled int44}45func (cm *CheckModule) InitCtx(ctx context.Context) {46 cm.initCtxCalled++47 assert.NotNil(cm.t, common.GetRuntime(ctx))48 assert.NotNil(cm.t, common.GetInitEnv(ctx))49 assert.Nil(cm.t, lib.GetState(ctx))50}51func (cm *CheckModule) VuCtx(ctx context.Context) {52 cm.vuCtxCalled++53 assert.NotNil(cm.t, common.GetRuntime(ctx))54 assert.Nil(cm.t, common.GetInitEnv(ctx))55 assert.NotNil(cm.t, lib.GetState(ctx))56}57var uniqueModuleNumber int64 //nolint:gochecknoglobals58func TestNewJSRunnerWithCustomModule(t *testing.T) {59 t.Parallel()60 checkModule := &CheckModule{t: t}61 moduleName := fmt.Sprintf("k6/x/check-%d", atomic.AddInt64(&uniqueModuleNumber, 1))62 modules.Register(moduleName, checkModule)63 script := fmt.Sprintf(`64 var check = require("%s");65 check.initCtx();66 module.exports.options = { vus: 1, iterations: 1 };67 module.exports.default = function() {68 check.vuCtx();69 };70 `, moduleName)71 logger := testutils.NewLogger(t)72 rtOptions := lib.RuntimeOptions{CompatibilityMode: null.StringFrom("base")}73 runner, err := js.New(74 logger,...
Check
Using AI Code Generation
1import (2func TestCheck(t *testing.T) {3 root, err := lib.NewGroup("", nil)4 require.NoError(t, err)5 rt := testutils.NewRuntime()6 vu, err := lib.NewVU(1, rt, lib.VUConfig{}, root)7 require.NoError(t, err)8 k6 := k6.New()9 ctx := context.Background()10 ctx = common.WithRuntime(ctx, rt)11 ctx = common.WithState(ctx, &common.State{Options: lib.Options{}})12 mux := httpmultibin.NewHTTPMultiBin(t)13 defer mux.Close()14 req, err := http.NewRequest("GET", mux.HTTPS("test-https"), nil)15 require.NoError(t, err)16 res, err := k6.Request(ctx, req)17 require.NoError(t, err)18 err = k6.Check(ctx, res, nil)19 require.NoError(t, err)20}21import (
Check
Using AI Code Generation
1import (2func TestTerraformKubernetesExample(t *testing.T) {3 t.Parallel()4 uniqueID := random.UniqueId()5 terraformOptions := &terraform.Options{6 Vars: map[string]interface{}{7 "example": fmt.Sprintf("terratest-%s", uniqueID),8 },9 EnvVars: map[string]string{10 },11 }12 defer terraform.Destroy(t, terraformOptions)13 terraform.InitAndApply(t, terraformOptions)14 options := k8s.NewKubectlOptions("", "/home/centos/.kube/config", "default")15 k8s.WaitUntilNumPodsCreated(t, options, 1, 60, 5)16 k8s.WaitUntilServiceAvailable(t, options, "terratest", 60, 5)17 k8s.WaitUntilNumDeploymentsCreated(t, options, 1,
Check
Using AI Code Generation
1import (2func main() {3 vm := otto.New()4 _, err := vm.Run(`5 var k6 = require("k6");6 var check = k6.check;7 var fail = k6.fail;8 var http = k6.http;9 if err != nil {10 log.Fatal(err)11 }12 value, err := vm.Get("check")13 if err != nil {14 log.Fatal(err)15 }16 check, err := value.ToFunction()17 if err != nil {18 log.Fatal(err)19 }20 _, err = check.Call(otto.NullValue(), "test", func(call otto.FunctionCall) otto.Value {21 arg, err := call.Argument(0).ToString()22 if err != nil {23 log.Fatal(err)24 }25 fmt.Println(arg)26 value, err := otto.ToValue(true)27 if err != nil {28 log.Fatal(err)29 }30 })31 if err != nil {32 log.Fatal(err)33 }34 value, err = vm.Get("fail")35 if err != nil {36 log.Fatal(err)37 }38 fail, err := value.ToFunction()39 if err != nil {40 log.Fatal(err)41 }42 _, err = fail.Call(otto.NullValue(), "test", func(call otto.FunctionCall) otto.Value {43 arg, err := call.Argument(0).ToString()44 if err != nil {45 log.Fatal(err)46 }47 fmt.Println(arg)48 value, err := otto.ToValue(true)49 if err != nil {50 log.Fatal(err)51 }52 })53 if err != nil {54 log.Fatal(err)55 }
Check
Using AI Code Generation
1import (2func main() {3 fmt.Println(k6.Check(10))4}5import (6func main() {7 fmt.Println(k6.Check(6))8}
Check
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 k6.Check("hello",func(){},nil)5}6import (7func main() {8 rand.Seed(time.Now().UnixNano())9 a := rand.Intn(100)10 b := rand.Intn(100)11 fmt.Println(a * b)12}13The problem is that I need to multiply two random numbers, but I don't know how to do it. I am not allowed to use the rand.Intn() function twice. I need to use the rand.Intn() function only once. Can someone please help me with this?14import (15func main() {16 rand.Seed(time.Now().UnixNano())17 a := rand.Intn(100)18 b := rand.Intn(100)19 fmt.Println(a * b)20}21The problem is that I need to multiply two random numbers, but I don't know how to do it. I am not allowed to use the rand.Intn() function twice. I need to use the rand.Intn() function only once. Can someone please help me with this?
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!!