|
16 | 16 | back_up_path,
|
17 | 17 | revert_back_up_path,
|
18 | 18 | safe_write_text,
|
| 19 | + safe_read_text, |
19 | 20 | write_text,
|
20 | 21 | )
|
21 | 22 | from databricks.labs.ucx.source_code.linters.base import Fixer
|
@@ -109,6 +110,46 @@ def apply(self, code) -> str:
|
109 | 110 | assert not fixer.is_supported("other-code")
|
110 | 111 |
|
111 | 112 |
|
| 113 | +def test_safe_read_text(tmp_path) -> None: |
| 114 | + """Should read the contents of a file.""" |
| 115 | + path = tmp_path / "file.txt" |
| 116 | + path.write_text("contents") |
| 117 | + |
| 118 | + contents = safe_read_text(path) |
| 119 | + |
| 120 | + assert contents == "contents" |
| 121 | + |
| 122 | + |
| 123 | +def test_safe_read_text_handles_non_existing_file() -> None: |
| 124 | + """Should return None when the file does not exist.""" |
| 125 | + contents = safe_read_text(Path("non-existing-file.txt")) |
| 126 | + assert contents is None |
| 127 | + |
| 128 | + |
| 129 | +def test_safe_read_text_handles_directory(tmp_path) -> None: |
| 130 | + """Should return None when the path is a directory.""" |
| 131 | + contents = safe_read_text(tmp_path) |
| 132 | + assert contents is None |
| 133 | + |
| 134 | + |
| 135 | +@pytest.mark.parametrize( |
| 136 | + "os_error", |
| 137 | + [ |
| 138 | + PermissionError("Permission denied"), |
| 139 | + FileNotFoundError("File not found"), |
| 140 | + UnicodeDecodeError("utf-8", b"\x80\x81\x82", 0, 1, "invalid start byte"), |
| 141 | + ], |
| 142 | +) |
| 143 | +def test_safe_read_text_handles_os_errors(os_error: OSError) -> None: |
| 144 | + """Should return None when an OSError occurs.""" |
| 145 | + path = create_autospec(Path) |
| 146 | + path.open.side_effect = os_error |
| 147 | + |
| 148 | + contents = safe_read_text(path) |
| 149 | + |
| 150 | + assert contents is None |
| 151 | + |
| 152 | + |
112 | 153 | def test_write_text_to_non_existing_file(tmp_path) -> None:
|
113 | 154 | path = tmp_path / "file.txt"
|
114 | 155 |
|
|
0 commit comments