~samwhited/xmpp

ref: 34ff471482b892b2fc10af24c8b590204c7320ec xmpp/streamerror/streamerror_test.go -rw-r--r-- 2.2 KiB
34ff4714Sam Whited xmpp: rename some vars (stream → streamData) 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright 2015 Sam Whited.
// Use of this source code is governed by the BSD 2-clause license that can be
// found in the LICENSE file.

package streamerror

import (
	"encoding/xml"
	"net"
	"testing"
)

var _ error = (*StreamError)(nil)
var _ error = StreamError{}
var _ xml.Marshaler = (*StreamError)(nil)
var _ xml.Marshaler = StreamError{}
var _ xml.Unmarshaler = (*StreamError)(nil)

func TestMarshalSeeOtherHost(t *testing.T) {
	for _, test := range []struct {
		ipaddr net.Addr
		xml    string
		err    bool
	}{
		// see-other-host errors should wrap IPv6 addresses in brackets.
		{&net.IPAddr{IP: net.ParseIP("::1")}, `<stream:error><see-other-host xmlns="urn:ietf:params:xml:ns:xmpp-streams">[::1]</see-other-host></stream:error>`, false},
		{&net.IPAddr{IP: net.ParseIP("127.0.0.1")}, `<stream:error><see-other-host xmlns="urn:ietf:params:xml:ns:xmpp-streams">127.0.0.1</see-other-host></stream:error>`, false},
	} {
		soh := SeeOtherHostError(test.ipaddr)
		xb, err := xml.Marshal(soh)
		switch xbs := string(xb); {
		case test.err && err == nil:
			t.Errorf("Expected marshaling SeeOtherHost error for address `%v` to fail", test.ipaddr)
			continue
		case !test.err && err != nil:
			t.Error(err)
			continue
		case err != nil:
			continue
		case xbs != test.xml:
			t.Logf("Expected `%s` but got `%s`", test.xml, xbs)
			t.Fail()
		}
	}
}

func TestUnmarshal(t *testing.T) {
	for _, test := range []struct {
		xml string
		se  StreamError
		err bool
	}{
		{
			`<stream:error><restricted-xml xmlns="urn:ietf:params:xml:ns:xmpp-streams"></restricted-xml></stream:error>`,
			RestrictedXML, false,
		},
		{
			`<stream:error></a>`,
			RestrictedXML, true,
		},
	} {
		s := StreamError{}
		err := xml.Unmarshal([]byte(test.xml), &s)
		switch {
		case test.err && err == nil:
			t.Errorf("Expected unmarshaling error for `%v` to fail", test.xml)
			continue
		case !test.err && err != nil:
			t.Error(err)
			continue
		case err != nil:
			continue
		case s.Err != test.se.Err || string(s.InnerXML) != string(test.se.InnerXML):
			t.Errorf("Expected `%#v` but got `%#v`", test.se, s)
		}
	}
}

func TestErrorReturnsErr(t *testing.T) {
	if RestrictedXML.Error() != "restricted-xml" {
		t.Error("Error should return the name of the err")
	}
}