"""
Binance Derivatives Trading Options REST API

OpenAPI Specification for the Binance Derivatives Trading Options 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_options.rest_api.api import TradeApi
from binance_sdk_derivatives_trading_options.rest_api.models import (
    AccountTradeListResponse,
)
from binance_sdk_derivatives_trading_options.rest_api.models import (
    CancelAllOptionOrdersByUnderlyingResponse,
)
from binance_sdk_derivatives_trading_options.rest_api.models import (
    CancelAllOptionOrdersOnSpecificSymbolResponse,
)
from binance_sdk_derivatives_trading_options.rest_api.models import (
    CancelMultipleOptionOrdersResponse,
)
from binance_sdk_derivatives_trading_options.rest_api.models import (
    CancelOptionOrderResponse,
)
from binance_sdk_derivatives_trading_options.rest_api.models import NewOrderResponse
from binance_sdk_derivatives_trading_options.rest_api.models import (
    OptionPositionInformationResponse,
)
from binance_sdk_derivatives_trading_options.rest_api.models import (
    PlaceMultipleOrdersResponse,
)
from binance_sdk_derivatives_trading_options.rest_api.models import (
    QueryCurrentOpenOptionOrdersResponse,
)
from binance_sdk_derivatives_trading_options.rest_api.models import (
    QueryOptionOrderHistoryResponse,
)
from binance_sdk_derivatives_trading_options.rest_api.models import (
    QuerySingleOrderResponse,
)
from binance_sdk_derivatives_trading_options.rest_api.models import (
    UserExerciseRecordResponse,
)


from binance_sdk_derivatives_trading_options.rest_api.models import NewOrderSideEnum
from binance_sdk_derivatives_trading_options.rest_api.models import NewOrderTypeEnum
from binance_sdk_derivatives_trading_options.rest_api.models import (
    NewOrderTimeInForceEnum,
)
from binance_sdk_derivatives_trading_options.rest_api.models import (
    NewOrderNewOrderRespTypeEnum,
)

from binance_sdk_derivatives_trading_options.rest_api.models import (
    PlaceMultipleOrdersOrdersParameterInner,
)


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

        expected_response = [
            {
                "id": 4611875134427365000,
                "tradeId": 239,
                "orderId": 4611875134427365000,
                "symbol": "BTC-200730-9000-C",
                "price": "100",
                "quantity": "1",
                "fee": "0",
                "realizedProfit": "0.00000000",
                "side": "BUY",
                "type": "LIMIT",
                "volatility": "0.9",
                "liquidity": "TAKER",
                "quoteAsset": "USDT",
                "time": 1592465880683,
                "priceScale": 2,
                "quantityScale": 2,
                "optionSide": "CALL",
            }
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.account_trade_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 "/eapi/v1/userTrades" 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(AccountTradeListResponse)

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

        assert response.data() == expected

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

        params = {
            "symbol": "symbol_example",
            "from_id": 1,
            "start_time": 1623319461670,
            "end_time": 1641782889000,
            "limit": 100,
            "recv_window": 5000,
        }

        expected_response = [
            {
                "id": 4611875134427365000,
                "tradeId": 239,
                "orderId": 4611875134427365000,
                "symbol": "BTC-200730-9000-C",
                "price": "100",
                "quantity": "1",
                "fee": "0",
                "realizedProfit": "0.00000000",
                "side": "BUY",
                "type": "LIMIT",
                "volatility": "0.9",
                "liquidity": "TAKER",
                "quoteAsset": "USDT",
                "time": 1592465880683,
                "priceScale": 2,
                "quantityScale": 2,
                "optionSide": "CALL",
            }
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.account_trade_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 "/eapi/v1/userTrades" 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(AccountTradeListResponse)

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

        assert response.data() == expected

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

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

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

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

        params = {
            "underlying": "underlying_example",
        }

        expected_response = {"code": 0, "msg": "success", "data": 0}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_all_option_orders_by_underlying(**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 "/eapi/v1/allOpenOrdersByUnderlying" in request_kwargs["url"]
        assert request_kwargs["method"] == "DELETE"
        assert normalized["underlying"] == "underlying_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(CancelAllOptionOrdersByUnderlyingResponse)

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

        assert response.data() == expected

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

        params = {"underlying": "underlying_example", "recv_window": 5000}

        expected_response = {"code": 0, "msg": "success", "data": 0}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_all_option_orders_by_underlying(**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 "/eapi/v1/allOpenOrdersByUnderlying" 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(CancelAllOptionOrdersByUnderlyingResponse)

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

        assert response.data() == expected

    def test_cancel_all_option_orders_by_underlying_missing_required_param_underlying(
        self,
    ):
        """Test that cancel_all_option_orders_by_underlying() raises RequiredError when 'underlying' is missing."""
        params = {
            "underlying": "underlying_example",
        }
        params["underlying"] = None

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

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

        params = {
            "underlying": "underlying_example",
        }

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

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

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

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

        expected_response = {"code": 0, "msg": "success"}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_all_option_orders_on_specific_symbol(**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 "/eapi/v1/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(CancelAllOptionOrdersOnSpecificSymbolResponse)

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

        assert response.data() == expected

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

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

        expected_response = {"code": 0, "msg": "success"}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_all_option_orders_on_specific_symbol(**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 "/eapi/v1/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(CancelAllOptionOrdersOnSpecificSymbolResponse)

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

        assert response.data() == expected

    def test_cancel_all_option_orders_on_specific_symbol_missing_required_param_symbol(
        self,
    ):
        """Test that cancel_all_option_orders_on_specific_symbol() 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_option_orders_on_specific_symbol(**params)

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

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

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

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

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

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

        expected_response = [
            {
                "orderId": 4611875134427365000,
                "symbol": "BTC-200730-9000-C",
                "price": "100",
                "quantity": "1",
                "executedQty": "0",
                "fee": 0,
                "side": "BUY",
                "type": "LIMIT",
                "timeInForce": "GTC",
                "createTime": 1592465880683,
                "status": "ACCEPTED",
                "avgPrice": "0",
                "reduceOnly": False,
                "clientOrderId": "",
                "updateTime": 1566818724722,
            }
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_multiple_option_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 "/eapi/v1/batchOrders" 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(CancelMultipleOptionOrdersResponse)

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

        assert response.data() == expected

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

        params = {
            "symbol": "symbol_example",
            "order_ids": [4611875134427365000],
            "client_order_ids": ["my_id_1"],
            "recv_window": 5000,
        }

        expected_response = [
            {
                "orderId": 4611875134427365000,
                "symbol": "BTC-200730-9000-C",
                "price": "100",
                "quantity": "1",
                "executedQty": "0",
                "fee": 0,
                "side": "BUY",
                "type": "LIMIT",
                "timeInForce": "GTC",
                "createTime": 1592465880683,
                "status": "ACCEPTED",
                "avgPrice": "0",
                "reduceOnly": False,
                "clientOrderId": "",
                "updateTime": 1566818724722,
            }
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_multiple_option_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 "/eapi/v1/batchOrders" 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(CancelMultipleOptionOrdersResponse)

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

        assert response.data() == expected

    def test_cancel_multiple_option_orders_missing_required_param_symbol(self):
        """Test that cancel_multiple_option_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_multiple_option_orders(**params)

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

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

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

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

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

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

        expected_response = {
            "orderId": 4611875134427365000,
            "symbol": "BTC-200730-9000-C",
            "price": "100",
            "quantity": "1",
            "executedQty": "0",
            "fee": "0",
            "side": "BUY",
            "type": "LIMIT",
            "timeInForce": "GTC",
            "reduceOnly": False,
            "postOnly": False,
            "createDate": 1592465880683,
            "updateTime": 1566818724722,
            "status": "ACCEPTED",
            "avgPrice": "0",
            "source": "API",
            "clientOrderId": "",
            "priceScale": 4,
            "quantityScale": 4,
            "optionSide": "CALL",
            "quoteAsset": "USDT",
            "mmp": False,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_option_order(**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 "/eapi/v1/order" 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(CancelOptionOrderResponse)

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

        assert response.data() == expected

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

        params = {
            "symbol": "symbol_example",
            "order_id": 1,
            "client_order_id": "1",
            "recv_window": 5000,
        }

        expected_response = {
            "orderId": 4611875134427365000,
            "symbol": "BTC-200730-9000-C",
            "price": "100",
            "quantity": "1",
            "executedQty": "0",
            "fee": "0",
            "side": "BUY",
            "type": "LIMIT",
            "timeInForce": "GTC",
            "reduceOnly": False,
            "postOnly": False,
            "createDate": 1592465880683,
            "updateTime": 1566818724722,
            "status": "ACCEPTED",
            "avgPrice": "0",
            "source": "API",
            "clientOrderId": "",
            "priceScale": 4,
            "quantityScale": 4,
            "optionSide": "CALL",
            "quoteAsset": "USDT",
            "mmp": False,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.cancel_option_order(**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 "/eapi/v1/order" 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(CancelOptionOrderResponse)

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

        assert response.data() == expected

    def test_cancel_option_order_missing_required_param_symbol(self):
        """Test that cancel_option_order() 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_option_order(**params)

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

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

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

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

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

        params = {
            "symbol": "symbol_example",
            "side": NewOrderSideEnum["BUY"].value,
            "type": NewOrderTypeEnum["LIMIT"].value,
            "quantity": 1.0,
        }

        expected_response = {
            "orderId": 4611875134427365000,
            "symbol": "BTC-200730-9000-C",
            "price": "100",
            "quantity": "1",
            "side": "BUY",
            "type": "LIMIT",
            "createDate": 1592465880683,
            "reduceOnly": False,
            "postOnly": False,
            "mmp": False,
            "executedQty": "0",
            "fee": "0",
            "timeInForce": "GTC",
            "createTime": 1592465880683,
            "updateTime": 1566818724722,
            "status": "ACCEPTED",
            "avgPrice": "0",
            "clientOrderId": "",
            "priceScale": 2,
            "quantityScale": 2,
            "optionSide": "CALL",
            "quoteAsset": "USDT",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.new_order(**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 "/eapi/v1/order" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"
        assert normalized["symbol"] == "symbol_example"
        assert normalized["side"] == NewOrderSideEnum["BUY"].value
        assert normalized["type"] == NewOrderTypeEnum["LIMIT"].value
