Skip to content
Myr

CliRunner: add stdout / stderr, allow separating standard streams (#868)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* add separated stderr to test runner

authored by Dave Carlson · committed by Dan Sully · parent b1b4449 · Browse files · 4 files+83 added−22 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+83 added−22 removed

  • tests:+31 added−7 removed
  • other:+52 added−15 removed

4 files+83 added−22 removed

modified:click/testing.py+52 added-15 removed
71 unmodified lines
7273class Result(object):74 """Holds the captured result of an invoked CLI script."""7576 def __init__(self, runner, output_bytes, exit_code, exception,77 exc_info=None):76 def __init__(self, runner, stdout_bytes, stderr_bytes, exit_code,77 exception, exc_info=None):78 #: The runner that created the result79 self.runner = runner80 #: The output as bytes.81 self.output_bytes = output_bytes80 #: The standard output as bytes.81 self.stdout_bytes = stdout_bytes82 #: The standard error as bytes, or False(y) if not available83 self.stderr_bytes = stderr_bytes84 #: The exit code as integer.85 self.exit_code = exit_code86 #: The exception that happend if one did.87 self.exception = exception
1 unmodified line
89 self.exc_info = exc_info9091 @property92 def output(self):91 """The output as unicode string."""92 return self.output_bytes.decode(self.runner.charset, 'replace') \93 """The (standard) output as unicode string."""94 return self.stdout9596 @property97 def stdout(self):98 """The standard output as unicode string."""99 return self.stdout_bytes.decode(self.runner.charset, 'replace') \100 .replace('\r\n', '\n')101102 @property103 def stderr(self):104 """The standard error as unicode string."""105 if not self.stderr_bytes:106 raise ValueError("stderr not separately captured")107 return self.stderr_bytes.decode(self.runner.charset, 'replace') \108 .replace('\r\n', '\n')109110111 def __repr__(self):96 return '<Result %s>' % (112 return '<%s %s>' % (113 type(self).__name__,114 self.exception and repr(self.exception) or 'okay',115 )116117
10 unmodified lines
128 :param echo_stdin: if this is set to `True`, then reading from stdin writes129 to stdout. This is useful for showing examples in130 some circumstances. Note that regular prompts131 will automatically echo the input.132 :param mix_stderr: if this is set to `False`, then stdout and stderr are133 preserved as independent streams. This is useful for134 Unix-philosophy apps that have predictable stdout and135 noisy stderr, such that each may be measured136 independently137 """138117 def __init__(self, charset=None, env=None, echo_stdin=False):139 def __init__(self, charset=None, env=None, echo_stdin=False,140 mix_stderr=True):141 if charset is None:142 charset = 'utf-8'143 self.charset = charset144 self.env = env or {}145 self.echo_stdin = echo_stdin146 self.mix_stderr = mix_stderr147148 def get_default_prog_name(self, cli):149 """Given a command object it will return the default program name150 for it. The default is the `name` attribute or ``"root"`` if not
36 unmodified lines
187188 env = self.make_env(env)189190 if PY2:167 sys.stdout = sys.stderr = bytes_output = StringIO()191 bytes_output = StringIO()192 if self.echo_stdin:193 input = EchoingStdin(input, bytes_output)194 sys.stdout = bytes_output195 if not self.mix_stderr:196 bytes_error = StringIO()197 sys.stderr = bytes_error198 else:199 bytes_output = io.BytesIO()200 if self.echo_stdin:201 input = EchoingStdin(input, bytes_output)202 input = io.TextIOWrapper(input, encoding=self.charset)175 sys.stdout = sys.stderr = io.TextIOWrapper(203 sys.stdout = io.TextIOWrapper(204 bytes_output, encoding=self.charset)205 if not self.mix_stderr:206 bytes_error = io.BytesIO()207 sys.stderr = io.TextIOWrapper(208 bytes_error, encoding=self.charset)209210 if self.mix_stderr:211 sys.stderr = sys.stdout212213 sys.stdin = input214215 def visible_input(prompt=None):216 sys.stdout.write(prompt or '')
40 unmodified lines
257 except Exception:258 pass259 else:260 os.environ[key] = value226 yield bytes_output261 yield (bytes_output, not self.mix_stderr and bytes_error)262 finally:263 for key, value in iteritems(old_env):264 if value is None:265 try:
11 unmodified lines
277 clickpkg.utils.should_strip_ansi = old_should_strip_ansi278 clickpkg.formatting.FORCED_WIDTH = old_forced_width279280 def invoke(self, cli, args=None, input=None, env=None,246 catch_exceptions=True, color=False, **extra):281 catch_exceptions=True, color=False, mix_stderr=False, **extra):282 """Invokes a command in an isolated environment. The arguments are283 forwarded directly to the command line script, the `extra` keyword284 arguments are passed to the :meth:`~clickpkg.Command.main` function of285 the command.
23 unmodified lines
309 :param color: whether the output should contain color codes. The310 application can still override this explicitly.311 """312 exc_info = None278 with self.isolation(input=input, env=env, color=color) as out:313 with self.isolation(input=input, env=env, color=color) as outstreams:314 exception = None315 exit_code = 0316317 if isinstance(args, string_types):
23 unmodified lines
341 exit_code = 1342 exc_info = sys.exc_info()343 finally:344 sys.stdout.flush()310 output = out.getvalue()345 stdout = outstreams[0].getvalue()346 stderr = outstreams[1] and outstreams[1].getvalue()347348 return Result(runner=self,313 output_bytes=output,349 stdout_bytes=stdout,350 stderr_bytes=stderr,351 exit_code=exit_code,352 exception=exception,353 exc_info=exc_info)354
16 unmodified lines
modified:tests/test_termui.py+2 added-2 removed
76 unmodified lines
77 assert '(none, day, week, month)' not in result.output787980def test_secho(runner):81 with runner.isolation() as out:81 with runner.isolation() as outstreams:82 click.secho(None, nl=False)83 bytes = out.getvalue()83 bytes = outstreams[0].getvalue()84 assert bytes == b''
modified:tests/test_testing.py+24 added
202 unmodified lines
203204 assert os.environ == env_orig205206207def test_stderr():208 @click.command()209 def cli_stderr():210 click.echo("stdout")211 click.echo("stderr", err=True)212213 runner = CliRunner(mix_stderr=False)214215 result = runner.invoke(cli_stderr)216217 assert result.output == 'stdout\n'218 assert result.stdout == 'stdout\n'219 assert result.stderr == 'stderr\n'220221 runner_mix = CliRunner(mix_stderr=True)222 result_mix = runner_mix.invoke(cli_stderr)223224 assert result_mix.output == 'stdout\nstderr\n'225 assert result_mix.stdout == 'stdout\nstderr\n'226227 with pytest.raises(ValueError):228 result_mix.stderr229230231@pytest.mark.parametrize('args, expected_output', [232 (None, 'bar\n'),233 ([], 'bar\n'),234 ('', 'bar\n'),
14 unmodified lines
modified:tests/test_utils.py+5 added-5 removed
8 unmodified lines
9from click._compat import WIN, PY2101112def test_echo(runner):13 with runner.isolation() as out:13 with runner.isolation() as outstreams:14 click.echo(u'\N{SNOWMAN}')15 click.echo(b'\x44\x44')16 click.echo(42, nl=False)17 click.echo(b'a', nl=False)18 click.echo('\x1b[31mx\x1b[39m', nl=False)19 bytes = out.getvalue().replace(b'\r\n', b'\n')19 bytes = outstreams[0].getvalue().replace(b'\r\n', b'\n')20 assert bytes == b'\xe2\x98\x83\nDD\n42ax'2122 # If we are in Python 2, we expect that writing bytes into a string io23 # does not do anything crazy. In Python 3
10 unmodified lines
34 @click.command()35 def cli():36 click.echo(b'\xf6')37 result = runner.invoke(cli, [])38 assert result.output_bytes == b'\xf6\n'38 assert result.stdout_bytes == b'\xf6\n'3940 # Ensure we do not strip for bytes.41 with runner.isolation() as out:41 with runner.isolation() as outstreams:42 click.echo(bytearray(b'\x1b[31mx\x1b[39m'), nl=False)43 assert out.getvalue() == b'\x1b[31mx\x1b[39m'43 assert outstreams[0].getvalue() == b'\x1b[31mx\x1b[39m'444546def test_echo_custom_file():47 import io
259 unmodified lines