github.com/yankunsam/loki/v2@v2.6.3-0.20220817130409-389df5235c27/pkg/prom1/storage/metric/metric_test.go (about)

     1  // This file was taken from Prometheus (https://github.com/prometheus/prometheus).
     2  // The original license header is included below:
     3  //
     4  // Copyright 2014 The Prometheus Authors
     5  // Licensed under the Apache License, Version 2.0 (the "License");
     6  // you may not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  // http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing, software
    12  // distributed under the License is distributed on an "AS IS" BASIS,
    13  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  // See the License for the specific language governing permissions and
    15  // limitations under the License.
    16  
    17  package metric
    18  
    19  import (
    20  	"testing"
    21  
    22  	"github.com/prometheus/common/model"
    23  )
    24  
    25  func TestMetric(t *testing.T) {
    26  	testMetric := model.Metric{
    27  		"to_delete": "test1",
    28  		"to_change": "test2",
    29  	}
    30  
    31  	scenarios := []struct {
    32  		fn  func(*Metric)
    33  		out model.Metric
    34  	}{
    35  		{
    36  			fn: func(cm *Metric) {
    37  				cm.Del("to_delete")
    38  			},
    39  			out: model.Metric{
    40  				"to_change": "test2",
    41  			},
    42  		},
    43  		{
    44  			fn: func(cm *Metric) {
    45  				cm.Set("to_change", "changed")
    46  			},
    47  			out: model.Metric{
    48  				"to_delete": "test1",
    49  				"to_change": "changed",
    50  			},
    51  		},
    52  	}
    53  
    54  	for i, s := range scenarios {
    55  		orig := testMetric.Clone()
    56  		cm := &Metric{
    57  			Metric: orig,
    58  			Copied: false,
    59  		}
    60  
    61  		s.fn(cm)
    62  
    63  		// Test that the original metric was not modified.
    64  		if !orig.Equal(testMetric) {
    65  			t.Fatalf("%d. original metric changed; expected %v, got %v", i, testMetric, orig)
    66  		}
    67  
    68  		// Test that the new metric has the right changes.
    69  		if !cm.Metric.Equal(s.out) {
    70  			t.Fatalf("%d. copied metric doesn't contain expected changes; expected %v, got %v", i, s.out, cm.Metric)
    71  		}
    72  	}
    73  }