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
Provenance
- Commit
c265355- Tree
3d3a0db- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
f3ee4e5
3 files changed+228 added−151 removed
added:click/testing.py+216 added
1+import os2+import sys3+import click4+import shutil5+import tempfile6+import contextlib7+8+from ._compat import iteritems, PY29+10+11+if PY2:12+ from cStringIO import StringIO13+else:14+ import io15+16+17+class EchoingStdin(object):18+19+ def __init__(self, input, output):20+ self._input = input21+ self._output = output22+23+ def __getattr__(self, x):24+ return getattr(self._input, x)25+26+ def _echo(self, rv):27+ self._output.write(rv)28+ return rv29+30+ def read(self, n=-1):31+ return self._echo(self._input.read(n))32+33+ def readline(self, n=-1):34+ return self._echo(self._input.readline(n))35+36+ def readlines(self):37+ return [self._echo(x) for x in self._input.readlines()]38+39+ def __iter__(self):40+ return iter(self._echo(x) for x in self._input)41+42+43+class Result(object):44+ """Holds the captured result of an invoked CLI script."""45+46+ 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 = exception53+54+ def __repr__(self):55+ return '<Result %s>' % (56+ self.exception and repr(self.exception) or 'okay',57+ )58+59+60+class 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+ """66+67+ def __init__(self, charset=None, env=None):68+ if charset is None:69+ charset = 'utf-8'70+ self.charset = charset71+ self.env = env or {}72+73+ 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'79+80+ 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 rv86+87+ @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).94+95+ This is automatically done in the :meth:`invoke` method.96+97+ :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)104+105+ old_stdout = sys.stdout106+ old_stderr = sys.stderr107+108+ env = self.make_env(env)109+110+ 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)123+124+ 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 val130+131+ def hidden_input(prompt=None):132+ sys.stdout.write((prompt or '') + '\n')133+ sys.stdout.flush()134+ return input.readline().rstrip('\r\n')135+136+ 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_input140+141+ 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_func166+167+ 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.172+173+ This returns a :class:`Result` object.174+175+ :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 = 0184+185+ 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')196+197+ return Result(output=output,198+ exit_code=exit_code,199+ exception=exception)200+201+ @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+ passmodified:docs/api.rst+11 added
120 unmodified lines121 -------122 123 .. autoclass:: OptionParser124 :members:125+126+Testing127+-------128+129+.. currentmodule:: click.testing130+131+.. autoclass:: CliRunner132+ :members:133+134+.. autoclass:: Result135+ :members:modified:tests/conftest.py+1 added-151 removed
1-import os2-import sys3-import click4-import shutil5-import tempfile6-import contextlib1+from click.testing import CliRunner2 3 import pytest4 10-PY2 = sys.version_info[0] == 211-if PY2:12- from cStringIO import StringIO13- iteritems = lambda x: x.iteritems()14-else:15- import io16- iteritems = lambda x: iter(x.items())5 18-19-class EchoingStdin(object):20-21- def __init__(self, input, output):22- self._input = input23- self._output = output24-25- def __getattr__(self, x):26- return getattr(self._input, x)27-28- 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 rv37-38- def read(self, n=-1):39- return self._echo(self._input.read(n))40-41- def readline(self, n=-1):42- return self._echo(self._input.readline(n))43-44- def readlines(self):45- return [self._echo(x) for x in self._input.readlines()]46-47- def __iter__(self):48- return iter(self._echo(x) for x in self._input)49-50-51-class Result(object):52-53- def __init__(self, output, exit_code, exception):54- self.output = output55- self.exit_code = exit_code56- self.exception = exception57-58-59-class CliRunner(object):60-61- @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')65-66- old_stdout = sys.stdout67- old_stderr = sys.stderr68-69- 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')82-83- 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 val89-90- def hidden_input(prompt=None):91- sys.stdout.write((prompt or '') + '\n')92- sys.stdout.flush()93- return input.readline().rstrip('\r\n')94-95- 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_input99-100- 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_func120-121- def invoke(self, cli, args, **extra):122- with self.isolation() as out:123- exception = None124- exit_code = 0125-126- 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')137-138- return Result(output=output, exit_code=exit_code,139- exception=exception)140-141- @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- pass154-155-6 @pytest.fixture(scope='function')7 def runner(request):8 return CliRunner()