def test_anonymous(self):
     filepath = str(Path(self.current_directory, "Anonymous.java"))
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = EmptyRethrow()
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = EmptyRethrow()
     self.assertEqual(pattern.value(ast), [19, 25])
 def test_canFindJoinedValidationOrFieldAccess(self):
     filepath = self.current_directory / "JoinedValidationOrFieldAccess.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = JoinedValidation()
     lines = pattern.value(ast)
     self.assertEqual([6], lines,
                      "Could not find joined validation in field access")
 def test_canFindJoinedValidationOrFunctionCall(self):
     filepath = self.current_directory / "JoinedValidationOrFunctionCall.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = JoinedValidation()
     lines = pattern.value(ast)
     self.assertEqual([8], lines,
                      "Could not find joined validation in function call")
 def test_canFindJoinedValidationOrOr(self):
     filepath = self.current_directory / "JoinedValidationOrOr.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = JoinedValidation()
     lines = pattern.value(ast)
     self.assertEqual([3], lines,
                      "Could not find joined validation in OrOr condition")
 def test_canSkipNoJoinedValidation(self):
     filepath = self.current_directory / "NoJoinedValidation.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = JoinedValidation()
     lines = pattern.value(ast)
     self.assertEqual([], lines,
                      "Could not skip when there is no joined validation")
示例#6
0
 def test_try_without_throws(self):
     pattern = RedundantCatch()
     filepath = os.path.dirname(
         os.path.realpath(__file__)) + "/ExcelReader.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     lines = pattern.value(ast)
     self.assertEqual(lines, [])
 def test_several(self):
     # It has 2 matches in anonymous class!
     filepath = self.current_directory / "Several.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = SuperMethod()
     lines = pattern.value(ast)
     self.assertEqual(len(lines), 6)
 def test_chained_exceptions3(self):
     filepath = str(
         Path(self.current_directory,
              "DatabaseNavigatorSourceContainer.java"))
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = EmptyRethrow()
     self.assertEqual(pattern.value(ast), [])
示例#9
0
    def test_class_computed_fields(self):
        ast = AST.build_from_javalang(
            build_ast(
                Path(__file__).absolute().parent /
                "MethodUseOtherMethodExample.java"))
        package = ast.get_root()
        assert len(package.types) == 1 and \
            package.types[0].node_type == ASTNodeType.CLASS_DECLARATION

        java_class = package.types[0]
        self.assertEqual(java_class.name, "MethodUseOtherMethod")
        self.assertEqual(java_class.modifiers, set())
        self.assertEqual(java_class.documentation,
                         "/**\n* Some documentation\n*/")

        # consider each field declaration declares single field
        fields_names = {field.names[0] for field in java_class.fields}
        self.assertEqual(fields_names, {"connectingField", "redundantField"})

        methods_names = {method.name for method in java_class.methods}
        self.assertEqual(
            methods_names,
            {
                "useOnlyMethods1",
                "useOnlyMethods2",
                "getField",
                "setField",
                "standAloneMethod",
                "shadowing",
            },
        )

        self.assertEqual(set(java_class.constructors), set())
示例#10
0
 def test_try_in_constructor(self):
     pattern = RedundantCatch()
     filepath = os.path.dirname(
         os.path.realpath(__file__)) + "/ExcelAnalyserImpl.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     lines = pattern.value(ast)
     self.assertEqual(lines, [43])
示例#11
0
 def value(self, filename: str) -> List[int]:
     lines: List[int] = []
     ast = AST.build_from_javalang(build_ast(filename))
     for method_declaration in ast.get_proxy_nodes(ASTNodeType.METHOD_DECLARATION):
         if 'protected' in method_declaration.modifiers:
             lines.append(method_declaration.line)
     return lines
示例#12
0
 def test_multiple_catch(self):
     pattern = RedundantCatch()
     filepath = os.path.dirname(
         os.path.realpath(__file__)) + "/MultipleCatch.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     lines = pattern.value(ast)
     self.assertEqual(lines, [3])
示例#13
0
def __count_value(value_dict,
                  input_params,
                  code_lines_dict,
                  java_file: str,
                  is_metric=False):
    """
    Count value for input dict

    :param value_dict: Pattern item or Metric item from CONFIG
    :param input_params: list with calculated patterns/metrics
    :param code_lines_dict: list with found code lines of patterns/metrics
    :param java_file: full path for java file
    :is_metric: is item metric?
    :return: None, it has side-effect
    """
    acronym = value_dict['code']
    try:
        ast = AST.build_from_javalang(build_ast(java_file))
        val = value_dict['make']().value(ast)
        if not is_metric:
            input_params[acronym] = len(val)
            code_lines_dict['lines_' + acronym] = val
        else:
            input_params[acronym] = val
    except Exception:
        exc_type, exc_value, exc_tb = sys.exc_info()
        raise Exception("Can't count {} metric: {}".format(
            acronym, str(type(exc_value))))
示例#14
0
 def value(self, filename: str) -> int:
     metric = 0
     ast = AST.build_from_javalang(build_ast(filename))
     for class_node in ast.get_proxy_nodes(ASTNodeType.CLASS_DECLARATION):
         for method_node in class_node.methods:
             metric += 1
     return metric
示例#15
0
 def test_try_inside_finally(self):
     pattern = RedundantCatch()
     filepath = os.path.dirname(
         os.path.realpath(__file__)) + "/TryInsideFinally.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     lines = pattern.value(ast)
     self.assertEqual(lines, [8])
示例#16
0
 def test_find_protected_method(self):
     filepath = self.current_directory / "ProtectedMethod.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = ProtectedMethod()
     lines = pattern.value(ast)
     self.assertEqual(lines, [2, 6],
                      "Should match pattern protected method")
示例#17
0
 def test_more_method_invocations(self):
     filepath = self.current_directory / "SequenceFile.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = SendNull()
     lines = pattern.value(ast)
     self.assertEqual(
         lines, [1097, 1186, 1201, 1217, 3285, 3298, 3367, 3537, 3550])
示例#18
0
 def test_sequential_catch_try(self):
     pattern = RedundantCatch()
     filepath = os.path.dirname(
         os.path.realpath(__file__)) + "/SequentialCatchTry.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     lines = pattern.value(ast)
     self.assertEqual(lines, [3, 10])
示例#19
0
 def test_fake(self):
     pattern = RedundantCatch()
     filepath = os.path.dirname(
         os.path.realpath(__file__)) + "/TrickyFake.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     lines = pattern.value(ast)
     self.assertEqual(lines, [])
示例#20
0
    def test_semantic_extraction(self):
        ast = AST.build_from_javalang(
            build_ast(self.current_directory / "SimpleMethods.java"))
        class_declaration = ast.get_root().types[0]
        assert class_declaration.name == "SimpleMethods", "Wrong java test class"

        for method_declaration in class_declaration.methods:
            with self.subTest(f"Test {method_declaration.name} method."):
                method_semantic = extract_method_statements_semantic(
                    ast.get_subtree(method_declaration))
                items_for_comparison = enumerate(
                    zip_longest(
                        method_semantic.keys(),
                        method_semantic.values(),
                        self.expected_semantic[method_declaration.name],
                    ))
                for (
                        comparison_index,
                    (statement, actual_statement_semantic,
                     expected_statement_semantic),
                ) in items_for_comparison:
                    with self.subTest(
                            f"Comparing {comparison_index}th statement {repr(statement)} "
                            f"on line {statement.line} of method {method_declaration.name}."
                    ):
                        self.assertEqual(actual_statement_semantic,
                                         expected_statement_semantic)
示例#21
0
 def test_catch_with_similar_name(self):
     pattern = RedundantCatch()
     filepath = os.path.dirname(
         os.path.realpath(__file__)) + "/NotThrow.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     lines = pattern.value(ast)
     self.assertEqual(lines, [256])
示例#22
0
 def test_catch_with_functions(self):
     pattern = RedundantCatch()
     filepath = os.path.dirname(
         os.path.realpath(__file__)) + "/CatchWithFunctions.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     lines = pattern.value(ast)
     self.assertEqual(lines, [6])
示例#23
0
    def value(self, filename: str) -> List[int]:
        lines: Set[int] = set()
        ast = AST.build_from_javalang(build_ast(filename))
        for node in ast.get_proxy_nodes(ASTNodeType.BINARY_OPERATION):
            if node.operator == '+' and self._check_left_right_operator(node):
                lines.add(node.line)

        return sorted(lines)
示例#24
0
 def value(self, filename: str) -> List[int]:
     lines: List[int] = []
     ast = AST.build_from_javalang(build_ast(filename))
     for method_declaration in ast.get_proxy_nodes(ASTNodeType.METHOD_DECLARATION,
                                                   ASTNodeType.CONSTRUCTOR_DECLARATION):
         if any(len(parameter.type.dimensions) > 0 for parameter in method_declaration.parameters):
             lines.append(method_declaration.line)
     return lines
 def test_canFindNoBracketsJoinedValidation(self):
     filepath = self.current_directory / "NoBracketsJoinedValidation.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = JoinedValidation()
     lines = pattern.value(ast)
     self.assertEqual(
         [3], lines,
         "Could not find joined validation when using no brackets")
示例#26
0
 def value(self, filename: str) -> List[int]:
     lines: List[int] = list()
     ast = AST.build_from_javalang(build_ast(filename))
     for class_declaration in ast.get_proxy_nodes(ASTNodeType.CLASS_DECLARATION):
         primary_lines = self.__find_primary(ast, class_declaration.body)
         if len(primary_lines) > 1:
             lines.extend(primary_lines)
     return lines
示例#27
0
 def value(self, filename: str) -> List[int]:
     ast = AST.build_from_javalang(build_ast(filename))
     lines: List[int] = []
     for if_statement in ast.get_proxy_nodes(ASTNodeType.IF_STATEMENT):
         if self._is_logical_or_used_in_expression(if_statement.condition) and \
            self._is_block_consist_of_single_throw(if_statement.then_statement):
             lines.append(if_statement.line)
     return lines
示例#28
0
 def value(self, filename: str):
     lines: List[int] = []
     ast = AST.build_from_javalang(build_ast(filename))
     for method_declaration in ast.get_proxy_nodes(
             ASTNodeType.METHOD_DECLARATION):
         if self._check_public_static(method_declaration):
             lines.append(method_declaration.line)
     return lines
示例#29
0
    def value(self, filename: str) -> List[int]:
        ast = AST.build_from_javalang(build_ast(filename))
        lines: List[int] = []
        for return_statement in ast.get_proxy_nodes(
                ASTNodeType.RETURN_STATEMENT):
            if self._check_null_return_statement(return_statement):
                lines.append(return_statement.line)

        return lines
示例#30
0
 def test_multi_level_invocation(self):
     filepath = self.current_directory / "Configuration.java"
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = SendNull()
     lines = pattern.value(ast)
     self.assertEqual(lines, [
         379, 442, 549, 638, 656, 830, 866, 1362, 2393, 2874, 2988, 3080,
         3492, 3758, 3855
     ])