gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/metric/utils_test.go (about)

     1  // Copyright 2022 The gVisor 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 metric
    16  
    17  import (
    18  	"google.golang.org/protobuf/proto"
    19  	"gvisor.dev/gvisor/pkg/eventchannel"
    20  )
    21  
    22  // sliceEmitter implements eventchannel.Emitter by appending all messages to a
    23  // slice.
    24  type sliceEmitter []proto.Message
    25  
    26  // Emit implements eventchannel.Emitter.Emit.
    27  func (s *sliceEmitter) Emit(msg proto.Message) (bool, error) {
    28  	*s = append(*s, msg)
    29  	return false, nil
    30  }
    31  
    32  // Emit implements eventchannel.Emitter.Close.
    33  func (s *sliceEmitter) Close() error {
    34  	return nil
    35  }
    36  
    37  // Reset clears all events in s.
    38  func (s *sliceEmitter) Reset() {
    39  	*s = nil
    40  }
    41  
    42  // emitter is the eventchannel.Emitter used for all tests. Package eventchannel
    43  // doesn't allow removing Emitters, so we must use one global emitter for all
    44  // test cases.
    45  var emitter sliceEmitter
    46  
    47  func init() {
    48  	resetTest()
    49  
    50  	eventchannel.AddEmitter(&emitter)
    51  }
    52  
    53  func resetTest() {
    54  	initialized.Store(false)
    55  	allMetrics = makeMetricSet()
    56  	emitter.Reset()
    57  }