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)
Exemple #2
0
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)
Exemple #3
0
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)
Exemple #4
0
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)
Exemple #5
0
 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)
Exemple #6
0
 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)
Exemple #7
0
 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')
Exemple #8
0
 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')
Exemple #9
0
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."'
        })
Exemple #10
0
 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')
Exemple #11
0
 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')
Exemple #12
0
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")
Exemple #13
0
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)
Exemple #15
0
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')
Exemple #17
0
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", "/")
Exemple #18
0
    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)
Exemple #19
0
    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)
Exemple #20
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)
Exemple #21
0
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")
Exemple #22
0
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_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
Exemple #24
0
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')
Exemple #25
0
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
Exemple #26
0
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")
Exemple #27
0
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
Exemple #28
0
    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()
Exemple #29
0
    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()
Exemple #30
0
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")
Exemple #31
0
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")
Exemple #32
0
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')
Exemple #33
0
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()
Exemple #34
0
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')
Exemple #35
0
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")
Exemple #36
0
 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)
Exemple #37
0
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)
Exemple #38
0
 def test_query_unknown_raises(self):
     hr = _make_host_resolver()
     with tests.assert_raises(greendns.dns.resolver.NoAnswer):
         hr.query('example.com')
Exemple #39
0
 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)
Exemple #40
0
 def test_nosuchtable(self):
     db = sqlsoup.SQLSoup(engine)
     assert_raises(exc.NoSuchTableError, getattr, db, 'nosuchtable')
Exemple #41
0
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')
Exemple #42
0
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)
Exemple #43
0
 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)
Exemple #44
0
 def test_unknown_rdtype(self):
     with tests.assert_raises(socket.gaierror):
         greendns.resolve('host.example.com', socket.AF_INET6 + 1)
Exemple #45
0
 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)
Exemple #46
0
 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')
Exemple #47
0
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"
Exemple #48
0
 def test_no_pk_reflected(self):
     db = sqlsoup.SQLSoup(engine)
     assert_raises(sqlsoup.SQLSoupError, getattr, db, 'nopk')
Exemple #49
0
 def test_timeout(self):
     greendns.resolver.raises = greendns.dns.exception.Timeout
     with tests.assert_raises(socket.gaierror):
         greendns.resolve_cname('alias.example.com')
Exemple #50
0
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")
Exemple #51
0
 def test_exc(self):
     greendns.resolver.raises = greendns.dns.exception.DNSException
     with tests.assert_raises(socket.gaierror):
         greendns.resolve('host.example.com')
Exemple #52
0
 def test_unknown_rdtype(self):
     with tests.assert_raises(socket.gaierror):
         greendns.resolve('host.example.com', socket.AF_INET6 + 1)
Exemple #53
0
 def test_nodata(self):
     greendns.resolver.raises = greendns.dns.exception.DNSException
     with tests.assert_raises(socket.gaierror):
         greendns.resolve_cname('alias.example.com')
Exemple #54
0
 def test_exc(self):
     greendns.resolver.raises = greendns.dns.exception.DNSException
     with tests.assert_raises(socket.gaierror):
         greendns.resolve('host.example.com')
Exemple #55
0
 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)
Exemple #56
0
 def test_timeout(self):
     greendns.resolver.raises = greendns.dns.exception.Timeout
     with tests.assert_raises(socket.gaierror):
         greendns.resolve_cname('alias.example.com')
Exemple #57
0
 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)
Exemple #58
0
 def test_nodata(self):
     greendns.resolver.raises = greendns.dns.exception.DNSException
     with tests.assert_raises(socket.gaierror):
         greendns.resolve_cname('alias.example.com')