github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/convert/profile/profile_test.go (about)

     1  package profile
     2  
     3  import (
     4  	"context"
     5  
     6  	. "github.com/onsi/ginkgo/v2"
     7  	. "github.com/onsi/gomega"
     8  
     9  	"github.com/pyroscope-io/pyroscope/pkg/ingestion"
    10  	"github.com/pyroscope-io/pyroscope/pkg/storage"
    11  	"github.com/pyroscope-io/pyroscope/pkg/storage/segment"
    12  )
    13  
    14  type mockIngester struct{ actual []*storage.PutInput }
    15  
    16  func (m *mockIngester) Put(_ context.Context, p *storage.PutInput) error {
    17  	m.actual = append(m.actual, p)
    18  	return nil
    19  }
    20  
    21  type mockExporter struct {
    22  	observe  bool
    23  	observer *mockObserver
    24  }
    25  
    26  func newMockExporter(observe bool) *mockExporter { return &mockExporter{observe: observe} }
    27  
    28  type mockObserver struct {
    29  	keys   []string
    30  	values []int
    31  }
    32  
    33  func (m *mockExporter) Evaluate(*storage.PutInput) (storage.SampleObserver, bool) {
    34  	if !m.observe {
    35  		return nil, false
    36  	}
    37  	m.observer = new(mockObserver)
    38  	return m.observer, true
    39  }
    40  
    41  func (m *mockObserver) Observe(k []byte, v int) {
    42  	m.keys = append(m.keys, string(k))
    43  	m.values = append(m.values, v)
    44  }
    45  
    46  var _ = Describe("metrics exporter", func() {
    47  	var (
    48  		exporter *mockExporter
    49  		ingester *mockIngester
    50  
    51  		md ingestion.Metadata
    52  		p  RawProfile
    53  	)
    54  
    55  	JustBeforeEach(func() {
    56  		ingester = new(mockIngester)
    57  		md = ingestion.Metadata{Key: new(segment.Key)}
    58  		p = RawProfile{
    59  			Format:  ingestion.FormatGroups,
    60  			RawData: []byte("foo;bar 1\nfoo;baz 2\n"),
    61  		}
    62  
    63  		Expect(p.Parse(context.Background(), ingester, exporter, md)).ToNot(HaveOccurred())
    64  	})
    65  
    66  	ItIngestsTree := func() {
    67  		Expect(ingester.actual[0].Val.Samples()).To(Equal(uint64(3)))
    68  	}
    69  
    70  	Context("if evaluation successful", func() {
    71  		BeforeEach(func() {
    72  			exporter = newMockExporter(true)
    73  		})
    74  		It("ingests the tree", ItIngestsTree)
    75  		It("observes stack values", func() {
    76  			Expect(exporter.observer.keys).To(Equal([]string{"foo;bar", "foo;baz"}))
    77  			Expect(exporter.observer.values).To(Equal([]int{1, 2}))
    78  		})
    79  	})
    80  
    81  	Context("if evaluation unsuccessful", func() {
    82  		BeforeEach(func() {
    83  			exporter = newMockExporter(false)
    84  		})
    85  		It("ingests the tree", ItIngestsTree)
    86  		It("does not observe stack values", func() {
    87  			Expect(exporter.observer).To(BeNil())
    88  		})
    89  	})
    90  })