Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix a bunch of minor issues and repetitions #1453

Merged
merged 2 commits into from
May 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions core/local/local_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -385,9 +385,8 @@ func TestExecutionSchedulerRunCustomConfigNoCrossover(t *testing.T) {
t.Parallel()
tb := httpmultibin.NewHTTPMultiBin(t)
defer tb.Cleanup()
sr := tb.Replacer.Replace

script := sr(`
script := tb.Replacer.Replace(`
import http from "k6/http";
import ws from 'k6/ws';
import { Counter } from 'k6/metrics';
Expand Down
4 changes: 4 additions & 0 deletions js/bundle.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ type BundleInstance struct {
Runtime *goja.Runtime
Context *context.Context

//TODO: maybe just have a reference to the Bundle? or save and pass rtOpts?
env map[string]string

exports map[string]goja.Callable
}

Expand Down Expand Up @@ -235,6 +238,7 @@ func (b *Bundle) Instantiate() (bi *BundleInstance, instErr error) {
Runtime: rt,
Context: ctxPtr,
exports: make(map[string]goja.Callable),
env: b.Env,
}

// Grab any exported functions that could be executed. These were
Expand Down
75 changes: 4 additions & 71 deletions js/modules/k6/http/request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ func newRuntime(
Transport: tb.HTTPTransport,
BPool: bpool.NewBufferPool(1),
Samples: samples,
Tags: map[string]string{"group": root.Path},
}

ctx := new(context.Context)
Expand Down Expand Up @@ -924,9 +925,9 @@ func TestRequestAndBatch(t *testing.T) {
})

t.Run("tags-precedence", func(t *testing.T) {
oldOpts := state.Options
defer func() { state.Options = oldOpts }()
state.Options.RunTags = stats.IntoSampleTags(&map[string]string{"runtag1": "val1", "runtag2": "val2"})
oldTags := state.Tags
defer func() { state.Tags = oldTags }()
state.Tags = map[string]string{"runtag1": "val1", "runtag2": "val2"}

_, err := common.RunString(rt, sr(`
let res = http.request("GET", "HTTPBIN_URL/headers", null, { tags: { method: "test", name: "myName", runtag1: "fromreq" } });
Expand Down Expand Up @@ -1268,74 +1269,6 @@ func TestRequestAndBatch(t *testing.T) {
})
})
}
func TestSystemTags(t *testing.T) {
t.Parallel()
tb, state, samples, rt, _ := newRuntime(t)
defer tb.Cleanup()

// Handple paths with custom logic
tb.Mux.HandleFunc("/wrong-redirect", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Location", "%")
w.WriteHeader(http.StatusTemporaryRedirect)
})

httpGet := fmt.Sprintf(`http.get("%s");`, tb.ServerHTTP.URL)
httpsGet := fmt.Sprintf(`http.get("%s");`, tb.ServerHTTPS.URL)

httpURL, err := url.Parse(tb.ServerHTTP.URL)
require.NoError(t, err)

testedSystemTags := []struct{ tag, code, expVal string }{
{"proto", httpGet, "HTTP/1.1"},
{"status", httpGet, "200"},
{"method", httpGet, "GET"},
{"url", httpGet, tb.ServerHTTP.URL},
{"url", httpsGet, tb.ServerHTTPS.URL},
{"ip", httpGet, httpURL.Hostname()},
{"name", httpGet, tb.ServerHTTP.URL},
{"group", httpGet, ""},
{"vu", httpGet, "0"},
{"iter", httpGet, "0"},
{"tls_version", httpsGet, expectedTLSVersion},
{"ocsp_status", httpsGet, "unknown"},
{
"error",
tb.Replacer.Replace(`http.get("http://127.0.0.1:1");`),
`dial: connection refused`,
},
{
"error_code",
tb.Replacer.Replace(`http.get("http://127.0.0.1:1");`),
"1212",
},
}

state.Options.Throw = null.BoolFrom(false)
state.Options.Apply(lib.Options{TLSVersion: &lib.TLSVersions{Max: lib.TLSVersion13}})

for num, tc := range testedSystemTags {
tc := tc
t.Run(fmt.Sprintf("TC %d with only %s", num, tc.tag), func(t *testing.T) {
state.Options.SystemTags = stats.ToSystemTagSet([]string{tc.tag})

_, err := common.RunString(rt, tc.code)
assert.NoError(t, err)

bufSamples := stats.GetBufferedSamples(samples)
assert.NotEmpty(t, bufSamples)
for _, sampleC := range bufSamples {

for _, sample := range sampleC.GetSamples() {
assert.NotEmpty(t, sample.Tags)
for emittedTag, emittedVal := range sample.Tags.CloneTags() {
assert.Equal(t, tc.tag, emittedTag)
assert.Equal(t, tc.expVal, emittedVal)
}
}
}
})
}
}

func TestRequestCompression(t *testing.T) {
t.Parallel()
Expand Down
14 changes: 9 additions & 5 deletions js/modules/k6/http/response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ const jsonData = `{"glossary": {
"GlossSeeAlso": ["GML","XML"]},
"GlossSee": "markup"}}}}}`

const invalidJSONData = `{
const invalidJSONData = `{
"a":"apple",
"t":testing"
}`
Expand Down Expand Up @@ -168,7 +168,11 @@ func TestResponse(t *testing.T) {
if assert.NoError(t, err) {
old := state.Group
state.Group = g
defer func() { state.Group = old }()
state.Tags["group"] = g.Path
defer func() {
state.Group = old
state.Tags["group"] = old.Path
}()
}

_, err = common.RunString(rt, sr(`
Expand Down Expand Up @@ -217,7 +221,7 @@ func TestResponse(t *testing.T) {
if (value != undefined)
{ throw new Error("Expected undefined, but got: " + value); }

value = res.json("glossary.null")
value = res.json("glossary.null")
if (value != null)
{ throw new Error("Expected null, but got: " + value); }

Expand All @@ -233,8 +237,8 @@ func TestResponse(t *testing.T) {
if (value != true)
{ throw new Error("Expected boolean true, but got: " + value); }

value = res.json("glossary.GlossDiv.GlossList.GlossEntry.GlossDef.title")
if (value != "example glossary")
value = res.json("glossary.GlossDiv.GlossList.GlossEntry.GlossDef.title")
if (value != "example glossary")
{ throw new Error("Expected 'example glossary'', but got: " + value); }

value = res.json("glossary.friends.#.first")[0]
Expand Down
25 changes: 0 additions & 25 deletions js/modules/k6/http/tls_go_1_11_test.go

This file was deleted.

25 changes: 0 additions & 25 deletions js/modules/k6/http/tls_go_1_12_test.go

This file was deleted.

28 changes: 14 additions & 14 deletions js/modules/k6/k6.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,23 @@ func (*K6) Group(ctx context.Context, name string, fn goja.Callable) (goja.Value

old := state.Group
state.Group = g
defer func() { state.Group = old }()

shouldUpdateTag := state.Options.SystemTags.Has(stats.TagGroup)
if shouldUpdateTag {
state.Tags["group"] = g.Path
}
defer func() {
state.Group = old
if shouldUpdateTag {
state.Tags["group"] = old.Path
}
}()

startTime := time.Now()
ret, err := fn(goja.Undefined())
t := time.Now()

tags := map[string]string{}
for k, v := range state.Tags {
tags[k] = v
}

tags := state.CloneTags()
stats.PushIfNotDone(ctx, state.Samples, stats.Sample{
Time: t,
Metric: metrics.GroupDuration,
Expand All @@ -113,14 +119,8 @@ func (*K6) Check(ctx context.Context, arg0, checks goja.Value, extras ...goja.Va
rt := common.GetRuntime(ctx)
t := time.Now()

// Prepare tags, make sure the `group` tag can't be overwritten.
commonTags := map[string]string{}
for k, v := range state.Tags {
commonTags[k] = v
}
if state.Options.SystemTags.Has(stats.TagGroup) {
commonTags["group"] = state.Group.Path
}
// Prepare the metric tags
commonTags := state.CloneTags()
if len(extras) > 0 {
obj := extras[0].ToObject(rt)
for _, k := range obj.Keys() {
Expand Down
1 change: 1 addition & 0 deletions js/modules/k6/k6_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ func TestCheck(t *testing.T) {
SystemTags: &stats.DefaultSystemTagSet,
},
Samples: samples,
Tags: map[string]string{"group": root.Path},
}, samples
}
t.Run("Object", func(t *testing.T) {
Expand Down
9 changes: 1 addition & 8 deletions js/modules/k6/metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,7 @@ func (m Metric) Add(ctx context.Context, v goja.Value, addTags ...map[string]str
return false, ErrMetricsAddInInitContext
}

tags := map[string]string{}
for k, v := range state.Tags {
tags[k] = v
}
if state.Options.SystemTags.Has(stats.TagGroup) {
tags["group"] = state.Group.Path
}

tags := state.CloneTags()
for _, ts := range addTags {
for k, v := range ts {
tags[k] = v
Expand Down
3 changes: 3 additions & 0 deletions js/modules/k6/metrics/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ func TestMetrics(t *testing.T) {
Options: lib.Options{SystemTags: stats.NewSystemTagSet(stats.TagGroup)},
Group: root,
Samples: samples,
Tags: map[string]string{"group": root.Path},
}

isTimeString := ""
Expand All @@ -96,8 +97,10 @@ func TestMetrics(t *testing.T) {
"Child": child,
}
for name, g := range groups {
name, g := name, g
t.Run(name, func(t *testing.T) {
state.Group = g
state.Tags["group"] = g.Path
for name, val := range values {
t.Run(name, func(t *testing.T) {
t.Run("Simple", func(t *testing.T) {
Expand Down
8 changes: 1 addition & 7 deletions js/modules/k6/ws/ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,7 @@ func (*WS) Connect(ctx context.Context, url string, args ...goja.Value) (*WSHTTP
// Leave header to nil by default so we can pass it directly to the Dialer
var header http.Header

tags := map[string]string{}
for k, v := range state.Tags {
tags[k] = v
}
tags := state.CloneTags()

// Parse the optional second argument (params)
if !goja.IsUndefined(paramsV) && !goja.IsNull(paramsV) {
Expand Down Expand Up @@ -147,9 +144,6 @@ func (*WS) Connect(ctx context.Context, url string, args ...goja.Value) (*WSHTTP
if state.Options.SystemTags.Has(stats.TagURL) {
tags["url"] = url
}
if state.Options.SystemTags.Has(stats.TagGroup) {
tags["group"] = state.Group.Path
}

// Pass a custom net.Dial function to websocket.Dialer that will substitute
// the underlying net.Conn with our own tracked netext.Conn
Expand Down
13 changes: 7 additions & 6 deletions js/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -396,13 +396,14 @@ func (u *VU) Activate(params *lib.VUActivationParams) lib.ActiveVU {
}

// Override the preset global env with any custom env vars
if len(params.Env) > 0 {
env := u.Runtime.Get("__ENV").Export().(map[string]string)
for key, value := range params.Env {
env[key] = value
}
u.Runtime.Set("__ENV", env)
env := make(map[string]string, len(u.env)+len(params.Env))
for key, value := range u.env {
env[key] = value
}
for key, value := range params.Env {
env[key] = value
}
u.Runtime.Set("__ENV", env)

avu := &ActiveVU{
VU: u,
Expand Down
Loading