sleektest.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. """
  2. SleekXMPP: The Sleek XMPP Library
  3. Copyright (C) 2010 Nathanael C. Fritz, Lance J.T. Stout
  4. This file is part of SleekXMPP.
  5. See the file LICENSE for copying permission.
  6. """
  7. import unittest
  8. from xml.parsers.expat import ExpatError
  9. from sleekxmpp import ClientXMPP, ComponentXMPP
  10. from sleekxmpp.util import Queue
  11. from sleekxmpp.stanza import Message, Iq, Presence
  12. from sleekxmpp.test import TestSocket, TestLiveSocket
  13. from sleekxmpp.xmlstream import ET
  14. from sleekxmpp.xmlstream import ElementBase
  15. from sleekxmpp.xmlstream.tostring import tostring
  16. from sleekxmpp.xmlstream.matcher import StanzaPath, MatcherId, MatchIDSender
  17. from sleekxmpp.xmlstream.matcher import MatchXMLMask, MatchXPath
  18. class SleekTest(unittest.TestCase):
  19. """
  20. A SleekXMPP specific TestCase class that provides
  21. methods for comparing message, iq, and presence stanzas.
  22. Methods:
  23. Message -- Create a Message stanza object.
  24. Iq -- Create an Iq stanza object.
  25. Presence -- Create a Presence stanza object.
  26. check_jid -- Check a JID and its component parts.
  27. check -- Compare a stanza against an XML string.
  28. stream_start -- Initialize a dummy XMPP client.
  29. stream_close -- Disconnect the XMPP client.
  30. make_header -- Create a stream header.
  31. send_header -- Check that the given header has been sent.
  32. send_feature -- Send a raw XML element.
  33. send -- Check that the XMPP client sent the given
  34. generic stanza.
  35. recv -- Queue data for XMPP client to receive, or
  36. verify the data that was received from a
  37. live connection.
  38. recv_header -- Check that a given stream header
  39. was received.
  40. recv_feature -- Check that a given, raw XML element
  41. was recveived.
  42. fix_namespaces -- Add top-level namespace to an XML object.
  43. compare -- Compare XML objects against each other.
  44. """
  45. def __init__(self, *args, **kwargs):
  46. unittest.TestCase.__init__(self, *args, **kwargs)
  47. self.xmpp = None
  48. def parse_xml(self, xml_string):
  49. try:
  50. xml = ET.fromstring(xml_string)
  51. return xml
  52. except (SyntaxError, ExpatError) as e:
  53. msg = e.msg if hasattr(e, 'msg') else e.message
  54. if 'unbound' in msg:
  55. known_prefixes = {
  56. 'stream': 'http://etherx.jabber.org/streams'}
  57. prefix = xml_string.split('<')[1].split(':')[0]
  58. if prefix in known_prefixes:
  59. xml_string = '<fixns xmlns:%s="%s">%s</fixns>' % (
  60. prefix,
  61. known_prefixes[prefix],
  62. xml_string)
  63. xml = self.parse_xml(xml_string)
  64. xml = list(xml)[0]
  65. return xml
  66. else:
  67. self.fail("XML data was mal-formed:\n%s" % xml_string)
  68. # ------------------------------------------------------------------
  69. # Shortcut methods for creating stanza objects
  70. def Message(self, *args, **kwargs):
  71. """
  72. Create a Message stanza.
  73. Uses same arguments as StanzaBase.__init__
  74. Arguments:
  75. xml -- An XML object to use for the Message's values.
  76. """
  77. return Message(self.xmpp, *args, **kwargs)
  78. def Iq(self, *args, **kwargs):
  79. """
  80. Create an Iq stanza.
  81. Uses same arguments as StanzaBase.__init__
  82. Arguments:
  83. xml -- An XML object to use for the Iq's values.
  84. """
  85. return Iq(self.xmpp, *args, **kwargs)
  86. def Presence(self, *args, **kwargs):
  87. """
  88. Create a Presence stanza.
  89. Uses same arguments as StanzaBase.__init__
  90. Arguments:
  91. xml -- An XML object to use for the Iq's values.
  92. """
  93. return Presence(self.xmpp, *args, **kwargs)
  94. def check_jid(self, jid, user=None, domain=None, resource=None,
  95. bare=None, full=None, string=None):
  96. """
  97. Verify the components of a JID.
  98. Arguments:
  99. jid -- The JID object to test.
  100. user -- Optional. The user name portion of the JID.
  101. domain -- Optional. The domain name portion of the JID.
  102. resource -- Optional. The resource portion of the JID.
  103. bare -- Optional. The bare JID.
  104. full -- Optional. The full JID.
  105. string -- Optional. The string version of the JID.
  106. """
  107. if user is not None:
  108. self.assertEqual(jid.user, user,
  109. "User does not match: %s" % jid.user)
  110. if domain is not None:
  111. self.assertEqual(jid.domain, domain,
  112. "Domain does not match: %s" % jid.domain)
  113. if resource is not None:
  114. self.assertEqual(jid.resource, resource,
  115. "Resource does not match: %s" % jid.resource)
  116. if bare is not None:
  117. self.assertEqual(jid.bare, bare,
  118. "Bare JID does not match: %s" % jid.bare)
  119. if full is not None:
  120. self.assertEqual(jid.full, full,
  121. "Full JID does not match: %s" % jid.full)
  122. if string is not None:
  123. self.assertEqual(str(jid), string,
  124. "String does not match: %s" % str(jid))
  125. def check_roster(self, owner, jid, name=None, subscription=None,
  126. afrom=None, ato=None, pending_out=None, pending_in=None,
  127. groups=None):
  128. roster = self.xmpp.roster[owner][jid]
  129. if name is not None:
  130. self.assertEqual(roster['name'], name,
  131. "Incorrect name value: %s" % roster['name'])
  132. if subscription is not None:
  133. self.assertEqual(roster['subscription'], subscription,
  134. "Incorrect subscription: %s" % roster['subscription'])
  135. if afrom is not None:
  136. self.assertEqual(roster['from'], afrom,
  137. "Incorrect from state: %s" % roster['from'])
  138. if ato is not None:
  139. self.assertEqual(roster['to'], ato,
  140. "Incorrect to state: %s" % roster['to'])
  141. if pending_out is not None:
  142. self.assertEqual(roster['pending_out'], pending_out,
  143. "Incorrect pending_out state: %s" % roster['pending_out'])
  144. if pending_in is not None:
  145. self.assertEqual(roster['pending_in'], pending_out,
  146. "Incorrect pending_in state: %s" % roster['pending_in'])
  147. if groups is not None:
  148. self.assertEqual(roster['groups'], groups,
  149. "Incorrect groups: %s" % roster['groups'])
  150. # ------------------------------------------------------------------
  151. # Methods for comparing stanza objects to XML strings
  152. def check(self, stanza, criteria, method='exact',
  153. defaults=None, use_values=True):
  154. """
  155. Create and compare several stanza objects to a correct XML string.
  156. If use_values is False, tests using stanza.values will not be used.
  157. Some stanzas provide default values for some interfaces, but
  158. these defaults can be problematic for testing since they can easily
  159. be forgotten when supplying the XML string. A list of interfaces that
  160. use defaults may be provided and the generated stanzas will use the
  161. default values for those interfaces if needed.
  162. However, correcting the supplied XML is not possible for interfaces
  163. that add or remove XML elements. Only interfaces that map to XML
  164. attributes may be set using the defaults parameter. The supplied XML
  165. must take into account any extra elements that are included by default.
  166. Arguments:
  167. stanza -- The stanza object to test.
  168. criteria -- An expression the stanza must match against.
  169. method -- The type of matching to use; one of:
  170. 'exact', 'mask', 'id', 'xpath', and 'stanzapath'.
  171. Defaults to the value of self.match_method.
  172. defaults -- A list of stanza interfaces that have default
  173. values. These interfaces will be set to their
  174. defaults for the given and generated stanzas to
  175. prevent unexpected test failures.
  176. use_values -- Indicates if testing using stanza.values should
  177. be used. Defaults to True.
  178. """
  179. if method is None and hasattr(self, 'match_method'):
  180. method = getattr(self, 'match_method')
  181. if method != 'exact':
  182. matchers = {'stanzapath': StanzaPath,
  183. 'xpath': MatchXPath,
  184. 'mask': MatchXMLMask,
  185. 'idsender': MatchIDSender,
  186. 'id': MatcherId}
  187. Matcher = matchers.get(method, None)
  188. if Matcher is None:
  189. raise ValueError("Unknown matching method.")
  190. test = Matcher(criteria)
  191. self.failUnless(test.match(stanza),
  192. "Stanza did not match using %s method:\n" % method + \
  193. "Criteria:\n%s\n" % str(criteria) + \
  194. "Stanza:\n%s" % str(stanza))
  195. else:
  196. stanza_class = stanza.__class__
  197. if not isinstance(criteria, ElementBase):
  198. xml = self.parse_xml(criteria)
  199. else:
  200. xml = criteria.xml
  201. # Ensure that top level namespaces are used, even if they
  202. # were not provided.
  203. self.fix_namespaces(stanza.xml, 'jabber:client')
  204. self.fix_namespaces(xml, 'jabber:client')
  205. stanza2 = stanza_class(xml=xml)
  206. if use_values:
  207. # Using stanza.values will add XML for any interface that
  208. # has a default value. We need to set those defaults on
  209. # the existing stanzas and XML so that they will compare
  210. # correctly.
  211. default_stanza = stanza_class()
  212. if defaults is None:
  213. known_defaults = {
  214. Message: ['type'],
  215. Presence: ['priority']
  216. }
  217. defaults = known_defaults.get(stanza_class, [])
  218. for interface in defaults:
  219. stanza[interface] = stanza[interface]
  220. stanza2[interface] = stanza2[interface]
  221. # Can really only automatically add defaults for top
  222. # level attribute values. Anything else must be accounted
  223. # for in the provided XML string.
  224. if interface not in xml.attrib:
  225. if interface in default_stanza.xml.attrib:
  226. value = default_stanza.xml.attrib[interface]
  227. xml.attrib[interface] = value
  228. values = stanza2.values
  229. stanza3 = stanza_class()
  230. stanza3.values = values
  231. debug = "Three methods for creating stanzas do not match.\n"
  232. debug += "Given XML:\n%s\n" % tostring(xml)
  233. debug += "Given stanza:\n%s\n" % tostring(stanza.xml)
  234. debug += "Generated stanza:\n%s\n" % tostring(stanza2.xml)
  235. debug += "Second generated stanza:\n%s\n" % tostring(stanza3.xml)
  236. result = self.compare(xml, stanza.xml, stanza2.xml, stanza3.xml)
  237. else:
  238. debug = "Two methods for creating stanzas do not match.\n"
  239. debug += "Given XML:\n%s\n" % tostring(xml)
  240. debug += "Given stanza:\n%s\n" % tostring(stanza.xml)
  241. debug += "Generated stanza:\n%s\n" % tostring(stanza2.xml)
  242. result = self.compare(xml, stanza.xml, stanza2.xml)
  243. self.failUnless(result, debug)
  244. # ------------------------------------------------------------------
  245. # Methods for simulating stanza streams.
  246. def stream_disconnect(self):
  247. """
  248. Simulate a stream disconnection.
  249. """
  250. if self.xmpp:
  251. self.xmpp.socket.disconnect_error()
  252. def stream_start(self, mode='client', skip=True, header=None, socket='mock', jid='tester@localhost',
  253. password='test', server='localhost', port=5222, sasl_mech=None, plugins=None, plugin_config=None):
  254. """
  255. Initialize an XMPP client or component using a dummy XML stream.
  256. Arguments:
  257. mode -- Either 'client' or 'component'. Defaults to 'client'.
  258. skip -- Indicates if the first item in the sent queue (the
  259. stream header) should be removed. Tests that wish
  260. to test initializing the stream should set this to
  261. False. Otherwise, the default of True should be used.
  262. socket -- Either 'mock' or 'live' to indicate if the socket
  263. should be a dummy, mock socket or a live, functioning
  264. socket. Defaults to 'mock'.
  265. jid -- The JID to use for the connection.
  266. Defaults to 'tester@localhost'.
  267. password -- The password to use for the connection.
  268. Defaults to 'test'.
  269. server -- The name of the XMPP server. Defaults to 'localhost'.
  270. port -- The port to use when connecting to the server.
  271. Defaults to 5222.
  272. plugins -- List of plugins to register. By default, all plugins
  273. are loaded.
  274. """
  275. if not plugin_config:
  276. plugin_config = {}
  277. if mode == 'client':
  278. self.xmpp = ClientXMPP(jid, password,
  279. sasl_mech=sasl_mech,
  280. plugin_config=plugin_config)
  281. elif mode == 'component':
  282. self.xmpp = ComponentXMPP(jid, password,
  283. server, port,
  284. plugin_config=plugin_config)
  285. else:
  286. raise ValueError("Unknown XMPP connection mode.")
  287. # Remove unique ID prefix to make it easier to test
  288. self.xmpp._id_prefix = ''
  289. self.xmpp._disconnect_wait_for_threads = False
  290. self.xmpp.default_lang = None
  291. self.xmpp.peer_default_lang = None
  292. # We will use this to wait for the session_start event
  293. # for live connections.
  294. skip_queue = Queue()
  295. if socket == 'mock':
  296. self.xmpp.set_socket(TestSocket())
  297. # Simulate connecting for mock sockets.
  298. self.xmpp.auto_reconnect = False
  299. self.xmpp.state._set_state('connected')
  300. # Must have the stream header ready for xmpp.process() to work.
  301. if not header:
  302. header = self.xmpp.stream_header
  303. self.xmpp.socket.recv_data(header)
  304. elif socket == 'live':
  305. self.xmpp.socket_class = TestLiveSocket
  306. def wait_for_session(x):
  307. self.xmpp.socket.clear()
  308. skip_queue.put('started')
  309. self.xmpp.add_event_handler('session_start', wait_for_session)
  310. if server is not None:
  311. self.xmpp.connect((server, port))
  312. else:
  313. self.xmpp.connect()
  314. else:
  315. raise ValueError("Unknown socket type.")
  316. if plugins is None:
  317. self.xmpp.register_plugins()
  318. else:
  319. for plugin in plugins:
  320. self.xmpp.register_plugin(plugin)
  321. # Some plugins require messages to have ID values. Set
  322. # this to True in tests related to those plugins.
  323. self.xmpp.use_message_ids = False
  324. self.xmpp.process(threaded=True)
  325. if skip:
  326. if socket != 'live':
  327. # Mark send queue as usable
  328. self.xmpp.session_bind_event.set()
  329. self.xmpp.session_started_event.set()
  330. # Clear startup stanzas
  331. self.xmpp.socket.next_sent(timeout=1)
  332. if mode == 'component':
  333. self.xmpp.socket.next_sent(timeout=1)
  334. else:
  335. skip_queue.get(block=True, timeout=10)
  336. def make_header(self, sto='',
  337. sfrom='',
  338. sid='',
  339. stream_ns="http://etherx.jabber.org/streams",
  340. default_ns="jabber:client",
  341. default_lang="en",
  342. version="1.0",
  343. xml_header=True):
  344. """
  345. Create a stream header to be received by the test XMPP agent.
  346. The header must be saved and passed to stream_start.
  347. Arguments:
  348. sto -- The recipient of the stream header.
  349. sfrom -- The agent sending the stream header.
  350. sid -- The stream's id.
  351. stream_ns -- The namespace of the stream's root element.
  352. default_ns -- The default stanza namespace.
  353. version -- The stream version.
  354. xml_header -- Indicates if the XML version header should be
  355. appended before the stream header.
  356. """
  357. header = '<stream:stream %s>'
  358. parts = []
  359. if xml_header:
  360. header = '<?xml version="1.0"?>' + header
  361. if sto:
  362. parts.append('to="%s"' % sto)
  363. if sfrom:
  364. parts.append('from="%s"' % sfrom)
  365. if sid:
  366. parts.append('id="%s"' % sid)
  367. if default_lang:
  368. parts.append('xml:lang="%s"' % default_lang)
  369. parts.append('version="%s"' % version)
  370. parts.append('xmlns:stream="%s"' % stream_ns)
  371. parts.append('xmlns="%s"' % default_ns)
  372. return header % ' '.join(parts)
  373. def recv(self, data, defaults=None, method='exact', use_values=True, timeout=1):
  374. """
  375. Pass data to the dummy XMPP client as if it came from an XMPP server.
  376. If using a live connection, verify what the server has sent.
  377. Arguments:
  378. data -- If a dummy socket is being used, the XML that is to
  379. be received next. Otherwise it is the criteria used
  380. to match against live data that is received.
  381. defaults -- A list of stanza interfaces with default values that
  382. may interfere with comparisons.
  383. method -- Select the type of comparison to use for
  384. verifying the received stanza. Options are 'exact',
  385. 'id', 'stanzapath', 'xpath', and 'mask'.
  386. Defaults to the value of self.match_method.
  387. use_values -- Indicates if stanza comparisons should test using
  388. stanza.values. Defaults to True.
  389. timeout -- Time to wait in seconds for data to be received by
  390. a live connection.
  391. """
  392. if not defaults:
  393. defaults = []
  394. if self.xmpp.socket.is_live:
  395. # we are working with a live connection, so we should
  396. # verify what has been received instead of simulating
  397. # receiving data.
  398. recv_data = self.xmpp.socket.next_recv(timeout)
  399. if recv_data is None:
  400. self.fail("No stanza was received.")
  401. xml = self.parse_xml(recv_data)
  402. self.fix_namespaces(xml, 'jabber:client')
  403. stanza = self.xmpp._build_stanza(xml, 'jabber:client')
  404. self.check(stanza, data,
  405. method=method,
  406. defaults=defaults,
  407. use_values=use_values)
  408. else:
  409. # place the data in the dummy socket receiving queue.
  410. data = str(data)
  411. self.xmpp.socket.recv_data(data)
  412. def recv_header(self, sto='',
  413. sfrom='',
  414. sid='',
  415. stream_ns="http://etherx.jabber.org/streams",
  416. default_ns="jabber:client",
  417. version="1.0",
  418. xml_header=False,
  419. timeout=1):
  420. """
  421. Check that a given stream header was received.
  422. Arguments:
  423. sto -- The recipient of the stream header.
  424. sfrom -- The agent sending the stream header.
  425. sid -- The stream's id. Set to None to ignore.
  426. stream_ns -- The namespace of the stream's root element.
  427. default_ns -- The default stanza namespace.
  428. version -- The stream version.
  429. xml_header -- Indicates if the XML version header should be
  430. appended before the stream header.
  431. timeout -- Length of time to wait in seconds for a
  432. response.
  433. """
  434. header = self.make_header(sto, sfrom, sid,
  435. stream_ns=stream_ns,
  436. default_ns=default_ns,
  437. version=version,
  438. xml_header=xml_header)
  439. recv_header = self.xmpp.socket.next_recv(timeout)
  440. if recv_header is None:
  441. raise ValueError("Socket did not return data.")
  442. # Apply closing elements so that we can construct
  443. # XML objects for comparison.
  444. header2 = header + '</stream:stream>'
  445. recv_header2 = recv_header + '</stream:stream>'
  446. xml = self.parse_xml(header2)
  447. recv_xml = self.parse_xml(recv_header2)
  448. if sid is None:
  449. # Ignore the id sent by the server since
  450. # we can't know in advance what it will be.
  451. if 'id' in recv_xml.attrib:
  452. del recv_xml.attrib['id']
  453. # Ignore the xml:lang attribute for now.
  454. if 'xml:lang' in recv_xml.attrib:
  455. del recv_xml.attrib['xml:lang']
  456. xml_ns = 'http://www.w3.org/XML/1998/namespace'
  457. if '{%s}lang' % xml_ns in recv_xml.attrib:
  458. del recv_xml.attrib['{%s}lang' % xml_ns]
  459. if list(recv_xml):
  460. # We received more than just the header
  461. for xml in recv_xml:
  462. self.xmpp.socket.recv_data(tostring(xml))
  463. attrib = recv_xml.attrib
  464. recv_xml.clear()
  465. recv_xml.attrib = attrib
  466. self.failUnless(
  467. self.compare(xml, recv_xml),
  468. "Stream headers do not match:\nDesired:\n%s\nReceived:\n%s" % (
  469. '%s %s' % (xml.tag, xml.attrib),
  470. '%s %s' % (recv_xml.tag, recv_xml.attrib)))
  471. def recv_feature(self, data, method='mask', use_values=True, timeout=1):
  472. """
  473. """
  474. if method is None and hasattr(self, 'match_method'):
  475. method = getattr(self, 'match_method')
  476. if self.xmpp.socket.is_live:
  477. # we are working with a live connection, so we should
  478. # verify what has been received instead of simulating
  479. # receiving data.
  480. recv_data = self.xmpp.socket.next_recv(timeout)
  481. xml = self.parse_xml(data)
  482. recv_xml = self.parse_xml(recv_data)
  483. if recv_data is None:
  484. self.fail("No stanza was received.")
  485. if method == 'exact':
  486. self.failUnless(self.compare(xml, recv_xml),
  487. "Features do not match.\nDesired:\n%s\nReceived:\n%s" % (
  488. tostring(xml), tostring(recv_xml)))
  489. elif method == 'mask':
  490. matcher = MatchXMLMask(xml)
  491. self.failUnless(matcher.match(recv_xml),
  492. "Stanza did not match using %s method:\n" % method + \
  493. "Criteria:\n%s\n" % tostring(xml) + \
  494. "Stanza:\n%s" % tostring(recv_xml))
  495. else:
  496. raise ValueError("Uknown matching method: %s" % method)
  497. else:
  498. # place the data in the dummy socket receiving queue.
  499. data = str(data)
  500. self.xmpp.socket.recv_data(data)
  501. def send_header(self, sto='',
  502. sfrom='',
  503. sid='',
  504. stream_ns="http://etherx.jabber.org/streams",
  505. default_ns="jabber:client",
  506. default_lang="en",
  507. version="1.0",
  508. xml_header=False,
  509. timeout=1):
  510. """
  511. Check that a given stream header was sent.
  512. Arguments:
  513. sto -- The recipient of the stream header.
  514. sfrom -- The agent sending the stream header.
  515. sid -- The stream's id.
  516. stream_ns -- The namespace of the stream's root element.
  517. default_ns -- The default stanza namespace.
  518. version -- The stream version.
  519. xml_header -- Indicates if the XML version header should be
  520. appended before the stream header.
  521. timeout -- Length of time to wait in seconds for a
  522. response.
  523. """
  524. header = self.make_header(sto, sfrom, sid,
  525. stream_ns=stream_ns,
  526. default_ns=default_ns,
  527. default_lang=default_lang,
  528. version=version,
  529. xml_header=xml_header)
  530. sent_header = self.xmpp.socket.next_sent(timeout)
  531. if sent_header is None:
  532. raise ValueError("Socket did not return data.")
  533. # Apply closing elements so that we can construct
  534. # XML objects for comparison.
  535. header2 = header + '</stream:stream>'
  536. sent_header2 = sent_header + b'</stream:stream>'
  537. xml = self.parse_xml(header2)
  538. sent_xml = self.parse_xml(sent_header2)
  539. self.failUnless(
  540. self.compare(xml, sent_xml),
  541. "Stream headers do not match:\nDesired:\n%s\nSent:\n%s" % (
  542. header, sent_header))
  543. def send_feature(self, data, method='mask', use_values=True, timeout=1):
  544. """
  545. """
  546. sent_data = self.xmpp.socket.next_sent(timeout)
  547. xml = self.parse_xml(data)
  548. sent_xml = self.parse_xml(sent_data)
  549. if sent_data is None:
  550. self.fail("No stanza was sent.")
  551. if method == 'exact':
  552. self.failUnless(self.compare(xml, sent_xml),
  553. "Features do not match.\nDesired:\n%s\nReceived:\n%s" % (
  554. tostring(xml), tostring(sent_xml)))
  555. elif method == 'mask':
  556. matcher = MatchXMLMask(xml)
  557. self.failUnless(matcher.match(sent_xml),
  558. "Stanza did not match using %s method:\n" % method + \
  559. "Criteria:\n%s\n" % tostring(xml) + \
  560. "Stanza:\n%s" % tostring(sent_xml))
  561. else:
  562. raise ValueError("Uknown matching method: %s" % method)
  563. def send(self, data, defaults=None, use_values=True,
  564. timeout=.5, method='exact'):
  565. """
  566. Check that the XMPP client sent the given stanza XML.
  567. Extracts the next sent stanza and compares it with the given
  568. XML using check.
  569. Arguments:
  570. stanza_class -- The class of the sent stanza object.
  571. data -- The XML string of the expected Message stanza,
  572. or an equivalent stanza object.
  573. use_values -- Modifies the type of tests used by check_message.
  574. defaults -- A list of stanza interfaces that have defaults
  575. values which may interfere with comparisons.
  576. timeout -- Time in seconds to wait for a stanza before
  577. failing the check.
  578. method -- Select the type of comparison to use for
  579. verifying the sent stanza. Options are 'exact',
  580. 'id', 'stanzapath', 'xpath', and 'mask'.
  581. Defaults to the value of self.match_method.
  582. """
  583. sent = self.xmpp.socket.next_sent(timeout)
  584. if data is None and sent is None:
  585. return
  586. if data is None and sent is not None:
  587. self.fail("Stanza data was sent: %s" % sent)
  588. if sent is None:
  589. self.fail("No stanza was sent.")
  590. xml = self.parse_xml(sent)
  591. self.fix_namespaces(xml, 'jabber:client')
  592. sent = self.xmpp._build_stanza(xml, 'jabber:client')
  593. self.check(sent, data,
  594. method=method,
  595. defaults=defaults,
  596. use_values=use_values)
  597. def stream_close(self):
  598. """
  599. Disconnect the dummy XMPP client.
  600. Can be safely called even if stream_start has not been called.
  601. Must be placed in the tearDown method of a test class to ensure
  602. that the XMPP client is disconnected after an error.
  603. """
  604. if hasattr(self, 'xmpp') and self.xmpp is not None:
  605. self.xmpp.socket.recv_data(self.xmpp.stream_footer)
  606. self.xmpp.disconnect()
  607. # ------------------------------------------------------------------
  608. # XML Comparison and Cleanup
  609. def fix_namespaces(self, xml, ns):
  610. """
  611. Assign a namespace to an element and any children that
  612. don't have a namespace.
  613. Arguments:
  614. xml -- The XML object to fix.
  615. ns -- The namespace to add to the XML object.
  616. """
  617. if xml.tag.startswith('{'):
  618. return
  619. xml.tag = '{%s}%s' % (ns, xml.tag)
  620. for child in xml:
  621. self.fix_namespaces(child, ns)
  622. def compare(self, xml, *other):
  623. """
  624. Compare XML objects.
  625. Arguments:
  626. xml -- The XML object to compare against.
  627. *other -- The list of XML objects to compare.
  628. """
  629. if not other:
  630. return False
  631. # Compare multiple objects
  632. if len(other) > 1:
  633. for xml2 in other:
  634. if not self.compare(xml, xml2):
  635. return False
  636. return True
  637. other = other[0]
  638. # Step 1: Check tags
  639. if xml.tag != other.tag:
  640. return False
  641. # Step 2: Check attributes
  642. if xml.attrib != other.attrib:
  643. return False
  644. # Step 3: Check text
  645. if xml.text is None:
  646. xml.text = ""
  647. if other.text is None:
  648. other.text = ""
  649. xml.text = xml.text.strip()
  650. other.text = other.text.strip()
  651. if xml.text != other.text:
  652. return False
  653. # Step 4: Check children count
  654. if len(list(xml)) != len(list(other)):
  655. return False
  656. # Step 5: Recursively check children
  657. for child in xml:
  658. child2s = other.findall("%s" % child.tag)
  659. if child2s is None:
  660. return False
  661. for child2 in child2s:
  662. if self.compare(child, child2):
  663. break
  664. else:
  665. return False
  666. # Step 6: Recursively check children the other way.
  667. for child in other:
  668. child2s = xml.findall("%s" % child.tag)
  669. if child2s is None:
  670. return False
  671. for child2 in child2s:
  672. if self.compare(child, child2):
  673. break
  674. else:
  675. return False
  676. # Everything matches
  677. return True