ronantakizawa/codereview-bench huggingface dataset:
Repository: uber-go/zap
File: http_handler.go (Go)

Code before:

	switch r.Method {
	case http.MethodGet:
		enc.Encode(payload{Level: lvl.Level()})
	case http.MethodPut:
		requestedLvl, err := lvl.decodePutRequest(r.Header.Get("Content-Type"), r.Body)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			enc.Encode(errorResponse{Error: err.Error()})
			return
		}
		lvl.SetLevel(requestedLvl)
		enc.Encode(payload{Level: lvl.Level()})
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
		enc.Encode(errorResponse{
			Error: "Only GET and PUT are supported.",
		})
	}
}

func (lvl AtomicLevel) decodePutRequest(contentType string, body io.Reader) (zapcore.Level, error) {
	if contentType == "application/x-www-form-urlencoded" {
		return lvl.decodePutURL(body)
	}
	return lvl.decodePutJSON(body)
}

func (lvl AtomicLevel) decodePutURL(body io.Reader) (zapcore.Level, error) {
	pld, err := ioutil.ReadAll(body)
	if err != nil {
		return 0, err
	}
	values, err := url.ParseQuery(string(pld))
	if err != nil {
		return 0, err
	}
	lvlHeader := values.Get("level")
	if lvlHeader == "" {
		return 0, fmt.Errorf("must specify logging level")
	}
	var l zapcore.Level
	if err := l.UnmarshalText([]byte(lvlHeader)); err != nil {
		return 0, err
	}
	return l, nil
}

func (lvl AtomicLevel) decodePutJSON(body io.Reader) (zapcore.Level, error) {
	var pld struct {
		Level *zapcore.Level `json:"level"`

Review comment (suggestion):
Minor: It looks like these methods could be top-level functions since they don't do anything with the AtomicLevel. I'm gonna change that.

Code after:
	}

	enc := json.NewEncoder(w)

	switch r.Method {
	case http.MethodGet:
		enc.Encode(payload{Level: lvl.Level()})
	case http.MethodPut:
		requestedLvl, err := decodePutRequest(r.Header.Get("Content-Type"), r)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			enc.Encode(errorResponse{Error: err.Error()})
			return
		}
		lvl.SetLevel(requestedLvl)
		enc.Encode(payload{Level: lvl.Level()})
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
		enc.Encode(errorResponse{
			Error: "Only GET and PUT are supported.",
		})
	}
}

// Decodes incoming PUT requests and returns the requested logging level.
func decodePutRequest(contentType string, r *http.Request) (zapcore.Level, error) {
	if contentType == "application/x-www-form-urlencoded" {
		return decodePutURL(r)
	}
	return decodePutJSON(r.Body)
}

func decodePutURL(r *http.Request) (zapcore.Level, error) {
	lvl := r.FormValue("level")
	if lvl == "" {
		return 0, fmt.Errorf("must specify logging level")
	}
	var l zapcore.Level
	if err := l.UnmarshalText([]byte(lvl)); err != nil {
		return 0, err
	}
	return l, nil
}

func decodePutJSON(body io.Reader) (zapcore.Level, error) {
	var pld struct {
		Level *zapcore.Level `json:"level"`
	}
	if err := json.NewDecoder(body).Decode(&pld); err != nil {
		return 0, fmt.Errorf("malformed request body: %v", err)
	}
Repository: uber-go/zap
File: example_test.go (Go)

Code before:
	).Info("tracked some metrics")
	// Output:
	// {"level":"info","msg":"tracked some metrics","metrics":{"counter":1}}
}

type request struct {
	URL string
	IP  string
}

func (r request) MarshalLogObject(enc zapcore.ObjectEncoder) error {
	enc.AddString("url", r.URL)
	enc.AddString("ip", r.IP)
	return nil
}

func ExampleObject() {
	logger := zap.NewExample()
	defer logger.Sync()

	req := &request{"/test", "127.0.0.1"}
	logger.Info("new request, in nested object", zap.Object("req", req))
	logger.Info("new request, inline", zap.InlineObject(req))
	// Output:
	// {"level":"info","msg":"new request, in nested object","req":{"url":"/test","ip":"127.0.0.1"}}
	// {"level":"info","msg":"new request, inline","url":"/test","ip":"127.0.0.1"}
}

func ExampleNewStdLog() {
	logger := zap.NewExample()
	defer logger.Sync()

	std := zap.NewStdLog(logger)
	std.Print("standard logger wrapper")
	// Output:
	// {"level":"info","msg":"standard logger wrapper"}
}

func ExampleRedirectStdLog() {
	logger := zap.NewExample()
	defer logger.Sync()

	undo := zap.RedirectStdLog(logger)
	defer undo()

	log.Print("redirected standard library")
	// Output:
	// {"level":"info","msg":"redirected standard library"}
}

func ExampleReplaceGlobals() {

Review comment (suggestion):
I think we need a test somewhere to also verify how this behaves when used inside an object. Like,

```
func (foo) MarshalLogObject(enc zapcore.ObjectEncoder) error {
  InlineObject(...).AddTo(enc)
}
```

Code after:
	).Info("tracked some metrics")
	// Output:
	// {"level":"info","msg":"tracked some metrics","metrics":{"counter":1}}
}

type addr struct {
	IP   string
	Port int
}

type request struct {
	URL    string
	Listen addr
	Remote addr
}

func (a addr) MarshalLogObject(enc zapcore.ObjectEncoder) error {
	enc.AddString("ip", a.IP)
	enc.AddInt("port", a.Port)
	return nil
}

func (r request) MarshalLogObject(enc zapcore.ObjectEncoder) error {
	enc.AddString("url", r.URL)
	zap.Inline(r.Listen).AddTo(enc)
	return enc.AddObject("remote", r.Remote)
}

func ExampleObject() {
	logger := zap.NewExample()
	defer logger.Sync()

	req := &request{
		URL:    "/test",
		Listen: addr{"127.0.0.1", 8080},
		Remote: addr{"127.0.0.1", 31200},
	}
	logger.Info("new request, in nested object", zap.Object("req", req))
	logger.Info("new request, inline", zap.Inline(req))
	// Output:
	// {"level":"info","msg":"new request, in nested object","req":{"url":"/test","ip":"127.0.0.1","port":8080,"remote":{"ip":"127.0.0.1","port":31200}}}
	// {"level":"info","msg":"new request, inline","url":"/test","ip":"127.0.0.1","port":8080,"remote":{"ip":"127.0.0.1","port":31200}}
}

func ExampleNewStdLog() {
	logger := zap.NewExample()
	defer logger.Sync()

	std := zap.NewStdLog(logger)
	std.Print("standard logger wrapper")
	// Output:
Repository: uber-go/zap
File: zaptest/observer/observer.go (Go)

Code before:
func (o *ObservedLogs) FilterField(field zapcore.Field) *ObservedLogs {
	return o.Filter(func(e LoggedEntry) bool {
		for _, ctxField := range e.Context {
			if ctxField.Equals(field) {
				return true
			}
		}
		return false
	})
}

// FilterFieldKey filters entries to those that have the specified key.
func (o *ObservedLogs) FilterFieldKey(key string) *ObservedLogs {
	return o.Filter(func(e LoggedEntry) bool {
		for _, ctxField := range e.Context {
			if ctxField.Key == key {
				return true
			}
		}
		return false
	})
}

// Filter filters entries to those for which the provided function returns
// true.
func (o *ObservedLogs) Filter(match func(LoggedEntry) bool) *ObservedLogs {
	o.mu.RLock()
	defer o.mu.RUnlock()

	var filtered []LoggedEntry
	for _, entry := range o.logs {
		if match(entry) {
			filtered = append(filtered, entry)
		}
	}
	return &ObservedLogs{logs: filtered}
}

func (o *ObservedLogs) add(log LoggedEntry) {
	o.mu.Lock()
	o.logs = append(o.logs, log)
	o.mu.Unlock()
}

// New creates a new Core that buffers logs in memory (without any encoding).
// It's particularly useful in tests.
func New(enab zapcore.LevelEnabler) (zapcore.Core, *ObservedLogs) {
	ol := &ObservedLogs{}
	return &contextObserver{
		LevelEnabler: enab,
		logs:         ol,

Review comment (suggestion):
minor: consider renaming `match` to `keep` to make it clear that entries that this function returns true for will be kept in the returned ObservedLogs.

Code after:
func (o *ObservedLogs) FilterField(field zapcore.Field) *ObservedLogs {
	return o.Filter(func(e LoggedEntry) bool {
		for _, ctxField := range e.Context {
			if ctxField.Equals(field) {
				return true
			}
		}
		return false
	})
}

// FilterFieldKey filters entries to those that have the specified key.
func (o *ObservedLogs) FilterFieldKey(key string) *ObservedLogs {
	return o.Filter(func(e LoggedEntry) bool {
		for _, ctxField := range e.Context {
			if ctxField.Key == key {
				return true
			}
		}
		return false
	})
}

// Filter returns a copy of this ObservedLogs containing only those entries
// for which the provided function returns true.
func (o *ObservedLogs) Filter(keep func(LoggedEntry) bool) *ObservedLogs {
	o.mu.RLock()
	defer o.mu.RUnlock()

	var filtered []LoggedEntry
	for _, entry := range o.logs {
		if keep(entry) {
			filtered = append(filtered, entry)
		}
	}
	return &ObservedLogs{logs: filtered}
}

func (o *ObservedLogs) add(log LoggedEntry) {
	o.mu.Lock()
	o.logs = append(o.logs, log)
	o.mu.Unlock()
}

// New creates a new Core that buffers logs in memory (without any encoding).
// It's particularly useful in tests.
func New(enab zapcore.LevelEnabler) (zapcore.Core, *ObservedLogs) {
	ol := &ObservedLogs{}
	return &contextObserver{
		LevelEnabler: enab,
		logs:         ol,
Repository: uber-go/zap
File: zaptest/observer/observer.go (Go)

Code before:
// FilterField filters entries to those that have the specified field.
func (o *ObservedLogs) FilterField(field zapcore.Field) *ObservedLogs {
	return o.Filter(func(e LoggedEntry) bool {
		for _, ctxField := range e.Context {
			if ctxField.Equals(field) {
				return true
			}
		}
		return false
	})
}

// FilterFieldKey filters entries to those that have the specified key.
func (o *ObservedLogs) FilterFieldKey(key string) *ObservedLogs {
	return o.Filter(func(e LoggedEntry) bool {
		for _, ctxField := range e.Context {
			if ctxField.Key == key {
				return true
			}
		}
		return false
	})
}

// Filter filters entries to those for which the provided function returns
// true.
func (o *ObservedLogs) Filter(match func(LoggedEntry) bool) *ObservedLogs {
	o.mu.RLock()
	defer o.mu.RUnlock()

	var filtered []LoggedEntry
	for _, entry := range o.logs {
		if match(entry) {
			filtered = append(filtered, entry)
		}
	}
	return &ObservedLogs{logs: filtered}
}

func (o *ObservedLogs) add(log LoggedEntry) {
	o.mu.Lock()
	o.logs = append(o.logs, log)
	o.mu.Unlock()
}

// New creates a new Core that buffers logs in memory (without any encoding).
// It's particularly useful in tests.
func New(enab zapcore.LevelEnabler) (zapcore.Core, *ObservedLogs) {
	ol := &ObservedLogs{}
	return &contextObserver{
		LevelEnabler: enab,

Review comment (suggestion):
Probably worth clarifying that this returns a new ObservedLogs.

How about,

```suggestion
// Filter returns a copy of this ObservedLogs containing only those entries
// for which the provided function returns true.
```

Code after:
// FilterField filters entries to those that have the specified field.
func (o *ObservedLogs) FilterField(field zapcore.Field) *ObservedLogs {
	return o.Filter(func(e LoggedEntry) bool {
		for _, ctxField := range e.Context {
			if ctxField.Equals(field) {
				return true
			}
		}
		return false
	})
}

// FilterFieldKey filters entries to those that have the specified key.
func (o *ObservedLogs) FilterFieldKey(key string) *ObservedLogs {
	return o.Filter(func(e LoggedEntry) bool {
		for _, ctxField := range e.Context {
			if ctxField.Key == key {
				return true
			}
		}
		return false
	})
}

// Filter returns a copy of this ObservedLogs containing only those entries
// for which the provided function returns true.
func (o *ObservedLogs) Filter(keep func(LoggedEntry) bool) *ObservedLogs {
	o.mu.RLock()
	defer o.mu.RUnlock()

	var filtered []LoggedEntry
	for _, entry := range o.logs {
		if keep(entry) {
			filtered = append(filtered, entry)
		}
	}
	return &ObservedLogs{logs: filtered}
}

func (o *ObservedLogs) add(log LoggedEntry) {
	o.mu.Lock()
	o.logs = append(o.logs, log)
	o.mu.Unlock()
}

// New creates a new Core that buffers logs in memory (without any encoding).
// It's particularly useful in tests.
func New(enab zapcore.LevelEnabler) (zapcore.Core, *ObservedLogs) {
	ol := &ObservedLogs{}
	return &contextObserver{
		LevelEnabler: enab,
Repository: uber-go/zap
File: zaptest/observer/observer_test.go (Go)

Code before:
			filtered: sink.FilterMessageSnippet("a").FilterField(zap.Int("b", 2)),
			want:     logs[1:2],
		},
		{
			msg:      "filter for map",
			filtered: sink.FilterField(zap.Any("map", map[string]string{"a": "b"})),
			want:     logs[5:6],
		},
		{
			msg:      "filter for slice",
			filtered: sink.FilterField(zap.Any("slice", []string{"a"})),
			want:     logs[6:7],
		},
		{
			msg:      "filter field key",
			filtered: sink.FilterFieldKey("filterMe"),
			want:     logs[7:9],
		},
		{
			msg: "filter by arbitrary function",
			filtered: sink.Filter(func(e LoggedEntry) bool {
				return len(e.Context) > 1
			}),
			want: func() []LoggedEntry {
				// Do not modify logs slice.
				w := []LoggedEntry{}
				w = append(w, logs[0:5]...)
				w = append(w, logs[7])
				return w
			}(),
		},
		{
			msg:      "filter level",
			filtered: sink.FilterLevelExact(zap.WarnLevel),
			want:     logs[9:10],
		},
	}

	for _, tt := range tests {
		got := tt.filtered.AllUntimed()
		assert.Equal(t, tt.want, got, tt.msg)
	}
}


Review comment (suggestion):
nit: can use nil slice or a pre-allocated slice here:
```suggestion
				w := make([]LoggedEntry, 0, len(logs))
```

Or,

```suggestion
				var w []LoggedEntry
```

Code after:
			filtered: sink.FilterMessageSnippet("a").FilterField(zap.Int("b", 2)),
			want:     logs[1:2],
		},
		{
			msg:      "filter for map",
			filtered: sink.FilterField(zap.Any("map", map[string]string{"a": "b"})),
			want:     logs[5:6],
		},
		{
			msg:      "filter for slice",
			filtered: sink.FilterField(zap.Any("slice", []string{"a"})),
			want:     logs[6:7],
		},
		{
			msg:      "filter field key",
			filtered: sink.FilterFieldKey("filterMe"),
			want:     logs[7:9],
		},
		{
			msg: "filter by arbitrary function",
			filtered: sink.Filter(func(e LoggedEntry) bool {
				return len(e.Context) > 1
			}),
			want: func() []LoggedEntry {
				// Do not modify logs slice.
				w := make([]LoggedEntry, 0, len(logs))
				w = append(w, logs[0:5]...)
				w = append(w, logs[7])
				return w
			}(),
		},
		{
			msg:      "filter level",
			filtered: sink.FilterLevelExact(zap.WarnLevel),
			want:     logs[9:10],
		},
	}

	for _, tt := range tests {
		got := tt.filtered.AllUntimed()
		assert.Equal(t, tt.want, got, tt.msg)
	}
}
Repository: uber-go/zap
File: clock.go (Go)

Code before:
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zap

import (
	"time"

	"go.uber.org/zap/zapcore"
)

// Clock is a source of time for logged entries.
type Clock zapcore.Clock

// systemClock implements default Clock that uses system time.
type systemClock struct{}

var _systemClock Clock = systemClock{}

func (systemClock) Now() time.Time {
	return time.Now()
}

func (systemClock) NewTicker(duration time.Duration) *time.Ticker {
	return time.NewTicker(duration)
}


Review comment (refactor):
Do we need to keep the zap-level Clock type? We haven't shipped this yet so we can move this type to zapcore without breaking anything.

Also, if we do want to keep it around, we probably want to use a type alias.

```suggestion
type Clock = zapcore.Clock
```

The current form declares a new type Clock that is distinct from zapcore.Clock, while the type alias resolves to zapcore.Clock at compile time.

Code after:
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zap

import (
	"time"

	"go.uber.org/zap/zapcore"
)

// Clock is a source of time for logged entries.
type Clock = zapcore.Clock

// systemClock implements default Clock that uses system time.
type systemClock struct{}

var _systemClock Clock = systemClock{}

func (systemClock) Now() time.Time {
	return time.Now()
}

func (systemClock) NewTicker(duration time.Duration) *time.Ticker {
	return time.NewTicker(duration)
}
Repository: uber-go/zap
File: clock_test.go (Go)

Code before:
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zap

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"go.uber.org/zap/zaptest/observer"
)

type constantClock time.Time

func (c constantClock) Now() time.Time { return time.Time(c) }
func (c constantClock) NewTicker(d time.Duration) *time.Ticker {
	return time.NewTicker(d)
}

func TestWithClock(t *testing.T) {
	date := time.Date(2077, 1, 23, 10, 15, 13, 441, time.UTC)
	clock := constantClock(date)
	withLogger(t, DebugLevel, []Option{WithClock(clock)}, func(log *Logger, logs *observer.ObservedLogs) {
		log.Info("")
		require.Equal(t, 1, logs.Len(), "Expected only one log entry to be written.")
		assert.Equal(t, date, logs.All()[0].Entry.Time, "Unexpected entry time.")
	})
}


Review comment (suggestion):
Behaviorally, I would assume that a constantClock will never advance the ticker since time never moves.

Code after:
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zap

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"go.uber.org/zap/zaptest/observer"
)

type constantClock time.Time

func (c constantClock) Now() time.Time { return time.Time(c) }
func (c constantClock) NewTicker(d time.Duration) *time.Ticker {
	return &time.Ticker{}
}

func TestWithClock(t *testing.T) {
	date := time.Date(2077, 1, 23, 10, 15, 13, 441, time.UTC)
	clock := constantClock(date)
	withLogger(t, DebugLevel, []Option{WithClock(clock)}, func(log *Logger, logs *observer.ObservedLogs) {
		log.Info("")
		require.Equal(t, 1, logs.Len(), "Expected only one log entry to be written.")
		assert.Equal(t, date, logs.All()[0].Entry.Time, "Unexpected entry time.")
	})
}

func TestSystemClockNewTicker(t *testing.T) {
	want := 3

	var n int
	timer := _systemClock.NewTicker(time.Millisecond)
	for range timer.C {
		n++
		if n == want {
			return
		}
	}
}
Repository: uber-go/zap
File: zapcore/clock_test.go (Go)

Code before:
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zapcore

import (
	"sync/atomic"
	"testing"
	"time"

	"github.com/benbjohnson/clock"
	"github.com/stretchr/testify/assert"
)

type controlledClock struct {
	mockClock *clock.Mock
}

func (c *controlledClock) Now() time.Time {
	return c.mockClock.Now()
}

func (c *controlledClock) NewTicker(d time.Duration) *time.Ticker {
	return &time.Ticker{C: c.mockClock.Ticker(d).C}
}

func TestMockClock(t *testing.T) {
	var n int32
	ctrlMock := &controlledClock{mockClock: clock.NewMock()}

	// Create a channel to increment every microsecond.
	go func() {
		ticker := ctrlMock.NewTicker(1 * time.Microsecond)
		for {
			<-ticker.C
			atomic.AddInt32(&n, 1)
		}
	}()
	time.Sleep(1 * time.Microsecond)

	// Move clock forward.
	ctrlMock.mockClock.Add(10 * time.Microsecond)
	assert.Equal(t, atomic.LoadInt32(&n), int32(10))
}


Review comment (suggestion):
This works but we can shorten this by embedding clock.Mock and only overriding NewTicker:

```
type controlledClock struct{
  *clock.Mock
}

func newControlledClock() *controlledClock

func (*controlledClock) NewTicker(...) *time.Ticker
```



Code after:
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zapcore

import (
	"testing"
	"time"

	"github.com/benbjohnson/clock"
	"github.com/stretchr/testify/assert"
	"go.uber.org/atomic"
)

type controlledClock struct{ *clock.Mock }

func newControlledClock() *controlledClock {
	return &controlledClock{clock.NewMock()}
}
func (c *controlledClock) NewTicker(d time.Duration) *time.Ticker {
	return &time.Ticker{C: c.Ticker(d).C}
}

func TestMockClock(t *testing.T) {
	var n atomic.Int32
	ctrlMock := newControlledClock()

	done := make(chan struct{})
	defer func() { <-done }() // wait for end

	quit := make(chan struct{})
	// Create a channel to increment every microsecond.
	go func(ticker *time.Ticker) {
		defer close(done)
		for {
			select {
			case <-quit:
				ticker.Stop()
				return
			case <-ticker.C:
				n.Inc()
			}
		}
	}(ctrlMock.NewTicker(time.Microsecond))

	// Move clock forward.
	ctrlMock.Add(2 * time.Microsecond)
	assert.Equal(t, int32(2), n.Load())
	close(quit)