Best K6 code snippet using execution.NewModuleInstance
execution_test.go
Source:execution_test.go
...43 var (44 rt = goja.New()45 ctx = context.Background()46 )47 m, ok := New().NewModuleInstance(48 &modulestest.VU{49 RuntimeField: rt,50 InitEnvField: &common.InitEnvironment{},51 CtxField: ctx,52 StateField: state,53 },54 ).(*ModuleInstance)55 require.True(t, ok)56 require.NoError(t, rt.Set("exec", m.Exports().Default))57 return execEnv{58 Module: m,59 Runtime: rt,60 LogHook: logHook,61 }62}63func TestVUTags(t *testing.T) {64 t.Parallel()65 t.Run("Get", func(t *testing.T) {66 t.Parallel()67 tenv := setupTagsExecEnv(t)68 tag, err := tenv.Runtime.RunString(`exec.vu.tags["vu"]`)69 require.NoError(t, err)70 assert.Equal(t, "42", tag.String())71 // not found72 tag, err = tenv.Runtime.RunString(`exec.vu.tags["not-existing-tag"]`)73 require.NoError(t, err)74 assert.Equal(t, "undefined", tag.String())75 })76 t.Run("JSONEncoding", func(t *testing.T) {77 t.Parallel()78 tenv := setupTagsExecEnv(t)79 state := tenv.Module.vu.State()80 state.Tags.Set("custom-tag", "mytag1")81 encoded, err := tenv.Runtime.RunString(`JSON.stringify(exec.vu.tags)`)82 require.NoError(t, err)83 assert.JSONEq(t, `{"vu":"42","custom-tag":"mytag1"}`, encoded.String())84 })85 t.Run("Set", func(t *testing.T) {86 t.Parallel()87 t.Run("SuccessAccetedTypes", func(t *testing.T) {88 t.Parallel()89 // bool and numbers are implicitly converted into string90 tests := map[string]struct {91 v interface{}92 exp string93 }{94 "string": {v: `"tag1"`, exp: "tag1"},95 "bool": {v: true, exp: "true"},96 "int": {v: 101, exp: "101"},97 "float": {v: 3.14, exp: "3.14"},98 }99 tenv := setupTagsExecEnv(t)100 for _, tc := range tests {101 _, err := tenv.Runtime.RunString(fmt.Sprintf(`exec.vu.tags["mytag"] = %v`, tc.v))102 require.NoError(t, err)103 val, err := tenv.Runtime.RunString(`exec.vu.tags["mytag"]`)104 require.NoError(t, err)105 assert.Equal(t, tc.exp, val.String())106 }107 })108 t.Run("SuccessOverwriteSystemTag", func(t *testing.T) {109 t.Parallel()110 tenv := setupTagsExecEnv(t)111 _, err := tenv.Runtime.RunString(`exec.vu.tags["vu"] = "vu101"`)112 require.NoError(t, err)113 val, err := tenv.Runtime.RunString(`exec.vu.tags["vu"]`)114 require.NoError(t, err)115 assert.Equal(t, "vu101", val.String())116 })117 t.Run("DiscardWrongTypeRaisingError", func(t *testing.T) {118 t.Parallel()119 tenv := setupTagsExecEnv(t)120 state := tenv.Module.vu.State()121 state.Options.Throw = null.BoolFrom(true)122 require.NotNil(t, state)123 // array124 _, err := tenv.Runtime.RunString(`exec.vu.tags["custom-tag"] = [1, 3, 5]`)125 require.Contains(t, err.Error(), "only String, Boolean and Number")126 // object127 _, err = tenv.Runtime.RunString(`exec.vu.tags["custom-tag"] = {f1: "value1", f2: 4}`)128 require.Contains(t, err.Error(), "only String, Boolean and Number")129 })130 t.Run("DiscardWrongTypeOnlyWarning", func(t *testing.T) {131 t.Parallel()132 tenv := setupTagsExecEnv(t)133 _, err := tenv.Runtime.RunString(`exec.vu.tags["custom-tag"] = [1, 3, 5]`)134 require.NoError(t, err)135 entries := tenv.LogHook.Drain()136 require.Len(t, entries, 1)137 assert.Contains(t, entries[0].Message, "discarded")138 })139 })140}141func TestAbortTest(t *testing.T) { //nolint:tparallel142 t.Parallel()143 var (144 rt = goja.New()145 state = &lib.State{}146 ctx = context.Background()147 )148 m, ok := New().NewModuleInstance(149 &modulestest.VU{150 RuntimeField: rt,151 InitEnvField: &common.InitEnvironment{},152 CtxField: ctx,153 StateField: state,154 },155 ).(*ModuleInstance)156 require.True(t, ok)157 require.NoError(t, rt.Set("exec", m.Exports().Default))158 prove := func(t *testing.T, script, reason string) {159 _, err := rt.RunString(script)160 require.NotNil(t, err)161 var x *goja.InterruptedError162 assert.ErrorAs(t, err, &x)163 v, ok := x.Value().(*common.InterruptError)164 require.True(t, ok)165 require.Equal(t, v.Reason, reason)166 }167 t.Run("default reason", func(t *testing.T) { //nolint: paralleltest168 prove(t, "exec.test.abort()", common.AbortTest)169 })170 t.Run("custom reason", func(t *testing.T) { //nolint: paralleltest171 prove(t, `exec.test.abort("mayday")`, fmt.Sprintf("%s: mayday", common.AbortTest))172 })173}174func TestOptionsTestFull(t *testing.T) {175 t.Parallel()176 expected := `{"paused":true,"scenarios":{"const-vus":{"executor":"constant-vus","startTime":"10s","gracefulStop":"30s","env":{"FOO":"bar"},"exec":"default","tags":{"tagkey":"tagvalue"},"vus":50,"duration":"10m0s"}},"executionSegment":"0:1/4","executionSegmentSequence":"0,1/4,1/2,1","noSetup":true,"setupTimeout":"1m0s","noTeardown":true,"teardownTimeout":"5m0s","rps":100,"dns":{"ttl":"1m","select":"roundRobin","policy":"any"},"maxRedirects":3,"userAgent":"k6-user-agent","batch":15,"batchPerHost":5,"httpDebug":"full","insecureSkipTLSVerify":true,"tlsCipherSuites":["TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"],"tlsVersion":{"min":"tls1.2","max":"tls1.3"},"tlsAuth":[{"domains":["example.com"],"cert":"mycert.pem","key":"mycert-key.pem"}],"throw":true,"thresholds":{"http_req_duration":[{"threshold":"rate>0.01","abortOnFail":true,"delayAbortEval":"10s"}]},"blacklistIPs":["192.0.2.0/24"],"blockHostnames":["test.k6.io","*.example.com"],"hosts":{"test.k6.io":"1.2.3.4:8443"},"noConnectionReuse":true,"noVUConnectionReuse":true,"minIterationDuration":"10s","ext":{"ext-one":{"rawkey":"rawvalue"}},"summaryTrendStats":["avg","min","max"],"summaryTimeUnit":"ms","systemTags":["iter","vu"],"tags":null,"metricSamplesBufferSize":8,"noCookiesReset":true,"discardResponseBodies":true,"consoleOutput":"loadtest.log","tags":{"runtag-key":"runtag-value"},"localIPs":"192.168.20.12-192.168.20.15,192.168.10.0/27"}`177 var (178 rt = goja.New()179 state = &lib.State{180 Options: lib.Options{181 Paused: null.BoolFrom(true),182 Scenarios: map[string]lib.ExecutorConfig{183 "const-vus": executor.ConstantVUsConfig{184 BaseConfig: executor.BaseConfig{185 Name: "const-vus",186 Type: "constant-vus",187 StartTime: types.NullDurationFrom(10 * time.Second),188 GracefulStop: types.NullDurationFrom(30 * time.Second),189 Env: map[string]string{190 "FOO": "bar",191 },192 Exec: null.StringFrom("default"),193 Tags: map[string]string{194 "tagkey": "tagvalue",195 },196 },197 VUs: null.IntFrom(50),198 Duration: types.NullDurationFrom(10 * time.Minute),199 },200 },201 ExecutionSegment: func() *lib.ExecutionSegment {202 seg, err := lib.NewExecutionSegmentFromString("0:1/4")203 require.NoError(t, err)204 return seg205 }(),206 ExecutionSegmentSequence: func() *lib.ExecutionSegmentSequence {207 seq, err := lib.NewExecutionSegmentSequenceFromString("0,1/4,1/2,1")208 require.NoError(t, err)209 return &seq210 }(),211 NoSetup: null.BoolFrom(true),212 NoTeardown: null.BoolFrom(true),213 NoConnectionReuse: null.BoolFrom(true),214 NoVUConnectionReuse: null.BoolFrom(true),215 InsecureSkipTLSVerify: null.BoolFrom(true),216 Throw: null.BoolFrom(true),217 NoCookiesReset: null.BoolFrom(true),218 DiscardResponseBodies: null.BoolFrom(true),219 RPS: null.IntFrom(100),220 MaxRedirects: null.IntFrom(3),221 UserAgent: null.StringFrom("k6-user-agent"),222 Batch: null.IntFrom(15),223 BatchPerHost: null.IntFrom(5),224 SetupTimeout: types.NullDurationFrom(1 * time.Minute),225 TeardownTimeout: types.NullDurationFrom(5 * time.Minute),226 MinIterationDuration: types.NullDurationFrom(10 * time.Second),227 HTTPDebug: null.StringFrom("full"),228 DNS: types.DNSConfig{229 TTL: null.StringFrom("1m"),230 Select: types.NullDNSSelect{DNSSelect: types.DNSroundRobin, Valid: true},231 Policy: types.NullDNSPolicy{DNSPolicy: types.DNSany, Valid: true},232 Valid: true,233 },234 TLSVersion: &lib.TLSVersions{235 Min: tls.VersionTLS12,236 Max: tls.VersionTLS13,237 },238 TLSAuth: []*lib.TLSAuth{239 {240 TLSAuthFields: lib.TLSAuthFields{241 Cert: "mycert.pem",242 Key: "mycert-key.pem",243 Domains: []string{"example.com"},244 },245 },246 },247 TLSCipherSuites: &lib.TLSCipherSuites{248 tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,249 },250 BlacklistIPs: []*lib.IPNet{251 {252 IPNet: func() net.IPNet {253 _, ipv4net, err := net.ParseCIDR("192.0.2.1/24")254 require.NoError(t, err)255 return *ipv4net256 }(),257 },258 },259 Thresholds: map[string]metrics.Thresholds{260 "http_req_duration": {261 Thresholds: []*metrics.Threshold{262 {263 Source: "rate>0.01",264 LastFailed: true,265 AbortOnFail: true,266 AbortGracePeriod: types.NullDurationFrom(10 * time.Second),267 },268 },269 },270 },271 BlockedHostnames: func() types.NullHostnameTrie {272 bh, err := types.NewNullHostnameTrie([]string{"test.k6.io", "*.example.com"})273 require.NoError(t, err)274 return bh275 }(),276 Hosts: map[string]*lib.HostAddress{277 "test.k6.io": {278 IP: []byte{0x01, 0x02, 0x03, 0x04},279 Port: 8443,280 },281 },282 External: map[string]json.RawMessage{283 "ext-one": json.RawMessage(`{"rawkey":"rawvalue"}`),284 },285 SummaryTrendStats: []string{"avg", "min", "max"},286 SummaryTimeUnit: null.StringFrom("ms"),287 SystemTags: func() *metrics.SystemTagSet {288 sysm := metrics.TagIter | metrics.TagVU289 return &sysm290 }(),291 RunTags: metrics.NewSampleTags(map[string]string{"runtag-key": "runtag-value"}),292 MetricSamplesBufferSize: null.IntFrom(8),293 ConsoleOutput: null.StringFrom("loadtest.log"),294 LocalIPs: func() types.NullIPPool {295 npool := types.NullIPPool{}296 err := npool.UnmarshalText([]byte("192.168.20.12-192.168.20.15,192.168.10.0/27"))297 require.NoError(t, err)298 return npool299 }(),300 // The following fields are not expected to be301 // in the final test.options object302 VUs: null.IntFrom(50),303 Iterations: null.IntFrom(100),304 Duration: types.NullDurationFrom(10 * time.Second),305 Stages: []lib.Stage{306 {307 Duration: types.NullDurationFrom(2 * time.Second),308 Target: null.IntFrom(2),309 },310 },311 },312 }313 ctx = context.Background()314 )315 m, ok := New().NewModuleInstance(316 &modulestest.VU{317 RuntimeField: rt,318 InitEnvField: &common.InitEnvironment{},319 CtxField: ctx,320 StateField: state,321 },322 ).(*ModuleInstance)323 require.True(t, ok)324 require.NoError(t, rt.Set("exec", m.Exports().Default))325 opts, err := rt.RunString(`JSON.stringify(exec.test.options)`)326 require.NoError(t, err)327 require.NotNil(t, opts)328 assert.JSONEq(t, expected, opts.String())329}330func TestOptionsTestSetPropertyDenied(t *testing.T) {331 t.Parallel()332 rt := goja.New()333 m, ok := New().NewModuleInstance(334 &modulestest.VU{335 RuntimeField: rt,336 InitEnvField: &common.InitEnvironment{},337 CtxField: context.Background(),338 StateField: &lib.State{339 Options: lib.Options{340 Paused: null.BoolFrom(true),341 },342 },343 },344 ).(*ModuleInstance)345 require.True(t, ok)346 require.NoError(t, rt.Set("exec", m.Exports().Default))347 _, err := rt.RunString(`exec.test.options.paused = false`)...
execution.go
Source:execution.go
...43// New returns a pointer to a new RootModule instance.44func New() *RootModule {45 return &RootModule{}46}47// NewModuleInstance implements the modules.IsModuleV2 interface to return48// a new instance for each VU.49func (*RootModule) NewModuleInstance(m modules.InstanceCore) modules.Instance {50 mi := &ModuleInstance{InstanceCore: m}51 rt := m.GetRuntime()52 o := rt.NewObject()53 defProp := func(name string, newInfo func() (*goja.Object, error)) {54 err := o.DefineAccessorProperty(name, rt.ToValue(func() goja.Value {55 obj, err := newInfo()56 if err != nil {57 common.Throw(rt, err)58 }59 return obj60 }), nil, goja.FLAG_FALSE, goja.FLAG_TRUE)61 if err != nil {62 common.Throw(rt, err)63 }...
NewModuleInstance
Using AI Code Generation
1import (2func main() {3 m := minify.New()4 m.AddFunc("application/javascript", js.Minify)5 m.AddFunc("application/ecmascript", js.Minify)6 m.AddFunc("text/ecmascript", js.Minify)7 m.AddFunc("text/javascript", js.Minify)8 m.AddFunc("text/x-ecmascript", js.Minify)9 m.AddFunc("text/x-javascript", js.Minify)10 m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), js.Minify)11 m.AddFuncRegexp(regexp.MustCompile("[/+]ecmascript$"), js.Minify)12 m.AddFuncRegexp(regexp.MustCompile("[/+]javascript$"), js.Minify)13 m.Add("application/javascript", &js.JS{})14 m.Add("application/ecmascript", &js.JS{})15 m.Add("text/ecmascript", &js.JS{})16 m.Add("text/javascript", &js.JS{})17 m.Add("text/x-ecmascript", &js.JS{})18 m.Add("text/x-javascript", &js.JS{})19 m.AddRegexp(regexp.MustCompile("[/+]json$"), &js.JS{})20 m.AddRegexp(regexp.MustCompile("[/+]ecmascript$"), &js.JS{})21 m.AddRegexp(regexp.MustCompile("[/+]javascript$"), &js.JS{})22 m.Add("text/html", &html.Minifier{23 })24 m.Add("text/xml", &xml.Minifier{25 })26 m.Add("application/xml", &xml.Minifier{27 })28 m.Add("image/svg+xml", &svg.Minifier{29 })30 m.Add("text/css", &css.Minifier{31 })32 m.Add("application/ld+json", &jsonld.Minifier{})33 m.Add("application/manifest+json", &manifest.Minifier{})34 m.Add("application/rdf+xml", &rdfxml.Minifier{})35 m.Add("application/rss+xml", &rss.Minifier{})
NewModuleInstance
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 golenv.LoadEnv()5 golmodule.NewModuleInstance("github.com/abhishekkr/gol/golenv")6}7import (8func main() {9 fmt.Println("Hello, playground")10 golenv.LoadEnv()11 golmodule.NewModule("github.com/abhishekkr/gol/golenv")12}
NewModuleInstance
Using AI Code Generation
1import (2func main() {3 vm := otto.New()4 vm.Run(`5 var module = {6 abc: function() {7 return this.foo;8 }9 }10 value, err := vm.Run("module")11 if err != nil {12 panic(err)13 }14 instance, err := vm.NewModuleInstance(value)15 if err != nil {16 panic(err)17 }18 result, err := instance.Call("abc")19 if err != nil {20 panic(err)21 }22}
NewModuleInstance
Using AI Code Generation
1execution := execution.NewExecution()2moduleInstance := execution.NewModuleInstance(module)3execution := execution.NewExecution()4moduleInstance := execution.NewModuleInstance(module)5execution := execution.NewExecution()6moduleInstance := execution.NewModuleInstance(module)7execution := execution.NewExecution()8moduleInstance := execution.NewModuleInstance(module)9execution := execution.NewExecution()10moduleInstance := execution.NewModuleInstance(module)11execution := execution.NewExecution()12moduleInstance := execution.NewModuleInstance(module)13execution := execution.NewExecution()14moduleInstance := execution.NewModuleInstance(module)15execution := execution.NewExecution()16moduleInstance := execution.NewModuleInstance(module)17execution := execution.NewExecution()18moduleInstance := execution.NewModuleInstance(module)
NewModuleInstance
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 moduleInstance := execution.NewModuleInstance("module1", "module1", "module1", "module1")5 moduleInstance.Execute()6}7import (8func main() {9 fmt.Println("Hello, playground")10 moduleInstance := execution.ModuleInstance{"module1", "module1", "module1", "module1"}11 moduleInstance.Execute()12}
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!!