diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7a3923f..d018e58 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -15,7 +15,7 @@ repos: - tomli - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.10.0 + rev: v0.11.0 hooks: - id: ruff - id: ruff-format diff --git a/cpplint.py b/cpplint.py index b396eae..eeca895 100755 --- a/cpplint.py +++ b/cpplint.py @@ -323,7 +323,6 @@ "readability/namespace", "readability/nolint", "readability/nul", - "readability/strings", "readability/todo", "readability/utf8", "runtime/arrays", diff --git a/cpplint_clitest.py b/cpplint_clitest.py index f7c633f..d6fddca 100755 --- a/cpplint_clitest.py +++ b/cpplint_clitest.py @@ -37,12 +37,13 @@ import subprocess import sys import tempfile -import unittest +import pytest from parameterized import parameterized -from pytest import mark from testfixtures import compare +import cpplint # noqa: F401 + BASE_CMD = sys.executable + " " + os.path.abspath("./cpplint.py ") @@ -74,15 +75,15 @@ def run_shell_command(cmd: str, args: str, cwd="."): return proc.returncode, out, err -class UsageTest(unittest.TestCase): +class TestUsage: def testHelp(self): (status, out, err) = run_shell_command(BASE_CMD, "--help") - self.assertEqual(0, status) - self.assertEqual(b"", out) - self.assertTrue(err.startswith(b"\nSyntax: cpplint")) + assert status == 0 + assert out == b"" + assert err.startswith(b"\nSyntax: cpplint") -class TemporaryFolderClassSetup(unittest.TestCase): +class TemporaryFolderClassSetup: """ Regression tests: The test starts a filetreewalker scanning for files name *.def Such files are expected to have as first line the argument @@ -92,6 +93,7 @@ class TemporaryFolderClassSetup(unittest.TestCase): systemerr output (two blank lines at end). """ + @pytest.fixture(autouse=True, name="setUpClass()", scope="class") @classmethod def setUpClass(cls): """setup tmp folder for testing with samples and custom additions by subclasses""" @@ -103,6 +105,8 @@ def setUpClass(cls): with contextlib.suppress(Exception): cls.tearDownClass() raise + # yield + # cls.tearDownClass() @classmethod def tearDownClass(cls): @@ -128,7 +132,7 @@ def check_all_in_folder(self, folder_name, expected_defs): if f.endswith(".def"): count += 1 self.check_def(os.path.join(dirpath, f)) - self.assertEqual(count, expected_defs) + assert count == expected_defs def check_def(self, path): """runs command and compares to expected output from def file""" @@ -160,13 +164,13 @@ def _run_and_compare(self, definition_file, args, expected_status, expected_out, # command to reproduce, do not forget first two lines have special meaning print("\ncd " + cwd + " && " + cmd + " " + args + " 2> ") (status, out, err) = run_shell_command(cmd, args, cwd) - self.assertEqual(expected_status, status, f"bad command status {status}") + assert expected_status == status, f"bad command status {status}" prefix = f"Failed check in {cwd} comparing to {definition_file} for command: {cmd}" compare("\n".join(expected_err), err.decode("utf8"), prefix=prefix, show_whitespace=True) compare("\n".join(expected_out), out.decode("utf8"), prefix=prefix, show_whitespace=True) -class NoRepoSignatureTests(TemporaryFolderClassSetup, unittest.TestCase): +class TestNoRepoSignature(TemporaryFolderClassSetup): """runs in a temporary folder (under /tmp in linux) without any .git/.hg/.svn file""" def get_extra_command_args(self, cwd): @@ -185,12 +189,12 @@ def _test_name_func(fun, _, x): ], name_func=_test_name_func, ) - @mark.timeout(180) + @pytest.mark.timeout(180) def testSamples(self, folder, case): self.check_def(os.path.join(f"./samples/{folder}-sample", case + ".def")) -class GitRepoSignatureTests(TemporaryFolderClassSetup, unittest.TestCase): +class TestGitRepoSignature(TemporaryFolderClassSetup): """runs in a temporary folder with .git file""" @classmethod @@ -202,7 +206,7 @@ def testCodeliteSample(self): self.check_all_in_folder("./samples/codelite-sample", 1) -class MercurialRepoSignatureTests(TemporaryFolderClassSetup, unittest.TestCase): +class TestMercurialRepoSignature(TemporaryFolderClassSetup): """runs in a temporary folder with .hg file""" @classmethod @@ -214,7 +218,7 @@ def testCodeliteSample(self): self.check_all_in_folder("./samples/codelite-sample", 1) -class SvnRepoSignatureTests(TemporaryFolderClassSetup, unittest.TestCase): +class TestSvnRepoSignature(TemporaryFolderClassSetup): """runs in a temporary folder with .svn file""" @classmethod @@ -227,4 +231,4 @@ def testCodeliteSample(self): if __name__ == "__main__": - unittest.main() + pytest.main([__file__]) diff --git a/cpplint_unittest.py b/cpplint_unittest.py index bae157d..66751a3 100755 --- a/cpplint_unittest.py +++ b/cpplint_unittest.py @@ -41,7 +41,6 @@ import subprocess import sys import tempfile -import unittest import pytest from parameterized import parameterized @@ -129,7 +128,7 @@ def open( return self.mock_file -class CpplintTestBase(unittest.TestCase): +class CpplintTestBase: """Provides some useful helper functions for cpplint tests.""" def setUp(self): @@ -139,6 +138,9 @@ def setUp(self): def tearDown(self): os.path.abspath = self.os_path_abspath_orig + def assertTrue(self, condition, message=""): + assert condition, message + # Perform lint on single line of input and return the error message. def PerformSingleLineLint(self, code): error_collector = ErrorCollector(self.assertTrue) @@ -239,17 +241,17 @@ def PerformIncludeWhatYouUse(self, code, filename="foo.h", io=codecs): # Perform lint and make sure one of the errors is what we want def TestLintContains(self, code, expected_message): - self.assertTrue(expected_message in self.PerformSingleLineLint(code)) + assert expected_message in self.PerformSingleLineLint(code) def TestLintNotContains(self, code, expected_message): - self.assertFalse(expected_message in self.PerformSingleLineLint(code)) + assert expected_message not in self.PerformSingleLineLint(code) # Perform lint and compare the error message with "expected_message". def TestLint(self, code, expected_message): - self.assertEqual(expected_message, self.PerformSingleLineLint(code)) + assert expected_message == self.PerformSingleLineLint(code) def TestMultiLineLint(self, code, expected_message): - self.assertEqual(expected_message, self.PerformMultiLineLint(code)) + assert expected_message == self.PerformMultiLineLint(code) def TestMultiLineLintRE(self, code, expected_message_re): message = self.PerformMultiLineLint(code) @@ -259,10 +261,10 @@ def TestMultiLineLintRE(self, code, expected_message_re): ) def TestLanguageRulesCheck(self, file_name, code, expected_message): - self.assertEqual(expected_message, self.PerformLanguageRulesCheck(file_name, code)) + assert expected_message == self.PerformLanguageRulesCheck(file_name, code) def TestIncludeWhatYouUse(self, code, expected_message): - self.assertEqual(expected_message, self.PerformIncludeWhatYouUse(code)) + assert expected_message == self.PerformIncludeWhatYouUse(code) def TestBlankLinesCheck(self, lines, start_errors, end_errors): for extension in ["c", "cc", "cpp", "cxx", "c++", "cu"]: @@ -271,23 +273,17 @@ def TestBlankLinesCheck(self, lines, start_errors, end_errors): def doTestBlankLinesCheck(self, lines, start_errors, end_errors, extension): error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData("foo." + extension, extension, lines, error_collector) - self.assertEqual( - start_errors, - error_collector.Results().count( - "Redundant blank line at the start of a code block " - "should be deleted. [whitespace/blank_line] [2]" - ), + assert start_errors == error_collector.Results().count( + "Redundant blank line at the start of a code block should be deleted. " + "[whitespace/blank_line] [2]" ) - self.assertEqual( - end_errors, - error_collector.Results().count( - "Redundant blank line at the end of a code block " - "should be deleted. [whitespace/blank_line] [3]" - ), + assert end_errors == error_collector.Results().count( + "Redundant blank line at the end of a code block should be deleted. " + "[whitespace/blank_line] [3]" ) -class CpplintTest(CpplintTestBase): +class TestCpplint(CpplintTestBase): def GetNamespaceResults(self, lines): error_collector = ErrorCollector(self.assertTrue) cpplint.RemoveMultiLineComments("foo.h", lines, error_collector) @@ -303,9 +299,7 @@ def testForwardDeclarationNamespaceIndentation(self): lines = ["namespace Test {", " class ForwardDeclaration;", "} // namespace Test"] results = self.GetNamespaceResults(lines) - self.assertEqual( - results, "Do not indent within a namespace. [whitespace/indent_namespace] [4]" - ) + assert results == "Do not indent within a namespace. [whitespace/indent_namespace] [4]" def testNamespaceIndentationForClass(self): lines = [ @@ -317,13 +311,10 @@ def testNamespaceIndentationForClass(self): ] results = self.GetNamespaceResults(lines) - self.assertEqual( - results, - [ - "Do not indent within a namespace. [whitespace/indent_namespace] [4]", - "Do not indent within a namespace. [whitespace/indent_namespace] [4]", - ], - ) + assert results == [ + "Do not indent within a namespace. [whitespace/indent_namespace] [4]", + "Do not indent within a namespace. [whitespace/indent_namespace] [4]", + ] def testNamespaceIndentationIndentedParameter(self): lines = [ @@ -333,7 +324,7 @@ def testNamespaceIndentationIndentedParameter(self): ] results = self.GetNamespaceResults(lines) - self.assertEqual(results, "") + assert results == "" def testNestingInNamespace(self): lines = [ @@ -349,61 +340,59 @@ def testNestingInNamespace(self): ] results = self.GetNamespaceResults(lines) - self.assertEqual(results, "") + assert results == "" # Test get line width. def testGetLineWidth(self): - self.assertEqual(0, cpplint.GetLineWidth("")) - self.assertEqual(10, cpplint.GetLineWidth("x" * 10)) - self.assertEqual(16, cpplint.GetLineWidth("\u90fd|\u9053|\u5e9c|\u770c|\u652f\u5e81")) - self.assertEqual(16, cpplint.GetLineWidth("都|道|府|県|支庁")) - self.assertEqual(5 + 13 + 9, cpplint.GetLineWidth("d𝐱/dt" + "f : t ⨯ 𝐱 → ℝ" + "t ⨯ 𝐱 → ℝ")) + assert cpplint.GetLineWidth("") == 0 + assert cpplint.GetLineWidth("x" * 10) == 10 + assert cpplint.GetLineWidth("都|道|府|県|支庁") == 16 + assert cpplint.GetLineWidth("都|道|府|県|支庁") == 16 + assert cpplint.GetLineWidth("d𝐱/dt" + "f : t ⨯ 𝐱 → ℝ" + "t ⨯ 𝐱 → ℝ") == 5 + 13 + 9 def testGetTextInside(self): - self.assertEqual("", cpplint._GetTextInside("fun()", r"fun\(")) - self.assertEqual("x, y", cpplint._GetTextInside("f(x, y)", r"f\(")) - self.assertEqual("a(), b(c())", cpplint._GetTextInside("printf(a(), b(c()))", r"printf\(")) - self.assertEqual("x, y{}", cpplint._GetTextInside("f[x, y{}]", r"f\[")) - self.assertEqual(None, cpplint._GetTextInside("f[a, b(}]", r"f\[")) - self.assertEqual(None, cpplint._GetTextInside("f[x, y]", r"f\(")) - self.assertEqual( - "y, h(z, (a + b))", cpplint._GetTextInside("f(x, g(y, h(z, (a + b))))", r"g\(") - ) - self.assertEqual("f(f(x))", cpplint._GetTextInside("f(f(f(x)))", r"f\(")) + assert cpplint._GetTextInside("fun()", r"fun\(") == "" + assert cpplint._GetTextInside("f(x, y)", r"f\(") == "x, y" + assert cpplint._GetTextInside("printf(a(), b(c()))", r"printf\(") == "a(), b(c())" + assert cpplint._GetTextInside("f[x, y{}]", r"f\[") == "x, y{}" + assert None is cpplint._GetTextInside("f[a, b(}]", r"f\[") + assert None is cpplint._GetTextInside("f[x, y]", r"f\(") + assert cpplint._GetTextInside("f(x, g(y, h(z, (a + b))))", r"g\(") == "y, h(z, (a + b))" + assert cpplint._GetTextInside("f(f(f(x)))", r"f\(") == "f(f(x))" # Supports multiple lines. - self.assertEqual( - "\n return loop(x);\n", - cpplint._GetTextInside("int loop(int x) {\n return loop(x);\n}\n", r"\{"), + assert ( + cpplint._GetTextInside("int loop(int x) {\n return loop(x);\n}\n", r"\{") + == "\n return loop(x);\n" ) # '^' matches the beginning of each line. - self.assertEqual( - "x, y", + assert ( cpplint._GetTextInside( '#include "inl.h" // skip #define\n' "#define A2(x, y) a_inl_(x, y, __LINE__)\n" '#define A(x) a_inl_(x, "", __LINE__)\n', r"^\s*#define\s*\w+\(", - ), + ) + == "x, y" ) def testFindNextMultiLineCommentStart(self): - self.assertEqual(1, cpplint.FindNextMultiLineCommentStart([""], 0)) + assert cpplint.FindNextMultiLineCommentStart([""], 0) == 1 lines = ["a", "b", "/* c"] - self.assertEqual(2, cpplint.FindNextMultiLineCommentStart(lines, 0)) + assert cpplint.FindNextMultiLineCommentStart(lines, 0) == 2 lines = ['char a[] = "/*";'] # not recognized as comment. - self.assertEqual(1, cpplint.FindNextMultiLineCommentStart(lines, 0)) + assert cpplint.FindNextMultiLineCommentStart(lines, 0) == 1 def testFindNextMultiLineCommentEnd(self): - self.assertEqual(1, cpplint.FindNextMultiLineCommentEnd([""], 0)) + assert cpplint.FindNextMultiLineCommentEnd([""], 0) == 1 lines = ["a", "b", " c */"] - self.assertEqual(2, cpplint.FindNextMultiLineCommentEnd(lines, 0)) + assert cpplint.FindNextMultiLineCommentEnd(lines, 0) == 2 def testRemoveMultiLineCommentsFromRange(self): lines = ["a", " /* comment ", " * still comment", " comment */ ", "b"] cpplint.RemoveMultiLineCommentsFromRange(lines, 1, 4) - self.assertEqual(["a", "/**/", "/**/", "/**/", "b"], lines) + assert lines == ["a", "/**/", "/**/", "/**/", "b"] def testSpacesAtEndOfLine(self): self.TestLint( @@ -507,7 +496,7 @@ def testErrorSuppression(self): ], error_collector, ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" # NOLINTNEXTLINE multiple categories silences warning for the next line instead of current # line error_collector = ErrorCollector(self.assertTrue) @@ -522,7 +511,7 @@ def testErrorSuppression(self): ], error_collector, ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" # LINT_C_FILE silences cast warnings for entire file. error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( @@ -537,7 +526,7 @@ def testErrorSuppression(self): ], error_collector, ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" # Vim modes silence cast warnings for entire file. for modeline in [ "vi:filetype=c", @@ -580,7 +569,7 @@ def testErrorSuppression(self): ], error_collector, ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" # LINT_KERNEL_FILE silences whitespace/tab warnings for entire file. error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( @@ -597,7 +586,7 @@ def testErrorSuppression(self): ], error_collector, ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" # NOLINT, NOLINTNEXTLINE silences the readability/braces warning for "};". error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( @@ -618,7 +607,7 @@ def testErrorSuppression(self): ], error_collector, ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" # NOLINTBEGIN and silences all warnings after it error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( @@ -632,7 +621,7 @@ def testErrorSuppression(self): ], error_collector, ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( "test.cc", @@ -645,7 +634,7 @@ def testErrorSuppression(self): ], error_collector, ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" # NOLINTEND will show warnings after that point error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( @@ -661,9 +650,9 @@ def testErrorSuppression(self): ], error_collector, ) - self.assertEqual( - "Lines should be <= 80 characters long [whitespace/line_length] [2]", - error_collector.Results(), + assert ( + error_collector.Results() + == "Lines should be <= 80 characters long [whitespace/line_length] [2]" ) # NOLINTBEGIN(category) silences category warnings after it error_collector = ErrorCollector(self.assertTrue) @@ -681,9 +670,9 @@ def testErrorSuppression(self): ], error_collector, ) - self.assertEqual( - "Lines should be <= 80 characters long [whitespace/line_length] [2]", - error_collector.Results(), + assert ( + error_collector.Results() + == "Lines should be <= 80 characters long [whitespace/line_length] [2]" ) # NOLINTEND(category) will generate an error that categories are not supported error_collector = ErrorCollector(self.assertTrue) @@ -700,10 +689,10 @@ def testErrorSuppression(self): ], error_collector, ) - self.assertEqual( - "NOLINT categories not supported in block END: readability/casting " - "[readability/nolint] [5]", - error_collector.Results(), + assert ( + error_collector.Results() + == "NOLINT categories not supported in block END: readability/casting " + "[readability/nolint] [5]" ) # nested NOLINTBEGIN is not allowed error_collector = ErrorCollector(self.assertTrue) @@ -721,9 +710,9 @@ def testErrorSuppression(self): ], error_collector, ) - self.assertEqual( - "NONLINT block already defined on line 2 [readability/nolint] [5]", - error_collector.Results(), + assert ( + error_collector.Results() + == "NONLINT block already defined on line 2 [readability/nolint] [5]" ) # error if NOLINGBEGIN is not ended error_collector = ErrorCollector(self.assertTrue) @@ -739,9 +728,7 @@ def testErrorSuppression(self): ], error_collector, ) - self.assertEqual( - "NONLINT block never ended [readability/nolint] [5]", error_collector.Results() - ) + assert error_collector.Results() == "NONLINT block never ended [readability/nolint] [5]" # error if unmatched NOLINTEND self.TestLint("// NOLINTEND", "Not in a NOLINT block [readability/nolint] [5]") self.TestLint("// NOLINTEND(*)", "Not in a NOLINT block [readability/nolint] [5]") @@ -1011,7 +998,7 @@ def testDeprecatedCast(self): ], error_collector, ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" # Return types for function pointers self.TestLint("typedef bool(FunctionPointer)();", "") @@ -1050,21 +1037,19 @@ def testMockMethod(self): ], # true positive error_collector, ) - self.assertEqual( - 0, + assert ( error_collector.Results().count( - "Using deprecated casting style. " - "Use static_cast(...) instead " + "Using deprecated casting style. Use static_cast(...) instead " "[readability/casting] [4]" - ), + ) + == 0 ) - self.assertEqual( - 1, + assert ( error_collector.Results().count( - "Using deprecated casting style. " - "Use static_cast(...) instead " + "Using deprecated casting style. Use static_cast(...) instead " "[readability/casting] [4]" - ), + ) + == 1 ) # Like gMock method definitions, MockCallback instantiations look very similar @@ -1090,9 +1075,9 @@ def testTypedefForPointerToFunction(self): def testIncludeWhatYouUseNoImplementationFiles(self): code = "std::vector foo;" for extension in ["h", "hpp", "hxx", "h++", "cuh", "c", "cc", "cpp", "cxx", "c++", "cu"]: - self.assertEqual( - "Add #include for vector<> [build/include_what_you_use] [4]", - self.PerformIncludeWhatYouUse(code, "foo." + extension), + assert ( + self.PerformIncludeWhatYouUse(code, "foo." + extension) + == "Add #include for vector<> [build/include_what_you_use] [4]" ) def testIncludeWhatYouUse(self): @@ -1351,43 +1336,40 @@ def testIncludeWhatYouUse(self): def testFilesBelongToSameModule(self): f = cpplint.FilesBelongToSameModule - self.assertEqual((True, ""), f("a.cc", "a.h")) - self.assertEqual((True, ""), f("base/google.cc", "base/google.h")) - self.assertEqual((True, ""), f("base/google_test.c", "base/google.h")) - self.assertEqual((True, ""), f("base/google_test.cc", "base/google.h")) - self.assertEqual((True, ""), f("base/google_test.cc", "base/google.hpp")) - self.assertEqual((True, ""), f("base/google_test.cxx", "base/google.hxx")) - self.assertEqual((True, ""), f("base/google_test.cpp", "base/google.hpp")) - self.assertEqual((True, ""), f("base/google_test.c++", "base/google.h++")) - self.assertEqual((True, ""), f("base/google_test.cu", "base/google.cuh")) - self.assertEqual((True, ""), f("base/google_unittest.cc", "base/google.h")) - self.assertEqual((True, ""), f("base/internal/google_unittest.cc", "base/public/google.h")) - self.assertEqual( - (True, "xxx/yyy/"), - f("xxx/yyy/base/internal/google_unittest.cc", "base/public/google.h"), - ) - self.assertEqual( - (True, "xxx/yyy/"), f("xxx/yyy/base/google_unittest.cc", "base/public/google.h") - ) - self.assertEqual((True, ""), f("base/google_unittest.cc", "base/google-inl.h")) - self.assertEqual( - (True, "/home/build/google3/"), f("/home/build/google3/base/google.cc", "base/google.h") - ) - - self.assertEqual((False, ""), f("/home/build/google3/base/google.cc", "basu/google.h")) - self.assertEqual((False, ""), f("a.cc", "b.h")) + assert f("a.cc", "a.h") == (True, "") + assert f("base/google.cc", "base/google.h") == (True, "") + assert f("base/google_test.c", "base/google.h") == (True, "") + assert f("base/google_test.cc", "base/google.h") == (True, "") + assert f("base/google_test.cc", "base/google.hpp") == (True, "") + assert f("base/google_test.cxx", "base/google.hxx") == (True, "") + assert f("base/google_test.cpp", "base/google.hpp") == (True, "") + assert f("base/google_test.c++", "base/google.h++") == (True, "") + assert f("base/google_test.cu", "base/google.cuh") == (True, "") + assert f("base/google_unittest.cc", "base/google.h") == (True, "") + assert f("base/internal/google_unittest.cc", "base/public/google.h") == (True, "") + assert f("xxx/yyy/base/internal/google_unittest.cc", "base/public/google.h") == ( + True, + "xxx/yyy/", + ) + assert f("xxx/yyy/base/google_unittest.cc", "base/public/google.h") == (True, "xxx/yyy/") + assert f("base/google_unittest.cc", "base/google-inl.h") == (True, "") + assert f("/home/build/google3/base/google.cc", "base/google.h") == ( + True, + "/home/build/google3/", + ) + + assert f("/home/build/google3/base/google.cc", "basu/google.h") == (False, "") + assert f("a.cc", "b.h") == (False, "") def testCleanseLine(self): - self.assertEqual("int foo = 0;", cpplint.CleanseComments("int foo = 0; // danger!")) - self.assertEqual("int o = 0;", cpplint.CleanseComments("int /* foo */ o = 0;")) - self.assertEqual( - "foo(int a, int b);", cpplint.CleanseComments("foo(int a /* abc */, int b);") - ) - self.assertEqual("f(a, b);", cpplint.CleanseComments("f(a, /* name */ b);")) - self.assertEqual("f(a, b);", cpplint.CleanseComments("f(a /* name */, b);")) - self.assertEqual("f(a, b);", cpplint.CleanseComments("f(a, /* name */b);")) - self.assertEqual("f(a, b, c);", cpplint.CleanseComments("f(a, /**/b, /**/c);")) - self.assertEqual("f(a, b, c);", cpplint.CleanseComments("f(a, /**/b/**/, c);")) + assert cpplint.CleanseComments("int foo = 0; // danger!") == "int foo = 0;" + assert cpplint.CleanseComments("int /* foo */ o = 0;") == "int o = 0;" + assert cpplint.CleanseComments("foo(int a /* abc */, int b);") == "foo(int a, int b);" + assert cpplint.CleanseComments("f(a, /* name */ b);") == "f(a, b);" + assert cpplint.CleanseComments("f(a /* name */, b);") == "f(a, b);" + assert cpplint.CleanseComments("f(a, /* name */b);") == "f(a, b);" + assert cpplint.CleanseComments("f(a, /**/b, /**/c);") == "f(a, b, c);" + assert cpplint.CleanseComments("f(a, /**/b/**/, c);") == "f(a, b, c);" def testRawStrings(self): self.TestMultiLineLint( @@ -1534,10 +1516,8 @@ def testMultilineStrings(self): ['const char* str = "This is a\\', ' multiline string.";'], error_collector, ) - self.assertEqual( - 2, # One per line. - error_collector.ResultList().count(multiline_string_error_message), - ) + # One per line. + assert error_collector.ResultList().count(multiline_string_error_message) == 2 # Test non-explicit single-argument constructors def testExplicitSingleArgumentConstructors(self): @@ -1924,12 +1904,12 @@ class Foo { ], error_collector, ) - self.assertEqual( - 0, + assert ( error_collector.ResultList().count( - "Constructors that require multiple arguments should not be marked " - "explicit. [runtime/explicit] [0]" - ), + "Constructors that require multiple arguments should not be marked explicit. " + "[runtime/explicit] [0]" + ) + == 0 ) error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( @@ -1943,12 +1923,12 @@ class Foo { ], error_collector, ) - self.assertEqual( - 0, + assert ( error_collector.ResultList().count( - "Constructors that require multiple arguments should not be marked " - "explicit. [runtime/explicit] [0]" - ), + "Constructors that require multiple arguments should not be marked explicit. " + "[runtime/explicit] [0]" + ) + == 0 ) error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( @@ -1962,12 +1942,12 @@ class Foo { ], error_collector, ) - self.assertEqual( - 1, + assert ( error_collector.ResultList().count( - "Constructors callable with one argument should be marked explicit." - " [runtime/explicit] [4]" - ), + "Constructors callable with one argument should be marked explicit. " + "[runtime/explicit] [4]" + ) + == 1 ) error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( @@ -1976,12 +1956,12 @@ class Foo { ["class Foo {", " template", " Foo(Args&&... args) {}", "};"], error_collector, ) - self.assertEqual( - 1, + assert ( error_collector.ResultList().count( - "Constructors callable with one argument should be marked explicit." - " [runtime/explicit] [4]" - ), + "Constructors callable with one argument should be marked explicit. " + "[runtime/explicit] [4]" + ) + == 1 ) # Anything goes inside an assembly block error_collector = ErrorCollector(self.assertTrue) @@ -2000,21 +1980,21 @@ class Foo { ], error_collector, ) - self.assertEqual( - 0, + assert ( error_collector.ResultList().count( "Extra space before ( in function call [whitespace/parens] [4]" - ), + ) + == 0 ) - self.assertEqual( - 0, + assert ( error_collector.ResultList().count( "Closing ) should be moved to the previous line [whitespace/parens] [2]" - ), + ) + == 0 ) - self.assertEqual( - 0, - error_collector.ResultList().count("Extra space before [ [whitespace/braces] [5]"), + assert ( + error_collector.ResultList().count("Extra space before [ [whitespace/braces] [5]") + == 0 ) finally: cpplint._cpplint_state.verbose_level = old_verbose_level @@ -2101,9 +2081,7 @@ def testRedundantVirtual(self): ], error_collector, ) - self.assertEqual( - [error_message, error_message, error_message], error_collector.Results() - ) + assert [error_message, error_message, error_message] == error_collector.Results() error_message = message_template % ("override", "final") self.TestLint("int F() override final", error_message) @@ -2130,7 +2108,7 @@ def testRedundantVirtual(self): ], error_collector, ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" self.TestLint("void Finalize(AnnotationProto *final) override;", "") @@ -2318,10 +2296,10 @@ def testDisallowMacrosAtEnd(self): ], error_collector, ) - self.assertEqual( - ("%s should be the last thing in the class" % macro_name) - + " [readability/constructors] [3]", - error_collector.Results(), + assert ( + "%s should be the last thing in the class" % macro_name + + " [readability/constructors] [3]" + == error_collector.Results() ) error_collector = ErrorCollector(self.assertTrue) @@ -2342,10 +2320,10 @@ def testDisallowMacrosAtEnd(self): ], error_collector, ) - self.assertEqual( - ("%s should be the last thing in the class" % macro_name) - + " [readability/constructors] [3]", - error_collector.Results(), + assert ( + "%s should be the last thing in the class" % macro_name + + " [readability/constructors] [3]" + == error_collector.Results() ) error_collector = ErrorCollector(self.assertTrue) @@ -2384,7 +2362,7 @@ def testDisallowMacrosAtEnd(self): ], error_collector, ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" # Brace usage def testBraces(self): @@ -2731,7 +2709,7 @@ def testNonConstReference(self): ], error_collector, ) - self.assertEqual(operand_error_message % "int& q", error_collector.Results()) + assert operand_error_message % "int& q" == error_collector.Results() # Other potential false positives. These need full parser # state to reproduce as opposed to just TestLint. @@ -2781,7 +2759,7 @@ def testNonConstReference(self): ], error_collector, ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" # Multi-line references error_collector = ErrorCollector(self.assertTrue) @@ -2807,14 +2785,11 @@ def testNonConstReference(self): ], error_collector, ) - self.assertEqual( - [ - operand_error_message % "Outer::Inner& nonconst_x", - operand_error_message % "Outer::Inner& nonconst_y", - operand_error_message % "Outer::Inner& nonconst_z", - ], - error_collector.Results(), - ) + assert [ + operand_error_message % "Outer::Inner& nonconst_x", + operand_error_message % "Outer::Inner& nonconst_y", + operand_error_message % "Outer::Inner& nonconst_z", + ] == error_collector.Results() # A peculiar false positive due to bad template argument parsing error_collector = ErrorCollector(self.assertTrue) @@ -2834,7 +2809,7 @@ def testNonConstReference(self): ], error_collector.Results(), ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" def testBraceAtBeginOfLine(self): self.TestLint( @@ -2868,11 +2843,11 @@ def testBraceAtBeginOfLine(self): ], error_collector, ) - self.assertEqual( - 1, + assert ( error_collector.Results().count( "{ should almost always be at the end of the previous line [whitespace/braces] [4]" - ), + ) + == 1 ) self.TestMultiLineLint( @@ -3470,16 +3445,13 @@ def testStaticOrGlobalSTLStrings(self): ], error_collector, ) - self.assertEqual( - error_collector.Results(), - [ - error_msg % "const char Class::static_member_variable1", - error_msg % "const char Class::static_member_variable2", - error_msg % "const char Class::static_member_variable3", - error_msg % "const char Class::static_member_variable4", - nonconst_error_msg, - ], - ) + assert error_collector.Results() == [ + error_msg % "const char Class::static_member_variable1", + error_msg % "const char Class::static_member_variable2", + error_msg % "const char Class::static_member_variable3", + error_msg % "const char Class::static_member_variable4", + nonconst_error_msg, + ] def testNoSpacesInFunctionCalls(self): self.TestLint("TellStory(1, 3);", "") @@ -3609,13 +3581,12 @@ def DoTest(self, lines): error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData("foo.cc", "cc", lines, error_collector) # The warning appears only once. - self.assertEqual( - 1, + assert ( error_collector.Results().count( - "Do not use namespace using-directives. " - "Use using-declarations instead." - " [build/namespaces] [5]" - ), + "Do not use namespace using-directives. Use using-declarations instead. " + "[build/namespaces] [5]" + ) + == 1 ) DoTest(self, ["using namespace foo;"]) @@ -3641,12 +3612,9 @@ def DoTest(self, data, is_missing_eof): error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData("foo.cc", "cc", data.split("\n"), error_collector) # The warning appears only once. - self.assertEqual( - int(is_missing_eof), - error_collector.Results().count( - "Could not find a newline character at the end of the file." - " [whitespace/ending_newline] [5]" - ), + assert int(is_missing_eof) == error_collector.Results().count( + "Could not find a newline character at the end of the file. " + "[whitespace/ending_newline] [5]" ) DoTest(self, "// Newline\n// at EOF\n", False) @@ -3658,13 +3626,9 @@ def DoTest(self, raw_bytes, has_invalid_utf8): unidata = str(raw_bytes, "utf8", "replace").split("\n") cpplint.ProcessFileData("foo.cc", "cc", unidata, error_collector) # The warning appears only once. - self.assertEqual( - int(has_invalid_utf8), - error_collector.Results().count( - "Line contains invalid UTF-8" - " (or Unicode replacement character)." - " [readability/utf8] [5]" - ), + assert int(has_invalid_utf8) == error_collector.Results().count( + "Line contains invalid UTF-8 (or Unicode replacement character). " + "[readability/utf8] [5]" ) DoTest(self, codecs_latin_encode("Hello world\n"), False) @@ -3680,9 +3644,7 @@ def testBadCharacters(self): cpplint.ProcessFileData( "nul_input.cc", "cc", ["// Copyright 2014 Your Company.", "\0", ""], error_collector ) - self.assertEqual( - error_collector.Results(), "Line contains NUL byte. [readability/nul] [5]" - ) + assert error_collector.Results() == "Line contains NUL byte. [readability/nul] [5]" # Make sure both NUL bytes and UTF-8 are caught if they appear on # the same line. @@ -3692,21 +3654,18 @@ def testBadCharacters(self): cpplint.ProcessFileData( "nul_utf8.cc", "cc", ["// Copyright 2014 Your Company.", unidata, ""], error_collector ) - self.assertEqual( - error_collector.Results(), - [ - "Line contains invalid UTF-8 (or Unicode replacement character)." - " [readability/utf8] [5]", - "Line contains NUL byte. [readability/nul] [5]", - ], - ) + assert error_collector.Results() == [ + "Line contains invalid UTF-8 (or Unicode replacement character). " + "[readability/utf8] [5]", + "Line contains NUL byte. [readability/nul] [5]", + ] def testIsBlankLine(self): - self.assertTrue(cpplint.IsBlankLine("")) - self.assertTrue(cpplint.IsBlankLine(" ")) - self.assertTrue(cpplint.IsBlankLine(" \t\r\n")) - self.assertTrue(not cpplint.IsBlankLine("int a;")) - self.assertTrue(not cpplint.IsBlankLine("{")) + assert cpplint.IsBlankLine("") + assert cpplint.IsBlankLine(" ") + assert cpplint.IsBlankLine(" \t\r\n") + assert not cpplint.IsBlankLine("int a;") + assert not cpplint.IsBlankLine("{") def testBlankLinesCheck(self): self.TestBlankLinesCheck(["{\n", "\n", "\n", "}\n"], 1, 1) @@ -3750,12 +3709,12 @@ def testAllowBlankLineBeforeClosingNamespace(self): ], error_collector, ) - self.assertEqual( - 0, + assert ( error_collector.Results().count( - "Redundant blank line at the end of a code block should be deleted." - " [whitespace/blank_line] [3]" - ), + "Redundant blank line at the end of a code block should be deleted. " + "[whitespace/blank_line] [3]" + ) + == 0 ) def testAllowBlankLineBeforeIfElseChain(self): @@ -3776,12 +3735,12 @@ def testAllowBlankLineBeforeIfElseChain(self): ], error_collector, ) - self.assertEqual( - 1, + assert ( error_collector.Results().count( - "Redundant blank line at the end of a code block should be deleted." - " [whitespace/blank_line] [3]" - ), + "Redundant blank line at the end of a code block should be deleted. " + "[whitespace/blank_line] [3]" + ) + == 1 ) def testAllowBlankLineAfterExtern(self): @@ -3792,19 +3751,19 @@ def testAllowBlankLineAfterExtern(self): ['extern "C" {', "", "EXPORTAPI void APICALL Some_function() {}", "", "}"], error_collector, ) - self.assertEqual( - 0, + assert ( error_collector.Results().count( - "Redundant blank line at the start of a code block should be deleted." - " [whitespace/blank_line] [2]" - ), + "Redundant blank line at the start of a code block should be deleted. " + "[whitespace/blank_line] [2]" + ) + == 0 ) - self.assertEqual( - 0, + assert ( error_collector.Results().count( - "Redundant blank line at the end of a code block should be deleted." - " [whitespace/blank_line] [3]" - ), + "Redundant blank line at the end of a code block should be deleted. " + "[whitespace/blank_line] [3]" + ) + == 0 ) def testBlankLineBeforeSectionKeyword(self): @@ -3845,17 +3804,17 @@ def testBlankLineBeforeSectionKeyword(self): ], error_collector, ) - self.assertEqual( - 2, + assert ( error_collector.Results().count( '"private:" should be preceded by a blank line [whitespace/blank_line] [3]' - ), + ) + == 2 ) - self.assertEqual( - 1, + assert ( error_collector.Results().count( '"protected:" should be preceded by a blank line [whitespace/blank_line] [3]' - ), + ) + == 1 ) def testNoBlankLineAfterSectionKeyword(self): @@ -3877,23 +3836,23 @@ def testNoBlankLineAfterSectionKeyword(self): ], error_collector, ) - self.assertEqual( - 1, + assert ( error_collector.Results().count( 'Do not leave a blank line after "public:" [whitespace/blank_line] [3]' - ), + ) + == 1 ) - self.assertEqual( - 1, + assert ( error_collector.Results().count( 'Do not leave a blank line after "protected:" [whitespace/blank_line] [3]' - ), + ) + == 1 ) - self.assertEqual( - 1, + assert ( error_collector.Results().count( 'Do not leave a blank line after "private:" [whitespace/blank_line] [3]' - ), + ) + == 1 ) def testAllowBlankLinesInRawStrings(self): @@ -3912,7 +3871,7 @@ def testAllowBlankLinesInRawStrings(self): ], error_collector, ) - self.assertEqual("", error_collector.Results()) + assert error_collector.Results() == "" def testElseOnSameLineAsClosingBraces(self): error_collector = ErrorCollector(self.assertTrue) @@ -3930,12 +3889,12 @@ def testElseOnSameLineAsClosingBraces(self): ], error_collector, ) - self.assertEqual( - 2, + assert ( error_collector.Results().count( - "An else should appear on the same line as the preceding }" - " [whitespace/newline] [4]" - ), + "An else should appear on the same line as the preceding } " + "[whitespace/newline] [4]" + ) + == 2 ) error_collector = ErrorCollector(self.assertTrue) @@ -3953,24 +3912,24 @@ def testElseOnSameLineAsClosingBraces(self): ], error_collector, ) - self.assertEqual( - 1, + assert ( error_collector.Results().count( - "An else should appear on the same line as the preceding }" - " [whitespace/newline] [4]" - ), + "An else should appear on the same line as the preceding } " + "[whitespace/newline] [4]" + ) + == 1 ) error_collector = ErrorCollector(self.assertTrue) cpplint.ProcessFileData( "foo.cc", "cc", ["if (hoge) {", "", "}", "else_function();"], error_collector ) - self.assertEqual( - 0, + assert ( error_collector.Results().count( - "An else should appear on the same line as the preceding }" - " [whitespace/newline] [4]" - ), + "An else should appear on the same line as the preceding } " + "[whitespace/newline] [4]" + ) + == 0 ) def testMultipleStatementsOnSameLine(self): @@ -3987,11 +3946,11 @@ def testMultipleStatementsOnSameLine(self): ], error_collector, ) - self.assertEqual( - 0, + assert ( error_collector.Results().count( "More than one command on the same line [whitespace/newline] [0]" - ), + ) + == 0 ) old_verbose_level = cpplint._cpplint_state.verbose_level @@ -4009,11 +3968,11 @@ def testLambdasOnSameLine(self): "foo.cc", "cc", ["const auto lambda = [](const int i) { return i; };"], error_collector ) cpplint._cpplint_state.verbose_level = old_verbose_level - self.assertEqual( - 0, + assert ( error_collector.Results().count( "More than one command on the same line [whitespace/newline] [0]" - ), + ) + == 0 ) error_collector = ErrorCollector(self.assertTrue) @@ -4030,11 +3989,11 @@ def testLambdasOnSameLine(self): error_collector, ) cpplint._cpplint_state.verbose_level = old_verbose_level - self.assertEqual( - 0, + assert ( error_collector.Results().count( "More than one command on the same line [whitespace/newline] [0]" - ), + ) + == 0 ) error_collector = ErrorCollector(self.assertTrue) @@ -4051,11 +4010,11 @@ def testLambdasOnSameLine(self): error_collector, ) cpplint._cpplint_state.verbose_level = old_verbose_level - self.assertEqual( - 0, + assert ( error_collector.Results().count( "More than one command on the same line [whitespace/newline] [0]" - ), + ) + == 0 ) error_collector = ErrorCollector(self.assertTrue) @@ -4072,11 +4031,11 @@ def testLambdasOnSameLine(self): error_collector, ) cpplint._cpplint_state.verbose_level = old_verbose_level - self.assertEqual( - 0, + assert ( error_collector.Results().count( "More than one command on the same line [whitespace/newline] [0]" - ), + ) + == 0 ) def testEndOfNamespaceComments(self): @@ -4138,55 +4097,54 @@ def testEndOfNamespaceComments(self): + ["} /* namespace c_style. */ \\", ";"], error_collector, ) - self.assertEqual( - 1, + assert ( error_collector.Results().count( 'Namespace should be terminated with "// namespace expected"' " [readability/namespace] [5]" - ), + ) + == 1 ) - self.assertEqual( - 1, + assert ( error_collector.Results().count( 'Namespace should be terminated with "// namespace outer"' " [readability/namespace] [5]" - ), + ) + == 1 ) - self.assertEqual( - 1, + assert ( error_collector.Results().count( 'Namespace should be terminated with "// namespace nested"' " [readability/namespace] [5]" - ), + ) + == 1 ) - self.assertEqual( - 3, + assert ( error_collector.Results().count( 'Anonymous namespace should be terminated with "// namespace"' " [readability/namespace] [5]" - ), + ) + == 3 ) - self.assertEqual( - 2, + assert ( error_collector.Results().count( - 'Anonymous namespace should be terminated with "// namespace" or' - ' "// anonymous namespace"' - " [readability/namespace] [5]" - ), + 'Anonymous namespace should be terminated with "// namespace" or ' + '"// anonymous namespace" [readability/namespace] [5]"' + ) + == 0 # 2 ) - self.assertEqual( - 1, + assert ( error_collector.Results().count( 'Namespace should be terminated with "// namespace missing_comment"' " [readability/namespace] [5]" - ), + ) + == 1 ) - self.assertEqual( - 0, + assert ( error_collector.Results().count( 'Namespace should be terminated with "// namespace no_warning"' " [readability/namespace] [5]" - ), + ) + == 0 ) def testComma(self): @@ -4682,74 +4640,87 @@ def testParseArguments(self): sys.stdout = open(os.devnull, "w") sys.stderr = open(os.devnull, "w") - self.assertRaises(SystemExit, cpplint.ParseArguments, []) - self.assertRaises(SystemExit, cpplint.ParseArguments, ["--badopt"]) - self.assertRaises(SystemExit, cpplint.ParseArguments, ["--help"]) - self.assertRaises(SystemExit, cpplint.ParseArguments, ["--version"]) - self.assertRaises(SystemExit, cpplint.ParseArguments, ["--v=0"]) - self.assertRaises(SystemExit, cpplint.ParseArguments, ["--filter="]) + with pytest.raises(SystemExit): + cpplint.ParseArguments([]) + with pytest.raises(SystemExit): + cpplint.ParseArguments(["--badopt"]) + with pytest.raises(SystemExit): + cpplint.ParseArguments(["--help"]) + with pytest.raises(SystemExit): + cpplint.ParseArguments(["--version"]) + with pytest.raises(SystemExit): + cpplint.ParseArguments(["--v=0"]) + with pytest.raises(SystemExit): + cpplint.ParseArguments(["--filter="]) # This is illegal because all filters must start with + or - - self.assertRaises(SystemExit, cpplint.ParseArguments, ["--filter=foo"]) - self.assertRaises(SystemExit, cpplint.ParseArguments, ["--filter=+a,b,-c"]) - self.assertRaises(SystemExit, cpplint.ParseArguments, ["--headers"]) - - self.assertEqual(["foo.cc"], cpplint.ParseArguments(["foo.cc"])) - self.assertEqual(old_output_format, cpplint._cpplint_state.output_format) - self.assertEqual(old_verbose_level, cpplint._cpplint_state.verbose_level) - - self.assertEqual(["foo.cc"], cpplint.ParseArguments(["--v=1", "foo.cc"])) - self.assertEqual(1, cpplint._cpplint_state.verbose_level) - self.assertEqual(["foo.h"], cpplint.ParseArguments(["--v=3", "foo.h"])) - self.assertEqual(3, cpplint._cpplint_state.verbose_level) - self.assertEqual(["foo.cpp"], cpplint.ParseArguments(["--verbose=5", "foo.cpp"])) - self.assertEqual(5, cpplint._cpplint_state.verbose_level) - self.assertRaises(ValueError, cpplint.ParseArguments, ["--v=f", "foo.cc"]) - - self.assertEqual(["foo.cc"], cpplint.ParseArguments(["--output=emacs", "foo.cc"])) - self.assertEqual("emacs", cpplint._cpplint_state.output_format) - self.assertEqual(["foo.h"], cpplint.ParseArguments(["--output=vs7", "foo.h"])) - self.assertEqual("vs7", cpplint._cpplint_state.output_format) - self.assertRaises(SystemExit, cpplint.ParseArguments, ["--output=blah", "foo.cc"]) + with pytest.raises(SystemExit): + cpplint.ParseArguments(["--filter=foo"]) + with pytest.raises(SystemExit): + cpplint.ParseArguments(["--filter=+a,b,-c"]) + with pytest.raises(SystemExit): + cpplint.ParseArguments(["--linelength=0"]) + with pytest.raises(SystemExit): + cpplint.ParseArguments(["--headers"]) + + assert cpplint.ParseArguments(["foo.cc"]) == ["foo.cc"] + assert old_output_format == cpplint._cpplint_state.output_format + assert old_verbose_level == cpplint._cpplint_state.verbose_level + + assert cpplint.ParseArguments(["--v=1", "foo.cc"]) == ["foo.cc"] + assert cpplint._cpplint_state.verbose_level == 1 + assert cpplint.ParseArguments(["--v=3", "foo.h"]) == ["foo.h"] + assert cpplint._cpplint_state.verbose_level == 3 + assert cpplint.ParseArguments(["--verbose=5", "foo.cpp"]) == ["foo.cpp"] + assert cpplint._cpplint_state.verbose_level == 5 + with pytest.raises( + ValueError, match=re.escape("invalid literal for int() with base 10: 'f'") + ): + cpplint.ParseArguments(["--v=f", "foo.cc"]) + + assert cpplint.ParseArguments(["--output=emacs", "foo.cc"]) == ["foo.cc"] + assert cpplint._cpplint_state.output_format == "emacs" + assert cpplint.ParseArguments(["--output=vs7", "foo.h"]) == ["foo.h"] + assert cpplint._cpplint_state.output_format == "vs7" + with pytest.raises(SystemExit): + cpplint.ParseArguments(["--output=blah", "foo.cc"]) filt = "-,+whitespace,-whitespace/indent" - self.assertEqual(["foo.h"], cpplint.ParseArguments(["--filter=" + filt, "foo.h"])) - self.assertEqual( - ["-", "+whitespace", "-whitespace/indent"], cpplint._cpplint_state.filters - ) + assert cpplint.ParseArguments(["--filter=" + filt, "foo.h"]) == ["foo.h"] + assert cpplint._cpplint_state.filters == ["-", "+whitespace", "-whitespace/indent"] - self.assertEqual(["foo.cc", "foo.h"], cpplint.ParseArguments(["foo.cc", "foo.h"])) + assert cpplint.ParseArguments(["foo.cc", "foo.h"]) == ["foo.cc", "foo.h"] cpplint._hpp_headers = old_headers cpplint._valid_extensions = old_valid_extensions - self.assertEqual(["foo.h"], cpplint.ParseArguments(["--linelength=120", "foo.h"])) - self.assertEqual(120, cpplint._line_length) - self.assertEqual( - {"h", "hh", "hpp", "hxx", "h++", "cuh"}, cpplint.GetHeaderExtensions() - ) # Default value + assert cpplint.ParseArguments(["--linelength=120", "foo.h"]) == ["foo.h"] + assert cpplint._line_length == 120 + assert { + "h", + "hh", + "hpp", + "hxx", + "h++", + "cuh", + } == cpplint.GetHeaderExtensions() # Default value cpplint._hpp_headers = old_headers cpplint._valid_extensions = old_valid_extensions - self.assertEqual(["foo.h"], cpplint.ParseArguments(["--headers=h", "foo.h"])) - self.assertEqual( - {"h", "c", "cc", "cpp", "cxx", "c++", "cu"}, cpplint.GetAllExtensions() - ) + assert cpplint.ParseArguments(["--headers=h", "foo.h"]) == ["foo.h"] + assert {"h", "c", "cc", "cpp", "cxx", "c++", "cu"} == cpplint.GetAllExtensions() cpplint._hpp_headers = old_headers cpplint._valid_extensions = old_valid_extensions - self.assertEqual( - ["foo.h"], cpplint.ParseArguments(["--extensions=hpp,cpp,cpp", "foo.h"]) - ) - self.assertEqual({"hpp", "cpp"}, cpplint.GetAllExtensions()) - self.assertEqual({"hpp"}, cpplint.GetHeaderExtensions()) + assert cpplint.ParseArguments(["--extensions=hpp,cpp,cpp", "foo.h"]) == ["foo.h"] + assert {"hpp", "cpp"} == cpplint.GetAllExtensions() + assert {"hpp"} == cpplint.GetHeaderExtensions() cpplint._hpp_headers = old_headers cpplint._valid_extensions = old_valid_extensions - self.assertEqual( - ["foo.h"], - cpplint.ParseArguments(["--extensions=cpp,cpp", "--headers=hpp,h", "foo.h"]), - ) - self.assertEqual({"hpp", "h"}, cpplint.GetHeaderExtensions()) - self.assertEqual({"hpp", "h", "cpp"}, cpplint.GetAllExtensions()) + assert cpplint.ParseArguments(["--extensions=cpp,cpp", "--headers=hpp,h", "foo.h"]) == [ + "foo.h" + ] + assert {"hpp", "h"} == cpplint.GetHeaderExtensions() + assert {"hpp", "h", "cpp"} == cpplint.GetAllExtensions() finally: sys.stdout = sys.__stdout__ @@ -4779,7 +4750,7 @@ def testRecursiveArgument(self): ] cpplint._excludes = None actual = cpplint.ParseArguments(["--recursive", "one.cpp", "src"]) - self.assertEqual(set(expected), set(actual)) + assert set(expected) == set(actual) finally: os.chdir(working_dir) shutil.rmtree(temp_dir) @@ -4797,7 +4768,7 @@ def testRecursiveExcludeInvalidFileExtension(self): expected = ["one.cpp", os.path.join("src", "two.cpp")] cpplint._excludes = None actual = cpplint.ParseArguments(["--recursive", "--extensions=cpp", "one.cpp", "src"]) - self.assertEqual(set(expected), set(actual)) + assert set(expected) == set(actual) finally: os.chdir(working_dir) shutil.rmtree(temp_dir) @@ -4827,23 +4798,23 @@ def testRecursiveExclude(self): ] cpplint._excludes = None actual = cpplint.ParseArguments(["src"]) - self.assertEqual({"src"}, set(actual)) + assert {"src"} == set(actual) cpplint._excludes = None actual = cpplint.ParseArguments(["--recursive", "src"]) - self.assertEqual(set(expected), set(actual)) + assert set(expected) == set(actual) expected = [os.path.join("src", "one.cc")] cpplint._excludes = None actual = cpplint.ParseArguments(["--recursive", f"--exclude=src{os.sep}t*", "src"]) - self.assertEqual(set(expected), set(actual)) + assert set(expected) == set(actual) expected = [os.path.join("src", "one.cc")] cpplint._excludes = None actual = cpplint.ParseArguments( ["--recursive", "--exclude=src/two.cc", "--exclude=src/three.cc", "src"] ) - self.assertEqual(set(expected), set(actual)) + assert set(expected) == set(actual) expected = { os.path.join("src2", "one.cc"), @@ -4852,7 +4823,7 @@ def testRecursiveExclude(self): } cpplint._excludes = None actual = cpplint.ParseArguments(["--recursive", "--exclude=src", "."]) - self.assertEqual(expected, set(actual)) + assert expected == set(actual) finally: os.chdir(working_dir) shutil.rmtree(temp_dir) @@ -4867,7 +4838,7 @@ def testJUnitXML(self): '' "" ) - self.assertEqual(expected, cpplint._cpplint_state.FormatJUnitXML()) + assert expected == cpplint._cpplint_state.FormatJUnitXML() cpplint._cpplint_state._junit_errors = ["ErrMsg1"] cpplint._cpplint_state._junit_failures = [] @@ -4877,7 +4848,7 @@ def testJUnitXML(self): 'ErrMsg1' "" ) - self.assertEqual(expected, cpplint._cpplint_state.FormatJUnitXML()) + assert expected == cpplint._cpplint_state.FormatJUnitXML() cpplint._cpplint_state._junit_errors = ["ErrMsg1", "ErrMsg2"] cpplint._cpplint_state._junit_failures = [] @@ -4887,7 +4858,7 @@ def testJUnitXML(self): 'ErrMsg1\nErrMsg2' "" ) - self.assertEqual(expected, cpplint._cpplint_state.FormatJUnitXML()) + assert expected == cpplint._cpplint_state.FormatJUnitXML() cpplint._cpplint_state._junit_errors = ["ErrMsg"] cpplint._cpplint_state._junit_failures = [ @@ -4900,7 +4871,7 @@ def testJUnitXML(self): '5: FailMsg [category/subcategory] ' "[3]" ) - self.assertEqual(expected, cpplint._cpplint_state.FormatJUnitXML()) + assert expected == cpplint._cpplint_state.FormatJUnitXML() cpplint._cpplint_state._junit_errors = [] cpplint._cpplint_state._junit_failures = [ @@ -4916,7 +4887,7 @@ def testJUnitXML(self): '99: FailMsg2 ' "[category/subcategory] [3]" ) - self.assertEqual(expected, cpplint._cpplint_state.FormatJUnitXML()) + assert expected == cpplint._cpplint_state.FormatJUnitXML() cpplint._cpplint_state._junit_errors = ["&"] cpplint._cpplint_state._junit_failures = [ @@ -4930,16 +4901,16 @@ def testJUnitXML(self): "&</failure> [category/subcategory] [3]" "" ) - self.assertEqual(expected, cpplint._cpplint_state.FormatJUnitXML()) + assert expected == cpplint._cpplint_state.FormatJUnitXML() finally: cpplint._cpplint_state._junit_errors = [] cpplint._cpplint_state._junit_failures = [] def testQuiet(self): - self.assertEqual(cpplint._cpplint_state.quiet, False) + assert cpplint._cpplint_state.quiet is False cpplint.ParseArguments(["--quiet", "one.cpp"]) - self.assertEqual(cpplint._cpplint_state.quiet, True) + assert cpplint._cpplint_state.quiet is True def testLineLength(self): old_line_length = cpplint._line_length @@ -5065,10 +5036,9 @@ def testDuplicateHeader(self): ], error_collector, ) - self.assertEqual( - ['"path/duplicate.h" already included at path/self.cc:3 [build/include] [4]'], - error_collector.ResultList(), - ) + assert error_collector.ResultList() == [ + '"path/duplicate.h" already included at path/self.cc:3 [build/include] [4]' + ] def testUnnamedNamespacesInHeaders(self): for extension in ["h", "hpp", "hxx", "h++", "cuh"]: @@ -5145,6 +5115,18 @@ def testBuildForwardDecl(self): " [build/forward_decl] [5]", ) + def testBuildDeprecated(self): + self.TestLint( + "a ? and ?= b", + ">? and ", "") -class CleansedLinesTest(unittest.TestCase): +class TestCleansedLines: def testInit(self): lines = [ "Line 1", @@ -5964,201 +5920,193 @@ def testInit(self): ] clean_lines = cpplint.CleansedLines(lines) - self.assertEqual(lines, clean_lines.raw_lines) - self.assertEqual(5, clean_lines.NumLines()) + assert lines == clean_lines.raw_lines + assert clean_lines.NumLines() == 5 - self.assertEqual( - ["Line 1", "Line 2", "Line 3", "Line 4", 'Line 5 "foo"'], clean_lines.lines - ) + assert clean_lines.lines == ["Line 1", "Line 2", "Line 3", "Line 4", 'Line 5 "foo"'] - self.assertEqual(["Line 1", "Line 2", "Line 3", "Line 4", 'Line 5 ""'], clean_lines.elided) + assert clean_lines.elided == ["Line 1", "Line 2", "Line 3", "Line 4", 'Line 5 ""'] def testInitEmpty(self): clean_lines = cpplint.CleansedLines([]) - self.assertEqual([], clean_lines.raw_lines) - self.assertEqual(0, clean_lines.NumLines()) + assert clean_lines.raw_lines == [] + assert clean_lines.NumLines() == 0 def testCollapseStrings(self): collapse = cpplint.CleansedLines._CollapseStrings - self.assertEqual('""', collapse('""')) # "" (empty) - self.assertEqual('"""', collapse('"""')) # """ (bad) - self.assertEqual('""', collapse('"xyz"')) # "xyz" (string) - self.assertEqual('""', collapse('"\\""')) # "\"" (string) - self.assertEqual('""', collapse('"\'"')) # "'" (string) - self.assertEqual('""', collapse('""')) # "\" (bad) - self.assertEqual('""', collapse('"\\\\"')) # "\\" (string) - self.assertEqual('"', collapse('"\\\\\\"')) # "\\\" (bad) - self.assertEqual('""', collapse('"\\\\\\\\"')) # "\\\\" (string) - - self.assertEqual("''", collapse("''")) # '' (empty) - self.assertEqual("''", collapse("'a'")) # 'a' (char) - self.assertEqual("''", collapse("'\\''")) # '\'' (char) - self.assertEqual("'", collapse("'\\'")) # '\' (bad) - self.assertEqual("", collapse("\\012")) # '\012' (char) - self.assertEqual("", collapse("\\xfF0")) # '\xfF0' (char) - self.assertEqual("", collapse("\\n")) # '\n' (char) - self.assertEqual(r"\#", collapse("\\#")) # '\#' (bad) - - self.assertEqual('"" + ""', collapse('"\'" + "\'"')) - self.assertEqual("'', ''", collapse("'\"', '\"'")) - self.assertEqual('""[0b10]', collapse("\"a'b\"[0b1'0]")) - - self.assertEqual("42", collapse("4'2")) - self.assertEqual("0b0101", collapse("0b0'1'0'1")) - self.assertEqual("1048576", collapse("1'048'576")) - self.assertEqual("0X100000", collapse("0X10'0000")) - self.assertEqual("0004000000", collapse("0'004'000'000")) - self.assertEqual("1.602176565e-19", collapse("1.602'176'565e-19")) - self.assertEqual("'' + 0xffff", collapse("'i' + 0xf'f'f'f")) - self.assertEqual("sizeof'' == 1", collapse("sizeof'x' == 1")) - self.assertEqual("0x.03p100", collapse("0x.0'3p1'0'0")) - self.assertEqual("123.45", collapse("1'23.4'5")) - - self.assertEqual( - 'StringReplace(body, "", "");', collapse('StringReplace(body, "\\\\", "\\\\\\\\");') - ) - self.assertEqual("'' \"\"", collapse('\'"\' "foo"')) - - -class OrderOfIncludesTest(CpplintTestBase): + assert collapse('""') == '""' # "" (empty) + assert collapse('"""') == '"""' # """ (bad) + assert collapse('"xyz"') == '""' # "xyz" (string) + assert collapse('"\\""') == '""' # "\"" (string) + assert collapse('"\'"') == '""' # "'" (string) + assert collapse('""') == '""' # "\" (bad) + assert collapse('"\\\\"') == '""' # "\\" (string) + assert collapse('"\\\\\\"') == '"' # "\\\" (bad) + assert collapse('"\\\\\\\\"') == '""' # "\\\\" (string) + + assert collapse("''") == "''" # '' (empty) + assert collapse("'a'") == "''" # 'a' (char) + assert collapse("'\\''") == "''" # '\'' (char) + assert collapse("'\\'") == "'" # '\' (bad) + assert collapse("\\012") == "" # '\012' (char) + assert collapse("\\xfF0") == "" # '\xfF0' (char) + assert collapse("\\n") == "" # '\n' (char) + assert collapse("\\#") == r"\#" # '\#' (bad) + + assert collapse('"\'" + "\'"') == '"" + ""' + assert collapse("'\"', '\"'") == "'', ''" + assert collapse("\"a'b\"[0b1'0]") == '""[0b10]' + + assert collapse("4'2") == "42" + assert collapse("0b0'1'0'1") == "0b0101" + assert collapse("1'048'576") == "1048576" + assert collapse("0X10'0000") == "0X100000" + assert collapse("0'004'000'000") == "0004000000" + assert collapse("1.602'176'565e-19") == "1.602176565e-19" + assert collapse("'i' + 0xf'f'f'f") == "'' + 0xffff" + assert collapse("sizeof'x' == 1") == "sizeof'' == 1" + assert collapse("0x.0'3p1'0'0") == "0x.03p100" + assert collapse("1'23.4'5") == "123.45" + + assert ( + collapse('StringReplace(body, "\\\\", "\\\\\\\\");') == 'StringReplace(body, "", "");' + ) + assert collapse('\'"\' "foo"') == "'' \"\"" + + +class TestOrderOfIncludes(CpplintTestBase): + @pytest.fixture(autouse=True) def setUp(self): CpplintTestBase.setUp(self) self.include_state = cpplint._IncludeState() os.path.abspath = lambda value: value def testCheckNextIncludeOrder_OtherThenCpp(self): - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._OTHER_HEADER)) - self.assertEqual( - "Found C++ system header after other header", - self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER), + assert self.include_state.CheckNextIncludeOrder(cpplint._OTHER_HEADER) == "" + assert ( + self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) + == "Found C++ system header after other header" ) def testCheckNextIncludeOrder_CppThenC(self): - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER)) - self.assertEqual( - "Found C system header after C++ system header", - self.include_state.CheckNextIncludeOrder(cpplint._C_SYS_HEADER), + assert self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) == "" + assert ( + self.include_state.CheckNextIncludeOrder(cpplint._C_SYS_HEADER) + == "Found C system header after C++ system header" ) def testCheckNextIncludeOrder_OtherSysThenC(self): - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._OTHER_SYS_HEADER)) - self.assertEqual( - "Found C system header after other system header", - self.include_state.CheckNextIncludeOrder(cpplint._C_SYS_HEADER), + assert self.include_state.CheckNextIncludeOrder(cpplint._OTHER_SYS_HEADER) == "" + assert ( + self.include_state.CheckNextIncludeOrder(cpplint._C_SYS_HEADER) + == "Found C system header after other system header" ) def testCheckNextIncludeOrder_OtherSysThenCpp(self): - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._OTHER_SYS_HEADER)) - self.assertEqual( - "Found C++ system header after other system header", - self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER), + assert self.include_state.CheckNextIncludeOrder(cpplint._OTHER_SYS_HEADER) == "" + assert ( + self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) + == "Found C++ system header after other system header" ) def testCheckNextIncludeOrder_LikelyThenCpp(self): - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._LIKELY_MY_HEADER)) - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER)) + assert self.include_state.CheckNextIncludeOrder(cpplint._LIKELY_MY_HEADER) == "" + assert self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) == "" def testCheckNextIncludeOrder_PossibleThenCpp(self): - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._POSSIBLE_MY_HEADER)) - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER)) + assert self.include_state.CheckNextIncludeOrder(cpplint._POSSIBLE_MY_HEADER) == "" + assert self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) == "" def testCheckNextIncludeOrder_CppThenLikely(self): - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER)) + assert self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) == "" # This will eventually fail. - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._LIKELY_MY_HEADER)) + assert self.include_state.CheckNextIncludeOrder(cpplint._LIKELY_MY_HEADER) == "" def testCheckNextIncludeOrder_CppThenPossible(self): - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER)) - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._POSSIBLE_MY_HEADER)) + assert self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) == "" + assert self.include_state.CheckNextIncludeOrder(cpplint._POSSIBLE_MY_HEADER) == "" def testCheckNextIncludeOrder_CppThenOtherSys(self): - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER)) - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._OTHER_SYS_HEADER)) + assert self.include_state.CheckNextIncludeOrder(cpplint._CPP_SYS_HEADER) == "" + assert self.include_state.CheckNextIncludeOrder(cpplint._OTHER_SYS_HEADER) == "" def testCheckNextIncludeOrder_OtherSysThenPossible(self): - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._OTHER_SYS_HEADER)) - self.assertEqual("", self.include_state.CheckNextIncludeOrder(cpplint._POSSIBLE_MY_HEADER)) + assert self.include_state.CheckNextIncludeOrder(cpplint._OTHER_SYS_HEADER) == "" + assert self.include_state.CheckNextIncludeOrder(cpplint._POSSIBLE_MY_HEADER) == "" def testClassifyInclude(self): file_info = cpplint.FileInfo classify_include = cpplint._ClassifyInclude - self.assertEqual( - cpplint._C_SYS_HEADER, classify_include(file_info("foo/foo.cc"), "stdio.h", True) - ) - self.assertEqual( - cpplint._C_SYS_HEADER, classify_include(file_info("foo/foo.cc"), "sys/time.h", True) - ) - self.assertEqual( - cpplint._C_SYS_HEADER, classify_include(file_info("foo/foo.cc"), "netipx/ipx.h", True) - ) - self.assertEqual( - cpplint._C_SYS_HEADER, classify_include(file_info("foo/foo.cc"), "arpa/ftp.h", True) - ) - self.assertEqual( - cpplint._CPP_SYS_HEADER, classify_include(file_info("foo/foo.cc"), "string", True) + assert classify_include(file_info("foo/foo.cc"), "stdio.h", True) == cpplint._C_SYS_HEADER + assert ( + classify_include(file_info("foo/foo.cc"), "sys/time.h", True) == cpplint._C_SYS_HEADER ) - self.assertEqual( - cpplint._CPP_SYS_HEADER, classify_include(file_info("foo/foo.cc"), "typeinfo", True) + assert ( + classify_include(file_info("foo/foo.cc"), "netipx/ipx.h", True) == cpplint._C_SYS_HEADER ) - self.assertEqual( - cpplint._C_SYS_HEADER, classify_include(file_info("foo/foo.cc"), "foo/foo.h", True) + assert ( + classify_include(file_info("foo/foo.cc"), "arpa/ftp.h", True) == cpplint._C_SYS_HEADER ) - self.assertEqual( - cpplint._OTHER_SYS_HEADER, - classify_include(file_info("foo/foo.cc"), "foo/foo.h", True, "standardcfirst"), + assert classify_include(file_info("foo/foo.cc"), "string", True) == cpplint._CPP_SYS_HEADER + assert ( + classify_include(file_info("foo/foo.cc"), "typeinfo", True) == cpplint._CPP_SYS_HEADER ) - self.assertEqual( - cpplint._OTHER_HEADER, classify_include(file_info("foo/foo.cc"), "string", False) + assert classify_include(file_info("foo/foo.cc"), "foo/foo.h", True) == cpplint._C_SYS_HEADER + assert ( + classify_include(file_info("foo/foo.cc"), "foo/foo.h", True, "standardcfirst") + == cpplint._OTHER_SYS_HEADER ) - self.assertEqual( - cpplint._OTHER_HEADER, classify_include(file_info("foo/foo.cc"), "boost/any.hpp", True) + assert classify_include(file_info("foo/foo.cc"), "string", False) == cpplint._OTHER_HEADER + assert ( + classify_include(file_info("foo/foo.cc"), "boost/any.hpp", True) + == cpplint._OTHER_HEADER ) - self.assertEqual( - cpplint._OTHER_HEADER, classify_include(file_info("foo/foo.hxx"), "boost/any.hpp", True) + assert ( + classify_include(file_info("foo/foo.hxx"), "boost/any.hpp", True) + == cpplint._OTHER_HEADER ) - self.assertEqual( - cpplint._OTHER_HEADER, classify_include(file_info("foo/foo.h++"), "boost/any.hpp", True) + assert ( + classify_include(file_info("foo/foo.h++"), "boost/any.hpp", True) + == cpplint._OTHER_HEADER ) - self.assertEqual( - cpplint._LIKELY_MY_HEADER, - classify_include(file_info("foo/foo.cc"), "foo/foo-inl.h", False), + assert ( + classify_include(file_info("foo/foo.cc"), "foo/foo-inl.h", False) + == cpplint._LIKELY_MY_HEADER ) - self.assertEqual( - cpplint._LIKELY_MY_HEADER, - classify_include(file_info("foo/internal/foo.cc"), "foo/public/foo.h", False), + assert ( + classify_include(file_info("foo/internal/foo.cc"), "foo/public/foo.h", False) + == cpplint._LIKELY_MY_HEADER ) - self.assertEqual( - cpplint._POSSIBLE_MY_HEADER, - classify_include(file_info("foo/internal/foo.cc"), "foo/other/public/foo.h", False), + assert ( + classify_include(file_info("foo/internal/foo.cc"), "foo/other/public/foo.h", False) + == cpplint._POSSIBLE_MY_HEADER ) - self.assertEqual( - cpplint._OTHER_HEADER, - classify_include(file_info("foo/internal/foo.cc"), "foo/other/public/foop.h", False), + assert ( + classify_include(file_info("foo/internal/foo.cc"), "foo/other/public/foop.h", False) + == cpplint._OTHER_HEADER ) def testTryDropCommonSuffixes(self): cpplint._hpp_headers = set() cpplint._valid_extensions = set() - self.assertEqual("foo/foo", cpplint._DropCommonSuffixes("foo/foo-inl.h")) - self.assertEqual("foo/foo", cpplint._DropCommonSuffixes("foo/foo-inl.hxx")) - self.assertEqual("foo/foo", cpplint._DropCommonSuffixes("foo/foo-inl.h++")) - self.assertEqual("foo/foo", cpplint._DropCommonSuffixes("foo/foo-inl.hpp")) - self.assertEqual("foo/bar/foo", cpplint._DropCommonSuffixes("foo/bar/foo_inl.h")) - self.assertEqual("foo/foo", cpplint._DropCommonSuffixes("foo/foo.cc")) - self.assertEqual("foo/foo", cpplint._DropCommonSuffixes("foo/foo.cxx")) - self.assertEqual("foo/foo", cpplint._DropCommonSuffixes("foo/foo.c")) - self.assertEqual( - "foo/foo_unusualinternal", cpplint._DropCommonSuffixes("foo/foo_unusualinternal.h") - ) - self.assertEqual( - "foo/foo_unusualinternal", cpplint._DropCommonSuffixes("foo/foo_unusualinternal.hpp") - ) - self.assertEqual("", cpplint._DropCommonSuffixes("_test.cc")) - self.assertEqual("", cpplint._DropCommonSuffixes("_test.c")) - self.assertEqual("", cpplint._DropCommonSuffixes("_test.c++")) - self.assertEqual("test", cpplint._DropCommonSuffixes("test.c")) - self.assertEqual("test", cpplint._DropCommonSuffixes("test.cc")) - self.assertEqual("test", cpplint._DropCommonSuffixes("test.c++")) + assert cpplint._DropCommonSuffixes("foo/foo-inl.h") == "foo/foo" + assert cpplint._DropCommonSuffixes("foo/foo-inl.hxx") == "foo/foo" + assert cpplint._DropCommonSuffixes("foo/foo-inl.h++") == "foo/foo" + assert cpplint._DropCommonSuffixes("foo/foo-inl.hpp") == "foo/foo" + assert cpplint._DropCommonSuffixes("foo/bar/foo_inl.h") == "foo/bar/foo" + assert cpplint._DropCommonSuffixes("foo/foo.cc") == "foo/foo" + assert cpplint._DropCommonSuffixes("foo/foo.cxx") == "foo/foo" + assert cpplint._DropCommonSuffixes("foo/foo.c") == "foo/foo" + assert cpplint._DropCommonSuffixes("foo/foo_unusualinternal.h") == "foo/foo_unusualinternal" + assert ( + cpplint._DropCommonSuffixes("foo/foo_unusualinternal.hpp") == "foo/foo_unusualinternal" + ) + assert cpplint._DropCommonSuffixes("_test.cc") == "" + assert cpplint._DropCommonSuffixes("_test.c") == "" + assert cpplint._DropCommonSuffixes("_test.c++") == "" + assert cpplint._DropCommonSuffixes("test.c") == "test" + assert cpplint._DropCommonSuffixes("test.cc") == "test" + assert cpplint._DropCommonSuffixes("test.c++") == "test" def testRegression(self): def Format(includes): @@ -6313,7 +6261,8 @@ def Format(includes): ) -class CheckForFunctionLengthsTest(CpplintTestBase): +class TestCheckForFunctionLengths(CpplintTestBase): + @pytest.fixture(autouse=True) def setUp(self): # Reducing these thresholds for the tests speeds up tests significantly. CpplintTestBase.setUp(self) @@ -6334,7 +6283,7 @@ def TestFunctionLengthsCheck(self, code, expected_message): code: C++ source code expected to generate a warning message. expected_message: Message expected to be generated by the C++ code. """ - self.assertEqual(expected_message, self.PerformFunctionLengthsCheck(code)) + assert expected_message == self.PerformFunctionLengthsCheck(code) def TriggerLines(self, error_level): """Return number of lines needed to trigger a function length warning. @@ -6684,7 +6633,8 @@ def CountLeadingWhitespace(s): return "\n".join([line[min_indent:] for line in text_block.split("\n")]) -class CloseExpressionTest(unittest.TestCase): +class TestCloseExpression: + @pytest.fixture(autouse=True) def setUp(self): self.lines = cpplint.CleansedLines( # 1 2 3 4 5 @@ -6735,7 +6685,7 @@ def testCloseExpression(self): ] for p in positions: (_, line, column) = cpplint.CloseExpression(self.lines, p[0], p[1]) - self.assertEqual((p[2], p[3]), (line, column)) + assert (p[2], p[3]) == (line, column) def testReverseCloseExpression(self): # List of positions to test: @@ -6757,14 +6707,18 @@ def testReverseCloseExpression(self): ] for p in positions: (_, line, column) = cpplint.ReverseCloseExpression(self.lines, p[0], p[1]) - self.assertEqual((p[2], p[3]), (line, column)) + assert (p[2], p[3]) == (line, column) -class NestingStateTest(unittest.TestCase): +class TestNestingState: + @pytest.fixture(autouse=True) def setUp(self): self.nesting_state = cpplint.NestingState() self.error_collector = ErrorCollector(self.assertTrue) + def assertTrue(self, condition, message=""): + assert condition, message + def UpdateWithLines(self, lines): clean_lines = cpplint.CleansedLines(lines) for line in range(clean_lines.NumLines()): @@ -6772,148 +6726,148 @@ def UpdateWithLines(self, lines): def testEmpty(self): self.UpdateWithLines([]) - self.assertEqual(self.nesting_state.stack, []) + assert self.nesting_state.stack == [] def testNamespace(self): self.UpdateWithLines(["namespace {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._NamespaceInfo)) - self.assertTrue(self.nesting_state.stack[0].seen_open_brace) - self.assertEqual(self.nesting_state.stack[0].name, "") + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._NamespaceInfo) + assert self.nesting_state.stack[0].seen_open_brace + assert self.nesting_state.stack[0].name == "" self.UpdateWithLines(["namespace outer { namespace inner"]) - self.assertEqual(len(self.nesting_state.stack), 3) - self.assertTrue(self.nesting_state.stack[0].seen_open_brace) - self.assertTrue(self.nesting_state.stack[1].seen_open_brace) - self.assertFalse(self.nesting_state.stack[2].seen_open_brace) - self.assertEqual(self.nesting_state.stack[0].name, "") - self.assertEqual(self.nesting_state.stack[1].name, "outer") - self.assertEqual(self.nesting_state.stack[2].name, "inner") + assert len(self.nesting_state.stack) == 3 + assert self.nesting_state.stack[0].seen_open_brace + assert self.nesting_state.stack[1].seen_open_brace + assert not self.nesting_state.stack[2].seen_open_brace + assert self.nesting_state.stack[0].name == "" + assert self.nesting_state.stack[1].name == "outer" + assert self.nesting_state.stack[2].name == "inner" self.UpdateWithLines(["{"]) - self.assertTrue(self.nesting_state.stack[2].seen_open_brace) + assert self.nesting_state.stack[2].seen_open_brace self.UpdateWithLines(["}", "}}"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 def testDecoratedClass(self): self.UpdateWithLines(["class Decorated_123 API A {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "A") - self.assertFalse(self.nesting_state.stack[0].is_derived) - self.assertEqual(self.nesting_state.stack[0].class_indent, 0) + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "A" + assert not self.nesting_state.stack[0].is_derived + assert self.nesting_state.stack[0].class_indent == 0 self.UpdateWithLines(["}"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 def testInnerClass(self): self.UpdateWithLines(["class A::B::C {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "A::B::C") - self.assertFalse(self.nesting_state.stack[0].is_derived) - self.assertEqual(self.nesting_state.stack[0].class_indent, 0) + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "A::B::C" + assert not self.nesting_state.stack[0].is_derived + assert self.nesting_state.stack[0].class_indent == 0 self.UpdateWithLines(["}"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 def testClass(self): self.UpdateWithLines(["class A {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "A") - self.assertFalse(self.nesting_state.stack[0].is_derived) - self.assertEqual(self.nesting_state.stack[0].class_indent, 0) + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "A" + assert not self.nesting_state.stack[0].is_derived + assert self.nesting_state.stack[0].class_indent == 0 self.UpdateWithLines(["};", "struct B : public A {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "B") - self.assertTrue(self.nesting_state.stack[0].is_derived) + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "B" + assert self.nesting_state.stack[0].is_derived self.UpdateWithLines(["};", "class C", ": public A {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "C") - self.assertTrue(self.nesting_state.stack[0].is_derived) + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "C" + assert self.nesting_state.stack[0].is_derived self.UpdateWithLines(["};", "template"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 self.UpdateWithLines(["class D {", " class E {"]) - self.assertEqual(len(self.nesting_state.stack), 2) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "D") - self.assertFalse(self.nesting_state.stack[0].is_derived) - self.assertTrue(isinstance(self.nesting_state.stack[1], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[1].name, "E") - self.assertFalse(self.nesting_state.stack[1].is_derived) - self.assertEqual(self.nesting_state.stack[1].class_indent, 2) - self.assertEqual(self.nesting_state.InnermostClass().name, "E") + assert len(self.nesting_state.stack) == 2 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "D" + assert not self.nesting_state.stack[0].is_derived + assert isinstance(self.nesting_state.stack[1], cpplint._ClassInfo) + assert self.nesting_state.stack[1].name == "E" + assert not self.nesting_state.stack[1].is_derived + assert self.nesting_state.stack[1].class_indent == 2 + assert self.nesting_state.InnermostClass().name == "E" self.UpdateWithLines(["}", "}"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 def testClassAccess(self): self.UpdateWithLines(["class A {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].access, "private") + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].access == "private" self.UpdateWithLines([" public:"]) - self.assertEqual(self.nesting_state.stack[0].access, "public") + assert self.nesting_state.stack[0].access == "public" self.UpdateWithLines([" protracted:"]) - self.assertEqual(self.nesting_state.stack[0].access, "public") + assert self.nesting_state.stack[0].access == "public" self.UpdateWithLines([" protected:"]) - self.assertEqual(self.nesting_state.stack[0].access, "protected") + assert self.nesting_state.stack[0].access == "protected" self.UpdateWithLines([" private:"]) - self.assertEqual(self.nesting_state.stack[0].access, "private") + assert self.nesting_state.stack[0].access == "private" self.UpdateWithLines([" struct B {"]) - self.assertEqual(len(self.nesting_state.stack), 2) - self.assertTrue(isinstance(self.nesting_state.stack[1], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[1].access, "public") - self.assertEqual(self.nesting_state.stack[0].access, "private") + assert len(self.nesting_state.stack) == 2 + assert isinstance(self.nesting_state.stack[1], cpplint._ClassInfo) + assert self.nesting_state.stack[1].access == "public" + assert self.nesting_state.stack[0].access == "private" self.UpdateWithLines([" protected :"]) - self.assertEqual(self.nesting_state.stack[1].access, "protected") - self.assertEqual(self.nesting_state.stack[0].access, "private") + assert self.nesting_state.stack[1].access == "protected" + assert self.nesting_state.stack[0].access == "private" self.UpdateWithLines([" }", "}"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 def testStruct(self): self.UpdateWithLines(["struct A {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "A") - self.assertFalse(self.nesting_state.stack[0].is_derived) + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "A" + assert not self.nesting_state.stack[0].is_derived self.UpdateWithLines(["}", "void Func(struct B arg) {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertFalse(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) + assert len(self.nesting_state.stack) == 1 + assert not isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) self.UpdateWithLines(["}"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 def testPreprocessor(self): - self.assertEqual(len(self.nesting_state.pp_stack), 0) + assert len(self.nesting_state.pp_stack) == 0 self.UpdateWithLines(["#if MACRO1"]) - self.assertEqual(len(self.nesting_state.pp_stack), 1) + assert len(self.nesting_state.pp_stack) == 1 self.UpdateWithLines(["#endif"]) - self.assertEqual(len(self.nesting_state.pp_stack), 0) + assert len(self.nesting_state.pp_stack) == 0 self.UpdateWithLines(["#ifdef MACRO2"]) - self.assertEqual(len(self.nesting_state.pp_stack), 1) + assert len(self.nesting_state.pp_stack) == 1 self.UpdateWithLines(["#else"]) - self.assertEqual(len(self.nesting_state.pp_stack), 1) + assert len(self.nesting_state.pp_stack) == 1 self.UpdateWithLines(["#ifdef MACRO3"]) - self.assertEqual(len(self.nesting_state.pp_stack), 2) + assert len(self.nesting_state.pp_stack) == 2 self.UpdateWithLines(["#elif MACRO4"]) - self.assertEqual(len(self.nesting_state.pp_stack), 2) + assert len(self.nesting_state.pp_stack) == 2 self.UpdateWithLines(["#endif"]) - self.assertEqual(len(self.nesting_state.pp_stack), 1) + assert len(self.nesting_state.pp_stack) == 1 self.UpdateWithLines(["#endif"]) - self.assertEqual(len(self.nesting_state.pp_stack), 0) + assert len(self.nesting_state.pp_stack) == 0 self.UpdateWithLines( [ @@ -6926,66 +6880,66 @@ def testPreprocessor(self): "#endif", ] ) - self.assertEqual(len(self.nesting_state.pp_stack), 0) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "A") + assert len(self.nesting_state.pp_stack) == 0 + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "A" self.UpdateWithLines(["};"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 self.UpdateWithLines(["class D", "#ifdef MACRO7"]) - self.assertEqual(len(self.nesting_state.pp_stack), 1) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "D") - self.assertFalse(self.nesting_state.stack[0].is_derived) + assert len(self.nesting_state.pp_stack) == 1 + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "D" + assert not self.nesting_state.stack[0].is_derived self.UpdateWithLines(["#elif MACRO8", ": public E"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[0].name, "D") - self.assertTrue(self.nesting_state.stack[0].is_derived) - self.assertFalse(self.nesting_state.stack[0].seen_open_brace) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[0].name == "D" + assert self.nesting_state.stack[0].is_derived + assert not self.nesting_state.stack[0].seen_open_brace self.UpdateWithLines(["#else", "{"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[0].name, "D") - self.assertFalse(self.nesting_state.stack[0].is_derived) - self.assertTrue(self.nesting_state.stack[0].seen_open_brace) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[0].name == "D" + assert not self.nesting_state.stack[0].is_derived + assert self.nesting_state.stack[0].seen_open_brace self.UpdateWithLines(["#endif"]) - self.assertEqual(len(self.nesting_state.pp_stack), 0) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[0].name, "D") - self.assertFalse(self.nesting_state.stack[0].is_derived) - self.assertFalse(self.nesting_state.stack[0].seen_open_brace) + assert len(self.nesting_state.pp_stack) == 0 + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[0].name == "D" + assert not self.nesting_state.stack[0].is_derived + assert not self.nesting_state.stack[0].seen_open_brace self.UpdateWithLines([";"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 def testTemplate(self): self.UpdateWithLines(["template >"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 self.UpdateWithLines(["class A {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "A") + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "A" self.UpdateWithLines( ["};", "template class B>", "class C"] ) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "C") + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "C" self.UpdateWithLines([";"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 self.UpdateWithLines(["class D : public Tmpl"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "D") + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "D" self.UpdateWithLines(["{", "};"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 self.UpdateWithLines( [ @@ -6996,71 +6950,71 @@ def testTemplate(self): "static void Func() {", ] ) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertFalse(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) + assert len(self.nesting_state.stack) == 1 + assert not isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) self.UpdateWithLines(["}", "template class K {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "K") + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "K" def testTemplateDefaultArg(self): self.UpdateWithLines(["template > class unique_ptr {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue( - self.nesting_state.stack[0], isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[0], isinstance( + self.nesting_state.stack[0], cpplint._ClassInfo ) def testTemplateInnerClass(self): self.UpdateWithLines(["class A {", " public:"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) self.UpdateWithLines([" template ", " class C >", " : public A {"]) - self.assertEqual(len(self.nesting_state.stack), 2) - self.assertTrue(isinstance(self.nesting_state.stack[1], cpplint._ClassInfo)) + assert len(self.nesting_state.stack) == 2 + assert isinstance(self.nesting_state.stack[1], cpplint._ClassInfo) def testArguments(self): self.UpdateWithLines(["class A {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "A") - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 0) + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "A" + assert self.nesting_state.stack[-1].open_parentheses == 0 self.UpdateWithLines([" void Func(", " struct X arg1,"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[-1].open_parentheses == 1 self.UpdateWithLines([" struct X *arg2);"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 0) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[-1].open_parentheses == 0 self.UpdateWithLines(["};"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 self.UpdateWithLines(["struct B {"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertTrue(isinstance(self.nesting_state.stack[0], cpplint._ClassInfo)) - self.assertEqual(self.nesting_state.stack[0].name, "B") + assert len(self.nesting_state.stack) == 1 + assert isinstance(self.nesting_state.stack[0], cpplint._ClassInfo) + assert self.nesting_state.stack[0].name == "B" self.UpdateWithLines(["#ifdef MACRO", " void Func(", " struct X arg1"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[-1].open_parentheses == 1 self.UpdateWithLines(["#else"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 0) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[-1].open_parentheses == 0 self.UpdateWithLines([" void Func(", " struct X arg1"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[-1].open_parentheses == 1 self.UpdateWithLines(["#endif"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[-1].open_parentheses == 1 self.UpdateWithLines([" struct X *arg2);"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 0) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[-1].open_parentheses == 0 self.UpdateWithLines(["};"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 def testInlineAssembly(self): self.UpdateWithLines( @@ -7069,14 +7023,14 @@ def testInlineAssembly(self): " int count) {", ] ) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 0) - self.assertEqual(self.nesting_state.stack[-1].inline_asm, cpplint._NO_ASM) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[-1].open_parentheses == 0 + assert self.nesting_state.stack[-1].inline_asm == cpplint._NO_ASM self.UpdateWithLines([" asm volatile ("]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) - self.assertEqual(self.nesting_state.stack[-1].inline_asm, cpplint._INSIDE_ASM) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[-1].open_parentheses == 1 + assert self.nesting_state.stack[-1].inline_asm == cpplint._INSIDE_ASM self.UpdateWithLines( [ @@ -7096,38 +7050,39 @@ def testInlineAssembly(self): ' : "memory", "cc"', ] ) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) - self.assertEqual(self.nesting_state.stack[-1].inline_asm, cpplint._INSIDE_ASM) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[-1].open_parentheses == 1 + assert self.nesting_state.stack[-1].inline_asm == cpplint._INSIDE_ASM self.UpdateWithLines(["#if defined(__SSE2__)", ' , "xmm0", "xmm1"']) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) - self.assertEqual(self.nesting_state.stack[-1].inline_asm, cpplint._INSIDE_ASM) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[-1].open_parentheses == 1 + assert self.nesting_state.stack[-1].inline_asm == cpplint._INSIDE_ASM self.UpdateWithLines(["#endif"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 1) - self.assertEqual(self.nesting_state.stack[-1].inline_asm, cpplint._INSIDE_ASM) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[-1].open_parentheses == 1 + assert self.nesting_state.stack[-1].inline_asm == cpplint._INSIDE_ASM self.UpdateWithLines([" );"]) - self.assertEqual(len(self.nesting_state.stack), 1) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 0) - self.assertEqual(self.nesting_state.stack[-1].inline_asm, cpplint._END_ASM) + assert len(self.nesting_state.stack) == 1 + assert self.nesting_state.stack[-1].open_parentheses == 0 + assert self.nesting_state.stack[-1].inline_asm == cpplint._END_ASM self.UpdateWithLines(["__asm {"]) - self.assertEqual(len(self.nesting_state.stack), 2) - self.assertEqual(self.nesting_state.stack[-1].open_parentheses, 0) - self.assertEqual(self.nesting_state.stack[-1].inline_asm, cpplint._BLOCK_ASM) + assert len(self.nesting_state.stack) == 2 + assert self.nesting_state.stack[-1].open_parentheses == 0 + assert self.nesting_state.stack[-1].inline_asm == cpplint._BLOCK_ASM self.UpdateWithLines(["}"]) - self.assertEqual(len(self.nesting_state.stack), 1) + assert len(self.nesting_state.stack) == 1 self.UpdateWithLines(["}"]) - self.assertEqual(len(self.nesting_state.stack), 0) + assert len(self.nesting_state.stack) == 0 -class QuietTest(unittest.TestCase): +class TestQuiet: + @pytest.fixture(autouse=True) def setUp(self): self.temp_dir = os.path.realpath(tempfile.mkdtemp()) self.this_dir_path = os.path.abspath(self.temp_dir) @@ -7156,52 +7111,52 @@ def _runCppLint(self, *args): def testNonQuietWithErrors(self): # This will fail: the test header is missing a copyright and header guard. (return_code, output) = self._runCppLint() - self.assertEqual(1, return_code) + assert return_code == 1 # Always-on behavior: Print error messages as they come up. - self.assertIn("[legal/copyright]", output) - self.assertIn("[build/header_guard]", output) + assert "[legal/copyright]" in output + assert "[build/header_guard]" in output # If --quiet was unspecified: Print 'Done processing' and 'Total errors..' - self.assertIn("Done processing", output) - self.assertIn("Total errors found:", output) + assert "Done processing" in output + assert "Total errors found:" in output def testQuietWithErrors(self): # When there are errors, behavior is identical to not passing --quiet. (return_code, output) = self._runCppLint("--quiet") - self.assertEqual(1, return_code) - self.assertIn("[legal/copyright]", output) - self.assertIn("[build/header_guard]", output) + assert return_code == 1 + assert "[legal/copyright]" in output + assert "[build/header_guard]" in output # Even though --quiet was used, print these since there were errors. - self.assertIn("Done processing", output) - self.assertIn("Total errors found:", output) + assert "Done processing" in output + assert "Total errors found:" in output def testNonQuietWithoutErrors(self): # This will succeed. We filtered out all the known errors for that file. (return_code, output) = self._runCppLint( "--filter=" + "-legal/copyright," + "-build/header_guard" ) - self.assertEqual(0, return_code, output) + assert return_code == 0, output # No cpplint errors are printed since there were no errors. - self.assertNotIn("[legal/copyright]", output) - self.assertNotIn("[build/header_guard]", output) + assert "[legal/copyright]" not in output + assert "[build/header_guard]" not in output # Print 'Done processing' since # --quiet was not specified. - self.assertIn("Done processing", output) + assert "Done processing" in output def testQuietWithoutErrors(self): # This will succeed. We filtered out all the known errors for that file. (return_code, output) = self._runCppLint( "--quiet", "--filter=" + "-legal/copyright," + "-build/header_guard" ) - self.assertEqual(0, return_code, output) + assert return_code == 0, output # No cpplint errors are printed since there were no errors. - self.assertNotIn("[legal/copyright]", output) - self.assertNotIn("[build/header_guard]", output) + assert "[legal/copyright]" not in output + assert "[build/header_guard]" not in output # --quiet was specified and there were no errors: # skip the printing of 'Done processing' and 'Total errors..' - self.assertNotIn("Done processing", output) - self.assertNotIn("Total errors found:", output) + assert "Done processing" not in output + assert "Total errors found:" not in output # Output with no errors must be completely blank! - self.assertEqual("", output) + assert output == "" # class FileFilterTest(unittest.TestCase): @@ -7217,38 +7172,20 @@ def setUp(): cpplint._cpplint_state.SetFilters("") -# pylint: disable=C6409 -def tearDown(): - """A global check to make sure all error-categories have been tested. - - The main tearDown() routine is the only code we can guarantee will be - run after all other tests have been executed. - """ - try: - if _run_verifyallcategoriesseen: - ErrorCollector(None).VerifyAllCategoriesAreSeen() - except NameError: - # If nobody set the global _run_verifyallcategoriesseen, then - # we assume we should silently not run the test - pass - - -@pytest.fixture(autouse=True) -def run_around_tests(): +@pytest.fixture(autouse=True, scope="session") +def run_around_tests(pytestconfig: pytest.Config): setUp() yield - tearDown() - - -if __name__ == "__main__": # We don't want to run the VerifyAllCategoriesAreSeen() test unless # we're running the full test suite: if we only run one test, # obviously we're not going to see all the error categories. So we - # only run VerifyAllCategoriesAreSeen() when no commandline flags - # are passed in. - global _run_verifyallcategoriesseen - _run_verifyallcategoriesseen = len(sys.argv) == 1 + # only run VerifyAllCategoriesAreSeen() when we don't filter for + # specific tests. + assert pytestconfig.getoption("-k", default=None) in [None, ""] + if pytestconfig.getoption("-k", default=None) in [None, ""]: + ErrorCollector(None).VerifyAllCategoriesAreSeen() + print("IIIIIIIIII saw the TV glow") - setUp() - unittest.main() - tearDown() + +if __name__ == "__main__": + pytest.main([__file__]) diff --git a/pyproject.toml b/pyproject.toml index 1c3c3ee..e64d1cd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -94,6 +94,7 @@ lint.select = [ "PGH", # pygrep-hooks "PIE", # flake8-pie "PL", # Pylint + "PT", # flake8-pytest-style "PYI", # flake8-pyi "Q", # flake8-quotes "RET", # flake8-return @@ -115,7 +116,6 @@ lint.select = [ # "DOC", # pydoclint # "ERA", # eradicate # "N", # pep8-naming - # "PT", # flake8-pytest-style # "PTH", # flake8-use-pathlib # "RUF", # Ruff-specific rules # "S", # flake8-bandit @@ -132,14 +132,14 @@ lint.ignore = [ lint.per-file-ignores."cpplint.py" = [ "ICN001", "PERF401", "PLR5501", "PLW0603", "PLW2901", "SIM102", "SIM108" ] lint.per-file-ignores."cpplint_unittest.py" = [ "FLY002", "PLW0604", "SIM115", "UP031" ] lint.mccabe.max-complexity = 29 -lint.pylint.allow-magic-value-types = [ "int", "str" ] +lint.pylint.allow-magic-value-types = [ "bytes", "int", "str" ] lint.pylint.max-args = 10 # Default is 5 lint.pylint.max-bool-expr = 8 # Default is 5 lint.pylint.max-branches = 30 # Default is 12 lint.pylint.max-locals = 16 # Default is 15 lint.pylint.max-public-methods = 130 # Default is 20 lint.pylint.max-returns = 9 # Default is 9 -lint.pylint.max-statements = 74 # Default is 50 +lint.pylint.max-statements = 79 # Default is 50 [tool.pylint.basic] argument-rgx = "[a-z_][a-z0-9_]{0,49}$" @@ -189,7 +189,7 @@ max-branches = 30 max-line-length = 100 max-locals = 25 max-returns = 10 -max-statements = 75 +max-statements = 79 min-public-methods = 0 [tool.pytest.ini_options]