github.com/cockroachdb/pebble@v0.0.0-20231214172447-ab4952c5f87b/replay/sampled_metric_test.go (about)

     1  // Copyright 2023 The LevelDB-Go and Pebble Authors. All rights reserved. Use
     2  // of this source code is governed by a BSD-style license that can be found in
     3  // the LICENSE file.
     4  
     5  package replay
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"strconv"
    11  	"strings"
    12  	"testing"
    13  	"time"
    14  
    15  	"github.com/cockroachdb/datadriven"
    16  	"github.com/stretchr/testify/require"
    17  )
    18  
    19  func TestSampledMetric(t *testing.T) {
    20  	var m SampledMetric
    21  	var buf bytes.Buffer
    22  	datadriven.RunTest(t, "testdata/sampled_metric", func(t *testing.T, td *datadriven.TestData) string {
    23  		switch td.Cmd {
    24  		case "init":
    25  			m = SampledMetric{samples: m.samples[:0]}
    26  			var cumDur time.Duration
    27  			for _, line := range strings.Split(td.Input, "\n") {
    28  				fields := strings.Fields(line)
    29  				v, err := strconv.ParseInt(fields[0], 10, 64)
    30  				require.NoError(t, err)
    31  				dur, err := time.ParseDuration(fields[1])
    32  				require.NoError(t, err)
    33  				cumDur += dur
    34  				m.samples = append(m.samples, sample{
    35  					value: v,
    36  					since: cumDur,
    37  				})
    38  			}
    39  			return ""
    40  		case "values":
    41  			buf.Reset()
    42  			var width int
    43  			td.ScanArgs(t, "width", &width)
    44  			for i, v := range m.Values(width) {
    45  				if i > 0 {
    46  					fmt.Fprint(&buf, " ")
    47  				}
    48  				fmt.Fprintf(&buf, "%.1f", v)
    49  			}
    50  			return buf.String()
    51  		case "plot":
    52  			var width, height int
    53  			var scaleStr string
    54  			td.ScanArgs(t, "width", &width)
    55  			td.ScanArgs(t, "height", &height)
    56  			td.ScanArgs(t, "scale", &scaleStr)
    57  			var scale float64
    58  			_, err := fmt.Sscanf(scaleStr, "%f", &scale)
    59  			require.NoError(t, err)
    60  			return m.Plot(width, height, scale)
    61  		case "plot-increasing-per-sec":
    62  			var width, height int
    63  			var scaleStr string
    64  			td.ScanArgs(t, "width", &width)
    65  			td.ScanArgs(t, "height", &height)
    66  			td.ScanArgs(t, "scale", &scaleStr)
    67  			var scale float64
    68  			_, err := fmt.Sscanf(scaleStr, "%f", &scale)
    69  			require.NoError(t, err)
    70  			return m.PlotIncreasingPerSec(width, height, scale)
    71  		default:
    72  			return fmt.Sprintf("unrecognized command %q", td.Cmd)
    73  		}
    74  	})
    75  }