Debian Codegraph @

core/tests/checker_test.py

raw symbols SCIP
1 """Tests for ``checker`` module."""
2
3 from __future__ import annotations
4
5 import os
6 import pathlib
7 import re
8 import shlex
9 import sys
10 import typing as t
11 from inspect import isfunction
12
13 import docutils.io
14 import docutils.nodes
15 import docutils.utils
16 import pytest
17
18 from rstcheck_core import _extras, _sphinx, checker, config, types
19
20 if t.TYPE_CHECKING:
21 import pytest_mock
22
23
24 def test_check_file(monkeypatch: pytest.MonkeyPatch) -> None:
25 """Test ``check_file`` returns accumulated errors from ``check_source``."""
26 errors = [
27 types.LintError(source_origin="<string>", line_number=0, message=""),
28 types.LintError(source_origin="<string>", line_number=1, message=""),
29 ]
30 monkeypatch.setattr(checker, "_get_source", lambda _: "source")
31 monkeypatch.setattr(
32 checker,
33 "check_source",
34 lambda _, source_file, ignores, report_level, warn_unknown_settings: (e for e in errors),
35 )
36 test_config = config.RstcheckConfig(config_path=pathlib.Path())
37
38 result = checker.check_file(pathlib.Path(), test_config)
39
40 assert result == errors
41
42
43 class TestRunConfigLoader:
44 """Test ``_load_run_config`` function."""
45
46 @staticmethod
47 def test_global_config_path_set() -> None:
48 """Test config path is set in main config.
49
50 This results in no change -> return of main config.
51 """
52 test_config = config.RstcheckConfig(config_path=pathlib.Path())
53
54 result = checker._load_run_config(pathlib.Path(), test_config)
55
56 assert result == test_config
57
58 @staticmethod
59 def test_no_config_file_in_dir_tree(monkeypatch: pytest.MonkeyPatch) -> None:
60 """Test config path is unset in main config and file dir tree has no config file.
61
62 This results in no change -> return of main config.
63 """
64 monkeypatch.setattr(config, "load_config_file_from_dir_tree", lambda _: None)
65 test_config = config.RstcheckConfig()
66
67 result = checker._load_run_config(pathlib.Path(), test_config)
68
69 assert result == test_config
70
71 @staticmethod
72 def test_config_file_in_dir_tree(monkeypatch: pytest.MonkeyPatch) -> None:
73 """Test config path is unset in main config and file dir tree has a config file.
74
75 This results in merge of configs -> return merged config.
76 """
77 test_file_config = config.RstcheckConfigFile(report_level=config.ReportLevel.SEVERE)
78 monkeypatch.setattr(config, "load_config_file_from_dir_tree", lambda _: test_file_config)
79 test_config = config.RstcheckConfig()
80
81 result = checker._load_run_config(pathlib.Path(), test_config, overwrite_config=True)
82
83 assert result is not None
84 assert test_config != config.ReportLevel.SEVERE
85 assert result.report_level == config.ReportLevel.SEVERE
86
87
88 class TestSourceGetter:
89 """Test ``_get_source`` function."""
90
91 @staticmethod
92 def test_file_name_is_dash(monkeypatch: pytest.MonkeyPatch) -> None:
93 """Test when file name is a dash, stdin is read."""
94 source = "Teststring"
95 monkeypatch.setattr(sys.stdin, "read", lambda: source)
96 test_file = pathlib.Path("-")
97
98 result = checker._get_source(test_file)
99
100 assert result == source
101
102 @staticmethod
103 def test_file_name_is_not_dash(tmp_path: pathlib.Path) -> None:
104 """Test when file name is not a dash, the file is read."""
105 source = """
106 Test
107 ====
108 """
109 test_file = tmp_path / "testfile.rst"
110 test_file.write_text(source)
111
112 result = checker._get_source(test_file)
113
114 assert result == source
115
116
117 def test__replace_ignored_substitutions() -> None:
118 """Test ``_replace_ignored_substitutions`` fucntion replaces substitutions."""
119 source = "|Substitution1| |Substitution2|"
120
121 result = checker._replace_ignored_substitutions(source, ["Substitution1"])
122
123 assert result == "xSubstitution1x |Substitution2|"
124
125
126 def test__create_ignore_dict_from_config() -> None:
127 """Test ``_create_ignore_dict_from_config`` fucntion creates ignore dict."""
128 ignore_messages = r"foo/bar"
129 ignore_messages_re = re.compile(ignore_messages)
130 ignore_languages = ["python", "cpp"]
131 ignore_directives = ["code"]
132 ignore_roles = ["role"]
133 ignore_substitutions = ["substi"]
134 test_config = config.RstcheckConfig(
135 ignore_messages=ignore_messages,
136 ignore_languages=ignore_languages,
137 ignore_directives=ignore_directives,
138 ignore_roles=ignore_roles,
139 ignore_substitutions=ignore_substitutions,
140 )
141
142 result = checker._create_ignore_dict_from_config(
143 test_config,
144 )
145
146 assert result == types.construct_ignore_dict(
147 messages=ignore_messages_re,
148 languages=ignore_languages,
149 directives=ignore_directives,
150 roles=ignore_roles,
151 substitutions=ignore_substitutions,
152 )
153
154
155 class TestSourceChecker:
156 """Test ``check_source`` fucntion."""
157
158 @staticmethod
159 def test_empty_source() -> None:
160 """Test empty source generates no errors."""
161 source = ""
162
163 result = list(checker.check_source(source))
164
165 assert not result
166
167 @staticmethod
168 def test_lint_error_no_source_file() -> None:
169 """Test lint error holds "<string>" if no source file is passed."""
170 source = """
171 Test
172 ===
173 """
174
175 result = list(checker.check_source(source))
176
177 assert len(result) == 1
178 assert result[0]["source_origin"] == "<string>"
179
180 @staticmethod
181 def test_lint_error_with_source_file() -> None:
182 """Test lint error holds source file."""
183 test_file = pathlib.Path("test_file.rst")
184 source = """
185 Test
186 ===
187 """
188
189 result = list(checker.check_source(source, test_file))
190
191 assert len(result) == 1
192 assert result[0]["source_origin"] == test_file
193
194 @staticmethod
195 def test_lint_error_returned_on_default_ignore() -> None:
196 """Test lint error is returned with default ignores."""
197 source = """
198 Test
199 ===
200 """
201
202 result = list(checker.check_source(source))
203
204 assert len(result) == 1
205 assert "Possible title underline, too short for the title" in result[0]["message"]
206
207 @staticmethod
208 def test_lint_error_skipped_on_set_ignore() -> None:
209 """Test lint error is skipped with set ignores."""
210 source = """
211 Test
212 ===
213 """
214 ignores = types.construct_ignore_dict(
215 messages=re.compile(r"Possible title underline, too short for the title")
216 )
217
218 result = list(checker.check_source(source, ignores=ignores))
219
220 assert not result
221
222 @staticmethod
223 @pytest.mark.skipif(_extras.SPHINX_INSTALLED, reason="Test without sphinx extra.")
224 def test_sphinx_directive_errors_without_sphinx() -> None:
225 """Test error on sphinx directive when sphinx is missing."""
226 source = """
227 .. py:function:: foo
228 """
229
230 result = list(checker.check_source(source))
231
232 assert len(result) > 0
233 assert 'No directive entry for "py:function"' in result[0]["message"]
234
235 @staticmethod
236 @pytest.mark.skipif(not _extras.SPHINX_INSTALLED, reason="Depends on sphinx extra.")
237 def test_sphinx_directive_does_not_error_with_sphinx() -> None:
238 """Test no error on sphinx directive when sphinx is installed."""
239 source = """
240 .. py:function:: foo
241 """
242
243 result = list(checker.check_source(source))
244
245 assert not result
246
247 @staticmethod
248 @pytest.mark.skipif(sys.version_info[0:2] > (3, 9), reason="Requires python3.9 or lower")
249 def test_code_block_lint_error_returned_on_default_ignore_pre310() -> None:
250 """Test code lint error is returned with default ignores.
251
252 In Python version 3.10 the error messag changed.
253 """
254 source = """
255 .. code:: python
256
257 print(
258 """
259
260 result = list(checker.check_source(source))
261
262 assert len(result) == 1
263 assert "unexpected EOF while parsing" in result[0]["message"]
264
265 @staticmethod
266 @pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires python3.10 or higher")
267 def test_code_block_lint_error_returned_on_default_ignore() -> None:
268 """Test code lint error is returned with default ignores."""
269 source = """
270 .. code:: python
271
272 print(
273 """
274
275 result = list(checker.check_source(source))
276
277 assert len(result) == 1
278 assert "'(' was never closed" in result[0]["message"]
279
280 @staticmethod
281 @pytest.mark.skipif(sys.version_info[0:2] > (3, 9), reason="Requires python3.9 or lower")
282 def test_code_block_no_error_on_set_ignore_pre310() -> None:
283 """Test code lint error is skipped with set ignores.
284
285 In Python version 3.10 the error messag changed.
286 """
287 source = """
288 .. code:: python
289
290 print(
291 """
292 ignores = types.construct_ignore_dict(messages=re.compile(r"unexpected EOF while parsing"))
293
294 result = list(checker.check_source(source, ignores=ignores))
295
296 assert not result
297
298 @staticmethod
299 @pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires python3.10 or higher")
300 def test_code_block_no_error_on_set_ignore() -> None:
301 """Test code lint error is skipped with set ignores."""
302 source = """
303 .. code:: python
304
305 print(
306 """
307 ignores = types.construct_ignore_dict(messages=re.compile(r"'\(' was never closed"))
308
309 result = list(checker.check_source(source, ignores=ignores))
310
311 assert not result
312
313 @staticmethod
314 def test_stdin_message() -> None:
315 """Test code lint error message for stdin."""
316 source = """
317 .. code:: python
318
319 print(
320 """
321 ignores = types.construct_ignore_dict()
322
323 result = list(checker.check_source(source, source_file=pathlib.Path("-"), ignores=ignores))
324
325 assert len(result) == 1
326 assert result[0]["source_origin"] == "<stdin>"
327
328 @staticmethod
329 @pytest.mark.skipif(_extras.SPHINX_INSTALLED, reason="Test without sphinx extra.")
330 @pytest.mark.skipif(sys.version_info[0:2] > (3, 9), reason="Requires python3.9 or lower")
331 @pytest.mark.parametrize("code_block_directive", ["code", "code-block", "sourcecode"])
332 def test_code_block_without_language_works_without_sphinx_pre310(
333 code_block_directive: str,
334 ) -> None:
335 """Test code blocks without a language are not checked and do not error without sphinx."""
336 source = f"""
337 .. {code_block_directive}::
338
339 print(
340
341 .. {code_block_directive}:: python
342
343 print(
344 """
345 ignores = types.construct_ignore_dict()
346
347 result = list(checker.check_source(source, ignores=ignores))
348
349 assert len(result) == 1
350 assert result[0]["line_number"] == 8
351 assert "unexpected EOF while parsing" in result[0]["message"]
352
353 @staticmethod
354 @pytest.mark.skipif(_extras.SPHINX_INSTALLED, reason="Test without sphinx extra.")
355 @pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires python3.10 or higher")
356 @pytest.mark.parametrize("code_block_directive", ["code", "code-block", "sourcecode"])
357 def test_code_block_without_language_works_without_sphinx(
358 code_block_directive: str,
359 ) -> None:
360 """Test code blocks without a language are not checked and do not error without sphinx."""
361 source = f"""
362 .. {code_block_directive}::
363
364 print(
365
366 .. {code_block_directive}:: python
367
368 print(
369 """
370 ignores = types.construct_ignore_dict()
371
372 result = list(checker.check_source(source, ignores=ignores))
373
374 assert len(result) == 1
375 assert result[0]["line_number"] == 8
376 assert "'(' was never closed" in result[0]["message"]
377
378 @staticmethod
379 @pytest.mark.skipif(not _extras.SPHINX_INSTALLED, reason="Depends on sphinx extra.")
380 @pytest.mark.skipif(sys.version_info[0:2] > (3, 9), reason="Requires python3.9 or lower")
381 @pytest.mark.xfail(
382 reason="Sphinx support fails for language-less code blocks. See #3", strict=True
383 )
384 @pytest.mark.parametrize("code_block_directive", ["code", "code-block", "sourcecode"])
385 def test_code_block_without_language_is_works_with_sphinx_pre310(
386 code_block_directive: str,
387 ) -> None:
388 """Test code blocks without a language are working and do not error with sphinx."""
389 source = f"""
390 .. {code_block_directive}::
391
392 print(
393
394 .. {code_block_directive}:: python
395
396 print(
397 """
398 ignores = types.construct_ignore_dict()
399 # fmt: off
400 with _sphinx.load_sphinx_if_available():
401
402 result = list(checker.check_source(source, ignores=ignores))
403
404 # fmt: on
405 assert len(result) == 1
406 assert result[0]["line_number"] == 9
407 assert "unexpected EOF while parsing" in result[0]["message"]
408
409 @staticmethod
410 @pytest.mark.skipif(not _extras.SPHINX_INSTALLED, reason="Depends on sphinx extra.")
411 @pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires python3.10 or higher")
412 @pytest.mark.xfail(
413 reason="Sphinx support fails for language-less code blocks. See #3", strict=True
414 )
415 @pytest.mark.parametrize("code_block_directive", ["code", "code-block", "sourcecode"])
416 def test_code_block_without_language_is_works_with_sphinx(
417 code_block_directive: str,
418 ) -> None:
419 """Test code blocks without a language are working and do not error with sphinx."""
420 source = f"""
421 .. {code_block_directive}::
422
423 print(
424
425 .. {code_block_directive}:: python
426
427 print(
428 """
429 ignores = types.construct_ignore_dict()
430 # fmt: off
431 with _sphinx.load_sphinx_if_available():
432
433 result = list(checker.check_source(source, ignores=ignores))
434
435 # fmt: on
436 assert len(result) == 1
437 assert result[0]["line_number"] == 9
438 assert "'(' was never closed" in result[0]["message"]
439
440 @staticmethod
441 @pytest.mark.skipif(_extras.SPHINX_INSTALLED, reason="Test without sphinx extra.")
442 @pytest.mark.parametrize("code_block_directive", ["code", "code-block", "sourcecode"])
443 def test_code_block_without_language_logs_nothing_without_sphinx(
444 code_block_directive: str,
445 caplog: pytest.LogCaptureFixture,
446 ) -> None:
447 """Test code blocks without a language log nothing and do not error without sphinx.
448
449 Conter part to the XFAIL tests ``test_code_block_without_language_is_works_with_sphinx``.
450 """
451 source = f"""
452 .. {code_block_directive}::
453
454 print(
455
456 .. {code_block_directive}:: python
457
458 print(
459 """
460 ignores = types.construct_ignore_dict()
461 # fmt: off
462 with _sphinx.load_sphinx_if_available():
463
464 result = list(checker.check_source(source, ignores=ignores))
465
466 # fmt: on
467 assert result
468 assert "An `AttributeError` error occured" not in caplog.text
469 assert (
470 "directive (code/code-block/sourcecode) without a specified language" not in caplog.text
471 )
472
473 @staticmethod
474 @pytest.mark.skipif(not _extras.SPHINX_INSTALLED, reason="Depends on sphinx extra.")
475 @pytest.mark.parametrize("code_block_directive", ["code", "code-block", "sourcecode"])
476 def test_code_block_without_language_logs_critcal_with_sphinx(
477 code_block_directive: str,
478 caplog: pytest.LogCaptureFixture,
479 ) -> None:
480 """Test code blocks without a language log critical and do not error with sphinx.
481
482 Conter part to the XFAIL tests ``test_code_block_without_language_is_works_with_sphinx``.
483 """
484 source = f"""
485 .. {code_block_directive}::
486
487 print(
488
489 .. {code_block_directive}:: python
490
491 print(
492 """
493 ignores = types.construct_ignore_dict()
494 # fmt: off
495 with _sphinx.load_sphinx_if_available():
496
497 result = list(checker.check_source(source, ignores=ignores))
498
499 # fmt: on
500 assert not result
501 assert "An `AttributeError` error occured" in caplog.text
502 assert "directive (code/code-block/sourcecode) without a specified language" in caplog.text
503
504
505 class TestCodeCheckRunner:
506 """Test ``_run_code_checker_and_filter_errors`` function."""
507
508 @staticmethod
509 def test_without_ignore() -> None:
510 """Test both checkers return error without ignore."""
511 cb_checker = checker.CodeBlockChecker("<string>")
512 checker_list = [
513 cb_checker.create_checker("print(", "python"),
514 cb_checker.create_checker("{", "json"),
515 ]
516
517 result = list(checker._run_code_checker_and_filter_errors(checker_list, None))
518
519 assert len(result) == 2
520
521 @staticmethod
522 def test_with_ignore() -> None:
523 """Test only one checker return error with ignore."""
524 cb_checker = checker.CodeBlockChecker("<string>")
525 checker_list = [
526 cb_checker.create_checker("print(", "python"),
527 cb_checker.create_checker("{", "json"),
528 ]
529 ignore_messages = re.compile(r"Expecting property name enclosed in double quotes")
530
531 result = list(checker._run_code_checker_and_filter_errors(checker_list, ignore_messages))
532
533 assert len(result) == 1
534
535
536 class TestRstErrorParseFilter:
537 """Test ``_parse_and_filter_rst_errors`` function."""
538
539 @staticmethod
540 def test_without_ignore() -> None:
541 """Test both error messages are parsed and returned."""
542 error_str = "<string>:1:1: Error message 1\n<string>:1:2: Error message 2"
543
544 result = list(checker._parse_and_filter_rst_errors(error_str, "<string>", None))
545
546 assert len(result) == 2
547
548 @staticmethod
549 def test_with_ignore() -> None:
550 """Test only one error message is parsed and returned."""
551 error_str = "<string>:1:1: Error message 1\n<string>:1:2: Error message 2"
552 ignore_messages = re.compile(r"Error message 1")
553
554 result = list(checker._parse_and_filter_rst_errors(error_str, "<string>", ignore_messages))
555
556 assert len(result) == 1
557
558
559 class TestCheckTranslator:
560 """Test ``_CheckTranslator`` class."""
561
562 @staticmethod
563 def test_no_checkers_on_init() -> None:
564 """Test checkers are empty on init."""
565 doc = docutils.utils.new_document("")
566
567 result = checker._CheckTranslator(doc, "", "<string>")
568
569 assert not result.checkers
570
571
572 class TestCodeBlockChecker:
573 """Test ``CodeBlockChecker`` class."""
574
575 @staticmethod
576 def test_init() -> None:
577 """Test nothing special happens on ``__init__`` method."""
578 source_origin: types.SourceFileOrString = "<string>"
579
580 result = checker.CodeBlockChecker(source_origin)
581
582 assert result.source_origin == source_origin
583 assert result.ignores is None
584 assert result.report_level == config.ReportLevel.INFO
585
586 @staticmethod
587 def test_language_is_supported_on_supported_lang() -> None:
588 """Test ``language_is_supported`` method returns ``True`` for supported language."""
589 cb_checker = checker.CodeBlockChecker("<string>")
590
591 result = cb_checker.language_is_supported("python")
592
593 assert result is True
594
595 @staticmethod
596 def test_language_is_supported_on_unsupported_lang() -> None:
597 """Test ``language_is_supported`` method returns ``False`` for unsupported language."""
598 cb_checker = checker.CodeBlockChecker("<string>")
599
600 result = cb_checker.language_is_supported("some-unsupported-lang")
601
602 assert result is False
603
604 @staticmethod
605 def test_create_checker_returns_function() -> None:
606 """Test ``create_checker`` method returns a lambda function.
607
608 Currently unknown how to test if lambda body is ``self.check``.
609 """
610 cb_checker = checker.CodeBlockChecker("<string>")
611
612 result = cb_checker.create_checker("", "")
613
614 assert isfunction(result)
615 assert result.__name__ == "<lambda>"
616
617 @staticmethod
618 def test_check_returns_none_on_unsupported_lang() -> None:
619 """Test ``check`` returns ``None`` on unsupported language."""
620 cb_checker = checker.CodeBlockChecker("<string>")
621
622 result = list(cb_checker.check("", "some-unsupported-lang"))
623
624 assert not result
625
626 @staticmethod
627 def test_check_returns_none_on_ok_code_block_for_supported_lang() -> None:
628 """Test ``check`` returns ``None`` on ok code block for supported language."""
629 source = """
630 print("rstcheck")
631 """
632 cb_checker = checker.CodeBlockChecker("<string>")
633
634 result = list(cb_checker.check(source, "python"))
635
636 assert not result
637
638 @staticmethod
639 @pytest.mark.skipif(sys.version_info[0:2] > (3, 9), reason="Requires python3.9 or lower")
640 def test_check_returns_error_on_bad_code_block_for_supported_lang_pre310() -> None:
641 """Test ``check`` returns error on bad code block for supported language.
642
643 In Python version 3.10 the error messag changed.
644 """
645 source = """
646 print(
647 """
648 cb_checker = checker.CodeBlockChecker("<string>")
649
650 result = list(cb_checker.check(source, "python"))
651
652 assert len(result) == 1
653 assert "unexpected EOF while parsing" in result[0]["message"]
654
655 @staticmethod
656 @pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires python3.10 or higher")
657 def test_check_returns_error_on_bad_code_block_for_supported_lang() -> None:
658 """Test ``check`` returns error on bad code block for supported language."""
659 source = """
660 print(
661 """
662 cb_checker = checker.CodeBlockChecker("<string>")
663
664 result = list(cb_checker.check(source, "python"))
665
666 assert len(result) == 1
667 assert "'(' was never closed" in result[0]["message"]
668
669 @staticmethod
670 def test_check_python_returns_none_on_ok_code_block() -> None:
671 """Test ``check_python`` returns ``None`` on ok code block."""
672 source = """
673 print("rstcheck")
674 """
675 cb_checker = checker.CodeBlockChecker("<string>")
676
677 result = list(cb_checker.check_python(source))
678
679 assert not result
680
681 @staticmethod
682 @pytest.mark.skipif(sys.version_info[0:2] > (3, 9), reason="Requires python3.9 or lower")
683 def test_check_python_returns_error_on_bad_code_block_pre310() -> None:
684 """Test ``check_python`` returns error on bad code block.
685
686 In Python version 3.10 the error messag changed.
687 """
688 source = """
689 print(
690 """
691 cb_checker = checker.CodeBlockChecker("<string>")
692
693 result = list(cb_checker.check_python(source))
694
695 assert len(result) == 1
696 assert "unexpected EOF while parsing" in result[0]["message"]
697
698 @staticmethod
699 @pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires python3.10 or higher")
700 def test_check_python_returns_error_on_bad_code_block() -> None:
701 """Test ``check_python`` returns error on bad code block."""
702 source = """
703 print(
704 """
705 cb_checker = checker.CodeBlockChecker("<string>")
706
707 result = list(cb_checker.check_python(source))
708
709 assert len(result) == 1
710 assert "'(' was never closed" in result[0]["message"]
711
712 @staticmethod
713 @pytest.mark.skipif(sys.version_info[0:2] > (3, 11), reason="Requires python3.11 or lower")
714 def test_check_python_returns_no_error_on_syntax_warning_pre312() -> None:
715 """Test ``check_python`` returns no error on SyntaxWarning.
716
717 With python 3.8 a SyntaxWarning is logged for '"is" with literals'.
718
719 Context: https://github.com/rstcheck/rstcheck/issues/122
720 """
721 source = """
722 if mystring is "ok":
723 ...
724 """
725 cb_checker = checker.CodeBlockChecker("<string>")
726
727 result = list(cb_checker.check_python(source))
728
729 assert len(result) == 1
730 assert '"is" with a literal' in result[0]["message"]
731
732 @staticmethod
733 @pytest.mark.skipif(sys.version_info < (3, 12), reason="Requires python3.12 or higher")
734 def test_check_python_returns_error_on_syntax_warning() -> None:
735 """Test ``check_python`` returns error on SyntaxWarning.
736
737 With python 3.8 a SyntaxWarning is logged for '"is" with literals'.
738
739 Context: https://github.com/rstcheck/rstcheck/issues/122
740 """
741 source = """
742 if mystring is "ok":
743 ...
744 """
745 cb_checker = checker.CodeBlockChecker("<string>")
746
747 result = list(cb_checker.check_python(source))
748
749 assert len(result) == 1
750 assert "\"is\" with 'str' literal" in result[0]["message"]
751
752 @staticmethod
753 def test_check_json_returns_none_on_ok_code_block() -> None:
754 """Test ``check_json`` returns ``None`` on ok code block."""
755 source = """
756 {
757 "key": "value"
758 }
759 """
760 cb_checker = checker.CodeBlockChecker("<string>")
761
762 result = list(cb_checker.check_json(source))
763
764 assert not result
765
766 @staticmethod
767 def test_check_json_returns_error_on_bad_code_block() -> None:
768 """Test ``check_json`` returns error on bad code block."""
769 source = """
770 {
771 "key":
772 }
773 """
774 cb_checker = checker.CodeBlockChecker("<string>")
775
776 result = list(cb_checker.check_json(source))
777
778 assert len(result) == 1
779 assert "Expecting value:" in result[0]["message"]
780
781 @staticmethod
782 @pytest.mark.skipif(checker.yaml_imported is False, reason="Requires pyyaml to be installed")
783 def test_check_yaml_returns_none_on_ok_code_block_no_pyyaml(
784 mocker: pytest_mock.MockerFixture,
785 ) -> None:
786 """Test ``check_json`` returns ``None`` on ok code block."""
787 source = """
788 spam: ham
789 eggs: ham
790 """
791 mocker.patch.object(checker, "yaml_imported", False) # noqa: FBT003
792 cb_checker = checker.CodeBlockChecker("<string>")
793
794 result = list(cb_checker.check_yaml(source))
795
796 assert not result
797
798 @staticmethod
799 @pytest.mark.skipif(checker.yaml_imported is False, reason="Requires pyyaml to be installed")
800 def test_check_yaml_returns_ok_on_bad_code_block_no_pyyaml(
801 mocker: pytest_mock.MockerFixture,
802 ) -> None:
803 """Test ``check_json`` returns error on bad code block."""
804 source = """
805 spam: ham
806 eggs: ham
807 """
808 mocker.patch.object(checker, "yaml_imported", False) # noqa: FBT003
809 cb_checker = checker.CodeBlockChecker("<string>")
810
811 result = list(cb_checker.check_yaml(source))
812
813 assert not result
814
815 @staticmethod
816 @pytest.mark.skipif(checker.yaml_imported is False, reason="Requires pyyaml to be installed")
817 def test_check_yaml_returns_none_on_ok_code_block() -> None:
818 """Test ``check_json`` returns ``None`` on ok code block."""
819 source = """
820 spam: ham
821 eggs: ham
822 """
823 cb_checker = checker.CodeBlockChecker("<string>")
824
825 result = list(cb_checker.check_yaml(source))
826
827 assert not result
828
829 @staticmethod
830 @pytest.mark.skipif(checker.yaml_imported is False, reason="Requires pyyaml to be installed")
831 def test_check_yaml_returns_error_on_bad_code_block() -> None:
832 """Test ``check_json`` returns error on bad code block."""
833 source = """
834 spam: ham
835 eggs: ham
836 """
837 cb_checker = checker.CodeBlockChecker("<string>")
838
839 result = list(cb_checker.check_yaml(source))
840
841 assert len(result) == 1
842 assert "mapping values are not allowed here" in result[0]["message"]
843
844 @staticmethod
845 def test_check_xml_returns_none_on_ok_code_block() -> None:
846 """Test ``check_xml`` returns ``None`` on ok code block."""
847 source = """<?xml version="1.0" encoding="UTF-8"?>
848 <note>
849 <heading>Reminder</heading>
850 </note>
851 """
852 cb_checker = checker.CodeBlockChecker("<string>")
853
854 result = list(cb_checker.check_xml(source))
855
856 assert not result
857
858 @staticmethod
859 def test_check_xml_returns_error_on_bad_code_block() -> None:
860 """Test ``check_xml`` returns error on bad code block."""
861 source = """<?xml version="1.0" encoding="UTF-8"?>
862 <note>
863 <heading>Reminder
864 </note>
865 """
866 cb_checker = checker.CodeBlockChecker("<string>")
867
868 result = list(cb_checker.check_xml(source))
869
870 assert len(result) == 1
871 assert "mismatched tag:" in result[0]["message"]
872
873 @staticmethod
874 def test_check_rst_returns_none_on_ok_code_block() -> None:
875 """Test ``check_rst`` returns ``None`` on ok code block."""
876 source = """
877 Heading
878 =======
879 """
880 cb_checker = checker.CodeBlockChecker("<string>")
881
882 result = list(cb_checker.check_rst(source))
883
884 assert not result
885
886 @staticmethod
887 def test_check_rst_returns_error_on_bad_code_block() -> None:
888 """Test ``check_rst`` returns error on bad code block."""
889 source = """
890 Heading
891 ======
892 """
893 cb_checker = checker.CodeBlockChecker("<string>")
894
895 result = list(cb_checker.check_rst(source))
896
897 assert len(result) == 1
898 assert "Title underline too short." in result[0]["message"]
899
900 @staticmethod
901 def test_check_doctest_returns_none_on_ok_code_block() -> None:
902 """Test ``check_doctest`` returns ``None`` on ok code block."""
903 source = """
904 >>> x = 1
905 >>> x
906 1
907 """
908 cb_checker = checker.CodeBlockChecker("<string>")
909
910 result = list(cb_checker.check_doctest(source))
911
912 assert not result
913
914 @staticmethod
915 def test_check_doctest_returns_error_on_bad_code_block() -> None:
916 """Test ``check_doctest`` returns error on bad code block."""
917 source = """
918 >>> x = 1
919 >>>> x
920 1
921 """
922 cb_checker = checker.CodeBlockChecker("<string>")
923
924 result = list(cb_checker.check_doctest(source))
925
926 assert len(result) == 1
927 assert "lacks blank after >>>: '>>>> x'" in result[0]["message"]
928
929 @staticmethod
930 def test_check_doctest_returns_none_on_bad_code_block_if_regex_no_matching(
931 monkeypatch: pytest.MonkeyPatch,
932 ) -> None:
933 """Test ``check_doctest`` returns ``None`` on bad code block if regex is not matching."""
934 monkeypatch.setattr(checker, "DOCTEST_LINE_NO_REGEX", re.compile("bad-regex"))
935 source = """
936 >>> x = 1
937 >>>> x
938 1
939 """
940 cb_checker = checker.CodeBlockChecker("<string>")
941
942 result = list(cb_checker.check_doctest(source))
943
944 assert not result
945
946 @staticmethod
947 def test_check_bash_returns_none_on_ok_code_block() -> None:
948 """Test ``check_bash`` returns ``None`` on ok code block."""
949 source = """
950 if [ "$x" == 'y' ]
951 then
952 exit 1
953 fi
954 """
955 cb_checker = checker.CodeBlockChecker("<string>")
956
957 result = list(cb_checker.check_bash(source))
958
959 assert not result
960
961 @staticmethod
962 @pytest.mark.skipif(
963 sys.platform == "win32",
964 reason="Unknown Windows specific wrong positiv. `list index out of range`",
965 )
966 def test_check_bash_returns_error_on_bad_code_block() -> None:
967 """Test ``check_bash`` returns error on bad code block."""
968 source = """
969 {
970 """
971 cb_checker = checker.CodeBlockChecker("<string>")
972
973 result = list(cb_checker.check_bash(source))
974
975 assert len(result) == 1
976 assert "syntax error: unexpected end of file" in result[0]["message"]
977
978 @staticmethod
979 def test_check_c_returns_none_on_ok_code_block() -> None:
980 """Test ``check_c`` returns ``None`` on ok code block."""
981 source = """
982 float foo(int n)
983 {
984 // Test C99.
985 float x[n];
986 x[0] = 1;
987 return x[0];
988 }
989 """
990 cb_checker = checker.CodeBlockChecker("<string>")
991
992 result = list(cb_checker.check_c(source))
993
994 assert not result
995
996 @staticmethod
997 @pytest.mark.skipif(sys.platform != "linux", reason="Linux specific error message")
998 def test_check_c_returns_error_on_bad_code_block_linux() -> None:
999 """Test ``check_c`` returns error on bad code block."""
1000 source = """
1001 int main()
1002 {
1003 return x;
1004 }
1005 """
1006 cb_checker = checker.CodeBlockChecker("<string>")
1007
1008 result = list(cb_checker.check_c(source))
1009
1010 assert len(result) > 0
1011 assert (
1012 "error: \u2018x\u2019 undeclared (first use in this function)" in result[0]["message"]
1013 )
1014
1015 @staticmethod
1016 @pytest.mark.skipif(sys.platform != "darwin", reason="MacOS specific error message")
1017 def test_check_c_returns_error_on_bad_code_block_macos() -> None:
1018 """Test ``check_c`` returns error on bad code block."""
1019 source = """
1020 int main()
1021 {
1022 return x;
1023 }
1024 """
1025 cb_checker = checker.CodeBlockChecker("<string>")
1026
1027 result = list(cb_checker.check_c(source))
1028
1029 assert len(result) > 0
1030 assert "error: use of undeclared identifier 'x'" in result[0]["message"]
1031
1032 @staticmethod
1033 @pytest.mark.skipif(sys.platform != "win32", reason="Windows specific error message")
1034 def test_check_c_returns_error_on_bad_code_block_windows() -> None:
1035 """Test ``check_c`` returns error on bad code block."""
1036 source = """
1037 int main()
1038 {
1039 return x;
1040 }
1041 """
1042 cb_checker = checker.CodeBlockChecker("<string>")
1043
1044 result = list(cb_checker.check_c(source))
1045
1046 assert len(result) > 0
1047 assert "error: 'x' undeclared (first use in this function)" in result[0]["message"]
1048
1049 @staticmethod
1050 def test_check_cpp_returns_none_on_ok_code_block() -> None:
1051 """Test ``check_cpp`` returns ``None`` on ok code block."""
1052 source = """
1053 #include <iostream>
1054
1055 int main()
1056 {
1057 auto x = 1;
1058 return x;
1059 }
1060 """
1061 cb_checker = checker.CodeBlockChecker("<string>")
1062
1063 result = list(cb_checker.check_cpp(source))
1064
1065 assert not result
1066
1067 @staticmethod
1068 @pytest.mark.skipif(sys.platform != "linux", reason="Linux specific error message")
1069 def test_check_cpp_returns_error_on_bad_code_block_linux() -> None:
1070 """Test ``check_cpp`` returns error on bad code block."""
1071 source = """
1072 int main()
1073 {
1074 return x;
1075 }
1076 """
1077 cb_checker = checker.CodeBlockChecker("<string>")
1078
1079 result = list(cb_checker.check_cpp(source))
1080
1081 assert len(result) == 1
1082 assert "error: \u2018x\u2019 was not declared in this scope" in result[0]["message"]
1083
1084 @staticmethod
1085 @pytest.mark.skipif(sys.platform != "darwin", reason="MacOS specific error message")
1086 def test_check_cpp_returns_error_on_bad_code_block_macos() -> None:
1087 """Test ``check_cpp`` returns error on bad code block."""
1088 source = """
1089 int main()
1090 {
1091 return x;
1092 }
1093 """
1094 cb_checker = checker.CodeBlockChecker("<string>")
1095
1096 result = list(cb_checker.check_cpp(source))
1097
1098 assert len(result) == 1
1099 assert "error: use of undeclared identifier 'x'" in result[0]["message"]
1100
1101 @staticmethod
1102 @pytest.mark.skipif(sys.platform != "win32", reason="Windows specific error message")
1103 def test_check_cpp_returns_error_on_bad_code_block_windows() -> None:
1104 """Test ``check_cpp`` returns error on bad code block."""
1105 source = """
1106 int main()
1107 {
1108 return x;
1109 }
1110 """
1111 cb_checker = checker.CodeBlockChecker("<string>")
1112
1113 result = list(cb_checker.check_cpp(source))
1114
1115 assert len(result) == 1
1116 assert "error: 'x' was not declared in this scope" in result[0]["message"]
1117
1118 @staticmethod
1119 def test__gcc_checker_returns_none_on_ok_cpp_code_block() -> None:
1120 """Test ``_gcc_checker`` returns ``None`` on ok c++ code block."""
1121 source = """
1122 #include <iostream>
1123
1124 int main()
1125 {
1126 auto x = 1;
1127 return x;
1128 }
1129 """
1130 cb_checker = checker.CodeBlockChecker("<string>")
1131
1132 result = list(
1133 cb_checker._gcc_checker(
1134 source,
1135 ".cpp",
1136 [
1137 os.getenv("CXX", "g++"),
1138 *shlex.split(os.getenv("CXXFLAGS", "")),
1139 *shlex.split(os.getenv("CPPFLAGS", "")),
1140 "-I.",
1141 "-I..",
1142 "-pedantic",
1143 "-fsyntax-only",
1144 ],
1145 )
1146 )
1147
1148 assert not result
1149
1150 @staticmethod
1151 @pytest.mark.skipif(sys.platform != "linux", reason="Linux specific error message")
1152 def test__gcc_checker_returns_error_on_bad_cpp_code_block_linux() -> None:
1153 """Test ``_gcc_checker`` returns error on bad c++ code block."""
1154 source = """
1155 int main()
1156 {
1157 return x;
1158 }
1159 """
1160 cb_checker = checker.CodeBlockChecker("<string>")
1161
1162 result = list(
1163 cb_checker._gcc_checker(
1164 source,
1165 ".cpp",
1166 [
1167 os.getenv("CXX", "g++"),
1168 *shlex.split(os.getenv("CXXFLAGS", "")),
1169 *shlex.split(os.getenv("CPPFLAGS", "")),
1170 "-I.",
1171 "-I..",
1172 "-pedantic",
1173 "-fsyntax-only",
1174 ],
1175 )
1176 )
1177
1178 assert len(result) == 1
1179 assert "error: \u2018x\u2019 was not declared in this scope" in result[0]["message"]
1180
1181 @staticmethod
1182 @pytest.mark.skipif(sys.platform != "darwin", reason="MacOS specific error message")
1183 def test__gcc_checker_returns_error_on_bad_cpp_code_block_macos() -> None:
1184 """Test ``_gcc_checker`` returns error on bad c++ code block."""
1185 source = """
1186 int main()
1187 {
1188 return x;
1189 }
1190 """
1191 cb_checker = checker.CodeBlockChecker("<string>")
1192
1193 result = list(
1194 cb_checker._gcc_checker(
1195 source,
1196 ".cpp",
1197 [
1198 os.getenv("CXX", "g++"),
1199 *shlex.split(os.getenv("CXXFLAGS", "")),
1200 *shlex.split(os.getenv("CPPFLAGS", "")),
1201 "-I.",
1202 "-I..",
1203 "-pedantic",
1204 "-fsyntax-only",
1205 ],
1206 )
1207 )
1208
1209 assert len(result) == 1
1210 assert "error: use of undeclared identifier 'x'" in result[0]["message"]
1211
1212 @staticmethod
1213 @pytest.mark.skipif(sys.platform != "win32", reason="Windows specific error message")
1214 def test__gcc_checker_returns_error_on_bad_cpp_code_block_windows() -> None:
1215 """Test ``_gcc_checker`` returns error on bad c++ code block."""
1216 source = """
1217 int main()
1218 {
1219 return x;
1220 }
1221 """
1222 cb_checker = checker.CodeBlockChecker("<string>")
1223
1224 result = list(
1225 cb_checker._gcc_checker(
1226 source,
1227 ".cpp",
1228 [
1229 os.getenv("CXX", "g++"),
1230 *shlex.split(os.getenv("CXXFLAGS", "")),
1231 *shlex.split(os.getenv("CPPFLAGS", "")),
1232 "-I.",
1233 "-I..",
1234 "-pedantic",
1235 "-fsyntax-only",
1236 ],
1237 )
1238 )
1239
1240 assert len(result) == 1
1241 assert "error: 'x' was not declared in this scope" in result[0]["message"]
1242
1243 @staticmethod
1244 def test__run_in_subprocess_returns_none_on_ok_cpp_code_block() -> None:
1245 """Test ``_run_in_subprocess`` returns ``None`` on ok c++ code block."""
1246 source = """
1247 #include <iostream>
1248
1249 int main()
1250 {
1251 auto x = 1;
1252 return x;
1253 }
1254 """
1255 cb_checker = checker.CodeBlockChecker("<string>")
1256
1257 result = cb_checker._run_in_subprocess(
1258 source,
1259 ".cpp",
1260 [
1261 os.getenv("CXX", "g++"),
1262 *shlex.split(os.getenv("CXXFLAGS", "")),
1263 *shlex.split(os.getenv("CPPFLAGS", "")),
1264 "-I.",
1265 "-I..",
1266 "-pedantic",
1267 "-fsyntax-only",
1268 ],
1269 )
1270
1271 assert not result
1272
1273 @staticmethod
1274 @pytest.mark.skipif(sys.platform != "linux", reason="Linux specific error message")
1275 def test__run_in_subprocess_returns_error_on_bad_cpp_code_block_linux() -> None:
1276 """Test ``_run_in_subprocess`` returns error on bad c++ code block."""
1277 source = """
1278 int main()
1279 {
1280 return x;
1281 }
1282 """
1283 cb_checker = checker.CodeBlockChecker("<string>")
1284
1285 result = cb_checker._run_in_subprocess(
1286 source,
1287 ".cpp",
1288 [
1289 os.getenv("CXX", "g++"),
1290 *shlex.split(os.getenv("CXXFLAGS", "")),
1291 *shlex.split(os.getenv("CPPFLAGS", "")),
1292 "-I.",
1293 "-I..",
1294 "-pedantic",
1295 "-fsyntax-only",
1296 ],
1297 )
1298
1299 assert result is not None
1300 assert "error: \u2018x\u2019 was not declared in this scope" in result[0]
1301 assert result[1].suffix == ".cpp"
1302
1303 @staticmethod
1304 @pytest.mark.skipif(sys.platform != "darwin", reason="MacOS specific error message")
1305 def test__run_in_subprocess_returns_error_on_bad_cpp_code_block_macos() -> None:
1306 """Test ``_run_in_subprocess`` returns error on bad c++ code block."""
1307 source = """
1308 int main()
1309 {
1310 return x;
1311 }
1312 """
1313 cb_checker = checker.CodeBlockChecker("<string>")
1314
1315 result = cb_checker._run_in_subprocess(
1316 source,
1317 ".cpp",
1318 [
1319 os.getenv("CXX", "g++"),
1320 *shlex.split(os.getenv("CXXFLAGS", "")),
1321 *shlex.split(os.getenv("CPPFLAGS", "")),
1322 "-I.",
1323 "-I..",
1324 "-pedantic",
1325 "-fsyntax-only",
1326 ],
1327 )
1328
1329 assert result is not None
1330 assert "error: use of undeclared identifier 'x'" in result[0]
1331 assert result[1].suffix == ".cpp"
1332
1333 @staticmethod
1334 @pytest.mark.skipif(sys.platform != "win32", reason="Windows specific error message")
1335 def test__run_in_subprocess_returns_error_on_bad_cpp_code_block_windows() -> None:
1336 """Test ``_run_in_subprocess`` returns error on bad c++ code block."""
1337 source = """
1338 int main()
1339 {
1340 return x;
1341 }
1342 """
1343 cb_checker = checker.CodeBlockChecker("<string>")
1344
1345 result = cb_checker._run_in_subprocess(
1346 source,
1347 ".cpp",
1348 [
1349 os.getenv("CXX", "g++"),
1350 *shlex.split(os.getenv("CXXFLAGS", "")),
1351 *shlex.split(os.getenv("CPPFLAGS", "")),
1352 "-I.",
1353 "-I..",
1354 "-pedantic",
1355 "-fsyntax-only",
1356 ],
1357 )
1358
1359 assert result is not None
1360 assert "error: 'x' was not declared in this scope" in result[0]
1361 assert result[1].suffix == ".cpp"
1362
1363 @staticmethod
1364 @pytest.mark.skipif(sys.platform != "linux", reason="Linux specific error message")
1365 def test__run_in_subprocess_returns_error_on_bad_cpp_code_block_with_filename_linux() -> None:
1366 """Test ``_run_in_subprocess`` returns error on bad c++ code block from filename."""
1367 source = """
1368 int main()
1369 {
1370 return x;
1371 }
1372 """
1373 cb_checker = checker.CodeBlockChecker(pathlib.Path("filename.cpp"))
1374
1375 result = cb_checker._run_in_subprocess(
1376 source,
1377 ".cpp",
1378 [
1379 os.getenv("CXX", "g++"),
1380 *shlex.split(os.getenv("CXXFLAGS", "")),
1381 *shlex.split(os.getenv("CPPFLAGS", "")),
1382 "-I.",
1383 "-I..",
1384 "-pedantic",
1385 "-fsyntax-only",
1386 ],
1387 )
1388
1389 assert result is not None
1390 assert "error: \u2018x\u2019 was not declared in this scope" in result[0]
1391 assert result[1].suffix == ".cpp"
1392
1393 @staticmethod
1394 @pytest.mark.skipif(sys.platform != "darwin", reason="MacOS specific error message")
1395 def test__run_in_subprocess_returns_error_on_bad_cpp_code_block_with_filename_macos() -> None:
1396 """Test ``_run_in_subprocess`` returns error on bad c++ code block from filename."""
1397 source = """
1398 int main()
1399 {
1400 return x;
1401 }
1402 """
1403 cb_checker = checker.CodeBlockChecker(pathlib.Path("filename.cpp"))
1404
1405 result = cb_checker._run_in_subprocess(
1406 source,
1407 ".cpp",
1408 [
1409 os.getenv("CXX", "g++"),
1410 *shlex.split(os.getenv("CXXFLAGS", "")),
1411 *shlex.split(os.getenv("CPPFLAGS", "")),
1412 "-I.",
1413 "-I..",
1414 "-pedantic",
1415 "-fsyntax-only",
1416 ],
1417 )
1418
1419 assert result is not None
1420 assert "error: use of undeclared identifier 'x'" in result[0]
1421 assert result[1].suffix == ".cpp"
1422
1423 @staticmethod
1424 @pytest.mark.skipif(sys.platform != "win32", reason="Windows specific error message")
1425 def test__run_in_subprocess_returns_error_on_bad_cpp_code_block_with_filename_windows() -> None:
1426 """Test ``_run_in_subprocess`` returns error on bad c++ code block from filename."""
1427 source = """
1428 int main()
1429 {
1430 return x;
1431 }
1432 """
1433 cb_checker = checker.CodeBlockChecker(pathlib.Path("filename.cpp"))
1434
1435 result = cb_checker._run_in_subprocess(
1436 source,
1437 ".cpp",
1438 [
1439 os.getenv("CXX", "g++"),
1440 *shlex.split(os.getenv("CXXFLAGS", "")),
1441 *shlex.split(os.getenv("CPPFLAGS", "")),
1442 "-I.",
1443 "-I..",
1444 "-pedantic",
1445 "-fsyntax-only",
1446 ],
1447 )
1448
1449 assert result is not None
1450 assert "error: 'x' was not declared in this scope" in result[0]
1451 assert result[1].suffix == ".cpp"
1452
1453 @staticmethod
1454 def test__parse_gcc_style_error_message_raises_on_bad_format() -> None:
1455 """Test ``_parse_gcc_style_error_message`` method raises ``ValueError`` on bad format."""
1456 message = "Foo bar"
1457
1458 with pytest.raises(ValueError, match="^Message cannot be parsed.$"):
1459 checker._parse_gcc_style_error_message(message, "<string>")
1460
1461 @staticmethod
1462 def test__parse_gcc_style_error_message_with_tempfile() -> None:
1463 """Test ``_parse_gcc_style_error_message`` method with tempfile."""
1464 message = "tempfile.cpp:16:32: Error message"
1465 error = types.LintError(
1466 source_origin=pathlib.Path("source.rst"),
1467 line_number=16,
1468 message="Error message",
1469 )
1470
1471 result = checker._parse_gcc_style_error_message(
1472 message, pathlib.Path("source.rst"), temp_file_name=pathlib.Path("tempfile.cpp")
1473 )
1474
1475 assert result == error
1476
1477 @staticmethod
1478 def test__parse_gcc_style_error_message_with_column() -> None:
1479 """Test ``_parse_gcc_style_error_message`` method with column."""
1480 message = "<string>:16:32: Error message"
1481 error = types.LintError(
1482 source_origin="<string>",
1483 line_number=16,
1484 message="Error message",
1485 )
1486
1487 result = checker._parse_gcc_style_error_message(message, "<string>")
1488
1489 assert result == error
1490
1491 @staticmethod
1492 def test__parse_gcc_style_error_message_without_column() -> None:
1493 """Test ``_parse_gcc_style_error_message`` method without column."""
1494 message = "<string>:16: Error message"
1495 error = types.LintError(
1496 source_origin="<string>",
1497 line_number=16,
1498 message="Error message",
1499 )
1500
1501 result = checker._parse_gcc_style_error_message(message, "<string>", has_column=False)
1502
1503 assert result == error