Skip to content

Commit

Permalink
Add testing & Fix black formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
jgomezve committed Dec 18, 2024
1 parent 8c195b0 commit d4415ea
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 18 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -390,5 +390,8 @@ $RECYCLE.BIN/
# vsCode
.vscode

# Python venv
venv/

# Ansible Collection tarball
cisco-aci-*.tar.gz
22 changes: 5 additions & 17 deletions extensions/eda/plugins/event_source/subscription.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,7 @@ def login(hostname: str, username: str, password: str) -> str:
return token


def subscribe(
hostname: str, token: str, rf_timeout: int, sub_urls: list[str]
) -> list[str]:
def subscribe(hostname: str, token: str, rf_timeout: int, sub_urls: list[str]) -> list[str]:
"""
subscribe to a websocket
Expand All @@ -70,9 +68,7 @@ def subscribe(
sub_ids = []

for sub in sub_urls:
sub_url = (
f"https://{hostname}{sub}&subscription=yes&refresh-timeout={rf_timeout}"
)
sub_url = f"https://{hostname}{sub}&subscription=yes&refresh-timeout={rf_timeout}"
cookie = {"APIC-cookie": token}
sub_response = requests.get(sub_url, verify=False, cookies=cookie, timeout=60)
if sub_response.ok:
Expand All @@ -81,9 +77,7 @@ def subscribe(
return sub_ids


async def refresh(
hostname: str, token: str, refresh_timeout: int, sub_ids: list[str]
) -> NoReturn:
async def refresh(hostname: str, token: str, refresh_timeout: int, sub_ids: list[str]) -> NoReturn:
"""
refresh subscriptions
Expand All @@ -109,16 +103,10 @@ async def main(queue: asyncio.Queue, args: Dict[str, Any]):
subscriptions = args.get("subscriptions")

if "" in [hostname, username, password]:
print(
f"hostname, username and password can't be empty:{hostname}, {username}, *****"
)
print(f"hostname, username and password can't be empty:{hostname}, {username}, *****")
sys.exit(1)

if (
not isinstance(subscriptions, list)
or subscriptions == []
or subscriptions is None
):
if not isinstance(subscriptions, list) or subscriptions == [] or subscriptions is None:
print(f"subscriptions is empty or not a list: {subscriptions}")
sys.exit(1)

Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ pyOpenSSL
python_dateutil
xmljson
requests
websockets
websockets
asyncmock
Empty file.
79 changes: 79 additions & 0 deletions tests/unit/event_source/test_subscription.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
from unittest.mock import patch
from typing import Any, List
from asyncmock import AsyncMock
from extensions.eda.plugins.event_source.subscription import main as subscription_main
import pytest
import json
import asyncio


# Refresh mock method
def refresh_patch(hostname: str, token: str, rf_timeout: int, sub_urls: List[str]) -> None:
pass


# Login mock method
def login_patch(hostname: str, username: str, password: str) -> str:
return f"{hostname}{username}{password}"


# Subscribe mock method
def subscribe_patch(hostname, token, rf_timeout, sub_urls) -> List[str]:
return [f"{hostname}{token}{rf_timeout}{url}" for url in sub_urls]


# Mock iterator
class AsyncIterator:
def __init__(self) -> None:
self.count = 0

async def __anext__(self) -> str:
if self.count < 2:
self.count += 1
return json.dumps({"eventid": f"00{self.count}"})
else:
raise StopAsyncIteration


# Mock Async Websocket
class MockWebSocket(AsyncMock): # type: ignore[misc]
def __aiter__(self) -> AsyncIterator:
return AsyncIterator()

async def close(self) -> None:
pass


# Mock AsyncQueue
class MockQueue(asyncio.Queue[Any]):
def __init__(self) -> None:
self.queue: list[Any] = []

async def put(self, item: Any) -> None:
self.queue.append(item)


def test_websocket_subscription() -> None:

with patch(
"websockets.connect",
return_value=MockWebSocket(),
), patch("unit.event_source.tmp_subscription.login", return_value=login_patch), patch(
"unit.event_source.tmp_subscription.subscribe", return_value=subscribe_patch
), patch("unit.event_source.tmp_subscription.refresh", return_value=refresh_patch):

my_queue = MockQueue()
asyncio.run(
subscription_main(
my_queue,
{
"hostname": "my-apic.com",
"username": "admin",
"password": "admin",
"subscriptions": ['/api/node/class/faultInst.json?query-target-filter=and(eq(faultInst.code,"F1386"))'],
},
)
)

assert my_queue.queue[0] == {"eventid": "001"}
assert len(my_queue.queue) == 2

0 comments on commit d4415ea

Please sign in to comment.