-
-
Save yv84/ea0af8b9889b92eba9d7 to your computer and use it in GitHub Desktop.
Mockin' asyncio coroutine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import unittest | |
import unittest.mock | |
class MyClass: | |
@asyncio.coroutine | |
def coro1(self): | |
g = yield from self.coro2() | |
print('\ncoro1->', g, '; type: ', type(g)) | |
@asyncio.coroutine | |
def coro2(self): | |
return (True,) | |
class MockTestCase(unittest.TestCase): | |
def setUp(self): | |
self.loop = asyncio.get_event_loop() | |
self.m = MyClass() | |
def set_future(self, *args): | |
f = asyncio.Future() | |
f.set_result(args) | |
print(f) | |
return f | |
def test_call_coro2_asyncio(self): | |
coro = self.m.coro1() | |
result = self.loop.run_until_complete(coro) | |
# coro1-> (True,) ; type: <class 'tuple'> | |
def test_call_coro2_mock(self): | |
self.m.coro2 = unittest.mock.Mock(return_value=self.set_future(True)) | |
coro = self.m.coro1() | |
result = self.loop.run_until_complete(coro) | |
self.assertTrue(self.m.coro2.call_count == 1) | |
# coro1-> (True,) ; type: <class 'tuple'> | |
def test_call_coro2_mock2(self): | |
mm = unittest.mock.MagicMock() | |
mm.iter.return_value = 'iterable' | |
self.m.coro2 = unittest.mock.Mock(return_value=mm) | |
coro = self.m.coro1() | |
result = self.loop.run_until_complete(coro) | |
self.assertEqual(1, mm.__iter__.call_count) | |
# coro1-> None ; type: <class 'NoneType'> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment