Beispiel #1
0
    def test_APIPostWithBytesQuery(self):
        wcapi = API(**self.api_params)
        nonce = b"%f\xff" % random.random()

        data = {
            "name": nonce,
            "type": "simple",
        }

        response = wcapi.post('products', data)
        response_obj = response.json()
        product_id = response_obj.get('id')

        expected = StrUtils.to_text(nonce, encoding='ascii', errors='replace')

        self.assertEqual(
            response_obj.get('name'),
            expected,
        )
        wcapi.delete('products/%s' % product_id)
Beispiel #2
0
    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

        try_hostname_mismatch = False

        if (isinstance(response_json, dict)
                and ('code' in response_json or 'message' in response_json)):
            reason = " - ".join([
                text_type(response_json.get(key))
                for key in ['code', 'message', 'data'] if key in response_json
            ])
            code = text_type(response_json.get('code'))

            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")

            elif code == 'woocommerce_rest_authentication_error':
                try_hostname_mismatch = True

        response_headers = {}
        if hasattr(response, 'headers'):
            response_headers = response.headers

        if not reason or try_hostname_mismatch:
            requester_api_url = self.requester.api_url
            links = []
            if hasattr(response, 'links') and response.links:
                links = response.links
            elif 'Link' in response_headers:
                links = [response_headers['Link']]
            if 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 StrUtils.to_text(header_api_url) !=
                        StrUtils.to_text(requester_api_url)):
                    reason = "hostname mismatch. %s != %s" % tuple(
                        map(StrUtils.to_text,
                            [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") % tuple(
                   map(StrUtils.to_text, [
                       request_url, response.status_code,
                       UrlUtils.beautify_response(response), response_headers,
                       StrUtils.to_binary(request_body)[:1000]
                   ]))
        if reason:
            msg += "\nBecause of %s" % StrUtils.to_binary(reason)
        if remedy:
            msg += "\n%s" % remedy
        raise UserWarning(msg)