Exemplo n.º 1
0
 def test_string_with_quotes(self):
     filepath = Path(self.dir_path, "RustServerCodegen.java")
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = StringConcatFinder()
     lines = pattern.value(ast)
     self.assertEqual(
         lines,
         [
             352,
             372,
             373,
             379,
             380,
             408,
             409,
             418,
             422,
             429,
             430,
             438,
             456,
             466,
             479,
             494,
             499,
             509,
             562,
             563,
             604,
             605,
             610,
             701,
             995,
             1009,
             1012,
             1029,
             1032,
             1080,
             1188,
             1258,
             1267,
             1337,
             1366,
             1372,
             1386,
             1414,
         ],
     )
Exemplo n.º 2
0
def execute_python_code_in_parallel_thread(file):
    """ This runs in a separate thread. """
    var_numbers = VarMiddle().value(file)
    nested_for_blocks = NestedBlocks(2, block_type=BlockType.FOR).value(file)
    nested_if_blocks = NestedBlocks(2, block_type=BlockType.IF).value(file)
    entropy = Entropy().value(file)
    spaces = SpacesCounter().value(file)
    concat_str_number = StringConcatFinder().value(file)
    return file, var_numbers, nested_for_blocks, nested_if_blocks, entropy, spaces, concat_str_number
Exemplo n.º 3
0
class TestConcatString(TestCase):
    dir_path = Path(os.path.realpath(__file__)).parent
    concat_finder = StringConcatFinder()

    def test_concat_strings_in_print(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'ConcatInPrint.java'))
        self.assertEqual(lines, [14])

    def test_member_plus_string(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'MemberPlusString.java'))
        self.assertEqual(lines, [99, 111])

    def test_empty_case(self):
        lines = self.concat_finder.value(Path(self.dir_path, 'Nothing.java'))
        self.assertEqual(lines, [])

    def test_string_plus_member(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'StringPlusMember.java'))
        self.assertEqual(len(lines), 1)

    def test_many_concats(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'ManyConcats.java'))
        self.assertEqual(lines, [12, 13, 14, 15])

    def test_concat_in_different_methods(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'DifferentMethods.java'))
        self.assertEqual(lines, [13, 27])

    def test_fake_operator_plus(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'FakePlusOperator.java'))
        self.assertEqual(lines, [])

    def test_string_with_quotes(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'RustServerCodegen.java'))
        self.assertEqual(lines, [
            352, 372, 373, 379, 380, 408, 409, 418, 422, 429, 430, 438, 456,
            466, 479, 494, 499, 509, 562, 563, 604, 605, 610, 701, 995, 1009,
            1012, 1029, 1032, 1080, 1258, 1267, 1337, 1386, 1414
        ])

    def test_comment_inside_line(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'XMLDataObject.java'))
        self.assertEqual(lines, [160, 165, 177, 192, 218, 279])

    def test_fake1(self):
        lines = self.concat_finder.value(Path(self.dir_path, 'Chain.java'))
        self.assertEqual(lines, [32])
Exemplo n.º 4
0
def main():
    exit_status = -1
    try:
        depth_for = 2
        depth_if = 2
        parser = argparse.ArgumentParser(
            description=
            'Find the pattern which has the largest impact on readability')
        parser.add_argument('--filename', help='path for Java file')
        parser.add_argument(
            '--version',
            action='version',
            version='%(prog)s {version}'.format(version=__version__))

        args = parser.parse_args(args=None if sys.argv[1:] else ['--help'])

        if args:
            java_file = str(Path(os.getcwd(), args.filename))

            order_queue = queue.Queue()
            order_queue.put([
                VarMiddle().value(java_file),
                'variable declaration in the middle of the function'
            ])
            order_queue.put([
                NestedBlocks(depth_for,
                             block_type=BlockType.FOR).value(java_file),
                'nested for cycle with depth = {}'.format(depth_for)
            ])
            order_queue.put([
                NestedBlocks(depth_if,
                             block_type=BlockType.IF).value(java_file),
                'nested if condition with depth = 2'.format(depth_if)
            ])
            order_queue.put([
                StringConcatFinder().value(java_file),
                'string concatenation with operator +'
            ])

            lines, output_string = order_queue.get()
            if not lines:
                print('Your code is perfect in aibolit\'s opinion')
            for line in lines:
                if line:
                    print('Line {}. Low readability due to: {}'.format(
                        line, output_string))
            order_queue.task_done()
            exit_status = 0
    except KeyboardInterrupt:
        exit_status = -1
    sys.exit(exit_status)
Exemplo n.º 5
0
class TestConcatString(TestCase):
    dir_path = Path(os.path.realpath(__file__)).parent
    concat_finder = StringConcatFinder()

    def test_concat_strings_in_print(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'ConcatInPrint.java'))
        assert len(lines) == 1

    def test_member_plus_string(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'MemberPlusString.java'))
        assert len(lines) == 1

    def test_multiple_concat(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'MultipleConcat.java'))
        assert len(lines) == 1

    def test_empty_case(self):
        lines = self.concat_finder.value(Path(self.dir_path, 'Nothing.java'))
        assert len(lines) == 0

    def test_string_plus_member(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'StringPlusMember.java'))
        assert len(lines) == 1

    def test_many_concats(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'ManyConcats.java'))
        assert len(lines) == 4

    def test_concat_in_different_methods(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'DifferentMethods.java'))
        assert len(lines) == 2

    def test_fake_operator_plus(self):
        lines = self.concat_finder.value(
            Path(self.dir_path, 'FakePlusOperator.java'))
        assert len(lines) == 0
Exemplo n.º 6
0
 def test_fake_operator_plus(self):
     filepath = Path(self.dir_path, "FakePlusOperator.java")
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = StringConcatFinder()
     lines = pattern.value(ast)
     self.assertEqual(lines, [])
Exemplo n.º 7
0
 def test_concat_in_different_methods(self):
     filepath = Path(self.dir_path, "DifferentMethods.java")
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = StringConcatFinder()
     lines = pattern.value(ast)
     self.assertEqual(lines, [13, 27])
Exemplo n.º 8
0
 def test_many_concats(self):
     filepath = Path(self.dir_path, "ManyConcats.java")
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = StringConcatFinder()
     lines = pattern.value(ast)
     self.assertEqual(lines, [12, 13, 14, 15])
Exemplo n.º 9
0
 def test_string_plus_member(self):
     filepath = Path(self.dir_path, "StringPlusMember.java")
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = StringConcatFinder()
     lines = pattern.value(ast)
     self.assertEqual(len(lines), 1)
Exemplo n.º 10
0
 def test_empty_case(self):
     filepath = Path(self.dir_path, "Nothing.java")
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = StringConcatFinder()
     lines = pattern.value(ast)
     self.assertEqual(lines, [])
Exemplo n.º 11
0
 def test_member_plus_string(self):
     filepath = Path(self.dir_path, "MemberPlusString.java")
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = StringConcatFinder()
     lines = pattern.value(ast)
     self.assertEqual(lines, [99, 111])
Exemplo n.º 12
0
 def test_concat_strings_in_print(self):
     filepath = Path(self.dir_path, "ConcatInPrint.java")
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = StringConcatFinder()
     lines = pattern.value(ast)
     self.assertEqual(lines, [14])
Exemplo n.º 13
0
 def test_fake1(self):
     filepath = Path(self.dir_path, "Chain.java")
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = StringConcatFinder()
     lines = pattern.value(ast)
     self.assertEqual(lines, [32])
Exemplo n.º 14
0
 def test_comment_inside_line(self):
     filepath = Path(self.dir_path, "XMLDataObject.java")
     ast = AST.build_from_javalang(build_ast(filepath))
     pattern = StringConcatFinder()
     lines = pattern.value(ast)
     self.assertEqual(lines, [160, 165, 177, 192, 218, 279])
Exemplo n.º 15
0
def main():
    exit_status = -1
    patterns_list = [
        'var_middle_number', 'this_find_number', 'string_concat_number',
        'instance_of_number', 'method_chain_number', 'var_decl_diff_number_11',
        'var_decl_diff_number_7', 'var_decl_diff_number_5',
        'super_method_call_number', 'force_type_cast_number', 'asserts_number',
        'setter_number', 'empty_rethrow_number',
        'prohibited_class_names_number', 'return_in_if_number',
        'impl_multi_number', 'many_prim_ctors_number', 'multiple_try_number',
        'non_final_field_number', 'null_check_number', 'part_sync_number',
        'red_catch_number', 'return_null_number'
    ]
    try:
        parser = argparse.ArgumentParser(
            description=
            'Find the pattern which has the largest impact on readability')
        parser.add_argument('--filename', help='path for Java file')
        parser.add_argument(
            '--version',
            action='version',
            version='%(prog)s {version}'.format(version=__version__))

        args = parser.parse_args(args=None if sys.argv[1:] else ['--help'])

        if args:
            java_file = str(Path(os.getcwd(), args.filename))
            halstead_volume = find_halstead(java_file)
            var_numbers = VarMiddle().value(java_file)
            entropy = Entropy().value(java_file)
            left_space_variance, right_space_variance, max_left_space_diff, max_right_space_diff \
                = IndentationCounter().value(java_file)
            concat_str_number = StringConcatFinder().value(java_file)
            instance_of_lines = InstanceOf().value(java_file)
            method_chain_lines = MethodChainFind().value(java_file)
            var_decl_diff_lines_5 = VarDeclarationDistance(
                lines_th=5).value(java_file)
            var_decl_diff_lines_7 = VarDeclarationDistance(
                lines_th=7).value(java_file)
            var_decl_diff_lines_11 = VarDeclarationDistance(
                lines_th=11).value(java_file)
            super_m_lines = SuperMethod().value(java_file)
            force_type_cast_number = ForceTypeCastingFinder().value(java_file)
            this_lines = ThisFinder().value(java_file)
            asserts_lines = AssertInCode().value(java_file)
            setter_lines = ClassicSetter().value(java_file)
            empty_rethrow_lines = EmptyRethrow().value(java_file)
            prohibited_class_names = ErClass().value(java_file)
            if_return_lines = CountIfReturn().value(java_file)
            impl_multi_lines = ImplementsMultiFinder().value(java_file)
            many_prim_ctors_lines = ManyPrimaryCtors().value(java_file)
            multiple_try_lines = MultipleTry().value(java_file)
            non_final_field_lines = NonFinalAttribute().value(java_file)
            null_check_lines = NullCheck().value(java_file)
            part_sync_lines = PartialSync().value(java_file)
            red_catch_lines = RedundantCatch().value(java_file)
            return_null_lines = ReturnNull().value(java_file)
            ncss_lightweight = NCSSMetric().value(java_file)

            code_lines_dict = {
                'var_middle_number': var_numbers,
                'string_concat_number': concat_str_number,
                'instance_of_number': instance_of_lines,
                'method_chain_number': method_chain_lines,
                'var_decl_diff_number_5': var_decl_diff_lines_5,
                'var_decl_diff_number_7': var_decl_diff_lines_7,
                'var_decl_diff_number_11': var_decl_diff_lines_11,
                'super_method_call_number': super_m_lines,
                'force_type_cast_number': force_type_cast_number,
                'this_find_number': this_lines,
                'asserts_number': asserts_lines,
                'setter_number': setter_lines,
                'empty_rethrow_number': empty_rethrow_lines,
                'prohibited_class_names_number': prohibited_class_names,
                'return_in_if_number': if_return_lines,
                'impl_multi_number': impl_multi_lines,
                'many_prim_ctors_number': many_prim_ctors_lines,
                'multiple_try_number': multiple_try_lines,
                'non_final_field_number': non_final_field_lines,
                'null_check_number': null_check_lines,
                'part_sync_number': part_sync_lines,
                'red_catch_number': red_catch_lines,
                'return_null_number': return_null_lines,
            }
            input_params = {
                'var_middle_number': len(var_numbers),
                'string_concat_number': len(concat_str_number),
                'instance_of_number': len(instance_of_lines),
                'method_chain_number': len(method_chain_lines),
                'var_decl_diff_number_5': len(var_decl_diff_lines_5),
                'var_decl_diff_number_7': len(var_decl_diff_lines_7),
                'var_decl_diff_number_11': len(var_decl_diff_lines_11),
                'super_method_call_number': len(super_m_lines),
                'force_type_cast_number': len(force_type_cast_number),
                'this_find_number': len(this_lines),
                'asserts_number': len(asserts_lines),
                'setter_number': len(setter_lines),
                'empty_rethrow_number': len(empty_rethrow_lines),
                'prohibited_class_names_number': len(prohibited_class_names),
                'return_in_if_number': len(if_return_lines),
                'impl_multi_number': len(impl_multi_lines),
                'many_prim_ctors_number': len(many_prim_ctors_lines),
                'multiple_try_number': len(multiple_try_lines),
                'non_final_field_number': len(non_final_field_lines),
                'null_check_number': len(null_check_lines),
                'part_sync_number': len(part_sync_lines),
                'red_catch_number': len(red_catch_lines),
                'return_null_number': len(return_null_lines),
                'entropy': entropy,
                'halstead volume': halstead_volume,
                'left_spaces_var': left_space_variance,
                'right_spaces_var': right_space_variance,
                'max_left_diff_spaces': max_left_space_diff,
                'max_right_diff_spaces': max_right_space_diff,
                'ncss_lightweight': ncss_lightweight,
            }

            sorted_result = predict(input_params)
            found_pattern = False
            code_lines = None
            value = None
            for iter, (key, val) in enumerate(sorted_result.items()):
                if key in patterns_list:
                    if not found_pattern:
                        pattern = key
                        code_lines = code_lines_dict.get(key)
                        # We show only positive gradient, we won't add patterns
                        if code_lines and val > 1.00000e-20:
                            found_pattern = True
                            value = val

            if not code_lines:
                print('Your code is perfect in aibolit\'s opinion')
            else:
                output_str = \
                    'The largest contribution for {file} is {val} for \"{pattern}\" pattern'.format(
                        file=java_file,
                        pattern=pattern,
                        val=value)
                print(output_str)
                for line in code_lines:
                    if line:
                        print('Line {}. Low readability due to: {}'.format(
                            line, pattern))
            exit_status = 0
    except KeyboardInterrupt:
        exit_status = -1
    sys.exit(exit_status)