Skip to content

Commit

Permalink
k6.sleep() actually implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
Emily Ekberg committed May 4, 2017
1 parent a0566d9 commit 274eef8
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
10 changes: 9 additions & 1 deletion js/modules/k6/k6.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ package k6
import (
"context"
"sync/atomic"

"time"

"github.com/dop251/goja"
Expand All @@ -34,6 +33,15 @@ import (

type K6 struct{}

func (*K6) Sleep(ctx context.Context, secs float64) {
timer := time.NewTimer(time.Duration(secs * float64(time.Second)))
select {
case <-timer.C:
case <-ctx.Done():
timer.Stop()
}
}

func (*K6) Group(ctx context.Context, name string, fn goja.Callable) (goja.Value, error) {
state := common.GetState(ctx)

Expand Down
42 changes: 42 additions & 0 deletions js/modules/k6/k6_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ package k6
import (
"context"
"fmt"
"runtime"
"testing"
"time"

"github.com/dop251/goja"
"github.com/loadimpact/k6/js/common"
Expand All @@ -32,6 +34,46 @@ import (
"github.com/stretchr/testify/assert"
)

func TestSleep(t *testing.T) {
rt := goja.New()
ctx, cancel := context.WithCancel(context.Background())
rt.Set("k6", common.Bind(rt, &K6{}, &ctx))

testdata := map[string]time.Duration{
"1": 1 * time.Second,
"1.0": 1 * time.Second,
"0.5": 500 * time.Millisecond,
}
for name, d := range testdata {
t.Run(name, func(t *testing.T) {
startTime := time.Now()
_, err := common.RunString(rt, `k6.sleep(1)`)
endTime := time.Now()
assert.NoError(t, err)
assert.True(t, endTime.Sub(startTime) > d, "did not sleep long enough")
})
}

t.Run("Cancel", func(t *testing.T) {
dch := make(chan time.Duration)
go func() {
startTime := time.Now()
_, err := common.RunString(rt, `k6.sleep(10)`)
endTime := time.Now()
assert.NoError(t, err)
dch <- endTime.Sub(startTime)
}()
runtime.Gosched()
time.Sleep(1 * time.Second)
runtime.Gosched()
cancel()
runtime.Gosched()
d := <-dch
assert.True(t, d > 500*time.Millisecond, "did not sleep long enough")
assert.True(t, d < 2*time.Second, "slept for too long!!")
})
}

func TestGroup(t *testing.T) {
root, err := lib.NewGroup("", nil)
assert.NoError(t, err)
Expand Down

0 comments on commit 274eef8

Please sign in to comment.