response_test.go 1.21 KB
Newer Older
1 2
package commands

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

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

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

	req := NewRequest(nil, nil, nil, nil, opts)
19

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

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

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

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

Matt Bell's avatar
Matt Bell committed
39
	res.SetError(fmt.Errorf("Oops!"), ErrClient)
Matt Bell's avatar
Matt Bell committed
40 41 42 43 44
	bytes, err = res.Marshal()
	if err != nil {
		t.Error("Should have passed")
	}
	output = string(bytes)
Matt Bell's avatar
Matt Bell committed
45 46
	fmt.Println(removeWhitespace(output))
	if removeWhitespace(output) != "{\"Message\":\"Oops!\",\"Code\":1}" {
Matt Bell's avatar
Matt Bell committed
47 48
		t.Error("Incorrect JSON output")
	}
49
}
Matt Bell's avatar
Matt Bell committed
50 51 52 53 54 55 56

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)
}