"""
Binance Derivatives Trading Portfolio Margin REST API

OpenAPI Specification for the Binance Derivatives Trading Portfolio Margin 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_derivatives_trading_portfolio_margin.rest_api.api import TradeApi
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    CancelAllCmOpenConditionalOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    CancelAllCmOpenOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    CancelAllUmOpenConditionalOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    CancelAllUmOpenOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    CancelCmConditionalOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    CancelCmOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    CancelMarginAccountAllOpenOrdersOnASymbolResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    CancelMarginAccountOcoOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    CancelMarginAccountOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    CancelUmConditionalOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    CancelUmOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    CmAccountTradeListResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    CmPositionAdlQuantileEstimationResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    GetUmFuturesBnbBurnStatusResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    MarginAccountBorrowResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    MarginAccountNewOcoResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    MarginAccountRepayResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    MarginAccountRepayDebtResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    MarginAccountTradeListResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    ModifyCmOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    ModifyUmOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewCmConditionalOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewCmOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewMarginOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmConditionalOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryAllCmConditionalOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryAllCmOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryAllCurrentCmOpenConditionalOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryAllCurrentCmOpenOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryAllCurrentUmOpenConditionalOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryAllCurrentUmOpenOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryAllMarginAccountOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryAllUmConditionalOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryAllUmOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryCmConditionalOrderHistoryResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryCmModifyOrderHistoryResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryCmOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryCurrentCmOpenConditionalOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryCurrentCmOpenOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryCurrentMarginOpenOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryCurrentUmOpenConditionalOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryCurrentUmOpenOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryMarginAccountOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryMarginAccountsAllOcoResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryMarginAccountsOcoResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryMarginAccountsOpenOcoResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryUmConditionalOrderHistoryResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryUmModifyOrderHistoryResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryUmOrderResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryUsersCmForceOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryUsersMarginForceOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryUsersUmForceOrdersResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    ToggleBnbBurnOnUmFuturesTradeResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    UmAccountTradeListResponse,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    UmPositionAdlQuantileEstimationResponse,
)


from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    MarginAccountNewOcoSideEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    MarginAccountNewOcoStopLimitTimeInForceEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    MarginAccountNewOcoNewOrderRespTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    MarginAccountNewOcoSideEffectTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    ModifyCmOrderSideEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    ModifyCmOrderPriceMatchEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    ModifyUmOrderSideEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    ModifyUmOrderPriceMatchEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewCmConditionalOrderSideEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewCmConditionalOrderStrategyTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewCmConditionalOrderPositionSideEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewCmConditionalOrderTimeInForceEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewCmConditionalOrderWorkingTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewCmOrderSideEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewCmOrderTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewCmOrderPositionSideEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewCmOrderTimeInForceEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewCmOrderPriceMatchEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewCmOrderNewOrderRespTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewMarginOrderSideEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewMarginOrderTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewMarginOrderNewOrderRespTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewMarginOrderSideEffectTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewMarginOrderTimeInForceEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewMarginOrderSelfTradePreventionModeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmConditionalOrderSideEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmConditionalOrderStrategyTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmConditionalOrderPositionSideEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmConditionalOrderTimeInForceEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmConditionalOrderWorkingTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmConditionalOrderPriceMatchEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmConditionalOrderSelfTradePreventionModeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmOrderSideEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmOrderTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmOrderPositionSideEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmOrderTimeInForceEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmOrderNewOrderRespTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmOrderPriceMatchEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    NewUmOrderSelfTradePreventionModeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryUsersCmForceOrdersAutoCloseTypeEnum,
)
from binance_sdk_derivatives_trading_portfolio_margin.rest_api.models import (
    QueryUsersUmForceOrdersAutoCloseTypeEnum,
)


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_cancel_all_cm_open_conditional_orders_success(self, mock_get_signature):
        """Test cancel_all_cm_open_conditional_orders() successfully with required parameters only."""

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

        expected_response = {
            "code": "200",
            "msg": "The operation of cancel all conditional open order is done.",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_all_cm_open_conditional_orders(**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 "/papi/v1/cm/conditional/allOpenOrders" 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(CancelAllCmOpenConditionalOrdersResponse)

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

        assert response.data() == expected

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

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

        expected_response = {
            "code": "200",
            "msg": "The operation of cancel all conditional open order is done.",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_all_cm_open_conditional_orders(**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 "/papi/v1/cm/conditional/allOpenOrders" 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(CancelAllCmOpenConditionalOrdersResponse)

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

        assert response.data() == expected

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

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

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

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

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

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

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

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

        expected_response = {
            "code": 200,
            "msg": "The operation of cancel all open order is done.",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_all_cm_open_orders(**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 "/papi/v1/cm/allOpenOrders" 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(CancelAllCmOpenOrdersResponse)

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

        assert response.data() == expected

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

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

        expected_response = {
            "code": 200,
            "msg": "The operation of cancel all open order is done.",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_all_cm_open_orders(**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 "/papi/v1/cm/allOpenOrders" 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(CancelAllCmOpenOrdersResponse)

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

        assert response.data() == expected

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

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

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

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

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

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

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

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

        expected_response = {
            "code": "200",
            "msg": "The operation of cancel all conditional open order is done.",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_all_um_open_conditional_orders(**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 "/papi/v1/um/conditional/allOpenOrders" 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(CancelAllUmOpenConditionalOrdersResponse)

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

        assert response.data() == expected

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

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

        expected_response = {
            "code": "200",
            "msg": "The operation of cancel all conditional open order is done.",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_all_um_open_conditional_orders(**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 "/papi/v1/um/conditional/allOpenOrders" 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(CancelAllUmOpenConditionalOrdersResponse)

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

        assert response.data() == expected

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

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

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

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

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

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

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

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

        expected_response = {
            "code": 200,
            "msg": "The operation of cancel all open order is done.",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_all_um_open_orders(**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 "/papi/v1/um/allOpenOrders" 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(CancelAllUmOpenOrdersResponse)

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

        assert response.data() == expected

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

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

        expected_response = {
            "code": 200,
            "msg": "The operation of cancel all open order is done.",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_all_um_open_orders(**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 "/papi/v1/um/allOpenOrders" 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(CancelAllUmOpenOrdersResponse)

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

        assert response.data() == expected

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

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

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

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

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

