"""
Binance Margin Trading REST API

OpenAPI Specification for the Binance Margin Trading REST API
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)

Do not edit the class manually.
"""

import json
import pytest
import requests

from unittest.mock import MagicMock, patch
from urllib.parse import parse_qs

from binance_common.configuration import ConfigurationRestAPI
from binance_common.errors import RequiredError
from binance_common.utils import normalize_query_values, is_one_of_model, snake_to_camel

from binance_sdk_margin_trading.rest_api.api import AccountApi
from binance_sdk_margin_trading.rest_api.models import (
    AdjustCrossMarginMaxLeverageResponse,
)
from binance_sdk_margin_trading.rest_api.models import (
    DisableIsolatedMarginAccountResponse,
)
from binance_sdk_margin_trading.rest_api.models import (
    EnableIsolatedMarginAccountResponse,
)
from binance_sdk_margin_trading.rest_api.models import GetBnbBurnStatusResponse
from binance_sdk_margin_trading.rest_api.models import GetSummaryOfMarginAccountResponse
from binance_sdk_margin_trading.rest_api.models import (
    QueryCrossIsolatedMarginCapitalFlowResponse,
)
from binance_sdk_margin_trading.rest_api.models import (
    QueryCrossMarginAccountDetailsResponse,
)
from binance_sdk_margin_trading.rest_api.models import QueryCrossMarginFeeDataResponse
from binance_sdk_margin_trading.rest_api.models import (
    QueryEnabledIsolatedMarginAccountLimitResponse,
)
from binance_sdk_margin_trading.rest_api.models import (
    QueryIsolatedMarginAccountInfoResponse,
)
from binance_sdk_margin_trading.rest_api.models import (
    QueryIsolatedMarginFeeDataResponse,
)


class TestAccountApi:
    @pytest.fixture(autouse=True)
    def setup_client(self):
        """Setup a client instance with mocked session before each test method."""
        self.mock_session = MagicMock(spec=requests.Session)
        config = ConfigurationRestAPI(
            api_key="test-api-key",
            api_secret="test-api-secret",
        )
        self.client = AccountApi(configuration=config, session=self.mock_session)

    def set_mock_response(self, data: dict = {}, status_code=200, headers=None):
        """Helper method to setup mock response for the client's session request."""
        if headers is None:
            headers = {}

        mock_response = MagicMock()
        mock_response.status_code = status_code
        mock_response.json.return_value = data
        mock_response.text = json.dumps(data)
        mock_response.headers = headers

        self.mock_session.request.return_value = mock_response

    @patch("binance_common.utils.get_signature")
    def test_adjust_cross_margin_max_leverage_success(self, mock_get_signature):
        """Test adjust_cross_margin_max_leverage() successfully with required parameters only."""

        params = {"max_leverage": 56}

        expected_response = {"success": True}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.adjust_cross_margin_max_leverage(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs
        parsed_params = parse_qs(request_kwargs["params"])
        camel_case_params = {snake_to_camel(k): v for k, v in params.items()}
        normalized = normalize_query_values(parsed_params, camel_case_params)

        self.mock_session.request.assert_called_once()
        mock_get_signature.assert_called_once()

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/max-leverage" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"
        assert normalized["maxLeverage"] == 56

        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(AdjustCrossMarginMaxLeverageResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif (
            is_oneof
            or is_list
            or hasattr(AdjustCrossMarginMaxLeverageResponse, "from_dict")
        ):
            expected = AdjustCrossMarginMaxLeverageResponse.from_dict(expected_response)
        else:
            expected = AdjustCrossMarginMaxLeverageResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    @patch("binance_common.utils.get_signature")
    def test_adjust_cross_margin_max_leverage_success_with_optional_params(
        self, mock_get_signature
    ):
        """Test adjust_cross_margin_max_leverage() successfully with optional parameters."""

        params = {"max_leverage": 56}

        expected_response = {"success": True}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.adjust_cross_margin_max_leverage(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/max-leverage" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"

        self.mock_session.request.assert_called_once()
        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(AdjustCrossMarginMaxLeverageResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif (
            is_oneof
            or is_list
            or hasattr(AdjustCrossMarginMaxLeverageResponse, "from_dict")
        ):
            expected = AdjustCrossMarginMaxLeverageResponse.from_dict(expected_response)
        else:
            expected = AdjustCrossMarginMaxLeverageResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    def test_adjust_cross_margin_max_leverage_missing_required_param_max_leverage(self):
        """Test that adjust_cross_margin_max_leverage() raises RequiredError when 'max_leverage' is missing."""
        params = {"max_leverage": 56}
        params["max_leverage"] = None

        with pytest.raises(
            RequiredError, match="Missing required parameter 'max_leverage'"
        ):
            self.client.adjust_cross_margin_max_leverage(**params)

    def test_adjust_cross_margin_max_leverage_server_error(self):
        """Test that adjust_cross_margin_max_leverage() raises an error when the server returns an error."""

        params = {"max_leverage": 56}

        mock_error = Exception("ResponseError")
        self.client.adjust_cross_margin_max_leverage = MagicMock(side_effect=mock_error)

        with pytest.raises(Exception, match="ResponseError"):
            self.client.adjust_cross_margin_max_leverage(**params)

    @patch("binance_common.utils.get_signature")
    def test_disable_isolated_margin_account_success(self, mock_get_signature):
        """Test disable_isolated_margin_account() successfully with required parameters only."""

        params = {
            "symbol": "symbol_example",
        }

        expected_response = {"success": True, "symbol": "BTCUSDT"}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.disable_isolated_margin_account(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs
        parsed_params = parse_qs(request_kwargs["params"])
        camel_case_params = {snake_to_camel(k): v for k, v in params.items()}
        normalized = normalize_query_values(parsed_params, camel_case_params)

        self.mock_session.request.assert_called_once()
        mock_get_signature.assert_called_once()

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/isolated/account" in request_kwargs["url"]
        assert request_kwargs["method"] == "DELETE"
        assert normalized["symbol"] == "symbol_example"

        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(DisableIsolatedMarginAccountResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif (
            is_oneof
            or is_list
            or hasattr(DisableIsolatedMarginAccountResponse, "from_dict")
        ):
            expected = DisableIsolatedMarginAccountResponse.from_dict(expected_response)
        else:
            expected = DisableIsolatedMarginAccountResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    @patch("binance_common.utils.get_signature")
    def test_disable_isolated_margin_account_success_with_optional_params(
        self, mock_get_signature
    ):
        """Test disable_isolated_margin_account() successfully with optional parameters."""

        params = {"symbol": "symbol_example", "recv_window": 5000}

        expected_response = {"success": True, "symbol": "BTCUSDT"}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.disable_isolated_margin_account(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/isolated/account" in request_kwargs["url"]
        assert request_kwargs["method"] == "DELETE"

        self.mock_session.request.assert_called_once()
        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(DisableIsolatedMarginAccountResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif (
            is_oneof
            or is_list
            or hasattr(DisableIsolatedMarginAccountResponse, "from_dict")
        ):
            expected = DisableIsolatedMarginAccountResponse.from_dict(expected_response)
        else:
            expected = DisableIsolatedMarginAccountResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    def test_disable_isolated_margin_account_missing_required_param_symbol(self):
        """Test that disable_isolated_margin_account() raises RequiredError when 'symbol' is missing."""
        params = {
            "symbol": "symbol_example",
        }
        params["symbol"] = None

        with pytest.raises(RequiredError, match="Missing required parameter 'symbol'"):
            self.client.disable_isolated_margin_account(**params)

    def test_disable_isolated_margin_account_server_error(self):
        """Test that disable_isolated_margin_account() raises an error when the server returns an error."""

        params = {
            "symbol": "symbol_example",
        }

        mock_error = Exception("ResponseError")
        self.client.disable_isolated_margin_account = MagicMock(side_effect=mock_error)

        with pytest.raises(Exception, match="ResponseError"):
            self.client.disable_isolated_margin_account(**params)

    @patch("binance_common.utils.get_signature")
    def test_enable_isolated_margin_account_success(self, mock_get_signature):
        """Test enable_isolated_margin_account() successfully with required parameters only."""

        params = {
            "symbol": "symbol_example",
        }

        expected_response = {"success": True, "symbol": "BTCUSDT"}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.enable_isolated_margin_account(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs
        parsed_params = parse_qs(request_kwargs["params"])
        camel_case_params = {snake_to_camel(k): v for k, v in params.items()}
        normalized = normalize_query_values(parsed_params, camel_case_params)

        self.mock_session.request.assert_called_once()
        mock_get_signature.assert_called_once()

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/isolated/account" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"
        assert normalized["symbol"] == "symbol_example"

        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(EnableIsolatedMarginAccountResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif (
            is_oneof
            or is_list
            or hasattr(EnableIsolatedMarginAccountResponse, "from_dict")
        ):
            expected = EnableIsolatedMarginAccountResponse.from_dict(expected_response)
        else:
            expected = EnableIsolatedMarginAccountResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    @patch("binance_common.utils.get_signature")
    def test_enable_isolated_margin_account_success_with_optional_params(
        self, mock_get_signature
    ):
        """Test enable_isolated_margin_account() successfully with optional parameters."""

        params = {"symbol": "symbol_example", "recv_window": 5000}

        expected_response = {"success": True, "symbol": "BTCUSDT"}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.enable_isolated_margin_account(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/isolated/account" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"

        self.mock_session.request.assert_called_once()
        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(EnableIsolatedMarginAccountResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif (
            is_oneof
            or is_list
            or hasattr(EnableIsolatedMarginAccountResponse, "from_dict")
        ):
            expected = EnableIsolatedMarginAccountResponse.from_dict(expected_response)
        else:
            expected = EnableIsolatedMarginAccountResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    def test_enable_isolated_margin_account_missing_required_param_symbol(self):
        """Test that enable_isolated_margin_account() raises RequiredError when 'symbol' is missing."""
        params = {
            "symbol": "symbol_example",
        }
        params["symbol"] = None

        with pytest.raises(RequiredError, match="Missing required parameter 'symbol'"):
            self.client.enable_isolated_margin_account(**params)

    def test_enable_isolated_margin_account_server_error(self):
        """Test that enable_isolated_margin_account() raises an error when the server returns an error."""

        params = {
            "symbol": "symbol_example",
        }

        mock_error = Exception("ResponseError")
        self.client.enable_isolated_margin_account = MagicMock(side_effect=mock_error)

        with pytest.raises(Exception, match="ResponseError"):
            self.client.enable_isolated_margin_account(**params)

    @patch("binance_common.utils.get_signature")
    def test_get_bnb_burn_status_success(self, mock_get_signature):
        """Test get_bnb_burn_status() successfully with required parameters only."""

        expected_response = {"spotBNBBurn": True, "interestBNBBurn": False}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_bnb_burn_status()

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        self.mock_session.request.assert_called_once()
        mock_get_signature.assert_called_once()

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/bnbBurn" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"

        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(GetBnbBurnStatusResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif is_oneof or is_list or hasattr(GetBnbBurnStatusResponse, "from_dict"):
            expected = GetBnbBurnStatusResponse.from_dict(expected_response)
        else:
            expected = GetBnbBurnStatusResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    @patch("binance_common.utils.get_signature")
    def test_get_bnb_burn_status_success_with_optional_params(self, mock_get_signature):
        """Test get_bnb_burn_status() successfully with optional parameters."""

        params = {"recv_window": 5000}

        expected_response = {"spotBNBBurn": True, "interestBNBBurn": False}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_bnb_burn_status(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/bnbBurn" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"

        self.mock_session.request.assert_called_once()
        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(GetBnbBurnStatusResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif is_oneof or is_list or hasattr(GetBnbBurnStatusResponse, "from_dict"):
            expected = GetBnbBurnStatusResponse.from_dict(expected_response)
        else:
            expected = GetBnbBurnStatusResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    def test_get_bnb_burn_status_server_error(self):
        """Test that get_bnb_burn_status() raises an error when the server returns an error."""

        mock_error = Exception("ResponseError")
        self.client.get_bnb_burn_status = MagicMock(side_effect=mock_error)

        with pytest.raises(Exception, match="ResponseError"):
            self.client.get_bnb_burn_status()

    @patch("binance_common.utils.get_signature")
    def test_get_summary_of_margin_account_success(self, mock_get_signature):
        """Test get_summary_of_margin_account() successfully with required parameters only."""

        expected_response = {
            "normalBar": "1.5",
            "marginCallBar": "1.3",
            "forceLiquidationBar": "1.1",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_summary_of_margin_account()

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        self.mock_session.request.assert_called_once()
        mock_get_signature.assert_called_once()

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/tradeCoeff" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"

        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(GetSummaryOfMarginAccountResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif (
            is_oneof
            or is_list
            or hasattr(GetSummaryOfMarginAccountResponse, "from_dict")
        ):
            expected = GetSummaryOfMarginAccountResponse.from_dict(expected_response)
        else:
            expected = GetSummaryOfMarginAccountResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    @patch("binance_common.utils.get_signature")
    def test_get_summary_of_margin_account_success_with_optional_params(
        self, mock_get_signature
    ):
        """Test get_summary_of_margin_account() successfully with optional parameters."""

        params = {"recv_window": 5000}

        expected_response = {
            "normalBar": "1.5",
            "marginCallBar": "1.3",
            "forceLiquidationBar": "1.1",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_summary_of_margin_account(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/tradeCoeff" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"

        self.mock_session.request.assert_called_once()
        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(GetSummaryOfMarginAccountResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif (
            is_oneof
            or is_list
            or hasattr(GetSummaryOfMarginAccountResponse, "from_dict")
        ):
            expected = GetSummaryOfMarginAccountResponse.from_dict(expected_response)
        else:
            expected = GetSummaryOfMarginAccountResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    def test_get_summary_of_margin_account_server_error(self):
        """Test that get_summary_of_margin_account() raises an error when the server returns an error."""

        mock_error = Exception("ResponseError")
        self.client.get_summary_of_margin_account = MagicMock(side_effect=mock_error)

        with pytest.raises(Exception, match="ResponseError"):
            self.client.get_summary_of_margin_account()

    @patch("binance_common.utils.get_signature")
    def test_query_cross_isolated_margin_capital_flow_success(self, mock_get_signature):
        """Test query_cross_isolated_margin_capital_flow() successfully with required parameters only."""

        expected_response = [
            {
                "id": 123456,
                "tranId": 123123,
                "timestamp": 1691116657000,
                "asset": "USDT",
                "symbol": "BTCUSDT",
                "type": "BORROW",
                "amount": "101",
            },
            {
                "id": 123457,
                "tranId": 123124,
                "timestamp": 1691116658000,
                "asset": "BTC",
                "symbol": "BTCUSDT",
                "type": "REPAY",
                "amount": "10",
            },
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.query_cross_isolated_margin_capital_flow()

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        self.mock_session.request.assert_called_once()
        mock_get_signature.assert_called_once()

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/capital-flow" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"

        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(QueryCrossIsolatedMarginCapitalFlowResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif (
            is_oneof
            or is_list
            or hasattr(QueryCrossIsolatedMarginCapitalFlowResponse, "from_dict")
        ):
            expected = QueryCrossIsolatedMarginCapitalFlowResponse.from_dict(
                expected_response
            )
        else:
            expected = QueryCrossIsolatedMarginCapitalFlowResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    @patch("binance_common.utils.get_signature")
    def test_query_cross_isolated_margin_capital_flow_success_with_optional_params(
        self, mock_get_signature
    ):
        """Test query_cross_isolated_margin_capital_flow() successfully with optional parameters."""

        params = {
            "asset": "asset_example",
            "symbol": "symbol_example",
            "type": "type_example",
            "start_time": 1623319461670,
            "end_time": 1641782889000,
            "from_id": 1,
            "limit": 500,
            "recv_window": 5000,
        }

        expected_response = [
            {
                "id": 123456,
                "tranId": 123123,
                "timestamp": 1691116657000,
                "asset": "USDT",
                "symbol": "BTCUSDT",
                "type": "BORROW",
                "amount": "101",
            },
            {
                "id": 123457,
                "tranId": 123124,
                "timestamp": 1691116658000,
                "asset": "BTC",
                "symbol": "BTCUSDT",
                "type": "REPAY",
                "amount": "10",
            },
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.query_cross_isolated_margin_capital_flow(**params)

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/capital-flow" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"

        self.mock_session.request.assert_called_once()
        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
            is_list and not isinstance(expected_response[0], list) if is_list else False
        )
        is_oneof = is_one_of_model(QueryCrossIsolatedMarginCapitalFlowResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif (
            is_oneof
            or is_list
            or hasattr(QueryCrossIsolatedMarginCapitalFlowResponse, "from_dict")
        ):
            expected = QueryCrossIsolatedMarginCapitalFlowResponse.from_dict(
                expected_response
            )
        else:
            expected = QueryCrossIsolatedMarginCapitalFlowResponse.model_validate_json(
                json.dumps(expected_response)
            )

        assert response.data() == expected

    def test_query_cross_isolated_margin_capital_flow_server_error(self):
        """Test that query_cross_isolated_margin_capital_flow() raises an error when the server returns an error."""

        mock_error = Exception("ResponseError")
        self.client.query_cross_isolated_margin_capital_flow = MagicMock(
            side_effect=mock_error
        )

        with pytest.raises(Exception, match="ResponseError"):
            self.client.query_cross_isolated_margin_capital_flow()

    @patch("binance_common.utils.get_signature")
    def test_query_cross_margin_account_details_success(self, mock_get_signature):
        """Test query_cross_margin_account_details() successfully with required parameters only."""

        expected_response = {
            "created": True,
            "borrowEnabled": True,
            "marginLevel": "11.64405625",
            "collateralMarginLevel": "3.2",
            "totalAssetOfBtc": "6.82728457",
            "totalLiabilityOfBtc": "0.58633215",
            "totalNetAssetOfBtc": "6.24095242",
            "TotalCollateralValueInUSDT": "5.82728457",
            "totalOpenOrderLossInUSDT": "582.728457",
            "tradeEnabled": True,
            "transferInEnabled": True,
            "transferOutEnabled": True,
            "accountType": "MARGIN_1",
            "userAssets": [
                {
                    "asset": "BTC",
                    "borrowed": "0.00000000",
                    "free": "0.00499500",
                    "interest": "0.00000000",
                    "locked": "0.00000000",
                    "netAsset": "0.00499500",
                },
                {
                    "asset": "BNB",
                    "borrowed": "201.66666672",
                    "free": "2346.50000000",
                    "interest": "0.00000000",
                    "locked": "0.00000000",
                    "netAsset": "2144.83333328",
                },
                {
                    "asset": "ETH",
                    "borrowed": "0.00000000",
                    "free": "0.00000000",
                    "interest": "0.00000000",
                    "locked": "0.00000000",
                    "netAsset": "0.00000000",
                },
                {
                    "asset": "USDT",
                    "borrowed": "0.00000000",
                    "free": "0.00000000",
                    "interest": "0.00000000",
                    "locked": "0.00000000",
                    "netAsset": "0.00000000",
                },
            ],
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.query_cross_margin_account_details()

        actual_call_args = self.mock_session.request.call_args
        request_kwargs = actual_call_args.kwargs

        self.mock_session.request.assert_called_once()
        mock_get_signature.assert_called_once()

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/account" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"

        assert response is not None
        is_list = isinstance(expected_response, list)
        is_flat_list = (
