response_test.go 1.31 KB
Newer Older
1 2
package commands

3
import (
4
	"bytes"
Matt Bell's avatar
Matt Bell committed
5
	"fmt"
Matt Bell's avatar
Matt Bell committed
6
	"strings"
Matt Bell's avatar
Matt Bell committed
7
	"testing"
8
)
9 10

type TestOutput struct {
Matt Bell's avatar
Matt Bell committed
11 12
	Foo, Bar string
	Baz      int
13 14 15
}

func TestMarshalling(t *testing.T) {
16 17 18
	cmd := &Command{}
	opts, _ := cmd.GetOptions(nil)

Matt Bell's avatar
Matt Bell committed
19
	req, _ := NewRequest(nil, nil, nil, nil, nil, opts)
20

Matt Bell's avatar
Matt Bell committed
21
	res := NewResponse(req)
22
	res.SetOutput(TestOutput{"beep", "boop", 1337})
23

24
	_, err := res.Marshal()
Matt Bell's avatar
Matt Bell committed
25 26 27
	if err == nil {
		t.Error("Should have failed (no encoding type specified in request)")
	}
28

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
29
	req.SetOption(EncShort, JSON)
Matt Bell's avatar
Matt Bell committed
30

31
	reader, err := res.Marshal()
Matt Bell's avatar
Matt Bell committed
32
	if err != nil {
Matt Bell's avatar
Matt Bell committed
33
		t.Error(err, "Should have passed")
Matt Bell's avatar
Matt Bell committed
34
	}
35 36 37
	var buf bytes.Buffer
	buf.ReadFrom(reader)
	output := buf.String()
Matt Bell's avatar
Matt Bell committed
38
	if removeWhitespace(output) != "{\"Foo\":\"beep\",\"Bar\":\"boop\",\"Baz\":1337}" {
Matt Bell's avatar
Matt Bell committed
39 40
		t.Error("Incorrect JSON output")
	}
41

Matt Bell's avatar
Matt Bell committed
42
	res.SetError(fmt.Errorf("Oops!"), ErrClient)
43
	reader, err = res.Marshal()
Matt Bell's avatar
Matt Bell committed
44 45 46
	if err != nil {
		t.Error("Should have passed")
	}
47 48 49
	buf.Reset()
	buf.ReadFrom(reader)
	output = buf.String()
Matt Bell's avatar
Matt Bell committed
50 51
	fmt.Println(removeWhitespace(output))
	if removeWhitespace(output) != "{\"Message\":\"Oops!\",\"Code\":1}" {
Matt Bell's avatar
Matt Bell committed
52 53
		t.Error("Incorrect JSON output")
	}
54
}
Matt Bell's avatar
Matt Bell committed
55 56 57 58 59 60 61

func removeWhitespace(input string) string {
	input = strings.Replace(input, " ", "", -1)
	input = strings.Replace(input, "\t", "", -1)
	input = strings.Replace(input, "\n", "", -1)
	return strings.Replace(input, "\r", "", -1)
}