def test_put_object(self):
        url = 'http://127.0.0.1:8888'
        with open('test.txt', 'rb') as f:
            Client.put_object(f, {'expected': 'success'}, url)

        with open('test.txt', 'rb') as f:
            try:
                Client.put_object(f, {'expected': 'fail'}, url)
                assert False
            except TeaException as e:
                self.assertEqual('NoSuchKey', e.code)
                self.assertEqual(400, e.data['httpCode'])
    def test_has_error(self):
        res = {'test': 'ok'}
        resp = Client.has_error(res)
        self.assertFalse(resp)

        res = {"result_code": "OK"}
        resp = Client.has_error(res)
        self.assertFalse(resp)

        res = {
            'response': {
                "result_code": "success"
            }
        }
        resp = Client.has_error(res)
        self.assertTrue(resp)
    def test_parse_upload_headers(self):
        res = Client.parse_upload_headers(12)
        self.assertEqual({}, res)

        res = Client.parse_upload_headers('{"test":"ok"}')
        self.assertEqual({}, res)

        res = Client.parse_upload_headers([
            {
                "name": "content-type",
                "value": "text",
            },
            {
                "name": "content-md5",
                "value": "md5value",
            },
        ])
        self.assertEqual('text', res['content-type'])
        self.assertEqual('md5value', res['content-md5'])
    def test_has_error(self):
        tmp = 'testInvalidJson'
        resp = Client.has_error(tmp, 'secret', 'ok')
        self.assertTrue(resp)

        tmp = '{"noResponse":"true"}'
        resp = Client.has_error(tmp, 'secret', 'ok')
        self.assertTrue(resp)

        tmp = '{"response":{"expired_time":"2021-01-04T17:04:42.072+08:00","file_id":"kjiac1a298f8d","req_msg_id":' \
              '"79e093b3ae0f3f2c1","result_code":"false"},"sign":"IUl/4uLq7utFnsjF1Zy6B6OWbCg="}'
        resp = Client.has_error(tmp, 'secret', 'ok')
        self.assertTrue(resp)

        tmp = '{"response":{"expired_time":"2021-01-04T17:04:42.072+08:00","file_id":"kjiac1a298f8d","req_msg_id":' \
              '"79e093b3ae0f3f2c1","result_code":"OK"}}'
        resp = Client.has_error(tmp, 'secret', 'success')
        self.assertTrue(resp)

        tmp = '{"response":{"expired_time":"2021-01-04T17:04:42.072+08:00","file_id":"kjiac1a298f8d","req_msg_id":' \
              '"79e093b3ae0f3f2c1","result_code":"OK"},"sign":"IUl/4uLq7utFnsjF1Zy6B6OWbCg="}'
        resp = Client.has_error(tmp, 'secret', 'ok')
        self.assertFalse(resp)

        tmp = '{"response":{"expired_time":"2021-01-04T17:04:42.072+08:00","file_id":"kjiac1a298f8d","req_msg_id":' \
              '"79e093b3ae0f3f2c1","result_code":"OK"},"sign":"IUl/4uLqtFnsjF1Zy6B6OWbCg="}'
        resp = Client.has_error(tmp, 'secret', 'ok')
        self.assertTrue(resp)
 def test_get_timestamp(self):
     timestamp = Client.get_timestamp()
     self.assertEqual(20, len(timestamp))
 def test_get_signature(self):
     params = {
         'test': 'ok'
     }
     signature = Client.get_signature(params, 'secret')
     self.assertEqual('qlB4B1lFcehlWRelL7Fo4uNHPCs=', signature)
Esempio n. 7
0
    def do_request(self, version, action, protocol, method, pathname, request, runtime):
        """
        Encapsulate the request and invoke the network

        :type action: str
        :param action: api name

        :type protocol: str
        :param protocol: http or https

        :type method: str
        :param method: e.g. GET

        :type pathname: str
        :param pathname: pathname of every api

        :type request: dict
        :param request: which contains request params

        :param runtime: which controls some details of call api, such as retry times

        :return: the response
        """
        runtime.validate()
        _runtime = {
            "timeouted": "retry",
            "readTimeout": UtilClient.default_number(runtime.read_timeout, self._read_timeout),
            "connectTimeout": UtilClient.default_number(runtime.connect_timeout, self._connect_timeout),
            "httpProxy": UtilClient.default_string(runtime.http_proxy, self._http_proxy),
            "httpsProxy": UtilClient.default_string(runtime.https_proxy, self._https_proxy),
            "noProxy": UtilClient.default_string(runtime.no_proxy, self._no_proxy),
            "maxIdleConns": UtilClient.default_number(runtime.max_idle_conns, self._max_idle_conns),
            "retry": {
                "retryable": runtime.autoretry,
                "maxAttempts": UtilClient.default_number(runtime.max_attempts, 3)
            },
            "backoff": {
                "policy": UtilClient.default_string(runtime.backoff_policy, "no"),
                "period": UtilClient.default_number(runtime.backoff_period, 1)
            },
            "ignoreSSL": runtime.ignore_ssl
        }
        _last_request = None
        _last_exception = None
        _now = time.time()
        _retry_times = 0
        while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
            if _retry_times > 0:
                _backoff_time = TeaCore.get_backoff_time(_runtime.get('backoff'), _retry_times)
                if _backoff_time > 0:
                    TeaCore.sleep(_backoff_time)
            _retry_times = _retry_times + 1
            try:
                _request = TeaRequest()
                _request.protocol = UtilClient.default_string(self._protocol, protocol)
                _request.method = method
                _request.pathname = pathname
                _request.query = {
                    "method": action,
                    "version": version,
                    "sign_type": "HmacSHA1",
                    "req_time": AlipayUtilClient.get_timestamp(),
                    "req_msg_id": UtilClient.get_nonce(),
                    "access_key": self._access_key_id,
                    "charset": "UTF-8",
                    "baseSdkVersion": "Tea-SDK",
                    "sdkVersion": "Tea-SDK-20200804"
                }
                if not UtilClient.empty(self._security_token):
                    _request.query["security_token"] = self._security_token
                _request.headers = {
                    "host": self._endpoint,
                    "user-agent": self.get_user_agent()
                }
                tmp = UtilClient.anyify_map_value(RPCUtilClient.query(request))
                _request.body = UtilClient.to_form_string(tmp)
                _request.headers["content-type"] = "application/x-www-form-urlencoded"
                signed_param = TeaCore.merge(_request.query,
                    RPCUtilClient.query(request))
                _request.query["sign"] = AlipayUtilClient.get_signature(signed_param, self._access_key_secret)
                _last_request = _request
                _response = TeaCore.do_action(_request, _runtime)
                obj = UtilClient.read_as_json(_response.body)
                res = UtilClient.assert_as_map(obj)
                resp = UtilClient.assert_as_map(res.get('response'))
                if AlipayUtilClient.has_error(res):
                    raise TeaException({
                        "message": resp.get('result_msg'),
                        "data": resp,
                        "code": resp.get('result_code')
                    })
                return resp
            except Exception as e:
                if TeaCore.is_retryable(e):
                    _last_exception = e
                    continue
                raise e
        raise UnretryableException(_last_request, _last_exception)
Esempio n. 8
0
 def do_request(
     self,
     version: str,
     action: str,
     protocol: str,
     method: str,
     pathname: str,
     request: dict,
     headers: Dict[str, str],
     runtime: util_models.RuntimeOptions,
 ) -> dict:
     """
     Encapsulate the request and invoke the network
     @param action: api name
     @param protocol: http or https
     @param method: e.g. GET
     @param pathname: pathname of every api
     @param request: which contains request params
     @param runtime: which controls some details of call api, such as retry times
     @return: the response
     """
     runtime.validate()
     _runtime = {
         'timeouted':
         'retry',
         'readTimeout':
         UtilClient.default_number(runtime.read_timeout,
                                   self._read_timeout),
         'connectTimeout':
         UtilClient.default_number(runtime.connect_timeout,
                                   self._connect_timeout),
         'httpProxy':
         UtilClient.default_string(runtime.http_proxy, self._http_proxy),
         'httpsProxy':
         UtilClient.default_string(runtime.https_proxy, self._https_proxy),
         'noProxy':
         UtilClient.default_string(runtime.no_proxy, self._no_proxy),
         'maxIdleConns':
         UtilClient.default_number(runtime.max_idle_conns,
                                   self._max_idle_conns),
         'maxIdleTimeMillis':
         self._max_idle_time_millis,
         'keepAliveDurationMillis':
         self._keep_alive_duration_millis,
         'maxRequests':
         self._max_requests,
         'maxRequestsPerHost':
         self._max_requests_per_host,
         'retry': {
             'retryable': runtime.autoretry,
             'maxAttempts':
             UtilClient.default_number(runtime.max_attempts, 3)
         },
         'backoff': {
             'policy': UtilClient.default_string(runtime.backoff_policy,
                                                 'no'),
             'period': UtilClient.default_number(runtime.backoff_period, 1)
         },
         'ignoreSSL':
         runtime.ignore_ssl,
         # 银行卡信息
     }
     _last_request = None
     _last_exception = None
     _now = time.time()
     _retry_times = 0
     while TeaCore.allow_retry(_runtime.get('retry'), _retry_times, _now):
         if _retry_times > 0:
             _backoff_time = TeaCore.get_backoff_time(
                 _runtime.get('backoff'), _retry_times)
             if _backoff_time > 0:
                 TeaCore.sleep(_backoff_time)
         _retry_times = _retry_times + 1
         try:
             _request = TeaRequest()
             _request.protocol = UtilClient.default_string(
                 self._protocol, protocol)
             _request.method = method
             _request.pathname = pathname
             _request.query = {
                 'method': action,
                 'version': version,
                 'sign_type': 'HmacSHA1',
                 'req_time': AntchainUtilClient.get_timestamp(),
                 'req_msg_id': AntchainUtilClient.get_nonce(),
                 'access_key': self._access_key_id,
                 'base_sdk_version': 'TeaSDK-2.0',
                 'sdk_version': '1.0.7'
             }
             if not UtilClient.empty(self._security_token):
                 _request.query['security_token'] = self._security_token
             _request.headers = TeaCore.merge(
                 {
                     'host':
                     UtilClient.default_string(
                         self._endpoint, 'openapi.antchain.antgroup.com'),
                     'user-agent':
                     UtilClient.get_user_agent(self._user_agent)
                 }, headers)
             tmp = UtilClient.anyify_map_value(RPCUtilClient.query(request))
             _request.body = UtilClient.to_form_string(tmp)
             _request.headers[
                 'content-type'] = 'application/x-www-form-urlencoded'
             signed_param = TeaCore.merge(_request.query,
                                          RPCUtilClient.query(request))
             _request.query['sign'] = AntchainUtilClient.get_signature(
                 signed_param, self._access_key_secret)
             _last_request = _request
             _response = TeaCore.do_action(_request, _runtime)
             raw = UtilClient.read_as_string(_response.body)
             obj = UtilClient.parse_json(raw)
             res = UtilClient.assert_as_map(obj)
             resp = UtilClient.assert_as_map(res.get('response'))
             if AntchainUtilClient.has_error(raw, self._access_key_secret):
                 raise TeaException({
                     'message': resp.get('result_msg'),
                     'data': resp,
                     'code': resp.get('result_code')
                 })
             return resp
         except Exception as e:
             if TeaCore.is_retryable(e):
                 _last_exception = e
                 continue
             raise e
     raise UnretryableException(_last_request, _last_exception)
 def test_get_nonce(self):
     self.assertEqual(32, len(Client.get_nonce()))