Skip to content

Commit

Permalink
Merge pull request #2 from bj00rn/chore/upgrade-pyscaffold
Browse files Browse the repository at this point in the history
Chore/upgrade pyscaffold
  • Loading branch information
bj00rn authored Dec 4, 2023
2 parents 7435d38 + 0c0a85b commit d3d195b
Show file tree
Hide file tree
Showing 12 changed files with 192 additions and 76 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ __pycache__/*
.pydevproject
.settings
.idea
.vscode
tags

# Package files
Expand Down
7 changes: 5 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ repos:
- id: trailing-whitespace
- id: check-added-large-files
- id: check-ast
- id: check-json
- id: check-merge-conflict
- id: check-xml
- id: check-yaml
- id: debug-statements
- id: end-of-file-fixer
Expand Down Expand Up @@ -74,3 +72,8 @@ repos:
- id: commitlint
stages: [commit-msg]
additional_dependencies: ['conventional-changelog-conventionalcommits']

- repo: https://gitlab.com/bmares/check-json5
rev: v1.0.0
hooks:
- id: check-json5
30 changes: 30 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Debug Test server",
"type": "python",
"request": "launch",
"module": "aiohttp.web",
"justMyCode": true,
"args": ["-H", "localhost", "-P", "3001", "tests.utils.test_server:run_server"]
},
{
"name": "Debug CLI",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/src/pysaleryd/skeleton.py",
"console": "integratedTerminal",
"justMyCode": true,
"args": [
"--host",
"localhost",
"--port",
"3001"
]
}
]
}
18 changes: 18 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"esbonio.sphinx.confDir": "",
"python.testing.pytestEnabled": true,
"python.testing.pytestArgs": [
// Coverage is not supported by vscode:
// https://github.com/Microsoft/vscode-python/issues/693
// Note that this will make pytest fail if pytest-cov is not installed,
// if that's the case, then this option needs to be be removed (overrides
// can be set at a workspace level, it's up to you to decide what's the
// best approach). You might also prefer to only set this option
// per-workspace (wherever coverage is used).
"--no-cov",
"-o",
"log_cli=1",
"--timeout=30",
"--verbose"
],
}
13 changes: 13 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Run test server",
"type": "shell",
"command": "python",
"args": ["-m", "aiohttp.web", "-H", "localhost", "-P", "3001", "tests.utils.test_server:run_server"]
}
]
}
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ norecursedirs =
dist
build
.tox
tests/utils
testpaths = tests
# Use pytest markers to select/deselect specific tests
# markers =
Expand Down
28 changes: 4 additions & 24 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
"""
Dummy conftest.py for pysaleryd.
Configure testing
"""
import asyncio

import aiohttp
import pytest
import pytest_asyncio
from aiohttp import web
from utils.test_server import WebsocketView


@pytest.fixture(scope="session")
Expand All @@ -18,29 +18,9 @@ def event_loop():
loop.close()


async def websocket_handler(request):
ws = web.WebSocketResponse()
await ws.prepare(request)

async def cleanup():
await ws.close(code=aiohttp.WSCloseCode.GOING_AWAY, message="Server shutdown")

try:
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
while True:
await ws.send_str("#MF: 1+ 0+ 2+1\r")
await asyncio.sleep(0.5)
finally:
await asyncio.shield(cleanup())

return ws


@pytest_asyncio.fixture()
async def ws_server(aiohttp_server: web.Server):
async def ws_server(aiohttp_server: "web.Server"):
"""Websocket test server"""
app = web.Application()

app.add_routes([web.get("/", websocket_handler)])
app.add_routes([web.view("/", WebsocketView)])
return await aiohttp_server(app, port=3001)
60 changes: 19 additions & 41 deletions tests/test_client.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,42 @@
"""Client tests"""
import asyncio
import typing

import aiohttp
import pytest
import pytest_asyncio

from pysaleryd.client import Client, State

if typing.TYPE_CHECKING:
from aiohttp import web_server

__author__ = "Björn Dalfors"
__copyright__ = "Björn Dalfors"
__license__ = "MIT"


async def on_shutdown(app):
"""Shutdown ws connections on shutdown"""
for ws in set(app["websockets"]):
try:
await ws.close(
code=aiohttp.WSCloseCode.GOING_AWAY, message="Server shutdown"
)
except Exception:
pass


@pytest_asyncio.fixture
async def hrv_client(ws_server):
@pytest_asyncio.fixture(name="hrv_client")
async def _hrv_client(ws_server):
"""HRV Client"""
try:
async with aiohttp.ClientSession() as session:
async with Client("localhost", 3001, session) as client:
yield client
except Exception:
pass
async with aiohttp.ClientSession() as session:
async with Client("localhost", 3001, session) as client:
yield client


@pytest.mark.asyncio
async def test_client_connect(hrv_client: Client):
async def test_client_connect(hrv_client: "Client"):
"""test connect"""
assert hrv_client.state == State.RUNNING


@pytest.mark.asyncio
async def test_client_connect_unsresponsive():
"""test status when client is unresponsive"""
async with aiohttp.ClientSession() as session:
client = Client("localhost", 3002, session)
try:
await client.connect()
except Exception: # noqa: W0718
pass

assert client.state == State.STOPPED


@pytest.mark.asyncio
async def test_handler(hrv_client: Client, mocker):
async def test_handler(hrv_client: "Client", mocker):
"""Test handler callback"""
handler = mocker.Mock()

def broken_handler(data):
raise Exception()
raise Exception() # pylint: disable=W0719

hrv_client.add_handler(broken_handler)
hrv_client.add_handler(handler)
Expand All @@ -67,15 +45,15 @@ def broken_handler(data):


@pytest.mark.asyncio
async def test_get_data(hrv_client: Client, mocker):
async def test_get_data(hrv_client: "Client"):
"""Test get data"""
await asyncio.sleep(1)
await asyncio.sleep(5)
assert isinstance(hrv_client.data, dict)
assert any(hrv_client.data.keys())


@pytest.mark.asyncio
async def test_reconnect(hrv_client: Client, ws_server):
async def test_reconnect(hrv_client: "Client", ws_server: "web_server.Server"):
"""Test reconnect"""

async def has_state(state):
Expand All @@ -90,16 +68,16 @@ async def has_state(state):


@pytest.mark.asyncio
async def test_send_command(hrv_client: Client, mocker):
async def test_send_command(hrv_client: "Client"):
"""Test send command"""
await hrv_client.send_command("MF", "0")


@pytest.mark.asyncio
async def test_disconnect(hrv_client: Client, mocker):
async def test_disconnect(hrv_client: "Client"):
"""Test send command"""
hrv_client.disconnect()
await asyncio.sleep(2)
assert hrv_client.state == State.STOPPED
await asyncio.sleep(2)
assert hrv_client._socket._ws.closed
assert hrv_client._socket._ws.closed # pylint: disable=all
14 changes: 7 additions & 7 deletions tests/test_utils.py → tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@
_LOGGER = logging.getLogger(__name__)


@pytest.fixture
def parser() -> Parser:
@pytest.fixture(name="parser")
def _parser() -> Parser:
return Parser()


def test_parse_int_from_list_str(parser: Parser):
"""Test parsing int list"""
(key, value) = parser.from_str("#MF: 1+ 0+ 2+30\r")
assert key == "MF"
assert isinstance(value, list)
Expand All @@ -28,13 +29,15 @@ def test_parse_int_from_list_str(parser: Parser):


def test_parse_int_from_str(parser: Parser):
"""Test parsing int"""
(key, value) = parser.from_str("#*XX:0\r")
assert key == "*XX"
assert isinstance(value, int)
assert value == 0


def test_parse_str_from_str(parser: Parser):
"""Test parsing str"""
(key, value) = parser.from_str("#*XX:xxx\r")
assert key == "*XX"
assert isinstance(value, str)
Expand All @@ -47,9 +50,6 @@ def test_parse_str_from_str(parser: Parser):


def test_parse_error(parser: Parser):
did_throw = False
try:
"""Test parse error"""
with pytest.raises(ParseError):
parser.from_str("wer")
except ParseError:
did_throw = True
assert did_throw
4 changes: 3 additions & 1 deletion tests/test_skeleton.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
"""CLI Tests"""

import pytest

from pysaleryd.skeleton import main
Expand All @@ -8,7 +10,7 @@


@pytest.mark.skip
def test_main(capsys, ws_server):
def test_main(capsys, ws_server): # pylint: disable W0613
"""CLI Tests"""
# capsys is a pytest fixture that allows asserts against stdout/stderr
# https://docs.pytest.org/en/stable/capture.html
Expand Down
Empty file added tests/utils/__init__.py
Empty file.
Loading

0 comments on commit d3d195b

Please sign in to comment.