Skip to content

Commit

Permalink
Test Sync() call when calling AddSync
Browse files Browse the repository at this point in the history
If call to `Sync()` fails, wrap the WriteSyncer with a fake `Sync()`.
Fixes uber-go#328
  • Loading branch information
Ulexus committed Mar 6, 2017
1 parent 1b7cf6e commit 9da32f3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
14 changes: 14 additions & 0 deletions zapcore/write_syncer.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,26 @@ type WriteSyncer interface {
func AddSync(w io.Writer) WriteSyncer {
switch w := w.(type) {
case WriteSyncer:
if !checkSync(w.(WriteSyncer)) {
return writerWrapper{w}
}
return w
default:
return writerWrapper{w}
}
}

// checkSync executes a Sync() on the WriteSyncer to check whether it operates
// cleanly. In the particular case of the WriteSyncer being a special file,
// calling Sync will return an `os.ErrInvalid` error. If, for whatever reason,
// the call of `Sync()` returns an error, this will return a `false`.
func checkSync(w WriteSyncer) bool {
if err := w.Sync(); err != nil {
return false
}
return true
}

type lockedWriteSyncer struct {
sync.Mutex
ws WriteSyncer
Expand Down
16 changes: 16 additions & 0 deletions zapcore/write_syncer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ package zapcore
import (
"bytes"
"errors"
"io/ioutil"
"os"
"testing"

"io"
Expand Down Expand Up @@ -65,6 +67,20 @@ func TestAddSyncWriter(t *testing.T) {
assert.NoError(t, ws.Sync(), "Unexpected error calling a no-op Sync method.")
}

func TestCheckSync(t *testing.T) {
assert.False(t, checkSync(os.Stdout), "Expected os.Stdout to fail sync check")
assert.False(t, checkSync(os.Stderr), "Expected os.Stderr to fail sync check")

// Test a real file, which should pass
tmpFile, err := ioutil.TempFile("/tmp", "zapcore-test")
if err != nil {
t.SkipNow()
return
}
defer tmpFile.Close()
assert.True(t, checkSync(tmpFile), "Expected os.Stderr to fail sync check")
}

func TestMultiWriteSyncerWritesBoth(t *testing.T) {
first := &bytes.Buffer{}
second := &bytes.Buffer{}
Expand Down

0 comments on commit 9da32f3

Please sign in to comment.