diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index afd8d76..20a8ec8 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -24,7 +24,7 @@ jobs: with: python-version: ${{ matrix.python-version }} - name: Install dependencies - run: pip install alibabacloud-tea coverage pytest alibabacloud-tea-util alibabacloud_credentials alibabacloud_openapi_util alibabacloud_gateway_spi alibabacloud_tea_xml httpretty + run: pip install alibabacloud-tea coverage pytest alibabacloud-tea-util alibabacloud_credentials alibabacloud_openapi_util alibabacloud_gateway_spi alibabacloud_tea_xml httpretty alibabacloud_gateway_pop aioresponses - name: Test with unittest run: | coverage run --source="./alibabacloud_tea_openapi" -m pytest tests/test_* diff --git a/golang/client/client_test.go b/golang/client/client_test.go index eff4a42..060fb0f 100644 --- a/golang/client/client_test.go +++ b/golang/client/client_test.go @@ -2,12 +2,14 @@ package client import ( "encoding/json" + "io/ioutil" "net/http" "regexp" "strings" "testing" "time" + pop "github.com/alibabacloud-go/alibabacloud-gateway-pop/client" openapiutil "github.com/alibabacloud-go/openapi-util/service" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" @@ -61,6 +63,11 @@ func (mock *mockHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { ", \"Description\":\"error description\", \"accessDeniedDetail\":{\"test\": 0}}" w.WriteHeader(400) w.Write([]byte(responseBody)) + case "serverError": + responseBody = "{\"Code\":\"error code\", \"Message\":\"error message\", \"RequestId\":\"A45EE076-334D-5012-9746-A8F828D20FD4\"" + + ", \"Description\":\"error description\", \"accessDeniedDetail\":{\"test\": 0}}" + w.WriteHeader(500) + w.Write([]byte(responseBody)) default: w.WriteHeader(200) w.Write([]byte(responseBody)) @@ -102,6 +109,31 @@ func TestConfig(t *testing.T) { Cert: tea.String("config.cert"), Ca: tea.String("config.ca"), } + config.SetEndpoint("config.endpoint") + config.SetEndpointType("public") + config.SetNetwork("config.network") + config.SetSuffix("config.suffix") + config.SetProtocol("config.protocol") + config.SetMethod("config.method") + config.SetRegionId("config.regionId") + config.SetUserAgent("config.userAgent") + config.SetReadTimeout(3000) + config.SetConnectTimeout(3000) + config.SetHttpProxy("config.httpProxy") + config.SetHttpsProxy("config.httpsProxy") + config.SetNoProxy("config.noProxy") + config.SetSocks5Proxy("config.socks5Proxy") + config.SetSocks5NetWork("config.socks5NetWork") + config.SetMaxIdleConns(128) + config.SetSignatureVersion("config.signatureVersion") + config.SetSignatureAlgorithm("config.signatureAlgorithm") + config.SetGlobalParameters(globalParameters) + config.SetKey("config.key") + config.SetCert("config.cert") + config.SetCa("config.ca") + config.SetOpenPlatformEndpoint("openPlatform.aliyuncs.com") + config.SetDisableHttp2(true) + creConfig := &credential.Config{ AccessKeyId: tea.String("accessKeyId"), AccessKeySecret: tea.String("accessKeySecret"), @@ -111,7 +143,7 @@ func TestConfig(t *testing.T) { cred, _err := credential.NewCredential(creConfig) tea_util.AssertNil(t, _err) - config.Credential = cred + config.SetCredential(cred) config.String() config.GoString() client, _err := NewClient(nil) @@ -151,10 +183,10 @@ func TestConfig(t *testing.T) { ty, _ = client.GetType() tea_util.AssertEqual(t, "bearer", tea.StringValue(ty)) - config.AccessKeyId = tea.String("ak") - config.AccessKeySecret = tea.String("secret") - config.SecurityToken = tea.String("token") - config.Type = tea.String("sts") + config.SetAccessKeyId("ak") + config.SetAccessKeySecret("secret") + config.SetSecurityToken("token") + config.SetType("sts") client, _err = NewClient(config) tea_util.AssertNil(t, _err) ak, _ = client.GetAccessKeyId() @@ -165,6 +197,25 @@ func TestConfig(t *testing.T) { tea_util.AssertEqual(t, "token", tea.StringValue(token)) ty, _ = client.GetType() tea_util.AssertEqual(t, "sts", tea.StringValue(ty)) + + config.SetType("bearer") + config.SetBearerToken("token") + config.SetAccessKeyId("") + config.SetAccessKeySecret("") + config.SetSecurityToken("") + client, _err = NewClient(config) + tea_util.AssertNil(t, _err) + ak, _ = client.GetAccessKeyId() + tea_util.AssertEqual(t, "", tea.StringValue(ak)) + sk, _ = client.GetAccessKeySecret() + tea_util.AssertEqual(t, "", tea.StringValue(sk)) + token, _ = client.GetSecurityToken() + tea_util.AssertEqual(t, "", tea.StringValue(token)) + token, _ = client.GetBearerToken() + tea_util.AssertEqual(t, "token", tea.StringValue(token)) + ty, _ = client.GetType() + tea_util.AssertEqual(t, "bearer", tea.StringValue(ty)) + config.AccessKeyId = tea.String("ak") config.AccessKeySecret = tea.String("secret") config.Type = tea.String("access_key") @@ -204,10 +255,77 @@ func TestConfig(t *testing.T) { tea_util.AssertEqual(t, "config.key", tea.StringValue(client.Key)) tea_util.AssertEqual(t, "config.cert", tea.StringValue(client.Cert)) tea_util.AssertEqual(t, "config.ca", tea.StringValue(client.Ca)) + tea_util.AssertEqual(t, true, tea.BoolValue(client.DisableHttp2)) + + globalParameters.SetHeaders(map[string]*string{ + "global-key": tea.String("test"), + }) + globalParameters.SetQueries(map[string]*string{ + "global-query": tea.String("test"), + }) + tea_util.AssertEqual(t, "test", tea.StringValue(client.GlobalParameters.Headers["global-key"])) + tea_util.AssertEqual(t, "test", tea.StringValue(client.GlobalParameters.Queries["global-query"])) _err = client.CheckConfig(config) tea_util.AssertNil(t, _err) } +func TestOpenApiRequest(t *testing.T) { + query := map[string]*string{ + "key": tea.String("value"), + } + body := map[string]interface{}{ + "key": tea.String("value"), + } + headers := map[string]*string{ + "key": tea.String("value"), + } + hostMap := map[string]*string{ + "key": tea.String("value"), + } + req := &OpenApiRequest{} + req.SetQuery(query) + req.SetBody(body) + req.SetHeaders(headers) + req.SetHostMap(hostMap) + req.SetEndpointOverride("test") + req.SetStream(strings.NewReader("test")) + req.GoString() + req.String() + + tea_util.AssertEqual(t, "value", tea.StringValue(req.Headers["key"])) + tea_util.AssertEqual(t, "value", tea.StringValue(req.Query["key"])) + tea_util.AssertEqual(t, body, req.Body) + tea_util.AssertEqual(t, "test", tea.StringValue(req.EndpointOverride)) + tea_util.AssertEqual(t, "value", tea.StringValue(req.HostMap["key"])) + byt, _ := ioutil.ReadAll(req.Stream) + tea_util.AssertEqual(t, "test", string(byt)) +} + +func TestParams(t *testing.T) { + params := &Params{} + params.SetAction("test") + params.SetVersion("test") + params.SetProtocol("test") + params.SetPathname("test") + params.SetMethod("test") + params.SetAuthType("test") + params.SetBodyType("test") + params.SetReqBodyType("test") + params.SetStyle("test") + params.GoString() + params.String() + + tea_util.AssertEqual(t, "test", tea.StringValue(params.Action)) + tea_util.AssertEqual(t, "test", tea.StringValue(params.Version)) + tea_util.AssertEqual(t, "test", tea.StringValue(params.Protocol)) + tea_util.AssertEqual(t, "test", tea.StringValue(params.Pathname)) + tea_util.AssertEqual(t, "test", tea.StringValue(params.Method)) + tea_util.AssertEqual(t, "test", tea.StringValue(params.AuthType)) + tea_util.AssertEqual(t, "test", tea.StringValue(params.BodyType)) + tea_util.AssertEqual(t, "test", tea.StringValue(params.ReqBodyType)) + tea_util.AssertEqual(t, "test", tea.StringValue(params.Style)) +} + func CreateConfig() (_result *Config) { globalParameters := &GlobalParameters{ Headers: map[string]*string{ @@ -1068,7 +1186,7 @@ func TestRequestBodyType(t *testing.T) { config := CreateConfig() runtime := CreateRuntimeOptions() config.Protocol = tea.String("HTTP") - config.Endpoint = tea.String("127.0.0.1:9009") + config.Endpoint = tea.String("127.0.0.1:9010") client, _err := NewClient(config) tea_util.AssertNil(t, _err) // formData @@ -1302,3 +1420,95 @@ func TestResponseBodyTypeROA(t *testing.T) { accessDeniedDetail, _ := err.AccessDeniedDetail["test"].(int) tea_util.AssertEqual(t, 0, accessDeniedDetail) } + +func TestRetryWithError(t *testing.T) { + mux := http.NewServeMux() + mux.Handle("/", &mockHandler{content: "serverError"}) + mux.Handle("/test", &mockHandler{content: "serverError"}) + var server *http.Server + server = &http.Server{ + Addr: ":9013", + WriteTimeout: time.Second * 4, + Handler: mux, + } + go server.ListenAndServe() + config := CreateConfig() + runtime := CreateRuntimeOptions() + runtime.Autoretry = tea.Bool(true) + runtime.MaxAttempts = tea.Int(3) + runtime.BackoffPolicy = tea.String("fix") + runtime.BackoffPeriod = tea.Int(1) + + config.Protocol = tea.String("HTTP") + config.SignatureAlgorithm = tea.String("v2") + config.Endpoint = tea.String("127.0.0.1:9013") + client, _err := NewClient(config) + tea_util.AssertNil(t, _err) + request := CreateOpenApiRequest() + + params := &Params{ + Action: tea.String("TestAPI"), + Version: tea.String("2022-06-01"), + Protocol: tea.String("HTTPS"), + Pathname: tea.String("/"), + Method: tea.String("POST"), + AuthType: tea.String("Anonymous"), + Style: tea.String("RPC"), + ReqBodyType: tea.String("formData"), + BodyType: tea.String("json"), + } + _, _err = client.CallApi(params, request, runtime) + tea_util.AssertNotNil(t, _err) + err := _err.(*tea.SDKError) + tea_util.AssertEqual(t, "code: 500, error message request id: A45EE076-334D-5012-9746-A8F828D20FD4", tea.StringValue(err.Message)) + + params = &Params{ + Action: tea.String("TestAPI"), + Version: tea.String("2022-06-01"), + Protocol: tea.String("HTTPS"), + Pathname: tea.String("/test"), + Method: tea.String("POST"), + AuthType: tea.String("Anonymous"), + Style: tea.String("ROA"), + ReqBodyType: tea.String("formData"), + BodyType: tea.String("json"), + } + _, _err = client.CallApi(params, request, runtime) + tea_util.AssertNotNil(t, _err) + err = _err.(*tea.SDKError) + tea_util.AssertEqual(t, "code: 500, error message request id: A45EE076-334D-5012-9746-A8F828D20FD4", tea.StringValue(err.Message)) + + params = &Params{ + Action: tea.String("TestAPI"), + Version: tea.String("2022-06-01"), + Protocol: tea.String("HTTPS"), + Pathname: tea.String("/test"), + Method: tea.String("POST"), + AuthType: tea.String("Anonymous"), + Style: tea.String("ROA"), + ReqBodyType: tea.String("json"), + BodyType: tea.String("json"), + } + _, _err = client.CallApi(params, request, runtime) + tea_util.AssertNotNil(t, _err) + err = _err.(*tea.SDKError) + tea_util.AssertEqual(t, "code: 500, error message request id: A45EE076-334D-5012-9746-A8F828D20FD4", tea.StringValue(err.Message)) + + params = &Params{ + Action: tea.String("TestAPI"), + Version: tea.String("2022-06-01"), + Protocol: tea.String("HTTPS"), + Pathname: tea.String("/test"), + Method: tea.String("POST"), + AuthType: tea.String("Anonymous"), + Style: tea.String("RPC"), + ReqBodyType: tea.String("json"), + BodyType: tea.String("json"), + } + client.ProductId = tea.String("test") + gatewayClient, _err := pop.NewClient() + tea_util.AssertNil(t, _err) + client.SetGatewayClient(gatewayClient) + _, _err = client.Execute(params, request, runtime) + tea_util.AssertNotNil(t, _err) +} diff --git a/golang/go.mod b/golang/go.mod index fdcfaef..fbed2be 100644 --- a/golang/go.mod +++ b/golang/go.mod @@ -3,12 +3,14 @@ module github.com/alibabacloud-go/darabonba-openapi/v2 go 1.14 require ( + github.com/alibabacloud-go/alibabacloud-gateway-pop v0.0.6 github.com/alibabacloud-go/alibabacloud-gateway-spi v0.0.4 github.com/alibabacloud-go/openapi-util v0.1.0 - github.com/alibabacloud-go/tea v1.2.1 + github.com/alibabacloud-go/tea v1.2.2 github.com/alibabacloud-go/tea-utils/v2 v2.0.6 github.com/alibabacloud-go/tea-xml v1.1.3 github.com/aliyun/credentials-go v1.3.1 github.com/clbanning/mxj/v2 v2.5.5 // indirect + github.com/json-iterator/go v1.1.12 // indirect github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect ) diff --git a/java/pom.xml b/java/pom.xml index e0a1526..0d26ae0 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -144,7 +144,7 @@ jacoco-maven-plugin 0.8.4 - + + + + + prepare-agent + + + + report + prepare-package + + report + diff --git a/java/src/test/java/com/aliyun/teaopenapi/ClientTest.java b/java/src/test/java/com/aliyun/teaopenapi/ClientTest.java index bcf2648..1196ef8 100644 --- a/java/src/test/java/com/aliyun/teaopenapi/ClientTest.java +++ b/java/src/test/java/com/aliyun/teaopenapi/ClientTest.java @@ -1,6 +1,9 @@ package com.aliyun.teaopenapi; +import com.aliyun.credentials.provider.ProfileCredentialsProvider; import com.aliyun.tea.*; +import com.aliyun.tea.interceptor.*; +import com.aliyun.tea.utils.AttributeMap; import com.aliyun.teaopenapi.models.Config; import com.aliyun.teaopenapi.models.GlobalParameters; import com.aliyun.teaopenapi.models.OpenApiRequest; @@ -12,6 +15,8 @@ import org.junit.Test; import java.io.ByteArrayInputStream; +import java.lang.reflect.Field; +import java.util.Collections; import java.util.List; import java.util.Map; @@ -92,6 +97,32 @@ public void testConfig() throws Exception { Assert.assertEquals("secret", client.getAccessKeySecret()); Assert.assertEquals("token", client.getSecurityToken()); Assert.assertEquals("sts", client.getType()); + + config.bearerToken = "token"; + config.type = "bearer"; + config.accessKeyId = ""; + config.accessKeySecret = ""; + config.securityToken = ""; + client = new Client(config); + Assert.assertEquals(null, client.getAccessKeyId()); + Assert.assertEquals(null, client.getAccessKeySecret()); + Assert.assertEquals(null, client.getSecurityToken()); + Assert.assertEquals("bearer", client.getType()); + Assert.assertEquals("token", client.getBearerToken()); + + config.bearerToken = ""; + config.type = ""; + config.accessKeyId = ""; + config.accessKeySecret = ""; + config.securityToken = ""; + config.credential = null; + client = new Client(config); + Assert.assertEquals("", client.getAccessKeyId()); + Assert.assertEquals("", client.getAccessKeySecret()); + Assert.assertEquals("", client.getSecurityToken()); + Assert.assertEquals("", client.getType()); + Assert.assertEquals("", client.getBearerToken()); + Assert.assertNull(client._spi); Assert.assertNull(client._endpointRule); Assert.assertNull(client._endpointMap); @@ -120,6 +151,28 @@ public void testConfig() throws Exception { Assert.assertEquals("config.cert", client._cert); Assert.assertEquals("config.ca", client._ca); Assert.assertEquals(false, client._disableHttp2); + + client.addRequestInterceptor(new RequestInterceptor() { + @Override + public TeaRequest modifyRequest(InterceptorContext interceptorContext, AttributeMap attributeMap) { + return interceptorContext.teaRequest(); + } + }); + client.addResponseInterceptor(new ResponseInterceptor() { + @Override + public TeaResponse modifyResponse(InterceptorContext interceptorContext, AttributeMap attributeMap) { + return interceptorContext.teaResponse(); + } + }); + client.addRuntimeOptionsInterceptor(new RuntimeOptionsInterceptor() { + @Override + public Map modifyRuntimeOptions(InterceptorContext interceptorContext, AttributeMap attributeMap) { + return interceptorContext.runtimeOptions(); + } + }); + Field field = Client.class.getDeclaredField("interceptorChain"); + field.setAccessible(true); + Assert.assertTrue(field.get(client) instanceof InterceptorChain); } public static Config createConfig() throws Exception { diff --git a/java/src/test/java/com/aliyun/teaopenapi/models/ConfigTest.java b/java/src/test/java/com/aliyun/teaopenapi/models/ConfigTest.java new file mode 100644 index 0000000..9c7bef5 --- /dev/null +++ b/java/src/test/java/com/aliyun/teaopenapi/models/ConfigTest.java @@ -0,0 +1,76 @@ +package com.aliyun.teaopenapi.models; + +import org.junit.Assert; +import org.junit.Test; + +public class ConfigTest { + + @Test + public void testSetterGetter() { + Config config = new Config(); + config.setAccessKeyId("test"); + Assert.assertEquals("test", config.getAccessKeyId()); + config.setAccessKeySecret("test"); + Assert.assertEquals("test", config.getAccessKeySecret()); + config.setSecurityToken("test"); + Assert.assertEquals("test", config.getSecurityToken()); + config.setBearerToken("test"); + Assert.assertEquals("test", config.getBearerToken()); + config.setProtocol("test"); + Assert.assertEquals("test", config.getProtocol()); + config.setMethod("test"); + Assert.assertEquals("test", config.getMethod()); + config.setRegionId("test"); + Assert.assertEquals("test", config.getRegionId()); + config.setReadTimeout(100); + Assert.assertEquals(100, (int) config.getReadTimeout()); + config.setConnectTimeout(100); + Assert.assertEquals(100, (int) config.getConnectTimeout()); + config.setHttpProxy("test"); + Assert.assertEquals("test", config.getHttpProxy()); + config.setEndpoint("test"); + Assert.assertEquals("test", config.getEndpoint()); + config.setHttpsProxy("test"); + Assert.assertEquals("test", config.getHttpsProxy()); + com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client(); // 假设Client类有默认构造函数 + config.setCredential(credential); + Assert.assertNotNull(config.getCredential()); + config.setEndpoint("test"); + Assert.assertEquals("test", config.getEndpoint()); + config.setNoProxy("test"); + Assert.assertEquals("test", config.getNoProxy()); + config.setMaxIdleConns(100); + Assert.assertEquals(100, (int) config.getMaxIdleConns()); + config.setNetwork("test"); + Assert.assertEquals("test", config.getNetwork()); + config.setUserAgent("test"); + Assert.assertEquals("test", config.getUserAgent()); + config.setSuffix("test"); + Assert.assertEquals("test", config.getSuffix()); + config.setSocks5Proxy("test"); + Assert.assertEquals("test", config.getSocks5Proxy()); + config.setSocks5NetWork("test"); + Assert.assertEquals("test", config.getSocks5NetWork()); + config.setEndpointType("test"); + Assert.assertEquals("test", config.getEndpointType()); + config.setOpenPlatformEndpoint("test"); + Assert.assertEquals("test", config.getOpenPlatformEndpoint()); + config.setType("test"); + Assert.assertEquals("test", config.getType()); + config.setSignatureVersion("test"); + Assert.assertEquals("test", config.getSignatureVersion()); + config.setSignatureAlgorithm("test"); + Assert.assertEquals("test", config.getSignatureAlgorithm()); + GlobalParameters globalParameters = new GlobalParameters(); + config.setGlobalParameters(globalParameters); + Assert.assertNotNull(config.getGlobalParameters()); + config.setKey("test"); + Assert.assertEquals("test", config.getKey()); + config.setCert("test"); + Assert.assertEquals("test", config.getCert()); + config.setCa("test"); + Assert.assertEquals("test", config.getCa()); + config.setDisableHttp2(true); + Assert.assertTrue(config.getDisableHttp2()); + } +} diff --git a/java/src/test/java/com/aliyun/teaopenapi/models/GlobalParametersTest.java b/java/src/test/java/com/aliyun/teaopenapi/models/GlobalParametersTest.java new file mode 100644 index 0000000..c3d3eb7 --- /dev/null +++ b/java/src/test/java/com/aliyun/teaopenapi/models/GlobalParametersTest.java @@ -0,0 +1,26 @@ +package com.aliyun.teaopenapi.models; + +import org.junit.Test; +import org.junit.Assert; + +import java.util.HashMap; +import java.util.Map; + +public class GlobalParametersTest { + + @Test + public void testSetterGetter() { + GlobalParameters globalParameters = new GlobalParameters(); + Map expectedHeaders = new HashMap<>(); + expectedHeaders.put("Content-Type", "application/json"); + expectedHeaders.put("Authorization", "Bearer token"); + globalParameters.setHeaders(expectedHeaders); + Assert.assertEquals(expectedHeaders, globalParameters.getHeaders()); + + Map expectedQueries = new HashMap<>(); + expectedQueries.put("param1", "value1"); + expectedQueries.put("param2", "value2"); + globalParameters.setQueries(expectedQueries); + Assert.assertEquals(expectedQueries, globalParameters.getQueries()); + } +} diff --git a/java/src/test/java/com/aliyun/teaopenapi/models/OpenApiRequestTest.java b/java/src/test/java/com/aliyun/teaopenapi/models/OpenApiRequestTest.java new file mode 100644 index 0000000..f266b65 --- /dev/null +++ b/java/src/test/java/com/aliyun/teaopenapi/models/OpenApiRequestTest.java @@ -0,0 +1,49 @@ +package com.aliyun.teaopenapi.models; + +import org.junit.Test; +import org.junit.Assert; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +public class OpenApiRequestTest { + + @Test + public void testSetterGetter() { + OpenApiRequest request = new OpenApiRequest(); + // Arrange + Map expectedHeaders = new HashMap<>(); + expectedHeaders.put("Content-Type", "application/json"); + expectedHeaders.put("Authorization", "Bearer token"); + request.setHeaders(expectedHeaders); + Assert.assertEquals(expectedHeaders, request.getHeaders()); + + Map expectedQuery = new HashMap<>(); + expectedQuery.put("param1", "value1"); + expectedQuery.put("param2", "value2"); + request.setQuery(expectedQuery); + Assert.assertEquals(expectedQuery, request.getQuery()); + + String bodyContent = "{\"key\":\"value\"}"; + Object expectedBody = bodyContent; + request.setBody(expectedBody); + Assert.assertEquals(expectedBody, request.getBody()); + + InputStream expectedStream = new ByteArrayInputStream("Test Stream Content".getBytes()); + request.setStream(expectedStream); + Assert.assertEquals(expectedStream, request.getStream()); + + Map expectedHostMap = new HashMap<>(); + expectedHostMap.put("host1", "value1"); + expectedHostMap.put("host2", "value2"); + request.setHostMap(expectedHostMap); + Assert.assertEquals(expectedHostMap, request.getHostMap()); + + String expectedEndpointOverride = "http://localhost:8080/api"; + request.setEndpointOverride(expectedEndpointOverride); + Assert.assertEquals(expectedEndpointOverride, request.getEndpointOverride()); + } + +} diff --git a/java/src/test/java/com/aliyun/teaopenapi/models/ParamsTest.java b/java/src/test/java/com/aliyun/teaopenapi/models/ParamsTest.java new file mode 100644 index 0000000..d1652a3 --- /dev/null +++ b/java/src/test/java/com/aliyun/teaopenapi/models/ParamsTest.java @@ -0,0 +1,30 @@ +package com.aliyun.teaopenapi.models; + +import org.junit.Test; +import org.junit.Assert; + +public class ParamsTest { + + @Test + public void testSetterGetter() { + Params params = new Params(); + params.setAction("testAction"); + Assert.assertEquals("testAction", params.getAction()); + params.setVersion("1.0"); + Assert.assertEquals("1.0", params.getVersion()); + params.setProtocol("https"); + Assert.assertEquals("https", params.getProtocol()); + params.setPathname("/path/to/resource"); + Assert.assertEquals("/path/to/resource", params.getPathname()); + params.setMethod("GET"); + Assert.assertEquals("GET", params.getMethod()); + params.setAuthType("AK"); + Assert.assertEquals("AK", params.getAuthType()); + params.setBodyType("json"); + Assert.assertEquals("json", params.getBodyType()); + params.setReqBodyType("json"); + Assert.assertEquals("json", params.getReqBodyType()); + params.setStyle("ROA"); + Assert.assertEquals("ROA", params.getStyle()); + } +} diff --git a/python/tests/test_client.py b/python/tests/test_client.py index 4c51d7c..1bb3018 100644 --- a/python/tests/test_client.py +++ b/python/tests/test_client.py @@ -1,11 +1,14 @@ # -*- coding: utf-8 -*- # This file is auto-generated, don't edit it. Thanks. import unittest +import asyncio import re import httpretty from Tea.exceptions import TeaException from httpretty.core import HTTPrettyRequest +from aioresponses import aioresponses +from alibabacloud_gateway_pop.client import Client as PopClient from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_credentials import models as credential_models from alibabacloud_credentials.client import Client as CredentialClient @@ -48,7 +51,8 @@ def test_config(self): global_parameters=global_parameters, key='config.key', cert='config.cert', - ca='config.ca' + ca='config.ca', + disable_http_2=True ) cre_config = credential_models.Config( access_key_id='accessKeyId', @@ -86,6 +90,32 @@ def test_config(self): self.assertEqual('secret', client.get_access_key_secret()) self.assertEqual('token', client.get_security_token()) self.assertEqual('sts', client.get_type()) + + config.bearer_token = 'token' + config.type = 'bearer' + config.access_key_id = '' + config.access_key_secret = '' + config.security_token = '' + client = OpenApiClient(config) + self.assertIsNone(client.get_access_key_id()) + self.assertIsNone(client.get_access_key_secret()) + self.assertIsNone(client.get_security_token()) + self.assertEqual('token', client.get_bearer_token()) + self.assertEqual('bearer', client.get_type()) + + config.bearer_token = '' + config.type = '' + config.access_key_id = '' + config.access_key_secret = '' + config.security_token = '' + config.credential = None + client = OpenApiClient(config) + self.assertEqual('', client.get_access_key_id()) + self.assertEqual('', client.get_access_key_secret()) + self.assertEqual('', client.get_security_token()) + self.assertEqual('', client.get_bearer_token()) + self.assertEqual('', client.get_type()) + self.assertIsNone(client._spi) self.assertIsNone(client._endpoint_rule) self.assertIsNone(client._endpoint_map) @@ -113,6 +143,7 @@ def test_config(self): self.assertEqual("config.key", client._key) self.assertEqual("config.cert", client._cert) self.assertEqual("config.ca", client._ca) + self.assertEqual(True, client._disable_http_2) def create_config(self) -> open_api_models.Config: global_parameters = open_api_models.GlobalParameters( @@ -137,7 +168,7 @@ def create_config(self) -> open_api_models.Config: global_parameters=global_parameters ) return config - + def create_bearer_token_config(self) -> open_api_models.Config: cre_config = credential_models.Config( bearer_token='token', @@ -255,6 +286,7 @@ def request_callback(request: HTTPrettyRequest, uri: str, headers: dict): config.signature_algorithm = 'v2' config.endpoint = 'test1.aliyuncs.com' client = OpenApiClient(config) + def bearer_request_callback(request: HTTPrettyRequest, uri: str, headers: dict): assert 'TestAPI' == request.querystring['Action'][0] assert '2022-06-01' == request.querystring['Version'][0] @@ -270,6 +302,7 @@ def bearer_request_callback(request: HTTPrettyRequest, uri: str, headers: dict): content_type) headers['x-acs-request-id'] = 'A45EE076-334D-5012-9746-A8F828D20FD4' return [200, headers, responseBody] + httpretty.register_uri( httpretty.POST, "http://test1.aliyuncs.com", body=bearer_request_callback) @@ -277,6 +310,97 @@ def bearer_request_callback(request: HTTPrettyRequest, uri: str, headers: dict): self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) self.assertEqual(200, result.get('statusCode')) + @aioresponses() + def test_call_api_for_rpcwith_v2sign_ak_form_async(self, m): + requestBody = 'key1=value&key2=1&key3=True' + responseBody = '{"AppId":"test", "ClassId":"test", "UserId":123}' + config = self.create_config() + runtime = self.create_runtime_options() + config.protocol = 'HTTP' + config.signature_algorithm = 'v2' + config.endpoint = 'test.aliyuncs.com' + client = OpenApiClient(config) + request = self.create_open_api_request() + params = open_api_models.Params( + action='TestAPI', + version='2022-06-01', + protocol='HTTPS', + pathname='/', + method='POST', + auth_type='AK', + style='RPC', + req_body_type='formData', + body_type='json' + ) + + def request_callback(url, **request): + assert None is not re.match( + '.+AccessKeyId=ak&Action=TestAPI&Format=json&SecurityToken=token&Signature=.+&SignatureMethod=HMAC-SHA1&SignatureNonce=.+&SignatureVersion=1.0&Timestamp=.+&Version=2022-06-01&global-query=global-value&key1=value&key2=1&key3=True', + str(url)) + assert 'global-value' == request['headers'].get('global-key') + assert 'extends-value' == request['headers'].get('extends-key') + assert 'test.aliyuncs.com' == request['headers'].get('host') + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert None is not re.match('AlibabaCloud.+TeaDSL/1 config.userAgent', + request['headers'].get('user-agent')) + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/x-www-form-urlencoded', 'expected application/x-www-form-urlencoded but received Content-Type: {}'.format( + content_type) + + responseHeaders = {'x-acs-request-id': 'A45EE076-334D-5012-9746-A8F828D20FD4'} + m.post(re.compile(r'http://test\.aliyuncs\.com/.*'), + body=responseBody, + status=200, + headers=responseHeaders, + callback=request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('test', result.get('body').get('AppId')) + self.assertEqual('test', result.get('body').get('ClassId')) + self.assertEqual(123, result.get('body').get('UserId')) + self.assertEqual(200, result.get('statusCode')) + + # bearer token + config = self.create_bearer_token_config() + config.protocol = 'HTTP' + config.signature_algorithm = 'v2' + config.endpoint = 'test1.aliyuncs.com' + client = OpenApiClient(config) + + def bearer_request_callback(url, **request): + assert None is not re.match( + '.+Action=TestAPI&BearerToken=token&Format=json&SignatureNonce=.+&SignatureType=BEARERTOKEN&Timestamp=.+&Version=2022-06-01&key1=value&key2=1&key3=True', + str(url)) + # assert 'bearer token' == request.headers.get('authorization') + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/x-www-form-urlencoded', 'expected application/x-www-form-urlencoded but received Content-Type: {}'.format( + content_type) + + responseHeaders = {'x-acs-request-id': 'A45EE076-334D-5012-9746-A8F828D20FD4'} + m.post(re.compile(r'http://test1\.aliyuncs\.com/.*'), + body=responseBody, + status=200, + headers=responseHeaders, + callback=bearer_request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual(200, result.get('statusCode')) + @httpretty.activate(allow_net_connect=False) def test_call_api_for_rpcwith_v2sign_anonymous_json(self): requestBody = 'key1=value&key2=1&key3=True' @@ -334,6 +458,64 @@ def request_callback(request: HTTPrettyRequest, uri: str, headers: dict): self.assertEqual(123, result.get('body').get('UserId')) self.assertEqual(200, result.get('statusCode')) + @aioresponses() + def test_call_api_for_rpcwith_v2sign_anonymous_json_async(self, m): + requestBody = 'key1=value&key2=1&key3=True' + responseBody = '{"AppId":"test", "ClassId":"test", "UserId":123}' + config = self.create_config() + runtime = self.create_runtime_options() + config.protocol = 'HTTP' + config.signature_algorithm = 'v2' + config.endpoint = 'test.aliyuncs.com' + client = OpenApiClient(config) + request = self.create_open_api_request() + params = open_api_models.Params( + action='TestAPI', + version='2022-06-01', + protocol='HTTPS', + pathname='/', + method='POST', + auth_type='Anonymous', + style='RPC', + req_body_type='json', + body_type='json' + ) + + def request_callback(url, **request): + assert None is not re.match( + '.+Action=TestAPI&Format=json&SignatureNonce=.+&Timestamp=.+&Version=2022-06-01&global-query=global-value&key1=value&key2=1&key3=True', + str(url)) + assert 'global-value' == request['headers'].get('global-key') + assert 'extends-value' == request['headers'].get('extends-key') + assert 'test.aliyuncs.com' == request['headers'].get('host') + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert None is not re.match('AlibabaCloud.+TeaDSL/1 config.userAgent', + request['headers'].get('user-agent')) + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/x-www-form-urlencoded', 'expected application/x-www-form-urlencoded but received Content-Type: {}'.format( + content_type) + + responseHeaders = {'x-acs-request-id': 'A45EE076-334D-5012-9746-A8F828D20FD4'} + m.post(re.compile(r'http://test\.aliyuncs\.com/.*'), + body=responseBody, + status=200, + headers=responseHeaders, + callback=request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('test', result.get('body').get('AppId')) + self.assertEqual('test', result.get('body').get('ClassId')) + self.assertEqual(123, result.get('body').get('UserId')) + self.assertEqual(200, result.get('statusCode')) + @httpretty.activate(allow_net_connect=False) def test_call_api_for_roawith_v2sign_ak_form(self): requestBody = 'key1=value&key2=1&key3=True' @@ -401,6 +583,7 @@ def request_callback(request: HTTPrettyRequest, uri: str, headers: dict): config.signature_algorithm = 'v2' config.endpoint = 'test1.aliyuncs.com' client = OpenApiClient(config) + def bearer_request_callback(request: HTTPrettyRequest, uri: str, headers: dict): assert '2022-06-01' == request.headers.get('x-acs-version') assert 'TestAPI' == request.headers.get('x-acs-action') @@ -414,6 +597,7 @@ def bearer_request_callback(request: HTTPrettyRequest, uri: str, headers: dict): content_type) headers['x-acs-request-id'] = 'A45EE076-334D-5012-9746-A8F828D20FD4' return [200, headers, responseBody] + httpretty.register_uri( httpretty.POST, "http://test1.aliyuncs.com/test", body=bearer_request_callback) @@ -435,6 +619,7 @@ def bearer_request_callback(request: HTTPrettyRequest, uri: str, headers: dict): req_body_type='json', body_type='json' ) + def bearer_json_request_callback(request: HTTPrettyRequest, uri: str, headers: dict): assert '2022-06-01' == request.headers.get('x-acs-version') assert 'TestAPI' == request.headers.get('x-acs-action') @@ -448,6 +633,7 @@ def bearer_json_request_callback(request: HTTPrettyRequest, uri: str, headers: d content_type) headers['x-acs-request-id'] = 'A45EE076-334D-5012-9746-A8F828D20FD4' return [200, headers, responseBody] + httpretty.register_uri( httpretty.POST, "http://test2.aliyuncs.com/test", body=bearer_json_request_callback) @@ -455,6 +641,149 @@ def bearer_json_request_callback(request: HTTPrettyRequest, uri: str, headers: d self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) self.assertEqual(200, result.get('statusCode')) + @aioresponses() + def test_call_api_for_roawith_v2sign_ak_form_async(self, m): + requestBody = 'key1=value&key2=1&key3=True' + responseBody = '{"AppId":"test", "ClassId":"test", "UserId":123}' + config = self.create_config() + runtime = self.create_runtime_options() + config.protocol = 'HTTP' + config.signature_algorithm = 'v2' + config.endpoint = 'test.aliyuncs.com' + client = OpenApiClient(config) + request = self.create_open_api_request() + params = open_api_models.Params( + action='TestAPI', + version='2022-06-01', + protocol='HTTPS', + pathname='/test', + method='POST', + auth_type='AK', + style='ROA', + req_body_type='formData', + body_type='json' + ) + + def request_callback(url, **request): + assert 'http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True' == str(url) + assert 'global-value' == request['headers'].get('global-key') + assert 'extends-value' == request['headers'].get('extends-key') + assert 'sdk' == request['headers'].get('for-test') + assert 'test.aliyuncs.com' == request['headers'].get('host') + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert 'application/json' == request['headers'].get('accept') + assert 'HMAC-SHA1' == request['headers'].get('x-acs-signature-method') + assert '1.0' == request['headers'].get('x-acs-signature-version') + assert 'ak' == request['headers'].get('x-acs-accesskey-id') + assert 'token' == request['headers'].get('x-acs-security-token') + assert None is not request['headers'].get('date') + assert None is not request['headers'].get('x-acs-signature-nonce') + + assert None is not re.match('acs ak:.+', request['headers'].get('authorization')) + assert None is not re.match('AlibabaCloud.+TeaDSL/1 config.userAgent', request['headers'].get('user-agent')) + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/x-www-form-urlencoded', 'expected application/x-www-form-urlencoded but received Content-Type: {}'.format( + content_type) + + responseHeaders = {'x-acs-request-id': 'A45EE076-334D-5012-9746-A8F828D20FD4'} + m.post('http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True', + body=responseBody, + status=200, + headers=responseHeaders, + callback=request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('test', result.get('body').get('AppId')) + self.assertEqual('test', result.get('body').get('ClassId')) + self.assertEqual(123, result.get('body').get('UserId')) + self.assertEqual(200, result.get('statusCode')) + + # bearer token + config = self.create_bearer_token_config() + config.protocol = 'HTTP' + config.signature_algorithm = 'v2' + config.endpoint = 'test1.aliyuncs.com' + client = OpenApiClient(config) + + def bearer_request_callback(url, **request): + assert 'http://test1.aliyuncs.com/test?key1=value&key2=1&key3=True' == str(url) + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert 'application/json' == request['headers'].get('accept') + assert 'token' == request['headers'].get('x-acs-bearer-token') + assert 'BEARERTOKEN' == request['headers'].get('x-acs-signature-type') + # assert 'bearer token' == request.headers.get('authorization') + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/x-www-form-urlencoded', 'expected application/x-www-form-urlencoded but received Content-Type: {}'.format( + content_type) + + m.post('http://test1.aliyuncs.com/test?key1=value&key2=1&key3=True', + body=responseBody, + status=200, + headers=responseHeaders, + callback=bearer_request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual(200, result.get('statusCode')) + + requestBody = '{"key1":"value","key2":1,"key3":true}' + config.endpoint = 'test2.aliyuncs.com' + client = OpenApiClient(config) + params = open_api_models.Params( + action='TestAPI', + version='2022-06-01', + protocol='HTTPS', + pathname='/test', + method='POST', + auth_type='AK', + style='ROA', + req_body_type='json', + body_type='json' + ) + + def bearer_json_request_callback(url, **request): + assert 'http://test2.aliyuncs.com/test?key1=value&key2=1&key3=True' == str(url) + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert 'application/json' == request['headers'].get('accept') + assert 'token' == request['headers'].get('x-acs-bearer-token') + assert 'BEARERTOKEN' == request['headers'].get('x-acs-signature-type') + # assert 'bearer token' == request.headers.get('authorization') + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/json; charset=utf-8', 'expected application/json but received Content-Type: {}'.format( + content_type) + + m.post('http://test2.aliyuncs.com/test?key1=value&key2=1&key3=True', + body=responseBody, + status=200, + headers=responseHeaders, + callback=bearer_json_request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual(200, result.get('statusCode')) + @httpretty.activate(allow_net_connect=False) def test_call_api_for_roawith_v2sign_anonymous_json(self): requestBody = '{"key1":"value","key2":1,"key3":true}' @@ -512,6 +841,67 @@ def request_callback(request: HTTPrettyRequest, uri: str, headers: dict): self.assertEqual(123, result.get('body').get('UserId')) self.assertEqual(200, result.get('statusCode')) + @aioresponses() + def test_call_api_for_roawith_v2sign_anonymous_json_async(self, m): + requestBody = '{"key1":"value","key2":1,"key3":true}' + responseBody = '{"AppId":"test", "ClassId":"test", "UserId":123}' + config = self.create_config() + runtime = self.create_runtime_options() + config.protocol = 'HTTP' + config.signature_algorithm = 'v2' + config.endpoint = 'test.aliyuncs.com' + client = OpenApiClient(config) + request = self.create_open_api_request() + params = open_api_models.Params( + action='TestAPI', + version='2022-06-01', + protocol='HTTPS', + pathname='/test', + method='POST', + auth_type='Anonymous', + style='ROA', + req_body_type='json', + body_type='json' + ) + + def request_callback(url, **request): + assert 'http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True' == str(url) + assert 'global-value' == request['headers'].get('global-key') + assert 'extends-value' == request['headers'].get('extends-key') + assert 'sdk' == request['headers'].get('for-test') + assert 'test.aliyuncs.com' == request['headers'].get('host') + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert 'application/json' == request['headers'].get('accept') + assert 'HMAC-SHA1' == request['headers'].get('x-acs-signature-method') + assert '1.0' == request['headers'].get('x-acs-signature-version') + assert None is not request['headers'].get('date') + assert None is not request['headers'].get('x-acs-signature-nonce') + assert None is not re.match('AlibabaCloud.+TeaDSL/1 config.userAgent', request['headers'].get('user-agent')) + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/json; charset=utf-8', 'expected application/json but received Content-Type: {}'.format( + content_type) + + responseHeaders = {'x-acs-request-id': 'A45EE076-334D-5012-9746-A8F828D20FD4'} + m.post('http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True', + body=responseBody, + status=200, + headers=responseHeaders, + callback=request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('test', result.get('body').get('AppId')) + self.assertEqual('test', result.get('body').get('ClassId')) + self.assertEqual(123, result.get('body').get('UserId')) + self.assertEqual(200, result.get('statusCode')) + @httpretty.activate(allow_net_connect=False) def test_call_api_for_rpcwith_v3sign_ak_form(self): requestBody = 'key1=value&key2=1&key3=True' @@ -579,6 +969,7 @@ def request_callback(request: HTTPrettyRequest, uri: str, headers: dict): config.protocol = 'HTTP' config.endpoint = 'test1.aliyuncs.com' client = OpenApiClient(config) + def bearer_request_callback(request: HTTPrettyRequest, uri: str, headers: dict): assert '2022-06-01' == request.headers.get('x-acs-version') assert 'TestAPI' == request.headers.get('x-acs-action') @@ -592,6 +983,7 @@ def bearer_request_callback(request: HTTPrettyRequest, uri: str, headers: dict): content_type) headers['x-acs-request-id'] = 'A45EE076-334D-5012-9746-A8F828D20FD4' return [200, headers, responseBody] + httpretty.register_uri( httpretty.POST, "http://test1.aliyuncs.com", body=bearer_request_callback) @@ -599,9 +991,9 @@ def bearer_request_callback(request: HTTPrettyRequest, uri: str, headers: dict): self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) self.assertEqual(200, result.get('statusCode')) - @httpretty.activate(allow_net_connect=False) - def test_call_api_for_rpcwith_v3sign_anonymous_json(self): - requestBody = '{"key1":"value","key2":1,"key3":true}' + @aioresponses() + def test_call_api_for_rpcwith_v3sign_ak_form_async(self, m): + requestBody = 'key1=value&key2=1&key3=True' responseBody = '{"AppId":"test", "ClassId":"test", "UserId":123}' config = self.create_config() runtime = self.create_runtime_options() @@ -615,52 +1007,212 @@ def test_call_api_for_rpcwith_v3sign_anonymous_json(self): protocol='HTTPS', pathname='/', method='POST', - auth_type='Anonymous', + auth_type='AK', style='RPC', - req_body_type='json', + req_body_type='formData', body_type='json' ) - def request_callback(request: HTTPrettyRequest, uri: str, headers: dict): - assert 'value' == request.querystring['key1'][0] - assert '1' == request.querystring['key2'][0] - assert 'True' == request.querystring['key3'][0] - assert 'global-value' == request.querystring['global-query'][0] - assert 'sdk' == request.headers.get('for-test') - assert 'global-value' == request.headers.get('global-key') - assert 'extends-value' == request.headers.get('extends-key') - assert 'test.aliyuncs.com' == request.headers.get('host') - assert '2022-06-01' == request.headers.get('x-acs-version') - assert 'TestAPI' == request.headers.get('x-acs-action') - assert 'application/json' == request.headers.get('accept') - assert None is not request.headers.get('x-acs-date') - assert None is not request.headers.get('x-acs-signature-nonce') - assert None is not request.headers.get('x-acs-content-sha256') + def request_callback(url, **request): + assert 'http://test.aliyuncs.com/?global-query=global-value&key1=value&key2=1&key3=True' == str(url) + assert 'sdk' == request['headers'].get('for-test') + assert 'global-value' == request['headers'].get('global-key') + assert 'extends-value' == request['headers'].get('extends-key') + assert 'test.aliyuncs.com' == request['headers'].get('host') + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert 'application/json' == request['headers'].get('accept') + assert 'ak' == request['headers'].get('x-acs-accesskey-id') + assert 'token' == request['headers'].get('x-acs-security-token') + assert None is not request['headers'].get('x-acs-date') + assert None is not request['headers'].get('x-acs-signature-nonce') + assert None is not request['headers'].get('x-acs-content-sha256') - assert None is not re.match('AlibabaCloud.+TeaDSL/1 config.userAgent', request.headers.get('user-agent')) - content_type = request.headers.get('content-type') - assert request.body.decode('utf-8') == requestBody, 'unexpected body: {}'.format(request.body) - assert content_type == 'application/json; charset=utf-8', 'expected application/json but received Content-Type: {}'.format( + assert None is not re.match( + 'ACS3-HMAC-SHA256 Credential=ak,SignedHeaders=accept;content-type;extends-key;for-test;global-key;' + + 'host;user-agent;x-acs-accesskey-id;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-security-token;' + + 'x-acs-signature-nonce;x-acs-version,Signature=.+', request['headers'].get('Authorization')) + assert None is not re.match('AlibabaCloud.+TeaDSL/1 config.userAgent', request['headers'].get('user-agent')) + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/x-www-form-urlencoded', 'expected application/x-www-form-urlencoded but received Content-Type: {}'.format( content_type) - headers['x-acs-request-id'] = 'A45EE076-334D-5012-9746-A8F828D20FD4' - return [200, headers, responseBody] - httpretty.register_uri( - httpretty.POST, "http://test.aliyuncs.com", - body=request_callback) - result = client.call_api(params, request, runtime) + responseHeaders = {'x-acs-request-id': 'A45EE076-334D-5012-9746-A8F828D20FD4'} + m.post('http://test.aliyuncs.com/?global-query=global-value&key1=value&key2=1&key3=True', + body=responseBody, + status=200, + headers=responseHeaders, + callback=request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) self.assertEqual('test', result.get('body').get('AppId')) self.assertEqual('test', result.get('body').get('ClassId')) self.assertEqual(123, result.get('body').get('UserId')) self.assertEqual(200, result.get('statusCode')) - @httpretty.activate(allow_net_connect=False) - def test_call_api_for_roawith_v3sign_ak_form(self): - requestBody = 'key1=value&key2=1&key3=True' - responseBody = '{"AppId":"test", "ClassId":"test", "UserId":123}' - config = self.create_config() - runtime = self.create_runtime_options() + # bearer token + config = self.create_bearer_token_config() + config.protocol = 'HTTP' + config.endpoint = 'test1.aliyuncs.com' + client = OpenApiClient(config) + + def bearer_request_callback(url, **request): + assert 'http://test1.aliyuncs.com/?SignatureType=BEARERTOKEN&key1=value&key2=1&key3=True' == str(url) + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert 'application/json' == request['headers'].get('accept') + assert 'token' == request['headers'].get('x-acs-bearer-token') + # assert 'bearer token' == request.headers.get('authorization') + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/x-www-form-urlencoded', 'expected application/x-www-form-urlencoded but received Content-Type: {}'.format( + content_type) + + responseHeaders = {'x-acs-request-id': 'A45EE076-334D-5012-9746-A8F828D20FD4'} + m.post('http://test1.aliyuncs.com/?SignatureType=BEARERTOKEN&key1=value&key2=1&key3=True', + body=responseBody, + status=200, + headers=responseHeaders, + callback=bearer_request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual(200, result.get('statusCode')) + + @httpretty.activate(allow_net_connect=False) + def test_call_api_for_rpcwith_v3sign_anonymous_json(self): + requestBody = '{"key1":"value","key2":1,"key3":true}' + responseBody = '{"AppId":"test", "ClassId":"test", "UserId":123}' + config = self.create_config() + runtime = self.create_runtime_options() + config.protocol = 'HTTP' + config.endpoint = 'test.aliyuncs.com' + client = OpenApiClient(config) + request = self.create_open_api_request() + params = open_api_models.Params( + action='TestAPI', + version='2022-06-01', + protocol='HTTPS', + pathname='/', + method='POST', + auth_type='Anonymous', + style='RPC', + req_body_type='json', + body_type='json' + ) + + def request_callback(request: HTTPrettyRequest, uri: str, headers: dict): + assert 'value' == request.querystring['key1'][0] + assert '1' == request.querystring['key2'][0] + assert 'True' == request.querystring['key3'][0] + assert 'global-value' == request.querystring['global-query'][0] + assert 'sdk' == request.headers.get('for-test') + assert 'global-value' == request.headers.get('global-key') + assert 'extends-value' == request.headers.get('extends-key') + assert 'test.aliyuncs.com' == request.headers.get('host') + assert '2022-06-01' == request.headers.get('x-acs-version') + assert 'TestAPI' == request.headers.get('x-acs-action') + assert 'application/json' == request.headers.get('accept') + assert None is not request.headers.get('x-acs-date') + assert None is not request.headers.get('x-acs-signature-nonce') + assert None is not request.headers.get('x-acs-content-sha256') + + assert None is not re.match('AlibabaCloud.+TeaDSL/1 config.userAgent', request.headers.get('user-agent')) + content_type = request.headers.get('content-type') + assert request.body.decode('utf-8') == requestBody, 'unexpected body: {}'.format(request.body) + assert content_type == 'application/json; charset=utf-8', 'expected application/json but received Content-Type: {}'.format( + content_type) + headers['x-acs-request-id'] = 'A45EE076-334D-5012-9746-A8F828D20FD4' + return [200, headers, responseBody] + + httpretty.register_uri( + httpretty.POST, "http://test.aliyuncs.com", + body=request_callback) + result = client.call_api(params, request, runtime) + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('test', result.get('body').get('AppId')) + self.assertEqual('test', result.get('body').get('ClassId')) + self.assertEqual(123, result.get('body').get('UserId')) + self.assertEqual(200, result.get('statusCode')) + + @aioresponses() + def test_call_api_for_rpcwith_v3sign_anonymous_json_async(self, m): + requestBody = '{"key1":"value","key2":1,"key3":true}' + responseBody = '{"AppId":"test", "ClassId":"test", "UserId":123}' + config = self.create_config() + runtime = self.create_runtime_options() + config.protocol = 'HTTP' + config.endpoint = 'test.aliyuncs.com' + client = OpenApiClient(config) + request = self.create_open_api_request() + params = open_api_models.Params( + action='TestAPI', + version='2022-06-01', + protocol='HTTPS', + pathname='/', + method='POST', + auth_type='Anonymous', + style='RPC', + req_body_type='json', + body_type='json' + ) + + def request_callback(url, **request): + assert 'http://test.aliyuncs.com/?global-query=global-value&key1=value&key2=1&key3=True' == str(url) + assert 'sdk' == request['headers'].get('for-test') + assert 'global-value' == request['headers'].get('global-key') + assert 'extends-value' == request['headers'].get('extends-key') + assert 'test.aliyuncs.com' == request['headers'].get('host') + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert 'application/json' == request['headers'].get('accept') + assert None is not request['headers'].get('x-acs-date') + assert None is not request['headers'].get('x-acs-signature-nonce') + assert None is not request['headers'].get('x-acs-content-sha256') + + assert None is not re.match('AlibabaCloud.+TeaDSL/1 config.userAgent', request['headers'].get('user-agent')) + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/json; charset=utf-8', 'expected application/json but received Content-Type: {}'.format( + content_type) + + responseHeaders = {'x-acs-request-id': 'A45EE076-334D-5012-9746-A8F828D20FD4'} + m.post('http://test.aliyuncs.com/?global-query=global-value&key1=value&key2=1&key3=True', + body=responseBody, + status=200, + headers=responseHeaders, + callback=request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('test', result.get('body').get('AppId')) + self.assertEqual('test', result.get('body').get('ClassId')) + self.assertEqual(123, result.get('body').get('UserId')) + self.assertEqual(200, result.get('statusCode')) + + @httpretty.activate(allow_net_connect=False) + def test_call_api_for_roawith_v3sign_ak_form(self): + requestBody = 'key1=value&key2=1&key3=True' + responseBody = '{"AppId":"test", "ClassId":"test", "UserId":123}' + config = self.create_config() + runtime = self.create_runtime_options() config.protocol = 'HTTP' config.endpoint = 'test.aliyuncs.com' client = OpenApiClient(config) @@ -722,6 +1274,7 @@ def request_callback(request: HTTPrettyRequest, uri: str, headers: dict): config.protocol = 'HTTP' config.endpoint = 'test1.aliyuncs.com' client = OpenApiClient(config) + def bearer_request_callback(request: HTTPrettyRequest, uri: str, headers: dict): assert '2022-06-01' == request.headers.get('x-acs-version') assert 'TestAPI' == request.headers.get('x-acs-action') @@ -735,6 +1288,7 @@ def bearer_request_callback(request: HTTPrettyRequest, uri: str, headers: dict): content_type) headers['x-acs-request-id'] = 'A45EE076-334D-5012-9746-A8F828D20FD4' return [200, headers, responseBody] + httpretty.register_uri( httpretty.POST, "http://test1.aliyuncs.com/test", body=bearer_request_callback) @@ -742,6 +1296,106 @@ def bearer_request_callback(request: HTTPrettyRequest, uri: str, headers: dict): self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) self.assertEqual(200, result.get('statusCode')) + @aioresponses() + def test_call_api_for_roawith_v3sign_ak_form_async(self, m): + requestBody = 'key1=value&key2=1&key3=True' + responseBody = '{"AppId":"test", "ClassId":"test", "UserId":123}' + config = self.create_config() + runtime = self.create_runtime_options() + config.protocol = 'HTTP' + config.endpoint = 'test.aliyuncs.com' + client = OpenApiClient(config) + request = self.create_open_api_request() + params = open_api_models.Params( + action='TestAPI', + version='2022-06-01', + protocol='HTTPS', + pathname='/test', + method='POST', + auth_type='AK', + style='ROA', + req_body_type='formData', + body_type='json' + ) + + def request_callback(url, **request): + assert 'http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True' == str(url) + assert 'sdk' == request['headers'].get('for-test') + assert 'global-value' == request['headers'].get('global-key') + assert 'extends-value' == request['headers'].get('extends-key') + assert 'test.aliyuncs.com' == request['headers'].get('host') + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert 'application/json' == request['headers'].get('accept') + assert 'ak' == request['headers'].get('x-acs-accesskey-id') + assert 'token' == request['headers'].get('x-acs-security-token') + assert None is not request['headers'].get('x-acs-date') + assert None is not request['headers'].get('x-acs-signature-nonce') + assert None is not request['headers'].get('x-acs-content-sha256') + + assert None is not re.match( + 'ACS3-HMAC-SHA256 Credential=ak,SignedHeaders=accept;content-type;extends-key;for-test;global-key;' + + 'host;user-agent;x-acs-accesskey-id;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-security-token;' + + 'x-acs-signature-nonce;x-acs-version,Signature=.+', request['headers'].get('Authorization')) + assert None is not re.match('AlibabaCloud.+TeaDSL/1 config.userAgent', request['headers'].get('user-agent')) + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/x-www-form-urlencoded', 'expected application/x-www-form-urlencoded but received Content-Type: {}'.format( + content_type) + + responseHeaders = {'x-acs-request-id': 'A45EE076-334D-5012-9746-A8F828D20FD4'} + m.post('http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True', + body=responseBody, + status=200, + headers=responseHeaders, + callback=request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('test', result.get('body').get('AppId')) + self.assertEqual('test', result.get('body').get('ClassId')) + self.assertEqual(123, result.get('body').get('UserId')) + self.assertEqual(200, result.get('statusCode')) + + # bearer token + config = self.create_bearer_token_config() + config.protocol = 'HTTP' + config.endpoint = 'test1.aliyuncs.com' + client = OpenApiClient(config) + + def bearer_request_callback(url, **request): + assert 'http://test1.aliyuncs.com/test?key1=value&key2=1&key3=True' == str(url) + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert 'application/json' == request['headers'].get('accept') + assert 'token' == request['headers'].get('x-acs-bearer-token') + assert 'BEARERTOKEN' == request['headers'].get('x-acs-signature-type') + # assert 'bearer token' == request.headers.get('authorization') + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/x-www-form-urlencoded', 'expected application/x-www-form-urlencoded but received Content-Type: {}'.format( + content_type) + + m.post('http://test1.aliyuncs.com/test?key1=value&key2=1&key3=True', + body=responseBody, + status=200, + headers=responseHeaders, + callback=bearer_request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual(200, result.get('statusCode')) + @httpretty.activate(allow_net_connect=False) def test_call_api_for_roawith_v3sign_anonymous_json(self): requestBody = '{"key1":"value","key2":1,"key3":true}' @@ -798,6 +1452,66 @@ def request_callback(request: HTTPrettyRequest, uri: str, headers: dict): self.assertEqual(123, result.get('body').get('UserId')) self.assertEqual(200, result.get('statusCode')) + @aioresponses() + def test_call_api_for_roawith_v3sign_anonymous_json_async(self, m): + requestBody = '{"key1":"value","key2":1,"key3":true}' + responseBody = '{"AppId":"test", "ClassId":"test", "UserId":123}' + config = self.create_config() + runtime = self.create_runtime_options() + config.protocol = 'HTTP' + config.endpoint = 'test.aliyuncs.com' + client = OpenApiClient(config) + request = self.create_open_api_request() + params = open_api_models.Params( + action='TestAPI', + version='2022-06-01', + protocol='HTTPS', + pathname='/test', + method='POST', + auth_type='Anonymous', + style='ROA', + req_body_type='json', + body_type='json' + ) + + def request_callback(url, **request): + assert 'http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True' == str(url) + assert 'sdk' == request['headers'].get('for-test') + assert 'global-value' == request['headers'].get('global-key') + assert 'extends-value' == request['headers'].get('extends-key') + assert 'test.aliyuncs.com' == request['headers'].get('host') + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert 'application/json' == request['headers'].get('accept') + assert None is not request['headers'].get('x-acs-date') + assert None is not request['headers'].get('x-acs-signature-nonce') + assert None is not request['headers'].get('x-acs-content-sha256') + + assert None is not re.match('AlibabaCloud.+TeaDSL/1 config.userAgent', request['headers'].get('user-agent')) + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/json; charset=utf-8', 'expected application/json but received Content-Type: {}'.format( + content_type) + + responseHeaders = {'x-acs-request-id': 'A45EE076-334D-5012-9746-A8F828D20FD4'} + m.post('http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True', + body=responseBody, + status=200, + headers=responseHeaders, + callback=request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('test', result.get('body').get('AppId')) + self.assertEqual('test', result.get('body').get('ClassId')) + self.assertEqual(123, result.get('body').get('UserId')) + self.assertEqual(200, result.get('statusCode')) + @httpretty.activate(allow_net_connect=False) def test_response_body_type(self): requestBody = 'key1=value&key2=1&key3=True' @@ -915,8 +1629,176 @@ def request_callback(request: HTTPrettyRequest, uri: str, headers: dict): self.assertEqual('error code', e.code) self.assertEqual(0, e.accessDeniedDetail['test']) + @aioresponses() + def test_response_body_type_async(self, m): + requestBody = 'key1=value&key2=1&key3=True' + config = self.create_config() + runtime = self.create_runtime_options() + config.protocol = 'HTTP' + config.endpoint = 'test.aliyuncs.com' + client = OpenApiClient(config) + request = self.create_open_api_request() + request.headers['type'] = 'json' + params = open_api_models.Params( + action='TestAPI', + version='2022-06-01', + protocol='HTTPS', + pathname='/test', + method='POST', + auth_type='AK', + style='ROA', + req_body_type='formData', + body_type='json' + ) + + def request_callback(url, **request): + assert 'http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True' == str(url) + assert 'sdk' == request['headers'].get('for-test') + assert 'global-value' == request['headers'].get('global-key') + assert 'extends-value' == request['headers'].get('extends-key') + assert 'test.aliyuncs.com' == request['headers'].get('host') + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert 'application/json' == request['headers'].get('accept') + assert 'ak' == request['headers'].get('x-acs-accesskey-id') + assert 'token' == request['headers'].get('x-acs-security-token') + assert None is not request['headers'].get('x-acs-date') + assert None is not request['headers'].get('x-acs-signature-nonce') + assert None is not request['headers'].get('x-acs-content-sha256') + + assert None is not re.match('AlibabaCloud.+TeaDSL/1 config.userAgent', request['headers'].get('user-agent')) + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/x-www-form-urlencoded', 'expected application/x-www-form-urlencoded but received Content-Type: {}'.format( + content_type) + + responseHeaders = {'x-acs-request-id': 'A45EE076-334D-5012-9746-A8F828D20FD4'} + m.post('http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True', + body='{"AppId":"test", "ClassId":"test", "UserId":123}', + status=200, + headers=responseHeaders, + callback=request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('test', result.get('body').get('AppId')) + self.assertEqual('test', result.get('body').get('ClassId')) + self.assertEqual(123, result.get('body').get('UserId')) + self.assertEqual(200, result.get('statusCode')) + + m.post('http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True', + body='["AppId", "ClassId", "UserId"]', + status=200, + headers=responseHeaders, + callback=request_callback) + + params.body_type = 'array' + request.headers.update({'type': 'array'}) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('AppId', result.get('body')[0]) + self.assertEqual('ClassId', result.get('body')[1]) + self.assertEqual('UserId', result.get('body')[2]) + self.assertEqual(200, result.get('statusCode')) + + m.post('http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True', + body='["AppId", "ClassId", "UserId"]', + status=200, + headers=responseHeaders, + callback=request_callback) + params.body_type = 'string' + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('["AppId", "ClassId", "UserId"]', result.get('body')) + self.assertEqual(200, result.get('statusCode')) + + m.post('http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True', + body='["AppId", "ClassId", "UserId"]', + status=200, + headers=responseHeaders, + callback=request_callback) + params.body_type = 'byte' + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('["AppId", "ClassId", "UserId"]', result.get('body').decode('utf-8')) + self.assertEqual(200, result.get('statusCode')) + + m.post('http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True', + body='{"Code":"error code", "Message":"error message", ' + '"RequestId":"A45EE076-334D-5012-9746-A8F828D20FD4", ' + '"Description":"error description", "AccessDeniedDetail":{}}', + status=400, + headers=responseHeaders, + callback=request_callback) + request.headers.update({'type': 'error'}) + + try: + loop.run_until_complete(client.call_api_async(params, request, runtime)) + assert False + except TeaException as e: + self.assertEqual('code: 400, error message request id: A45EE076-334D-5012-9746-A8F828D20FD4', e.message) + self.assertEqual('error code', e.code) + self.assertFalse('test' in e.accessDeniedDetail) + + m.post('http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True', + body='{"Code":"error code", "Message":"error message", ' + '"RequestId":"A45EE076-334D-5012-9746-A8F828D20FD4", ' + '"Description":"error description", "AccessDeniedDetail":{}, "accessDeniedDetail":{"test": 0}}', + status=400, + headers=responseHeaders, + callback=request_callback) + request.headers.update({'type': 'error1'}) + + try: + loop.run_until_complete(client.call_api_async(params, request, runtime)) + assert False + except TeaException as e: + self.assertEqual('code: 400, error message request id: A45EE076-334D-5012-9746-A8F828D20FD4', e.message) + self.assertEqual('error code', e.code) + self.assertFalse('test' in e.accessDeniedDetail) + + m.post('http://test.aliyuncs.com/test?global-query=global-value&key1=value&key2=1&key3=True', + body='{"Code":"error code", "Message":"error message", ' + '"RequestId":"A45EE076-334D-5012-9746-A8F828D20FD4", ' + '"Description":"error description", "accessDeniedDetail":{"test": 0}}', + status=400, + headers=responseHeaders, + callback=request_callback) + request.headers.update({'type': 'error2'}) + + try: + loop.run_until_complete(client.call_api_async(params, request, runtime)) + assert False + except TeaException as e: + self.assertEqual('code: 400, error message request id: A45EE076-334D-5012-9746-A8F828D20FD4', e.message) + self.assertEqual('error code', e.code) + self.assertEqual(0, e.accessDeniedDetail['test']) + @httpretty.activate(allow_net_connect=False) - def test_response_body_type(self): + def test_request_body_type(self): config = self.create_config() runtime = self.create_runtime_options() config.protocol = 'HTTP' @@ -941,12 +1823,15 @@ def test_response_body_type(self): request = open_api_models.OpenApiRequest( body=OpenApiUtilClient.parse_to_map(body) ) + def request_callback_1(request: HTTPrettyRequest, uri: str, headers: dict): content_type = request.headers.get('content-type') - assert request.body.decode('utf-8') == 'key1=value&key2=1&key3=True', 'unexpected body: {}'.format(request.body) + assert request.body.decode('utf-8') == 'key1=value&key2=1&key3=True', 'unexpected body: {}'.format( + request.body) assert content_type == 'application/x-www-form-urlencoded', 'expected application/x-www-form-urlencoded but received Content-Type: {}'.format( content_type) return [200, headers, '{"AppId":"test", "ClassId":"test", "UserId":123}'] + httpretty.register_uri( httpretty.POST, "http://test.aliyuncs.com/test1", body=request_callback_1) @@ -956,12 +1841,15 @@ def request_callback_1(request: HTTPrettyRequest, uri: str, headers: dict): # json params.pathname = '/test2' params.req_body_type = 'json' + def request_callback_2(request: HTTPrettyRequest, uri: str, headers: dict): content_type = request.headers.get('content-type') - assert request.body.decode('utf-8') == '{"key1":"value","key2":1,"key3":true}', 'unexpected body: {}'.format(request.body) + assert request.body.decode( + 'utf-8') == '{"key1":"value","key2":1,"key3":true}', 'unexpected body: {}'.format(request.body) assert content_type == 'application/json; charset=utf-8', 'expected application/json but received Content-Type: {}'.format( content_type) return [200, headers, '{"AppId":"test", "ClassId":"test", "UserId":123}'] + httpretty.register_uri( httpretty.POST, "http://test.aliyuncs.com/test2", body=request_callback_2) @@ -975,12 +1863,14 @@ def request_callback_2(request: HTTPrettyRequest, uri: str, headers: dict): request = open_api_models.OpenApiRequest( body=byte_body ) + def request_callback_3(request: HTTPrettyRequest, uri: str, headers: dict): content_type = request.headers.get('content-type') assert request.body == UtilClient.to_bytes('test byte'), 'unexpected body: {}'.format(request.body) assert content_type is None, 'expected text/plain but received Content-Type: {}'.format( content_type) return [200, headers, '{"AppId":"test", "ClassId":"test", "UserId":123}'] + httpretty.register_uri( httpretty.POST, "http://test.aliyuncs.com/test3", body=request_callback_3) @@ -993,16 +1883,266 @@ def request_callback_3(request: HTTPrettyRequest, uri: str, headers: dict): request = open_api_models.OpenApiRequest( stream=byte_body ) + def request_callback_4(request: HTTPrettyRequest, uri: str, headers: dict): content_type = request.headers.get('content-type') - print(request) assert request.body.decode('utf-8') == 'test byte', 'unexpected body: {}'.format(request.body) assert content_type == 'application/octet-stream', 'expected application/octet-stream but received Content-Type: {}'.format( content_type) return [200, headers, '{"AppId":"test", "ClassId":"test", "UserId":123}'] + httpretty.register_uri( httpretty.POST, "http://test.aliyuncs.com/test4", body=request_callback_4) result = client.call_api(params, request, runtime) self.assertEqual(200, result.get('statusCode')) + @aioresponses() + def test_request_body_type_async(self, m): + config = self.create_config() + runtime = self.create_runtime_options() + config.protocol = 'HTTP' + config.endpoint = 'test.aliyuncs.com' + client = OpenApiClient(config) + # formData + params = open_api_models.Params( + action='TestAPI', + version='2022-06-01', + protocol='HTTPS', + pathname='/test1', + method='POST', + auth_type='AK', + style='ROA', + req_body_type='formData', + body_type='json' + ) + body = {} + body['key1'] = 'value' + body['key2'] = 1 + body['key3'] = True + request = open_api_models.OpenApiRequest( + body=OpenApiUtilClient.parse_to_map(body) + ) + + def request_callback_1(url, **request): + assert 'http://test.aliyuncs.com/test1?global-query=global-value' == str(url) + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == 'key1=value&key2=1&key3=True', 'unexpected body: {}'.format( + request['data']) + assert content_type == 'application/x-www-form-urlencoded', 'expected application/x-www-form-urlencoded but received Content-Type: {}'.format( + content_type) + + m.post('http://test.aliyuncs.com/test1?global-query=global-value', + body='{"AppId":"test", "ClassId":"test", "UserId":123}', + status=200, + callback=request_callback_1) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual(200, result.get('statusCode')) + + # json + params.pathname = '/test2' + params.req_body_type = 'json' + + def request_callback_2(url, **request): + assert 'http://test.aliyuncs.com/test2?global-query=global-value' == str(url) + content_type = request['headers'].get('content-type') + assert request['data'].decode( + 'utf-8') == '{"key1":"value","key2":1,"key3":true}', 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/json; charset=utf-8', 'expected application/json but received Content-Type: {}'.format( + content_type) + + m.post('http://test.aliyuncs.com/test2?global-query=global-value', + body='{"AppId":"test", "ClassId":"test", "UserId":123}', + status=200, + callback=request_callback_2) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual(200, result.get('statusCode')) + + # byte + params.pathname = '/test3' + params.req_body_type = 'byte' + byte_body = UtilClient.to_bytes('test byte') + request = open_api_models.OpenApiRequest( + body=byte_body + ) + + def request_callback_3(url, **request): + assert 'http://test.aliyuncs.com/test3?global-query=global-value' == str(url) + content_type = request['headers'].get('content-type') + assert request['data'] == UtilClient.to_bytes('test byte'), 'unexpected body: {}'.format(request['data']) + assert content_type is None, 'expected text/plain but received Content-Type: {}'.format( + content_type) + + m.post('http://test.aliyuncs.com/test3?global-query=global-value', + body='{"AppId":"test", "ClassId":"test", "UserId":123}', + status=200, + callback=request_callback_3) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual(200, result.get('statusCode')) + + # stream + params.pathname = '/test4' + params.req_body_type = 'binary' + request = open_api_models.OpenApiRequest( + stream=byte_body + ) + + def request_callback_4(url, **request): + assert 'http://test.aliyuncs.com/test4?global-query=global-value' == str(url) + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == 'test byte', 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/octet-stream', 'expected application/octet-stream but received Content-Type: {}'.format( + content_type) + + m.post('http://test.aliyuncs.com/test4?global-query=global-value', + body='{"AppId":"test", "ClassId":"test", "UserId":123}', + status=200, + callback=request_callback_4) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.call_api_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual(200, result.get('statusCode')) + + @httpretty.activate + def test_execute(self): + requestBody = '{"key1":"value","key2":1,"key3":true}' + responseBody = '{"AppId":"test", "ClassId":"test", "UserId":123}' + config = self.create_config() + runtime = self.create_runtime_options() + config.protocol = 'HTTP' + config.endpoint = 'test.aliyuncs.com' + client = OpenApiClient(config) + client._product_id = 'test' + gateway_client = PopClient() + client.set_gateway_client(gateway_client) + request = self.create_open_api_request() + params = open_api_models.Params( + action='TestAPI', + version='2022-06-01', + protocol='HTTPS', + pathname='/', + method='POST', + auth_type='Anonymous', + style='RPC', + req_body_type='json', + body_type='json' + ) + + def request_callback(request: HTTPrettyRequest, uri: str, headers: dict): + assert 'value' == request.querystring['key1'][0] + assert '1' == request.querystring['key2'][0] + assert 'True' == request.querystring['key3'][0] + assert 'global-value' == request.querystring['global-query'][0] + assert 'sdk' == request.headers.get('for-test') + assert 'global-value' == request.headers.get('global-key') + assert 'extends-value' == request.headers.get('extends-key') + assert 'test.aliyuncs.com' == request.headers.get('host') + assert '2022-06-01' == request.headers.get('x-acs-version') + assert 'TestAPI' == request.headers.get('x-acs-action') + assert 'application/json' == request.headers.get('accept') + assert None is not request.headers.get('x-acs-date') + assert None is not request.headers.get('x-acs-signature-nonce') + assert None is not request.headers.get('x-acs-content-sha256') + + assert None is not re.match('AlibabaCloud.+TeaDSL/1 config.userAgent', request.headers.get('user-agent')) + content_type = request.headers.get('content-type') + assert request.body.decode('utf-8') == requestBody, 'unexpected body: {}'.format(request.body) + assert content_type == 'application/json; charset=utf-8', 'expected application/json but received Content-Type: {}'.format( + content_type) + headers['x-acs-request-id'] = 'A45EE076-334D-5012-9746-A8F828D20FD4' + return [200, headers, responseBody] + + httpretty.register_uri( + httpretty.POST, "http://test.aliyuncs.com", + body=request_callback) + result = client.execute(params, request, runtime) + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('test', result.get('body').get('AppId')) + self.assertEqual('test', result.get('body').get('ClassId')) + self.assertEqual(123, result.get('body').get('UserId')) + self.assertEqual(200, result.get('statusCode')) + + @aioresponses() + def test_execute_async(self, m): + requestBody = '{"key1":"value","key2":1,"key3":true}' + responseBody = '{"AppId":"test", "ClassId":"test", "UserId":123}' + config = self.create_config() + runtime = self.create_runtime_options() + config.protocol = 'HTTP' + config.endpoint = 'test.aliyuncs.com' + client = OpenApiClient(config) + client._product_id = 'test' + gateway_client = PopClient() + client.set_gateway_client(gateway_client) + request = self.create_open_api_request() + params = open_api_models.Params( + action='TestAPI', + version='2022-06-01', + protocol='HTTPS', + pathname='/', + method='POST', + auth_type='Anonymous', + style='RPC', + req_body_type='json', + body_type='json' + ) + + def request_callback(url, **request): + assert 'http://test.aliyuncs.com/?global-query=global-value&key1=value&key2=1&key3=True' == str(url) + assert 'sdk' == request['headers'].get('for-test') + assert 'global-value' == request['headers'].get('global-key') + assert 'extends-value' == request['headers'].get('extends-key') + assert 'test.aliyuncs.com' == request['headers'].get('host') + assert '2022-06-01' == request['headers'].get('x-acs-version') + assert 'TestAPI' == request['headers'].get('x-acs-action') + assert 'application/json' == request['headers'].get('accept') + assert None is not request['headers'].get('x-acs-date') + assert None is not request['headers'].get('x-acs-signature-nonce') + assert None is not request['headers'].get('x-acs-content-sha256') + + assert None is not re.match('AlibabaCloud.+TeaDSL/1 config.userAgent', request['headers'].get('user-agent')) + content_type = request['headers'].get('content-type') + assert request['data'].decode('utf-8') == requestBody, 'unexpected body: {}'.format(request['data']) + assert content_type == 'application/json; charset=utf-8', 'expected application/json but received Content-Type: {}'.format( + content_type) + + responseHeaders = {'x-acs-request-id': 'A45EE076-334D-5012-9746-A8F828D20FD4'} + m.post('http://test.aliyuncs.com/?global-query=global-value&key1=value&key2=1&key3=True', + body=responseBody, + status=200, + headers=responseHeaders, + callback=request_callback) + + loop = asyncio.get_event_loop() + task = asyncio.ensure_future( + client.execute_async(params, request, runtime) + ) + loop.run_until_complete(task) + result = task.result() + self.assertEqual('A45EE076-334D-5012-9746-A8F828D20FD4', result.get("headers").get("x-acs-request-id")) + self.assertEqual('test', result.get('body').get('AppId')) + self.assertEqual('test', result.get('body').get('ClassId')) + self.assertEqual(123, result.get('body').get('UserId')) + self.assertEqual(200, result.get('statusCode')) diff --git a/python/tests/test_models.py b/python/tests/test_models.py new file mode 100644 index 0000000..b1bac55 --- /dev/null +++ b/python/tests/test_models.py @@ -0,0 +1,333 @@ +import unittest +from io import BytesIO +from alibabacloud_tea_openapi.models import GlobalParameters, Config, OpenApiRequest, Params +from alibabacloud_credentials.client import Client as CredentialClient +from alibabacloud_credentials import models as credential_models +from Tea.exceptions import RequiredArgumentException + + +class TestGlobalParameters(unittest.TestCase): + + def test_initialization(self): + params = GlobalParameters() + self.assertIsNone(params.headers) + self.assertIsNone(params.queries) + headers = {"Content-Type": "application/json"} + queries = {"test": "value"} + params = GlobalParameters(headers=headers, queries=queries) + self.assertEqual(params.headers, headers) + self.assertEqual(params.queries, queries) + + def test_to_from_map(self): + headers = {"header_key": "header_value"} + queries = {"query_key": "query_value"} + params = GlobalParameters(headers=headers, queries=queries) + map_data = params.to_map() + self.assertIn('headers', map_data) + self.assertIn('queries', map_data) + self.assertEqual(map_data['headers'], headers) + self.assertEqual(map_data['queries'], queries) + from_params = GlobalParameters() + from_params.from_map(map_data) + self.assertEqual(from_params.headers, headers) + self.assertEqual(from_params.queries, queries) + + def test_validate(self): + params = GlobalParameters() + params.validate() + + +class TestConfig(unittest.TestCase): + + def setUp(self): + self.global_params = GlobalParameters() + self.credential_client = CredentialClient(credential_models.Config( + bearer_token='token', + type='bearer' + )) + + def test_initialization(self): + config = Config( + access_key_id='ak', + access_key_secret='secret', + security_token='token', + bearer_token='token', + type='sts', + endpoint='config.endpoint', + endpoint_type='config.endpointType', + network='config.network', + suffix='config.suffix', + protocol='config.protocol', + method='config.method', + region_id='config.regionId', + user_agent='config.userAgent', + read_timeout=3000, + connect_timeout=3000, + http_proxy='config.httpProxy', + https_proxy='config.httpsProxy', + no_proxy='config.noProxy', + socks_5proxy='config.socks5Proxy', + socks_5net_work='config.socks5NetWork', + max_idle_conns=128, + signature_version='config.signatureVersion', + signature_algorithm='config.signatureAlgorithm', + global_parameters=self.global_params, + key='config.key', + cert='config.cert', + ca='config.ca', + credential=self.credential_client, + disable_http_2=True, + open_platform_endpoint='config.openPlatformEndpoint', + ) + self.assertEqual(config.access_key_id, 'ak') + self.assertEqual(config.access_key_secret, 'secret') + self.assertEqual(config.security_token, 'token') + self.assertEqual(config.bearer_token, 'token') + self.assertEqual(config.type, 'sts') + self.assertEqual(config.endpoint, 'config.endpoint') + self.assertEqual(config.endpoint_type, 'config.endpointType') + self.assertEqual(config.network, 'config.network') + self.assertEqual(config.suffix, 'config.suffix') + self.assertEqual(config.protocol, 'config.protocol') + self.assertEqual(config.method, 'config.method') + self.assertEqual(config.region_id, 'config.regionId') + self.assertEqual(config.user_agent, 'config.userAgent') + self.assertEqual(config.read_timeout, 3000) + self.assertEqual(config.connect_timeout, 3000) + self.assertEqual(config.http_proxy, 'config.httpProxy') + self.assertEqual(config.https_proxy, 'config.httpsProxy') + self.assertEqual(config.no_proxy, 'config.noProxy') + self.assertEqual(config.socks_5proxy, 'config.socks5Proxy') + self.assertEqual(config.socks_5net_work, 'config.socks5NetWork') + self.assertEqual(config.max_idle_conns, 128) + self.assertEqual(config.signature_version, 'config.signatureVersion') + self.assertEqual(config.signature_algorithm, 'config.signatureAlgorithm') + self.assertEqual(config.global_parameters, self.global_params) + self.assertEqual(config.key, 'config.key') + self.assertEqual(config.cert, 'config.cert') + self.assertEqual(config.ca, 'config.ca') + self.assertEqual(config.credential, self.credential_client) + self.assertEqual(config.disable_http_2, True) + self.assertEqual(config.open_platform_endpoint, 'config.openPlatformEndpoint') + + def test_to_from_map(self): + config = Config( + access_key_id='ak', + access_key_secret='secret', + security_token='token', + bearer_token='token', + type='sts', + endpoint='config.endpoint', + endpoint_type='config.endpointType', + network='config.network', + suffix='config.suffix', + protocol='config.protocol', + method='config.method', + region_id='config.regionId', + user_agent='config.userAgent', + read_timeout=3000, + connect_timeout=3000, + http_proxy='config.httpProxy', + https_proxy='config.httpsProxy', + no_proxy='config.noProxy', + socks_5proxy='config.socks5Proxy', + socks_5net_work='config.socks5NetWork', + max_idle_conns=128, + signature_version='config.signatureVersion', + signature_algorithm='config.signatureAlgorithm', + global_parameters=self.global_params, + key='config.key', + cert='config.cert', + ca='config.ca', + credential=self.credential_client, + disable_http_2=True, + open_platform_endpoint='config.openPlatformEndpoint', + ) + map_data = config.to_map() + self.assertEqual('ak', map_data['accessKeyId']) + self.assertEqual('secret', map_data['accessKeySecret']) + self.assertEqual('token', map_data['securityToken']) + self.assertEqual('token', map_data['bearerToken']) + self.assertEqual('sts', map_data['type']) + self.assertEqual('config.endpoint', map_data['endpoint']) + self.assertEqual('config.endpointType', map_data['endpointType']) + self.assertEqual('config.network', map_data['network']) + self.assertEqual('config.suffix', map_data['suffix']) + self.assertEqual('config.protocol', map_data['protocol']) + self.assertEqual('config.method', map_data['method']) + self.assertEqual('config.regionId', map_data['regionId']) + self.assertEqual('config.userAgent', map_data['userAgent']) + self.assertEqual(3000, map_data['readTimeout']) + self.assertEqual(3000, map_data['connectTimeout']) + self.assertEqual('config.httpProxy', map_data['httpProxy']) + self.assertEqual('config.httpsProxy', map_data['httpsProxy']) + self.assertEqual('config.noProxy', map_data['noProxy']) + self.assertEqual('config.socks5Proxy', map_data['socks5Proxy']) + self.assertEqual('config.socks5NetWork', map_data['socks5NetWork']) + self.assertEqual(128, map_data['maxIdleConns']) + self.assertEqual('config.signatureVersion', map_data['signatureVersion']) + self.assertEqual('config.signatureAlgorithm', map_data['signatureAlgorithm']) + self.assertEqual({}, map_data['globalParameters']) + self.assertEqual('config.key', map_data['key']) + self.assertEqual('config.cert', map_data['cert']) + self.assertEqual('config.ca', map_data['ca']) + self.assertEqual(self.credential_client, map_data['credential']) + self.assertEqual(True, map_data['disableHttp2']) + self.assertEqual('config.openPlatformEndpoint', map_data['openPlatformEndpoint']) + config = Config() + config.from_map(map_data) + self.assertEqual(config.access_key_id, 'ak') + self.assertEqual(config.access_key_secret, 'secret') + self.assertEqual(config.security_token, 'token') + self.assertEqual(config.bearer_token, 'token') + self.assertEqual(config.type, 'sts') + self.assertEqual(config.endpoint, 'config.endpoint') + self.assertEqual(config.endpoint_type, 'config.endpointType') + self.assertEqual(config.network, 'config.network') + self.assertEqual(config.suffix, 'config.suffix') + self.assertEqual(config.protocol, 'config.protocol') + self.assertEqual(config.method, 'config.method') + self.assertEqual(config.region_id, 'config.regionId') + self.assertEqual(config.user_agent, 'config.userAgent') + self.assertEqual(config.read_timeout, 3000) + self.assertEqual(config.connect_timeout, 3000) + self.assertEqual(config.http_proxy, 'config.httpProxy') + self.assertEqual(config.https_proxy, 'config.httpsProxy') + self.assertEqual(config.no_proxy, 'config.noProxy') + self.assertEqual(config.socks_5proxy, 'config.socks5Proxy') + self.assertEqual(config.socks_5net_work, 'config.socks5NetWork') + self.assertEqual(config.max_idle_conns, 128) + self.assertEqual(config.signature_version, 'config.signatureVersion') + self.assertEqual(config.signature_algorithm, 'config.signatureAlgorithm') + self.assertIsNotNone(config.global_parameters) + self.assertEqual(config.key, 'config.key') + self.assertEqual(config.cert, 'config.cert') + self.assertEqual(config.ca, 'config.ca') + self.assertEqual(config.credential, self.credential_client) + self.assertEqual(config.disable_http_2, True) + self.assertEqual(config.open_platform_endpoint, 'config.openPlatformEndpoint') + + def test_validate(self): + config = Config() + config.validate() + config = Config(global_parameters=GlobalParameters()) + config.validate() + + +class TestOpenApiRequest(unittest.TestCase): + + def test_initialization(self): + f = BytesIO() + f.write(bytes('test', 'utf-8')) + f.seek(0) + request = OpenApiRequest( + headers={"Content-Type": "text/plain"}, + query={"test": "query"}, + body='test', + stream=f, + host_map={"test": "test"}, + endpoint_override='http://localhost:8080/api' + ) + self.assertEqual({"Content-Type": "text/plain"}, request.headers) + self.assertEqual({"test": "query"}, request.query) + self.assertEqual('test', request.body) + self.assertEqual(b'test', request.stream.read()) + self.assertEqual({"test": "test"}, request.host_map) + self.assertEqual('http://localhost:8080/api', request.endpoint_override) + + def test_to_from_map(self): + f = BytesIO() + f.write(bytes('test', 'utf-8')) + f.seek(0) + request = OpenApiRequest( + headers={"Content-Type": "text/plain"}, + query={"test": "query"}, + body='test', + stream=f, + host_map={"test": "test"}, + endpoint_override='http://localhost:8080/api' + ) + map_data = request.to_map() + self.assertEqual('query', map_data['query']['test']) + self.assertEqual('text/plain', map_data['headers']['Content-Type']) + self.assertEqual('test', map_data['body']) + self.assertEqual(b'test', map_data['stream'].read()) + self.assertEqual({"test": "test"}, map_data['hostMap']) + self.assertEqual('http://localhost:8080/api', map_data['endpointOverride']) + request = OpenApiRequest() + request.from_map(map_data) + self.assertEqual({"Content-Type": "text/plain"}, request.headers) + self.assertEqual({"test": "query"}, request.query) + self.assertEqual('test', request.body) + self.assertEqual({"test": "test"}, request.host_map) + self.assertEqual('http://localhost:8080/api', request.endpoint_override) + + def test_validate(self): + request = OpenApiRequest() + request.validate() + + +class TestParams(unittest.TestCase): + + def test_initialization_and_validation(self): + params = Params() + with self.assertRaises(RequiredArgumentException): + params.validate() + + params = Params( + action="action", + version="version", + protocol="protocol", + pathname="pathname", + method="method", + auth_type="auth_type", + body_type="body_type", + req_body_type="req_body_type", + style='style' + ) + params.validate() + self.assertEqual("action", params.action) + self.assertEqual("version", params.version) + self.assertEqual("protocol", params.protocol) + self.assertEqual("pathname", params.pathname) + self.assertEqual("method", params.method) + self.assertEqual("auth_type", params.auth_type) + self.assertEqual("body_type", params.body_type) + self.assertEqual("req_body_type", params.req_body_type) + self.assertEqual("style", params.style) + + def test_to_from_map(self): + params = Params( + action="action", + version="version", + protocol="protocol", + pathname="pathname", + method="method", + auth_type="auth_type", + body_type="body_type", + req_body_type="req_body_type", + style='style' + ) + + map_data = params.to_map() + self.assertEqual('action', map_data['action']) + self.assertEqual('version', map_data['version']) + self.assertEqual('protocol', map_data['protocol']) + self.assertEqual('pathname', map_data['pathname']) + self.assertEqual('method', map_data['method']) + self.assertEqual('auth_type', map_data['authType']) + self.assertEqual('body_type', map_data['bodyType']) + self.assertEqual('req_body_type', map_data['reqBodyType']) + self.assertEqual('style', map_data['style']) + + params = Params() + params.from_map(map_data) + self.assertEqual("action", params.action) + self.assertEqual("version", params.version) + self.assertEqual("protocol", params.protocol) + self.assertEqual("pathname", params.pathname) + self.assertEqual("method", params.method) + self.assertEqual("auth_type", params.auth_type) + self.assertEqual("body_type", params.body_type) + self.assertEqual("req_body_type", params.req_body_type) + self.assertEqual("style", params.style)