How to use getSimpleBundle method of js Package

Best K6 code snippet using js.getSimpleBundle

bundle_test.go

Source:bundle_test.go Github

copy

Full Screen

...43 "go.k6.io/k6/lib/types"44 "go.k6.io/k6/loader"45)46const isWindows = runtime.GOOS == "windows"47func getSimpleBundle(tb testing.TB, filename, data string, opts ...interface{}) (*Bundle, error) {48 var (49 fs = afero.NewMemMapFs()50 rtOpts = lib.RuntimeOptions{}51 logger logrus.FieldLogger = testutils.NewLogger(tb)52 )53 for _, o := range opts {54 switch opt := o.(type) {55 case afero.Fs:56 fs = opt57 case lib.RuntimeOptions:58 rtOpts = opt59 case logrus.FieldLogger:60 logger = opt61 }62 }63 return NewBundle(64 logger,65 &loader.SourceData{66 URL: &url.URL{Path: filename, Scheme: "file"},67 Data: []byte(data),68 },69 map[string]afero.Fs{"file": fs, "https": afero.NewMemMapFs()},70 rtOpts,71 metrics.NewRegistry(),72 )73}74func TestNewBundle(t *testing.T) {75 t.Parallel()76 t.Run("Blank", func(t *testing.T) {77 t.Parallel()78 _, err := getSimpleBundle(t, "/script.js", "")79 assert.EqualError(t, err, "no exported functions in script")80 })81 t.Run("Invalid", func(t *testing.T) {82 t.Parallel()83 _, err := getSimpleBundle(t, "/script.js", "\x00")84 assert.NotNil(t, err)85 assert.Contains(t, err.Error(), "SyntaxError: file:///script.js: Unexpected character '\x00' (1:0)\n> 1 | \x00\n")86 })87 t.Run("Error", func(t *testing.T) {88 t.Parallel()89 _, err := getSimpleBundle(t, "/script.js", `throw new Error("aaaa");`)90 exception := new(scriptException)91 assert.ErrorAs(t, err, &exception)92 assert.EqualError(t, err, "Error: aaaa\n\tat file:///script.js:1:7(2)\n")93 })94 t.Run("InvalidExports", func(t *testing.T) {95 t.Parallel()96 _, err := getSimpleBundle(t, "/script.js", `exports = null`)97 assert.EqualError(t, err, "exports must be an object")98 })99 t.Run("DefaultUndefined", func(t *testing.T) {100 t.Parallel()101 _, err := getSimpleBundle(t, "/script.js", `export default undefined;`)102 assert.EqualError(t, err, "no exported functions in script")103 })104 t.Run("DefaultNull", func(t *testing.T) {105 t.Parallel()106 _, err := getSimpleBundle(t, "/script.js", `export default null;`)107 assert.EqualError(t, err, "no exported functions in script")108 })109 t.Run("DefaultWrongType", func(t *testing.T) {110 t.Parallel()111 _, err := getSimpleBundle(t, "/script.js", `export default 12345;`)112 assert.EqualError(t, err, "no exported functions in script")113 })114 t.Run("Minimal", func(t *testing.T) {115 t.Parallel()116 _, err := getSimpleBundle(t, "/script.js", `export default function() {};`)117 assert.NoError(t, err)118 })119 t.Run("stdin", func(t *testing.T) {120 t.Parallel()121 b, err := getSimpleBundle(t, "-", `export default function() {};`)122 if assert.NoError(t, err) {123 assert.Equal(t, "file://-", b.Filename.String())124 assert.Equal(t, "file:///", b.BaseInitContext.pwd.String())125 }126 })127 t.Run("CompatibilityMode", func(t *testing.T) {128 t.Parallel()129 t.Run("Extended/ok/global", func(t *testing.T) {130 t.Parallel()131 rtOpts := lib.RuntimeOptions{132 CompatibilityMode: null.StringFrom(lib.CompatibilityModeExtended.String()),133 }134 _, err := getSimpleBundle(t, "/script.js",135 `module.exports.default = function() {}136 if (global.Math != Math) {137 throw new Error("global is not defined");138 }`, rtOpts)139 assert.NoError(t, err)140 })141 t.Run("Base/ok/Minimal", func(t *testing.T) {142 t.Parallel()143 rtOpts := lib.RuntimeOptions{144 CompatibilityMode: null.StringFrom(lib.CompatibilityModeBase.String()),145 }146 _, err := getSimpleBundle(t, "/script.js",147 `module.exports.default = function() {};`, rtOpts)148 assert.NoError(t, err)149 })150 t.Run("Base/err", func(t *testing.T) {151 t.Parallel()152 testCases := []struct {153 name string154 compatMode string155 code string156 expErr string157 }{158 {159 "InvalidCompat", "es1", `export default function() {};`,160 `invalid compatibility mode "es1". Use: "extended", "base"`,161 },162 // ES2015 modules are not supported163 {164 "Modules", "base", `export default function() {};`,165 "file:///script.js: Line 1:1 Unexpected reserved word",166 },167 // BigInt is not supported168 {169 "BigInt", "base",170 `module.exports.default = function() {}; BigInt(1231412444)`,171 "ReferenceError: BigInt is not defined\n\tat file:///script.js:1:47(6)\n",172 },173 }174 for _, tc := range testCases {175 tc := tc176 t.Run(tc.name, func(t *testing.T) {177 t.Parallel()178 rtOpts := lib.RuntimeOptions{CompatibilityMode: null.StringFrom(tc.compatMode)}179 _, err := getSimpleBundle(t, "/script.js", tc.code, rtOpts)180 assert.EqualError(t, err, tc.expErr)181 })182 }183 })184 })185 t.Run("Options", func(t *testing.T) {186 t.Parallel()187 t.Run("Empty", func(t *testing.T) {188 t.Parallel()189 _, err := getSimpleBundle(t, "/script.js", `190 export let options = {};191 export default function() {};192 `)193 assert.NoError(t, err)194 })195 t.Run("Invalid", func(t *testing.T) {196 t.Parallel()197 invalidOptions := map[string]struct {198 Expr, Error string199 }{200 "Array": {`[]`, "json: cannot unmarshal array into Go value of type lib.Options"},201 "Function": {`function(){}`, "json: unsupported type: func(goja.FunctionCall) goja.Value"},202 }203 for name, data := range invalidOptions {204 t.Run(name, func(t *testing.T) {205 _, err := getSimpleBundle(t, "/script.js", fmt.Sprintf(`206 export let options = %s;207 export default function() {};208 `, data.Expr))209 assert.EqualError(t, err, data.Error)210 })211 }212 })213 t.Run("Paused", func(t *testing.T) {214 t.Parallel()215 b, err := getSimpleBundle(t, "/script.js", `216 export let options = {217 paused: true,218 };219 export default function() {};220 `)221 if assert.NoError(t, err) {222 assert.Equal(t, null.BoolFrom(true), b.Options.Paused)223 }224 })225 t.Run("VUs", func(t *testing.T) {226 t.Parallel()227 b, err := getSimpleBundle(t, "/script.js", `228 export let options = {229 vus: 100,230 };231 export default function() {};232 `)233 if assert.NoError(t, err) {234 assert.Equal(t, null.IntFrom(100), b.Options.VUs)235 }236 })237 t.Run("Duration", func(t *testing.T) {238 t.Parallel()239 b, err := getSimpleBundle(t, "/script.js", `240 export let options = {241 duration: "10s",242 };243 export default function() {};244 `)245 if assert.NoError(t, err) {246 assert.Equal(t, types.NullDurationFrom(10*time.Second), b.Options.Duration)247 }248 })249 t.Run("Iterations", func(t *testing.T) {250 t.Parallel()251 b, err := getSimpleBundle(t, "/script.js", `252 export let options = {253 iterations: 100,254 };255 export default function() {};256 `)257 if assert.NoError(t, err) {258 assert.Equal(t, null.IntFrom(100), b.Options.Iterations)259 }260 })261 t.Run("Stages", func(t *testing.T) {262 t.Parallel()263 b, err := getSimpleBundle(t, "/script.js", `264 export let options = {265 stages: [],266 };267 export default function() {};268 `)269 if assert.NoError(t, err) {270 assert.Len(t, b.Options.Stages, 0)271 }272 t.Run("Empty", func(t *testing.T) {273 t.Parallel()274 b, err := getSimpleBundle(t, "/script.js", `275 export let options = {276 stages: [277 {},278 ],279 };280 export default function() {};281 `)282 if assert.NoError(t, err) {283 if assert.Len(t, b.Options.Stages, 1) {284 assert.Equal(t, lib.Stage{}, b.Options.Stages[0])285 }286 }287 })288 t.Run("Target", func(t *testing.T) {289 t.Parallel()290 b, err := getSimpleBundle(t, "/script.js", `291 export let options = {292 stages: [293 {target: 10},294 ],295 };296 export default function() {};297 `)298 if assert.NoError(t, err) {299 if assert.Len(t, b.Options.Stages, 1) {300 assert.Equal(t, lib.Stage{Target: null.IntFrom(10)}, b.Options.Stages[0])301 }302 }303 })304 t.Run("Duration", func(t *testing.T) {305 t.Parallel()306 b, err := getSimpleBundle(t, "/script.js", `307 export let options = {308 stages: [309 {duration: "10s"},310 ],311 };312 export default function() {};313 `)314 if assert.NoError(t, err) {315 if assert.Len(t, b.Options.Stages, 1) {316 assert.Equal(t, lib.Stage{Duration: types.NullDurationFrom(10 * time.Second)}, b.Options.Stages[0])317 }318 }319 })320 t.Run("DurationAndTarget", func(t *testing.T) {321 t.Parallel()322 b, err := getSimpleBundle(t, "/script.js", `323 export let options = {324 stages: [325 {duration: "10s", target: 10},326 ],327 };328 export default function() {};329 `)330 if assert.NoError(t, err) {331 if assert.Len(t, b.Options.Stages, 1) {332 assert.Equal(t, lib.Stage{Duration: types.NullDurationFrom(10 * time.Second), Target: null.IntFrom(10)}, b.Options.Stages[0])333 }334 }335 })336 t.Run("RampUpAndPlateau", func(t *testing.T) {337 t.Parallel()338 b, err := getSimpleBundle(t, "/script.js", `339 export let options = {340 stages: [341 {duration: "10s", target: 10},342 {duration: "5s"},343 ],344 };345 export default function() {};346 `)347 if assert.NoError(t, err) {348 if assert.Len(t, b.Options.Stages, 2) {349 assert.Equal(t, lib.Stage{Duration: types.NullDurationFrom(10 * time.Second), Target: null.IntFrom(10)}, b.Options.Stages[0])350 assert.Equal(t, lib.Stage{Duration: types.NullDurationFrom(5 * time.Second)}, b.Options.Stages[1])351 }352 }353 })354 })355 t.Run("MaxRedirects", func(t *testing.T) {356 t.Parallel()357 b, err := getSimpleBundle(t, "/script.js", `358 export let options = {359 maxRedirects: 10,360 };361 export default function() {};362 `)363 if assert.NoError(t, err) {364 assert.Equal(t, null.IntFrom(10), b.Options.MaxRedirects)365 }366 })367 t.Run("InsecureSkipTLSVerify", func(t *testing.T) {368 t.Parallel()369 b, err := getSimpleBundle(t, "/script.js", `370 export let options = {371 insecureSkipTLSVerify: true,372 };373 export default function() {};374 `)375 if assert.NoError(t, err) {376 assert.Equal(t, null.BoolFrom(true), b.Options.InsecureSkipTLSVerify)377 }378 })379 t.Run("TLSCipherSuites", func(t *testing.T) {380 t.Parallel()381 for suiteName, suiteID := range lib.SupportedTLSCipherSuites {382 t.Run(suiteName, func(t *testing.T) {383 t.Parallel()384 script := `385 export let options = {386 tlsCipherSuites: ["%s"]387 };388 export default function() {};389 `390 script = fmt.Sprintf(script, suiteName)391 b, err := getSimpleBundle(t, "/script.js", script)392 if assert.NoError(t, err) {393 if assert.Len(t, *b.Options.TLSCipherSuites, 1) {394 assert.Equal(t, (*b.Options.TLSCipherSuites)[0], suiteID)395 }396 }397 })398 }399 })400 t.Run("TLSVersion", func(t *testing.T) {401 t.Parallel()402 t.Run("Object", func(t *testing.T) {403 t.Parallel()404 b, err := getSimpleBundle(t, "/script.js", `405 export let options = {406 tlsVersion: {407 min: "tls1.0",408 max: "tls1.2"409 }410 };411 export default function() {};412 `)413 if assert.NoError(t, err) {414 assert.Equal(t, b.Options.TLSVersion.Min, lib.TLSVersion(tls.VersionTLS10))415 assert.Equal(t, b.Options.TLSVersion.Max, lib.TLSVersion(tls.VersionTLS12))416 }417 })418 t.Run("String", func(t *testing.T) {419 t.Parallel()420 b, err := getSimpleBundle(t, "/script.js", `421 export let options = {422 tlsVersion: "tls1.0"423 };424 export default function() {};425 `)426 if assert.NoError(t, err) {427 assert.Equal(t, b.Options.TLSVersion.Min, lib.TLSVersion(tls.VersionTLS10))428 assert.Equal(t, b.Options.TLSVersion.Max, lib.TLSVersion(tls.VersionTLS10))429 }430 })431 })432 t.Run("Thresholds", func(t *testing.T) {433 t.Parallel()434 b, err := getSimpleBundle(t, "/script.js", `435 export let options = {436 thresholds: {437 http_req_duration: ["avg<100"],438 },439 };440 export default function() {};441 `)442 if assert.NoError(t, err) {443 if assert.Len(t, b.Options.Thresholds["http_req_duration"].Thresholds, 1) {444 assert.Equal(t, "avg<100", b.Options.Thresholds["http_req_duration"].Thresholds[0].Source)445 }446 }447 })448 t.Run("Unknown field", func(t *testing.T) {449 t.Parallel()450 logger := logrus.New()451 logger.SetLevel(logrus.InfoLevel)452 logger.Out = ioutil.Discard453 hook := testutils.SimpleLogrusHook{454 HookedLevels: []logrus.Level{logrus.WarnLevel, logrus.InfoLevel, logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel},455 }456 logger.AddHook(&hook)457 _, err := getSimpleBundle(t, "/script.js", `458 export let options = {459 something: {460 http_req_duration: ["avg<100"],461 },462 };463 export default function() {};464 `, logger)465 require.NoError(t, err)466 entries := hook.Drain()467 require.Len(t, entries, 1)468 assert.Equal(t, logrus.WarnLevel, entries[0].Level)469 require.Contains(t, entries[0].Message, "There were unknown fields")470 require.Contains(t, entries[0].Data["error"].(error).Error(), "unknown field \"something\"")471 })472 })473}474func getArchive(tb testing.TB, data string, rtOpts lib.RuntimeOptions) (*lib.Archive, error) {475 b, err := getSimpleBundle(tb, "script.js", data, rtOpts)476 if err != nil {477 return nil, err478 }479 return b.makeArchive(), nil480}481func TestNewBundleFromArchive(t *testing.T) {482 t.Parallel()483 es5Code := `module.exports.options = { vus: 12345 }; module.exports.default = function() { return "hi!" };`484 es6Code := `export let options = { vus: 12345 }; export default function() { return "hi!"; };`485 baseCompatModeRtOpts := lib.RuntimeOptions{CompatibilityMode: null.StringFrom(lib.CompatibilityModeBase.String())}486 extCompatModeRtOpts := lib.RuntimeOptions{CompatibilityMode: null.StringFrom(lib.CompatibilityModeExtended.String())}487 logger := testutils.NewLogger(t)488 checkBundle := func(t *testing.T, b *Bundle) {489 assert.Equal(t, lib.Options{VUs: null.IntFrom(12345)}, b.Options)490 bi, err := b.Instantiate(logger, 0, newModuleVUImpl())491 require.NoError(t, err)492 val, err := bi.exports[consts.DefaultFn](goja.Undefined())493 require.NoError(t, err)494 assert.Equal(t, "hi!", val.Export())495 }496 checkArchive := func(t *testing.T, arc *lib.Archive, rtOpts lib.RuntimeOptions, expError string) {497 b, err := NewBundleFromArchive(logger, arc, rtOpts, metrics.NewRegistry())498 if expError != "" {499 require.Error(t, err)500 assert.Contains(t, err.Error(), expError)501 } else {502 require.NoError(t, err)503 checkBundle(t, b)504 }505 }506 t.Run("es6_script_default", func(t *testing.T) {507 t.Parallel()508 arc, err := getArchive(t, es6Code, lib.RuntimeOptions{}) // default options509 require.NoError(t, err)510 require.Equal(t, lib.CompatibilityModeExtended.String(), arc.CompatibilityMode)511 checkArchive(t, arc, lib.RuntimeOptions{}, "") // default options512 checkArchive(t, arc, extCompatModeRtOpts, "")513 checkArchive(t, arc, baseCompatModeRtOpts, "Unexpected reserved word")514 })515 t.Run("es6_script_explicit", func(t *testing.T) {516 t.Parallel()517 arc, err := getArchive(t, es6Code, extCompatModeRtOpts)518 require.NoError(t, err)519 require.Equal(t, lib.CompatibilityModeExtended.String(), arc.CompatibilityMode)520 checkArchive(t, arc, lib.RuntimeOptions{}, "")521 checkArchive(t, arc, extCompatModeRtOpts, "")522 checkArchive(t, arc, baseCompatModeRtOpts, "Unexpected reserved word")523 })524 t.Run("es5_script_with_extended", func(t *testing.T) {525 t.Parallel()526 arc, err := getArchive(t, es5Code, lib.RuntimeOptions{})527 require.NoError(t, err)528 require.Equal(t, lib.CompatibilityModeExtended.String(), arc.CompatibilityMode)529 checkArchive(t, arc, lib.RuntimeOptions{}, "")530 checkArchive(t, arc, extCompatModeRtOpts, "")531 checkArchive(t, arc, baseCompatModeRtOpts, "")532 })533 t.Run("es5_script", func(t *testing.T) {534 t.Parallel()535 arc, err := getArchive(t, es5Code, baseCompatModeRtOpts)536 require.NoError(t, err)537 require.Equal(t, lib.CompatibilityModeBase.String(), arc.CompatibilityMode)538 checkArchive(t, arc, lib.RuntimeOptions{}, "")539 checkArchive(t, arc, extCompatModeRtOpts, "")540 checkArchive(t, arc, baseCompatModeRtOpts, "")541 })542 t.Run("es6_archive_with_wrong_compat_mode", func(t *testing.T) {543 t.Parallel()544 arc, err := getArchive(t, es6Code, baseCompatModeRtOpts)545 require.Error(t, err)546 require.Nil(t, arc)547 })548 t.Run("messed_up_archive", func(t *testing.T) {549 t.Parallel()550 arc, err := getArchive(t, es6Code, extCompatModeRtOpts)551 require.NoError(t, err)552 arc.CompatibilityMode = "blah" // intentionally break the archive553 checkArchive(t, arc, lib.RuntimeOptions{}, "invalid compatibility mode") // fails when it uses the archive one554 checkArchive(t, arc, extCompatModeRtOpts, "") // works when I force the compat mode555 checkArchive(t, arc, baseCompatModeRtOpts, "Unexpected reserved word") // failes because of ES6556 })557 t.Run("script_options_dont_overwrite_metadata", func(t *testing.T) {558 t.Parallel()559 code := `export let options = { vus: 12345 }; export default function() { return options.vus; };`560 arc := &lib.Archive{561 Type: "js",562 FilenameURL: &url.URL{Scheme: "file", Path: "/script"},563 K6Version: consts.Version,564 Data: []byte(code),565 Options: lib.Options{VUs: null.IntFrom(999)},566 PwdURL: &url.URL{Scheme: "file", Path: "/"},567 Filesystems: nil,568 }569 b, err := NewBundleFromArchive(logger, arc, lib.RuntimeOptions{}, metrics.NewRegistry())570 require.NoError(t, err)571 bi, err := b.Instantiate(logger, 0, newModuleVUImpl())572 require.NoError(t, err)573 val, err := bi.exports[consts.DefaultFn](goja.Undefined())574 require.NoError(t, err)575 assert.Equal(t, int64(999), val.Export())576 })577}578func TestOpen(t *testing.T) {579 testCases := [...]struct {580 name string581 openPath string582 pwd string583 isError bool584 isArchiveError bool585 }{586 {587 name: "notOpeningUrls",588 openPath: "github.com",589 isError: true,590 pwd: "/path/to",591 },592 {593 name: "simple",594 openPath: "file.txt",595 pwd: "/path/to",596 },597 {598 name: "simple with dot",599 openPath: "./file.txt",600 pwd: "/path/to",601 },602 {603 name: "simple with two dots",604 openPath: "../to/file.txt",605 pwd: "/path/not",606 },607 {608 name: "fullpath",609 openPath: "/path/to/file.txt",610 pwd: "/path/to",611 },612 {613 name: "fullpath2",614 openPath: "/path/to/file.txt",615 pwd: "/path",616 },617 {618 name: "file is dir",619 openPath: "/path/to/",620 pwd: "/path/to",621 isError: true,622 },623 {624 name: "file is missing",625 openPath: "/path/to/missing.txt",626 isError: true,627 },628 {629 name: "relative1",630 openPath: "to/file.txt",631 pwd: "/path",632 },633 {634 name: "relative2",635 openPath: "./path/to/file.txt",636 pwd: "/",637 },638 {639 name: "relative wonky",640 openPath: "../path/to/file.txt",641 pwd: "/path",642 },643 {644 name: "empty open doesn't panic",645 openPath: "",646 pwd: "/path",647 isError: true,648 },649 }650 fss := map[string]func() (afero.Fs, string, func()){651 "MemMapFS": func() (afero.Fs, string, func()) {652 fs := afero.NewMemMapFs()653 require.NoError(t, fs.MkdirAll("/path/to", 0o755))654 require.NoError(t, afero.WriteFile(fs, "/path/to/file.txt", []byte(`hi`), 0o644))655 return fs, "", func() {}656 },657 "OsFS": func() (afero.Fs, string, func()) {658 prefix, err := ioutil.TempDir("", "k6_open_test")659 require.NoError(t, err)660 fs := afero.NewOsFs()661 filePath := filepath.Join(prefix, "/path/to/file.txt")662 require.NoError(t, fs.MkdirAll(filepath.Join(prefix, "/path/to"), 0o755))663 require.NoError(t, afero.WriteFile(fs, filePath, []byte(`hi`), 0o644))664 if isWindows {665 fs = fsext.NewTrimFilePathSeparatorFs(fs)666 }667 return fs, prefix, func() { require.NoError(t, os.RemoveAll(prefix)) }668 },669 }670 logger := testutils.NewLogger(t)671 for name, fsInit := range fss {672 t.Run(name, func(t *testing.T) {673 t.Parallel()674 for _, tCase := range testCases {675 tCase := tCase676 testFunc := func(t *testing.T) {677 t.Parallel()678 fs, prefix, cleanUp := fsInit()679 defer cleanUp()680 fs = afero.NewReadOnlyFs(fs)681 openPath := tCase.openPath682 // if fullpath prepend prefix683 if openPath != "" && (openPath[0] == '/' || openPath[0] == '\\') {684 openPath = filepath.Join(prefix, openPath)685 }686 if isWindows {687 openPath = strings.Replace(openPath, `\`, `\\`, -1)688 }689 pwd := tCase.pwd690 if pwd == "" {691 pwd = "/path/to/"692 }693 data := `694 export let file = open("` + openPath + `");695 export default function() { return file };`696 sourceBundle, err := getSimpleBundle(t, filepath.ToSlash(filepath.Join(prefix, pwd, "script.js")), data, fs)697 if tCase.isError {698 assert.Error(t, err)699 return700 }701 require.NoError(t, err)702 arcBundle, err := NewBundleFromArchive(logger, sourceBundle.makeArchive(), lib.RuntimeOptions{}, metrics.NewRegistry())703 require.NoError(t, err)704 for source, b := range map[string]*Bundle{"source": sourceBundle, "archive": arcBundle} {705 b := b706 t.Run(source, func(t *testing.T) {707 bi, err := b.Instantiate(logger, 0, newModuleVUImpl())708 require.NoError(t, err)709 v, err := bi.exports[consts.DefaultFn](goja.Undefined())710 require.NoError(t, err)711 assert.Equal(t, "hi", v.Export())712 })713 }714 }715 t.Run(tCase.name, testFunc)716 if isWindows {717 // windowsify the testcase718 tCase.openPath = strings.Replace(tCase.openPath, `/`, `\`, -1)719 tCase.pwd = strings.Replace(tCase.pwd, `/`, `\`, -1)720 t.Run(tCase.name+" with windows slash", testFunc)721 }722 }723 })724 }725}726func TestBundleInstantiate(t *testing.T) {727 t.Parallel()728 t.Run("Run", func(t *testing.T) {729 t.Parallel()730 b, err := getSimpleBundle(t, "/script.js", `731 export let options = {732 vus: 5,733 teardownTimeout: '1s',734 };735 let val = true;736 export default function() { return val; }737 `)738 require.NoError(t, err)739 logger := testutils.NewLogger(t)740 bi, err := b.Instantiate(logger, 0, newModuleVUImpl())741 require.NoError(t, err)742 v, err := bi.exports[consts.DefaultFn](goja.Undefined())743 if assert.NoError(t, err) {744 assert.Equal(t, true, v.Export())745 }746 })747 t.Run("SetAndRun", func(t *testing.T) {748 t.Parallel()749 b, err := getSimpleBundle(t, "/script.js", `750 export let options = {751 vus: 5,752 teardownTimeout: '1s',753 };754 let val = true;755 export default function() { return val; }756 `)757 require.NoError(t, err)758 logger := testutils.NewLogger(t)759 bi, err := b.Instantiate(logger, 0, newModuleVUImpl())760 require.NoError(t, err)761 bi.Runtime.Set("val", false)762 v, err := bi.exports[consts.DefaultFn](goja.Undefined())763 if assert.NoError(t, err) {764 assert.Equal(t, false, v.Export())765 }766 })767 t.Run("Options", func(t *testing.T) {768 t.Parallel()769 b, err := getSimpleBundle(t, "/script.js", `770 export let options = {771 vus: 5,772 teardownTimeout: '1s',773 };774 let val = true;775 export default function() { return val; }776 `)777 require.NoError(t, err)778 logger := testutils.NewLogger(t)779 bi, err := b.Instantiate(logger, 0, newModuleVUImpl())780 require.NoError(t, err)781 // Ensure `options` properties are correctly marshalled782 jsOptions := bi.Runtime.Get("options").ToObject(bi.Runtime)783 vus := jsOptions.Get("vus").Export()784 assert.Equal(t, int64(5), vus)785 tdt := jsOptions.Get("teardownTimeout").Export()786 assert.Equal(t, "1s", tdt)787 // Ensure options propagate correctly from outside to the script788 optOrig := b.Options.VUs789 b.Options.VUs = null.IntFrom(10)790 bi2, err := b.Instantiate(logger, 0, newModuleVUImpl())791 assert.NoError(t, err)792 jsOptions = bi2.Runtime.Get("options").ToObject(bi2.Runtime)793 vus = jsOptions.Get("vus").Export()794 assert.Equal(t, int64(10), vus)795 b.Options.VUs = optOrig796 })797}798func TestBundleEnv(t *testing.T) {799 t.Parallel()800 rtOpts := lib.RuntimeOptions{Env: map[string]string{801 "TEST_A": "1",802 "TEST_B": "",803 }}804 data := `805 export default function() {806 if (__ENV.TEST_A !== "1") { throw new Error("Invalid TEST_A: " + __ENV.TEST_A); }807 if (__ENV.TEST_B !== "") { throw new Error("Invalid TEST_B: " + __ENV.TEST_B); }808 }809 `810 b1, err := getSimpleBundle(t, "/script.js", data, rtOpts)811 require.NoError(t, err)812 logger := testutils.NewLogger(t)813 b2, err := NewBundleFromArchive(logger, b1.makeArchive(), lib.RuntimeOptions{}, metrics.NewRegistry())814 require.NoError(t, err)815 bundles := map[string]*Bundle{"Source": b1, "Archive": b2}816 for name, b := range bundles {817 b := b818 t.Run(name, func(t *testing.T) {819 t.Parallel()820 assert.Equal(t, "1", b.RuntimeOptions.Env["TEST_A"])821 assert.Equal(t, "", b.RuntimeOptions.Env["TEST_B"])822 bi, err := b.Instantiate(logger, 0, newModuleVUImpl())823 if assert.NoError(t, err) {824 _, err := bi.exports[consts.DefaultFn](goja.Undefined())825 assert.NoError(t, err)826 }827 })828 }829}830func TestBundleNotSharable(t *testing.T) {831 t.Parallel()832 data := `833 export default function() {834 if (__ITER == 0) {835 if (typeof __ENV.something !== "undefined") {836 throw new Error("invalid something: " + __ENV.something + " should be undefined");837 }838 __ENV.something = __VU;839 } else if (__ENV.something != __VU) {840 throw new Error("invalid something: " + __ENV.something+ " should be "+ __VU);841 }842 }843 `844 b1, err := getSimpleBundle(t, "/script.js", data)845 require.NoError(t, err)846 logger := testutils.NewLogger(t)847 b2, err := NewBundleFromArchive(logger, b1.makeArchive(), lib.RuntimeOptions{}, metrics.NewRegistry())848 require.NoError(t, err)849 bundles := map[string]*Bundle{"Source": b1, "Archive": b2}850 vus, iters := 10, 1000851 for name, b := range bundles {852 b := b853 t.Run(name, func(t *testing.T) {854 t.Parallel()855 for i := 0; i < vus; i++ {856 bi, err := b.Instantiate(logger, uint64(i), newModuleVUImpl())857 require.NoError(t, err)858 for j := 0; j < iters; j++ {859 bi.Runtime.Set("__ITER", j)860 _, err := bi.exports[consts.DefaultFn](goja.Undefined())861 assert.NoError(t, err)862 }863 }864 })865 }866}867func TestBundleMakeArchive(t *testing.T) {868 t.Parallel()869 testCases := []struct {870 cm lib.CompatibilityMode871 script string872 exclaim string873 }{874 {875 lib.CompatibilityModeExtended, `876 import exclaim from "./exclaim.js";877 export let options = { vus: 12345 };878 export let file = open("./file.txt");879 export default function() { return exclaim(file); };`,880 `export default function(s) { return s + "!" };`,881 },882 {883 lib.CompatibilityModeBase, `884 var exclaim = require("./exclaim.js");885 module.exports.options = { vus: 12345 };886 module.exports.file = open("./file.txt");887 module.exports.default = function() { return exclaim(module.exports.file); };`,888 `module.exports.default = function(s) { return s + "!" };`,889 },890 }891 for _, tc := range testCases {892 tc := tc893 t.Run(tc.cm.String(), func(t *testing.T) {894 t.Parallel()895 fs := afero.NewMemMapFs()896 _ = fs.MkdirAll("/path/to", 0o755)897 _ = afero.WriteFile(fs, "/path/to/file.txt", []byte(`hi`), 0o644)898 _ = afero.WriteFile(fs, "/path/to/exclaim.js", []byte(tc.exclaim), 0o644)899 rtOpts := lib.RuntimeOptions{CompatibilityMode: null.StringFrom(tc.cm.String())}900 b, err := getSimpleBundle(t, "/path/to/script.js", tc.script, fs, rtOpts)901 assert.NoError(t, err)902 arc := b.makeArchive()903 assert.Equal(t, "js", arc.Type)904 assert.Equal(t, lib.Options{VUs: null.IntFrom(12345)}, arc.Options)905 assert.Equal(t, "file:///path/to/script.js", arc.FilenameURL.String())906 assert.Equal(t, tc.script, string(arc.Data))907 assert.Equal(t, "file:///path/to/", arc.PwdURL.String())908 exclaimData, err := afero.ReadFile(arc.Filesystems["file"], "/path/to/exclaim.js")909 assert.NoError(t, err)910 assert.Equal(t, tc.exclaim, string(exclaimData))911 fileData, err := afero.ReadFile(arc.Filesystems["file"], "/path/to/file.txt")912 assert.NoError(t, err)913 assert.Equal(t, `hi`, string(fileData))914 assert.Equal(t, consts.Version, arc.K6Version)...

Full Screen

Full Screen

getSimpleBundle

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c := js.Global.Get("getSimpleBundle")4 fmt.Println(c)5}6import (7func main() {8 c := js.Global.Get("getSimpleBundle")9 fmt.Println(c)10}11import (12func main() {13 c := js.Global.Get("getSimpleBundle")14 fmt.Println(c)15}16import (17func main() {18 c := js.Global.Get("getSimpleBundle")19 fmt.Println(c)20}21import (22func main() {23 c := js.Global.Get("getSimpleBundle")24 fmt.Println(c)25}26import (27func main() {28 c := js.Global.Get("getSimpleBundle")29 fmt.Println(c)30}31import (32func main() {33 c := js.Global.Get("getSimpleBundle")34 fmt.Println(c)35}36import (37func main() {38 c := js.Global.Get("getSimpleBundle")39 fmt.Println(c)40}

Full Screen

Full Screen

getSimpleBundle

Using AI Code Generation

copy

Full Screen

1public class Test {2 public static void main(String[] args) {3 ScriptEngineManager factory = new ScriptEngineManager();4 ScriptEngine engine = factory.getEngineByName("JavaScript");5 try {6 engine.eval("load('C:/Users/Abhishek/Desktop/1.js')");7 Invocable inv = (Invocable) engine;8 inv.invokeFunction("getSimpleBundle");9 } catch (ScriptException e) {10 e.printStackTrace();11 } catch (NoSuchMethodException e) {12 e.printStackTrace();13 }14 }15}16{key1=value1, key2=value2, key3=value3}

Full Screen

Full Screen

getSimpleBundle

Using AI Code Generation

copy

Full Screen

1import "github.com/robertkrimen/otto"2import "fmt"3func main() {4vm := otto.New()5vm.Run(`6 var js = require('js');7 var bundle = js.getSimpleBundle();8 console.log(bundle);9}10function getSimpleBundle() {11 return {12 "address": {13 }14 }15}16module.exports = {17}

Full Screen

Full Screen

getSimpleBundle

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 bundle := js.Global.Get("getSimpleBundle").Invoke()4 value := bundle.Get("key")5 fmt.Println(value)6}

Full Screen

Full Screen

getSimpleBundle

Using AI Code Generation

copy

Full Screen

1var bundleClass = Java.use("com.example.test.MyBundle");2var bundle = bundleClass.getSimpleBundle();3console.log("Bundle: " + bundle);4var bundleClass = Java.use("com.example.test.MyBundle");5var bundle = bundleClass.getBundle();6console.log("Bundle: " + bundle);7var bundleClass = Java.use("com.example.test.MyBundle");8var bundle = bundleClass.getBundle();9console.log("Bundle: " + bundle);10var bundleClass = Java.use("com.example.test.MyBundle");11var bundle = bundleClass.getBundle();12console.log("Bundle: " + bundle);13var bundleClass = Java.use("com.example.test.MyBundle");14var bundle = bundleClass.getBundle();15console.log("Bundle: " + bundle);16var bundleClass = Java.use("com.example.test.MyBundle");17var bundle = bundleClass.getBundle();18console.log("Bundle: " + bundle);19var bundleClass = Java.use("com.example.test.MyBundle");20var bundle = bundleClass.getBundle();21console.log("Bundle: " + bundle);22var bundleClass = Java.use("com.example.test.MyBundle");23var bundle = bundleClass.getBundle();24console.log("Bundle

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.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful