Debian Codegraph @

tests/test_lint.py

raw
1 # Spdx-FileCopyrightText: © 2023 Christian BUHTZ <[email protected]>
2 #
3 # SPDX-License-Identifier: GPL-3.0-only
4 #
5 # This file is part of the program "Hyperorg" which is released under GNU
6 # General Public License v3 (GPLv3).
7 # See folder LICENSES or go to <https://www.gnu.org/licenses/#GPL>.
8 """Tests using several linters"""
9 import unittest
10 import os
11 import logging
12 import pathlib
13 import subprocess
14 from importlib import metadata
15 from typing import Iterable
16
17 # Not all linters follow strict PEP8
18 PEP8_MAX_LINE_LENGTH = 79
19
20
21 class MirrorMirrorOnTheWall(unittest.TestCase):
22 """Check all py-files in the package incl. its test files if they are
23 PEP8 compliant or don't smell and not having usual typos.
24 """
25
26 @classmethod
27 def setUpClass(cls):
28 cls.PACKAGE_NAME = 'hyperorg'
29 cls.TEST_FOLDER_NAME = pathlib.Path(__file__).parent.name
30 cls.collected_py_files \
31 = cls._get_package_files() + cls._get_test_files()
32
33 @classmethod
34 def _get_test_files(cls) -> Iterable[pathlib.Path]:
35 """Return list of Python files in the tests folder"""
36 test_path = pathlib.Path.cwd() / cls.TEST_FOLDER_NAME
37
38 return list(test_path.rglob('*.py'))
39
40 @classmethod
41 def _get_package_files(cls) -> Iterable[pathlib.Path]:
42 """Return list of all py-files of the (editable) installed package."""
43
44 # get all files in this package
45 files = metadata.files(cls.PACKAGE_NAME)
46 files = [f.locate() for f in files]
47
48 # py-files only
49 files = filter(
50 lambda fp: fp.suffix == '.py' # Python file
51 and not fp.name.startswith('.#') # no editor temp files
52 and fp.parent.name is not cls.TEST_FOLDER_NAME, # no test file
53 files)
54
55 return list(files)
56
57 def test010_ruff(self):
58 """Ruff in default mode."""
59
60 # ATTENTIION: Some settings are found in pyproject.toml
61 cmd = [
62 'ruff',
63 'check',
64 '--line-length', str(PEP8_MAX_LINE_LENGTH),
65 # Additionally activate subset of PyLint (PL)
66 # and PyCodestyle (E, W) rules
67 '--extend-select=PL,E,W',
68 # But ignore...
69 '--ignore='
70 'PLR2004,' # magic value in comparison
71 'PLW2901', # `for` loop variable `e` overwritten by
72 # assignment target
73 # Ruff counting branches different from PyLint.
74 # See: <https://www.reddit.com/r/learnpython/comments/
75 # 1buojae/comment/kxu0mp3>
76 '--config', 'pylint.max-branches=13',
77 '--config', 'flake8-quotes.inline-quotes = "single"',
78 # one error per line (no context lines)
79 '--output-format=concise',
80 '--quiet',
81 '.',
82 ]
83
84 proc = subprocess.run(
85 cmd,
86 check=False,
87 universal_newlines=True,
88 capture_output=True
89 )
90
91 # No errors other then linter rules
92 self.assertIn(proc.returncode, [0, 1], proc.stderr)
93
94 error_n = len(proc.stdout.splitlines())
95 if error_n > 0:
96 print('\n' + proc.stdout) # noqa: T201
97
98 self.assertEqual(0, error_n, f'Ruff found {error_n} problem(s).')
99
100 # any other errors?
101 self.assertEqual(proc.stderr, '')
102
103 def test020_flake8(self):
104 """Flake8 in default mode."""
105 cmd = [
106 'flake8',
107 f'--max-line-length={PEP8_MAX_LINE_LENGTH}',
108 '--builtins=_,ngettext',
109 # '--enable-extensions='
110 ]
111
112 cmd.extend(str(v) for v in self.collected_py_files)
113
114 proc = subprocess.run(
115 cmd,
116 check=False,
117 universal_newlines=True,
118 capture_output=True
119 )
120
121 error_n = len(proc.stdout.splitlines())
122 if error_n > 0:
123 print('')
124 print(proc.stdout)
125
126 self.assertEqual(0, error_n, f'Flake8 found {error_n} problem(s).')
127
128 # any other errors?
129 self.assertEqual(proc.stderr, '')
130
131 def test030_pylint(self):
132 """Use Pylint to check for specific error codes.
133
134 Some facts about PyLint
135 - It is one of the slowest available linters.
136 - It is able to catch lints none of the other linters
137 """
138
139 # Pylint base command
140 cmd = [
141 'pylint',
142 # # Output format (default: text)
143 # '--output-format=colorized',
144 # Storing results in a pickle file is unnecessary
145 '--persistent=n',
146 # autodetec number of parallel jobs (pylint default)
147 '--jobs=0',
148 # Disable scoring ("Your code has been rated at xx/10")
149 '--score=n',
150 # PEP8 conform line length (see PyLint Issue #3078)
151 f'--max-line-length={PEP8_MAX_LINE_LENGTH}',
152 # # prevent false-positive no-module-member errors
153 # '--extension-pkg-whitelist='
154 # 'pygments,pygments.formatters,pygments.formatters.html',
155 # List of members which are set dynamically and missed by pylint
156 # inference system, and so shouldn't trigger E1101 when accessed.
157 '--generated-members=pygments.formatters.HtmlFormatter',
158 # Allowlist variable names
159 '--good-names=idx,fp,fn,maxDiff',
160 # Allow fstrings when logging
161 '--disable=logging-fstring-interpolation',
162 # https://github.com/pylint-dev/pylint/issues/9547
163 '--ignored-argument-names=_',
164 ]
165
166 # Add py files
167 cmd.extend(str(v) for v in self.collected_py_files)
168
169 # subprocess.run(cmd, check=True)
170 proc = subprocess.run(
171 cmd,
172 check=False,
173 universal_newlines=True,
174 capture_output=True)
175
176 # Count lines except module headings
177 error_n = len(list(filter(
178 lambda line: line[:2] not in ('**', ' ', '==', ' (', ''),
179 proc.stdout.splitlines())))
180 print(proc.stdout) # noqa: T201
181
182 if proc.returncode != 0:
183 logging.error(proc.stdout)
184
185 self.assertEqual(0, error_n, f'PyLint found {error_n} problem(s).')
186
187 # any other errors?
188 self.assertEqual(proc.stderr, '')
189
190 def test040_codespell(self):
191 """Codespell to check for common typos.
192
193 Config can be found in pyproject.toml.
194 """
195
196 # cmd = [
197 # 'codespell',
198 # # Skip these files
199 # '--skip',
200 # '.git,.pytest_cache,.ruff_cache,build,*.egg-info,'
201 # 'docs,#*.py#,.venv,venv,./example/html',
202 # # Print N lines of surrounding context
203 # '--context', '1',
204 # # Check hidden files also
205 # '--check-hidden',
206 # # Dictionaries to use (default: "clear,rare"). Current: all.
207 # '--builtin',
208 # 'clear,rare,informal,usage,code,names,en-GB_to_en-US',
209 # # Print number of errors as last line on stderr
210 # '--count',
211 # # Simulate "# noqa" and ignore all lines with
212 # # "# codespell-ignore" at the end.
213 # # Credits: https://github.com/codespell-project/codespell/
214 # # issues/1212#issuecomment-1721152455
215 # '--ignore-regex', '.*# codespell-ignore$',
216 # # Allowed (ignored) words
217 # '--ignore-words-list=assertIn',
218 # # Allowed (ignored) words in URLs and URIs
219 # '--uri-ignore-words-list=master',
220 # '--enable-colors',
221 # ]
222
223 proc = subprocess.run(
224 ['codespell'],
225 check=False,
226 universal_newlines=True,
227 capture_output=True)
228
229 error_n = int(proc.stderr)
230
231 if error_n > 0:
232 logging.error(proc.stdout)
233
234 self.assertEqual(0, error_n, f'Codespell found {error_n} problem(s).')
235
236 def test050_reuse_spdx(self):
237 """Check REUSE Software and SPDX specifications"""
238 env = os.environ
239 env['LC_ALL'] = 'C'
240
241 proc = subprocess.run(
242 ['reuse', 'lint'],
243 check=False,
244 universal_newlines=True,
245 env=env,
246 capture_output=True)
247
248 self.assertEqual(proc.returncode, 0, proc.stdout)