Skip to content
Myr

Merge branch '7.x'

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

authored by David Lord · committed by David Lord · parents 93b1699, 8e81a91 · Browse files · 24 files+448 added−209 removed
This commit

State

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

Diff stats

24 files+448 added−209 removed

  • tests:+195 added−14 removed
  • other:+253 added−195 removed

24 files+448 added−209 removed

modified:click/_compat.py+13 added-1 removed
567 unmodified lines
568def strip_ansi(value):569 return _ansi_re.sub('', value)570571572def _is_jupyter_kernel_output(stream):573 if WIN:574 # TODO: Couldn't test on Windows, should't try to support until575 # someone tests the details wrt colorama.576 return577578 while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):579 stream = stream._stream580581 return stream.__class__.__module__.startswith("ipykernel.")582583584def should_strip_ansi(stream=None, color=None):585 if color is None:586 if stream is None:587 stream = sys.stdin576 return not isatty(stream)588 return not isatty(stream) and not _is_jupyter_kernel_output(stream)589 return not color590591592# If we're on Windows, we provide transparent integration through
121 unmodified lines
modified:click/_unicodefun.py+1 added-1 removed
41 unmodified lines
42 '__future__ import. This is heavily discouraged '43 'because it can introduce subtle bugs in your '44 'code. You should instead use explicit u"" literals '45 'for your unicode strings. For more information see '46 'https://click.palletsprojects.com/python3/'),46 'https://click.palletsprojects.com/en/7.x/python3/'),47 stacklevel=bad_frame)484950def _verify_python3_env():
75 unmodified lines
modified:click/core.py+20 added-3 removed
235 unmodified lines
236 default is autodetection. This is only needed if ANSI237 codes are used in texts that Click prints which is by238 default not the case. This for instance would affect239 help output.240 :param show_default: if True, shows defaults for all options.241 Even if an option is later created with show_default=False,242 this command-level setting overrides it.243 """244245 def __init__(self, command, parent=None, info_name=None, obj=None,246 auto_envvar_prefix=None, default_map=None,247 terminal_width=None, max_content_width=None,248 resilient_parsing=False, allow_extra_args=None,249 allow_interspersed_args=None,250 ignore_unknown_options=None, help_option_names=None,248 token_normalize_func=None, color=None):251 token_normalize_func=None, color=None, show_default=None):252 #: the parent context or `None` if none exists.253 self.parent = parent254 #: the :class:`Command` for this context.255 self.command = command
112 unmodified lines
368369 #: Controls if styling output is wanted or not.370 self.color = color371372 self.show_default = show_default373374 self._close_callbacks = []375 self._depth = 0376 self._source_by_paramname = {}377
458 unmodified lines
836 .. versionchanged:: 2.0837 Added the `context_settings` parameter.838 .. versionchanged:: 8.0839 Added repr showing the command name840 .. versionchanged:: 7.1841 Added the `no_args_is_help` parameter.842843 :param name: the name of the command to use unless a group overrides it.844 :param context_settings: an optional dictionary with defaults that are845 passed to the context object.
6 unmodified lines
852 :param short_help: the short help to use for this command. This is853 shown on the command listing of the parent command.854 :param add_help_option: by default each command registers a ``--help``855 option. This can be disabled by this parameter.856 :param no_args_is_help: this controls what happens if no arguments are857 provided. This option is disabled by default.858 If enabled this will add ``--help`` as argument859 if no arguments are passed860 :param hidden: hide this command from help outputs.861862 :param deprecated: issues a message indicating that863 the command is deprecated.
1 unmodified line
865866 def __init__(self, name, context_settings=None, callback=None,867 params=None, help=None, epilog=None, short_help=None,868 options_metavar='[OPTIONS]', add_help_option=True,858 hidden=False, deprecated=False):869 no_args_is_help=False, hidden=False, deprecated=False):870 BaseCommand.__init__(self, name, context_settings)871 #: the callback to execute when the command fires. This might be872 #: `None` in which case nothing happens.873 self.callback = callback
9 unmodified lines
883 self.epilog = epilog884 self.options_metavar = options_metavar885 self.short_help = short_help886 self.add_help_option = add_help_option887 self.no_args_is_help = no_args_is_help888 self.hidden = hidden889 self.deprecated = deprecated890891 def __repr__(self):
115 unmodified lines
1007 with formatter.indentation():1008 formatter.write_text(self.epilog)10091010 def parse_args(self, ctx, args):1011 if not args and self.no_args_is_help and not ctx.resilient_parsing:1012 echo(ctx.get_help(), color=ctx.color)1013 ctx.exit()10141015 parser = self.make_parser(ctx)1016 opts, args, param_order = parser.parse_args(args=args)10171018 for param in iter_params_for_processing(
782 unmodified lines
1801 extra.append('env var: %s' % (1802 ', '.join('%s' % d for d in envvar)1803 if isinstance(envvar, (list, tuple))1804 else envvar, ))1789 if self.default is not None and self.show_default:1805 if self.default is not None and \1806 (self.show_default or ctx.show_default):1807 if isinstance(self.show_default, string_types):1808 default_string = '({})'.format(self.show_default)1809 elif isinstance(self.default, (list, tuple)):1810 default_string = ', '.join('%s' % d for d in self.default)
135 unmodified lines
modified:click/globals.py+1 added-1 removed
13 unmodified lines
14 To push the current context, :meth:`Context.scope` can be used.1516 .. versionadded:: 5.01718 :param silent: is set to `True` the return value is `None` if no context18 :param silent: if set to `True` the return value is `None` if no context19 is available. The default behavior is to raise a20 :exc:`RuntimeError`.21 """22 try:
26 unmodified lines
modified:click/termui.py+7 added-1 removed
270 unmodified lines
271 to calculate remaining time and more. By default, this progress bar272 will not be rendered if the file is not a terminal.273274 The context manager creates the progress bar. When the context275 manager is entered the progress bar is already displayed. With every275 manager is entered the progress bar is already created. With every276 iteration over the progress bar, the iterable passed to the bar is277 advanced and the bar is updated. When the context manager exits,278 a newline is printed and the progress bar is finalized on screen.279280 Note: The progress bar is currently designed for use cases where the281 total progress can be expected to take at least several seconds.282 Because of this, the ProgressBar class object won't display283 progress that is considered too fast, and progress where the time284 between steps is less than a second.285286 No printing must happen or the progress bar will be unintentionally287 destroyed.288289 Example usage::
323 unmodified lines
modified:docs/commands.rst+1 added-1 removed
25 unmodified lines
26 @click.option('--debug/--no-debug', default=False)27 def cli(debug):28 click.echo('Debug mode is %s' % ('on' if debug else 'off'))2930 @cli.command()30 @cli.command() # @cli, not @click!31 def sync():32 click.echo('Syncing')3334Here is what this looks like:
528 unmodified lines
modified:docs/parameters.rst+20 added-10 removed
108 unmodified lines
109Implementing Custom Types110-------------------------111112To implement a custom type, you need to subclass the :class:`ParamType`113class. Types can be invoked with or without context and parameter object,114which is why they need to be able to deal with this.113class. Override the :meth:`~ParamType.convert` method to convert the114value from a string to the correct type.115116The following code implements an integer type that accepts hex and octal117numbers in addition to normal integers, and converts them into regular118integers::118integers.119120.. code-block:: python121122 import click123124 class BasedIntParamType(click.ParamType):123 name = 'integer'125 name = "integer"126127 def convert(self, value, param, ctx):128 try:127 if value[:2].lower() == '0x':129 if value[:2].lower() == "0x":130 return int(value[2:], 16)129 elif value[:1] == '0':131 elif value[:1] == "0":132 return int(value, 8)133 return int(value, 10)134 except TypeError:135 self.fail(136 "expected string for int() conversion, got "137 f"{value!r} of type {type(value).__name__}",138 param,139 ctx,140 )141 except ValueError:133 self.fail('%s is not a valid integer' % value, param, ctx)142 self.fail(f"{value!r} is not a valid integer", param, ctx)143144 BASED_INT = BasedIntParamType()145137As you can see, a subclass needs to implement the :meth:`ParamType.convert`138method and optionally provide the :attr:`ParamType.name` attribute. The139latter can be used for documentation purposes.146The :attr:`~ParamType.name` attribute is optional and is used for147documentation. Call :meth:`~ParamType.fail` if conversion fails. The148``param`` and ``ctx`` arguments may be ``None`` in some cases such as149prompts.
modified:docs/python3.rst+5 added
157 unmodified lines
158* `LC_CTYPE=C: pydoc leaves terminal in an unusable state159 <http://bugs.python.org/issue21398>`_ (this is relevant to Click160 because the pager support is provided by the stdlib pydoc module)161162Note (Python 3.7 onwards): Even though your locale may not be properly163configured, Python 3.7 Click will not raise the above exception because Python1643.7 programs are better at choosing default locales. This doesn't change the165general issue that your locale may be misconfigured.166167Unicode Literals168----------------169170Starting with Click 5.0 there will be a warning for the use of the
18 unmodified lines
modified:docs/testing.rst+89 added-62 removed
18 unmodified lines
19:meth:`CliRunner.invoke` method runs the command line script in isolation20and captures the output as both bytes and binary data.2122The return value is a :class:`Result` object, which has the captured output23data, exit code, and optional exception attached.23data, exit code, and optional exception attached:2425Example::25.. code-block:: python26 :caption: hello.py2727 import click28 from click.testing import CliRunner28 import click2930 def test_hello_world():31 @click.command()32 @click.argument('name')33 def hello(name):34 click.echo('Hello %s!' % name)30 @click.command()31 @click.argument('name')32 def hello(name):33 click.echo('Hello %s!' % name)3436 runner = CliRunner()37 result = runner.invoke(hello, ['Peter'])38 assert result.exit_code == 039 assert result.output == 'Hello Peter!\n'35.. code-block:: python36 :caption: test_hello.py3741For subcommand testing, a subcommand name must be specified in the `args` parameter of :meth:`CliRunner.invoke` method.38 from click.testing import CliRunner39 from hello import hello4043Example::41 def test_hello_world():42 runner = CliRunner()43 result = runner.invoke(hello, ['Peter'])44 assert result.exit_code == 045 assert result.output == 'Hello Peter!\n'4645 import click46 from click.testing import CliRunner47 48 def test_sync():49 @click.group()50 @click.option('--debug/--no-debug', default=False)51 def cli(debug):52 click.echo('Debug mode is %s' % ('on' if debug else 'off')) 53 54 @cli.command()55 def sync():56 click.echo('Syncing')57 58 runner = CliRunner()59 result = runner.invoke(cli, ['--debug', 'sync'])60 assert result.exit_code == 061 assert 'Debug mode is on' in result.output62 assert 'Syncing' in result.output47For subcommand testing, a subcommand name must be specified in the `args` parameter of :meth:`CliRunner.invoke` method:4864Additional keyword arguments passed to ``.invoke()`` will be used to construct the initial Context object. For example, if you want to run your tests against a fixed terminal width you can use the following::49.. code-block:: python50 :caption: sync.py5152 import click5354 @click.group()55 @click.option('--debug/--no-debug', default=False)56 def cli(debug):57 click.echo('Debug mode is %s' % ('on' if debug else 'off'))5859 @cli.command()60 def sync():61 click.echo('Syncing')6263.. code-block:: python64 :caption: test_sync.py6566 from click.testing import CliRunner67 from sync import cli6869 def test_sync():70 runner = CliRunner()71 result = runner.invoke(cli, ['--debug', 'sync'])72 assert result.exit_code == 073 assert 'Debug mode is on' in result.output74 assert 'Syncing' in result.output7576Additional keyword arguments passed to ``.invoke()`` will be used to construct the initial Context object.77For example, if you want to run your tests against a fixed terminal width you can use the following::7879 runner = CliRunner()80 result = runner.invoke(cli, ['--debug', 'sync'], terminal_width=60)8182File System Isolation83---------------------8485For basic command line tools that want to operate with the file system, the86:meth:`CliRunner.isolated_filesystem` method comes in useful which sets up74an empty folder and changes the current working directory to.87an empty folder and changes the current working directory to:8876Example::89.. code-block:: python90 :caption: cat.py9178 import click79 from click.testing import CliRunner92 import click9381 def test_cat():82 @click.command()83 @click.argument('f', type=click.File())84 def cat(f):85 click.echo(f.read())94 @click.command()95 @click.argument('f', type=click.File())96 def cat(f):97 click.echo(f.read())9887 runner = CliRunner()88 with runner.isolated_filesystem():89 with open('hello.txt', 'w') as f:90 f.write('Hello World!')99.. code-block:: python100 :caption: test_cat.py10192 result = runner.invoke(cat, ['hello.txt'])93 assert result.exit_code == 094 assert result.output == 'Hello World!\n'102 from click.testing import CliRunner103 from cat import cat104105 def test_cat():106 runner = CliRunner()107 with runner.isolated_filesystem():108 with open('hello.txt', 'w') as f:109 f.write('Hello World!')110111 result = runner.invoke(cat, ['hello.txt'])112 assert result.exit_code == 0113 assert result.output == 'Hello World!\n'114115Input Streams116-------------117118The test wrapper can also be used to provide input data for the input100stream (stdin). This is very useful for testing prompts, for instance::119stream (stdin). This is very useful for testing prompts, for instance:120102 import click103 from click.testing import CliRunner121.. code-block:: python122 :caption: prompt.py123105 def test_prompts():106 @click.command()107 @click.option('--foo', prompt=True)108 def test(foo):109 click.echo('foo=%s' % foo)124 import click125111 runner = CliRunner()112 result = runner.invoke(test, input='wau wau\n')113 assert not result.exception114 assert result.output == 'Foo: wau wau\nfoo=wau wau\n'126 @click.command()127 @click.option('--foo', prompt=True)128 def prompt(foo):129 click.echo('foo=%s' % foo)130131.. code-block:: python132 :caption: test_prompt.py133134 from click.testing import CliRunner135 from prompt import prompt136137 def test_prompts():138 runner = CliRunner()139 result = runner.invoke(prompt, input='wau wau\n')140 assert not result.exception141 assert result.output == 'Foo: wau wau\nfoo=wau wau\n'142143Note that prompts will be emulated so that they write the input data to144the output stream as well. If hidden input is expected then this145obviously does not happen.
modified:docs/why.rst+1 added-1 removed
123 unmodified lines
124reasons for this. The biggest one is that too much configurability makes125it hard to achieve a consistent command line experience.126127The best example for this is optparse's ``callback`` functionality for128accepting arbitrary number of arguments. Due to syntactical ambiguities128accepting an arbitrary number of arguments. Due to syntactical ambiguities129on the command line, there is no way to implement fully variadic arguments.130There are always tradeoffs that need to be made and in case of131``argparse`` these tradeoffs have been critical enough, that a system like132Click cannot even be implemented on top of it.
20 unmodified lines
modified:examples/complex/complex/commands/cmd_init.py+2 added-2 removed
1import click2from complex.cli import pass_context2from complex.cli import pass_environment345@click.command('init', short_help='Initializes a repo.')6@click.argument('path', required=False, type=click.Path(resolve_path=True))7@pass_context7@pass_environment8def cli(ctx, path):9 """Initializes a repository."""10 if path is None:11 path = ctx.home
2 unmodified lines
modified:examples/complex/complex/commands/cmd_status.py+2 added-2 removed
1import click2from complex.cli import pass_context2from complex.cli import pass_environment345@click.command('status', short_help='Shows file changes.')6@pass_context6@pass_environment7def cli(ctx):8 """Shows file changes in the current working directory."""9 ctx.log('Changed files: none')10 ctx.vlog('bla bla bla, debug info')
modified:examples/complex/complex/cli.py+3 added-3 removed
4 unmodified lines
56CONTEXT_SETTINGS = dict(auto_envvar_prefix='COMPLEX')789class Context(object):9class Environment(object):1011 def __init__(self):12 self.verbose = False13 self.home = os.getcwd()
9 unmodified lines
23 if self.verbose:24 self.log(msg, *args)252627pass_context = click.make_pass_decorator(Context, ensure=True)27pass_environment = click.make_pass_decorator(Environment, ensure=True)28cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__),29 'commands'))3031
24 unmodified lines
56 resolve_path=True),57 help='Changes the folder to operate on.')58@click.option('-v', '--verbose', is_flag=True,59 help='Enables verbose mode.')60@pass_context60@pass_environment61def cli(ctx, verbose, home):62 """A complex command line interface."""63 ctx.verbose = verbose64 if home is not None:
1 unmodified line
modified:tests/test_commands.py+10 added
66 unmodified lines
67 r'special-chars\s+Login and store the token in ~/.netrc\.\s*',68 result.output) is not None697071def test_no_args_is_help(runner):72 @click.command(no_args_is_help=True)73 def cli():74 pass7576 result = runner.invoke(cli, [])77 assert result.exit_code == 078 assert 'Show this message and exit.' in result.output798081def test_default_maps(runner):82 @click.group()83 def cli():84 pass
209 unmodified lines
modified:tests/test_compat.py+22 added-12 removed
1import click2import pytest3from click._compat import should_strip_ansi, WIN455if click.__version__ >= '3.0':6 def test_legacy_callbacks(runner):7 def legacy_callback(ctx, value):8 return value.upper()6def test_legacy_callbacks(runner):7 def legacy_callback(ctx, value):8 return value.upper()910 @click.command()11 @click.option('--foo', callback=legacy_callback)12 def cli(foo):13 click.echo(foo)10 @click.command()11 @click.option('--foo', callback=legacy_callback)12 def cli(foo):13 click.echo(foo)1415 with pytest.warns(Warning, match='Invoked legacy parameter callback'):16 result = runner.invoke(cli, ['--foo', 'wat'])17 assert result.exit_code == 018 assert 'WAT' in result.output15 with pytest.warns(Warning, match='Invoked legacy parameter callback'):16 result = runner.invoke(cli, ['--foo', 'wat'])17 assert result.exit_code == 018 assert 'WAT' in result.output192021def test_bash_func_name():22 from click._bashcomplete import get_completion_script23 script = get_completion_script('foo-bar baz_blah', '_COMPLETE_VAR', 'bash').strip()24 assert script.startswith('_foo_barbaz_blah_completion()')25 assert '_COMPLETE_VAR=complete $1' in script262728@pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows")29def test_is_jupyter_kernel_output():30 class JupyterKernelFakeStream(object):31 pass3233 # implementation detail, aka cheapskate test34 JupyterKernelFakeStream.__module__ = "ipykernel.faked"35 assert not should_strip_ansi(stream=JupyterKernelFakeStream())
modified:tests/test_formatting.py+16 added
295 unmodified lines
296 '',297 'Options:',298 ' --help Show this message and exit.',299 ]300301302def test_global_show_default(runner):303 @click.command(context_settings=dict(show_default=True))304 @click.option("-f", "in_file", default="out.txt", help="Output file name")305 def cli():306 pass307308 result = runner.invoke(cli, ['--help'],)309 assert result.output.splitlines() == [310 'Usage: cli [OPTIONS]',311 '',312 'Options:',313 ' -f TEXT Output file name [default: out.txt]',314 ' --help Show this message and exit. [default: False]'315 ]
modified:tests/test_termui.py+147 added-2 removed
1# -*- coding: utf-8 -*-2import pytest34import click5import time67import click._termui_impl8from click._compat import WIN91011class FakeClock(object):12 def __init__(self):13 self.now = time.time()14
3 unmodified lines
18 def time(self):19 return self.now202122def _create_progress(length=10, length_known=True, **kwargs):23 progress = click.progressbar(tuple(range(length)))24 for key, value in kwargs.items():25 setattr(progress, key, value)26 progress.length_known = length_known27 return progress282930def test_progressbar_strip_regression(runner, monkeypatch):31 fake_clock = FakeClock()32 label = ' padded line'3334 @click.command()35 def cli():22 with click.progressbar(tuple(range(10)), label=label) as progress:36 with _create_progress(label=label) as progress:37 for thing in progress:38 fake_clock.advance_time()3940 monkeypatch.setattr(time, 'time', fake_clock.time)
39 unmodified lines
80 label = 'whatever'8182 @click.command()83 def cli():70 with click.progressbar(tuple(range(10)), label=label) as progress:84 with _create_progress(label=label) as progress:85 for thing in progress:86 fake_clock.advance_time()8788 monkeypatch.setattr(time, 'time', fake_clock.time)89 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: False)90 assert runner.invoke(cli, []).output == ''919293@pytest.mark.parametrize('avg, expected', [([], 0.0), ([1, 4], 2.5)])94def test_progressbar_time_per_iteration(runner, avg, expected):95 with _create_progress(2, avg=avg) as progress:96 assert progress.time_per_iteration == expected979899@pytest.mark.parametrize('finished, expected', [(False, 5), (True, 0)])100def test_progressbar_eta(runner, finished, expected):101 with _create_progress(2, finished=finished, avg=[1, 4]) as progress:102 assert progress.eta == expected103104105@pytest.mark.parametrize('eta, expected',106 [(0, '00:00:00'), (30, '00:00:30'), (90, '00:01:30'), (900, '00:15:00'),107 (9000, '02:30:00'), (99999999999, '1157407d 09:46:39'), (None, '')])108def test_progressbar_format_eta(runner, eta, expected):109 with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress:110 assert progress.format_eta() == expected111112113@pytest.mark.parametrize('pos, length', [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])114def test_progressbar_format_pos(runner, pos, length):115 with _create_progress(length, length_known=length != 0, pos=pos) as progress:116 result = progress.format_pos()117 if progress.length_known:118 assert result == '%s/%s' % (pos, length)119 else:120 assert result == str(pos)121122123@pytest.mark.parametrize('length, finished, pos, avg, expected',124 [(8, False, 7, 0, '#######-'),125 (0, True, 8, 0, '########'),126 (0, False, 8, 0, '--------'),127 (0, False, 5, 3, '#-------')128 ])129def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):130 with _create_progress(length,131 length_known=length != 0,132 width=8,133 pos=pos,134 finished=finished,135 avg=[avg]) as progress:136 assert progress.format_bar() == expected137138139@pytest.mark.parametrize('length, length_known, show_percent, show_pos, pos, expected',140 [(0, True, True, True, 0, ' [--------] 0/0 0%'),141 (0, True, False, True, 0, ' [--------] 0/0'),142 (0, True, False, False, 0, ' [--------]'),143 (0, False, False, False, 0, ' [--------]'),144 (8, True, True, True, 8, ' [########] 8/8 100%')145 ])146def test_progressbar_format_progress_line(runner, length, length_known, show_percent, show_pos, pos, expected):147 with _create_progress(length,148 length_known,149 width=8,150 show_percent=show_percent,151 pos=pos,152 show_pos=show_pos) as progress:153 assert progress.format_progress_line() == expected154155156@pytest.mark.parametrize('test_item', ['test', None])157def test_progressbar_format_progress_line_with_show_func(runner, test_item):158159 def item_show_func(item):160 return item161162 with _create_progress(item_show_func=item_show_func, current_item=test_item) as progress:163 if test_item:164 assert progress.format_progress_line().endswith(test_item)165 else:166 assert progress.format_progress_line().endswith(progress.format_pct())167168169def test_progressbar_init_exceptions(runner):170 try:171 click.progressbar()172 except TypeError as e:173 assert str(e) == 'iterable or length is required'174 else:175 assert False, 'Expected an exception because unspecified arguments'176177178def test_progressbar_iter_outside_with_exceptions(runner):179 try:180 progress = click.progressbar(length=2)181 iter(progress)182 except RuntimeError as e:183 assert str(e) == 'You need to use progress bars in a with block.'184 else:185 assert False, 'Expected an exception because of abort-related inputs.'186187188def test_choices_list_in_prompt(runner, monkeypatch):189 @click.command()190 @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),191 prompt=True)
44 unmodified lines
236 assert ' 25% 00:00:03' in lines[0]237 assert ' 50% 00:00:02' in lines[1]238 assert ' 75% 00:00:01' in lines[2]239 assert '100% ' in lines[3]240241242@pytest.mark.parametrize(243 'key_char', (u'h', u'H', u'é', u'À', u' ', u'字', u'àH', u'àR')244)245@pytest.mark.parametrize('echo', [True, False])246@pytest.mark.skipif(not WIN, reason='Tests user-input using the msvcrt module.')247def test_getchar_windows(runner, monkeypatch, key_char, echo):248 monkeypatch.setattr(click._termui_impl.msvcrt, 'getwche', lambda: key_char)249 monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: key_char)250 monkeypatch.setattr(click.termui, '_getchar', None)251 assert click.getchar(echo) == key_char252253254@pytest.mark.parametrize('special_key_char, key_char', [(u'\x00', 'a'), (u'\x00', 'b'), (u'\xe0', 'c')])255@pytest.mark.skipif(not WIN, reason='Tests special character inputs using the msvcrt module.')256def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):257 ordered_inputs = [key_char, special_key_char]258 monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: ordered_inputs.pop())259 monkeypatch.setattr(click.termui, '_getchar', None)260 assert click.getchar() == special_key_char + key_char261262263@pytest.mark.parametrize('key_char', [u'\x03', u'\x1a'])264@pytest.mark.skipif(not WIN, reason='Tests user-input using the msvcrt module.')265def test_getchar_windows_exceptions(runner, monkeypatch, key_char):266 monkeypatch.setattr(click._termui_impl.msvcrt, 'getwch', lambda: key_char)267 monkeypatch.setattr(click.termui, '_getchar', None)268 try:269 click.getchar()270 except KeyboardInterrupt:271 assert key_char == u'\x03'272 except EOFError:273 assert key_char == u'\x1a'274 else:275 assert False, 'Expected an exception because of abort-specific inputs.'
deleted:.appveyor.yml-28 removed
1environment:2 global:3 TOXENV: py,codecov45 matrix:6 - PYTHON: C:\Python37-x647 - PYTHON: C:\Python27-x648 - PYTHON: C:\Python379 - PYTHON: C:\Python271011init:12 - SET PATH=%PYTHON%;%PATH%1314install:15 - python -m pip install -U tox1617build: false1819test_script:20 - python -m tox2122branches:23 only:24 - master25 - /^.*\.x$/2627cache:28 - '%LOCALAPPDATA%\pip\Cache'
added:.azure-pipelines.yml+61 added
1trigger:2 - master3 - "*.x"45variables:6 vmImage: ubuntu-latest7 python.version: "3.7"8 TOXENV: py,coverage-ci9 hasTestResults: true1011strategy:12 matrix:13 Python 3.7 Linux:14 vmImage: ubuntu-latest15 Python 3.7 Windows:16 vmImage: windows-latest17 Python 3.7 Mac:18 vmImage: macos-latest19 PyPy 3 Linux:20 python.version: pypy321 Python 3.6 Linux:22 python.version: 3.623 Python 3.5 Linux:24 python.version: 3.525 Python 2.7 Linux:26 python.version: 2.727 Python 2.7 Windows:28 python.version: 2.729 vmImage: windows-latest30 Docs:31 TOXENV: docs32 hasTestResults: false3334pool:35 vmImage: $(vmImage)3637steps:38 - task: UsePythonVersion@039 inputs:40 versionSpec: "$(python.version)"41 displayName: Use Python $(python.version)4243 - script: pip --disable-pip-version-check install -U tox44 displayName: Install tox4546 - script: tox -s false -- --junit-xml=test-results.xml47 displayName: Run tox4849 - task: PublishTestResults@250 inputs:51 testResultsFiles: test-results.xml52 testRunTitle: $(Agent.JobName)53 condition: eq(variables['hasTestResults'], 'true')54 displayName: Publish test results5556 - task: PublishCodeCoverageResults@157 inputs:58 codeCoverageTool: Cobertura59 summaryFileLocation: coverage.xml60 condition: eq(variables['hasTestResults'], 'true')61 displayName: Publish coverage results
deleted:.travis.yml-55 removed
1os: linux2sudo: false3language: python4python:5 - "3.6"6 - "3.5"7 - "3.4"8 - "2.7"9 - "nightly"10 - "pypy3"11 - "pypy"12env: TOXENV=py,codecov1314matrix:15 include:16 - env: TOXENV=docs-html17 - os: osx18 language: generic19 env: TOXENV=py3,py2,codecov20 cache:21 pip: false22 directories:23 - $HOME/Library/Caches/Homebrew24 - $HOME/Library/Caches/pip25 allow_failures:26 - python: nightly27 - python: pypy328 - python: pypy29 - os: osx30 fast_finish: true3132before_install:33 - |34 if [[ $TRAVIS_OS_NAME == 'osx' ]]; then35 brew upgrade python36 brew install python@237 export PATH="/usr/local/opt/python/libexec/bin:${PATH}"38 fi3940install:41 - pip install tox4243script:44 - tox4546cache:47 - pip4849branches:50 only:51 - master52 - /^.*\.x$/5354notifications:55 email: false
modified:CHANGES.rst+11 added
17 unmodified lines
18-----------1920Unreleased2122- Add ``no_args_is_help`` option to ``click.Command``, defaults to False (`#1167`_)23- Fix link in ``unicode_literals`` error message. (`#1151`_)24- Add support for colored output on UNIX Jupyter notebooks. (`#1185`_)25- Remove unused compat shim for ``bytes``. (`#1195`_)26- Expand unit testing around termui, especially getchar (Windows). (`#1116`_)2728.. _#1167: https://github.com/pallets/click/pull/116729.. _#1151: https://github.com/pallets/click/pull/115130.. _#1185: https://github.com/pallets/click/issues/118531.. _#1195: https://github.com/pallets/click/pull/119532.. _#1116: https://github.com/pallets/click/issues/11163334Version 7.035-----------3637Released 2018-09-25
627 unmodified lines
modified:CONTRIBUTING.rst+3 added
37 unmodified lines
38 `external package <https://click.palletsprojects.com/en/7.x/contrib/>`_3940- For docs and bug fixes: Submit against the latest maintenance branch instead of master!4142- Non docs or text related changes need an entry in ``CHANGES.rst``,43 and ``.. versionadded`` or ``.. versionchanged`` markers in the docs.4445Running the testsuite46---------------------4748You probably want to set up a `virtualenv
18 unmodified lines
modified:README.rst+4 added-8 removed
37 unmodified lines
3839.. code-block:: python4041 import click42 4243 @click.command()44 @click.option("--count", default=1, help="Number of greetings.")45 @click.option("--name", prompt="Your name",46 help="The person to greet.")47 def hello(count, name):48 """Simple program that greets NAME for a total of COUNT times."""49 for _ in range(count):50 click.echo("Hello, %s!" % name)51 5152 if __name__ == '__main__':53 hello()5455And what it looks like when run:
26 unmodified lines
82* License: `BSD <https://github.com/pallets/click/blob/master/LICENSE.rst>`_83* Releases: https://pypi.org/project/click/84* Code: https://github.com/pallets/click85* Issue tracker: https://github.com/pallets/click/issues86* Test status:8788 * Linux, Mac: https://travis-ci.org/pallets/click89 * Windows: https://ci.appveyor.com/project/pallets/click9091* Test coverage: https://codecov.io/gh/pallets/click86* Test status: https://dev.azure.com/pallets/click/_build87* Official chat: https://discord.gg/t6rrQZH
modified:tox.ini+9 added-16 removed
1[tox]2envlist =3 py{37,36,35,34,27,py3,py}4 docs-html5 coverage-report3 py{37,36,35,27,py3,py}4 docs5 coverage6skip_missing_interpreters = true78[testenv]9passenv = LANG9deps =10 pytest11 coverage12 colorama14commands = coverage run -p -m pytest {posargs}13commands = coverage run -p -m pytest --tb=short -Werror --basetemp={envtmpdir} {posargs}1416[testenv:docs-html]15[testenv:docs]16deps = -r docs/requirements.txt17commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html1820[testenv:docs-linkcheck]21deps = -r docs/requirements.txt22commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs {envtmpdir}/linkcheck2324[testenv:coverage-report]19[testenv:coverage]20deps = coverage21skip_install = true22commands =23 coverage combine29 coverage report24 coverage html25 coverage report2632[testenv:codecov]33passenv = CI TRAVIS TRAVIS_* APPVEYOR APPVEYOR_*27[testenv:coverage-ci]28deps = codecov29skip_install = true30commands =31 coverage combine38 coverage report39 codecov32 coverage xml