Skip to content

Commit

Permalink
Add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
nnsnodnb committed Jan 11, 2023
1 parent 806e2cb commit 24ea8b3
Show file tree
Hide file tree
Showing 7 changed files with 95 additions and 53 deletions.
18 changes: 17 additions & 1 deletion kalyke/clients/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from httpx import AsyncClient, Response

from ..exceptions import ApnsProviderException
from ..internal.status_code import StatusCode
from ..models import ApnsConfig, Payload


Expand All @@ -17,7 +18,22 @@ async def send_message(
payload: Union[Payload, Dict[str, Any]],
apns_config: ApnsConfig,
) -> str:
raise NotImplementedError
if isinstance(payload, Payload):
data = payload.dict()
elif isinstance(payload, Dict):
data = payload
else:
raise ValueError("Type of 'payload' must be specified by Payload or Dict[str, Any].")

async with self._init_client(apns_config=apns_config) as client:
request_url = self._make_url(device_token=device_token)
res = await self._send(client=client, url=request_url, data=data)

status_code = StatusCode(res.status_code)
if status_code.is_success:
return res.headers["apns-id"]

raise self._handle_error(error_json=res.json())

@property
def _base_url(self) -> str:
Expand Down
28 changes: 2 additions & 26 deletions kalyke/clients/apns.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Union
from typing import Union

import jwt
from httpx import AsyncClient

from ..internal.status_code import StatusCode
from ..models import ApnsConfig, Payload
from ..models import ApnsConfig
from . import __Client as BaseClient


Expand All @@ -30,29 +29,6 @@ def __init__(
else:
self._auth_key_filepath = Path(auth_key_filepath)

async def send_message(
self,
device_token: str,
payload: Union[Payload, Dict[str, Any]],
apns_config: ApnsConfig,
) -> str:
if isinstance(payload, Payload):
data = payload.dict()
elif isinstance(payload, Dict):
data = payload
else:
data = {}

async with self._init_client(apns_config=apns_config) as client:
request_url = self._make_url(device_token=device_token)
res = await self._send(client=client, url=request_url, data=data)

status_code = StatusCode(res.status_code)
if status_code.is_success:
return res.headers["apns-id"]

raise self._handle_error(error_json=res.json())

def _init_client(self, apns_config: ApnsConfig) -> AsyncClient:
headers = apns_config.make_headers()
headers["authorization"] = f"bearer {self._make_authorization()}"
Expand Down
26 changes: 2 additions & 24 deletions kalyke/clients/voip.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
from pathlib import Path
from typing import Any, Dict, Union
from typing import Union

import httpx
from httpx import AsyncClient

from ..internal.status_code import StatusCode
from ..models import ApnsConfig, Payload
from ..models import ApnsConfig
from . import __Client as BaseClient


Expand All @@ -19,27 +18,6 @@ def __init__(self, use_sandbox: bool, auth_key_filepath: Union[str, Path]) -> No
else:
self._auth_key_filepath = Path(auth_key_filepath)

async def send_message(
self,
device_token: str,
payload: Union[Payload, Dict[str, Any]],
apns_config: ApnsConfig,
) -> str:
if isinstance(payload, Payload):
data = payload.dict()
else:
data = payload

async with self._init_client(apns_config=apns_config) as client:
request_url = self._make_url(device_token=device_token)
res = await self._send(client=client, url=request_url, data=data)

status_code = StatusCode(res.status_code)
if status_code.is_success:
return res.headers["apns-id"]

raise self._handle_error(error_json=res.json())

def _init_client(self, apns_config: ApnsConfig) -> AsyncClient:
headers = apns_config.make_headers()
context = httpx.create_ssl_context()
Expand Down
23 changes: 23 additions & 0 deletions tests/clients/apns/test_init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from kalyke import ApnsClient


def test_initialize_with_pathlib(auth_key_filepath):
client = ApnsClient(
use_sandbox=True,
team_id="DUMMY_TEAM_ID",
auth_key_id="DUMMY",
auth_key_filepath=auth_key_filepath,
)

assert isinstance(client, ApnsClient)


def test_initialize_with_str(auth_key_filepath):
client = ApnsClient(
use_sandbox=True,
team_id="DUMMY_TEAM_ID",
auth_key_id="DUMMY",
auth_key_filepath=str(auth_key_filepath),
)

assert isinstance(client, ApnsClient)
18 changes: 17 additions & 1 deletion tests/clients/apns/test_send_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ async def test_success(httpx_mock, auth_key_filepath):


@pytest.mark.asyncio
async def test_failure(httpx_mock, auth_key_filepath):
async def test_bad_device_token(httpx_mock, auth_key_filepath):
httpx_mock.add_response(
status_code=400,
http_version="HTTP/2.0",
Expand All @@ -53,3 +53,19 @@ async def test_failure(httpx_mock, auth_key_filepath):
)

assert str(e.value) == str(BadDeviceToken(error={}))


@pytest.mark.asyncio
async def test_value_error(httpx_mock, auth_key_filepath):
client = ApnsClient(
use_sandbox=True, team_id="DUMMY_TEAM_ID", auth_key_id="DUMMY", auth_key_filepath=auth_key_filepath
)

with pytest.raises(ValueError) as e:
await client.send_message(
device_token="stub_device_token",
payload=["test alert"],
apns_config=ApnsConfig(topic="com.example.App"),
)

assert str(e.value) == "Type of 'payload' must be specified by Payload or Dict[str, Any]."
19 changes: 19 additions & 0 deletions tests/clients/voip/test_init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from kalyke import VoIPClient


def test_initialize_with_pathlib(auth_key_filepath):
client = VoIPClient(
use_sandbox=True,
auth_key_filepath=auth_key_filepath,
)

assert isinstance(client, VoIPClient)


def test_initialize_with_str(auth_key_filepath):
client = VoIPClient(
use_sandbox=True,
auth_key_filepath=str(auth_key_filepath),
)

assert isinstance(client, VoIPClient)
16 changes: 15 additions & 1 deletion tests/clients/voip/test_send_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async def test_success(httpx_mock, auth_key_filepath):


@pytest.mark.asyncio
async def test_failure(httpx_mock, auth_key_filepath):
async def test_bad_device_token(httpx_mock, auth_key_filepath):
httpx_mock.add_response(
status_code=400,
http_version="HTTP/2.0",
Expand All @@ -44,3 +44,17 @@ async def test_failure(httpx_mock, auth_key_filepath):
)

assert str(e.value) == str(BadDeviceToken(error={}))


@pytest.mark.asyncio
async def test_value_error(httpx_mock, auth_key_filepath):
client = VoIPClient(use_sandbox=True, auth_key_filepath=auth_key_filepath)

with pytest.raises(ValueError) as e:
await client.send_message(
device_token="stub_device_token",
payload=["test alert"],
apns_config=ApnsConfig(topic="com.example.App"),
)

assert str(e.value) == "Type of 'payload' must be specified by Payload or Dict[str, Any]."

0 comments on commit 24ea8b3

Please sign in to comment.