subprocess2_test.py 21.3 KB
Newer Older
1
#!/usr/bin/env python
2
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 4 5 6 7
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Unit tests for subprocess2.py."""

8
import logging
9 10 11 12 13 14
import optparse
import os
import sys
import time
import unittest

15
try:
16
  import fcntl  # pylint: disable=import-error
17 18 19
except ImportError:
  fcntl = None

20
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
21

22
import subprocess
23 24
import subprocess2

25 26
from testing_support import auto_stub

27
# Method could be a function
28
# pylint: disable=no-self-use
29 30


31 32 33 34 35 36 37 38
# Create aliases for subprocess2 specific tests. They shouldn't be used for
# regression tests.
TIMED_OUT = subprocess2.TIMED_OUT
VOID = subprocess2.VOID
PIPE = subprocess2.PIPE
STDOUT = subprocess2.STDOUT


39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
def convert_to_crlf(string):
  """Unconditionally convert LF to CRLF."""
  return string.replace('\n', '\r\n')


def convert_to_cr(string):
  """Unconditionally convert LF to CR."""
  return string.replace('\n', '\r')


def convert_win(string):
  """Converts string to CRLF on Windows only."""
  if sys.platform == 'win32':
    return string.replace('\n', '\r\n')
  return string


56 57 58 59
class DefaultsTest(auto_stub.TestCase):
  # TODO(maruel): Do a reopen() on sys.__stdout__ and sys.__stderr__ so they
  # can be trapped in the child process for better coverage.
  def _fake_communicate(self):
60
    """Mocks subprocess2.communicate()."""
61
    results = {}
62
    def fake_communicate(args, **kwargs):
63
      assert not results
64 65
      results.update(kwargs)
      results['args'] = args
66
      return ('stdout', 'stderr'), 0
67
    self.mock(subprocess2, 'communicate', fake_communicate)
68 69
    return results

70
  def _fake_Popen(self):
71
    """Mocks the whole subprocess2.Popen class."""
72 73 74 75 76 77 78
    results = {}
    class fake_Popen(object):
      returncode = -8
      def __init__(self, args, **kwargs):
        assert not results
        results.update(kwargs)
        results['args'] = args
79
      @staticmethod
80
      # pylint: disable=redefined-builtin
81
      def communicate(input=None, timeout=None, nag_max=None, nag_timer=None):
82
        return None, None
83
    self.mock(subprocess2, 'Popen', fake_Popen)
84 85
    return results

86
  def _fake_subprocess_Popen(self):
87
    """Mocks the base class subprocess.Popen only."""
88
    results = {}
89 90 91 92 93 94
    def __init__(self, args, **kwargs):
      assert not results
      results.update(kwargs)
      results['args'] = args
    def communicate():
      return None, None
95 96
    self.mock(subprocess.Popen, '__init__', __init__)
    self.mock(subprocess.Popen, 'communicate', communicate)
97 98
    return results

99
  def test_check_call_defaults(self):
100
    results = self._fake_communicate()
101
    self.assertEquals(
102
        ('stdout', 'stderr'), subprocess2.check_call_out(['foo'], a=True))
103 104 105 106 107 108
    expected = {
        'args': ['foo'],
        'a':True,
    }
    self.assertEquals(expected, results)

109 110 111 112 113 114 115 116 117 118 119 120
  def test_capture_defaults(self):
    results = self._fake_communicate()
    self.assertEquals(
        'stdout', subprocess2.capture(['foo'], a=True))
    expected = {
        'args': ['foo'],
        'a':True,
        'stdin': subprocess2.VOID,
        'stdout': subprocess2.PIPE,
    }
    self.assertEquals(expected, results)

121
  def test_communicate_defaults(self):
122
    results = self._fake_Popen()
123 124
    self.assertEquals(
        ((None, None), -8), subprocess2.communicate(['foo'], a=True))
125 126 127 128 129 130 131 132 133
    expected = {
        'args': ['foo'],
        'a': True,
    }
    self.assertEquals(expected, results)

  def test_Popen_defaults(self):
    results = self._fake_subprocess_Popen()
    proc = subprocess2.Popen(['foo'], a=True)
134
    # Cleanup code in subprocess.py needs this member to be set.
135
    # pylint: disable=attribute-defined-outside-init
136
    proc._child_created = None
137 138 139 140 141
    expected = {
        'args': ['foo'],
        'a': True,
        'shell': bool(sys.platform=='win32'),
    }
142 143 144 145 146 147 148 149 150
    if sys.platform != 'win32':
      env = os.environ.copy()
      is_english = lambda name: env.get(name, 'en').startswith('en')
      if not is_english('LANG'):
        env['LANG'] = 'en_US.UTF-8'
        expected['env'] = env
      if not is_english('LANGUAGE'):
        env['LANGUAGE'] = 'en_US.UTF-8'
        expected['env'] = env
151
    self.assertEquals(expected, results)
152
    self.assertTrue(time.time() >= proc.start)
153

154
  def test_check_output_defaults(self):
155
    results = self._fake_communicate()
156
    # It's discarding 'stderr' because it assumes stderr=subprocess2.STDOUT but
157
    # fake_communicate() doesn't 'implement' that.
158 159 160 161
    self.assertEquals('stdout', subprocess2.check_output(['foo'], a=True))
    expected = {
        'args': ['foo'],
        'a':True,
162
        'stdin': subprocess2.VOID,
163 164 165 166
        'stdout': subprocess2.PIPE,
    }
    self.assertEquals(expected, results)

167

168
class BaseTestCase(unittest.TestCase):
169
  def setUp(self):
170
    super(BaseTestCase, self).setUp()
171 172 173 174 175 176 177 178 179 180 181
    self.exe_path = __file__
    self.exe = [sys.executable, self.exe_path, '--child']
    self.states = {}
    if fcntl:
      for v in (sys.stdin, sys.stdout, sys.stderr):
        fileno = v.fileno()
        self.states[fileno] = fcntl.fcntl(fileno, fcntl.F_GETFL)

  def tearDown(self):
    for fileno, fl in self.states.iteritems():
      self.assertEquals(fl, fcntl.fcntl(fileno, fcntl.F_GETFL))
182
    super(BaseTestCase, self).tearDown()
183

184 185 186 187 188 189
  def _check_res(self, res, stdout, stderr, returncode):
    (out, err), code = res
    self.assertEquals(stdout, out)
    self.assertEquals(stderr, err)
    self.assertEquals(returncode, code)

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

class RegressionTest(BaseTestCase):
  # Regression tests to ensure that subprocess and subprocess2 have the same
  # behavior.
  def _run_test(self, function):
    """Runs tests in 12 combinations:
    - LF output with universal_newlines=False
    - CR output with universal_newlines=False
    - CRLF output with universal_newlines=False
    - LF output with universal_newlines=True
    - CR output with universal_newlines=True
    - CRLF output with universal_newlines=True

    Once with subprocess, once with subprocess2.

    First |function| argument is the conversion for the original expected LF
    string to the right EOL.
    Second |function| argument is the executable and initial flag to run, to
    control what EOL is used by the child process.
    Third |function| argument is universal_newlines value.
    """
    noop = lambda x: x
    for subp in (subprocess, subprocess2):
      function(noop, self.exe, False, subp)
      function(convert_to_cr, self.exe + ['--cr'], False, subp)
      function(convert_to_crlf, self.exe + ['--crlf'], False, subp)
      function(noop, self.exe, True, subp)
      function(noop, self.exe + ['--cr'], True, subp)
      function(noop, self.exe + ['--crlf'], True, subp)

220
  def _check_exception(self, subp, e, stdout, stderr, returncode):
221
    """On exception, look if the exception members are set correctly."""
222
    self.assertEquals(returncode, e.returncode)
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    if subp is subprocess:
      # subprocess never save the output.
      self.assertFalse(hasattr(e, 'stdout'))
      self.assertFalse(hasattr(e, 'stderr'))
    elif subp is subprocess2:
      self.assertEquals(stdout, e.stdout)
      self.assertEquals(stderr, e.stderr)
    else:
      self.fail()

  def test_check_output_no_stdout(self):
    try:
      subprocess2.check_output(self.exe, stdout=subprocess2.PIPE)
      self.fail()
    except ValueError:
      pass
239

240 241 242
    if (sys.version_info[0] * 10 + sys.version_info[1]) >= 27:
      # python 2.7+
      try:
243
        # pylint: disable=no-member
244 245 246 247 248 249 250 251 252 253 254 255 256
        subprocess.check_output(self.exe, stdout=subprocess.PIPE)
        self.fail()
      except ValueError:
        pass

  def test_check_output_throw_stdout(self):
    def fn(c, e, un, subp):
      if not hasattr(subp, 'check_output'):
        return
      try:
        subp.check_output(
            e + ['--fail', '--stdout'], universal_newlines=un)
        self.fail()
257 258
      except subp.CalledProcessError, exception:
        self._check_exception(subp, exception, c('A\nBB\nCCC\n'), None, 64)
259 260 261 262 263 264 265 266 267 268
    self._run_test(fn)

  def test_check_output_throw_no_stderr(self):
    def fn(c, e, un, subp):
      if not hasattr(subp, 'check_output'):
        return
      try:
        subp.check_output(
            e + ['--fail', '--stderr'], universal_newlines=un)
        self.fail()
269 270
      except subp.CalledProcessError, exception:
        self._check_exception(subp, exception, c(''), None, 64)
271 272 273 274 275 276 277 278 279 280 281 282
    self._run_test(fn)

  def test_check_output_throw_stderr(self):
    def fn(c, e, un, subp):
      if not hasattr(subp, 'check_output'):
        return
      try:
        subp.check_output(
            e + ['--fail', '--stderr'],
            stderr=subp.PIPE,
            universal_newlines=un)
        self.fail()
283 284
      except subp.CalledProcessError, exception:
        self._check_exception(subp, exception, '', c('a\nbb\nccc\n'), 64)
285 286 287 288 289 290 291 292 293 294 295 296
    self._run_test(fn)

  def test_check_output_throw_stderr_stdout(self):
    def fn(c, e, un, subp):
      if not hasattr(subp, 'check_output'):
        return
      try:
        subp.check_output(
            e + ['--fail', '--stderr'],
            stderr=subp.STDOUT,
            universal_newlines=un)
        self.fail()
297 298
      except subp.CalledProcessError, exception:
        self._check_exception(subp, exception, c('a\nbb\nccc\n'), None, 64)
299 300 301 302 303 304 305
    self._run_test(fn)

  def test_check_call_throw(self):
    for subp in (subprocess, subprocess2):
      try:
        subp.check_call(self.exe + ['--fail', '--stderr'])
        self.fail()
306 307
      except subp.CalledProcessError, exception:
        self._check_exception(subp, exception, None, None, 64)
308

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
  def test_redirect_stderr_to_stdout_pipe(self):
    def fn(c, e, un, subp):
      # stderr output into stdout.
      proc = subp.Popen(
          e + ['--stderr'],
          stdout=subp.PIPE,
          stderr=subp.STDOUT,
          universal_newlines=un)
      res = proc.communicate(), proc.returncode
      self._check_res(res, c('a\nbb\nccc\n'), None, 0)
    self._run_test(fn)

  def test_redirect_stderr_to_stdout(self):
    def fn(c, e, un, subp):
      # stderr output into stdout but stdout is not piped.
      proc = subp.Popen(
          e + ['--stderr'], stderr=STDOUT, universal_newlines=un)
      res = proc.communicate(), proc.returncode
      self._check_res(res, None, None, 0)
    self._run_test(fn)

330 331
  def test_stderr(self):
    cmd = ['expr', '1', '/', '0']
332 333 334 335
    if sys.platform == 'win32':
      cmd = ['cmd.exe', '/c', 'exit', '1']
    p1 = subprocess.Popen(cmd, stderr=subprocess.PIPE, shell=False)
    p2 = subprocess2.Popen(cmd, stderr=subprocess.PIPE, shell=False)
336 337 338 339
    r1 = p1.communicate()
    r2 = p2.communicate(timeout=100)
    self.assertEquals(r1, r2)

340 341 342 343

class S2Test(BaseTestCase):
  # Tests that can only run in subprocess2, e.g. new functionalities.
  # In particular, subprocess2.communicate() doesn't exist in subprocess.
344 345 346 347 348 349 350 351 352
  def _run_test(self, function):
    """Runs tests in 6 combinations:
    - LF output with universal_newlines=False
    - CR output with universal_newlines=False
    - CRLF output with universal_newlines=False
    - LF output with universal_newlines=True
    - CR output with universal_newlines=True
    - CRLF output with universal_newlines=True

353
    First |function| argument is the conversion for the origianl expected LF
354 355 356 357 358 359 360 361 362 363 364 365 366
    string to the right EOL.
    Second |function| argument is the executable and initial flag to run, to
    control what EOL is used by the child process.
    Third |function| argument is universal_newlines value.
    """
    noop = lambda x: x
    function(noop, self.exe, False)
    function(convert_to_cr, self.exe + ['--cr'], False)
    function(convert_to_crlf, self.exe + ['--crlf'], False)
    function(noop, self.exe, True)
    function(noop, self.exe + ['--cr'], True)
    function(noop, self.exe + ['--crlf'], True)

367 368 369 370 371
  def _check_exception(self, e, stdout, stderr, returncode):
    """On exception, look if the exception members are set correctly."""
    self.assertEquals(returncode, e.returncode)
    self.assertEquals(stdout, e.stdout)
    self.assertEquals(stderr, e.stderr)
372

373
  def test_timeout(self):
374 375
    # timeout doesn't exist in subprocess.
    def fn(c, e, un):
376
      res = subprocess2.communicate(
377 378
          self.exe + ['--sleep_first', '--stdout'],
          timeout=0.01,
379
          stdout=PIPE,
380
          shell=False)
381 382 383 384 385 386 387 388 389 390 391
      self._check_res(res, '', None, TIMED_OUT)
    self._run_test(fn)

  def test_timeout_shell_throws(self):
    def fn(c, e, un):
      try:
        # With shell=True, it needs a string.
        subprocess2.communicate(' '.join(self.exe), timeout=0.01, shell=True)
        self.fail()
      except TypeError:
        pass
392
    self._run_test(fn)
393

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
  def test_stdin(self):
    def fn(c, e, un):
      stdin = '0123456789'
      res = subprocess2.communicate(
          e + ['--read'],
          stdin=stdin,
          universal_newlines=un)
      self._check_res(res, None, None, 10)
    self._run_test(fn)

  def test_stdin_unicode(self):
    def fn(c, e, un):
      stdin = u'0123456789'
      res = subprocess2.communicate(
          e + ['--read'],
          stdin=stdin,
          universal_newlines=un)
      self._check_res(res, None, None, 10)
    self._run_test(fn)

414 415 416 417 418 419 420 421 422 423
  def test_stdin_empty(self):
    def fn(c, e, un):
      stdin = ''
      res = subprocess2.communicate(
          e + ['--read'],
          stdin=stdin,
          universal_newlines=un)
      self._check_res(res, None, None, 0)
    self._run_test(fn)

424 425 426 427 428 429 430 431 432 433 434 435
  def test_stdin_void(self):
    res = subprocess2.communicate(self.exe + ['--read'], stdin=VOID)
    self._check_res(res, None, None, 0)

  def test_stdin_void_stdout_timeout(self):
    # Make sure a mix of VOID, PIPE and timeout works.
    def fn(c, e, un):
      res = subprocess2.communicate(
          e + ['--stdout', '--read'],
          stdin=VOID,
          stdout=PIPE,
          timeout=10,
436 437
          universal_newlines=un,
          shell=False)
438 439 440
      self._check_res(res, c('A\nBB\nCCC\n'), None, 0)
    self._run_test(fn)

441
  def test_stdout_void(self):
442
    def fn(c, e, un):
443
      res = subprocess2.communicate(
444
          e + ['--stdout', '--stderr'],
445 446
          stdout=VOID,
          stderr=PIPE,
447
          universal_newlines=un)
448
      self._check_res(res, None, c('a\nbb\nccc\n'), 0)
449
    self._run_test(fn)
450 451

  def test_stderr_void(self):
452
    def fn(c, e, un):
453
      res = subprocess2.communicate(
454
          e + ['--stdout', '--stderr'],
455 456
          stdout=PIPE,
          stderr=VOID,
457
          universal_newlines=un)
458 459 460 461 462 463 464 465 466 467 468
      self._check_res(res, c('A\nBB\nCCC\n'), None, 0)
    self._run_test(fn)

  def test_stdout_void_stderr_redirect(self):
    def fn(c, e, un):
      res = subprocess2.communicate(
          e + ['--stdout', '--stderr'],
          stdout=VOID,
          stderr=STDOUT,
          universal_newlines=un)
      self._check_res(res, None, None, 0)
469
    self._run_test(fn)
470

471
  def test_tee_stderr(self):
472
    def fn(c, e, un):
473
      stderr = []
474
      res = subprocess2.communicate(
475 476 477 478 479 480 481 482 483 484 485 486 487
          e + ['--stderr'], stderr=stderr.append, universal_newlines=un)
      self.assertEquals(c('a\nbb\nccc\n'), ''.join(stderr))
      self._check_res(res, None, None, 0)
    self._run_test(fn)

  def test_tee_stdout_stderr(self):
    def fn(c, e, un):
      stdout = []
      stderr = []
      res = subprocess2.communicate(
          e + ['--stdout', '--stderr'],
          stdout=stdout.append,
          stderr=stderr.append,
488
          universal_newlines=un)
489 490 491
      self.assertEquals(c('A\nBB\nCCC\n'), ''.join(stdout))
      self.assertEquals(c('a\nbb\nccc\n'), ''.join(stderr))
      self._check_res(res, None, None, 0)
492 493
    self._run_test(fn)

494
  def test_tee_stdin(self):
495
    def fn(c, e, un):
496
      # Mix of stdin input and stdout callback.
497 498
      stdout = []
      stdin = '0123456789'
499
      res = subprocess2.communicate(
500 501 502
          e + ['--stdout', '--read'],
          stdin=stdin,
          stdout=stdout.append,
503 504
          universal_newlines=un)
      self.assertEquals(c('A\nBB\nCCC\n'), ''.join(stdout))
505
      self._check_res(res, None, None, 10)
506 507
    self._run_test(fn)

508 509
  def test_tee_throw(self):
    def fn(c, e, un):
510
      # Make sure failure still returns stderr completely.
511 512 513
      stderr = []
      try:
        subprocess2.check_output(
514 515
            e + ['--stderr', '--fail'],
            stderr=stderr.append,
516 517
            universal_newlines=un)
        self.fail()
518 519
      except subprocess2.CalledProcessError, exception:
        self._check_exception(exception, '', None, 64)
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
        self.assertEquals(c('a\nbb\nccc\n'), ''.join(stderr))
    self._run_test(fn)

  def test_tee_timeout_stdout_void(self):
    def fn(c, e, un):
      stderr = []
      res = subprocess2.communicate(
          e + ['--stdout', '--stderr', '--fail'],
          stdout=VOID,
          stderr=stderr.append,
          shell=False,
          timeout=10,
          universal_newlines=un)
      self._check_res(res, None, None, 64)
      self.assertEquals(c('a\nbb\nccc\n'), ''.join(stderr))
    self._run_test(fn)

  def test_tee_timeout_stderr_void(self):
    def fn(c, e, un):
      stdout = []
      res = subprocess2.communicate(
          e + ['--stdout', '--stderr', '--fail'],
          stdout=stdout.append,
          stderr=VOID,
          shell=False,
          timeout=10,
          universal_newlines=un)
      self._check_res(res, None, None, 64)
      self.assertEquals(c('A\nBB\nCCC\n'), ''.join(stdout))
    self._run_test(fn)

  def test_tee_timeout_stderr_stdout(self):
    def fn(c, e, un):
      stdout = []
      res = subprocess2.communicate(
          e + ['--stdout', '--stderr', '--fail'],
          stdout=stdout.append,
          stderr=STDOUT,
          shell=False,
          timeout=10,
          universal_newlines=un)
      self._check_res(res, None, None, 64)
      # Ordering is random due to buffering.
      self.assertEquals(
          set(c('a\nbb\nccc\nA\nBB\nCCC\n').splitlines(True)),
          set(''.join(stdout).splitlines(True)))
    self._run_test(fn)

  def test_tee_large(self):
    stdout = []
    # Read 128kb. On my workstation it takes >2s. Welcome to 2011.
    res = subprocess2.communicate(self.exe + ['--large'], stdout=stdout.append)
    self.assertEquals(128*1024, len(''.join(stdout)))
    self._check_res(res, None, None, 0)

  def test_tee_large_stdin(self):
    stdout = []
    # Write 128kb.
    stdin = '0123456789abcdef' * (8*1024)
    res = subprocess2.communicate(
        self.exe + ['--large', '--read'], stdin=stdin, stdout=stdout.append)
    self.assertEquals(128*1024, len(''.join(stdout)))
582 583 584
    # Windows return code is > 8 bits.
    returncode = len(stdin) if sys.platform == 'win32' else 0
    self._check_res(res, None, None, returncode)
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599

  def test_tee_cb_throw(self):
    # Having a callback throwing up should not cause side-effects. It's a bit
    # hard to measure.
    class Blow(Exception):
      pass
    def blow(_):
      raise Blow()
    proc = subprocess2.Popen(self.exe + ['--stdout'], stdout=blow)
    try:
      proc.communicate()
      self.fail()
    except Blow:
      self.assertNotEquals(0, proc.returncode)

szager@chromium.org's avatar
szager@chromium.org committed
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
  def test_nag_timer(self):
    w = []
    l = logging.getLogger()
    class _Filter(logging.Filter):
      def filter(self, record):
        if record.levelno == logging.WARNING:
          w.append(record.getMessage().lstrip())
        return 0
    f = _Filter()
    l.addFilter(f)
    proc = subprocess2.Popen(
        self.exe + ['--stdout', '--sleep_first'], stdout=PIPE)
    res = proc.communicate(nag_timer=3), proc.returncode
    l.removeFilter(f)
    self._check_res(res, 'A\nBB\nCCC\n', None, 0)
    expected = ['No output for 3 seconds from command:', proc.cmd_str,
                'No output for 6 seconds from command:', proc.cmd_str,
                'No output for 9 seconds from command:', proc.cmd_str]
    self.assertEquals(w, expected)
619

620

621
def child_main(args):
622 623
  if sys.platform == 'win32':
    # Annoying, make sure the output is not translated on Windows.
624
    # pylint: disable=no-member,import-error
625 626 627 628
    import msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
    msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)

629 630 631 632 633 634 635
  parser = optparse.OptionParser()
  parser.add_option(
      '--fail',
      dest='return_value',
      action='store_const',
      default=0,
      const=64)
636 637 638 639
  parser.add_option(
      '--crlf', action='store_const', const='\r\n', dest='eol', default='\n')
  parser.add_option(
      '--cr', action='store_const', const='\r', dest='eol')
640 641
  parser.add_option('--stdout', action='store_true')
  parser.add_option('--stderr', action='store_true')
642 643 644 645
  parser.add_option('--sleep_first', action='store_true')
  parser.add_option('--sleep_last', action='store_true')
  parser.add_option('--large', action='store_true')
  parser.add_option('--read', action='store_true')
646 647 648
  options, args = parser.parse_args(args)
  if args:
    parser.error('Internal error')
649 650
  if options.sleep_first:
    time.sleep(10)
651 652 653

  def do(string):
    if options.stdout:
654 655
      sys.stdout.write(string.upper())
      sys.stdout.write(options.eol)
656
    if options.stderr:
657 658
      sys.stderr.write(string.lower())
      sys.stderr.write(options.eol)
659 660 661 662

  do('A')
  do('BB')
  do('CCC')
663 664 665 666 667
  if options.large:
    # Print 128kb.
    string = '0123456789abcdef' * (8*1024)
    sys.stdout.write(string)
  if options.read:
668
    assert options.return_value is 0
669
    try:
670 671
      while sys.stdin.read(1):
        options.return_value += 1
672 673 674
    except OSError:
      pass
  if options.sleep_last:
675
    time.sleep(10)
676 677 678 679
  return options.return_value


if __name__ == '__main__':
680 681 682
  logging.basicConfig(level=
      [logging.WARNING, logging.INFO, logging.DEBUG][
        min(2, sys.argv.count('-v'))])
683 684 685
  if len(sys.argv) > 1 and sys.argv[1] == '--child':
    sys.exit(child_main(sys.argv[2:]))
  unittest.main()