Debian Codegraph @

core/tests/runner_test.py

raw symbols SCIP
1 """Tests for ``runner`` module."""
2
3 from __future__ import annotations
4
5 import contextlib
6 import multiprocessing
7 import pathlib
8 import sys
9 import typing as t
10 from pathlib import Path
11
12 import pytest
13
14 from rstcheck_core import checker, config, runner, types
15
16 if t.TYPE_CHECKING:
17 import pytest_mock
18
19
20 class TestRstcheckMainRunnerInit:
21 """Test ``RstcheckMainRunner.__init__`` method."""
22
23 @staticmethod
24 def test_load_config_file_if_set(mocker: pytest_mock.MockerFixture) -> None:
25 """Test config file is loaded if set."""
26 mocked_loader = mocker.patch.object(runner.RstcheckMainRunner, "load_config_file")
27 config_file_path = pathlib.Path("some-file")
28 init_config = config.RstcheckConfig(config_path=config_file_path)
29
30 runner.RstcheckMainRunner([], init_config) # act
31
32 mocked_loader.assert_called_once_with(config_file_path, warn_unknown_settings=False)
33
34 @staticmethod
35 def test_no_load_config_file_if_unset(mocker: pytest_mock.MockerFixture) -> None:
36 """Test no config file is loaded if unset."""
37 mocked_loader = mocker.patch.object(runner.RstcheckMainRunner, "load_config_file")
38 init_config = config.RstcheckConfig()
39
40 runner.RstcheckMainRunner([], init_config) # act
41
42 mocked_loader.assert_not_called()
43
44 @staticmethod
45 @pytest.mark.skipif(sys.platform != "win32", reason="Windows specific.")
46 @pytest.mark.parametrize("pool_size", [0, 1, 60, 61, 62, 100])
47 def test_max_pool_size_on_windows(pool_size: int, monkeypatch: pytest.MonkeyPatch) -> None:
48 """Test pool size is 61 at max on windows."""
49 monkeypatch.setattr(multiprocessing, "cpu_count", lambda: pool_size)
50 init_config = config.RstcheckConfig()
51
52 result = runner.RstcheckMainRunner([], init_config)._pool_size
53
54 assert result <= 61
55
56
57 class TestRstcheckMainRunnerConfigFileLoader:
58 """Test ``RstcheckMainRunner.load_config_file`` method."""
59
60 @staticmethod
61 def test_no_config_update_on_no_file_config(monkeypatch: pytest.MonkeyPatch) -> None:
62 """Test config is not updated when no file config is found."""
63 monkeypatch.setattr(
64 config, "load_config_file_from_path", lambda _, warn_unknown_settings: None
65 )
66 init_config = config.RstcheckConfig()
67 _runner = runner.RstcheckMainRunner([], init_config)
68
69 _runner.load_config_file(pathlib.Path()) # act
70
71 assert _runner.config == init_config
72
73 @staticmethod
74 def test_config_update_on_found_file_config(monkeypatch: pytest.MonkeyPatch) -> None:
75 """Test config is updated when file config is found."""
76 file_config = config.RstcheckConfigFile(report_level=config.ReportLevel.SEVERE)
77 monkeypatch.setattr(
78 config, "load_config_file_from_path", lambda _, warn_unknown_settings: file_config
79 )
80 init_config = config.RstcheckConfig(report_level=config.ReportLevel.INFO)
81 _runner = runner.RstcheckMainRunner([], init_config, overwrite_config=True)
82
83 _runner.load_config_file(pathlib.Path()) # act
84
85 assert _runner.config.report_level == config.ReportLevel.SEVERE
86
87
88 class TestRstcheckMainRunnerFileListUpdater:
89 """Test ``RstcheckMainRunner.update_file_list`` method."""
90
91 @staticmethod
92 def test_empty_file_list() -> None:
93 """Test empty file list results in no changes."""
94 file_list: list[pathlib.Path] = []
95 init_config = config.RstcheckConfig()
96 _runner = runner.RstcheckMainRunner(file_list, init_config)
97
98 _runner.update_file_list() # act
99
100 assert not _runner._files_to_check
101
102 @staticmethod
103 def test_single_file_in_list(tmp_path: pathlib.Path) -> None:
104 """Test single file in list results in only this file in the list."""
105 test_file = tmp_path / "rst.rst"
106 test_file.touch()
107 file_list = [test_file]
108 init_config = config.RstcheckConfig()
109 _runner = runner.RstcheckMainRunner(file_list, init_config)
110
111 _runner.update_file_list() # act
112
113 assert _runner._files_to_check == file_list
114
115 @staticmethod
116 def test_multiple_files_in_list(tmp_path: pathlib.Path) -> None:
117 """Test multiple files in list results in only these files in the list."""
118 test_dir_1 = tmp_path / "one"
119 test_dir_1.mkdir()
120 test_dir_2 = tmp_path / "two"
121 test_dir_2.mkdir()
122 test_file1 = test_dir_1 / "rst.rst"
123 test_file1.touch()
124 test_file2 = test_dir_2 / "rst.rst"
125 test_file2.touch()
126 file_list = [test_file1, test_file2]
127 init_config = config.RstcheckConfig()
128 _runner = runner.RstcheckMainRunner(file_list, init_config)
129
130 _runner.update_file_list() # act
131
132 assert _runner._files_to_check == file_list
133
134 @staticmethod
135 def test_non_rst_files(tmp_path: pathlib.Path) -> None:
136 """Test non rst files are filtered out."""
137 test_file1 = tmp_path / "rst.rst"
138 test_file1.touch()
139 test_file2 = tmp_path / "foo.bar"
140 test_file2.touch()
141 test_file3 = tmp_path / "rst.rst"
142 test_file3.touch()
143 file_list = [test_file1, test_file2, test_file3]
144 init_config = config.RstcheckConfig()
145 _runner = runner.RstcheckMainRunner(file_list, init_config)
146
147 _runner.update_file_list() # act
148
149 assert len(_runner._files_to_check) == 2
150
151 @staticmethod
152 def test_directory_without_recursive(tmp_path: pathlib.Path) -> None:
153 """Test directory without recusrive results in empty file list."""
154 test_file = tmp_path / "rst.rst"
155 test_file.touch()
156 file_list = [tmp_path]
157 init_config = config.RstcheckConfig()
158 _runner = runner.RstcheckMainRunner(file_list, init_config)
159
160 _runner.update_file_list() # act
161
162 assert not _runner._files_to_check
163
164 @staticmethod
165 def test_directory_with_recursive(tmp_path: pathlib.Path) -> None:
166 """Test directory with recusrive results in directories files in file list."""
167 test_file1 = tmp_path / "rst.rst"
168 test_file1.touch()
169 test_file2 = tmp_path / "rst2.rst"
170 test_file2.touch()
171 file_list = [tmp_path]
172 init_config = config.RstcheckConfig(recursive=True)
173 _runner = runner.RstcheckMainRunner(file_list, init_config)
174
175 _runner.update_file_list() # act
176
177 assert len(_runner._files_to_check) == 2
178 assert tmp_path / "rst.rst" in _runner._files_to_check
179 assert tmp_path / "rst2.rst" in _runner._files_to_check
180
181 @staticmethod
182 def test_dash_as_file() -> None:
183 """Test dash as file."""
184 file_list = [pathlib.Path("-")]
185 init_config = config.RstcheckConfig()
186 _runner = runner.RstcheckMainRunner(file_list, init_config)
187
188 _runner.update_file_list() # act
189
190 assert file_list == _runner._files_to_check
191
192 @staticmethod
193 def test_dash_as_file_with_others(tmp_path: pathlib.Path) -> None:
194 """Test dash as file with other files gets ignored."""
195 test_file = tmp_path / "rst.rst"
196 test_file.touch()
197 file_list = [pathlib.Path("-"), test_file]
198 init_config = config.RstcheckConfig()
199 _runner = runner.RstcheckMainRunner(file_list, init_config)
200
201 _runner.update_file_list() # act
202
203 assert len(_runner._files_to_check) == 1
204 assert test_file in _runner._files_to_check
205
206
207 class TestRstcheckMainRunnerFileListFilter:
208 """Test ``RstcheckMainRunner._filter_nonexisting`` method."""
209
210 @staticmethod
211 def test_empty_file_list() -> None:
212 """Test empty file list results in no changes."""
213 file_list: list[pathlib.Path] = []
214 init_config = config.RstcheckConfig()
215 _runner = runner.RstcheckMainRunner(file_list, init_config)
216
217 result = _runner._filter_nonexisting_paths(file_list)
218
219 assert not result
220 assert not _runner._nonexisting_paths
221
222 @staticmethod
223 def test_single_file_in_list(tmp_path: pathlib.Path) -> None:
224 """Test single file in list results in only this file in the list."""
225 test_file = tmp_path / "rst.rst"
226 test_file.touch()
227 file_list = [test_file]
228 init_config = config.RstcheckConfig()
229 _runner = runner.RstcheckMainRunner(file_list, init_config)
230
231 result = _runner._filter_nonexisting_paths(file_list)
232
233 assert result == file_list
234 assert not _runner._nonexisting_paths
235
236 @staticmethod
237 def test_multiple_files_in_list(tmp_path: pathlib.Path) -> None:
238 """Test multiple files in list results in only these files in the list."""
239 test_dir_1 = tmp_path / "one"
240 test_dir_1.mkdir()
241 test_dir_2 = tmp_path / "two"
242 test_dir_2.mkdir()
243 test_file1 = test_dir_1 / "rst.rst"
244 test_file1.touch()
245 test_file2 = test_dir_2 / "rst.rst"
246 test_file2.touch()
247 file_list = [test_file1, test_file2]
248 init_config = config.RstcheckConfig()
249 _runner = runner.RstcheckMainRunner(file_list, init_config)
250
251 result = _runner._filter_nonexisting_paths(file_list)
252
253 assert result == file_list
254 assert not _runner._nonexisting_paths
255
256 @staticmethod
257 def test_non_rst_files(tmp_path: pathlib.Path) -> None:
258 """Test non rst files are not filtered out."""
259 test_file1 = tmp_path / "rst.rst"
260 test_file1.touch()
261 test_file2 = tmp_path / "foo.bar"
262 test_file2.touch()
263 test_file3 = tmp_path / "rst.rst"
264 test_file3.touch()
265 file_list = [test_file1, test_file2, test_file3]
266 init_config = config.RstcheckConfig()
267 _runner = runner.RstcheckMainRunner(file_list, init_config)
268
269 result = _runner._filter_nonexisting_paths(file_list)
270
271 assert result == file_list
272 assert not _runner._nonexisting_paths
273
274 @staticmethod
275 def test_directory_without_recursive(tmp_path: pathlib.Path) -> None:
276 """Test directory without recusrive results in empty file list."""
277 test_file = tmp_path / "rst.rst"
278 test_file.touch()
279 file_list = [tmp_path]
280 init_config = config.RstcheckConfig()
281 _runner = runner.RstcheckMainRunner(file_list, init_config)
282
283 result = _runner._filter_nonexisting_paths(file_list)
284
285 assert not result
286 assert _runner._nonexisting_paths == file_list
287
288 @staticmethod
289 def test_directory_with_recursive(tmp_path: pathlib.Path) -> None:
290 """Test directory with recusrive results in directories files in file list."""
291 test_file1 = tmp_path / "rst.rst"
292 test_file1.touch()
293 test_file2 = tmp_path / "rst2.rst"
294 test_file2.touch()
295 file_list = [tmp_path]
296 init_config = config.RstcheckConfig(recursive=True)
297 _runner = runner.RstcheckMainRunner(file_list, init_config)
298
299 result = _runner._filter_nonexisting_paths(file_list)
300
301 assert result == file_list
302 assert not _runner._nonexisting_paths
303
304 @staticmethod
305 def test_dash_as_file() -> None:
306 """Test dash as file gets filtered out."""
307 file_list = [pathlib.Path("-")]
308 init_config = config.RstcheckConfig()
309 _runner = runner.RstcheckMainRunner(file_list, init_config)
310
311 result = _runner._filter_nonexisting_paths(file_list)
312
313 assert not result
314 assert _runner._nonexisting_paths == file_list
315
316
317 @pytest.mark.parametrize(
318 "lint_errors",
319 [[], [types.LintError(source_origin="<string>", line_number=0, message="message")]],
320 )
321 def test__run_checks_sync_method(
322 lint_errors: list[types.LintError], monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path
323 ) -> None:
324 """Test ``RstcheckMainRunner._run_checks_sync`` method.
325
326 Test results are returned.
327 """
328 monkeypatch.setattr(checker, "check_file", lambda _0, _1, _3: lint_errors)
329 test_file1 = tmp_path / "rst.rst"
330 test_file1.touch()
331 test_file2 = tmp_path / "rst2.rst"
332 test_file2.touch()
333 file_list = [test_file1, test_file2]
334 init_config = config.RstcheckConfig()
335 _runner = runner.RstcheckMainRunner(file_list, init_config)
336
337 result = _runner._run_checks_sync()
338
339 assert len(result) == 2
340 assert len(result[0]) == len(lint_errors)
341 assert len(result[1]) == len(lint_errors)
342
343
344 @pytest.mark.parametrize(
345 "lint_errors",
346 [[], [types.LintError(source_origin="<string>", line_number=0, message="message")]],
347 )
348 def test__run_checks_parallel_method(
349 lint_errors: list[types.LintError], monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path
350 ) -> None:
351 """Test ``RstcheckMainRunner._run_checks_parallel`` method.
352
353 Test results are returned.
354 The multiprocessing.Pool needs to be mocked, because it interferes with pytest-xdist.
355 """
356
357 class MockedPool:
358 """Mocked instance of ``multiprocessing.Pool``."""
359
360 @staticmethod
361 def starmap(_0, _1) -> list[list[types.LintError]]:
362 """Mock for ``multiprocessing.Pool.starmap`` method."""
363 return [lint_errors, lint_errors]
364
365 @contextlib.contextmanager
366 def mock_pool(_) -> t.Generator[MockedPool, None, None]:
367 """Mock context manager for ``multiprocessing.Pool``."""
368 yield MockedPool()
369
370 monkeypatch.setattr(multiprocessing, "Pool", mock_pool)
371 test_file1 = tmp_path / "rst.rst"
372 test_file1.touch()
373 test_file2 = tmp_path / "rst2.rst"
374 test_file2.touch()
375 file_list = [test_file1, test_file2]
376 init_config = config.RstcheckConfig()
377 _runner = runner.RstcheckMainRunner(file_list, init_config)
378
379 result = _runner._run_checks_parallel() # act
380
381 assert len(result) == 2
382 assert len(result[0]) == len(lint_errors)
383 assert len(result[1]) == len(lint_errors)
384
385
386 @pytest.mark.parametrize(
387 ("results", "error_count"),
388 [([], 0), ([[types.LintError(source_origin="<string>", line_number=0, message="message")]], 1)],
389 )
390 def test__update_results_method(results: list[list[types.LintError]], error_count: int) -> None:
391 """Test ``RstcheckMainRunner._update_results`` method.
392
393 Test results are set.
394 """
395 init_config = config.RstcheckConfig()
396 _runner = runner.RstcheckMainRunner([], init_config)
397
398 _runner._update_results(results) # act
399
400 assert len(_runner.errors) == error_count
401
402
403 def test_check_method_sync_with_1_file(mocker: pytest_mock.MockerFixture) -> None:
404 """Test ``RstcheckMainRunner.check`` method.
405
406 Test checks are run in sync for 1 file.
407 """
408 mocked_sync_runner = mocker.patch.object(runner.RstcheckMainRunner, "_run_checks_sync")
409 mocked_parallel_runner = mocker.patch.object(runner.RstcheckMainRunner, "_run_checks_parallel")
410 init_config = config.RstcheckConfig()
411 _runner = runner.RstcheckMainRunner([], init_config)
412 _runner._files_to_check = [pathlib.Path("file")]
413
414 _runner.check() # act
415
416 mocked_sync_runner.assert_called_once()
417 mocked_parallel_runner.assert_not_called()
418
419
420 def test_check_method_parallel_with_more_files(mocker: pytest_mock.MockerFixture) -> None:
421 """Test ``RstcheckMainRunner.check`` method.
422
423 Test checks are run in parallel for more file.
424 """
425 mocked_sync_runner = mocker.patch.object(runner.RstcheckMainRunner, "_run_checks_sync")
426 mocked_parallel_runner = mocker.patch.object(runner.RstcheckMainRunner, "_run_checks_parallel")
427 init_config = config.RstcheckConfig()
428 _runner = runner.RstcheckMainRunner([], init_config)
429 _runner._files_to_check = [pathlib.Path("file"), pathlib.Path("file2")]
430
431 _runner.check() # act
432
433 mocked_sync_runner.assert_not_called()
434 mocked_parallel_runner.assert_called_once()
435
436
437 class TestRstcheckMainRunnerResultPrinter:
438 """Test ``RstcheckMainRunner.get_result`` method."""
439
440 @staticmethod
441 def test_exit_code_on_success() -> None:
442 """Test exit code 0 is returned on no erros."""
443 init_config = config.RstcheckConfig()
444 _runner = runner.RstcheckMainRunner([], init_config)
445
446 result = _runner.print_result()
447
448 assert result == 0
449
450 @staticmethod
451 def test_success_message_on_success(capsys: pytest.CaptureFixture[str]) -> None:
452 """Test success message is printed to stdout by default if no errors."""
453 init_config = config.RstcheckConfig()
454 _runner = runner.RstcheckMainRunner([], init_config)
455
456 _runner.print_result() # act
457
458 assert "Success! No issues detected." in capsys.readouterr().out
459
460 @staticmethod
461 def test_error_message_on_error(
462 tmp_path: pathlib.Path, capsys: pytest.CaptureFixture[str]
463 ) -> None:
464 """Test error message is printed to stderr by default if errors are found."""
465 test_file = tmp_path / "nonexisting.rst"
466 init_config = config.RstcheckConfig()
467 _runner = runner.RstcheckMainRunner([test_file], init_config)
468
469 _runner.print_result() # act
470
471 assert "Error! Issues detected." in capsys.readouterr().err
472
473 @staticmethod
474 def test_success_message_print_to_file(tmp_path: pathlib.Path) -> None:
475 """Test success message is printed to given file."""
476 out_file = tmp_path / "outfile.txt"
477 out_file.touch()
478 init_config = config.RstcheckConfig()
479 _runner = runner.RstcheckMainRunner([], init_config)
480 # fmt: off
481 with Path(out_file).open(encoding="utf-8", mode="w") as out_file_handle:
482
483 _runner.print_result(output_file=out_file_handle) # act
484
485 # fmt: on
486 assert "Success! No issues detected." in out_file.read_text()
487
488 @staticmethod
489 def test_exit_code_on_error() -> None:
490 """Test exit code 1 is returned when erros were found."""
491 init_config = config.RstcheckConfig()
492 _runner = runner.RstcheckMainRunner([], init_config)
493 _runner.errors = [
494 types.LintError(source_origin="<string>", line_number=0, message="message")
495 ]
496
497 result = _runner.print_result()
498
499 assert result == 1
500
501 @staticmethod
502 def test_no_success_message_on_error(capsys: pytest.CaptureFixture[str]) -> None:
503 """Test no succuess message is printed when erros were found."""
504 init_config = config.RstcheckConfig()
505 _runner = runner.RstcheckMainRunner([], init_config)
506 _runner.errors = [
507 types.LintError(source_origin="<string>", line_number=0, message="message")
508 ]
509
510 _runner.print_result() # act
511
512 assert "Success! No issues detected." not in capsys.readouterr()
513
514 @staticmethod
515 def test_error_printed_to_stderr_by_default(capsys: pytest.CaptureFixture[str]) -> None:
516 """Test errors are printed to stderr."""
517 init_config = config.RstcheckConfig()
518 _runner = runner.RstcheckMainRunner([], init_config)
519 _runner._update_results(
520 [[types.LintError(source_origin="<string>", line_number=0, message="Some error.")]]
521 )
522
523 _runner.print_result() # act
524
525 assert "(ERROR/3) Some error" in capsys.readouterr().err
526
527 @staticmethod
528 def test_error_printed_to_file(tmp_path: pathlib.Path) -> None:
529 """Test errors are printed to stderr."""
530 out_file = tmp_path / "outfile.txt"
531 out_file.touch()
532 init_config = config.RstcheckConfig()
533 _runner = runner.RstcheckMainRunner([], init_config)
534 _runner._update_results(
535 [[types.LintError(source_origin="<string>", line_number=0, message="Some error.")]]
536 )
537 # fmt: off
538 with Path(out_file).open(encoding="utf-8", mode="w") as out_file_handle:
539
540 _runner.print_result(output_file=out_file_handle) # act
541
542 # fmt: on
543 assert "(ERROR/3) Some error" in out_file.read_text()
544
545 @staticmethod
546 def test_error_category_prepend(capsys: pytest.CaptureFixture[str]) -> None:
547 """Test ``(ERROR/3)`` is prepended when no category is present."""
548 init_config = config.RstcheckConfig()
549 _runner = runner.RstcheckMainRunner([], init_config)
550 _runner._update_results(
551 [[types.LintError(source_origin="<string>", line_number=0, message="Some error.")]]
552 )
553
554 _runner.print_result() # act
555
556 assert "(ERROR/3) Some error." in capsys.readouterr().err
557
558 @staticmethod
559 def test_error_message_format(capsys: pytest.CaptureFixture[str]) -> None:
560 """Test error message format."""
561 init_config = config.RstcheckConfig()
562 _runner = runner.RstcheckMainRunner([], init_config)
563 _runner._update_results(
564 [
565 [
566 types.LintError(
567 source_origin="<string>", line_number=0, message="(ERROR/3) Some error."
568 )
569 ]
570 ]
571 )
572
573 _runner.print_result() # act
574
575 assert "<string>:0: (ERROR/3) Some error." in capsys.readouterr().err