-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_main.py
More file actions
938 lines (818 loc) · 34.6 KB
/
test_main.py
File metadata and controls
938 lines (818 loc) · 34.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
# pylint: disable=unused-argument
# Standard imports
import asyncio
import json
import random
import urllib.parse
from unittest.mock import AsyncMock, MagicMock, call, patch
# Third-party imports
from fastapi import FastAPI, Request
from mangum import Mangum
import pytest
# Local imports
from config import GITHUB_WEBHOOK_SECRET
from constants.general import PRODUCT_NAME
import main
from main import (
app,
mangum_handler,
handle_webhook,
handler,
root,
api_retarget_pr,
api_sync_files_from_github_to_coverage,
)
from payloads.aws.event_bridge_scheduler.event_types import EventBridgeSchedulerEvent
@pytest.fixture
def mock_github_request():
"""Create a mock request object for testing."""
mock_req = MagicMock(spec=Request)
mock_req.headers = {
"X-GitHub-Event": "push",
"X-GitHub-Delivery": f"test-delivery-{random.randint(1000000, 9999999)}",
}
mock_req.body = AsyncMock(return_value=b'{"key": "value"}')
return mock_req
@pytest.fixture
def mock_github_request_no_event_header():
"""Create a mock request object without X-GitHub-Event header."""
mock_req = MagicMock(spec=Request)
mock_req.headers = {
"X-GitHub-Delivery": f"test-delivery-{random.randint(1000000, 9999999)}",
}
mock_req.body = AsyncMock(return_value=b'{"key": "value"}')
return mock_req
@pytest.fixture
def mock_github_request_with_url_encoded_body():
"""Create a mock request with URL-encoded body."""
mock_req = MagicMock(spec=Request)
mock_req.headers = {
"X-GitHub-Event": "push",
"X-GitHub-Delivery": f"test-delivery-{random.randint(1000000, 9999999)}",
}
payload = json.dumps({"key": "value"})
encoded_body = f"payload={urllib.parse.quote(payload)}"
mock_req.body = AsyncMock(return_value=encoded_body.encode())
return mock_req
@pytest.fixture
def mock_github_request_with_malformed_url_encoded_body():
"""Create a mock request with malformed URL-encoded body."""
mock_req = MagicMock(spec=Request)
mock_req.headers = {
"X-GitHub-Event": "push",
"X-GitHub-Delivery": f"test-delivery-{random.randint(1000000, 9999999)}",
}
# URL-encoded body without payload key
encoded_body = "other_key=some_value"
mock_req.body = AsyncMock(return_value=encoded_body.encode())
return mock_req
@pytest.fixture
def mock_github_request_with_invalid_json_in_url_encoded():
"""Create a mock request with invalid JSON in URL-encoded payload."""
mock_req = MagicMock(spec=Request)
mock_req.headers = {
"X-GitHub-Event": "push",
"X-GitHub-Delivery": f"test-delivery-{random.randint(1000000, 9999999)}",
}
# URL-encoded body with invalid JSON in payload
encoded_body = "payload=invalid_json_content"
mock_req.body = AsyncMock(return_value=encoded_body.encode())
return mock_req
@pytest.fixture
def mock_event_bridge_event():
"""Create a mock EventBridge Scheduler event."""
return EventBridgeSchedulerEvent(
triggerType="schedule",
ownerName="test-owner",
repoName="test-repo",
ownerId=123456,
ownerType="Organization",
repoId=789012,
userId=345678,
userName="test-user",
installationId=901234,
)
@pytest.fixture
def mock_event_bridge_event_missing_names():
"""Create a mock EventBridge Scheduler event with missing owner/repo names."""
return {
"triggerType": "schedule",
# Missing ownerName and repoName to test default empty strings
"ownerId": 123456,
"ownerType": "Organization",
"repoId": 789012,
"userId": 345678,
"userName": "test-user",
"installationId": 901234,
}
class TestHandler:
@patch("main.schedule_handler")
@patch("main.slack_notify")
def test_handler_schedule_event_success(
self, mock_slack_notify, mock_schedule_handler, mock_event_bridge_event
):
"""Test handler function with a successful schedule event."""
# Setup
mock_slack_notify.return_value = "thread-123"
mock_schedule_handler.return_value = {"status": "success"}
# Execute
result = handler(event=mock_event_bridge_event, context={})
# Verify
mock_schedule_handler.assert_called_with(event=mock_event_bridge_event)
mock_slack_notify.assert_has_calls(
[
call("Event Scheduler started for test-owner/test-repo"),
call("Completed", "thread-123"),
]
)
assert mock_slack_notify.call_count == 2
assert result is None
@patch("main.schedule_handler")
@patch("main.slack_notify")
def test_handler_schedule_event_failure(
self, mock_slack_notify, mock_schedule_handler, mock_event_bridge_event
):
"""Test handler function with a failed schedule event."""
# Setup
mock_slack_notify.return_value = "thread-123"
mock_schedule_handler.return_value = {
"status": "error",
"message": "Something went wrong",
}
# Execute
result = handler(event=mock_event_bridge_event, context={})
# Verify
mock_schedule_handler.assert_called_with(event=mock_event_bridge_event)
mock_slack_notify.assert_has_calls(
[
call("Event Scheduler started for test-owner/test-repo"),
call("<!channel> Failed: Something went wrong", "thread-123"),
]
)
assert mock_slack_notify.call_count == 2
assert result is None
@patch("main.schedule_handler")
@patch("main.slack_notify")
def test_handler_schedule_event_missing_owner_repo_names(
self,
mock_slack_notify,
mock_schedule_handler,
mock_event_bridge_event_missing_names,
):
"""Test handler function with schedule event missing owner/repo names."""
# Setup
mock_slack_notify.return_value = "thread-456"
mock_schedule_handler.return_value = {"status": "success"}
# Execute
result = handler(event=mock_event_bridge_event_missing_names, context={})
# Verify
mock_schedule_handler.assert_called_with(
event=mock_event_bridge_event_missing_names
)
mock_slack_notify.assert_has_calls(
[
call("Event Scheduler started for /"), # Empty owner/repo names
call("Completed", "thread-456"),
]
)
assert mock_slack_notify.call_count == 2
assert result is None
@patch("main.mangum_handler")
def test_handler_non_schedule_event(self, mock_mangum_handler):
"""Test handler function with a non-schedule event."""
# Setup
event = {"key": "value", "triggerType": "not-schedule"} # Not a schedule event
context = {"context": "data"}
mock_mangum_handler.return_value = {"status": "success"}
# Execute
result = handler(event=event, context=context)
# Verify
mock_mangum_handler.assert_called_with(event=event, context=context)
assert result == {"status": "success"}
@patch("main.mangum_handler")
def test_handler_without_trigger_type(self, mock_mangum_handler):
"""Test handler function with an event that doesn't have triggerType."""
# Setup
event = {"key": "value"} # No triggerType
context = {"context": "data"}
mock_mangum_handler.return_value = {"status": "success"}
# Execute
result = handler(event=event, context=context)
# Verify
mock_mangum_handler.assert_called_with(event=event, context=context)
assert result == {"status": "success"}
class TestHandleWebhook:
@patch("main.insert_webhook_delivery")
@patch("main.extract_lambda_info")
@patch("main.verify_webhook_signature", new_callable=AsyncMock)
@patch("main.handle_webhook_event", new_callable=AsyncMock)
@pytest.mark.asyncio
async def test_handle_webhook_success(
self,
mock_handle_webhook_event,
mock_verify_signature,
mock_extract_lambda_info,
mock_insert_webhook_delivery,
mock_github_request,
):
"""Test handle_webhook function with successful execution."""
# Setup
mock_insert_webhook_delivery.return_value = True
mock_verify_signature.return_value = None
mock_handle_webhook_event.return_value = None
mock_extract_lambda_info.return_value = {
"log_group": "/aws/lambda/pr-agent-prod",
"log_stream": "2025/09/04/pr-agent-prod[$LATEST]841315c5",
"request_id": "17921070-5cb6-43ee-8d2e-b5161ae89729",
}
# Execute
response = await handle_webhook(request=mock_github_request)
# Verify
mock_verify_signature.assert_called_once_with(
request=mock_github_request, secret=GITHUB_WEBHOOK_SECRET
)
mock_extract_lambda_info.assert_called_once_with(mock_github_request)
call_args = mock_handle_webhook_event.call_args
assert call_args.kwargs["event_name"] == "push"
assert call_args.kwargs["payload"] == {"key": "value"}
assert (
call_args.kwargs["lambda_info"]["log_group"] == "/aws/lambda/pr-agent-prod"
)
assert (
call_args.kwargs["lambda_info"]["log_stream"]
== "2025/09/04/pr-agent-prod[$LATEST]841315c5"
)
assert (
call_args.kwargs["lambda_info"]["request_id"]
== "17921070-5cb6-43ee-8d2e-b5161ae89729"
)
assert "delivery_id" in call_args.kwargs["lambda_info"]
assert response == {"message": "Webhook processed successfully"}
@patch("main.extract_lambda_info")
@patch("main.verify_webhook_signature", new_callable=AsyncMock)
@patch("main.handle_webhook_event", new_callable=AsyncMock)
@pytest.mark.asyncio
async def test_handle_webhook_no_event_header(
self,
mock_handle_webhook_event,
mock_verify_signature,
mock_extract_lambda_info,
mock_github_request_no_event_header,
):
"""Test handle_webhook function when X-GitHub-Event header is missing."""
# Setup
mock_verify_signature.return_value = None
mock_handle_webhook_event.return_value = None
mock_extract_lambda_info.return_value = {}
# Execute
response = await handle_webhook(request=mock_github_request_no_event_header)
# Verify
mock_verify_signature.assert_called_once_with(
request=mock_github_request_no_event_header, secret=GITHUB_WEBHOOK_SECRET
)
mock_extract_lambda_info.assert_called_once_with(
mock_github_request_no_event_header
)
call_args = mock_handle_webhook_event.call_args
assert call_args.kwargs["event_name"] == "Event not specified"
assert call_args.kwargs["payload"] == {"key": "value"}
assert "delivery_id" in call_args.kwargs["lambda_info"]
assert response == {"message": "Webhook processed successfully"}
@patch("main.extract_lambda_info")
@patch("main.verify_webhook_signature", new_callable=AsyncMock)
@patch("main.handle_webhook_event", new_callable=AsyncMock)
@pytest.mark.asyncio
async def test_handle_webhook_body_error(
self,
mock_handle_webhook_event,
mock_verify_signature,
mock_extract_lambda_info,
mock_github_request,
):
"""Test handle_webhook function when request.body() raises an exception."""
# Setup
mock_verify_signature.return_value = None
mock_github_request.body.side_effect = Exception("Body error")
mock_extract_lambda_info.return_value = {}
# Execute
response = await handle_webhook(request=mock_github_request)
# Verify
mock_verify_signature.assert_called_once_with(
request=mock_github_request, secret=GITHUB_WEBHOOK_SECRET
)
mock_extract_lambda_info.assert_called_once_with(mock_github_request)
call_args = mock_handle_webhook_event.call_args
assert call_args.kwargs["event_name"] == "push"
assert call_args.kwargs["payload"] == {}
assert "delivery_id" in call_args.kwargs["lambda_info"]
assert response == {"message": "Webhook processed successfully"}
@patch("main.extract_lambda_info")
@patch("main.verify_webhook_signature", new_callable=AsyncMock)
@patch("main.handle_webhook_event", new_callable=AsyncMock)
@pytest.mark.asyncio
async def test_handle_webhook_json_decode_error(
self,
mock_handle_webhook_event,
mock_verify_signature,
mock_extract_lambda_info,
mock_github_request,
):
"""Test handle_webhook function when JSON decoding fails."""
# Setup
mock_verify_signature.return_value = None
mock_github_request.body.return_value = b"invalid json"
mock_extract_lambda_info.return_value = {}
# Execute
response = await handle_webhook(request=mock_github_request)
# Verify
mock_verify_signature.assert_called_once_with(
request=mock_github_request, secret=GITHUB_WEBHOOK_SECRET
)
mock_extract_lambda_info.assert_called_once_with(mock_github_request)
call_args = mock_handle_webhook_event.call_args
assert call_args.kwargs["event_name"] == "push"
assert call_args.kwargs["payload"] == {}
assert "delivery_id" in call_args.kwargs["lambda_info"]
assert response == {"message": "Webhook processed successfully"}
@patch("main.extract_lambda_info")
@patch("main.verify_webhook_signature", new_callable=AsyncMock)
@patch("main.handle_webhook_event", new_callable=AsyncMock)
@pytest.mark.asyncio
async def test_handle_webhook_url_encoded_payload(
self,
mock_handle_webhook_event,
mock_verify_signature,
mock_extract_lambda_info,
mock_github_request_with_url_encoded_body,
):
"""Test handle_webhook function with URL-encoded payload."""
# Setup
mock_verify_signature.return_value = None
mock_handle_webhook_event.return_value = None
mock_extract_lambda_info.return_value = {"log_group": "test-group"}
# Execute
response = await handle_webhook(
request=mock_github_request_with_url_encoded_body
)
# Verify
mock_verify_signature.assert_called_once_with(
request=mock_github_request_with_url_encoded_body,
secret=GITHUB_WEBHOOK_SECRET,
)
mock_extract_lambda_info.assert_called_once_with(
mock_github_request_with_url_encoded_body
)
call_args = mock_handle_webhook_event.call_args
assert call_args.kwargs["event_name"] == "push"
assert call_args.kwargs["payload"] == {"key": "value"}
assert call_args.kwargs["lambda_info"]["log_group"] == "test-group"
assert "delivery_id" in call_args.kwargs["lambda_info"]
assert response == {"message": "Webhook processed successfully"}
@patch("main.extract_lambda_info")
@patch("main.verify_webhook_signature", new_callable=AsyncMock)
@patch("main.handle_webhook_event", new_callable=AsyncMock)
@pytest.mark.asyncio
async def test_handle_webhook_url_encoded_without_payload_key(
self,
mock_handle_webhook_event,
mock_verify_signature,
mock_extract_lambda_info,
mock_github_request_with_malformed_url_encoded_body,
):
"""Test handle_webhook function with URL-encoded body without payload key."""
# Setup
mock_verify_signature.return_value = None
mock_handle_webhook_event.return_value = None
mock_extract_lambda_info.return_value = {}
# Execute
response = await handle_webhook(
request=mock_github_request_with_malformed_url_encoded_body
)
# Verify
mock_verify_signature.assert_called_once_with(
request=mock_github_request_with_malformed_url_encoded_body,
secret=GITHUB_WEBHOOK_SECRET,
)
mock_extract_lambda_info.assert_called_once_with(
mock_github_request_with_malformed_url_encoded_body
)
call_args = mock_handle_webhook_event.call_args
assert call_args.kwargs["event_name"] == "push"
assert call_args.kwargs["payload"] == {}
assert "delivery_id" in call_args.kwargs["lambda_info"]
assert response == {"message": "Webhook processed successfully"}
@patch("main.extract_lambda_info")
@patch("main.verify_webhook_signature", new_callable=AsyncMock)
@patch("main.handle_webhook_event", new_callable=AsyncMock)
@pytest.mark.asyncio
async def test_handle_webhook_url_encoded_invalid_json_payload(
self,
mock_handle_webhook_event,
mock_verify_signature,
mock_extract_lambda_info,
mock_github_request_with_invalid_json_in_url_encoded,
):
"""Test handle_webhook function with invalid JSON in URL-encoded payload."""
# Setup
mock_verify_signature.return_value = None
mock_handle_webhook_event.return_value = None
mock_extract_lambda_info.return_value = {}
# Execute
response = await handle_webhook(
request=mock_github_request_with_invalid_json_in_url_encoded
)
# Verify
mock_verify_signature.assert_called_once_with(
request=mock_github_request_with_invalid_json_in_url_encoded,
secret=GITHUB_WEBHOOK_SECRET,
)
mock_extract_lambda_info.assert_called_once_with(
mock_github_request_with_invalid_json_in_url_encoded
)
call_args = mock_handle_webhook_event.call_args
assert call_args.kwargs["event_name"] == "push"
assert call_args.kwargs["payload"] == {}
assert "delivery_id" in call_args.kwargs["lambda_info"]
assert response == {"message": "Webhook processed successfully"}
@patch("main.insert_webhook_delivery")
@patch("main.extract_lambda_info")
@patch("main.verify_webhook_signature", new_callable=AsyncMock)
@patch("main.handle_webhook_event", new_callable=AsyncMock)
@pytest.mark.asyncio
async def test_handle_webhook_general_exception_in_json_parsing(
self,
mock_handle_webhook_event,
mock_verify_signature,
mock_extract_lambda_info,
mock_insert_webhook_delivery,
mock_github_request,
):
"""Test handle_webhook function when a general exception occurs during JSON parsing."""
# Setup
mock_insert_webhook_delivery.return_value = True
mock_verify_signature.return_value = None
mock_handle_webhook_event.return_value = None
mock_extract_lambda_info.return_value = {}
# Mock json.loads to raise a general exception (not JSONDecodeError)
with patch("main.json.loads", side_effect=Exception("General parsing error")):
# Execute
response = await handle_webhook(request=mock_github_request)
# Verify
mock_verify_signature.assert_called_once_with(
request=mock_github_request, secret=GITHUB_WEBHOOK_SECRET
)
mock_extract_lambda_info.assert_called_once_with(mock_github_request)
call_args = mock_handle_webhook_event.call_args
assert call_args.kwargs["event_name"] == "push"
assert call_args.kwargs["payload"] == {}
assert "delivery_id" in call_args.kwargs["lambda_info"]
assert response == {"message": "Webhook processed successfully"}
@patch("main.extract_lambda_info")
@patch("main.verify_webhook_signature", new_callable=AsyncMock)
@patch("main.handle_webhook_event", new_callable=AsyncMock)
@pytest.mark.asyncio
async def test_handle_webhook_with_custom_event_name(
self,
mock_handle_webhook_event,
mock_verify_signature,
mock_extract_lambda_info,
mock_github_request,
):
"""Test handle_webhook function with a custom event name."""
# Setup
mock_verify_signature.return_value = None
mock_handle_webhook_event.return_value = None
mock_github_request.headers = {
"X-GitHub-Event": "issue_comment",
"X-GitHub-Delivery": f"test-delivery-{random.randint(1000000, 9999999)}",
}
mock_extract_lambda_info.return_value = {"request_id": "test-request-123"}
# Execute
response = await handle_webhook(request=mock_github_request)
# Verify
mock_verify_signature.assert_called_once_with(
request=mock_github_request, secret=GITHUB_WEBHOOK_SECRET
)
mock_extract_lambda_info.assert_called_once_with(mock_github_request)
call_args = mock_handle_webhook_event.call_args
assert call_args.kwargs["event_name"] == "issue_comment"
assert call_args.kwargs["payload"] == {"key": "value"}
assert call_args.kwargs["lambda_info"]["request_id"] == "test-request-123"
assert "delivery_id" in call_args.kwargs["lambda_info"]
assert response == {"message": "Webhook processed successfully"}
class TestRootEndpoint:
@pytest.mark.asyncio
async def test_root_endpoint(self):
"""Test root endpoint returns correct product name."""
response = await root()
assert response == {"message": PRODUCT_NAME}
class TestAppConfiguration:
def test_app_routes(self):
"""Test that the FastAPI app has the expected routes."""
# Simple test to verify app has routes
assert len(app.routes) > 0
# Test that we can access the root endpoint
result = asyncio.run(root())
assert result == {"message": PRODUCT_NAME}
def test_app_instance(self):
"""Test that the FastAPI app instance is properly configured."""
assert isinstance(app, FastAPI)
assert app is not None
def test_mangum_handler_instance(self):
"""Test that the Mangum handler is properly configured."""
assert isinstance(mangum_handler, Mangum)
assert mangum_handler is not None
def test_app_routes_configuration(self):
"""Test that the FastAPI app has the expected route paths."""
route_paths = [
getattr(route, "path") for route in app.routes if hasattr(route, "path")
]
# Check that expected routes exist
assert "/" in route_paths
assert "/webhook" in route_paths
class TestEdgeCases:
@patch("main.extract_lambda_info")
@patch("main.verify_webhook_signature", new_callable=AsyncMock)
@patch("main.handle_webhook_event", new_callable=AsyncMock)
@pytest.mark.asyncio
async def test_handle_webhook_empty_body(
self,
mock_handle_webhook_event,
mock_verify_signature,
mock_extract_lambda_info,
):
"""Test handle_webhook function with empty request body."""
# Setup
mock_req = MagicMock(spec=Request)
mock_req.headers = {
"X-GitHub-Event": "ping",
"X-GitHub-Delivery": f"test-delivery-{random.randint(1000000, 9999999)}",
}
mock_req.body = AsyncMock(return_value=b"")
mock_verify_signature.return_value = None
mock_handle_webhook_event.return_value = None
mock_extract_lambda_info.return_value = {}
# Execute
response = await handle_webhook(request=mock_req)
# Verify
mock_verify_signature.assert_called_once_with(
request=mock_req, secret=GITHUB_WEBHOOK_SECRET
)
mock_extract_lambda_info.assert_called_once_with(mock_req)
call_args = mock_handle_webhook_event.call_args
assert call_args.kwargs["event_name"] == "ping"
assert call_args.kwargs["payload"] == {}
assert "delivery_id" in call_args.kwargs["lambda_info"]
assert response == {"message": "Webhook processed successfully"}
@patch("main.schedule_handler")
@patch("main.slack_notify")
def test_handler_schedule_event_with_none_result_status(
self, mock_slack_notify, mock_schedule_handler, mock_event_bridge_event
):
"""Test handler function when schedule_handler returns None status."""
# Setup
mock_slack_notify.return_value = "thread-789"
mock_schedule_handler.return_value = {
"status": None,
"message": "Unknown status",
}
# Execute
result = handler(event=mock_event_bridge_event, context={})
# Verify
mock_schedule_handler.assert_called_with(event=mock_event_bridge_event)
mock_slack_notify.assert_has_calls(
[
call("Event Scheduler started for test-owner/test-repo"),
call("<!channel> Failed: Unknown status", "thread-789"),
]
)
assert mock_slack_notify.call_count == 2
assert result is None
@patch("main.extract_lambda_info")
@patch("main.verify_webhook_signature", new_callable=AsyncMock)
@patch("main.handle_webhook_event", new_callable=AsyncMock)
@pytest.mark.asyncio
async def test_handle_webhook_with_unicode_content(
self,
mock_handle_webhook_event,
mock_verify_signature,
mock_extract_lambda_info,
):
"""Test handle_webhook function with Unicode content in request body."""
# Setup
mock_req = MagicMock(spec=Request)
mock_req.headers = {
"X-GitHub-Event": "issues",
"X-GitHub-Delivery": f"test-delivery-{random.randint(1000000, 9999999)}",
}
unicode_content = '{"title": "测试 Unicode 内容", "body": "🚀 Emoji test"}'
mock_req.body = AsyncMock(return_value=unicode_content.encode("utf-8"))
mock_verify_signature.return_value = None
mock_handle_webhook_event.return_value = None
mock_extract_lambda_info.return_value = {}
# Execute
response = await handle_webhook(request=mock_req)
# Verify
mock_verify_signature.assert_called_once_with(
request=mock_req, secret=GITHUB_WEBHOOK_SECRET
)
mock_extract_lambda_info.assert_called_once_with(mock_req)
call_args = mock_handle_webhook_event.call_args
assert call_args.kwargs["event_name"] == "issues"
assert call_args.kwargs["payload"] == {
"title": "测试 Unicode 内容",
"body": "🚀 Emoji test",
}
assert "delivery_id" in call_args.kwargs["lambda_info"]
assert response == {"message": "Webhook processed successfully"}
@patch("main.schedule_handler")
@patch("main.slack_notify")
def test_handler_schedule_event_with_missing_message_in_result(
self, mock_slack_notify, mock_schedule_handler, mock_event_bridge_event
):
"""Test handler function when schedule_handler returns error status without message."""
# Setup
mock_slack_notify.return_value = "thread-999"
mock_schedule_handler.return_value = {
"status": "error"
} # Missing 'message' key
# Execute
result = handler(event=mock_event_bridge_event, context={})
# Verify
mock_schedule_handler.assert_called_with(event=mock_event_bridge_event)
mock_slack_notify.assert_has_calls(
[
call("Event Scheduler started for test-owner/test-repo"),
call("<!channel> Failed: Unknown error", "thread-999"),
]
)
assert mock_slack_notify.call_count == 2
assert result is None
class TestLogStatements:
@patch("main.logger")
@patch("main.schedule_handler")
@patch("main.slack_notify")
def test_handler_schedule_event_logs_message(
self,
mock_slack_notify,
mock_schedule_handler,
mock_logger,
mock_event_bridge_event,
):
"""Test that handler function logs the correct message for schedule events."""
# Setup
mock_slack_notify.return_value = "thread-123"
mock_schedule_handler.return_value = {"status": "success"}
# Execute
handler(event=mock_event_bridge_event, context={})
# Verify
mock_logger.info.assert_called_once_with("EventBridge Scheduler invoked")
@patch("main.logger")
@patch("main.extract_lambda_info")
@patch("main.verify_webhook_signature", new_callable=AsyncMock)
@patch("main.handle_webhook_event", new_callable=AsyncMock)
@pytest.mark.asyncio
async def test_handle_webhook_logs_body_error(
self,
mock_handle_webhook_event,
mock_verify_signature,
mock_extract_lambda_info,
mock_logger,
mock_github_request,
):
"""Test that handle_webhook logs error message when body reading fails."""
# Setup
mock_verify_signature.return_value = None
mock_github_request.body.side_effect = Exception("Body read error")
mock_extract_lambda_info.return_value = {}
# Execute
await handle_webhook(request=mock_github_request)
# Verify
mock_logger.error.assert_called_once()
call_args = mock_logger.error.call_args
assert call_args[0][0] == "Error reading request body: %s"
assert str(call_args[0][1]) == "Body read error"
@patch("main.logger")
@patch("main.insert_webhook_delivery")
@patch("main.extract_lambda_info")
@patch("main.verify_webhook_signature", new_callable=AsyncMock)
@patch("main.handle_webhook_event", new_callable=AsyncMock)
@pytest.mark.asyncio
async def test_handle_webhook_logs_json_parsing_error(
self,
mock_handle_webhook_event,
mock_verify_signature,
mock_extract_lambda_info,
mock_insert_webhook_delivery,
mock_logger,
mock_github_request,
):
"""Test that handle_webhook logs error message when JSON parsing fails."""
# Setup
mock_verify_signature.return_value = None
mock_extract_lambda_info.return_value = {}
mock_insert_webhook_delivery.return_value = True
# Mock json.loads to raise a general exception
with patch("main.json.loads", side_effect=Exception("JSON parsing error")):
# Execute
await handle_webhook(request=mock_github_request)
# Verify
mock_logger.error.assert_called_once()
call_args = mock_logger.error.call_args
assert call_args[0][0] == "Error parsing JSON payload: %s"
assert str(call_args[0][1]) == "JSON parsing error"
class TestEventLoopSetup:
@patch("main.mangum_handler")
def test_handler_creates_event_loop_when_missing(self, mock_mangum_handler):
"""Python 3.14 removed implicit event loop creation in asyncio.get_event_loop().
Verify handler creates one before calling mangum_handler."""
event = {"key": "value"}
context = {"context": "data"}
mock_mangum_handler.return_value = {"status": "success"}
# Remove the current event loop to simulate Python 3.14 behavior
policy = asyncio.get_event_loop_policy()
policy.set_event_loop(None) # type: ignore[arg-type]
# handler() should NOT raise RuntimeError — it ensures a loop exists
result = handler(event=event, context=context)
mock_mangum_handler.assert_called_with(event=event, context=context)
assert result == {"status": "success"}
# Verify an event loop now exists
loop = asyncio.get_event_loop()
assert loop is not None
class TestModuleImports:
def test_required_imports_available(self):
"""Test that all required modules and functions are properly imported."""
# Test FastAPI app
assert hasattr(main, "app")
assert hasattr(main, "mangum_handler")
# Test handler functions
assert hasattr(main, "handler")
assert hasattr(main, "handle_webhook")
assert hasattr(main, "root")
# Test that functions are callable
assert callable(main.handler)
assert callable(main.handle_webhook)
assert callable(main.root)
class TestTypeAnnotations:
@pytest.mark.asyncio
async def test_handle_webhook_return_type(self, mock_github_request):
"""Test that handle_webhook returns the correct type."""
with patch("main.extract_lambda_info"), patch(
"main.verify_webhook_signature", new_callable=AsyncMock
), patch("main.handle_webhook_event", new_callable=AsyncMock):
result = await handle_webhook(request=mock_github_request)
# Should return a dictionary with string keys and values
assert isinstance(result, dict)
assert all(isinstance(k, str) for k in result.keys())
assert all(isinstance(v, str) for v in result.values())
@pytest.mark.asyncio
async def test_root_return_type(self):
"""Test that root endpoint returns the correct type."""
result = await root()
assert isinstance(result, dict)
assert all(isinstance(k, str) for k in result.keys())
class TestApiRetargetPr:
@patch("main.retarget_pr")
@patch("main.get_installation_access_token", return_value="fake-token")
@pytest.mark.asyncio
async def test_api_retarget_pr_uses_background_task(
self, mock_get_token, mock_retarget
):
mock_background_tasks = MagicMock()
result = await api_retarget_pr(
owner="test-owner",
repo="test-repo",
body=MagicMock(
installation_id=123, new_base_branch="develop", pr_number=42
),
background_tasks=mock_background_tasks,
api_key="test-api-key",
)
mock_background_tasks.add_task.assert_called_once()
call_kwargs = mock_background_tasks.add_task.call_args.kwargs
assert call_kwargs["owner_name"] == "test-owner"
assert call_kwargs["repo_name"] == "test-repo"
assert call_kwargs["token"] == "fake-token"
assert call_kwargs["new_base_branch"] == "develop"
assert call_kwargs["pr_number"] == 42
assert call_kwargs["installation_id"] == 123
assert result == {"status": "processing"}
class TestApiSyncFilesFromGithubToCoverage:
@patch("main.sync_files_from_github_to_coverage")
@pytest.mark.asyncio
async def test_api_sync_files_success(self, mock_sync_files):
mock_background_tasks = MagicMock()
result = await api_sync_files_from_github_to_coverage(
owner="test-owner",
repo="test-repo",
body=MagicMock(branch="main", owner_id=123, repo_id=456, user_name="user"),
background_tasks=mock_background_tasks,
api_key="test-api-key",
)
mock_background_tasks.add_task.assert_called_once()
call_kwargs = mock_background_tasks.add_task.call_args.kwargs
assert call_kwargs["owner"] == "test-owner"
assert call_kwargs["repo"] == "test-repo"
assert call_kwargs["branch"] == "main"
assert call_kwargs["api_key"] == "test-api-key"
assert result == {"status": "syncing"}