"""
Binance Sub Account REST API

OpenAPI Specification for the Binance Sub Account 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_sub_account.rest_api.api import AccountManagementApi
from binance_sdk_sub_account.rest_api.models import CreateAVirtualSubAccountResponse
from binance_sdk_sub_account.rest_api.models import EnableFuturesForSubAccountResponse
from binance_sdk_sub_account.rest_api.models import EnableOptionsForSubAccountResponse
from binance_sdk_sub_account.rest_api.models import (
    GetFuturesPositionRiskOfSubAccountResponse,
)
from binance_sdk_sub_account.rest_api.models import (
    GetFuturesPositionRiskOfSubAccountV2Response,
)
from binance_sdk_sub_account.rest_api.models import (
    GetSubAccountsStatusOnMarginOrFuturesResponse,
)
from binance_sdk_sub_account.rest_api.models import QuerySubAccountListResponse
from binance_sdk_sub_account.rest_api.models import (
    QuerySubAccountTransactionStatisticsResponse,
)


class TestAccountManagementApi:
    @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 = AccountManagementApi(
            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_create_a_virtual_sub_account_success(self, mock_get_signature):
        """Test create_a_virtual_sub_account() successfully with required parameters only."""

        params = {
            "sub_account_string": "sub_account_string_example",
        }

        expected_response = {"email": "addsdd_virtual@aasaixwqnoemail.com"}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.create_a_virtual_sub_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/sub-account/virtualSubAccount" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"
        assert normalized["subAccountString"] == "sub_account_string_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(CreateAVirtualSubAccountResponse)

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

        assert response.data() == expected

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

        params = {
            "sub_account_string": "sub_account_string_example",
            "recv_window": 5000,
        }

        expected_response = {"email": "addsdd_virtual@aasaixwqnoemail.com"}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.create_a_virtual_sub_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/sub-account/virtualSubAccount" 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(CreateAVirtualSubAccountResponse)

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

        assert response.data() == expected

    def test_create_a_virtual_sub_account_missing_required_param_sub_account_string(
        self,
    ):
        """Test that create_a_virtual_sub_account() raises RequiredError when 'sub_account_string' is missing."""
        params = {
            "sub_account_string": "sub_account_string_example",
        }
        params["sub_account_string"] = None

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

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

        params = {
            "sub_account_string": "sub_account_string_example",
        }

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

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

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

        params = {
            "email": "sub-account-email@email.com",
        }

        expected_response = {"email": "123@test.com", "isFuturesEnabled": True}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.enable_futures_for_sub_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/sub-account/futures/enable" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"
        assert normalized["email"] == "sub-account-email@email.com"

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

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

        assert response.data() == expected

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

        params = {"email": "sub-account-email@email.com", "recv_window": 5000}

        expected_response = {"email": "123@test.com", "isFuturesEnabled": True}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.enable_futures_for_sub_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/sub-account/futures/enable" 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(EnableFuturesForSubAccountResponse)

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

        assert response.data() == expected

    def test_enable_futures_for_sub_account_missing_required_param_email(self):
        """Test that enable_futures_for_sub_account() raises RequiredError when 'email' is missing."""
        params = {
            "email": "sub-account-email@email.com",
        }
        params["email"] = None

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

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

        params = {
            "email": "sub-account-email@email.com",
        }

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

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

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

        params = {
            "email": "sub-account-email@email.com",
        }

        expected_response = {"email": "123@test.com", "isEOptionsEnabled": True}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.enable_options_for_sub_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/sub-account/eoptions/enable" in request_kwargs["url"]
        assert request_kwargs["method"] == "POST"
        assert normalized["email"] == "sub-account-email@email.com"

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

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

        assert response.data() == expected

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

        params = {"email": "sub-account-email@email.com", "recv_window": 5000}

        expected_response = {"email": "123@test.com", "isEOptionsEnabled": True}
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.enable_options_for_sub_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/sub-account/eoptions/enable" 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(EnableOptionsForSubAccountResponse)

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

        assert response.data() == expected

    def test_enable_options_for_sub_account_missing_required_param_email(self):
        """Test that enable_options_for_sub_account() raises RequiredError when 'email' is missing."""
        params = {
            "email": "sub-account-email@email.com",
        }
        params["email"] = None

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

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

        params = {
            "email": "sub-account-email@email.com",
        }

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

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

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

        params = {
            "email": "sub-account-email@email.com",
        }

        expected_response = [
            {
                "entryPrice": "9975.12000",
                "leverage": "50",
                "maxNotional": "1000000",
                "liquidationPrice": "7963.54",
                "markPrice": "9973.50770517",
                "positionAmount": "0.010",
                "symbol": "BTCUSDT",
                "unrealizedProfit": "-0.01612295",
            }
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_futures_position_risk_of_sub_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/sub-account/futures/positionRisk" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"
        assert normalized["email"] == "sub-account-email@email.com"

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

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

        assert response.data() == expected

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

        params = {"email": "sub-account-email@email.com", "recv_window": 5000}

        expected_response = [
            {
                "entryPrice": "9975.12000",
                "leverage": "50",
                "maxNotional": "1000000",
                "liquidationPrice": "7963.54",
                "markPrice": "9973.50770517",
                "positionAmount": "0.010",
                "symbol": "BTCUSDT",
                "unrealizedProfit": "-0.01612295",
            }
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_futures_position_risk_of_sub_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/sub-account/futures/positionRisk" 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(GetFuturesPositionRiskOfSubAccountResponse)

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

        assert response.data() == expected

    def test_get_futures_position_risk_of_sub_account_missing_required_param_email(
        self,
    ):
        """Test that get_futures_position_risk_of_sub_account() raises RequiredError when 'email' is missing."""
        params = {
            "email": "sub-account-email@email.com",
        }
        params["email"] = None

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

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

        params = {
            "email": "sub-account-email@email.com",
        }

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

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

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

        params = {
            "email": "sub-account-email@email.com",
            "futures_type": 56,
        }

        expected_response = {
            "futurePositionRiskVos": [
                {
                    "entryPrice": "9975.12000",
                    "leverage": "50",
                    "maxNotional": "1000000",
                    "liquidationPrice": "7963.54",
                    "markPrice": "9973.50770517",
                    "positionAmount": "0.010",
                    "symbol": "BTCUSDT",
                    "unrealizedProfit": "-0.01612295",
                }
            ],
            "deliveryPositionRiskVos": [
                {
                    "entryPrice": "9975.12000",
                    "markPrice": "9973.50770517",
                    "leverage": "20",
                    "isolated": "False",
                    "isolatedWallet": "9973.50770517",
                    "isolatedMargin": "0.00000000",
                    "isAutoAddMargin": "False",
                    "positionSide": "BOTH",
                    "positionAmount": "1.230",
                    "symbol": "BTCUSD_201225",
                    "unrealizedProfit": "-0.01612295",
                }
            ],
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_futures_position_risk_of_sub_account_v2(**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/v2/sub-account/futures/positionRisk" in request_kwargs["url"]
        assert request_kwargs["method"] == "GET"
        assert normalized["email"] == "sub-account-email@email.com"
        assert normalized["futuresType"] == 56

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

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

        assert response.data() == expected

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

        params = {
            "email": "sub-account-email@email.com",
            "futures_type": 56,
            "recv_window": 5000,
        }

        expected_response = {
            "futurePositionRiskVos": [
                {
                    "entryPrice": "9975.12000",
                    "leverage": "50",
                    "maxNotional": "1000000",
                    "liquidationPrice": "7963.54",
                    "markPrice": "9973.50770517",
                    "positionAmount": "0.010",
                    "symbol": "BTCUSDT",
                    "unrealizedProfit": "-0.01612295",
                }
            ],
            "deliveryPositionRiskVos": [
                {
                    "entryPrice": "9975.12000",
                    "markPrice": "9973.50770517",
                    "leverage": "20",
                    "isolated": "False",
                    "isolatedWallet": "9973.50770517",
                    "isolatedMargin": "0.00000000",
                    "isAutoAddMargin": "False",
                    "positionSide": "BOTH",
                    "positionAmount": "1.230",
                    "symbol": "BTCUSD_201225",
                    "unrealizedProfit": "-0.01612295",
                }
            ],
        }
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_futures_position_risk_of_sub_account_v2(**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/v2/sub-account/futures/positionRisk" 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(GetFuturesPositionRiskOfSubAccountV2Response)

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

        assert response.data() == expected

    def test_get_futures_position_risk_of_sub_account_v2_missing_required_param_email(
        self,
    ):
        """Test that get_futures_position_risk_of_sub_account_v2() raises RequiredError when 'email' is missing."""
        params = {
            "email": "sub-account-email@email.com",
            "futures_type": 56,
        }
        params["email"] = None

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

    def test_get_futures_position_risk_of_sub_account_v2_missing_required_param_futures_type(
        self,
    ):
        """Test that get_futures_position_risk_of_sub_account_v2() raises RequiredError when 'futures_type' is missing."""
        params = {
            "email": "sub-account-email@email.com",
            "futures_type": 56,
        }
        params["futures_type"] = None

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

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

        params = {
            "email": "sub-account-email@email.com",
            "futures_type": 56,
        }

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

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

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

        expected_response = [
            {
                "email": "123@test.com",
                "isSubUserEnabled": True,
                "isUserActive": True,
                "insertTime": 1570791523523,
                "isMarginEnabled": True,
                "isFutureEnabled": True,
                "mobile": 1570791523523,
            }
        ]
        mock_get_signature.return_value = "mocked_signature"
        self.set_mock_response(expected_response)

        response = self.client.get_sub_accounts_status_on_margin_or_futures()

        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/sub-account/status" 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(GetSubAccountsStatusOnMarginOrFuturesResponse)

        if is_list and not is_flat_list:
            expected = expected_response
        elif (
            is_oneof
            or is_list
