Skip to content

Commit

Permalink
Init proxy tests (#3352)
Browse files Browse the repository at this point in the history
* Init proxy tests

* lint
  • Loading branch information
ludeeus authored Nov 17, 2023
1 parent a746614 commit 5a3b9dd
Show file tree
Hide file tree
Showing 7 changed files with 124 additions and 6 deletions.
65 changes: 59 additions & 6 deletions tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,24 @@
import os
from typing import Any

from aiohttp import ClientWebSocketResponse
from aiohttp import ClientSession, ClientWebSocketResponse
from aiohttp.typedefs import StrOrURL
from homeassistant import auth, config_entries, core as ha
from homeassistant.auth import (
auth_store,
models as auth_models,
permissions as auth_permissions,
)
from homeassistant.auth import auth_store, models as auth_models
from homeassistant.components.http import (
CONFIG_SCHEMA as HTTP_CONFIG_SCHEMA,
async_setup as http_async_setup,
)
from homeassistant.const import EVENT_HOMEASSISTANT_CLOSE
from homeassistant.helpers import storage
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.device_registry import DeviceRegistry
from homeassistant.helpers.entity_registry import EntityRegistry
from homeassistant.helpers.issue_registry import IssueRegistry
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as date_util
from homeassistant.util.unit_system import METRIC_SYSTEM
from yarl import URL

from custom_components.hacs.base import HacsBase
from custom_components.hacs.repositories.base import HacsManifest, HacsRepository
Expand Down Expand Up @@ -312,3 +311,57 @@ async def receive_json(self) -> dict[str, Any]:
async def send_and_receive_json(self, type: str, payload: dict[str, Any]) -> dict[str, Any]:
await self.send_json(type=type, payload=payload)
return await self.client.receive_json()


class MockedResponse:
def __init__(self, **kwargs) -> None:
self.status = kwargs.get("status", 200)
self.read = kwargs.get("read", AsyncMock())
self.json = kwargs.get("json", AsyncMock())
self.exception = kwargs.get("exception", None)


class ResponseMocker:
responses: dict[str, MockedResponse] = {}

def add(self, url: str, response: MockedResponse) -> None:
self.responses[url] = response

def get(self, url: str) -> MockedResponse:
return self.responses.pop(url, None)


async def client_session_proxy(hass: ha.HomeAssistant) -> ClientSession:
"""Create a mocked client session."""
base = async_get_clientsession(hass)
response_mocker = ResponseMocker()

async def _request(method: str, str_or_url: StrOrURL, *args, **kwargs):
url = URL(str_or_url)
fp = os.path.join(
os.path.dirname(__file__),
f"fixtures/proxy/{url.host}{url.path}{'.json' if url.host == 'api.github.com' else ''}",
)
print(f"Using fixture {fp} for request to {url.host}")

if (resp := response_mocker.get(str_or_url)) is not None:
if resp.exception:
raise resp.exception
return resp

if not os.path.exists(fp):
raise AssertionError(f"Missing fixture for proxy/{url.host}{url.path}")

async def read():
with open(fp, encoding="utf-8") as fptr:
return fptr.read().encode("utf-8")

async def json():
with open(fp, encoding="utf-8") as fptr:
return json.loads(fptr.read())

return AsyncMock(status=200, url=url, read=read, json=json)

base._request = _request

return base
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
## Example readme file (1.0.0)
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "Proxy integration"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
## Example readme file (2.0.0)
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"name": "Proxy integration"
}
36 changes: 36 additions & 0 deletions tests/repositories/test_get_documentation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from typing import Any

import pytest

from custom_components.hacs.base import HacsBase
from custom_components.hacs.repositories.base import HacsRepository

from tests.common import client_session_proxy


@pytest.mark.parametrize(
"data,result",
[
({"installed": True, "installed_version": "1.0.0"}, "Example readme file (1.0.0)"),
(
{"installed": True, "installed_version": "1.0.0", "last_version": "2.0.0"},
"Example readme file (1.0.0)",
),
({"installed": False, "last_version": "2.0.0"}, "Example readme file (2.0.0)"),
({"installed": False, "last_version": "99.99.99"}, None),
],
)
@pytest.mark.asyncio
async def test_validate_repository(hacs: HacsBase, data: dict[str, Any], result: str | None):
repository = HacsRepository(hacs=hacs)
repository.data.full_name = "octocat/integration"
for key, value in data.items():
setattr(repository.data, key, value)

hacs.session = await client_session_proxy(hacs.hass)
docs = await repository.get_documentation(filename="README.md")

if result:
assert result in docs
else:
assert result is None
21 changes: 21 additions & 0 deletions tests/repositories/test_get_hacs_json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import pytest

from custom_components.hacs.base import HacsBase
from custom_components.hacs.repositories.base import HacsRepository

from tests.common import client_session_proxy


@pytest.mark.parametrize("version,name", [("1.0.0", "Proxy integration"), ("99.99.99", None)])
@pytest.mark.asyncio
async def test_validate_repository(hacs: HacsBase, version: str, name: str | None):
repository = HacsRepository(hacs=hacs)
repository.data.full_name = "octocat/integration"

hacs.session = await client_session_proxy(hacs.hass)
manifest = await repository.get_hacs_json(version=version)

if name:
assert manifest.name == name
else:
assert manifest is None

0 comments on commit 5a3b9dd

Please sign in to comment.