Skip to content

Commit

Permalink
Merge pull request #475 from mraniki/dev
Browse files Browse the repository at this point in the history
✅ Unit Test
  • Loading branch information
mraniki authored Jul 7, 2024
2 parents a2fee8f + f1c4037 commit 9f8a3f2
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 34 deletions.
11 changes: 4 additions & 7 deletions cefi/handler/ccxt.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ def __init__(
"""
super().__init__(**kwargs)
if self.name is None:
return
client = getattr(ccxt, self.name)

self.client = client(
Expand All @@ -52,7 +54,6 @@ def __init__(
self.account_number = self.client.uid
self.name = self.client.id


async def get_quote(self, instrument):
"""
Asynchronously fetches a ask/offer quote
Expand All @@ -71,8 +72,6 @@ async def get_quote(self, instrument):
except Exception as e:
logger.error("{} Error {}", self.name, e)



async def get_bid(self, instrument):
"""
Asynchronously retrieves the bid
Expand Down Expand Up @@ -111,10 +110,8 @@ async def get_account_balance(self):
raw_balance = self.client.fetch_free_balance()
data = list(raw_balance.items())
if self.balance_limit:
data = data[:self.balance_limit_value]
if filtered_balance := {
k: v for k, v in data if v is not None and v > 0
}:
data = data[: self.balance_limit_value]
if filtered_balance := {k: v for k, v in data if v is not None and v > 0}:
balance_str = "".join(
f"{iterator}: {value} \n"
for iterator, value in filtered_balance.items()
Expand Down
57 changes: 30 additions & 27 deletions cefi/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,40 +63,42 @@ def __init__(self):
None
"""
# Check if the module is enabled
self.enabled = settings.cex_enabled or True
self.enabled = settings.cex_enabled

# Create a mapping of library names to client classes
self.client_classes = self.get_all_client_classes()
# logger.debug("client_classes available {}", self.client_classes)

if not self.enabled:
logger.info("Module is disabled. No clients will be created.")
logger.info("Module is disabled. No Client will be created.")
return
self.clients = []
# Create a client for each client in settings.myllm
# Create a client for each client in settings.cex
for name, client_config in settings.cex.items():
# Skip template and empty string client names
if name in ["", "template"] or not client_config.get("enabled"):
if (
# Skip empty client configs
client_config is None
# Skip non-dict client configs
or not isinstance(client_config, dict)
# Skip template and empty string client names
or name in ["", "template"]
# Skip disabled clients
or not client_config.get("enabled")
):
continue
try:
# Create the client
client = self._create_client(**client_config, name=name)
# If the client has a valid client attribute, append it to the list
if client and getattr(client, "client", None):
self.clients.append(client)
except Exception as e:
# Log the error if the client fails to be created
logger.error(f"Failed to create client {name}: {e}")

# Create the client
logger.debug("Creating client {}", name)
client = self._create_client(**client_config, name=name)
# If the client has a valid client attribute, append it to the list
if client and getattr(client, "client", None):
self.clients.append(client)

# Log the number of clients that were created
logger.info(f"Loaded {len(self.clients)} clients")
if not self.clients:
logger.warning(
"""
No clients were created.
Check your settings or disable the module.
https://talky.readthedocs.io/en/latest/02_config.html
"""
"No Client were created. Check your settings or disable the module."
)

def _create_client(self, **kwargs):
Expand Down Expand Up @@ -133,14 +135,15 @@ def _create_client(self, **kwargs):
"""

library = kwargs.get("protocol") or kwargs.get("library")
client_class = self.client_classes.get(f"{library.capitalize()}Handler")

if client_class is None:
logger.error(f"library {library} not supported")
return None

return client_class(**kwargs)
library = (
kwargs.get("library")
or kwargs.get("platform")
or kwargs.get("protocol")
or kwargs.get("parser_library")
or "ccxt"
)
cls = self.client_classes.get((f"{library.capitalize()}Handler"))
return None if cls is None else cls(**kwargs)

def get_all_client_classes(self):
"""
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ addopts = """
-v
--show-capture=stderr
"""
asyncio_mode = "auto"

[tool.coverage.run]
omit = [
Expand Down
39 changes: 39 additions & 0 deletions tests/test_unit_exception.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""
CexTrader Exception Testing
"""

import pytest

from cefi import CexTrader
from cefi.config import settings


@pytest.fixture(scope="session", autouse=True)
def set_test_settings():
settings.configure(FORCE_ENV_FOR_DYNACONF="exception")


@pytest.mark.asyncio
async def test_module_exception(caplog):
result = CexTrader()
print(result)
assert any(
record.message == "Module is disabled. No Client will be created."
for record in caplog.records
if record.levelname == "INFO"
)


# @pytest.mark.asyncio
async def test_create_client_exception(caplog):
settings.cex_enabled = True
test_class = CexTrader()
result = test_class._create_client()
print(result)
assert result is not None
assert any(
record.message
== "No Client were created. Check your settings or disable the module."
for record in caplog.records
if record.levelname == "WARNING"
)

0 comments on commit 9f8a3f2

Please sign in to comment.