|
| 1 | +import sys |
| 2 | +import os |
| 3 | +import time |
| 4 | +import asyncio |
| 5 | +import unittest |
| 6 | +from unittest.mock import patch, AsyncMock |
| 7 | + |
| 8 | +sys.path.append(os.path.abspath('docs/3. Handling CPU and IO Bound Tasks')) |
| 9 | +from ex_3_1 import fetch_data as fetch_data_ex_1, main as main_ex_1 |
| 10 | + |
| 11 | + |
| 12 | +class TestEx1AsyncHttpx(unittest.IsolatedAsyncioTestCase): |
| 13 | + @patch('httpx.AsyncClient.get') |
| 14 | + async def test_fetch_data_success(self, mock_get): |
| 15 | + """Test successful fetching of data.""" |
| 16 | + mock_response = mock_get.return_value |
| 17 | + mock_response.status_code = 200 |
| 18 | + mock_response.text = 'Success' |
| 19 | + |
| 20 | + url = 'https://www.example.com/' |
| 21 | + response = await fetch_data_ex_1(url) |
| 22 | + mock_get.assert_called_once_with(url) |
| 23 | + |
| 24 | + self.assertEqual(response.status_code, 200) |
| 25 | + self.assertEqual(response.text, 'Success') |
| 26 | + |
| 27 | + @patch('httpx.AsyncClient.get') |
| 28 | + async def test_fetch_data_failure(self, mock_get): |
| 29 | + """Test failure when fetching data.""" |
| 30 | + mock_response = mock_get.return_value |
| 31 | + mock_response.status_code = 404 |
| 32 | + |
| 33 | + url = 'https://www.example.com/' |
| 34 | + response = await fetch_data_ex_1(url) |
| 35 | + mock_get.assert_called_once_with(url) |
| 36 | + |
| 37 | + self.assertEqual(response.status_code, 404) |
| 38 | + |
| 39 | + @patch('ex_3_1.fetch_data', new_callable=AsyncMock) |
| 40 | + async def test_main_success(self, mock_fetch): |
| 41 | + """Test main function when fetch_data is successful.""" |
| 42 | + mock_fetch.return_value.status_code = 200 |
| 43 | + mock_fetch.return_value = '<Response [200 OK]>' |
| 44 | + |
| 45 | + with patch('builtins.print') as mocked_print: |
| 46 | + await main_ex_1() |
| 47 | + mocked_print.assert_any_call(f"response is: {mock_fetch.return_value}") |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == '__main__': |
| 51 | + unittest.main() |
0 commit comments