How to use newTestEngine method of core Package

Best K6 code snippet using core.newTestEngine

engine_test.go

Source:engine_test.go Github

copy

Full Screen

...47 e.SetLogger(logger)48 return hook49}50// Wrapper around newEngine that applies a null logger.51func newTestEngine(ex lib.Executor, opts lib.Options) (*Engine, error) {52 if !opts.MetricSamplesBufferSize.Valid {53 opts.MetricSamplesBufferSize = null.IntFrom(200)54 }55 e, err := NewEngine(ex, opts)56 if err != nil {57 return e, err58 }59 applyNullLogger(e)60 return e, nil61}62func LF(fn func(ctx context.Context, out chan<- stats.SampleContainer) error) lib.Executor {63 return local.New(&lib.MiniRunner{Fn: fn})64}65func TestNewEngine(t *testing.T) {66 _, err := newTestEngine(nil, lib.Options{})67 assert.NoError(t, err)68}69func TestNewEngineOptions(t *testing.T) {70 t.Run("Duration", func(t *testing.T) {71 e, err := newTestEngine(nil, lib.Options{72 Duration: types.NullDurationFrom(10 * time.Second),73 })74 assert.NoError(t, err)75 assert.Nil(t, e.Executor.GetStages())76 assert.Equal(t, types.NullDurationFrom(10*time.Second), e.Executor.GetEndTime())77 t.Run("Infinite", func(t *testing.T) {78 e, err := newTestEngine(nil, lib.Options{Duration: types.NullDuration{}})79 assert.NoError(t, err)80 assert.Nil(t, e.Executor.GetStages())81 assert.Equal(t, types.NullDuration{}, e.Executor.GetEndTime())82 })83 })84 t.Run("Stages", func(t *testing.T) {85 e, err := newTestEngine(nil, lib.Options{86 Stages: []lib.Stage{87 {Duration: types.NullDurationFrom(10 * time.Second), Target: null.IntFrom(10)},88 },89 })90 assert.NoError(t, err)91 if assert.Len(t, e.Executor.GetStages(), 1) {92 assert.Equal(t, e.Executor.GetStages()[0], lib.Stage{Duration: types.NullDurationFrom(10 * time.Second), Target: null.IntFrom(10)})93 }94 })95 t.Run("Stages/Duration", func(t *testing.T) {96 e, err := newTestEngine(nil, lib.Options{97 Duration: types.NullDurationFrom(60 * time.Second),98 Stages: []lib.Stage{99 {Duration: types.NullDurationFrom(10 * time.Second), Target: null.IntFrom(10)},100 },101 })102 assert.NoError(t, err)103 if assert.Len(t, e.Executor.GetStages(), 1) {104 assert.Equal(t, e.Executor.GetStages()[0], lib.Stage{Duration: types.NullDurationFrom(10 * time.Second), Target: null.IntFrom(10)})105 }106 assert.Equal(t, types.NullDurationFrom(60*time.Second), e.Executor.GetEndTime())107 })108 t.Run("Iterations", func(t *testing.T) {109 e, err := newTestEngine(nil, lib.Options{Iterations: null.IntFrom(100)})110 assert.NoError(t, err)111 assert.Equal(t, null.IntFrom(100), e.Executor.GetEndIterations())112 })113 t.Run("VUsMax", func(t *testing.T) {114 t.Run("not set", func(t *testing.T) {115 e, err := newTestEngine(nil, lib.Options{})116 assert.NoError(t, err)117 assert.Equal(t, int64(0), e.Executor.GetVUsMax())118 assert.Equal(t, int64(0), e.Executor.GetVUs())119 })120 t.Run("set", func(t *testing.T) {121 e, err := newTestEngine(nil, lib.Options{122 VUsMax: null.IntFrom(10),123 })124 assert.NoError(t, err)125 assert.Equal(t, int64(10), e.Executor.GetVUsMax())126 assert.Equal(t, int64(0), e.Executor.GetVUs())127 })128 })129 t.Run("VUs", func(t *testing.T) {130 t.Run("no max", func(t *testing.T) {131 _, err := newTestEngine(nil, lib.Options{132 VUs: null.IntFrom(10),133 })134 assert.EqualError(t, err, "can't raise vu count (to 10) above vu cap (0)")135 })136 t.Run("negative max", func(t *testing.T) {137 _, err := newTestEngine(nil, lib.Options{138 VUsMax: null.IntFrom(-1),139 })140 assert.EqualError(t, err, "vu cap can't be negative")141 })142 t.Run("max too low", func(t *testing.T) {143 _, err := newTestEngine(nil, lib.Options{144 VUsMax: null.IntFrom(1),145 VUs: null.IntFrom(10),146 })147 assert.EqualError(t, err, "can't raise vu count (to 10) above vu cap (1)")148 })149 t.Run("max higher", func(t *testing.T) {150 e, err := newTestEngine(nil, lib.Options{151 VUsMax: null.IntFrom(10),152 VUs: null.IntFrom(1),153 })154 assert.NoError(t, err)155 assert.Equal(t, int64(10), e.Executor.GetVUsMax())156 assert.Equal(t, int64(1), e.Executor.GetVUs())157 })158 t.Run("max just right", func(t *testing.T) {159 e, err := newTestEngine(nil, lib.Options{160 VUsMax: null.IntFrom(10),161 VUs: null.IntFrom(10),162 })163 assert.NoError(t, err)164 assert.Equal(t, int64(10), e.Executor.GetVUsMax())165 assert.Equal(t, int64(10), e.Executor.GetVUs())166 })167 })168 t.Run("Paused", func(t *testing.T) {169 t.Run("not set", func(t *testing.T) {170 e, err := newTestEngine(nil, lib.Options{})171 assert.NoError(t, err)172 assert.False(t, e.Executor.IsPaused())173 })174 t.Run("false", func(t *testing.T) {175 e, err := newTestEngine(nil, lib.Options{176 Paused: null.BoolFrom(false),177 })178 assert.NoError(t, err)179 assert.False(t, e.Executor.IsPaused())180 })181 t.Run("true", func(t *testing.T) {182 e, err := newTestEngine(nil, lib.Options{183 Paused: null.BoolFrom(true),184 })185 assert.NoError(t, err)186 assert.True(t, e.Executor.IsPaused())187 })188 })189 t.Run("thresholds", func(t *testing.T) {190 e, err := newTestEngine(nil, lib.Options{191 Thresholds: map[string]stats.Thresholds{192 "my_metric": {},193 },194 })195 assert.NoError(t, err)196 assert.Contains(t, e.thresholds, "my_metric")197 t.Run("submetrics", func(t *testing.T) {198 e, err := newTestEngine(nil, lib.Options{199 Thresholds: map[string]stats.Thresholds{200 "my_metric{tag:value}": {},201 },202 })203 assert.NoError(t, err)204 assert.Contains(t, e.thresholds, "my_metric{tag:value}")205 assert.Contains(t, e.submetrics, "my_metric")206 })207 })208}209func TestEngineRun(t *testing.T) {210 logrus.SetLevel(logrus.DebugLevel)211 t.Run("exits with context", func(t *testing.T) {212 duration := 100 * time.Millisecond213 e, err := newTestEngine(nil, lib.Options{})214 assert.NoError(t, err)215 ctx, cancel := context.WithTimeout(context.Background(), duration)216 defer cancel()217 startTime := time.Now()218 assert.NoError(t, e.Run(ctx))219 assert.WithinDuration(t, startTime.Add(duration), time.Now(), 100*time.Millisecond)220 })221 t.Run("exits with executor", func(t *testing.T) {222 e, err := newTestEngine(nil, lib.Options{223 VUs: null.IntFrom(10),224 VUsMax: null.IntFrom(10),225 Iterations: null.IntFrom(100),226 })227 assert.NoError(t, err)228 assert.NoError(t, e.Run(context.Background()))229 assert.Equal(t, int64(100), e.Executor.GetIterations())230 })231 // Make sure samples are discarded after context close (using "cutoff" timestamp in local.go)232 t.Run("collects samples", func(t *testing.T) {233 testMetric := stats.New("test_metric", stats.Trend)234 signalChan := make(chan interface{})235 var e *Engine236 e, err := newTestEngine(LF(func(ctx context.Context, samples chan<- stats.SampleContainer) error {237 samples <- stats.Sample{Metric: testMetric, Time: time.Now(), Value: 1}238 close(signalChan)239 <-ctx.Done()240 // HACK(robin): Add a sleep here to temporarily workaround two problems with this test:241 // 1. The sample times are compared against the `cutoff` in core/local/local.go and sometimes the242 // second sample (below) gets a `Time` smaller than `cutoff` because the lines below get executed243 // before the `<-ctx.Done()` select in local.go:Run() on multi-core systems where244 // goroutines can run in parallel.245 // 2. Sometimes the `case samples := <-vuOut` gets selected before the `<-ctx.Done()` in246 // core/local/local.go:Run() causing all samples from this mocked "RunOnce()" function to be accepted.247 time.Sleep(time.Millisecond * 10)248 samples <- stats.Sample{Metric: testMetric, Time: time.Now(), Value: 2}249 return nil250 }), lib.Options{251 VUs: null.IntFrom(1),252 VUsMax: null.IntFrom(1),253 Iterations: null.IntFrom(1),254 })255 if !assert.NoError(t, err) {256 return257 }258 c := &dummy.Collector{}259 e.Collectors = []lib.Collector{c}260 ctx, cancel := context.WithCancel(context.Background())261 errC := make(chan error)262 go func() { errC <- e.Run(ctx) }()263 <-signalChan264 cancel()265 assert.NoError(t, <-errC)266 found := 0267 for _, s := range c.Samples {268 if s.Metric != testMetric {269 continue270 }271 found++272 assert.Equal(t, 1.0, s.Value, "wrong value")273 }274 assert.Equal(t, 1, found, "wrong number of samples")275 })276}277func TestEngineAtTime(t *testing.T) {278 e, err := newTestEngine(nil, lib.Options{})279 assert.NoError(t, err)280 ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)281 defer cancel()282 assert.NoError(t, e.Run(ctx))283}284func TestEngineCollector(t *testing.T) {285 testMetric := stats.New("test_metric", stats.Trend)286 e, err := newTestEngine(LF(func(ctx context.Context, out chan<- stats.SampleContainer) error {287 out <- stats.Sample{Metric: testMetric}288 return nil289 }), lib.Options{VUs: null.IntFrom(1), VUsMax: null.IntFrom(1), Iterations: null.IntFrom(1)})290 assert.NoError(t, err)291 c := &dummy.Collector{}292 e.Collectors = []lib.Collector{c}293 assert.NoError(t, e.Run(context.Background()))294 cSamples := []stats.Sample{}295 for _, sample := range c.Samples {296 if sample.Metric == testMetric {297 cSamples = append(cSamples, sample)298 }299 }300 metric := e.Metrics["test_metric"]301 if assert.NotNil(t, metric) {302 sink := metric.Sink.(*stats.TrendSink)303 if assert.NotNil(t, sink) {304 numCollectorSamples := len(cSamples)305 numEngineSamples := len(sink.Values)306 assert.Equal(t, numEngineSamples, numCollectorSamples)307 }308 }309}310func TestEngine_processSamples(t *testing.T) {311 metric := stats.New("my_metric", stats.Gauge)312 t.Run("metric", func(t *testing.T) {313 e, err := newTestEngine(nil, lib.Options{})314 assert.NoError(t, err)315 e.processSamples(316 []stats.SampleContainer{stats.Sample{Metric: metric, Value: 1.25, Tags: stats.IntoSampleTags(&map[string]string{"a": "1"})}},317 )318 assert.IsType(t, &stats.GaugeSink{}, e.Metrics["my_metric"].Sink)319 })320 t.Run("submetric", func(t *testing.T) {321 ths, err := stats.NewThresholds([]string{`1+1==2`})322 assert.NoError(t, err)323 e, err := newTestEngine(nil, lib.Options{324 Thresholds: map[string]stats.Thresholds{325 "my_metric{a:1}": ths,326 },327 })328 assert.NoError(t, err)329 sms := e.submetrics["my_metric"]330 assert.Len(t, sms, 1)331 assert.Equal(t, "my_metric{a:1}", sms[0].Name)332 assert.EqualValues(t, map[string]string{"a": "1"}, sms[0].Tags.CloneTags())333 e.processSamples(334 []stats.SampleContainer{stats.Sample{Metric: metric, Value: 1.25, Tags: stats.IntoSampleTags(&map[string]string{"a": "1", "b": "2"})}},335 )336 assert.IsType(t, &stats.GaugeSink{}, e.Metrics["my_metric"].Sink)337 assert.IsType(t, &stats.GaugeSink{}, e.Metrics["my_metric{a:1}"].Sink)338 })339}340func TestEngine_runThresholds(t *testing.T) {341 metric := stats.New("my_metric", stats.Gauge)342 thresholds := make(map[string]stats.Thresholds, 1)343 ths, err := stats.NewThresholds([]string{"1+1==3"})344 assert.NoError(t, err)345 t.Run("aborted", func(t *testing.T) {346 ths.Thresholds[0].AbortOnFail = true347 thresholds[metric.Name] = ths348 e, err := newTestEngine(nil, lib.Options{Thresholds: thresholds})349 assert.NoError(t, err)350 e.processSamples(351 []stats.SampleContainer{stats.Sample{Metric: metric, Value: 1.25, Tags: stats.IntoSampleTags(&map[string]string{"a": "1"})}},352 )353 ctx, cancel := context.WithCancel(context.Background())354 aborted := false355 cancelFunc := func() {356 cancel()357 aborted = true358 }359 e.runThresholds(ctx, cancelFunc)360 assert.True(t, aborted)361 })362 t.Run("canceled", func(t *testing.T) {363 ths.Abort = false364 thresholds[metric.Name] = ths365 e, err := newTestEngine(nil, lib.Options{Thresholds: thresholds})366 assert.NoError(t, err)367 e.processSamples(368 []stats.SampleContainer{stats.Sample{Metric: metric, Value: 1.25, Tags: stats.IntoSampleTags(&map[string]string{"a": "1"})}},369 )370 ctx, cancel := context.WithCancel(context.Background())371 cancel()372 done := make(chan struct{})373 go func() {374 defer close(done)375 e.runThresholds(ctx, cancel)376 }()377 select {378 case <-done:379 return380 case <-time.After(1 * time.Second):381 assert.Fail(t, "Test should have completed within a second")382 }383 })384}385func TestEngine_processThresholds(t *testing.T) {386 metric := stats.New("my_metric", stats.Gauge)387 testdata := map[string]struct {388 pass bool389 ths map[string][]string390 abort bool391 }{392 "passing": {true, map[string][]string{"my_metric": {"1+1==2"}}, false},393 "failing": {false, map[string][]string{"my_metric": {"1+1==3"}}, false},394 "aborting": {false, map[string][]string{"my_metric": {"1+1==3"}}, true},395 "submetric,match,passing": {true, map[string][]string{"my_metric{a:1}": {"1+1==2"}}, false},396 "submetric,match,failing": {false, map[string][]string{"my_metric{a:1}": {"1+1==3"}}, false},397 "submetric,nomatch,passing": {true, map[string][]string{"my_metric{a:2}": {"1+1==2"}}, false},398 "submetric,nomatch,failing": {true, map[string][]string{"my_metric{a:2}": {"1+1==3"}}, false},399 }400 for name, data := range testdata {401 t.Run(name, func(t *testing.T) {402 thresholds := make(map[string]stats.Thresholds, len(data.ths))403 for m, srcs := range data.ths {404 ths, err := stats.NewThresholds(srcs)405 assert.NoError(t, err)406 ths.Thresholds[0].AbortOnFail = data.abort407 thresholds[m] = ths408 }409 e, err := newTestEngine(nil, lib.Options{Thresholds: thresholds})410 assert.NoError(t, err)411 e.processSamples(412 []stats.SampleContainer{stats.Sample{Metric: metric, Value: 1.25, Tags: stats.IntoSampleTags(&map[string]string{"a": "1"})}},413 )414 abortCalled := false415 abortFunc := func() {416 abortCalled = true417 }418 e.processThresholds(abortFunc)419 assert.Equal(t, data.pass, !e.IsTainted())420 if data.abort {421 assert.True(t, abortCalled)422 }423 })...

Full Screen

Full Screen

newTestEngine

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 engine := beego.NewTestBeegoEngine()4 engine.Router("/test", func(ctx *context.Context) {5 ctx.Output.Body([]byte("hello world"))6 })7 resp := engine.ServeHTTP("/test")8 if resp.Code != 200 {9 fmt.Println("status code is not 200")10 }11 if string(resp.Body()) != "hello world" {12 fmt.Println("body is not hello world")13 }14}15import (16func main() {17 engine := beego.NewTestBeegoEngine()18 engine.Router("/test", func(ctx *context.Context) {19 ctx.Output.Body([]byte("hello world"))20 })21 resp := engine.ServeHTTP("/test")22 if resp.Code != 200 {23 fmt.Println("status code is not 200")24 }25 if string(resp.Body()) != "hello world" {26 fmt.Println("body is not hello world")27 }28}29import (30func main() {31 engine := beego.NewTestBeegoEngine()32 engine.Router("/test", func(ctx *context.Context) {33 ctx.Output.Body([]byte("hello world"))34 })35 resp := engine.ServeHTTP("/test")36 if resp.Code != 200 {37 fmt.Println("status code is not 200")38 }39 if string(resp.Body()) != "hello world" {40 fmt.Println("body is not hello world")41 }42}43import (

Full Screen

Full Screen

newTestEngine

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World")4}5import (6type Engine struct {7}8type Car struct {9}10func (e *Engine) newTestEngine(name string) {11}12import (13func main() {14 car := Car{}15 car.newTestEngine("Test Engine")16 fmt.Println(car)17}18{ 0 0 {Test Engine}}

Full Screen

Full Screen

newTestEngine

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 testEngine := core.NewTestEngine()4 fmt.Println(testEngine)5}6&{1.0.0}

Full Screen

Full Screen

newTestEngine

Using AI Code Generation

copy

Full Screen

1import (2func main() {3e := core.NewTestEngine()4e.Run()5}6import (7func main() {8e := core.NewTestEngine()9e.Run()10}11import (12func main() {13e := core.NewTestEngine()14e.Run()15}16import (17func main() {18e := core.NewTestEngine()19e.Run()20}21import (22func main() {23e := core.NewTestEngine()24e.Run()25}

Full Screen

Full Screen

newTestEngine

Using AI Code Generation

copy

Full Screen

1func main() {2 engine := core.NewTestEngine()3 engine.Start()4}5import "fmt"6type TestEngine struct {7}8func (t *TestEngine) Start() {9 fmt.Println("Engine started")10}11func NewTestEngine() *TestEngine {12 return &TestEngine{}13}

Full Screen

Full Screen

newTestEngine

Using AI Code Generation

copy

Full Screen

1import "core"2func main() {3}4I've tried that, but it doesn't seem to work. I've put the core package in the src directory of my GOPATH and tried to import it from the 1.go and 2.go files but it doesn't seem to work. 5 /usr/local/go/src/pkg/core (from $GOROOT)6 /home/user/go/src/pkg/core (from $GOPATH)7I've tried to put the core package in the src directory of my GOPATH and tried to import it from the 1.go and 2.go files but it doesn't seem to work. 8 /usr/local/go/src/pkg/core (from $GOROOT)9 /home/user/go/src/pkg/core (from $GOPATH)10import "fmt"11func main() {12 fmt.Println("Hello, world.")13}

Full Screen

Full Screen

newTestEngine

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 core := core.NewTestEngine()4 core.Start()5 core.Stop()6 fmt.Println("Done")7}8import (9type TestEngine struct {10}11func NewTestEngine() *TestEngine {12 return &TestEngine{}13}14func (t *TestEngine) Start() {15 fmt.Println("Engine Started")16}17func (t *TestEngine) Stop() {18 fmt.Println("Engine Stopped")19}

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful