Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(234)

Side by Side Diff: third_party/pexpect/tests/test_expect.py

Issue 1398903002: Add third_party/pexpect (Closed) Base URL: https://chromium.googlesource.com/crashpad/crashpad@end-to-end-test
Patch Set: Created 5 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 #!/usr/bin/env python
2 '''
3 PEXPECT LICENSE
4
5 This license is approved by the OSI and FSF as GPL-compatible.
6 http://opensource.org/licenses/isc-license.txt
7
8 Copyright (c) 2012, Noah Spurrier <noah@noah.org>
9 PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
10 PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
11 COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
12 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19
20 '''
21 import multiprocessing
22 import unittest
23 import subprocess
24 import time
25 import signal
26 import sys
27 import os
28
29 import pexpect
30 from . import PexpectTestCase
31 from .utils import no_coverage_env
32
33 # Many of these test cases blindly assume that sequential directory
34 # listings of the /bin directory will yield the same results.
35 # This may not be true, but seems adequate for testing now.
36 # I should fix this at some point.
37
38 FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)])
39 def hex_dump(src, length=16):
40 result=[]
41 for i in xrange(0, len(src), length):
42 s = src[i:i+length]
43 hexa = ' '.join(["%02X"%ord(x) for x in s])
44 printable = s.translate(FILTER)
45 result.append("%04X %-*s %s\n" % (i, length*3, hexa, printable))
46 return ''.join(result)
47
48 def hex_diff(left, right):
49 diff = ['< %s\n> %s' % (_left, _right,) for _left, _right in zip(
50 hex_dump(left).splitlines(), hex_dump(right).splitlines())
51 if _left != _right]
52 return '\n' + '\n'.join(diff,)
53
54
55 class ExpectTestCase (PexpectTestCase.PexpectTestCase):
56
57 def test_expect_basic (self):
58 p = pexpect.spawn('cat', echo=False, timeout=5)
59 p.sendline (b'Hello')
60 p.sendline (b'there')
61 p.sendline (b'Mr. Python')
62 p.expect (b'Hello')
63 p.expect (b'there')
64 p.expect (b'Mr. Python')
65 p.sendeof ()
66 p.expect (pexpect.EOF)
67
68 def test_expect_exact_basic (self):
69 p = pexpect.spawn('cat', echo=False, timeout=5)
70 p.sendline (b'Hello')
71 p.sendline (b'there')
72 p.sendline (b'Mr. Python')
73 p.expect_exact (b'Hello')
74 p.expect_exact (b'there')
75 p.expect_exact (b'Mr. Python')
76 p.sendeof ()
77 p.expect_exact (pexpect.EOF)
78
79 def test_expect_ignore_case(self):
80 '''This test that the ignorecase flag will match patterns
81 even if case is different using the regex (?i) directive.
82 '''
83 p = pexpect.spawn('cat', echo=False, timeout=5)
84 p.sendline (b'HELLO')
85 p.sendline (b'there')
86 p.expect (b'(?i)hello')
87 p.expect (b'(?i)THERE')
88 p.sendeof ()
89 p.expect (pexpect.EOF)
90
91 def test_expect_ignore_case_flag(self):
92 '''This test that the ignorecase flag will match patterns
93 even if case is different using the ignorecase flag.
94 '''
95 p = pexpect.spawn('cat', echo=False, timeout=5)
96 p.ignorecase = True
97 p.sendline (b'HELLO')
98 p.sendline (b'there')
99 p.expect (b'hello')
100 p.expect (b'THERE')
101 p.sendeof ()
102 p.expect (pexpect.EOF)
103
104 def test_expect_order (self):
105 '''This tests that patterns are matched in the same order as given in th e pattern_list.
106
107 (Or does it? Doesn't it also pass if expect() always chooses
108 (one of the) the leftmost matches in the input? -- grahn)
109 ... agreed! -jquast, the buffer ptr isn't forwarded on match, see first two test cases
110 '''
111 p = pexpect.spawn('cat', echo=False, timeout=5)
112 self._expect_order(p)
113
114 def test_expect_order_exact (self):
115 '''Like test_expect_order(), but using expect_exact().
116 '''
117 p = pexpect.spawn('cat', echo=False, timeout=5)
118 p.expect = p.expect_exact
119 self._expect_order(p)
120
121 def _expect_order (self, p):
122 p.sendline (b'1234')
123 p.sendline (b'abcd')
124 p.sendline (b'wxyz')
125 p.sendline (b'7890')
126 p.sendeof ()
127 index = p.expect ([
128 b'1234',
129 b'abcd',
130 b'wxyz',
131 pexpect.EOF,
132 b'7890' ])
133 assert index == 0, (index, p.before, p.after)
134 index = p.expect ([
135 b'54321',
136 pexpect.TIMEOUT,
137 b'1234',
138 b'abcd',
139 b'wxyz',
140 pexpect.EOF], timeout=5)
141 assert index == 3, (index, p.before, p.after)
142 index = p.expect ([
143 b'54321',
144 pexpect.TIMEOUT,
145 b'1234',
146 b'abcd',
147 b'wxyz',
148 pexpect.EOF], timeout=5)
149 assert index == 4, (index, p.before, p.after)
150 index = p.expect ([
151 pexpect.EOF,
152 b'abcd',
153 b'wxyz',
154 b'7890' ])
155 assert index == 3, (index, p.before, p.after)
156
157 index = p.expect ([
158 b'abcd',
159 b'wxyz',
160 b'7890',
161 pexpect.EOF])
162 assert index == 3, (index, p.before, p.after)
163
164 def test_expect_setecho_off(self):
165 '''This tests that echo may be toggled off.
166 '''
167 p = pexpect.spawn('cat', echo=True, timeout=5)
168 try:
169 self._expect_echo_toggle(p)
170 except IOError:
171 if sys.platform.lower().startswith('sunos'):
172 if hasattr(unittest, 'SkipTest'):
173 raise unittest.SkipTest("Not supported on this platform.")
174 return 'skip'
175 raise
176
177 def test_expect_setecho_off_exact(self):
178 p = pexpect.spawn('cat', echo=True, timeout=5)
179 p.expect = p.expect_exact
180 try:
181 self._expect_echo_toggle(p)
182 except IOError:
183 if sys.platform.lower().startswith('sunos'):
184 if hasattr(unittest, 'SkipTest'):
185 raise unittest.SkipTest("Not supported on this platform.")
186 return 'skip'
187 raise
188
189 def test_waitnoecho(self):
190 " Tests setecho(False) followed by waitnoecho() "
191 p = pexpect.spawn('cat', echo=False, timeout=5)
192 try:
193 p.setecho(False)
194 p.waitnoecho()
195 except IOError:
196 if sys.platform.lower().startswith('sunos'):
197 if hasattr(unittest, 'SkipTest'):
198 raise unittest.SkipTest("Not supported on this platform.")
199 return 'skip'
200 raise
201
202 def test_waitnoecho_order(self):
203
204 ''' This tests that we can wait on a child process to set echo mode.
205 For example, this tests that we could wait for SSH to set ECHO False
206 when asking of a password. This makes use of an external script
207 echo_wait.py. '''
208
209 p1 = pexpect.spawn('%s echo_wait.py' % self.PYTHONBIN)
210 start = time.time()
211 try:
212 p1.waitnoecho(timeout=10)
213 except IOError:
214 if sys.platform.lower().startswith('sunos'):
215 if hasattr(unittest, 'SkipTest'):
216 raise unittest.SkipTest("Not supported on this platform.")
217 return 'skip'
218 raise
219
220
221 end_time = time.time() - start
222 assert end_time < 10 and end_time > 2, "waitnoecho did not set ECHO off in the expected window of time."
223
224 # test that we actually timeout and return False if ECHO is never set of f.
225 p1 = pexpect.spawn('cat')
226 start = time.time()
227 retval = p1.waitnoecho(timeout=4)
228 end_time = time.time() - start
229 assert end_time > 3, "waitnoecho should have waited longer than 2 second s. retval should be False, retval=%d"%retval
230 assert retval==False, "retval should be False, retval=%d"%retval
231
232 # This one is mainly here to test default timeout for code coverage.
233 p1 = pexpect.spawn('%s echo_wait.py' % self.PYTHONBIN)
234 start = time.time()
235 p1.waitnoecho()
236 end_time = time.time() - start
237 assert end_time < 10, "waitnoecho did not set ECHO off in the expected w indow of time."
238
239 def test_expect_echo (self):
240 '''This tests that echo is on by default.
241 '''
242 p = pexpect.spawn('cat', echo=True, timeout=5)
243 self._expect_echo(p)
244
245 def test_expect_echo_exact (self):
246 '''Like test_expect_echo(), but using expect_exact().
247 '''
248 p = pexpect.spawn('cat', echo=True, timeout=5)
249 p.expect = p.expect_exact
250 self._expect_echo(p)
251
252 def _expect_echo (self, p):
253 p.sendline (b'1234') # Should see this twice (once from tty echo and aga in from cat).
254 index = p.expect ([
255 b'1234',
256 b'abcd',
257 b'wxyz',
258 pexpect.EOF,
259 pexpect.TIMEOUT])
260 assert index == 0, "index="+str(index)+"\n"+p.before
261 index = p.expect ([
262 b'1234',
263 b'abcd',
264 b'wxyz',
265 pexpect.EOF])
266 assert index == 0, "index="+str(index)
267
268 def _expect_echo_toggle(self, p):
269 p.sendline (b'1234') # Should see this twice (once from tty echo and aga in from cat).
270 index = p.expect ([
271 b'1234',
272 b'abcd',
273 b'wxyz',
274 pexpect.EOF,
275 pexpect.TIMEOUT])
276 assert index == 0, "index="+str(index)+"\n"+p.before
277 index = p.expect ([
278 b'1234',
279 b'abcd',
280 b'wxyz',
281 pexpect.EOF])
282 assert index == 0, "index="+str(index)
283 p.setecho(0) # Turn off tty echo
284 p.waitnoecho()
285 p.sendline (b'abcd') # Now, should only see this once.
286 p.sendline (b'wxyz') # Should also be only once.
287 index = p.expect ([
288 pexpect.EOF,
289 pexpect.TIMEOUT,
290 b'abcd',
291 b'wxyz',
292 b'1234'])
293 assert index == 2, "index="+str(index)
294 index = p.expect ([
295 pexpect.EOF,
296 b'abcd',
297 b'wxyz',
298 b'7890'])
299 assert index == 2, "index="+str(index)
300 p.setecho(1) # Turn on tty echo
301 p.sendline (b'7890') # Should see this twice.
302 index = p.expect ([pexpect.EOF,b'abcd',b'wxyz',b'7890'])
303 assert index == 3, "index="+str(index)
304 index = p.expect ([pexpect.EOF,b'abcd',b'wxyz',b'7890'])
305 assert index == 3, "index="+str(index)
306 p.sendeof()
307
308 def test_expect_index (self):
309 '''This tests that mixed list of regex strings, TIMEOUT, and EOF all
310 return the correct index when matched.
311 '''
312 p = pexpect.spawn('cat', echo=False, timeout=5)
313 self._expect_index(p)
314
315 def test_expect_index_exact (self):
316 '''Like test_expect_index(), but using expect_exact().
317 '''
318 p = pexpect.spawn('cat', echo=False, timeout=5)
319 p.expect = p.expect_exact
320 self._expect_index(p)
321
322 def _expect_index (self, p):
323 p.sendline (b'1234')
324 index = p.expect ([b'abcd',b'wxyz',b'1234',pexpect.EOF])
325 assert index == 2, "index="+str(index)
326 p.sendline (b'abcd')
327 index = p.expect ([pexpect.TIMEOUT,b'abcd',b'wxyz',b'1234',pexpect.EOF])
328 assert index == 1, "index="+str(index)+str(p)
329 p.sendline (b'wxyz')
330 index = p.expect ([b'54321',pexpect.TIMEOUT,b'abcd',b'wxyz',b'1234',pexp ect.EOF])
331 assert index == 3, "index="+str(index) # Expect 'wxyz'
332 p.sendline (b'$*!@?')
333 index = p.expect ([b'54321',pexpect.TIMEOUT,b'abcd',b'wxyz',b'1234',pexp ect.EOF],
334 timeout=1)
335 assert index == 1, "index="+str(index) # Expect TIMEOUT
336 p.sendeof ()
337 index = p.expect ([b'54321',pexpect.TIMEOUT,b'abcd',b'wxyz',b'1234',pexp ect.EOF])
338 assert index == 5, "index="+str(index) # Expect EOF
339
340 def test_expect (self):
341 the_old_way = subprocess.Popen(args=['ls', '-l', '/bin'],
342 stdout=subprocess.PIPE).communicate()[0].rstrip()
343 p = pexpect.spawn('ls -l /bin')
344 the_new_way = b''
345 while 1:
346 i = p.expect ([b'\n', pexpect.EOF])
347 the_new_way = the_new_way + p.before
348 if i == 1:
349 break
350 the_new_way = the_new_way.rstrip()
351 the_new_way = the_new_way.replace(b'\r\n', b'\n'
352 ).replace(b'\r', b'\n').replace(b'\n\n', b'\n').rstrip()
353 the_old_way = the_old_way.replace(b'\r\n', b'\n'
354 ).replace(b'\r', b'\n').replace(b'\n\n', b'\n').rstrip()
355 assert the_old_way == the_new_way, hex_diff(the_old_way, the_new_way)
356
357 def test_expect_exact (self):
358 the_old_way = subprocess.Popen(args=['ls', '-l', '/bin'],
359 stdout=subprocess.PIPE).communicate()[0].rstrip()
360 p = pexpect.spawn('ls -l /bin')
361 the_new_way = b''
362 while 1:
363 i = p.expect_exact ([b'\n', pexpect.EOF])
364 the_new_way = the_new_way + p.before
365 if i == 1:
366 break
367 the_new_way = the_new_way.replace(b'\r\n', b'\n'
368 ).replace(b'\r', b'\n').replace(b'\n\n', b'\n').rstrip()
369 the_old_way = the_old_way.replace(b'\r\n', b'\n'
370 ).replace(b'\r', b'\n').replace(b'\n\n', b'\n').rstrip()
371 assert the_old_way == the_new_way, hex_diff(the_old_way, the_new_way)
372 p = pexpect.spawn('echo hello.?world')
373 i = p.expect_exact(b'.?')
374 self.assertEqual(p.before, b'hello')
375 self.assertEqual(p.after, b'.?')
376
377 def test_expect_eof (self):
378 the_old_way = subprocess.Popen(args=['/bin/ls', '-l', '/bin'],
379 stdout=subprocess.PIPE).communicate()[0].rstrip()
380 p = pexpect.spawn('/bin/ls -l /bin')
381 p.expect(pexpect.EOF) # This basically tells it to read everything. Same as pexpect.run() function.
382 the_new_way = p.before
383 the_new_way = the_new_way.replace(b'\r\n', b'\n'
384 ).replace(b'\r', b'\n').replace(b'\n\n', b'\n').rstrip()
385 the_old_way = the_old_way.replace(b'\r\n', b'\n'
386 ).replace(b'\r', b'\n').replace(b'\n\n', b'\n').rstrip()
387 assert the_old_way == the_new_way, hex_diff(the_old_way, the_new_way)
388
389 def test_expect_timeout (self):
390 p = pexpect.spawn('cat', timeout=5)
391 p.expect(pexpect.TIMEOUT) # This tells it to wait for timeout.
392 self.assertEqual(p.after, pexpect.TIMEOUT)
393
394 def test_unexpected_eof (self):
395 p = pexpect.spawn('ls -l /bin')
396 try:
397 p.expect('_Z_XY_XZ') # Probably never see this in ls output.
398 except pexpect.EOF:
399 pass
400 else:
401 self.fail ('Expected an EOF exception.')
402
403 def _before_after(self, p):
404 p.timeout = 5
405
406 p.expect(b'5')
407 self.assertEqual(p.after, b'5')
408 assert p.before.startswith(b'[0, 1, 2'), p.before
409
410 p.expect(b'50')
411 self.assertEqual(p.after, b'50')
412 assert p.before.startswith(b', 6, 7, 8'), p.before[:20]
413 assert p.before.endswith(b'48, 49, '), p.before[-20:]
414
415 p.expect(pexpect.EOF)
416 self.assertEqual(p.after, pexpect.EOF)
417 assert p.before.startswith(b', 51, 52'), p.before[:20]
418 assert p.before.endswith(b', 99]\r\n'), p.before[-20:]
419
420 def test_before_after(self):
421 '''This tests expect() for some simple before/after things.
422 '''
423 p = pexpect.spawn('%s -Wi list100.py' % self.PYTHONBIN, env=no_coverage_ env())
424 self._before_after(p)
425
426 def test_before_after_exact(self):
427 '''This tests some simple before/after things, for
428 expect_exact(). (Grahn broke it at one point.)
429 '''
430 p = pexpect.spawn('%s -Wi list100.py' % self.PYTHONBIN, env=no_coverage_ env())
431 # mangle the spawn so we test expect_exact() instead
432 p.expect = p.expect_exact
433 self._before_after(p)
434
435 def _ordering(self, p):
436 p.timeout = 5
437 p.expect(b'>>> ')
438
439 p.sendline('list(range(4*3))')
440 self.assertEqual(p.expect([b'5,', b'5,']), 0)
441 p.expect(b'>>> ')
442
443 p.sendline(b'list(range(4*3))')
444 self.assertEqual(p.expect([b'7,', b'5,']), 1)
445 p.expect(b'>>> ')
446
447 p.sendline(b'list(range(4*3))')
448 self.assertEqual(p.expect([b'5,', b'7,']), 0)
449 p.expect(b'>>> ')
450
451 p.sendline(b'list(range(4*5))')
452 self.assertEqual(p.expect([b'2,', b'12,']), 0)
453 p.expect(b'>>> ')
454
455 p.sendline(b'list(range(4*5))')
456 self.assertEqual(p.expect([b'12,', b'2,']), 1)
457
458 def test_ordering(self):
459 '''This tests expect() for which pattern is returned
460 when many may eventually match. I (Grahn) am a bit
461 confused about what should happen, but this test passes
462 with pexpect 2.1.
463 '''
464 p = pexpect.spawn(self.PYTHONBIN)
465 self._ordering(p)
466
467 def test_ordering_exact(self):
468 '''This tests expect_exact() for which pattern is returned
469 when many may eventually match. I (Grahn) am a bit
470 confused about what should happen, but this test passes
471 for the expect() method with pexpect 2.1.
472 '''
473 p = pexpect.spawn(self.PYTHONBIN)
474 # mangle the spawn so we test expect_exact() instead
475 p.expect = p.expect_exact
476 self._ordering(p)
477
478 def _greed(self, expect):
479 # End at the same point: the one with the earliest start should win
480 self.assertEqual(expect([b'3, 4', b'2, 3, 4']), 1)
481
482 # Start at the same point: first pattern passed wins
483 self.assertEqual(expect([b'5,', b'5, 6']), 0)
484
485 # Same pattern passed twice: first instance wins
486 self.assertEqual(expect([b'7, 8', b'7, 8, 9', b'7, 8']), 0)
487
488 def _greed_read1(self, expect):
489 # Here, one has an earlier start and a later end. When processing
490 # one character at a time, the one that finishes first should win,
491 # because we don't know about the other match when it wins.
492 # If maxread > 1, this behaviour is currently undefined, although in
493 # most cases the one that starts first will win.
494 self.assertEqual(expect([b'1, 2, 3', b'2,']), 1)
495
496 def test_greed(self):
497 p = pexpect.spawn(self.PYTHONBIN + ' list100.py')
498 self._greed(p.expect)
499
500 p = pexpect.spawn(self.PYTHONBIN + ' list100.py', maxread=1)
501 self._greed_read1(p.expect)
502
503 def test_greed_exact(self):
504 p = pexpect.spawn(self.PYTHONBIN + ' list100.py')
505 self._greed(p.expect_exact)
506
507 p = pexpect.spawn(self.PYTHONBIN + ' list100.py', maxread=1)
508 self._greed_read1(p.expect_exact)
509
510 def test_bad_arg(self):
511 p = pexpect.spawn('cat')
512 with self.assertRaisesRegexp(TypeError, '.*must be one of'):
513 p.expect(1)
514 with self.assertRaisesRegexp(TypeError, '.*must be one of'):
515 p.expect([1, b'2'])
516 with self.assertRaisesRegexp(TypeError, '.*must be one of'):
517 p.expect_exact(1)
518 with self.assertRaisesRegexp(TypeError, '.*must be one of'):
519 p.expect_exact([1, b'2'])
520
521 def test_timeout_none(self):
522 p = pexpect.spawn('echo abcdef', timeout=None)
523 p.expect('abc')
524 p.expect_exact('def')
525 p.expect(pexpect.EOF)
526
527 def test_signal_handling(self):
528 '''
529 This tests the error handling of a signal interrupt (usually a
530 SIGWINCH generated when a window is resized), but in this test, we
531 are substituting an ALARM signal as this is much easier for testing
532 and is treated the same as a SIGWINCH.
533
534 To ensure that the alarm fires during the expect call, we are
535 setting the signal to alarm after 1 second while the spawned process
536 sleeps for 2 seconds prior to sending the expected output.
537 '''
538 def noop(x, y):
539 pass
540 signal.signal(signal.SIGALRM, noop)
541
542 p1 = pexpect.spawn('%s sleep_for.py 2' % self.PYTHONBIN, timeout=5)
543 p1.expect('READY')
544 signal.alarm(1)
545 p1.expect('END')
546
547 def test_stdin_closed(self):
548 '''
549 Ensure pexpect continues to operate even when stdin is closed
550 '''
551 class Closed_stdin_proc(multiprocessing.Process):
552 def run(self):
553 sys.__stdin__.close()
554 cat = pexpect.spawn('cat')
555 cat.sendeof()
556 cat.expect(pexpect.EOF)
557
558 proc = Closed_stdin_proc()
559 proc.start()
560 proc.join()
561 assert proc.exitcode == 0
562
563 def test_stdin_stdout_closed(self):
564 '''
565 Ensure pexpect continues to operate even when stdin and stdout is closed
566 '''
567 class Closed_stdin_stdout_proc(multiprocessing.Process):
568 def run(self):
569 sys.__stdin__.close()
570 sys.__stdout__.close()
571 cat = pexpect.spawn('cat')
572 cat.sendeof()
573 cat.expect(pexpect.EOF)
574
575 proc = Closed_stdin_stdout_proc()
576 proc.start()
577 proc.join()
578 assert proc.exitcode == 0
579
580 if __name__ == '__main__':
581 unittest.main()
582
583 suite = unittest.makeSuite(ExpectTestCase, 'test')
OLDNEW
« no previous file with comments | « third_party/pexpect/tests/test_dotall.py ('k') | third_party/pexpect/tests/test_filedescriptor.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698