Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️ Capitalcom _fetch_account_data refactor #481

Merged
merged 4 commits into from
Jul 15, 2024
Merged

♻️ Capitalcom _fetch_account_data refactor #481

merged 4 commits into from
Jul 15, 2024

Conversation

mraniki
Copy link
Owner

@mraniki mraniki commented Jul 15, 2024

Summary by Sourcery

This pull request refactors the _fetch_account_data method in the capitalcom handler to enhance account switching logic and error handling. Additionally, a new test case for the modify_position method has been added.

  • Enhancements:
    • Refactored the _fetch_account_data method to improve account switching logic and error handling.
  • Tests:
    • Added a new test case for the modify_position method in the test suite.

Copy link

sourcery-ai bot commented Jul 15, 2024

Reviewer's Guide by Sourcery

This pull request refactors the _fetch_account_data method in cefi/handler/capitalcom.py to enhance error handling and logging, and improve the logic for setting the account number. Additionally, a new test case for modifying positions is added in tests/test_unit.py, with some assertions commented out for future validation.

File-Level Changes

Files Changes
cefi/handler/capitalcom.py Refactored _fetch_account_data method for better error handling and logging, and improved account switching logic.
tests/test_unit.py Added a new test case for modifying positions and commented out some assertions for future validation.

Tips
  • Trigger a new Sourcery review by commenting @sourcery-ai review on the pull request.
  • Continue your discussion with Sourcery by replying directly to review comments.
  • You can change your review settings at any time by accessing your dashboard:
    • Enable or disable the Sourcery-generated pull request summary or reviewer's guide;
    • Change the review language;
  • You can always contact us if you have any questions or feedback.

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @mraniki - I've reviewed your changes and found some issues that need to be addressed.

Blocking issues:

  • Typo in method name (link)
  • Incorrect variable used in switch_account (link)
Here's what I looked at during the review
  • 🔴 General issues: 2 blocking issues, 2 other issues
  • 🟡 Security: 1 issue found
  • 🟡 Testing: 2 issues found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment to tell me if it was helpful.

Comment on lines +86 to +95
# try:
# if self.default_account:
# logger.debug("Default account: {}", self.default_account)
# self.switch_account(self.default_account)
# self.accounts_data = self.client.all_accounts()
# except Exception as e:
# logger.error("Error fetching account data: {}", e)
# return False
# logger.debug("Account data: {}", self.accounts_data)
# self.account_number = self.accounts_data["accounts"][0]["accountId"]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Remove commented-out code

The commented-out code should be removed to keep the codebase clean and maintainable. If this code is no longer needed, it's better to delete it rather than leaving it commented out.

try:
self.accounts_data = self.client.all_accounts()
logger.debug("Account data: {}", self.accounts_data)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 issue (security): Potential sensitive data logging

Ensure that self.accounts_data does not contain sensitive information before logging it. Logging sensitive data can lead to security vulnerabilities.

Comment on lines +103 to +105
for account in self.accounts_data["accounts"]:
if account["accountId"] == self.default_account:
self.account_number = account["accountId"]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (performance): Inefficient loop for finding default account

Consider using a more efficient method to find the default account, such as a dictionary lookup, if possible. This will improve the performance, especially if the number of accounts is large.

Suggested change
for account in self.accounts_data["accounts"]:
if account["accountId"] == self.default_account:
self.account_number = account["accountId"]
account_dict = {account["accountId"]: account for account in self.accounts_data["accounts"]}
self.account_number = account_dict.get(self.default_account, self.accounts_data["accounts"][0])["accountId"]

self.account_number = self.accounts_data["accounts"][0]["accountId"]

logger.debug("Account number: {}", self.account_number)
logger.debug("Session details: {}", self.client.get_sesion_details())
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (typo): Typo in method name

There is a typo in the method name get_sesion_details(). It should be get_session_details(). Ensure that the correct method name is used.

@@ -106,7 +123,9 @@ def switch_account(self, account_number):
Returns:
None
"""
self.client.switch_account(self.default_account)
logger.debug("Switching to account {}", account_number)
switch = self.client.switch_account(self.default_account)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Incorrect variable used in switch_account

The method switch_account should use the account_number parameter instead of self.default_account. This ensures that the correct account is switched to.

Comment on lines +112 to +119
@pytest.mark.asyncio
async def test_modify_position(CXTrader, order):
result = await CXTrader.modify_position(order)
print(result)
assert result is not None

# assert ("binance" in result) or ("huobi" in result) or ("capital" in result)
# assert ("🔵" in result) or ("Error" in result)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Add more assertions to cover edge cases

The test test_modify_position currently only checks if the result is not None. It would be beneficial to add more assertions to cover different edge cases and expected outcomes. For example, you could check if the result contains specific keys or values that indicate a successful modification or an error.

Suggested change
@pytest.mark.asyncio
async def test_modify_position(CXTrader, order):
result = await CXTrader.modify_position(order)
print(result)
assert result is not None
# assert ("binance" in result) or ("huobi" in result) or ("capital" in result)
# assert ("🔵" in result) or ("Error" in result)
@pytest.mark.asyncio
async def test_modify_position(CXTrader, order):
result = await CXTrader.modify_position(order)
print(result)
assert result is not None
assert isinstance(result, dict)
assert "status" in result
assert result["status"] in ["success", "error"]
if result["status"] == "error":
assert "message" in result

Comment on lines +113 to +116
async def test_modify_position(CXTrader, order):
result = await CXTrader.modify_position(order)
print(result)
assert result is not None
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Consider adding a test for exception handling

It would be useful to add a test case that simulates an exception being raised during the modify_position method. This will ensure that your code handles exceptions gracefully and behaves as expected under error conditions.

Suggested change
async def test_modify_position(CXTrader, order):
result = await CXTrader.modify_position(order)
print(result)
assert result is not None
async def test_modify_position(CXTrader, order):
try:
result = await CXTrader.modify_position(order)
print(result)
assert result is not None
except Exception as e:
print(f"Exception occurred: {e}")
assert False

Copy link

codecov bot commented Jul 15, 2024

Codecov Report

Attention: Patch coverage is 50.00000% with 6 lines in your changes missing coverage. Please review.

Project coverage is 74.19%. Comparing base (b3207f1) to head (541dd7a).

Files Patch % Lines
cefi/handler/capitalcom.py 50.00% 6 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##             main     #481       +/-   ##
===========================================
+ Coverage   58.69%   74.19%   +15.49%     
===========================================
  Files           7        7               
  Lines         460      465        +5     
===========================================
+ Hits          270      345       +75     
+ Misses        190      120       -70     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@mraniki mraniki merged commit b3c4171 into main Jul 15, 2024
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant