|
| 1 | +import sys |
| 2 | +import os |
| 3 | +import asyncio |
| 4 | +import unittest |
| 5 | +from unittest.mock import patch |
| 6 | + |
| 7 | +sys.path.append(os.path.abspath('docs/2. Getting Started with asyncio')) |
| 8 | +from ex_2_1 import async_sleep_for_one_second as async_sleep_ex_1 |
| 9 | +from ex_2_2 import async_sleep_for_one_second as async_sleep_ex_2 |
| 10 | + |
| 11 | + |
| 12 | +class TestAsyncSleep(unittest.TestCase): |
| 13 | + @patch('asyncio.sleep', return_value=None) |
| 14 | + def test_async_sleep_for_one_second(self, mock_sleep): |
| 15 | + with patch('builtins.print') as mock_print: |
| 16 | + asyncio.run(async_sleep_ex_1()) |
| 17 | + |
| 18 | + # Check if the print statements were called correctly |
| 19 | + mock_print.assert_any_call('stared sleeping for 1 second!') |
| 20 | + mock_print.assert_any_call('Finished sleeping!') |
| 21 | + |
| 22 | + # Ensure that asyncio.sleep was called once |
| 23 | + mock_sleep.assert_called_once_with(1) |
| 24 | + |
| 25 | + |
| 26 | +class TestAsyncSleep(unittest.TestCase): |
| 27 | + @patch('asyncio.sleep', return_value=None) |
| 28 | + def test_async_sleep_for_one_second(self, mock_sleep): |
| 29 | + with patch('builtins.print') as mock_print: |
| 30 | + with asyncio.Runner() as runner: |
| 31 | + runner.run(async_sleep_ex_2()) |
| 32 | + |
| 33 | + # Check if the print statements were called correctly |
| 34 | + mock_print.assert_any_call('stared sleeping for 1 second!') |
| 35 | + mock_print.assert_any_call('Finished sleeping!') |
| 36 | + |
| 37 | + # Ensure that asyncio.sleep was called once |
| 38 | + mock_sleep.assert_called_once_with(1) |
| 39 | + |
| 40 | + |
| 41 | +if __name__ == '__main__': |
| 42 | + unittest.main() |
0 commit comments