Skip to content

Commit 16fc00e

Browse files
authored
Do not trigger a BytesWarning under python -bb (#3642)
2 parents fe3ad76 + dbfb10a commit 16fc00e

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

src/click/types.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1104,7 +1104,8 @@ def convert(
11041104
) -> str | bytes | os.PathLike[str]:
11051105
rv = value
11061106

1107-
is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")
1107+
dash = b"-" if isinstance(rv, bytes) else "-"
1108+
is_dash = self.file_okay and self.allow_dash and rv == dash
11081109

11091110
if not is_dash:
11101111
if self.resolve_path:

tests/test_types.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import os.path
22
import pathlib
33
import platform
4+
import subprocess
5+
import sys
46
import tempfile
57

68
import pytest
@@ -125,6 +127,29 @@ def test_path_type(runner, cls, expect):
125127
assert result.return_value == expect
126128

127129

130+
def test_path_dash_no_byteswarning():
131+
"""Detecting the ``-`` dash sentinel must not compare ``bytes`` against
132+
``str``, which raises a ``BytesWarning`` under ``python -bb``.
133+
134+
The warning is only emitted when the interpreter runs with ``-b``, so this
135+
has to be checked in a subprocess. ``-bb`` turns the warning into an error,
136+
so a clean exit means no mismatched comparison happened.
137+
"""
138+
program = (
139+
"import click\n"
140+
"convert = click.Path(allow_dash=True).convert\n"
141+
"for value in ('-', '', b'-', b''):\n"
142+
" convert(value, None, None)\n"
143+
)
144+
result = subprocess.run(
145+
[sys.executable, "-bb", "-c", program],
146+
capture_output=True,
147+
text=True,
148+
)
149+
assert result.returncode == 0, result.stderr
150+
assert "BytesWarning" not in result.stderr
151+
152+
128153
def _symlinks_supported():
129154
with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:
130155
target = os.path.join(tempdir, "target")

0 commit comments

Comments
 (0)