Best K6 code snippet using js.InitEnv
client.go
Source:client.go
...33func (c *Client) Load(importPaths []string, filenames ...string) ([]MethodInfo, error) {34 if c.vu.State() != nil {35 return nil, errors.New("load must be called in the init context")36 }37 initEnv := c.vu.InitEnv()38 if initEnv == nil {39 return nil, errors.New("missing init environment")40 }41 // If no import paths are specified, use the current working directory42 if len(importPaths) == 0 {43 importPaths = append(importPaths, initEnv.CWD.Path)44 }45 parser := protoparse.Parser{46 ImportPaths: importPaths,47 InferImportPaths: false,48 Accessor: protoparse.FileAccessor(func(filename string) (io.ReadCloser, error) {49 absFilePath := initEnv.GetAbsFilePath(filename)50 return initEnv.FileSystems["file"].Open(absFilePath)51 }),...
metrics_test.go
Source:metrics_test.go
...60 rt := goja.New()61 rt.SetFieldNameMapper(common.FieldNameMapper{})62 mii := &modulestest.InstanceCore{63 Runtime: rt,64 InitEnv: &common.InitEnvironment{Registry: metrics.NewRegistry()},65 Ctx: context.Background(),66 }67 m, ok := New().NewModuleInstance(mii).(*ModuleInstance)68 require.True(t, ok)69 require.NoError(t, rt.Set("metrics", m.GetExports().Named))70 root, _ := lib.NewGroup("", nil)71 child, _ := root.Group("child")72 samples := make(chan stats.SampleContainer, 1000)73 state := &lib.State{74 Options: lib.Options{SystemTags: stats.NewSystemTagSet(stats.TagGroup), Throw: null.BoolFrom(true)},75 Group: root,76 Samples: samples,77 Tags: map[string]string{"group": root.Path},78 }79 isTimeString := ""80 if isTime {81 isTimeString = `, true`82 }83 _, err := rt.RunString(fmt.Sprintf(`var m = new metrics.%s("my_metric"%s)`, fn, isTimeString))84 require.NoError(t, err)85 t.Run("ExitInit", func(t *testing.T) {86 mii.State = state87 mii.InitEnv = nil88 _, err := rt.RunString(fmt.Sprintf(`new metrics.%s("my_metric")`, fn))89 assert.Contains(t, err.Error(), "metrics must be declared in the init context")90 })91 groups := map[string]*lib.Group{92 "Root": root,93 "Child": child,94 }95 for name, g := range groups {96 name, g := name, g97 t.Run(name, func(t *testing.T) {98 state.Group = g99 state.Tags["group"] = g.Path100 for name, val := range values {101 name, val := name, val102 t.Run(name, func(t *testing.T) {103 t.Run("Simple", func(t *testing.T) {104 _, err := rt.RunString(fmt.Sprintf(`m.add(%v)`, val.JS))105 assert.NoError(t, err)106 bufSamples := stats.GetBufferedSamples(samples)107 if assert.Len(t, bufSamples, 1) {108 sample, ok := bufSamples[0].(stats.Sample)109 require.True(t, ok)110 assert.NotZero(t, sample.Time)111 assert.Equal(t, sample.Value, val.Float)112 assert.Equal(t, map[string]string{113 "group": g.Path,114 }, sample.Tags.CloneTags())115 assert.Equal(t, "my_metric", sample.Metric.Name)116 assert.Equal(t, mtyp, sample.Metric.Type)117 assert.Equal(t, valueType, sample.Metric.Contains)118 }119 })120 t.Run("Tags", func(t *testing.T) {121 _, err := rt.RunString(fmt.Sprintf(`m.add(%v, {a:1})`, val.JS))122 assert.NoError(t, err)123 bufSamples := stats.GetBufferedSamples(samples)124 if assert.Len(t, bufSamples, 1) {125 sample, ok := bufSamples[0].(stats.Sample)126 require.True(t, ok)127 assert.NotZero(t, sample.Time)128 assert.Equal(t, sample.Value, val.Float)129 assert.Equal(t, map[string]string{130 "group": g.Path,131 "a": "1",132 }, sample.Tags.CloneTags())133 assert.Equal(t, "my_metric", sample.Metric.Name)134 assert.Equal(t, mtyp, sample.Metric.Type)135 assert.Equal(t, valueType, sample.Metric.Contains)136 }137 })138 })139 }140 })141 }142 })143 }144 })145 }146}147func TestMetricGetName(t *testing.T) {148 t.Parallel()149 rt := goja.New()150 rt.SetFieldNameMapper(common.FieldNameMapper{})151 mii := &modulestest.InstanceCore{152 Runtime: rt,153 InitEnv: &common.InitEnvironment{Registry: metrics.NewRegistry()},154 Ctx: context.Background(),155 }156 m, ok := New().NewModuleInstance(mii).(*ModuleInstance)157 require.True(t, ok)158 require.NoError(t, rt.Set("metrics", m.GetExports().Named))159 v, err := rt.RunString(`160 var m = new metrics.Counter("my_metric")161 m.name162 `)163 require.NoError(t, err)164 require.Equal(t, "my_metric", v.String())165 _, err = rt.RunString(`166 "use strict";167 m.name = "something"168 `)169 require.Error(t, err)170 require.Contains(t, err.Error(), "TypeError: Cannot assign to read only property 'name'")171}172func TestMetricDuplicates(t *testing.T) {173 t.Parallel()174 rt := goja.New()175 rt.SetFieldNameMapper(common.FieldNameMapper{})176 mii := &modulestest.InstanceCore{177 Runtime: rt,178 InitEnv: &common.InitEnvironment{Registry: metrics.NewRegistry()},179 Ctx: context.Background(),180 }181 m, ok := New().NewModuleInstance(mii).(*ModuleInstance)182 require.True(t, ok)183 require.NoError(t, rt.Set("metrics", m.GetExports().Named))184 _, err := rt.RunString(`185 var m = new metrics.Counter("my_metric")186 `)187 require.NoError(t, err)188 _, err = rt.RunString(`189 var m2 = new metrics.Counter("my_metric")190 `)191 require.NoError(t, err)192 _, err = rt.RunString(`...
loki.go
Source:loki.go
...46 return &Loki{vu: vu, metrics: m}47}48func registerMetrics(vu modules.VU) (lokiMetrics, error) {49 var err error50 registry := vu.InitEnv().Registry51 m := lokiMetrics{}52 m.ClientUncompressedBytes, err = registry.NewMetric("loki_client_uncompressed_bytes", metrics.Counter, metrics.Data)53 if err != nil {54 return m, err55 }56 m.ClientLines, err = registry.NewMetric("loki_client_lines", metrics.Counter, metrics.Default)57 if err != nil {58 return m, err59 }60 m.BytesProcessedTotal, err = registry.NewMetric("loki_bytes_processed_total", metrics.Counter, metrics.Data)61 if err != nil {62 return m, err63 }64 m.BytesProcessedPerSeconds, err = registry.NewMetric("loki_bytes_processed_per_second", metrics.Trend, metrics.Data)65 if err != nil {66 return m, err67 }68 m.LinesProcessedTotal, err = registry.NewMetric("loki_lines_processed_total", metrics.Counter, metrics.Default)69 if err != nil {70 return m, err71 }72 m.LinesProcessedPerSeconds, err = registry.NewMetric("loki_lines_processed_per_second", metrics.Trend, metrics.Default)73 if err != nil {74 return m, err75 }76 return m, nil77}78// Loki is the k6 extension that can be imported in the Javascript test file.79type Loki struct {80 vu modules.VU81 metrics lokiMetrics82}83func (r *Loki) Exports() modules.Exports {84 return modules.Exports{85 Named: map[string]interface{}{86 "Config": r.config,87 "Client": r.client,88 "getLables": r.getLabels,89 },90 }91}92// config provides a constructor interface for the Config for the Javascript runtime93// ```js94// const cfg = new loki.Config(url);95// ```96func (r *Loki) config(c goja.ConstructorCall) *goja.Object {97 initEnv := r.vu.InitEnv()98 if initEnv == nil {99 common.Throw(r.vu.Runtime(), errors.New("Client constructor needs to be called in the init context"))100 }101 urlString := c.Argument(0).String()102 timeoutMs := int(c.Argument(1).ToInteger())103 protobufRatio := c.Argument(2).ToFloat()104 var cardinalities map[string]int105 rt := r.vu.Runtime()106 err := rt.ExportTo(c.Argument(3), &cardinalities)107 if err != nil {108 common.Throw(rt, fmt.Errorf("Config constructor expects map of string to integers as forth argument"))109 }110 if timeoutMs == 0 {111 timeoutMs = DefaultPushTimeout...
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!!