Beispiel #1
0
 def wait(self, timeout):
     with gevent.Timeout(timeout, False):
         for index in xrange(1000000):
             try:
                 gevent_socket.gethostbyname('www.x%s.com' % index)
             except socket.error:
                 pass
         raise AssertionError('Timeout was not raised')
Beispiel #2
0
 def wait(self, timeout):
     with gevent.Timeout(timeout, False):
         for index in xrange(1000000):
             try:
                 gevent_socket.gethostbyname('www.x%s.com' % index)
             except socket.error:
                 pass
         raise AssertionError('Timeout was not raised')
Beispiel #3
0
 def test(self):
     events = [Event() for _ in xrange(self.N)]
     asyncs = [AsyncResult() for _ in xrange(self.N)]
     max_len = len(events) + len(asyncs)
     sender = gevent.spawn(self._sender, events, asyncs)
     results = gevent.wait(events + asyncs, count=self.count, timeout=self.timeout)
     if self.timeout is None:
         expected_len = max_len
     else:
         expected_len = min(max_len, self.timeout / self.period)
     if self.count is None:
         assert sender.ready()
     else:
         expected_len = min(self.count, expected_len)
         assert not sender.ready()
         sender.kill()
     assert expected_len == len(results), (expected_len, results)
Beispiel #4
0
    def test_greenlet_link(self):
        lst = []

        # test that links are executed in the same order as they were added
        g = gevent.spawn(lst.append, 0)

        for i in xrange(1, self.count):
            g.link(appender(lst, i))
        g.join()
        self.assertEqual(lst, list(range(self.count)))
Beispiel #5
0
    def test_greenlet_link(self):
        lst = []

        # test that links are executed in the same order as they were added
        g = gevent.spawn(lst.append, 0)

        for i in xrange(1, self.count):
            g.link(appender(lst, i))
        g.join()
        self.assertEqual(lst, range(self.count))
Beispiel #6
0
 def test(self):
     events = [Event() for _ in xrange(self.N)]
     asyncs = [AsyncResult() for _ in xrange(self.N)]
     max_len = len(events) + len(asyncs)
     sender = gevent.spawn(self._sender, events, asyncs)
     results = gevent.wait(events + asyncs,
                           count=self.count,
                           timeout=self.timeout)
     if self.timeout is None:
         expected_len = max_len
     else:
         expected_len = min(max_len, self.timeout / self.period)
     if self.count is None:
         assert sender.ready()
     else:
         expected_len = min(self.count, expected_len)
         assert not sender.ready()
         sender.kill()
     assert expected_len == len(results), (expected_len, results)
Beispiel #7
0
 def queue_join_test(self, q):
     self.cum = 0
     for i in (0, 1):
         threading.Thread(target=self.worker, args=(q,)).start()
     for i in xrange(100):
         q.put(i)
     q.join()
     self.assertEquals(self.cum, sum(range(100)), "q.join() did not block until all tasks were done")
     for i in (0, 1):
         q.put(None)  # instruct the threads to close
     q.join()  # verify that you can join twice
Beispiel #8
0
 def queue_join_test(self, q):
     self.cum = 0
     for i in (0, 1):
         threading.Thread(target=self.worker, args=(q, )).start()
     for i in xrange(100):
         q.put(i)
     q.join()
     self.assertEquals(self.cum, sum(range(100)),
                       "q.join() did not block until all tasks were done")
     for i in (0, 1):
         q.put(None)  # instruct the threads to close
     q.join()  # verify that you can join twice
Beispiel #9
0
    def setUp(self):
        self.resource = NoteResource()
        self.request = MockRequest()
        self.request.path = '/api/v1/notes/'
        self.request.GET = {'limit': '100'}

        user = User.objects.create_user('foo', 'pass')

        for i in six.xrange(0, 200):
            Note.objects.create(author=user,
                                title='Note #%s' % i,
                                slug='note-%s' % i)

        super(ResourceProfilingTestCase, self).setUp()
Beispiel #10
0
    def test(self):
        server = backdoor.BackdoorServer(("127.0.0.1", 0))
        server.start()

        def connect():
            conn = create_connection(("127.0.0.1", server.server_port))
            read_until(conn, ">>> ")
            conn.sendall("2+2\r\n")
            line = conn.makefile().readline()
            assert line.strip() == "4", repr(line)

        jobs = [gevent.spawn(connect) for _ in xrange(10)]
        gevent.joinall(jobs)
        server.close()
Beispiel #11
0
    def test(self):
        server = backdoor.BackdoorServer(('127.0.0.1', 0))
        server.start()

        def connect():
            conn = create_connection(('127.0.0.1', server.server_port))
            read_until(conn, '>>> ')
            conn.sendall('2+2\r\n')
            line = conn.makefile().readline()
            assert line.strip() == '4', repr(line)

        jobs = [gevent.spawn(connect) for _ in xrange(10)]
        gevent.joinall(jobs)
        server.close()
Beispiel #12
0
    def test(self):
        server = backdoor.BackdoorServer(('127.0.0.1', 0))
        server.start()

        def connect():
            conn = create_connection(('127.0.0.1', server.server_port))
            read_until(conn, b'>>> ')
            conn.sendall(b'2+2\r\n')
            line = conn.makefile('rb', 0).readline()
            assert line.strip() == b'4', repr(line)
            read_until(conn, b'>>> ')

        jobs = [gevent.spawn(connect) for _ in xrange(10)]
        gevent.joinall(jobs)
        server.close()
Beispiel #13
0
    def test(self):
        server = backdoor.BackdoorServer(('127.0.0.1', 0))

        def connect():
            conn = create_connection(('127.0.0.1', server.server_port))
            read_until(conn, '>>> ')
            conn.sendall('2+2\r\n')
            line = conn.makefile().readline()
            assert line.strip() == '4', repr(line)

        server.start()
        try:
            jobs = [gevent.spawn(connect) for _ in xrange(10)]
            gevent.joinall(jobs, raise_error=True)
        finally:
            server.close()
Beispiel #14
0
 def test_enumerate_after_join(self):
     # Try hard to trigger #1703448: a thread is still returned in
     # threading.enumerate() after it has been join()ed.
     enum = threading.enumerate
     old_interval = sys.getcheckinterval()
     try:
         for i in xrange(1, 100):
             # Try a couple times at each thread-switching interval
             # to get more interleavings.
             sys.setcheckinterval(i // 5)
             t = threading.Thread(target=lambda: None)
             t.start()
             t.join()
             l = enum()
             self.assertFalse(t in l,
                 "#1703448 triggered after %d trials: %s" % (i, l))
     finally:
         sys.setcheckinterval(old_interval)
Beispiel #15
0
    def test(self):
        server = backdoor.BackdoorServer(('127.0.0.1', 0))
        server.start()

        def connect():
            conn = create_connection(('127.0.0.1', server.server_port))
            try:
                read_until(conn, '>>> ')
                conn.sendall(b'2+2\r\n')
                line = readline(conn)
                self.assertEqual(line.strip(), '4', repr(line))
            finally:
                conn.close()

        try:
            jobs = [gevent.spawn(connect) for _ in xrange(10)]
            gevent.joinall(jobs, raise_error=True)
        finally:
            server.close()
    if fuzzy is None:
        if RUNNING_ON_APPVEYOR:
            fuzzy = expected * 2.0
        else:
            fuzzy = expected / 2.0
    start = time()
    yield
    elapsed = time() - start
    assert expected - fuzzy <= elapsed <= expected + fuzzy, 'Expected: %r; elapsed: %r' % (expected, elapsed)


def no_time(fuzzy=0.001):
    return expected_time(0, fuzzy=fuzzy)


for _a in xrange(2):

    # exiting because the spawned greenlet finished execution (spawn (=callback) variant)
    for _ in xrange(2):
        x = gevent.spawn(lambda: 5)
        with no_time(SMALL):
            result = gevent.wait(timeout=10)
        assert result is True, repr(result)
        assert x.dead, x
        assert x.value == 5, x

    # exiting because the spawned greenlet finished execution (spawn_later (=timer) variant)
    for _ in xrange(2):
        x = gevent.spawn_later(SMALL, lambda: 5)
        with expected_time(SMALL):
            result = gevent.wait(timeout=10)
Beispiel #17
0
 def __doXOr(self, s, value):
     slist = list(s)
     for index in xrange(len(slist)):
         slist[index] = chr(ord(slist[index]) ^ value)
     return "".join(slist)
@contextmanager
def expected_time(expected, fuzzy=None):
    if fuzzy is None:
        fuzzy = expected / 2.
    start = time()
    yield
    elapsed = time() - start
    assert expected - fuzzy <= elapsed <= expected + fuzzy, 'Expected: %r; elapsed: %r' % (
        expected, elapsed)


def no_time(fuzzy=0.001):
    return expected_time(0, fuzzy=fuzzy)


for _a in xrange(2):

    # exiting because the spawned greenlet finished execution (spawn (=callback) variant)
    for _ in xrange(2):
        x = gevent.spawn(lambda: 5)
        with no_time(SMALL):
            result = gevent.wait(timeout=10)
        assert result is True, repr(result)
        assert x.dead, x
        assert x.value == 5, x

    # exiting because the spawned greenlet finished execution (spawn_later (=timer) variant)
    for _ in xrange(2):
        x = gevent.spawn_later(SMALL, lambda: 5)
        with expected_time(SMALL):
            result = gevent.wait(timeout=10)
import sys
from six import xrange

if 'runtestcase' in sys.argv[1:]:
    import gevent
    import gevent.subprocess
    gevent.spawn(sys.exit, 'bye')
    gevent.subprocess.Popen('python -c "1/0"'.split())
    gevent.sleep(1)
else:
    import subprocess
    for _ in xrange(5):
        out, err = subprocess.Popen([sys.executable, __file__, 'runtestcase'],
                                    stderr=subprocess.PIPE).communicate()
        if b'refs' in err:
            assert err.startswith(b'bye'), repr(err)
        else:
            assert err.strip() == b'bye', repr(err)
import sys
from six import xrange


if 'runtestcase' in sys.argv[1:]:
    import gevent
    import gevent.subprocess
    gevent.spawn(sys.exit, 'bye')
    gevent.subprocess.Popen('python -c "1/0"'.split())
    gevent.sleep(1)
else:
    import subprocess
    for _ in xrange(5):
        out, err = subprocess.Popen([sys.executable, __file__, 'runtestcase'], stderr=subprocess.PIPE).communicate()
        if 'refs' in err:
            assert err.startswith('bye'), repr(err)
        else:
            assert err.strip() == 'bye', repr(err)
from __future__ import print_function
import os
import gevent
from gevent import core
from six import xrange


for count in xrange(2):
    for backend in core.supported_backends():
        hub = gevent.get_hub(backend, default=False)
        assert hub.loop.backend == backend, (hub.loop.backend, backend)
        gevent.sleep(0.001)
        fileno = hub.loop.fileno()
        if fileno is not None:
            print('%s. Testing %r: %r' % (count, backend, hub))
            os.close(fileno)
            try:
                gevent.sleep(0.001)
            except SystemError as ex:
                if '(libev)' in str(ex):
                    print('The error is expected: %s' % ex)
                else:
                    raise
            else:
                raise AssertionError('gevent.sleep() is expected to fail after loop fd was closed')
        else:
            print('%s. %r lacks fileno()' % (count, backend))
        hub.destroy()
        assert 'destroyed' in repr(hub), repr(hub)
from __future__ import print_function
import os
import gevent
from gevent import core
from six import xrange

for count in xrange(2):
    for backend in core.supported_backends():
        hub = gevent.get_hub(backend, default=False)
        assert hub.loop.backend == backend, (hub.loop.backend, backend)
        gevent.sleep(0.001)
        fileno = hub.loop.fileno()
        if fileno is not None:
            print('%s. Testing %r: %r' % (count, backend, hub))
            os.close(fileno)
            try:
                gevent.sleep(0.001)
            except SystemError as ex:
                if '(libev)' in str(ex):
                    print('The error is expected: %s' % ex)
                else:
                    raise
            else:
                raise AssertionError(
                    'gevent.sleep() is expected to fail after loop fd was closed'
                )
        else:
            print('%s. %r lacks fileno()' % (count, backend))
        hub.destroy()
        assert 'destroyed' in repr(hub), repr(hub)
Beispiel #23
0
    def test_get_list(self):
        get_list = self.resource.get_list
        request = self.request

        for i in six.xrange(0, 50):
            get_list(request)