Skip to content
Myr

Moved the test code into the API

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 f3ee4e5 · Browse files · 3 files+228 added−151 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+228 added−151 removed

  • tests:+1 added−151 removed
  • other:+227 added−0 removed

3 files+228 added−151 removed

added:click/testing.py+216 added
1import os2import sys3import click4import shutil5import tempfile6import contextlib78from ._compat import iteritems, PY291011if PY2:12 from cStringIO import StringIO13else:14 import io151617class EchoingStdin(object):1819 def __init__(self, input, output):20 self._input = input21 self._output = output2223 def __getattr__(self, x):24 return getattr(self._input, x)2526 def _echo(self, rv):27 self._output.write(rv)28 return rv2930 def read(self, n=-1):31 return self._echo(self._input.read(n))3233 def readline(self, n=-1):34 return self._echo(self._input.readline(n))3536 def readlines(self):37 return [self._echo(x) for x in self._input.readlines()]3839 def __iter__(self):40 return iter(self._echo(x) for x in self._input)414243class Result(object):44 """Holds the captured result of an invoked CLI script."""4546 def __init__(self, output, exit_code, exception):47 #: The output as unicode string.48 self.output = output49 #: The exit code as integer.50 self.exit_code = exit_code51 #: The exception that happend if one did.52 self.exception = exception5354 def __repr__(self):55 return '<Result %s>' % (56 self.exception and repr(self.exception) or 'okay',57 )585960class CliRunner(object):61 """The CLI runner provides functionality to invoke a Click command line62 script for unittesting purposes in a isolated environment. This only63 works in single-threaded systems without any concurrency as it changes64 global interpreter state.65 """6667 def __init__(self, charset=None, env=None):68 if charset is None:69 charset = 'utf-8'70 self.charset = charset71 self.env = env or {}7273 def get_default_prog_name(self, cli):74 """Given a command object it will return the default program name75 for it. The default is the `name` attribute or ``"root"`` if not76 set.77 """78 return cli.name or 'root'7980 def make_env(self, overrides=None):81 """Returns the environment overrides for invoking a script."""82 rv = dict(self.env)83 if overrides:84 rv.update(overrides)85 return rv8687 @contextlib.contextmanager88 def isolation(self, input=None, env=None):89 """A context manager that set up the isolation for invoking of a90 command line tool. This sets up stdin with the given input data,91 and `os.environ` with the overrides from the given dictionary.92 This also rebinds some internals in Click to be mocked (like the93 prompt functionality).9495 This is automatically done in the :meth:`invoke` method.9697 :param input: the input stream to put into sys.stdin.98 :param env: the environment overrides as dictionary.99 """100 if hasattr(input, 'read'):101 input = input.read()102 if input is not None and not isinstance(input, bytes):103 input = input.encode(self.charset)104105 old_stdout = sys.stdout106 old_stderr = sys.stderr107108 env = self.make_env(env)109110 if PY2:111 input = StringIO(input or '')112 output = StringIO()113 sys.stdin = EchoingStdin(input, output)114 sys.stdin.encoding = self.charset115 sys.stdout = sys.stderr = output116 else:117 real_input = io.BytesIO(input)118 output = io.BytesIO()119 input = io.TextIOWrapper(real_input, encoding=self.charset)120 sys.stdin = EchoingStdin(real_input, output)121 sys.stdout = sys.stderr = io.TextIOWrapper(output,122 encoding=self.charset)123124 def visible_input(prompt=None):125 sys.stdout.write(prompt or '')126 val = input.readline().rstrip('\r\n')127 sys.stdout.write(val + '\n')128 sys.stdout.flush()129 return val130131 def hidden_input(prompt=None):132 sys.stdout.write((prompt or '') + '\n')133 sys.stdout.flush()134 return input.readline().rstrip('\r\n')135136 old_visible_prompt_func = click.termui.visible_prompt_func137 old_hidden_prompt_func = click.termui.hidden_prompt_func138 click.termui.visible_prompt_func = visible_input139 click.termui.hidden_prompt_func = hidden_input140141 old_env = {}142 try:143 for key, value in iteritems(env):144 old_env[key] = os.environ.get(value)145 if value is None:146 try:147 del os.environ[key]148 except Exception:149 pass150 else:151 os.environ[key] = value152 yield output153 finally:154 for key, value in iteritems(old_env):155 if value is None:156 try:157 del os.environ[key]158 except Exception:159 pass160 else:161 os.environ[key] = value162 sys.stdout = old_stdout163 sys.stderr = old_stderr164 click.termui.visible_prompt_func = old_visible_prompt_func165 click.termui.hidden_prompt_func = old_hidden_prompt_func166167 def invoke(self, cli, args, input=None, env=None, **extra):168 """Invokes a command in an isolated environment. The arguments are169 forwarded directly to the command line script, the `extra` keyword170 arguments are passed to the :meth:`~click.Command.main` function of171 the command.172173 This returns a :class:`Result` object.174175 :param cli: the command to invoke176 :param args: the arguments to invoke177 :param input: the input data for `sys.stdin`.178 :param env: the environment overrides.179 :param extra: the keyword arguments to pass to :meth:`main`.180 """181 with self.isolation(input=input, env=env) as out:182 exception = None183 exit_code = 0184185 try:186 cli.main(args=args, prog_name=self.get_default_prog_name(cli),187 **extra)188 except SystemExit as e:189 if e.code != 0:190 exception = e191 exit_code = e.code192 except Exception as e:193 exception = e194 exit_code = -1195 output = out.getvalue().decode(self.charset).replace('\r\n', '\n')196197 return Result(output=output,198 exit_code=exit_code,199 exception=exception)200201 @contextlib.contextmanager202 def isolated_filesystem(self):203 """A context manager that creates a temporary folder and changes204 the current working directory to it for isolated filesystem tests.205 """206 cwd = os.getcwd()207 t = tempfile.mkdtemp()208 os.chdir(t)209 try:210 yield211 finally:212 os.chdir(cwd)213 try:214 shutil.rmtree(t)215 except (OSError, IOError):216 pass
modified:docs/api.rst+11 added
120 unmodified lines
121-------122123.. autoclass:: OptionParser124 :members:125126Testing127-------128129.. currentmodule:: click.testing130131.. autoclass:: CliRunner132 :members:133134.. autoclass:: Result135 :members:
modified:tests/conftest.py+1 added-151 removed
1import os2import sys3import click4import shutil5import tempfile6import contextlib1from click.testing import CliRunner23import pytest410PY2 = sys.version_info[0] == 211if PY2:12 from cStringIO import StringIO13 iteritems = lambda x: x.iteritems()14else:15 import io16 iteritems = lambda x: iter(x.items())51819class EchoingStdin(object):2021 def __init__(self, input, output):22 self._input = input23 self._output = output2425 def __getattr__(self, x):26 return getattr(self._input, x)2728 def _echo(self, rv):29 mark = False30 if rv.endswith('\xff'):31 rv = rv[:-1]32 mark = True33 self._output.write(rv)34 if mark:35 self._output.write('^D\n')36 return rv3738 def read(self, n=-1):39 return self._echo(self._input.read(n))4041 def readline(self, n=-1):42 return self._echo(self._input.readline(n))4344 def readlines(self):45 return [self._echo(x) for x in self._input.readlines()]4647 def __iter__(self):48 return iter(self._echo(x) for x in self._input)495051class Result(object):5253 def __init__(self, output, exit_code, exception):54 self.output = output55 self.exit_code = exit_code56 self.exception = exception575859class CliRunner(object):6061 @contextlib.contextmanager62 def isolation(self, input=None, env=None):63 if input is not None and not isinstance(input, bytes):64 input = input.encode('utf-8')6566 old_stdout = sys.stdout67 old_stderr = sys.stderr6869 if PY2:70 input = StringIO(input or '')71 output = StringIO()72 sys.stdin = EchoingStdin(input, output)73 sys.stdin.encoding = 'utf-8'74 sys.stdout = sys.stderr = output75 else:76 real_input = io.BytesIO(input)77 output = io.BytesIO()78 input = io.TextIOWrapper(real_input, encoding='utf-8')79 sys.stdin = EchoingStdin(real_input, output)80 sys.stdout = sys.stderr = io.TextIOWrapper(output,81 encoding='utf-8')8283 def visible_input(prompt=None):84 sys.stdout.write(prompt or '')85 val = input.readline().rstrip('\r\n')86 sys.stdout.write(val + '\n')87 sys.stdout.flush()88 return val8990 def hidden_input(prompt=None):91 sys.stdout.write((prompt or '') + '\n')92 sys.stdout.flush()93 return input.readline().rstrip('\r\n')9495 old_visible_prompt_func = click.termui.visible_prompt_func96 old_hidden_prompt_func = click.termui.hidden_prompt_func97 click.termui.visible_prompt_func = visible_input98 click.termui.hidden_prompt_func = hidden_input99100 old_env = {}101 try:102 if env:103 for key, value in iteritems(env):104 old_env[key] = os.environ.get(value)105 os.environ[key] = value106 yield output107 finally:108 for key, value in iteritems(old_env):109 if value is None:110 try:111 del os.environ[key]112 except Exception:113 pass114 else:115 os.environ[key] = value116 sys.stdout = old_stdout117 sys.stderr = old_stderr118 click.termui.visible_prompt_func = old_visible_prompt_func119 click.termui.hidden_prompt_func = old_hidden_prompt_func120121 def invoke(self, cli, args, **extra):122 with self.isolation() as out:123 exception = None124 exit_code = 0125126 try:127 cli.main(args=args, prog_name=cli.name or 'root',128 **extra)129 except SystemExit as e:130 if e.code != 0:131 exception = e132 exit_code = e.code133 except Exception as e:134 exception = e135 exit_code = -1136 output = out.getvalue().decode('utf-8').replace('\r\n', '\n')137138 return Result(output=output, exit_code=exit_code,139 exception=exception)140141 @contextlib.contextmanager142 def isolated_filesystem(self):143 cwd = os.getcwd()144 t = tempfile.mkdtemp()145 os.chdir(t)146 try:147 yield148 finally:149 os.chdir(cwd)150 try:151 shutil.rmtree(t)152 except (OSError, IOError):153 pass1541556@pytest.fixture(scope='function')7def runner(request):8 return CliRunner()