stock-ai-agent/backend/tests/test_bitget_trading_api_sdk_unit.py
2026-03-30 11:34:15 +08:00

120 lines
3.2 KiB
Python

"""
BitgetTradingAPI 单元测试
覆盖重点:
- U 本位账户余额固定走 mix account 接口
- 杠杆设置固定走 mix set-leverage 接口
"""
import importlib.util
import os
import sys
import types
from pathlib import Path
from unittest.mock import MagicMock
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
def load_bitget_sdk_class():
sdk_path = Path(__file__).resolve().parents[1] / 'app' / 'services' / 'bitget_trading_api_sdk.py'
if 'ccxt' not in sys.modules:
ccxt_module = types.ModuleType('ccxt')
ccxt_module.BaseError = Exception
ccxt_module.bitget = MagicMock()
sys.modules['ccxt'] = ccxt_module
module_name = 'app.services.bitget_trading_api_sdk_test'
spec = importlib.util.spec_from_file_location(module_name, sdk_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
return module.BitgetTradingAPI
def test_get_balance_uses_usdt_futures_account_endpoint():
BitgetTradingAPI = load_bitget_sdk_class()
api = BitgetTradingAPI.__new__(BitgetTradingAPI)
api.exchange = MagicMock()
api.use_unified_account = True
api.exchange.privateUtaGetV3AccountAssets.return_value = {
'code': '00000',
'data': {
'assets': [
{
'coin': 'USDT',
'available': '123.45',
'locked': '6.78',
'equity': '130.23',
}
],
},
}
balance = api.get_balance()
api.exchange.privateUtaGetV3AccountAssets.assert_called_once_with({
'coin': 'USDT',
})
assert balance == {
'USDT': {
'available': '123.45',
'frozen': '6.78',
'locked': '6.78',
'equity': '130.23',
}
}
def test_get_balance_supports_alternative_uta_asset_fields():
BitgetTradingAPI = load_bitget_sdk_class()
api = BitgetTradingAPI.__new__(BitgetTradingAPI)
api.exchange = MagicMock()
api.use_unified_account = True
api.exchange.privateUtaGetV3AccountAssets.return_value = {
'code': '00000',
'data': {
'assetList': [
{
'asset': 'USDT',
'availableBalance': '222.2',
'occupied': '11.1',
'accountEquity': '233.3',
}
],
},
}
balance = api.get_balance()
assert balance == {
'USDT': {
'available': '222.2',
'frozen': '11.1',
'locked': '11.1',
'equity': '233.3',
}
}
def test_set_leverage_uses_mix_contract_endpoint():
BitgetTradingAPI = load_bitget_sdk_class()
api = BitgetTradingAPI.__new__(BitgetTradingAPI)
api.exchange = MagicMock()
api.use_unified_account = True
api.exchange.privateUtaPostV3AccountSetLeverage.return_value = {
'code': '00000',
'msg': 'success',
}
success = api.set_leverage('BTC', 10)
assert success is True
api.exchange.privateUtaPostV3AccountSetLeverage.assert_called_once_with({
'symbol': 'BTCUSDT',
'coin': 'USDT',
'category': 'USDT-FUTURES',
'leverage': '10',
})