Skip to content

Commit

Permalink
activate async tests again
Browse files Browse the repository at this point in the history
Signed-off-by: Rosi2143 <[email protected]>
  • Loading branch information
Rosi2143 committed May 12, 2024
1 parent eb2aaba commit 0f4e867
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 90 deletions.
19 changes: 14 additions & 5 deletions pyIndego/indego_async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,23 @@ def __init__(
self._session = aiohttp.ClientSession(raise_for_status=False)
self._should_close_session = True

async def __aenter__(self):
"""Enter for async with."""
await self.start()
return self

async def __aexit__(self, exc_type, exc_value, traceback):
"""Exit for async with."""
await self.close()

async def start(self):
"""get the OAuth-token"""
if self._token_refresh_method is not None:
_LOGGER.debug("Refreshing token")
self._token = await self._token_refresh_method()
else:
_LOGGER.debug("Token refresh is NOT available")

async def close(self):
"""Close the aiohttp session."""
if self._should_close_session:
Expand Down Expand Up @@ -472,11 +485,7 @@ async def _request( # noqa: C901
_LOGGER.warning("Five attempts done, please try again later")
return None

if self._token_refresh_method is not None:
_LOGGER.debug("Refreshing token")
self._token = await self._token_refresh_method()
else:
_LOGGER.debug("Token refresh is NOT available")
await self.start()

url = f"{self._api_url}{path}"

Expand Down
8 changes: 3 additions & 5 deletions test_new.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import json
import logging
import pytz
import pytz # $ pip install pytz
import tzlocal # $ pip install tzlocal
from pyIndego import IndegoClient
from datetime import datetime
import time
Expand Down Expand Up @@ -86,7 +84,7 @@ def main(config):
#print("=[indego.update_next_mow]===")
#indego.update_next_mow()
#print(indego.next_mow)

# Wakes mower!
# # print(" ")
# print("=[operating data]====")
Expand All @@ -108,7 +106,7 @@ def main(config):
#print("=[updates]====")
#indego.update_updates_available()
#print(indego.update_available)

#print(" ")
#print("=[user]====")
#indego.update_user()
Expand All @@ -118,7 +116,7 @@ def main(config):
if __name__ == "__main__":
with open("config.json", "r") as config_file:
config = json.load(config_file)

for i in range(10):
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
Expand Down
22 changes: 10 additions & 12 deletions test_new_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ async def main(config):
async with IndegoAsyncClient(**config) as indego:
#Update and cache all calls from API
#await indego.update_all()

# await indego.update_alerts()
# print("alerts: ", indego.alerts)
###### FUNCTION! print("alert count: ", indego.alerts_count)
Expand Down Expand Up @@ -53,7 +53,7 @@ async def main(config):

# await indego.update_predictive_calendar()
# print("predictive calendar: ", indego.predictive_calendar)
#
#
# await indego.update_predictive_schedule()
# print("predictive schedule: ", indego.predictive_schedule)

Expand All @@ -72,18 +72,18 @@ async def main(config):
# print("serial: ", indego.serial)
#print("xPos: ", indego.state.xPos)
#print("yPos: ", indego.state.yPos)

f = open('percentage.log', 'a')

from time import gmtime, strftime
logtime = strftime("%H:%M", gmtime())
print(logtime , end = ' ')
print("Mowed: ", indego.state.mowed)









f.write(str(logtime) + " - ")
f.write(str(indego.state.mowed) + "\n")
f.close()
Expand All @@ -102,19 +102,17 @@ async def main(config):
# print("state description: ", indego.state_description)
# print("state description detail: ", indego.state_description_detail)


# await indego.update_updates_available()
# print("update available: ", indego.update_available)

# await indego.update_user()
# print("user: ", indego.user)



if __name__ == "__main__":
with open("config.json", "r") as config_file:
config = json.load(config_file)
# config.pop("serial")
# config["username"] = "sdjbfajhbsdf"
loop = asyncio.get_event_loop()
loop.run_until_complete(main(config))
asyncio.run(main(config))
80 changes: 12 additions & 68 deletions tests/test_indego.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from socket import error as SocketError

import pytest
import pytest_asyncio
from aiohttp import (
ClientOSError,
ClientResponseError,
Expand Down Expand Up @@ -43,6 +44,8 @@

_LOGGER = logging.getLogger(__name__)

pytest_plugins = ('pytest_asyncio',)

alert = {
"alm_sn": "test_sn",
"alert_id": "5efda84ffbf591182723be89",
Expand Down Expand Up @@ -366,7 +369,7 @@
"mow_trig": True,
}

test_config = {"username": "testname", "password": "testpassword", "api_url": "", "serial": "123456789"}
test_config = {"serial": "123456789", "token": "testtoken"}


class AsyncMock(MagicMock):
Expand Down Expand Up @@ -666,6 +669,7 @@ def test_date_parsing(self, date_str, date_dt):
(False, IndegoAsyncClient.update_all, "user", None, None),
],
)
@pytest.mark.asyncio
async def test_client_update_functions(
self, sync, func, attr, ret_value, assert_value
):
Expand All @@ -674,8 +678,6 @@ async def test_client_update_functions(
resp = MockResponseSync(ret_value, 200)
with patch("requests.request", return_value=resp):
indego = IndegoClient(**test_config)
indego._online = True
indego._userid = "test_user_id"
func(indego)
assert getattr(indego, attr) == assert_value
if attr == "state":
Expand All @@ -687,9 +689,6 @@ async def test_client_update_functions(
"pyIndego.IndegoAsyncClient.start", return_value=True
):
async with IndegoAsyncClient(**test_config) as indego:
indego._contextid = "askdjfbaks"
indego._online = True
indego._userid = "test_user_id"
await func(indego)
assert getattr(indego, attr) == assert_value
if attr == "state":
Expand Down Expand Up @@ -749,6 +748,7 @@ async def test_client_update_functions(
),
],
)
@pytest.mark.asyncio
async def test_client_update_state_params(
self, sync, func, param, attr, ret_value, assert_value
):
Expand All @@ -757,8 +757,6 @@ async def test_client_update_state_params(
resp = MockResponseSync(ret_value, 200)
with patch("requests.request", return_value=resp):
indego = IndegoClient(**test_config)
indego._online = True
indego._userid = "test_user_id"
func(indego, **param)
assert getattr(indego, attr) == assert_value
else:
Expand All @@ -767,9 +765,6 @@ async def test_client_update_state_params(
"pyIndego.IndegoAsyncClient.start", return_value=True
):
async with IndegoAsyncClient(**test_config) as indego:
indego._contextid = "askdjfbaks"
indego._online = True
indego._userid = "test_user_id"
await func(indego, **param)
assert getattr(indego, attr) == assert_value

Expand All @@ -780,14 +775,13 @@ async def test_client_update_state_params(
(False, IndegoAsyncClient.update_user, "user", user, User(**user)),
],
)
@pytest.mark.asyncio
async def test_client_replace(self, sync, func, attr, ret_value, assert_value):
"""Test the base client functions with 200."""
if sync:
resp = MockResponseSync(ret_value, 200)
with patch("requests.request", return_value=resp):
indego = IndegoClient(**test_config)
indego._online = True
indego._userid = "test_user_id"
func(indego)
assert getattr(indego, attr) == assert_value
func(indego)
Expand All @@ -798,9 +792,6 @@ async def test_client_replace(self, sync, func, attr, ret_value, assert_value):
"pyIndego.IndegoAsyncClient.start", return_value=True
):
async with IndegoAsyncClient(**test_config) as indego:
indego._contextid = "askdjfbaks"
indego._online = True
indego._userid = "test_user_id"
await func(indego)
assert getattr(indego, attr) == assert_value
await func(indego)
Expand All @@ -825,22 +816,19 @@ async def test_client_replace(self, sync, func, attr, ret_value, assert_value):
(False, 504, IndegoAsyncClient.update_user, "user", user),
],
)
@pytest.mark.asyncio
async def test_client_responses(self, sync, response, func, attr, ret_value):
"""Test the request functions with different responses."""
if sync:
resp = MockResponseSync(ret_value, response)
with patch("requests.request", return_value=resp):
indego = IndegoClient(**test_config)
indego._online = True
indego._userid = "test_user_id"
func(indego)
assert getattr(indego, attr) == None
else:
resp = MockResponseAsync(ret_value, response)
with patch("aiohttp.ClientSession.request", return_value=resp):
async with IndegoAsyncClient(**test_config) as indego:
indego._online = True
indego._userid = "test_user_id"
await func(indego)
assert getattr(indego, attr) == None

Expand All @@ -858,14 +846,13 @@ async def test_client_responses(self, sync, response, func, attr, ret_value):
(SocketError),
],
)
@pytest.mark.asyncio
async def test_a_client_response_errors(self, error):
"""Test the request functions with different responses."""
with patch("aiohttp.ClientSession.request", side_effect=error), patch(
"asyncio.sleep", new_callable=AsyncMock
):
async with IndegoAsyncClient(**test_config) as indego:
indego._online = True
indego._userid = "test_user_id"
resp = await indego._request(
method=Methods.GET, path="alerts", timeout=1
)
Expand All @@ -880,8 +867,6 @@ def test_client_response_errors(self, error):
"time.sleep", new_callable=SyncMock
):
indego = IndegoClient(**test_config)
indego._online = True
indego._userid = "test_user_id"
resp = indego._request(method=Methods.GET, path="alerts", timeout=1)
assert resp is None

Expand All @@ -894,13 +879,12 @@ def test_client_response_errors(self, error):
(None, False, 0, ValueError),
],
)
@pytest.mark.asyncio
async def test_alert_functions(self, alerts, loaded, index, error):
"""Test the function for handling alerts."""
resp = MockResponseSync(True, 200)
with patch("requests.request", return_value=resp):
indego = IndegoClient(**test_config)
indego._online = True
indego._userid = "test_user_id"
indego.alerts = alerts
indego._alerts_loaded = loaded
try:
Expand Down Expand Up @@ -944,8 +928,6 @@ async def test_alert_functions(self, alerts, loaded, index, error):
"pyIndego.IndegoAsyncClient.start", return_value=True
):
async with IndegoAsyncClient(**test_config) as indego:
indego._online = True
indego._userid = "test_user_id"
indego.alerts = alerts
indego._alerts_loaded = loaded
try:
Expand Down Expand Up @@ -1003,13 +985,12 @@ async def test_alert_functions(self, alerts, loaded, index, error):
("pred_cal", {"cals": 1}, ValueError),
],
)
@pytest.mark.asyncio
async def test_commands(self, command, param, error):
"""Test the function for handling alerts."""
resp = MockResponseSync(True, 200)
with patch("requests.request", return_value=resp):
indego = IndegoClient(**test_config)
indego._online = True
indego._userid = "test_user_id"
if command == "command":
try:
indego.put_command(param)
Expand Down Expand Up @@ -1043,8 +1024,6 @@ async def test_commands(self, command, param, error):
"pyIndego.IndegoAsyncClient.start", return_value=True
):
async with IndegoAsyncClient(**test_config) as indego:
indego._online = True
indego._userid = "test_user_id"
if command == "command":
try:
await indego.put_command(param)
Expand Down Expand Up @@ -1073,46 +1052,11 @@ async def test_commands(self, command, param, error):
except error:
assert True

@pytest.mark.parametrize(
"config",
[
({"username": "testname", "password": "testpassword", "api_url": ""}),
(
{
"username": "testname",
"password": "testpassword",
"serial": "123456789",
"api_url": "",
}
),
],
)
async def test_login(self, config):
"""Test the function for handling alerts."""
resp_json = {"contextId": "98765", "userId": "12345"}
resp_get = [{"alm_sn": "123456789"}]
resp_login_s = MockResponseSync(resp_json, 200)
with patch("requests.request", return_value=resp_login_s), patch(
"pyIndego.IndegoClient.get", return_value=resp_get
):
indego = IndegoClient(**config)
indego.login()
assert indego._userid == "12345"
assert indego.serial == "123456789"

resp_login_a = MockResponseAsync(resp_json, 200)
with patch("aiohttp.ClientSession.request", return_value=resp_login_a), patch(
"pyIndego.IndegoAsyncClient.start", return_value=True
), patch("pyIndego.IndegoAsyncClient.get", return_value=resp_get):
async with IndegoAsyncClient(**config) as indego:
await indego.login()
assert indego._userid == "12345"
assert indego.serial == "123456789"

@pytest.mark.parametrize(
"config, param, error",
[(None, None, ValueError), (None, "test.svg", None), ("test.svg", None, None)],
)
@pytest.mark.asyncio
async def test_download(self, config, param, error):
"""Test the function for download map."""
conf = test_config.copy()
Expand Down

0 comments on commit 0f4e867

Please sign in to comment.