test_epoll.py 8.7 KB
Newer Older
Christian Heimes's avatar
Christian Heimes committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# Copyright (c) 2001-2006 Twisted Matrix Laboratories.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
Tests for epoll wrapper.
"""
import errno
25
import os
Christian Heimes's avatar
Christian Heimes committed
26
import select
27 28
import socket
import time
Christian Heimes's avatar
Christian Heimes committed
29 30 31
import unittest

if not hasattr(select, "epoll"):
Benjamin Peterson's avatar
Benjamin Peterson committed
32
    raise unittest.SkipTest("test works only on Linux 2.6")
Christian Heimes's avatar
Christian Heimes committed
33

Christian Heimes's avatar
Christian Heimes committed
34 35
try:
    select.epoll()
36
except OSError as e:
Christian Heimes's avatar
Christian Heimes committed
37
    if e.errno == errno.ENOSYS:
Benjamin Peterson's avatar
Benjamin Peterson committed
38
        raise unittest.SkipTest("kernel doesn't support epoll()")
39
    raise
Christian Heimes's avatar
Christian Heimes committed
40

Christian Heimes's avatar
Christian Heimes committed
41 42 43 44 45
class TestEPoll(unittest.TestCase):

    def setUp(self):
        self.serverSocket = socket.socket()
        self.serverSocket.bind(('127.0.0.1', 0))
46
        self.serverSocket.listen()
Christian Heimes's avatar
Christian Heimes committed
47 48 49 50 51 52 53 54 55 56 57
        self.connections = [self.serverSocket]

    def tearDown(self):
        for skt in self.connections:
            skt.close()

    def _connected_pair(self):
        client = socket.socket()
        client.setblocking(False)
        try:
            client.connect(('127.0.0.1', self.serverSocket.getsockname()[1]))
58
        except OSError as e:
59
            self.assertEqual(e.args[0], errno.EINPROGRESS)
Christian Heimes's avatar
Christian Heimes committed
60 61 62 63 64 65 66 67 68 69 70 71
        else:
            raise AssertionError("Connect should have raised EINPROGRESS")
        server, addr = self.serverSocket.accept()

        self.connections.extend((client, server))
        return client, server

    def test_create(self):
        try:
            ep = select.epoll(16)
        except OSError as e:
            raise AssertionError(str(e))
72 73
        self.assertTrue(ep.fileno() > 0, ep.fileno())
        self.assertTrue(not ep.closed)
Christian Heimes's avatar
Christian Heimes committed
74
        ep.close()
75
        self.assertTrue(ep.closed)
Christian Heimes's avatar
Christian Heimes committed
76
        self.assertRaises(ValueError, ep.fileno)
77 78
        if hasattr(select, "EPOLL_CLOEXEC"):
            select.epoll(select.EPOLL_CLOEXEC).close()
79 80
            select.epoll(flags=select.EPOLL_CLOEXEC).close()
            select.epoll(flags=0).close()
81
            self.assertRaises(OSError, select.epoll, flags=12356)
Christian Heimes's avatar
Christian Heimes committed
82 83 84 85 86 87 88 89 90

    def test_badcreate(self):
        self.assertRaises(TypeError, select.epoll, 1, 2, 3)
        self.assertRaises(TypeError, select.epoll, 'foo')
        self.assertRaises(TypeError, select.epoll, None)
        self.assertRaises(TypeError, select.epoll, ())
        self.assertRaises(TypeError, select.epoll, ['foo'])
        self.assertRaises(TypeError, select.epoll, {})

91 92 93 94 95 96 97
    def test_context_manager(self):
        with select.epoll(16) as ep:
            self.assertGreater(ep.fileno(), 0)
            self.assertFalse(ep.closed)
        self.assertTrue(ep.closed)
        self.assertRaises(ValueError, ep.fileno)

Christian Heimes's avatar
Christian Heimes committed
98 99 100 101 102 103 104 105 106 107
    def test_add(self):
        server, client = self._connected_pair()

        ep = select.epoll(2)
        try:
            ep.register(server.fileno(), select.EPOLLIN | select.EPOLLOUT)
            ep.register(client.fileno(), select.EPOLLIN | select.EPOLLOUT)
        finally:
            ep.close()

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
        # adding by object w/ fileno works, too.
        ep = select.epoll(2)
        try:
            ep.register(server, select.EPOLLIN | select.EPOLLOUT)
            ep.register(client, select.EPOLLIN | select.EPOLLOUT)
        finally:
            ep.close()

        ep = select.epoll(2)
        try:
            # TypeError: argument must be an int, or have a fileno() method.
            self.assertRaises(TypeError, ep.register, object(),
                select.EPOLLIN | select.EPOLLOUT)
            self.assertRaises(TypeError, ep.register, None,
                select.EPOLLIN | select.EPOLLOUT)
            # ValueError: file descriptor cannot be a negative integer (-1)
            self.assertRaises(ValueError, ep.register, -1,
                select.EPOLLIN | select.EPOLLOUT)
126 127
            # OSError: [Errno 9] Bad file descriptor
            self.assertRaises(OSError, ep.register, 10000,
128 129 130
                select.EPOLLIN | select.EPOLLOUT)
            # registering twice also raises an exception
            ep.register(server, select.EPOLLIN | select.EPOLLOUT)
131
            self.assertRaises(OSError, ep.register, server,
132 133 134 135
                select.EPOLLIN | select.EPOLLOUT)
        finally:
            ep.close()

Christian Heimes's avatar
Christian Heimes committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    def test_fromfd(self):
        server, client = self._connected_pair()

        ep = select.epoll(2)
        ep2 = select.epoll.fromfd(ep.fileno())

        ep2.register(server.fileno(), select.EPOLLIN | select.EPOLLOUT)
        ep2.register(client.fileno(), select.EPOLLIN | select.EPOLLOUT)

        events = ep.poll(1, 4)
        events2 = ep2.poll(0.9, 4)
        self.assertEqual(len(events), 2)
        self.assertEqual(len(events2), 2)

        ep.close()
        try:
            ep2.poll(1, 4)
153
        except OSError as e:
154
            self.assertEqual(e.args[0], errno.EBADF, e)
Christian Heimes's avatar
Christian Heimes committed
155 156 157 158 159 160 161 162 163 164 165 166
        else:
            self.fail("epoll on closed fd didn't raise EBADF")

    def test_control_and_wait(self):
        client, server = self._connected_pair()

        ep = select.epoll(16)
        ep.register(server.fileno(),
                   select.EPOLLIN | select.EPOLLOUT | select.EPOLLET)
        ep.register(client.fileno(),
                   select.EPOLLIN | select.EPOLLOUT | select.EPOLLET)

167
        now = time.monotonic()
Christian Heimes's avatar
Christian Heimes committed
168
        events = ep.poll(1, 4)
169
        then = time.monotonic()
170
        self.assertFalse(then - now > 0.1, then - now)
Christian Heimes's avatar
Christian Heimes committed
171 172 173 174 175 176

        events.sort()
        expected = [(client.fileno(), select.EPOLLOUT),
                    (server.fileno(), select.EPOLLOUT)]
        expected.sort()

177
        self.assertEqual(events, expected)
Christian Heimes's avatar
Christian Heimes committed
178 179

        events = ep.poll(timeout=2.1, maxevents=4)
180
        self.assertFalse(events)
Christian Heimes's avatar
Christian Heimes committed
181 182 183 184

        client.send(b"Hello!")
        server.send(b"world!!!")

185
        now = time.monotonic()
Christian Heimes's avatar
Christian Heimes committed
186
        events = ep.poll(1, 4)
187
        then = time.monotonic()
188
        self.assertFalse(then - now > 0.01)
Christian Heimes's avatar
Christian Heimes committed
189 190 191 192 193 194

        events.sort()
        expected = [(client.fileno(), select.EPOLLIN | select.EPOLLOUT),
                    (server.fileno(), select.EPOLLIN | select.EPOLLOUT)]
        expected.sort()

195
        self.assertEqual(events, expected)
Christian Heimes's avatar
Christian Heimes committed
196 197 198

        ep.unregister(client.fileno())
        ep.modify(server.fileno(), select.EPOLLOUT)
199
        now = time.monotonic()
Christian Heimes's avatar
Christian Heimes committed
200
        events = ep.poll(1, 4)
201
        then = time.monotonic()
202
        self.assertFalse(then - now > 0.01)
Christian Heimes's avatar
Christian Heimes committed
203 204

        expected = [(server.fileno(), select.EPOLLOUT)]
205
        self.assertEqual(events, expected)
Christian Heimes's avatar
Christian Heimes committed
206 207 208 209 210 211 212 213 214 215 216 217

    def test_errors(self):
        self.assertRaises(ValueError, select.epoll, -2)
        self.assertRaises(ValueError, select.epoll().register, -1,
                          select.EPOLLIN)

    def test_unregister_closed(self):
        server, client = self._connected_pair()
        fd = server.fileno()
        ep = select.epoll(16)
        ep.register(server)

218
        now = time.monotonic()
Christian Heimes's avatar
Christian Heimes committed
219
        events = ep.poll(1, 4)
220
        then = time.monotonic()
221
        self.assertFalse(then - now > 0.01)
Christian Heimes's avatar
Christian Heimes committed
222 223 224 225

        server.close()
        ep.unregister(fd)

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    def test_close(self):
        open_file = open(__file__, "rb")
        self.addCleanup(open_file.close)
        fd = open_file.fileno()
        epoll = select.epoll()

        # test fileno() method and closed attribute
        self.assertIsInstance(epoll.fileno(), int)
        self.assertFalse(epoll.closed)

        # test close()
        epoll.close()
        self.assertTrue(epoll.closed)
        self.assertRaises(ValueError, epoll.fileno)

        # close() can be called more than once
        epoll.close()

        # operations must fail with ValueError("I/O operation on closed ...")
        self.assertRaises(ValueError, epoll.modify, fd, select.EPOLLIN)
        self.assertRaises(ValueError, epoll.poll, 1.0)
        self.assertRaises(ValueError, epoll.register, fd, select.EPOLLIN)
        self.assertRaises(ValueError, epoll.unregister, fd)

250 251 252 253 254
    def test_fd_non_inheritable(self):
        epoll = select.epoll()
        self.addCleanup(epoll.close)
        self.assertEqual(os.get_inheritable(epoll.fileno()), False)

255

Christian Heimes's avatar
Christian Heimes committed
256
if __name__ == "__main__":
257
    unittest.main()