Skip to content

Commit 362c8c3

Browse files
test: ch3-ex1 covered.
1 parent 7e41626 commit 362c8c3

File tree

2 files changed

+60
-3
lines changed

2 files changed

+60
-3
lines changed

docs/3. Handling CPU and IO Bound Tasks/ex_3_1.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,16 @@
33
import httpx
44

55

6+
async def fetch_data(url):
7+
async with httpx.AsyncClient() as client:
8+
response = await client.get(url)
9+
return response
10+
11+
612
async def main():
713
t = time.time()
8-
async with httpx.AsyncClient() as client:
9-
response = await client.get('https://www.example.com/')
10-
print(response)
14+
response = await fetch_data('https://www.example.com/')
15+
print(f"response is: {response}")
1116
print(f"it took {time.time() - t} s")
17+
1218
asyncio.run(main())

tests/test_ch3.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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

Comments
 (0)