"""
Binance Margin Trading REST API

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

Do not edit the class manually.
"""

import json
import pytest
import requests

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

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

from binance_sdk_margin_trading.rest_api.api import BorrowRepayApi
from binance_sdk_margin_trading.rest_api.models import (
    GetFutureHourlyInterestRateResponse,
)
from binance_sdk_margin_trading.rest_api.models import GetInterestHistoryResponse
from binance_sdk_margin_trading.rest_api.models import MarginAccountBorrowRepayResponse
from binance_sdk_margin_trading.rest_api.models import (
    QueryBorrowRepayRecordsInMarginAccountResponse,
)
from binance_sdk_margin_trading.rest_api.models import (
    QueryMarginInterestRateHistoryResponse,
)
from binance_sdk_margin_trading.rest_api.models import QueryMaxBorrowResponse


class TestBorrowRepayApi:
    @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 = BorrowRepayApi(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_get_future_hourly_interest_rate_success(self, mock_get_signature):
        """Test get_future_hourly_interest_rate() successfully with required parameters only."""

        params = {"assets": "assets_example", "is_isolated": False}

        expected_response = [
            {"asset": "BTC", "nextHourlyInterestRate": "0.00000571"},
            {"asset": "ETH", "nextHourlyInterestRate": "0.00000578"},
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

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

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

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

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/next-hourly-interest-rate" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"
        assert normalized["assets"] == "assets_example"
        assert normalized["isIsolated"] is False

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

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

        assert response.data() == expected

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

        params = {"assets": "assets_example", "is_isolated": False}

        expected_response = [
            {"asset": "BTC", "nextHourlyInterestRate": "0.00000571"},
            {"asset": "ETH", "nextHourlyInterestRate": "0.00000578"},
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

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

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

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/next-hourly-interest-rate" 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(GetFutureHourlyInterestRateResponse)

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

        assert response.data() == expected

    def test_get_future_hourly_interest_rate_missing_required_param_assets(self):
        """Test that get_future_hourly_interest_rate() raises RequiredError when 'assets' is missing."""
        params = {"assets": "assets_example", "is_isolated": False}
        params["assets"] = None

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

    def test_get_future_hourly_interest_rate_missing_required_param_is_isolated(self):
        """Test that get_future_hourly_interest_rate() raises RequiredError when 'is_isolated' is missing."""
        params = {"assets": "assets_example", "is_isolated": False}
        params["is_isolated"] = None

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

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

        params = {"assets": "assets_example", "is_isolated": False}

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

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

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

        expected_response = {
            "rows": [
                {
                    "txId": 1352286576452864800,
                    "interestAccuredTime": 1672160400000,
                    "asset": "USDT",
                    "rawAsset": "USDT",
                    "principal": "45.3313",
                    "interest": "0.00024995",
                    "interestRate": "0.00013233",
                    "type": "ON_BORROW",
                    "isolatedSymbol": "BNBUSDT",
                }
            ],
            "total": 1,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_interest_history()

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

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

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/interestHistory" 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(GetInterestHistoryResponse)

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

        assert response.data() == expected

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

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

        expected_response = {
            "rows": [
                {
                    "txId": 1352286576452864800,
                    "interestAccuredTime": 1672160400000,
                    "asset": "USDT",
                    "rawAsset": "USDT",
                    "principal": "45.3313",
                    "interest": "0.00024995",
                    "interestRate": "0.00013233",
                    "type": "ON_BORROW",
                    "isolatedSymbol": "BNBUSDT",
                }
            ],
            "total": 1,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

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

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

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/interestHistory" 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(GetInterestHistoryResponse)

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

        assert response.data() == expected

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

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

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

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

        params = {
            "asset": "asset_example",
            "is_isolated": "FALSE",
            "symbol": "symbol_example",
            "amount": "amount_example",
            "type": "type_example",
        }

        expected_response = {"tranId": 100000001}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

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

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

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

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/borrow-repay" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"
        assert normalized["asset"] == "asset_example"
        assert normalized["isIsolated"] == "FALSE"
        assert normalized["symbol"] == "symbol_example"
        assert normalized["amount"] == "amount_example"
        assert normalized["type"] == "type_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(MarginAccountBorrowRepayResponse)

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

        assert response.data() == expected

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

        params = {
            "asset": "asset_example",
            "is_isolated": "FALSE",
            "symbol": "symbol_example",
            "amount": "amount_example",
            "type": "type_example",
            "recv_window": 5000,
        }

        expected_response = {"tranId": 100000001}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

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

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

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

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

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

        assert response.data() == expected

    def test_margin_account_borrow_repay_missing_required_param_asset(self):
        """Test that margin_account_borrow_repay() raises RequiredError when 'asset' is missing."""
        params = {
            "asset": "asset_example",
            "is_isolated": "FALSE",
            "symbol": "symbol_example",
            "amount": "amount_example",
            "type": "type_example",
        }
        params["asset"] = None

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

    def test_margin_account_borrow_repay_missing_required_param_is_isolated(self):
        """Test that margin_account_borrow_repay() raises RequiredError when 'is_isolated' is missing."""
        params = {
            "asset": "asset_example",
            "is_isolated": "FALSE",
            "symbol": "symbol_example",
            "amount": "amount_example",
            "type": "type_example",
        }
        params["is_isolated"] = None

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

    def test_margin_account_borrow_repay_missing_required_param_symbol(self):
        """Test that margin_account_borrow_repay() raises RequiredError when 'symbol' is missing."""
        params = {
            "asset": "asset_example",
            "is_isolated": "FALSE",
            "symbol": "symbol_example",
            "amount": "amount_example",
            "type": "type_example",
        }
        params["symbol"] = None

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

    def test_margin_account_borrow_repay_missing_required_param_amount(self):
        """Test that margin_account_borrow_repay() raises RequiredError when 'amount' is missing."""
        params = {
            "asset": "asset_example",
            "is_isolated": "FALSE",
            "symbol": "symbol_example",
            "amount": "amount_example",
            "type": "type_example",
        }
        params["amount"] = None

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

    def test_margin_account_borrow_repay_missing_required_param_type(self):
        """Test that margin_account_borrow_repay() raises RequiredError when 'type' is missing."""
        params = {
            "asset": "asset_example",
            "is_isolated": "FALSE",
            "symbol": "symbol_example",
            "amount": "amount_example",
            "type": "type_example",
        }
        params["type"] = None

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

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

        params = {
            "asset": "asset_example",
            "is_isolated": "FALSE",
            "symbol": "symbol_example",
            "amount": "amount_example",
            "type": "type_example",
        }

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

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

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

        params = {
            "type": "type_example",
        }

        expected_response = {
            "rows": [
                {
                    "type": "AUTO",
                    "isolatedSymbol": "BNBUSDT",
                    "amount": "14.00000000",
                    "asset": "BNB",
                    "interest": "0.01866667",
                    "principal": "13.98133333",
                    "status": "CONFIRMED",
                    "timestamp": 1563438204000,
                    "txId": 2970933056,
                }
            ],
            "total": 1,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

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

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

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

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/borrow-repay" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"
        assert normalized["type"] == "type_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(QueryBorrowRepayRecordsInMarginAccountResponse)

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

        assert response.data() == expected

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

        params = {
            "type": "type_example",
            "asset": "asset_example",
            "isolated_symbol": "isolated_symbol_example",
            "tx_id": 1,
            "start_time": 1623319461670,
            "end_time": 1641782889000,
            "current": 1,
            "size": 10,
            "recv_window": 5000,
        }

        expected_response = {
            "rows": [
                {
                    "type": "AUTO",
                    "isolatedSymbol": "BNBUSDT",
                    "amount": "14.00000000",
                    "asset": "BNB",
                    "interest": "0.01866667",
                    "principal": "13.98133333",
                    "status": "CONFIRMED",
                    "timestamp": 1563438204000,
                    "txId": 2970933056,
                }
            ],
            "total": 1,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

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

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

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/borrow-repay" 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(QueryBorrowRepayRecordsInMarginAccountResponse)

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

        assert response.data() == expected

    def test_query_borrow_repay_records_in_margin_account_missing_required_param_type(
        self,
    ):
        """Test that query_borrow_repay_records_in_margin_account() raises RequiredError when 'type' is missing."""
        params = {
            "type": "type_example",
        }
        params["type"] = None

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

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

        params = {
            "type": "type_example",
        }

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

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

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

        params = {
            "asset": "asset_example",
        }

        expected_response = [
            {
                "asset": "BTC",
                "dailyInterestRate": "0.00025000",
                "timestamp": 1611544731000,
                "vipLevel": 1,
            },
            {
                "asset": "BTC",
                "dailyInterestRate": "0.00035000",
                "timestamp": 1610248118000,
                "vipLevel": 1,
            },
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

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

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

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

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/interestRateHistory" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"
        assert normalized["asset"] == "asset_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(QueryMarginInterestRateHistoryResponse)

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

        assert response.data() == expected

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

        params = {
            "asset": "asset_example",
            "vip_level": 1,
            "start_time": 1623319461670,
            "end_time": 1641782889000,
            "recv_window": 5000,
        }

        expected_response = [
            {
                "asset": "BTC",
                "dailyInterestRate": "0.00025000",
                "timestamp": 1611544731000,
                "vipLevel": 1,
            },
            {
                "asset": "BTC",
                "dailyInterestRate": "0.00035000",
                "timestamp": 1610248118000,
                "vipLevel": 1,
            },
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

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

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

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert "/sapi/v1/margin/interestRateHistory" 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(QueryMarginInterestRateHistoryResponse)

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

        assert response.data() == expected

    def test_query_margin_interest_rate_history_missing_required_param_asset(self):
        """Test that query_margin_interest_rate_history() raises RequiredError when 'asset' is missing."""
        params = {
            "asset": "asset_example",
        }
        params["asset"] = None

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

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

        params = {
            "asset": "asset_example",
        }

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

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

    @patch("binance_common.utils.get_signature")
    def test_query_max_borrow_success(self, mock_get_signature):
