| 1 |
import sys |
| 2 |
from pathlib import Path |
| 3 |
from unittest.mock import patch |
| 4 |
|
| 5 |
import pytest |
| 6 |
|
| 7 |
from isort import io |
| 8 |
from isort.exceptions import UnsupportedEncoding |
| 9 |
|
| 10 |
|
| 11 |
class TestFile: |
| 12 |
@pytest.mark.skipif(sys.platform == "win32", reason="Can't run file encoding test in AppVeyor") |
| 13 |
def test_read(self, tmp_path: Path) -> None: |
| 14 |
test_file_content = """# -*- encoding: ascii -*- |
| 15 |
|
| 16 |
import Ὡ |
| 17 |
""" |
| 18 |
test_file = tmp_path / "file.py" |
| 19 |
test_file.write_text(test_file_content) |
| 20 |
with pytest.raises(UnicodeDecodeError): |
| 21 |
with io.File.read(str(test_file)) as file_handler: |
| 22 |
file_handler.stream.read() |
| 23 |
|
| 24 |
def test_from_content(self, tmp_path: Path) -> None: |
| 25 |
test_file = tmp_path / "file.py" |
| 26 |
test_file.write_text("import os", "utf8") |
| 27 |
file_obj = io.File.from_contents("import os", filename=str(test_file)) |
| 28 |
assert file_obj |
| 29 |
assert file_obj.extension == "py" |
| 30 |
|
| 31 |
def test_open(self, tmp_path: Path) -> None: |
| 32 |
with pytest.raises(FileNotFoundError): |
| 33 |
io.File._open("THISCANTBEAREALFILEὩὩὩὩὩὩὩὩὩὩὩὩ.ὩὩὩὩὩ") |
| 34 |
|
| 35 |
def raise_arbitrary_exception(*args: object, **kwargs: object) -> None: |
| 36 |
raise RuntimeError("test") |
| 37 |
|
| 38 |
test_file = tmp_path / "file.py" |
| 39 |
test_file.write_text("import os") |
| 40 |
assert io.File._open(str(test_file)) |
| 41 |
|
| 42 |
# correctly responds to error determining encoding |
| 43 |
with patch("tokenize.detect_encoding", raise_arbitrary_exception): |
| 44 |
with pytest.raises(UnsupportedEncoding): |
| 45 |
io.File._open(str(test_file)) |