Skip to content

Commit

Permalink
⚡ handle timeout error and add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Mips2648 committed Jun 4, 2024
1 parent 15352e3 commit a24e16a
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 18 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/pytest-3.11.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install flake8 pytest
python -m pip install flake8 pytest pytest-asyncio aioresponses
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Lint with flake8
run: |
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/pytest-3.9.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install flake8 pytest
python -m pip install flake8 pytest pytest-asyncio aioresponses
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Lint with flake8
run: |
Expand Down
15 changes: 10 additions & 5 deletions jeedomdaemon/aio_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,11 +119,16 @@ async def send_to_jeedom(self, payload):
return true or false if successful
"""
self._logger.debug('Send to jeedom: %s', payload)
async with self._jeedom_session.post(self._callback_url + '?apikey=' + self._api_key, json=payload) as resp:
if resp.status != 200:
self._logger.error('Error on send request to jeedom, return %s-%s', resp.status, resp.reason)
return False
return True
try:
async with self._jeedom_session.post(self._callback_url + '?apikey=' + self._api_key, json=payload) as resp:
if resp.status != 200:
self._logger.error('Error on send request to jeedom, return %s-%s', resp.status, resp.reason)
return False
return True
except asyncio.TimeoutError:
self._logger.warning('Timeout on send request to jeedom')
return False


async def add_change(self, key: str, value):
"""
Expand Down
7 changes: 5 additions & 2 deletions jeedomdaemon/base_daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,11 @@ def run(self):
Utils.write_pid(str(self._config.pid_filename))

asyncio.run(self.__run())
except Exception as e: # pylint: disable=broad-exception-caught
self._logger.error('Fatal error: %s', e)
except Exception as ex: # pylint: disable=broad-exception-caught
exception_type, exception_object, exception_traceback = sys.exc_info()
filename = exception_traceback.tb_frame.f_code.co_filename
line_number = exception_traceback.tb_lineno
self._logger.error('Fatal error: %s(%s) in %s on line %s', ex, exception_type, filename, line_number)
finally:
self._logger.info("Shutdown")
try:
Expand Down
49 changes: 40 additions & 9 deletions tests/base_daemon_test.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,53 @@
"""Test class for base config."""

import re
import sys
import os
import unittest
from unittest.mock import patch, mock_open
import pytest
from aioresponses import aioresponses

sys.path.append(os.path.realpath(os.path.dirname(__file__) + '/..'))

from jeedomdaemon.base_daemon import BaseDaemon # pylint: disable=wrong-import-position
from jeedomdaemon.base_config import BaseConfig # pylint: disable=wrong-import-position
from jeedomdaemon.aio_connector import Publisher

class TestBaseConfig(unittest.TestCase):
def test_base_daemon_creation(self):
class TestBaseDaemon():
def _get_test_config(self):
config = BaseConfig()
config.parse(['--loglevel', 'info', '--socketport', '42000', '--callback', 'http://localhost/path', '--apikey', 'cnysltyql', '--pid', '/tmp/test_daemon'])
return config

@patch("builtins.open", new_callable=mock_open)
def test_base_daemon_creation(self, dummy_file):
"""
Test that it can create a basic config parser
Test that it can create a basic daemon
"""
config = BaseConfig()
config.parse([])
BaseDaemon(config)
config = self._get_test_config()
testdaemon = BaseDaemon(config)
with pytest.raises(SystemExit) as pytest_wrapped_e:
testdaemon.run()
assert pytest_wrapped_e.type == SystemExit
assert pytest_wrapped_e.value.code == 0

class TestPublisher():

@pytest.mark.asyncio
async def test_send_to_jeedom(self):
pub = Publisher('http://local/', 'cnysltyql')
with aioresponses() as mocked:
pattern = re.compile(r'^http://local/\?apikey=.*$')
mocked.get(pattern, status=200, body='test')
mocked.post(pattern, status=200, body='test')
resp = await pub.send_to_jeedom({})
assert resp == True

if __name__ == '__main__':
unittest.main()
@pytest.mark.asyncio
async def test_send_to_jeedom_timeout(self):
pub = Publisher('http://local/', 'cnysltyql')
with aioresponses() as mocked:
pattern = re.compile(r'^http://local/\?apikey=.*$')
mocked.post(pattern, status=200, timeout=True)
resp = await pub.send_to_jeedom({})
assert resp == False

0 comments on commit a24e16a

Please sign in to comment.