~samwhited/xmpp

ref: a42ef11e9469b0b65746f979e1bdf5155d1c13dd xmpp/stanza/message_test.go -rw-r--r-- 1.9 KiB
a42ef11eSam Whited all: update copyright message 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
// Copyright 2015 The Mellium Contributors.
// 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 TestMarshalMessageTypeAttr(t *testing.T) {
	for i, tc := range [...]struct {
		messagetype stanza.MessageType
		value       string
		err         error
	}{
		0: {stanza.MessageType(""), "", nil},
		1: {stanza.NormalMessage, "normal", nil},
		2: {stanza.ChatMessage, "chat", nil},
		3: {stanza.HeadlineMessage, "headline", nil},
		4: {stanza.ErrorMessage, "error", nil},
	} {
		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
			b, err := xml.Marshal(stanza.Message{Type: tc.messagetype})
			if err != tc.err {
				t.Fatalf("Got unexpected error while marshaling Message: want='%v', got='%v'", tc.err, err)
			}

			// Special case to check that empty values are omitted
			if string(tc.messagetype) == "" {
				if bytes.Contains(b, []byte("type")) {
					t.Fatalf(`Didn't expect output to contain type attribute, found: %s`, b)
				}
				return
			}

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

func TestUnmarshalMessageTypeAttr(t *testing.T) {
	for i, tc := range [...]struct {
		message     string
		messagetype stanza.MessageType
	}{
		0: {`<message type="normal"/>`, stanza.NormalMessage},
		1: {`<message type="error"/>`, stanza.ErrorMessage},
	} {
		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
			message := stanza.Message{}
			switch err := xml.Unmarshal([]byte(tc.message), &message); {
			case err != nil:
				t.Errorf("Got unexpected error while unmarshaling Message: %v", err)
			case tc.messagetype != message.Type:
				t.Errorf("Wrong type when unmarshaling Message: want=%s, got=%s", tc.messagetype, message.Type)
			}
		})
	}
}