Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add mypy & typeguard tests + fix dependencies + add some typing #593

Merged
merged 5 commits into from
Oct 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,17 @@ jobs:
include:
- { python-version: "3.11", os: ubuntu-latest, session: "pre-commit" }
- { python-version: "3.11", os: ubuntu-latest, session: "safety" }
# - { python-version: "3.11", os: ubuntu-latest, session: "mypy" }
# - { python-version: "3.10", os: ubuntu-latest, session: "mypy" }
# - { python-version: "3.9", os: ubuntu-latest, session: "mypy" }
# - { python-version: "3.8", os: ubuntu-latest, session: "mypy" }
- { python-version: "3.11", os: ubuntu-latest, session: "mypy" }
- { python-version: "3.10", os: ubuntu-latest, session: "mypy" }
- { python-version: "3.9", os: ubuntu-latest, session: "mypy" }
- { python-version: "3.8", os: ubuntu-latest, session: "mypy" }
- { python-version: "3.11", os: ubuntu-latest, session: "tests" }
- { python-version: "3.10", os: ubuntu-latest, session: "tests" }
- { python-version: "3.9", os: ubuntu-latest, session: "tests" }
- { python-version: "3.8", os: ubuntu-latest, session: "tests" }
- { python-version: "3.11", os: windows-latest, session: "tests" }
- { python-version: "3.11", os: macos-latest, session: "tests" }
# - { python-version: "3.11", os: ubuntu-latest, session: "typeguard" }
- { python-version: "3.11", os: ubuntu-latest, session: "typeguard" }
- { python-version: "3.11", os: ubuntu-latest, session: "xdoctest" }
- { python-version: "3.11", os: ubuntu-latest, session: "docs-build" }

Expand Down
26 changes: 0 additions & 26 deletions mypy.ini

This file was deleted.

8 changes: 4 additions & 4 deletions noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@
nox.options.sessions = (
"pre-commit",
"safety",
# "mypy",
"mypy",
"tests",
# "typeguard",
"typeguard",
"xdoctest",
"docs-build",
)
Expand Down Expand Up @@ -172,7 +172,7 @@ def docs_build(session: Session) -> None:
"""Build the documentation."""
args = session.posargs or ["docs", "docs/_build"]
session.install(".")
session.install("sphinx", "sphinx-click", "sphinx-rtd-theme")
session.install("sphinx", "sphinx-click")

build_dir = Path("docs", "_build")
if build_dir.exists():
Expand All @@ -186,7 +186,7 @@ def docs(session: Session) -> None:
"""Build and serve the documentation with live reloading on file changes."""
args = session.posargs or ["--open-browser", "docs", "docs/_build"]
session.install(".")
session.install("sphinx", "sphinx-autobuild", "sphinx-click", "sphinx-rtd-theme")
session.install("sphinx", "sphinx-autobuild", "sphinx-click")
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add sphinx-rtd-theme entirely in a new PR


build_dir = Path("docs", "_build")
if build_dir.exists():
Expand Down
24 changes: 12 additions & 12 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Changelog = "https://github.com/hacf-fr/freebox-api/releases"

[tool.poetry.dependencies]
python = "^3.8.18"
urllib3 = "^1.26.17"
urllib3 = "^1.26.18"
aiohttp = ">=3,<4"
importlib-metadata = {version = ">=3.3,<5.0", python = "<3.12"}

Expand All @@ -39,7 +39,7 @@ coverage = {extras = ["toml"], version = "^7.2"}
safety = "^2.3.5"
mypy = "^1.6"
typeguard = "^4.1.5"
xdoctest = {extras = ["colors"], version = "^1.6.1"}
xdoctest = {extras = ["colors"], version = "^1.1.1"}
sphinx = "^4.2.0"
sphinx-autobuild = "^2021.3.14"
pre-commit = "^3.5.0"
Expand Down Expand Up @@ -75,6 +75,12 @@ pretty = true
show_column_numbers = true
show_error_codes = true
show_error_context = true
# TODO: Work on removing that
allow_untyped_defs = true
allow_untyped_calls = true
exclude = [
'^tests/example\.py$',
]

[build-system]
requires = ["poetry-core>=1.0.0"]
Expand Down
4 changes: 2 additions & 2 deletions src/freebox_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
# importlib.metadata available from Python 3.8 use importlib_metadata for
# earlier versions.
try:
from importlib.metadata import version, PackageNotFoundError # type: ignore
from importlib.metadata import version, PackageNotFoundError
except ImportError: # pragma: no cover
from importlib_metadata import version, PackageNotFoundError # type: ignore


try:
__version__ = version(__name__)
__version__: str = version(__name__)
except PackageNotFoundError: # pragma: no cover
__version__ = "unknown"

Expand Down
110 changes: 66 additions & 44 deletions src/freebox_api/access.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import hmac
import json
import logging
from typing import Any
from typing import Dict
from typing import Optional
from urllib.parse import urljoin

from aiohttp import ClientSession

from freebox_api.exceptions import AuthorizationError
from freebox_api.exceptions import HttpRequestError
from freebox_api.exceptions import InsufficientPermissionsError
Expand All @@ -11,30 +16,39 @@


class Access:
def __init__(self, session, base_url, app_token, app_id, http_timeout):
def __init__(
self,
session: ClientSession,
base_url: str,
app_token: str,
app_id: str,
http_timeout: int,
):
self.session = session
self.base_url = base_url
self.app_token = app_token
self.app_id = app_id
self.timeout = http_timeout
self.session_token = None
self.session_permissions = None
self.session_token: Optional[str] = None
self.session_permissions: Optional[Dict[str, bool]] = None

Check warning on line 33 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L32-L33

Added lines #L32 - L33 were not covered by tests

async def _get_challenge(self, base_url, timeout=10):
"""
Return challenge from freebox API
"""
url = urljoin(base_url, "login")
r = await self.session.get(url, timeout=timeout)
resp = await r.json()
resp = await self.session.get(url, timeout=timeout)
resp_data = await resp.json()

Check warning on line 41 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L40-L41

Added lines #L40 - L41 were not covered by tests

# raise exception if resp.success != True
if not resp.get("success"):
if not resp_data.get("success"):
raise AuthorizationError(
"Getting challenge failed (APIResponse: {})".format(json.dumps(resp))
"Getting challenge failed (APIResponse: {})".format(
json.dumps(resp_data)
)
)

return resp["result"]["challenge"]
return resp_data["result"]["challenge"]

Check warning on line 51 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L51

Added line #L51 was not covered by tests

async def _get_session_token(self, base_url, app_token, app_id, timeout=10):
"""
Expand All @@ -50,17 +64,19 @@

url = urljoin(base_url, "login/session/")
data = json.dumps({"app_id": app_id, "password": password})
r = await self.session.post(url, data=data, timeout=timeout)
resp = await r.json()
resp = await self.session.post(url, data=data, timeout=timeout)
resp_data = await resp.json()

Check warning on line 68 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L67-L68

Added lines #L67 - L68 were not covered by tests

# raise exception if resp.success != True
if not resp.get("success"):
if not resp_data.get("success"):
raise AuthorizationError(
"Starting session failed (APIResponse: {})".format(json.dumps(resp))
"Starting session failed (APIResponse: {})".format(
json.dumps(resp_data)
)
)

session_token = resp.get("result").get("session_token")
session_permissions = resp.get("result").get("permissions")
session_token = resp_data["result"].get("session_token")
session_permissions = resp_data["result"].get("permissions")

Check warning on line 79 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L78-L79

Added lines #L78 - L79 were not covered by tests

return (session_token, session_permissions)

Expand All @@ -75,7 +91,7 @@
self.session_token = session_token
self.session_permissions = session_permissions

def _get_headers(self):
def _get_headers(self) -> Dict[str, Optional[str]]:
return {"X-Fbx-App-Auth": self.session_token}

async def _perform_request(self, verb, end_url, **kwargs):
Expand All @@ -91,58 +107,64 @@
"headers": self._get_headers(),
"timeout": self.timeout,
}
r = await verb(url, **request_params)
resp = await verb(url, **request_params)

Check warning on line 110 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L110

Added line #L110 was not covered by tests

# Return response if content is not json
if r.content_type != "application/json":
return r
else:
resp = await r.json()
if resp.content_type != "application/json":
return resp

Check warning on line 114 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L114

Added line #L114 was not covered by tests

if resp.get("error_code") in ["auth_required", "invalid_session"]:
logger.debug("Invalid session")
await self._refresh_session_token()
request_params["headers"] = self._get_headers()
r = await verb(url, **request_params)
resp = await r.json()
resp_data = await resp.json()

Check warning on line 116 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L116

Added line #L116 was not covered by tests
if resp_data.get("error_code") in ["auth_required", "invalid_session"]:
logger.debug("Invalid session")
await self._refresh_session_token()
request_params["headers"] = self._get_headers()
resp = await verb(url, **request_params)
resp_data = await resp.json()

Check warning on line 122 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L118-L122

Added lines #L118 - L122 were not covered by tests

if not resp["success"]:
err_msg = "Request failed (APIResponse: {})".format(json.dumps(resp))
if resp.get("error_code") == "insufficient_rights":
raise InsufficientPermissionsError(err_msg)
else:
raise HttpRequestError(err_msg)
if not resp_data["success"]:
err_msg = "Request failed (APIResponse: {})".format(json.dumps(resp_data))

Check warning on line 125 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L125

Added line #L125 was not covered by tests
if resp_data.get("error_code") == "insufficient_rights":
raise InsufficientPermissionsError(err_msg)
raise HttpRequestError(err_msg)

Check warning on line 128 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L127-L128

Added lines #L127 - L128 were not covered by tests

return resp["result"] if "result" in resp else None
return resp_data.get("result")

Check warning on line 130 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L130

Added line #L130 was not covered by tests

async def get(self, end_url):
async def get(
self, end_url: str
) -> Any: # Union[Dict[str, Any], List[Dict[str, Any]]]:
"""
Send get request and return results
"""
return await self._perform_request(self.session.get, end_url)

async def post(self, end_url, payload=None):
async def post(
self, end_url: str, payload: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Send post request and return results
"""
data = json.dumps(payload) if payload is not None else None
return await self._perform_request(self.session.post, end_url, data=data)
data = json.dumps(payload) if payload else None
return await self._perform_request(self.session.post, end_url, data=data) # type: ignore

Check warning on line 147 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L146-L147

Added lines #L146 - L147 were not covered by tests

async def put(self, end_url, payload=None):
async def put(
self, end_url: str, payload: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Send post request and return results
"""
data = json.dumps(payload) if payload is not None else None
return await self._perform_request(self.session.put, end_url, data=data)
data = json.dumps(payload) if payload else None
return await self._perform_request(self.session.put, end_url, data=data) # type: ignore

Check warning on line 156 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L155-L156

Added lines #L155 - L156 were not covered by tests

async def delete(self, end_url, payload=None):
async def delete(
self, end_url: str, payload: Optional[Dict[str, Any]] = None
) -> Optional[Dict[str, bool]]:
"""
Send delete request and return results
"""
data = json.dumps(payload) if payload is not None else None
return await self._perform_request(self.session.delete, end_url, data=data)
data = json.dumps(payload) if payload else None
return await self._perform_request(self.session.delete, end_url, data=data) # type: ignore

Check warning on line 165 in src/freebox_api/access.py

View check run for this annotation

Codecov / codecov/patch

src/freebox_api/access.py#L164-L165

Added lines #L164 - L165 were not covered by tests

async def get_permissions(self):
async def get_permissions(self) -> Optional[Dict[str, bool]]:
"""
Returns the permissions for this session/app.
"""
Expand Down
Loading
Loading