├── .gitignore ├── LICENSE ├── README.md ├── async_receive.py ├── receive.py ├── test_async_receive.py └── test_receive.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Miguel Grinberg 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Testing asyncio code 2 | 3 | This repository contains the examples featured in my blog article 4 | [Unit Testing AsyncIO Code](https://blog.miguelgrinberg.com/post/unit-testing-asyncio-code). 5 | 6 | Note that these tests work only on Python 3.5+. 7 | 8 | To run the unit synchronous unit tests, use the following command: 9 | 10 | $ python test_receive.py 11 | 12 | To run the asynchronous unit tests, use the following command: 13 | 14 | $ python test_async_receive.py 15 | -------------------------------------------------------------------------------- /async_receive.py: -------------------------------------------------------------------------------- 1 | async def send_to_client(packet_type, packet_data): 2 | """Implementation of this function not shown.""" 3 | raise RuntimeError('Nope') 4 | 5 | 6 | async def trigger_event(event_name, event_data): 7 | """Implementation of this function not shown.""" 8 | raise RuntimeError('Nope') 9 | 10 | 11 | async def receive(packet_type, packet_data): 12 | """Receive packet from the client.""" 13 | if packet_type == 'PING': 14 | await send_to_client("PONG", packet_data) 15 | elif packet_type == 'MESSAGE': 16 | response = await trigger_event('message', packet_data) 17 | await send_to_client('MESSAGE', response) 18 | else: 19 | raise ValueError('Invalid packet type') 20 | -------------------------------------------------------------------------------- /receive.py: -------------------------------------------------------------------------------- 1 | def send_to_client(packet_type, packet_data): 2 | """Implementation of this function not shown.""" 3 | raise RuntimeError('Nope') 4 | 5 | 6 | def trigger_event(event_name, event_data): 7 | """Implementation of this function not shown.""" 8 | raise RuntimeError('Nope') 9 | 10 | 11 | def receive(packet_type, packet_data): 12 | """Receive packet from the client.""" 13 | if packet_type == 'PING': 14 | send_to_client("PONG", packet_data) 15 | elif packet_type == 'MESSAGE': 16 | response = trigger_event('message', packet_data) 17 | send_to_client('MESSAGE', response) 18 | else: 19 | raise ValueError('Invalid packet type') 20 | -------------------------------------------------------------------------------- /test_async_receive.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import asyncio 3 | import unittest 4 | from unittest import mock 5 | from async_receive import receive 6 | 7 | 8 | def _run(coro): 9 | """Run the given coroutine.""" 10 | return asyncio.get_event_loop().run_until_complete(coro) 11 | 12 | def AsyncMock(*args, **kwargs): 13 | """Create an async function mock.""" 14 | m = mock.MagicMock(*args, **kwargs) 15 | 16 | async def mock_coro(*args, **kwargs): 17 | return m(*args, **kwargs) 18 | 19 | mock_coro.mock = m 20 | return mock_coro 21 | 22 | 23 | class TestReceive(unittest.TestCase): 24 | def test_invalid_packet(self): 25 | self.assertRaises(ValueError, _run, receive('FOO', 'data')) 26 | 27 | @mock.patch('async_receive.send_to_client', new=AsyncMock()) 28 | def test_ping(self): 29 | _run(receive('PING', 'data')) 30 | from async_receive import send_to_client 31 | send_to_client.mock.assert_called_once_with('PONG', 'data') 32 | 33 | @mock.patch('async_receive.send_to_client', new=AsyncMock()) 34 | @mock.patch('async_receive.trigger_event', 35 | new=AsyncMock(return_value='my response')) 36 | def test_message(self): 37 | _run(receive('MESSAGE', 'data')) 38 | from async_receive import send_to_client, trigger_event 39 | trigger_event.mock.assert_called_once_with('message', 'data') 40 | send_to_client.mock.assert_called_once_with('MESSAGE', 'my response') 41 | 42 | 43 | if __name__ == '__main__': 44 | unittest.main() 45 | -------------------------------------------------------------------------------- /test_receive.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import unittest 3 | from unittest import mock 4 | from receive import receive 5 | 6 | 7 | class TestReceive(unittest.TestCase): 8 | def test_invalid_packet(self): 9 | self.assertRaises(ValueError, receive, 'FOO', 'data') 10 | 11 | @mock.patch('receive.send_to_client') 12 | def test_ping(self, send_to_client): 13 | receive('PING', 'data') 14 | send_to_client.assert_called_once_with('PONG', 'data') 15 | 16 | @mock.patch('receive.trigger_event', return_value='my response') 17 | @mock.patch('receive.send_to_client') 18 | def test_message(self, send_to_client, trigger_event): 19 | receive('MESSAGE', 'data') 20 | trigger_event.assert_called_once_with('message', 'data') 21 | send_to_client.assert_called_once_with('MESSAGE', 'my response') 22 | 23 | 24 | if __name__ == '__main__': 25 | unittest.main() 26 | --------------------------------------------------------------------------------