response_test.go 1.04 KB
Newer Older
1 2
package commands

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

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

func TestMarshalling(t *testing.T) {
Matt Bell's avatar
Matt Bell committed
14
	req := NewRequest()
15

Matt Bell's avatar
Matt Bell committed
16 17 18 19
	res := Response{
		req:   req,
		Value: TestOutput{"beep", "boop", 1337},
	}
20

Matt Bell's avatar
Matt Bell committed
21 22 23 24 25 26 27 28
	// get command global options so we can set the encoding option
	cmd := Command{}
	options, err := cmd.GetOptions(nil)
	if err != nil {
		t.Error(err)
	}

	_, err = res.Marshal()
Matt Bell's avatar
Matt Bell committed
29 30 31
	if err == nil {
		t.Error("Should have failed (no encoding type specified in request)")
	}
32

Matt Bell's avatar
Matt Bell committed
33 34 35
	req.SetOption("enc", Json)
	req.convertOptions(options)

Matt Bell's avatar
Matt Bell committed
36 37
	bytes, err := res.Marshal()
	if err != nil {
Matt Bell's avatar
Matt Bell committed
38
		t.Error(err, "Should have passed")
Matt Bell's avatar
Matt Bell committed
39 40 41 42 43
	}
	output := string(bytes)
	if output != "{\"Foo\":\"beep\",\"Bar\":\"boop\",\"Baz\":1337}" {
		t.Error("Incorrect JSON output")
	}
44

Matt Bell's avatar
Matt Bell committed
45 46 47 48 49 50 51 52 53
	res.SetError(fmt.Errorf("You broke something!"), Client)
	bytes, err = res.Marshal()
	if err != nil {
		t.Error("Should have passed")
	}
	output = string(bytes)
	if output != "{\"Message\":\"You broke something!\",\"Code\":1}" {
		t.Error("Incorrect JSON output")
	}
54
}