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
Provenance
- Commit
15f0e22- Tree
e938ba3- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
75a3443
3 files changed+113 added−22 removed
modified:click/testing.py+53 added-20 removed
10 unmodified lines11 if PY2:12 from cStringIO import StringIO13 else:14 import io15+ from ._compat import _find_binary_reader16 17 18 class EchoingStdin(object):19 19 unmodified lines39 40 def __iter__(self):41 return iter(self._echo(x) for x in self._input)42 43+ def __repr__(self):44+ return repr(self._input)45 46+47+def 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.')56+57+ 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)64+65+66 class Result(object):67 """Holds the captured result of an invoked CLI script."""68 69 def __init__(self, runner, output_bytes, exit_code, exception):22 unmodified lines92 """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.96+97+ :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 """106 75- 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_stdin113 114 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 not20 unmodified lines137 138 :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)142 143+ old_stdin = sys.stdin144 old_stdout = sys.stdout145 old_stderr = sys.stderr146 147 env = self.make_env(env)148 149 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)160 161+ sys.stdin = input162+163 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 lines187 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 lines199 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_func206 175- 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 lines222 exception = None223 exit_code = 0224 225 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()237 238 return Result(runner=self,239 output_bytes=output,19 unmodified linesmodified:click/types.py+3 added-2 removed
69 unmodified lines70 71 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 linesadded:tests/test_testing.py+57 added
1+import click2+3+from click.testing import CliRunner4+5+from click._compat import PY26+7+# Use the most reasonable io that users would use for the python version.8+if PY2:9+ from cStringIO import StringIO as ReasonableBytesIO10+else:11+ from io import BytesIO as ReasonableBytesIO12+13+14+def 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()25+26+ runner = CliRunner()27+ result = runner.invoke(test, input='Hello World!\n')28+ assert not result.exception29+ assert result.output == 'Hello World!\n'30+31+ 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'35+36+37+def 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()48+49+ runner = CliRunner()50+ result = runner.invoke(test, input=ReasonableBytesIO(b'Hello World!\n'))51+ assert not result.exception52+ assert result.output == 'Hello World!\n'53+54+ 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'