def __request(self, method, endpoint, data, **kwargs): """ Do requests """ endpoint_url = self.requester.endpoint_url(endpoint) endpoint_url = self.auth.get_auth_url(endpoint_url, method, **kwargs) auth = self.auth.get_auth() content_type = 'application/json' for key, value in kwargs.get('headers', {}).items(): if key.lower() == 'content-type': content_type = value.lower() if data is not None and content_type.startswith('application/json'): data = StrUtils.jsonencode(data, ensure_ascii=False) # enforce utf-8 encoded binary data = StrUtils.to_binary(data) response = self.requester.request(method=method, url=endpoint_url, auth=auth, data=data, **kwargs) if response.status_code not in [200, 201, 202]: self.request_post_mortem(response) return response
def endpoint_url(self, endpoint): endpoint = StrUtils.decapitate(endpoint, self.api_ver_url) endpoint = StrUtils.decapitate(endpoint, self.api_ver_url_no_port) endpoint = StrUtils.decapitate(endpoint, '/') components = [self.url, self.api] if self.api_version != 'wp/v1': components += [self.api_version] components += [endpoint] return UrlUtils.join_components(components)
def test_get_sign_key(self): oauth_token_secret = "PNW9j1yBki3e7M7EqB5qZxbe9n5tR6bIIefSMQ9M2pdyRI9g" key = self.api.auth.get_sign_key(self.consumer_secret, oauth_token_secret) self.assertEqual( StrUtils.to_binary(key), StrUtils.to_binary("%s&%s" % (self.consumer_secret, oauth_token_secret)))
def test_str_remove_head(self): self.assertEqual( 'sdf', StrUtils.remove_head('/sdf', '/') ) self.assertEqual( 'sdf', StrUtils.decapitate('sdf', '/') )
def test_get_sign_key(self): self.assertEqual( StrUtils.to_binary( self.wcapi.auth.get_sign_key(self.consumer_secret)), StrUtils.to_binary("%s&" % self.consumer_secret)) self.assertEqual( StrUtils.to_binary( self.wcapi.auth.get_sign_key(self.twitter_consumer_secret, self.twitter_token_secret)), StrUtils.to_binary(self.twitter_signing_key))
def test_APIPostMedia(self): img_path = 'tests/data/test.jpg' with open(img_path, 'rb') as test_file: img_data = test_file.read() img_name = os.path.basename(img_path) res = self.wpapi.post( 'media', data=img_data, headers={ 'Content-Type': 'image/jpg', 'Content-Disposition' : 'attachment; filename=%s'% img_name } ) self.assertEqual(res.status_code, 201) res_obj = res.json() created_id = res_obj.get('id') self.assertTrue(created_id) uploaded_res = requests.get(res_obj.get('source_url')) # check for bug where image bytestream was quoted self.assertNotEqual(StrUtils.to_binary(uploaded_res.text[0]), b'"') self.wpapi.delete('media/%s?force=True' % created_id)
def test_APIPostWithLatin1Query(self): wcapi = API(**self.api_params) nonce = "%f\u00ae" % random.random() data = { "name": nonce.encode('latin-1'), "type": "simple", } response = wcapi.post('products', data) response_obj = response.json() product_id = response_obj.get('id') expected = StrUtils.to_text(StrUtils.to_binary(nonce, encoding='latin-1'), encoding='ascii', errors='replace') self.assertEqual(response_obj.get('name'), expected) wcapi.delete('products/%s' % product_id)
def request_post_mortem(self, response=None): """ Attempt to diagnose what went wrong in a request """ reason = None remedy = None response_json = {} try: response_json = response.json() except ValueError: pass # import pudb; pudb.set_trace() request_body = {} request_url = "" if hasattr(response, 'request'): if hasattr(response.request, 'url'): request_url = response.request.url if hasattr(response.request, 'body'): request_body = response.request.body if isinstance(response_json, dict) and ('code' in response_json or 'message' in response_json): reason = u" - ".join([ str(response_json.get(key)) for key in ['code', 'message', 'data'] \ if key in response_json ]) if 'code' == 'rest_user_invalid_email': remedy = "Try checking the email %s doesn't already exist" % \ request_body.get('email') elif 'code' == 'json_oauth1_consumer_mismatch': remedy = "Try deleting the cached credentials at %s" % \ self.auth.creds_store elif 'code' == 'woocommerce_rest_cannot_view': if not self.auth.query_string_auth: remedy = "Try enabling query_string_auth" else: remedy = ( "This error is super generic and can be caused by just " "about anything. Here are some things to try: \n" " - Check that the account which as assigned to your " "oAuth creds has the correct access level\n" " - Enable logging and check for error messages in " "wp-content and wp-content/uploads/wc-logs\n" " - Check that your query string parameters are valid\n" " - Make sure your server is not messing with authentication headers\n" " - Try a different endpoint\n" " - Try enabling HTTPS and using basic authentication\n" ) response_headers = {} if hasattr(response, 'headers'): response_headers = response.headers if not reason: requester_api_url = self.requester.api_url if hasattr(response, 'links') and response.links: links = response.links first_link_key = list(links)[0] header_api_url = links[first_link_key].get('url', '') if header_api_url: header_api_url = StrUtils.eviscerate(header_api_url, '/') if header_api_url and requester_api_url\ and header_api_url != requester_api_url: reason = "hostname mismatch. %s != %s" % ( header_api_url, requester_api_url) header_url = StrUtils.eviscerate(header_api_url, '/') header_url = StrUtils.eviscerate(header_url, self.requester.api) header_url = StrUtils.eviscerate(header_url, '/') remedy = "try changing url to %s" % header_url msg = "API call to %s returned \nCODE: %s\nRESPONSE:%s \nHEADERS: %s\nREQ_BODY:%s" % ( request_url, str( response.status_code), UrlUtils.beautify_response(response), str(response_headers), str(request_body)[:1000]) if reason: msg += "\nBecause of %s" % reason if remedy: msg += "\n%s" % remedy raise UserWarning(msg)
def endpoint_url(self, endpoint): endpoint = StrUtils.decapitate(endpoint, '/') return UrlUtils.join_components( [self.url, self.api, self.api_version, endpoint])
def test_str_remove_tail(self): self.assertEqual( 'sdf', StrUtils.remove_tail('sdf/','/') )
def test_flatten_params(self): self.assertEqual( StrUtils.to_binary(UrlUtils.flatten_params( self.twitter_params_raw)), StrUtils.to_binary(self.twitter_param_string))