1 | # Copyright (c) 2003-2008 Ralph Meijer |
---|
2 | # See LICENSE for details. |
---|
3 | |
---|
4 | """ |
---|
5 | Unit test helpers. |
---|
6 | """ |
---|
7 | |
---|
8 | from twisted.words.xish.utility import EventDispatcher |
---|
9 | |
---|
10 | class XmlStreamStub(object): |
---|
11 | """ |
---|
12 | Stub for testing objects that communicate through XML Streams. |
---|
13 | |
---|
14 | Instances of this stub hold an object in L{xmlstream} that acts like an |
---|
15 | L{XmlStream<twisted.words.xish.xmlstream.XmlStream} after connection stream |
---|
16 | initialization. Stanzas can be sent through it by calling its C{send} |
---|
17 | method with an object implementing |
---|
18 | L{IElement<twisted.words.xish.domish.IElement>} as its first argument. |
---|
19 | These appear in sequence in the L{output} instance variable of the stub. |
---|
20 | |
---|
21 | For the reverse direction, stanzas passed to L{send} of the stub, will be |
---|
22 | dispatched in the stubbed XmlStream as if it was received over the wire, so |
---|
23 | that registered observers will be called. |
---|
24 | |
---|
25 | Example: |
---|
26 | |
---|
27 | >>> stub = XmlStreamStub() |
---|
28 | >>> stub.xmlstream.send(domish.Element((None, 'presence'))) |
---|
29 | >>> stub.output[-1].toXml() |
---|
30 | u'<presence/>' |
---|
31 | >>> def cb(stanza): |
---|
32 | ... print "Got: %r" stanza.toXml() |
---|
33 | >>> stub.xmlstream.addObserver('/presence') |
---|
34 | >>> stub.send(domish.Element((None, 'presence'))) |
---|
35 | Got: u'<presence/>' |
---|
36 | |
---|
37 | @ivar xmlstream: Stubbed XML Stream. |
---|
38 | @type xmlstream: L{EventDispatcher} |
---|
39 | @ivar output: List of stanzas sent to the XML Stream. |
---|
40 | @type output: L{list} |
---|
41 | """ |
---|
42 | |
---|
43 | def __init__(self): |
---|
44 | self.output = [] |
---|
45 | self.xmlstream = EventDispatcher() |
---|
46 | self.xmlstream.send = self.output.append |
---|
47 | |
---|
48 | def send(self, obj): |
---|
49 | """ |
---|
50 | Pass an element to the XML Stream as if received. |
---|
51 | |
---|
52 | @param obj: Element to be dispatched to C{self.xmlstream}. |
---|
53 | @type obj: object implementing |
---|
54 | L{IElement<twisted.words.xish.domish.IElement>}. |
---|
55 | """ |
---|
56 | self.xmlstream.dispatch(obj) |
---|