Best Go-testdeep code snippet using td.newMap
oc_to_traces_test.go
Source:oc_to_traces_test.go
1// Copyright The OpenTelemetry Authors2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14package opencensus15import (16 "strconv"17 "testing"18 occommon "github.com/census-instrumentation/opencensus-proto/gen-go/agent/common/v1"19 ocresource "github.com/census-instrumentation/opencensus-proto/gen-go/resource/v1"20 octrace "github.com/census-instrumentation/opencensus-proto/gen-go/trace/v1"21 "github.com/stretchr/testify/assert"22 "go.opentelemetry.io/collector/pdata/pcommon"23 "go.opentelemetry.io/collector/pdata/ptrace"24 "google.golang.org/protobuf/proto"25 "google.golang.org/protobuf/types/known/timestamppb"26 "google.golang.org/protobuf/types/known/wrapperspb"27 "github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/occonventions"28 "github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/testdata"29)30func TestOcTraceStateToInternal(t *testing.T) {31 assert.EqualValues(t, "", ocTraceStateToInternal(nil))32 tracestate := &octrace.Span_Tracestate{33 Entries: []*octrace.Span_Tracestate_Entry{34 {35 Key: "abc",36 Value: "def",37 },38 },39 }40 assert.EqualValues(t, "abc=def", ocTraceStateToInternal(tracestate))41 tracestate.Entries = append(tracestate.Entries,42 &octrace.Span_Tracestate_Entry{43 Key: "123",44 Value: "4567",45 })46 assert.EqualValues(t, "abc=def,123=4567", ocTraceStateToInternal(tracestate))47}48func TestInitAttributeMapFromOC(t *testing.T) {49 attrs := pcommon.NewMap()50 initAttributeMapFromOC(nil, attrs)51 assert.EqualValues(t, pcommon.NewMap(), attrs)52 assert.EqualValues(t, 0, ocAttrsToDroppedAttributes(nil))53 ocAttrs := &octrace.Span_Attributes{}54 attrs = pcommon.NewMap()55 initAttributeMapFromOC(ocAttrs, attrs)56 assert.EqualValues(t, pcommon.NewMap(), attrs)57 assert.EqualValues(t, 0, ocAttrsToDroppedAttributes(ocAttrs))58 ocAttrs = &octrace.Span_Attributes{59 DroppedAttributesCount: 123,60 }61 attrs = pcommon.NewMap()62 initAttributeMapFromOC(ocAttrs, attrs)63 assert.EqualValues(t, pcommon.NewMap(), attrs)64 assert.EqualValues(t, 123, ocAttrsToDroppedAttributes(ocAttrs))65 ocAttrs = &octrace.Span_Attributes{66 AttributeMap: map[string]*octrace.AttributeValue{},67 DroppedAttributesCount: 234,68 }69 attrs = pcommon.NewMap()70 initAttributeMapFromOC(ocAttrs, attrs)71 assert.EqualValues(t, pcommon.NewMap(), attrs)72 assert.EqualValues(t, 234, ocAttrsToDroppedAttributes(ocAttrs))73 ocAttrs = &octrace.Span_Attributes{74 AttributeMap: map[string]*octrace.AttributeValue{75 "abc": {76 Value: &octrace.AttributeValue_StringValue{StringValue: &octrace.TruncatableString{Value: "def"}},77 },78 },79 DroppedAttributesCount: 234,80 }81 attrs = pcommon.NewMap()82 initAttributeMapFromOC(ocAttrs, attrs)83 assert.EqualValues(t,84 pcommon.NewMapFromRaw(85 map[string]interface{}{86 "abc": "def",87 }),88 attrs)89 assert.EqualValues(t, 234, ocAttrsToDroppedAttributes(ocAttrs))90 ocAttrs.AttributeMap["intval"] = &octrace.AttributeValue{91 Value: &octrace.AttributeValue_IntValue{IntValue: 345},92 }93 ocAttrs.AttributeMap["boolval"] = &octrace.AttributeValue{94 Value: &octrace.AttributeValue_BoolValue{BoolValue: true},95 }96 ocAttrs.AttributeMap["doubleval"] = &octrace.AttributeValue{97 Value: &octrace.AttributeValue_DoubleValue{DoubleValue: 4.5},98 }99 attrs = pcommon.NewMap()100 initAttributeMapFromOC(ocAttrs, attrs)101 expectedAttr := pcommon.NewMapFromRaw(map[string]interface{}{102 "abc": "def",103 "intval": 345,104 "boolval": true,105 "doubleval": 4.5,106 })107 assert.EqualValues(t, expectedAttr.Sort(), attrs.Sort())108 assert.EqualValues(t, 234, ocAttrsToDroppedAttributes(ocAttrs))109}110func TestOcSpanKindToInternal(t *testing.T) {111 tests := []struct {112 ocAttrs *octrace.Span_Attributes113 ocKind octrace.Span_SpanKind114 otlpKind ptrace.SpanKind115 }{116 {117 ocKind: octrace.Span_CLIENT,118 otlpKind: ptrace.SpanKindClient,119 },120 {121 ocKind: octrace.Span_SERVER,122 otlpKind: ptrace.SpanKindServer,123 },124 {125 ocKind: octrace.Span_SPAN_KIND_UNSPECIFIED,126 otlpKind: ptrace.SpanKindUnspecified,127 },128 {129 ocKind: octrace.Span_SPAN_KIND_UNSPECIFIED,130 ocAttrs: &octrace.Span_Attributes{131 AttributeMap: map[string]*octrace.AttributeValue{132 "span.kind": {Value: &octrace.AttributeValue_StringValue{133 StringValue: &octrace.TruncatableString{Value: "consumer"}}},134 },135 },136 otlpKind: ptrace.SpanKindConsumer,137 },138 {139 ocKind: octrace.Span_SPAN_KIND_UNSPECIFIED,140 ocAttrs: &octrace.Span_Attributes{141 AttributeMap: map[string]*octrace.AttributeValue{142 "span.kind": {Value: &octrace.AttributeValue_StringValue{143 StringValue: &octrace.TruncatableString{Value: "producer"}}},144 },145 },146 otlpKind: ptrace.SpanKindProducer,147 },148 {149 ocKind: octrace.Span_SPAN_KIND_UNSPECIFIED,150 ocAttrs: &octrace.Span_Attributes{151 AttributeMap: map[string]*octrace.AttributeValue{152 "span.kind": {Value: &octrace.AttributeValue_IntValue{153 IntValue: 123}},154 },155 },156 otlpKind: ptrace.SpanKindUnspecified,157 },158 {159 ocKind: octrace.Span_CLIENT,160 ocAttrs: &octrace.Span_Attributes{161 AttributeMap: map[string]*octrace.AttributeValue{162 "span.kind": {Value: &octrace.AttributeValue_StringValue{163 StringValue: &octrace.TruncatableString{Value: "consumer"}}},164 },165 },166 otlpKind: ptrace.SpanKindClient,167 },168 {169 ocKind: octrace.Span_SPAN_KIND_UNSPECIFIED,170 ocAttrs: &octrace.Span_Attributes{171 AttributeMap: map[string]*octrace.AttributeValue{172 "span.kind": {Value: &octrace.AttributeValue_StringValue{173 StringValue: &octrace.TruncatableString{Value: "internal"}}},174 },175 },176 otlpKind: ptrace.SpanKindInternal,177 },178 }179 for _, test := range tests {180 t.Run(test.otlpKind.String(), func(t *testing.T) {181 got := ocSpanKindToInternal(test.ocKind, test.ocAttrs)182 assert.EqualValues(t, test.otlpKind, got, "Expected "+test.otlpKind.String()+", got "+got.String())183 })184 }185}186func TestOcToInternal(t *testing.T) {187 ocNode := &occommon.Node{}188 ocResource1 := &ocresource.Resource{Labels: map[string]string{"resource-attr": "resource-attr-val-1"}}189 ocResource2 := &ocresource.Resource{Labels: map[string]string{"resource-attr": "resource-attr-val-2"}}190 startTime := timestamppb.New(testdata.TestSpanStartTime)191 eventTime := timestamppb.New(testdata.TestSpanEventTime)192 endTime := timestamppb.New(testdata.TestSpanEndTime)193 ocSpan1 := &octrace.Span{194 Name: &octrace.TruncatableString{Value: "operationA"},195 StartTime: startTime,196 EndTime: endTime,197 TimeEvents: &octrace.Span_TimeEvents{198 TimeEvent: []*octrace.Span_TimeEvent{199 {200 Time: eventTime,201 Value: &octrace.Span_TimeEvent_Annotation_{202 Annotation: &octrace.Span_TimeEvent_Annotation{203 Description: &octrace.TruncatableString{Value: "event-with-attr"},204 Attributes: &octrace.Span_Attributes{205 AttributeMap: map[string]*octrace.AttributeValue{206 "span-event-attr": {207 Value: &octrace.AttributeValue_StringValue{208 StringValue: &octrace.TruncatableString{Value: "span-event-attr-val"},209 },210 },211 },212 DroppedAttributesCount: 2,213 },214 },215 },216 },217 {218 Time: eventTime,219 Value: &octrace.Span_TimeEvent_Annotation_{220 Annotation: &octrace.Span_TimeEvent_Annotation{221 Description: &octrace.TruncatableString{Value: "event"},222 Attributes: &octrace.Span_Attributes{223 DroppedAttributesCount: 2,224 },225 },226 },227 },228 },229 DroppedAnnotationsCount: 1,230 },231 Attributes: &octrace.Span_Attributes{232 DroppedAttributesCount: 1,233 },234 Status: &octrace.Status{Message: "status-cancelled", Code: 1},235 }236 // TODO: Create another unit test fully covering ocSpanToInternal237 ocSpanZeroedParentID := proto.Clone(ocSpan1).(*octrace.Span)238 ocSpanZeroedParentID.ParentSpanId = []byte{0, 0, 0, 0, 0, 0, 0, 0}239 ocSpan2 := &octrace.Span{240 Name: &octrace.TruncatableString{Value: "operationB"},241 StartTime: startTime,242 EndTime: endTime,243 Links: &octrace.Span_Links{244 Link: []*octrace.Span_Link{245 {246 Attributes: &octrace.Span_Attributes{247 AttributeMap: map[string]*octrace.AttributeValue{248 "span-link-attr": {249 Value: &octrace.AttributeValue_StringValue{250 StringValue: &octrace.TruncatableString{Value: "span-link-attr-val"},251 },252 },253 },254 DroppedAttributesCount: 4,255 },256 },257 {258 Attributes: &octrace.Span_Attributes{259 DroppedAttributesCount: 4,260 },261 },262 },263 DroppedLinksCount: 3,264 },265 }266 ocSpan3 := &octrace.Span{267 Name: &octrace.TruncatableString{Value: "operationC"},268 StartTime: startTime,269 EndTime: endTime,270 Resource: ocResource2,271 Attributes: &octrace.Span_Attributes{272 AttributeMap: map[string]*octrace.AttributeValue{273 "span-attr": {274 Value: &octrace.AttributeValue_StringValue{275 StringValue: &octrace.TruncatableString{Value: "span-attr-val"},276 },277 },278 },279 DroppedAttributesCount: 5,280 },281 }282 tests := []struct {283 name string284 td ptrace.Traces285 node *occommon.Node286 resource *ocresource.Resource287 spans []*octrace.Span288 }{289 {290 name: "empty",291 td: ptrace.NewTraces(),292 },293 {294 name: "one-empty-resource-spans",295 td: testdata.GenerateTracesOneEmptyResourceSpans(),296 node: ocNode,297 },298 {299 name: "no-libraries",300 td: testdata.GenerateTracesNoLibraries(),301 resource: ocResource1,302 },303 {304 name: "one-span-no-resource",305 td: testdata.GenerateTracesOneSpanNoResource(),306 node: ocNode,307 resource: &ocresource.Resource{},308 spans: []*octrace.Span{ocSpan1},309 },310 {311 name: "one-span",312 td: testdata.GenerateTracesOneSpan(),313 node: ocNode,314 resource: ocResource1,315 spans: []*octrace.Span{ocSpan1},316 },317 {318 name: "one-span-zeroed-parent-id",319 td: testdata.GenerateTracesOneSpan(),320 node: ocNode,321 resource: ocResource1,322 spans: []*octrace.Span{ocSpanZeroedParentID},323 },324 {325 name: "one-span-one-nil",326 td: testdata.GenerateTracesOneSpan(),327 node: ocNode,328 resource: ocResource1,329 spans: []*octrace.Span{ocSpan1, nil},330 },331 {332 name: "two-spans-same-resource",333 td: testdata.GenerateTracesTwoSpansSameResource(),334 node: ocNode,335 resource: ocResource1,336 spans: []*octrace.Span{ocSpan1, nil, ocSpan2},337 },338 {339 name: "two-spans-same-resource-one-different",340 td: testdata.GenerateTracesTwoSpansSameResourceOneDifferent(),341 node: ocNode,342 resource: ocResource1,343 spans: []*octrace.Span{ocSpan1, ocSpan2, ocSpan3},344 },345 {346 name: "two-spans-and-separate-in-the-middle",347 td: testdata.GenerateTracesTwoSpansSameResourceOneDifferent(),348 node: ocNode,349 resource: ocResource1,350 spans: []*octrace.Span{ocSpan1, ocSpan3, ocSpan2},351 },352 }353 for _, test := range tests {354 t.Run(test.name, func(t *testing.T) {355 assert.EqualValues(t, test.td, OCToTraces(test.node, test.resource, test.spans))356 })357 }358}359func TestOcSameProcessAsParentSpanToInternal(t *testing.T) {360 span := ptrace.NewSpan()361 ocSameProcessAsParentSpanToInternal(nil, span)362 assert.Equal(t, 0, span.Attributes().Len())363 ocSameProcessAsParentSpanToInternal(wrapperspb.Bool(false), span)364 assert.Equal(t, 1, span.Attributes().Len())365 v, ok := span.Attributes().Get(occonventions.AttributeSameProcessAsParentSpan)366 assert.True(t, ok)367 assert.EqualValues(t, pcommon.ValueTypeBool, v.Type())368 assert.False(t, v.BoolVal())369 ocSameProcessAsParentSpanToInternal(wrapperspb.Bool(true), span)370 assert.Equal(t, 1, span.Attributes().Len())371 v, ok = span.Attributes().Get(occonventions.AttributeSameProcessAsParentSpan)372 assert.True(t, ok)373 assert.EqualValues(t, pcommon.ValueTypeBool, v.Type())374 assert.True(t, v.BoolVal())375}376func BenchmarkSpansWithAttributesOCToInternal(b *testing.B) {377 resource := generateOCTestResource()378 spans := []*octrace.Span{generateSpanWithAttributes(15)}379 b.ResetTimer()380 for n := 0; n < b.N; n++ {381 OCToTraces(nil, resource, spans)382 }383}384func BenchmarkSpansWithAttributesUnmarshal(b *testing.B) {385 ocSpan := generateSpanWithAttributes(15)386 bytes, err := proto.Marshal(ocSpan)387 if err != nil {388 b.Fail()389 }390 b.ResetTimer()391 for n := 0; n < b.N; n++ {392 unmarshalOc := &octrace.Span{}393 if err := proto.Unmarshal(bytes, unmarshalOc); err != nil {394 b.Fail()395 }396 if len(unmarshalOc.Attributes.AttributeMap) != 15 {397 b.Fail()398 }399 }400}401func generateSpanWithAttributes(len int) *octrace.Span {402 startTime := timestamppb.New(testdata.TestSpanStartTime)403 endTime := timestamppb.New(testdata.TestSpanEndTime)404 ocSpan2 := &octrace.Span{405 Name: &octrace.TruncatableString{Value: "operationB"},406 StartTime: startTime,407 EndTime: endTime,408 Attributes: &octrace.Span_Attributes{409 DroppedAttributesCount: 3,410 },411 }412 ocSpan2.Attributes.AttributeMap = make(map[string]*octrace.AttributeValue, len)413 ocAttr := ocSpan2.Attributes.AttributeMap414 for i := 0; i < len; i++ {415 ocAttr["span-link-attr_"+strconv.Itoa(i)] = &octrace.AttributeValue{416 Value: &octrace.AttributeValue_StringValue{417 StringValue: &octrace.TruncatableString{Value: "span-link-attr-val"},418 },419 }420 }421 return ocSpan2422}...
bench.go
Source:bench.go
1package bench2import (3 "context"4 "fmt"5 "math/rand"6 "time"7 "github.com/pilosa/go-pilosa"8)9// Benchmark is an interface run benchmark components. Benchmarks should Marshal10// to valid JSON so that their configuration may be recorded with their results.11type Benchmark interface {12 Run(ctx context.Context, client *pilosa.Client, agentNum int) (*Result, error)13}14type HostSetup struct {15 Hosts []string16 ClientOptions []pilosa.ClientOption17}18// Results holds the output from the run of a benchmark - the Benchmark's Run()19// method may set Stats, Responses, and Extra, and the RunBenchmark helper20// function will set the Duration, AgentNum, PilosaVersion, and Configuration.21// Either may set Error if there is an error. The structure of Result assumes22// that most benchmarks will run multiple queries and track statistics about how23// long each one takes. The Extra field is for benchmarks which either do not24// fit this model, or want to return additional information not covered by Stats25// and Responses.26type Result struct {27 Stats *Stats `json:"stats"`28 Responses []*pilosa.QueryResponse `json:"responses"`29 Extra map[string]interface{} `json:"extra"`30 AgentNum int `json:"agentnum"`31 PilosaVersion string `json:"pilosa-version"`32 Configuration interface{} `json:"configuration"`33 // Error exists so that errors can be correctly marshalled to JSON. It is set using Result.err.Error()34 Error string `json:"error,omitempty"`35}36// NewResult intializes and returns a Result.37func NewResult() *Result {38 return &Result{39 Stats: NewStats(),40 Extra: make(map[string]interface{}),41 Responses: make([]*pilosa.QueryResponse, 0),42 }43}44// Add adds the duration to the Result's Stats object. If resp is non-nil, it45// also adds it to the slice of responses.46func (r *Result) Add(d time.Duration, resp *pilosa.QueryResponse) {47 r.Stats.Add(d)48 if resp != nil {49 r.Responses = append(r.Responses, resp)50 }51}52// ensureSchema ensures that a given index and field exist.53func ensureSchema(client *pilosa.Client, indexName, fieldName string, opts ...interface{}) (index *pilosa.Index, field *pilosa.Field, err error) {54 var indexOpts []pilosa.IndexOption55 var fieldOpts []pilosa.FieldOption56 for _, opt := range opts {57 switch opt := opt.(type) {58 case pilosa.IndexOption:59 indexOpts = append(indexOpts, opt)60 case pilosa.FieldOption:61 fieldOpts = append(fieldOpts, opt)62 }63 }64 schema, err := client.Schema()65 if err != nil {66 return nil, nil, fmt.Errorf("cannot read schema: %v", err)67 }68 index = schema.Index(indexName, indexOpts...)69 if err := client.EnsureIndex(index); err != nil {70 return nil, nil, fmt.Errorf("cannot ensure index: %v", err)71 }72 if fieldName != "" {73 field = index.Field(fieldName, fieldOpts...)74 if err := client.EnsureField(field); err != nil {75 return nil, nil, fmt.Errorf("cannot ensure field: %v", err)76 }77 }78 if err := client.SyncSchema(schema); err != nil {79 return nil, nil, fmt.Errorf("cannot sync schema: %v", err)80 }81 return index, field, nil82}83// wrapper type to force human-readable JSON output84type PrettyDuration time.Duration85// MarshalJSON returns a nicely formatted duration, instead of it just being86// treated like an int.87func (d PrettyDuration) MarshalJSON() ([]byte, error) {88 s := time.Duration(d).String()89 return []byte("\"" + s + "\""), nil90}91// Recursively replaces elements of ugly types with their pretty wrappers92func Prettify(m map[string]interface{}) map[string]interface{} {93 newmap := make(map[string]interface{})94 for k, v := range m {95 switch v.(type) {96 case map[string]interface{}:97 newmap[k] = Prettify(v.(map[string]interface{}))98 case []time.Duration:99 newslice := make([]PrettyDuration, len(v.([]time.Duration)))100 slice := v.([]time.Duration)101 for n, e := range slice {102 newslice[n] = PrettyDuration(e)103 }104 newmap[k] = newslice105 case time.Duration:106 newmap[k] = PrettyDuration(v.(time.Duration))107 default:108 if interv, ok := v.([]map[string]interface{}); ok {109 for i, iv := range interv {110 interv[i] = Prettify(iv)111 }112 }113 newmap[k] = v114 }115 }116 return newmap117}118// NewQueryGenerator returns a new QueryGenerator.119func NewQueryGenerator(index *pilosa.Index, field *pilosa.Field, seed int64) *QueryGenerator {120 return &QueryGenerator{121 index: index,122 field: field,123 rand: rand.New(rand.NewSource(seed)),124 }125}126// QueryGenerator holds the configuration and state for randomly generating queries.127type QueryGenerator struct {128 index *pilosa.Index129 field *pilosa.Field130 rand *rand.Rand131}132// Random returns a randomly generated query.133func (g *QueryGenerator) Random(maxN, depth, maxargs int, idmin, idmax uint64) pilosa.PQLQuery {134 val := g.rand.Intn(5)135 switch val {136 case 0:137 return g.RandomTopN(maxN, depth, maxargs, idmin, idmax)138 default:139 return g.RandomBitmapCall(depth, maxargs, idmin, idmax)140 }141}142// RandomRangeQuery returns a randomly generated sum or range query.143func (g *QueryGenerator) RandomRangeQuery(depth, maxargs int, idmin, idmax uint64) pilosa.PQLQuery {144 switch g.rand.Intn(5) {145 case 1:146 return g.RandomSum(depth, maxargs, idmin, idmax)147 default:148 return g.RandomRange(maxargs, idmin, idmax)149 }150}151func (g *QueryGenerator) RandomRange(numArg int, idmin, idmax uint64) *pilosa.PQLRowQuery {152 choose := g.rand.Intn(4)153 if choose == 0 {154 return g.RangeCall(idmin, idmax)155 }156 a := make([]*pilosa.PQLRowQuery, numArg)157 for i := 0; i < numArg; i++ {158 a[i] = g.RangeCall(idmin, idmax)159 }160 switch choose {161 case 1:162 return g.index.Difference(a...)163 case 2:164 return g.index.Intersect(a...)165 case 3:166 return g.index.Union(a...)167 default:168 panic("unreachable")169 }170}171func (g *QueryGenerator) RangeCall(idmin, idmax uint64) *pilosa.PQLRowQuery {172 const operationN = 5173 switch g.rand.Intn(operationN) {174 case 0:175 return g.field.GT(g.rand.Intn(int(idmax - idmin)))176 case 1:177 return g.field.LT(g.rand.Intn(int(idmax - idmin)))178 case 2:179 return g.field.GTE(g.rand.Intn(int(idmax - idmin)))180 case 3:181 return g.field.LTE(g.rand.Intn(int(idmax - idmin)))182 case 4:183 return g.field.Equals(g.rand.Intn(int(idmax - idmin)))184 default:185 panic("unreachable")186 }187}188// RandomSum returns a randomly generated sum query.189func (g *QueryGenerator) RandomSum(depth, maxargs int, idmin, idmax uint64) pilosa.PQLQuery {190 switch g.rand.Intn(4) {191 case 0:192 return g.field.Sum(g.RandomBitmapCall(depth, maxargs, idmin, idmax))193 default:194 return g.field.Sum(g.RandomRange(maxargs, idmin, idmax))195 }196}197// RandomTopN returns a randomly generated TopN query.198func (g *QueryGenerator) RandomTopN(maxN, depth, maxargs int, idmin, idmax uint64) *pilosa.PQLRowQuery {199 return g.field.RowTopN(uint64(g.rand.Intn(maxN-1)+1), g.RandomBitmapCall(depth, maxargs, idmin, idmax))200}201// RandomBitmapCall returns a randomly generate query which returns a bitmap.202func (g *QueryGenerator) RandomBitmapCall(depth, maxargs int, idmin, idmax uint64) *pilosa.PQLRowQuery {203 if depth <= 1 {204 return g.field.Row(uint64(g.rand.Int63n(int64(idmax)-int64(idmin)) + int64(idmin)))205 }206 choose := g.rand.Intn(4)207 if choose == 0 {208 return g.RandomBitmapCall(1, 0, idmin, idmax)209 }210 numargs := 2211 if maxargs > 2 {212 numargs = g.rand.Intn(maxargs-2) + 2213 }214 a := make([]*pilosa.PQLRowQuery, numargs)215 for i := 0; i < numargs; i++ {216 a[i] = g.RandomBitmapCall(depth-1, maxargs, idmin, idmax)217 }218 switch choose {219 case 1:220 return g.index.Difference(a...)221 case 2:222 return g.index.Intersect(a...)223 case 3:224 return g.index.Union(a...)225 default:226 panic("unreachable")227 }228}229// Stats object helps track timing stats.230type Stats struct {231 sumSquareDelta float64232 Min time.Duration `json:"min"`233 Max time.Duration `json:"max"`234 Mean time.Duration `json:"mean"`235 Total time.Duration `json:"total-time"`236 Num int64 `json:"num"`237 All []time.Duration `json:"all"`238 SaveAll bool `json:"-"`239}240// NewStats gets a Stats object.241func NewStats() *Stats {242 return &Stats{243 Min: 1<<63 - 1,244 All: make([]time.Duration, 0),245 }246}247// Add adds a new time to the stats object.248func (s *Stats) Add(td time.Duration) {249 if s.SaveAll {250 s.All = append(s.All, td)251 }252 s.Num += 1253 s.Total += td254 if td < s.Min {255 s.Min = td256 }257 if td > s.Max {258 s.Max = td259 }260 // online variance calculation261 // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm262 delta := td - s.Mean263 s.Mean += delta / time.Duration(s.Num)264 s.sumSquareDelta += float64(delta * (td - s.Mean))265}266func (s *Stats) Combine(other *Stats) {267 if other.Min < s.Min {268 s.Min = other.Min269 }270 if other.Max > s.Max {271 s.Max = other.Max272 }273 s.Total += other.Total274 s.Num += other.Num275 s.Mean = s.Total / time.Duration(s.Num)276 s.All = append(s.All, other.All...)277}278// NumStats object helps track stats. This and Stats (which was279// originally made specifically for time) should probably be unified.280type NumStats struct {281 sumSquareDelta float64282 // NumZero counts the number of values that have been added which283 // are zero. This is a cheap, simple, replacement for more284 // sophisticated tracking of the distribution of the data that285 // let's us know if (e.g.) we have a bunch of queries doing286 // nothing because we're querying empty rows or something.287 NumZero int64 `json:"num-zero"`288 Min int64 `json:"min"`289 Max int64 `json:"max"`290 Mean int64 `json:"mean"`291 Total int64 `json:"total"`292 Num int64 `json:"num"`293 All []int64 `json:"all"`294 SaveAll bool `json:"-"`295}296// NewNumStats gets a NumStats object.297func NewNumStats() *NumStats {298 return &NumStats{299 Min: 1<<63 - 1,300 All: make([]int64, 0),301 }302}303// Add adds a new value to the stats object.304func (s *NumStats) Add(td int64) {305 if s.SaveAll {306 s.All = append(s.All, td)307 }308 if td == 0 {309 s.NumZero++310 }311 s.Num += 1312 s.Total += td313 if td < s.Min {314 s.Min = td315 }316 if td > s.Max {317 s.Max = td318 }319 // online variance calculation320 // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm321 delta := td - s.Mean322 s.Mean += delta / int64(s.Num)323 s.sumSquareDelta += float64(delta * (td - s.Mean))324}325func (s *NumStats) Combine(other *NumStats) {326 if other.Min < s.Min {327 s.Min = other.Min328 }329 if other.Max > s.Max {330 s.Max = other.Max331 }332 s.NumZero += other.NumZero333 s.Total += other.Total334 s.Num += other.Num335 s.Mean = s.Total / s.Num336 s.All = append(s.All, other.All...)337}...
compare.go
Source:compare.go
...56 c.Flags().Float64Var(&errorAt, "error", 0, "error when values change more or less than this percentage amount and exit 1")57 opts = addMetricFlags(c)58 return c59}60func stdoutPrint(keys []familyKey, oldMap, newMap metricMap, deltas oldNewDeltaMap) {61 // Show comparisons62 for _, k := range keys {63 delta := deltas[k]64 if oldMap[k].value != 0 {65 prefixParts := make([]string, 0)66 if delta.isWarn || delta.isError {67 prefixParts = append(prefixParts, "1")68 }69 if delta.isError {70 prefixParts = append(prefixParts, "31", "4")71 }72 decorationPrefix := ""73 if len(prefixParts) > 0 {74 decorationPrefix = "\033[" + strings.Join(prefixParts, ";") + "m"75 }76 decorationSuffix := ""77 if decorationPrefix != "" {78 decorationSuffix = "\033[0m"79 }80 fmt.Printf("%s%s %s (old: %s, new %s): change: %0.4f%%%s\n",81 decorationPrefix, k.metric, k.labels, oldMap[k].String(), newMap[k].String(), delta.percentChange, decorationSuffix)82 } else {83 fmt.Printf("%s %s (old: %s, new %s)\n", k.metric, k.labels, oldMap[k].String(), newMap[k].String())84 }85 }86}87func csvPrint(keys []familyKey, oldMap, newMap metricMap, deltas oldNewDeltaMap) {88 for _, k := range keys {89 newMetric := newMap[k]90 oldMetric := oldMap[k]91 delta := deltas[k]92 if oldMetric.value != 0 {93 fmt.Printf("%s,%s,%g,%g,%g\n", k.metric, k.labels, oldMetric.value, newMetric.value, delta.percentChange)94 //fmt.Printf("%s %s (old: %s, new %s): change: %0.4f%%\n", k.metric, k.labels, oldMap[k].String(), newMap[k].String(), percentChange)95 } else {96 fmt.Printf("%s,%s,%g,%g,N/A\n", k.metric, k.labels, oldMetric.value, newMetric.value)97 }98 }99}100func htmlTablePrint(keys []familyKey, oldMap, newMap metricMap, deltas oldNewDeltaMap) {101 fmt.Printf("<table>\n")102 fmt.Printf("<thead><th>Metric</th><th>Labels</th><th>Baseline Value</th><th>New Value</th><th>Delta</th></thead>\n")103 fmt.Printf("<tbody>\n")104 for _, k := range keys {105 delta := deltas[k]106 rowBackground := "#fff"107 cells := make([]string, 0)108 cells = append(cells, k.metric, k.labels, oldMap[k].String(), newMap[k].String())109 if oldMap[k].value != 0 {110 if delta.isWarn {111 rowBackground = "yellow"112 }113 if delta.isError {114 rowBackground = "orange"115 }116 cells = append(cells, fmt.Sprintf("%0.4f%%", delta.percentChange))117 } else {118 cells = append(cells, "n/a")119 }120 fmt.Printf("<tr style=\"background: %s;\">\n", rowBackground)121 for _, cell := range cells {122 fmt.Printf("<td>%s</td>", cell)123 }124 fmt.Printf("\n</tr>\n")125 }126 fmt.Printf("</tbody>\n</table>\n")127}128type oldNewDelta struct {129 percentChange float64130 isWarn bool131 isError bool132}133type oldNewDeltaMap map[familyKey]oldNewDelta134func getDeltas(keys []familyKey, oldMap, newMap metricMap, thresholds changeThresholds) oldNewDeltaMap {135 deltas := make(oldNewDeltaMap)136 for _, k := range keys {137 newMetric := newMap[k]138 oldMetric := oldMap[k]139 if oldMetric.value != 0 {140 percentChange := (newMetric.value - oldMetric.value) / oldMetric.value * 100141 deltas[k] = oldNewDelta{142 percentChange: percentChange,143 isError: thresholds.errorAt != 0.0 && math.Abs(percentChange) > thresholds.errorAt,144 isWarn: thresholds.warnAt != 0.0 && math.Abs(percentChange) > thresholds.warnAt,145 }146 } else {147 deltas[k] = oldNewDelta{148 isWarn: false,149 isError: false,150 }151 }152 }153 return deltas154}155func compareMetricMaps(oldMap, newMap metricMap, thresholds changeThresholds, opts *metricOptions) {156 var keys []familyKey157 for k := range oldMap {158 if _, ok := newMap[k]; ok {159 keys = append(keys, k)160 }161 }162 sort.Slice(keys, func(i, j int) bool {163 if keys[i].metric != keys[j].metric {164 return keys[i].metric < keys[j].metric165 }166 return keys[i].labels < keys[j].labels167 })168 var deltas = getDeltas(keys, oldMap, newMap, thresholds)169 switch opts.format {170 case "plain":171 stdoutPrint(keys, oldMap, newMap, deltas)172 case "csv":173 csvPrint(keys, oldMap, newMap, deltas)174 case "html-table":175 htmlTablePrint(keys, oldMap, newMap, deltas)176 default:177 panic("unknown output format")178 }179 for _, v := range deltas {180 if v.isError {181 os.Exit(1)182 }183 }184}...
newMap
Using AI Code Generation
1import (2type td struct {3}4func (t td) newMap() map[string]interface{}{5 return map[string]interface{}{6 }7}8func main() {9 t := td{"test", 23}10 m := t.newMap()11 fmt.Println(m)12}
newMap
Using AI Code Generation
1import (2func main() {3 td := new(td)4 td.newMap()5 fmt.Println(td.m)6}7import (8func main() {9 td := new(td)10 td.newMap()11 fmt.Println(td.m)12}13import (14func main() {15 td := new(td)16 td.newMap()17 fmt.Println(td.m)18}19import (20func main() {21 td := new(td)22 td.newMap()23 fmt.Println(td.m)24}25import (26func main() {27 td := new(td)28 td.newMap()29 fmt.Println(td.m)30}31import (32func main() {33 td := new(td)34 td.newMap()35 fmt.Println(td.m)36}37import (38func main() {39 td := new(td)40 td.newMap()41 fmt.Println(td.m)42}43import (44func main() {45 td := new(td)46 td.newMap()47 fmt.Println(td.m)48}49import (50func main() {51 td := new(td)52 td.newMap()53 fmt.Println(td.m)54}55import (56func main() {57 td := new(td)58 td.newMap()59 fmt.Println(td.m)60}61import (62func main() {63 td := new(td)64 td.newMap()65 fmt.Println(td.m)66}67import (68func main() {69 td := new(td)70 td.newMap()71 fmt.Println(td.m)72}73import (74func main() {75 td := new(td)76 td.newMap()77 fmt.Println(td.m)78}79import (80func main() {81 td := new(td)82 td.newMap()83 fmt.Println(td.m)84}85import (86func main() {87 td := new(td)88 td.newMap()89 fmt.Println(td.m)90}91import (92func main() {93 td := new(td)94 td.newMap()95 fmt.Println(td.m)96}97import (98func main() {99 td := new(td)100 td.newMap()101 fmt.Println(td.m)102}103import (104func main() {105 td := new(td)106 td.newMap()
newMap
Using AI Code Generation
1import (2func main() {3 m := newMap()4 fmt.Println(m)5}6import (7func main() {8 m := newMap()9 fmt.Println(m)10}11import (12func main() {13 m := newMap()14 fmt.Println(m)15}16import (17func main() {18 m := newMap()19 fmt.Println(m)20}21import (22func main() {23 m := newMap()24 fmt.Println(m)25}26import (27func main() {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!