~samwhited/xmpp

ref: e8c09b3ff1c1489c21d96a0f7f8f0e8728fc095a xmpp/disco/items_test.go -rw-r--r-- 2.3 KiB
e8c09b3fSam Whited design: fix typo in design doc template 1 year, 4 months 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Copyright 2021 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 disco_test

import (
	"context"
	"encoding/xml"
	"reflect"
	"strconv"
	"testing"

	"mellium.im/xmlstream"
	"mellium.im/xmpp/disco"
	"mellium.im/xmpp/internal/xmpptest"
	"mellium.im/xmpp/jid"
	"mellium.im/xmpp/stanza"
)

var testGetItems = [...]struct {
	node  string
	items map[string][]disco.Item
	err   error
}{
	0: {},
	1: {
		items: map[string][]disco.Item{
			"": {{
				XMLName: xml.Name{Space: disco.NSItems, Local: "item"},
				JID:     jid.MustParse("juliet@example.com"),
				Name:    "Juliet",
			}, {
				XMLName: xml.Name{Space: disco.NSItems, Local: "item"},
				JID:     jid.MustParse("benvolio@example.org"),
			}},
		},
	},
	2: {
		node: "test",
		items: map[string][]disco.Item{
			"test": {{
				XMLName: xml.Name{Space: disco.NSItems, Local: "item"},
				JID:     jid.MustParse("benvolio@example.org"),
			}},
		},
	},
}

type queryItems struct {
	XMLName xml.Name     `xml:"http://jabber.org/protocol/disco#items query"`
	Items   []disco.Item `xml:"item"`
}

func TestGetItems(t *testing.T) {
	var IQ = stanza.IQ{
		ID:   "123",
		Type: stanza.ResultIQ,
	}
	for i, tc := range testGetItems {
		t.Run(strconv.Itoa(i), func(t *testing.T) {
			cs := xmpptest.NewClientServer(
				xmpptest.ServerHandlerFunc(func(e xmlstream.TokenReadEncoder, start *xml.StartElement) error {
					query := disco.ItemsQuery{}
					err := xml.NewTokenDecoder(e).Decode(&query)
					if err != nil {
						return err
					}
					sendIQ := struct {
						stanza.IQ
						Query queryItems
					}{
						IQ: IQ,
						Query: queryItems{
							Items: tc.items[query.Node],
						},
					}
					return e.Encode(sendIQ)
				}),
			)
			iter := disco.GetItemsIQ(context.Background(), tc.node, IQ, cs.Client)
			items := make([]disco.Item, 0, len(tc.items))
			for iter.Next() {
				items = append(items, iter.Item())
			}
			if err := iter.Err(); err != tc.err {
				t.Errorf("wrong error after iter: want=%q, got=%q", tc.err, err)
			}
			iter.Close()

			// Don't try to compare nil and empty slice with DeepEqual
			if len(items) == 0 && len(tc.items) == 0 {
				return
			}

			if !reflect.DeepEqual(items, tc.items[tc.node]) {
				t.Errorf("wrong items:\nwant=\n%+v,\ngot=\n%+v", tc.items[tc.node], items)
			}
		})
	}
}