Path: blob/main/component/common/loki/client/fake/client.go
4096 views
package fake12// This code is copied from Promtail. The fake package is used to configure3// fake client that can be used in testing.45import (6"sync"78"github.com/grafana/agent/component/common/loki"9)1011// Client is a fake client used for testing.12type Client struct {13entries loki.LogsReceiver14received []loki.Entry15once sync.Once16mtx sync.Mutex17wg sync.WaitGroup18OnStop func()19}2021func NewClient(stop func()) *Client {22c := &Client{23OnStop: stop,24entries: make(loki.LogsReceiver),25}26c.wg.Add(1)27go func() {28defer c.wg.Done()29for e := range c.entries {30c.mtx.Lock()31c.received = append(c.received, e)32c.mtx.Unlock()33}34}()35return c36}3738// Stop implements client.Client39func (c *Client) Stop() {40c.once.Do(func() { close(c.entries) })41c.wg.Wait()42c.OnStop()43}4445func (c *Client) Chan() chan<- loki.Entry {46return c.entries47}4849// LogsReceiver returns this client as a LogsReceiver, which is useful in testing.50func (c *Client) LogsReceiver() loki.LogsReceiver {51return c.entries52}5354func (c *Client) Received() []loki.Entry {55c.mtx.Lock()56defer c.mtx.Unlock()57cpy := make([]loki.Entry, len(c.received))58copy(cpy, c.received)59return cpy60}6162// StopNow implements client.Client63func (c *Client) StopNow() {64c.Stop()65}6667func (c *Client) Name() string {68return "fake"69}7071// Clear is used to clean up the buffered received entries, so the same client can be re-used between72// test cases.73func (c *Client) Clear() {74c.mtx.Lock()75defer c.mtx.Unlock()76c.received = []loki.Entry{}77}787980