Skip to content

Commit 442f0fe

Browse files
Merge pull request #3 from aligheshlaghi97/feat/test
Feat/test
2 parents c56bc52 + 773ca62 commit 442f0fe

File tree

7 files changed

+444
-3
lines changed

7 files changed

+444
-3
lines changed

docs/6. Exploring Python 3.12 Features/ex_6_2.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ async def light_coro():
77

88

99
async def main():
10-
print('Before running task group!')
10+
print('Before running gather!')
1111
tasks_list = [light_coro() for _ in range(1000000)]
1212
time0 = time.time()
1313

requirements.txt

+3
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,5 @@
11
pytest~=8.3.3
22
httpx~=0.27.2
3+
uvicorn~=0.30.2
4+
gunicorn~=19.9.0
5+
starlette==0.37.2

tests/test_ch3.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -163,8 +163,8 @@ def test_with_and_without_mp(self):
163163
self.assertEqual(value1_mp, value2_mp)
164164
self.assertEqual(value1_mp, self.value * self.step)
165165
self.assertEqual(value2_mp, self.value * self.step)
166-
self.assertLessEqual(time_taken_mp * 1.7, time_taken,
167-
msg='time taken without mp is less than 1.7 times of with mp!')
166+
self.assertLessEqual(time_taken_mp * 1.5, time_taken,
167+
msg='time taken without mp is less than 1.5 times of with mp!')
168168

169169
def test_main(self):
170170
with patch('builtins.print') as mocked_print:

tests/test_ch4.py

+142
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
import sys
2+
import os
3+
import time
4+
import asyncio
5+
import unittest
6+
from unittest.mock import patch, AsyncMock, MagicMock
7+
8+
sys.path.append(os.path.abspath('docs/4. Synchronization and Coordination'))
9+
import ex_4_1 as ex1
10+
import ex_4_2 as ex2
11+
import ex_4_3 as ex3
12+
import ex_4_4 as ex4
13+
import ex_4_5 as ex5
14+
15+
16+
class TestEx1AsyncTask(unittest.TestCase):
17+
@patch('asyncio.sleep', return_value=None)
18+
def test_task(self, mock_sleep):
19+
"""Test task function."""
20+
ex1.value = 0
21+
22+
asyncio.run(ex1.task())
23+
self.assertEqual(ex1.value, 1)
24+
25+
asyncio.run(ex1.task())
26+
self.assertEqual(ex1.value, 2)
27+
28+
mock_sleep.assert_called_with(0.01)
29+
30+
def test_main_success(self):
31+
"""Test main function"""
32+
with patch('builtins.print') as mocked_print:
33+
asyncio.run(ex1.main())
34+
mocked_print.assert_any_call(1)
35+
36+
37+
class TestEx2AsyncTask(unittest.TestCase):
38+
@patch('asyncio.sleep', return_value=None)
39+
def test_task(self, mock_sleep):
40+
"""Test task function."""
41+
ex2.value = 0
42+
lock = asyncio.Lock()
43+
asyncio.run(ex2.task(lock))
44+
self.assertEqual(ex2.value, 1)
45+
46+
asyncio.run(ex2.task(lock))
47+
self.assertEqual(ex2.value, 2)
48+
49+
mock_sleep.assert_called_with(0.00)
50+
51+
def test_main_success(self):
52+
"""Test main function"""
53+
with patch('builtins.print') as mocked_print:
54+
asyncio.run(ex2.main())
55+
mocked_print.assert_any_call(10000)
56+
57+
58+
class TestEx3Semaphore(unittest.IsolatedAsyncioTestCase):
59+
@patch('asyncio.sleep', return_value=None)
60+
def test_limited_resource(self, mock_sleep):
61+
"""Test limited resource function."""
62+
ex2.value = 0
63+
lock = asyncio.Lock()
64+
asyncio.run(ex2.task(lock))
65+
self.assertEqual(ex2.value, 1)
66+
67+
asyncio.run(ex2.task(lock))
68+
self.assertEqual(ex2.value, 2)
69+
70+
with patch('builtins.print') as mocked_print:
71+
asyncio.run(ex3.main())
72+
mocked_print.assert_any_call("Accessing limited resource")
73+
mocked_print.assert_any_call("Finished using limited resource")
74+
75+
mock_sleep.assert_called_with(1)
76+
77+
def test_main_success(self):
78+
"""Test main function"""
79+
with patch('builtins.print') as mocked_print:
80+
time_start = time.time()
81+
asyncio.run(ex3.main())
82+
time_taken = time.time() - time_start
83+
84+
self.assertLess(time_taken, 3)
85+
self.assertLess(2, time_taken)
86+
87+
mocked_print.assert_any_call("Accessing limited resource")
88+
mocked_print.assert_any_call("Finished using limited resource")
89+
90+
91+
class TestEx4Barrier(unittest.TestCase):
92+
@patch('asyncio.sleep', return_value=None)
93+
def test_example_barrier(self, mock_sleep):
94+
"""Test example barrier function."""
95+
with patch('builtins.print') as mock_print:
96+
asyncio.run(ex4.example_barrier())
97+
mock_print.assert_any_call("barrier passed")
98+
calls = mock_print.call_args_list
99+
100+
self.assertEqual(len(calls), 4)
101+
102+
printed_outputs = [call[0][0] for call in calls]
103+
expected_output = [
104+
'[filling, waiters:0/3]',
105+
'[filling, waiters:0/3]',
106+
'barrier passed',
107+
'[filling, waiters:0/3]',
108+
]
109+
for out_idx in range(3):
110+
self.assertIn(expected_output[out_idx], str(printed_outputs[out_idx]))
111+
112+
mock_sleep.assert_called_with(0)
113+
114+
115+
class TestEx5EventWaiter(unittest.IsolatedAsyncioTestCase):
116+
async def test_waiter(self):
117+
"""Test waiter(event) function."""
118+
event = asyncio.Event()
119+
with patch('builtins.print') as mock_print:
120+
time_start = time.time()
121+
waiter_task = asyncio.create_task(ex5.waiter(event))
122+
event.set()
123+
await waiter_task
124+
time_taken = time.time() - time_start
125+
self.assertLess(time_taken, 0.01)
126+
127+
mock_print.assert_any_call("waiting for it ...")
128+
mock_print.assert_any_call("... got it!")
129+
130+
def test_main(self):
131+
with patch('builtins.print') as mock_print:
132+
time_start = time.time()
133+
asyncio.run(ex5.main())
134+
time_taken = time.time() - time_start
135+
self.assertGreater(time_taken, 1)
136+
137+
mock_print.assert_any_call("waiting for it ...")
138+
mock_print.assert_any_call("... got it!")
139+
140+
141+
if __name__ == '__main__':
142+
unittest.main()

tests/test_ch5.py

+173
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
import sys
2+
import os
3+
import time
4+
import asyncio
5+
import unittest
6+
from unittest.mock import patch, AsyncMock, MagicMock
7+
8+
sys.path.append(os.path.abspath('docs/5. Advanced Techniques'))
9+
import ex_5_1 as ex1
10+
import ex_5_2 as ex2
11+
import ex_5_3 as ex3
12+
import ex_5_4 as ex4
13+
import ex_5_5 as ex5
14+
import ex_5_6 as ex6
15+
16+
17+
class TestEx1ExceptionPropagate(unittest.TestCase):
18+
@patch('asyncio.sleep', return_value=None)
19+
def test_shorter_task(self, mock_sleep):
20+
"""Test shorter task function."""
21+
with patch('builtins.print') as mocked_print:
22+
with patch('ex_5_1.Exception') as mock_exception, self.assertRaises(Exception):
23+
asyncio.run(ex1.shorter_task())
24+
mock_exception.assert_called_once_with("Some exception happened!")
25+
mocked_print.assert_called_once_with("Executing the task to raise an exception!")
26+
mock_sleep.assert_called_once_with(0.1)
27+
28+
@patch('asyncio.sleep', return_value=None)
29+
def test_longer_task(self, mock_sleep):
30+
"""Test longer task function."""
31+
with patch('builtins.print') as mocked_print:
32+
asyncio.run(ex1.longer_task())
33+
mocked_print.assert_any_call("Executing the task which will complete!")
34+
mock_sleep.assert_called_once_with(1)
35+
mocked_print.assert_any_call("longer_task is done!")
36+
37+
@patch('asyncio.sleep', return_value=None)
38+
def test_main(self, mock_sleep):
39+
"""Test main function."""
40+
with patch('builtins.print') as mocked_print:
41+
asyncio.run(ex1.main())
42+
mocked_print.assert_any_call("Main coroutine started!")
43+
mocked_print.assert_any_call("Executing the task to raise an exception!")
44+
mocked_print.assert_any_call("Executing the task which will complete!")
45+
mock_sleep.assert_any_call(1)
46+
mock_sleep.assert_any_call(0.1)
47+
mocked_print.assert_any_call("longer_task is done!")
48+
mocked_print.assert_any_call("Exception: Some exception happened!")
49+
mocked_print.assert_any_call("Main coroutine done!")
50+
51+
52+
class TestEx2ExceptionHandler(unittest.TestCase):
53+
@patch('asyncio.sleep', return_value=None)
54+
def test_shorter_task(self, mock_sleep):
55+
"""Test shorter task function."""
56+
with patch('builtins.print') as mocked_print:
57+
with patch('ex_5_2.Exception') as mock_exception, self.assertRaises(Exception):
58+
asyncio.run(ex2.shorter_task())
59+
mock_exception.assert_called_once_with("Some exception happened!")
60+
mocked_print.assert_called_once_with("Executing the task to raise an exception!")
61+
mock_sleep.assert_called_once_with(0.01)
62+
63+
@patch('asyncio.sleep', return_value=None)
64+
def test_longer_task(self, mock_sleep):
65+
"""Test longer task function."""
66+
with patch('builtins.print') as mocked_print:
67+
asyncio.run(ex2.longer_task())
68+
mocked_print.assert_any_call("Executing the task which will complete!")
69+
mock_sleep.assert_called_once_with(1)
70+
mocked_print.assert_any_call("longer_task is done!")
71+
72+
def test_exception_handler(self):
73+
"""Test exception handler."""
74+
with patch('builtins.print') as mocked_print:
75+
context = {"exception": "Test exception!"}
76+
ex2.exception_handler(None, context)
77+
mocked_print.assert_called_once_with("Exception: Test exception!")
78+
79+
@patch('asyncio.sleep', return_value=None)
80+
def test_main(self, mock_sleep):
81+
"""Test main function."""
82+
with patch('builtins.print') as mocked_print:
83+
asyncio.run(ex2.main())
84+
mocked_print.assert_any_call("Main coroutine started!")
85+
mocked_print.assert_any_call("Executing the task to raise an exception!")
86+
mocked_print.assert_any_call("Executing the task which will complete!")
87+
mock_sleep.assert_any_call(1)
88+
mock_sleep.assert_any_call(0.01)
89+
mocked_print.assert_any_call("longer_task is done!")
90+
mocked_print.assert_any_call("Exception: Some exception happened!")
91+
mocked_print.assert_any_call("Main coroutine done!")
92+
93+
94+
class TestEx3CancelTask(unittest.TestCase):
95+
@patch('asyncio.sleep', return_value=None)
96+
def test_cancel_me(self, mock_sleep):
97+
"""Test cancel_me function."""
98+
asyncio.run(ex3.cancel_me())
99+
mock_sleep.assert_called_once_with(1)
100+
101+
@patch('asyncio.sleep', return_value=None)
102+
def test_main(self, mock_sleep):
103+
"""Test main function"""
104+
with patch('builtins.print') as mocked_print:
105+
asyncio.run(ex3.main())
106+
mocked_print.assert_called_once_with("main(): cancel_me is cancelled now")
107+
mock_sleep.assert_any_call(0.01)
108+
109+
110+
class TestEx4ChainTasks(unittest.IsolatedAsyncioTestCase):
111+
@patch('asyncio.sleep', return_value=None)
112+
async def test_task1(self, mock_sleep):
113+
"""Test task1 function."""
114+
with patch('builtins.print') as mocked_print:
115+
result = await ex4.task1()
116+
mock_sleep.assert_called_once_with(1)
117+
mocked_print.assert_called_once_with(">task1()")
118+
self.assertEqual(result, 1)
119+
120+
@patch('asyncio.sleep', return_value=None)
121+
async def test_task2(self, mock_sleep):
122+
"""Test task2 function."""
123+
with patch('builtins.print') as mocked_print:
124+
value = 1
125+
await ex4.task2(value)
126+
mock_sleep.assert_called_once_with(1)
127+
mocked_print.assert_called_once_with(f">task2() got {value}")
128+
129+
@patch('asyncio.sleep', return_value=None)
130+
def test_main(self, mock_sleep):
131+
"""Test main function"""
132+
with patch('builtins.print') as mocked_print:
133+
asyncio.run(ex4.main())
134+
mocked_print.assert_any_call(">task1()")
135+
mocked_print.assert_any_call(f">task2() got 1")
136+
137+
mocked_print.assert_any_call("Main: chain is done")
138+
mock_sleep.assert_any_call(1)
139+
self.assertTrue(ex4.event.is_set())
140+
141+
142+
class TestEx5ProducerConsumer(unittest.TestCase):
143+
@patch('asyncio.sleep', return_value=None)
144+
def test_producer(self, mock_sleep):
145+
"""Test producer function"""
146+
channel = asyncio.Queue()
147+
asyncio.run(ex5.producer(channel))
148+
self.assertEqual(channel.qsize(), 5)
149+
mock_sleep.assert_any_call(1)
150+
151+
@patch('asyncio.sleep', return_value=None)
152+
def test_main(self, mock_sleep):
153+
"""Test main function"""
154+
with patch('builtins.print') as mocked_print:
155+
asyncio.run(ex5.main())
156+
mocked_print.assert_any_call("Done!")
157+
for num in range(5):
158+
mocked_print.assert_any_call(f"Got number {num}")
159+
mock_sleep.assert_any_call(1)
160+
161+
162+
class TestEx6Future(unittest.TestCase):
163+
def test_main(self):
164+
"""Test main function"""
165+
with patch('builtins.print') as mocked_print:
166+
asyncio.run(ex6.main())
167+
mocked_print.assert_any_call("future status is done: False")
168+
mocked_print.assert_any_call("future status is done: True, future result: 10")
169+
mocked_print.assert_any_call("future result after being awaited: 10")
170+
171+
172+
if __name__ == '__main__':
173+
unittest.main()

0 commit comments

Comments
 (0)