"""
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 TradeApi
from binance_sdk_margin_trading.rest_api.models import CreateSpecialKeyResponse


from binance_sdk_margin_trading.rest_api.models import GetForceLiquidationRecordResponse
from binance_sdk_margin_trading.rest_api.models import (
    GetSmallLiabilityExchangeCoinListResponse,
)
from binance_sdk_margin_trading.rest_api.models import (
    GetSmallLiabilityExchangeHistoryResponse,
)
from binance_sdk_margin_trading.rest_api.models import (
    MarginAccountCancelAllOpenOrdersOnASymbolResponse,
)
from binance_sdk_margin_trading.rest_api.models import MarginAccountCancelOcoResponse
from binance_sdk_margin_trading.rest_api.models import MarginAccountCancelOrderResponse
from binance_sdk_margin_trading.rest_api.models import MarginAccountNewOcoResponse
from binance_sdk_margin_trading.rest_api.models import MarginAccountNewOrderResponse
from binance_sdk_margin_trading.rest_api.models import MarginAccountNewOtoResponse
from binance_sdk_margin_trading.rest_api.models import MarginAccountNewOtocoResponse
from binance_sdk_margin_trading.rest_api.models import MarginManualLiquidationResponse
from binance_sdk_margin_trading.rest_api.models import (
    QueryCurrentMarginOrderCountUsageResponse,
)
from binance_sdk_margin_trading.rest_api.models import QueryMarginAccountsAllOcoResponse
from binance_sdk_margin_trading.rest_api.models import (
    QueryMarginAccountsAllOrdersResponse,
)
from binance_sdk_margin_trading.rest_api.models import QueryMarginAccountsOcoResponse
from binance_sdk_margin_trading.rest_api.models import (
    QueryMarginAccountsOpenOcoResponse,
)
from binance_sdk_margin_trading.rest_api.models import (
    QueryMarginAccountsOpenOrdersResponse,
)
from binance_sdk_margin_trading.rest_api.models import QueryMarginAccountsOrderResponse
from binance_sdk_margin_trading.rest_api.models import (
    QueryMarginAccountsTradeListResponse,
)
from binance_sdk_margin_trading.rest_api.models import QuerySpecialKeyResponse
from binance_sdk_margin_trading.rest_api.models import QuerySpecialKeyListResponse


from binance_sdk_margin_trading.rest_api.models import MarginAccountNewOcoSideEnum
from binance_sdk_margin_trading.rest_api.models import (
    MarginAccountNewOcoNewOrderRespTypeEnum,
)
from binance_sdk_margin_trading.rest_api.models import MarginAccountNewOrderSideEnum
from binance_sdk_margin_trading.rest_api.models import (
    MarginAccountNewOrderNewOrderRespTypeEnum,
)
from binance_sdk_margin_trading.rest_api.models import (
    MarginAccountNewOrderTimeInForceEnum,
)
from binance_sdk_margin_trading.rest_api.models import (
    MarginAccountNewOtoNewOrderRespTypeEnum,
)
from binance_sdk_margin_trading.rest_api.models import (
    MarginAccountNewOtocoNewOrderRespTypeEnum,
)


class TestTradeApi:
    @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 = TradeApi(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_create_special_key_success(self, mock_get_signature):
        """Test create_special_key() successfully with required parameters only."""

        params = {
            "api_name": "api_name_example",
        }

        expected_response = {
            "apiKey": "npOzOAeLVgr2TuxWfNo43AaPWpBbJEoKezh1o8mSQb6ryE2odE11A4AoVlJbQoGx",
            "secretKey": "87ssWB7azoy6ACRfyp6OVOL5U3rtZptX31QWw2kWjl1jHEYRbyM1pd6qykRBQw8p",
            "type": "HMAC_SHA256",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.create_special_key(**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/apiKey" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"
        assert normalized["apiName"] == "api_name_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(CreateSpecialKeyResponse)

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

        assert response.data() == expected

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

        params = {
            "api_name": "api_name_example",
            "symbol": "symbol_example",
            "ip": "ip_example",
            "public_key": "public_key_example",
            "permission_mode": "value",
            "recv_window": 5000,
        }

        expected_response = {
            "apiKey": "npOzOAeLVgr2TuxWfNo43AaPWpBbJEoKezh1o8mSQb6ryE2odE11A4AoVlJbQoGx",
            "secretKey": "87ssWB7azoy6ACRfyp6OVOL5U3rtZptX31QWw2kWjl1jHEYRbyM1pd6qykRBQw8p",
            "type": "HMAC_SHA256",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.create_special_key(**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/apiKey" 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(CreateSpecialKeyResponse)

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

        assert response.data() == expected

    def test_create_special_key_missing_required_param_api_name(self):
        """Test that create_special_key() raises RequiredError when 'api_name' is missing."""
        params = {
            "api_name": "api_name_example",
        }
        params["api_name"] = None

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

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

        params = {
            "api_name": "api_name_example",
        }

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

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

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

        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response({})

        response = self.client.delete_special_key()

        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/apiKey" in request_kwargs["url"]
        assert request_kwargs["method"] == "DELETE"

        assert response is not None

        assert response.data() == {}

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

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

        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response({})

        response = self.client.delete_special_key(**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/apiKey" in request_kwargs["url"]
        assert request_kwargs["method"] == "DELETE"

        self.mock_session.request.assert_called_once()
        assert response is not None

        assert response.data() == {}

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

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

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

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

        params = {
            "ip": "ip_example",
        }

        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response({})

        response = self.client.edit_ip_for_special_key(**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/apiKey/ip" in request_kwargs["url"]
        assert request_kwargs["method"] == "PUT"
        assert normalized["ip"] == "ip_example"

        assert response is not None

        assert response.data() == {}

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

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

        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response({})

        response = self.client.edit_ip_for_special_key(**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/apiKey/ip" in request_kwargs["url"]
        assert request_kwargs["method"] == "PUT"

        self.mock_session.request.assert_called_once()
        assert response is not None

        assert response.data() == {}

    def test_edit_ip_for_special_key_missing_required_param_ip(self):
        """Test that edit_ip_for_special_key() raises RequiredError when 'ip' is missing."""
        params = {
            "ip": "ip_example",
        }
        params["ip"] = None

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

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

        params = {
            "ip": "ip_example",
        }

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

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

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

        expected_response = {
            "rows": [
                {
                    "avgPrice": "0.00388359",
                    "executedQty": "31.39000000",
                    "orderId": 180015097,
                    "price": "0.00388110",
                    "qty": "31.39000000",
                    "side": "SELL",
                    "symbol": "BNBBTC",
                    "timeInForce": "GTC",
                    "isIsolated": True,
                    "updatedTime": 1558941374745,
                }
            ],
            "total": 1,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_force_liquidation_record()

        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/forceLiquidationRec" 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(GetForceLiquidationRecordResponse)

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

        assert response.data() == expected

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

        params = {
            "start_time": 1623319461670,
            "end_time": 1641782889000,
            "isolated_symbol": "isolated_symbol_example",
            "current": 1,
            "size": 10,
            "recv_window": 5000,
        }

        expected_response = {
            "rows": [
                {
                    "avgPrice": "0.00388359",
                    "executedQty": "31.39000000",
                    "orderId": 180015097,
                    "price": "0.00388110",
                    "qty": "31.39000000",
                    "side": "SELL",
                    "symbol": "BNBBTC",
                    "timeInForce": "GTC",
                    "isIsolated": True,
                    "updatedTime": 1558941374745,
                }
            ],
            "total": 1,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_force_liquidation_record(**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/forceLiquidationRec" 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(GetForceLiquidationRecordResponse)

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

        assert response.data() == expected

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

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

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

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

        expected_response = [
            {
                "asset": "ETH",
                "interest": "0.00083334",
                "principal": "0.001",
                "liabilityAsset": "USDT",
                "liabilityQty": 0.3552,
            }
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_small_liability_exchange_coin_list()

        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/exchange-small-liability" 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(GetSmallLiabilityExchangeCoinListResponse)

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

        assert response.data() == expected

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

        params = {"recv_window": 5000}

        expected_response = [
            {
                "asset": "ETH",
                "interest": "0.00083334",
                "principal": "0.001",
                "liabilityAsset": "USDT",
                "liabilityQty": 0.3552,
            }
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_small_liability_exchange_coin_list(**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/exchange-small-liability" 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(GetSmallLiabilityExchangeCoinListResponse)

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

        assert response.data() == expected

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

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

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

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

        params = {
            "current": 1,
            "size": 10,
        }

        expected_response = {
            "total": 1,
            "rows": [
                {
                    "asset": "ETH",
                    "amount": "0.00083434",
                    "targetAsset": "BUSD",
                    "targetAmount": "1.37576819",
                    "bizType": "EXCHANGE_SMALL_LIABILITY",
                    "timestamp": 1672801339253,
                }
            ],
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_small_liability_exchange_history(**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/exchange-small-liability-history" in request_kwargs["url"]
        )
        assert request_kwargs["method"] == "GET"
        assert normalized["current"] == 1
        assert normalized["size"] == 10

        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(GetSmallLiabilityExchangeHistoryResponse)

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

        assert response.data() == expected

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

        params = {
            "current": 1,
            "size": 10,
            "start_time": 1623319461670,
            "end_time": 1641782889000,
            "recv_window": 5000,
        }

        expected_response = {
            "total": 1,
            "rows": [
                {
                    "asset": "ETH",
                    "amount": "0.00083434",
                    "targetAsset": "BUSD",
                    "targetAmount": "1.37576819",
                    "bizType": "EXCHANGE_SMALL_LIABILITY",
                    "timestamp": 1672801339253,
                }
            ],
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_small_liability_exchange_history(**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/exchange-small-liability-history" 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(GetSmallLiabilityExchangeHistoryResponse)

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

        assert response.data() == expected

    def test_get_small_liability_exchange_history_missing_required_param_current(self):
        """Test that get_small_liability_exchange_history() raises RequiredError when 'current' is missing."""
        params = {
            "current": 1,
            "size": 10,
        }
        params["current"] = None

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

    def test_get_small_liability_exchange_history_missing_required_param_size(self):
        """Test that get_small_liability_exchange_history() raises RequiredError when 'size' is missing."""
        params = {
            "current": 1,
            "size": 10,
        }
        params["size"] = None

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

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

        params = {
            "current": 1,
            "size": 10,
        }

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

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

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

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

        expected_response = [
            {
                "symbol": "BTCUSDT",
                "isIsolated": True,
                "origClientOrderId": "E6APeyTJvkMvLMYMqu1KQ4",
                "orderId": 11,
                "orderListId": -1,
                "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
                "price": "0.089853",
                "origQty": "0.178622",
                "executedQty": "0.000000",
                "cummulativeQuoteQty": "0.000000",
                "status": "CANCELED",
                "timeInForce": "GTC",
                "type": "LIMIT",
                "side": "BUY",
                "selfTradePreventionMode": "NONE",
            },
            {
                "symbol": "BTCUSDT",
                "isIsolated": False,
                "origClientOrderId": "A3EF2HCwxgZPFMrfwbgrhv",
                "orderId": 13,
                "orderListId": -1,
                "clientOrderId": "pXLV6Hz6mprAcVYpVMTGgx",
                "price": "0.090430",
                "origQty": "0.178622",
                "executedQty": "0.000000",
                "cummulativeQuoteQty": "0.000000",
                "status": "CANCELED",
                "timeInForce": "GTC",
                "type": "LIMIT",
                "side": "BUY",
                "selfTradePreventionMode": "NONE",
            },
            {
                "orderListId": 1929,
                "contingencyType": "OCO",
                "listStatusType": "ALL_DONE",
                "listOrderStatus": "ALL_DONE",
                "listClientOrderId": "2inzWQdDvZLHbbAmAozX2N",
                "transactionTime": 1585230948299,
                "symbol": "BTCUSDT",
                "isIsolated": True,
                "orders": [
                    {
                        "symbol": "BTCUSDT",
                        "orderId": 20,
