"""
Binance Derivatives Trading COIN Futures REST API

OpenAPI Specification for the Binance Derivatives Trading COIN Futures 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_coin_futures.rest_api.api import AccountApi
from binance_sdk_derivatives_trading_coin_futures.rest_api.models import (
    AccountInformationResponse,
)
from binance_sdk_derivatives_trading_coin_futures.rest_api.models import (
    FuturesAccountBalanceResponse,
)
from binance_sdk_derivatives_trading_coin_futures.rest_api.models import (
    GetCurrentPositionModeResponse,
)
from binance_sdk_derivatives_trading_coin_futures.rest_api.models import (
    GetDownloadIdForFuturesOrderHistoryResponse,
)
from binance_sdk_derivatives_trading_coin_futures.rest_api.models import (
    GetDownloadIdForFuturesTradeHistoryResponse,
)
from binance_sdk_derivatives_trading_coin_futures.rest_api.models import (
    GetDownloadIdForFuturesTransactionHistoryResponse,
)
from binance_sdk_derivatives_trading_coin_futures.rest_api.models import (
    GetFuturesOrderHistoryDownloadLinkByIdResponse,
)
from binance_sdk_derivatives_trading_coin_futures.rest_api.models import (
    GetFuturesTradeDownloadLinkByIdResponse,
)
from binance_sdk_derivatives_trading_coin_futures.rest_api.models import (
    GetFuturesTransactionHistoryDownloadLinkByIdResponse,
)
from binance_sdk_derivatives_trading_coin_futures.rest_api.models import (
    GetIncomeHistoryResponse,
)
from binance_sdk_derivatives_trading_coin_futures.rest_api.models import (
    NotionalBracketForPairResponse,
)
from binance_sdk_derivatives_trading_coin_futures.rest_api.models import (
    NotionalBracketForSymbolResponse,
)
from binance_sdk_derivatives_trading_coin_futures.rest_api.models import (
    UserCommissionRateResponse,
)


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

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

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

        self.mock_session.request.return_value = mock_response

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

        expected_response = {
            "assets": [
                {
                    "asset": "BTC",
                    "walletBalance": "0.00241969",
                    "unrealizedProfit": "0.00000000",
                    "marginBalance": "0.00241969",
                    "maintMargin": "0.00000000",
                    "initialMargin": "0.00000000",
                    "positionInitialMargin": "0.00000000",
                    "openOrderInitialMargin": "0.00000000",
                    "maxWithdrawAmount": "0.00241969",
                    "crossWalletBalance": "0.00241969",
                    "crossUnPnl": "0.00000000",
                    "availableBalance": "0.00241969",
                    "updateTime": 1625474304765,
                }
            ],
            "positions": [
                {
                    "symbol": "BTCUSD_201225",
                    "positionAmt": "0",
                    "initialMargin": "0",
                    "maintMargin": "0",
                    "unrealizedProfit": "0.00000000",
                    "positionInitialMargin": "0",
                    "openOrderInitialMargin": "0",
                    "leverage": "125",
                    "isolated": False,
                    "positionSide": "BOTH",
                    "entryPrice": "0.0",
                    "breakEvenPrice": "0.0",
                    "maxQty": "50",
                    "updateTime": 0,
                },
                {
                    "symbol": "BTCUSD_201225",
                    "positionAmt": "0",
                    "initialMargin": "0",
                    "maintMargin": "0",
                    "unrealizedProfit": "0.00000000",
                    "positionInitialMargin": "0",
                    "openOrderInitialMargin": "0",
                    "leverage": "125",
                    "isolated": False,
                    "positionSide": "LONG",
                    "entryPrice": "0.0",
                    "breakEvenPrice": "0.0",
                    "maxQty": "50",
                    "updateTime": 0,
                },
                {
                    "symbol": "BTCUSD_201225",
                    "positionAmt": "0",
                    "initialMargin": "0",
                    "maintMargin": "0",
                    "unrealizedProfit": "0.00000000",
                    "positionInitialMargin": "0",
                    "openOrderInitialMargin": "0",
                    "leverage": "125",
                    "isolated": False,
                    "positionSide": "SHORT",
                    "entryPrice": "0.0",
                    "breakEvenPrice": "0.0",
                    "maxQty": "50",
                    "notionalValue": "0",
                    "updateTime": 1627026881327,
                },
            ],
            "canDeposit": True,
            "canTrade": True,
            "canWithdraw": True,
            "feeTier": 2,
            "updateTime": 0,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.account_information()

        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 "/dapi/v1/account" 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(AccountInformationResponse)

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

        assert response.data() == expected

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

        params = {"recv_window": 5000}

        expected_response = {
            "assets": [
                {
                    "asset": "BTC",
                    "walletBalance": "0.00241969",
                    "unrealizedProfit": "0.00000000",
                    "marginBalance": "0.00241969",
                    "maintMargin": "0.00000000",
                    "initialMargin": "0.00000000",
                    "positionInitialMargin": "0.00000000",
                    "openOrderInitialMargin": "0.00000000",
                    "maxWithdrawAmount": "0.00241969",
                    "crossWalletBalance": "0.00241969",
                    "crossUnPnl": "0.00000000",
                    "availableBalance": "0.00241969",
                    "updateTime": 1625474304765,
                }
            ],
            "positions": [
                {
                    "symbol": "BTCUSD_201225",
                    "positionAmt": "0",
                    "initialMargin": "0",
                    "maintMargin": "0",
                    "unrealizedProfit": "0.00000000",
                    "positionInitialMargin": "0",
                    "openOrderInitialMargin": "0",
                    "leverage": "125",
                    "isolated": False,
                    "positionSide": "BOTH",
                    "entryPrice": "0.0",
                    "breakEvenPrice": "0.0",
                    "maxQty": "50",
                    "updateTime": 0,
                },
                {
                    "symbol": "BTCUSD_201225",
                    "positionAmt": "0",
                    "initialMargin": "0",
                    "maintMargin": "0",
                    "unrealizedProfit": "0.00000000",
                    "positionInitialMargin": "0",
                    "openOrderInitialMargin": "0",
                    "leverage": "125",
                    "isolated": False,
                    "positionSide": "LONG",
                    "entryPrice": "0.0",
                    "breakEvenPrice": "0.0",
                    "maxQty": "50",
                    "updateTime": 0,
                },
                {
                    "symbol": "BTCUSD_201225",
                    "positionAmt": "0",
                    "initialMargin": "0",
                    "maintMargin": "0",
                    "unrealizedProfit": "0.00000000",
                    "positionInitialMargin": "0",
                    "openOrderInitialMargin": "0",
                    "leverage": "125",
                    "isolated": False,
                    "positionSide": "SHORT",
                    "entryPrice": "0.0",
                    "breakEvenPrice": "0.0",
                    "maxQty": "50",
                    "notionalValue": "0",
                    "updateTime": 1627026881327,
                },
            ],
            "canDeposit": True,
            "canTrade": True,
            "canWithdraw": True,
            "feeTier": 2,
            "updateTime": 0,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.account_information(**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 "/dapi/v1/account" 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(AccountInformationResponse)

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

        assert response.data() == expected

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

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

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

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

        expected_response = [
            {
                "accountAlias": "SgsR",
                "asset": "BTC",
                "balance": "0.00250000",
                "withdrawAvailable": "0.00250000",
                "crossWalletBalance": "0.00241969",
                "crossUnPnl": "0.00000000",
                "availableBalance": "0.00241969",
                "updateTime": 1592468353979,
            }
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.futures_account_balance()

        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 "/dapi/v1/balance" 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(FuturesAccountBalanceResponse)

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

        assert response.data() == expected

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

        params = {"recv_window": 5000}

        expected_response = [
            {
                "accountAlias": "SgsR",
                "asset": "BTC",
                "balance": "0.00250000",
                "withdrawAvailable": "0.00250000",
                "crossWalletBalance": "0.00241969",
                "crossUnPnl": "0.00000000",
                "availableBalance": "0.00241969",
                "updateTime": 1592468353979,
            }
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.futures_account_balance(**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 "/dapi/v1/balance" 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(FuturesAccountBalanceResponse)

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

        assert response.data() == expected

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

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

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

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

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

        response = self.client.get_current_position_mode()

        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 "/dapi/v1/positionSide/dual" 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(GetCurrentPositionModeResponse)

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

        assert response.data() == expected

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

        params = {"recv_window": 5000}

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

        response = self.client.get_current_position_mode(**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 "/dapi/v1/positionSide/dual" 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(GetCurrentPositionModeResponse)

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

        assert response.data() == expected

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

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

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

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

        params = {
            "start_time": 1623319461670,
            "end_time": 1641782889000,
        }

        expected_response = {
            "avgCostTimestampOfLast30d": 7241837,
            "downloadId": "546975389218332672",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_download_id_for_futures_order_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 "/dapi/v1/order/asyn" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"
        assert normalized["startTime"] == 1623319461670
        assert normalized["endTime"] == 1641782889000

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

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

        assert response.data() == expected

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

        params = {
            "start_time": 1623319461670,
            "end_time": 1641782889000,
            "recv_window": 5000,
        }

        expected_response = {
            "avgCostTimestampOfLast30d": 7241837,
            "downloadId": "546975389218332672",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_download_id_for_futures_order_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 "/dapi/v1/order/asyn" 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(GetDownloadIdForFuturesOrderHistoryResponse)

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

        assert response.data() == expected

    def test_get_download_id_for_futures_order_history_missing_required_param_start_time(
        self,
    ):
        """Test that get_download_id_for_futures_order_history() raises RequiredError when 'start_time' is missing."""
        params = {
            "start_time": 1623319461670,
            "end_time": 1641782889000,
        }
        params["start_time"] = None

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

    def test_get_download_id_for_futures_order_history_missing_required_param_end_time(
        self,
    ):
        """Test that get_download_id_for_futures_order_history() raises RequiredError when 'end_time' is missing."""
        params = {
            "start_time": 1623319461670,
            "end_time": 1641782889000,
        }
        params["end_time"] = None

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

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

        params = {
            "start_time": 1623319461670,
            "end_time": 1641782889000,
        }

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

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

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

        params = {
            "start_time": 1623319461670,
            "end_time": 1641782889000,
        }

        expected_response = {
            "avgCostTimestampOfLast30d": 7241837,
            "downloadId": "546975389218332672",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_download_id_for_futures_trade_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 "/dapi/v1/trade/asyn" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"
        assert normalized["startTime"] == 1623319461670
        assert normalized["endTime"] == 1641782889000

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

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

        assert response.data() == expected

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

        params = {
            "start_time": 1623319461670,
            "end_time": 1641782889000,
            "recv_window": 5000,
        }

        expected_response = {
            "avgCostTimestampOfLast30d": 7241837,
            "downloadId": "546975389218332672",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_download_id_for_futures_trade_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 "/dapi/v1/trade/asyn" 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(GetDownloadIdForFuturesTradeHistoryResponse)

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

        assert response.data() == expected

    def test_get_download_id_for_futures_trade_history_missing_required_param_start_time(
        self,
    ):
        """Test that get_download_id_for_futures_trade_history() raises RequiredError when 'start_time' is missing."""
        params = {
            "start_time": 1623319461670,
            "end_time": 1641782889000,
        }
        params["start_time"] = None

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

    def test_get_download_id_for_futures_trade_history_missing_required_param_end_time(
        self,
    ):
        """Test that get_download_id_for_futures_trade_history() raises RequiredError when 'end_time' is missing."""
        params = {
            "start_time": 1623319461670,
            "end_time": 1641782889000,
        }
        params["end_time"] = None

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

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

        params = {
            "start_time": 1623319461670,
            "end_time": 1641782889000,
        }

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

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

    @patch("binance_common.utils.get_signature")
