Skip to content

Commit

Permalink
Add unit tests with mocks for fetch_url function to simulate HTTP res…
Browse files Browse the repository at this point in the history
…ponses and errors
  • Loading branch information
aviolaris committed Oct 12, 2024
1 parent 9ab4452 commit 1e5afdf
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions tests/test_healthcheck.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""Imports"""
import unittest
from unittest.mock import patch, MagicMock
import requests
from app.healthcheck import fetch_url


class TestHealthCheck(unittest.TestCase):
"""Unit Tests"""

@patch('app.healthcheck.requests.get')
@patch('app.healthcheck.sys.exit')
def test_fetch_url_success(self, mock_exit, mock_get):
"""
Test fetch_url with a successful 200 status code
"""
mock_response = MagicMock()
mock_response.status_code = 200
mock_get.return_value = mock_response
fetch_url('http://localhost:5000')
mock_exit.assert_called_once_with(0)

@patch('app.healthcheck.requests.get')
@patch('app.healthcheck.sys.exit')
def test_fetch_url_non_200(self, mock_exit, mock_get):
"""
Test fetch_url with a non-200 status code
"""
mock_response = MagicMock()
mock_response.status_code = 500
mock_get.return_value = mock_response
fetch_url('http://localhost:5000')
mock_exit.assert_called_once_with(1)

@patch('app.healthcheck.requests.get', side_effect=requests.exceptions.Timeout)
@patch('app.healthcheck.sys.exit')
def test_fetch_url_timeout(self, mock_exit, _):
"""
Test fetch_url handling of a timeout exception
"""
fetch_url('http://localhost:5000')
mock_exit.assert_called_once_with(1)


if __name__ == '__main__':
unittest.main()

0 comments on commit 1e5afdf

Please sign in to comment.