~samwhited/xmpp

ref: a2ffaf710170d692a9289c2b428a4efa90c8e703 xmpp/stanza/presence_test.go -rw-r--r-- 1.7 KiB
a2ffaf71Sam Whited all: update deps 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
// Copyright 2016 Sam Whited.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.

package stanza_test

import (
	"bytes"
	"encoding/xml"
	"fmt"
	"testing"

	"mellium.im/xmpp/stanza"
)

func TestMarshalPresenceTypeAttr(t *testing.T) {
	for i, tc := range [...]struct {
		presencetype stanza.PresenceType
		value        string
	}{
		0: {stanza.PresenceType(""), ""},
		1: {stanza.ErrorPresence, "error"},
	} {
		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
			b, err := xml.Marshal(stanza.Presence{Type: tc.presencetype})
			if err != nil {
				t.Fatal("Unexpected error while marshaling:", err)
			}

			// Special case empty presence to make sure its omitted.
			if string(tc.presencetype) == "" {
				if bytes.Contains(b, []byte("type=")) {
					t.Fatalf(`Expected empty presence type to be omitted, found: %s`, b)
				}
				return
			}

			if !bytes.Contains(b, []byte(fmt.Sprintf(`type="%s"`, tc.presencetype))) {
				t.Errorf(`Expected output to contain type="%s", found: %s`, tc.presencetype, b)
			}
		})
	}
}

func TestUnmarshalPresenceTypeAttr(t *testing.T) {
	for i, tc := range [...]struct {
		presence     string
		presencetype stanza.PresenceType
	}{
		0: {`<presence/>`, stanza.PresenceType("")},
		1: {`<presence type=""/>`, stanza.PresenceType("")},
		2: {`<presence type="probe"/>`, stanza.ProbePresence},
	} {
		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
			presence := stanza.Presence{}
			switch err := xml.Unmarshal([]byte(tc.presence), &presence); {
			case err != nil:
				t.Error("Got unexpected error while unmarshaling Presence:", err)
			case tc.presencetype != presence.Type:
				t.Errorf("Wrong type when unmarshaling Presence: want=%s, got=%s", tc.presencetype, presence.Type)
			}
		})
	}
}