"""
Binance Simple Earn REST API

OpenAPI Specification for the Binance Simple Earn 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_simple_earn.rest_api.api import FlexibleLockedApi
from binance_sdk_simple_earn.rest_api.models import GetCollateralRecordResponse
from binance_sdk_simple_earn.rest_api.models import GetFlexiblePersonalLeftQuotaResponse
from binance_sdk_simple_earn.rest_api.models import GetFlexibleProductPositionResponse
from binance_sdk_simple_earn.rest_api.models import GetFlexibleRedemptionRecordResponse
from binance_sdk_simple_earn.rest_api.models import GetFlexibleRewardsHistoryResponse
from binance_sdk_simple_earn.rest_api.models import (
    GetFlexibleSubscriptionPreviewResponse,
)
from binance_sdk_simple_earn.rest_api.models import (
    GetFlexibleSubscriptionRecordResponse,
)
from binance_sdk_simple_earn.rest_api.models import GetLockedPersonalLeftQuotaResponse
from binance_sdk_simple_earn.rest_api.models import GetLockedProductPositionResponse
from binance_sdk_simple_earn.rest_api.models import GetLockedRedemptionRecordResponse
from binance_sdk_simple_earn.rest_api.models import GetLockedRewardsHistoryResponse
from binance_sdk_simple_earn.rest_api.models import GetLockedSubscriptionPreviewResponse
from binance_sdk_simple_earn.rest_api.models import GetLockedSubscriptionRecordResponse
from binance_sdk_simple_earn.rest_api.models import GetRateHistoryResponse
from binance_sdk_simple_earn.rest_api.models import (
    GetSimpleEarnFlexibleProductListResponse,
)
from binance_sdk_simple_earn.rest_api.models import (
    GetSimpleEarnLockedProductListResponse,
)
from binance_sdk_simple_earn.rest_api.models import RedeemFlexibleProductResponse
from binance_sdk_simple_earn.rest_api.models import RedeemLockedProductResponse
from binance_sdk_simple_earn.rest_api.models import SetFlexibleAutoSubscribeResponse
from binance_sdk_simple_earn.rest_api.models import SetLockedAutoSubscribeResponse
from binance_sdk_simple_earn.rest_api.models import SetLockedProductRedeemOptionResponse
from binance_sdk_simple_earn.rest_api.models import SimpleAccountResponse
from binance_sdk_simple_earn.rest_api.models import SubscribeFlexibleProductResponse
from binance_sdk_simple_earn.rest_api.models import SubscribeLockedProductResponse


class TestFlexibleLockedApi:
    @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 = FlexibleLockedApi(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_collateral_record_success(self, mock_get_signature):
        """Test get_collateral_record() successfully with required parameters only."""

        expected_response = {
            "rows": [
                {
                    "amount": "100.00000000",
                    "productId": "BUSD001",
                    "asset": "USDT",
                    "createTime": 1575018510000,
                    "type": "REPAY",
                    "productName": "USDT",
                    "orderId": 26055,
                }
            ],
            "total": "1",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_collateral_record()

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

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

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert (
            "/sapi/v1/simple-earn/flexible/history/collateralRecord"
            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(GetCollateralRecordResponse)

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

        assert response.data() == expected

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

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

        expected_response = {
            "rows": [
                {
                    "amount": "100.00000000",
                    "productId": "BUSD001",
                    "asset": "USDT",
                    "createTime": 1575018510000,
                    "type": "REPAY",
                    "productName": "USDT",
                    "orderId": 26055,
                }
            ],
            "total": "1",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

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

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

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert (
            "/sapi/v1/simple-earn/flexible/history/collateralRecord"
            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(GetCollateralRecordResponse)

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

        assert response.data() == expected

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

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

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

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

        params = {
            "product_id": "1",
        }

        expected_response = {"leftPersonalQuota": "1000"}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_flexible_personal_left_quota(**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/simple-earn/flexible/personalLeftQuota" in request_kwargs["url"]
        )
        assert request_kwargs["method"] == "GET"
        assert normalized["productId"] == "1"

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

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

        assert response.data() == expected

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

        params = {"product_id": "1", "recv_window": 5000}

        expected_response = {"leftPersonalQuota": "1000"}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_flexible_personal_left_quota(**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/simple-earn/flexible/personalLeftQuota" 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(GetFlexiblePersonalLeftQuotaResponse)

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

        assert response.data() == expected

    def test_get_flexible_personal_left_quota_missing_required_param_product_id(self):
        """Test that get_flexible_personal_left_quota() raises RequiredError when 'product_id' is missing."""
        params = {
            "product_id": "1",
        }
        params["product_id"] = None

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

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

        params = {
            "product_id": "1",
        }

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

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

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

        expected_response = {
            "rows": [
                {
                    "totalAmount": "75.46000000",
                    "tierAnnualPercentageRate": {"0-5BTC": 0.05, "5-10BTC": 0.03},
                    "latestAnnualPercentageRate": "0.02599895",
                    "yesterdayAirdropPercentageRate": "0.02599895",
                    "asset": "USDT",
                    "airDropAsset": "BETH",
                    "canRedeem": True,
                    "collateralAmount": "232.23123213",
                    "productId": "USDT001",
                    "yesterdayRealTimeRewards": "0.10293829",
                    "cumulativeBonusRewards": "0.22759183",
                    "cumulativeRealTimeRewards": "0.22759183",
                    "cumulativeTotalRewards": "0.45459183",
                    "autoSubscribe": True,
                }
            ],
            "total": 1,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_flexible_product_position()

        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/simple-earn/flexible/position" 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(GetFlexibleProductPositionResponse)

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

        assert response.data() == expected

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

        params = {
            "asset": "asset_example",
            "product_id": "1",
            "current": 1,
            "size": 10,
            "recv_window": 5000,
        }

        expected_response = {
            "rows": [
                {
                    "totalAmount": "75.46000000",
                    "tierAnnualPercentageRate": {"0-5BTC": 0.05, "5-10BTC": 0.03},
                    "latestAnnualPercentageRate": "0.02599895",
                    "yesterdayAirdropPercentageRate": "0.02599895",
                    "asset": "USDT",
                    "airDropAsset": "BETH",
                    "canRedeem": True,
                    "collateralAmount": "232.23123213",
                    "productId": "USDT001",
                    "yesterdayRealTimeRewards": "0.10293829",
                    "cumulativeBonusRewards": "0.22759183",
                    "cumulativeRealTimeRewards": "0.22759183",
                    "cumulativeTotalRewards": "0.45459183",
                    "autoSubscribe": True,
                }
            ],
            "total": 1,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_flexible_product_position(**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/simple-earn/flexible/position" 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(GetFlexibleProductPositionResponse)

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

        assert response.data() == expected

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

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

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

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

        expected_response = {
            "rows": [
                {
                    "amount": "10.54000000",
                    "asset": "USDT",
                    "time": 1577257222000,
                    "projectId": "USDT001",
                    "redeemId": 40607,
                    "destAccount": "SPOT",
                    "status": "PAID",
                }
            ],
            "total": 1,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_flexible_redemption_record()

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

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

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert (
            "/sapi/v1/simple-earn/flexible/history/redemptionRecord"
            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(GetFlexibleRedemptionRecordResponse)

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

        assert response.data() == expected

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

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

        expected_response = {
            "rows": [
                {
                    "amount": "10.54000000",
                    "asset": "USDT",
                    "time": 1577257222000,
                    "projectId": "USDT001",
                    "redeemId": 40607,
                    "destAccount": "SPOT",
                    "status": "PAID",
                }
            ],
            "total": 1,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

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

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

        assert "url" in request_kwargs
        assert "signature" in parse_qs(request_kwargs["params"])
        assert (
            "/sapi/v1/simple-earn/flexible/history/redemptionRecord"
            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(GetFlexibleRedemptionRecordResponse)

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

        assert response.data() == expected

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

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

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

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

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

        expected_response = {
            "rows": [
                {
                    "asset": "BUSD",
                    "rewards": "0.00006408",
                    "projectId": "USDT001",
                    "type": "BONUS",
                    "time": 1577233578000,
                },
                {
                    "asset": "USDT",
                    "rewards": "0.00687654",
                    "projectId": "USDT001",
                    "type": "REALTIME",
                    "time": 1577233562000,
                },
            ],
            "total": 2,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_flexible_rewards_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/simple-earn/flexible/history/rewardsRecord"
            in request_kwargs["url"]
        )
        assert request_kwargs["method"] == "GET"
        assert normalized["type"] == "s"

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

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

        assert response.data() == expected

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

        params = {
            "type": "s",
            "product_id": "1",
            "asset": "asset_example",
            "start_time": 1623319461670,
            "end_time": 1641782889000,
            "current": 1,
            "size": 10,
            "recv_window": 5000,
        }

        expected_response = {
            "rows": [
                {
                    "asset": "BUSD",
                    "rewards": "0.00006408",
                    "projectId": "USDT001",
                    "type": "BONUS",
                    "time": 1577233578000,
                },
                {
                    "asset": "USDT",
                    "rewards": "0.00687654",
                    "projectId": "USDT001",
                    "type": "REALTIME",
                    "time": 1577233562000,
                },
            ],
            "total": 2,
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_flexible_rewards_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/simple-earn/flexible/history/rewardsRecord"
            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(GetFlexibleRewardsHistoryResponse)

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

        assert response.data() == expected

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

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

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

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

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

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

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

        params = {
            "product_id": "1",
            "amount": 1.0,
        }

        expected_response = {
            "totalAmount": "1232.32230982",
            "rewardAsset": "BUSD",
            "airDropAsset": "BETH",
            "estDailyBonusRewards": "0.22759183",
            "estDailyRealTimeRewards": "0.22759183",
            "estDailyAirdropRewards": "0.22759183",
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_flexible_subscription_preview(**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/simple-earn/flexible/subscriptionPreview" in request_kwargs["url"]
        )
        assert request_kwargs["method"] == "GET"
        assert normalized["productId"] == "1"
        assert normalized["amount"] == 1.0

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

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

        assert response.data() == expected

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

        params = {"product_id": "1", "amount": 1.0, "recv_window": 5000}

        expected_response = {
