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

Apply stricter typing to this project #138

Merged
merged 4 commits into from
May 12, 2022
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
52 changes: 52 additions & 0 deletions .github/workflows/typing.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
---
name: Typing

# yamllint disable-line rule:truthy
on:
push:
pull_request:
workflow_dispatch:

jobs:
mypy:
name: mypy on Python ${{ matrix.python }}
runs-on: ubuntu-latest
strategy:
matrix:
python: ["3.9", "3.10"]
steps:
- name: ⤵️ Check out code from GitHub
uses: actions/[email protected]
- name: 🏗 Set up Python ${{ matrix.python }}
id: python
uses: actions/[email protected]
with:
python-version: ${{ matrix.python }}
- name: 🏗 Get pip cache dir
id: pip-cache
run: |
echo "::set-output name=dir::$(pip cache dir)"
- name: ⤵️ Restore cached Python PIP packages
uses: actions/[email protected]
with:
path: ${{ steps.pip-cache.outputs.dir }}
key: pip-${{ runner.os }}-v1-${{ steps.python.outputs.python-version }}-${{ hashFiles('.github/workflows/requirements.txt') }}
restore-keys: |
pip-${{ runner.os }}-v1-${{ steps.python.outputs.python-version }}-
- name: 🏗 Install workflow dependencies
run: |
pip install -r .github/workflows/requirements.txt
poetry config virtualenvs.create true
poetry config virtualenvs.in-project true
- name: ⤵️ Restore cached Python virtual environment
id: cached-poetry-dependencies
uses: actions/[email protected]
with:
path: .venv
key: venv-${{ runner.os }}-v1-${{ steps.python.outputs.python-version }}-${{ hashFiles('poetry.lock') }}
restore-keys: |
venv-${{ runner.os }}-v1-${{ steps.python.outputs.python-version }}-
- name: 🏗 Install dependencies
run: poetry install --no-interaction
- name: 🚀 Run mypy
run: poetry run mypy gridnet tests
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,11 @@ repos:
language: system
types: [python]
entry: poetry run isort
- id: mypy
name: 🆎 Static type checking using mypy
language: system
types: [python]
entry: poetry run mypy
- id: no-commit-to-branch
name: 🛑 Don't commit to main branch
language: system
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
[![Code Quality][code-quality-shield]][code-quality]
[![Maintainability][maintainability-shield]][maintainability-url]
[![Code Coverage][codecov-shield]][codecov-url]

[![Build Status][build-shield]][build-url]
[![Typing Status][typing-shield]][typing-url]

Asynchronous Python client for Net2Grid devices.

Expand Down Expand Up @@ -175,6 +177,8 @@ SOFTWARE.
[project-stage-shield]: https://img.shields.io/badge/project%20stage-experimental-yellow.svg
[pypi]: https://pypi.org/project/gridnet/
[python-versions-shield]: https://img.shields.io/pypi/pyversions/gridnet
[typing-shield]: https://github.com/klaasnicolaas/python-gridnet/actions/workflows/typing.yaml/badge.svg
[typing-url]: https://github.com/klaasnicolaas/python-gridnet/actions/workflows/typing.yaml
[releases-shield]: https://img.shields.io/github/release/klaasnicolaas/python-gridnet.svg
[releases]: https://github.com/klaasnicolaas/python-gridnet/releases
[stars-shield]: https://img.shields.io/github/stars/klaasnicolaas/python-gridnet.svg
Expand Down
8 changes: 4 additions & 4 deletions gridnet/gridnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class GridNet:
"""Main class for handling connections with the devices."""

host: str
request_timeout: int = 10
request_timeout: float = 10.0
session: aiohttp.ClientSession | None = None

_close_session: bool = False
Expand All @@ -32,8 +32,8 @@ async def _request(
uri: str,
*,
method: str = hdrs.METH_GET,
data: dict | None = None,
) -> dict[str, Any]:
data: dict[str, Any] | None = None,
) -> Any:
"""Handle a request to the device.

Args:
Expand Down Expand Up @@ -115,7 +115,7 @@ async def __aenter__(self) -> GridNet:
"""
return self

async def __aexit__(self, *_exc_info) -> None:
async def __aexit__(self, *_exc_info: str) -> None:
"""Async exit.

Args:
Expand Down
16 changes: 8 additions & 8 deletions gridnet/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def from_dict(data: dict[str, Any]) -> SmartBridge:
"""
data = data["elec"]

def convert(value):
def convert(value: float) -> float:
"""Convert the unit of measurement.

Args:
Expand All @@ -35,7 +35,7 @@ def convert(value):
Value in kWh rounded with 1 decimal.
"""
value = value / 1000
return round(value, 1)
return float(round(value, 1))

return SmartBridge(
power_flow=data["power"]["now"].get("value"),
Expand Down Expand Up @@ -67,10 +67,10 @@ def from_dict(data: dict[str, Any]) -> Device:
"""

return Device(
n2g_id=data.get("id"),
model=data.get("model"),
batch=data.get("batch"),
firmware=data.get("fw"),
hardware=data.get("hw"),
manufacturer=data.get("mf"),
n2g_id=data["id"],
model=data["model"],
batch=data["batch"],
firmware=data["fw"],
hardware=data["hw"],
manufacturer=data["mf"],
)
39 changes: 38 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,43 @@ source = ["gridnet"]
profile = "black"
multi_line_output = 3

[tool.mypy]
# Specify the target platform details in config, so your developers are
# free to run mypy on Windows, Linux, or macOS and get consistent
# results.
platform = "linux"
python_version = 3.9

# flake8-mypy expects the two following for sensible formatting
show_column_numbers = true

# show error messages from unrelated files
follow_imports = "normal"

# suppress errors about unsatisfied imports
ignore_missing_imports = true

# be strict
check_untyped_defs = true
disallow_any_generics = true
disallow_incomplete_defs = true
disallow_subclassing_any = true
disallow_untyped_calls = true
disallow_untyped_defs = true
disallow_untyped_decorators = false # thanks backoff :(
no_implicit_optional = true
no_implicit_reexport = true
strict_optional = true
warn_incomplete_stub = true
warn_no_return = true
warn_redundant_casts = true
warn_return_any = true
warn_unused_configs = true
warn_unused_ignores = true

# No incremental mode
cache_dir = "/dev/null"

[tool.pylint.BASIC]
good-names = [
"_",
Expand Down Expand Up @@ -123,5 +160,5 @@ paths = ["gridnet"]
verbose = true

[build-system]
requires = ["setuptools", "poetry-core>=1.0.0"]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
2 changes: 1 addition & 1 deletion tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import os


def load_fixtures(filename):
def load_fixtures(filename: str) -> str:
"""Load a fixture."""
path = os.path.join(os.path.dirname(__file__), "fixtures", filename)
with open(path, encoding="utf-8") as fptr:
Expand Down
19 changes: 10 additions & 9 deletions tests/test_gridnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import aiohttp
import pytest
from aresponses import Response, ResponsesMockServer

from gridnet import GridNet
from gridnet.exceptions import GridNetConnectionError, GridNetError
Expand All @@ -13,7 +14,7 @@


@pytest.mark.asyncio
async def test_json_request(aresponses):
async def test_json_request(aresponses: ResponsesMockServer) -> None:
"""Test JSON response is handled correctly."""
aresponses.add(
"example.com",
Expand All @@ -32,7 +33,7 @@ async def test_json_request(aresponses):


@pytest.mark.asyncio
async def test_internal_session(aresponses):
async def test_internal_session(aresponses: ResponsesMockServer) -> None:
"""Test JSON response is handled correctly."""
aresponses.add(
"example.com",
Expand All @@ -49,10 +50,10 @@ async def test_internal_session(aresponses):


@pytest.mark.asyncio
async def test_timeout(aresponses):
async def test_timeout(aresponses: ResponsesMockServer) -> None:
"""Test request timeout from the API."""
# Faking a timeout by sleeping
async def response_handler(_):
async def response_handler(_: aiohttp.ClientResponse) -> Response:
await asyncio.sleep(0.2)
return aresponses.Response(
body="Goodmorning!", text=load_fixtures("smartbridge.json")
Expand All @@ -67,7 +68,7 @@ async def response_handler(_):


@pytest.mark.asyncio
async def test_client_error():
async def test_client_error() -> None:
"""Test request client error from the API."""
async with aiohttp.ClientSession() as session:
client = GridNet(host="example.com", session=session)
Expand All @@ -79,7 +80,7 @@ async def test_client_error():

@pytest.mark.asyncio
@pytest.mark.parametrize("status", [401, 403])
async def test_http_error401(aresponses, status):
async def test_http_error401(aresponses: ResponsesMockServer, status: int) -> None:
"""Test HTTP 401 response handling."""
aresponses.add(
"example.com",
Expand All @@ -95,7 +96,7 @@ async def test_http_error401(aresponses, status):


@pytest.mark.asyncio
async def test_http_error400(aresponses):
async def test_http_error400(aresponses: ResponsesMockServer) -> None:
"""Test HTTP 404 response handling."""
aresponses.add(
"example.com",
Expand All @@ -111,7 +112,7 @@ async def test_http_error400(aresponses):


@pytest.mark.asyncio
async def test_http_error500(aresponses):
async def test_http_error500(aresponses: ResponsesMockServer) -> None:
"""Test HTTP 500 response handling."""
aresponses.add(
"example.com",
Expand All @@ -130,7 +131,7 @@ async def test_http_error500(aresponses):


@pytest.mark.asyncio
async def test_no_success(aresponses):
async def test_no_success(aresponses: ResponsesMockServer) -> None:
"""Test a message without a success message throws."""
aresponses.add(
"example.com",
Expand Down
5 changes: 3 additions & 2 deletions tests/test_models.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
"""Test the models."""
import aiohttp
import pytest
from aresponses import ResponsesMockServer

from gridnet import Device, GridNet, SmartBridge

from . import load_fixtures


@pytest.mark.asyncio
async def test_device(aresponses):
async def test_device(aresponses: ResponsesMockServer) -> None:
"""Test request from the device - Device object."""
aresponses.add(
"example.com",
Expand All @@ -33,7 +34,7 @@ async def test_device(aresponses):


@pytest.mark.asyncio
async def test_smartbridge(aresponses):
async def test_smartbridge(aresponses: ResponsesMockServer) -> None:
"""Test request from the device - SmartBridge object."""
aresponses.add(
"example.com",
Expand Down