Skip to content

Commit

Permalink
Add: Unit tests for retrying of requests in NVDApi
Browse files Browse the repository at this point in the history
  • Loading branch information
n-thumann committed Dec 6, 2024
1 parent 0ee1fae commit f888815
Showing 1 changed file with 47 additions and 1 deletion.
48 changes: 47 additions & 1 deletion tests/nvd/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import unittest
from datetime import datetime
from typing import Any, Iterator
from unittest.mock import AsyncMock, MagicMock, patch
from unittest.mock import AsyncMock, MagicMock, call, patch

from httpx import AsyncClient, Response

Expand Down Expand Up @@ -129,6 +129,52 @@ async def test_no_rate_limit(

sleep_mock.assert_not_called()

@patch("pontos.nvd.api.asyncio.sleep", autospec=True)
@patch("pontos.nvd.api.AsyncClient", spec=AsyncClient)
async def test_retry(
self,
async_client: MagicMock,
sleep_mock: MagicMock,
):
response_mocks = [
MagicMock(spec=Response, status_code=500),
MagicMock(spec=Response, status_code=500),
MagicMock(spec=Response, status_code=500),
MagicMock(spec=Response, status_code=200),
]
http_client = AsyncMock()
http_client.get.side_effect = response_mocks
async_client.return_value = http_client

api = NVDApi("https://foo.bar/baz", request_attempts=4)

result = await api._get()

calls = [call(2.0), call(4.0), call(8.0)]
sleep_mock.assert_has_calls(calls)
self.assertEqual(result.status_code, 200)

@patch("pontos.nvd.api.asyncio.sleep", autospec=True)
@patch("pontos.nvd.api.AsyncClient", spec=AsyncClient)
async def test_no_retry(
self,
async_client: MagicMock,
sleep_mock: MagicMock,
):
response_mock = MagicMock(spec=Response)
response_mock.status_code = 200

http_client = AsyncMock()
http_client.get.return_value = response_mock
async_client.return_value = http_client

api = NVDApi("https://foo.bar/baz")

result = await api._get()

sleep_mock.assert_not_called()
self.assertEqual(result.status_code, 200)


class Result:
def __init__(self, value: int) -> None:
Expand Down

0 comments on commit f888815

Please sign in to comment.