Skip to content

Commit

Permalink
Add thread-safe mock sink for testing (#68)
Browse files Browse the repository at this point in the history
A common error in test code is to use a racy Store or Sink implementation and the existing MockSink cannot be used in a thread-safe manner by consumers of this library.  This PR adds a thread-safe Sink implementation that can be used with the existing Store code.

Additionally, the Sink has helper methods to make testing easier.
  • Loading branch information
charlievieth authored Feb 25, 2019
1 parent 2f3ea18 commit 62bb3d8
Show file tree
Hide file tree
Showing 6 changed files with 606 additions and 22 deletions.
58 changes: 57 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ go get github.com/lyft/gostats
## Building & Testing

```sh
make install
make install
make test
```

Expand All @@ -22,3 +22,59 @@ In order to start using `gostats`, import it into your project with:
```go
import "github.com/lyft/gostats"
```


## Mocking

A thread-safe mock sink is provided by the [gostats/mock](https://github.com/lyft/gostats/blob/mock-sink/mock/sink.go) package. The mock sink also provides methods that are useful for testing (as demonstrated below).
```go
package mock_test

import (
"testing"

"github.com/lyft/gostats"
"github.com/lyft/gostats/mock"
)

type Config struct {
Stats stats.Store
}

func TestMockExample(t *testing.T) {
sink := mock.NewSink()
conf := Config{
Stats: stats.NewStore(sink, false),
}
conf.Stats.NewCounter("name").Inc()
conf.Stats.Flush()
sink.AssertCounterEquals(t, "name", 1)
}
```

If you do not need to assert on the contents of the sink the below example can be used to quickly create a thread-safe `stats.Scope`:
```go
package config

import (
"github.com/lyft/gostats"
"github.com/lyft/gostats/mock"
)

type Config struct {
Stats stats.Store
}

func NewConfig() *Config {
return &Config{
Stats: stats.NewDefaultStore(),
}
}

func NewMockConfig() *Config {
sink := mock.NewSink()
return &Config{
Stats: stats.NewStore(sink, false),
}
}
```
Loading

0 comments on commit 62bb3d8

Please sign in to comment.