Ejemplo n.º 1
0
def _url_valid(url):
    """检查 URL 是否有效
    
    URL 有效性检验参考了 requests 模块 models 检验的代码
    """
    # Support for unicode domain names and paths.
    try:
        scheme, auth, host, port, path, query, fragment = urllib3.util.parse_url(
            url)
    except exceptions.LocationParseError as e:
        raise exceptions.InvalidURL(*e.args)

    if not scheme:
        error = (
            "Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?"
        )
        error = error.format(url)

        raise exceptions.MissingSchema(error)

    if not host:
        raise exceptions.InvalidURL("Invalid URL %r: No host supplied" % url)

    # In general, we want to try IDNA encoding the hostname if the string contains
    # non-ASCII characters. This allows users to automatically get the correct IDNA
    # behaviour. For strings containing only ASCII characters, we need to also verify
    # it doesn't start with a wildcard (*), before allowing the unencoded hostname.
    if not host:
        raise exceptions.InvalidURL('URL has an invalid label.')
    elif host.startswith('*'):
        raise exceptions.InvalidURL('URL has an invalid label.')

    return True
Ejemplo n.º 2
0
    def test_invalid_url_error(self, requests_get: MagicMock):
        """ should fail if the url is not valid """

        requests_get.side_effect = request_exceptions.InvalidURL('Fake')

        r = support.run_command('connect "a url"')
        self.assert_has_error_code(r, 'INVALID_URL')
 def test_analyze_exception_request(self):
     self.assertEqual(errors.SYSTEM_TRANSIENT,
                      self.apic_handler.analyze_exception(rexc.Timeout()))
     self.assertEqual(
         errors.SYSTEM_TRANSIENT,
         self.apic_handler.analyze_exception(rexc.ConnectionError()))
     self.assertEqual(
         errors.OPERATION_CRITICAL,
         self.apic_handler.analyze_exception(rexc.InvalidURL()))
     self.assertEqual(
         errors.OPERATION_CRITICAL,
         self.apic_handler.analyze_exception(rexc.URLRequired()))
     self.assertEqual(
         errors.OPERATION_TRANSIENT,
         self.apic_handler.analyze_exception(rexc.RequestException()))
     self.assertEqual(errors.UNKNOWN,
                      self.apic_handler.analyze_exception(Exception()))
Ejemplo n.º 4
0
def ensure_valid_url(url):
    """Ensure a url is valid.

    Args:
        url (str): URL to validate

    Raises:
        InvalidURL: URL is not a valid url
        ConnectionError: Failed to connect to url
        HTTPError: Reponse was not 200 <OK>

    Returns:
        str: valid url

    """
    if not is_url(url):
        raise reqexc.InvalidURL(f"{url} is not a valid url!")
    resp = requests.head(url, allow_redirects=True)
    resp.raise_for_status()
    return url
Ejemplo n.º 5
0
def getConnectSnList():
    # Set the request parameters
    url = ConnDet.url
    user = ConnDet.user
    pwd = ConnDet.pwd

    # Set proper headers
    headers = {"Accept": "application/json"}
    # Do the HTTP request
    response = requests.get(url, auth=(user, pwd), headers=headers)

    if response.status_code != 200:
        loghttp.debug('Response other than 200 in getConnectSnList()' +
                      str(response.status_code))
        raise exc.InvalidURL(str(response.status_code))

    if response.status_code != 200:
        #print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:', response.json())
        exit()

    # Decode the JSON response into a dictionary and use the data
    if response.status_code == 200:
        loghttp.debug('Connection is okk.... \n getConnectSnList()' +
                      str(response.status_code))
        #print('Status:', response.status_code)

    #print(response.json())
    try:
        resData = json.dumps(response.json())
        resDataJson = json.loads(resData)  # result in string error solved

    except Exception as e:
        loghttp.debug("Error while parsing JSON having html response")
        loghttp.debug(e.__str__())

    parseRes = resDataJson['result']
    loghttp.debug('JSON is returned backed from getConnectSnList()' +
                  str(response.status_code))

    return parseRes
 def test_invalid_url(self):
     signal = http_checks.check_fail(rex.InvalidURL())
     self._assert_has_tags(self.bad_request_tags, signal)
     self._assert_has_slug("HTTP_FAIL_INVALID_URL", signal)