@@ -160,9 +160,27 @@ def generator_handler_exception(job):
160
160
'''
161
161
print (job )
162
162
yield "test1"
163
+ print ("Raise exception" )
163
164
raise Exception () # pylint: disable=broad-exception-raised
164
165
165
166
167
+ def test_generator_handler_exception ():
168
+ """ Test generator_handler_exception """
169
+ job = {"id" : "test_job" }
170
+ gen = generator_handler_exception (job )
171
+
172
+ # Process the first yielded value
173
+ output = next (gen )
174
+ assert output == "test1" , "First output should be 'test1'"
175
+
176
+ # Attempt to get the next value, expecting an exception
177
+ try :
178
+ next (gen )
179
+ assert False , "Expected an exception to be raised"
180
+ except Exception : # pylint: disable=broad-except
181
+ assert True , "Exception was caught as expected"
182
+
183
+
166
184
class TestRunWorker (IsolatedAsyncioTestCase ):
167
185
""" Tests for runpod | serverless| worker """
168
186
@@ -254,27 +272,27 @@ async def test_run_worker_generator_handler_exception(
254
272
'''
255
273
Test run_worker with generator handler.
256
274
257
- Args:
258
- mock_stream_result (_type_): _description_
259
- mock_run_job_generator (_type_): _description_
260
- mock_run_job (_type_): _description_
261
- mock_get_job (_type_): _description_
275
+ This test verifies that:
276
+ - `stream_result` is called exactly once before an exception occurs.
277
+ - `run_job` is never called since `handler` is a generator function.
278
+ - An error is correctly reported back via `send_result`.
262
279
'''
263
- # Define the mock behaviors
264
- mock_get_job .return_value = {
265
- "id" : "generator-123-exception" , "input" : {"number" : 1 }}
280
+ RunPodLogger ().set_level ("DEBUG" )
266
281
267
- # Test generator handler
268
- generator_config = {
269
- "handler" : generator_handler_exception , "refresh_worker" : True }
270
- runpod .serverless .start (generator_config )
282
+ # Setup: Mock `get_job` to return a predefined job.
283
+ mock_get_job .return_value = {"id" : "generator-123-exception" , "input" : {"number" : 1 }}
284
+
285
+ runpod .serverless .start ({
286
+ "handler" : generator_handler_exception ,
287
+ "refresh_worker" : True
288
+ })
271
289
272
290
assert mock_stream_result .call_count == 1
273
291
assert not mock_run_job .called
274
292
275
293
# Since return_aggregate_stream is NOT activated, we should not submit any outputs.
276
294
_ , args , _ = mock_send_result .mock_calls [0 ]
277
- assert 'error' in args [1 ]
295
+ assert 'error' in args [1 ], "Expected the error to be reported in the results."
278
296
279
297
@patch ("runpod.serverless.modules.rp_scale.get_job" )
280
298
@patch ("runpod.serverless.worker.run_job" )
0 commit comments