diff --git a/tests/unit/common/__init__.py b/tests/unit/common/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/unit/common/test.log b/tests/unit/common/test.log new file mode 100644 index 000000000..e69de29bb diff --git a/tests/unit/common/test_build_req_inter.py b/tests/unit/common/test_build_req_inter.py new file mode 100644 index 000000000..cb411cb17 --- /dev/null +++ b/tests/unit/common/test_build_req_inter.py @@ -0,0 +1,36 @@ +import pytest + +from tencentcloud.common import abstract_client +from tencentcloud.common.exception import TencentCloudSDKException + + +def test_build_req_inter_skip_sign(mocker): + options = {'SkipSign': True} + client = abstract_client.AbstractClient(None, None, None) + mock_method = mocker.patch.object(client, '_build_req_without_signature') + client._build_req_inter('action', {'param': 'value'}, 'req_inter', options) + assert mock_method.called + + +def test_build_req_inter_tc3_signature(mocker): + client = abstract_client.AbstractClient(None, None, None) + mock_method = mocker.patch.object(client, '_build_req_with_tc3_signature') + client._build_req_inter('action', {'param': 'value'}, 'req_inter') + assert mock_method.called + + +def test_build_req_inter_old_signature(mocker): + client = abstract_client.AbstractClient(None, None, None) + client.profile.signMethod = "HmacSHA1" + mock_method = mocker.patch.object(client, '_build_req_with_old_signature') + client._build_req_inter('action', {'param': 'value'}, 'req_inter') + assert mock_method.called + + +def test_build_req_inter_invalid_signature_method(): + client = abstract_client.AbstractClient(None, None, None) + client.profile.signMethod = "InvalidMethod" + with pytest.raises(TencentCloudSDKException) as context: + client._build_req_inter('action', {'param': 'value'}, 'req_inter') + assert context.value.code == "ClientError" + assert context.value.message == "Invalid signature method." diff --git a/tests/unit/common/test_build_req_with_old_signature_inter.py b/tests/unit/common/test_build_req_with_old_signature_inter.py new file mode 100644 index 000000000..3c783e001 --- /dev/null +++ b/tests/unit/common/test_build_req_with_old_signature_inter.py @@ -0,0 +1,41 @@ +import os + +from tencentcloud.common import abstract_client, credential +from tencentcloud.common.profile.client_profile import ClientProfile +from tencentcloud.common.profile.http_profile import HttpProfile + + +class Request: + def __init__(self, data, header): + self.data = data + self.header = header + + +def test_build_req_with_old_signature_inter_correct(mocker): + cred = credential.Credential( + os.environ.get("TENCENTCLOUD_SECRET_ID"), + os.environ.get("TENCENTCLOUD_SECRET_KEY")) + httpProfile = HttpProfile() + httpProfile.endpoint = "sts.tencentcloudapi.com" + + clientProfile = ClientProfile() + clientProfile.httpProfile = httpProfile + clientProfile.signMethod = "HmacSHA256" + + client = abstract_client.AbstractClient(cred, None, profile=clientProfile) + + req = Request({ + "data": { + "name": "张三", + "age": 30, + "email": "zhangsan@example.com" + } + }, + { + "header": { + "Content-Type": "application/json" + }}) + with mocker.patch('time.time', return_value=1634567890), mocker.patch('random.randint', return_value=123456): + """设置mock对象,固定时间戳和随机数""" + client._build_req_with_old_signature('action', {}, req) + assert req.header["Content-Type"] == "application/x-www-form-urlencoded" diff --git a/tests/unit/common/test_build_req_without_signature.py b/tests/unit/common/test_build_req_without_signature.py new file mode 100644 index 000000000..adedb55e0 --- /dev/null +++ b/tests/unit/common/test_build_req_without_signature.py @@ -0,0 +1,122 @@ +import copy +import json +import os +from unittest.mock import MagicMock, patch +from tencentcloud.common import credential, abstract_client +from urllib.parse import urlencode +from tencentcloud.common.profile.client_profile import ClientProfile +from tencentcloud.common.profile.http_profile import HttpProfile + +_default_content_type = "application/json" +_form_urlencoded_content = "application/x-www-form-urlencoded" +_json_content = "application/json" +_multipart_content = "multipart/form-data" +_octet_stream = "application/octet-stream" + + +def get_client(): + cred = credential.Credential( + os.environ.get("TENCENTCLOUD_SECRET_ID"), + os.environ.get("TENCENTCLOUD_SECRET_KEY")) + httpProfile = HttpProfile() + httpProfile.endpoint = "sts.tencentcloudapi.com" + + clientProfile = ClientProfile() + clientProfile.httpProfile = httpProfile + clientProfile.signMethod = "HmacSHA256" + + client = abstract_client.AbstractClient(cred, "ap-shanghai", profile=clientProfile) + return client + + +class Request: + def __init__(self, data, header, method): + self.data = data + self.header = header + self.method = method + + +def test_build_req_without_signature_get_method(): + """测试 GET 请求""" + client = get_client() + req = Request({}, {}, "GET") + action = 'DescribeServices' + params = {'service': 'cvm'} + options = None + client._build_req_without_signature(action, params, req, options) + print(req.header) + assert req.header["Content-Type"] == _form_urlencoded_content + assert req.data == urlencode(copy.deepcopy(client._fix_params(params))) + + +def test_build_req_without_signature_post_method(): + """测试 POST 请求""" + client = get_client() + req = Request({}, {}, "GET") + action = 'DescribeServices' + params = {'service': 'cvm'} + options = None + req.method = 'POST' + client._build_req_without_signature(action, params, req, options) + assert req.header["Content-Type"] == _json_content + assert req.data == json.dumps(params) + + +def test_build_req_without_signature_multipart_method(mocker): + """测试 multipart格式""" + client = get_client() + req = Request({}, {}, "GET") + action = 'DescribeServices' + params = {'service': 'cvm'} + options = {"IsMultipart": True} + req.method = 'POST' + with mocker.patch('uuid.uuid4', return_value=MagicMock(hex="123456")): + client._build_req_without_signature(action, params, req, options) + expected_content_type = f"{_multipart_content}; boundary=123456" + assert req.header["Content-Type"] == expected_content_type + + +def test_build_req_without_signature_octet_stream_method(): + """测试 octet-stream""" + client = get_client() + req = Request({}, {}, "POST") + action = 'DescribeServices' + params = {'service': 'cvm'} + options = {"IsOctetStream": True} + client._build_req_without_signature(action, params, req, options) + assert req.header["Content-Type"] == _octet_stream + + +def test_build_req_without_signature_unsigned_payload(): + """测试无签名""" + client = get_client() + req = Request({}, {}, "POST") + action = 'DescribeServices' + params = {'service': 'cvm'} + options = None + client.profile.unsignedPayload = True + client._build_req_without_signature(action, params, req, options) + assert req.header["X-TC-Content-SHA256"] == "UNSIGNED-PAYLOAD" + + +def test_build_req_without_signature_region(): + """测试 region""" + client = get_client() + req = Request({}, {}, "POST") + action = 'DescribeServices' + params = {'service': 'cvm'} + options = None + client._build_req_without_signature(action, params, req, options) + assert req.header['X-TC-Region'] == client.region + + +def test_build_req_without_signature_language(): + """测试所选语言""" + client = get_client() + req = Request({}, {}, "POST") + action = 'DescribeServices' + params = {'service': 'cvm'} + options = None + client.profile.language = 'zh-CN' + client._build_req_without_signature(action, params, req, options) + assert req.header['X-TC-Language'] == client.profile.language diff --git a/tests/unit/common/test_call_with_region_breaker.py b/tests/unit/common/test_call_with_region_breaker.py new file mode 100644 index 000000000..b4071591f --- /dev/null +++ b/tests/unit/common/test_call_with_region_breaker.py @@ -0,0 +1,49 @@ +import os + + +from tencentcloud.common import abstract_client, credential +from tencentcloud.common.profile.client_profile import ClientProfile +from tencentcloud.common.profile.http_profile import HttpProfile + + +def test_normal_request(mocker): + cred = credential.Credential( + os.environ.get("TENCENTCLOUD_SECRET_ID"), + os.environ.get("TENCENTCLOUD_SECRET_KEY")) + httpProfile = HttpProfile() + httpProfile.endpoint = "sts.tencentcloudapi.com" + + clientProfile = ClientProfile() + clientProfile.httpProfile = httpProfile + clientProfile.signMethod = "HmacSHA256" + clientProfile.disable_region_breaker = False + + client = abstract_client.AbstractClient(cred, None, profile=clientProfile) + action = "DescribeServices" + params = {"service": "cvm"} + mock_request = mocker.patch.object(client, 'request') + client._call_with_region_breaker(action, params) + mock_request.send_request.assert_called_once() + + +def test_circuit_breaker_open(mocker): + cred = credential.Credential( + os.environ.get("TENCENTCLOUD_SECRET_ID"), + os.environ.get("TENCENTCLOUD_SECRET_KEY")) + httpProfile = HttpProfile() + httpProfile.endpoint = "sts.tencentcloudapi.com" + + clientProfile = ClientProfile() + clientProfile.httpProfile = httpProfile + clientProfile.signMethod = "HmacSHA256" + clientProfile.disable_region_breaker = False + + client = abstract_client.AbstractClient(cred, None, profile=clientProfile) + + action = "DescribeServices" + params = {"service": "cvm"} + mocker_circuit_breaker = mocker.patch.object(client, 'circuit_breaker') + mocker_circuit_breaker.before_requests.return_value = 1, True + client._call_with_region_breaker(action, params) + assert ".tencentcloudapi.com" in client._get_endpoint() + diff --git a/tests/unit/common/test_chat_completions.py b/tests/unit/common/test_chat_completions.py new file mode 100644 index 000000000..c942c2f58 --- /dev/null +++ b/tests/unit/common/test_chat_completions.py @@ -0,0 +1,150 @@ +import json +import os +import types + +import pytest + +from tencentcloud.common import credential +from tencentcloud.common.exception import TencentCloudSDKException +from tencentcloud.common.profile.client_profile import ClientProfile +from tencentcloud.common.profile.http_profile import HttpProfile +from tencentcloud.hunyuan.v20230901 import hunyuan_client, models + + +def test_chat_completions(): + cred = credential.Credential( + os.environ.get("TENCENTCLOUD_SECRET_ID"), + os.environ.get("TENCENTCLOUD_SECRET_KEY")) + httpProfile = HttpProfile() + httpProfile.endpoint = "hunyuan.tencentcloudapi.com" + + clientProfile = ClientProfile() + clientProfile.httpProfile = httpProfile + client = hunyuan_client.HunyuanClient(cred, "", clientProfile) + + req = models.ChatCompletionsRequest() + params = { + "Model": "hunyuan-pro", + "Messages": [ + { + "Role": "user", + "Content": "你好啊,早上好" + } + ] + } + req.from_json_string(json.dumps(params)) + + # 返回的resp是一个ChatCompletionsResponse的实例,与请求对象对应 + resp = client.ChatCompletions(req) + assert isinstance(resp, types.GeneratorType) is False + + req1 = models.ChatCompletionsRequest() + params = { + "Model": "hunyuan-pro", + "Messages": [ + { + "Role": "user", + "Content": "你好啊,早上好" + } + ], + "Stream": True + } + req1.from_json_string(json.dumps(params)) + + resp = client.ChatCompletions(req1) + assert isinstance(resp, types.GeneratorType) is True + + +def test_chat_completions_with_exception(): + with pytest.raises(TencentCloudSDKException): + client = hunyuan_client.HunyuanClient(None, "", None) + params = {} + client.ChatCompletions(params) + + +def test_hunyuan_get_embedding(): + cred = credential.Credential( + os.environ.get("TENCENTCLOUD_SECRET_ID"), + os.environ.get("TENCENTCLOUD_SECRET_KEY")) + + httpProfile = HttpProfile() + httpProfile.endpoint = "hunyuan.tencentcloudapi.com" + + clientProfile = ClientProfile() + clientProfile.httpProfile = httpProfile + client = hunyuan_client.HunyuanClient(cred, "", clientProfile) + + req = models.GetEmbeddingRequest() + params = { + "Input": "你好" + } + req.from_json_string(json.dumps(params)) + + resp = client.GetEmbedding(req) + assert resp is not None + + +def test_hunyuan_get_embedding_with_exception(): + with pytest.raises(TencentCloudSDKException): + client = hunyuan_client.HunyuanClient(None, "", None) + params = {} + client.GetEmbedding(params) + + +def test_hunyuan_get_token_count(): + cred = credential.Credential( + os.environ.get("TENCENTCLOUD_SECRET_ID"), + os.environ.get("TENCENTCLOUD_SECRET_KEY")) + httpProfile = HttpProfile() + httpProfile.endpoint = "hunyuan.tencentcloudapi.com" + + clientProfile = ClientProfile() + clientProfile.httpProfile = httpProfile + client = hunyuan_client.HunyuanClient(cred, "", clientProfile) + + req = models.GetTokenCountRequest() + params = { + "Prompt": "你好" + } + req.from_json_string(json.dumps(params)) + + resp = client.GetTokenCount(req) + assert resp.TokenCount == 1 + assert resp.CharacterCount == 2 + assert resp.Tokens == ["你好"] + + +def test_hunyuan_get_token_count_with_exception(): + with pytest.raises(TencentCloudSDKException): + client = hunyuan_client.HunyuanClient(None, "", None) + params = {} + client.GetTokenCount(params) + + +def test_submit_hunyuan_image_job(): + cred = credential.Credential( + os.environ.get("TENCENTCLOUD_SECRET_ID"), + os.environ.get("TENCENTCLOUD_SECRET_KEY")) + + httpProfile = HttpProfile() + httpProfile.endpoint = "hunyuan.tencentcloudapi.com" + + clientProfile = ClientProfile() + clientProfile.httpProfile = httpProfile + client = hunyuan_client.HunyuanClient(cred, "ap-guangzhou", clientProfile) + + req = models.SubmitHunyuanImageJobRequest() + params = { + "Prompt": "火山" + } + req.from_json_string(json.dumps(params)) + + resp = client.SubmitHunyuanImageJob(req) + assert resp is not None + + +def test_submit_hunyuan_image_job_with_exception(): + with pytest.raises(TencentCloudSDKException): + client = hunyuan_client.HunyuanClient(None, "", None) + params = {} + client.SubmitHunyuanImageJob(params) diff --git a/tests/unit/common/test_cvm_role_credential_init.py b/tests/unit/common/test_cvm_role_credential_init.py new file mode 100644 index 000000000..bc777d945 --- /dev/null +++ b/tests/unit/common/test_cvm_role_credential_init.py @@ -0,0 +1,26 @@ +from tencentcloud.common.credential import CVMRoleCredential + + +def test_cvm_role_credential_init_id(mocker): + credential = CVMRoleCredential("cvm") + update_credential = mocker.patch.object(credential, "update_credential") + _secret_id = credential.secret_id + update_credential.assert_called_once() + assert _secret_id == credential.secretId + + +def test_cvm_role_credential_init_key(mocker): + credential = CVMRoleCredential("cvm") + update_credential = mocker.patch.object(credential, "update_credential") + _secret_key = credential.secret_key + update_credential.assert_called_once() + assert _secret_key == credential.secretId + assert credential.secretKey is None + + +def test_cvm_role_credential_init_token(mocker): + credential = CVMRoleCredential("cvm") + update_credential = mocker.patch.object(credential, "update_credential") + credential.token + update_credential.assert_called_once() + assert credential.token is None diff --git a/tests/unit/common/test_default_credential_provider.py b/tests/unit/common/test_default_credential_provider.py new file mode 100644 index 000000000..b1aa1956d --- /dev/null +++ b/tests/unit/common/test_default_credential_provider.py @@ -0,0 +1,69 @@ +from tencentcloud.common.credential import DefaultCredentialProvider, EnvironmentVariableCredential +from tencentcloud.common.exception import TencentCloudSDKException + + +def test_get_credential(mocker): + credential = DefaultCredentialProvider() + mock_get_credentials = mocker.patch.object(credential, 'get_credentials') + credential.get_credential() + mock_get_credentials.assert_called_once_with() + + +def test_get_credentials_with_cred(): + credential = DefaultCredentialProvider() + credential.cred = 'test' + assert credential.get_credentials() == 'test' + + +def test_get_credentials_without_cred_env(mocker): + credential = DefaultCredentialProvider() + credential.cred = None + with mocker.patch('tencentcloud.common.credential.EnvironmentVariableCredential.get_credential', + return_value="env_cred"): + cred = credential.get_credentials() + assert cred == "env_cred" + + +def test_get_credential_without_cred_pro(mocker): + credential = DefaultCredentialProvider() + credential.cred = None + with mocker.patch('tencentcloud.common.credential.EnvironmentVariableCredential.get_credential', return_value=None), \ + mocker.patch('tencentcloud.common.credential.ProfileCredential.get_credential', return_value="env_cred"): + cred = credential.get_credentials() + assert cred == "env_cred" + + +def test_get_credential_without_cred_cvm(mocker): + credential = DefaultCredentialProvider() + credential.cred = None + with mocker.patch('tencentcloud.common.credential.EnvironmentVariableCredential.get_credential', return_value=None), \ + mocker.patch('tencentcloud.common.credential.ProfileCredential.get_credential', return_value=None), \ + mocker.patch('tencentcloud.common.credential.CVMRoleCredential.get_credential', return_value="env_cred"): + cred = credential.get_credentials() + assert cred == "env_cred" + + +def test_get_credential_without_cred_default(mocker): + credential = DefaultCredentialProvider() + credential.cred = None + with mocker.patch('tencentcloud.common.credential.EnvironmentVariableCredential.get_credential', return_value=None), \ + mocker.patch('tencentcloud.common.credential.ProfileCredential.get_credential', return_value=None), \ + mocker.patch('tencentcloud.common.credential.CVMRoleCredential.get_credential', return_value=None), \ + mocker.patch('tencentcloud.common.credential.DefaultTkeOIDCRoleArnProvider.get_credential', return_value="env_cred"): + cred = credential.get_credentials() + assert cred == "env_cred" + + +def test_get_credential_without_cred_exception(mocker): + credential = DefaultCredentialProvider() + credential.cred = None + with mocker.patch('tencentcloud.common.credential.EnvironmentVariableCredential.get_credential', return_value=None), \ + mocker.patch('tencentcloud.common.credential.ProfileCredential.get_credential', return_value=None), \ + mocker.patch('tencentcloud.common.credential.CVMRoleCredential.get_credential', return_value=None), \ + mocker.patch('tencentcloud.common.credential.DefaultTkeOIDCRoleArnProvider.get_credential', return_value=None): + try: + cred = credential.get_credentials() + assert cred == "env_cred" + except TencentCloudSDKException as e: + assert e.message == "no valid credentail." + assert e.code == "ClientSideError" diff --git a/tests/unit/common/test_default_tke_oidc_role_arn_provider.py b/tests/unit/common/test_default_tke_oidc_role_arn_provider.py new file mode 100644 index 000000000..fd4049856 --- /dev/null +++ b/tests/unit/common/test_default_tke_oidc_role_arn_provider.py @@ -0,0 +1,15 @@ +from tencentcloud.common.credential import DefaultTkeOIDCRoleArnProvider, OIDCRoleArnCredential + + +def test_default_tke_oidc_role_arn_provider_get_credential(mocker): + provider = DefaultTkeOIDCRoleArnProvider() + get_credentials = mocker.patch.object(provider, "get_credentials") + provider.get_credential() + get_credentials.assert_called_once() + + +def test_default_tke_oidc_role_arn_provider_get_credentials(mocker): + provider = DefaultTkeOIDCRoleArnProvider() + with mocker.patch('tencentcloud.common.credential.OIDCRoleArnCredential._init_from_tke', return_value=None): + cred = provider.get_credentials() + assert cred._is_tke is True diff --git a/tests/unit/common/test_empty_handle.py b/tests/unit/common/test_empty_handle.py new file mode 100644 index 000000000..772928cf3 --- /dev/null +++ b/tests/unit/common/test_empty_handle.py @@ -0,0 +1,14 @@ +import warnings +import pytest + +import logging +from tencentcloud.common import abstract_client + + +def test_empty_handler_emit(): + warnings.simplefilter('error') + empty_handler = abstract_client.EmptyHandler() + + log_record = logging.LogRecord("test_logger", logging.INFO, "", 0, "Test message", (), None) + empty_handler.emit(log_record) + assert True diff --git a/tests/unit/common/test_environment_variable_credential.py b/tests/unit/common/test_environment_variable_credential.py new file mode 100644 index 000000000..9cb885df0 --- /dev/null +++ b/tests/unit/common/test_environment_variable_credential.py @@ -0,0 +1,29 @@ +import os + +from tencentcloud.common.credential import EnvironmentVariableCredential + + +def test_get_credential_with_valid_env_vars(): + credential = EnvironmentVariableCredential() + os.environ['TENCENTCLOUD_SECRET_ID'] = 'valid_secret_id' + os.environ['TENCENTCLOUD_SECRET_KEY'] = 'valid_secret_key' + assert credential.get_credential() is not None + assert credential.secret_id == 'valid_secret_id' + assert credential.secret_key == 'valid_secret_key' + + +def test_get_credential_with_missing_env_vars(): + credential = EnvironmentVariableCredential() + # 清除环境变量 + if 'TENCENTCLOUD_SECRET_ID' in os.environ: + del os.environ['TENCENTCLOUD_SECRET_ID'] + if 'TENCENTCLOUD_SECRET_KEY' in os.environ: + del os.environ['TENCENTCLOUD_SECRET_KEY'] + assert credential.get_credential() is None + + +def test_get_credential_with_empty_env_vars(): + credential = EnvironmentVariableCredential() + os.environ['TENCENTCLOUD_SECRET_ID'] = '' + os.environ['TENCENTCLOUD_SECRET_KEY'] = '' + assert credential.get_credential() is None diff --git a/tests/unit/hunyuan/__init__.py b/tests/unit/hunyuan/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/unit/hunyuan/test_chat_completions_request.py b/tests/unit/hunyuan/test_chat_completions_request.py new file mode 100644 index 000000000..f8cb62aa3 --- /dev/null +++ b/tests/unit/hunyuan/test_chat_completions_request.py @@ -0,0 +1,67 @@ +import warnings + +from tencentcloud.hunyuan.v20230901.models import ChatCompletionsRequest + + +def test_chat_completions_request_init(): + request = ChatCompletionsRequest() + request.Model = 'gpt-3.5-turbo-0613' + assert request.Model == 'gpt-3.5-turbo-0613' + + request.Messages = [ + { + 'role': 'user', + 'content': 'Hello, world!' + } + ] + assert request.Messages[0]['role'] == 'user' + assert request.Messages[0]['content'] == 'Hello, world!' + + request.Stream = True + assert request.Stream is True + + request.StreamModeration = True + assert request.StreamModeration is True + + request.TopP = 0.9 + assert request.TopP == 0.9 + + request.Temperature = 0.9 + assert request.Temperature == 0.9 + + request.EnableEnhancement = True + assert request.EnableEnhancement is True + + request.Tools = ['gpt-3.5-turbo-0613', ''] + assert request.Tools == ['gpt-3.5-turbo-0613', ''] + + request.ToolChoice = 'gpt-3.5-turbo-0613' + assert request.ToolChoice == 'gpt-3.5-turbo-0613' + + request.CustomTool = ['gpt-3.5-turbo'] + assert request.CustomTool == ['gpt-3.5-turbo'] + + +def test_chat_completions_request_deserialize(mocker): + request = ChatCompletionsRequest() + params = { + "Model": "TestModel", + "Messages": [{"message_id": 1, "content": "Test message"}], + "Stream": "TestStream", + "StreamModeration": "TestStreamModeration", + "TopP": "TestTopP", + "Temperature": "TestTemperature", + "EnableEnhancement": "TestEnableEnhancement", + "Tools": [1, 2, 3], + "ToolChoice": "TestToolChoice", + "CustomTool": "111", + "test": "test" + } + + with mocker.patch('tencentcloud.hunyuan.v20230901.models.Message._deserialize', return_value=111) as mock_Message, \ + mocker.patch('tencentcloud.hunyuan.v20230901.models.Tool._deserialize', return_value=222) as mock_Tool, \ + warnings.catch_warnings(record=True) as w: + request._deserialize(params) + assert request._Model == 'TestModel' + assert len(request.Messages) == 1 + assert str(w.pop().message) == "test fileds are useless." diff --git a/tests/unit/hunyuan/test_chat_completions_response.py b/tests/unit/hunyuan/test_chat_completions_response.py new file mode 100644 index 000000000..2b6e2c098 --- /dev/null +++ b/tests/unit/hunyuan/test_chat_completions_response.py @@ -0,0 +1,47 @@ +from datetime import datetime + +from tencentcloud.hunyuan.v20230901.models import ChatCompletionsResponse + + +def test_chat_completions_response(): + response = ChatCompletionsResponse() + + response.Created = datetime(year=2020, month=1, day=1) + assert response.Created == datetime(year=2020, month=1, day=1) + + response.Usage = 10 + assert response.Usage == 10 + + response.Note = "test" + assert response.Note == "test" + + response.Id = 123456 + assert response.Id == 123456 + + response.Choices = 1 + assert response.Choices == 1 + + response.RequestId = 'a-dm338d-s3ms3k4s-sa' + assert response.RequestId == 'a-dm338d-s3ms3k4s-sa' + + response.ErrorMsg = "test" + assert response.ErrorMsg == "test" + + +def test_chat_completions_response_deserialize(mocker): + response = ChatCompletionsResponse() + params = { + "Created": "2020-01-01", + "Usage": 10, + "Note": "test", + "Id": 123456, + "Choices": [1, 2, 3], + "RequestId": "a-dm338d-s3ms3k4s-sa", + "ErrorMsg": "test" + } + with mocker.patch('tencentcloud.hunyuan.v20230901.models.Usage._deserialize', return_value=111) as mock_usage, \ + mocker.patch('tencentcloud.hunyuan.v20230901.models.Choice._deserialize', return_value=222) as mock_Choice, \ + mocker.patch('tencentcloud.hunyuan.v20230901.models.ErrorMsg._deserialize', + return_value=333) as mock_ErrorMsg: + response._deserialize(params) + assert response._Created == "2020-01-01" diff --git a/tests/unit/hunyuan/test_hunyuan_choice.py b/tests/unit/hunyuan/test_hunyuan_choice.py new file mode 100644 index 000000000..5f3880c6c --- /dev/null +++ b/tests/unit/hunyuan/test_hunyuan_choice.py @@ -0,0 +1,28 @@ +import warnings +import unittest +from tencentcloud.hunyuan.v20230901.models import Choice + + +def test_hunyuan_choice(): + choice = Choice() + + choice.FinishReason = "test" + assert choice.FinishReason == "test" + + choice.Delta = "test" + assert choice.Delta == "test" + + choice.Message = "test" + assert choice.Message == "test" + + +def test_hunyuan_choice_deserialize(mocker): + choice = Choice() + params = {"Delta": "111", "Message": "222", "FinishReason": "333", "fake": "444"} + with mocker.patch('tencentcloud.hunyuan.v20230901.models.Message._deserialize', return_value=111) as mock_Message, \ + mocker.patch('tencentcloud.hunyuan.v20230901.models.Delta._deserialize', return_value=222) as mock_Delta, \ + warnings.catch_warnings(record=True) as captured_warnings: + choice._deserialize(params) + assert choice._FinishReason == "333" + assert len(captured_warnings) == 1 + assert 'fake fileds are useless.' in str(captured_warnings[0].message) \ No newline at end of file diff --git a/tests/unit/hunyuan/test_hunyuan_content.py b/tests/unit/hunyuan/test_hunyuan_content.py new file mode 100644 index 000000000..745305393 --- /dev/null +++ b/tests/unit/hunyuan/test_hunyuan_content.py @@ -0,0 +1,30 @@ +import warnings + +from tencentcloud.hunyuan.v20230901.models import Content + + +def test_hunyuan_content(): + content = Content() + + content.Type = 1 + content.Text = "111.text" + content.ImageUrl = "https://hunyuan.com" + assert content.Type == 1 + assert content.Text == "111.text" + assert content.ImageUrl == "https://hunyuan.com" + + +def test_hunyuan_deserialize(mocker): + content = Content() + params = { + "Type": 1, + "Text": "111.text", + "ImageUrl": "https://hunyuan.com", + "test": "test" + } + with mocker.patch('tencentcloud.hunyuan.v20230901.models.ImageUrl._deserialize', return_value=111), \ + warnings.catch_warnings(record=True) as captured_warnings: + content._deserialize(params) + assert content._Type == 1 + assert content._Text == "111.text" + assert str(captured_warnings.pop().message) == "test fileds are useless." diff --git a/tests/unit/hunyuan/test_hunyuan_delta.py b/tests/unit/hunyuan/test_hunyuan_delta.py new file mode 100644 index 000000000..8e87efee6 --- /dev/null +++ b/tests/unit/hunyuan/test_hunyuan_delta.py @@ -0,0 +1,27 @@ +import warnings + +from tencentcloud.hunyuan.v20230901.models import Delta, Tool + + +def test_hunyuan_delta(): + delta = Delta() + + delta.Role = 'normal_user' + assert delta.Role == 'normal_user' + + delta.Content = 'hello world' + assert delta.Content == 'hello world' + + delta.ToolCalls = "tool test" + assert delta.ToolCalls == "tool test" + + +def test_hunyuan_delta_deserialize(mocker): + delta = Delta() + params = {'Role': 'normal_user', 'Content': 'hello world', 'ToolCalls': [1, 2, 3], "test": "test"} + with mocker.patch('tencentcloud.hunyuan.v20230901.models.ToolCall._deserialize', return_value=111), \ + warnings.catch_warnings(record=True) as captured_warnings: + delta._deserialize(params) + assert delta.Role == 'normal_user' + assert delta.Content == 'hello world' + assert str(captured_warnings.pop().message) == "test fileds are useless." diff --git a/tests/unit/hunyuan/test_hunyuan_embedding_data.py b/tests/unit/hunyuan/test_hunyuan_embedding_data.py new file mode 100644 index 000000000..2b79bfee0 --- /dev/null +++ b/tests/unit/hunyuan/test_hunyuan_embedding_data.py @@ -0,0 +1,31 @@ +import warnings + +from tencentcloud.hunyuan.v20230901.models import EmbeddingData + + +def test_hunyuan_embedding_data(): + embedding = EmbeddingData() + embedding.Embedding = 'test/embedding/embedding' + assert embedding.Embedding == 'test/embedding/embedding' + + embedding.Index = 'test/embedding/index' + assert embedding.Index == 'test/embedding/index' + + embedding.Object = True + assert embedding.Object is True + + +def test_hunyuan_embedding_data_deserialize(): + embedding = EmbeddingData() + params = { + 'Embedding': 'test/embedding/embedding', + 'Index': 'test/embedding/index', + 'Object': True, + "test": "test" + } + with warnings.catch_warnings(record=True) as w: + embedding._deserialize(params) + assert embedding.Embedding == 'test/embedding/embedding' + assert embedding.Index == 'test/embedding/index' + assert embedding.Object is True + assert str(w.pop().message) == "test fileds are useless." diff --git a/tests/unit/hunyuan/test_hunyuan_embedding_usage.py b/tests/unit/hunyuan/test_hunyuan_embedding_usage.py new file mode 100644 index 000000000..c7f09970b --- /dev/null +++ b/tests/unit/hunyuan/test_hunyuan_embedding_usage.py @@ -0,0 +1,25 @@ +import warnings + +from tencentcloud.hunyuan.v20230901.models import EmbeddingUsage + + +def test_hunyuan_embedding_usage(): + embedding = EmbeddingUsage() + embedding.PromptTokens = 100 + assert embedding.PromptTokens == 100 + embedding.TotalTokens = 1000 + assert embedding.TotalTokens == 1000 + + +def test_hunyuan_embedding_usage_deserialize(): + embedding = EmbeddingUsage() + params = { + "PromptTokens": 100, + "TotalTokens": 1000, + "test": "test" + } + with warnings.catch_warnings(record=True) as w: + embedding._deserialize(params) + assert embedding.PromptTokens == 100 + assert embedding.TotalTokens == 1000 + assert str(w.pop().message) == "test fileds are useless." diff --git a/tests/unit/hunyuan/test_hunyuan_error_msg.py b/tests/unit/hunyuan/test_hunyuan_error_msg.py new file mode 100644 index 000000000..e8572a556 --- /dev/null +++ b/tests/unit/hunyuan/test_hunyuan_error_msg.py @@ -0,0 +1,26 @@ +import warnings + +from tencentcloud.hunyuan.v20230901.models import ErrorMsg + + +def test_hunyuan_error_msg(): + msg = ErrorMsg() + msg.Msg = "Hello World!" + assert msg.Msg == "Hello World!" + + msg.Code = "InternalError" + assert msg.Code == "InternalError" + + +def test_hunyuan_error_msg_deserialize(): + msg = ErrorMsg() + params = { + "Msg": "Hello World!", + "Code": "InternalError", + "test": "test" + } + with warnings.catch_warnings(record=True) as w: + msg._deserialize(params) + assert msg.Msg == "Hello World!" + assert msg.Code == "InternalError" + assert str(w.pop().message) == "test fileds are useless." diff --git a/tests/unit/hunyuan/test_hunyuan_get_embedding_request.py b/tests/unit/hunyuan/test_hunyuan_get_embedding_request.py new file mode 100644 index 000000000..54e6a0af6 --- /dev/null +++ b/tests/unit/hunyuan/test_hunyuan_get_embedding_request.py @@ -0,0 +1,21 @@ +import warnings + +from tencentcloud.hunyuan.v20230901.models import GetEmbeddingRequest + + +def test_hunyuan_get_embedding_request(): + req = GetEmbeddingRequest() + req.Input = "test_input" + assert req.Input == "test_input" + + +def test_hunyuan_get_embedding_request_deserialize(): + req = GetEmbeddingRequest() + params = { + "Input": "test_input", + "test": "test" + } + with warnings.catch_warnings(record=True) as w: + req._deserialize(params) + assert req.Input == "test_input" + assert str(w.pop().message) == "test fileds are useless."