go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/tsmon/callback_test.go (about)

     1  // Copyright 2016 The LUCI Authors.
     2  //
     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 at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // 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 and
    13  // limitations under the License.
    14  
    15  package tsmon
    16  
    17  import (
    18  	"context"
    19  	"testing"
    20  	"time"
    21  
    22  	"go.chromium.org/luci/common/tsmon/field"
    23  	"go.chromium.org/luci/common/tsmon/types"
    24  
    25  	. "github.com/smartystreets/goconvey/convey"
    26  )
    27  
    28  func TestCallbacks(t *testing.T) {
    29  	t.Parallel()
    30  
    31  	Convey("With a testing State", t, func() {
    32  		c := WithState(context.Background(), NewState())
    33  
    34  		Convey("Register global callback without metrics panics", func() {
    35  			So(func() {
    36  				RegisterGlobalCallbackIn(c, func(context.Context) {})
    37  			}, ShouldPanic)
    38  		})
    39  
    40  		Convey("Callback is run on Flush", func() {
    41  			c, s, m := WithFakes(c)
    42  
    43  			RegisterCallbackIn(c, func(ctx context.Context) {
    44  				s.Cells = append(s.Cells, types.Cell{
    45  					types.MetricInfo{
    46  						Name:      "foo",
    47  						Fields:    []field.Field{},
    48  						ValueType: types.StringType,
    49  					},
    50  					types.MetricMetadata{},
    51  					types.CellData{
    52  						FieldVals: []any{},
    53  						ResetTime: time.Unix(1234, 1000),
    54  						Value:     "bar",
    55  					},
    56  				})
    57  			})
    58  
    59  			So(Flush(c), ShouldBeNil)
    60  
    61  			So(len(m.Cells), ShouldEqual, 1)
    62  			So(len(m.Cells[0]), ShouldEqual, 1)
    63  			So(m.Cells[0][0], ShouldResemble, types.Cell{
    64  				types.MetricInfo{
    65  					Name:      "foo",
    66  					Fields:    []field.Field{},
    67  					ValueType: types.StringType,
    68  				},
    69  				types.MetricMetadata{},
    70  				types.CellData{
    71  					FieldVals: []any{},
    72  					ResetTime: time.Unix(1234, 1000),
    73  					Value:     "bar",
    74  				},
    75  			})
    76  		})
    77  	})
    78  }