Skip to content
Myr

Added tests for stream wrapping.

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

authored by Armin Ronacher · committed by Armin Ronacher · parent 75a3443 · Browse files · 3 files+113 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

3 files+113 added−22 removed

  • tests:+57 added−0 removed
  • other:+56 added−22 removed

3 files+113 added−22 removed

modified:click/testing.py+53 added-20 removed
10 unmodified lines
11if PY2:12 from cStringIO import StringIO13else:14 import io15 from ._compat import _find_binary_reader161718class EchoingStdin(object):19
19 unmodified lines
3940 def __iter__(self):41 return iter(self._echo(x) for x in self._input)4243 def __repr__(self):44 return repr(self._input)454647def make_input_stream(input, charset):48 # Is already an input stream.49 if hasattr(input, 'read'):50 if PY2:51 return input52 rv = _find_binary_reader(input)53 if rv is not None:54 return rv55 raise TypeError('Could not find binary reader for input stream.')5657 if input is None:58 input = b''59 elif not isinstance(input, bytes):60 input = input.encode(charset)61 if PY2:62 return StringIO(input)63 return io.BytesIO(input)646566class Result(object):67 """Holds the captured result of an invoked CLI script."""6869 def __init__(self, runner, output_bytes, exit_code, exception):
22 unmodified lines
92 """The CLI runner provides functionality to invoke a Click command line93 script for unittesting purposes in a isolated environment. This only94 works in single-threaded systems without any concurrency as it changes95 global interpreter state.9697 :param charset: the character set for the input and output data. This is98 utf-8 by default and should not be changed currently as99 the reporting to click only works on Python 2 properly.100 :param env: a dictionary with environment variables for overriding.101 :param echo_stdin: if this is set to `True`, then reading from stdin writes102 to stdout. This is useful for showing examples in103 some circumstances. Note that regular prompts104 will automatically echo the input.105 """10675 def __init__(self, charset=None, env=None):107 def __init__(self, charset=None, env=None, echo_stdin=False):108 if charset is None:109 charset = 'utf-8'110 self.charset = charset111 self.env = env or {}112 self.echo_stdin = echo_stdin113114 def get_default_prog_name(self, cli):115 """Given a command object it will return the default program name116 for it. The default is the `name` attribute or ``"root"`` if not
20 unmodified lines
137138 :param input: the input stream to put into sys.stdin.139 :param env: the environment overrides as dictionary.140 """108 if hasattr(input, 'read'):109 input = input.read()110 if input is not None and not isinstance(input, bytes):111 input = input.encode(self.charset)141 input = make_input_stream(input, self.charset)142143 old_stdin = sys.stdin144 old_stdout = sys.stdout145 old_stderr = sys.stderr146147 env = self.make_env(env)148149 if PY2:119 input = StringIO(input or '')120 output = StringIO()121 sys.stdin = EchoingStdin(input, output)122 sys.stdin.encoding = self.charset123 sys.stdout = sys.stderr = output150 sys.stdout = sys.stderr = bytes_output = StringIO()151 if self.echo_stdin:152 input = EchoingStdin(input, bytes_output)153 else:125 real_input = io.BytesIO(input)126 output = io.BytesIO()127 input = io.TextIOWrapper(real_input, encoding=self.charset)128 sys.stdin = EchoingStdin(real_input, output)129 sys.stdout = sys.stderr = io.TextIOWrapper(output,130 encoding=self.charset)154 bytes_output = io.BytesIO()155 if self.echo_stdin:156 input = EchoingStdin(input, bytes_output)157 input = io.TextIOWrapper(input, encoding=self.charset)158 sys.stdout = sys.stderr = io.TextIOWrapper(159 bytes_output, encoding=self.charset)160161 sys.stdin = input162163 def visible_input(prompt=None):164 sys.stdout.write(prompt or '')165 val = input.readline().rstrip('\r\n')166 sys.stdout.write(val + '\n')
20 unmodified lines
187 except Exception:188 pass189 else:190 os.environ[key] = value160 yield output191 yield bytes_output192 finally:193 for key, value in iteritems(old_env):194 if value is None:195 try:
3 unmodified lines
199 else:200 os.environ[key] = value201 sys.stdout = old_stdout202 sys.stderr = old_stderr203 sys.stdin = old_stdin204 click.termui.visible_prompt_func = old_visible_prompt_func205 click.termui.hidden_prompt_func = old_hidden_prompt_func206175 def invoke(self, cli, args, input=None, env=None, **extra):207 def invoke(self, cli, args=None, input=None, env=None, **extra):208 """Invokes a command in an isolated environment. The arguments are209 forwarded directly to the command line script, the `extra` keyword210 arguments are passed to the :meth:`~click.Command.main` function of211 the command.
10 unmodified lines
222 exception = None223 exit_code = 0224225 try:194 cli.main(args=args, prog_name=self.get_default_prog_name(cli),195 **extra)226 cli.main(args=args or (),227 prog_name=self.get_default_prog_name(cli), **extra)228 except SystemExit as e:229 if e.code != 0:230 exception = e231 exit_code = e.code232 except Exception as e:233 exception = e234 exit_code = -1235 sys.stdout.flush()236 output = out.getvalue()237238 return Result(runner=self,239 output_bytes=output,
19 unmodified lines
modified:click/types.py+3 added-2 removed
69 unmodified lines
7071 def convert(self, value, param, ctx):72 if isinstance(value, bytes):73 try:74 if sys.stdin.encoding is not None:75 value = value.decode(sys.stdin.encoding)74 enc = getattr(sys.stdin, 'encoding', None)75 if enc is not None:76 value = value.decode(enc)77 except UnicodeError:78 try:79 value = value.decode(sys.getfilesystemencoding())80 except UnicodeError:
318 unmodified lines
added:tests/test_testing.py+57 added
1import click23from click.testing import CliRunner45from click._compat import PY267# Use the most reasonable io that users would use for the python version.8if PY2:9 from cStringIO import StringIO as ReasonableBytesIO10else:11 from io import BytesIO as ReasonableBytesIO121314def test_runner():15 @click.command()16 def test():17 i = click.get_binary_stream('stdin')18 o = click.get_binary_stream('stdout')19 while 1:20 chunk = i.read(4096)21 if not chunk:22 break23 o.write(chunk)24 o.flush()2526 runner = CliRunner()27 result = runner.invoke(test, input='Hello World!\n')28 assert not result.exception29 assert result.output == 'Hello World!\n'3031 runner = CliRunner(echo_stdin=True)32 result = runner.invoke(test, input='Hello World!\n')33 assert not result.exception34 assert result.output == 'Hello World!\nHello World!\n'353637def test_runner_with_stream():38 @click.command()39 def test():40 i = click.get_binary_stream('stdin')41 o = click.get_binary_stream('stdout')42 while 1:43 chunk = i.read(4096)44 if not chunk:45 break46 o.write(chunk)47 o.flush()4849 runner = CliRunner()50 result = runner.invoke(test, input=ReasonableBytesIO(b'Hello World!\n'))51 assert not result.exception52 assert result.output == 'Hello World!\n'5354 runner = CliRunner(echo_stdin=True)55 result = runner.invoke(test, input=ReasonableBytesIO(b'Hello World!\n'))56 assert not result.exception57 assert result.output == 'Hello World!\nHello World!\n'