Skip to content

Commit

Permalink
Fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
itssimon committed Aug 15, 2023
1 parent ddda0cc commit 500f902
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 28 deletions.
12 changes: 6 additions & 6 deletions starlette_apitally/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,9 @@ def __init__(self, client_id: str, env: str, enable_keys: bool = False, send_eve
self._stop_sync_loop = False
self.start_sync_loop()

@property
def base_url(self) -> str:
return f"{HUB_BASE_URL}/{HUB_VERSION}/{self.client_id}/{self.env}"
def get_http_client(self) -> httpx.AsyncClient:
base_url = f"{HUB_BASE_URL}/{HUB_VERSION}/{self.client_id}/{self.env}"
return httpx.AsyncClient(base_url=base_url)

def start_sync_loop(self) -> None:
self._stop_sync_loop = False
Expand All @@ -73,7 +73,7 @@ async def _run_sync_loop(self) -> None:
while not self._stop_sync_loop:
try:
await asyncio.sleep(self.send_every)
async with httpx.AsyncClient(base_url=self.base_url) as client:
async with self.get_http_client() as client:
await self.send_requests_data(client)
if self.enable_keys:
await self._get_keys(client)

Check warning on line 79 in starlette_apitally/client.py

View check run for this annotation

Codecov / codecov/patch

starlette_apitally/client.py#L76-L79

Added lines #L76 - L79 were not covered by tests
Expand All @@ -94,7 +94,7 @@ def send_app_info(self, app: ASGIApp, app_version: Optional[str], openapi_url: O

@retry
async def _send_app_info(self, payload: Any) -> None:
async with httpx.AsyncClient(base_url=self.base_url) as client:
async with self.get_http_client() as client:
response = await client.post(url="/info", json=payload)
if response.status_code == 404 and "Client ID" in response.text:
self.stop_sync_loop()
Expand All @@ -119,7 +119,7 @@ async def _send_requests_data(self, client: httpx.AsyncClient, payload: Any) ->
response.raise_for_status()

async def get_keys(self) -> None:
async with httpx.AsyncClient(base_url=self.base_url) as client:
async with self.get_http_client() as client:
await self._get_keys(client)

@retry
Expand Down
1 change: 0 additions & 1 deletion starlette_apitally/fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ async def __call__(self, request: Request) -> Optional[Key]:
keys = self._get_keys()
key = keys.get(param)
if key is None and self.auto_error:
print(keys.keys)
raise HTTPException(

Check warning on line 38 in starlette_apitally/fastapi.py

View check run for this annotation

Codecov / codecov/patch

starlette_apitally/fastapi.py#L34-L38

Added lines #L34 - L38 were not covered by tests
status_code=HTTP_403_FORBIDDEN,
detail="Invalid API key",
Expand Down
52 changes: 31 additions & 21 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import asyncio
import json
from typing import TYPE_CHECKING, AsyncIterator
from typing import TYPE_CHECKING
from unittest.mock import MagicMock

import pytest
Expand All @@ -18,34 +18,32 @@


@pytest.fixture()
async def client() -> AsyncIterator[ApitallyClient]:
async def client() -> ApitallyClient:
from starlette_apitally.client import ApitallyClient

client = ApitallyClient(client_id=CLIENT_ID, env="default", send_every=0.01)
try:
client.requests.log_request(
method="GET",
path="/test",
status_code=200,
response_time=0.105,
)
client.requests.log_request(
method="GET",
path="/test",
status_code=200,
response_time=0.227,
)
yield client
finally:
client.stop_sync_loop()
await asyncio.sleep(0.02)
client = ApitallyClient(client_id=CLIENT_ID, env="default", enable_keys=True)
client.stop_sync_loop()
client.requests.log_request(
method="GET",
path="/test",
status_code=200,
response_time=0.105,
)
client.requests.log_request(
method="GET",
path="/test",
status_code=200,
response_time=0.227,
)
return client


async def test_send_requests_data(client: ApitallyClient, httpx_mock: HTTPXMock):
from starlette_apitally.client import HUB_BASE_URL, HUB_VERSION

httpx_mock.add_response()
await asyncio.sleep(0.03)
async with client.get_http_client() as http_client:
await client.send_requests_data(client=http_client)

requests = httpx_mock.get_requests(url=f"{HUB_BASE_URL}/{HUB_VERSION}/{CLIENT_ID}/default/requests")
assert len(requests) == 1
Expand All @@ -69,3 +67,15 @@ async def test_send_app_info(client: ApitallyClient, httpx_mock: HTTPXMock, mock
request_data = json.loads(requests[0].content)
assert request_data["paths"] == []
assert request_data["client_version"] == "1.0.0"


async def test_get_keys(client: ApitallyClient, httpx_mock: HTTPXMock):
from starlette_apitally.client import HUB_BASE_URL, HUB_VERSION

httpx_mock.add_response(json={"salt": "x", "keys": {"x": {"key_id": 1, "expires_in_seconds": None}}})
await client.get_keys()
await asyncio.sleep(0.01)

requests = httpx_mock.get_requests(url=f"{HUB_BASE_URL}/{HUB_VERSION}/{CLIENT_ID}/default/keys")
assert len(requests) == 1
assert len(client.keys.keys) == 1

0 comments on commit 500f902

Please sign in to comment.