Created
June 14, 2018 19:11
-
-
Save crgimenes/f80944a8c2e3eab172dcd6f1613497cc to your computer and use it in GitHub Desktop.
closer and tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package helper | |
// closer close descriptor and log error | |
func closer(f io.Closer) { | |
err := f.Close() | |
if err != nil { | |
log.Errorln("closing ", err) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package helper | |
type closerSuccess struct { | |
} | |
func (c closerSuccess) Close() (err error) { | |
return | |
} | |
type closerError struct { | |
} | |
func (c closerError) Close() (err error) { | |
err = errors.New("closer error") | |
return | |
} | |
func Test_closer(t *testing.T) { | |
getStdout := func(obj io.Closer) (out []byte, err error) { | |
rescueStdout := os.Stdout | |
defer func() { os.Stdout = rescueStdout }() | |
r, w, err := os.Pipe() | |
if err != nil { | |
return nil, err | |
} | |
os.Stdout = w | |
closer(obj) | |
err = w.Close() | |
if err != nil { | |
return | |
} | |
out, err = ioutil.ReadAll(r) | |
return | |
} | |
cs := closerSuccess{} | |
ce := closerError{} | |
type args struct { | |
body io.Closer | |
} | |
type expected struct { | |
err bool | |
} | |
tests := []struct { | |
name string | |
args args | |
want expected | |
}{ | |
{ | |
name: "success", | |
args: args{ | |
body: cs, | |
}, | |
want: expected{ | |
err: false, | |
}, | |
}, | |
{ | |
name: "error", | |
args: args{ | |
body: ce, | |
}, | |
want: expected{ | |
err: true, | |
}, | |
}, | |
} | |
for _, tt := range tests { | |
t.Run(tt.name, func(t *testing.T) { | |
out, err := getStdout(tt.args.body) | |
if err != nil { | |
t.Error(err) | |
return | |
} | |
if (len(out) > 0) != tt.want.err { | |
fmt.Printf("out: %q\n", string(out)) | |
t.Errorf("closer() unexpected log %q", string(out)) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment