Skip to content

Commit c10a8ca

Browse files
committed
Improve unit tests for the slack notifier module
1 parent e2b28ad commit c10a8ca

File tree

4 files changed

+329
-142
lines changed

4 files changed

+329
-142
lines changed

src/models/service_quality_oracle.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,19 +41,20 @@ def main(run_date_override: date = None):
4141
run_date_override: If provided, use this date for the run instead of today.
4242
"""
4343
start_time = time.time()
44-
slack_notifier = None
4544
stage = "Initialization"
4645
project_root_path = Path(__file__).resolve().parents[2]
46+
slack_notifier = None
4747

4848
try:
4949
# Configuration and credentials
50-
credential_manager.setup_google_credentials()
5150
config = load_config()
5251
slack_notifier = create_slack_notifier(config.get("SLACK_WEBHOOK_URL"))
52+
5353
if slack_notifier:
5454
logger.info("Slack notifications enabled")
5555
else:
5656
logger.info("Slack notifications disabled (no webhook URL configured)")
57+
credential_manager.setup_google_credentials()
5758

5859
# Define the date for the current run
5960
current_run_date = run_date_override or date.today()

src/utils/slack_notifier.py

Lines changed: 20 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,11 @@ def __init__(self, webhook_url: str) -> None:
3030

3131

3232
@retry_with_backoff(
33-
max_attempts=8, min_wait=1, max_wait=128, exceptions=(requests.exceptions.RequestException,)
33+
max_attempts=8,
34+
min_wait=1,
35+
max_wait=128,
36+
exceptions=(requests.exceptions.RequestException,),
37+
reraise=True,
3438
)
3539
def _send_message(self, payload: Dict) -> bool:
3640
"""
@@ -40,37 +44,28 @@ def _send_message(self, payload: Dict) -> bool:
4044
payload: The message payload to send
4145
4246
Returns:
43-
bool: True if message was sent successfully, False otherwise
47+
bool: True if message was sent successfully.
48+
Raises:
49+
requests.exceptions.RequestException: If the request fails after all retries.
4450
"""
4551
# Get the message type from the payload
4652
message_type = payload.get("text", "Unknown")
4753

4854
# Log the message type
4955
logger.info(f"Sending Slack notification: {message_type}")
5056

51-
try:
52-
response = requests.post(
53-
self.webhook_url,
54-
json=payload,
55-
timeout=self.timeout,
56-
headers={"Content-Type": "application/json"},
57-
)
58-
59-
# If the message is sent successfully, return True
60-
if response.status_code == 200:
61-
logger.info("Slack notification sent successfully")
62-
return True
63-
else:
64-
# log message failure
65-
logger.warning(f"Slack notification failed: {response.status_code}")
66-
# Raise an exception to trigger retry
67-
response.raise_for_status()
68-
return False
69-
70-
# If there is an error when trying to send the message, log the error and re-raise
71-
except requests.exceptions.RequestException as e:
72-
logger.warning(f"Slack notification failed: {str(e)}")
73-
raise
57+
response = requests.post(
58+
self.webhook_url,
59+
json=payload,
60+
timeout=self.timeout,
61+
headers={"Content-Type": "application/json"},
62+
)
63+
# Raise an exception for 4xx/5xx responses
64+
response.raise_for_status()
65+
66+
# If the message is sent successfully, return True
67+
logger.info("Slack notification sent successfully")
68+
return True
7469

7570

7671
def _create_payload(self, text: str, fields: List[Dict], color: str = "good") -> Dict:

tests/test_service_quality_oracle.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,8 +159,8 @@ def test_main_handles_failures_gracefully(oracle_context, failing_component, exp
159159
f"Oracle failed at stage '{expected_stage}': {error}", exc_info=True
160160
)
161161

162-
# If Slack notifier creation fails, no notification can be sent.
163-
if failing_component == "slack_create":
162+
# If config loading or Slack notifier creation fails, no notification can be sent.
163+
if failing_component in ["load_config", "slack_create"]:
164164
ctx["slack"]["notifier"].send_failure_notification.assert_not_called()
165165
else:
166166
ctx["slack"]["notifier"].send_failure_notification.assert_called_once()
@@ -186,6 +186,7 @@ def test_main_with_no_eligible_indexers(oracle_context):
186186
"""Test the execution path when the pipeline finds no eligible indexers."""
187187
ctx = oracle_context
188188
ctx["pipeline"].process.return_value = ([], ["0xIneligible"])
189+
ctx["client"].batch_allow_indexers_issuance_eligibility.return_value = [] # No txns
189190

190191
ctx["main"]()
191192

@@ -198,6 +199,12 @@ def test_main_with_no_eligible_indexers(oracle_context):
198199
replace=True,
199200
)
200201
ctx["slack"]["notifier"].send_success_notification.assert_called_once()
202+
# Verify the contents of the success notification for the zero-eligible case
203+
call_kwargs = ctx["slack"]["notifier"].send_success_notification.call_args.kwargs
204+
assert call_kwargs["eligible_indexers"] == []
205+
assert call_kwargs["total_processed"] == 0
206+
assert call_kwargs["transaction_links"] == []
207+
assert call_kwargs["batch_count"] == 0
201208

202209

203210
def test_main_no_slack_configured(oracle_context):

0 commit comments

Comments
 (0)