remove py2 parts of _compat module
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 · parent 5cddd7f · Browse files · 16 files·+267 added−639 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+267 added−639 removed
- tests:+12 added−30 removed
- other:+255 added−609 removed
Provenance
- Commit
00883dd- Tree
4be9d2d- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
5cddd7f
16 files changed+267 added−639 removed
modified:docs/conf.py+5 added
1 from pallets_sphinx_themes import get_version2 from pallets_sphinx_themes import ProjectLink3 4+import click._compat5+6+# compat until pallets-sphinx-themes is updated7+click._compat.text_type = str8+9 # Project --------------------------------------------------------------10 11 project = "Click"12 copyright = "2014 Pallets"43 unmodified linesmodified:src/click/__init__.py+1 added-5 removed
70 unmodified lines71 from .utils import get_os_args72 from .utils import get_text_stream73 from .utils import open_file74 75-# Controls if click should emit the warning about the use of unicode76-# literals.77-disable_unicode_literals_warning = False78-79-__version__ = "8.0.dev"75+__version__ = "8.0.0.dev"modified:src/click/_compat.py+168 added-347 removed
1-# flake8: noqa1 import codecs2 import io3 import os4 import re5 import sys6 from weakref import WeakKeyDictionary7 9-PY2 = sys.version_info[0] == 28 CYGWIN = sys.platform.startswith("cygwin")9 MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)10 # Determine local App Engine environment, per Google's own suggestion11 APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(12 "SERVER_SOFTWARE", ""13 )14 WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS215 DEFAULT_COLUMNS = 8018-19-16+auto_wrap_for_ansi = None17+colorama = None18+get_winterm_size = None19 _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")20 21 22 def get_filesystem_encoding():43 unmodified lines66 force_writable=False,67 **extra68 ):69 self._stream = stream = _FixupStream(stream, force_readable, force_writable)71- io.TextIOWrapper.__init__(self, stream, encoding, errors, **extra)70+ super().__init__(stream, encoding, errors, **extra)71 73- # The io module is a place where the Python 3 text behavior74- # was forced upon Python 2, so we need to unbreak75- # it to look like Python 2.76- if PY2:77-78- def write(self, x):79- if isinstance(x, str) or is_bytes(x):80- try:81- self.flush()82- except Exception:83- pass84- return self.buffer.write(str(x))85- return io.TextIOWrapper.write(self, x)86-87- def writelines(self, lines):88- for line in lines:89- self.write(line)90-72 def __del__(self):73 try:74 self.detach()75 except Exception:25 unmodified lines101 def read1(self, size):102 f = getattr(self._stream, "read1", None)103 if f is not None:104 return f(size)124- # We only dispatch to readline instead of read in Python 2 as we125- # do not want cause problems with the different implementation126- # of line buffering.127- if PY2:128- return self._stream.readline(size)105+106 return self._stream.read(size)107 108 def readable(self):109 if self._force_readable:32 unmodified lines142 return False143 return True144 145 169-if PY2:170- text_type = unicode171- raw_input = raw_input172- string_types = (str, unicode)173- int_types = (int, long)174- iteritems = lambda x: x.iteritems()175- range_type = xrange146+def is_bytes(x):147+ return isinstance(x, (bytes, memoryview, bytearray))148 177- from pipes import quote as shlex_quote149 179- def is_bytes(x):180- return isinstance(x, (buffer, bytearray))181-182- _identifier_re = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")183-184- # For Windows, we need to force stdout/stdin/stderr to binary if it's185- # fetched for that. This obviously is not the most correct way to do186- # it as it changes global state. Unfortunately, there does not seem to187- # be a clear better way to do it as just reopening the file in binary188- # mode does not change anything.189- #190- # An option would be to do what Python 3 does and to open the file as191- # binary only, patch it back to the system, and then use a wrapper192- # stream that converts newlines. It's not quite clear what's the193- # correct option here.194- #195- # This code also lives in _winconsole for the fallback to the console196- # emulation stream.197- #198- # There are also Windows environments where the `msvcrt` module is not199- # available (which is why we use try-catch instead of the WIN variable200- # here), such as the Google App Engine development server on Windows. In201- # those cases there is just nothing we can do.202- def set_binary_mode(f):203- return f204-150+def _is_binary_reader(stream, default=False):151 try:206- import msvcrt207- except ImportError:208- pass209- else:152+ return isinstance(stream.read(0), bytes)153+ except Exception:154+ return default155+ # This happens in some cases where the stream was already156+ # closed. In this case, we assume the default.157 211- def set_binary_mode(f):212- try:213- fileno = f.fileno()214- except Exception:215- pass216- else:217- msvcrt.setmode(fileno, os.O_BINARY)218- return f158 159+def _is_binary_writer(stream, default=False):160 try:221- import fcntl222- except ImportError:223- pass224- else:161+ stream.write(b"")162+ except Exception:163+ try:164+ stream.write("")165+ return False166+ except Exception:167+ pass168+ return default169+ return True170 226- def set_binary_mode(f):227- try:228- fileno = f.fileno()229- except Exception:230- pass231- else:232- flags = fcntl.fcntl(fileno, fcntl.F_GETFL)233- fcntl.fcntl(fileno, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)234- return f171 236- def isidentifier(x):237- return _identifier_re.search(x) is not None172+def _find_binary_reader(stream):173+ # We need to figure out if the given stream is already binary.174+ # This can happen because the official docs recommend detaching175+ # the streams to get binary streams. Some code might do this, so176+ # we need to deal with this case explicitly.177+ if _is_binary_reader(stream, False):178+ return stream179 239- def get_binary_stdin():240- return set_binary_mode(sys.stdin)180+ buf = getattr(stream, "buffer", None)181 242- def get_binary_stdout():243- _wrap_std_stream("stdout")244- return set_binary_mode(sys.stdout)182+ # Same situation here; this time we assume that the buffer is183+ # actually binary in case it's closed.184+ if buf is not None and _is_binary_reader(buf, True):185+ return buf186 246- def get_binary_stderr():247- _wrap_std_stream("stderr")248- return set_binary_mode(sys.stderr)187 250- def get_text_stdin(encoding=None, errors=None):251- rv = _get_windows_console_stream(sys.stdin, encoding, errors)252- if rv is not None:253- return rv254- return _make_text_stream(sys.stdin, encoding, errors, force_readable=True)188+def _find_binary_writer(stream):189+ # We need to figure out if the given stream is already binary.190+ # This can happen because the official docs recommend detaching191+ # the streams to get binary streams. Some code might do this, so192+ # we need to deal with this case explicitly.193+ if _is_binary_writer(stream, False):194+ return stream195 256- def get_text_stdout(encoding=None, errors=None):257- _wrap_std_stream("stdout")258- rv = _get_windows_console_stream(sys.stdout, encoding, errors)259- if rv is not None:260- return rv261- return _make_text_stream(sys.stdout, encoding, errors, force_writable=True)196+ buf = getattr(stream, "buffer", None)197 263- def get_text_stderr(encoding=None, errors=None):264- _wrap_std_stream("stderr")265- rv = _get_windows_console_stream(sys.stderr, encoding, errors)266- if rv is not None:267- return rv268- return _make_text_stream(sys.stderr, encoding, errors, force_writable=True)198+ # Same situation here; this time we assume that the buffer is199+ # actually binary in case it's closed.200+ if buf is not None and _is_binary_writer(buf, True):201+ return buf202 270- def filename_to_ui(value):271- if isinstance(value, bytes):272- value = value.decode(get_filesystem_encoding(), "replace")273- return value203 204+def _stream_is_misconfigured(stream):205+ """A stream is misconfigured if its encoding is ASCII."""206+ # If the stream does not have an encoding set, we assume it's set207+ # to ASCII. This appears to happen in certain unittest208+ # environments. It's not quite clear what the correct behavior is209+ # but this at least will force Click to recover somehow.210+ return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")211 276-else:277- import io212 279- text_type = str280- raw_input = input281- string_types = (str,)282- int_types = (int,)283- range_type = range284- isidentifier = lambda x: x.isidentifier()285- iteritems = lambda x: iter(x.items())213+def _is_compat_stream_attr(stream, attr, value):214+ """A stream attribute is compatible if it is equal to the215+ desired value or the desired value is unset and the attribute216+ has a value.217+ """218+ stream_value = getattr(stream, attr, None)219+ return stream_value == value or (value is None and stream_value is not None)220 287- from shlex import quote as shlex_quote221 289- def is_bytes(x):290- return isinstance(x, (bytes, memoryview, bytearray))222+def _is_compatible_text_stream(stream, encoding, errors):223+ """Check if a stream's encoding and errors attributes are224+ compatible with the desired values.225+ """226+ return _is_compat_stream_attr(227+ stream, "encoding", encoding228+ ) and _is_compat_stream_attr(stream, "errors", errors)229 292- def _is_binary_reader(stream, default=False):293- try:294- return isinstance(stream.read(0), bytes)295- except Exception:296- return default297- # This happens in some cases where the stream was already298- # closed. In this case, we assume the default.230 300- def _is_binary_writer(stream, default=False):301- try:302- stream.write(b"")303- except Exception:304- try:305- stream.write("")306- return False307- except Exception:308- pass309- return default310- return True231+def _force_correct_text_stream(232+ text_stream,233+ encoding,234+ errors,235+ is_binary,236+ find_binary,237+ force_readable=False,238+ force_writable=False,239+):240+ if is_binary(text_stream, False):241+ binary_reader = text_stream242+ else:243+ # If the stream looks compatible, and won't default to a244+ # misconfigured ascii encoding, return it as-is.245+ if _is_compatible_text_stream(text_stream, encoding, errors) and not (246+ encoding is None and _stream_is_misconfigured(text_stream)247+ ):248+ return text_stream249 312- def _find_binary_reader(stream):313- # We need to figure out if the given stream is already binary.314- # This can happen because the official docs recommend detaching315- # the streams to get binary streams. Some code might do this, so316- # we need to deal with this case explicitly.317- if _is_binary_reader(stream, False):318- return stream250+ # Otherwise, get the underlying binary reader.251+ binary_reader = find_binary(text_stream)252 320- buf = getattr(stream, "buffer", None)253+ # If that's not possible, silently use the original reader254+ # and get mojibake instead of exceptions.255+ if binary_reader is None:256+ return text_stream257 322- # Same situation here; this time we assume that the buffer is323- # actually binary in case it's closed.324- if buf is not None and _is_binary_reader(buf, True):325- return buf258+ # Default errors to replace instead of strict in order to get259+ # something that works.260+ if errors is None:261+ errors = "replace"262 327- def _find_binary_writer(stream):328- # We need to figure out if the given stream is already binary.329- # This can happen because the official docs recommend detaching330- # the streams to get binary streams. Some code might do this, so331- # we need to deal with this case explicitly.332- if _is_binary_writer(stream, False):333- return stream263+ # Wrap the binary stream in a text stream with the correct264+ # encoding parameters.265+ return _make_text_stream(266+ binary_reader,267+ encoding,268+ errors,269+ force_readable=force_readable,270+ force_writable=force_writable,271+ )272 335- buf = getattr(stream, "buffer", None)273 337- # Same situation here; this time we assume that the buffer is338- # actually binary in case it's closed.339- if buf is not None and _is_binary_writer(buf, True):340- return buf274+def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):275+ return _force_correct_text_stream(276+ text_reader,277+ encoding,278+ errors,279+ _is_binary_reader,280+ _find_binary_reader,281+ force_readable=force_readable,282+ )283 342- def _stream_is_misconfigured(stream):343- """A stream is misconfigured if its encoding is ASCII."""344- # If the stream does not have an encoding set, we assume it's set345- # to ASCII. This appears to happen in certain unittest346- # environments. It's not quite clear what the correct behavior is347- # but this at least will force Click to recover somehow.348- return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")284 350- def _is_compat_stream_attr(stream, attr, value):351- """A stream attribute is compatible if it is equal to the352- desired value or the desired value is unset and the attribute353- has a value.354- """355- stream_value = getattr(stream, attr, None)356- return stream_value == value or (value is None and stream_value is not None)357-358- def _is_compatible_text_stream(stream, encoding, errors):359- """Check if a stream's encoding and errors attributes are360- compatible with the desired values.361- """362- return _is_compat_stream_attr(363- stream, "encoding", encoding364- ) and _is_compat_stream_attr(stream, "errors", errors)365-366- def _force_correct_text_stream(367- text_stream,285+def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):286+ return _force_correct_text_stream(287+ text_writer,288 encoding,289 errors,370- is_binary,371- find_binary,372- force_readable=False,373- force_writable=False,374- ):375- if is_binary(text_stream, False):376- binary_reader = text_stream377- else:378- # If the stream looks compatible, and won't default to a379- # misconfigured ascii encoding, return it as-is.380- if _is_compatible_text_stream(text_stream, encoding, errors) and not (381- encoding is None and _stream_is_misconfigured(text_stream)382- ):383- return text_stream290+ _is_binary_writer,291+ _find_binary_writer,292+ force_writable=force_writable,293+ )294 385- # Otherwise, get the underlying binary reader.386- binary_reader = find_binary(text_stream)295 388- # If that's not possible, silently use the original reader389- # and get mojibake instead of exceptions.390- if binary_reader is None:391- return text_stream296+def get_binary_stdin():297+ reader = _find_binary_reader(sys.stdin)298+ if reader is None:299+ raise RuntimeError("Was not able to determine binary stream for sys.stdin.")300+ return reader301 393- # Default errors to replace instead of strict in order to get394- # something that works.395- if errors is None:396- errors = "replace"302 398- # Wrap the binary stream in a text stream with the correct399- # encoding parameters.400- return _make_text_stream(401- binary_reader,402- encoding,403- errors,404- force_readable=force_readable,405- force_writable=force_writable,406- )303+def get_binary_stdout():304+ writer = _find_binary_writer(sys.stdout)305+ if writer is None:306+ raise RuntimeError("Was not able to determine binary stream for sys.stdout.")307+ return writer308 408- def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):409- return _force_correct_text_stream(410- text_reader,411- encoding,412- errors,413- _is_binary_reader,414- _find_binary_reader,415- force_readable=force_readable,416- )309 418- def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):419- return _force_correct_text_stream(420- text_writer,421- encoding,422- errors,423- _is_binary_writer,424- _find_binary_writer,425- force_writable=force_writable,426- )310+def get_binary_stderr():311+ writer = _find_binary_writer(sys.stderr)312+ if writer is None:313+ raise RuntimeError("Was not able to determine binary stream for sys.stderr.")314+ return writer315 428- def get_binary_stdin():429- reader = _find_binary_reader(sys.stdin)430- if reader is None:431- raise RuntimeError("Was not able to determine binary stream for sys.stdin.")432- return reader316 434- def get_binary_stdout():435- writer = _find_binary_writer(sys.stdout)436- if writer is None:437- raise RuntimeError(438- "Was not able to determine binary stream for sys.stdout."439- )440- return writer317+def get_text_stdin(encoding=None, errors=None):318+ rv = _get_windows_console_stream(sys.stdin, encoding, errors)319+ if rv is not None:320+ return rv321+ return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True)322 442- def get_binary_stderr():443- writer = _find_binary_writer(sys.stderr)444- if writer is None:445- raise RuntimeError(446- "Was not able to determine binary stream for sys.stderr."447- )448- return writer323 450- def get_text_stdin(encoding=None, errors=None):451- rv = _get_windows_console_stream(sys.stdin, encoding, errors)452- if rv is not None:453- return rv454- return _force_correct_text_reader(455- sys.stdin, encoding, errors, force_readable=True456- )324+def get_text_stdout(encoding=None, errors=None):325+ rv = _get_windows_console_stream(sys.stdout, encoding, errors)326+ if rv is not None:327+ return rv328+ return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True)329 458- def get_text_stdout(encoding=None, errors=None):459- rv = _get_windows_console_stream(sys.stdout, encoding, errors)460- if rv is not None:461- return rv462- return _force_correct_text_writer(463- sys.stdout, encoding, errors, force_writable=True464- )330 466- def get_text_stderr(encoding=None, errors=None):467- rv = _get_windows_console_stream(sys.stderr, encoding, errors)468- if rv is not None:469- return rv470- return _force_correct_text_writer(471- sys.stderr, encoding, errors, force_writable=True472- )331+def get_text_stderr(encoding=None, errors=None):332+ rv = _get_windows_console_stream(sys.stderr, encoding, errors)333+ if rv is not None:334+ return rv335+ return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)336 474- def filename_to_ui(value):475- if isinstance(value, bytes):476- value = value.decode(get_filesystem_encoding(), "replace")477- else:478- value = value.encode("utf-8", "surrogateescape").decode("utf-8", "replace")479- return value337 338+def filename_to_ui(value):339+ if isinstance(value, bytes):340+ value = value.decode(get_filesystem_encoding(), "replace")341+ else:342+ value = value.encode("utf-8", "surrogateescape").decode("utf-8", "replace")343+ return value344 345+482-def get_streerror(e, default=None):346+def get_strerror(e, default=None):347 if hasattr(e, "strerror"):348 msg = e.strerror349 else:350 if default is not None:5 unmodified lines356 return msg357 358 359 def _wrap_io_open(file, mode, encoding, errors):496- """On Python 2, :func:`io.open` returns a text file wrapper that497- requires passing ``unicode`` to ``write``. Need to open the file in498- binary mode then wrap it in a subclass that can write ``str`` and499- ``unicode``.360+ """Handles not passing ``encoding`` and ``errors`` in binary mode."""361+ if "b" in mode:362+ return io.open(file, mode)363 501- Also handles not passing ``encoding`` and ``errors`` in binary mode.502- """503- binary = "b" in mode364+ return io.open(file, mode, encoding=encoding, errors=errors)365 505- if binary:506- kwargs = {}507- else:508- kwargs = {"encoding": encoding, "errors": errors}366 510- if not PY2 or binary:511- return io.open(file, mode, **kwargs)512-513- f = io.open(file, "{}b".format(mode.replace("t", "")))514- return _make_text_stream(f, **kwargs)515-516-367 def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):368 binary = "b" in mode369 370 # Standard streams first. These are simple because they don't need65 unmodified lines436 f = _wrap_io_open(fd, mode, encoding, errors)437 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True438 439 590-# Used in a destructor call, needs extra protection from interpreter cleanup.591-if hasattr(os, "replace"):592- _replace = os.replace593- _can_replace = True594-else:595- _replace = os.rename596- _can_replace = not WIN597-598-440 class _AtomicFile(object):441 def __init__(self, f, tmp_filename, real_filename):442 self._f = f443 self._tmp_filename = tmp_filename7 unmodified lines451 def close(self, delete=False):452 if self.closed:453 return454 self._f.close()614- if not _can_replace:615- try:616- os.remove(self._real_filename)617- except OSError:618- pass619- _replace(self._tmp_filename, self._real_filename)455+ os.replace(self._tmp_filename, self._real_filename)456 self.closed = True457 458 def __getattr__(self, name):459 return getattr(self._f, name)7 unmodified lines467 def __repr__(self):468 return repr(self._f)469 470 635-auto_wrap_for_ansi = None636-colorama = None637-get_winterm_size = None638-639-471 def strip_ansi(value):472 return _ansi_re.sub("", value)473 474 23 unmodified lines498 if WIN:499 # Windows has a smaller terminal500 DEFAULT_COLUMNS = 79501 671- from ._winconsole import _get_windows_console_stream, _wrap_std_stream502+ from ._winconsole import _get_windows_console_stream503 504 def _get_argv_encoding():505 import locale506 507 return locale.getpreferredencoding()508 678- if PY2:679-680- def raw_input(prompt=""):681- sys.stderr.flush()682- if prompt:683- stdout = _default_text_stdout()684- stdout.write(prompt)685- stdin = _default_text_stdin()686- return stdin.readline().rstrip("\r\n")687-509 try:510 import colorama511 except ImportError:512 pass19 unmodified lines532 533 def _safe_write(s):534 try:535 return _write(s)715- except:536+ except BaseException:537 ansi_wrapper.reset_all()538 raise539 540 rv.write = _safe_write14 unmodified lines555 556 def _get_argv_encoding():557 return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()558 738- _get_windows_console_stream = lambda *x: None739- _wrap_std_stream = lambda *x: None559+ def _get_windows_console_stream(f, encoding, errors):560+ return None561 562 563 def term_len(x):564 return len(strip_ansi(x))47 unmodified linesmodified:src/click/_termui_impl.py+10 added-12 removed
5 unmodified lines6 """7 import contextlib8 import math9 import os10+import shlex11 import sys12 import time13 14 from ._compat import _default_text_stdout15 from ._compat import CYGWIN16 from ._compat import get_best_encoding16-from ._compat import int_types17 from ._compat import isatty18 from ._compat import open_stream19-from ._compat import range_type20-from ._compat import shlex_quote19 from ._compat import strip_ansi20 from ._compat import term_len21 from ._compat import WIN22 from .exceptions import ClickException19 unmodified lines42 try:43 hint = get_hint(obj)44 except TypeError:45 return None48- if hint is NotImplemented or not isinstance(hint, int_types) or hint < 0:46+ if hint is NotImplemented or not isinstance(hint, int) or hint < 0:47 return None48 return hint49 50 35 unmodified lines86 length = _length_hint(iterable)87 if iterable is None:88 if length is None:89 raise TypeError("iterable or length is required")92- iterable = range_type(length)90+ iterable = range(length)91 self.iter = iter(iterable)92 self.length = length93 self.length_known = length is not None94 self.pos = 0263 unmodified lines358 os.close(fd)359 try:360 if (361 hasattr(os, "system")364- and os.system("more {}".format(shlex_quote(filename))) == 0362+ and os.system("more {}".format(shlex.quote(filename))) == 0363 ):364 return _pipepager(generator, "more", color)365 return _nullpager(stdout, generator, color)366 finally:61 unmodified lines428 encoding = get_best_encoding(sys.stdout)429 with open_stream(filename, "wb")[0] as f:430 f.write(text.encode(encoding))431 try:434- os.system("{} {}".format(shlex_quote(cmd), shlex_quote(filename)))432+ os.system("{} {}".format(shlex.quote(cmd), shlex.quote(filename)))433 finally:434 os.unlink(filename)435 436 36 unmodified lines473 else:474 environ = None475 try:476 c = subprocess.Popen(479- "{} {}".format(shlex_quote(editor), shlex_quote(filename)),477+ "{} {}".format(shlex.quote(editor), shlex.quote(filename)),478 env=environ,479 shell=True,480 )481 exit_code = c.wait()68 unmodified lines550 null.close()551 elif WIN:552 if locate:553 url = _unquote_file(url)556- args = "explorer /select,{}".format(shlex_quote(url))554+ args = "explorer /select,{}".format(shlex.quote(url))555 else:558- args = 'start {} "" {}'.format("/WAIT" if wait else "", shlex_quote(url))556+ args = 'start {} "" {}'.format("/WAIT" if wait else "", shlex.quote(url))557 return os.system(args)558 elif CYGWIN:559 if locate:560 url = _unquote_file(url)563- args = "cygstart {}".format(shlex_quote(os.path.dirname(url)))561+ args = "cygstart {}".format(shlex.quote(os.path.dirname(url)))562 else:565- args = "cygstart {} {}".format("-w" if wait else "", shlex_quote(url))563+ args = "cygstart {} {}".format("-w" if wait else "", shlex.quote(url))564 return os.system(args)565 566 try:567 if locate:109 unmodified linesmodified:src/click/_unicodefun.py-49 removed
1 import codecs2 import os3-import sys3 5-from ._compat import PY24 7-8-def _find_unicode_literals_frame():9- import __future__10-11- if not hasattr(sys, "_getframe"): # not all Python implementations have it12- return 013- frm = sys._getframe(1)14- idx = 115- while frm is not None:16- if frm.f_globals.get("__name__", "").startswith("click."):17- frm = frm.f_back18- idx += 119- elif frm.f_code.co_flags & __future__.unicode_literals.compiler_flag:20- return idx21- else:22- break23- return 024-25-26-def _check_for_unicode_literals():27- if not __debug__:28- return29-30- from . import disable_unicode_literals_warning31-32- if not PY2 or disable_unicode_literals_warning:33- return34- bad_frame = _find_unicode_literals_frame()35- if bad_frame <= 0:36- return37- from warnings import warn38-39- warn(40- Warning(41- "Click detected the use of the unicode_literals __future__"42- " import. This is heavily discouraged because it can"43- " introduce subtle bugs in your code. You should instead"44- ' use explicit u"" literals for your unicode strings. For'45- " more information see"46- " https://click.palletsprojects.com/python3/"47- ),48- stacklevel=bad_frame,49- )50-51-5 def _verify_python3_env():6 """Ensures that the environment is good for unicode on Python 3."""54- if PY2:55- return7 try:8 import locale9 10 fs_enc = codecs.lookup(locale.getpreferredencoding()).name72 unmodified linesmodified:src/click/_winconsole.py+8 added-67 removed
7 unmodified lines8 # the entire interpreter but just work in our little world of9 # echo and prompt.10 import ctypes11 import io12-import os13-import sys12 import time15-import zlib13 from ctypes import byref14 from ctypes import c_char15 from ctypes import c_char_p16 from ctypes import c_int2 unmodified lines19 from ctypes import c_void_p20 from ctypes import POINTER21 from ctypes import py_object22 from ctypes import windll26-from ctypes import WinError23 from ctypes import WINFUNCTYPE24 from ctypes.wintypes import DWORD25 from ctypes.wintypes import HANDLE26 from ctypes.wintypes import LPCWSTR1 unmodified line28 29 import msvcrt30 31 from ._compat import _NonClosingTextIOWrapper36-from ._compat import PY237-from ._compat import text_type32 33 try:34 from ctypes import pythonapi35 54 unmodified lines90 ("suboffsets", c_ssize_p),91 ("internal", c_void_p),92 ]93 100- if PY2:101- _fields_.insert(-1, ("smalltable", c_ssize_t * 2))94 103-95 # On PyPy we cannot get buffers so our ability to operate here is96 # severely limited.97 if pythonapi is None:98 get_buffer = None95 unmodified lines194 def name(self):195 return self.buffer.name196 197 def write(self, x):207- if isinstance(x, text_type):198+ if isinstance(x, str):199 return self._text_stream.write(x)200 try:201 self.flush()202 except Exception:40 unmodified lines243 self.__wrapped.write(text[written : written + to_write])244 written += to_write245 246 256-_wrapped_std_streams = set()257-258-259-def _wrap_std_stream(name):260- # Python 2 & Windows 7 and below261- if (262- PY2263- and sys.getwindowsversion()[:2] <= (6, 1)264- and name not in _wrapped_std_streams265- ):266- setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))267- _wrapped_std_streams.add(name)268-269-247 def _get_text_stdin(buffer_stream):248 text_stream = _NonClosingTextIOWrapper(249 io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),250 "utf-16-le",22 unmodified lines273 )274 return ConsoleStream(text_stream, buffer_stream)275 276 300-if PY2:301-302- def _hash_py_argv():303- return zlib.crc32("\x00".join(sys.argv[1:]))304-305- _initial_argv_hash = _hash_py_argv()306-307- def _get_windows_argv():308- argc = c_int(0)309- argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))310- if not argv_unicode:311- raise WinError()312- try:313- argv = [argv_unicode[i] for i in range(0, argc.value)]314- finally:315- LocalFree(argv_unicode)316- del argv_unicode317-318- if not hasattr(sys, "frozen"):319- argv = argv[1:]320- while len(argv) > 0:321- arg = argv[0]322- if not arg.startswith("-") or arg == "-":323- break324- argv = argv[1:]325- if arg.startswith(("-c", "-m")):326- break327-328- return argv[1:]329-330-277 _stream_factories = {278 0: _get_text_stdin,279 1: _get_text_stdout,280 2: _get_text_stderr,15 unmodified lines296 297 def _get_windows_console_stream(f, encoding, errors):298 if (299 get_buffer is not None354- and encoding in ("utf-16-le", None)355- and errors in ("strict", None)300+ and encoding in {"utf-16-le", None}301+ and errors in {"strict", None}302 and _is_console(f)303 ):304 func = _stream_factories.get(f.fileno())305 if func is not None:360- if not PY2:361- f = getattr(f, "buffer", None)362- if f is None:363- return None364- else:365- # If we are on Python 2 we need to set the stream that we366- # deal with to binary mode as otherwise the exercise if a367- # bit moot. The same problems apply as for368- # get_binary_stdin and friends from _compat.369- msvcrt.setmode(f.fileno(), os.O_BINARY)306+ f = getattr(f, "buffer", None)307+308+ if f is None:309+ return None310+311 return func(f)modified:src/click/core.py+8 added-18 removed
4 unmodified lines5 from contextlib import contextmanager6 from functools import update_wrapper7 from itertools import repeat8 9-from ._compat import isidentifier10-from ._compat import iteritems11-from ._compat import PY212-from ._compat import string_types13-from ._unicodefun import _check_for_unicode_literals9 from ._unicodefun import _verify_python3_env10 from .exceptions import Abort11 from .exceptions import BadParameter12 from .exceptions import ClickException12 unmodified lines25 from .types import BOOL26 from .types import convert_type27 from .types import IntRange28 from .utils import echo34-from .utils import get_os_args29 from .utils import make_default_short_help30 from .utils import make_str31 from .utils import PacifyFlushWrapper32 696 unmodified lines729 :param parent: the parent context if available.730 :param extra: extra keyword arguments forwarded to the context731 constructor.732 """739- for key, value in iteritems(self.context_settings):733+ for key, value in self.context_settings.items():734 if key not in extra:735 extra[key] = value736 ctx = Context(self, info_name=info_name, parent=parent, **extra)737 with ctx.scope(cleanup=False):52 unmodified lines790 of :meth:`invoke`.791 :param extra: extra keyword arguments are forwarded to the context792 constructor. See :class:`Context` for more information.793 """800- # If we are in Python 3, we will verify that the environment is801- # sane at this point or reject further execution to avoid a802- # broken script.803- if not PY2:804- _verify_python3_env()805- else:806- _check_for_unicode_literals()794+ # Verify that the environment is configured correctly, or reject795+ # further execution to avoid a broken script.796+ _verify_python3_env()797 798 if args is None:809- args = get_os_args()799+ args = sys.argv[1:]800 else:801 args = list(args)802 803 if prog_name is None:1026 unmodified lines1830 name = None1831 possible_names = []1832 1833 for decl in decls:1844- if isidentifier(decl):1834+ if decl.isidentifier():1835 if name is not None:1836 raise TypeError("Name defined twice")1837 name = decl1838 else:13 unmodified lines1852 1853 if name is None and possible_names:1854 possible_names.sort(key=lambda x: -len(x[0])) # group long options first1855 name = possible_names[0][1].replace("-", "_").lower()1866- if not isidentifier(name):1856+ if not name.isidentifier():1857 name = None1858 1859 if name is None:1860 if not expose_value:70 unmodified lines1931 else envvar1932 )1933 )1934 if self.default is not None and (self.show_default or ctx.show_default):1945- if isinstance(self.show_default, string_types):1935+ if isinstance(self.show_default, str):1936 default_string = "({})".format(self.show_default)1937 elif isinstance(self.default, (list, tuple)):1938 default_string = ", ".join(str(d) for d in self.default)1939 elif inspect.isfunction(self.default):138 unmodified linesmodified:src/click/decorators.py+1 added-4 removed
1 import inspect2 import sys3 from functools import update_wrapper4 5-from ._compat import iteritems6-from ._unicodefun import _check_for_unicode_literals5 from .core import Argument6 from .core import Command7 from .core import Group8 from .core import Option82 unmodified lines91 help = help.decode("utf-8")92 else:93 help = inspect.cleandoc(help)94 attrs["help"] = help97- _check_for_unicode_literals()95 return cls(96 name=name or f.__name__.lower().replace("_", "-"),97 callback=f,98 params=params,184 unmodified lines283 pass284 else:285 for dist in pkg_resources.working_set:286 scripts = dist.get_entry_map().get("console_scripts") or {}290- for _, entry_point in iteritems(scripts):287+ for entry_point in scripts.values():288 if entry_point.module_name == module:289 ver = dist.version290 break291 if ver is None:39 unmodified linesmodified:src/click/exceptions.py+2 added-19 removed
1 from ._compat import filename_to_ui2 from ._compat import get_text_stderr3-from ._compat import PY23 from .utils import echo4 5 6 def _join_param_hints(param_hint):4 unmodified lines11 12 class ClickException(Exception):13 """An exception that Click can handle and show to the user."""14 16- #: The exit code for this exception15+ #: The exit code for this exception.16 exit_code = 117 18 def __init__(self, message):20- ctor_msg = message21- if PY2:22- if ctor_msg is not None:23- ctor_msg = ctor_msg.encode("utf-8")24- Exception.__init__(self, ctor_msg)19+ super().__init__(message)20 self.message = message21 22 def format_message(self):23 return self.message24 25 def __str__(self):26 return self.message27 33- if PY2:34- __unicode__ = __str__35-36- def __str__(self):37- return self.message.encode("utf-8")38-28 def show(self, file=None):29 if file is None:30 file = get_text_stderr()31 echo("Error: {}".format(self.format_message()), file=file)118 unmodified lines150 return "missing parameter: {}".format(param_name)151 else:152 return self.message153 165- if PY2:166- __unicode__ = __str__154 168- def __str__(self):169- return self.__unicode__().encode("utf-8")170-171-155 class NoSuchOption(UsageError):156 """Raised if click attempted to handle an option that does not157 exist.158 78 unmodified linesmodified:src/click/termui.py+3 added-6 removed
6 unmodified lines7 8 from ._compat import DEFAULT_COLUMNS9 from ._compat import get_winterm_size10 from ._compat import isatty11-from ._compat import raw_input12-from ._compat import string_types11 from ._compat import strip_ansi14-from ._compat import text_type12 from ._compat import WIN13 from .exceptions import Abort14 from .exceptions import UsageError15 from .globals import resolve_color_default4 unmodified lines20 from .utils import LazyFile21 22 # The prompt functions to use. The doc tools currently override these23 # functions to customize how they work.27-visible_prompt_func = raw_input24+visible_prompt_func = input25 26 _ansi_colors = {27 "black": 30,28 "red": 31,245 unmodified lines274 color = resolve_color_default(color)275 276 if inspect.isgeneratorfunction(text_or_generator):277 i = text_or_generator()281- elif isinstance(text_or_generator, string_types):278+ elif isinstance(text_or_generator, str):279 i = [text_or_generator]280 else:281 i = iter(text_or_generator)282 283 # convert every element of i to a text type if necessary287- text_generator = (el if isinstance(el, string_types) else text_type(el) for el in i)284+ text_generator = (el if isinstance(el, str) else str(el) for el in i)285 286 from ._termui_impl import pager287 288 return pager(itertools.chain(text_generator, "\n"), color)404 unmodified linesmodified:src/click/testing.py+19 added-34 removed
1 import contextlib2+import io3 import os4 import shlex5 import shutil6 import sys1 unmodified line8 9 from . import formatting10 from . import termui11 from . import utils11-from ._compat import iteritems12-from ._compat import PY213-from ._compat import string_types12+from ._compat import _find_binary_reader13 14 16-if PY2:17- from cStringIO import StringIO18-else:19- import io20- from ._compat import _find_binary_reader21-22-15 class EchoingStdin(object):16 def __init__(self, input, output):17 self._input = input18 self._output = output23 unmodified lines42 43 def make_input_stream(input, charset):44 # Is already an input stream.45 if hasattr(input, "read"):54- if PY2:55- return input46 rv = _find_binary_reader(input)47+48 if rv is not None:49 return rv50+51 raise TypeError("Could not find binary reader for input stream.")52 53 if input is None:54 input = b""55 elif not isinstance(input, bytes):56 input = input.encode(charset)65- if PY2:66- return StringIO(input)57+58 return io.BytesIO(input)59 60 61 class Result(object):112 unmodified lines174 formatting.FORCED_WIDTH = 80175 176 env = self.make_env(env)177 187- if PY2:188- bytes_output = StringIO()189- if self.echo_stdin:190- input = EchoingStdin(input, bytes_output)191- sys.stdout = bytes_output192- if not self.mix_stderr:193- bytes_error = StringIO()194- sys.stderr = bytes_error195- else:196- bytes_output = io.BytesIO()178+ bytes_output = io.BytesIO()197- if self.echo_stdin:198- input = EchoingStdin(input, bytes_output)199- input = io.TextIOWrapper(input, encoding=self.charset)200- sys.stdout = io.TextIOWrapper(bytes_output, encoding=self.charset)201- if not self.mix_stderr:202- bytes_error = io.BytesIO()203- sys.stderr = io.TextIOWrapper(bytes_error, encoding=self.charset)179 180+ if self.echo_stdin:181+ input = EchoingStdin(input, bytes_output)182+183+ input = io.TextIOWrapper(input, encoding=self.charset)184+ sys.stdout = io.TextIOWrapper(bytes_output, encoding=self.charset)185+186+ if not self.mix_stderr:187+ bytes_error = io.BytesIO()188+ sys.stderr = io.TextIOWrapper(bytes_error, encoding=self.charset)189+190 if self.mix_stderr:191 sys.stderr = sys.stdout192 193 sys.stdin = input34 unmodified lines228 utils.should_strip_ansi = should_strip_ansi229 230 old_env = {}231 try:247- for key, value in iteritems(env):232+ for key, value in env.items():233 old_env[key] = os.environ.get(key)234 if value is None:235 try:236 del os.environ[key]2 unmodified lines239 else:240 os.environ[key] = value241 yield (bytes_output, not self.mix_stderr and bytes_error)242 finally:258- for key, value in iteritems(old_env):243+ for key, value in old_env.items():244 if value is None:245 try:246 del os.environ[key]247 except Exception:53 unmodified lines301 with self.isolation(input=input, env=env, color=color) as outstreams:302 exception = None303 exit_code = 0304 320- if isinstance(args, string_types):305+ if isinstance(args, str):306 args = shlex.split(args)307 308 try:309 prog_name = extra.pop("prog_name")58 unmodified linesmodified:src/click/types.py+9 added-17 removed
3 unmodified lines4 5 from ._compat import _get_argv_encoding6 from ._compat import filename_to_ui7 from ._compat import get_filesystem_encoding8-from ._compat import get_streerror8+from ._compat import get_strerror9 from ._compat import open_stream10-from ._compat import PY211-from ._compat import text_type10 from .exceptions import BadParameter11 from .utils import LazyFile12 from .utils import safecall13 77 unmodified lines91 try:92 return self.func(value)93 except ValueError:94 try:97- value = text_type(value)95+ value = str(value)96 except UnicodeError:99- value = str(value).decode("utf-8", "replace")97+ value = value.decode("utf-8", "replace")98+99 self.fail(value, param, ctx)100 101 102 class UnprocessedParamType(ParamType):74 unmodified lines177 for normed_choice, original in normed_choices.items()178 }179 180 if not self.case_sensitive:182- if PY2:183- lower = str.lower184- else:185- lower = str.casefold186-187- normed_value = lower(normed_value)181+ normed_value = normed_value.casefold()182 normed_choices = {189- lower(normed_choice): original183+ normed_choice.casefold(): original184 for normed_choice, original in normed_choices.items()185 }186 187 if normed_value in normed_choices:232 unmodified lines420 def convert(self, value, param, ctx):421 import uuid422 423 try:430- if PY2 and isinstance(value, text_type):431- value = value.encode("ascii")424 return uuid.UUID(value)425 except ValueError:426 self.fail("{} is not a valid UUID value".format(value), param, ctx)427 80 unmodified lines508 return f509 except (IOError, OSError) as e: # noqa: B014510 self.fail(511 "Could not open file: {}: {}".format(520- filename_to_ui(value), get_streerror(e)512+ filename_to_ui(value), get_strerror(e)513 ),514 param,515 ctx,516 )63 unmodified lines580 self.path_type = "Path"581 582 def coerce_path_result(self, rv):583 if self.type is not None and not isinstance(rv, self.type):592- if self.type is text_type:584+ if self.type is str:585 rv = rv.decode(get_filesystem_encoding())586 else:587 rv = rv.encode(get_filesystem_encoding())588 return rv103 unmodified lines692 if isinstance(ty, tuple):693 return Tuple(ty)694 if isinstance(ty, ParamType):695 return ty704- if ty is text_type or ty is str or ty is None:696+ if ty is str or ty is None:697 return STRING698 if ty is int:699 return INT700 # Booleans are only okay if not guessed. This is done because for54 unmodified linesmodified:src/click/utils.py+21 added-31 removed
1 unmodified line2 import sys3 4 from ._compat import _default_text_stderr5 from ._compat import _default_text_stdout6+from ._compat import _find_binary_writer7 from ._compat import auto_wrap_for_ansi8 from ._compat import binary_streams9 from ._compat import filename_to_ui10 from ._compat import get_filesystem_encoding10-from ._compat import get_streerror11+from ._compat import get_strerror12 from ._compat import is_bytes13 from ._compat import open_stream13-from ._compat import PY214 from ._compat import should_strip_ansi15-from ._compat import string_types15 from ._compat import strip_ansi16 from ._compat import text_streams18-from ._compat import text_type17 from ._compat import WIN18 from .globals import resolve_color_default19 22-if not PY2:23- from ._compat import _find_binary_writer24-elif WIN:25- from ._winconsole import _get_windows_argv26- from ._winconsole import _hash_py_argv27- from ._winconsole import _initial_argv_hash20 29-echo_native_types = string_types + (bytes, bytearray)21+echo_native_types = (str, bytes, bytearray)22 23 24 def _posixify(name):25 return "-".join(name.split()).lower()17 unmodified lines43 try:44 return value.decode(get_filesystem_encoding())45 except UnicodeError:46 return value.decode("utf-8", "replace")55- return text_type(value)47+ return str(value)48 49 50 def make_default_short_help(help, max_length=45):51 """Return a condensed version of help string."""68 unmodified lines120 )121 except (IOError, OSError) as e: # noqa: E402122 from .exceptions import FileError123 132- raise FileError(self.name, hint=get_streerror(e))124+ raise FileError(self.name, hint=get_strerror(e))125 self._f = rv126 return rv127 128 def close(self):93 unmodified lines222 file = _default_text_stdout()223 224 # Convert non bytes/text into the native string type.225 if message is not None and not isinstance(message, echo_native_types):234- message = text_type(message)226+ message = str(message)227 228 if nl:229 message = message or u""238- if isinstance(message, text_type):230+ if isinstance(message, str):231 message += u"\n"232 else:233 message += b"\n"234 1 unmodified line236 # like bytes, we manually need to find the binary stream and write the237 # message in there. This is done separately so that most stream238 # types will work as you would expect. Eg: you can write to StringIO239 # for other cases.248- if message and not PY2 and is_bytes(message):240+ if message and is_bytes(message):241 binary_file = _find_binary_writer(file)242 if binary_file is not None:243 file.flush()244 binary_file.write(message)86 unmodified lines331 return f332 333 334 def get_os_args():343- """This returns the argument part of sys.argv in the most appropriate344- form for processing. What this means is that this return value is in345- a format that works for Click to process but does not necessarily346- correspond well to what's actually standard for the interpreter.335+ """Returns the argument part of ``sys.argv``, removing the first336+ value which is the name of the script.337 348- On most environments the return value is ``sys.argv[:1]`` unchanged.349- However if you are on Windows and running Python 2 the return value350- will actually be a list of unicode strings instead because the351- default behavior on that platform otherwise will not be able to352- carry all possible values that sys.argv can have.353-354- .. versionadded:: 6.0338+ .. deprecated:: 8.0339+ Will be removed in 8.1. Access ``sys.argv[1:]`` directly340+ instead.341 """356- # We can only extract the unicode argv if sys.argv has not been357- # changed since the startup of the application.358- if PY2 and WIN and _initial_argv_hash == _hash_py_argv():359- return _get_windows_argv()342+ import warnings343+344+ warnings.warn(345+ "'get_os_args' is deprecated and will be removed in 8.1. Access"346+ " 'sys.argv[1:]' directly instead.",347+ DeprecationWarning,348+ stacklevel=2,349+ )350 return sys.argv[1:]351 352 353 def format_filename(filename, shorten=False):92 unmodified linesmodified:tests/test_arguments.py+6 added-17 removed
2 unmodified lines3 4 import pytest5 6 import click7-from click._compat import PY28-from click._compat import text_type7 8 9 def test_nargs_star(runner):10 @click.command()69 unmodified lines80 @click.command()81 @click.argument("arg")82 def from_bytes(arg):83 assert isinstance(86- arg, text_type84+ arg, str85 ), "UTF-8 encoded argument should be implicitly converted to Unicode"86 87 # Simulate empty locale environment variables90- if PY2:91- monkeypatch.setattr(sys.stdin, "encoding", "ANSI_X3.4-1968")92- monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "ANSI_X3.4-1968")93- monkeypatch.setattr(sys, "getdefaultencoding", lambda: "ascii")94- else:95- monkeypatch.setattr(sys.stdin, "encoding", "utf-8")96- monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")97- monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")88+ monkeypatch.setattr(sys.stdin, "encoding", "utf-8")89+ monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")90+ monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")91 92 runner.invoke(93 from_bytes,94 [u"Something outside of ASCII range: 林".encode("UTF-8")],165 unmodified lines260 for arg in (a, b, c):261 click.echo(arg)262 263 result = runner.invoke(cmd, ["a", "b", "c"])271- assert result.output.splitlines() == ["(u'a',)" if PY2 else "('a',)", "b", "c"]264+ assert result.output.splitlines() == ["('a',)", "b", "c"]265 266 267 def test_nargs_specified_plus_star_ordering(runner):268 @click.command()4 unmodified lines273 for arg in (a, b, c):274 click.echo(arg)275 276 result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])284- assert result.output.splitlines() == [285- "(u'a', u'b', u'c')" if PY2 else "('a', 'b', 'c')",286- "d",287- "(u'e', u'f')" if PY2 else "('e', 'f')",288- ]277+ assert result.output.splitlines() == ["('a', 'b', 'c')", "d", "('e', 'f')"]278 279 280 def test_defaults_for_nargs(runner):281 @click.command()23 unmodified linesmodified:tests/test_options.py+3 added-4 removed
3 unmodified lines4 5 import pytest6 7 import click8-from click._compat import text_type8 9 10 def test_prefixes(runner):11 @click.command()156 unmodified lines168 @click.command()169 @click.option("--arg1", multiple=True, default=("foo", "bar"))170 @click.option("--arg2", multiple=True, default=(1, "a"))171 def cmd(arg1, arg2):173- assert all(isinstance(e[0], text_type) for e in arg1)174- assert all(isinstance(e[1], text_type) for e in arg1)172+ assert all(isinstance(e[0], str) for e in arg1)173+ assert all(isinstance(e[1], str) for e in arg1)174 175 assert all(isinstance(e[0], int) for e in arg2)177- assert all(isinstance(e[1], text_type) for e in arg2)176+ assert all(isinstance(e[1], str) for e in arg2)177 178 result = runner.invoke(179 cmd, "--arg1 a b --arg1 test 1 --arg2 2 two --arg2 4 four".split()180 )377 unmodified linesmodified:tests/test_testing.py+3 added-9 removed
1 import os2 import sys3+from io import BytesIO4 5 import pytest6 7 import click7-from click._compat import PY28 from click._compat import WIN9 from click.testing import CliRunner10 11-# Use the most reasonable io that users would use for the python version.12-if PY2:13- from cStringIO import StringIO as ReasonableBytesIO14-else:15- from io import BytesIO as ReasonableBytesIO11 17-12 def test_runner():13 @click.command()14 def test():15 i = click.get_binary_stream("stdin")28 unmodified lines44 o.write(chunk)45 o.flush()46 47 runner = CliRunner()54- result = runner.invoke(test, input=ReasonableBytesIO(b"Hello World!\n"))48+ result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))49 assert not result.exception50 assert result.output == "Hello World!\n"51 52 runner = CliRunner(echo_stdin=True)59- result = runner.invoke(test, input=ReasonableBytesIO(b"Hello World!\n"))53+ result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))54 assert not result.exception55 assert result.output == "Hello World!\nHello World!\n"56 57 240 unmodified lines