def test_greenpool_type_check(): eventlet.GreenPool(0) eventlet.GreenPool(1) eventlet.GreenPool(1e3) with tests.assert_raises(TypeError): eventlet.GreenPool('foo') with tests.assert_raises(ValueError): eventlet.GreenPool(-1)
def test_semaphore_type_check(): eventlet.Semaphore(0) eventlet.Semaphore(1) eventlet.Semaphore(1e2) with tests.assert_raises(TypeError): eventlet.Semaphore('foo') with tests.assert_raises(ValueError): eventlet.Semaphore(-1)
def test_dont_persist_alias(self): db = sqlsoup.SQLSoup(engine) MappedBooks = db.books b = db.books._table s = select([b.c.published_year, func.count('*').label('n')], from_obj=[b], group_by=[b.c.published_year]) s = s.alias('years_with_count') years_with_count = db.map(s, primary_key=[s.c.published_year]) assert_raises(sqlsoup.SQLSoupError, years_with_count.insert, published_year='2007', n=1)
def test_nxdomain(self): res = self._make_mock_resolver() rp = greendns.ResolverProxy() rp._resolver = res res.raises = greendns.dns.resolver.NXDOMAIN with tests.assert_raises(greendns.dns.resolver.NXDOMAIN): rp.query('host.example.com')
def test_parse_www_authenticate_malformed(): # TODO: test (and fix) header value 'barbqwnbm-bb...:asd' leads to dead loop with tests.assert_raises(httplib2.MalformedHeader): httplib2._parse_www_authenticate({ 'www-authenticate': 'OAuth "Facebook Platform" "invalid_token" "Invalid OAuth access token."' })
def test_noanswer(self): res = self._make_mock_resolver() rp = greendns.ResolverProxy() rp._resolver = res res.raises = greendns.dns.resolver.NoAnswer with tests.assert_raises(greendns.dns.resolver.NoAnswer): rp.query('host.example.com')
def test_server_not_found_error_is_raised_for_invalid_hostname( mock_socket_connect): """Invalidates https://github.com/httplib2/httplib2/pull/100.""" mock_socket_connect.side_effect = _raise_name_not_known_error http = httplib2.Http(proxy_info=httplib2.ProxyInfo( httplib2.socks.PROXY_TYPE_HTTP, "255.255.255.255", 8001)) with tests.assert_raises(httplib2.ServerNotFoundError): http.request("http://invalid.hostname.foo.bar/", "GET")
def test_parse_www_authenticate_malformed(): # TODO: test (and fix) header value 'barbqwnbm-bb...:asd' leads to dead loop with tests.assert_raises(httplib2.MalformedHeader): httplib2._parse_www_authenticate( { "www-authenticate": 'OAuth "Facebook Platform" "invalid_token" "Invalid OAuth access token."' } )
def test_udp_ipv6_wrong_addr_ignore(self): with tests.mock.patch( 'eventlet.support.greendns.socket.socket.recvfrom', side_effect=socket.timeout): with tests.assert_raises(dns.exception.Timeout): greendns.udp(self.query, '::1', timeout=0.1, ignore_unexpected=True)
def test_min_tls_version(): # skip on Python versions that don't support TLS min if not hasattr(ssl.SSLContext(), 'minimum_version'): return # BadSSL server that supports max TLS 1.1, # forcing 1.2 should always fail http = httplib2.Http(tls_minimum_version="TLSv1_2") with tests.assert_raises(ssl.SSLError): http.request("https://tls-v1-1.badssl.com:1011/")
def test_github_100_socks_basestring(): # https://github.com/httplib2/httplib2/pull/100 # NameError: name 'basestring' is not defined # TODO: replace invalid address with dummy local server http = httplib2.Http(proxy_info=httplib2.ProxyInfo( httplib2.socks.PROXY_TYPE_HTTP, '255.255.255.255', 8001)) with tests.assert_raises(httplib2.ServerNotFoundError): with mock.patch('socket.socket.connect', side_effect=socket.gaierror): http.request('http://255.255.255.255/', 'GET')
def test_connection_proxy_info_attribute_error(conn_type): # HTTPConnectionWithTimeout did not initialize its .proxy_info attribute # https://github.com/httplib2/httplib2/pull/97 # Thanks to Joseph Ryan https://github.com/germanjoey conn = conn_type("no-such-hostname.", 80) # TODO: replace mock with dummy local server with tests.assert_raises(socket.gaierror): with mock.patch("socket.socket.connect", side_effect=socket.gaierror): conn.request("GET", "/")
def test_getaddrinfo_hosts_only_dns_error(self): hostsres = _make_mock_base_resolver() hostsres.raises = greendns.dns.resolver.NoAnswer greendns.resolver = greendns.ResolverProxy(hostsres()) res = _make_mock_base_resolver() res.raises = greendns.dns.exception.DNSException greendns.resolver._resolver = res() with tests.assert_raises(socket.gaierror): greendns.getaddrinfo('example.com', 0, 0)
def test_connect_exception_type(): # This autoformatting PR actually changed the behavior of error handling: # https://github.com/httplib2/httplib2/pull/105/files#diff-c6669c781a2dee1b2d2671cab4e21c66L985 # potentially changing the type of the error raised by connect() # https://github.com/httplib2/httplib2/pull/150 http = httplib2.Http() with mock.patch("httplib2.socket.socket.connect", side_effect=socket.timeout("foo")): with tests.assert_raises(socket.timeout): http.request(tests.DUMMY_URL)
def test_server_not_found_error_is_raised_for_invalid_hostname(mock_socket_connect): """Invalidates https://github.com/httplib2/httplib2/pull/100.""" mock_socket_connect.side_effect = _raise_name_not_known_error http = httplib2.Http( proxy_info=httplib2.ProxyInfo( httplib2.socks.PROXY_TYPE_HTTP, "255.255.255.255", 8001 ) ) with tests.assert_raises(httplib2.ServerNotFoundError): http.request("http://invalid.hostname.foo.bar/", "GET")
def test_connection_refused(): http = httplib2.Http() http.force_exception_to_status_code = False with tests.assert_raises(socket.error): http.request(dummy_url) # Now test with exceptions turned off http.force_exception_to_status_code = True response, content = http.request(dummy_url) assert response['content-type'] == 'text/plain' assert (b"Connection refused" in content or b"actively refused" in content) assert response.status == 400
def test_ssl_wrong_ca(): # Test that we get a SSLHandshakeError if we try to access # https://www.google.com, using a CA cert file that doesn't contain # the CA Google uses (i.e., simulating a cert that's not signed by a # trusted CA). other_ca_certs = os.path.join( os.path.dirname(os.path.abspath(httplib2.__file__)), 'test', 'other_cacerts.txt') assert os.path.exists(other_ca_certs) http = httplib2.Http(ca_certs=other_ca_certs) http.follow_redirects = False with tests.assert_raises(ssl.SSLError): http.request('https://www.google.com/', 'GET')
def test_unknown_server(): http = httplib2.Http() http.force_exception_to_status_code = False with tests.assert_raises(httplib2.ServerNotFoundError): with mock.patch('socket.socket.connect', side_effect=socket.gaierror): http.request("http://no-such-hostname./") # Now test with exceptions turned off http.force_exception_to_status_code = True response, content = http.request("http://no-such-hostname./") assert response['content-type'] == 'text/plain' assert content.startswith(b"Unable to find") assert response.status == 400
def test_ssl_wrong_ca(): # Test that we get a SSLHandshakeError if we try to access # https://www.google.com, using a CA cert file that doesn't contain # the CA Google uses (i.e., simulating a cert that's not signed by a # trusted CA). other_ca_certs = os.path.join( os.path.dirname(os.path.abspath(httplib2.__file__)), "test", "other_cacerts.txt") assert os.path.exists(other_ca_certs) http = httplib2.Http(ca_certs=other_ca_certs) http.follow_redirects = False with tests.assert_raises(ssl.SSLError): http.request("https://www.google.com/", "GET")
def test_unknown_server(): http = httplib2.Http() http.force_exception_to_status_code = False with tests.assert_raises(httplib2.ServerNotFoundError): with mock.patch("socket.socket.connect", side_effect=socket.gaierror): http.request("http://no-such-hostname./") # Now test with exceptions turned off http.force_exception_to_status_code = True response, content = http.request("http://no-such-hostname./") assert response["content-type"] == "text/plain" assert content.startswith(b"Unable to find") assert response.status == 400
def test_wait_except(self): # https://github.com/eventlet/eventlet/issues/407 q = eventlet.Queue() def get(): q.get() raise KeyboardInterrupt eventlet.spawn(get) eventlet.sleep() with tests.assert_raises(KeyboardInterrupt): q.put(None) eventlet.sleep()
def test_gzip_malformed_response(): http = httplib2.Http() # Test that we raise a good exception when the gzip fails http.force_exception_to_status_code = False response = tests.http_response_bytes(headers={"content-encoding": "gzip"}, body=b"obviously not compressed") with tests.server_const_bytes(response, request_count=2) as uri: with tests.assert_raises(httplib2.FailedToDecompressContent): http.request(uri, "GET") # Re-run the test with out the exceptions http.force_exception_to_status_code = True response, content = http.request(uri, "GET") assert response.status == 500 assert response.reason.startswith("Content purported")
def test_deflate_malformed_response(): # Test that we raise a good exception when the deflate fails http = httplib2.Http() http.force_exception_to_status_code = False response = tests.http_response_bytes( headers={"content-encoding": "deflate"}, body=b"obviously not compressed" ) with tests.server_const_bytes(response, request_count=2) as uri: with tests.assert_raises(httplib2.FailedToDecompressContent): http.request(uri, "GET") # Re-run the test with out the exceptions http.force_exception_to_status_code = True response, content = http.request(uri, "GET") assert response.status == 500 assert response.reason.startswith("Content purported")
def test_deflate_malformed_response(): # Test that we raise a good exception when the deflate fails http = httplib2.Http() http.force_exception_to_status_code = False response = tests.http_response_bytes( headers={'content-encoding': 'deflate'}, body=b'obviously not compressed', ) with tests.server_const_bytes(response, request_count=2) as uri: with tests.assert_raises(httplib2.FailedToDecompressContent): http.request(uri, 'GET') # Re-run the test with out the exceptions http.force_exception_to_status_code = True response, content = http.request(uri, 'GET') assert response.status == 500 assert response.reason.startswith('Content purported')
def test_select_mark_file_as_reopened(): # https://github.com/eventlet/eventlet/pull/294 # Fix API inconsistency in select and Hub. # mark_as_closed takes one argument, but called without arguments. # on_error takes file descriptor, but called with an exception object. s = original_socket.socket() s.setblocking(0) s.bind(('127.0.0.1', 0)) s.listen(5) gt = eventlet.spawn(select.select, [s], [s], [s]) eventlet.sleep(0.01) with eventlet.Timeout(0.5) as t: with tests.assert_raises(hubs.IOClosed): hubs.get_hub().mark_as_reopened(s.fileno()) gt.wait() t.cancel()
def test_gzip_malformed_response(): http = httplib2.Http() # Test that we raise a good exception when the gzip fails http.force_exception_to_status_code = False response = tests.http_response_bytes( headers={'content-encoding': 'gzip'}, body=b'obviously not compressed', ) with tests.server_const_bytes(response, request_count=2) as uri: with tests.assert_raises(httplib2.FailedToDecompressContent): http.request(uri, 'GET') # Re-run the test with out the exceptions http.force_exception_to_status_code = True response, content = http.request(uri, 'GET') assert response.status == 500 assert response.reason.startswith('Content purported')
def test_socks5_auth(): def proxy_conn(client, tick): data = client.recv(64) assert data == b"\x05\x02\x00\x02" client.send(b"\x05\x02") # select username/password auth data = client.recv(64) assert data == b"\x01\x08user_str\x08pass_str" client.send(b"\x01\x01") # deny tick(None) with tests.server_socket(proxy_conn) as uri: uri_parsed = urllib.parse.urlparse(uri) proxy_info = httplib2.ProxyInfo( httplib2.socks.PROXY_TYPE_SOCKS5, proxy_host=uri_parsed.hostname, proxy_port=uri_parsed.port, proxy_rdns=True, proxy_user=u"user_str", proxy_pass=u"pass_str", ) http = httplib2.Http(proxy_info=proxy_info) with tests.assert_raises(httplib2.socks.Socks5AuthError): http.request(uri, "GET")
def test_query_unknown_type(self): hr = _make_host_resolver() with tests.assert_raises(greendns.dns.resolver.NoAnswer): hr.query('example.com', dns.rdatatype.MX)
def test_connection_refused_raises_exception(mock_socket_connect): mock_socket_connect.side_effect = _raise_connection_refused_exception http = httplib2.Http() http.force_exception_to_status_code = False with tests.assert_raises(socket.error): http.request(DUMMY_URL)
def test_query_unknown_raises(self): hr = _make_host_resolver() with tests.assert_raises(greendns.dns.resolver.NoAnswer): hr.query('example.com')
def test_numerichost(self): greendns.resolve = _make_mock_resolve() greendns.resolve.add('example.com', '1.2.3.4') with tests.assert_raises(socket.gaierror): greendns.getaddrinfo('example.com', 80, 0, 0, 0, socket.AI_NUMERICHOST)
def test_nosuchtable(self): db = sqlsoup.SQLSoup(engine) assert_raises(exc.NoSuchTableError, getattr, db, 'nosuchtable')
def test_ssl_invalid_ca_certs_path(): # Test that we get an ssl.SSLError when specifying a non-existent CA # certs file. http = httplib2.Http(ca_certs='/nosuchfile') with tests.assert_raises(IOError): http.request('https://www.google.com/', 'GET')
def test_udp_ipv6_wrong_addr_ignore(self): with tests.mock.patch('eventlet.support.greendns.socket.socket.recvfrom', side_effect=socket.timeout): with tests.assert_raises(dns.exception.Timeout): greendns.udp(self.query, '::1', timeout=0.1, ignore_unexpected=True)
def test_unknown_rdtype(self): with tests.assert_raises(socket.gaierror): greendns.resolve('host.example.com', socket.AF_INET6 + 1)
def test_query_unknown_type(self): hr = self._make_host_resolver() with tests.assert_raises(greendns.dns.resolver.NoAnswer): hr.query('example.com', dns.rdatatype.MX)
def test_udp_ipv6_wrong_addr(self): with tests.mock.patch('eventlet.support.greendns.socket.socket.recvfrom', return_value=(self.query_wire, ('ffff:0000::1', 53, 0, 0))): with tests.assert_raises(dns.query.UnexpectedSource): greendns.udp(self.query, '::1')
def test_convert_byte_str(): with tests.assert_raises(TypeError): httplib2._convert_byte_str(4) assert httplib2._convert_byte_str(b"Hello") == "Hello" assert httplib2._convert_byte_str("World") == "World"
def test_no_pk_reflected(self): db = sqlsoup.SQLSoup(engine) assert_raises(sqlsoup.SQLSoupError, getattr, db, 'nopk')
def test_timeout(self): greendns.resolver.raises = greendns.dns.exception.Timeout with tests.assert_raises(socket.gaierror): greendns.resolve_cname('alias.example.com')
def test_ssl_invalid_ca_certs_path(): # Test that we get an ssl.SSLError when specifying a non-existent CA # certs file. http = httplib2.Http(ca_certs="/nosuchfile") with tests.assert_raises(IOError): http.request("https://www.google.com/", "GET")
def test_exc(self): greendns.resolver.raises = greendns.dns.exception.DNSException with tests.assert_raises(socket.gaierror): greendns.resolve('host.example.com')
def test_nodata(self): greendns.resolver.raises = greendns.dns.exception.DNSException with tests.assert_raises(socket.gaierror): greendns.resolve_cname('alias.example.com')
def test_udp_ipv6_timeout(self): with tests.mock.patch('eventlet.support.greendns.socket.socket.recvfrom', side_effect=socket.timeout): with tests.assert_raises(dns.exception.Timeout): greendns.udp(self.query, '::1', timeout=0.1)