Skip to content

Always read python source using UTF-8 #59

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
Release History
---------------

2.2.1
- Python source is now always read using utf-8, even if default encoding for
reading files is set otherwise.

2.2.0

- Added `--skip-incompatible` flag to `pip-extra-reqs`, which makes it ignore
Expand Down
2 changes: 1 addition & 1 deletion pip_check_reqs/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '2.2.0'
__version__ = '2.2.1'
2 changes: 1 addition & 1 deletion pip_check_reqs/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def find_imported_modules(options):
log.info('ignoring: %s', os.path.relpath(filename))
continue
log.debug('scanning: %s', os.path.relpath(filename))
with open(filename) as f:
with open(filename, encoding='utf-8') as f:
content = f.read()
vis.set_location(filename)
vis.visit(ast.parse(content))
Expand Down
31 changes: 30 additions & 1 deletion tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ class FakeFile():
'from . import friend',
]

def __init__(self, filename):
def __init__(self, filename, encoding=None):
pass

def read(self):
Expand Down Expand Up @@ -196,3 +196,32 @@ def ignore_reqs(self, modname):
requirements_filename=str(fake_requirements_file),
)
assert not reqs


def test_find_imported_modules_sets_encoding_to_utf8_when_reading(tmp_path):
(tmp_path / 'module.py').touch()

class options:
paths = [tmp_path]

def ignore_files(*_):
return False

expected_encoding = 'utf-8'
used_encoding = None

original_open = common.__builtins__['open']

def mocked_open(*args, **kwargs):
# As of Python 3.9, the args to open() are as follows:
# file, mode, buffering, encoding, erorrs, newline, closedf, opener
nonlocal used_encoding
if 'encoding' in kwargs:
used_encoding = kwargs['encoding']
return original_open(*args, **kwargs)

common.__builtins__['open'] = mocked_open
common.find_imported_modules(options)
common.__builtins__['open'] = original_open

assert used_encoding == expected_encoding