examples, tests: Replace all @asyncio.coroutines with proper async functions.

This commit is contained in:
Emmanuel Gil Peyrot 2018-08-19 17:47:26 +01:00
parent 35fa33e3c2
commit 9f6fa65139
13 changed files with 58 additions and 71 deletions

View file

@ -51,18 +51,17 @@ class AskConfirm(slixmpp.ClientXMPP):
else:
self.confirmed.set_result(True)
@asyncio.coroutine
def start(self, event):
async def start(self, event):
log.info('Sending confirm request %s to %s who wants to access %s using '
'method %s...' % (self.id, self.recipient, self.url, self.method))
try:
confirmed = yield from self['xep_0070'].ask_confirm(self.recipient,
confirmed = await self['xep_0070'].ask_confirm(self.recipient,
id=self.id,
url=self.url,
method=self.method,
message='Plz say yes or no for {method} {url} ({id}).')
if isinstance(confirmed, slixmpp.Message):
confirmed = yield from self.confirmed
confirmed = await self.confirmed
else:
confirmed = True
except IqError:

View file

@ -54,8 +54,7 @@ class Disco(slixmpp.ClientXMPP):
# our roster.
self.add_event_handler("session_start", self.start)
@asyncio.coroutine
def start(self, event):
async def start(self, event):
"""
Process the session_start event.
@ -77,13 +76,13 @@ class Disco(slixmpp.ClientXMPP):
try:
if self.get in self.info_types:
# function using the callback parameter.
info = yield from self['xep_0030'].get_info(jid=self.target_jid,
info = await self['xep_0030'].get_info(jid=self.target_jid,
node=self.target_node)
if self.get in self.items_types:
# The same applies from above. Listen for the
# disco_items event or pass a callback function
# if you need to process a non-blocking request.
items = yield from self['xep_0030'].get_items(jid=self.target_jid,
items = await self['xep_0030'].get_items(jid=self.target_jid,
node=self.target_node)
if self.get not in self.info_types and self.get not in self.items_types:
logging.error("Invalid disco request type.")

View file

@ -47,8 +47,7 @@ class AvatarDownloader(slixmpp.ClientXMPP):
self.roster_received.set()
self.presences_received.clear()
@asyncio.coroutine
def start(self, event):
async def start(self, event):
"""
Process the session_start event.
@ -65,16 +64,15 @@ class AvatarDownloader(slixmpp.ClientXMPP):
self.get_roster(callback=self.roster_received_cb)
print('Waiting for presence updates...\n')
yield from self.roster_received.wait()
await self.roster_received.wait()
print('Roster received')
yield from self.presences_received.wait()
await self.presences_received.wait()
self.disconnect()
@asyncio.coroutine
def on_vcard_avatar(self, pres):
async def on_vcard_avatar(self, pres):
print("Received vCard avatar update from %s" % pres['from'].bare)
try:
result = yield from self['xep_0054'].get_vcard(pres['from'].bare, cached=True,
result = await self['xep_0054'].get_vcard(pres['from'].bare, cached=True,
timeout=5)
except XMPPError:
print("Error retrieving avatar for %s" % pres['from'])
@ -89,14 +87,13 @@ class AvatarDownloader(slixmpp.ClientXMPP):
with open(filename, 'wb+') as img:
img.write(avatar['BINVAL'])
@asyncio.coroutine
def on_avatar(self, msg):
async def on_avatar(self, msg):
print("Received avatar update from %s" % msg['from'])
metadata = msg['pubsub_event']['items']['item']['avatar_metadata']
for info in metadata['items']:
if not info['url']:
try:
result = yield from self['xep_0084'].retrieve_avatar(msg['from'].bare, info['id'],
result = await self['xep_0084'].retrieve_avatar(msg['from'].bare, info['id'],
timeout=5)
except XMPPError:
print("Error retrieving avatar for %s" % msg['from'])

View file

@ -33,10 +33,9 @@ class HttpUpload(slixmpp.ClientXMPP):
self.add_event_handler("session_start", self.start)
@asyncio.coroutine
def start(self, event):
async def start(self, event):
log.info('Uploading file %s...', self.filename)
url = yield from self['xep_0363'].upload_file(self.filename)
url = await self['xep_0363'].upload_file(self.filename)
log.info('Upload success!')
log.info('Sending file to %s', self.recipient)

View file

@ -39,8 +39,7 @@ class IBBSender(slixmpp.ClientXMPP):
# our roster.
self.add_event_handler("session_start", self.start)
@asyncio.coroutine
def start(self, event):
async def start(self, event):
"""
Process the session_start event.
@ -58,13 +57,13 @@ class IBBSender(slixmpp.ClientXMPP):
try:
# Open the IBB stream in which to write to.
stream = yield from self['xep_0047'].open_stream(self.receiver, use_messages=self.use_messages)
stream = await self['xep_0047'].open_stream(self.receiver, use_messages=self.use_messages)
# If you want to send in-memory bytes, use stream.sendall() instead.
yield from stream.sendfile(self.file, timeout=10)
await stream.sendfile(self.file, timeout=10)
# And finally close the stream.
yield from stream.close(timeout=10)
await stream.close(timeout=10)
except (IqError, IqTimeout):
print('File transfer errored')
else:

View file

@ -38,8 +38,7 @@ class PingTest(slixmpp.ClientXMPP):
# our roster.
self.add_event_handler("session_start", self.start)
@asyncio.coroutine
def start(self, event):
async def start(self, event):
"""
Process the session_start event.
@ -56,7 +55,7 @@ class PingTest(slixmpp.ClientXMPP):
self.get_roster()
try:
rtt = yield from self['xep_0199'].ping(self.pingjid,
rtt = await self['xep_0199'].ping(self.pingjid,
timeout=10)
logging.info("Success! RTT: %s", rtt)
except IqError as e:

View file

@ -32,87 +32,86 @@ class PubsubClient(slixmpp.ClientXMPP):
self.add_event_handler('session_start', self.start)
@asyncio.coroutine
def start(self, event):
async def start(self, event):
self.get_roster()
self.send_presence()
try:
yield from getattr(self, self.action)()
await getattr(self, self.action)()
except:
logging.exception('Could not execute %s:', self.action)
self.disconnect()
def nodes(self):
async def nodes(self):
try:
result = yield from self['xep_0060'].get_nodes(self.pubsub_server, self.node)
result = await self['xep_0060'].get_nodes(self.pubsub_server, self.node)
for item in result['disco_items']['items']:
logging.info(' - %s', str(item))
except XMPPError as error:
logging.error('Could not retrieve node list: %s', error.format())
def create(self):
async def create(self):
try:
yield from self['xep_0060'].create_node(self.pubsub_server, self.node)
await self['xep_0060'].create_node(self.pubsub_server, self.node)
logging.info('Created node %s', self.node)
except XMPPError as error:
logging.error('Could not create node %s: %s', self.node, error.format())
def delete(self):
async def delete(self):
try:
yield from self['xep_0060'].delete_node(self.pubsub_server, self.node)
await self['xep_0060'].delete_node(self.pubsub_server, self.node)
logging.info('Deleted node %s', self.node)
except XMPPError as error:
logging.error('Could not delete node %s: %s', self.node, error.format())
def get_configure(self):
async def get_configure(self):
try:
configuration_form = yield from self['xep_0060'].get_node_config(self.pubsub_server, self.node)
configuration_form = await self['xep_0060'].get_node_config(self.pubsub_server, self.node)
logging.info('Configure form received from node %s: %s', self.node, configuration_form['pubsub_owner']['configure']['form'])
except XMPPError as error:
logging.error('Could not retrieve configure form from node %s: %s', self.node, error.format())
def publish(self):
async def publish(self):
payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data)
try:
result = yield from self['xep_0060'].publish(self.pubsub_server, self.node, payload=payload)
result = await self['xep_0060'].publish(self.pubsub_server, self.node, payload=payload)
logging.info('Published at item id: %s', result['pubsub']['publish']['item']['id'])
except XMPPError as error:
logging.error('Could not publish to %s: %s', self.node, error.format())
def get(self):
async def get(self):
try:
result = yield from self['xep_0060'].get_item(self.pubsub_server, self.node, self.data)
result = await self['xep_0060'].get_item(self.pubsub_server, self.node, self.data)
for item in result['pubsub']['items']['substanzas']:
logging.info('Retrieved item %s: %s', item['id'], tostring(item['payload']))
except XMPPError as error:
logging.error('Could not retrieve item %s from node %s: %s', self.data, self.node, error.format())
def retract(self):
async def retract(self):
try:
yield from self['xep_0060'].retract(self.pubsub_server, self.node, self.data)
await self['xep_0060'].retract(self.pubsub_server, self.node, self.data)
logging.info('Retracted item %s from node %s', self.data, self.node)
except XMPPError as error:
logging.error('Could not retract item %s from node %s: %s', self.data, self.node, error.format())
def purge(self):
async def purge(self):
try:
yield from self['xep_0060'].purge(self.pubsub_server, self.node)
await self['xep_0060'].purge(self.pubsub_server, self.node)
logging.info('Purged all items from node %s', self.node)
except XMPPError as error:
logging.error('Could not purge items from node %s: %s', self.node, error.format())
def subscribe(self):
async def subscribe(self):
try:
iq = yield from self['xep_0060'].subscribe(self.pubsub_server, self.node)
iq = await self['xep_0060'].subscribe(self.pubsub_server, self.node)
subscription = iq['pubsub']['subscription']
logging.info('Subscribed %s to node %s', subscription['jid'], subscription['node'])
except XMPPError as error:
logging.error('Could not subscribe %s to node %s: %s', self.boundjid.bare, self.node, error.format())
def unsubscribe(self):
async def unsubscribe(self):
try:
yield from self['xep_0060'].unsubscribe(self.pubsub_server, self.node)
await self['xep_0060'].unsubscribe(self.pubsub_server, self.node)
logging.info('Unsubscribed %s from node %s', self.boundjid.bare, self.node)
except XMPPError as error:
logging.error('Could not unsubscribe %s from node %s: %s', self.boundjid.bare, self.node, error.format())

View file

@ -66,7 +66,7 @@ class RegisterBot(slixmpp.ClientXMPP):
# We're only concerned about registering, so nothing more to do here.
self.disconnect()
def register(self, iq):
async def register(self, iq):
"""
Fill out and submit a registration form.
@ -90,7 +90,7 @@ class RegisterBot(slixmpp.ClientXMPP):
resp['register']['password'] = self.password
try:
yield from resp.send()
await resp.send()
logging.info("Account created for %s!" % self.boundjid)
except IqError as e:
logging.error("Could not register account: %s" %

View file

@ -38,8 +38,7 @@ class RosterBrowser(slixmpp.ClientXMPP):
self.received = set()
self.presences_received = asyncio.Event()
@asyncio.coroutine
def start(self, event):
async def start(self, event):
"""
Process the session_start event.
@ -57,7 +56,7 @@ class RosterBrowser(slixmpp.ClientXMPP):
future.set_result(None)
try:
self.get_roster(callback=callback)
yield from future
await future
except IqError as err:
print('Error: %s' % err.iq['error']['condition'])
except IqTimeout:
@ -66,7 +65,7 @@ class RosterBrowser(slixmpp.ClientXMPP):
print('Waiting for presence updates...\n')
yield from asyncio.sleep(10)
await asyncio.sleep(10)
print('Roster for %s' % self.boundjid.bare)
groups = self.client_roster.groups()

View file

@ -36,8 +36,7 @@ class S5BSender(slixmpp.ClientXMPP):
# and the XML streams are ready for use.
self.add_event_handler("session_start", self.start)
@asyncio.coroutine
def start(self, event):
async def start(self, event):
"""
Process the session_start event.
@ -53,14 +52,14 @@ class S5BSender(slixmpp.ClientXMPP):
try:
# Open the S5B stream in which to write to.
proxy = yield from self['xep_0065'].handshake(self.receiver)
proxy = await self['xep_0065'].handshake(self.receiver)
# Send the entire file.
while True:
data = self.file.read(1048576)
if not data:
break
yield from proxy.write(data)
await proxy.write(data)
# And finally close the stream.
proxy.transport.write_eof()

View file

@ -33,8 +33,7 @@ class AvatarSetter(slixmpp.ClientXMPP):
self.filepath = filepath
@asyncio.coroutine
def start(self, event):
async def start(self, event):
"""
Process the session_start event.
@ -68,20 +67,20 @@ class AvatarSetter(slixmpp.ClientXMPP):
used_xep84 = False
print('Publish XEP-0084 avatar data')
result = yield from self['xep_0084'].publish_avatar(avatar)
result = await self['xep_0084'].publish_avatar(avatar)
if isinstance(result, XMPPError):
print('Could not publish XEP-0084 avatar')
else:
used_xep84 = True
print('Update vCard with avatar')
result = yield from self['xep_0153'].set_avatar(avatar=avatar, mtype=avatar_type)
result = await self['xep_0153'].set_avatar(avatar=avatar, mtype=avatar_type)
if isinstance(result, XMPPError):
print('Could not set vCard avatar')
if used_xep84:
print('Advertise XEP-0084 avatar metadata')
result = yield from self['xep_0084'].publish_avatar_metadata([
result = await self['xep_0084'].publish_avatar_metadata([
{'id': avatar_id,
'type': avatar_type,
'bytes': avatar_bytes}

View file

@ -59,7 +59,7 @@ class XEP_0077(BasePlugin):
def _force_stream_feature(self, stanza):
if isinstance(stanza, StreamFeatures):
if self.xmpp.use_tls or self.xmpp.use_ssl:
if not self.xmpp.disable_starttls:
if 'starttls' not in self.xmpp.features:
return stanza
elif not isinstance(self.xmpp.socket, ssl.SSLSocket):

View file

@ -79,8 +79,7 @@ class TestInBandByteStreams(SlixTest):
self.assertEqual(events, {'ibb_stream_start', 'callback'})
@asyncio.coroutine
def testSendData(self):
async def testSendData(self):
"""Test sending data over an in-band bytestream."""
streams = []
@ -117,7 +116,7 @@ class TestInBandByteStreams(SlixTest):
# Test sending data out
yield from stream.send("Testing")
await stream.send("Testing")
self.send("""
<iq type="set" id="2"