Debian Codegraph @

pypy/module/select/test/test_select.py

raw symbols SCIP
1 import sys
2 import py
3
4 from pypy.interpreter.error import OperationError
5
6
7 class _AppTestSelect:
8 def test_sleep(self):
9 """
10 The timeout parameter to select.select specifies the approximate
11 maximum amount of time for that function to block before it returns
12 to report that no results are available.
13 """
14 import time, select
15 readend, writeend = self.getpair()
16 try:
17 start = time.time()
18 iwtd, owtd, ewtd = select.select([readend], [], [], 0.3)
19 end = time.time()
20 assert iwtd == owtd == ewtd == []
21 assert end - start > 0.25
22 finally:
23 readend.close()
24 writeend.close()
25 raises(ValueError, select.select, [], [], [], -1)
26
27 def test_list_tuple(self):
28 import time, select
29 readend, writeend = self.getpair()
30 try:
31 iwtd, owtd, ewtd = select.select([readend], (), (), .3)
32 finally:
33 readend.close()
34 writeend.close()
35
36 def test_readable(self):
37 """
38 select.select returns elements from the "read list" (the first
39 parameter) which may have data available to be read.
40 """
41 import select
42 readend, writeend = self.getpair()
43 try:
44 iwtd, owtd, ewtd = select.select([readend], [], [], 0)
45 assert iwtd == owtd == ewtd == []
46 writeend.send(b'X')
47 iwtd, owtd, ewtd = select.select([readend], [], [])
48 assert iwtd == [readend]
49 assert owtd == ewtd == []
50 finally:
51 writeend.close()
52 readend.close()
53
54 def test_writable(self):
55 """
56 select.select returns elements from the "write list" (the second
57 parameter) on which a write/send may be possible.
58 """
59 import select
60 readend, writeend = self.getpair()
61 try:
62 iwtd, owtd, ewtd = select.select([], [writeend], [], 0)
63 assert iwtd == ewtd == []
64 assert owtd == [writeend]
65 finally:
66 writeend.close()
67 readend.close()
68
69 def test_write_read(self):
70 """
71 select.select returns elements from the "write list" (the second
72 parameter) on which a write/send may be possible. select.select
73 returns elements from the "read list" (the first parameter) which
74 may have data available to be read. (the second part of this test
75 overlaps significantly with test_readable. -exarkun)
76 """
77 import select
78 readend, writeend = self.getpair()
79 try:
80 total_out = 0
81 while True:
82 iwtd, owtd, ewtd = select.select([], [writeend], [], 0)
83 assert iwtd == ewtd == []
84 if owtd == []:
85 break
86 assert owtd == [writeend]
87 total_out += writeend.send(b'x' * 512)
88 total_in = 0
89 while total_in < total_out:
90 iwtd, owtd, ewtd = select.select([readend], [], [], 5)
91 assert owtd == ewtd == []
92 assert iwtd == [readend] # there is more expected
93 data = readend.recv(4096)
94 assert len(data) > 0
95 assert data == b'x' * len(data)
96 total_in += len(data)
97 assert total_in == total_out
98 iwtd, owtd, ewtd = select.select([readend], [], [], 0)
99 assert owtd == ewtd == []
100 assert iwtd == [] # there is not more expected
101 finally:
102 writeend.close()
103 readend.close()
104
105 def test_write_close(self):
106 """
107 select.select returns elements from the "read list" (the first
108 parameter) which have no data to be read but which have been closed.
109 """
110 import select, sys
111 readend, writeend = self.getpair()
112 try:
113 try:
114 total_out = writeend.send(b'x' * 512)
115 finally:
116 # win32 sends the 'closed' event immediately, even when
117 # more data is available
118 if sys.platform != 'win32':
119 writeend.close()
120 import gc; gc.collect()
121 assert 1 <= total_out <= 512
122 total_in = 0
123 while True:
124 iwtd, owtd, ewtd = select.select([readend], [], [])
125 assert iwtd == [readend]
126 assert owtd == ewtd == []
127 data = readend.recv(4096)
128 if len(data) == 0:
129 break
130 assert data == b'x' * len(data)
131 total_in += len(data)
132 # win32: check that closing the socket exits the loop
133 if sys.platform == 'win32' and total_in == total_out:
134 writeend.close()
135 assert total_in == total_out
136 finally:
137 readend.close()
138
139 def test_read_closed(self):
140 """
141 select.select returns elements from the "read list" (the first
142 parameter) which are at eof (even if they are the write end of a
143 pipe).
144 """
145 import select
146 readend, writeend = self.getpair()
147 try:
148 readend.close()
149 import gc; gc.collect()
150 iwtd, owtd, ewtd = select.select([writeend], [], [], 0)
151 assert iwtd == [writeend]
152 assert owtd == ewtd == []
153 finally:
154 writeend.close()
155
156 def test_read_many(self):
157 """
158 select.select returns only the elements from the "read list" (the
159 first parameter) which may have data available to be read.
160 (test_readable has a lot of overlap with this test. -exarkun)
161 """
162 import select
163 readends = []
164 writeends = []
165 try:
166 for i in range(10):
167 fd1, fd2 = self.getpair()
168 readends.append(fd1)
169 writeends.append(fd2)
170 iwtd, owtd, ewtd = select.select(readends, [], [], 0)
171 assert iwtd == owtd == ewtd == []
172
173 for i in range(50):
174 n = (i*3) % 10
175 writeends[n].send(b'X')
176 iwtd, owtd, ewtd = select.select(readends, [], [])
177 assert iwtd == [readends[n]]
178 assert owtd == ewtd == []
179 data = readends[n].recv(1)
180 assert data == b'X'
181
182 finally:
183 for fd in readends + writeends:
184 fd.close()
185
186 def test_read_end_closed(self):
187 """
188 select.select returns elements from the "write list" (the second
189 parameter) when they are not writable but when the corresponding
190 read end has been closed. (this test currently doesn't make the
191 write end non-writable before testing its selectability. -exarkun)
192 """
193 import select
194 readend, writeend = self.getpair()
195 readend.close()
196 try:
197 iwtd, owtd, ewtd = select.select([writeend], [writeend], [writeend])
198 assert iwtd == owtd == [writeend]
199 assert ewtd == []
200 finally:
201 writeend.close()
202
203 def test_select_descr_out_of_bounds(self):
204 import sys, select
205 raises(ValueError, select.select, [-1], [], [])
206 raises(ValueError, select.select, [], [-2], [])
207 raises(ValueError, select.select, [], [], [-3])
208 if sys.platform != 'win32':
209 raises(ValueError, select.select, [2000000000], [], [])
210 raises(ValueError, select.select, [], [2000000000], [])
211 raises(ValueError, select.select, [], [], [2000000000])
212
213 def test_poll_arguments(self):
214 import select
215 if not hasattr(select, 'poll'):
216 skip("no select.poll() on this platform")
217 pollster = select.poll()
218 pollster.register(1)
219 raises(ValueError, pollster.register, 0, -1)
220 raises(OverflowError, pollster.register, 0, 1 << 64)
221 pollster.register(0, 32768) # SHRT_MAX + 1
222 exc = raises(ValueError, pollster.register, 0, -32768 - 1)
223 assert "positive" in str(exc.value)
224 exc = raises(OverflowError, pollster.register, 0, 1000000)
225 assert "unsigned" in str(exc.value)
226 pollster.register(0, 65535) # USHRT_MAX
227 raises(OverflowError, pollster.register, 0, 65536) # USHRT_MAX + 1
228 raises(OverflowError, pollster.poll, 2147483648) # INT_MAX + 1
229 raises(OverflowError, pollster.poll, 4294967296) # UINT_MAX + 1
230 exc = raises(TypeError, pollster.poll, '123')
231 assert str(exc.value) == 'timeout must be an integer or None'
232
233 raises(ValueError, pollster.modify, 1, -1)
234 raises(OverflowError, pollster.modify, 1, 1 << 64)
235
236 def test_select_new_forbidden(self):
237 import select
238 if not hasattr(select, 'poll'):
239 skip("no select.poll() on this platform")
240 pollster = select.poll()
241 Poll = type(select.poll())
242 with raises(TypeError) as info:
243 Poll()
244 assert "cannot create 'select.poll' instances" in str(info.value)
245
246
247 class AppTestSelectWithPipes(_AppTestSelect):
248 "Use a pipe to get pairs of file descriptors"
249 spaceconfig = {
250 "usemodules": ["select", "time", "thread"]
251 }
252
253 def setup_class(cls):
254 if sys.platform == 'win32':
255 py.test.skip("select() doesn't work with pipes on win32")
256
257 def w_getpair(self):
258 # Wraps a file descriptor in an socket-like object
259 import os
260 class FileAsSocket:
261 def __init__(self, fd):
262 self.fd = fd
263 def fileno(self):
264 return self.fd
265 def send(self, data):
266 return os.write(self.fd, data)
267 def recv(self, length):
268 return os.read(self.fd, length)
269 def close(self):
270 return os.close(self.fd)
271 s1, s2 = os.pipe()
272 return FileAsSocket(s1), FileAsSocket(s2)
273
274 def test_poll(self):
275 import select
276 if not hasattr(select, 'poll'):
277 skip("no select.poll() on this platform")
278 readend, writeend = self.getpair()
279 try:
280 class A(object):
281 def fileno(self):
282 return readend.fileno()
283 poll = select.poll()
284 poll.register(A())
285
286 res = poll.poll(10) # timeout in ms
287 assert res == []
288 res = poll.poll(1.1) # check floats
289 assert res == []
290
291 writeend.send(b"foo!")
292 # can't easily test actual blocking, is done in lib-python tests
293 res = poll.poll()
294 assert res == [(readend.fileno(), 1)]
295
296 # check negative timeout
297 # proper test in lib-python, test_poll_blocks_with_negative_ms
298 res = poll.poll(-0.001)
299 assert res == [(readend.fileno(), 1)]
300 finally:
301 readend.close()
302 writeend.close()
303
304 def test_poll_threaded(self):
305 import os, select, _thread as thread, time
306 if not hasattr(select, 'poll'):
307 skip("no select.poll() on this platform")
308 r, w = os.pipe()
309 rfds = [os.dup(r) for _ in range(10)]
310 try:
311 pollster = select.poll()
312 for fd in rfds:
313 pollster.register(fd, select.POLLIN)
314
315 t = thread.start_new_thread(pollster.poll, ())
316 try:
317 time.sleep(0.3)
318 for i in range(100): print(''), # to release GIL untranslated
319 # trigger ufds array reallocation
320 for fd in rfds:
321 pollster.unregister(fd)
322 pollster.register(w, select.POLLOUT)
323 exc = raises(RuntimeError, pollster.poll)
324 assert str(exc.value) == 'concurrent poll() invocation'
325 finally:
326 # and make the call to poll() from the thread return
327 os.write(w, b'spam')
328 time.sleep(0.3)
329 for i in range(100): print(''), # to release GIL untranslated
330 finally:
331 os.close(r)
332 os.close(w)
333 for fd in rfds:
334 os.close(fd)
335
336 def test_resize_list_in_select(self):
337 import select
338 class Foo(object):
339 def fileno(self):
340 if len(l) < 100:
341 l.append(Foo())
342 return 0
343 l = [Foo()]
344 select.select(l, (), (), 0)
345 assert 1 <= len(l) <= 100
346 # ^^^ CPython gives 100, PyPy gives 1. I think both are OK as
347 # long as there is no crash.
348
349 def test_PIPE_BUF(self):
350 # no PIPE_BUF on Windows; this test class is skipped on Windows.
351 import select
352 assert isinstance(select.PIPE_BUF, int)
353
354
355 class AppTestSelectWithSockets(_AppTestSelect):
356 """Same tests with connected sockets.
357 socket.socketpair() does not exists on win32,
358 so we start our own server.
359 """
360 spaceconfig = {
361 "usemodules": ["select", "_socket", "time", "thread"],
362 }
363
364 import os
365 if hasattr(os, 'uname') and os.uname()[4] == 's390x':
366 py.test.skip("build bot for s390x cannot open sockets")
367
368 def w_make_server(self):
369 import _socket
370 if hasattr(self, 'sock'):
371 return self.sock
372 self.sock = _socket.socket()
373 try_ports = [1023] + list(range(20000, 30000, 437))
374 for port in try_ports:
375 print('binding to port %d:' % (port,))
376 self.sockaddress = ('127.0.0.1', port)
377 try:
378 self.sock.bind(self.sockaddress)
379 break
380 except _socket.error as e: # should get a "Permission denied"
381 print(e)
382 else:
383 raise(e)
384
385 def w_getpair(self):
386 """Helper method which returns a pair of connected sockets."""
387 import _socket
388 import _thread
389
390 self.make_server()
391
392 self.make_server()
393
394 self.sock.listen(1)
395 s2 = _socket.socket()
396 _thread.start_new_thread(s2.connect, (self.sockaddress,))
397 fd, addr2 = self.sock._accept()
398 s1 = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM,
399 proto=0, fileno=fd)
400
401 # speed up the tests that want to fill the buffers
402 s1.setsockopt(_socket.SOL_SOCKET, _socket.SO_RCVBUF, 4096)
403 s2.setsockopt(_socket.SOL_SOCKET, _socket.SO_SNDBUF, 4096)
404
405 return s1, s2