def test_create_connection_with_invalid_idna_labels(self, host: str) -> None: with pytest.raises( LocationParseError, match=f"Failed to parse: '{host}', label empty or too long", ): create_connection((host, 80))
def _new_conn(self): extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['socket_options'] = self.socket_options custom_host = self.custom_ip if self.custom_ip else self._dns_host #if self.custom_ip: # logging.debug('Using custom ip %s for host %s' % (self.custom_ip, self._dns_host)) try: conn = connection.create_connection( (custom_host, self.port), self.timeout, **extra_kw) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout)) except SocketError as e: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e) return conn
def test_create_connection_with_scoped_ipv6( self, socket: MagicMock, getaddrinfo: MagicMock) -> None: # Check that providing create_connection with a scoped IPv6 address # properly propagates the scope to getaddrinfo, and that the returned # scoped ID makes it to the socket creation call. fake_scoped_sa6 = ("a::b", 80, 0, 42) getaddrinfo.return_value = [( socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", fake_scoped_sa6, )] socket.return_value = fake_sock = MagicMock() create_connection(("a::b%iface", 80)) assert getaddrinfo.call_args[0][0] == "a::b%iface" fake_sock.connect.assert_called_once_with(fake_scoped_sa6)
def test_create_connection_with_valid_idna_labels(self, socket, getaddrinfo, host): getaddrinfo.return_value = [(None, None, None, None, None)] socket.return_value = Mock() create_connection((host, 80))
def test_create_connection_with_invalid_idna_labels(self, host): with pytest.raises(LocationParseError) as ctx: create_connection((host, 80)) assert str( ctx.value) == f"Failed to parse: '{host}', label empty or too long"
def test_dnsresolver_expected_error(self): with pytest.raises(socket.gaierror): # windows: [Errno 11001] getaddrinfo failed in windows # linux: [Errno -2] Name or service not known # macos: [Errno 8] nodename nor servname provided, or not known create_connection(("badhost.invalid", 80))
def test_dnsresolver_forced_error(self, getaddrinfo): getaddrinfo.side_effect = socket.gaierror() with pytest.raises(socket.gaierror): # dns is valid but we force the error just for the sake of the test create_connection(("example.com", 80))
def test_create_connection_error(self, getaddrinfo): getaddrinfo.return_value = [] with pytest.raises(OSError, match="getaddrinfo returns an empty list"): create_connection(("example.com", 80))
def send( self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None ): """Sends PreparedRequest object. Returns Response object. Args: request (PreparedRequest): the request being sent. stream (bool, optional): unused timeout (float, optional): unused verify (bool, optional): unused cert (str, optional): unused proxies (dict, optional): unused Returns: request.Response: the response to the request. """ # https://docs.python-requests.org/en/master/api/#requests.PreparedRequest # Connect to LSP server using raw socket purl = parse_url(request.url) hostport = purl.host + ':' + str(purl.port) conn = self._connections.get(hostport, None) if not conn: conn = connection.create_connection([purl.host, purl.port]) self._connections[hostport] = conn # Calculate header block with Content-length header = 'Content-Length: ' + str(len(request.body)) output = [] # encode everything into bytes output.append(header.encode()) output.append(b'') # add body output.append(request.body) if self.debug: for line in output: print('> ' + line.decode('utf-8')) conn.sendall(b'\r\n'.join(output)) # Parse response response = Response() response.request = request # [ ] if "id" is not specified, the read will hang # so don't read if no "id" in initial JSON fs = conn.makefile('rb') # read Content-Length header header = fs.readline() if self.debug: print('< ' + header.strip().decode('utf-8')) line = fs.readline() if self.debug: print('< ' + line.strip().decode('utf-8')) readlen = int(header.split()[1]) response.headers['Content-Length'] = readlen body = fs.read(readlen) if self.debug: print('< ' + body.decode('utf-8')) response._content = body fs.close() return response
def test_create_connection_with_valid_idna_labels(self, socket: MagicMock, getaddrinfo: MagicMock, host: str) -> None: getaddrinfo.return_value = [(None, None, None, None, None)] socket.return_value = Mock() create_connection((host, 80))
def test_interrupted_request(): # requests.get("http://192.168.2.50/index.html") sock = create_connection(('192.168.2.51', 80), socket_options=[(6, 1, 1)]) sock.close()