Best K6 code snippet using lib.ReturnVU
vu_handle_test.go
Source:vu_handle_test.go
1package executor2import (3 "context"4 "sync"5 "sync/atomic"6 "testing"7 "time"8 "github.com/sirupsen/logrus"9 "github.com/stretchr/testify/assert"10 "github.com/stretchr/testify/require"11 "go.k6.io/k6/lib"12 "go.k6.io/k6/lib/testutils"13 "go.k6.io/k6/lib/testutils/minirunner"14 "go.k6.io/k6/stats"15)16func mockNextIterations() (uint64, uint64) {17 return 12, 1518}19// this test is mostly interesting when -race is enabled20func TestVUHandleRace(t *testing.T) {21 t.Parallel()22 ctx, cancel := context.WithCancel(context.Background())23 defer cancel()24 logHook := &testutils.SimpleLogrusHook{HookedLevels: []logrus.Level{logrus.DebugLevel}}25 testLog := logrus.New()26 testLog.AddHook(logHook)27 testLog.SetOutput(testutils.NewTestOutput(t))28 // testLog.Level = logrus.DebugLevel29 logEntry := logrus.NewEntry(testLog)30 runner := &minirunner.MiniRunner{}31 runner.Fn = func(ctx context.Context, out chan<- stats.SampleContainer) error {32 return nil33 }34 var getVUCount int6435 var returnVUCount int6436 getVU := func() (lib.InitializedVU, error) {37 return runner.NewVU(uint64(atomic.AddInt64(&getVUCount, 1)), 0, nil)38 }39 returnVU := func(_ lib.InitializedVU) {40 atomic.AddInt64(&returnVUCount, 1)41 // do something42 }43 var interruptedIter int6444 var fullIterations int6445 runIter := func(ctx context.Context, vu lib.ActiveVU) bool {46 _ = vu.RunOnce()47 select {48 case <-ctx.Done():49 // Don't log errors or emit iterations metrics from cancelled iterations50 atomic.AddInt64(&interruptedIter, 1)51 return false52 default:53 atomic.AddInt64(&fullIterations, 1)54 return true55 }56 }57 vuHandle := newStoppedVUHandle(ctx, getVU, returnVU, mockNextIterations, &BaseConfig{}, logEntry)58 go vuHandle.runLoopsIfPossible(runIter)59 var wg sync.WaitGroup60 wg.Add(3)61 go func() {62 defer wg.Done()63 for i := 0; i < 10000; i++ {64 err := vuHandle.start()65 require.NoError(t, err)66 }67 }()68 go func() {69 defer wg.Done()70 for i := 0; i < 1000; i++ {71 vuHandle.gracefulStop()72 time.Sleep(1 * time.Nanosecond)73 }74 }()75 go func() {76 defer wg.Done()77 for i := 0; i < 100; i++ {78 vuHandle.hardStop()79 time.Sleep(10 * time.Nanosecond)80 }81 }()82 wg.Wait()83 vuHandle.hardStop() // STOP it84 time.Sleep(time.Millisecond * 50)85 interruptedBefore := atomic.LoadInt64(&interruptedIter)86 fullBefore := atomic.LoadInt64(&fullIterations)87 _ = vuHandle.start()88 time.Sleep(time.Millisecond * 50) // just to be sure an iteration will squeeze in89 cancel()90 time.Sleep(time.Millisecond * 50)91 interruptedAfter := atomic.LoadInt64(&interruptedIter)92 fullAfter := atomic.LoadInt64(&fullIterations)93 assert.True(t, interruptedBefore >= interruptedAfter-1,94 "too big of a difference %d >= %d - 1", interruptedBefore, interruptedAfter)95 assert.True(t, fullBefore+1 <= fullAfter,96 "too small of a difference %d + 1 <= %d", fullBefore, fullAfter)97 require.Equal(t, atomic.LoadInt64(&getVUCount), atomic.LoadInt64(&returnVUCount))98}99// this test is mostly interesting when -race is enabled100func TestVUHandleStartStopRace(t *testing.T) {101 t.Parallel()102 ctx, cancel := context.WithCancel(context.Background())103 defer cancel()104 logHook := &testutils.SimpleLogrusHook{HookedLevels: []logrus.Level{logrus.DebugLevel}}105 testLog := logrus.New()106 testLog.AddHook(logHook)107 testLog.SetOutput(testutils.NewTestOutput(t))108 // testLog.Level = logrus.DebugLevel109 logEntry := logrus.NewEntry(testLog)110 runner := &minirunner.MiniRunner{}111 runner.Fn = func(ctx context.Context, out chan<- stats.SampleContainer) error {112 return nil113 }114 var vuID uint64115 testIterations := 10000116 returned := make(chan struct{})117 getVU := func() (lib.InitializedVU, error) {118 returned = make(chan struct{})119 return runner.NewVU(atomic.AddUint64(&vuID, 1), 0, nil)120 }121 returnVU := func(v lib.InitializedVU) {122 require.Equal(t, atomic.LoadUint64(&vuID), v.(*minirunner.VU).ID)123 close(returned)124 }125 var interruptedIter int64126 var fullIterations int64127 runIter := func(ctx context.Context, vu lib.ActiveVU) bool {128 _ = vu.RunOnce()129 select {130 case <-ctx.Done():131 // Don't log errors or emit iterations metrics from cancelled iterations132 atomic.AddInt64(&interruptedIter, 1)133 return false134 default:135 atomic.AddInt64(&fullIterations, 1)136 return true137 }138 }139 vuHandle := newStoppedVUHandle(ctx, getVU, returnVU, mockNextIterations, &BaseConfig{}, logEntry)140 go vuHandle.runLoopsIfPossible(runIter)141 for i := 0; i < testIterations; i++ {142 err := vuHandle.start()143 vuHandle.gracefulStop()144 require.NoError(t, err)145 select {146 case <-returned:147 case <-time.After(100 * time.Millisecond):148 go panic("returning took too long")149 time.Sleep(time.Second)150 }151 }152 vuHandle.hardStop() // STOP it153 time.Sleep(time.Millisecond * 5)154 interruptedBefore := atomic.LoadInt64(&interruptedIter)155 fullBefore := atomic.LoadInt64(&fullIterations)156 _ = vuHandle.start()157 time.Sleep(time.Millisecond * 50) // just to be sure an iteration will squeeze in158 cancel()159 time.Sleep(time.Millisecond * 5)160 interruptedAfter := atomic.LoadInt64(&interruptedIter)161 fullAfter := atomic.LoadInt64(&fullIterations)162 assert.True(t, interruptedBefore >= interruptedAfter-1,163 "too big of a difference %d >= %d - 1", interruptedBefore, interruptedAfter)164 assert.True(t, fullBefore+1 <= fullAfter,165 "too small of a difference %d + 1 <= %d", fullBefore, fullAfter)166}167type handleVUTest struct {168 runner *minirunner.MiniRunner169 getVUCount uint32170 returnVUCount uint32171 interruptedIter int64172 fullIterations int64173}174func (h *handleVUTest) getVU() (lib.InitializedVU, error) {175 return h.runner.NewVU(uint64(atomic.AddUint32(&h.getVUCount, 1)), 0, nil)176}177func (h *handleVUTest) returnVU(_ lib.InitializedVU) {178 atomic.AddUint32(&h.returnVUCount, 1)179}180func (h *handleVUTest) runIter(ctx context.Context, _ lib.ActiveVU) bool {181 select {182 case <-time.After(time.Second):183 case <-ctx.Done():184 }185 select {186 case <-ctx.Done():187 // Don't log errors or emit iterations metrics from cancelled iterations188 atomic.AddInt64(&h.interruptedIter, 1)189 return false190 default:191 atomic.AddInt64(&h.fullIterations, 1)192 return true193 }194}195func TestVUHandleSimple(t *testing.T) {196 t.Parallel()197 t.Run("start before gracefulStop finishes", func(t *testing.T) {198 t.Parallel()199 logHook := &testutils.SimpleLogrusHook{HookedLevels: []logrus.Level{logrus.DebugLevel}}200 testLog := logrus.New()201 testLog.AddHook(logHook)202 testLog.SetOutput(testutils.NewTestOutput(t))203 // testLog.Level = logrus.DebugLevel204 logEntry := logrus.NewEntry(testLog)205 test := &handleVUTest{runner: &minirunner.MiniRunner{}}206 ctx, cancel := context.WithCancel(context.Background())207 defer cancel()208 vuHandle := newStoppedVUHandle(ctx, test.getVU, test.returnVU, mockNextIterations, &BaseConfig{}, logEntry)209 var wg sync.WaitGroup210 wg.Add(1)211 go func() {212 defer wg.Done()213 vuHandle.runLoopsIfPossible(test.runIter)214 }()215 err := vuHandle.start()216 require.NoError(t, err)217 time.Sleep(time.Millisecond * 50)218 vuHandle.gracefulStop()219 // time.Sleep(time.Millisecond * 5) // No sleep as we want to always not return the VU220 err = vuHandle.start()221 require.NoError(t, err)222 time.Sleep(time.Millisecond * 1500)223 assert.EqualValues(t, 1, atomic.LoadUint32(&test.getVUCount))224 assert.EqualValues(t, 0, atomic.LoadUint32(&test.returnVUCount))225 assert.EqualValues(t, 0, atomic.LoadInt64(&test.interruptedIter))226 assert.EqualValues(t, 1, atomic.LoadInt64(&test.fullIterations))227 cancel()228 wg.Wait()229 time.Sleep(time.Millisecond * 5)230 assert.EqualValues(t, 1, atomic.LoadUint32(&test.getVUCount))231 assert.EqualValues(t, 1, atomic.LoadUint32(&test.returnVUCount))232 assert.EqualValues(t, 1, atomic.LoadInt64(&test.interruptedIter))233 assert.EqualValues(t, 1, atomic.LoadInt64(&test.fullIterations))234 })235 t.Run("start after gracefulStop finishes", func(t *testing.T) {236 t.Parallel()237 logHook := &testutils.SimpleLogrusHook{HookedLevels: []logrus.Level{logrus.DebugLevel}}238 testLog := logrus.New()239 testLog.AddHook(logHook)240 testLog.SetOutput(testutils.NewTestOutput(t))241 // testLog.Level = logrus.DebugLevel242 logEntry := logrus.NewEntry(testLog)243 test := &handleVUTest{runner: &minirunner.MiniRunner{}}244 ctx, cancel := context.WithCancel(context.Background())245 defer cancel()246 vuHandle := newStoppedVUHandle(ctx, test.getVU, test.returnVU, mockNextIterations, &BaseConfig{}, logEntry)247 var wg sync.WaitGroup248 wg.Add(1)249 go func() {250 defer wg.Done()251 vuHandle.runLoopsIfPossible(test.runIter)252 }()253 err := vuHandle.start()254 require.NoError(t, err)255 time.Sleep(time.Millisecond * 50)256 vuHandle.gracefulStop()257 time.Sleep(time.Millisecond * 1500)258 assert.EqualValues(t, 1, atomic.LoadUint32(&test.getVUCount))259 assert.EqualValues(t, 1, atomic.LoadUint32(&test.returnVUCount))260 assert.EqualValues(t, 0, atomic.LoadInt64(&test.interruptedIter))261 assert.EqualValues(t, 1, atomic.LoadInt64(&test.fullIterations))262 err = vuHandle.start()263 require.NoError(t, err)264 time.Sleep(time.Millisecond * 1500)265 cancel()266 wg.Wait()267 time.Sleep(time.Millisecond * 50)268 assert.EqualValues(t, 2, atomic.LoadUint32(&test.getVUCount))269 assert.EqualValues(t, 2, atomic.LoadUint32(&test.returnVUCount))270 assert.EqualValues(t, 1, atomic.LoadInt64(&test.interruptedIter))271 assert.EqualValues(t, 2, atomic.LoadInt64(&test.fullIterations))272 })273 t.Run("start after hardStop", func(t *testing.T) {274 t.Parallel()275 logHook := &testutils.SimpleLogrusHook{HookedLevels: []logrus.Level{logrus.DebugLevel}}276 testLog := logrus.New()277 testLog.AddHook(logHook)278 testLog.SetOutput(testutils.NewTestOutput(t))279 // testLog.Level = logrus.DebugLevel280 logEntry := logrus.NewEntry(testLog)281 test := &handleVUTest{runner: &minirunner.MiniRunner{}}282 ctx, cancel := context.WithCancel(context.Background())283 defer cancel()284 vuHandle := newStoppedVUHandle(ctx, test.getVU, test.returnVU, mockNextIterations, &BaseConfig{}, logEntry)285 var wg sync.WaitGroup286 wg.Add(1)287 go func() {288 defer wg.Done()289 vuHandle.runLoopsIfPossible(test.runIter)290 }()291 err := vuHandle.start()292 require.NoError(t, err)293 time.Sleep(time.Millisecond * 5)294 vuHandle.hardStop()295 time.Sleep(time.Millisecond * 15)296 assert.EqualValues(t, 1, atomic.LoadUint32(&test.getVUCount))297 assert.EqualValues(t, 1, atomic.LoadUint32(&test.returnVUCount))298 assert.EqualValues(t, 1, atomic.LoadInt64(&test.interruptedIter))299 assert.EqualValues(t, 0, atomic.LoadInt64(&test.fullIterations))300 err = vuHandle.start()301 require.NoError(t, err)302 time.Sleep(time.Millisecond * 1500)303 cancel()304 wg.Wait()305 time.Sleep(time.Millisecond * 5)306 assert.EqualValues(t, 2, atomic.LoadUint32(&test.getVUCount))307 assert.EqualValues(t, 2, atomic.LoadUint32(&test.returnVUCount))308 assert.EqualValues(t, 2, atomic.LoadInt64(&test.interruptedIter))309 assert.EqualValues(t, 1, atomic.LoadInt64(&test.fullIterations))310 })311}312func BenchmarkVUHandleIterations(b *testing.B) {313 logHook := &testutils.SimpleLogrusHook{HookedLevels: []logrus.Level{logrus.DebugLevel}}314 testLog := logrus.New()315 testLog.AddHook(logHook)316 // testLog.Level = logrus.DebugLevel317 logEntry := logrus.NewEntry(testLog)318 var (319 getVUCount uint32320 returnVUCount uint32321 interruptedIter int64322 fullIterations int64323 )324 reset := func() {325 getVUCount = 0326 returnVUCount = 0327 interruptedIter = 0328 fullIterations = 0329 }330 runner := &minirunner.MiniRunner{}331 runner.Fn = func(ctx context.Context, out chan<- stats.SampleContainer) error {332 return nil333 }334 getVU := func() (lib.InitializedVU, error) {335 return runner.NewVU(uint64(atomic.AddUint32(&getVUCount, 1)), 0, nil)336 }337 returnVU := func(_ lib.InitializedVU) {338 atomic.AddUint32(&returnVUCount, 1)339 }340 runIter := func(ctx context.Context, _ lib.ActiveVU) bool {341 // Do nothing342 select {343 case <-ctx.Done():344 // Don't log errors or emit iterations metrics from cancelled iterations345 atomic.AddInt64(&interruptedIter, 1)346 return false347 default:348 atomic.AddInt64(&fullIterations, 1)349 return true350 }351 }352 reset()353 ctx, cancel := context.WithCancel(context.Background())354 defer cancel()355 vuHandle := newStoppedVUHandle(ctx, getVU, returnVU, mockNextIterations, &BaseConfig{}, logEntry)356 var wg sync.WaitGroup357 wg.Add(1)358 go func() {359 defer wg.Done()360 vuHandle.runLoopsIfPossible(runIter)361 }()362 start := time.Now()363 b.ResetTimer()364 err := vuHandle.start()365 require.NoError(b, err)366 time.Sleep(time.Second)367 cancel()368 wg.Wait()369 b.StopTimer()370 took := time.Since(start)371 b.ReportMetric(float64(atomic.LoadInt64(&fullIterations))/float64(took), "iterations/ns")372}...
ReturnVU
Using AI Code Generation
1func main() {2 lib.ReturnVU()3}4func main() {5 lib.ReturnVU()6}7func main() {8 lib.ReturnVU()9}10func main() {11 lib.ReturnVU()12}13func main() {14 lib.ReturnVU()15}16func main() {17 lib.ReturnVU()18}19func main() {20 lib.ReturnVU()21}22func main() {23 lib.ReturnVU()24}25func main() {26 lib.ReturnVU()27}28func main() {29 lib.ReturnVU()30}31func main() {32 lib.ReturnVU()33}34func main() {35 lib.ReturnVU()36}37func main() {38 lib.ReturnVU()39}40func main() {41 lib.ReturnVU()42}43func main() {44 lib.ReturnVU()45}46func main() {47 lib.ReturnVU()48}49func main() {50 lib.ReturnVU()51}
ReturnVU
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World!")4 lib.ReturnVU()5}6import (7func ReturnVU() {8 fmt.Println("Hello VU")9}
ReturnVU
Using AI Code Generation
1import (2func main() {3 lib.ReturnVU()4}5import (6type Lib struct {7}8func (l *Lib) ReturnVU() {9 fmt.Println("VU")10}11func main() {12 l := &Lib{}13 l.ReturnVU()14}15import (16func main() {17 lib.ReturnVU()18}
ReturnVU
Using AI Code Generation
1func main() {2 v1, v2 = lib.ReturnVU()3 fmt.Println(v1, v2)4}5import "fmt"6func ReturnVU() (float64, float64) {7 fmt.Println("Enter V1: ")8 fmt.Scan(&v1)9 fmt.Println("Enter V2: ")10 fmt.Scan(&v2)11}
ReturnVU
Using AI Code Generation
1import (2var (3 settings = gobreaker.Settings{4 ReadyToTrip: func(counts gobreaker.Counts) bool {5 ratio := float64(counts.TotalFailures) / float64(counts.Requests)6 },7 }8func main() {9 for i := 0; i < 5; i++ {10 wg.Add(1)11 go func() {12 defer wg.Done()13 breaker := gobreaker.NewCircuitBreaker(settings)14 for {15 _, err := breaker.Execute(func() (interface{}, error) {16 return nil, fmt.Errorf("error")17 })18 if err != nil {19 log.Println(err)20 }21 time.Sleep(500 * time.Millisecond)22 }23 }()24 }25 wg.Wait()26}27import (28var (29 settings = gobreaker.Settings{30 ReadyToTrip: func(counts gobreaker.Counts) bool {31 ratio := float64(counts.TotalFailures) / float64(counts.Requests)32 },33 }34func main() {35 for i := 0; i < 5; i++ {36 wg.Add(1)37 go func() {38 defer wg.Done()39 breaker := gobreaker.NewCircuitBreaker(settings)40 for {41 _, err := breaker.Execute(func() (interface{}, error) {42 return nil, fmt.Errorf("error")43 })
ReturnVU
Using AI Code Generation
1import (2func main() {3 fmt.Println(lib.ReturnVU())4}5import "fmt"6func ReturnVU() string {7}8import "testing"9func TestReturnVU(t *testing.T) {10 got := ReturnVU()11 if got != want {12 t.Errorf("got %q want %q", got, want)13 }14}15import "testing"16func TestReturnVU(t *testing.T) {17 got := ReturnVU()18 if got != want {19 t.Errorf("got %q want %q", got, want)20 }21}22import "fmt"23func ReturnVU() string {24}25import (26func main() {27 fmt.Println(lib.ReturnVU())28}29import "testing"30func TestReturnVU(t *testing.T) {31 got := ReturnVU()32 if got != want {33 t.Errorf("got %q want %q", got, want)34 }35}36import "fmt"37func ReturnVU() string {38}39import (40func main() {41 fmt.Println(lib.ReturnVU())42}
ReturnVU
Using AI Code Generation
1import (2func main() {3 lib := libclass.LibClass{}4 lib.SetVU(5)5 fmt.Println(lib.ReturnVU())6}
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!!