|
| 1 | +package k6 |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "runtime/pprof" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/stretchr/testify/require" |
| 11 | + "go.opentelemetry.io/otel/baggage" |
| 12 | +) |
| 13 | + |
| 14 | +func Test_getBaggageLabels(t *testing.T) { |
| 15 | + t.Run("empty values are skipped", func(t *testing.T) { |
| 16 | + req := httptest.NewRequest("GET", "http://example.com", nil) |
| 17 | + req = testRequestWithBaggage(t, req, map[string]string{ |
| 18 | + "blank": "", |
| 19 | + }) |
| 20 | + |
| 21 | + labelSet := getBaggageLabels(req) |
| 22 | + gotLabels := testPprofLabelsToMap(t, *labelSet) |
| 23 | + |
| 24 | + expectedLabels := map[string]string{} |
| 25 | + require.Equal(t, expectedLabels, gotLabels) |
| 26 | + }) |
| 27 | + |
| 28 | + t.Run("with K6Options", func(t *testing.T) { |
| 29 | + req := httptest.NewRequest("GET", "http://example.com", nil) |
| 30 | + req = testRequestWithBaggage(t, req, map[string]string{ |
| 31 | + "k6.test_run_id": "123", |
| 32 | + "not_k6.some_other_key": "value", |
| 33 | + }) |
| 34 | + |
| 35 | + labelSet := getBaggageLabels(req) |
| 36 | + gotLabels := testPprofLabelsToMap(t, *labelSet) |
| 37 | + |
| 38 | + expectedLabels := map[string]string{ |
| 39 | + "k6_test_run_id": "123", |
| 40 | + } |
| 41 | + require.Equal(t, expectedLabels, gotLabels) |
| 42 | + }) |
| 43 | + |
| 44 | + t.Run("does not allocate with failure to parse baggage", func(t *testing.T) { |
| 45 | + req := httptest.NewRequest("GET", "http://example.com", nil) |
| 46 | + req.Header.Add("Baggage", "invalid") |
| 47 | + |
| 48 | + labelSet := getBaggageLabels(req) |
| 49 | + require.Nil(t, labelSet) |
| 50 | + }) |
| 51 | +} |
| 52 | + |
| 53 | +func testRequestWithBaggage(t *testing.T, req *http.Request, bag map[string]string) *http.Request { |
| 54 | + t.Helper() |
| 55 | + |
| 56 | + members := []baggage.Member{} |
| 57 | + for k, v := range bag { |
| 58 | + member, err := baggage.NewMember(k, v) |
| 59 | + require.NoError(t, err) |
| 60 | + |
| 61 | + members = append(members, member) |
| 62 | + } |
| 63 | + |
| 64 | + b, err := baggage.New(members...) |
| 65 | + require.NoError(t, err) |
| 66 | + |
| 67 | + req.Header.Add("Baggage", b.String()) |
| 68 | + return req |
| 69 | +} |
| 70 | + |
| 71 | +func testPprofLabelsToMap(t *testing.T, labelSet pprof.LabelSet) map[string]string { |
| 72 | + t.Helper() |
| 73 | + |
| 74 | + gotLabels := map[string]string{} |
| 75 | + ctx := pprof.WithLabels(context.Background(), labelSet) |
| 76 | + pprof.ForLabels(ctx, func(key, value string) bool { |
| 77 | + gotLabels[key] = value |
| 78 | + return true |
| 79 | + }) |
| 80 | + |
| 81 | + return gotLabels |
| 82 | +} |
0 commit comments