Use bytes.Buffer or strings.Builder directly - no need for the bufio.Writer.
bufio.Writer only speeds up writing by calling the underlying Writer less, 
with bigger slices.
Here you Write into a memory, just as bufio.Writer.

Also, you can save some allocations by creating the buffer once outside of 
the loop,
and Reset() it in each cycle before calling handleCommand.


amits...@gmail.com a következőt írta (2020. október 20., kedd, 6:03:31 
UTC+2):

> Hi all, Consider the following test configuration:
>
>
> func TestHandleCommand(t *testing.T) {
>
> type expectedResult struct {
> output string
> err error
> }
> type testConfig struct {
> args []string
> result expectedResult
> }
>
> testConfigs := []testConfig{
> testConfig{
> args: []string{"-h"},
> result: expectedResult{
> err: nil,
> output: `Expected output`,
> },
> },
> }
>
> Then, I do this:
>
>
> for _, tc := range testConfigs {
> byteBuf := new(bytes.Buffer)
> w := bufio.NewWriter(byteBuf)
>
> err := handleCommand(w, tc.args)
> if tc.result.err == nil && err != nil {
> t.Errorf("Expected nil error, got %v", err)
> }
>
> if tc.result.err != nil && err.Error() != tc.result.err.Error() {
> t.Errorf("Expected error %v, got %v", tc.result.err, err)
> }
>
> if len(tc.result.output) != 0 {
> w.Flush()
> gotOutput := byteBuf.String()
> if tc.result.output != gotOutput {
> t.Errorf("Expected output to be: %v, Got: %v",
> tc.result.output, gotOutput)
> }
> }
> }
> }
>
> The above pattern works for me since the function may return an error
> and/or it may have something it writes to the provided writer, w.
>
> Is there a more concise way to write this?
>
>
>
> Thanks,
> Amit.
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/2759fea4-a3d6-42ee-b3e4-2c0ac208f2b9n%40googlegroups.com.

Reply via email to