Skip to content

Commit

Permalink
allowing variable name for tests
Browse files Browse the repository at this point in the history
  • Loading branch information
xoscar committed Jan 20, 2023
1 parent 1b55d5f commit 0fe5e80
Show file tree
Hide file tree
Showing 12 changed files with 189 additions and 174 deletions.
55 changes: 24 additions & 31 deletions examples/test-from-id.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,45 @@
import { check } from 'k6';
import { Http, Tracetest } from "k6/x/tracetest";
import { sleep } from "k6";

export const options = {
vus: 1,
duration: "5s",
duration: "6s",
};

const http = new Http();
const tracetest = Tracetest({
serverUrl: "http://localhost:3000",
});
const testId = "J0d887oVR";
const testId = "kc_MgKoVR";
const pokemonId = 6;
const http = new Http();

export default function () {
/// successful test run
http.get("http://localhost:8081/pokemon?take=5", {
const url = "http://localhost:8081/pokemon/import";
const payload = JSON.stringify({
id: pokemonId,
});
const params = {
tracetest: {
testId,
},
});

/// failed test specs test run
http.get("http://localhost:8081/pokemon?take=10", {
tracetest: {
testId: "nDdBCnoVg",
headers: {
'Content-Type': 'application/json',
},
});

/// not existing test
// http.get("http://localhost:8081/pokemon?take=10", {
// tracetest: {
// testId: "doesnt-exist",
// },
// });
};

/// wrong endpoint
// http.get("http://localhost:8081/wrong", {
// tracetest: {
// testId: "nDdBCnoVg",
// },
// });
const response = http.post(url, payload, params);

check(response, {
'is status 200': (r) => r.status === 200,
'body matches de id': (r) => JSON.parse(r.body).id === pokemonId,
});
sleep(1);
}

export function handleSummary() {
return {
stdout: tracetest.summary(),
'tracetest.json': tracetest.json(),
};
}
// export function handleSummary() {
// return {
// stdout: tracetest.summary(),
// "tracetest.json": tracetest.json(),
// };
// }
8 changes: 4 additions & 4 deletions modules/tracetest/options.go → models/apiOptions.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package tracetest
package models

import (
"fmt"
Expand All @@ -8,7 +8,7 @@ import (
"go.k6.io/k6/js/modules"
)

type Options struct {
type ApiOptions struct {
ServerUrl string
ServerPath string
}
Expand All @@ -19,9 +19,9 @@ const (
ServerPath = "serverPath"
)

func getOptions(vu modules.VU, val goja.Value) (Options, error) {
func NewApiOptions(vu modules.VU, val goja.Value) (ApiOptions, error) {
rawOptions := utils.ParseOptions(vu, val)
options := Options{
options := ApiOptions{
ServerUrl: DefaultServerUrl,
ServerPath: "",
}
Expand Down
58 changes: 58 additions & 0 deletions models/httpClientOptions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package models

import (
"fmt"
"strings"

"github.com/dop251/goja"
"github.com/kubeshop/xk6-tracetest/utils"
"go.k6.io/k6/js/modules"
)

var defaultPropagatorList = []PropagatorName{
TraceContext,
Baggage,
PropagatorB3,
OT,
Jaeger,
XRay,
}

type HttpClientOptions struct {
Propagator Propagator
Tracetest TracetestOptions
}

func NewHttpClientOptions(vu modules.VU, val goja.Value) (HttpClientOptions, error) {
rawOptions := utils.ParseOptions(vu, val)
options := HttpClientOptions{
Propagator: NewPropagator(defaultPropagatorList),
Tracetest: TracetestOptions{
ShouldWait: true,
VariableName: "TRACE_ID",
},
}

if len(rawOptions) == 0 {
return options, nil
}

for key, value := range rawOptions {
switch key {
case "propagator":
rawPropagatorList := strings.Split(value.ToString().String(), ",")
propagatorList := make([]PropagatorName, len(rawPropagatorList))
for i, propagator := range rawPropagatorList {
propagatorList[i] = PropagatorName(propagator)
}

options.Propagator = NewPropagator(propagatorList)
case "tracetest":
options.Tracetest = NewTracetestOptions(vu.Runtime(), val.ToObject(vu.Runtime()))
default:
return options, fmt.Errorf("unknown HTTP tracing option '%s'", key)
}
}

return options, nil
}
34 changes: 19 additions & 15 deletions models/job.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,29 +22,33 @@ const (
)

type Job struct {
TraceID string
TestID string
JobType JobType
Request Request
Run *TracetestRun
JobStatus JobStatus
ShouldWait bool
TraceID string
TestID string
VariableName string
JobType JobType
Request Request
Run *TracetestRun
JobStatus JobStatus
TracetestOptions TracetestOptions
Error string
}

func NewJob(traceID, testID string, jobType JobType, shouldWait bool, request Request) Job {
func NewJob(traceId string, options TracetestOptions, request Request) Job {
return Job{
TraceID: traceID,
TestID: testID,
JobType: jobType,
Request: request,
JobStatus: Pending,
ShouldWait: shouldWait,
JobType: RunTestFromId,
Request: request,
JobStatus: Pending,

TraceID: traceId,
TestID: options.TestID,
TracetestOptions: options,
}
}

func (job Job) HandleRunResponse(run *openapi.TestRun, err error) Job {
if run == nil {
job.JobStatus = Failed
job.Error = err.Error()
} else {
job.JobStatus = Success
job.Run = &TracetestRun{
Expand All @@ -57,7 +61,7 @@ func (job Job) HandleRunResponse(run *openapi.TestRun, err error) Job {
}

func (job Job) Summary(baseUrl string) string {
runSummary := "JobStatus=" + string(job.JobStatus)
runSummary := fmt.Sprintf("JobStatus=%s, Error=%s", string(job.JobStatus), job.Error)
if job.Run != nil {
runSummary = job.Run.Summary(baseUrl)
}
Expand Down
35 changes: 35 additions & 0 deletions models/tracetestOptions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package models

import "github.com/dop251/goja"

type TracetestOptions struct {
TestID string
ShouldWait bool
VariableName string
}

func NewTracetestOptions(runTime *goja.Runtime, params *goja.Object) TracetestOptions {
rawOptions := params.Get("tracetest")
options := TracetestOptions{
ShouldWait: true,
VariableName: "TRACE_ID",
}

if rawOptions == nil {
return options
}

optionsObject := rawOptions.ToObject(runTime)
for _, key := range optionsObject.Keys() {
switch key {
case "testId":
options.TestID = optionsObject.Get(key).String()
case "shouldWait":
options.ShouldWait = optionsObject.Get(key).ToBoolean()
case "variableName":
options.VariableName = optionsObject.Get(key).ToString().String()
}
}

return options
}
30 changes: 21 additions & 9 deletions modules/httpClient/enhancers.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
package httpClient

import (
"context"
"fmt"
"time"

"github.com/dop251/goja"
"github.com/kubeshop/xk6-tracetest/models"
"github.com/kubeshop/xk6-tracetest/utils"
k6HTTP "go.k6.io/k6/js/modules/k6/http"
"go.k6.io/k6/lib"
"go.k6.io/k6/metrics"
)

const (
TraceID = "trace_id"
TestID = "test_id"
ShouldWait = "should_wait"
TraceID = "trace_id"
TestID = "test_id"
ShouldWait = "should_wait"
VariableName = "variable_name"
)

func (c *HttpClient) WithTrace(fn HttpFunc, url goja.Value, args ...goja.Value) (*HTTPResponse, error) {
Expand Down Expand Up @@ -72,19 +75,21 @@ func (c *HttpClient) WithTrace(fn HttpFunc, url goja.Value, args ...goja.Value)
}

func (c *HttpClient) setTags(rt *goja.Runtime, state *lib.State, traceID string, params *goja.Object) {
tracetestOptions := parseTracetestOptions(rt, params)
tracetestOptions := models.NewTracetestOptions(rt, params)
state.Tags.Modify(func(tagsAndMeta *metrics.TagsAndMeta) {
tagsAndMeta.SetMetadata(TraceID, traceID)

if tracetestOptions.testID != "" {
tagsAndMeta.SetMetadata(TestID, tracetestOptions.testID)
} else if c.options.Tracetest.testID != "" {
tagsAndMeta.SetMetadata(TestID, c.options.Tracetest.testID)
if tracetestOptions.TestID != "" {
tagsAndMeta.SetMetadata(TestID, tracetestOptions.TestID)
} else if c.options.Tracetest.TestID != "" {
tagsAndMeta.SetMetadata(TestID, c.options.Tracetest.TestID)
}

if tracetestOptions.shouldWait || c.options.Tracetest.shouldWait {
if tracetestOptions.ShouldWait || c.options.Tracetest.ShouldWait {
tagsAndMeta.SetMetadata(ShouldWait, "true")
}

tagsAndMeta.SetMetadata(VariableName, tracetestOptions.VariableName)
})
}

Expand All @@ -93,5 +98,12 @@ func (c *HttpClient) deleteTags(state *lib.State) {
tagsAndMeta.DeleteMetadata(TraceID)
tagsAndMeta.DeleteMetadata(TestID)
tagsAndMeta.DeleteMetadata(ShouldWait)
tagsAndMeta.DeleteMetadata(VariableName)
})
}

func requestToHttpFunc(method string, request HttpRequestFunc) HttpFunc {
return func(ctx context.Context, url goja.Value, args ...goja.Value) (*k6HTTP.Response, error) {
return request(method, url, args...)
}
}
5 changes: 3 additions & 2 deletions modules/httpClient/httpClient.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net/http"

"github.com/dop251/goja"
"github.com/kubeshop/xk6-tracetest/models"
"go.k6.io/k6/js/common"
"go.k6.io/k6/js/modules"
k6HTTP "go.k6.io/k6/js/modules/k6/http"
Expand All @@ -14,7 +15,7 @@ type HttpClient struct {
vu modules.VU
httpRequest HttpRequestFunc

options Options
options models.HttpClientOptions
}

type HTTPResponse struct {
Expand Down Expand Up @@ -46,7 +47,7 @@ func New(vu modules.VU) *HttpClient {

func (h *HttpClient) Constructor(call goja.ConstructorCall) *goja.Object {
rt := h.vu.Runtime()
options, err := getOptions(h.vu, call.Argument(0))
options, err := models.NewHttpClientOptions(h.vu, call.Argument(0))
if err != nil {
common.Throw(rt, err)
}
Expand Down
Loading

0 comments on commit 0fe5e80

Please sign in to comment.