~samwhited/xmpp

ref: dcc6772f31033948a00a7dfb9232a120120be5b7 xmpp/mux/mux_test.go -rw-r--r-- 24.6 KiB
dcc6772fSam Whited all: add strict namespace checking to mux 29 days 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
// Copyright 2017 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 mux_test

import (
	"bytes"
	"encoding/xml"
	"errors"
	"fmt"
	"io"
	"strconv"
	"strings"
	"testing"

	"mellium.im/xmlstream"
	"mellium.im/xmpp/disco/info"
	"mellium.im/xmpp/disco/items"
	"mellium.im/xmpp/internal/marshal"
	"mellium.im/xmpp/internal/ns"
	"mellium.im/xmpp/internal/xmpptest"
	"mellium.im/xmpp/mux"
	"mellium.im/xmpp/stanza"
)

var _ info.FeatureIter = (*mux.ServeMux)(nil)

var (
	errPassTest = errors.New("mux_test: PASSED")
	errFailTest = errors.New("mux_test: FAILED")
)

const exampleNS = "com.example"

type passHandler struct{}

func (passHandler) HandleXMPP(xmlstream.TokenReadEncoder, *xml.StartElement) error {
	return errPassTest
}
func (passHandler) HandleMessage(stanza.Message, xmlstream.TokenReadEncoder) error {
	return errPassTest
}
func (passHandler) HandlePresence(stanza.Presence, xmlstream.TokenReadEncoder) error {
	return errPassTest
}
func (passHandler) HandleIQ(stanza.IQ, xmlstream.TokenReadEncoder, *xml.StartElement) error {
	return errPassTest
}

type multiHandler struct{}

func (multiHandler) HandlePresence(_ stanza.Presence, t xmlstream.TokenReadEncoder) error {
	d := xml.NewTokenDecoder(t)
	data := struct {
		stanza.Presence

		Test    string `xml:"com.example test"`
		Example string `xml:"com.example example"`
	}{}
	err := d.Decode(&data)
	if err != nil {
		return err
	}
	if data.Test != "test" {
		return fmt.Errorf("wrong value for test element: want=%q, got=%q", "test", data.Test)
	}
	if data.Example != "example" {
		return fmt.Errorf("wrong value for example element: want=%q, got=%q", "example", data.Test)
	}
	return errPassTest
}

func (m multiHandler) HandleMessage(_ stanza.Message, t xmlstream.TokenReadEncoder) error {
	d := xml.NewTokenDecoder(t)
	data := struct {
		stanza.Message

		Test    string `xml:"com.example test"`
		Example string `xml:"com.example example"`
	}{}
	err := d.Decode(&data)
	if err != nil {
		return err
	}
	if data.Test != "test" {
		return fmt.Errorf("wrong value for test element: want=%q, got=%q", "test", data.Test)
	}
	if data.Example != "example" {
		return fmt.Errorf("wrong value for example element: want=%q, got=%q", "example", data.Test)
	}
	return errPassTest
}

type failHandler struct{}

func (failHandler) HandleXMPP(t xmlstream.TokenReadEncoder, start *xml.StartElement) error {
	return errFailTest
}
func (failHandler) HandleMessage(msg stanza.Message, t xmlstream.TokenReadEncoder) error {
	return errFailTest
}
func (failHandler) HandlePresence(p stanza.Presence, t xmlstream.TokenReadEncoder) error {
	return errFailTest
}
func (failHandler) HandleIQ(iq stanza.IQ, t xmlstream.TokenReadEncoder, start *xml.StartElement) error {
	return errFailTest
}

type decodeHandler struct {
	Body string
}

func (h decodeHandler) HandleMessage(msg stanza.Message, t xmlstream.TokenReadEncoder) error {
	d := xml.NewTokenDecoder(t)
	data := struct {
		stanza.Message

		Body string `xml:"body"`
	}{}
	err := d.Decode(&data)
	if err != nil {
		return err
	}
	if h.Body != data.Body {
		return fmt.Errorf("wrong body: want=%q, got=%q", h.Body, data.Body)
	}
	return errPassTest
}

var testCases = [...]struct {
	m           []mux.Option
	x           string
	expectPanic bool
	err         error
	stanzaNS    string
}{
	0: {
		// Basic muxing based on localname and IQ type should work.
		m: []mux.Option{
			mux.IQ(stanza.GetIQ, xml.Name{}, passHandler{}),
			mux.IQ(stanza.SetIQ, xml.Name{}, failHandler{}),
			mux.Presence(stanza.AvailablePresence, xml.Name{}, failHandler{}),
		},
		x:   `<iq xml:lang="en-us" type="get" xmlns="jabber:client"><a/></iq>`,
		err: errPassTest,
	},
	1: {
		// Basic muxing isn't affected by the server namespace.
		m: []mux.Option{
			mux.IQFunc(stanza.SetIQ, xml.Name{}, passHandler{}.HandleIQ),
			mux.IQ(stanza.GetIQ, xml.Name{}, failHandler{}),
			mux.Presence(stanza.AvailablePresence, xml.Name{}, failHandler{}),
		},
		x:        `<iq type="set" xmlns="jabber:server"><b/></iq>`,
		err:      errPassTest,
		stanzaNS: ns.Server,
	},
	2: {
		// The message option works with a client namespace.
		m: []mux.Option{
			mux.IQ(stanza.GetIQ, xml.Name{}, failHandler{}),
			mux.Message(stanza.ChatMessage, xml.Name{}, passHandler{}),
		},
		x:   `<message id="123" type="chat" xmlns="jabber:client"></message>`,
		err: errPassTest,
	},
	3: {
		// The message option works with a server namespace.
		m: []mux.Option{
			mux.IQ(stanza.GetIQ, xml.Name{}, failHandler{}),
			mux.MessageFunc(stanza.ChatMessage, xml.Name{}, passHandler{}.HandleMessage),
		},
		x:        `<message to="feste@example.net" from="olivia@example.net" type="chat" xmlns="jabber:server"></message>`,
		err:      errPassTest,
		stanzaNS: ns.Server,
	},
	4: {
		// The presence option works with a client namespace and no type attribute.
		m: []mux.Option{
			mux.Message(stanza.HeadlineMessage, xml.Name{}, failHandler{}),
			mux.IQ(stanza.SetIQ, xml.Name{}, failHandler{}),
			mux.Presence(stanza.AvailablePresence, xml.Name{}, passHandler{}),
		},
		x:   `<presence id="484" xml:lang="es" xmlns="jabber:client"></presence>`,
		err: errPassTest,
	},
	5: {
		m: []mux.Option{
			// The presence option works with a server namespace and an empty type
			// attribute.
			mux.Message(stanza.ChatMessage, xml.Name{}, failHandler{}),
			mux.IQ(stanza.GetIQ, xml.Name{}, failHandler{}),
			mux.PresenceFunc(stanza.AvailablePresence, xml.Name{}, passHandler{}.HandlePresence),
		},
		x:        `<presence type="" xmlns="jabber:server"></presence>`,
		err:      errPassTest,
		stanzaNS: ns.Server,
	},
	6: {
		// Other top level elements can be routed with a wildcard namespace.
		m:   []mux.Option{mux.Handle(xml.Name{Local: "test"}, passHandler{})},
		x:   `<test xmlns="summertime"/>`,
		err: errPassTest,
	},
	7: {
		// Other top level elements can be routed with a wildcard localname.
		m:   []mux.Option{mux.HandleFunc(xml.Name{Space: "summertime"}, passHandler{}.HandleXMPP)},
		x:   `<test xmlns="summertime"/>`,
		err: errPassTest,
	},
	8: {
		// Other top level elements can be routed with an exact match.
		m: []mux.Option{
			mux.Handle(xml.Name{Local: "test"}, failHandler{}),
			mux.HandleFunc(xml.Name{Space: "summertime"}, failHandler{}.HandleXMPP),
			mux.HandleFunc(xml.Name{Local: "test", Space: "summertime"}, passHandler{}.HandleXMPP),
		},
		x:   `<test xmlns="summertime"/>`,
		err: errPassTest,
	},
	9: {
		// IQ exact child match handler.
		m: []mux.Option{
			mux.IQ(stanza.GetIQ, xml.Name{Local: "a", Space: exampleNS}, failHandler{}),
			mux.IQ(stanza.GetIQ, xml.Name{Local: "test", Space: "b"}, failHandler{}),
			mux.IQ(stanza.SetIQ, xml.Name{Local: "a", Space: exampleNS}, failHandler{}),
			mux.IQ(stanza.SetIQ, xml.Name{Local: "test", Space: "b"}, failHandler{}),
			mux.IQ(stanza.SetIQ, xml.Name{Local: "test", Space: exampleNS}, failHandler{}),
			mux.IQ(stanza.GetIQ, xml.Name{Local: "test", Space: exampleNS}, passHandler{}),
		},
		x:   `<iq type="get" xmlns="jabber:client"><test xmlns="com.example"/></iq>`,
		err: errPassTest,
	},
	10: {
		// If no exact match is available, fallback to the namespace wildcard
		// handler.
		m: []mux.Option{
			mux.IQ(stanza.GetIQ, xml.Name{Local: "test", Space: ""}, passHandler{}),
			mux.IQ(stanza.GetIQ, xml.Name{Local: "", Space: exampleNS}, failHandler{}),
		},
		x:   `<iq type="get" xmlns="jabber:client"><test xmlns="com.example"/></iq>`,
		err: errPassTest,
	},
	11: {
		// If no exact match or namespace handler is available, fallback local name
		// handler.
		m: []mux.Option{
			mux.IQ(stanza.GetIQ, xml.Name{Local: "", Space: exampleNS}, passHandler{}),
			mux.IQ(stanza.ResultIQ, xml.Name{Local: "", Space: exampleNS}, failHandler{}),
		},
		x:   `<iq type="get" xmlns="jabber:client"><test xmlns="com.example"/></iq>`,
		err: errPassTest,
	},
	12: {
		// If no exact match or localname/namespace wildcard is available, fallback
		// to just matching on type alone.
		m: []mux.Option{
			mux.IQ(stanza.ResultIQ, xml.Name{Local: "test", Space: exampleNS}, failHandler{}),
			mux.IQ(stanza.ErrorIQ, xml.Name{}, passHandler{}),
		},
		x:   `<iq type="error" xmlns="jabber:client"><test xmlns="com.example"/></iq>`,
		err: errPassTest,
	},
	13: {
		// Test nop non-stanza handler.
		x: `<nop/>`,
	},
	14: {
		// Test nop message handler.
		m: []mux.Option{mux.Message(stanza.HeadlineMessage, xml.Name{}, failHandler{})},
		x: `<message xml:lang="de" type="chat" xmlns="jabber:server"/>`,
	},
	15: {
		// Test nop presence handler.
		m: []mux.Option{mux.Presence(stanza.SubscribedPresence, xml.Name{}, failHandler{})},
		x: `<presence to="romeo@example.net" from="mercutio@example.net" xmlns="jabber:server"/>`,
	},
	16: {
		// Expect nil IQ handler to panic.
		m:           []mux.Option{mux.IQ(stanza.GetIQ, xml.Name{}, nil)},
		expectPanic: true,
	},
	17: {
		// Expect nil message handler to panic.
		m:           []mux.Option{mux.Message(stanza.ChatMessage, xml.Name{}, nil)},
		expectPanic: true,
	},
	18: {
		// Expect nil presence handler to panic.
		m:           []mux.Option{mux.Presence(stanza.ProbePresence, xml.Name{}, nil)},
		expectPanic: true,
	},
	19: {
		// Expect nil top level element handler to panic.
		m:           []mux.Option{mux.Handle(xml.Name{Local: "test"}, nil)},
		expectPanic: true,
	},
	20: {
		// Expect duplicate IQ handler to panic.
		m: []mux.Option{
			mux.IQ(stanza.GetIQ, xml.Name{}, failHandler{}),
			mux.IQ(stanza.GetIQ, xml.Name{}, failHandler{}),
		},
		expectPanic: true,
	},
	21: {
		// Expect duplicate message handler to panic.
		m: []mux.Option{
			mux.Message(stanza.ChatMessage, xml.Name{}, failHandler{}),
			mux.Message(stanza.ChatMessage, xml.Name{}, failHandler{}),
		},
		expectPanic: true,
	},
	22: {
		// Expect duplicate presence handler to panic.
		m: []mux.Option{
			mux.Presence(stanza.ProbePresence, xml.Name{}, failHandler{}),
			mux.Presence(stanza.ProbePresence, xml.Name{}, failHandler{}),
		},
		expectPanic: true,
	},
	23: {
		// Expect duplicate top level element handler to panic.
		m: []mux.Option{
			mux.Handle(xml.Name{Local: "test"}, failHandler{}),
			mux.Handle(xml.Name{Local: "test"}, failHandler{}),
		},
		expectPanic: true,
	},
	24: {
		// Expect {}message registration with Handle to panic
		m: []mux.Option{
			mux.Handle(xml.Name{Local: "message"}, failHandler{}),
		},
		expectPanic: true,
	},
	25: {
		// Expect {jabber:server}message registration with Handle to panic
		m: []mux.Option{
			mux.Handle(xml.Name{Space: ns.Server, Local: "message"}, failHandler{}),
		},
		expectPanic: true,
	},
	26: {
		// Expect {jabber:server}message registration with Handle to panic
		m: []mux.Option{
			mux.Handle(xml.Name{Space: ns.Client, Local: "message"}, failHandler{}),
		},
		expectPanic: true,
	},
	27: {
		// Expect {}presence registration with Handle to panic
		m: []mux.Option{
			mux.Handle(xml.Name{Local: "presence"}, failHandler{}),
		},
		expectPanic: true,
	},
	28: {
		// Expect {jabber:server}presence registration with Handle to panic
		m: []mux.Option{
			mux.Handle(xml.Name{Space: ns.Server, Local: "presence"}, failHandler{}),
		},
		expectPanic: true,
	},
	29: {
		// Expect {jabber:server}presence registration with Handle to panic
		m: []mux.Option{
			mux.Handle(xml.Name{Space: ns.Client, Local: "presence"}, failHandler{}),
		},
		expectPanic: true,
	},
	30: {
		// Expect {}iq registration with Handle to panic
		m: []mux.Option{
			mux.Handle(xml.Name{Local: "iq"}, failHandler{}),
		},
		expectPanic: true,
	},
	31: {
		// Expect {jabber:server}iq registration with Handle to panic
		m: []mux.Option{
			mux.Handle(xml.Name{Space: ns.Server, Local: "iq"}, failHandler{}),
		},
		expectPanic: true,
	},
	32: {
		// Expect {jabber:server}iq registration with Handle to panic
		m: []mux.Option{
			mux.Handle(xml.Name{Space: ns.Client, Local: "iq"}, failHandler{}),
		},
		expectPanic: true,
	},
	33: {
		// If no exact match is available, fallback to the namespace wildcard
		// handler.
		m: []mux.Option{
			mux.Message(stanza.ChatMessage, xml.Name{Local: "test", Space: ""}, passHandler{}),
			mux.Message(stanza.ChatMessage, xml.Name{Local: "", Space: exampleNS}, failHandler{}),
		},
		x:   `<message type="chat" xmlns="jabber:client"><test xmlns="com.example"/></message>`,
		err: errPassTest,
	},
	34: {
		// If no exact match or namespace handler is available, fallback local name
		// handler.
		m: []mux.Option{
			mux.Message(stanza.ChatMessage, xml.Name{Local: "", Space: exampleNS}, passHandler{}),
			mux.Message(stanza.NormalMessage, xml.Name{Local: "", Space: exampleNS}, failHandler{}),
		},
		x:   `<message type="chat" xmlns="jabber:client"><test xmlns="com.example"/></message>`,
		err: errPassTest,
	},
	35: {
		// If no exact match or localname/namespace wildcard is available, fallback
		// to just matching on type alone.
		m: []mux.Option{
			mux.Message(stanza.NormalMessage, xml.Name{Local: "test", Space: exampleNS}, failHandler{}),
			mux.Message(stanza.ChatMessage, xml.Name{}, passHandler{}),
		},
		x:   `<message type="chat" xmlns="jabber:client"><test xmlns="com.example"/></message>`,
		err: errPassTest,
	},
	36: {
		// If no exact match is available, fallback to the namespace wildcard
		// handler.
		m: []mux.Option{
			mux.Presence(stanza.SubscribePresence, xml.Name{Local: "test", Space: ""}, passHandler{}),
			mux.Presence(stanza.SubscribePresence, xml.Name{Local: "", Space: exampleNS}, failHandler{}),
		},
		x:   `<presence type="subscribe" xmlns="jabber:client"><test xmlns="com.example"/></presence>`,
		err: errPassTest,
	},
	37: {
		// If no exact match or namespace handler is available, fallback local name
		// handler.
		m: []mux.Option{
			mux.Presence(stanza.SubscribePresence, xml.Name{Local: "", Space: exampleNS}, passHandler{}),
			mux.Presence(stanza.SubscribedPresence, xml.Name{Local: "", Space: exampleNS}, failHandler{}),
		},
		x:   `<presence type="subscribe" xmlns="jabber:client"><test xmlns="com.example"/></presence>`,
		err: errPassTest,
	},
	38: {
		// If no exact match or localname/namespace wildcard is available, fallback
		// to just matching on type alone.
		m: []mux.Option{
			mux.Presence(stanza.SubscribedPresence, xml.Name{Local: "test", Space: exampleNS}, failHandler{}),
			mux.Presence(stanza.SubscribePresence, xml.Name{}, passHandler{}),
		},
		x:   `<presence type="subscribe" xmlns="jabber:client"><test xmlns="com.example"/></presence>`,
		err: errPassTest,
	},
	39: {
		// Test that multiple handlers can run correctly for presence.
		m: []mux.Option{
			mux.Presence(stanza.SubscribePresence, xml.Name{Local: "test", Space: exampleNS}, multiHandler{}),
			mux.Presence(stanza.SubscribePresence, xml.Name{Local: "example", Space: exampleNS}, multiHandler{}),
		},
		x:   `<presence type="subscribe" xmlns="jabber:client"><example xmlns="com.example">example</example><test xmlns="com.example">test</test></presence>`,
		err: errors.New("mux_test: PASSED, mux_test: PASSED"),
	},
	40: {
		// Test that multiple handlers can run correctly for messages.
		m: []mux.Option{
			mux.Message(stanza.NormalMessage, xml.Name{Local: "test", Space: exampleNS}, multiHandler{}),
			mux.Message(stanza.NormalMessage, xml.Name{Local: "example", Space: exampleNS}, multiHandler{}),
		},
		x:        `<message type="normal" xmlns="jabber:server"><test xmlns="com.example">test</test><example xmlns="com.example">example</example></message>`,
		err:      errors.New("mux_test: PASSED, mux_test: PASSED"),
		stanzaNS: ns.Server,
	},
	41: {
		m: []mux.Option{
			mux.Message(stanza.ChatMessage, xml.Name{}, decodeHandler{}),
		},
		x:   `<message xmlns='jabber:client' type='chat'/>`,
		err: errPassTest,
	},
	42: {
		// An empty IQ is illegal and should result in EOF.
		m: []mux.Option{
			mux.IQ(stanza.GetIQ, xml.Name{}, failHandler{}),
			mux.IQ(stanza.SetIQ, xml.Name{}, failHandler{}),
			mux.Presence(stanza.AvailablePresence, xml.Name{}, failHandler{}),
		},
		x:   `<iq xml:lang="en-us" type="get" xmlns="jabber:client"></iq>`,
		err: io.EOF,
	},
}

type nopEncoder struct {
	xml.TokenReader
}

func (nopEncoder) Encode(interface{}) error                          { return nil }
func (nopEncoder) EncodeElement(interface{}, xml.StartElement) error { return nil }
func (nopEncoder) EncodeToken(xml.Token) error                       { return nil }

func TestMux(t *testing.T) {
	for i, tc := range testCases {
		t.Run(strconv.Itoa(i), func(t *testing.T) {
			if tc.expectPanic {
				defer func() {
					r := recover()
					if r == nil {
						t.Error("Expected panic")
					}
				}()
			}
			stanzaNS := tc.stanzaNS
			if stanzaNS == "" {
				stanzaNS = ns.Client
			}
			m := mux.New(stanzaNS, tc.m...)
			d := xml.NewDecoder(strings.NewReader(tc.x))
			tok, _ := d.Token()
			start, ok := tok.(xml.StartElement)
			if !ok {
				t.Fatalf("did not get start element, got token %v of type %[1]T", tok)
			}

			err := m.HandleXMPP(nopEncoder{TokenReader: d}, &start)
			switch {
			case tc.err == nil && err != nil:
				t.Fatalf("unexpected error: %v", err)
			case tc.err != nil && err == nil:
				t.Fatalf("got nil error but expected %v", tc.err)
			case tc.err == nil && err == nil:
				// All good
			case tc.err.Error() != err.Error():
				t.Fatalf("unexpected error: want=%v, got=%v", tc.err.Error(), err.Error())
			}
		})
	}
}

type testEncoder struct {
	xml.TokenReader
	xmlstream.TokenWriter
}

func (e testEncoder) Encode(v interface{}) error {
	return marshal.EncodeXML(e.TokenWriter, v)
}
func (e testEncoder) EncodeElement(v interface{}, start xml.StartElement) error {
	return marshal.EncodeXMLElement(e.TokenWriter, v, start)
}

func TestFallback(t *testing.T) {
	buf := &bytes.Buffer{}
	rw := struct {
		io.Reader
		io.Writer
	}{
		Reader: strings.NewReader(`<iq xmlns="jabber:client" to="romeo@example.com" from="juliet@example.com" id="123"><test/></iq>`),
		Writer: buf,
	}
	s := xmpptest.NewClientSession(0, rw)

	r := s.TokenReader()
	defer r.Close()
	tok, err := r.Token()
	if err != nil {
		t.Fatalf("Bad start token read: `%v'", err)
	}
	start := tok.(xml.StartElement)
	w := s.TokenWriter()
	defer w.Close()
	err = mux.New(ns.Client).HandleXMPP(testEncoder{
		TokenReader: r,
		TokenWriter: w,
	}, &start)
	if err != nil {
		t.Errorf("Unexpected error: `%v'", err)
	}
	if err := w.Flush(); err != nil {
		t.Errorf("Unexpected error flushing token writer: %q", err)
	}

	const expected = `<iq xmlns="jabber:client" type="error" to="juliet@example.com" from="romeo@example.com" id="123"><error type="cancel"><service-unavailable xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"></service-unavailable></error></iq>`
	if buf.String() != expected {
		t.Errorf("Bad output:\nwant=`%v'\n got=`%v'", expected, buf.String())
	}
}

func TestLazyServeMuxMapInitialization(t *testing.T) {
	m := &mux.ServeMux{}

	// This will panic if the map isn't initialized lazily.
	mux.Handle(xml.Name{}, failHandler{})(m)
	mux.IQ(stanza.GetIQ, xml.Name{}, failHandler{})(m)
	mux.Message(stanza.NormalMessage, xml.Name{}, failHandler{})(m)
	mux.Presence(stanza.SubscribePresence, xml.Name{}, failHandler{})(m)
}

const (
	testFeature         = "urn:example"
	iqTestFeature       = "urn:example:iq"
	msgTestFeature      = "urn:example:message"
	presenceTestFeature = "urn:example:presence"
)

type handleFeature struct{}

func (handleFeature) HandleXMPP(xmlstream.TokenReadEncoder, *xml.StartElement) error {
	panic("should not be called")
}

func (handleFeature) ForFeatures(node string, f func(info.Feature) error) error {
	return f(info.Feature{
		Var: testFeature,
	})
}

func (handleFeature) ForItems(node string, f func(items.Item) error) error {
	return f(items.Item{
		Name: testFeature,
	})
}

type iqFeature struct{}

func (iqFeature) HandleIQ(stanza.IQ, xmlstream.TokenReadEncoder, *xml.StartElement) error {
	panic("should not be called")
}

func (iqFeature) ForFeatures(node string, f func(info.Feature) error) error {
	return f(info.Feature{
		Var: iqTestFeature,
	})
}

func (iqFeature) ForItems(node string, f func(items.Item) error) error {
	return f(items.Item{
		Name: iqTestFeature,
	})
}

type messageFeature struct{}

func (messageFeature) HandleMessage(stanza.Message, xmlstream.TokenReadEncoder) error {
	panic("should not be called")
}

func (messageFeature) ForFeatures(node string, f func(info.Feature) error) error {
	return f(info.Feature{
		Var: msgTestFeature,
	})
}

func (messageFeature) ForItems(node string, f func(items.Item) error) error {
	return f(items.Item{
		Name: msgTestFeature,
	})
}

type presenceFeature struct{}

func (presenceFeature) HandlePresence(stanza.Presence, xmlstream.TokenReadEncoder) error {
	panic("should not be called")
}

func (presenceFeature) ForFeatures(node string, f func(info.Feature) error) error {
	return f(info.Feature{
		Var: presenceTestFeature,
	})
}

func (presenceFeature) ForItems(node string, f func(items.Item) error) error {
	return f(items.Item{
		Name: presenceTestFeature,
	})
}

func TestFeatures(t *testing.T) {
	m := mux.New(
		ns.Client,
		mux.Handle(xml.Name{}, handleFeature{}),
		mux.IQ("", xml.Name{}, iqFeature{}),
		mux.Message("", xml.Name{}, messageFeature{}),
		mux.Presence("", xml.Name{}, presenceFeature{}),
	)
	var (
		foundHandler  bool
		foundIQ       bool
		foundPresence bool
		foundMsg      bool
	)
	err := m.ForFeatures("", func(i info.Feature) error {
		switch i.Var {
		case testFeature:
			foundHandler = true
		case iqTestFeature:
			foundIQ = true
		case msgTestFeature:
			foundMsg = true
		case presenceTestFeature:
			foundPresence = true
		}
		return nil
	})
	if err != nil {
		t.Fatalf("unexpected error while iterating over features: %v", err)
	}
	if !foundHandler {
		t.Errorf("features iter did not find plain handler feature")
	}
	if !foundIQ {
		t.Errorf("features iter did not find IQ feature")
	}
	if !foundMsg {
		t.Errorf("features iter did not find message feature")
	}
	if !foundPresence {
		t.Errorf("features iter did not find presence feature")
	}
}

func TestItems(t *testing.T) {
	m := mux.New(
		ns.Client,
		mux.Handle(xml.Name{}, handleFeature{}),
		mux.IQ("", xml.Name{}, iqFeature{}),
		mux.Message("", xml.Name{}, messageFeature{}),
		mux.Presence("", xml.Name{}, presenceFeature{}),
	)
	var (
		foundHandler  bool
		foundIQ       bool
		foundPresence bool
		foundMsg      bool
	)
	err := m.ForItems("", func(i items.Item) error {
		switch i.Name {
		case testFeature:
			foundHandler = true
		case iqTestFeature:
			foundIQ = true
		case msgTestFeature:
			foundMsg = true
		case presenceTestFeature:
			foundPresence = true
		}
		return nil
	})
	if err != nil {
		t.Fatalf("unexpected error while iterating over features: %v", err)
	}
	if !foundHandler {
		t.Errorf("items iter did not find plain handler item")
	}
	if !foundIQ {
		t.Errorf("items iter did not find IQ item")
	}
	if !foundMsg {
		t.Errorf("items iter did not find message item")
	}
	if !foundPresence {
		t.Errorf("items iter did not find presence item")
	}
}

func TestFeaturesHandlerErr(t *testing.T) {
	m := mux.New(
		ns.Client,
		mux.Handle(xml.Name{}, handleFeature{}),
	)
	err := m.ForFeatures("", func(i info.Feature) error {
		return io.EOF
	})
	if err != io.EOF {
		t.Fatalf("wrong error: want=%v, got=%v", io.EOF, err)
	}
}

func TestFeaturesHandleIQErr(t *testing.T) {
	m := mux.New(
		ns.Client,
		mux.IQ("", xml.Name{}, iqFeature{}),
	)
	err := m.ForFeatures("", func(i info.Feature) error {
		return io.EOF
	})
	if err != io.EOF {
		t.Fatalf("wrong error: want=%v, got=%v", io.EOF, err)
	}
}
func TestFeaturesHandleMsgErr(t *testing.T) {
	m := mux.New(
		ns.Client,
		mux.Message("", xml.Name{}, messageFeature{}),
	)
	err := m.ForFeatures("", func(i info.Feature) error {
		return io.EOF
	})
	if err != io.EOF {
		t.Fatalf("wrong error: want=%v, got=%v", io.EOF, err)
	}
}
func TestFeaturesHandlePresenceErr(t *testing.T) {
	m := mux.New(
		ns.Client,
		mux.Presence("", xml.Name{}, presenceFeature{}),
	)
	err := m.ForFeatures("", func(i info.Feature) error {
		return io.EOF
	})
	if err != io.EOF {
		t.Fatalf("wrong error: want=%v, got=%v", io.EOF, err)
	}
}

func TestItemsHandlerErr(t *testing.T) {
	m := mux.New(
		ns.Client,
		mux.Handle(xml.Name{}, handleFeature{}),
	)
	err := m.ForItems("", func(i items.Item) error {
		return io.EOF
	})
	if err != io.EOF {
		t.Fatalf("wrong error: want=%v, got=%v", io.EOF, err)
	}
}
func TestItemsHandleIQErr(t *testing.T) {
	m := mux.New(
		ns.Client,
		mux.IQ("", xml.Name{}, iqFeature{}),
	)
	err := m.ForItems("", func(i items.Item) error {
		return io.EOF
	})
	if err != io.EOF {
		t.Fatalf("wrong error: want=%v, got=%v", io.EOF, err)
	}
}
func TestItemsHandleMsgErr(t *testing.T) {
	m := mux.New(
		ns.Client,
		mux.Message("", xml.Name{}, messageFeature{}),
	)
	err := m.ForItems("", func(i items.Item) error {
		return io.EOF
	})
	if err != io.EOF {
		t.Fatalf("wrong error: want=%v, got=%v", io.EOF, err)
	}
}
func TestItemsHandlePresenceErr(t *testing.T) {
	m := mux.New(
		ns.Client,
		mux.Presence("", xml.Name{}, presenceFeature{}),
	)
	err := m.ForItems("", func(i items.Item) error {
		return io.EOF
	})
	if err != io.EOF {
		t.Fatalf("wrong error: want=%v, got=%v", io.EOF, err)
	}
}