Browse code

Fix a bug in Output.Write, and improve testing coverage of error cases.

Solomon Hykes authored on 2013/11/22 11:28:56
Showing 2 changed files
... ...
@@ -89,7 +89,7 @@ func (o *Output) Write(p []byte) (n int, err error) {
89 89
 			firstErr = err
90 90
 		}
91 91
 	}
92
-	return len(p), err
92
+	return len(p), firstErr
93 93
 }
94 94
 
95 95
 // Close unregisters all destinations and waits for all background
... ...
@@ -4,6 +4,7 @@ import (
4 4
 	"bufio"
5 5
 	"bytes"
6 6
 	"fmt"
7
+	"io"
7 8
 	"io/ioutil"
8 9
 	"strings"
9 10
 	"testing"
... ...
@@ -208,6 +209,27 @@ func TestOutputAdd(t *testing.T) {
208 208
 	}
209 209
 }
210 210
 
211
+func TestOutputWriteError(t *testing.T) {
212
+	o := NewOutput()
213
+	buf := &bytes.Buffer{}
214
+	o.Add(buf)
215
+	r, w := io.Pipe()
216
+	input := "Hello there"
217
+	expectedErr := fmt.Errorf("This is an error")
218
+	r.CloseWithError(expectedErr)
219
+	o.Add(w)
220
+	n, err := o.Write([]byte(input))
221
+	if err != expectedErr {
222
+		t.Fatalf("Output.Write() should return the first error encountered, if any")
223
+	}
224
+	if buf.String() != input {
225
+		t.Fatalf("Output.Write() should attempt write on all destinations, even after encountering an error")
226
+	}
227
+	if n != len(input) {
228
+		t.Fatalf("Output.Write() should return the size of the input if it successfully writes to at least one destination")
229
+	}
230
+}
231
+
211 232
 func TestInputAddEmpty(t *testing.T) {
212 233
 	i := NewInput()
213 234
 	var b bytes.Buffer