Skip to content

Commit d17aa5e

Browse files
Merge pull request #59 from MrMino/fix-encoding
Always read python source using UTF-8
2 parents a743935 + 53bac9b commit d17aa5e

File tree

4 files changed

+36
-3
lines changed

4 files changed

+36
-3
lines changed

CHANGELOG.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22
Release History
33
---------------
44

5+
2.2.1
6+
- Python source is now always read using utf-8, even if default encoding for
7+
reading files is set otherwise.
8+
59
2.2.0
610

711
- Added `--skip-incompatible` flag to `pip-extra-reqs`, which makes it ignore

pip_check_reqs/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = '2.2.0'
1+
__version__ = '2.2.1'

pip_check_reqs/common.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def find_imported_modules(options):
119119
log.info('ignoring: %s', os.path.relpath(filename))
120120
continue
121121
log.debug('scanning: %s', os.path.relpath(filename))
122-
with open(filename) as f:
122+
with open(filename, encoding='utf-8') as f:
123123
content = f.read()
124124
vis.set_location(filename)
125125
vis.visit(ast.parse(content))

tests/test_common.py

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ class FakeFile():
106106
'from . import friend',
107107
]
108108

109-
def __init__(self, filename):
109+
def __init__(self, filename, encoding=None):
110110
pass
111111

112112
def read(self):
@@ -196,3 +196,32 @@ def ignore_reqs(self, modname):
196196
requirements_filename=str(fake_requirements_file),
197197
)
198198
assert not reqs
199+
200+
201+
def test_find_imported_modules_sets_encoding_to_utf8_when_reading(tmp_path):
202+
(tmp_path / 'module.py').touch()
203+
204+
class options:
205+
paths = [tmp_path]
206+
207+
def ignore_files(*_):
208+
return False
209+
210+
expected_encoding = 'utf-8'
211+
used_encoding = None
212+
213+
original_open = common.__builtins__['open']
214+
215+
def mocked_open(*args, **kwargs):
216+
# As of Python 3.9, the args to open() are as follows:
217+
# file, mode, buffering, encoding, erorrs, newline, closedf, opener
218+
nonlocal used_encoding
219+
if 'encoding' in kwargs:
220+
used_encoding = kwargs['encoding']
221+
return original_open(*args, **kwargs)
222+
223+
common.__builtins__['open'] = mocked_open
224+
common.find_imported_modules(options)
225+
common.__builtins__['open'] = original_open
226+
227+
assert used_encoding == expected_encoding

0 commit comments

Comments
 (0)