How to use NewBundleFromArchive method of js Package

Best K6 code snippet using js.NewBundleFromArchive

bundle_test.go

Source:bundle_test.go Github

copy

Full Screen

...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)...

Full Screen

Full Screen

bundle.go

Source:bundle.go Github

copy

Full Screen

...115 }116 }117 return &bundle, nil118}119// NewBundleFromArchive creates a new bundle from an lib.Archive.120func NewBundleFromArchive(arc *lib.Archive, rtOpts lib.RuntimeOptions) (*Bundle, error) {121 if arc.Type != "js" {122 return nil, errors.Errorf("expected bundle type 'js', got '%s'", arc.Type)123 }124 compatMode, err := lib.ValidateCompatibilityMode(arc.CompatibilityMode)125 if err != nil {126 return nil, err127 }128 c := compiler.New()129 pgm, _, err := c.Compile(string(arc.Data), arc.FilenameURL.String(), "", "", true, compatMode)130 if err != nil {131 return nil, err132 }133 initctx := NewInitContext(goja.New(), c, compatMode,134 new(context.Context), arc.Filesystems, arc.PwdURL)...

Full Screen

Full Screen

inspect.go

Source:inspect.go Github

copy

Full Screen

...67 arc, err = lib.ReadArchive(bytes.NewBuffer(src.Data))68 if err != nil {69 return err70 }71 b, err = js.NewBundleFromArchive(logger, arc, runtimeOptions, registry)72 if err != nil {73 return err74 }75 opts = b.Options76 case typeJS:77 b, err = js.NewBundle(logger, src, filesystems, runtimeOptions, registry)78 if err != nil {79 return err80 }81 opts = b.Options82 }83 data, err := json.MarshalIndent(opts, "", " ")84 if err != nil {85 return err...

Full Screen

Full Screen

NewBundleFromArchive

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 vm := otto.New()4 vm.Run(`5 var js = require('js');6 var archive = js.newArchive();7 archive.add('foo.js', 'exports.foo = "foo";');8 var bundle = js.newBundleFromArchive(archive);9 var mod = bundle.require('foo.js');10}11import (12func main() {13 vm := otto.New()14 vm.Run(`15 var js = require('js');16 var bundle = js.newBundleFromFiles('foo.js');17 var mod = bundle.require('foo.js');18}19import (20func main() {21 vm := otto.New()22 vm.Run(`23 var js = require('js');24 var bundle = js.newBundleFromDir('foo.js');25 var mod = bundle.require('foo.js');26}27import (28func main() {29 vm := otto.New()30 vm.Run(`31 var js = require('js');32 var files = {33 'foo.js': 'exports.foo = "foo";'34 };35 var bundle = js.newBundleFromMap(files);36 var mod = bundle.require('foo.js');37}38import (39func main() {40 vm := otto.New()41 vm.Run(`42 var js = require('js');

Full Screen

Full Screen

NewBundleFromArchive

Using AI Code Generation

copy

Full Screen

1func main() {2}3func main() {4}5func main() {6}7func main() {8}9func main() {10}11func main() {12}13func main() {14}15func main() {16}17func main() {18}19func main() {20}21func main() {22}23func main() {24}25func main() {26}

Full Screen

Full Screen

NewBundleFromArchive

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 log.Fatal(err)5 }6 defer resp.Body.Close()7 body, err := ioutil.ReadAll(resp.Body)8 if err != nil {9 log.Fatal(err)10 }11 vm := otto.New()12 vm.Set("NewBundleFromArchive", func(call otto.FunctionCall) otto.Value {13 fmt.Println("NewBundleFromArchive called")14 return otto.UndefinedValue()15 })16 vm.Run(strings.NewReader(string(body)))17 time.Sleep(5 * time.Second)18}19import (20func main() {21 if err != nil {22 log.Fatal(err)23 }24 defer resp.Body.Close()25 body, err := ioutil.ReadAll(resp.Body)26 if err != nil {27 log.Fatal(err)28 }29 vm := otto.New()30 vm.Set("NewBundleFromArchive", func(call otto.FunctionCall) otto.Value {31 fmt.Println("NewBundleFromArchive called")32 return otto.UndefinedValue()33 })34 vm.Run(strings.NewReader(string(body)))35 time.Sleep(5 * time.Second)36}37import (

Full Screen

Full Screen

NewBundleFromArchive

Using AI Code Generation

copy

Full Screen

1func main() {2 b, err := js.NewBundleFromArchive("test.zip")3 if err != nil {4 log.Fatal(err)5 }6 defer b.Close()7}8func main() {9 b, err := js.NewBundleFromArchive("test.tar.gz")10 if err != nil {11 log.Fatal(err)12 }13 defer b.Close()14}15func main() {16 b, err := js.NewBundleFromArchive("test.tar.bz2")17 if err != nil {18 log.Fatal(err)19 }20 defer b.Close()21}22func main() {23 b, err := js.NewBundleFromArchive("test.tar")24 if err != nil {25 log.Fatal(err)26 }27 defer b.Close()28}29func main() {30 b, err := js.NewBundleFromArchive("test.tar.xz")31 if err != nil {32 log.Fatal(err)33 }34 defer b.Close()35}36func main() {37 b, err := js.NewBundleFromArchive("test.tar.zst")38 if err != nil {39 log.Fatal(err)40 }41 defer b.Close()42}43func main() {44 b, err := js.NewBundleFromArchive("test.tar.sz")45 if err != nil {46 log.Fatal(err)47 }48 defer b.Close()49}50func main() {51 b, err := js.NewBundleFromArchive("test.tar.sz")52 if err != nil {53 log.Fatal(err)54 }55 defer b.Close()

Full Screen

Full Screen

NewBundleFromArchive

Using AI Code Generation

copy

Full Screen

1func TestBundleFromArchive(t *testing.T) {2 archive, err := os.Open("test_data/test.wasm")3 if err != nil {4 t.Fatal(err)5 }6 defer archive.Close()7 b, err := wasm.NewBundleFromArchive(archive)8 if err != nil {9 t.Fatal(err)10 }11 defer b.Close()12}13func TestBundleFromArchive(t *testing.T) {14 archive, err := os.Open("test_data/test.wasm")15 if err != nil {16 t.Fatal(err)17 }18 defer archive.Close()19 b, err := wasm.NewBundleFromArchive(archive)20 if err != nil {21 t.Fatal(err)22 }23 defer b.Close()24}25func TestBundleFromArchive(t *testing.T) {26 archive, err := os.Open("test_data/test.wasm")27 if err != nil {28 t.Fatal(err)29 }30 defer archive.Close()31 b, err := wasm.NewBundleFromArchive(archive)32 if err != nil {33 t.Fatal(err)34 }35 defer b.Close()36}37func TestBundleFromArchive(t *testing.T) {38 archive, err := os.Open("test_data/test.wasm")39 if err != nil {40 t.Fatal(err)41 }42 defer archive.Close()43 b, err := wasm.NewBundleFromArchive(archive)44 if err != nil {45 t.Fatal(err)46 }47 defer b.Close()48}49func TestBundleFromArchive(t *testing.T) {

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