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
Provenance
- Commit
a438322- Tree
f69f63f- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
93b1699- Parent 2
8e81a91
24 files changed+448 added−209 removed
modified:click/_compat.py+13 added-1 removed
567 unmodified lines568 def strip_ansi(value):569 return _ansi_re.sub('', value)570 571 572+def _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+ return577+578+ while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):579+ stream = stream._stream580+581+ return stream.__class__.__module__.startswith("ipykernel.")582+583+584 def 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 color590 591 592 # If we're on Windows, we provide transparent integration through121 unmodified linesmodified:click/_unicodefun.py+1 added-1 removed
41 unmodified lines42 '__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)48 49 50 def _verify_python3_env():75 unmodified linesmodified:click/core.py+20 added-3 removed
235 unmodified lines236 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 """244 245 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 = command112 unmodified lines368 369 #: Controls if styling output is wanted or not.370 self.color = color371 372+ self.show_default = show_default373+374 self._close_callbacks = []375 self._depth = 0376 self._source_by_paramname = {}377 458 unmodified lines836 .. 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.842 843 :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 lines852 :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.861 862 :param deprecated: issues a message indicating that863 the command is deprecated.1 unmodified line865 866 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 = callback9 unmodified lines883 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 = deprecated890 891 def __repr__(self):115 unmodified lines1007 with formatter.indentation():1008 formatter.write_text(self.epilog)1009 1010 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()1014+1015 parser = self.make_parser(ctx)1016 opts, args, param_order = parser.parse_args(args=args)1017 1018 for param in iter_params_for_processing(782 unmodified lines1801 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 linesmodified:click/globals.py+1 added-1 removed
13 unmodified lines14 To push the current context, :meth:`Context.scope` can be used.15 16 .. versionadded:: 5.017 18- :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 linesmodified:click/termui.py+7 added-1 removed
270 unmodified lines271 to calculate remaining time and more. By default, this progress bar272 will not be rendered if the file is not a terminal.273 274 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.279 280+ 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.285+286 No printing must happen or the progress bar will be unintentionally287 destroyed.288 289 Example usage::323 unmodified linesmodified:docs/commands.rst+1 added-1 removed
25 unmodified lines26 @click.option('--debug/--no-debug', default=False)27 def cli(debug):28 click.echo('Debug mode is %s' % ('on' if debug else 'off'))29 30- @cli.command()30+ @cli.command() # @cli, not @click!31 def sync():32 click.echo('Syncing')33 34 Here is what this looks like:528 unmodified linesmodified:docs/parameters.rst+20 added-10 removed
108 unmodified lines109 Implementing Custom Types110 -------------------------111 112 To implement a custom type, you need to subclass the :class:`ParamType`113-class. Types can be invoked with or without context and parameter object,114-which is why they need to be able to deal with this.113+class. Override the :meth:`~ParamType.convert` method to convert the114+value from a string to the correct type.115 116 The following code implements an integer type that accepts hex and octal117 numbers in addition to normal integers, and converts them into regular118-integers::118+integers.119 120+.. code-block:: python121+122 import click123 124 class BasedIntParamType(click.ParamType):123- name = 'integer'125+ name = "integer"126 127 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)143 144 BASED_INT = BasedIntParamType()145 137-As you can see, a subclass needs to implement the :meth:`ParamType.convert`138-method and optionally provide the :attr:`ParamType.name` attribute. The139-latter can be used for documentation purposes.146+The :attr:`~ParamType.name` attribute is optional and is used for147+documentation. Call :meth:`~ParamType.fail` if conversion fails. The148+``param`` and ``ctx`` arguments may be ``None`` in some cases such as149+prompts.modified:docs/python3.rst+5 added
157 unmodified lines158 * `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)161 162+Note (Python 3.7 onwards): Even though your locale may not be properly163+configured, Python 3.7 Click will not raise the above exception because Python164+3.7 programs are better at choosing default locales. This doesn't change the165+general issue that your locale may be misconfigured.166+167 Unicode Literals168 ----------------169 170 Starting with Click 5.0 there will be a warning for the use of the18 unmodified linesmodified:docs/testing.rst+89 added-62 removed
18 unmodified lines19 :meth:`CliRunner.invoke` method runs the command line script in isolation20 and captures the output as both bytes and binary data.21 22 The return value is a :class:`Result` object, which has the captured output23-data, exit code, and optional exception attached.23+data, exit code, and optional exception attached:24 25-Example::25+.. code-block:: python26+ :caption: hello.py27 27- import click28- from click.testing import CliRunner28+ import click29 30- 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)34 36- 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.py37 41-For 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 hello40 43-Example::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'46 45- 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.output47+For subcommand testing, a subcommand name must be specified in the `args` parameter of :meth:`CliRunner.invoke` method:48 64-Additional 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.py51 52+ import click53+54+ @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'))58+59+ @cli.command()60+ def sync():61+ click.echo('Syncing')62+63+.. code-block:: python64+ :caption: test_sync.py65+66+ from click.testing import CliRunner67+ from sync import cli68+69+ 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.output75+76+Additional keyword arguments passed to ``.invoke()`` will be used to construct the initial Context object.77+For example, if you want to run your tests against a fixed terminal width you can use the following::78+79 runner = CliRunner()80 result = runner.invoke(cli, ['--debug', 'sync'], terminal_width=60)81 82 File System Isolation83 ---------------------84 85 For basic command line tools that want to operate with the file system, the86 :meth:`CliRunner.isolated_filesystem` method comes in useful which sets up74-an empty folder and changes the current working directory to.87+an empty folder and changes the current working directory to:88 76-Example::89+.. code-block:: python90+ :caption: cat.py91 78- import click79- from click.testing import CliRunner92+ import click93 81- 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())98 87- 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.py101 92- 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 cat104 105+ def test_cat():106+ runner = CliRunner()107+ with runner.isolated_filesystem():108+ with open('hello.txt', 'w') as f:109+ f.write('Hello World!')110+111+ result = runner.invoke(cat, ['hello.txt'])112+ assert result.exit_code == 0113+ assert result.output == 'Hello World!\n'114+115 Input Streams116 -------------117 118 The test wrapper can also be used to provide input data for the input100-stream (stdin). This is very useful for testing prompts, for instance::119+stream (stdin). This is very useful for testing prompts, for instance:120 102- import click103- from click.testing import CliRunner121+.. code-block:: python122+ :caption: prompt.py123 105- def test_prompts():106- @click.command()107- @click.option('--foo', prompt=True)108- def test(foo):109- click.echo('foo=%s' % foo)124+ import click125 111- 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)130 131+.. code-block:: python132+ :caption: test_prompt.py133+134+ from click.testing import CliRunner135+ from prompt import prompt136+137+ 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'142+143 Note that prompts will be emulated so that they write the input data to144 the output stream as well. If hidden input is expected then this145 obviously does not happen.modified:docs/why.rst+1 added-1 removed
123 unmodified lines124 reasons for this. The biggest one is that too much configurability makes125 it hard to achieve a consistent command line experience.126 127 The best example for this is optparse's ``callback`` functionality for128-accepting arbitrary number of arguments. Due to syntactical ambiguities128+accepting an arbitrary number of arguments. Due to syntactical ambiguities129 on the command line, there is no way to implement fully variadic arguments.130 There are always tradeoffs that need to be made and in case of131 ``argparse`` these tradeoffs have been critical enough, that a system like132 Click cannot even be implemented on top of it.20 unmodified linesmodified:examples/complex/complex/commands/cmd_init.py+2 added-2 removed
1 import click2-from complex.cli import pass_context2+from complex.cli import pass_environment3 4 5 @click.command('init', short_help='Initializes a repo.')6 @click.argument('path', required=False, type=click.Path(resolve_path=True))7-@pass_context7+@pass_environment8 def cli(ctx, path):9 """Initializes a repository."""10 if path is None:11 path = ctx.home2 unmodified linesmodified:examples/complex/complex/commands/cmd_status.py+2 added-2 removed
1 import click2-from complex.cli import pass_context2+from complex.cli import pass_environment3 4 5 @click.command('status', short_help='Shows file changes.')6-@pass_context6+@pass_environment7 def 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 lines5 6 CONTEXT_SETTINGS = dict(auto_envvar_prefix='COMPLEX')7 8 9-class Context(object):9+class Environment(object):10 11 def __init__(self):12 self.verbose = False13 self.home = os.getcwd()9 unmodified lines23 if self.verbose:24 self.log(msg, *args)25 26 27-pass_context = click.make_pass_decorator(Context, ensure=True)27+pass_environment = click.make_pass_decorator(Environment, ensure=True)28 cmd_folder = os.path.abspath(os.path.join(os.path.dirname(__file__),29 'commands'))30 31 24 unmodified lines56 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_environment61 def cli(ctx, verbose, home):62 """A complex command line interface."""63 ctx.verbose = verbose64 if home is not None:1 unmodified linemodified:tests/test_commands.py+10 added
66 unmodified lines67 r'special-chars\s+Login and store the token in ~/.netrc\.\s*',68 result.output) is not None69 70 71+def test_no_args_is_help(runner):72+ @click.command(no_args_is_help=True)73+ def cli():74+ pass75+76+ result = runner.invoke(cli, [])77+ assert result.exit_code == 078+ assert 'Show this message and exit.' in result.output79+80+81 def test_default_maps(runner):82 @click.group()83 def cli():84 pass209 unmodified linesmodified:tests/test_compat.py+22 added-12 removed
1 import click2 import pytest3+from click._compat import should_strip_ansi, WIN4 5 5-if click.__version__ >= '3.0':6- def test_legacy_callbacks(runner):7- def legacy_callback(ctx, value):8- return value.upper()6+def test_legacy_callbacks(runner):7+ def legacy_callback(ctx, value):8+ return value.upper()9 10- @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)14 15- 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.output19 20 21 def 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 script26+27+28+@pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows")29+def test_is_jupyter_kernel_output():30+ class JupyterKernelFakeStream(object):31+ pass32+33+ # 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 lines296 '',297 'Options:',298 ' --help Show this message and exit.',299 ]300+301+302+def 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+ pass307+308+ 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 -*-2+import pytest3+4 import click5 import time6 7+import click._termui_impl8+from click._compat import WIN9 10+11 class FakeClock(object):12 def __init__(self):13 self.now = time.time()14 3 unmodified lines18 def time(self):19 return self.now20 21 22+def _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 progress28+29+30 def test_progressbar_strip_regression(runner, monkeypatch):31 fake_clock = FakeClock()32 label = ' padded line'33 34 @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()39 40 monkeypatch.setattr(time, 'time', fake_clock.time)39 unmodified lines80 label = 'whatever'81 82 @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()87 88 monkeypatch.setattr(time, 'time', fake_clock.time)89 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: False)90 assert runner.invoke(cli, []).output == ''91 92 93+@pytest.mark.parametrize('avg, expected', [([], 0.0), ([1, 4], 2.5)])94+def test_progressbar_time_per_iteration(runner, avg, expected):95+ with _create_progress(2, avg=avg) as progress:96+ assert progress.time_per_iteration == expected97+98+99+@pytest.mark.parametrize('finished, expected', [(False, 5), (True, 0)])100+def test_progressbar_eta(runner, finished, expected):101+ with _create_progress(2, finished=finished, avg=[1, 4]) as progress:102+ assert progress.eta == expected103+104+105+@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, '')])108+def 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() == expected111+112+113+@pytest.mark.parametrize('pos, length', [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])114+def 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)121+122+123+@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+ ])129+def 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() == expected137+138+139+@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+ ])146+def 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() == expected154+155+156+@pytest.mark.parametrize('test_item', ['test', None])157+def test_progressbar_format_progress_line_with_show_func(runner, test_item):158+159+ def item_show_func(item):160+ return item161+162+ 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())167+168+169+def 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'176+177+178+def 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.'186+187+188 def 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 lines236 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]240+241+242+@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.')247+def 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_char252+253+254+@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.')256+def 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_char261+262+263+@pytest.mark.parametrize('key_char', [u'\x03', u'\x1a'])264+@pytest.mark.skipif(not WIN, reason='Tests user-input using the msvcrt module.')265+def 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
1-environment:2- global:3- TOXENV: py,codecov4-5- matrix:6- - PYTHON: C:\Python37-x647- - PYTHON: C:\Python27-x648- - PYTHON: C:\Python379- - PYTHON: C:\Python2710-11-init:12- - SET PATH=%PYTHON%;%PATH%13-14-install:15- - python -m pip install -U tox16-17-build: false18-19-test_script:20- - python -m tox21-22-branches:23- only:24- - master25- - /^.*\.x$/26-27-cache:28- - '%LOCALAPPDATA%\pip\Cache'added:.azure-pipelines.yml+61 added
1+trigger:2+ - master3+ - "*.x"4+5+variables:6+ vmImage: ubuntu-latest7+ python.version: "3.7"8+ TOXENV: py,coverage-ci9+ hasTestResults: true10+11+strategy: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: false33+34+pool:35+ vmImage: $(vmImage)36+37+steps:38+ - task: UsePythonVersion@039+ inputs:40+ versionSpec: "$(python.version)"41+ displayName: Use Python $(python.version)42+43+ - script: pip --disable-pip-version-check install -U tox44+ displayName: Install tox45+46+ - script: tox -s false -- --junit-xml=test-results.xml47+ displayName: Run tox48+49+ - task: PublishTestResults@250+ inputs:51+ testResultsFiles: test-results.xml52+ testRunTitle: $(Agent.JobName)53+ condition: eq(variables['hasTestResults'], 'true')54+ displayName: Publish test results55+56+ - task: PublishCodeCoverageResults@157+ inputs:58+ codeCoverageTool: Cobertura59+ summaryFileLocation: coverage.xml60+ condition: eq(variables['hasTestResults'], 'true')61+ displayName: Publish coverage resultsdeleted:.travis.yml-55 removed
1-os: linux2-sudo: false3-language: python4-python:5- - "3.6"6- - "3.5"7- - "3.4"8- - "2.7"9- - "nightly"10- - "pypy3"11- - "pypy"12-env: TOXENV=py,codecov13-14-matrix: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: true31-32-before_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- fi39-40-install:41- - pip install tox42-43-script:44- - tox45-46-cache:47- - pip48-49-branches:50- only:51- - master52- - /^.*\.x$/53-54-notifications:55- email: falsemodified:CHANGES.rst+11 added
17 unmodified lines18 -----------19 20 Unreleased21 22+- 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`_)27 28+.. _#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/111633+34 Version 7.035 -----------36 37 Released 2018-09-25627 unmodified linesmodified:CONTRIBUTING.rst+3 added
37 unmodified lines38 `external package <https://click.palletsprojects.com/en/7.x/contrib/>`_39 40 - For docs and bug fixes: Submit against the latest maintenance branch instead of master!41 42+- Non docs or text related changes need an entry in ``CHANGES.rst``,43+ and ``.. versionadded`` or ``.. versionchanged`` markers in the docs.44+45 Running the testsuite46 ---------------------47 48 You probably want to set up a `virtualenv18 unmodified linesmodified:README.rst+4 added-8 removed
37 unmodified lines38 39 .. code-block:: python40 41 import click42- 42+43 @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- 51+52 if __name__ == '__main__':53 hello()54 55 And what it looks like when run:26 unmodified lines82 * 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:87-88- * Linux, Mac: https://travis-ci.org/pallets/click89- * Windows: https://ci.appveyor.com/project/pallets/click90-91-* Test coverage: https://codecov.io/gh/pallets/click86+* Test status: https://dev.azure.com/pallets/click/_build87+* Official chat: https://discord.gg/t6rrQZHmodified:tox.ini+9 added-16 removed
1 [tox]2 envlist =3- py{37,36,35,34,27,py3,py}4- docs-html5- coverage-report3+ py{37,36,35,27,py3,py}4+ docs5+ coverage6 skip_missing_interpreters = true7 8 [testenv]9-passenv = LANG9 deps =10 pytest11 coverage12 colorama14-commands = coverage run -p -m pytest {posargs}13+commands = coverage run -p -m pytest --tb=short -Werror --basetemp={envtmpdir} {posargs}14 16-[testenv:docs-html]15+[testenv:docs]16 deps = -r docs/requirements.txt17 commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html18 20-[testenv:docs-linkcheck]21-deps = -r docs/requirements.txt22-commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs {envtmpdir}/linkcheck23-24-[testenv:coverage-report]19+[testenv:coverage]20 deps = coverage21 skip_install = true22 commands =23 coverage combine29- coverage report24 coverage html25+ coverage report26 32-[testenv:codecov]33-passenv = CI TRAVIS TRAVIS_* APPVEYOR APPVEYOR_*27+[testenv:coverage-ci]28 deps = codecov29 skip_install = true30 commands =31 coverage combine38- coverage report39- codecov32+ coverage xml