Debian Codegraph @

cpplint_clitest.py

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2009 Google Inc. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions are
7 # met:
8 #
9 # * Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 # * Redistributions in binary form must reproduce the above
12 # copyright notice, this list of conditions and the following disclaimer
13 # in the documentation and/or other materials provided with the
14 # distribution.
15 # * Neither the name of Google Inc. nor the names of its
16 # contributors may be used to endorse or promote products derived from
17 # this software without specific prior written permission.
18 #
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 """Command Line interface integration test for cpplint.py."""
32
33 import contextlib
34 import glob
35 import os
36 import shutil
37 import subprocess
38 import sys
39 import tempfile
40
41 import pytest
42 from testfixtures import compare # type: ignore[import-untyped]
43
44 import cpplint # noqa: F401
45
•46 BASE_CMD = "cpplint"
47
48
49 def run_shell_command(cmd: str, args: str, cwd: str = ".") -> tuple[int, bytes, bytes]:
50 """Executes a command
51
52 Args:
53 cmd: A string to execute.
54 args: A string with arguments to the command.
55 cwd: from which folder to run.
56 """
57 cmd, args = cmd.split(), args.replace('"', "").split() # type: ignore[assignment]
58 proc = subprocess.run(cmd + args, cwd=cwd, capture_output=True, check=False)
59 out, err = proc.stdout, proc.stderr
60
61 # Make output system-agnostic, aka support Windows
62 if os.sep == "\\":
63 # TODO(aaronliu0130): Support scenario with multiple input names
64 # We currently only support the last arguments as the input name
65 # to prevent accidentally replacing sed tests.
66 # Fixing would likely need coding an internal "replace slashes" option for cpplint itself.
67 win_path = (os.path.dirname(args[-1]) + "\\").encode()
68 good_path = win_path.replace(b"\\", b"/")
69 out, err = out.replace(win_path, good_path), err.replace(win_path, good_path)
70 if os.linesep == "\r\n":
71 out, err = out.replace(b"\r\n", b"\n"), err.replace(b"\r\n", b"\n")
72
73 # print(err) # to get the output at time of test
74 return proc.returncode, out, err
75
76
77 def test_help():
78 (status, out, err) = run_shell_command(BASE_CMD, "--help")
79 assert status == 0
80 assert out == b""
81 assert err.startswith(b"\nSyntax: cpplint")
82
83
84 class TemporaryFolderClassSetup:
85 """
86 Regression tests: The test starts a filetreewalker scanning for files name *.def
87 Such files are expected to have as first line the argument
88 to a cpplint invocation from within the same directory, as second line the
89 expected status code, then the line count of stdout lines,
90 then the stdout lines, and all other lines the expected
91 systemerr output (two blank lines at end).
92 """
93
94 @pytest.fixture(autouse=True, name="set_up()", scope="class")
95 @classmethod
96 def set_up(cls):
97 """setup tmp folder for testing with samples and custom additions by subclasses"""
98 try:
99 cls._root = os.path.realpath(tempfile.mkdtemp())
100 shutil.copytree("samples", os.path.join(cls._root, "samples"))
101 cls.prepare_directory(cls._root)
102 except Exception:
103 with contextlib.suppress(Exception):
104 cls.tear_down()
105 raise
106 # yield
107 # cls.tear_down()
108
109 @classmethod
110 def tear_down(cls):
111 if cls._root:
112 # pass
113 shutil.rmtree(cls._root)
114
115 @classmethod
116 def prepare_directory(cls, root):
117 """Override in subclass to manipulate temporary samples root folder before tests"""
118 pass
119
120 def get_extra_command_args(self, cwd):
121 """Override in subclass to add arguments to command"""
122 return ""
123
124 def check_all_in_folder(self, folder_name, expected_defs):
125 # uncomment to show complete diff
126 # self.maxDiff = None
127 count = 0
128 for dirpath, _, fnames in os.walk(folder_name):
129 for f in fnames:
130 if f.endswith(".def"):
131 count += 1
132 self.check_def(os.path.join(dirpath, f))
133 assert count == expected_defs
134
135 def check_def(self, path):
136 """runs command and compares to expected output from def file"""
137 # self.maxDiff = None # to see full diff
138 with open(path, "rb") as file_handle:
139 data = file_handle.readlines()
140 stdout_lines = int(data[2])
141 filenames = data[0].decode("utf8").strip()
142 args, _, filenames = filenames.rpartition(" ")
143 if "*" in filenames:
144 rel_cwd = os.path.dirname(path)
145 filenames = " ".join(
146 filename[len(rel_cwd) + 1 :]
147 for filename in glob.glob(rel_cwd + "/" + filenames)
148 )
149 args += " " + filenames
150 self._run_and_compare(
151 path,
152 args,
153 int(data[1]),
154 [line.decode("utf8").strip() for line in data[3 : 3 + stdout_lines]],
155 [line.decode("utf8").strip() for line in data[3 + stdout_lines :]],
156 )
157
158 def _run_and_compare(self, definition_file, args, expected_status, expected_out, expected_err):
159 rel_cwd = os.path.dirname(definition_file)
160 cmd = BASE_CMD + self.get_extra_command_args(rel_cwd)
161 cwd = os.path.join(self._root, rel_cwd)
162 # command to reproduce, do not forget first two lines have special meaning
163 print("\ncd " + cwd + " && " + cmd + " " + args + " 2> <filename>")
164 (status, out, err) = run_shell_command(cmd, args, cwd)
165 assert expected_status == status, f"bad command status {status}"
166 prefix = f"Failed check in {cwd} comparing to {definition_file} for command: {cmd}"
167 compare("\n".join(expected_err), err.decode("utf8"), prefix=prefix, show_whitespace=True)
168 compare("\n".join(expected_out), out.decode("utf8"), prefix=prefix, show_whitespace=True)
169
170
171 class TestNoRepoSignature(TemporaryFolderClassSetup):
172 """runs in a temporary folder (under /tmp in linux) without any .git/.hg/.svn file"""
173
174 def get_extra_command_args(self, cwd):
175 return f" --repository {self._root} "
176
177 @pytest.mark.parametrize(
178 ("folder", "case"),
179 [
180 (folder, case[:-4])
181 for folder in ["chromium", "vlc", "silly", "boost", "protobuf", "codelite", "v8"]
182 for case in os.listdir(f"./samples/{folder}-sample")
183 if case.endswith(".def")
184 ],
185 )
186 def test_samples(self, folder, case):
187 self.check_def(os.path.join(f"./samples/{folder}-sample", case + ".def"))
188
189
190 class TestGitRepoSignature(TemporaryFolderClassSetup):
191 """runs in a temporary folder with .git file"""
192
193 @classmethod
194 def prepare_directory(cls, root):
195 with open(os.path.join(root, ".git"), "a"):
196 pass
197
198 def test_codelite_sample(self):
199 self.check_all_in_folder("./samples/codelite-sample", 1)
200
201
202 class TestMercurialRepoSignature(TemporaryFolderClassSetup):
203 """runs in a temporary folder with .hg file"""
204
205 @classmethod
206 def prepare_directory(cls, root):
207 with open(os.path.join(root, ".hg"), "a"):
208 pass
209
210 def test_codelite_sample(self):
211 self.check_all_in_folder("./samples/codelite-sample", 1)
212
213
214 class TestSvnRepoSignature(TemporaryFolderClassSetup):
215 """runs in a temporary folder with .svn file"""
216
217 @classmethod
218 def prepare_directory(cls, root):
219 with open(os.path.join(root, ".svn"), "a"):
220 pass
221
222 def test_codelite_sample(self):
223 self.check_all_in_folder("./samples/codelite-sample", 1)
224
225
226 if __name__ == "__main__":
227 pytest.main([__file__])