Skip to content

Instantly share code, notes, and snippets.

@nopcall
Forked from ly0/asyncio_unittest.py
Created April 3, 2018 09:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nopcall/ccab5342dc6a1107898046bf1fb2058c to your computer and use it in GitHub Desktop.
Save nopcall/ccab5342dc6a1107898046bf1fb2058c to your computer and use it in GitHub Desktop.
asyncio unittest
import unittest
import asyncio
import inspect
def async_test(f):
def wrapper(*args, **kwargs):
if inspect.iscoroutinefunction(f):
future = f(*args, **kwargs)
else:
coroutine = asyncio.coroutine(f)
future = coroutine(*args, **kwargs)
asyncio.get_event_loop().run_until_complete(future)
return wrapper
class TestExample(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
# asyncio test normal function with yield from statements
@async_test
def test_tcp1_success(self):
test = yield from asyncio.open_connection('www.baidu.com', 80)
print('test_tcp1_success')
# asyncio test coroutine function with yield from statements
@async_test
@asyncio.coroutine
def test_tcp2_success(self):
test = yield from asyncio.open_connection('www.baidu.com', 80)
print('test_tcp2_success')
# asyncio test with await keywords
@async_test
async def test_tcp3_success(self):
test = await asyncio.open_connection('www.baidu.com', 80)
print('test_tcp3_success')
# asyncio test with await keywords
@async_test
async def test_tcp3_fail(self):
test = await asyncio.open_connection('www.baidu.com', 80)
self.assertTrue(False, 'test_tcp3_fail')
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment