Skip to content

Commit

Permalink
Merge 20c22d9 into 2039c56
Browse files Browse the repository at this point in the history
  • Loading branch information
mstoykov committed Jun 25, 2021
2 parents 2039c56 + 20c22d9 commit d19c491
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 9 deletions.
16 changes: 10 additions & 6 deletions js/modules/k6/metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,16 @@ func newMetric(ctxPtr *context.Context, name string, t stats.MetricType, isTime
}

rt := common.GetRuntime(*ctxPtr)
return common.Bind(rt, Metric{stats.New(name, t, valueType)}, ctxPtr), nil
bound := common.Bind(rt, Metric{stats.New(name, t, valueType)}, ctxPtr)
o := rt.NewObject()
err := o.DefineDataProperty("name", rt.ToValue(name), goja.FLAG_FALSE, goja.FLAG_FALSE, goja.FLAG_TRUE)
if err != nil {
return nil, err
}
if err = o.Set("add", rt.ToValue(bound["add"])); err != nil {
return nil, err
}
return o, nil
}

func (m Metric) Add(ctx context.Context, v goja.Value, addTags ...map[string]string) (bool, error) {
Expand All @@ -91,11 +100,6 @@ func (m Metric) Add(ctx context.Context, v goja.Value, addTags ...map[string]str
return true, nil
}

// GetName returns the metric name
func (m Metric) GetName() string {
return m.metric.Name
}

type Metrics struct{}

func New() *Metrics {
Expand Down
21 changes: 19 additions & 2 deletions js/modules/k6/metrics/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,23 @@ func TestMetricNames(t *testing.T) {

func TestMetricGetName(t *testing.T) {
t.Parallel()
metric := Metric{metric: &stats.Metric{Name: "myMetricName"}}
assert.Equal(t, "myMetricName", metric.GetName())
rt := goja.New()
rt.SetFieldNameMapper(common.FieldNameMapper{})

ctxPtr := new(context.Context)
*ctxPtr = common.WithRuntime(context.Background(), rt)
require.NoError(t, rt.Set("metrics", common.Bind(rt, New(), ctxPtr)))
v, err := rt.RunString(`
var m = new metrics.Counter("my_metric")
m.name
`)
require.NoError(t, err)
require.Equal(t, "my_metric", v.String())

_, err = rt.RunString(`
"use strict";
m.name = "something"
`)
require.Error(t, err)
require.Contains(t, err.Error(), "TypeError: Cannot assign to read only property 'name'")
}
2 changes: 1 addition & 1 deletion samples/custom_metrics.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export default function () {

// Add one for number of requests
myCounter.add(1);
console.log(myCounter.getName(), " is config ready")
console.log(myCounter.name, " is config ready")

// Set max response time seen
maxResponseTime = Math.max(maxResponseTime, res.timings.duration);
Expand Down

0 comments on commit d19c491

Please sign in to comment.