diff options
author | Stephan Herrmann | 2010-04-02 00:39:52 +0000 |
---|---|---|
committer | Stephan Herrmann | 2010-04-02 00:39:52 +0000 |
commit | 19cb79afe09fcf0aa68482ed32696549b02352d2 (patch) | |
tree | 730f9988539021b1dfee9e02679f9e9be407b5ee /testplugins | |
parent | ad9196228a6d6781b950429669ff6a4d29996809 (diff) | |
download | org.eclipse.objectteams-19cb79afe09fcf0aa68482ed32696549b02352d2.tar.gz org.eclipse.objectteams-19cb79afe09fcf0aa68482ed32696549b02352d2.tar.xz org.eclipse.objectteams-19cb79afe09fcf0aa68482ed32696549b02352d2.zip |
initial commit in accordance with CQ 3784
Diffstat (limited to 'testplugins')
165 files changed, 49939 insertions, 0 deletions
diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.core.resources.prefs b/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 000000000..5ce5a23a5 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,3 @@ +#Wed Jun 21 10:51:57 CEST 2006 +eclipse.preferences.version=1 +encoding/<project>=ISO-8859-1 diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.jdt.core.prefs b/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 000000000..1ecf1cb76 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,363 @@ +#Fri Nov 28 09:49:27 CET 2008
+eclipse.preferences.version=1
+org.eclipse.jdt.core.builder.cleanOutputFolder=clean
+org.eclipse.jdt.core.builder.duplicateResourceTask=warning
+org.eclipse.jdt.core.builder.invalidClasspath=abort
+org.eclipse.jdt.core.builder.resourceCopyExclusionFilter=*.launch
+org.eclipse.jdt.core.circularClasspath=error
+org.eclipse.jdt.core.classpath.exclusionPatterns=enabled
+org.eclipse.jdt.core.classpath.multipleOutputLocations=enabled
+org.eclipse.jdt.core.codeComplete.argumentPrefixes=
+org.eclipse.jdt.core.codeComplete.argumentSuffixes=
+org.eclipse.jdt.core.codeComplete.fieldPrefixes=f
+org.eclipse.jdt.core.codeComplete.fieldSuffixes=
+org.eclipse.jdt.core.codeComplete.localPrefixes=
+org.eclipse.jdt.core.codeComplete.localSuffixes=
+org.eclipse.jdt.core.codeComplete.staticFieldPrefixes=fg
+org.eclipse.jdt.core.codeComplete.staticFieldSuffixes=
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=disabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.4
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.doc.comment.support=enabled
+org.eclipse.jdt.core.compiler.maxProblemPerUnit=100
+org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning
+org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
+org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
+org.eclipse.jdt.core.compiler.problem.deadCode=warning
+org.eclipse.jdt.core.compiler.problem.deprecation=warning
+org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
+org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled
+org.eclipse.jdt.core.compiler.problem.discouragedReference=ignore
+org.eclipse.jdt.core.compiler.problem.emptyStatement=warning
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning
+org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
+org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled
+org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
+org.eclipse.jdt.core.compiler.problem.finalParameterBound=ignore
+org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
+org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
+org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=error
+org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=error
+org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
+org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=warning
+org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning
+org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled
+org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=disabled
+org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled
+org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=private
+org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
+org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=error
+org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
+org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=error
+org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore
+org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=enabled
+org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public
+org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=all_standard_tags
+org.eclipse.jdt.core.compiler.problem.missingJavadocTags=warning
+org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled
+org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=private
+org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=warning
+org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
+org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=error
+org.eclipse.jdt.core.compiler.problem.noEffectAssignment=error
+org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=error
+org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
+org.eclipse.jdt.core.compiler.problem.nullReference=error
+org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=error
+org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=error
+org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
+org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
+org.eclipse.jdt.core.compiler.problem.redundantNullCheck=warning
+org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
+org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
+org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=error
+org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
+org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
+org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
+org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
+org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
+org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
+org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
+org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=error
+org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
+org.eclipse.jdt.core.compiler.problem.unusedImport=error
+org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
+org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
+org.eclipse.jdt.core.compiler.problem.unusedParameter=warning
+org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
+org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
+org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
+org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
+org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
+org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
+org.eclipse.jdt.core.compiler.source=1.3
+org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_assignment=0
+org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_compact_if=16
+org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=48
+org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0
+org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16
+org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16
+org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16
+org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16
+org.eclipse.jdt.core.formatter.blank_lines_after_imports=1
+org.eclipse.jdt.core.formatter.blank_lines_after_package=1
+org.eclipse.jdt.core.formatter.blank_lines_before_field=1
+org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0
+org.eclipse.jdt.core.formatter.blank_lines_before_imports=1
+org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1
+org.eclipse.jdt.core.formatter.blank_lines_before_method=1
+org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1
+org.eclipse.jdt.core.formatter.blank_lines_before_package=0
+org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1
+org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1
+org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false
+org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false
+org.eclipse.jdt.core.formatter.comment.format_block_comments=false
+org.eclipse.jdt.core.formatter.comment.format_header=false
+org.eclipse.jdt.core.formatter.comment.format_html=true
+org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true
+org.eclipse.jdt.core.formatter.comment.format_line_comments=false
+org.eclipse.jdt.core.formatter.comment.format_source_code=true
+org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true
+org.eclipse.jdt.core.formatter.comment.indent_root_tags=true
+org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert
+org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert
+org.eclipse.jdt.core.formatter.comment.line_length=100
+org.eclipse.jdt.core.formatter.compact_else_if=true
+org.eclipse.jdt.core.formatter.continuation_indentation=2
+org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2
+org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true
+org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true
+org.eclipse.jdt.core.formatter.indent_empty_lines=false
+org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true
+org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true
+org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true
+org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true
+org.eclipse.jdt.core.formatter.indentation.size=4
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert
+org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert
+org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert
+org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert
+org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert
+org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.join_lines_in_comments=true
+org.eclipse.jdt.core.formatter.join_wrapped_lines=false
+org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false
+org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false
+org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false
+org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false
+org.eclipse.jdt.core.formatter.lineSplit=200
+org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=true
+org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=true
+org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
+org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=3
+org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
+org.eclipse.jdt.core.formatter.tabulation.char=tab
+org.eclipse.jdt.core.formatter.tabulation.size=4
+org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false
+org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true
+org.eclipse.jdt.core.incompatibleJDKLevel=ignore
+org.eclipse.jdt.core.incompleteClasspath=error
diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.jdt.launching.prefs b/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.jdt.launching.prefs new file mode 100644 index 000000000..a5ee5cd1a --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.jdt.launching.prefs @@ -0,0 +1,3 @@ +#Tue Oct 07 11:47:24 CEST 2008 +eclipse.preferences.version=1 +org.eclipse.jdt.launching.PREF_STRICTLY_COMPATIBLE_JRE_NOT_AVAILABLE=error diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.jdt.ui.prefs b/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 000000000..ee520890d --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,12 @@ +#Tue Jul 15 15:34:15 CEST 2008 +eclipse.preferences.version=1 +formatter_profile=_JDT UI Code Style Conventions +formatter_settings_version=11 +org.eclipse.jdt.ui.exception.name=e +org.eclipse.jdt.ui.gettersetter.use.is=true +org.eclipse.jdt.ui.ignorelowercasenames=true +org.eclipse.jdt.ui.importorder=java;javax;sun;com;org;org.apache;org.w3c;org.eclipse;org.eclipse.swt;org.eclipse.core;org.eclipse.core.runtime;org.eclipse.core.resources;org.eclipse.core.filebuffers;org.eclipse.text;org.eclipse.jface;org.eclipse.jface.text;org.eclipse.ui;org.eclipse.ui.workbench.texteditor;org.eclipse.ui.texteditor;org.eclipse.ui.editors;org.eclipse.compare;org.eclipse.debug;org.eclipse.debug.ui;org.eclipse.search;org.eclipse.search2;org.eclipse.ltk;org.eclipse.jdt.core;org.eclipse.jdt.internal;org.eclipse.jdt.launching;org.eclipse.jdt.ui;org.eclipse.jdt.internal.ui; +org.eclipse.jdt.ui.keywordthis=false +org.eclipse.jdt.ui.ondemandthreshold=99 +org.eclipse.jdt.ui.overrideannotation=true +org.eclipse.jdt.ui.staticondemandthreshold=99 diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.pde.prefs b/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.pde.prefs new file mode 100644 index 000000000..eab969f54 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/.settings/org.eclipse.pde.prefs @@ -0,0 +1,15 @@ +#Mon Jan 29 10:51:35 CET 2007 +compilers.incompatible-environment=1 +compilers.p.build=0 +compilers.p.deprecated=1 +compilers.p.missing-packages=0 +compilers.p.no-required-att=0 +compilers.p.not-externalized-att=2 +compilers.p.unknown-attribute=0 +compilers.p.unknown-class=0 +compilers.p.unknown-element=0 +compilers.p.unknown-resource=0 +compilers.p.unresolved-ex-points=0 +compilers.p.unresolved-import=0 +compilers.use-project=true +eclipse.preferences.version=1 diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/META-INF/MANIFEST.MF b/testplugins/org.eclipse.jdt.ui.tests.refactoring/META-INF/MANIFEST.MF new file mode 100644 index 000000000..2c22a35ae --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/META-INF/MANIFEST.MF @@ -0,0 +1,41 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: %Plugin.name +Bundle-SymbolicName: org.eclipse.jdt.ui.tests.refactoring; singleton:=true +Bundle-Version: 3.6.0 +Bundle-ClassPath: refactoringtests.jar +Bundle-Activator: org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringTestPlugin +Bundle-ActivationPolicy: lazy +Bundle-Vendor: %Plugin.providerName +Bundle-Localization: plugin +Export-Package: + org.eclipse.jdt.ui.tests.refactoring;x-internal:=true, + org.eclipse.jdt.ui.tests.refactoring.actions;x-internal:=true, + org.eclipse.jdt.ui.tests.refactoring.all;x-internal:=true, + org.eclipse.jdt.ui.tests.refactoring.ccp;x-internal:=true, + org.eclipse.jdt.ui.tests.refactoring.changes;x-internal:=true, + org.eclipse.jdt.ui.tests.refactoring.extensions;x-internal:=true, + org.eclipse.jdt.ui.tests.refactoring.infra;x-internal:=true, + org.eclipse.jdt.ui.tests.refactoring.nls;x-internal:=true, + org.eclipse.jdt.ui.tests.refactoring.reorg;x-internal:=true, + org.eclipse.jdt.ui.tests.refactoring.type;x-internal:=true, + org.eclipse.jdt.ui.tests.refactoring.typeconstraints;x-internal:=true +Require-Bundle: + org.eclipse.core.filebuffers, + org.eclipse.core.filesystem, + org.eclipse.core.resources, + org.eclipse.core.runtime, + org.eclipse.jdt.core, + org.eclipse.jdt.core.manipulation, + org.eclipse.jdt.ui;bundle-version="[3.6.0,4.0.0)", + org.eclipse.jdt.ui.tests, + org.eclipse.jface.text, + org.eclipse.ltk.core.refactoring, + org.eclipse.ltk.ui.refactoring, + org.eclipse.team.core, + org.eclipse.test.performance, + org.eclipse.ui, + org.eclipse.ui.ide, + org.eclipse.ui.workbench.texteditor, + org.junit;bundle-version="3.8.2" +Bundle-RequiredExecutionEnvironment: J2SE-1.4 diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AbstractSelectionTestCase.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AbstractSelectionTestCase.java new file mode 100644 index 000000000..53957f026 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AbstractSelectionTestCase.java @@ -0,0 +1,200 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.IOException; +import java.io.InputStream; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.IResourceChangeListener; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.jface.text.ITextSelection; +import org.eclipse.jface.text.TextSelection; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.CheckConditionsOperation; +import org.eclipse.ltk.core.refactoring.IUndoManager; +import org.eclipse.ltk.core.refactoring.PerformRefactoringOperation; +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.JavaCore; + +import org.eclipse.jdt.ui.tests.refactoring.infra.AbstractCUTestCase; +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringTestPlugin; + +public abstract class AbstractSelectionTestCase extends AbstractCUTestCase { + + public static final String SQUARE_BRACKET_OPEN= "/*[*/"; + public static final int SQUARE_BRACKET_OPEN_LENGTH= SQUARE_BRACKET_OPEN.length(); + public static final String SQUARE_BRACKET_CLOSE= "/*]*/"; + public static final int SQUARE_BRACKET_CLOSE_LENGTH= SQUARE_BRACKET_CLOSE.length(); + + protected static final int VALID_SELECTION= 1; + protected static final int INVALID_SELECTION= 2; + protected static final int COMPARE_WITH_OUTPUT= 3; + + private boolean fIgnoreSelectionMarker; + private int[] fSelection; + protected boolean fIsPreDeltaTest; + + public AbstractSelectionTestCase(String name) { + this(name, false); + } + + public AbstractSelectionTestCase(String name, boolean ignoreSelectionMarker) { + super(name); + fIgnoreSelectionMarker= ignoreSelectionMarker; + } + + protected void setUp() throws Exception { + super.setUp(); + fIsPreDeltaTest= false; + } + + protected int[] getSelection() { + return fSelection; + } + + protected ITextSelection getTextSelection() { + int[] s= getSelection(); + return new TextSelection(s[0], s[1]); + } + + protected InputStream getFileInputStream(String fileName) throws IOException { + return RefactoringTestPlugin.getDefault().getTestResourceStream(fileName); + } + + protected String getFileContents(InputStream in) throws IOException { + String result= super.getFileContents(in); + initializeSelection(result); + if (fIgnoreSelectionMarker) { + result= result.replaceAll("/\\*\\[\\*/", ""); + result= result.replaceAll("/\\*\\]\\*/", ""); + } + return result; + } + + protected void performTest(final ICompilationUnit unit, final Refactoring refactoring, int mode, final String out, boolean doUndo) throws Exception { + IProgressMonitor pm= new NullProgressMonitor(); + switch (mode) { + case VALID_SELECTION: + assertTrue(checkPreconditions(refactoring, pm).isOK()); + break; + case INVALID_SELECTION: + assertTrue(!checkPreconditions(refactoring, pm).isOK()); + break; + case COMPARE_WITH_OUTPUT: + IUndoManager undoManager= RefactoringCore.getUndoManager(); + undoManager.flush(); + String original= unit.getSource(); + + final PerformRefactoringOperation op= new PerformRefactoringOperation( + refactoring, getCheckingStyle()); + if (fIsPreDeltaTest) { + IWorkspace workspace= ResourcesPlugin.getWorkspace(); + IResourceChangeListener listener= new IResourceChangeListener() { + public void resourceChanged(IResourceChangeEvent event) { + TestModelProvider.assertTrue(event.getDelta()); + } + }; + try { + clearPreDelta(); + workspace.checkpoint(false); + workspace.addResourceChangeListener(listener); + JavaCore.run(op, new NullProgressMonitor()); + } finally { + workspace.removeResourceChangeListener(listener); + } + } else { + JavaCore.run(op, new NullProgressMonitor()); + } + assertTrue("Precondition check failed: " + op.getConditionStatus().toString(), !op.getConditionStatus().hasFatalError()); + assertTrue("Validation check failed: " + op.getConditionStatus().toString(), !op.getValidationStatus().hasFatalError()); + assertNotNull("No Undo", op.getUndoChange()); + compareSource(unit.getSource(), out); + Change undo= op.getUndoChange(); + assertNotNull("Undo doesn't exist", undo); + assertTrue("Undo manager is empty", undoManager.anythingToUndo()); + + if (doUndo) { + undoManager.performUndo(null, new NullProgressMonitor()); + assertTrue("Undo manager still has undo", !undoManager.anythingToUndo()); + assertTrue("Undo manager is empty", undoManager.anythingToRedo()); + compareSource(original, unit.getSource()); + } + break; + } + } + + protected RefactoringStatus checkPreconditions(Refactoring refactoring, IProgressMonitor pm) throws CoreException { + CheckConditionsOperation op= new CheckConditionsOperation(refactoring, getCheckingStyle()); + op.run(pm); + return op.getStatus(); + } + + protected int getCheckingStyle() { + return CheckConditionsOperation.ALL_CONDITIONS; + } + + protected void clearPreDelta() { + TestModelProvider.clearDelta(); + } + + private void initializeSelection(String source) { + int start= -1; + int end= -1; + int includingStart= source.indexOf(SQUARE_BRACKET_OPEN); + int excludingStart= source.indexOf(SQUARE_BRACKET_CLOSE); + int includingEnd= source.lastIndexOf(SQUARE_BRACKET_CLOSE); + int excludingEnd= source.lastIndexOf(SQUARE_BRACKET_OPEN); + + if (includingStart > excludingStart && excludingStart != -1) { + includingStart= -1; + } else if (excludingStart > includingStart && includingStart != -1) { + excludingStart= -1; + } + + if (includingEnd < excludingEnd) { + includingEnd= -1; + } else if (excludingEnd < includingEnd) { + excludingEnd= -1; + } + + if (includingStart != -1) { + start= includingStart; + } else { + start= excludingStart + SQUARE_BRACKET_CLOSE_LENGTH; + } + + if (excludingEnd != -1) { + end= excludingEnd; + } else { + end= includingEnd + SQUARE_BRACKET_CLOSE_LENGTH; + } + + assertTrue("Selection invalid", start >= 0 && end >= 0 && end >= start); + + fSelection= new int[] { + start - (fIgnoreSelectionMarker ? SQUARE_BRACKET_CLOSE_LENGTH : 0), + end - start + }; + // System.out.println("|"+ source.substring(result[0], result[0] + result[1]) + "|"); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllChangeTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllChangeTests.java new file mode 100644 index 000000000..a003a342c --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllChangeTests.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2000, 2005 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class AllChangeTests { + private static final Class clazz= AllChangeTests.class; + + public static Test suite() { + TestSuite suite= new TestSuite(clazz.getName()); + suite.addTest(new TestSuite(RenameResourceChangeTests.class)); + suite.addTest(new TestSuite(RenameSourceFolderChangeTests.class)); + suite.addTest(new TestSuite(CopyPackageChangeTest.class)); + return new RefactoringTestSetup(suite); + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllRefactoringTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllRefactoringTests.java new file mode 100644 index 000000000..af4d0415d --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllRefactoringTests.java @@ -0,0 +1,90 @@ +/******************************************************************************* + * Copyright (c) 2000, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +public class AllRefactoringTests { + + private static final Class clazz= AllRefactoringTests.class; + + public static Test suite() { + TestSuite suite= new TestSuite(clazz.getName()); + + //--code + suite.addTest(ExtractMethodTests.suite()); + suite.addTest(InlineMethodTests.suite()); + suite.addTest(ReplaceInvocationsTests.suite()); + suite.addTest(SefTests.suite()); + suite.addTest(InlineTempTests.suite()); + suite.addTest(ExtractTempTests.suite()); + suite.addTest(RenameTempTests.suite()); + suite.addTest(ExtractConstantTests.suite()); + suite.addTest(PromoteTempToFieldTests.suite()); + suite.addTest(ConvertAnonymousToNestedTests.suite()); + suite.addTest(InlineConstantTests.suite()); + suite.addTest(IntroduceParameterTests.suite()); + suite.addTest(IntroduceFactoryTests.suite()); + + //-- structure + suite.addTest(ChangeSignatureTests.suite()); + suite.addTest(IntroduceParameterObjectTests.suite()); + suite.addTest(PullUpTests.suite()); + suite.addTest(PushDownTests.suite()); + suite.addTest(MoveMembersTests.suite()); + suite.addTest(ExtractInterfaceTests.suite()); + suite.addTest(ExtractSupertypeTests.suite()); + suite.addTest(MoveInnerToTopLevelTests.suite()); + suite.addTest(UseSupertypeWherePossibleTests.suite()); + suite.addTest(ExtractClassTests.suite()); + + //-- generics + suite.addTest(InferTypeArgumentsTests.suite()); + + //--methods + suite.addTest(RenameVirtualMethodInClassTests.suite()); + suite.addTest(RenameMethodInInterfaceTests.suite()); + suite.addTest(RenamePrivateMethodTests.suite()); + suite.addTest(RenameStaticMethodTests.suite()); + suite.addTest(RenameParametersTests.suite()); + suite.addTest(MoveInstanceMethodTests.suite()); + suite.addTest(IntroduceIndirectionTests.suite()); + + //--types + suite.addTest(RenameTypeTests.suite()); + suite.addTest(RenameTypeParameterTests.suite()); + suite.addTest(ChangeTypeRefactoringTests.suite()); + + //--packages + suite.addTest(RenamePackageTests.suite()); + + //--fields + suite.addTest(RenamePrivateFieldTests.suite()); + suite.addTest(RenameNonPrivateFieldTests.suite()); + + //--projects + suite.addTest(RenameJavaProjectTests.suite()); + + //--binaries + suite.addTest(BinaryReferencesTests.suite()); + + // validate edit +// suite.addTest(ValidateEditTests.suite()); + + //--helpers + suite.addTest(RenamingNameSuggestorTests.suite()); + suite.addTest(DelegateCreatorTests.suite()); + return suite; + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllTests.java new file mode 100644 index 000000000..0e1e4bc52 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllTests.java @@ -0,0 +1,31 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class AllTests { + + private static final Class clazz= AllTests.class; + + public static Test suite() { + TestSuite suite= new TestSuite(clazz.getName()); + suite.addTest(AllRefactoringTests.suite()); + suite.addTest(AllChangeTests.suite()); + suite.addTest(UndoManagerTests.suite()); + suite.addTest(PathTransformationTests.suite()); + suite.addTest(RefactoringScannerTests.suite()); + suite.addTest(SurroundWithTests.suite()); + return suite; + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/BinaryReferencesTestSetup.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/BinaryReferencesTestSetup.java new file mode 100644 index 000000000..e9ecb1dcd --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/BinaryReferencesTestSetup.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +import org.osgi.framework.Bundle; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.Path; + +import org.eclipse.core.resources.IFolder; + +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; + +import org.eclipse.jdt.ui.tests.refactoring.infra.AbstractRefactoringTestSetup; +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringTestPlugin; + +/** + * Sets up two projects for testing binary references. Contents taken from /resources/BinaryReferencesWorkspace. + */ +public class BinaryReferencesTestSetup extends AbstractRefactoringTestSetup { + + public BinaryReferencesTestSetup(Test test) { + super(test); + } + + private IJavaProject fSource; + private IJavaProject fBinaryReference; + + public IJavaProject getSourceProject() { + return fSource; + } + + public IJavaProject getBinaryReferenceProject() { + return fBinaryReference; + } + + protected void setUp() throws Exception { + super.setUp(); + Bundle bundle= RefactoringTestPlugin.getDefault().getBundle(); + + fSource= JavaProjectHelper.createJavaProject("Source", "bin"); + JavaProjectHelper.addRTJar(fSource); + IPackageFragmentRoot sourceContainer= JavaProjectHelper.addSourceContainer(fSource, "src"); + JavaProjectHelper.importResources((IFolder) sourceContainer.getResource(), bundle, "resources/BinaryReferencesWorkspace/Source/src"); + + + fBinaryReference= JavaProjectHelper.createJavaProject("BinaryReference", null); + JavaProjectHelper.addRTJar(fBinaryReference); + + IClasspathEntry cpeSource= JavaCore.newProjectEntry(fSource.getProject().getFullPath()); + JavaProjectHelper.addToClasspath(fBinaryReference, cpeSource); + + IFolder binary= fBinaryReference.getProject().getFolder("binary"); + binary.create(false, true, null); + JavaProjectHelper.importResources(binary, bundle, "resources/BinaryReferencesWorkspace/Reference/bin"); + // attach source to get search results ( https://bugs.eclipse.org/bugs/show_bug.cgi?id=127442 ): + IFolder srcAtt= fBinaryReference.getProject().getFolder("srcAtt"); + srcAtt.create(false, true, null); + JavaProjectHelper.importResources(srcAtt, bundle, "resources/BinaryReferencesWorkspace/Reference/src"); + + IClasspathEntry cpeBinary= JavaCore.newLibraryEntry(binary.getFullPath(), srcAtt.getFullPath(), Path.ROOT, false); + JavaProjectHelper.addToClasspath(fBinaryReference, cpeBinary); + } + + protected void tearDown() throws Exception { + JavaProjectHelper.delete(fSource); + JavaProjectHelper.delete(fBinaryReference); + super.tearDown(); + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/BinaryReferencesTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/BinaryReferencesTests.java new file mode 100644 index 000000000..3ea2c7616 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/BinaryReferencesTests.java @@ -0,0 +1,467 @@ +/******************************************************************************* + * Copyright (c) 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; + +import org.eclipse.ltk.core.refactoring.CheckConditionsOperation; +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.MoveRefactoring; +import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.ExpressionStatement; +import org.eclipse.jdt.core.dom.MethodDeclaration; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.JavaRefactoringDescriptor; +import org.eclipse.jdt.core.refactoring.descriptors.MoveDescriptor; +import org.eclipse.jdt.core.refactoring.descriptors.MoveStaticMembersDescriptor; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; +import org.eclipse.jdt.core.search.SearchMatch; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; +import org.eclipse.jdt.internal.corext.refactoring.ParameterInfo; +import org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext; +import org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring; +import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil; +import org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureProcessor; +import org.eclipse.jdt.internal.corext.refactoring.structure.MoveInstanceMethodProcessor; +import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; + +import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; + +public class BinaryReferencesTests extends TestCase { + + private static BinaryReferencesTestSetup fgTestSetup; + + public BinaryReferencesTests(String name) { + super(name); + } + + public static Test suite() { + fgTestSetup= new BinaryReferencesTestSetup(new TestSuite(BinaryReferencesTests.class)); + return fgTestSetup; + } + + public static Test setUpTest(Test test) { + fgTestSetup= new BinaryReferencesTestSetup(test); + return fgTestSetup; + } + + private static void assertContainsMatches(List matches, String[] expectedHandleIdentifiers) { + int matchCount= matches.size(); + assertTrue("match count too small: " + matchCount, matchCount >= expectedHandleIdentifiers.length); + + List actual= new ArrayList(); + for (int i= 0; i < matchCount; i++) { + SearchMatch match= (SearchMatch) matches.get(i); + String handleIdentifier= ((IJavaElement) match.getElement()).getHandleIdentifier(); + actual.add(handleIdentifier); + } + List expected= new ArrayList(Arrays.asList(expectedHandleIdentifiers)); + expected.removeAll(actual); + if (expected.size() != 0) + assertEquals("not all expected matches", expected.toString(), actual.toString()); + } + + private static IType findType(String typeName) throws JavaModelException { + return fgTestSetup.getSourceProject().findType(typeName); + } + + private static IMethod findMethod(IType type, String methodName) throws JavaModelException { + IMethod method= type.getMethod(methodName, new String[0]); + if (! method.exists()) { + IMethod[] methods= type.getMethods(); + for (int i= 0; i < methods.length; i++) { + if (methods[i].getElementName().equals(methodName)) { + method= methods[i]; + break; + } + } + } + return method; + } + + private static List doRefactoring(JavaRefactoringDescriptor descriptor) throws CoreException { + RefactoringStatus status= new RefactoringStatus(); + Refactoring refactoring= descriptor.createRefactoring(status); + assertTrue(status.isOK()); + + return doCheckConditions(refactoring); + } + + private static List doCheckConditions(Refactoring refactoring) throws CoreException { + CheckConditionsOperation op= new CheckConditionsOperation(refactoring, CheckConditionsOperation.ALL_CONDITIONS); + op.run(null); + RefactoringStatus validationStatus= op.getStatus(); + assertTrue(!validationStatus.hasFatalError()); + assertTrue(validationStatus.hasError()); + assertEquals(1, validationStatus.getEntries().length); + + ReferencesInBinaryContext context= (ReferencesInBinaryContext) validationStatus.getEntryAt(0).getContext(); + return context.getMatches(); + } + + public void testRenameType01() throws Exception { + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_TYPE); + descriptor.setJavaElement(findType("source.BaseClass")); + descriptor.setNewName("RenamedBaseClass"); + descriptor.setUpdateReferences(true); + + List matches= doRefactoring(descriptor); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(SubClass.class[SubClass", + "=BinaryReference/binary<ref(SubClass.class[SubClass", + "=BinaryReference/binary<ref(SubClass.class[SubClass~compareTo~Lsource.BaseClass;" + }); + } + + public void testRenameType02() throws Exception { + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_TYPE); + descriptor.setJavaElement(findType("source.Color")); + descriptor.setNewName("Colour"); + descriptor.setUpdateSimilarDeclarations(true); + descriptor.setMatchStrategy(RenameJavaElementDescriptor.STRATEGY_SUFFIX); + descriptor.setUpdateReferences(true); + + RefactoringStatus status= new RefactoringStatus(); + Refactoring refactoring= descriptor.createRefactoring(status); + assertTrue(status.isOK()); + + CheckConditionsOperation op= new CheckConditionsOperation(refactoring, CheckConditionsOperation.ALL_CONDITIONS); + op.run(null); + RefactoringStatus validationStatus= op.getStatus(); + assertTrue(!validationStatus.hasFatalError()); + assertTrue(validationStatus.hasError()); + assertEquals(2, validationStatus.getEntries().length); + + ReferencesInBinaryContext context= (ReferencesInBinaryContext) validationStatus.getEntryAt(0).getContext(); + List matches= context.getMatches(); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(SubClass.class[SubClass", + "=BinaryReference/binary<ref(SubClass.class[SubClass~paintColor~Lsource.Color;" + }); + + context= (ReferencesInBinaryContext) validationStatus.getEntryAt(1).getContext(); + matches= context.getMatches(); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;" + }); + } + + private static List doRenameMethod(String typeName, String methodName) throws CoreException { + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_METHOD); + IMethod method= findMethod(findType(typeName), methodName); + descriptor.setJavaElement(method); + descriptor.setNewName("newName"); + descriptor.setUpdateReferences(true); + + return doRefactoring(descriptor); + } + + public void testRenameVirtualMethod01() throws Exception { + List matches= doRenameMethod("source.BaseClass", "baseMethod"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(SubClass.class[SubClass~baseMethod" + }); + } + + public void testRenameVirtualMethod02() throws Exception { + List matches= doRenameMethod("source.BaseClass", "compareTo"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(SubClass.class[SubClass~compareTo~Lsource.BaseClass;" + }); + } + + public void testRenameVirtualMethod03() throws Exception { + List matches= doRenameMethod("source.BaseClass", "referencedVirtualMethod"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;", + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;", + "=BinaryReference/binary<ref(SubClass.class[SubClass~baseMethod" + }); + } + + public void testRenameNonVirtualMethod01() throws Exception { + List matches= doRenameMethod("source.BaseClass", "referencedMethod"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;" + }); + } + + public void testRenameNonVirtualMethod02() throws Exception { + List matches= doRenameMethod("source.BaseClass", "referencedStaticMethod"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;" + }); + } + + private static List doRenameField(String typeName, String fieldName) throws CoreException { + IField field= findType(typeName).getField(fieldName); + String refactoringID= field.isEnumConstant() ? IJavaRefactorings.RENAME_ENUM_CONSTANT : IJavaRefactorings.RENAME_FIELD; + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(refactoringID); + descriptor.setJavaElement(field); + descriptor.setNewName(field.isEnumConstant() ? "BLA" : "newName"); + descriptor.setUpdateReferences(true); + + return doRefactoring(descriptor); + } + + public void testRenameField01() throws Exception { + List matches= doRenameField("source.BaseClass", "fProtected"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(SubClass.class[SubClass~SubClass~I" + }); + } + + public void testRenameField02() throws Exception { + List matches= doRenameField("source.BaseClass", "fPublic"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;" + }); + } + + public void testRenameField03() throws Exception { + List matches= doRenameField("source.Color", "RED"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;" + }); + } + + public void testRenameField04() throws Exception { + if (true) // https://bugs.eclipse.org/bugs/show_bug.cgi?id=226660 + return; + List matches= doRenameField("source.Color", "GREEN"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;" + }); + } + + public void testRenamePackage01() throws Exception { + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_PACKAGE); + IPackageFragment pack= findType("source.BaseClass").getPackageFragment(); + descriptor.setJavaElement(pack); + descriptor.setNewName("newName"); + descriptor.setUpdateReferences(true); + descriptor.setUpdateHierarchy(false); + + List matches= doRefactoring(descriptor); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass", + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass", + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass", + "=BinaryReference/binary<ref(SubClass.class[SubClass", + "=BinaryReference/binary<ref(SubClass.class[SubClass", + }); + } + + public void testRenamePackage02() throws Exception { + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_PACKAGE); + IPackageFragment pack= findType("source.BaseClass").getPackageFragment(); + descriptor.setJavaElement(pack); + descriptor.setNewName("newName"); + descriptor.setUpdateReferences(true); + descriptor.setUpdateHierarchy(true); + + RefactoringStatus status= new RefactoringStatus(); + Refactoring refactoring= descriptor.createRefactoring(status); + assertTrue(status.isOK()); + CheckConditionsOperation op= new CheckConditionsOperation(refactoring, CheckConditionsOperation.ALL_CONDITIONS); + op.run(null); + RefactoringStatus validationStatus= op.getStatus(); + assertTrue(!validationStatus.hasFatalError()); + assertTrue(validationStatus.hasError()); + assertEquals(2, validationStatus.getEntries().length); + + ReferencesInBinaryContext context= (ReferencesInBinaryContext) validationStatus.getEntryAt(0).getContext(); + List matches= context.getMatches(); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass", + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass", + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass", + "=BinaryReference/binary<ref(SubClass.class[SubClass", + "=BinaryReference/binary<ref(SubClass.class[SubClass", + }); + + context= (ReferencesInBinaryContext) validationStatus.getEntryAt(1).getContext(); + matches= context.getMatches(); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;", + "=BinaryReference/binary<ref(SubClass.class[SubClass" + }); + } + + private static List doChangeSignature(String typeName, String methodName) throws JavaModelException, Exception, CoreException { + IMethod method= findMethod(findType(typeName), methodName); + ChangeSignatureProcessor processor= new ChangeSignatureProcessor(method); + + String[] newNames= { "x" }; + String[] newTypes= { "int" }; + String[] newDefaultValues= { "0" }; + ParameterInfo[] newParamInfos= ChangeSignatureTests.createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= { 0 }; + ChangeSignatureTests.addInfos(processor.getParameterInfos(), newParamInfos, newIndices); + + Refactoring refactoring= new ProcessorBasedRefactoring(processor); + + return doCheckConditions(refactoring); + } + + public void testChangeSignature01() throws Exception { + List matches= doChangeSignature("source.BaseClass", "baseMethod"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(SubClass.class[SubClass~baseMethod", + "=BinaryReference/binary<ref(SubClass.class[SubClass~baseMethod" + }); + } + + public void testChangeSignature02() throws Exception { + List matches= doChangeSignature("source.BaseClass", "compareTo"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(SubClass.class[SubClass~compareTo~Lsource.BaseClass;" + }); + } + + public void testChangeSignature03() throws Exception { + List matches= doChangeSignature("source.BaseClass", "referencedMethod"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;" + }); + } + + public void testChangeConstructorSignature01() throws Exception { + List matches= doChangeSignature("source.BaseClass", "BaseClass"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(SubClass.class[SubClass~SubClass~I", + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;" + }); + } + + private static List doInlineMethod(String typeName, String methodName) throws JavaModelException, Exception, CoreException { + IMethod method= findMethod(findType(typeName), methodName); + ICompilationUnit cu= method.getCompilationUnit(); + CompilationUnit node= new RefactoringASTParser(AST.JLS3).parse(cu, true); + ISourceRange nameRange= method.getNameRange(); + Refactoring refactoring= InlineMethodRefactoring.create(cu, node, nameRange.getOffset(), nameRange.getLength()); + return doCheckConditions(refactoring); + } + + public void testInlineMethod01() throws Exception { + List matches= doInlineMethod("source.BaseClass", "referencedMethod"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;" + }); + } + + public void testInlineMethod02() throws Exception { + // no error if inlining only selected reference from source + IMethod baseMethod= findMethod(findType("source.BaseClass"), "baseMethod"); + ICompilationUnit cu= baseMethod.getCompilationUnit(); + + CompilationUnit node= new RefactoringASTParser(AST.JLS3).parse(cu, true); + MethodDeclaration baseDecl= ASTNodeSearchUtil.getMethodDeclarationNode(baseMethod, node); + ExpressionStatement methodStmt= (ExpressionStatement) baseDecl.getBody().statements().get(0); + + Refactoring refactoring= InlineMethodRefactoring.create(cu, node, methodStmt.getStartPosition(), methodStmt.getLength()); + CheckConditionsOperation op= new CheckConditionsOperation(refactoring, CheckConditionsOperation.ALL_CONDITIONS); + op.run(null); + RefactoringStatus validationStatus= op.getStatus(); + assertTrue(!validationStatus.hasError()); + } + + private static List doMoveType(String typeName, String newPackageName) throws CoreException { + IType type= findType(typeName); + IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(type); + + MoveDescriptor descriptor= (MoveDescriptor) RefactoringCore.getRefactoringContribution(IJavaRefactorings.MOVE).createDescriptor(); + descriptor.setMoveResources(new IFile[0], new IFolder[0], new ICompilationUnit[] { type.getCompilationUnit() }); + descriptor.setDestination(root.getPackageFragment(newPackageName)); + descriptor.setUpdateReferences(true); + + return doRefactoring(descriptor); + } + + public void testMoveType01() throws Exception { + List matches= doMoveType("source.BaseClass", "source.sub"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(SubClass.class[SubClass", + "=BinaryReference/binary<ref(SubClass.class[SubClass", + "=BinaryReference/binary<ref(SubClass.class[SubClass~compareTo~Lsource.BaseClass;", + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass", + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;", + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;", // + more of these... + }); + } + + private static List doMoveStaticMembers(IMember[] members, String targetTypeName) throws CoreException { + IType targetType= findType(targetTypeName); + + MoveStaticMembersDescriptor descriptor= (MoveStaticMembersDescriptor) RefactoringCore.getRefactoringContribution(IJavaRefactorings.MOVE_STATIC_MEMBERS).createDescriptor(); + descriptor.setDestinationType(targetType); + descriptor.setMembers(members); + + return doRefactoring(descriptor); + } + + public void testMoveStaticMember01() throws Exception { + IType type= findType("source.BaseClass"); + IMethod method= findMethod(type, "referencedStaticMethod"); + IField field= type.getField("CONST"); + List matches= doMoveStaticMembers(new IMember[] { method, field }, "source.sub.InSubPack"); + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;", + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;" + }); + } + + public void testMoveMethod01() throws Exception { + IType type= findType("source.BaseClass"); + IMethod method= findMethod(type, "referencedMethod"); + + MoveInstanceMethodProcessor processor= new MoveInstanceMethodProcessor(method, JavaPreferencesSettings.getCodeGenerationSettings(method.getJavaProject())); + Refactoring ref= new MoveRefactoring(processor); + RefactoringStatus preconditionResult= ref.checkInitialConditions(new NullProgressMonitor()); + assertTrue("activation was supposed to be successful", preconditionResult.isOK()); + + MoveInstanceMethodTests.chooseNewTarget(processor, MoveInstanceMethodTests.PARAMETER, "c"); + List matches= doCheckConditions(ref); + + assertContainsMatches(matches, new String[] { + "=BinaryReference/binary<ref(ReferenceClass.class[ReferenceClass~main~\\[Ljava.lang.String;" + }); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java new file mode 100644 index 000000000..17854a1bd --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java @@ -0,0 +1,2249 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Technical University Berlin - adapted for Object Teams + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.dom.Modifier; +import org.eclipse.jdt.core.refactoring.descriptors.JavaRefactoringDescriptor; + +import org.eclipse.jdt.internal.corext.refactoring.ExceptionInfo; +import org.eclipse.jdt.internal.corext.refactoring.ParameterInfo; +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; +import org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureProcessor; +import org.eclipse.jdt.internal.corext.util.JdtFlags; + +/** + * @see org.eclipse.jdt.core.Signature for encoding of signature strings. + */ +public class ChangeSignatureTests extends RefactoringTest { + private static final Class clazz= ChangeSignatureTests.class; + private static final String REFACTORING_PATH= "ChangeSignature/"; + + private static final boolean BUG_83691_CORE_JAVADOC_REF= true; + + private static final boolean RUN_CONSTRUCTOR_TEST= true; + + public ChangeSignatureTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + if (true) { + return new RefactoringTestSetup(new TestSuite(clazz)); + } else { + System.err.println("*** Running only parts of " + clazz.getName() + "!"); + TestSuite suite= new TestSuite(); + suite.addTest(new ChangeSignatureTests("testDelegate05")); + return new RefactoringTestSetup(suite); + } + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + private String getSimpleTestFileName(boolean canReorder, boolean input){ + String fileName = "A_" + getName(); + if (canReorder) + fileName += input ? "_in": "_out"; + return fileName + ".java"; + } + + private String getTestFileName(boolean canReorder, boolean input){ + String fileName= getTestFolderPath(canReorder); + return fileName + getSimpleTestFileName(canReorder, input); + } + + private String getTestFolderPath(boolean canModify) { + String fileName= TEST_PATH_PREFIX + getRefactoringPath(); + fileName += (canModify ? "canModify/": "cannotModify/"); + return fileName; + } + + //---helpers + + protected ICompilationUnit createCUfromTestFile(IPackageFragment pack, boolean canRename, boolean input) throws Exception { + return createCU(pack, getSimpleTestFileName(canRename, input), getFileContents(getTestFileName(canRename, input))); + } + + static ParameterInfo[] createNewParamInfos(String[] newTypes, String[] newNames, String[] newDefaultValues) { + if (newTypes == null) + return new ParameterInfo[0]; + ParameterInfo[] result= new ParameterInfo[newTypes.length]; + for (int i= 0; i < newDefaultValues.length; i++) { + result[i]= ParameterInfo.createInfoForAddedParameter(newTypes[i], newNames[i], newDefaultValues[i]); + } + return result; + } + + static void addInfos(List list, ParameterInfo[] newParamInfos, int[] newIndices) { + if (newParamInfos == null || newIndices == null) + return; + for (int i= newIndices.length - 1; i >= 0; i--) { + list.add(newIndices[i], newParamInfos[i]); + } + } + + private void helperAdd(String[] signature, ParameterInfo[] newParamInfos, int[] newIndices) throws Exception { + helperAdd(signature, newParamInfos, newIndices, false); + } + + private void helperAdd(String[] signature, ParameterInfo[] newParamInfos, int[] newIndices, boolean createDelegate) throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + IType classA= getType(cu, "A"); + IMethod method = classA.getMethod("m", signature); + assertTrue("method does not exist", method.exists()); + assertTrue("refactoring not available", RefactoringAvailabilityTester.isChangeSignatureAvailable(method)); + + ChangeSignatureProcessor processor= new ChangeSignatureProcessor(method); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + processor.setDelegateUpdating(createDelegate); + addInfos(processor.getParameterInfos(), newParamInfos, newIndices); + RefactoringStatus initialConditions= ref.checkInitialConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to pass:"+initialConditions.getEntryWithHighestSeverity(), initialConditions.isOK()); + JavaRefactoringDescriptor descriptor= processor.createDescriptor(); + RefactoringStatus result= performRefactoring(descriptor); + assertEquals("precondition was supposed to pass", null, result); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + String expectedFileContents= getFileContents(getTestFileName(true, false)); + assertEqualLines("invalid renaming", expectedFileContents, newcu.getSource()); + + assertParticipant(classA); + } + + private static void assertParticipant(IType typeOfMethod) throws JavaModelException { + TestChangeMethodSignaturParticipant.testParticipant(typeOfMethod); + } + + /* + * Rename method 'A.m(signature)' to 'A.newMethodName(signature)' + */ + private void helperRenameMethod(String[] signature, String newMethodName, boolean createDelegate) throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + IType classA= getType(cu, "A"); + IMethod method = classA.getMethod("m", signature); + assertTrue("method m does not exist in A", method.exists()); + assertTrue("refactoring not available", RefactoringAvailabilityTester.isChangeSignatureAvailable(method)); + + ChangeSignatureProcessor processor= new ChangeSignatureProcessor(method); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + processor.setNewMethodName(newMethodName); + processor.setDelegateUpdating(createDelegate); + ref.checkInitialConditions(new NullProgressMonitor()); + JavaRefactoringDescriptor descriptor= processor.createDescriptor(); + RefactoringStatus result= performRefactoring(descriptor); + assertEquals("precondition was supposed to pass", null, result); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + String expectedFileContents= getFileContents(getTestFileName(true, false)); + assertEqualLines("invalid change of method name", expectedFileContents, newcu.getSource()); + + assertParticipant(classA); + } + + private void helperDoAll(String typeName, + String methodName, + String[] signature, + ParameterInfo[] newParamInfos, + int[] newIndices, + String[] oldParamNames, + String[] newParamNames, + String[] newParameterTypeNames, + int[] permutation, + int newVisibility, + int[] deleted, String returnTypeName, boolean createDelegate) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + IType classA= getType(cu, typeName); + IMethod method = classA.getMethod(methodName, signature); + assertTrue("method " + methodName +" does not exist", method.exists()); + helperDoAll(method, newParamInfos, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation, newVisibility, deleted, returnTypeName, createDelegate); + } + + private void helperDoAll(IMethod method, ParameterInfo[] newParamInfos, int[] newIndices, String[] oldParamNames, String[] newParamNames, String[] newParameterTypeNames, int[] permutation, int newVisibility, int[] deleted, String returnTypeName, boolean createDelegate) throws Exception { + assertTrue("refactoring not available", RefactoringAvailabilityTester.isChangeSignatureAvailable(method)); + + ChangeSignatureProcessor processor= new ChangeSignatureProcessor(method); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + + if (returnTypeName != null) + processor.setNewReturnTypeName(returnTypeName); + processor.setDelegateUpdating(createDelegate); + markAsDeleted(processor.getParameterInfos(), deleted); + modifyInfos(processor.getParameterInfos(), newParamInfos, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation); + if (newVisibility != JdtFlags.VISIBILITY_CODE_INVALID) + processor.setVisibility(newVisibility); + RefactoringStatus initialConditions= ref.checkInitialConditions(new NullProgressMonitor()); + assertTrue(initialConditions.isOK()); + JavaRefactoringDescriptor descriptor= processor.createDescriptor(); + RefactoringStatus result= performRefactoring(descriptor); + assertEquals("precondition was supposed to pass", null, result); + + IPackageFragment pack= (IPackageFragment)method.getCompilationUnit().getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + String expectedFileContents= getFileContents(getTestFileName(true, false)); + assertEqualLines(expectedFileContents, newcu.getSource()); + + assertParticipant(method.getDeclaringType()); + } + + private void helperDoAll(String typeName, String methodName, String[] signature, ParameterInfo[] newParamInfos, int[] newIndices, + String[] oldParamNames, String[] newParamNames, String[] newParameterTypeNames, int[] permutation, int newVisibility, int[] deleted, + String returnTypeName) throws Exception { + helperDoAll(typeName, methodName, signature, newParamInfos, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation, + newVisibility, deleted, returnTypeName, false); + } + + private void markAsDeleted(List list, int[] deleted) { + if (deleted == null) + return; + for (int i= 0; i < deleted.length; i++) { + ((ParameterInfo)list.get(deleted[i])).markAsDeleted(); + } + } + + private void helper1(String[] newOrder, String[] signature) throws Exception{ + helper1(newOrder, signature, null, null); + } + + private void helper1(String[] newOrder, String[] signature, boolean createDelegate) throws Exception{ + helper1(newOrder, signature, null, null, createDelegate); + } + + private void helper1(String[] newOrder, String[] signature, String[] oldNames, String[] newNames) throws Exception{ + helper1(newOrder, signature, oldNames, newNames, false); + } + + private void helper1(String[] newOrder, String[] signature, String[] oldNames, String[] newNames, boolean createDelegate) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + IType classA= getType(cu, "A"); + IMethod method = classA.getMethod("m", signature); + assertTrue("method does not exist", method.exists()); + assertTrue("refactoring not available", RefactoringAvailabilityTester.isChangeSignatureAvailable(method)); + + ChangeSignatureProcessor processor= new ChangeSignatureProcessor(method); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + processor.setDelegateUpdating(createDelegate); + modifyInfos(processor.getParameterInfos(), newOrder, oldNames, newNames); + ref.checkInitialConditions(new NullProgressMonitor()); + JavaRefactoringDescriptor descriptor= processor.createDescriptor(); + RefactoringStatus result= performRefactoring(descriptor); + assertEquals("precondition was supposed to pass", null, result); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + String expectedFileContents= getFileContents(getTestFileName(true, false)); +// assertEquals("invalid renaming", expectedFileContents, newcu.getSource()); + assertEqualLines(expectedFileContents, newcu.getSource()); + + assertParticipant(classA); + } + + private void modifyInfos(List infos, ParameterInfo[] newParamInfos, int[] newIndices, String[] oldParamNames, String[] newParamNames, String[] newParamTypeNames, int[] permutation) { + addInfos(infos, newParamInfos, newIndices); + List swapped= new ArrayList(infos.size()); + List oldNameList= Arrays.asList(oldParamNames); + List newNameList= Arrays.asList(newParamNames); + for (int i= 0; i < permutation.length; i++) { + if (((ParameterInfo)infos.get(i)).isAdded()) + continue; + if (! swapped.contains(new Integer(i))){ + swapped.add(new Integer(permutation[i])); + + ParameterInfo infoI= (ParameterInfo)infos.get(i); + infoI.setNewName((String)newNameList.get(oldNameList.indexOf(infoI.getOldName()))); + if (newParamTypeNames != null) + infoI.setNewTypeName(newParamTypeNames[oldNameList.indexOf(infoI.getOldName())]); + + ParameterInfo infoI1= (ParameterInfo)infos.get(permutation[i]); + infoI1.setNewName((String)newNameList.get(oldNameList.indexOf(infoI1.getOldName()))); + if (newParamTypeNames != null) + infoI1.setNewTypeName(newParamTypeNames[oldNameList.indexOf(infoI1.getOldName())]); + + swap(infos, i, permutation[i]); + } + } + } + + private static void modifyInfos(List infos, String[] newOrder, String[] oldNames, String[] newNames) { + int[] permutation= createPermutation(infos, newOrder); + List swapped= new ArrayList(infos.size()); + if (oldNames == null || newNames == null){ + ParameterInfo[] newInfos= new ParameterInfo[infos.size()]; + for (int i= 0; i < permutation.length; i++) { + newInfos[i]= (ParameterInfo)infos.get(permutation[i]); + } + infos.clear(); + for (int i= 0; i < newInfos.length; i++) { + infos.add(newInfos[i]); + } + return; + } else { + List oldNameList= Arrays.asList(oldNames); + List newNameList= Arrays.asList(newNames); + for (int i= 0; i < permutation.length; i++) { + if (! swapped.contains(new Integer(i))){ + swapped.add(new Integer(permutation[i])); + ParameterInfo infoI= (ParameterInfo)infos.get(i); + infoI.setNewName((String)newNameList.get(oldNameList.indexOf(infoI.getOldName()))); + ParameterInfo infoI1= (ParameterInfo)infos.get(permutation[i]); + infoI1.setNewName((String)newNameList.get(oldNameList.indexOf(infoI1.getOldName()))); + swap(infos, i, permutation[i]); + } + } + } + } + + private static void swap(List infos, int i, int i1) { + Object o= infos.get(i); + infos.set(i, infos.get(i1)); + infos.set(i1, o); + } + + private static int[] createPermutation(List infos, String[] newOrder) { + int[] result= new int[infos.size()]; + for (int i= 0; i < result.length; i++) { + result[i]= indexOfOldName(infos, newOrder[i]); + } + return result; + } + + private static int indexOfOldName(List infos, String string) { + for (Iterator iter= infos.iterator(); iter.hasNext();) { + ParameterInfo info= (ParameterInfo) iter.next(); + if (info.getOldName().equals(string)) + return infos.indexOf(info); + } + assertTrue(false); + return -1; + } + + private void helperFail(String[] newOrder, String[] signature, int expectedSeverity) throws Exception{ + IType classA= getType(createCUfromTestFile(getPackageP(), false, false), "A"); + IMethod method= classA.getMethod("m", signature); + assertTrue("refactoring not available", RefactoringAvailabilityTester.isChangeSignatureAvailable(method)); + + ChangeSignatureProcessor processor= new ChangeSignatureProcessor(method); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + modifyInfos(processor.getParameterInfos(), newOrder, null, null); + ref.checkInitialConditions(new NullProgressMonitor()); + RefactoringStatus result= ref.checkInitialConditions(new NullProgressMonitor()); + if (result.isOK()) { + JavaRefactoringDescriptor descriptor= processor.createDescriptor(); + result= performRefactoring(descriptor, true); + } + assertNotNull("precondition was supposed to fail", result); + assertEquals("Severity:", expectedSeverity, result.getSeverity()); + } + + private void helperAddFail(String[] signature, ParameterInfo[] newParamInfos, int[] newIndices, int expectedSeverity) throws Exception{ + IType classA= getType(createCUfromTestFile(getPackageP(), false, false), "A"); + IMethod method= classA.getMethod("m", signature); + assertTrue("refactoring not available", RefactoringAvailabilityTester.isChangeSignatureAvailable(method)); + + ChangeSignatureProcessor processor= new ChangeSignatureProcessor(method); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + addInfos(processor.getParameterInfos(), newParamInfos, newIndices); + RefactoringStatus result= ref.checkInitialConditions(new NullProgressMonitor()); + if (result.isOK()) { + JavaRefactoringDescriptor descriptor= processor.createDescriptor(); + result= performRefactoring(descriptor, true); + } + assertNotNull("precondition was supposed to fail", result); + assertEquals("Severity:" + result.getMessageMatchingSeverity(result.getSeverity()), expectedSeverity, result.getSeverity()); + } + + private void helperDoAllFail(String methodName, + String[] signature, + ParameterInfo[] newParamInfos, + int[] newIndices, + String[] oldParamNames, + String[] newParamNames, + String[] newParameterTypeNames, + int[] permutation, + int newVisibility, + int[] deleted, int expectedSeverity) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), false, false); + IType classA= getType(cu, "A"); + IMethod method = classA.getMethod(methodName, signature); + assertTrue("method does not exist", method.exists()); + assertTrue("refactoring not available", RefactoringAvailabilityTester.isChangeSignatureAvailable(method)); + + ChangeSignatureProcessor processor= new ChangeSignatureProcessor(method); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + markAsDeleted(processor.getParameterInfos(), deleted); + modifyInfos(processor.getParameterInfos(), newParamInfos, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation); + if (newVisibility != JdtFlags.VISIBILITY_CODE_INVALID) + processor.setVisibility(newVisibility); + RefactoringStatus result= ref.checkInitialConditions(new NullProgressMonitor()); + if (result.isOK()) { + JavaRefactoringDescriptor descriptor= processor.createDescriptor(); + result= performRefactoring(descriptor); + } + assertNotNull("precondition was supposed to fail", result); + assertEquals("Severity:" + result.getMessageMatchingSeverity(result.getSeverity()), expectedSeverity, result.getSeverity()); + } + + private void helperDoAllWithExceptions(String typeName, + String methodName, + String[] signature, + ParameterInfo[] newParamInfos, + int[] newIndices, + String[] oldParamNames, + String[] newParamNames, + String[] newParameterTypeNames, + int[] permutation, + int newVisibility, + int[] deleted, + String returnTypeName, + String [] removeExceptions, + String[] addExceptions) throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + IType classA= getType(cu, typeName); + IMethod method = classA.getMethod(methodName, signature); + assertTrue("method " + methodName +" does not exist", method.exists()); + assertTrue("refactoring not available", RefactoringAvailabilityTester.isChangeSignatureAvailable(method)); + + ChangeSignatureProcessor processor= new ChangeSignatureProcessor(method); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + if (returnTypeName != null) + processor.setNewReturnTypeName(returnTypeName); + markAsDeleted(processor.getParameterInfos(), deleted); + modifyInfos(processor.getParameterInfos(), newParamInfos, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation); + if (newVisibility != JdtFlags.VISIBILITY_CODE_INVALID) + processor.setVisibility(newVisibility); + + // from RefactoringTest#performRefactoring(): + RefactoringStatus status= ref.checkInitialConditions(new NullProgressMonitor()); + assertTrue("checkActivation was supposed to pass", status.isOK()); + + mangleExceptions(processor.getExceptionInfos(), removeExceptions, addExceptions, method.getCompilationUnit()); + + status= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("checkInput was supposed to pass", status.isOK()); + Change undo= performChange(ref, true); + assertNotNull(undo); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + String expectedFileContents= getFileContents(getTestFileName(true, false)); + assertEqualLines(expectedFileContents, newcu.getSource()); + } + + + private void helperException(String[] signature, String[] removeExceptions, String[] addExceptions) throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + IType classA= getType(cu, "A"); + IMethod method = classA.getMethod("m", signature); + assertTrue("method does not exist", method.exists()); + assertTrue("refactoring not available", RefactoringAvailabilityTester.isChangeSignatureAvailable(method)); + + ChangeSignatureProcessor processor= new ChangeSignatureProcessor(method); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + // from RefactoringTest#performRefactoring(): + RefactoringStatus status= ref.checkInitialConditions(new NullProgressMonitor()); + assertTrue("checkActivation was supposed to pass", status.isOK()); + + mangleExceptions(processor.getExceptionInfos(), removeExceptions, addExceptions, method.getCompilationUnit()); + + status= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("checkInput was supposed to pass", status.isOK()); + Change undo= performChange(ref, true); + assertNotNull(undo); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + String expectedFileContents= getFileContents(getTestFileName(true, false)); + assertEqualLines("invalid renaming", expectedFileContents, newcu.getSource()); + } + + + private void mangleExceptions(List list, String[] removeExceptions, String[] addExceptions, ICompilationUnit cu) throws Exception { + for (Iterator iter= list.iterator(); iter.hasNext(); ) { + ExceptionInfo info= (ExceptionInfo) iter.next(); + String name= info.getFullyQualifiedName(); + for (int i= 0; i < removeExceptions.length; i++) { + if (name.equals(removeExceptions[i])) + info.markAsDeleted(); + } + } + for (int i= 0; i < addExceptions.length; i++) { + IType type= cu.getJavaProject().findType(addExceptions[i]); + list.add(ExceptionInfo.createInfoForAddedException(type)); + } + } + + //------- tests + + public void testFail0() throws Exception{ + helperFail(new String[]{"j", "i"}, new String[]{"I", "I"}, RefactoringStatus.ERROR); + } + + public void testFail1() throws Exception{ + helperFail(new String[0], new String[0], RefactoringStatus.FATAL); + } + + public void testFailAdd2() throws Exception{ + String[] signature= {"I"}; + String[] newNames= {"x"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"0"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + helperAddFail(signature, newParamInfo, newIndices, RefactoringStatus.ERROR); + } + + public void testFailAdd3() throws Exception{ + String[] signature= {"I"}; + String[] newNames= {"x"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"not good"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + helperAddFail(signature, newParamInfo, newIndices, RefactoringStatus.FATAL); + } + + public void testFailAdd4() throws Exception{ + String[] signature= {"I"}; + String[] newNames= {"x"}; + String[] newTypes= {"not a type"}; + String[] newDefaultValues= {"0"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + helperAddFail(signature, newParamInfo, newIndices, RefactoringStatus.FATAL); + } + + public void testFailDoAll5()throws Exception{ + String[] signature= {"I"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"i", "j"}; + String[] newParamNames= {"i", "j"}; + int[] permutation= {0}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.NONE; + int expectedSeverity= RefactoringStatus.ERROR; + helperDoAllFail("m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, expectedSeverity); + } + + public void testFailDoAll6()throws Exception{ + String[] signature= {"I"}; + String[] newNames= {"a"}; + String[] newTypes= {"Certificate"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.NONE; + int expectedSeverity= RefactoringStatus.ERROR; + helperDoAllFail("m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, expectedSeverity); + } + + public void testFailDoAll7()throws Exception{ + String[] signature= {"I"}; + String[] newNames= {"a"}; + String[] newTypes= {"Fred"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.NONE; + int expectedSeverity= RefactoringStatus.ERROR; + helperDoAllFail("m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, expectedSeverity); + } + + public void testFailDoAll8()throws Exception{ + String[] signature= {"I"}; + ParameterInfo[] newParamInfo= null; + int[] newIndices= {0}; + + String[] oldParamNames= {"I"}; + String[] newParamNames= {}; + int[] permutation= {}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.NONE; + int expectedSeverity= RefactoringStatus.ERROR; + helperDoAllFail("run", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, expectedSeverity); + } + + public void testFailAnnotation1() throws Exception{ + IType classA= getType(createCUfromTestFile(getPackageP(), false, false), "A"); + IMethod method= classA.getMethod("name", new String[0]); + assertNotNull(method); + assertFalse(RefactoringAvailabilityTester.isChangeSignatureAvailable(method)); + } + + public void testFailVararg01() throws Exception { + //cannot change m(int, String...) to m(String..., int) + String[] signature= {"I", "[QString;"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"i", "names"}; + String[] newParamNames= {"i", "names"}; + int[] permutation= {1, 0}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + int expectedSeverity= RefactoringStatus.FATAL; + helperDoAllFail("m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, expectedSeverity); + } + + public void testFailVararg02() throws Exception { + //cannot introduce vararg in non-last position + String[] signature= {"I", "[QString;"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"i", "names"}; + String[] newParamNames= {"i", "names"}; + String[] newParamTypeNames= {"int...", "String[]"}; + int[] permutation= {0, 1}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + int expectedSeverity= RefactoringStatus.FATAL; + helperDoAllFail("m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParamTypeNames, permutation, newVisibility, deletedIndices, expectedSeverity); + } + + public void testFailVararg03() throws Exception { + //cannot change parameter type which is vararg in overriding method + String[] signature= {"I", "[QString;"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"i", "names"}; + String[] newParamNames= {"i", "names"}; + String[] newParamTypeNames= {"int", "Object[]"}; + int[] permutation= {1, 0}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + int expectedSeverity= RefactoringStatus.FATAL; + helperDoAllFail("m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParamTypeNames, permutation, newVisibility, deletedIndices, expectedSeverity); + } + + public void testFailVararg04() throws Exception { + //cannot change vararg to non-vararg + String[] signature= {"I", "[QString;"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"i", "names"}; + String[] newParamNames= {"i", "names"}; + String[] newParamTypeNames= {"int", "String[]"}; + int[] permutation= {0, 1}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + int expectedSeverity= RefactoringStatus.FATAL; + helperDoAllFail("m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParamTypeNames, permutation, newVisibility, deletedIndices, expectedSeverity); + } + + public void testFailVararg05() throws Exception { + //cannot move parameter which is vararg in ripple method + String[] signature= {"I", "[QString;"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"i", "names"}; + String[] newParamNames= {"i", "names"}; + int[] permutation= {1, 0}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + int expectedSeverity= RefactoringStatus.FATAL; + helperDoAllFail("m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, expectedSeverity); + } + + public void testFailGenerics01() throws Exception { + //type variable name may not be available in related methods + String[] signature= {"QE;"}; + String[] newNames= {"e2"}; + String[] newTypes= {"E"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {}; + int[] deletedIndices= {}; + int newVisibility= Modifier.NONE; + int expectedSeverity= RefactoringStatus.ERROR; + helperDoAllFail("m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, expectedSeverity); + } + + //--------- + public void test0() throws Exception{ + helper1(new String[]{"j", "i"}, new String[]{"I", "I"}); + } + + public void test1() throws Exception{ + helper1(new String[]{"j", "i"}, new String[]{"I", "I"}); + } + + public void test2() throws Exception{ + helper1(new String[]{"j", "i"}, new String[]{"I", "I"}); + } + + public void test3() throws Exception{ + helper1(new String[]{"j", "i"}, new String[]{"I", "I"}); + } + + public void test4() throws Exception{ + helper1(new String[]{"j", "i"}, new String[]{"I", "I"}); + } + + public void test5() throws Exception{ + helper1(new String[]{"j", "i"}, new String[]{"I", "I"}); + } + + public void test6() throws Exception{ + helper1(new String[]{"k", "i", "j"}, new String[]{"I", "I", "I"}); + } + + public void test7() throws Exception{ + helper1(new String[]{"i", "k", "j"}, new String[]{"I", "I", "I"}); + } + + public void test8() throws Exception{ + helper1(new String[]{"k", "j", "i"}, new String[]{"I", "I", "I"}); + } + + public void test9() throws Exception{ + helper1(new String[]{"j", "i", "k"}, new String[]{"I", "I", "I"}); + } + + public void test10() throws Exception{ + helper1(new String[]{"j", "k", "i"}, new String[]{"I", "I", "I"}); + } + + public void test11() throws Exception{ + helper1(new String[]{"j", "k", "i"}, new String[]{"I", "I", "I"}); + } + + public void test12() throws Exception{ + helper1(new String[]{"j", "k", "i"}, new String[]{"I", "I", "I"}); + } + + public void test13() throws Exception{ + helper1(new String[]{"j", "k", "i"}, new String[]{"I", "I", "I"}); + } + + public void test14() throws Exception{ + helper1(new String[]{"j", "i"}, new String[]{"I", "I"}); + } + + public void test15() throws Exception{ + helper1(new String[]{"b", "i"}, new String[]{"I", "Z"}, true); + } + + public void test16() throws Exception{ + helper1(new String[]{"b", "i"}, new String[]{"I", "Z"}, true); + } + + public void test17() throws Exception{ + //exception because of bug 11151 + helper1(new String[]{"b", "i"}, new String[]{"I", "Z"}, true); + } + + public void test18() throws Exception{ + //exception because of bug 11151 + helper1(new String[]{"b", "i"}, new String[]{"I", "Z"}, true); + } + + public void test19() throws Exception{ +// printTestDisabledMessage("bug 7274 - reorder parameters: incorrect when parameters have more than 1 modifiers"); + helper1(new String[]{"b", "i"}, new String[]{"I", "Z"}, true); + } + public void test20() throws Exception{ +// printTestDisabledMessage("bug 18147"); + helper1(new String[]{"b", "a"}, new String[]{"I", "[I"}, true); + } + +//constructor tests + public void test21() throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + String[] signature= {"I", "I"}; + ParameterInfo[] newParamInfo= null; + int[] newIndices= null; + + String[] oldParamNames= {"a", "b"}; + String[] newParamNames= {"a", "b"}; + int[] permutation= {1, 0}; + int newVisibility= JdtFlags.VISIBILITY_CODE_INVALID;//retain + int[] deleted= null; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deleted, newReturnTypeName); + } + public void test22() throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + String[] signature= {"I", "I"}; + ParameterInfo[] newParamInfo= null; + int[] newIndices= null; + + String[] oldParamNames= {"a", "b"}; + String[] newParamNames= {"a", "b"}; + int[] permutation= {1, 0}; + int newVisibility= JdtFlags.VISIBILITY_CODE_INVALID;//retain + int[] deleted= null; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deleted, newReturnTypeName); + } + public void test23() throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + String[] signature= {"I", "I"}; + ParameterInfo[] newParamInfo= null; + int[] newIndices= null; + + String[] oldParamNames= {"a", "b"}; + String[] newParamNames= {"a", "b"}; + int[] permutation= {1, 0}; + int newVisibility= JdtFlags.VISIBILITY_CODE_INVALID;//retain + int[] deleted= null; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deleted, newReturnTypeName); + } + public void test24() throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } +// if (true){ +// printTestDisabledMessage("Bug 24230"); +// return; +// } + String[] signature= {"I", "I"}; + ParameterInfo[] newParamInfo= null; + int[] newIndices= null; + + String[] oldParamNames= {"a", "b"}; + String[] newParamNames= {"a", "b"}; + int[] permutation= {1, 0}; + int newVisibility= JdtFlags.VISIBILITY_CODE_INVALID;//retain + int[] deleted= null; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deleted, newReturnTypeName); + } + public void test25() throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + String[] signature= {"I", "I"}; + ParameterInfo[] newParamInfo= null; + int[] newIndices= null; + + String[] oldParamNames= {"a", "b"}; + String[] newParamNames= {"a", "b"}; + int[] permutation= {1, 0}; + int newVisibility= JdtFlags.VISIBILITY_CODE_INVALID;//retain + int[] deleted= null; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deleted, newReturnTypeName); + } + public void test26() throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + String[] signature= {"I", "I"}; + ParameterInfo[] newParamInfo= null; + int[] newIndices= null; + + String[] oldParamNames= {"a", "b"}; + String[] newParamNames= {"a", "b"}; + int[] permutation= {1, 0}; + int newVisibility= JdtFlags.VISIBILITY_CODE_INVALID;//retain + int[] deleted= null; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deleted, newReturnTypeName); + } + + public void test27() throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + String[] signature= {"QString;", "QObject;", "I"}; + ParameterInfo[] newParamInfo= createNewParamInfos(new String[]{"Object"}, new String[]{"newParam"}, new String[]{"null"}); + int[] newIndices= { 3 }; + + String[] oldParamNames= {"msg", "xml", "id"}; + String[] newParamNames= {"msg", "xml", "id"}; + int[] permutation= {0, 1, 2}; + int newVisibility= JdtFlags.VISIBILITY_CODE_INVALID;//retain + int[] deleted= null; + String newReturnTypeName= null; + helperDoAll("Query.PoolMessageEvent", "PoolMessageEvent", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deleted, newReturnTypeName, true); + } + + public void testRenameReorder26() throws Exception{ + helper1(new String[]{"a", "y"}, new String[]{"Z", "I"}, new String[]{"y", "a"}, new String[]{"zzz", "bb"}, true); + } + + public void testRenameReorder27() throws Exception{ + helper1(new String[]{"a", "y"}, new String[]{"Z", "I"}, new String[]{"y", "a"}, new String[]{"yyy", "a"}, true); + } + + public void testAdd28()throws Exception{ + String[] signature= {"I"}; + String[] newNames= {"x"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"0"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1}; + helperAdd(signature, newParamInfo, newIndices, true); + } + + public void testAdd29()throws Exception{ + String[] signature= {"I"}; + String[] newNames= {"x"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"0"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + helperAdd(signature, newParamInfo, newIndices, true); + } + + public void testAdd30()throws Exception{ + String[] signature= {"I"}; + String[] newNames= {"x"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"0"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1}; + helperAdd(signature, newParamInfo, newIndices, true); + } + + public void testAdd31()throws Exception{ + String[] signature= {"I"}; + String[] newNames= {"x"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"0"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1}; + helperAdd(signature, newParamInfo, newIndices, true); + } + + public void testAdd32()throws Exception{ + String[] signature= {"I"}; + String[] newNames= {"x"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"0"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + helperAdd(signature, newParamInfo, newIndices, true); + } + + public void testAdd33()throws Exception{ + String[] signature= {}; + String[] newNames= {"x"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"0"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + helperAdd(signature, newParamInfo, newIndices, true); + } + + public void testAddReorderRename34()throws Exception{ + String[] signature= {"I", "Z"}; + String[] newNames= {"x"}; + String[] newTypes= {"Object"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1}; + + String[] oldParamNames= {"iii", "j"}; + String[] newParamNames= {"i", "jj"}; + int[] permutation= {2, -1, 0}; + int[] deletedIndices= null; + int newVisibility= JdtFlags.VISIBILITY_CODE_INVALID;//retain + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName, true); + } + + public void testAll35()throws Exception{ + String[] signature= {"I", "Z"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"iii", "j"}; + String[] newParamNames= oldParamNames; + int[] permutation= {0, 1}; + int[] deletedIndices= null; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll36()throws Exception{ + String[] signature= {"I", "Z"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"iii", "j"}; + String[] newParamNames= oldParamNames; + int[] permutation= {0, 1}; + int[] deletedIndices= null; + int newVisibility= Modifier.PRIVATE; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll37()throws Exception{ + String[] signature= {"I", "Z"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"iii", "j"}; + String[] newParamNames= oldParamNames; + int[] permutation= {0, 1}; + int[] deletedIndices= null; + int newVisibility= Modifier.PROTECTED; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll38()throws Exception{ + String[] signature= {"I", "Z"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"iii", "j"}; + String[] newParamNames= oldParamNames; + int[] permutation= {0, 1}; + int[] deletedIndices= null; + int newVisibility= Modifier.PROTECTED; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll39()throws Exception{ + String[] signature= {"I", "Z"}; + String[] newNames= {"x"}; + String[] newTypes= {"Object"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1}; + + String[] oldParamNames= {"iii", "j"}; + String[] newParamNames= {"i", "jj"}; + int[] permutation= {2, -1, 0}; + int[] deletedIndices= null; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll40()throws Exception{ + String[] signature= {"I", "Z"}; + String[] newNames= {"x"}; + String[] newTypes= {"int[]"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1}; + + String[] oldParamNames= {"iii", "j"}; + String[] newParamNames= {"i", "jj"}; + int[] permutation= {2, -1, 0}; + int[] deletedIndices= null; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll41()throws Exception{ + String[] signature= {"I"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"i"}; + String[] newParamNames= {"i"}; + int[] permutation= {0}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName, true); + } + + public void testAll42()throws Exception{ + String[] signature= {"I"}; + String[] newNames= {"i"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"0"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1}; + + String[] oldParamNames= {"i"}; + String[] newParamNames= {"i"}; + int[] permutation= {0, -1}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll43()throws Exception{ + String[] signature= {"I", "I"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"i", "j"}; + String[] newParamNames= {"i", "j"}; + int[] permutation= {1, 0}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName, true); + } + + public void testAll44()throws Exception{ + if (true){ + printTestDisabledMessage("need to decide how to treat compile errors"); + return; + } + String[] signature= {"I", "I"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"i", "j"}; + String[] newParamNames= {"i", "j"}; + int[] permutation= {0, 1}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.NONE; + String newReturnTypeName= "boolean"; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll45()throws Exception{ + if (true){ + printTestDisabledMessage("need to decide how to treat compile errors"); + return; + } + + String[] signature= {"I", "I"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"i", "j"}; + String[] newParamNames= {"i", "j"}; + String[] newParamTypeNames= {"int", "boolean"}; + int[] permutation= {0, 1}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParamTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll46()throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + + String[] signature= {}; + String[] newNames= {"i"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"1"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= null; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll47()throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + + String[] signature= {}; + String[] newNames= {"i"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"1"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= null; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll48()throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + + String[] signature= {}; + String[] newNames= {"i"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"1"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= null; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll49()throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + + String[] signature= {}; + String[] newNames= {"i"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"1"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= null; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll50()throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + + String[] signature= {}; + String[] newNames= {"i"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"1"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= null; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll51()throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + + String[] signature= {}; + String[] newNames= {"i"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"1"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= null; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll52()throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + + String[] signature= {}; + String[] newNames= {"i"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"1"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= null; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll53()throws Exception{ + String[] signature= {"I"}; + String[] newNames= {"a"}; + String[] newTypes= {"HashSet"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll54()throws Exception{ + String[] signature= {"I"}; + String[] newNames= {"a"}; + String[] newTypes= {"List"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll55()throws Exception{ +// printTestDisabledMessage("test for bug 32654 [Refactoring] Change method signature with problems"); + String[] signature= {"[QObject;", "I", "Z"}; + String[] newNames= {"e"}; + String[] newTypes= {"boolean"}; + String[] newDefaultValues= {"true"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {2}; + helperAdd(signature, newParamInfo, newIndices); + + } + + public void testAll56()throws Exception{ + if (! RUN_CONSTRUCTOR_TEST){ + printTestDisabledMessage("disabled for constructors for now"); + return; + } + +// printTestDisabledMessage("test for 38366 ArrayIndexOutOfBoundsException in change signeture [refactoring] "); + String[] signature= {"QEvaViewPart;", "I"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {}; + + String[] oldParamNames= {"part", "title"}; + String[] newParamNames= {"part", "title"}; + int[] permutation= {0, 1}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("HistoryFrame", "HistoryFrame", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll57()throws Exception{ +// printTestDisabledMessage("test for 39633 classcast exception when refactoring change method signature [refactoring]"); +// if (true) +// return; + String[] signature= {"I", "QString;", "QString;"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"i", "hello", "goodbye"}; + String[] newParamNames= oldParamNames; + int[] permutation= {0, 2, 1}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("TEST.X", "method", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll58()throws Exception{ + String[] signature= {"I", "[[[QString;"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"a", "b"}; + String[] newParamNames= {"abb", "bbb"}; + int[] permutation= {1, 0}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll59() throws Exception{ + String[] signature= {"I", "J"}; + String[] newNames= {"really"}; + String[] newTypes= {"boolean"}; + String[] newDefaultValues= {"true"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {"from", "to"}; + String[] newParamNames= {"f", "t"}; + String[] newParameterTypeNames= {"int", "char"}; + int[] permutation= {0, 1, 2}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= "java.util.List"; + helperDoAll("A", "getList", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll60() throws Exception{ + String[] signature= {"I", "J"}; + String[] newNames= {"l"}; + String[] newTypes= {"java.util.List"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1}; + + String[] oldParamNames= {"from", "to"}; + String[] newParamNames= {"to", "tho"}; + String[] newParameterTypeNames= {"int", "long"}; + int[] permutation= {2, 1, 0}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= "java.util.List"; + String[] removeExceptions= {"java.io.IOException"}; + String[] addExceptions= {"java.lang.Exception"}; + helperDoAllWithExceptions("I", "getList", signature, newParamInfo, newIndices, + oldParamNames, newParamNames, newParameterTypeNames, permutation, newVisibility, + deletedIndices, newReturnTypeName, removeExceptions, addExceptions); + } + + public void testAll61()throws Exception{ //bug 51634 + String[] signature= {}; + ParameterInfo[] newParamInfo= null; + int[] newIndices= null; + + String[] oldParamNames= {}; + String[] newParamNames= oldParamNames; + int[] permutation= {}; + int[] deletedIndices= null; + int newVisibility= Modifier.NONE; + String newReturnTypeName= "Object"; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll62()throws Exception{ //bug + String[] signature= {"QBigInteger;", "QBigInteger;", "QBigInteger;"}; + ParameterInfo[] newParamInfo= null; + int[] newIndices= null; + String[] newParamTypeNames= {"long", "long", "long"}; + String[] oldParamNames= {"a", "b", "c"}; + String[] newParamNames= {"x", "y", "z"}; + int[] permutation= {0, 1, 2}; + int[] deletedIndices= null; + int newVisibility= Modifier.NONE; + String newReturnTypeName= "void"; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParamTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll63()throws Exception{ //bug + String[] signature= {}; + ParameterInfo[] newParamInfo= null; + int[] newIndices= null; + String[] newParamTypeNames= {}; + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {}; + int[] deletedIndices= null; + int newVisibility= Modifier.PROTECTED; + String newReturnTypeName= "void"; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParamTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testAll64() throws Exception{ // https://bugs.eclipse.org/bugs/show_bug.cgi?id=158008 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=201929 + ParameterInfo[] newParamInfo= { ParameterInfo.createInfoForAddedParameter("java.util.List<Local>", "list", "null") }; + int[] newIndices= { 2 }; + String[] newParamTypeNames= {}; + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.PRIVATE; + String newReturnTypeName= "void"; + + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + int lastNasty= cu.getSource().lastIndexOf("nasty"); + IMethod method= (IMethod) cu.getElementAt(lastNasty); + assertTrue(method.exists()); + helperDoAll(method, newParamInfo, newIndices, oldParamNames, newParamNames, newParamTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName, false); + } + + public void testAddSyntaxError01()throws Exception{ // https://bugs.eclipse.org/bugs/show_bug.cgi?id=191349 + String refNameIn= "A_testAddSyntaxError01_Ref_in.java"; + String refNameOut= "A_testAddSyntaxError01_Ref_out.java"; + ICompilationUnit refCu= createCU(getPackageP(), refNameIn, getFileContents(getTestFolderPath(true) + refNameIn)); + + String[] signature= {"QString;"}; + String[] newNames= {"newParam"}; + String[] newTypes= {"Object"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfos= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= { 1 }; + helperAdd(signature, newParamInfos, newIndices); + + String expectedRefContents= getFileContents(getTestFolderPath(true) + refNameOut); + assertEqualLines(expectedRefContents, refCu.getSource()); + } + + public void testAddRecursive1()throws Exception{ //bug 42100 + String[] signature= {"I"}; + String[] newNames= {"bool"}; + String[] newTypes= {"boolean"}; + String[] newDefaultValues= {"true"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1}; + helperAdd(signature, newParamInfo, newIndices, true); + } + + public void testException01() throws Exception { + String[] signature= {"J"}; + String[] remove= {}; + String[] add= {"java.util.zip.ZipException"}; + helperException(signature, remove, add); + } + + public void testException02() throws Exception { + String[] add= new String[] {"java.lang.RuntimeException"}; + helperException(new String[0], new String[0], add); + } + + public void testException03() throws Exception { //bug 52091 + String[] remove= new String[] {"java.lang.RuntimeException"}; + helperException(new String[0], remove, new String[0]); + } + + public void testException04() throws Exception { //bug 52058 + String[] add= new String[] {"java.io.IOException", "java.lang.ClassNotFoundException"}; + helperException(new String[0], new String[0], add); + } + + public void testException05() throws Exception { //bug 56132 + String[] remove= new String[] {"java.lang.IllegalArgumentException", "java.io.IOException"}; + helperException(new String[0], remove, new String[0]); + } + + public void testInStatic01() throws Exception { //bug 47062 + String[] signature= {"QString;", "QString;"}; + ParameterInfo[] newParamInfo= null; + int[] newIndices= null; + + String[] oldParamNames= {"arg1", "arg2"}; + String[] newParamNames= {"a", "b"}; + int[] permutation= {1, 0}; + int newVisibility= JdtFlags.VISIBILITY_CODE_INVALID;//retain + int[] deleted= null; + String newReturnTypeName= null; + helperDoAll("Example", "Example", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deleted, newReturnTypeName); + } + + public void testInStatic02() throws Exception { //bug 47062 + String[] signature= {"QString;", "QString;"}; + ParameterInfo[] newParamInfo= null; + int[] newIndices= null; + + String[] oldParamNames= {"arg1", "arg2"}; + String[] newParamNames= {"a", "b"}; + int[] permutation= {1, 0}; + int newVisibility= JdtFlags.VISIBILITY_CODE_INVALID;//retain + int[] deleted= null; + String newReturnTypeName= null; + helperDoAll("Example", "getExample", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deleted, newReturnTypeName); + } + + public void testName01() throws Exception { + String[] signature= {"QString;"}; + helperRenameMethod(signature, "newName", false); + } + + public void testName02() throws Exception { + String[] signature= {"QString;"}; + helperRenameMethod(signature, "newName", false); + } + + public void testFailImport01() throws Exception { + String[] signature= {}; + String[] newTypes= {"Permission"}; + String[] newNames= {"p"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + helperAddFail(signature, newParamInfo, newIndices, RefactoringStatus.ERROR); + } + + public void testImport01() throws Exception { + String[] signature= {}; + String[] newTypes= {"java.security.acl.Permission", "Permission"}; + String[] newNames= {"acl", "p"}; + String[] newDefaultValues= {"null", "perm"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0, 0}; + helperAdd(signature, newParamInfo, newIndices); + } + + public void testImport02() throws Exception { + String[] signature= {}; + String[] newTypes= {"Permission", "java.security.acl.Permission"}; + String[] newNames= {"p", "acl"}; + String[] newDefaultValues= {"null", "null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0, 0}; + helperAdd(signature, newParamInfo, newIndices); + } + + public void testImport03() throws Exception { + String[] signature= {}; + String[] newTypes= {"java.security.acl.Permission", "java.security.Permission"}; + String[] newNames= {"p", "pp"}; + String[] newDefaultValues= {"0", "0"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0, 0}; + helperAdd(signature, newParamInfo, newIndices); + } + + public void testImport04() throws Exception { + String[] signature= {}; + String[] newTypes= {"Object"}; + String[] newNames= {"o"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + helperAdd(signature, newParamInfo, newIndices); + } + + public void testImport05() throws Exception { + // printTestDisabledMessage("49772: Change method signature: remove unused imports [refactoring]"); + String[] signature= {}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {}; + int[] deletedIndices= null; + int newVisibility= Modifier.NONE; + String newReturnTypeName= "Object"; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testImport06() throws Exception { + String[] signature= {"QPermission;", "Qjava.security.acl.Permission;"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {}; + + String[] oldParamNames= {"perm", "acl"}; + String[] newParamNames= {"xacl", "xperm"}; + String[] newParamTypeNames= {"java.security.acl.Permission [] []", "java.security.Permission"}; + int[] permutation= {1, 0}; + int[] deletedIndices= null; + int newVisibility= Modifier.NONE; + String newReturnTypeName= "java.security.acl.Permission"; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParamTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testImport07() throws Exception { + // printTestDisabledMessage("49772: Change method signature: remove unused imports [refactoring]"); + String[] signature= {"QList;"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {}; + + String[] oldParamNames= {"list"}; + String[] newParamNames= oldParamNames; + String[] newParamTypeNames= null; + int[] permutation= {0}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParamTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testImport08() throws Exception { + // printTestDisabledMessage("68504: Refactor -> Change Method Signature removes import [refactoring]"); + String[] signature= {"QString;", "QVector;"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {}; + + String[] oldParamNames= {"text", "v"}; + String[] newParamNames= oldParamNames; + String[] newParamTypeNames= null; + int[] permutation= {1, 0}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "textContains", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParamTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testEnum01() throws Exception { + if (BUG_83691_CORE_JAVADOC_REF) { + printTestDisabledMessage("BUG_83691_CORE_JAVADOC_REF"); + return; + } + String[] signature= {"I"}; + String[] newNames= {"a"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"17"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1}; + + String[] oldParamNames= {"i"}; + String[] newParamNames= {"i"}; + int[] permutation= {0}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PRIVATE; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testEnum02() throws Exception { + String[] signature= {"I"}; + String[] newNames= {"a"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"17"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1}; + + String[] oldParamNames= {"i"}; + String[] newParamNames= {"i"}; + int[] permutation= {0}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PRIVATE; + String newReturnTypeName= null; + helperDoAll("A_testEnum02_in", "A_testEnum02_in", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testEnum03() throws Exception { + if (BUG_83691_CORE_JAVADOC_REF) { + printTestDisabledMessage("BUG_83691_CORE_JAVADOC_REF"); + return; + } + String[] signature= {}; + String[] newNames= {"obj"}; + String[] newTypes= {"Object"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {}; + int[] deletedIndices= {}; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "A", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testEnum04() throws Exception { + String[] signature= {}; + String[] newNames= {"forward"}; + String[] newTypes= {"boolean"}; + String[] newDefaultValues= {"true"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "getNext", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testStaticImport01() throws Exception { + helperRenameMethod(new String[0], "abc", false); + } + + public void testStaticImport02() throws Exception { + String[] signature= {"QInteger;"}; + String[] newTypes= {"Object"}; + String[] newNames= {"o"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1}; + helperAdd(signature, newParamInfo, newIndices); + } + + public void testVararg01() throws Exception { + String[] signature= {"I", "[QString;"}; + String[] newNames= {}; + String[] newTypes= {}; + String[] newDefaultValues= {}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {}; + + String[] oldParamNames= {"i", "names"}; + String[] newParamNames= {"i", "strings"}; + int[] permutation= {0, 1}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testVararg02() throws Exception { + String[] signature= {"I", "[QString;"}; + String[] newNames= {"o"}; + String[] newTypes= {"Object"}; + String[] newDefaultValues= {"new Object()"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {"i", "names"}; + String[] newParamNames= oldParamNames; + int[] permutation= {0, 1, 2}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName, true); + } + + public void testVararg03() throws Exception { + String[] signature= {"[QString;"}; + String[] newNames= {}; + String[] newTypes= {}; + String[] newDefaultValues= {}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {}; + + String[] oldParamNames= {"args"}; + String[] newParamNames= oldParamNames; + String[] newParameterTypeNames= {"Object..."}; + int[] permutation= {0}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "use", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testVararg04() throws Exception { + String[] signature= {"[QString;"}; + String[] newNames= {"i"}; + String[] newTypes= {"int"}; + String[] newDefaultValues= {"1"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {"args"}; + String[] newParamNames= {"args"}; + int[] permutation= {}; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "use", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testVararg05() throws Exception { + String[] signature= {"QObject;", "[QString;"}; + String[] newNames= {}; + String[] newTypes= {}; + String[] newDefaultValues= {}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {}; + + String[] oldParamNames= {"first", "args"}; + String[] newParamNames= {"arg", "invalid name"}; + int[] permutation= {0, 1}; + int[] deletedIndices= {1}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "use", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName, true); + } + + public void testVararg06() throws Exception { + String[] signature= {"I", "[QString;"}; + String[] newNames= {}; + String[] newTypes= {}; + String[] newDefaultValues= {}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {}; + + String[] oldParamNames= {"i", "names"}; + String[] newParamNames= {"i", "names"}; + String[] newParameterTypeNames= {"int", "String..."}; + int[] permutation= {0, 1}; + int[] deletedIndices= { }; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testVararg07() throws Exception { + //can remove parameter which is vararg in ripple method + String[] signature= {"I", "[QString;"}; + String[] newNames= {"j", "k"}; + String[] newTypes= {"String", "Integer"}; + String[] newDefaultValues= {"\"none\"", "17"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {1, 2}; + + String[] oldParamNames= {"i", "names"}; + String[] newParamNames= {"i", "names"}; + int[] permutation= {0, 1, 2, 3}; + int[] deletedIndices= { 1 }; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName, true); + } + + public void testVararg08() throws Exception { + //can add vararg parameter with empty default value + String[] signature= {}; + String[] newNames= {"args"}; + String[] newTypes= {"String ..."}; + String[] newDefaultValues= {""}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= { }; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testVararg09() throws Exception { + //can add vararg parameter with one-expression default value + String[] signature= {}; + String[] newNames= {"args"}; + String[] newTypes= {"String ..."}; + String[] newDefaultValues= {"\"Hello\""}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= { }; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testVararg10() throws Exception { + //can add vararg parameter with multiple-expressions default value + String[] signature= {}; + String[] newNames= {"args"}; + String[] newTypes= {"String ..."}; + String[] newDefaultValues= {"\"Hello\", new String()"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {0}; + + String[] oldParamNames= {}; + String[] newParamNames= {}; + int[] permutation= {0}; + int[] deletedIndices= { }; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testGenerics01() throws Exception { + String[] signature= {"QInteger;", "QE;"}; + String[] newNames= {}; + String[] newTypes= {}; + String[] newDefaultValues= {}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {}; + + String[] oldParamNames= {"i", "e"}; + String[] newParamNames= {"integer", "e"}; + String[] newParameterTypeNames= null; + int[] permutation= {1, 0}; + int[] deletedIndices= { }; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName, true); + } + + public void testGenerics02() throws Exception { + String[] signature= {"QT;", "QE;"}; + String[] newNames= {"maps"}; + String[] newTypes= {"java.util.List<HashMap>"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {2}; + + String[] oldParamNames= {"e", "t"}; + String[] newParamNames= {"e", "t"}; + String[] newParameterTypeNames= null; + int[] permutation= {1, 0, 2}; + int[] deletedIndices= { }; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testGenerics03() throws Exception { + String[] signature= {"QT;", "QE;"}; + String[] newNames= {"maps"}; + String[] newTypes= {"java.util.List<HashMap>"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {2}; + + String[] oldParamNames= {"e", "t"}; + String[] newParamNames= {"e", "t"}; + String[] newParameterTypeNames= null; + int[] permutation= {1, 0, 2}; + int[] deletedIndices= { }; + int newVisibility= Modifier.NONE; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testGenerics04() throws Exception { + String[] signature= {"QList<QInteger;>;", "QA<QString;>;"}; + String[] newNames= {"li"}; + String[] newTypes= {"List<Integer>"}; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {2}; + +//{ObjectTeams: avoid keyword "as" - renamed to "a_of_string" + String[] oldParamNames= {"li", "a_of_string"}; + String[] newParamNames= {"li", "a_of_string"}; +// SH} + String[] newParameterTypeNames= null; + int[] permutation= {1, 2, 0}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testGenerics05() throws Exception { + String[] signature= { "QClass;" }; + String[] newNames= {}; + String[] newTypes= {}; + String[] newDefaultValues= {}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {}; + + String[] oldParamNames= { "arg" }; + String[] newParamNames= { "arg" }; + String[] newParameterTypeNames= { "Class<?>" }; + int[] permutation= { 0 }; + int[] deletedIndices= {}; + int newVisibility= Modifier.PUBLIC; + String newReturnTypeName= null; + helperDoAll("I", "test", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation, + newVisibility, deletedIndices, newReturnTypeName); + } + + public void testGenerics06() throws Exception { + String[] signature= { "QString;" }; + String[] newNames= {}; + String[] newTypes= {}; + String[] newDefaultValues= {}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= {}; + + String[] oldParamNames= { "string" }; + String[] newParamNames= {}; + String[] newParameterTypeNames= {}; + int[] permutation= {}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.PRIVATE; + String newReturnTypeName= null; + helperDoAll("C", "foo", signature, newParamInfo, newIndices, oldParamNames, newParamNames, newParameterTypeNames, permutation, newVisibility, deletedIndices, newReturnTypeName); + } + + public void testDelegate01() throws Exception { + // simple reordering with delegate + helper1(new String[]{"j", "i"}, new String[]{"I", "QString;"}, null, null, true); + } + + public void testDelegate02() throws Exception { + // add a parameter -> import it + String[] signature= {}; + String[] newTypes= {"java.util.List" }; + String[] newNames= {"list" }; + String[] newDefaultValues= {"null"}; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= { 0 }; + helperAdd(signature, newParamInfo, newIndices, true); + } + + public void testDelegate03() throws Exception { + // reordering with imported type in body => don't remove import + helper1(new String[]{"j", "i"}, new String[]{"I", "QString;"}, null, null, true); + } + + public void testDelegate04() throws Exception { + // delete a parameter => import stays + String[] signature= {"QList;"}; + String[] newNames= null; + String[] newTypes= null; + String[] newDefaultValues= null; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= null; + + String[] oldParamNames= {"l"}; + String[] newParamNames= {"l"}; + int[] permutation= {}; + int[] deletedIndices= {0}; + int newVisibility= Modifier.PRIVATE; + String newReturnTypeName= null; + helperDoAll("A", "m", signature, newParamInfo, newIndices, oldParamNames, newParamNames, null, permutation, newVisibility, deletedIndices, newReturnTypeName, true); + } + + public void testDelegate05() throws Exception { + // bug 138320 + String[] signature= {}; + helperRenameMethod(signature, "renamed", true); + } + +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeTypeRefactoringTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeTypeRefactoringTests.java new file mode 100644 index 000000000..2a55a9f03 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeTypeRefactoringTests.java @@ -0,0 +1,615 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.Collection; + +import junit.framework.Assert; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.StringAsserts; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.ISourceRange; + +import org.eclipse.jdt.internal.corext.refactoring.structure.ChangeTypeRefactoring; + +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +/** + * @author rfuhrer, tip + * + */ +public class ChangeTypeRefactoringTests extends RefactoringTest { + + private static final boolean BUG_CORE_TYPE_HIERARCHY_ILLEGAL_PARAMETERIZED_INTERFACES= true; + + private static final Class clazz= ChangeTypeRefactoringTests.class; + private static final String REFACTORING_PATH= "ChangeTypeRefactoring/"; + + public static ChangeTypeRefactoring create(ICompilationUnit cu, int selectionStart, int selectionLength){ + return new ChangeTypeRefactoring(cu, selectionStart, selectionLength); + } + + public static ChangeTypeRefactoring create(ICompilationUnit cu, int selectionStart, int selectionLength, String selectedType){ + return new ChangeTypeRefactoring(cu, selectionStart, selectionLength, selectedType); + } + + public ChangeTypeRefactoringTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + private String getSimpleTestFileName(boolean input) { + String fileName= "A_" + getName() + (input ? "_in" : "_out") + ".java"; + + return fileName; + } + + private String getTestFileName(boolean positive, boolean input){ + String fileName= TEST_PATH_PREFIX + getRefactoringPath(); + + fileName += (positive ? "positive/": "negative/"); + fileName += getSimpleTestFileName(input); + return fileName; + } + + private ICompilationUnit createCUfromTestFile(IPackageFragment pack, boolean positive, boolean input) throws Exception { + return createCU(pack, getSimpleTestFileName(input), getFileContents(getTestFileName(positive, input))); + } + + private ICompilationUnit createAdditionalCU(String fileName, IPackageFragment pack) throws Exception { + String fullName= TEST_PATH_PREFIX + getRefactoringPath() + "positive/" + fileName + ".java"; + return createCU(pack, fileName + ".java", getFileContents(fullName)); + } + + private ChangeTypeRefactoring helper1(int startLine, int startColumn, int endLine, int endColumn, String selectedTypeName) + throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ChangeTypeRefactoring ref= new ChangeTypeRefactoring(cu, selection.getOffset(), selection.getLength(), selectedTypeName); + + // TODO Set parameters on your refactoring instance from arguments... + + RefactoringStatus activationResult= ref.checkInitialConditions(new NullProgressMonitor()); + + assertTrue("activation was supposed to be successful:" + activationResult.toString(), activationResult.isOK()); + + Collection validTypes= ref.computeValidTypes(new NullProgressMonitor()); + if (validTypes.isEmpty()) + return ref; + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + + assertTrue("precondition was supposed to pass but was " + checkInputResult.toString(), checkInputResult.isOK()); + + performChange(ref, false); + + String newSource= cu.getSource(); + + assertEqualLines(getName() + ": ", getFileContents(getTestFileName(true, false)), newSource); + + + return ref; + } + + private void failHelper1(int startLine, int startColumn, int endLine, int endColumn, + int expectedStatus, String selectedTypeName) throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), false, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ChangeTypeRefactoring ref= new ChangeTypeRefactoring(cu, selection.getOffset(), selection.getLength(), selectedTypeName); + RefactoringStatus result= performRefactoring(ref); + + assertNotNull("precondition was supposed to fail", result); + assertEquals("status", expectedStatus, result.getSeverity()); + + String canonAfterSrcName= getTestFileName(false, true); + + assertEqualLines(getFileContents(canonAfterSrcName), cu.getSource()); + } + + //--- TESTS + public void testLocalVarName() throws Exception { + System.out.println("running testLocalVarName()"); + Collection types= helper1(5, 19, 5, 24, "java.util.Map").getValidTypeNames(); + Assert.assertTrue(types.size() == 1); + Assert.assertTrue(types.contains("java.util.Map")); + } + public void testLocalVarType() throws Exception { + Collection types= helper1(5, 9, 5, 18, "java.util.Map").getValidTypeNames(); + Assert.assertTrue(types.size() == 1); + Assert.assertTrue(types.contains("java.util.Map")); + } + public void testLocalVarDecl() throws Exception { + Collection types= helper1(8, 9, 8, 23, "java.util.Map").getValidTypeNames(); + Assert.assertTrue(types.size() == 1); + Assert.assertTrue(types.contains("java.util.Map")); + } + public void testLocalSuperTypesOfArrayList() throws Exception { + Collection types= helper1(5, 19, 5, 23, "java.util.List").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Object", "java.lang.Cloneable", "java.lang.Iterable", + "java.io.Serializable", "java.util.Collection", "java.util.List", + "java.util.AbstractList", "java.util.AbstractCollection", "java.util.RandomAccess" }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testParameterName() throws Exception { + Collection types= helper1(4, 31, 4, 36, "java.util.Map").getValidTypeNames(); + Assert.assertTrue(types.size() == 2); + Assert.assertTrue(types.contains("java.util.Map")); + Assert.assertTrue(types.contains("java.util.Dictionary")); + } + public void testParameterType() throws Exception { + Collection types= helper1(4, 21, 4, 29, "java.util.Dictionary").getValidTypeNames(); + Assert.assertTrue(types.size() == 2); + Assert.assertTrue(types.contains("java.util.Map")); + Assert.assertTrue(types.contains("java.util.Dictionary")); + } + public void testParameterDecl() throws Exception { + Collection types= helper1(4, 21, 4, 36, "java.util.Map").getValidTypeNames(); + Assert.assertTrue(types.size() == 2); + Assert.assertTrue(types.contains("java.util.Map")); + Assert.assertTrue(types.contains("java.util.Dictionary")); + } + public void testFieldName() throws Exception { + Collection types= helper1(10, 29, 10, 33, "java.util.AbstractList").getValidTypeNames(); + Assert.assertTrue(types.size() == 2); + Assert.assertTrue(types.contains("java.util.AbstractList")); + Assert.assertTrue(types.contains("java.util.List")); + } + public void testFieldType() throws Exception { + Collection types= helper1(10, 19, 10, 27, "java.util.AbstractList").getValidTypeNames(); + Assert.assertTrue(types.size() == 2); + Assert.assertTrue(types.contains("java.util.AbstractList")); + Assert.assertTrue(types.contains("java.util.List")); + } + public void testFieldDecl() throws Exception { + Collection types= helper1(10, 19, 10, 32, "java.util.AbstractList").getValidTypeNames(); + Assert.assertTrue(types.size() == 2); + Assert.assertTrue(types.contains("java.util.AbstractList")); + Assert.assertTrue(types.contains("java.util.List")); + } + public void testFieldUseSubtypesOfList() throws Exception { + Collection types= helper1(5, 22, 5, 26, "java.util.List").getValidTypeNames(); + Assert.assertTrue(types.size() == 2); + Assert.assertTrue(types.contains("java.util.AbstractList")); + Assert.assertTrue(types.contains("java.util.List")); + } + public void testFieldDeclSubtypesOfList() throws Exception { + Collection types= helper1(8, 12, 8, 25, "java.util.List").getValidTypeNames(); + Assert.assertTrue(types.size() == 2); + Assert.assertTrue(types.contains("java.util.AbstractList")); + Assert.assertTrue(types.contains("java.util.List")); + } + public void testLocalVarUse() throws Exception { + Collection types= helper1(6, 22, 6, 26, "java.util.AbstractList").getValidTypeNames(); + Assert.assertTrue(types.size() == 2); + Assert.assertTrue(types.contains("java.util.AbstractList")); + Assert.assertTrue(types.contains("java.util.List")); + } + public void testReturnTypeWithCall() throws Exception { + Collection types= helper1(4, 12, 4, 20, "java.util.AbstractList").getValidTypeNames(); + Assert.assertTrue(types.size() == 2); + Assert.assertTrue(types.contains("java.util.AbstractList")); + Assert.assertTrue(types.contains("java.util.List")); + } + public void testParameterNameWithOverride() throws Exception { + Collection types= helper1(5, 38, 5, 40, "java.util.Collection").getValidTypeNames(); + Assert.assertTrue(types.size() == 3); + Assert.assertTrue(types.contains("java.util.AbstractCollection")); +// Assert.assertTrue(types.contains("java.util.ArrayList")); + Assert.assertTrue(types.contains("java.util.List")); + Assert.assertTrue(types.contains("java.util.Collection")); + } + public void testParameterTypeWithOverride() throws Exception { + Collection types= helper1(10, 25, 10, 36, "java.util.List").getValidTypeNames(); + Assert.assertTrue(types.size() == 3); + Assert.assertTrue(types.contains("java.util.AbstractCollection")); +// Assert.assertTrue(types.contains("java.util.ArrayList")); + Assert.assertTrue(types.contains("java.util.List")); + Assert.assertTrue(types.contains("java.util.Collection")); + } + public void testParameterDeclWithOverride() throws Exception { + Collection types= helper1(10, 25, 10, 39, "java.util.AbstractCollection").getValidTypeNames(); + Assert.assertTrue(types.size() == 3); + Assert.assertTrue(types.contains("java.util.AbstractCollection")); + Assert.assertTrue(types.contains("java.util.List")); + Assert.assertTrue(types.contains("java.util.Collection")); + } + public void testLocalVarCast() throws Exception { + Collection types= helper1(7, 24, 7, 24, "java.util.List").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Object", "java.lang.Cloneable", "java.lang.Iterable", + "java.io.Serializable", "java.util.Collection", "java.util.List", + "java.util.AbstractList", "java.util.AbstractCollection", "java.util.RandomAccess" }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testReturnType() throws Exception { + createAdditionalCU("A_testReturnType2", getPackageP()); + Collection types= helper1(6, 12, 6, 15, "java.util.Collection").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { "java.lang.Object", "java.lang.Iterable", "java.util.Collection" }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testFieldWithAccess() throws Exception { + createAdditionalCU("A_testFieldWithAccess2", getPackageP()); + Collection types= helper1(6, 12, 6, 21, "java.util.Collection").getValidTypeNames(); + Assert.assertTrue(types.size() == 1); + Assert.assertTrue(types.contains("java.util.Collection")); + } + public void testParameterTypeWithOverriding() throws Exception { + createAdditionalCU("A_testParameterTypeWithOverriding2", getPackageP()); + Collection types= helper1(6, 21, 6, 24, "java.util.Collection").getValidTypeNames(); + Assert.assertTrue(types.size() == 1); + Assert.assertTrue(types.contains("java.util.Collection")); + } + public void testMultiCU() throws Exception { + createAdditionalCU("A_testMultiCUInterface1", getPackageP()); + createAdditionalCU("A_testMultiCUInterface2", getPackageP()); + createAdditionalCU("A_testMultiCUClass1", getPackageP()); + createAdditionalCU("A_testMultiCUClass2", getPackageP()); + Collection types= helper1(6, 21, 6, 26, "java.util.Collection").getValidTypeNames(); + Assert.assertTrue(types.size() == 1); + Assert.assertTrue(types.contains("java.util.Collection")); + } + public void testHashMap() throws Exception { + Collection types= helper1(15, 17, 15, 19, "java.util.AbstractMap").getValidTypeNames(); + Assert.assertTrue(types.size() == 2); + Assert.assertTrue(types.contains("java.util.AbstractMap")); + Assert.assertTrue(types.contains("java.util.Map")); + } + public void testString() throws Exception { + Collection types= helper1(4, 9, 4, 14, "java.lang.Object").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Object", "java.lang.CharSequence", "java.lang.Comparable<java.lang.String>", "java.io.Serializable" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testInterfaceTypes() throws Exception { + Collection types= helper1(4, 11, 4, 11, "p.I").getValidTypeNames(); + Assert.assertTrue(types.size() == 3); + Assert.assertTrue(types.contains("java.lang.Object")); + Assert.assertTrue(types.contains("p.I")); + Assert.assertTrue(types.contains("p.A")); + } + public void testImport() throws Exception { + Collection types= helper1(11, 9, 11, 17, "java.util.List").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Object", "java.lang.Cloneable", "java.lang.Iterable", + "java.io.Serializable", "java.util.Collection", "java.util.List", + "java.util.AbstractList", "java.util.AbstractCollection", "java.util.RandomAccess" }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testParametricTypeWithParametricSuperType() throws Exception { + Collection types= helper1(5, 22, 5, 22, "java.util.Collection<java.lang.String>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.util.Collection<java.lang.String>", + "java.lang.Object", + "java.lang.Iterable<java.lang.String>" }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testParametricTypeWithNonParametricSuperType() throws Exception { + Collection types= helper1(5, 22, 5, 22, "java.lang.Object").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.util.Collection<java.lang.String>", + "java.lang.Object", + "java.lang.Iterable<java.lang.String>" }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testNonParametricTypeWithParametricSuperType() throws Exception { + Collection types= helper1(5, 16, 5, 16, "java.lang.Comparable<java.lang.String>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + //"java.lang.String", + "java.lang.Comparable<java.lang.String>", + "java.lang.CharSequence", + "java.io.Serializable", + "java.lang.Object" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testNestedParametricType() throws Exception { + Collection types= helper1(5, 32, 5, 32, "java.util.AbstractCollection<java.util.Vector<java.lang.String>>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.util.AbstractCollection<java.util.Vector<java.lang.String>>", + "java.util.Collection<java.util.Vector<java.lang.String>>", + "java.util.RandomAccess", + "java.lang.Cloneable", + "java.lang.Object", + "java.io.Serializable", + "java.util.List<java.util.Vector<java.lang.String>>", + "java.util.AbstractList<java.util.Vector<java.lang.String>>", + "java.lang.Iterable<java.util.Vector<java.lang.String>>" + + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testParametricHashtable() throws Exception { + Collection types= helper1(5, 9, 5, 36, "java.util.Map<java.lang.String,java.lang.Integer>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.util.Map<java.lang.String,java.lang.Integer>", + "java.util.Dictionary<java.lang.String,java.lang.Integer>", + "java.lang.Object", + "java.lang.Cloneable", + "java.io.Serializable" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testNestedParametricHashtable() throws Exception { + Collection types= helper1(6, 9, 6, 44, "java.util.Dictionary<java.lang.String,java.util.Vector<java.lang.Integer>>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.util.Map<java.lang.String,java.util.Vector<java.lang.Integer>>", + "java.util.Dictionary<java.lang.String,java.util.Vector<java.lang.Integer>>", + "java.lang.Object", + "java.lang.Cloneable", + "java.io.Serializable" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testNestedRawParametricHashtable() throws Exception { + Collection types= helper1(6, 9, 6, 36, "java.util.Dictionary<java.lang.String,java.util.Vector>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.util.Map<java.lang.String,java.util.Vector>", + "java.util.Dictionary<java.lang.String,java.util.Vector>", + "java.lang.Object", + "java.lang.Cloneable", + "java.io.Serializable" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testReorderTypeParameters() throws Exception { + Collection types= helper1(6, 28, 6, 28, "p.A<java.lang.Integer,java.lang.String>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Object", + "p.A<java.lang.Integer,java.lang.String>" + + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void test4TypeParameters() throws Exception { + if (BUG_CORE_TYPE_HIERARCHY_ILLEGAL_PARAMETERIZED_INTERFACES) { + printTestDisabledMessage("core bug"); + return; + } + + Collection types= helper1(3, 40, 3, 40, "p.I<java.lang.Double,java.lang.Float>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Object", + "p.I<java.lang.Double,java.lang.Float>", + "p.J<java.lang.Float,java.lang.Double>", + "p.I<java.lang.String,java.lang.Integer>" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testRawComment() throws Exception { + Collection types= helper1(5, 27, 5, 27, "java.util.Collection").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.util.Collection" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testNonRawComment() throws Exception { + Collection types= helper1(5, 31, 5, 31, "java.util.Collection<java.lang.String>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.util.Collection<java.lang.String>" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + + public void testUnrelatedTypeParameters() throws Exception { + Collection types= helper1(3, 20, 3, 20, "p.E<java.lang.String>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "p.F", + "p.E<java.lang.String>", + "java.lang.Object" + + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testUnboundTypeParameter() throws Exception { + Collection types= helper1(5, 17, 5, 20, "java.lang.Iterable<T>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Iterable<T>", + "java.util.Collection<T>", + "java.lang.Object" + + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testRawSubType() throws Exception { + Collection types= helper1(7, 5, 7, 10, "java.lang.Comparable<java.lang.String>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Comparable<java.lang.String>" + + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + + public void testParametricField() throws Exception { + Collection types= helper1(6, 5, 6, 25, "java.lang.Iterable<java.lang.Integer>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.util.Collection<java.lang.Integer>", + "java.util.AbstractCollection<java.lang.Integer>", + "java.util.List<java.lang.Integer>", + "java.lang.Iterable<java.lang.Integer>", + "java.lang.Cloneable", + "java.lang.Object", + "java.util.RandomAccess", + "java.io.Serializable", + "java.util.AbstractList<java.lang.Integer>" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + + public void testParametricReturnType() throws Exception { + Collection types= helper1(5, 12, 5, 25, "java.lang.Iterable<java.lang.String>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.util.List<java.lang.String>", + "java.io.Serializable", + "java.lang.Iterable<java.lang.String>", + "java.lang.Cloneable", + "java.util.RandomAccess", + "java.util.Collection<java.lang.String>", + "java.util.AbstractCollection<java.lang.String>", + "java.lang.Object", + "java.util.AbstractList<java.lang.String>" + + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testParametricParameter() throws Exception { + Collection types= helper1(10, 54, 10, 65, "java.lang.Iterable<java.lang.Object>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Object", + "java.lang.Iterable<java.lang.Object>", + "java.util.Collection<java.lang.Object>" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testParametricLocalVar() throws Exception { + Collection types= helper1(14, 9, 14, 20, "java.lang.Iterable<java.lang.String>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Object", + "java.lang.Iterable<java.lang.String>", + "java.util.Collection<java.lang.String>" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testParametricEmptySelection() throws Exception { + Collection types= helper1(7, 12, 7, 12, "java.lang.Iterable<java.lang.String>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Object", + "java.lang.Iterable<java.lang.String>", + "java.util.Collection<java.lang.String>" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testQualifiedNameEmptySelection() throws Exception { + Collection types= helper1(10, 31, 10, 31, "java.lang.Iterable<java.lang.Object>").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Object", + "java.lang.Iterable<java.lang.Object>", + "java.util.Collection<java.lang.Object>" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + public void testCatchClause() throws Exception { + Collection types= helper1(7, 18, 7, 18, "java.io.IOException").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Throwable", + "java.lang.Exception", + "java.io.IOException" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + + public void testVarArg() throws Exception { + Collection types= helper1(5, 17, 5, 18, "java.lang.Object").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { + "java.lang.Object", + "java.io.Serializable", + "java.lang.Comparable<java.lang.Integer>", + "java.lang.Number" + }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + + public void testVarArg2() throws Exception { + Collection types= helper1(2, 21, 2, 21, "java.lang.Object").getValidTypeNames(); + String[] actual= (String[]) types.toArray(new String[types.size()]); + String[] expected= { }; + StringAsserts.assertEqualStringsIgnoreOrder(actual, expected); + } + + // tests that are supposed to fail + + public void testInvalidSelection() throws Exception { + failHelper1(5, 23, 5, 37, 4, "java.lang.Object"); + } + public void testBogusSelection() throws Exception { + failHelper1(6, 23, 6, 35, 4, "java.lang.Object"); + } + public void testMultiDeclaration() throws Exception { + failHelper1(8, 22, 8, 26, 4, "java.util.List"); + } + public void testUpdateNotPossible() throws Exception { + failHelper1(5, 19, 5, 20, 4, "java.util.Hashtable"); + } + public void testArray() throws Exception { + failHelper1(5, 18, 5, 19, 4, "java.lang.Object"); + } + public void testArray2() throws Exception { + failHelper1(4, 33, 4, 33, 4, "java.lang.Object"); + } + public void testPrimitive() throws Exception { + failHelper1(5, 13, 5, 13, 4, "java.lang.Object"); + } + public void testOverriddenBinaryMethod() throws Exception { + failHelper1(3, 12, 3, 17, 4, "java.lang.Object"); + } + public void testFieldOfLocalType() throws Exception { + failHelper1(5, 21, 5, 45, 4, "java.lang.Object"); + } + public void testObjectReturnType() throws Exception { + failHelper1(3, 17, 3, 22, 4, "java.lang.Object"); + } + public void testTypeParameter() throws Exception { + failHelper1(3, 9, 3, 9, 4, "java.lang.Object"); + } + public void testEnum() throws Exception { + failHelper1(9, 11, 9, 11, 4, "java.lang.Object"); + } + public void testQualifiedFieldRef() throws Exception { + failHelper1(4, 9, 4, 15, 4, "java.lang.Object"); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ConvertAnonymousToNestedTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ConvertAnonymousToNestedTests.java new file mode 100644 index 000000000..a1bfe7f58 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ConvertAnonymousToNestedTests.java @@ -0,0 +1,382 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * N.Metchev@teamphone.com - contributed fixes for + * - convert anonymous to nested should sometimes declare class as static [refactoring] + * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=43360) + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.Hashtable; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.dom.Modifier; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.refactoring.code.ConvertAnonymousToNestedRefactoring; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +public class ConvertAnonymousToNestedTests extends RefactoringTest { + + private static final Class clazz= ConvertAnonymousToNestedTests.class; + private static final String REFACTORING_PATH= "ConvertAnonymousToNested/"; + + private Object fCompactPref; + + public ConvertAnonymousToNestedTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new Java15Setup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + private String getSimpleTestFileName(boolean canInline, boolean input){ + String fileName = "A_" + getName(); + if (canInline) + fileName += input ? "_in": "_out"; + return fileName + ".java"; + } + + private String getTestFileName(boolean canConvert, boolean input){ + String fileName= TEST_PATH_PREFIX + getRefactoringPath(); + fileName += (canConvert ? "canConvert/": "cannotConvert/"); + return fileName + getSimpleTestFileName(canConvert, input); + } + + protected ICompilationUnit createCUfromTestFile(IPackageFragment pack, boolean canConvert, boolean input) throws Exception { + return createCU(pack, getSimpleTestFileName(canConvert, input), getFileContents(getTestFileName(canConvert, input))); + } + + protected void setUp() throws Exception { + super.setUp(); + Hashtable options= JavaCore.getOptions(); + + String setting= DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR; + fCompactPref= options.get(setting); + options.put(setting, DefaultCodeFormatterConstants.TRUE); + JavaCore.setOptions(options); + + IJavaProject project= getPackageP().getJavaProject(); + StubUtility.setCodeTemplate(CodeTemplateContextType.TYPECOMMENT_ID, "", project); + StubUtility.setCodeTemplate(CodeTemplateContextType.CONSTRUCTORCOMMENT_ID, "", project); + StubUtility.setCodeTemplate(CodeTemplateContextType.FIELDCOMMENT_ID, "", project); + + } + + protected void tearDown() throws Exception { + super.tearDown(); + Hashtable options= JavaCore.getOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR, fCompactPref); + JavaCore.setOptions(options); + } + + private void helper1(int startLine, int startColumn, int endLine, int endColumn, boolean makeFinal, String className, int visibility) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ConvertAnonymousToNestedRefactoring ref= new ConvertAnonymousToNestedRefactoring(cu, selection.getOffset(), selection.getLength()); + + RefactoringStatus preconditionResult= ref.checkInitialConditions(new NullProgressMonitor()); + if (preconditionResult.isOK()) + preconditionResult= null; + assertEquals("activation was supposed to be successful", null, preconditionResult); + + ref.setClassName(className); + ref.setDeclareFinal(makeFinal); + ref.setVisibility(visibility); + + if (preconditionResult == null) + preconditionResult= ref.checkFinalConditions(new NullProgressMonitor()); + else + preconditionResult.merge(ref.checkFinalConditions(new NullProgressMonitor())); + if (preconditionResult.isOK()) + preconditionResult= null; + assertEquals("precondition was supposed to pass", null, preconditionResult); + + performChange(ref, false); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + assertEqualLines(getFileContents(getTestFileName(true, false)), newcu.getSource()); + } + + private void helper1(int startLine, int startColumn, int endLine, int endColumn, boolean makeFinal, boolean makeStatic, String className, int visibility) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ConvertAnonymousToNestedRefactoring ref= new ConvertAnonymousToNestedRefactoring(cu, selection.getOffset(), selection.getLength()); + + RefactoringStatus preconditionResult= ref.checkInitialConditions(new NullProgressMonitor()); + if (preconditionResult.isOK()) + preconditionResult= null; + assertEquals("activation was supposed to be successful", null, preconditionResult); + + ref.setClassName(className); + ref.setDeclareFinal(makeFinal); + ref.setDeclareStatic(makeStatic); + ref.setVisibility(visibility); + + if (preconditionResult == null) + preconditionResult= ref.checkFinalConditions(new NullProgressMonitor()); + else + preconditionResult.merge(ref.checkFinalConditions(new NullProgressMonitor())); + if (preconditionResult.isOK()) + preconditionResult= null; + assertEquals("precondition was supposed to pass", null, preconditionResult); + + performChange(ref, false); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + assertEqualLines(getFileContents(getTestFileName(true, false)), newcu.getSource()); + } + + private void failHelper1(int startLine, int startColumn, int endLine, int endColumn, boolean makeFinal, String className, int visibility, int expectedSeverity) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), false, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ConvertAnonymousToNestedRefactoring ref= new ConvertAnonymousToNestedRefactoring(cu, selection.getOffset(), selection.getLength()); + + RefactoringStatus preconditionResult= ref.checkInitialConditions(new NullProgressMonitor()); + if (preconditionResult.isOK()) + preconditionResult= null; + assertEquals("activation was supposed to be successful", null, preconditionResult); + + ref.setClassName(className); + ref.setDeclareFinal(makeFinal); + ref.setVisibility(visibility); + + if (preconditionResult == null) + preconditionResult= ref.checkFinalConditions(new NullProgressMonitor()); + else + preconditionResult.merge(ref.checkFinalConditions(new NullProgressMonitor())); + if (preconditionResult.isOK()) + preconditionResult= null; + assertNotNull("precondition was supposed to fail",preconditionResult); + + assertEquals("incorrect severity:", expectedSeverity, preconditionResult.getSeverity()); + } + + private void failActivationHelper(int startLine, int startColumn, int endLine, int endColumn, int expectedSeverity) throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), false, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ConvertAnonymousToNestedRefactoring ref= new ConvertAnonymousToNestedRefactoring(cu, selection.getOffset(), selection.getLength()); + + RefactoringStatus preconditionResult= ref.checkInitialConditions(new NullProgressMonitor()); + assertEquals("activation was supposed to fail", expectedSeverity, preconditionResult.getSeverity()); + } + + //--- TESTS + + public void testFail0() throws Exception{ + printTestDisabledMessage("corner case - local types"); +// failHelper1(6, 14, 6, 16, true, "Inner", Modifier.PRIVATE, RefactoringStatus.FATAL); + } + + public void testFail1() throws Exception{ + failHelper1(5, 17, 5, 17, true, "Inner", Modifier.PRIVATE, RefactoringStatus.FATAL); + } + + public void testFail2() throws Exception{ + failHelper1(5, 17, 5, 18, true, "Inner", Modifier.PRIVATE, RefactoringStatus.FATAL); + } + + public void testFail3() throws Exception{ + failActivationHelper(13, 27, 13, 27, RefactoringStatus.FATAL); + } + + public void testFail4() throws Exception{ + failHelper1(8, 31, 8, 31, true, "Inner", Modifier.PRIVATE, RefactoringStatus.ERROR); + } + + public void test0() throws Exception{ + helper1(5, 17, 5, 17, true, "Inner", Modifier.PRIVATE); + } + + public void test1() throws Exception{ + helper1(5, 17, 5, 17, true, "Inner", Modifier.PUBLIC); + } + + public void test2() throws Exception{ + helper1(5, 17, 5, 17, true, "Inner", Modifier.PUBLIC); + } + + public void test3() throws Exception{ + helper1(5, 17, 5, 17, false, "Inner", Modifier.PUBLIC); + } + + public void test4() throws Exception{ + helper1(7, 17, 7, 17, true, "Inner", Modifier.PRIVATE); + } + + public void test5() throws Exception{ + helper1(7, 17, 7, 19, true, "Inner", Modifier.PRIVATE); + } + + public void test6() throws Exception{ + helper1(8, 13, 9, 14, true, "Inner", Modifier.PRIVATE); + } + + public void test7() throws Exception{ + helper1(7, 18, 7, 18, true, "Inner", Modifier.PRIVATE); + } + + public void test8() throws Exception{ + helper1(8, 14, 8, 15, true, "Inner", Modifier.PRIVATE); + } + + public void test9() throws Exception{ + helper1(8, 13, 8, 14, true, "Inner", Modifier.PRIVATE); + } + + public void test10() throws Exception{ + helper1(7, 13, 7, 14, true, "Inner", Modifier.PRIVATE); + } + + public void test11() throws Exception{ + helper1(5, 15, 5, 17, true, "Inner", Modifier.PRIVATE); + } + + public void test12() throws Exception{ + helper1(8, 9, 10, 10, true, "Inner", Modifier.PRIVATE); + } + + public void test13() throws Exception{ + helper1(6, 28, 6, 28, true, "Inner", Modifier.PRIVATE); + } + + public void test14() throws Exception{ + helper1(5, 13, 5, 23, true, "Inner", Modifier.PRIVATE); + } + + public void test15() throws Exception{ + helper1(7, 26, 7, 26, true, "Inner", Modifier.PRIVATE); + } + + public void test16() throws Exception{ + helper1(4, 10, 4, 26, true, "Inner", Modifier.PRIVATE); + } + + public void test17() throws Exception{ + helper1(6, 14, 6, 15, true, "Inner", Modifier.PRIVATE); + } + + public void test18() throws Exception{ + helper1(5, 15, 5, 17, true, "Inner", Modifier.PRIVATE); + } + + public void test19() throws Exception{ + helper1(5, 12, 6, 21, true, "Inner", Modifier.PRIVATE); + } + + public void test20() throws Exception{ + helper1(4, 25, 4, 25, true, "Inner", Modifier.PRIVATE); + } + + public void test21() throws Exception{ + helper1(4, 25, 4, 25, true, "Inner", Modifier.PRIVATE); + } + + public void test22() throws Exception{ + helper1(9, 34, 9, 34, true, "Inner", Modifier.PRIVATE); + } + + public void test23() throws Exception{ + helper1(6, 33, 6, 33, true, "Inner", Modifier.PRIVATE); + } + + public void test24() throws Exception{ + helper1(3, 26, 3, 26, true, "Inner", Modifier.PRIVATE); + } + + public void test25() throws Exception{ + helper1(8, 28, 8, 28, true, "Inner", Modifier.PRIVATE); + } + + public void test26() throws Exception{ + helper1(8, 28, 8, 28, true, "Inner", Modifier.PRIVATE); + } + + public void test27() throws Exception{ + helper1(11, 39, 11, 39, true, "Inner", Modifier.PRIVATE); + } + + public void test28() throws Exception{ +// printTestDisabledMessage("disabled: bug 43360"); + helper1(10, 27, 10, 27, true, "Inner", Modifier.PRIVATE); + } + + public void test29() throws Exception{ + helper1(6, 14, 6, 14, true, "Inner", Modifier.PRIVATE); + } + + public void test30() throws Exception{ // 2 syntax errors + helper1(5, 32, 5, 32, true, true, "Greeter", Modifier.PRIVATE); + } + + public void testGenerics0() throws Exception{ + helper1(5, 20, 5, 20, true, "Inner", Modifier.PRIVATE); + } + + public void testGenerics1() throws Exception{ + helper1(5, 20, 5, 20, true, "Inner", Modifier.PUBLIC); + } + + public void testGenerics2() throws Exception{ + helper1(5, 20, 5, 20, true, "Inner", Modifier.PUBLIC); + } + + public void testGenerics3() throws Exception{ + helper1(5, 20, 5, 20, false, "Inner", Modifier.PUBLIC); + } + + public void testGenerics4() throws Exception{ + helper1(7, 20, 7, 20, true, "Inner", Modifier.PRIVATE); + } + + public void testGenerics5() throws Exception{ + helper1(7, 20, 7, 20, true, "Inner", Modifier.PRIVATE); + } + + public void testGenerics6() throws Exception{ + helper1(7, 20, 7, 20, true, true, "Inner", Modifier.PRIVATE); + } + + public void test31() throws Exception{ // for bug 181054 + helper1(10, 24, 10, 30, true, false, "Inner1Extension", Modifier.PRIVATE); + } + + public void test32() throws Exception{ // for bug 158028 + helper1(10, 30, 10, 36, true, false, "Inner1Extension", Modifier.PRIVATE); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/CopyPackageChangeTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/CopyPackageChangeTest.java new file mode 100644 index 000000000..ffff351ab --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/CopyPackageChangeTest.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +import org.eclipse.jdt.internal.corext.refactoring.changes.CopyPackageChange; + +public class CopyPackageChangeTest extends RefactoringTest { + + private static final String REFACTORING_PATH= "CopyPackageChange/"; + private static final Class clazz= CopyPackageChangeTest.class; + + public CopyPackageChangeTest(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public void test0() throws Exception{ + createCU(getPackageP(), "A.java", getFileContents(getRefactoringPath() + "A.java")); + + IPackageFragmentRoot newRoot= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "newName"); + + String packName= getPackageP().getElementName(); + CopyPackageChange change= new CopyPackageChange(getPackageP(), newRoot, null); + change.initializeValidationData(new NullProgressMonitor()); + performChange(change); + IPackageFragment copied= newRoot.getPackageFragment(packName); + assertTrue("copied.exists()", copied.exists()); + assertTrue(copied.getChildren().length == 1); + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/DelegateCreatorTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/DelegateCreatorTests.java new file mode 100644 index 000000000..ad705298d --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/DelegateCreatorTests.java @@ -0,0 +1,238 @@ +/******************************************************************************* + * Copyright (c) 2000, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.IOException; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.BodyDeclaration; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.TypeDeclaration; +import org.eclipse.jdt.core.refactoring.CompilationUnitChange; + +import org.eclipse.jdt.internal.corext.refactoring.delegates.DelegateCreator; +import org.eclipse.jdt.internal.corext.refactoring.delegates.DelegateFieldCreator; +import org.eclipse.jdt.internal.corext.refactoring.delegates.DelegateMethodCreator; +import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser; + +public class DelegateCreatorTests extends RefactoringTest { + + private static final Class clazz= DelegateCreatorTests.class; + private static final String REFACTORING_PATH= "DelegateCreator/"; + + public DelegateCreatorTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + private void methodHelper(String methodName, String[] args, boolean copy, String newName, String newTypeName) throws Exception { + ITypeBinding destination= createTargetBinding(newTypeName); + helper(methodName, args, null, copy, newName, destination); + } + + private void fieldHelper(String fieldName, boolean copy, String newName, String newTypeName) throws Exception { + ITypeBinding destination= createTargetBinding(newTypeName); + helper(null, null, fieldName, copy, newName, destination); + } + + private ITypeBinding createTargetBinding(String newTypeName) throws Exception, JavaModelException { + ITypeBinding destination= null; + if (newTypeName != null) { + ICompilationUnit cu2= createCUfromTestFile(getPackageP(), newTypeName); + IType classNew= getType(cu2, newTypeName); + CompilationUnit cuNode= new RefactoringASTParser(AST.JLS3).parse(cu2, true, null); + TypeDeclaration td= ASTNodeSearchUtil.getTypeDeclarationNode(classNew, cuNode); + destination= td.resolveBinding(); + } + return destination; + } + + private void helper(String methodName, String[] args, String fieldName, boolean copy, String newName, ITypeBinding destination) throws Exception, JavaModelException, CoreException, IOException { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType classA= getType(cu, "A"); + + try{ + CompilationUnitRewrite rewrite= new CompilationUnitRewrite(cu); + rewrite.setResolveBindings(false); + BodyDeclaration d; + DelegateCreator creator; + if (methodName != null) { + IMethod method= classA.getMethod(methodName, args); + d= ASTNodeSearchUtil.getMethodDeclarationNode(method, rewrite.getRoot()); + creator= new DelegateMethodCreator(); + } + else { + IField field= classA.getField(fieldName); + d= ASTNodeSearchUtil.getFieldDeclarationNode(field, rewrite.getRoot()); + creator= new DelegateFieldCreator(); + } + + creator.setDeclaration(d); + creator.setSourceRewrite(rewrite); + creator.setCopy(copy); + if (newName != null) creator.setNewElementName(newName); + if (destination != null) creator.setNewLocation(destination); + creator.prepareDelegate(); + creator.createEdit(); + CompilationUnitChange createChange= rewrite.createChange(true); + createChange.initializeValidationData(new NullProgressMonitor()); + createChange.perform(new NullProgressMonitor()); + assertEqualLines("invalid delegate created", getFileContents(getOutputTestFileName("A")), cu.getSource()); + + } finally{ + performDummySearch(); + classA.getCompilationUnit().delete(true, null); + } + } + + public void testm01() throws Exception { + // just create a delegate without extras + methodHelper("foo", new String[0], true, null, null); + } + + public void testm02() throws Exception { + // copy existing javadoc + methodHelper("foo", new String[0], true, null, null); + } + + public void testm03() throws Exception { + // existing annotations + methodHelper("foo", new String[0], true, null, null); + } + + public void testm04() throws Exception { + // a new name + methodHelper("foo", new String[0], true, "bar", null); + } + + public void testm05() throws Exception { + // a new type + methodHelper("foo", new String[0], true, null, "B"); + } + + public void testm06() throws Exception { + // a new name and new type + methodHelper("foo", new String[0], true, "bar", "B"); + } + + public void testm07() throws Exception { + // ensure comments inside parameters et al. are copied as well. + methodHelper("foo", new String[] { "QString;", "QString;" }, true, "bar", null); + } + + public void testm08() throws Exception { + // import + IPackageFragment e= getRoot().createPackageFragment("e", true, null); + ICompilationUnit cu2= createCUfromTestFile(e, "E"); + IType classNew= getType(cu2, "E"); + CompilationUnit cuNode= new RefactoringASTParser(AST.JLS3).parse(cu2, true, null); + TypeDeclaration td= ASTNodeSearchUtil.getTypeDeclarationNode(classNew, cuNode); + ITypeBinding destination= td.resolveBinding(); + + helper("foo", new String[0], null, true, null, destination); + } + + public void testm09() throws Exception { + // abstract method: ensure no body is created + methodHelper("foo", new String[0], true, null, null); + } + + public void testm10() throws Exception { + // interface method: ensure no body is created + methodHelper("foo", new String[0], true, null, null); + } + + public void testm11() throws Exception { + // constructor + methodHelper("A", new String[0], true, null, null); + } + + // FIELDS + + public void testf01() throws Exception { + // just create a delegate without extras + fieldHelper("foo", true, null, null); + } + + public void testf02() throws Exception { + // copy existing javadoc + fieldHelper("foo", true, null, null); + } + + public void testf03() throws Exception { + // existing annotations + fieldHelper("foo", true, null, null); + } + + public void testf04() throws Exception { + // a new name + fieldHelper("foo", true, "bar", null); + } + + public void testf05() throws Exception { + // a new type + fieldHelper("foo", true, null, "B"); + } + + public void testf06() throws Exception { + // a new name and new type + fieldHelper("foo", true, "bar", "B"); + } + + public void testf07() throws Exception { + // ensure comments inside parameters et al. are copied as well. + fieldHelper("foo", true, null, null); + } + + public void testf08() throws Exception { + // import + IPackageFragment e= getRoot().createPackageFragment("e", true, null); + ICompilationUnit cu2= createCUfromTestFile(e, "E"); + IType classNew= getType(cu2, "E"); + CompilationUnit cuNode= new RefactoringASTParser(AST.JLS3).parse(cu2, true, null); + TypeDeclaration td= ASTNodeSearchUtil.getTypeDeclarationNode(classNew, cuNode); + ITypeBinding destination= td.resolveBinding(); + + helper(null, null, "foo", true, null, destination); + } + + public void testf09() throws Exception { + // initializer removed? + fieldHelper("foo", true, null, null); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractClassTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractClassTests.java new file mode 100644 index 000000000..fc62fbcea --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractClassTests.java @@ -0,0 +1,407 @@ +/******************************************************************************* + * Copyright (c) 2007, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.jface.preference.IPreferenceStore; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.refactoring.descriptors.ExtractClassDescriptor; +import org.eclipse.jdt.core.refactoring.descriptors.ExtractClassDescriptor.Field; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; + +import org.eclipse.jdt.ui.PreferenceConstants; + +import org.eclipse.jdt.internal.ui.JavaPlugin; + +public class ExtractClassTests extends RefactoringTest { + + private static final String REFACTORING_PATH= "ExtractClass/"; + private IPackageFragment fPack; + private ExtractClassDescriptor fDescriptor; + + public ExtractClassTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(ExtractClassTests.class)); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + private IType setupType() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), getCUName(), true); + IType type= cu.getType(getCUName()); + assertNotNull(type); + assertTrue(type.exists()); + return type; + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + private void checkAdditionalFile(String fileName) throws Exception, JavaModelException, IOException { + ICompilationUnit cu= fPack.getCompilationUnit(fileName + ".java"); + assertNotNull(cu); + assertTrue(cu.getPath() + " does not exist", cu.exists()); + String actual= cu.getSource(); + String expected= getFileContents(getOutputTestFileName(fileName)); + assertEqualLines(expected, actual); + } + + private void createAdditionalFile(String fileName) throws Exception { + ICompilationUnit cu= createCUfromTestFile(fPack, fileName, true); + assertNotNull(cu); + assertTrue(cu.exists()); + } + + private void createAdditionalFile(String subDir, String fileName) throws Exception { + IPackageFragment pack= getSubPackage(subDir); + ICompilationUnit cu= createCUfromTestFile(pack, fileName, true); + assertNotNull(cu); + assertTrue(cu.exists()); + } + + private IPackageFragment getSubPackage(String subDir) throws Exception { + IPackageFragment pack= getPackageP(); + if (subDir != null) { + String packageName= pack.getElementName() + "." + subDir; + pack= getRoot().getPackageFragment(packageName); + if (!pack.exists()) { + IPackageFragment create= getRoot().createPackageFragment(packageName, true, new NullProgressMonitor()); + assertNotNull(create); + assertTrue(create.exists()); + return create; + } + } + return pack; + } + + private String getCUName() { + StringBuffer sb= new StringBuffer(); + String name= getName(); + if (name.startsWith("test")) + name= name.substring(4); + sb.append(Character.toUpperCase(name.charAt(0)) + name.substring(1)); + return sb.toString(); + } + + private String getCUFileName() { + StringBuffer sb= new StringBuffer(); + sb.append(getCUName()); + sb.append(".java"); + return sb.toString(); + } + + private RefactoringStatus runRefactoring(boolean expectError) throws Exception { + RefactoringStatus status= performRefactoring(fDescriptor); + if (expectError) { + assertNotNull(status + "", status); + return status; + } else { + if (status!=null) + assertTrue(status+"",status.getEntryWithHighestSeverity().getSeverity() <= RefactoringStatus.WARNING); + } + String expected= getFileContents(getOutputTestFileName(getCUName())); + assertNotNull(expected); + ICompilationUnit resultCU= fPack.getCompilationUnit(getCUFileName()); + assertNotNull(resultCU); + assertTrue(resultCU.exists()); + String result= resultCU.getSource(); + assertNotNull(result); + assertEqualLines(expected, result); + if (fDescriptor.isCreateTopLevel() && !expectError) { + String packageName= fDescriptor.getPackage(); + if (packageName != null) + fPack= getRoot().getPackageFragment(packageName); + assertNotNull(fPack); + String parameterClassFile= fDescriptor.getClassName() + ".java"; + ICompilationUnit unit= fPack.getCompilationUnit(parameterClassFile); + assertNotNull(unit); + assertTrue(unit.exists()); + expected= getFileContents(getOutputTestFileName(fDescriptor.getClassName())); + result= unit.getSource(); + assertNotNull(result); + assertEqualLines(expected, result); + } + return status; + } + + protected void setUp() throws Exception { + super.setUp(); + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false); + fDescriptor= RefactoringSignatureDescriptorFactory.createExtractClassDescriptor(); + fDescriptor.setFieldName("parameterObject"); + fPack= getPackageP(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + fDescriptor= null; + fPack= null; + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + store.setToDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS); + } + + public void testComplexExtract() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setClassName("ComplexExtractParameter"); + runRefactoring(false); + } + + public void testInitializerProblem() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setClassName("InitializerProblemParameter"); + runRefactoring(false); + } + + public void testMethodUpdate() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setClassName("MethodUpdateParameter"); + runRefactoring(false); + } + + public void testInheritanceUpdate() throws Exception { + createAdditionalFile("InheritanceUpdateImpl"); + fDescriptor.setType(setupType()); + fDescriptor.setClassName("InheritanceUpdateParameter"); + runRefactoring(false); + checkAdditionalFile("InheritanceUpdateImpl"); + } + + public void testInheritanceUpdateGetterSetter() throws Exception { + createAdditionalFile("InheritanceUpdateImplGetterSetter"); + fDescriptor.setType(setupType()); + fDescriptor.setCreateGetterSetter(true); + fDescriptor.setClassName("InheritanceUpdateGetterSetterParameter"); + runRefactoring(false); + checkAdditionalFile("InheritanceUpdateImplGetterSetter"); + } + + public void testComplexExtractGetterSetter() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setCreateGetterSetter(true); + fDescriptor.setClassName("ComplexExtractGetterSetterParameter"); + runRefactoring(false); + } + + public void testComplexExtractNested() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setCreateTopLevel(false); + fDescriptor.setClassName("ComplexExtractNestedParameter"); + runRefactoring(false); + } + + public void testStaticInstanceFields() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setClassName("StaticInstanceFieldsParameter"); + RefactoringStatus status= runRefactoring(true); + RefactoringStatusEntry[] entries= status.getEntries(); + //Warning for no IFields moved + assertEquals(1, entries.length); + for (int i= 0; i < entries.length; i++) { + RefactoringStatusEntry refactoringStatusEntry= entries[i]; + assertEquals("Status was:" + refactoringStatusEntry, true, refactoringStatusEntry.isFatalError()); + } + } + + public void testImportRemove() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setClassName("ImportRemoveParameter"); + runRefactoring(false); + } + + public void testSwitchCase() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setClassName("SwitchCaseParameter"); + RefactoringStatus status= runRefactoring(true); + RefactoringStatusEntry[] entries= status.getEntries(); + //Error for usage in Switch case + assertEquals(1, entries.length); + for (int i= 0; i < entries.length; i++) { + RefactoringStatusEntry refactoringStatusEntry= entries[i]; + assertEquals(true, refactoringStatusEntry.isError()); + } + } + + public void testCopyModifierAnnotations() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setClassName("CopyModifierAnnotationsParameter"); + RefactoringStatus status= runRefactoring(true); + RefactoringStatusEntry[] entries= status.getEntries(); + //Warning for transient + //Warning for volatile + assertEquals(2, entries.length); + for (int i= 0; i < entries.length; i++) { + RefactoringStatusEntry refactoringStatusEntry= entries[i]; + assertEquals(true, refactoringStatusEntry.isWarning()); + } + } + + public void testUFOGetter() throws Exception { + fDescriptor.setType(setupType()); + Field[] fields= ExtractClassDescriptor.getFields(fDescriptor.getType()); + for (int i= 0; i < fields.length; i++) { + Field field= fields[i]; + if ("homePlanet".equals(field.getFieldName())) + field.setCreateField(false); + } + fDescriptor.setFields(fields); + fDescriptor.setClassName("Position"); + fDescriptor.setFieldName("position"); + fDescriptor.setCreateGetterSetter(true); + runRefactoring(false); + } + + public void testControlBodyUpdates() throws Exception { + IJavaProject javaProject= getRoot().getJavaProject(); + Map originalOptions= javaProject.getOptions(true); + try { + HashMap newOptions= new HashMap(originalOptions); + newOptions.put(JavaCore.CODEASSIST_FIELD_PREFIXES, "f"); + javaProject.setOptions(newOptions); + fDescriptor.setType(setupType()); + fDescriptor.setCreateGetterSetter(true); + fDescriptor.setClassName("ControlBodyUpdatesParameter"); + runRefactoring(false); + } finally { + javaProject.setOptions(originalOptions); + } + } + + public void testArrayInitializer() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setCreateGetterSetter(true); + fDescriptor.setClassName("ArrayInitializerParameter"); + runRefactoring(false); + } + + public void testVariableDeclarationInitializer() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setCreateGetterSetter(true); + fDescriptor.setClassName("VariableDeclarationInitializerParameter"); + runRefactoring(false); + } + + public void testUpdateSimpleName() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setCreateGetterSetter(true); + fDescriptor.setClassName("UpdateSimpleNameParameter"); + runRefactoring(false); + } + + public void testArrayLengthAccess() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setCreateGetterSetter(true); + fDescriptor.setClassName("ArrayLengthAccessParameter"); + runRefactoring(false); + } + + public void testInnerDocumentedClass() throws Exception { + IType outer= setupType(); + IType inner= outer.getType("InnerClass"); + assertTrue(inner.exists()); + fDescriptor.setType(inner); + fDescriptor.setCreateGetterSetter(true); + fDescriptor.setClassName("InnerClassParameter"); + runRefactoring(false); + } + + public void testPackageReferences() throws Exception { + createAdditionalFile("subPack","PackEx"); + fDescriptor.setType(setupType()); + fDescriptor.setCreateGetterSetter(true); + fDescriptor.setClassName("PackageReferencesParameter"); + RefactoringStatus status= runRefactoring(true); + RefactoringStatusEntry[] entries= status.getEntries(); + //Error for privateInner reference + //Error for OtherPackageProteced reference + assertEquals(2, entries.length); + for (int i= 0; i < entries.length; i++) { + RefactoringStatusEntry refactoringStatusEntry= entries[i]; + assertEquals(true, refactoringStatusEntry.isError()); + } + } + + public void testDuplicateParamName() throws Exception { + IJavaProject javaProject= getRoot().getJavaProject(); + Map originalOptions= javaProject.getOptions(true); + try { + HashMap newOptions= new HashMap(originalOptions); + newOptions.put(JavaCore.CODEASSIST_FIELD_PREFIXES, "f"); + javaProject.setOptions(newOptions); + fDescriptor.setType(setupType()); + fDescriptor.setCreateGetterSetter(true); + fDescriptor.setClassName("DuplicateParamNameParameter"); + runRefactoring(false); + } finally { + javaProject.setOptions(originalOptions); + } + } + + public void testLowestVisibility() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setCreateGetterSetter(true); + fDescriptor.setClassName("LowestVisibilityParameter"); + runRefactoring(false); + } + + public void testSwitchCaseUpdates() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setCreateGetterSetter(true); + fDescriptor.setClassName("SwitchCaseUpdatesParameter"); + runRefactoring(false); + } + + public void testFieldsWithJavadoc() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setFieldName("data"); + fDescriptor.setCreateGetterSetter(true); + runRefactoring(false); + } + + public void testQualifiedIncrements() throws Exception { + fDescriptor.setType(setupType()); + fDescriptor.setCreateGetterSetter(true); + fDescriptor.setClassName("QualifiedIncrementsParameter"); + RefactoringStatus status= runRefactoring(false); + RefactoringStatusEntry[] entries= status.getEntries(); + //3*Warning for semantic change + assertEquals(3, entries.length); + for (int i= 0; i < entries.length; i++) { + RefactoringStatusEntry refactoringStatusEntry= entries[i]; + assertEquals(true, refactoringStatusEntry.isWarning()); + } + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractConstantTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractConstantTests.java new file mode 100644 index 000000000..0dbf96b1d --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractConstantTests.java @@ -0,0 +1,416 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.Hashtable; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.jface.preference.IPreferenceStore; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatusCodes; +import org.eclipse.jdt.internal.corext.refactoring.code.ExtractConstantRefactoring; + +import org.eclipse.jdt.ui.PreferenceConstants; +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +import org.eclipse.jdt.internal.ui.JavaPlugin; + +public class ExtractConstantTests extends RefactoringTest { + + private static final Class clazz = ExtractConstantTests.class; + private static final String REFACTORING_PATH = "ExtractConstant/"; + + private static final boolean BUG_86113_ImportRewrite= true; + + private Object fCompactPref; + private boolean fAddComments; + + public ExtractConstantTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + private String getSimpleTestFileName(boolean canInline, boolean input){ + String fileName = "A_" + getName(); + if (canInline) + fileName += input ? "_in": "_out"; + return fileName + ".java"; + } + + private String getTestFileName(boolean canExtract, boolean input){ + String fileName= TEST_PATH_PREFIX + getRefactoringPath(); + fileName += (canExtract ? "canExtract/": "cannotExtract/"); + return fileName + getSimpleTestFileName(canExtract, input); + } + + protected ICompilationUnit createCUfromTestFile(IPackageFragment pack, boolean canExtract, boolean input) throws Exception { + return createCU(pack, getSimpleTestFileName(canExtract, input), getFileContents(getTestFileName(canExtract, input))); + } + + protected void setUp() throws Exception { + super.setUp(); + Hashtable options= JavaCore.getOptions(); + + String setting= DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR; + fCompactPref= options.get(setting); + options.put(setting, DefaultCodeFormatterConstants.TRUE); + JavaCore.setOptions(options); + + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + fAddComments= store.getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS); + store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false); + } + + protected void tearDown() throws Exception { + super.tearDown(); + Hashtable options= JavaCore.getOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR, fCompactPref); + JavaCore.setOptions(options); + + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, fAddComments); + } + + private void guessHelper(int startLine, int startColumn, int endLine, int endColumn, String expectedGuessedName) throws Exception { + ICompilationUnit cu= createCU(getPackageP(), getName()+".java", getFileContents(TEST_PATH_PREFIX + getRefactoringPath() + "nameGuessing/" + getName()+".java")); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ExtractConstantRefactoring ref= new ExtractConstantRefactoring(cu, selection.getOffset(), selection.getLength()); + RefactoringStatus preconditionResult= ref.checkInitialConditions(new NullProgressMonitor()); + assertTrue("activation was supposed to be successful" + preconditionResult.toString(), preconditionResult.isOK()); + assertEquals("constant name not guessed", expectedGuessedName, ref.guessConstantName()); + } + + private void helper1(int startLine, int startColumn, int endLine, int endColumn, boolean replaceAll, boolean allowLoadtime, boolean qualifyReferencesWithConstantName, String constantName, String guessedConstantName) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ExtractConstantRefactoring ref= new ExtractConstantRefactoring(cu, selection.getOffset(), selection.getLength()); + RefactoringStatus preconditionResult= ref.checkInitialConditions(new NullProgressMonitor()); + assertTrue("activation was supposed to be successful" + preconditionResult.toString(), preconditionResult.isOK()); + + if(!allowLoadtime) + assertTrue("The selected expression has been erroneously reported to contain references to non-static or non-final fields.", ref.selectionAllStaticFinal()); + + ref.setReplaceAllOccurrences(replaceAll); + ref.setQualifyReferencesWithDeclaringClassName(qualifyReferencesWithConstantName); + ref.setConstantName(constantName); + + assertEquals("constant name incorrectly guessed", guessedConstantName, ref.guessConstantName()); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to pass", checkInputResult.isOK()); + + performChange(ref, false); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + assertEqualLines(getFileContents(getTestFileName(true, false)), newcu.getSource()); + } + + private void helper1(int startLine, int startColumn, int endLine, int endColumn, boolean replaceAll, boolean allowLoadtime, String constantName, String guessedConstantName) throws Exception{ + helper1(startLine, startColumn, endLine, endColumn, replaceAll, allowLoadtime, false, constantName, guessedConstantName); + } + + private void failHelper1(int startLine, int startColumn, int endLine, int endColumn, boolean replaceAll, boolean allowLoadtime, String constantName) throws Exception { + failHelper1(startLine, startColumn, endLine, endColumn, replaceAll, allowLoadtime, constantName, 0, false); + } + + private void failHelper1(int startLine, int startColumn, int endLine, int endColumn, boolean replaceAll, boolean allowLoadtime, String constantName, int errorCode, boolean checkCode) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), false, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ExtractConstantRefactoring ref= new ExtractConstantRefactoring(cu, selection.getOffset(), selection.getLength()); + ref.setReplaceAllOccurrences(replaceAll); + ref.setConstantName(constantName); + RefactoringStatus result= performRefactoring(ref); + + if(!allowLoadtime && !ref.selectionAllStaticFinal()) + return; + + assertNotNull("precondition was supposed to fail", result); + if(checkCode) + assertEquals(errorCode, result.getEntryMatchingSeverity(RefactoringStatus.ERROR).getCode()); + } + + //--- TESTS + + public void test0() throws Exception { + helper1(5, 16, 5, 17, true, false, "CONSTANT", "_0"); + } + + public void test1() throws Exception { + helper1(5, 16, 5, 21, false, false, "CONSTANT", "INT"); + } + + public void test2() throws Exception { + helper1(8, 16, 8, 27, false, false, "CONSTANT", "INT"); + } + + public void test3() throws Exception { + helper1(8, 16, 8, 27, true, false, "CONSTANT", "INT"); + } + + public void test4() throws Exception { + helper1(5, 23, 5, 34, true, false, "CONSTANT", "INT"); + } + + public void test5() throws Exception { + helper1(11, 20, 11, 26, true, true, "CONSTANT", "R_G"); + } + + public void test6() throws Exception { + helper1(13, 20, 13, 35, true, true, "CONSTANT", "R_F"); + } + + public void test7() throws Exception { + helper1(12, 20, 12, 28, true, true, "CONSTANT", "R_G"); + } + + public void test8() throws Exception { + helper1(8, 16, 8, 22, true, true, "CONSTANT", "INT"); + } + + public void test9() throws Exception { + helper1(6, 24, 6, 29, true, true, "CONSTANT", "INT"); + } + + public void test10() throws Exception { + helper1(8, 17, 8, 22, true, true, "CONSTANT", "INT"); + } + + public void test11() throws Exception { + helper1(10, 37, 10, 43, true, true, "CONSTANT", "INT"); + } + + public void test12() throws Exception { + helper1(9, 19, 9, 24, true, true, "CONSTANT", "INT"); + } + + public void test13() throws Exception{ + helper1(9, 16, 9, 28, true, true, "CONSTANT", "F"); + } + + public void test14() throws Exception{ + helper1(10, 28, 10, 44, true, true, "CONSTANT", "INT"); + } + + public void test15() throws Exception{ + helper1(5, 16, 5, 25, true, false, "CONSTANT", "FRED"); + } + + public void test16() throws Exception{ + helper1(5, 20, 5, 27, true, false, "CONSTANT", "RED"); + } + + public void test17() throws Exception{ + helper1(5, 16, 5, 35, true, false, "CONSTANT", "YET_ANOTHER_FRED"); + } + + public void test18() throws Exception { + helper1(5, 16, 5, 17, true, false, true, "CONSTANT", "_0"); + } + + public void test19() throws Exception { + helper1(5, 23, 5, 38, false, false, "CONSTANT", "STRING"); + } + + public void test20() throws Exception { + helper1(7, 19, 7, 28, false, false, "CONSTANT", "STRING"); + } + + public void test21() throws Exception { + helper1(4, 28, 4, 37, false, false, "CONSTANT", "STRING"); + } + + public void test22() throws Exception { + helper1(9, 35, 9, 59, false, false, "ITEMS", "ARRAY_LIST"); + } + + public void test23() throws Exception { + helper1(14, 12, 14, 15, true, false, "COLOR", "RED2"); + } + + public void test24() throws Exception { + if (BUG_86113_ImportRewrite) { + printTestDisabledMessage("BUG_86113_ImportRewrite"); + return; + } + helper1(9, 28, 9, 36, true, false, "NUM", "ENUM"); + } + + public void test25() throws Exception { + helper1(5, 27, 5, 40, false, false, "DEFAULT_NAME", "JEAN_PIERRE"); + } + + public void test26() throws Exception { + helper1(6, 16, 6, 32, true, false, true, "INT", "A"); + } + + public void test27() throws Exception { + helper1(13, 14, 13, 19, true, false, false, "FOO", "FOO"); + } + + public void test28() throws Exception { + helper1(13, 14, 13, 19, true, false, false, "FOO", "FOO"); + } + + public void test29() throws Exception { + helper1(12, 19, 12, 28, false, true, "NUMBER", "NUMBER"); + } + + public void test30() throws Exception { + helper1(12, 19, 12, 28, false, true, "INTEGER", "INTEGER"); + } + + public void test31() throws Exception { //bug 104293 + helper1(9, 32, 9, 44, true, false, "AS_LIST", "AS_LIST"); + } + + public void test32() throws Exception { //bug 104293 + helper1(7, 20, 7, 35, true, false, "STRING", "STRING"); + } + + public void test33() throws Exception { //bug 108354 + helper1(7, 20, 7, 35, true, false, "STRING", "STRING"); + } + + public void test34() throws Exception { // syntax error + helper1(7, 20, 7, 35, true, false, "STRING", "STRING"); + } + + public void test35() throws Exception { // bug 218108 + helper1(7, 20, 7, 25, true, false, "BUG", "BUG"); + } + + public void test36() throws Exception { // bug 218108 + helper1(7, 20, 7, 25, true, false, "BUG", "BUG"); + } + + public void testZeroLengthSelection0() throws Exception { + helper1(5, 18, 5, 18, false, false, "CONSTANT", "_100"); + } + + // -- testing failing preconditions + public void testFail0() throws Exception{ + failHelper1(8, 16, 8, 21, true, true, "CONSTANT"); + } + + public void testFail1() throws Exception{ + failHelper1(8, 16, 8, 26 , true, true, "CONSTANT"); + } + + public void testFail2() throws Exception{ + failHelper1(9, 20, 9, 21 , true, true, "CONSTANT"); + } + + public void testFail3() throws Exception{ + failHelper1(9, 18, 9, 25, true, true, "CONSTANT"); + } + + public void testFail4() throws Exception{ + failHelper1(6, 16, 6, 20, true, true, "CONSTANT"); + } + + public void testFail5() throws Exception{ + failHelper1(9, 16, 9, 25, true, true, "CONSTANT"); + } + + public void testFail6() throws Exception{ + failHelper1(11, 20, 11, 24, true, true, "CONSTANT"); + } + + public void testFail7() throws Exception{ + failHelper1(11, 20, 11, 34, true, true, "CONSTANT"); + } + + public void testFail10() throws Exception{ + failHelper1(15, 20, 15, 37, true, false, "CONSTANT"); + } + + public void testFail11() throws Exception{ + failHelper1(8, 16, 8, 22, true, false, "CONSTANT"); + } + + public void testFail12() throws Exception{ + failHelper1(4, 7, 4, 8, true, true, "CONSTANT", RefactoringStatusCodes.EXPRESSION_NOT_RVALUE, true); + } + + public void testFail13() throws Exception { + failHelper1(2, 9, 2, 10, true, true, "CONSTANT", RefactoringStatusCodes.EXPRESSION_NOT_RVALUE, true); + } + + public void testFail14() throws Exception { + failHelper1(5, 9, 5, 11, true, true, "CONSTANT"); + } + + public void testFail15() throws Exception { + failHelper1(5, 10, 5, 13, true, true, "CONSTANT"); + } + + public void testFail16() throws Exception { + failHelper1(9, 20, 9, 38, true, false, "CONSTANT"); + } + + public void testFail17() throws Exception { + failHelper1(16, 18, 16, 21, true, true, "COLOR"); + } + + public void testGuessStringLiteral0() throws Exception { + //test for bug 37377 + guessHelper(4, 19, 4, 32, "FOO_HASH_MAP"); + } + + public void testGuessStringLiteral1() throws Exception { + //test for bug 37377 + guessHelper(4, 19, 4, 33, "FOO_HASH_MAP"); + } + + public void testGuessStringLiteral2() throws Exception { + //test for bug 37377 + guessHelper(4, 19, 4, 56, "HANS_IM_GLUECK123_34_BLA_BLA"); + } + + public void testGuessStringLiteral3() throws Exception { + guessHelper(5, 16, 5, 16, "ASSUME_CAMEL_CASE"); + } + + public void testGuessFromGetterName0() throws Exception { + guessHelper(4, 19, 4, 30, "FOO_BAR"); + } + + public void testGuessFromGetterName1() throws Exception { + guessHelper(4, 23, 4, 33, "FOO_BAR"); + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractInterfaceTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractInterfaceTests.java new file mode 100644 index 000000000..f79d304d7 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractInterfaceTests.java @@ -0,0 +1,934 @@ +/******************************************************************************* + * Copyright (c) 2000, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.Hashtable; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; + +public class ExtractInterfaceTests extends RefactoringTest { + + private static final Class clazz= ExtractInterfaceTests.class; + private static final String REFACTORING_PATH= "ExtractInterface/"; + private Hashtable fOldOptions; + private boolean fGenerateAnnotations= false; + + public ExtractInterfaceTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + protected void setUp() throws Exception { + super.setUp(); + StubUtility.setCodeTemplate(CodeTemplateContextType.NEWTYPE_ID, + "${package_declaration}" + + System.getProperty("line.separator", "\n") + + "${"+ CodeTemplateContextType.TYPE_COMMENT+"}" + + System.getProperty("line.separator", "\n") + + "${type_declaration}", null); + + StubUtility.setCodeTemplate(CodeTemplateContextType.TYPECOMMENT_ID, "/** typecomment template*/", null); + + fOldOptions= JavaCore.getOptions(); + + Hashtable options= TestOptions.getDefaultOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR, DefaultCodeFormatterConstants.TRUE); + options.put(DefaultCodeFormatterConstants.FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE, "1"); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.TAB); + + JavaCore.setOptions(options); + } + + protected void tearDown() throws Exception { + super.tearDown(); + JavaCore.setOptions(fOldOptions); + fOldOptions= null; + } + + private static String getTopLevelTypeName(String typeQualifiedTyperName){ + int dotIndex= typeQualifiedTyperName.indexOf('.'); + if (dotIndex == -1) + return typeQualifiedTyperName; + return typeQualifiedTyperName.substring(0, dotIndex); + } + + private IType getClassFromTestFile(IPackageFragment pack, String className) throws Exception{ + return getType(createCUfromTestFile(pack, getTopLevelTypeName(className)), className); + } + + private void validatePassingTest(String className, String[] cuNames, String newInterfaceName, boolean replaceOccurrences, String[] extractedMethodNames, String[][] extractedSignatures, String[] extractedFieldNames) throws Exception { + IType clas= getClassFromTestFile(getPackageP(), className); + + ExtractInterfaceProcessor processor= new ExtractInterfaceProcessor(clas, JavaPreferencesSettings.getCodeGenerationSettings(clas.getJavaProject())); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + processor.setTypeName(newInterfaceName); + assertEquals("interface name should be accepted", RefactoringStatus.OK, processor.checkTypeName(newInterfaceName).getSeverity()); + + ICompilationUnit[] cus= new ICompilationUnit[cuNames.length]; + for (int i= 0; i < cuNames.length; i++) { + if (cuNames[i].equals(clas.getCompilationUnit().findPrimaryType().getElementName())) + cus[i]= clas.getCompilationUnit(); + else + cus[i]= createCUfromTestFile(clas.getPackageFragment(), cuNames[i]); + } + processor.setReplace(replaceOccurrences); + processor.setAnnotations(fGenerateAnnotations); + IMethod[] extractedMethods= getMethods(clas, extractedMethodNames, extractedSignatures); + IField[] extractedFields= getFields(clas, extractedFieldNames); + processor.setExtractedMembers(merge(extractedMethods, extractedFields)); + assertEquals("was supposed to pass", null, performRefactoring(ref)); + + for (int i= 0; i < cus.length; i++) { + String expected= getFileContents(getOutputTestFileName(cuNames[i])); + String actual= cus[i].getSource(); + assertEqualLines("(" + cus[i].getElementName() +")", expected, actual); + } + + ICompilationUnit interfaceCu= clas.getPackageFragment().getCompilationUnit(newInterfaceName + ".java"); + assertEqualLines("(interface cu)", getFileContents(getOutputTestFileName(newInterfaceName)), interfaceCu.getSource()); + } + + private void validatePassingTest(String className, String newInterfaceName, boolean extractAll, boolean replaceOccurrences) throws Exception { + IType clas= getClassFromTestFile(getPackageP(), className); + ICompilationUnit cu= clas.getCompilationUnit(); + IPackageFragment pack= (IPackageFragment)cu.getParent(); + + ExtractInterfaceProcessor processor= new ExtractInterfaceProcessor(clas, JavaPreferencesSettings.getCodeGenerationSettings(clas.getJavaProject())); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + processor.setTypeName(newInterfaceName); + assertEquals("interface name should be accepted", RefactoringStatus.OK, processor.checkTypeName(newInterfaceName).getSeverity()); + + if (extractAll) + processor.setExtractedMembers(processor.getExtractableMembers()); + processor.setReplace(replaceOccurrences); + processor.setAnnotations(fGenerateAnnotations); + assertEquals("was supposed to pass", null, performRefactoring(ref)); + assertEqualLines("incorrect changes in " + className, + getFileContents(getOutputTestFileName(className)), + cu.getSource()); + + ICompilationUnit interfaceCu= pack.getCompilationUnit(newInterfaceName + ".java"); + assertEqualLines("incorrect interface created", + getFileContents(getOutputTestFileName(newInterfaceName)), + interfaceCu.getSource()); + } + + private void validateFailingTest(String className, String newInterfaceName, boolean extractAll, int expectedSeverity) throws Exception { + IType clas= getClassFromTestFile(getPackageP(), className); + ExtractInterfaceProcessor processor= new ExtractInterfaceProcessor(clas, JavaPreferencesSettings.getCodeGenerationSettings(clas.getJavaProject())); + Refactoring ref= new ProcessorBasedRefactoring(processor); + processor.setTypeName(newInterfaceName); + if (extractAll) + processor.setExtractedMembers(processor.getExtractableMembers()); + assertTrue("was not supposed to pass", performRefactoring(ref) != null); + assertEquals("was not supposed to fail with different severity", expectedSeverity, performRefactoring(ref).getSeverity()); + } + + private void standardPassingTest() throws Exception{ + String[] names= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, null); + } + //---------------tests ---------------------- + + public void test0() throws Exception{ + validatePassingTest("A", "I", true, false); + } + + public void test1() throws Exception{ + validatePassingTest("A", "I", true, false); + } + + public void test2() throws Exception{ + validatePassingTest("A", "I", true, false); + } + + public void test3() throws Exception{ + validatePassingTest("A", "I", true, false); + } + + public void test4() throws Exception{ + validatePassingTest("A", "I", true, false); + } + + public void test5() throws Exception{ + validatePassingTest("A", "I", true, false); + } + + public void test6() throws Exception{ + validatePassingTest("A", "I", true, false); + } + + public void test7() throws Exception{ + validatePassingTest("A", "I", true, false); + } + + public void test8() throws Exception{ + validatePassingTest("A", "I", true, false); + } + + public void test9() throws Exception{ + validatePassingTest("A", "I", true, false); + } + + public void test10() throws Exception{ + validatePassingTest("A", "I", true, false); + } + + public void test11() throws Exception{ + validatePassingTest("A", "I", true, false); + } + + public void test12() throws Exception{ + validatePassingTest("A", "I", true, true); + } + + public void test13() throws Exception{ + validatePassingTest("A", "I", true, true); + } + + public void test14() throws Exception{ + standardPassingTest(); + } + + public void test15() throws Exception{ + String[] names= new String[]{"m", "m1"}; + String[][] signatures= new String[][]{new String[0], new String[0]}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, null); + } + + public void test16() throws Exception{ + standardPassingTest(); + } + + public void test17() throws Exception{ + standardPassingTest(); + } + + public void test18() throws Exception{ + standardPassingTest(); + } + + public void test19() throws Exception{ + standardPassingTest(); + } + + public void test20() throws Exception{ + String[] names= new String[]{"m", "m1"}; + String[][] signatures= new String[][]{new String[0], new String[0]}; + validatePassingTest("A", new String[]{"A"},"I", true, names, signatures, null); + } + + public void test21() throws Exception{ + validatePassingTest("A", "I", true, true); + } + + public void test22() throws Exception{ + validatePassingTest("A", "I", true, true); + } + + public void test23() throws Exception{ + validatePassingTest("A", "I", true, true); + } + + public void test24() throws Exception{ + standardPassingTest(); + } + + public void test25() throws Exception{ + validatePassingTest("A", "I", true, true); + } + + public void test26() throws Exception{ + standardPassingTest(); + } + + public void test27() throws Exception{ + standardPassingTest(); + } + + public void test28() throws Exception{ + standardPassingTest(); + } + + public void test29() throws Exception{ + standardPassingTest(); + } + + public void test30() throws Exception{ + standardPassingTest(); + } + + public void test31() throws Exception{ + standardPassingTest(); + } + + public void test32() throws Exception{ + standardPassingTest(); + } + + public void test33() throws Exception{ + standardPassingTest(); + } + + public void test34() throws Exception{ + standardPassingTest(); + } + + public void test35() throws Exception{ + standardPassingTest(); + } + + public void test36() throws Exception{ + standardPassingTest(); + } + + public void test37() throws Exception{ + standardPassingTest(); + } + + public void test38() throws Exception{ + standardPassingTest(); + } + + public void test39() throws Exception{ + standardPassingTest(); + } + + public void test40() throws Exception{ + standardPassingTest(); + } + + public void test41() throws Exception{ + standardPassingTest(); + } + + public void test42() throws Exception{ + standardPassingTest(); + } + + public void test43() throws Exception{ + standardPassingTest(); + } + + public void test44() throws Exception{ + standardPassingTest(); + } + + public void test45() throws Exception{ + standardPassingTest(); + } + + public void test46() throws Exception{ + standardPassingTest(); + } + + public void test47() throws Exception{ + standardPassingTest(); + } + + public void test48() throws Exception{ + standardPassingTest(); + } + + public void test49() throws Exception{ + standardPassingTest(); + } + + public void test50() throws Exception{ + standardPassingTest(); + } + + public void test51() throws Exception{ + standardPassingTest(); + } + + public void test52() throws Exception{ + standardPassingTest(); + } + + public void test53() throws Exception{ + standardPassingTest(); + } + + public void test54() throws Exception{ + String[] names= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A", "A1"}, "I", true, names, signatures, null); + } + + public void test55() throws Exception{ + String[] names= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A", "A1"}, "I", true, names, signatures, null); + } + + public void test56() throws Exception{ + String[] names= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A", "A1"}, "I", true, names, signatures, null); + } + + public void test57() throws Exception{ + String[] names= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A", "A1"}, "I", true, names, signatures, null); + } + + public void test58() throws Exception{ + standardPassingTest(); + } + + public void test59() throws Exception{ +// printTestDisabledMessage("bug 22946 "); + standardPassingTest(); + } + + public void test60() throws Exception{ + standardPassingTest(); + } + + public void test61() throws Exception{ + standardPassingTest(); + } + + public void test62() throws Exception{ + standardPassingTest(); + } + + public void test63() throws Exception{ + standardPassingTest(); + } + + public void test64() throws Exception{ +// printTestDisabledMessage("test for 23105"); + String[] names= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A", "Inter"}, "I", true, names, signatures, null); + } + + public void test65() throws Exception{ +// printTestDisabledMessage("test for 23105"); + standardPassingTest(); + } + + public void test66() throws Exception{ + standardPassingTest(); + } + + public void test67() throws Exception{ +// printTestDisabledMessage("test for 23105"); + String[] names= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A", "Outer", "Inter"}, "I", true, names, signatures, null); + } + + public void test68() throws Exception{ + String[] names= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A", "As"}, "I", true, names, signatures, null); + } + + public void test69() throws Exception{ + String[] names= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A", "As"}, "I", true, names, signatures, null); + } + + public void test70() throws Exception{ + standardPassingTest(); + } + + public void test71() throws Exception{ + String[] names= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A", "As"}, "I", true, names, signatures, null); + } + + public void test72() throws Exception{ +// printTestDisabledMessage("bug 23705"); + String[] names= new String[]{"m"}; + String[][] signatures= new String[][]{new String[]{"QA;"}}; + validatePassingTest("A", new String[]{"A", "As"}, "I", true, names, signatures, null); + } + + public void test73() throws Exception{ +// printTestDisabledMessage("bug 23953"); + String[] names= new String[]{"amount"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A", "B", "OldInterface"}, "I", true, names, signatures, null); + } + + public void test74() throws Exception{ +// printTestDisabledMessage("bug 23953"); + String[] names= new String[]{"amount"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A", "B", "OldInterface"}, "I", true, names, signatures, null); + } + + public void test75() throws Exception{ +// printTestDisabledMessage("bug 23953"); + String[] names= new String[]{"amount"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A", "B", "C"}, "I", true, names, signatures, null); + } + + public void test76() throws Exception{ +// printTestDisabledMessage("bug 23953"); + String[] names= new String[]{"amount"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A", new String[]{"A", "B", "C"}, "I", true, names, signatures, null); + } + + public void test77() throws Exception{ +// printTestDisabledMessage("Waiting for new type constraints infrastructure"); + String[] names= new String[]{"amount"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("A.Inner", new String[]{"A", "B"}, "I", true, names, signatures, null); + } + + public void test78() throws Exception{ +// printTestDisabledMessage("bug 23705"); + String[] names= new String[]{"m"}; + String[][] signatures= new String[][]{new String[]{"QA;"}}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, null); + } + + public void test79() throws Exception{ +// printTestDisabledMessage("bug 23697"); + String[] names= new String[]{"getFoo", "foo"}; + String[][] signatures= new String[][]{new String[0], new String[]{"QA;"}}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, null); + } + + public void test80() throws Exception{ +// printTestDisabledMessage("bug 33223"); + String[] names= new String[]{"f", "fz", "f1", "f1z", "f11", "f2"}; + String[][] signatures= new String[][]{new String[0], new String[0], new String[0], new String[0], new String[0], new String[0]}; + String[] fieldNames= {"I1", "I1z", "I2", "I2z", "I3", "I4"}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test81() throws Exception{ +// printTestDisabledMessage("bug 33878 extract interface: incorrect handling of arrays "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test82() throws Exception{ +// printTestDisabledMessage("bug 33878 extract interface: incorrect handling of arrays "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test83() throws Exception{ +// printTestDisabledMessage("bug 33878 extract interface: incorrect handling of arrays "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test84() throws Exception{ +// printTestDisabledMessage("bug 34931 Extract Interface does not update all references "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test85() throws Exception{ +// printTestDisabledMessage("bug 34931 Extract Interface does not update all references "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test86() throws Exception{ +// printTestDisabledMessage("bug 34931 Extract Interface does not update all references "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test87() throws Exception{ +// printTestDisabledMessage("bug 34931 Extract Interface does not update all references "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test88() throws Exception{ +// printTestDisabledMessage("bug 34931 Extract Interface does not update all references "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test89() throws Exception{ +// printTestDisabledMessage("bug 34931 Extract Interface does not update all references "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test90() throws Exception{ +// printTestDisabledMessage("bug 34931 Extract Interface does not update all references "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test91() throws Exception{ +// printTestDisabledMessage("bug 34931 Extract Interface does not update all references "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test92() throws Exception{ +// printTestDisabledMessage("bug 34931 Extract Interface does not update all references "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test93() throws Exception{ +// printTestDisabledMessage("bug 34931 Extract Interface does not update all references "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test94() throws Exception{ +// printTestDisabledMessage("bug 34931 Extract Interface does not update all references "); + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test95() throws Exception{ + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test96() throws Exception{ + String[] names= {}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test97() throws Exception{ + //printTestDisabledMessage("bug 40373"); + String[] names= {"foo"}; + String[][] signatures= {{}}; + String[] fieldNames= {}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void test98() throws Exception{ + //test for 41464 + String[] names= new String[]{"foo"}; + String[][] signatures= new String[][]{new String[0]}; + validatePassingTest("Foo", new String[]{"Foo", "Bar"}, "IFoo", true, names, signatures, null); + } + + public void test99() throws Exception{ + String[] names= new String[]{}; + String[][] signatures= new String[][]{}; + validatePassingTest("C", new String[]{"A", "B", "C"}, "I", true, names, signatures, null); + } + + public void test100() throws Exception{ + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=47785 + validatePassingTest("A", "I", true, false); + } + + public void test101() throws Exception{ + String[] names= new String[]{}; + String[][] signatures= new String[][]{}; + validatePassingTest("C", new String[]{"A", "B", "C"}, "I", true, names, signatures, null); + } + + public void test102() throws Exception{ + String[] names= new String[]{}; + String[][] signatures= new String[][]{}; + + validatePassingTest("C", new String[]{"A", "B", "C"}, "I", true, names, signatures, null); + } + + public void test103() throws Exception{ + String[] names= new String[]{}; + String[][] signatures= new String[][]{}; + + validatePassingTest("C", new String[]{"A", "B", "C"}, "I", true, names, signatures, null); + } + + public void test104() throws Exception { + // bug 195817 + String[] names= new String[]{ "m1" }; + String[][] signatures= new String[][]{ new String[0] }; + + validatePassingTest("A", new String[]{"A", "B"}, "I", true, names, signatures, null); + } + + public void test105() throws Exception{ + // bug 195817 + String[] names= new String[]{ "m2" }; + String[][] signatures= new String[][]{ new String[0] }; + + validatePassingTest("A", new String[]{"A", "B"}, "I", true, names, signatures, null); + } + + public void test106() throws Exception { + // bug 195817 + String[] names= new String[]{ "m1" }; + String[][] signatures= new String[][]{ new String[0] }; + + validatePassingTest("A", new String[]{"A", "B"}, "I", true, names, signatures, null); + } + + public void test107() throws Exception{ + // bug 195817 + String[] names= new String[]{ "m2" }; + String[][] signatures= new String[][]{ new String[0] }; + + validatePassingTest("A", new String[]{"A", "B"}, "I", true, names, signatures, null); + } + + public void test108() throws Exception{ + // bug 195817 + fGenerateAnnotations= true; // should not generate because project is 1.5 + standardPassingTest(); + } + + public void test109() throws Exception{ + // Generate @Override in 1.6 project + fGenerateAnnotations= true; + RefactoringTestSetup refactoringTestSetup= new RefactoringTestSetup(null); + try { + JavaProjectHelper.addRTJar16(getRoot().getJavaProject()); + + standardPassingTest(); + + refactoringTestSetup.tearDown(); + } finally { + refactoringTestSetup.setUp(); + } + } + + public void testPaperExample0() throws Exception{ + String[] names= new String[]{"add", "addAll", "iterator"}; + String[][] signatures= new String[][]{new String[]{"QComparable;"}, new String[]{"QA;"}, new String[0]}; + String[] fieldNames= null; + validatePassingTest("A", new String[]{"A"}, "Bag", true, names, signatures, fieldNames); + } + + public void testPaperExample1() throws Exception{ + String[] names= new String[]{"add", "addAll", "iterator"}; + String[][] signatures= new String[][]{new String[]{"QComparable;"}, new String[]{"QA;"}, new String[0]}; + String[] fieldNames= null; + validatePassingTest("A", new String[]{"A"}, "Bag", true, names, signatures, fieldNames); + } + + public void testPaperExampleSimplified0() throws Exception{ + String[] names= new String[]{}; + String[][] signatures= {{}}; + String[] fieldNames= null; + validatePassingTest("A", new String[]{"A"}, "Bag", true, names, signatures, fieldNames); + } + + + public void testConditional1() throws Exception { + String[] names= new String[]{}; + String[][] signatures= {{}}; + String[] fieldNames= null; + validatePassingTest("X", new String[]{"A", "X"}, "I", true, names, signatures, fieldNames); + } + + public void testConditional2() throws Exception { + String[] names= new String[]{ "dot" }; + String[][] signatures= {new String[]{"QX;"}}; + String[] fieldNames= null; + validatePassingTest("X", new String[]{"A", "X"}, "I", true, names, signatures, fieldNames); + } + + public void testConstant80() throws Exception{ + String[] names= null; + String[][] signatures= null; + String[] fieldNames= {"X"}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void testConstant81() throws Exception{ + String[] names= null; + String[][] signatures= null; + String[] fieldNames= {"X"}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void testConstant82() throws Exception{ + String[] names= null; + String[][] signatures= null; + String[] fieldNames= {"X"}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void testConstant83() throws Exception{ + String[] names= null; + String[][] signatures= null; + String[] fieldNames= {"X"}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void testConstant84() throws Exception{ + String[] names= null; + String[][] signatures= null; + String[] fieldNames= {"X"}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void testConstant85() throws Exception{ + String[] names= null; + String[][] signatures= null; + String[] fieldNames= {"X"}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void testConstant86() throws Exception{ + String[] names= null; + String[][] signatures= null; + String[] fieldNames= {"X", "Y"}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void testConstant87() throws Exception{ + String[] names= null; + String[][] signatures= null; + String[] fieldNames= {"X", "Y"}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void testConstant88() throws Exception{ + String[] names= null; + String[][] signatures= null; + String[] fieldNames= {"X", "Y"}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void testInterface0() throws Exception{ + String[] names= {"m"}; + String[][] signatures= {new String[0]}; + String[] fieldNames= null; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void testInterface1() throws Exception{ + String[] names= {"m"}; + String[][] signatures= {new String[0]}; + String[] fieldNames= null; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void testInterface2() throws Exception{ + String[] names= {"m"}; + String[][] signatures= {new String[0]}; + String[] fieldNames= {"i", "j"}; + validatePassingTest("A", new String[]{"A"}, "I", true, names, signatures, fieldNames); + } + + public void testInterface3() throws Exception{ + String[] methodNames= {"m", "m1", "m2", "m4", "m5"}; + String[][] signatures= {new String[0], new String[0], new String[0], new String[0], new String[0]}; + String[] fieldNames= {"I", "I1", "I2", "I4", "I5"}; + validatePassingTest("A", new String[]{"A"}, "I", true, methodNames, signatures, fieldNames); + } + + public void testInterface4() throws Exception{ +// printTestDisabledMessage("cannot yet update references (in methods) to itself if it's an interface"); + String[] methodNames= {"a"}; + String[][] signatures= {{"QA;", "QA;"}}; + String[] fieldNames= null; + validatePassingTest("A", new String[]{"A"}, "I", true, methodNames, signatures, fieldNames); + } + + public void testInterface5() throws Exception{ + String[] methodNames= {"a"}; + String[][] signatures= {new String[0]}; + String[] fieldNames= null; + validatePassingTest("A", new String[]{"A"}, "I", true, methodNames, signatures, fieldNames); + } + + public void testInterface6() throws Exception{ + String[] methodNames= {"foo0", "foo1", "foo2", "foo3"}; + String[][] signatures= {new String[0], new String[0], new String[0], new String[0]}; + String[] fieldNames= null; + validatePassingTest("A", new String[]{"A"}, "I", true, methodNames, signatures, fieldNames); + } + + public void testFail1() throws Exception{ + validateFailingTest("A", "I", true, RefactoringStatus.FATAL); + } + + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTestSetup.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTestSetup.java new file mode 100644 index 000000000..5dc089eff --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTestSetup.java @@ -0,0 +1,173 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +import org.eclipse.ltk.core.refactoring.RefactoringCore; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +public class ExtractMethodTestSetup extends RefactoringTestSetup { + + private IPackageFragment fSelectionPackage; + private IPackageFragment fInvalidSelectionPackage; + private IPackageFragment fValidSelectionPackage; + private IPackageFragment fValidSelectionCheckedPackage; + private IPackageFragment fSemicolonPackage; + private IPackageFragment fTryPackage; + private IPackageFragment fLocalsPackage; + private IPackageFragment fExpressionPackage; + private IPackageFragment fNestedPackage; + private IPackageFragment fReturnPackage; + private IPackageFragment fBranchPackage; + private IPackageFragment fErrorPackage; + private IPackageFragment fWikiPackage; + private IPackageFragment fParameterNamePackage; + private IPackageFragment fDuplicatesPackage; + private IPackageFragment fInitializerPackage; + private IPackageFragment fDestinationPackage; + private IPackageFragment fGenericsPackage; + private IPackageFragment fEnumsPackage; + private IPackageFragment fVarargsPackage; + private IPackageFragment fFieldInitializerPackage; + + public ExtractMethodTestSetup(Test test) { + super(test); + } + + protected void setUp() throws Exception { + super.setUp(); + + RefactoringCore.getUndoManager().flush(); + + IPackageFragmentRoot root= getDefaultSourceFolder(); + fSelectionPackage= root.createPackageFragment("selection", true, null); + fInvalidSelectionPackage= root.createPackageFragment("invalidSelection", true, null); + fValidSelectionPackage= root.createPackageFragment("validSelection", true, null); + fValidSelectionCheckedPackage= root.createPackageFragment("validSelection_in", true, null); + fSemicolonPackage= root.createPackageFragment("semicolon_in", true, null); + fTryPackage= root.createPackageFragment("try_in", true, null); + fLocalsPackage= root.createPackageFragment("locals_in", true, null); + fExpressionPackage= root.createPackageFragment("expression_in", true, null); + fNestedPackage= root.createPackageFragment("nested_in", true, null); + fReturnPackage= root.createPackageFragment("return_in", true, null); + fBranchPackage= root.createPackageFragment("branch_in", true, null); + fErrorPackage= root.createPackageFragment("error_in", true, null); + fWikiPackage= root.createPackageFragment("wiki_in", true, null); + fParameterNamePackage= root.createPackageFragment("parameterName_in", true, null); + fDuplicatesPackage= root.createPackageFragment("duplicates_in", true, null); + fInitializerPackage= root.createPackageFragment("initializer_in", true, null); + fDestinationPackage= root.createPackageFragment("destination_in", true, null); + fGenericsPackage= root.createPackageFragment("generics_in", true, null); + fEnumsPackage= root.createPackageFragment("enums_in", true, null); + fVarargsPackage= root.createPackageFragment("varargs_in", true, null); + fFieldInitializerPackage= root.createPackageFragment("fieldInitializer_in", true, null); + + ICompilationUnit cu= fExpressionPackage.createCompilationUnit( + "A.java", + "package expression_in; import java.io.File; class A { public File getFile() { return null; } public void useFile(File file) { } }", + true, null); + + cu= fExpressionPackage.createCompilationUnit( + "B.java", + "package expression_in; import java.util.List; public class B { public List[] foo() { return null; } }", + true, null); + cu.save(null, true); + } + + public IPackageFragment getExpressionPackage() { + return fExpressionPackage; + } + + public IPackageFragment getInvalidSelectionPackage() { + return fInvalidSelectionPackage; + } + + public IPackageFragment getLocalsPackage() { + return fLocalsPackage; + } + + public IPackageFragment getNestedPackage() { + return fNestedPackage; + } + + public IPackageFragment getReturnPackage() { + return fReturnPackage; + } + + public IPackageFragment getSelectionPackage() { + return fSelectionPackage; + } + + public IPackageFragment getSemicolonPackage() { + return fSemicolonPackage; + } + + public IPackageFragment getTryPackage() { + return fTryPackage; + } + + public IPackageFragment getValidSelectionPackage() { + return fValidSelectionPackage; + } + + public IPackageFragment getValidSelectionCheckedPackage() { + return fValidSelectionCheckedPackage; + } + + public IPackageFragment getBranchPackage() { + return fBranchPackage; + } + + public IPackageFragment getErrorPackage() { + return fErrorPackage; + } + + public IPackageFragment getWikiPackage() { + return fWikiPackage; + } + + public IPackageFragment getParameterNamePackage() { + return fParameterNamePackage; + } + + public IPackageFragment getDuplicatesPackage() { + return fDuplicatesPackage; + } + + public IPackageFragment getInitializerPackage() { + return fInitializerPackage; + } + + public IPackageFragment getDestinationPackage() { + return fDestinationPackage; + } + + public IPackageFragment getGenericsPackage() { + return fGenericsPackage; + } + + public IPackageFragment getEnumsPackage() { + return fEnumsPackage; + } + + public IPackageFragment getVarargsPackage() { + return fVarargsPackage; + } + + public IPackageFragment getFieldInitializerPackage() { + return fFieldInitializerPackage; + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java new file mode 100644 index 000000000..a8ab644b7 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java @@ -0,0 +1,2058 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Benjamin Muskalla <bmuskalla@eclipsesource.com> - [extract method] Does not replace similar code in parent class of anonymous class - https://bugs.eclipse.org/bugs/show_bug.cgi?id=160853 + * Benjamin Muskalla <bmuskalla@eclipsesource.com> - [extract method] Missing return value, while extracting code out of a loop - https://bugs.eclipse.org/bugs/show_bug.cgi?id=213519 + * Benjamin Muskalla <bmuskalla@eclipsesource.com> - [extract method] missing return type when code can throw exception - https://bugs.eclipse.org/bugs/show_bug.cgi?id=97413 + * Benjamin Muskalla <bmuskalla@eclipsesource.com> - [extract method] Extract method and continue https://bugs.eclipse.org/bugs/show_bug.cgi?id=48056 + * Benjamin Muskalla <bmuskalla@eclipsesource.com> - [extract method] should declare method static if extracted from anonymous in static method - https://bugs.eclipse.org/bugs/show_bug.cgi?id=152004 + * Benjamin Muskalla <bmuskalla@eclipsesource.com> - [extract method] extracting return value results in compile error - https://bugs.eclipse.org/bugs/show_bug.cgi?id=264606 + * Technical University Berlin - adapted for Object Teams + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.CheckConditionsOperation; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.ISourceRange; + +import org.eclipse.jdt.internal.corext.refactoring.ParameterInfo; +import org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring; + +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +public class ExtractMethodTests extends AbstractSelectionTestCase { + private static ExtractMethodTestSetup fgTestSetup; + + public ExtractMethodTests(String name) { + super(name); + } + + public static Test suite() { + fgTestSetup= new ExtractMethodTestSetup(new TestSuite(ExtractMethodTests.class)); + return fgTestSetup; + } + + public static Test setUpTest(Test test) { + fgTestSetup= new ExtractMethodTestSetup(test); + return fgTestSetup; + } + + protected void setUp() throws Exception { + super.setUp(); + fIsPreDeltaTest= true; + } + + protected String getResourceLocation() { + return "ExtractMethodWorkSpace/ExtractMethodTests/"; + } + + protected String adaptName(String name) { + return name + "_" + getName() + ".java"; + } + + protected void selectionTest(int startLine, int startColumn, int endLine, int endColumn) throws Exception{ + ICompilationUnit unit= createCU(getSelectionPackage(), "A"); + int[] selection= getSelection(); + ISourceRange expected= TextRangeUtil.getSelection(unit, startLine, startColumn, endLine, endColumn); + assertEquals(expected.getOffset(), selection[0]); + assertEquals(expected.getLength(), selection[1]); + } + + private IPackageFragment getSelectionPackage() { + return fgTestSetup.getSelectionPackage(); + } + + protected void performTest(IPackageFragment packageFragment, String id, int mode, String outputFolder) throws Exception { + performTest(packageFragment, id, mode, outputFolder, null, null, 0); + } + + protected void performTest(IPackageFragment packageFragment, String id, int mode, String outputFolder, String[] newNames, int[] newOrder, int destination) throws Exception { + ICompilationUnit unit= createCU(packageFragment, id); + int[] selection= getSelection(); + ExtractMethodRefactoring refactoring= new ExtractMethodRefactoring(unit, selection[0], selection[1]); + refactoring.setMethodName("extracted"); + refactoring.setVisibility(Modifier.PROTECTED); + TestModelProvider.clearDelta(); + RefactoringStatus status= refactoring.checkInitialConditions(new NullProgressMonitor()); + switch (mode) { + case VALID_SELECTION: + assertTrue(status.isOK()); + break; + case INVALID_SELECTION: + if (!status.isOK()) + return; + } + List parameters= refactoring.getParameterInfos(); + if (newNames != null && newNames.length > 0) { + for (int i= 0; i < newNames.length; i++) { + if (newNames[i] != null) + ((ParameterInfo)parameters.get(i)).setNewName(newNames[i]); + } + } + if (newOrder != null && newOrder.length > 0) { + assertTrue(newOrder.length == parameters.size()); + List current= new ArrayList(parameters); + for (int i= 0; i < newOrder.length; i++) { + parameters.set(newOrder[i], current.get(i)); + } + } + refactoring.setDestination(destination); + + String out= null; + switch (mode) { + case COMPARE_WITH_OUTPUT: + out= getProofedContent(outputFolder, id); + break; + } + performTest(unit, refactoring, mode, out, true); + } + + protected int getCheckingStyle() { + return CheckConditionsOperation.FINAL_CONDITIONS; + } + + protected void clearPreDelta() { + // Do nothing. We clear the delta before + // initial condition checking + } + + protected void invalidSelectionTest() throws Exception { + performTest(fgTestSetup.getInvalidSelectionPackage(), "A", INVALID_SELECTION, null); + } + + protected void validSelectionTest() throws Exception { + performTest(fgTestSetup.getValidSelectionPackage(), "A", VALID_SELECTION, null); + } + + protected void validSelectionTestChecked() throws Exception { + performTest(fgTestSetup.getValidSelectionCheckedPackage(), "A", COMPARE_WITH_OUTPUT, "validSelection_out"); + } + + protected void semicolonTest() throws Exception { + performTest(fgTestSetup.getSemicolonPackage(), "A", COMPARE_WITH_OUTPUT, "semicolon_out"); + } + + protected void tryTest() throws Exception { + performTest(fgTestSetup.getTryPackage(), "A", COMPARE_WITH_OUTPUT, "try_out"); + } + + protected void localsTest() throws Exception { + performTest(fgTestSetup.getLocalsPackage(), "A", COMPARE_WITH_OUTPUT, "locals_out"); + } + + protected void expressionTest() throws Exception { + performTest(fgTestSetup.getExpressionPackage(), "A", COMPARE_WITH_OUTPUT, "expression_out"); + } + + protected void nestedTest() throws Exception { + performTest(fgTestSetup.getNestedPackage(), "A", COMPARE_WITH_OUTPUT, "nested_out"); + } + + protected void returnTest() throws Exception { + performTest(fgTestSetup.getReturnPackage(), "A", COMPARE_WITH_OUTPUT, "return_out"); + } + + protected void branchTest() throws Exception { + performTest(fgTestSetup.getBranchPackage(), "A", COMPARE_WITH_OUTPUT, "branch_out"); + } + + protected void errorTest() throws Exception { + performTest(fgTestSetup.getErrorPackage(), "A", COMPARE_WITH_OUTPUT, "error_out"); + } + + protected void wikiTest() throws Exception { + performTest(fgTestSetup.getWikiPackage(), "A", COMPARE_WITH_OUTPUT, "wiki_out"); + } + + protected void duplicatesTest() throws Exception { + performTest(fgTestSetup.getDuplicatesPackage(), "A", COMPARE_WITH_OUTPUT, "duplicates_out"); + } + + protected void initializerTest() throws Exception { + performTest(fgTestSetup.getInitializerPackage(), "A", COMPARE_WITH_OUTPUT, "initializer_out"); + } + + protected void destinationTest(int destination) throws Exception { + performTest(fgTestSetup.getDestinationPackage(), "A", COMPARE_WITH_OUTPUT, "destination_out", + null, null, destination); + } + + protected void genericTest() throws Exception { + performTest(fgTestSetup.getGenericsPackage(), "A", COMPARE_WITH_OUTPUT, "generics_out"); + } + + protected void enumTest() throws Exception { + performTest(fgTestSetup.getEnumsPackage(), "A", COMPARE_WITH_OUTPUT, "enums_out"); + } + + //===================================================================================== + // Testing selections + //===================================================================================== + + + public void test1() throws Exception { + selectionTest(5, 9, 5, 24); + } + + public void test2() throws Exception { + selectionTest(5, 9, 5, 19); + } + + public void test3() throws Exception { + selectionTest(5, 14, 5, 24); + } + + public void test4() throws Exception { + selectionTest(5, 14, 5, 19); + } + + //===================================================================================== + // Testing invalid selections + //===================================================================================== + + //---- Misc + + public void test010() throws Exception { + invalidSelectionTest(); + } + + public void test011() throws Exception { + invalidSelectionTest(); + } + + public void test012() throws Exception { + invalidSelectionTest(); + } + + public void test013() throws Exception { + invalidSelectionTest(); + } + + public void test014() throws Exception { + invalidSelectionTest(); + } + + public void test015() throws Exception { + invalidSelectionTest(); + } +/*{ObjectTeams: becoming obsolete after https://bugs.eclipse.org/bugs/show_bug.cgi?id=245007 + public void test016() throws Exception { + invalidSelectionTest(); + } +//SH}*/ + //---- Switch / Case + + public void test020() throws Exception { + invalidSelectionTest(); + } + + public void test021() throws Exception { + invalidSelectionTest(); + } + + public void test022() throws Exception { + invalidSelectionTest(); + } + + //---- Block + + public void test030() throws Exception { + invalidSelectionTest(); + } + + public void test031() throws Exception { + invalidSelectionTest(); + } + + //---- For + + public void test040() throws Exception { + invalidSelectionTest(); + } + + public void test041() throws Exception { + invalidSelectionTest(); + } + + public void test042() throws Exception { + invalidSelectionTest(); + } + + public void test043() throws Exception { + invalidSelectionTest(); + } + + public void test044() throws Exception { + invalidSelectionTest(); + } + + public void test045() throws Exception { + invalidSelectionTest(); + } + + public void test046() throws Exception { + invalidSelectionTest(); + } + + public void test047() throws Exception { + invalidSelectionTest(); + } + + public void test048() throws Exception { + invalidSelectionTest(); + } + + //---- While + + public void test050() throws Exception { + invalidSelectionTest(); + } + + public void test051() throws Exception { + invalidSelectionTest(); + } + + public void test052() throws Exception { + invalidSelectionTest(); + } + + //---- do / While + + public void test060() throws Exception { + invalidSelectionTest(); + } + + public void test061() throws Exception { + invalidSelectionTest(); + } + + public void test062() throws Exception { + invalidSelectionTest(); + } + + public void test063() throws Exception { + invalidSelectionTest(); + } + + //---- switch + + public void test070() throws Exception { + invalidSelectionTest(); + } + + public void test071() throws Exception { + invalidSelectionTest(); + } + + public void test072() throws Exception { + invalidSelectionTest(); + } + + public void test073() throws Exception { + invalidSelectionTest(); + } + + //---- if then else + + public void test080() throws Exception { + invalidSelectionTest(); + } + + public void test081() throws Exception { + invalidSelectionTest(); + } + + public void test082() throws Exception { + invalidSelectionTest(); + } + + public void test083() throws Exception { + invalidSelectionTest(); + } + + public void test084() throws Exception { + invalidSelectionTest(); + } + + public void test085() throws Exception { + invalidSelectionTest(); + } + + //---- Break + + public void test090() throws Exception { + invalidSelectionTest(); + } + + public void test091() throws Exception { + invalidSelectionTest(); + } + + public void test092() throws Exception { + invalidSelectionTest(); + } + + public void test093() throws Exception { + invalidSelectionTest(); + } + + public void test094() throws Exception { + invalidSelectionTest(); + } + + public void test095() throws Exception { + invalidSelectionTest(); + } + + public void test096() throws Exception { + invalidSelectionTest(); + } + + //---- Try / catch / finally + + public void test100() throws Exception { + invalidSelectionTest(); + } + + public void test101() throws Exception { + invalidSelectionTest(); + } + + public void test102() throws Exception { + invalidSelectionTest(); + } + + public void test103() throws Exception { + invalidSelectionTest(); + } + + public void test104() throws Exception { + invalidSelectionTest(); + } + + public void test105() throws Exception { + invalidSelectionTest(); + } + + public void test106() throws Exception { + invalidSelectionTest(); + } + + public void test107() throws Exception { + invalidSelectionTest(); + } + + public void test108() throws Exception { + invalidSelectionTest(); + } + + public void test109() throws Exception { + invalidSelectionTest(); + } + + public void test110() throws Exception { + invalidSelectionTest(); + } + + public void test111() throws Exception { + invalidSelectionTest(); + } + + public void test112() throws Exception { + invalidSelectionTest(); + } + + public void test113() throws Exception { + invalidSelectionTest(); + } + + public void test114() throws Exception { + invalidSelectionTest(); + } + + public void test115() throws Exception { + invalidSelectionTest(); + } + + //---- invalid local var selection + + public void test120() throws Exception { + invalidSelectionTest(); + } + + public void test121() throws Exception { + invalidSelectionTest(); + } + + public void test122() throws Exception { + invalidSelectionTest(); + } + + public void test123() throws Exception { + invalidSelectionTest(); + } + + //---- invalid local type selection + + public void test130() throws Exception { + invalidSelectionTest(); + } + + public void test131() throws Exception { + invalidSelectionTest(); + } + + //---- invalid return statement selection + + public void test140() throws Exception { + invalidSelectionTest(); + } + + public void test141() throws Exception { + invalidSelectionTest(); + } + + public void test142() throws Exception { + invalidSelectionTest(); + } + + public void test143() throws Exception { + invalidSelectionTest(); + } + + public void test144() throws Exception { + invalidSelectionTest(); + } + + public void test145() throws Exception { + invalidSelectionTest(); + } + + public void test146() throws Exception { + invalidSelectionTest(); + } + + public void test147() throws Exception { + invalidSelectionTest(); + } + + public void test148() throws Exception { + invalidSelectionTest(); + } + + public void test149() throws Exception { + invalidSelectionTest(); + } + + //---- Synchronized statement + + public void test150() throws Exception { + invalidSelectionTest(); + } + + public void test151() throws Exception { + invalidSelectionTest(); + } + + public void test152() throws Exception { + invalidSelectionTest(); + } + + public void test153() throws Exception { + invalidSelectionTest(); + } + + public void test160() throws Exception { + invalidSelectionTest(); + } + + public void test161() throws Exception { + invalidSelectionTest(); + } + + //----- local declarations + + public void test170() throws Exception { + invalidSelectionTest(); + } + + public void test171() throws Exception { + invalidSelectionTest(); + } + + public void test172() throws Exception { + invalidSelectionTest(); + } + + public void test173() throws Exception { + invalidSelectionTest(); + } + + //---- Constructor + + public void test180() throws Exception { + // System.out.println(getClass().getName() + "::"+ getName() + " disabled - see bug 11853"); + invalidSelectionTest(); + } + + public void test181() throws Exception { + // System.out.println(getClass().getName() + "::"+ getName() + " disabled - see bug 11853"); + invalidSelectionTest(); + } + + //---- More return statement handling + + public void test190() throws Exception { + invalidSelectionTest(); + } + + public void test191() throws Exception { + invalidSelectionTest(); + } + + //---- Assignment + + public void test192() throws Exception { + invalidSelectionTest(); + } + + public void test193() throws Exception { + invalidSelectionTest(); + } + + //---- single names + + public void test194() throws Exception { + invalidSelectionTest(); + } + + //---- case expression + + public void test195() throws Exception { + invalidSelectionTest(); + } + + //---- more than one value to return + + public void test196() throws Exception { + invalidSelectionTest(); + } + + //---- continue not possible + + public void test197() throws Exception { + invalidSelectionTest(); + } + + + + //==================================================================================== + // Testing valid selections + //===================================================================================== + + //---- Misc + + public void test200() throws Exception { + validSelectionTest(); + } + + public void test201() throws Exception { + validSelectionTest(); + } + + public void test202() throws Exception { + validSelectionTest(); + } + + public void test203() throws Exception { + validSelectionTest(); + } + + //---- Block + + public void test230() throws Exception { + validSelectionTest(); + } + + public void test231() throws Exception { + validSelectionTest(); + } + + public void test232() throws Exception { + validSelectionTest(); + } + + public void test233() throws Exception { + validSelectionTest(); + } + + public void test234() throws Exception { + validSelectionTest(); + } + + public void test235() throws Exception { + validSelectionTest(); + } + + //---- For statement + + public void test240() throws Exception { + validSelectionTest(); + } + + public void test241() throws Exception { + validSelectionTest(); + } + + public void test244() throws Exception { + validSelectionTest(); + } + + public void test245() throws Exception { + validSelectionTest(); + } + + public void test246() throws Exception { + validSelectionTest(); + } + + public void test247() throws Exception { + validSelectionTest(); + } + + public void test248() throws Exception { + validSelectionTest(); + } + + public void test249() throws Exception { + validSelectionTest(); + } + + //---- While statement + + public void test250() throws Exception { + validSelectionTest(); + } + + public void test251() throws Exception { + validSelectionTest(); + } + + public void test252() throws Exception { + validSelectionTest(); + } + + public void test253() throws Exception { + validSelectionTest(); + } + + public void test254() throws Exception { + validSelectionTest(); + } + + public void test255() throws Exception { + validSelectionTest(); + } + + //---- do while statement + + public void test260() throws Exception { + validSelectionTest(); + } + + public void test261() throws Exception { + validSelectionTest(); + } + + public void test262() throws Exception { + validSelectionTest(); + } + + public void test263() throws Exception { + validSelectionTest(); + } + + //---- switch + + public void test270() throws Exception { + validSelectionTest(); + } + + public void test271() throws Exception { + validSelectionTest(); + } + + public void test272() throws Exception { + validSelectionTest(); + } + + public void test273() throws Exception { + validSelectionTest(); + } + + public void test274() throws Exception { + validSelectionTest(); + } + + public void test275() throws Exception { + validSelectionTest(); + } + + //---- if then else + + public void test280() throws Exception { + validSelectionTest(); + } + + public void test281() throws Exception { + validSelectionTest(); + } + + public void test282() throws Exception { + validSelectionTest(); + } + + public void test283() throws Exception { + validSelectionTest(); + } + + public void test284() throws Exception { + validSelectionTest(); + } + + public void test285() throws Exception { + validSelectionTest(); + } + + //---- try / catch / finally + + public void test300() throws Exception { + validSelectionTest(); + } + + public void test301() throws Exception { + validSelectionTest(); + } + + public void test302() throws Exception { + validSelectionTest(); + } + + public void test304() throws Exception { + validSelectionTest(); + } + + public void test305() throws Exception { + validSelectionTest(); + } + + public void test306() throws Exception { + validSelectionTest(); + } + + public void test307() throws Exception { + validSelectionTest(); + } + + public void test308() throws Exception { + validSelectionTest(); + } + + public void test309() throws Exception { + validSelectionTest(); + } + + public void test310() throws Exception { + validSelectionTest(); + } + + public void test311() throws Exception { + validSelectionTest(); + } + + //---- Synchronized statement + + public void test350() throws Exception { + validSelectionTest(); + } + + public void test351() throws Exception { + validSelectionTest(); + } + + public void test352() throws Exception { + validSelectionTest(); + } + + public void test353() throws Exception { + validSelectionTest(); + } + + public void test360() throws Exception { + validSelectionTestChecked(); + } + + public void test361() throws Exception { + validSelectionTestChecked(); + } + + public void test362() throws Exception { + validSelectionTestChecked(); + } + + public void test363() throws Exception { + validSelectionTestChecked(); + } + + public void test364() throws Exception { + validSelectionTestChecked(); + } + + public void test365() throws Exception { + validSelectionTestChecked(); + } + + public void test366() throws Exception { + validSelectionTestChecked(); + } + + public void test367() throws Exception { + validSelectionTestChecked(); + } + + public void test368() throws Exception { + validSelectionTestChecked(); + } + + public void test369() throws Exception { + validSelectionTestChecked(); + } + + public void test370() throws Exception { + validSelectionTestChecked(); + } + + public void test371() throws Exception { + validSelectionTestChecked(); + } + + public void test372() throws Exception { + validSelectionTestChecked(); + } + + public void test373() throws Exception { + validSelectionTestChecked(); + } + + //==================================================================================== + // Testing Extracted result + //==================================================================================== + + //---- Test semicolon + + public void test400() throws Exception { + semicolonTest(); + } + + public void test401() throws Exception { + semicolonTest(); + } + + public void test402() throws Exception { + semicolonTest(); + } + + public void test403() throws Exception { + semicolonTest(); + } + + public void test404() throws Exception { + semicolonTest(); + } + + public void test406() throws Exception { + semicolonTest(); + } + + public void test407() throws Exception { + semicolonTest(); + } + + public void test409() throws Exception { + semicolonTest(); + } + + //---- Test Try / catch block + + public void test450() throws Exception { + tryTest(); + } + + public void test451() throws Exception { + tryTest(); + } + + public void test452() throws Exception { + tryTest(); + } + + public void test453() throws Exception { + tryTest(); + } + + public void test454() throws Exception { + tryTest(); + } + + public void test455() throws Exception { + tryTest(); + } + + public void test456() throws Exception { + tryTest(); + } + + public void test457() throws Exception { + tryTest(); + } + + public void test458() throws Exception { + tryTest(); + } + + public void test459() throws Exception { + tryTest(); + } + + public void test460() throws Exception { + tryTest(); + } + + public void test461() throws Exception { + tryTest(); + } + + public void test462() throws Exception { + tryTest(); + } + + //---- Test local vars and types + + public void test500() throws Exception { + localsTest(); + } + + public void test501() throws Exception { + localsTest(); + } + + public void test502() throws Exception { + localsTest(); + } + + public void test503() throws Exception { + localsTest(); + } + + public void test504() throws Exception { + localsTest(); + } + + public void test505() throws Exception { + localsTest(); + } + + public void test506() throws Exception { + localsTest(); + } + + public void test507() throws Exception { + localsTest(); + } + + public void test508() throws Exception { + localsTest(); + } + + public void test509() throws Exception { + localsTest(); + } + + public void test510() throws Exception { + localsTest(); + } + + public void test511() throws Exception { + localsTest(); + } + + public void test512() throws Exception { + localsTest(); + } + + public void test513() throws Exception { + localsTest(); + } + + public void test514() throws Exception { + localsTest(); + } + + public void test515() throws Exception { + localsTest(); + } + + public void test516() throws Exception { + localsTest(); + } + + public void test517() throws Exception { + localsTest(); + } + + public void test518() throws Exception { + localsTest(); + } + + public void test519() throws Exception { + localsTest(); + } + + public void test520() throws Exception { + localsTest(); + } + + public void test521() throws Exception { + localsTest(); + } + + public void test522() throws Exception { + localsTest(); + } + + public void test523() throws Exception { + localsTest(); + } + + public void test524() throws Exception { + localsTest(); + } + + public void test525() throws Exception { + localsTest(); + } + + public void test526() throws Exception { + localsTest(); + } + + public void test527() throws Exception { + localsTest(); + } + + public void test528() throws Exception { + localsTest(); + } + + public void test530() throws Exception { + localsTest(); + } + + public void test531() throws Exception { + localsTest(); + } + + public void test532() throws Exception { + localsTest(); + } + + public void test533() throws Exception { + localsTest(); + } + + public void test534() throws Exception { + localsTest(); + } + + public void test535() throws Exception { + localsTest(); + } + + public void test536() throws Exception { + localsTest(); + } + + public void test537() throws Exception { + localsTest(); + } + + public void test538() throws Exception { + localsTest(); + } + + public void test539() throws Exception { + localsTest(); + } + + public void test540() throws Exception { + localsTest(); + } + + public void test541() throws Exception { + localsTest(); + } + + public void test542() throws Exception { + localsTest(); + } + + public void test543() throws Exception { + localsTest(); + } + + public void test550() throws Exception { + localsTest(); + } + + public void test551() throws Exception { + localsTest(); + } + + public void test552() throws Exception { + localsTest(); + } + + public void test553() throws Exception { + localsTest(); + } + + public void test554() throws Exception { + localsTest(); + } + + public void test555() throws Exception { + localsTest(); + } + + public void test556() throws Exception { + localsTest(); + } + + public void test557() throws Exception { + localsTest(); + } + + public void test558() throws Exception { + localsTest(); + } + + public void test559() throws Exception { + localsTest(); + } + + public void test560() throws Exception { + localsTest(); + } + + public void test561() throws Exception { + localsTest(); + } + + public void test562() throws Exception { + localsTest(); + } + + public void test563() throws Exception { + localsTest(); + } + + public void test564() throws Exception { + localsTest(); + } + + public void test565() throws Exception { + localsTest(); + } + + public void test566() throws Exception { + localsTest(); + } + + public void test567() throws Exception { + localsTest(); + } + + public void test568() throws Exception { + localsTest(); + } + + public void test569() throws Exception { + localsTest(); + } + + public void test570() throws Exception { + localsTest(); + } + + public void test571() throws Exception { + localsTest(); + } + + public void test572() throws Exception { + localsTest(); + } + + public void test575() throws Exception { + localsTest(); + } + + public void test576() throws Exception { + localsTest(); + } + + public void test577() throws Exception { + localsTest(); + } + + public void test578() throws Exception { + localsTest(); + } + + //---- Test expressions + + public void test600() throws Exception { + expressionTest(); + } + + public void test601() throws Exception { + expressionTest(); + } + + public void test602() throws Exception { + expressionTest(); + } + + public void test603() throws Exception { + expressionTest(); + } + + public void test604() throws Exception { + expressionTest(); + } + + public void test605() throws Exception { + expressionTest(); + } + + public void test606() throws Exception { + expressionTest(); + } + + public void test607() throws Exception { + expressionTest(); + } + + public void test608() throws Exception { + expressionTest(); + } + + public void test609() throws Exception { + expressionTest(); + } + + public void test610() throws Exception { + expressionTest(); + } + + public void test611() throws Exception { + expressionTest(); + } + + public void test612() throws Exception { + expressionTest(); + } + + public void test613() throws Exception { + expressionTest(); + } + + public void test614() throws Exception { + expressionTest(); + } + + public void test615() throws Exception { + expressionTest(); + } + + public void test616() throws Exception { + expressionTest(); + } + + public void test617() throws Exception { + expressionTest(); + } + + public void test618() throws Exception { + expressionTest(); + } + + public void test619() throws Exception { + expressionTest(); + } + + public void test620() throws Exception { + expressionTest(); + } + + public void test621() throws Exception { + expressionTest(); + } + + public void test622() throws Exception { + expressionTest(); + } + + //---- Test nested methods and constructor + + public void test650() throws Exception { + nestedTest(); + } + + public void test651() throws Exception { + nestedTest(); + } + + public void test652() throws Exception { + nestedTest(); + } + + public void test653() throws Exception { + nestedTest(); + } + + public void test654() throws Exception { + nestedTest(); + } + + //---- Extracting method containing a return statement. + + public void test700() throws Exception { + returnTest(); + } + + public void test701() throws Exception { + returnTest(); + } + + public void test702() throws Exception { + returnTest(); + } + + public void test703() throws Exception { + returnTest(); + } + + public void test704() throws Exception { + returnTest(); + } + + public void test705() throws Exception { + returnTest(); + } + + public void test706() throws Exception { + returnTest(); + } + + public void test707() throws Exception { + returnTest(); + } + + public void test708() throws Exception { + returnTest(); + } + + public void test709() throws Exception { + returnTest(); + } + + public void test710() throws Exception { + returnTest(); + } + + public void test711() throws Exception { + returnTest(); + } + + public void test712() throws Exception { + returnTest(); + } + + public void test713() throws Exception { + returnTest(); + } + + public void test714() throws Exception { + returnTest(); + } + + public void test715() throws Exception { + returnTest(); + } + + public void test716() throws Exception { + returnTest(); + } + + public void test717() throws Exception { + returnTest(); + } + + public void test718() throws Exception { + returnTest(); + } + + public void test719() throws Exception { + returnTest(); + } + + public void test720() throws Exception { + returnTest(); + } + + public void test721() throws Exception { + returnTest(); + } + + public void test722() throws Exception { + returnTest(); + } + + public void test723() throws Exception { + returnTest(); + } + + public void test724() throws Exception { + returnTest(); + } + + public void test725() throws Exception { + returnTest(); + } + + public void test726() throws Exception { + returnTest(); + } + + public void test727() throws Exception { + returnTest(); + } + + public void test728() throws Exception { + returnTest(); + } + + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=213519 + public void test729() throws Exception { + returnTest(); + } + + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=213519 + public void test730() throws Exception { + returnTest(); + } + + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=213519 + public void test731() throws Exception { + returnTest(); + } + + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=213519 + public void test732() throws Exception { + returnTest(); + } + + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=97413 + public void test733() throws Exception { + returnTest(); + } + + // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=97413 + public void test734() throws Exception { + returnTest(); + } + + //---- Branch statements + + public void test750() throws Exception { + branchTest(); + } + + public void test751() throws Exception { + branchTest(); + } + + public void test752() throws Exception { + branchTest(); + } + + public void test753() throws Exception { + branchTest(); + } + + public void test754() throws Exception { + branchTest(); + } + + public void test755() throws Exception { + branchTest(); + } + + public void test756() throws Exception { + branchTest(); + } + + public void test757() throws Exception { + branchTest(); + } + + public void test758() throws Exception { + branchTest(); + } + + public void test759() throws Exception { + branchTest(); + } + + public void test760() throws Exception { + branchTest(); + } + + public void test761() throws Exception { + branchTest(); + } + + public void test762() throws Exception { + branchTest(); + } + + public void test763() throws Exception { + branchTest(); + } + + public void test764() throws Exception { + branchTest(); + } + + public void test765() throws Exception { + branchTest(); + } + + public void test766() throws Exception { + branchTest(); + } + + public void test767() throws Exception { + branchTest(); + } + + public void test768() throws Exception { + branchTest(); + } + + public void test769() throws Exception { + branchTest(); + } + + //---- Test for CUs with compiler errors + + public void test800() throws Exception { + errorTest(); + } + + public void test801() throws Exception { + errorTest(); + } + + public void test802() throws Exception { + errorTest(); + } + + public void test803() throws Exception { + errorTest(); + } + + //---- Test parameter name changes + + private void invalidParameterNameTest(String[] newNames) throws Exception { + performTest(fgTestSetup.getParameterNamePackage(), "A", INVALID_SELECTION, null, newNames, null, 0); + } + + private void parameterNameTest(String[] newNames, int[] newOrder) throws Exception { + performTest(fgTestSetup.getParameterNamePackage(), "A", COMPARE_WITH_OUTPUT, "parameterName_out", newNames, newOrder, 0); + } + + public void test900() throws Exception { + invalidParameterNameTest(new String[] {"y"}); + } + + public void test901() throws Exception { + invalidParameterNameTest(new String[] {null, "i"}); + } + + public void test902() throws Exception { + invalidParameterNameTest(new String[] {"System"}); + } + + public void test903() throws Exception { + parameterNameTest(new String[] {"xxx", "yyyy"}, null); + } + + public void test904() throws Exception { + parameterNameTest(new String[] {"xx", "zz"}, new int[] {1, 0}); + } + + public void test905() throws Exception { + parameterNameTest(new String[] {"message"}, null); + } + + public void test906() throws Exception { + parameterNameTest(new String[] {"xxx"}, null); + } + + //---- Test duplicate code snippets ---------------------------------------- + + public void test950() throws Exception { + duplicatesTest(); + } + + public void test951() throws Exception { + duplicatesTest(); + } + + public void test952() throws Exception { + duplicatesTest(); + } + + public void test953() throws Exception { + duplicatesTest(); + } + + public void test954() throws Exception { + duplicatesTest(); + } + + public void test955() throws Exception { + duplicatesTest(); + } + + public void test956() throws Exception { + duplicatesTest(); + } + + public void test957() throws Exception { + duplicatesTest(); + } + + public void test958() throws Exception { + duplicatesTest(); + } + + public void test959() throws Exception { + duplicatesTest(); + } + + public void test960() throws Exception { + duplicatesTest(); + } + + public void test961() throws Exception { + duplicatesTest(); + } + + public void test962() throws Exception { + duplicatesTest(); + } + + public void test963() throws Exception { + duplicatesTest(); + } + + public void test964() throws Exception { + duplicatesTest(); + } + + public void test965() throws Exception { + duplicatesTest(); + } + + public void test966() throws Exception { + duplicatesTest(); + } + + public void test967() throws Exception { + duplicatesTest(); + } + + public void test968() throws Exception { + duplicatesTest(); + } + + public void test969() throws Exception { + duplicatesTest(); + } + + public void test970() throws Exception { + duplicatesTest(); // for https://bugs.eclipse.org/bugs/show_bug.cgi?id=186061 + } + + public void test971() throws Exception { + performTest(fgTestSetup.getDuplicatesPackage(), "A", COMPARE_WITH_OUTPUT, "duplicates_out", null, null, 1); // for https://bugs.eclipse.org/bugs/show_bug.cgi?id=160853 + } + + public void test972() throws Exception { + duplicatesTest(); // for https://bugs.eclipse.org/bugs/show_bug.cgi?id=160853 + } + + public void test980() throws Exception { + duplicatesTest(); // for https://bugs.eclipse.org/bugs/show_bug.cgi?id=264606 + } + + public void test981() throws Exception { + duplicatesTest(); // for https://bugs.eclipse.org/bugs/show_bug.cgi?id=264606 + } + + public void test982() throws Exception { + duplicatesTest(); // for https://bugs.eclipse.org/bugs/show_bug.cgi?id=264606 + } + + public void test983() throws Exception { + duplicatesTest(); // for https://bugs.eclipse.org/bugs/show_bug.cgi?id=264606 + } + + public void test984() throws Exception { + duplicatesTest(); // for https://bugs.eclipse.org/bugs/show_bug.cgi?id=264606 + } + + public void test985() throws Exception { + duplicatesTest(); // for https://bugs.eclipse.org/bugs/show_bug.cgi?id=264606 + } + + public void test986() throws Exception { + duplicatesTest(); // for https://bugs.eclipse.org/bugs/show_bug.cgi?id=264606 + } + + public void test987() throws Exception { + duplicatesTest(); // for https://bugs.eclipse.org/bugs/show_bug.cgi?id=264606 + } + + //---- Test code in initializers ----------------------------------------------- + + public void test1000() throws Exception { + initializerTest(); + } + + public void test1001() throws Exception { + initializerTest(); + } + + public void test1002() throws Exception { + initializerTest(); + } + + public void test1003() throws Exception { + initializerTest(); + } + + //---- Test destination ----------------------------------------------- + + public void test1050() throws Exception { + destinationTest(1); + } + + public void test1051() throws Exception { + destinationTest(1); + } + + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=152004 + public void test1052() throws Exception { + destinationTest(1); + } + + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=152004 + public void test1053() throws Exception { + destinationTest(1); + } + + //---- Test Generics -------------------------------------------------- + + public void test1100() throws Exception { + genericTest(); + } + + public void test1101() throws Exception { + genericTest(); + } + + public void test1102() throws Exception { + genericTest(); + } + + public void test1103() throws Exception { + genericTest(); + } + + public void test1104() throws Exception { + genericTest(); + } + + public void test1105() throws Exception { + genericTest(); + } + + public void test1106() throws Exception { + genericTest(); + } + + public void test1107() throws Exception { + genericTest(); + } + + public void test1108() throws Exception { + genericTest(); + } + + public void test1109() throws Exception { + genericTest(); + } + + public void test1110() throws Exception { + genericTest(); + } + + public void test1111() throws Exception { + genericTest(); + } + + public void test1112() throws Exception { + genericTest(); + } + + public void test1113() throws Exception { + genericTest(); + } + + public void test1114() throws Exception { + genericTest(); + } + + public void test1115() throws Exception { + genericTest(); + } + + public void test1116() throws Exception { + genericTest(); + } + + public void test1117() throws Exception { + genericTest(); + } + + public void test1118() throws Exception { + genericTest(); + } + + public void test1119() throws Exception { + genericTest(); + } + + //---- Test enums --------------------------------- + + public void test1150() throws Exception { + enumTest(); + } + + public void test1151() throws Exception { + enumTest(); + } + + public void test1152() throws Exception { + enumTest(); + } + + //---- Test varargs --------------------------------- + + protected void varargsTest() throws Exception { + performTest(fgTestSetup.getVarargsPackage(), "A", COMPARE_WITH_OUTPUT, "varargs_out"); + } + + public void test1200() throws Exception { + varargsTest(); + } + + public void test1201() throws Exception { + varargsTest(); + } + + public void test1202() throws Exception { + varargsTest(); + } + + //---- Test field initializer --------------------------------- + + protected void fieldInitializerTest() throws Exception { + performTest(fgTestSetup.getFieldInitializerPackage(), "A", COMPARE_WITH_OUTPUT, "fieldInitializer_out"); + } + + public void test1250() throws Exception { + fieldInitializerTest(); + } + + public void test1251() throws Exception { + fieldInitializerTest(); + } + + public void test1252() throws Exception { + fieldInitializerTest(); + } + + //---- Test copied from http://c2.com/cgi/wiki?RefactoringBenchmarksForExtractMethod + + public void test2001() throws Exception { + wikiTest(); + } + + public void test2002() throws Exception { + wikiTest(); + } + + public void test2003() throws Exception { + wikiTest(); + } + + public void test2004() throws Exception { + wikiTest(); + } + + public void test2005() throws Exception { + wikiTest(); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractSupertypeTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractSupertypeTests.java new file mode 100644 index 000000000..9cdbdcd04 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractSupertypeTests.java @@ -0,0 +1,152 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.Arrays; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; +import org.eclipse.jdt.internal.corext.refactoring.structure.ExtractSupertypeProcessor; +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; + +import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; + +/** + * Test suite for the extract supertype tests. + * + * Note: Extract Supertype heavily relies on PullUpRefactoring and its tests + */ +public final class ExtractSupertypeTests extends RefactoringTest { + + private static final Class clazz= ExtractSupertypeTests.class; + + private static final String REFACTORING_PATH= "ExtractSupertype/"; + + private static ExtractSupertypeProcessor createRefactoringProcessor(IMember[] members) throws JavaModelException { + IJavaProject project= null; + if (members != null && members.length > 0) + project= members[0].getJavaProject(); + if (RefactoringAvailabilityTester.isExtractSupertypeAvailable(members)) { + final CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(project); + settings.createComments= false; + ExtractSupertypeProcessor processor= new ExtractSupertypeProcessor(members, settings); + new ProcessorBasedRefactoring(processor); + return processor; + } + return null; + } + + private static IMethod[] getMethods(IMember[] members) { + List l= Arrays.asList(JavaElementUtil.getElementsOfType(members, IJavaElement.METHOD)); + return (IMethod[]) l.toArray(new IMethod[l.size()]); + } + + public static Test setUpTest(Test someTest) { + return new Java15Setup(someTest); + } + + public static Test suite() { + return new Java15Setup(new TestSuite(clazz)); + } + + public ExtractSupertypeTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + private void helper1(String[] methodNames, String[][] signatures, boolean deleteAllInSourceType, boolean deleteAllMatchingMethods, boolean replaceOccurences) throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + try { + IType type= getType(cu, "B"); + IMethod[] methods= getMethods(type, methodNames, signatures); + + ExtractSupertypeProcessor processor= createRefactoringProcessor(methods); + Refactoring refactoring= processor.getRefactoring(); + processor.setMembersToMove(methods); + + assertTrue("activation", refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()); + + processor.setTypesToExtract(new IType[] { type}); + processor.setTypeName("Z"); + processor.setCreateMethodStubs(true); + processor.setInstanceOf(false); + processor.setReplace(replaceOccurences); + if (deleteAllInSourceType) + processor.setDeletedMethods(methods); + if (deleteAllMatchingMethods) + processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); + + RefactoringStatus status= refactoring.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to pass", !status.hasError()); + performChange(refactoring, false); + + String expected= getFileContents(getOutputTestFileName("A")); + String actual= cu.getSource(); + assertEqualLines(expected, actual); + + expected= getFileContents(getOutputTestFileName("Z")); + ICompilationUnit unit= getPackageP().getCompilationUnit("Z.java"); + if (!unit.exists()) + assertTrue("extracted compilation unit does not exist", false); + actual= unit.getBuffer().getContents(); + assertEqualLines(expected, actual); + + } finally { + performDummySearch(); + cu.delete(false, null); + } + } + + public void test0() throws Exception { + helper1(new String[] { "m"}, new String[][] { new String[0]}, true, false, true); + } + + public void test1() throws Exception { + helper1(new String[] { "m"}, new String[][] { new String[0]}, true, false, true); + } + + public void test2() throws Exception { + helper1(new String[] { "m", "n"}, new String[][] { new String[0], new String[0]}, true, false, true); + } + + public void test3() throws Exception { + helper1(new String[] { "m", "n"}, new String[][] { new String[0], new String[0]}, true, false, true); + } + + public void test4() throws Exception { + helper1(new String[] { "m"}, new String[][] { new String[0]}, true, false, true); + } + + public void testBug151683() throws Exception { + helper1(new String[] { "m"}, new String[][] { new String[0]}, true, false, false); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractTempTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractTempTests.java new file mode 100644 index 000000000..a994a7f51 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractTempTests.java @@ -0,0 +1,844 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.Hashtable; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring; + +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +public class ExtractTempTests extends RefactoringTest { + + private static final Class clazz= ExtractTempTests.class; + private static final String REFACTORING_PATH= "ExtractTemp/"; + + private static final boolean BUG_82166_ImportRewrite_context= true; + private static final boolean BUG_161617_ASTRewrite_space= true; + + private Object fCompactPref; + + public ExtractTempTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + private String getSimpleTestFileName(boolean canExtract, boolean input){ + String fileName = "A_" + getName(); + if (canExtract) + fileName += input ? "_in": "_out"; + return fileName + ".java"; + } + + private String getTestFileName(boolean canExtract, boolean input){ + String fileName= TEST_PATH_PREFIX + getRefactoringPath(); + fileName += canExtract ? "canExtract/": "cannotExtract/"; + return fileName + getSimpleTestFileName(canExtract, input); + } + + private ICompilationUnit createCUfromTestFile(IPackageFragment pack, boolean canExtract, boolean input) throws Exception { + return createCU(pack, getSimpleTestFileName(canExtract, input), getFileContents(getTestFileName(canExtract, input))); + } + + protected void setUp() throws Exception { + super.setUp(); + Hashtable options= JavaCore.getOptions(); + + String setting= DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR; + fCompactPref= options.get(setting); + options.put(setting, DefaultCodeFormatterConstants.TRUE); + JavaCore.setOptions(options); + } + + protected void tearDown() throws Exception { + super.tearDown(); + Hashtable options= JavaCore.getOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR, fCompactPref); + JavaCore.setOptions(options); + } + + private void helper1(int startLine, int startColumn, int endLine, int endColumn, boolean replaceAll, boolean makeFinal, String tempName, String guessedTempName) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ExtractTempRefactoring ref= new ExtractTempRefactoring(cu, selection.getOffset(), selection.getLength()); + + RefactoringStatus activationResult= ref.checkInitialConditions(new NullProgressMonitor()); + assertTrue("activation was supposed to be successful", activationResult.isOK()); + + ref.setReplaceAllOccurrences(replaceAll); + ref.setDeclareFinal(makeFinal); + ref.setTempName(tempName); + + assertEquals("temp name incorrectly guessed", guessedTempName, ref.guessTempName()); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to pass but was " + checkInputResult.toString(), checkInputResult.isOK()); + + performChange(ref, false); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + assertEqualLines(getFileContents(getTestFileName(true, false)), newcu.getSource()); + } + + private void warningHelper1(int startLine, int startColumn, int endLine, int endColumn, boolean replaceAll, boolean makeFinal, String tempName, String guessedTempName, int expectedStatus) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ExtractTempRefactoring ref= new ExtractTempRefactoring(cu, selection.getOffset(), selection.getLength()); + + RefactoringStatus activationResult= ref.checkInitialConditions(new NullProgressMonitor()); + assertTrue("activation was supposed to be successful", activationResult.isOK()); + + ref.setReplaceAllOccurrences(replaceAll); + ref.setDeclareFinal(makeFinal); + ref.setTempName(tempName); + + assertEquals("temp name incorrectly guessed", guessedTempName, ref.guessTempName()); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertEquals("status", expectedStatus, checkInputResult.getSeverity()); + + performChange(ref, false); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + assertEqualLines(getFileContents(getTestFileName(true, false)), newcu.getSource()); + } + + private void failHelper1(int startLine, int startColumn, int endLine, int endColumn, boolean replaceAll, boolean makeFinal, String tempName, int expectedStatus) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), false, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ExtractTempRefactoring ref= new ExtractTempRefactoring(cu, selection.getOffset(), selection.getLength()); + ref.setReplaceAllOccurrences(replaceAll); + ref.setDeclareFinal(makeFinal); + ref.setTempName(tempName); + RefactoringStatus result= performRefactoring(ref); + assertNotNull("precondition was supposed to fail", result); + assertEquals("status", expectedStatus, result.getSeverity()); + } + + //--- TESTS + + public void test0() throws Exception{ + helper1(4, 16, 4, 17, false, false, "temp", "j"); + } + + public void test1() throws Exception{ + helper1(4, 16, 4, 17, true, false, "temp", "j"); + } + + public void test2() throws Exception{ + helper1(4, 16, 4, 17, true, true, "temp", "j"); + } + + public void test3() throws Exception{ + helper1(4, 16, 4, 17, false, true, "temp", "j"); + } + + public void test4() throws Exception{ + helper1(4, 16, 4, 21, false, false, "temp", "j"); + } + + public void test5() throws Exception{ + helper1(4, 16, 4, 21, true, false, "temp", "j"); + } + + public void test6() throws Exception{ + helper1(4, 16, 4, 21, true, true, "temp", "j"); + } + + public void test7() throws Exception{ + helper1(4, 16, 4, 21, false, true, "temp", "j"); + } + + public void test8() throws Exception{ + helper1(5, 20, 5, 25, true, false, "temp", "j"); + } + + public void test9() throws Exception{ + helper1(5, 20, 5, 25, false, false, "temp", "j"); + } + + public void test10() throws Exception{ + helper1(5, 20, 5, 25, true, false, "temp", "i"); + } + + public void test11() throws Exception{ + helper1(5, 20, 5, 25, true, false, "temp", "i"); + } + + public void test12() throws Exception{ + helper1(5, 17, 5, 22, true, false, "temp", "i"); + } + + public void test13() throws Exception{ + helper1(7, 16, 7, 42, true, false, "temp", "iterator"); + } + + public void test14() throws Exception{ + helper1(6, 15, 6, 20, false, false, "temp", "y2"); + } + + public void test15() throws Exception{ + helper1(7, 23, 7, 28, false, false, "temp", "y2"); + } + + public void test16() throws Exception{ + helper1(7, 23, 7, 28, false, false, "temp", "y2"); + } + + public void test17() throws Exception{ + helper1(5, 20, 5, 25, true, false, "temp", "j"); + } + + public void test18() throws Exception{ + helper1(6, 20, 6, 25, true, false, "temp", "i"); + } + + public void test19() throws Exception{ + helper1(5, 20, 5, 23, true, false, "temp", "f"); + } + +//cannot do it - see testFail16 +// public void test20() throws Exception{ +// printTestDisabledMessage("regression test for bug#11474"); +// helper1(5, 9, 5, 12, false, false, "temp", "temp"); +// } + + public void test21() throws Exception{ + helper1(5, 16, 5, 17, false, false, "temp", "f2"); + } + +//cannot do it - see testFail17 +// public void test22() throws Exception{ +// printTestDisabledMessage("regression test for bug#11474"); +// helper1(6, 13, 6, 16, false, false, "temp", "temp"); +// } + + public void test23() throws Exception{ + helper1(7, 17, 7, 20, false, false, "temp", "b"); + } + +// public void test24() throws Exception{ +//test disabled - trainling semicolons are disallowed now +// //regression test for bug#8116 +// helper1(4, 16, 4, 18, false, false, "temp", "temp"); +// } + + public void test25() throws Exception{ +// printTestDisabledMessage("regression test for bug#8895"); + helper1(4, 17, 4, 22, true, false, "temp", "i"); + } + + public void test26() throws Exception{ +// printTestDisabledMessage("regression test for 9905"); + helper1(5, 19, 5, 23, true, false, "temp", "i"); + } + + public void test27() throws Exception{ +// printTestDisabledMessage("regression test for 8123"); + helper1(4, 15, 4, 19, true, false, "temp", "j"); + } + + public void test28() throws Exception{ +// printTestDisabledMessage("regression test for 11026"); + helper1(4, 16, 4, 31, true, false, "temp", "b"); + } + + public void test29() throws Exception{ + helper1(4, 19, 4, 22, true, false, "temp", "string"); + } + + public void test30() throws Exception{ + helper1(5, 16, 5, 20, true, false, "temp", "ff2"); + } + + public void test31() throws Exception{ + helper1(5, 16, 5, 20, true, false, "temp", "j"); + } + + public void test32() throws Exception{ + helper1(4, 16, 4, 22, true, false, "temp", "j"); + } + + public void test33() throws Exception{ +// printTestDisabledMessage("regression test for bug#11449"); + helper1(4, 19, 4, 33, true, false, "temp", "object"); + } + + public void test34() throws Exception{ +// printTestDisabledMessage("another regression test for bug#11449"); + helper1(4, 19, 4, 46, true, false, "temp", "arrayList"); + } + + public void test35() throws Exception{ +// printTestDisabledMessage("another regression test for bug#11622"); + helper1(8, 19, 8, 28, true, false, "temp", "lists"); + } + + public void test36() throws Exception{ +// printTestDisabledMessage("another regression test for bug#12205"); + helper1(11, 15, 11, 25, true, false, "temp", "foo"); + } + + public void test37() throws Exception{ +// printTestDisabledMessage("another regression test for bug#15196"); + helper1(8, 20, 8, 25, true, false, "temp", "j"); + } + + public void test38() throws Exception{ +// printTestDisabledMessage("regression test for bug#17473"); + helper1(5, 28, 5, 32, true, false, "temp1", "temp2"); + } + + public void test39() throws Exception{ +// printTestDisabledMessage("regression test for bug#20520 "); + helper1(4, 14, 4, 26, true, false, "temp", "object"); + } + + public void test40() throws Exception{ +// printTestDisabledMessage("test for bug 21815"); + helper1(4, 9, 4, 16, true, false, "temp", "a"); + } + + public void test41() throws Exception{ +// printTestDisabledMessage("test for bug 21815"); + helper1(4, 9, 4, 36, true, false, "temp", "length"); + } + + public void test42() throws Exception{ +// printTestDisabledMessage("test for bug 19930"); + helper1(5, 16, 5, 35, true, false, "temp", "length"); + } + + public void test43() throws Exception{ +// printTestDisabledMessage("test for bug 19930"); + helper1(5, 20, 5, 36, true, false, "temp", "fred"); + } + + public void test44() throws Exception{ + //21939 + helper1(5, 20, 5, 28, true, false, "temp", "fred"); + } + + public void test45() throws Exception{ + //21939 + helper1(4, 16, 4, 19, true, false, "temp", "f"); + } + + public void test46() throws Exception{ +// printTestDisabledMessage("test for bug 21815"); + helper1(4, 9, 4, 12, true, false, "temp", "f"); + } + + public void test47() throws Exception{ + helper1(5, 9, 5, 12, true, false, "temp", "r"); + } + + public void test48() throws Exception{ +// printTestDisabledMessage("test for bug#22054"); + helper1(4, 16, 4, 32, true, false, "temp", "string"); + } + + public void test49() throws Exception{ +// printTestDisabledMessage("test for bug#23282 "); + helper1(5, 15, 5, 19, true, false, "temp", "flag2"); + } + + public void test50() throws Exception{ +// printTestDisabledMessage("test for bug#23283 "); + helper1(5, 15, 5, 19, true, false, "temp", "flag2"); + } + + public void test51() throws Exception{ +// printTestDisabledMessage("test for bug#23281"); + helper1(5, 15, 5, 18, true, false, "temp", "i"); + } + + public void test52() throws Exception{ +// printTestDisabledMessage("test for bug#26036"); + helper1(15, 47, 15, 60, true, false, "valueOnIndexI", "object"); + } + + public void test53() throws Exception{ + helper1(6, 17, 6, 22, true, false, "temp", "i"); + } + + public void test54() throws Exception{ + helper1(6, 37, 6, 43, true, false, "temp", "i"); + } + + public void test55() throws Exception{ + helper1(6, 19, 6, 24, true, false, "temp", "i"); + } + + public void test56() throws Exception{ + helper1(6, 24, 6, 29, true, false, "temp", "i"); + } + + public void test57() throws Exception{ +// printTestDisabledMessage("test for bug 24808"); + helper1(8, 30, 8, 54, true, false, "newVariable", "string"); + } + + public void test58() throws Exception{ +// printTestDisabledMessage("test for bug 30304"); + helper1(7, 14, 7, 30, true, false, "temp", "equals"); + } + + public void test59() throws Exception{ +// printTestDisabledMessage("test for bug 30304"); + helper1(7, 17, 7, 18, true, false, "temp", "s2"); + } + + public void test60() throws Exception{ +// printTestDisabledMessage("test for bug 30304"); + helper1(7, 17, 7, 18, true, false, "temp", "s2"); + } + + public void test61() throws Exception{ +// printTestDisabledMessage("test for bug 30304"); + helper1(7, 17, 7, 18, true, false, "temp", "s2"); + } + + public void test62() throws Exception{ +// printTestDisabledMessage("test for bug 33405 Refactoring extract local variable fails in nested if statements"); + helper1(10, 17, 10, 28, true, false, "temp", "string"); + } + + public void test63() throws Exception{ +// printTestDisabledMessage("test for bug 33405 Refactoring extract local variable fails in nested if statements"); + helper1(9, 20, 9, 23, true, false, "temp", "string"); + } + + public void test64() throws Exception{ +// printTestDisabledMessage("test for bug 33405 Refactoring extract local variable fails in nested if statements"); + helper1(10, 17, 10, 28, true, false, "temp", "string"); + } + + public void test65() throws Exception{ +// printTestDisabledMessage("test for bug 35981 extract local variable causing exception [refactoring] "); + helper1(6, 19, 6, 22, true, false, "temp", "bar2"); + } + + public void test66() throws Exception{ + helper1(7, 32, 7, 33, true, false, "temp", "e2"); + } + + public void test67() throws Exception{ +// printTestDisabledMessage("test for bug 37834"); + helper1(6, 16, 6, 21, true, false, "temp", "integer"); + } + + public void test68() throws Exception{ +// printTestDisabledMessage("test for bug 37834"); + helper1(6, 14, 6, 21, true, false, "temp", "d2"); + } + + public void test69() throws Exception{ + helper1(5, 24, 5, 26, true, false, "temp", "string2"); + } + + public void test70() throws Exception{ +// printTestDisabledMessage("test for bug 40353"); + helper1(7, 28, 7, 42, true, true, "temp", "length"); + } + + public void test71() throws Exception{ +// printTestDisabledMessage("test for bug 40353"); + helper1(8, 24, 8, 34, true, false, "temp", "string"); + } + + public void test72() throws Exception{ +// printTestDisabledMessage("test for bug 40353"); + helper1(8, 32, 8, 33, true, false, "temp", "i2"); + } + + public void test73() throws Exception{ +// printTestDisabledMessage("test for bug 40353"); + warningHelper1(6, 39, 6, 40, true, false, "temp", "i2", RefactoringStatus.WARNING); + // (warning is superfluous, but detection would need flow analysis) + } + + public void test74() throws Exception{ +// printTestDisabledMessage("test for bug 40353"); + helper1(7, 36, 7, 49, true, false, "temp", "string"); + } + + public void test75() throws Exception{ +// printTestDisabledMessage("test for bug 40353"); + helper1(7, 36, 7, 39, true, false, "temp", "j"); + } + + public void test76() throws Exception{ +// printTestDisabledMessage("test for bug 40353"); + helper1(7, 48, 7, 49, true, false, "temp", "k2"); + } + + public void test77() throws Exception { +// printTestDisabledMessage("test for bug 40353: extracting fragment which matches for_initializer"); + helper1(10, 13, 10, 17, true, false, "temp", "f"); + } + + public void test78() throws Exception { +// printTestDisabledMessage("test for bug 50971: Extract temp: index out of bounds error [refactoring]"); + helper1(5, 21, 5, 27, true, false, "o2", "o"); + } + + public void test79() throws Exception { + helper1(10, 40, 10, 60, true, false, "strong", "string"); + } + + public void test80() throws Exception { + helper1(5, 37, 5, 45, true, false, "name", "string"); + } + + public void test81() throws Exception { + helper1(7, 18, 7, 23, true, false, "k", "const2"); + } + + public void test82() throws Exception { + helper1(5, 1, 6, 1, true, false, "one", "integer"); + } + + public void test83() throws Exception{ + if (BUG_82166_ImportRewrite_context) { + printTestDisabledMessage("BUG_82166_ImportRewrite_context"); + return; + } + helper1(7, 17, 7, 27, false, false, "temp", "test"); + } + + public void test84() throws Exception{ + helper1(5, 16, 5, 17, false, false, "temp", "j"); + } + + public void test85() throws Exception{ + if (BUG_82166_ImportRewrite_context) { + printTestDisabledMessage("BUG_82166_ImportRewrite_context"); + return; + } + helper1(10, 22, 10, 32, true, true, "temp", "test2"); + } + + public void test86() throws Exception{ +// printTestDisabledMessage("test for parameterized class instance creation"); + helper1(14, 22, 14, 37, true, true, "name", "a"); + } + + public void test87() throws Exception{ +// printTestDisabledMessage("test for parameterized class instance creation"); + helper1(15, 17, 15, 27, true, true, "a2", "a2"); + } + + public void test88() throws Exception{ + helper1(14, 14, 14, 19, true, false, "foo", "foo"); + } + + public void test89() throws Exception{ + IPackageFragment a= getRoot().createPackageFragment("a", true, null); + ICompilationUnit aA= a.createCompilationUnit("A.java", "package a; public class A {}", true, null); + aA.save(null, true); + + IPackageFragment b= getRoot().createPackageFragment("b", true, null); + ICompilationUnit bA= b.createCompilationUnit("A.java", "package b; public class A {}", true, null); + bA.save(null, true); + + helper1(15, 7, 15, 15, true, false, "foo", "method"); + } + + public void test90() throws Exception { + helper1(8, 19, 8, 28, true, false, "temp", "number"); + } + + public void test91() throws Exception { + helper1(8, 19, 8, 28, true, false, "temp", "integer"); + } + + public void test92() throws Exception { //bug 104293 + helper1(9, 32, 9, 44, true, false, "asList", "asList"); + } + + public void test93() throws Exception { // syntax error + helper1(6, 28, 6, 34, true, false, "bla", "string"); + } + + public void test94() throws Exception { + //test for bug 19851, syntax error + helper1(6, 9, 6, 24, false, false, "temp", "string"); + } + + public void test95() throws Exception { + //test for bug 131556 + helper1(5, 23, 5, 33, true, false, "temp", "b"); + } + + public void test96() throws Exception { + //test for bug 71762 + helper1(6, 32, 6, 37, true, false, "isquared", "j"); + } + + public void test97() throws Exception { + //test for bug 48231 + helper1(10, 32, 10, 47, true, false, "temp", "nextElement"); + } + + public void test98() throws Exception { + //test for bug 132931 + helper1(8, 32, 8, 44, true, true, "temp", "string"); + } + + public void test99() throws Exception { + //test for bug 99963 + helper1(7, 32, 7, 36, true, false, "temp", "a"); + } + + public void test100() throws Exception { + //test for bug 161617 + if (BUG_161617_ASTRewrite_space) { + printTestDisabledMessage("BUG_161617_ASTRewrite_space"); + return; + } + helper1(5, 28, 5, 40, true, false, "temp", "object"); + } + + public void test101() throws Exception { + helper1(9, 13, 9, 25, true, false, "temp", "object"); + } + + public void test102() throws Exception { + helper1(9, 24, 9, 29, true, false, "temp", "j"); + } + + public void test103() throws Exception { + //test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=243101 + helper1(7, 21, 7, 33, true, false, "temp", "valueOf"); + } + + + public void testZeroLengthSelection0() throws Exception { +// printTestDisabledMessage("test for bug 30146"); + helper1(4, 18, 4, 18, true, false, "temp", "j"); + } + + // -- testing failing preconditions + public void testFail0() throws Exception{ + failHelper1(5, 16, 5, 17, false, false, "temp", RefactoringStatus.ERROR); + } + + public void testFail1() throws Exception{ + failHelper1(4, 9, 5, 13, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail2() throws Exception{ + failHelper1(4, 9, 4, 20, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail3() throws Exception{ + failHelper1(4, 9, 4, 20, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail4() throws Exception{ + failHelper1(5, 9, 5, 12, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail5() throws Exception{ + failHelper1(3, 12, 3, 15, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail6() throws Exception{ + failHelper1(4, 14, 4, 19, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail7() throws Exception{ + failHelper1(4, 15, 4, 20, false, false, "temp", RefactoringStatus.FATAL); + } + +// public void testFail8() throws Exception{ +// printTestDisabledMessage("removed"); +// failHelper1(5, 16, 5, 20, false, false, "temp", RefactoringStatus.FATAL); +// } + + public void testFail9() throws Exception{ + failHelper1(4, 19, 4, 23, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail10() throws Exception{ + failHelper1(4, 33, 4, 39, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail11() throws Exception{ +// printTestDisabledMessage("regression test for bug#13061"); + failHelper1(4, 18, 4, 19, false, false, "temp", RefactoringStatus.FATAL); + } + +// removed - allowe now (see bug 98847) +// public void testFail12() throws Exception{ +// failHelper1(4, 16, 4, 29, false, false, "temp", RefactoringStatus.FATAL); +// } + +//removed +// public void testFail13() throws Exception{ +// failHelper1(5, 16, 5, 20, false, false, "temp", RefactoringStatus.FATAL); +// } + +//removed +// public void testFail14() throws Exception{ +// failHelper1(4, 16, 4, 22, false, false, "temp", RefactoringStatus.FATAL); +// } + +//removed +// public void testFail15() throws Exception{ +// failHelper1(4, 19, 4, 22, false, false, "temp", RefactoringStatus.FATAL); +// } + +//removed - allowed now (see bug 21815) +// public void testFail16() throws Exception{ +// failHelper1(5, 9, 5, 12, false, false, "temp", RefactoringStatus.FATAL); +// } +// +// public void testFail17() throws Exception{ +// failHelper1(6, 13, 6, 16, false, false, "temp", RefactoringStatus.FATAL); +// } + + public void testFail18() throws Exception{ +// printTestDisabledMessage("regression test for bug#8149"); +// printTestDisabledMessage("regression test for bug#37547"); + // test for bug 40353: is now FATAL" + failHelper1(4, 27, 4, 28, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail19() throws Exception{ +// printTestDisabledMessage("regression test for bug#8149"); + failHelper1(6, 16, 6, 18, false, false, "temp", RefactoringStatus.WARNING); + } + + public void testFail20() throws Exception{ +// printTestDisabledMessage("regression test for bug#13249"); + failHelper1(3, 9, 3, 41, false, false, "temp", RefactoringStatus.FATAL); + } + +//removed - allowed now (see bug 53243) +// public void testFail21() throws Exception{ +// //test for bug 19851 +// failHelper1(6, 9, 6, 24, false, false, "temp", RefactoringStatus.FATAL); +// } + + public void testFail22() throws Exception{ +// printTestDisabledMessage("test for bug 21815"); + failHelper1(5, 9, 5, 12, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail23() throws Exception{ +// printTestDisabledMessage("test for bug 24265"); + failHelper1(4, 13, 4, 14, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail24() throws Exception{ +// printTestDisabledMessage("test for bug 24265"); + failHelper1(4, 13, 4, 14, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail25() throws Exception{ + failHelper1(4, 16, 4, 18, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail26() throws Exception{ + failHelper1(4, 15, 4, 20, false, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail27() throws Exception{ +// printTestDisabledMessage("test for bug 29513"); + failHelper1(7, 13, 7, 24, true, false, "temp", RefactoringStatus.WARNING); + } + + public void testFail28() throws Exception{ +// printTestDisabledMessage("test for bug 29513"); + failHelper1(7, 17, 7, 28, true, false, "temp", RefactoringStatus.WARNING); + } + + public void testFail29() throws Exception { +// printTestDisabledMessage("test for bug 40353: extracting for_updater referring to loop variable"); + failHelper1(5, 32, 5, 35, true, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail30() throws Exception { +// printTestDisabledMessage("test for bug 40353: extracting for_test referring to loop variable"); + failHelper1(5, 25, 5, 30, true, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail31() throws Exception { +// printTestDisabledMessage("test for bug 40353: extracting for_test referring to loop variable"); + failHelper1(5, 31, 5, 32, true, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail32() throws Exception { +// printTestDisabledMessage("test for bug 40353: extracting for_test referring to loop variable"); + failHelper1(6, 35, 6, 36, true, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail33() throws Exception { +// printTestDisabledMessage("test for bug 40353: extracting for_updater"); + failHelper1(6, 17, 6, 21, true, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail34() throws Exception { +// printTestDisabledMessage("test for bug 40353: extracting for_initializer"); + failHelper1(9, 20, 9, 24, true, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail35() throws Exception { +// printTestDisabledMessage("test for bug 45007: QualifiedName"); + failHelper1(6, 33, 6, 38, true, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail36() throws Exception { +// printTestDisabledMessage("test for bug 45007: FieldAccess"); + failHelper1(6, 33, 6, 38, true, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail37() throws Exception { +// printTestDisabledMessage("test for bug 45007: QualifiedName (nested)"); + failHelper1(5, 40, 5, 51, true, false, "temp", RefactoringStatus.FATAL); + } + + public void testFail38() throws Exception { + failHelper1(4, 45, 4, 50, true, false, "temp", RefactoringStatus.FATAL); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InferTypeArgumentsTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InferTypeArgumentsTests.java new file mode 100644 index 000000000..8ff6749a1 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InferTypeArgumentsTests.java @@ -0,0 +1,463 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.zip.ZipInputStream; + +import junit.framework.Assert; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.JavaTestPlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.CheckConditionsOperation; +import org.eclipse.ltk.core.refactoring.PerformRefactoringOperation; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; + +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; +import org.eclipse.jdt.internal.corext.refactoring.generics.InferTypeArgumentsRefactoring; + +import org.eclipse.jdt.ui.tests.refactoring.infra.ZipTools; + +public class InferTypeArgumentsTests extends RefactoringTest { + + private static final boolean DETERMINE_ELEMENT_TYPE_FROM_CAST= false; + private static final boolean BUG_86967_core_restore_binding= true; + private static final boolean BUG_86990_core_no_main_type= true; + private static final boolean BUG_87050_core_resolve_method_type_param= false; + + private static final Class clazz= InferTypeArgumentsTests.class; + private static final String REFACTORING_PATH= "InferTypeArguments/"; + + private boolean fAssumeCloneReturnsSameType= true; + private boolean fLeaveUnconstrainedRaw= true; + + public static Test suite() { + return setUpTest(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new Java16Setup(someTest); + } + + public InferTypeArgumentsTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + private void performCu(int expectedInitialStatus, int expectedFinalStatus) throws Exception { + IPackageFragment packageP= getPackageP(); + String cuName="A"; + ICompilationUnit cu= packageP.getCompilationUnit(cuName + ".java"); + if (!cu.exists()) + cu= createCUfromTestFile(packageP, cuName); + IJavaElement[] elements= { cu }; + boolean performed= perform(elements, expectedInitialStatus, expectedFinalStatus); + if (! performed) + return; + + String expected= getFileContents(getOutputTestFileName("A")); + String actual= cu.getSource(); + assertEqualLines(expected, actual); + } + + /** + * @param elements + * @param expectedInitialStatus + * @param expectedFinalStatus + * @return <code>true</code> iff performed + * @throws CoreException + */ + private boolean perform(IJavaElement[] elements, int expectedInitialStatus, int expectedFinalStatus) throws CoreException { + InferTypeArgumentsRefactoring refactoring= ((RefactoringAvailabilityTester.isInferTypeArgumentsAvailable(elements)) ? new InferTypeArgumentsRefactoring(elements) : null); + + NullProgressMonitor pm= new NullProgressMonitor(); + RefactoringStatus initialStatus= refactoring.checkInitialConditions(pm); + assertEquals("wrong initial condition status: " + initialStatus, expectedInitialStatus, initialStatus.getSeverity()); + if (! initialStatus.isOK()) + return false; + + refactoring.setAssumeCloneReturnsSameType(fAssumeCloneReturnsSameType); + refactoring.setLeaveUnconstrainedRaw(fLeaveUnconstrainedRaw); + + PerformRefactoringOperation op= new PerformRefactoringOperation( + refactoring, CheckConditionsOperation.FINAL_CONDITIONS); + JavaCore.run(op, new NullProgressMonitor()); + RefactoringStatus finalStatus= op.getConditionStatus(); + assertEquals("wrong final condition status: " + finalStatus, expectedFinalStatus, finalStatus.getSeverity()); + if (finalStatus.getSeverity() == RefactoringStatus.FATAL) + return false; + + assertTrue("Validation check failed: " + op.getValidationStatus(), !op.getValidationStatus().hasFatalError()); + assertNotNull("No Undo", op.getUndoChange()); + return true; + } + + private void performCuOK() throws Exception { + performCu(RefactoringStatus.OK, RefactoringStatus.OK); + } + + public void compareWithZipFile(IPackageFragmentRoot src, String zipFileName) throws Exception { + String fullName= TEST_PATH_PREFIX + getRefactoringPath() + zipFileName; + ZipInputStream zis= new ZipInputStream(getFileInputStream(fullName)); + ZipTools.compareWithZipped(src, zis, JavaProjectHelper.JUNIT_SRC_ENCODING); + } + + public void testCuQualifiedName() throws Exception { + performCuOK(); + } + + public void testCuAnonymous01() throws Exception { + performCuOK(); + } + + public void testCuTypeParams9() throws Exception { + performCuOK(); + } + + public void testCuExistingParameterized01() throws Exception { + performCuOK(); + } + + public void testCuGetClass() throws Exception { + performCuOK(); + } + + public void testCuGetClass2() throws Exception { + // Test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=211037 + // In 1.6, Object#getClass() declares return type Class<?>, but in 1.5, it's Class<? extends Object>. + performCuOK(); + + // Test the same with 1.5: + IJavaProject project= RefactoringTestSetup.getProject(); + + ArrayList classpath= new ArrayList(Arrays.asList(project.getRawClasspath())); + IClasspathEntry jreEntry= RefactoringTestSetup.getJRELibrary().getRawClasspathEntry(); + classpath.remove(jreEntry); + IClasspathEntry[] noRTJarCPEs= (IClasspathEntry[])classpath.toArray(new IClasspathEntry[classpath.size()]); + + project.setRawClasspath(noRTJarCPEs, new NullProgressMonitor()); + JavaProjectHelper.addRTJar15(project); + + try { + performCuOK(); + } finally { + project.setRawClasspath(noRTJarCPEs, new NullProgressMonitor()); + JavaProjectHelper.addRTJar16(project); + } + } + + public void testCuGetSuperclass() throws Exception { + performCuOK(); + } + + public void testCuTypeLiteral() throws Exception { + performCuOK(); + } + + public void testCuMethodTypeParam() throws Exception { + performCuOK(); + } + + public void testCuGetTakeClassStayRaw() throws Exception { + performCuOK(); + } + + public void testCuGetClassNewInstance() throws Exception { + performCuOK(); + } + + public void testCuSynchronizedList() throws Exception { + fLeaveUnconstrainedRaw= false; + performCuOK(); + } + + public void testCuAddAll() throws Exception { + performCuOK(); + } + + public void testCuNestedCells1() throws Exception { + createCUfromTestFile(getPackageP(), "Cell"); + fLeaveUnconstrainedRaw= false; + performCuOK(); + } + + public void testCuNestedVectors0() throws Exception { + fLeaveUnconstrainedRaw= false; + performCuOK(); + } + + public void testCuNestedVectors1() throws Exception { + performCuOK(); + } + + public void testCuInferTypeVariable01() throws Exception { + if (BUG_86990_core_no_main_type || BUG_87050_core_resolve_method_type_param) { + printTestDisabledMessage("BUG_86990_core_no_main_type || BUG_87050_core_resolve_method_type_param"); + return; + } + performCuOK(); + } + + public void testCuBoxing01() throws Exception { + performCuOK(); + } + + public void testCuBoxing02() throws Exception { + performCuOK(); + } + + public void testCuConstructor01() throws Exception { + performCuOK(); + } + + public void testJUnit() throws Exception { + fAssumeCloneReturnsSameType= false; + fLeaveUnconstrainedRaw= true; + IJavaProject javaProject= JavaProjectHelper.createJavaProject("InferTypeArguments", "bin"); + try { + IPackageFragmentRoot jdk= JavaProjectHelper.addRTJar(javaProject); + Assert.assertNotNull(jdk); + + File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC_381); + Assert.assertTrue(junitSrcArchive != null && junitSrcArchive.exists()); + + IPackageFragmentRoot src= JavaProjectHelper.addSourceContainerWithImport(javaProject, "src", junitSrcArchive, JavaProjectHelper.JUNIT_SRC_ENCODING); + + boolean performed= perform(new IJavaElement[] { javaProject }, RefactoringStatus.OK, RefactoringStatus.OK); + assertTrue(performed); + + compareWithZipFile(src, "junit381-noUI-generified-src.zip"); + } finally { + if (javaProject != null && javaProject.exists()) + JavaProjectHelper.delete(javaProject); + } + + } + + public void testJUnitWithCloneNotRaw() throws Exception { + fAssumeCloneReturnsSameType= true; + fLeaveUnconstrainedRaw= false; + + IJavaProject javaProject= JavaProjectHelper.createJavaProject("InferTypeArguments", "bin"); + try { + IPackageFragmentRoot jdk= JavaProjectHelper.addRTJar(javaProject); + Assert.assertNotNull(jdk); + + File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC_381); + Assert.assertTrue(junitSrcArchive != null && junitSrcArchive.exists()); + + IPackageFragmentRoot src= JavaProjectHelper.addSourceContainerWithImport(javaProject, "src", junitSrcArchive, JavaProjectHelper.JUNIT_SRC_ENCODING); + + boolean performed= perform(new IJavaElement[] { javaProject }, RefactoringStatus.OK, RefactoringStatus.OK); + assertTrue(performed); + + compareWithZipFile(src, "junit381-noUI-clone-not-raw-src.zip"); + } finally { + if (javaProject != null && javaProject.exists()) + JavaProjectHelper.delete(javaProject); + } + + } + + public void testCuTwoVectorElements() throws Exception { + performCuOK(); + } + + public void testCuHalfPair() throws Exception { + performCuOK(); + } + + public void testCuMethodAndTypeGeneric01() throws Exception { + performCuOK(); + } + + public void testCuMethodAndTypeGeneric02() throws Exception { + performCuOK(); + } + + public void testPairDance() throws Exception { + createCUfromTestFile(getPackageP(), "Pair"); + createCUfromTestFile(getPackageP(), "InvertedPair"); + performCuOK(); + // deleted in tearDown + } + + public void testCuAddString() throws Exception { + performCuOK(); + } + + public void testCuAddString2() throws Exception { + performCuOK(); + } + + public void testCuIntermediateLocal() throws Exception { + performCuOK(); + } + + public void testCuSuperAndSub() throws Exception { + performCuOK(); + } + + public void testCuCommonSuper() throws Exception { + performCuOK(); + } + + public void testCuAddGetString() throws Exception { + performCuOK(); + } + + public void testCuAddIntegerGetNumber() throws Exception { + performCuOK(); + } + + public void testCuAddGetIterator() throws Exception { + performCuOK(); + } + + public void testCuContains() throws Exception { + performCuOK(); + } + + public void testCuMethodParam() throws Exception { + performCuOK(); + } + + public void testCuMethodReturns() throws Exception { + performCuOK(); + } + + public void testCuCollectionsMin() throws Exception { + performCuOK(); + } + + public void testCuAddStringInteger() throws Exception { + printTestDisabledMessage("currently, we don't follow flow through variables of type Object"); +// performCuOK(); //TODO + } + + public void testCuAddStringIntegerA() throws Exception { + performCuOK(); + } + + public void testCuInferFromCast() throws Exception { + printTestDisabledMessage("not implemented yet"); +// performCuOK(); //TODO + } + + public void testCuRippleMethods() throws Exception { + performCuOK(); + } + + public void testCuRippleMethods2() throws Exception { + performCuOK(); + } + + public void testCuCannotStringDouble() throws Exception { + printTestDisabledMessage("not implemented yet"); +// performCuOK(); + } + + public void testCuRippleMethods3() throws Exception { + printTestDisabledMessage("not implemented yet"); +// performCuOK(); + } + + public void testCuVarargs01() throws Exception { + performCuOK(); + } + + public void testCuArrays01() throws Exception { + performCuOK(); + } + + public void testCuArrays02() throws Exception { + performCuOK(); + } + + public void testCuArrays03() throws Exception { + performCuOK(); + } + + public void testCuArrays04() throws Exception { + performCuOK(); + } + + public void testCuArrays05() throws Exception { + if (! DETERMINE_ELEMENT_TYPE_FROM_CAST) { + printTestDisabledMessage("DETERMINE_ELEMENT_TYPE_FROM_CAST"); + return; + } + performCuOK(); + } + + public void testCuArrays06() throws Exception { + performCuOK(); + } + + public void testCuArrays07() throws Exception { + performCuOK(); + } + + public void testCuToArray01() throws Exception { + performCuOK(); + } + + public void testCuToArray02() throws Exception { + performCuOK(); + } + + public void testCuMapEntry01() throws Exception { + if (BUG_86967_core_restore_binding) { + printTestDisabledMessage("BUG_86967_core_restore_binding"); + return; + } + performCuOK(); + } + + public void testCuFieldAccess01() throws Exception { + performCuOK(); + } + + public void testCuFieldAccess02() throws Exception { + performCuOK(); + } + + public void testCuMemberOfRaw() throws Exception { + // regression test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=110594 + performCuOK(); + } + + public void testCuParameterizedTypes1() throws Exception { + // regression test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=176742 + performCuOK(); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineConstantTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineConstantTests.java new file mode 100644 index 000000000..5069e649c --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineConstantTests.java @@ -0,0 +1,316 @@ +/******************************************************************************* + * Copyright (c) 2000, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.Assert; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.dom.AST; + +import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatusCodes; +import org.eclipse.jdt.internal.corext.refactoring.code.InlineConstantRefactoring; +import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser; + +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +public class InlineConstantTests extends RefactoringTest { + private static final Class clazz = InlineConstantTests.class; + private static final String REFACTORING_PATH = "InlineConstant/"; + + private boolean toSucceed; + + public InlineConstantTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH + successPath(); + } + + private String successPath() { + return toSucceed ? "/canInline/" : "/cannotInline/"; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + private String getSimpleName(String qualifiedName) { + return qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1); + } + + private String getQualifier(String qualifiedName) { + int dot= qualifiedName.lastIndexOf('.'); + return qualifiedName.substring(0, dot != -1 ? dot : 0); + } + + private ICompilationUnit[] createCUs(String[] qualifiedNames) throws Exception { + ICompilationUnit[] cus= new ICompilationUnit[qualifiedNames.length]; + for(int i= 0; i < qualifiedNames.length; i++) { + Assert.isNotNull(qualifiedNames[i]); + + cus[i]= createCUfromTestFile(getRoot().createPackageFragment(getQualifier(qualifiedNames[i]), true, null), + getSimpleName(qualifiedNames[i])); + } + return cus; + } + + private int firstIndexOf(String one, String[] others) { + for(int i= 0; i < others.length; i++) + if(one == null && others[i] == null || one.equals(others[i])) + return i; + return -1; + } + private void helper1(String cuQName, int startLine, int startColumn, int endLine, int endColumn, boolean replaceAll, boolean removeDeclaration) throws Exception{ + helper1(new String[] {cuQName}, cuQName, startLine, startColumn, endLine, endColumn, replaceAll, removeDeclaration); + } + private void helper1(String[] cuQNames, String selectionCuQName, int startLine, int startColumn, int endLine, int endColumn, boolean replaceAll, boolean removeDeclaration) throws Exception{ + int selectionCuIndex= firstIndexOf(selectionCuQName, cuQNames); + Assert.isTrue(selectionCuIndex != -1, "parameter selectionCuQName must match some String in cuQNames."); + helper1(cuQNames, selectionCuIndex, startLine, startColumn, endLine, endColumn, replaceAll, removeDeclaration); + } + private void helper1(String[] cuQNames, int selectionCuIndex, int startLine, int startColumn, int endLine, int endColumn, boolean replaceAll, boolean removeDeclaration) throws Exception{ + Assert.isTrue(0 <= selectionCuIndex && selectionCuIndex < cuQNames.length); + + toSucceed= true; + + ICompilationUnit[] cus= createCUs(cuQNames); + ICompilationUnit selectionCu= cus[selectionCuIndex]; + + ISourceRange selection= TextRangeUtil.getSelection(selectionCu, startLine, startColumn, endLine, endColumn); + InlineConstantRefactoring ref= new InlineConstantRefactoring(selectionCu, new RefactoringASTParser(AST.JLS3).parse(selectionCu, true), selection.getOffset(), selection.getLength()); + if (ref.checkStaticFinalConstantNameSelected().hasFatalError()) + ref= null; + RefactoringStatus preconditionResult= ref.checkInitialConditions(new NullProgressMonitor()); + + assertTrue("activation was supposed to be successful", preconditionResult.isOK()); + + ref.setReplaceAllReferences(replaceAll); + ref.setRemoveDeclaration(removeDeclaration); + + preconditionResult.merge(ref.checkFinalConditions(new NullProgressMonitor())); + + assertTrue("precondition was supposed to pass",preconditionResult.isOK()); + + performChange(ref, false); + + for(int i= 0; i < cus.length; i++){ + String outputTestFileName= getOutputTestFileName(getSimpleName(cuQNames[i])); + assertEqualLines("Incorrect inline in " + outputTestFileName, getFileContents(outputTestFileName), cus[i].getSource()); + } + } + + private void failHelper1(String cuQName, int startLine, int startColumn, int endLine, int endColumn, boolean replaceAll, boolean removeDeclaration, int errorCode) throws Exception{ + failHelper1(new String[] {cuQName}, cuQName, startLine, startColumn, endLine, endColumn, replaceAll, removeDeclaration, errorCode); + } + private void failHelper1(String[] cuQNames, String selectionCuQName, int startLine, int startColumn, int endLine, int endColumn, boolean replaceAll, boolean removeDeclaration, int errorCode) throws Exception{ + int selectionCuIndex= firstIndexOf(selectionCuQName, cuQNames); + Assert.isTrue(selectionCuIndex != -1, "parameter selectionCuQName must match some String in cuQNames."); + failHelper1(cuQNames, selectionCuIndex, startLine, startColumn, endLine, endColumn, replaceAll, removeDeclaration, errorCode); + } + private void failHelper1(String[] cuQNames, int selectionCuIndex, int startLine, int startColumn, int endLine, int endColumn, boolean replaceAll, boolean removeDeclaration, int errorCode) throws Exception{ + Assert.isTrue(0 <= selectionCuIndex && selectionCuIndex < cuQNames.length); + + toSucceed= false; + + ICompilationUnit[] cus= createCUs(cuQNames); + ICompilationUnit selectionCu= cus[selectionCuIndex]; + + ISourceRange selection= TextRangeUtil.getSelection(selectionCu, startLine, startColumn, endLine, endColumn); + InlineConstantRefactoring ref= new InlineConstantRefactoring(selectionCu, new RefactoringASTParser(AST.JLS3).parse(selectionCu, true), selection.getOffset(), selection.getLength()); + if (ref.checkStaticFinalConstantNameSelected().hasFatalError()) + ref= null; + if (ref == null) + return; + RefactoringStatus result= ref.checkInitialConditions(new NullProgressMonitor()); + + if(!result.isOK()) { + assertEquals(errorCode, result.getEntryMatchingSeverity(RefactoringStatus.ERROR).getCode()); + return; + } else { + + ref.setReplaceAllReferences(replaceAll); + ref.setRemoveDeclaration(removeDeclaration); + + result.merge(ref.checkFinalConditions(new NullProgressMonitor())); + + assertTrue("precondition checking is expected to fail.", !result.isOK()); + assertEquals(errorCode, result.getEntryMatchingSeverity(RefactoringStatus.ERROR).getCode()); + } + } + + //--- TESTS + + public void test0() throws Exception { + helper1("p.C", 5, 30, 5, 36, true, false); + } + + public void test1() throws Exception { + helper1("C", 3, 33, 3, 40, true, false); + } + + public void test2() throws Exception { + helper1("p.Klass", 10, 22, 10, 30, false, false); + } + + public void test3() throws Exception { + helper1("p.LeVinSuperieure", 5, 32, 5, 43, true, true); + } + + public void test4() throws Exception { + helper1("p.Klus", 5, 36, 5, 36, true, false); + } + + public void test5() throws Exception { + helper1("p.PartOfDeclNameSelected", 5, 32, 5, 34, true, true); + } + + public void test6() throws Exception { + helper1("p.CursorPositionedInReference", 8, 57, 8, 57, false, false); + } + + public void test7() throws Exception { + helper1("p.PartOfReferenceSelected", 8, 52, 8, 62, false, false); + } + + public void test8() throws Exception { + helper1(new String[] {"p1.C", "p2.D"}, "p1.C", 5, 29, 5, 37, true, false); + } + + public void test9() throws Exception { + helper1(new String[] {"p1.C", "p2.D", "p3.E"}, "p2.D", 8, 18, 8, 26, true, true); + } + + public void test10() throws Exception { + helper1(new String[] {"p1.A", "p2.B"}, "p2.B", 9, 28, 9, 37, false, false); + } + + public void test11() throws Exception { + helper1(new String[] {"p1.A", "p2.B", "p3.C"}, "p1.A", 8, 25, 8, 25, false, false); + } + + public void test12() throws Exception { + helper1(new String[] {"p1.Declarer", "p2.InlineSite"}, "p2.InlineSite", 7, 37, 7, 43, true, false); + } + + public void test13() throws Exception { + helper1(new String[] {"p1.A", "p2.InlineSite"}, "p2.InlineSite", 8, 19, 8, 29, false, false); + } + + public void test14() throws Exception { + helper1("cantonzuerich.GrueziWohl", 7, 35, 7, 35, true, false); + } + + public void test15() throws Exception { + helper1("schweiz.zuerich.zuerich.Froehlichkeit", 14, 16, 14, 32, true, false); + } + + public void test16() throws Exception { + helper1("p.IntegerMath", 8, 23, 8, 23, true, true); + } + + public void test17() throws Exception { + helper1("p.EnumRef", 4, 59, 4, 59, true, true); + } + + public void test18() throws Exception { + helper1("p.Annot", 5, 18, 5, 18, true, true); + } + + public void test19() throws Exception { + helper1("p.Test", 7, 36, 7, 36, true, false); + } + + public void test20() throws Exception { + helper1("p.Test", 10, 21, 10, 21, true, true); + } + + public void test21() throws Exception { + helper1(new String[] {"p.A", "q.Consts"}, "p.A", 8, 16, 8, 19, true, false); + } + + public void test22() throws Exception { + helper1(new String[] {"p.A", "q.Consts", "r.Third"}, "p.A", 11, 16, 11, 19, true, true); + } + + public void test23() throws Exception { + helper1("p.Test", 6, 26, 6, 26, false, false); + } + + public void test24() throws Exception { + helper1(new String[] {"p.A", "q.Consts"}, "p.A", 14, 17, 14, 17, true, true); + } + + public void test25() throws Exception { + helper1("p.A", 5, 32, 5, 32, true, true); + } + + public void test26() throws Exception { // test for bug 93689 + helper1("p.A", 5, 42, 5, 42, true, true); + } + + public void test27() throws Exception { // test for bug 109071 + helper1("p.A", 4, 24, 4, 29, true, true); + } + + public void test28() throws Exception { + helper1(new String[] {"p.Const", "p.AnotherClass", "q.UsedClass"}, "p.Const", 6, 35, 6, 43, true, true); + } + + public void test29() throws Exception { // test for bug 174327 + helper1("p.A", 7, 44, 7, 44, true, true); + } + + public void test30() throws Exception { //test for bug 237547 (inline unused constant) + helper1(new String[] {"p.A", "p.B", "p.C", "p.D", "q.Consts"}, "q.Consts", 5, 32, 5, 40, true, true); + } + + public void test31() throws Exception { // test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=265448 + helper1("p.A", 4, 23, 4, 28, true, true); + } + + public void test32() throws Exception { // test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=265448 + helper1("p.A", 4, 23, 4, 28, true, true); + } + + public void test33() throws Exception { // test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=279715 + helper1("p.A", 5, 29, 5, 30, true, true); + } + + public void test34() throws Exception { // test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=297760 + helper1("p.A", 4, 24, 4, 25, true, true); + } + + // -- testing failing preconditions + + public void testFail0() throws Exception { + failHelper1("foo.NeueZuercherZeitung", 5, 27, 5, 28, true, false, RefactoringStatusCodes.NOT_STATIC_FINAL_SELECTED); + } + + public void testFail1() throws Exception { + failHelper1("fun.Fun", 8, 35, 8, 35, false, false, RefactoringStatusCodes.DECLARED_IN_CLASSFILE); + } + + public void testFail2() throws Exception { + failHelper1("p.EnumRef", 7, 22, 7, 22, true, true, RefactoringStatusCodes.NOT_STATIC_FINAL_SELECTED); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTestSetup.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTestSetup.java new file mode 100644 index 000000000..9c4733b14 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTestSetup.java @@ -0,0 +1,230 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.IOException; +import java.net.URL; +import java.util.Enumeration; + +import junit.framework.Test; + +import org.osgi.framework.Bundle; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.Path; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; + +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringTestPlugin; + +public class InlineMethodTestSetup extends RefactoringTestSetup { + + private IPackageFragment fInvalid; + private IPackageFragment fBugs; + private IPackageFragment fSimple; + private IPackageFragment fArgument; + private IPackageFragment fNameConflict; + private IPackageFragment fCall; + private IPackageFragment fExpression; + private IPackageFragment fControlStatement; + private IPackageFragment fReceiver; + private IPackageFragment fImport; + private IPackageFragment fCast; + private IPackageFragment fEnum; + private IPackageFragment fGeneric; + private IPackageFragment fBinary; + private IPackageFragment fOperator; + + public InlineMethodTestSetup(Test test) { + super(test); + } + + protected void setUp() throws Exception { + super.setUp(); + + IPackageFragmentRoot root= getDefaultSourceFolder(); + fInvalid= root.createPackageFragment("invalid", true, null); + fBugs= root.createPackageFragment("bugs_in", true, null); + fSimple= root.createPackageFragment("simple_in", true, null); + fArgument= root.createPackageFragment("argument_in", true, null); + fNameConflict= root.createPackageFragment("nameconflict_in", true, null); + fCall= root.createPackageFragment("call_in", true, null); + fExpression= root.createPackageFragment("expression_in", true, null); + fControlStatement= root.createPackageFragment("controlStatement_in", true, null); + fReceiver= root.createPackageFragment("receiver_in", true, null); + fImport= root.createPackageFragment("import_in", true, null); + fCast= root.createPackageFragment("cast_in", true, null); + fEnum= root.createPackageFragment("enum_in", true, null); + fGeneric= root.createPackageFragment("generic_in", true, null); + fBinary= root.createPackageFragment("binary_in", true, null); + fOperator= root.createPackageFragment("operator_in", true, null); + + IJavaProject javaProject= getProject(); + IProject project= javaProject.getProject(); + copyFilesFromResources(project, "binary/classes", "*.class"); + copyFilesFromResources(project, "binary_src/classes", "*.java"); + + IClasspathEntry[] classpath= javaProject.getRawClasspath(); + IClasspathEntry[] newClasspath= new IClasspathEntry[classpath.length + 1]; + System.arraycopy(classpath, 0, newClasspath, 0, classpath.length); + IClasspathEntry binaryFolder= JavaCore.newLibraryEntry(javaProject.getPath().append("binary"), javaProject.getPath().append("binary_src"), null); + newClasspath[classpath.length]= binaryFolder; + javaProject.setRawClasspath(newClasspath, null); + + fImport.createCompilationUnit( + "Provider.java", + "package import_in;\n" + + "\n" + + "import import_use.List;\n" + + "import java.io.File;\n" + + "import java.util.ArrayList;\n" + + "import java.util.Map;\n" + + "import static java.lang.Math.PI;\n" + + "\n" + + "public class Provider {\n" + + " public File useAsReturn() {\n" + + " return null;\n" + + " }\n" + + " public void useInArgument(File file) {\n" + + " file= null;\n" + + " }\n" + + " public void useInDecl() {\n" + + " List list= null;\n" + + " }\n" + + " public int useInDecl2() {\n" + + " return new ArrayList().size();\n" + + " }\n" + + " public Object useInDecl3() {\n" + + " return new java.util.HashMap();\n" + + " }\n" + + " public void useInClassLiteral() {\n" + + " Class clazz= File.class;\n" + + " }\n" + + " public void useArray() {\n" + + " List[] lists= null;\n" + + " }\n" + + " public void useInLocalClass() {\n" + + " class Local extends File {\n" + + " private static final long serialVersionUID = 1L;\n" + + " public Local(String s) {\n" + + " super(s);\n" + + " }\n" + + " public void foo(Map map) {\n" + + " }\n" + + " public void bar(Byte b) {\n" + + " }\n" + + " }\n" + + " }\n" + + " public void useStaticImport() {\n" + + " double i= PI;\n" + + " }\n" + + "}\n", + true, null); + + IPackageFragment importUse= root.createPackageFragment("import_use", true, null); + importUse.createCompilationUnit("List.java", + "package import_use;" + + "" + + "public class List {" + + "}", + true, null); + + } + + private static void copyFilesFromResources(IProject project, String pathInRoot, String filePattern) throws CoreException, IOException { + String[] folders= pathInRoot.split("/"); + IFolder folder= project.getFolder(folders[0]); + folder.create(true, true, null); + for (int i= 1; i < folders.length; i++) { + folder= folder.getFolder(folders[i]); + folder.create(true, true, null); + } + + Bundle bundle= RefactoringTestPlugin.getDefault().getBundle(); + Enumeration/*URL*/ classUrls= bundle.findEntries("/resources/InlineMethodWorkspace/TestCases/" + pathInRoot, filePattern, false); + while (classUrls.hasMoreElements()) { + URL classUrl= (URL) classUrls.nextElement(); + String urlFile= classUrl.getFile(); + String fileName= urlFile.substring(urlFile.lastIndexOf('/') + 1); + + IFile file= folder.getFile(new Path(fileName)); + file.create(classUrl.openStream(), true, null); + } + } + + public IPackageFragment getInvalidPackage() { + return fInvalid; + } + + public IPackageFragment getBugsPackage() { + return fBugs; + } + + public IPackageFragment getSimplePackage() { + return fSimple; + } + + public IPackageFragment getArgumentPackage() { + return fArgument; + } + + public IPackageFragment getNameConflictPackage() { + return fNameConflict; + } + + public IPackageFragment getCallPackage() { + return fCall; + } + + public IPackageFragment getExpressionPackage() { + return fExpression; + } + + public IPackageFragment getControlStatementPackage() { + return fControlStatement; + } + + public IPackageFragment getReceiverPackage() { + return fReceiver; + } + + public IPackageFragment getImportPackage() { + return fImport; + } + + public IPackageFragment getCastPackage() { + return fCast; + } + + public IPackageFragment getEnumPackage() { + return fEnum; + } + + public IPackageFragment getGenericPackage() { + return fGeneric; + } + + public IPackageFragment getBinaryPackage() { + return fBinary; + } + + public IPackageFragment getOperatorPackage() { + return fOperator; + } +}
\ No newline at end of file diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java new file mode 100644 index 000000000..fd6435c6f --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java @@ -0,0 +1,1068 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fixes for: + * o bug "inline method - doesn't handle implicit cast" (see + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=24941). + * o bug inline method: compile error (array related) [refactoring] + * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38471) + * o bug "Inline refactoring showed bogus error" (see bugzilla + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=42753) + * o inline call that is used in a field initializer + * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38137) + * o inline call a field initializer: could detect self reference + * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=44417) + * o Allow 'this' constructor to be inlined + * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=38093) + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.jdt.core.IClassFile; +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.InfixExpression; +import org.eclipse.jdt.core.dom.InfixExpression.Operator; + +import org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring; +import org.eclipse.jdt.internal.corext.refactoring.code.OperatorPrecedence; +import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser; + +public class InlineMethodTests extends AbstractSelectionTestCase { + private static InlineMethodTestSetup fgTestSetup; + private static final boolean BUG_82166= true; + + public InlineMethodTests(String name) { + super(name, true); + } + + public static Test suite() { + fgTestSetup= new InlineMethodTestSetup(new TestSuite(InlineMethodTests.class)); + return fgTestSetup; + } + + public static Test setUpTest(Test someTest) { + fgTestSetup= new InlineMethodTestSetup(someTest); + return fgTestSetup; + } + + protected void setUp() throws Exception { + super.setUp(); + fIsPreDeltaTest= true; + } + + protected String getResourceLocation() { + return "InlineMethodWorkspace/TestCases/"; + } + + protected String adaptName(String name) { + return Character.toUpperCase(name.charAt(0)) + name.substring(1) + ".java"; + } + + protected void performTestInlineCall(IPackageFragment packageFragment, String id, int mode, String outputFolder) throws Exception { + ICompilationUnit unit= createCU(packageFragment, id); + int[] selection= getSelection(); + InlineMethodRefactoring refactoring= InlineMethodRefactoring.create(unit, new RefactoringASTParser(AST.JLS3).parse(unit, true), selection[0], selection[1]); + String out= null; + switch (mode) { + case COMPARE_WITH_OUTPUT: + out= getProofedContent(outputFolder, id); + break; + } + performTest(unit, refactoring, mode, out, true); + } + + private void performTestInlineMethod(IPackageFragment packageFragment, String id, int mode, String outputFolder) throws Exception { + ICompilationUnit unit= createCU(packageFragment, id); + IType type= unit.getTypes()[0]; + IMethod method= getMethodToInline(type); + InlineMethodRefactoring refactoring= InlineMethodRefactoring.create(unit, new RefactoringASTParser(AST.JLS3).parse(unit, true), method.getNameRange().getOffset(), method.getNameRange().getLength()); + String out= null; + switch (mode) { + case COMPARE_WITH_OUTPUT: + out= getProofedContent(outputFolder, id); + break; + } + performTest(unit, refactoring, mode, out, true); + } + + private IMethod getMethodToInline(IType type) throws CoreException { + IMethod[] methods= type.getMethods(); + for (int i= 0; i < methods.length; i++) { + if ("toInline".equals(methods[i].getElementName())) + return methods[i]; + } + return null; + } + + private void performTestInlineFirstConstructor(IPackageFragment packageFragment, String id, int mode, String outputFolder) throws Exception { + ICompilationUnit unit= createCU(packageFragment, id); + IType type= unit.getTypes()[0]; + IMethod method= getFirstConstructor(type); + InlineMethodRefactoring refactoring= InlineMethodRefactoring.create(unit, new RefactoringASTParser(AST.JLS3).parse(unit, true), method.getNameRange().getOffset(), method.getNameRange().getLength()); + String out= null; + switch (mode) { + case COMPARE_WITH_OUTPUT: + out= getProofedContent(outputFolder, id); + break; + } + performTest(unit, refactoring, mode, out, true); + } + + private IMethod getFirstConstructor(IType type) throws CoreException { + IMethod[] methods= type.getMethods(); + for (int i= 0; i < methods.length; i++) { + if (methods[i].isConstructor()) + return methods[i]; + } + return null; + } + + /* *********************** Invalid Tests ******************************* */ + + protected void performInvalidTest() throws Exception { + performTestInlineCall(fgTestSetup.getInvalidPackage(), getName(), INVALID_SELECTION, null); + } + + private void performInvalidTestInlineMethod() throws Exception { + performTestInlineMethod(fgTestSetup.getInvalidPackage(), getName(), INVALID_SELECTION, null); + } + + public void testRecursion() throws Exception { + performInvalidTest(); + } + + public void testInvalidFieldInitializer1() throws Exception { + performInvalidTest(); + } + + public void testInvalidFieldInitializer2() throws Exception { + performInvalidTest(); + } + + public void testInvalidFieldInitializer3() throws Exception { + performInvalidTest(); + } + + public void testLocalInitializer() throws Exception { + performInvalidTest(); + } + + public void testInterruptedStatement() throws Exception { + performInvalidTest(); + } + + public void testInterruptedExecutionFlow() throws Exception { + performInvalidTest(); + } + + public void testMultiLocal() throws Exception { + performInvalidTest(); + } + + public void testComplexBody() throws Exception { + performInvalidTest(); + } + + public void testCompileError1() throws Exception { + performInvalidTest(); + } + + public void testCompileError2() throws Exception { + performInvalidTest(); + } + + public void testCompileError3() throws Exception { + performInvalidTest(); + } + + public void testMultipleMethods() throws Exception { + performInvalidTestInlineMethod(); + } + + public void testSuperInThis() throws Exception { + performInvalidTestInlineMethod(); + } + + public void testNotMethodName() throws Exception { + ICompilationUnit unit= createCU(fgTestSetup.getInvalidPackage(), getName()); + int[] selection= getSelection(); + InlineMethodRefactoring refactoring= InlineMethodRefactoring.create(unit, new RefactoringASTParser(AST.JLS3).parse(unit, true), selection[0], selection[1]); + assertNull(refactoring); + } + + /* *********************** Simple Tests ******************************* */ + + private void performSimpleTest() throws Exception { + performTestInlineCall(fgTestSetup.getSimplePackage(), getName(), COMPARE_WITH_OUTPUT, "simple_out"); + } + + private void performSimpleTestInlineMethod() throws Exception { + performTestInlineMethod(fgTestSetup.getSimplePackage(), getName(), COMPARE_WITH_OUTPUT, "simple_out"); + } + + private void performSimpleTestInlineConstrcutor() throws Exception { + performTestInlineFirstConstructor(fgTestSetup.getSimplePackage(), getName(), COMPARE_WITH_OUTPUT, "simple_out"); + } + + public void testBasic1() throws Exception { + performSimpleTest(); + } + + public void testBasic2() throws Exception { + performSimpleTest(); + } + + public void testEmptyBody() throws Exception { + performSimpleTest(); + } + + public void testPrimitiveArray() throws Exception { + performSimpleTest(); + } + + public void testTypeArray() throws Exception { + performSimpleTest(); + } + + public void testInitializer() throws Exception { + performSimpleTest(); + } + + public void testSuper() throws Exception { + performSimpleTest(); + } + + public void testFieldInitializer1() throws Exception { + performSimpleTest(); + } + + public void testFieldInitializer2() throws Exception { + performSimpleTest(); + } + + public void testFieldInitializerAnonymous() throws Exception { + performSimpleTest(); + } + + public void testLabeledStatement() throws Exception { + performSimpleTest(); + } + + public void testConstructor1() throws Exception { + performSimpleTest(); + } + + public void testConstructor2() throws Exception { + performSimpleTestInlineConstrcutor(); + } + + public void testCatchClause() throws Exception { + performSimpleTest(); + } + + public void testTwoCalls() throws Exception { + performSimpleTestInlineMethod(); + } + + public void testNestedCalls() throws Exception { + performSimpleTestInlineMethod(); + } + + public void testSurroundingCallers() throws Exception { + performSimpleTestInlineMethod(); + } + + public void testComment1() throws Exception { + performSimpleTestInlineMethod(); + } + + /* *********************** Bug Tests ******************************* */ + + private void performBugTest() throws Exception { + performTestInlineCall(fgTestSetup.getBugsPackage(), getName(), COMPARE_WITH_OUTPUT, "bugs_out"); + } + + private void performBugTestInlineMethod() throws Exception { + performTestInlineMethod(fgTestSetup.getBugsPackage(), getName(), COMPARE_WITH_OUTPUT, "bugs_out"); + } + + public void test_72836() throws Exception { + performBugTest(); + } + + public void test_76241() throws Exception { + performBugTestInlineMethod(); + } + + public void test_94426() throws Exception { + performBugTestInlineMethod(); + } + + public void test_95128() throws Exception { + performBugTestInlineMethod(); + } + + public void test_117053() throws Exception { + performBugTest(); + } + + public void test_123356() throws Exception { + performBugTest(); + } + + public void test_44419() throws Exception { + performBugTest(); + } + + public void test_44419_2() throws Exception { + performBugTest(); + } + + public void test_98856() throws Exception { + performBugTest(); + } + + public void test_50139() throws Exception { + performBugTest(); + } + + public void test_287378() throws Exception { + performBugTest(); + } + + /* *********************** Argument Tests ******************************* */ + + private void performArgumentTest() throws Exception { + performTestInlineCall(fgTestSetup.getArgumentPackage(), getName(), COMPARE_WITH_OUTPUT, "argument_out"); + } + + public void testFieldReference() throws Exception { + performArgumentTest(); + } + + public void testLocalReferenceUnused() throws Exception { + performArgumentTest(); + } + + public void testLocalReferenceRead() throws Exception { + performArgumentTest(); + } + + public void testLocalReferenceRead2() throws Exception { + performArgumentTest(); + } + + public void testLocalReferenceWrite() throws Exception { + performArgumentTest(); + } + + public void testLocalReferenceLoop() throws Exception { + performArgumentTest(); + } + + public void testLocalReferenceLoop1() throws Exception { + performArgumentTest(); + } + + public void testLocalReferenceLoop2() throws Exception { + performArgumentTest(); + } + + public void testLocalReferenceLoop3() throws Exception { + performArgumentTest(); + } + + public void testLocalReferenceLoop4() throws Exception { + performArgumentTest(); + } + + public void testLocalReferenceLoop5() throws Exception { + performArgumentTest(); + } + + public void testLocalReferencePrefix() throws Exception { + performArgumentTest(); + } + + public void testLiteralReferenceRead() throws Exception { + performArgumentTest(); + } + + public void testLiteralReferenceWrite() throws Exception { + performArgumentTest(); + } + + public void testParameterNameUsed1() throws Exception { + performArgumentTest(); + } + + public void testParameterNameUsed2() throws Exception { + performArgumentTest(); + } + + public void testParameterNameUsed3() throws Exception { + performArgumentTest(); + } + + public void testParameterNameUsed4() throws Exception { + performArgumentTest(); + } + + public void testParameterNameUnused1() throws Exception { + performArgumentTest(); + } + + public void testParameterNameUnused2() throws Exception { + performArgumentTest(); + } + + public void testParameterNameUnused3() throws Exception { + performArgumentTest(); + } + + public void testOneRead() throws Exception { + performArgumentTest(); + } + + public void testTwoReads() throws Exception { + performArgumentTest(); + } + + public void testWrite() throws Exception { + performArgumentTest(); + } + + public void testArray() throws Exception { + performArgumentTest(); + } + + public void testVarargs() throws Exception { + performArgumentTest(); + } + + public void testVarargs2() throws Exception { + performArgumentTest(); + } + + public void testVarargs3() throws Exception { + performArgumentTest(); + } + + public void testVarargs4() throws Exception { + performArgumentTest(); + } + + public void testVarargs5() throws Exception { + performArgumentTest(); + } + + public void testVarargs6() throws Exception { + performArgumentTest(); + } + + public void test91470() throws Exception { + performArgumentTest(); + } + + /* *********************** Name Conflict Tests ******************************* */ + + private void performNameConflictTest() throws Exception { + performTestInlineCall(fgTestSetup.getNameConflictPackage(), getName(), COMPARE_WITH_OUTPUT, "nameconflict_out"); + } + + public void testSameLocal() throws Exception { + performNameConflictTest(); + } + + public void testSameType() throws Exception { + performNameConflictTest(); + } + + public void testSameTypeAfter() throws Exception { + performNameConflictTest(); + } + + public void testSameTypeInSibling() throws Exception { + performNameConflictTest(); + } + + public void testLocalInType() throws Exception { + performNameConflictTest(); + } + + public void testFieldInType() throws Exception { + performNameConflictTest(); + } + + public void testSwitchStatement() throws Exception { + performNameConflictTest(); + } + + public void testBlocks() throws Exception { + performNameConflictTest(); + } + + /* *********************** Call Tests ******************************* */ + + private void performCallTest() throws Exception { + performTestInlineCall(fgTestSetup.getCallPackage(), getName(), COMPARE_WITH_OUTPUT, "call_out"); + } + + public void testExpressionStatement() throws Exception { + performCallTest(); + } + + public void testExpressionStatementWithReturn() throws Exception { + performCallTest(); + } + + public void testStatementWithFunction1() throws Exception { + performCallTest(); + } + + public void testStatementWithFunction2() throws Exception { + performCallTest(); + } + + public void testParenthesis() throws Exception { + performCallTest(); + } + + /* *********************** Expression Tests ******************************* */ + + private void performExpressionTest() throws Exception { + performTestInlineCall(fgTestSetup.getExpressionPackage(), getName(), COMPARE_WITH_OUTPUT, "expression_out"); + } + + public void testSimpleExpression() throws Exception { + performExpressionTest(); + } + + public void testSimpleExpressionWithStatements() throws Exception { + performExpressionTest(); + } + + public void testSimpleBody() throws Exception { + performExpressionTest(); + } + + public void testAssignment() throws Exception { + performExpressionTest(); + } + + public void testReturnStatement() throws Exception { + performExpressionTest(); + } + + public void testConditionalExpression() throws Exception { + performExpressionTest(); + } + + /* *********************** Control Statements Tests ******************************* */ + + private void performControlStatementTest() throws Exception { + performTestInlineCall(fgTestSetup.getControlStatementPackage(), getName(), COMPARE_WITH_OUTPUT, "controlStatement_out"); + } + + public void testForEmpty() throws Exception { + performControlStatementTest(); + } + + public void testForOne() throws Exception { + performControlStatementTest(); + } + + public void testForTwo() throws Exception { + performControlStatementTest(); + } + + public void testEnhancedForOne() throws Exception { + performControlStatementTest(); + } + + public void testEnhancedForTwo() throws Exception { + performControlStatementTest(); + } + + public void testIfThenTwo() throws Exception { + performControlStatementTest(); + } + + public void testIfElseTwo() throws Exception { + performControlStatementTest(); + } + + public void testForAssignmentOne() throws Exception { + performControlStatementTest(); + } + + public void testForAssignmentTwo() throws Exception { + performControlStatementTest(); + } + + public void testLabelOne() throws Exception { + performControlStatementTest(); + } + + public void testLabelTwo() throws Exception { + performControlStatementTest(); + } + + public void testDanglingIf() throws Exception { + performControlStatementTest(); + } + + public void testIfWithVariable() throws Exception { + performControlStatementTest(); + } + + public void testDanglingIfBug229734() throws Exception { + performControlStatementTest(); + } + + public void testDanglingIfBug229734_2() throws Exception { + performControlStatementTest(); + } + + /* *********************** Receiver Tests ******************************* */ + + private void performReceiverTest() throws Exception { + performTestInlineCall(fgTestSetup.getReceiverPackage(), getName(), COMPARE_WITH_OUTPUT, "receiver_out"); + } + + private void performReceiverTestInlineMethod() throws Exception { + performTestInlineMethod(fgTestSetup.getReceiverPackage(), getName(), COMPARE_WITH_OUTPUT, "receiver_out"); + } + + public void testNoImplicitReceiver() throws Exception { + performReceiverTest(); + } + + public void testNameThisReceiver() throws Exception { + performReceiverTest(); + } + + public void testNameImplicitReceiver() throws Exception { + performReceiverTest(); + } + + public void testExpressionZeroImplicitReceiver() throws Exception { + performReceiverTest(); + } + + public void testExpressionOneImplicitReceiver() throws Exception { + performReceiverTest(); + } + + public void testExpressionTwoImplicitReceiver() throws Exception { + performReceiverTest(); + } + + public void testStaticReceiver() throws Exception { + performReceiverTest(); + } + + public void testReceiverWithStatic() throws Exception { + performReceiverTest(); + } + + public void testThisExpression() throws Exception { + performReceiverTest(); + } + + public void testFieldReceiver() throws Exception { + performReceiverTest(); + } + + public void testExplicitStaticThisFieldReceiver() throws Exception { + performReceiverTest(); + } + + public void testExplicitThisFieldReceiver() throws Exception { + performReceiverTest(); + } + + public void testExplicitStaticThisMethodReceiver() throws Exception { + performReceiverTest(); + } + + public void testExplicitThisMethodReceiver() throws Exception { + performReceiverTest(); + } + + public void testThisReceiver() throws Exception { + performReceiverTestInlineMethod(); + } + + public void testImplicitReceiverMethod() throws Exception { + performReceiverTest(); + } + + public void testImplicitReceiverField() throws Exception { + performReceiverTest(); + } + + public void testRemoteFieldReceiver() throws Exception { + performReceiverTest(); + } + + /* *********************** Import Tests ******************************* */ + + private void performImportTest() throws Exception { + performTestInlineCall(fgTestSetup.getImportPackage(), getName(), COMPARE_WITH_OUTPUT, "import_out"); + } + + public void testUseArray() throws Exception { + performImportTest(); + } + + public void testUseInArgument() throws Exception { + performImportTest(); + } + + public void testUseInClassLiteral() throws Exception { + performImportTest(); + } + + public void testUseInDecl() throws Exception { + performImportTest(); + } + + public void testUseInDecl2() throws Exception { + performImportTest(); + } + + public void testUseInDecl3() throws Exception { + performImportTest(); + } + + public void testUseInDeclClash() throws Exception { + performImportTest(); + } + + public void testUseInLocalClass() throws Exception { + performImportTest(); + } + + public void testStaticImport() throws Exception { + performImportTest(); + } + + public void testStaticImport2() throws Exception { + if (BUG_82166) { + System.out.println("Disabled static import test 2 due to bug 82166"); + return; + } + performImportTest(); + } + + /* *********************** Cast Tests ******************************* */ + + private void performCastTest() throws Exception { + performTestInlineCall(fgTestSetup.getCastPackage(), getName(), COMPARE_WITH_OUTPUT, "cast_out"); + } + + public void testNotOverloaded() throws Exception { + performCastTest(); + } + + public void testOverloadedPrimitives() throws Exception { + performCastTest(); + } + + public void testNotCastableOverloaded() throws Exception { + performCastTest(); + } + + public void testOverloaded() throws Exception { + performCastTest(); + } + + public void testHierarchyOverloadedPrimitives() throws Exception { + performCastTest(); + } + + public void testHierarchyOverloaded() throws Exception { + performCastTest(); + } + + public void testHierarchyOverloadedPrivate() throws Exception { + performCastTest(); + } + + public void testReceiverCast() throws Exception { + performCastTest(); + } + + public void testNoCast() throws Exception { + performCastTest(); + } + + /* *********************** Enum Tests ******************************* */ + + private void performEnumTest() throws Exception { + performTestInlineCall(fgTestSetup.getEnumPackage(), getName(), COMPARE_WITH_OUTPUT, "enum_out"); + } + + public void testBasic() throws Exception { + performEnumTest(); + } + + public void testAnonymousEnum() throws Exception { + performEnumTest(); + } + + /* *********************** Generic Tests ******************************* */ + + private void performGenericTest() throws Exception { + performTestInlineCall(fgTestSetup.getGenericPackage(), getName(), COMPARE_WITH_OUTPUT, "generic_out"); + } + + private void performGenericTestInlineMethod() throws Exception { + performTestInlineMethod(fgTestSetup.getGenericPackage(), getName(), COMPARE_WITH_OUTPUT, "generic_out"); + } + + public void testClassInstance() throws Exception { + performGenericTest(); + } + + public void testClassInstance2() throws Exception { + performGenericTestInlineMethod(); + } + + public void testSubClass1() throws Exception { + performGenericTest(); + } + + public void testSubClass2() throws Exception { + performGenericTest(); + } + + public void testMethodInstance1() throws Exception { + performGenericTest(); + } + + public void testMethodInstance2() throws Exception { + performGenericTest(); + } + + public void testMethodInstance3() throws Exception { + performGenericTestInlineMethod(); + } + + public void testParameterizedType1() throws Exception { + performGenericTest(); + } + + public void testParameterizedType2() throws Exception { + performGenericTest(); + } + + public void testParameterizedType3() throws Exception { + performGenericTest(); + } + + /* *********************** Binary Tests ******************************* */ + + public void testBinaryInlineSingle() throws Exception { // uses classes.Target# + performTestInlineCall(fgTestSetup.getBinaryPackage(), getName(), COMPARE_WITH_OUTPUT, "binary_out"); + } + + public void testBinaryInlineAll() throws Exception { // inlines all classes.Target2#logMessage(..) + String id= getName(); + ICompilationUnit unit= createCU(fgTestSetup.getBinaryPackage(), id); + IType target2type= unit.getJavaProject().findType("classes.Target2"); + IClassFile target2ClassFile= target2type.getClassFile(); + IMethod logMessage= target2type.getMethods()[1]; // method 0 is ctor + InlineMethodRefactoring refactoring= InlineMethodRefactoring.create( + target2ClassFile, + new RefactoringASTParser(AST.JLS3).parse(target2ClassFile, true), + logMessage.getNameRange().getOffset(), + logMessage.getNameRange().getLength()); + + assertFalse(refactoring.canEnableDeleteSource()); + refactoring.setCurrentMode(InlineMethodRefactoring.Mode.INLINE_ALL); + + String out= null; + switch (COMPARE_WITH_OUTPUT) { + case COMPARE_WITH_OUTPUT: + out= getProofedContent("binary_out", id); + break; + } + performTest(unit, refactoring, COMPARE_WITH_OUTPUT, out, true); + } + + public void testBinaryNoSource() throws Exception { + performTestInlineCall(fgTestSetup.getBinaryPackage(), getName(), INVALID_SELECTION, null); + } + + public void test_133575() throws Exception { // uses classes.BinEnum + performTestInlineCall(fgTestSetup.getBinaryPackage(), getName(), COMPARE_WITH_OUTPUT, "binary_out"); + } + + /* *********************** Operator Tests ******************************* */ + + private void performOperatorTest() throws Exception { + performTestInlineCall(fgTestSetup.getOperatorPackage(), getName(), COMPARE_WITH_OUTPUT, "operator_out"); + } + + public void testPlusPlus() throws Exception { + performOperatorTest(); + } + + public void testTimesPlus() throws Exception { + performOperatorTest(); + } + + public void testPrefixPlus() throws Exception { + performOperatorTest(); + } + + public void testPostfixPlus() throws Exception { + performOperatorTest(); + } + + public void testPlusTimes() throws Exception { + performOperatorTest(); + } + + public void testPlusPrefix() throws Exception { + performOperatorTest(); + } + + public void testPlusPostfix() throws Exception { + performOperatorTest(); + } + + public void testOperatorPredence() throws Exception { + AST ast= AST.newAST(AST.JLS3); + + int assignment= OperatorPrecedence.getExpressionPrecedence(ast.newAssignment()); + int conditional= OperatorPrecedence.getExpressionPrecedence(ast.newConditionalExpression()); + assertTrue(assignment < conditional); + + InfixExpression exp= ast.newInfixExpression(); + exp.setOperator(Operator.CONDITIONAL_OR); + int conditional_or= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(conditional < conditional_or); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.CONDITIONAL_AND); + int conditional_and= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(conditional_or < conditional_and); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.OR); + int bitwiseInclusiveOR= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(conditional_and < bitwiseInclusiveOR); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.XOR); + int bitwiseEnclusiveOR= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(bitwiseInclusiveOR < bitwiseEnclusiveOR); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.AND); + int bitwiseAnd= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(bitwiseEnclusiveOR < bitwiseAnd); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.EQUALS); + int equals= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(bitwiseAnd < equals); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.NOT_EQUALS); + int notEquals= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(equals == notEquals); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.LESS); + int less= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(notEquals < less); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.LESS_EQUALS); + int lessEquals= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(less == lessEquals); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.GREATER); + int greater= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(lessEquals == greater); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.GREATER_EQUALS); + int greaterEquals= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(greater == greaterEquals); + + int instance= OperatorPrecedence.getExpressionPrecedence(ast.newInstanceofExpression()); + assertTrue(greaterEquals == instance); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.LEFT_SHIFT); + int leftShift= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(instance < leftShift); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.RIGHT_SHIFT_SIGNED); + int rightShiftSigned= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(leftShift == rightShiftSigned); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.RIGHT_SHIFT_UNSIGNED); + int rightShiftUnSigned= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(rightShiftSigned == rightShiftUnSigned); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.PLUS); + int plus= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(rightShiftUnSigned < plus); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.MINUS); + int minus= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(plus == minus); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.TIMES); + int times= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(minus < times); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.DIVIDE); + int divide= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(times == divide); + + exp= ast.newInfixExpression(); + exp.setOperator(Operator.REMAINDER); + int remainder= OperatorPrecedence.getExpressionPrecedence(exp); + assertTrue(divide == remainder); + + int cast= OperatorPrecedence.getExpressionPrecedence(ast.newCastExpression()); + assertTrue(times < cast); + + int prefix= OperatorPrecedence.getExpressionPrecedence(ast.newPrefixExpression()); + assertTrue(cast < prefix); + + int postfix= OperatorPrecedence.getExpressionPrecedence(ast.newPostfixExpression()); + assertTrue(prefix < postfix); + + int newClass= OperatorPrecedence.getExpressionPrecedence(ast.newClassInstanceCreation()); + assertTrue(postfix == newClass); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineTempTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineTempTests.java new file mode 100644 index 000000000..671a352c7 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineTempTests.java @@ -0,0 +1,368 @@ +/******************************************************************************* + * Copyright (c) 2000, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.SourceRange; + +import org.eclipse.jdt.internal.corext.refactoring.code.InlineTempRefactoring; + +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +public class InlineTempTests extends RefactoringTest { + + private static final Class clazz= InlineTempTests.class; + private static final String REFACTORING_PATH= "InlineTemp/"; + + public InlineTempTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + private String getSimpleTestFileName(boolean canInline, boolean input){ + String fileName = "A_" + getName(); + if (canInline) + fileName += input ? "_in": "_out"; + return fileName + ".java"; + } + + private String getTestFileName(boolean canInline, boolean input){ + String fileName= TEST_PATH_PREFIX + getRefactoringPath(); + fileName += (canInline ? "canInline/": "cannotInline/"); + return fileName + getSimpleTestFileName(canInline, input); + } + + protected ICompilationUnit createCUfromTestFile(IPackageFragment pack, boolean canInline, boolean input) throws Exception { + return createCU(pack, getSimpleTestFileName(canInline, input), getFileContents(getTestFileName(canInline, input))); + } + + private ISourceRange getSelection(ICompilationUnit cu) throws Exception{ + String source= cu.getSource(); + int offset= source.indexOf(AbstractSelectionTestCase.SQUARE_BRACKET_OPEN); + int end= source.indexOf(AbstractSelectionTestCase.SQUARE_BRACKET_CLOSE); + return new SourceRange(offset, end - offset); + } + + private void helper1(ICompilationUnit cu, ISourceRange selection) throws Exception{ + InlineTempRefactoring ref= new InlineTempRefactoring(cu, selection.getOffset(), selection.getLength()); + if (ref.checkIfTempSelected().hasFatalError()) + ref= null; + RefactoringStatus result= performRefactoring(ref); + assertEquals("precondition was supposed to pass", null, result); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + assertEqualLines("incorrect inlining", getFileContents(getTestFileName(true, false)), newcu.getSource()); + } + + private void helper1(int startLine, int startColumn, int endLine, int endColumn) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + helper1(cu, selection); + } + + private void helper2() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), false, true); + helper2(cu, getSelection(cu)); + } + + private void helper2(ICompilationUnit cu, ISourceRange selection) throws Exception{ + InlineTempRefactoring ref= new InlineTempRefactoring(cu, selection.getOffset(), selection.getLength()); + if (ref.checkIfTempSelected().hasFatalError()) + ref= null; + if (ref != null){ + RefactoringStatus result= performRefactoring(ref); + assertNotNull("precondition was supposed to fail", result); + } + } + + private void helper2(int startLine, int startColumn, int endLine, int endColumn) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), false, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + helper2(cu, selection); + } + + + //--- tests + + public void test0() throws Exception{ + helper1(4, 9, 4, 18); + } + + public void test1() throws Exception{ + helper1(4, 9, 4, 18); + } + + public void test2() throws Exception{ + helper1(4, 9, 4, 18); + } + + public void test3() throws Exception{ + helper1(4, 9, 4, 22); + } + + public void test4() throws Exception{ + helper1(4, 9, 4, 22); + } + + public void test5() throws Exception{ + helper1(4, 9, 4, 22); + } + + public void test6() throws Exception{ + //printTestDisabledMessage("bug#6429 declaration source start incorrect on local variable"); + helper1(9, 13, 9, 14); + } + + public void test7() throws Exception{ + helper1(9, 9, 9, 18); + } + + public void test8() throws Exception{ + //printTestDisabledMessage("bug#6429 declaration source start incorrect on local variable"); + helper1(5, 13, 5, 14); + } + + public void test9() throws Exception{ + helper1(5, 9, 5, 21); + } + + public void test10() throws Exception{ +// printTestDisabledMessage("regression test for bug#9001"); + helper1(4, 21, 4, 25); + } + + public void test11() throws Exception{ + helper1(5, 21, 5, 25); + } + + public void test12() throws Exception{ + helper1(5, 15, 5, 19); + } + + public void test13() throws Exception{ + helper1(5, 17, 5, 18); + } + + public void test14() throws Exception{ +// printTestDisabledMessage("regression for bug 11664"); + helper1(4, 13, 4, 14); + } + + public void test15() throws Exception{ +// printTestDisabledMessage("regression for bug 11664"); + helper1(4, 19, 4, 20); + } + + public void test16() throws Exception{ +// printTestDisabledMessage("regression test for 10751"); + helper1(5, 17, 5, 24); + } + + public void test17() throws Exception{ +// printTestDisabledMessage("regression test for 12200"); + helper1(8, 18, 8, 21); + } + + public void test18() throws Exception{ +// printTestDisabledMessage("regression test for 12200"); + helper1(6, 18, 6, 21); + } + + public void test19() throws Exception{ +// printTestDisabledMessage("regression test for 12212"); + helper1(6, 19, 6, 19); + } + + public void test20() throws Exception{ +// printTestDisabledMessage("regression test for 16054"); + helper1(4, 17, 4, 18); + } + + public void test21() throws Exception{ +// printTestDisabledMessage("regression test for 17479"); + helper1(6, 20, 6, 25); + } + + public void test22() throws Exception{ +// printTestDisabledMessage("regression test for 18284"); + helper1(5, 13, 5, 17); + } + + public void test23() throws Exception{ +// printTestDisabledMessage("regression test for 22938"); + helper1(5, 16, 5, 20); + } + + public void test24() throws Exception{ +// printTestDisabledMessage("regression test for 26242"); + helper1(5, 19, 5, 24); + } + + public void test25() throws Exception{ +// printTestDisabledMessage("regression test for 26242"); + helper1(5, 19, 5, 24); + } + + public void test26() throws Exception{ + helper1(5, 17, 5, 24); + } + + public void test27() throws Exception{ + helper1(5, 22, 5, 29); + } + + public void test28() throws Exception{ + helper1(11, 14, 11, 21); + } + + public void test29() throws Exception{ + helper1(4, 8, 4, 11); + } + + public void test30() throws Exception{ + helper1(4, 8, 4, 11); + } + + public void test31() throws Exception{ + helper1(8, 30, 8, 30); + } + + public void test32() throws Exception{ + helper1(10, 27, 10, 27); + } + + public void test33() throws Exception{ + // add explicit cast for primitive types: https://bugs.eclipse.org/bugs/show_bug.cgi?id=46216 + helper1(5, 14, 5, 15); + } + + public void test34() throws Exception{ + // add explicit cast for boxing: https://bugs.eclipse.org/bugs/show_bug.cgi?id=201434#c4 + helper1(5, 17, 5, 17); + } + + public void test35() throws Exception{ + // add explicit cast for unchecked conversion: https://bugs.eclipse.org/bugs/show_bug.cgi?id=201434#c0 + helper1(7, 32, 7, 36); + } + + public void test36() throws Exception{ + // parenthesize complex cast expression + helper1(8, 21, 8, 24); + } + + public void test37() throws Exception{ + // parameterized method invocation needs class expression: https://bugs.eclipse.org/bugs/show_bug.cgi?id=277968 + helper1(5, 16, 5, 17); + } + + public void test38() throws Exception{ + // parameterized method invocation needs this expression: https://bugs.eclipse.org/bugs/show_bug.cgi?id=277968 + helper1(5, 16, 5, 17); + } + + public void test39() throws Exception{ + // parameterized method invocation needs to keep super expression: https://bugs.eclipse.org/bugs/show_bug.cgi?id=277968 + helper1(5, 16, 5, 17); + } + + public void test40() throws Exception{ + // better cast for unboxing: https://bugs.eclipse.org/bugs/show_bug.cgi?id=297868 + helper1(5, 43, 5, 46); + } + + //------ + + public void testFail0() throws Exception{ + printTestDisabledMessage("compile errors are ok now"); +// helper2(); + } + + public void testFail1() throws Exception{ + printTestDisabledMessage("compile errors are ok now"); +// helper2(); + } + + public void testFail2() throws Exception{ + helper2(); + } + + public void testFail3() throws Exception{ + helper2(); + } + + public void testFail4() throws Exception{ + helper2(); + } + + public void testFail5() throws Exception{ + helper2(); + } + + public void testFail6() throws Exception{ + helper2(); + } + + public void testFail7() throws Exception{ + helper2(); + } + + public void testFail8() throws Exception{ + helper2(); + } + + public void testFail9() throws Exception{ + //test for 16737 + helper2(3, 9, 3, 13); + } + + public void testFail10() throws Exception{ + //test for 16737 + helper2(3, 5, 3, 17); + } + + public void testFail11() throws Exception{ + //test for 17253 + helper2(8, 14, 8, 18); + } + + public void testFail12() throws Exception{ + //test for 19851 + helper2(10, 16, 10, 19); + } + + public void testFail13() throws Exception{ +// printTestDisabledMessage("12106"); + helper2(4, 18, 4, 19); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceFactoryTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceFactoryTests.java new file mode 100644 index 000000000..de4e2d130 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceFactoryTests.java @@ -0,0 +1,744 @@ +/******************************************************************************* + * Copyright (c) 2000, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.SourceRange; + +import org.eclipse.jdt.internal.corext.refactoring.code.IntroduceFactoryRefactoring; + +/** + * @author rfuhrer@watson.ibm.com + */ +public class IntroduceFactoryTests extends RefactoringTest { + + private static final Class clazz= IntroduceFactoryTests.class; + private static final String REFACTORING_PATH= "IntroduceFactory/"; + + public IntroduceFactoryTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new Java16Setup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new Java16Setup(someTest); + } + + /** + * Produces a test file name based on the name of this JUnit testcase. + * For input files, trims off the trailing part of the test name that + * begins with a '_', to get rid of the options part, so that we can + * have a single (suite of) input file(s) but several outputs dependent + * on the option settings. + * @param input true iff the requested file is an input file. + * @return the name of the test file, with a trailing "_in.java" if an input + * file and a trailing "_XXX.java" if an output file and the test name/options + * are "_XXX". + */ + private String getSimpleTestFileName(boolean input) { + String testName = getName(); + int usIdx= testName.indexOf('_'); + int endIdx= (usIdx >= 0) ? usIdx : testName.length(); + String fileName = (input ? (testName.substring(4, endIdx) + "_in") : testName.substring(4)); + + return fileName + ".java"; + } + + /** + * Produces a test file name based on the name of this JUnit testcase, + * like getSimpleTestFileName(), but also prepends the appropriate version + * of the resource path (depending on the value of <code>positive</code>). + * Test files are assumed to be located in the resources directory. + * @param positive true iff the requested file is for a positive unit test + * @param input true iff the requested file is an input file + * @return the test file name + */ + private String getTestFileName(boolean positive, boolean input) { + String path= TEST_PATH_PREFIX + getRefactoringPath(); + + path += (positive ? "positive/": "negative/"); + return path + getSimpleTestFileName(input); + } + + /** + * Produces a compilation unit from an input source file whose name + * is based on the testcase name. + * Test files are assumed to be located in the resources directory. + * @param pack + * @param positive + * @param input + * @return the ICompilationUnit created from the specified test file + * @throws Exception + */ + private ICompilationUnit createCUForSimpleTest(IPackageFragment pack, + boolean positive, boolean input) + throws Exception + { + String fileName= getTestFileName(positive, input); + String cuName= getSimpleTestFileName(input); + + return createCU(pack, cuName, getFileContents(fileName)); + } + + /** + * Produces a test file name based on the name of this JUnit testcase, + * like getSimpleTestFileName(), but also prepends the appropriate version + * of the resource path (depending on the value of <code>positive</code>). + * Test files are assumed to be located in the resources directory. + * @param project the project + * @param pack the package fragment + * @param fileName the file name + * @param input true iff the requested file is an input file + * @return the test file name + */ + private String getBugTestFileName(IJavaProject project, IPackageFragment pack, String fileName, boolean input) { + String testName= getName(); + String testNumber= testName.substring("test".length());//$NON-NLS-1$ + String path= TEST_PATH_PREFIX + getRefactoringPath() + "Bugzilla/" + testNumber + "/" + + (project == null ? "" : project.getElementName() + "/") + + (pack == getPackageP() ? "" : pack.getElementName() + "/"); + + return path + fileName + (input ? "" : "_out") + ".java";//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + /** + * Produces a compilation unit from an input source file whose path + * is based on the testcase name, but whose basename is supplied by + * the caller. + * Test files are assumed to be located in the resources directory. + * @param project can be null if only 1 project exists in the test workspace + * @param pack + * @param baseName + * @param input + * @return the ICompilationUnit created from the specified test file + * @throws Exception + */ + private ICompilationUnit createCUForBugTestCase(IJavaProject project, + IPackageFragment pack, String baseName, boolean input) + throws Exception + { + String fileName= getBugTestFileName(project, pack, baseName, input); + String cuName= baseName + (input ? "" : "_out") + ".java"; + + return createCU(pack, cuName, getFileContents(fileName)); + } + + static final String SELECTION_START_HERALD= "/*[*/"; + static final String SELECTION_END_HERALD= "/*]*/"; + + /** + * Finds and returns the selection markers in the given source string, + * i.e. the first occurrences of <code>SELECTION_START_HERALD</code> and + * <code>SELECTION_END_HERALD</code>. Fails an assertion if either of these + * markers is not present in the source string. + * @param source + * @return an ISourceRange representing the marked selection + * @throws Exception + */ + private ISourceRange findSelectionInSource(String source) throws Exception { + int begin= source.indexOf(SELECTION_START_HERALD) + SELECTION_START_HERALD.length(); + int end= source.indexOf(SELECTION_END_HERALD); + + if (begin < SELECTION_START_HERALD.length()) + assertTrue("No selection start comment in input source file!", false); + if (end < 0) + assertTrue("No selection end comment in input source file!", false); + + return new SourceRange(begin, end-begin); + } + + private void doSingleUnitTest(boolean protectConstructor, ICompilationUnit cu, String outputFileName) throws Exception, JavaModelException, IOException { + ISourceRange selection= findSelectionInSource(cu.getSource()); + IntroduceFactoryRefactoring ref= new IntroduceFactoryRefactoring(cu, selection.getOffset(), selection.getLength()); + + ref.setProtectConstructor(protectConstructor); + + RefactoringStatus activationResult= ref.checkInitialConditions(new NullProgressMonitor()); + + assertTrue("activation was supposed to be successful", activationResult.isOK()); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + + if (!checkInputResult.isOK()) { + performChange(ref, false); + + String newSource = cu.getSource(); + + System.err.println("!!!Precondition failed for " + getName() + "!!!"); + System.err.println("Compile-time error: " + checkInputResult.toString()); + System.err.println("Offending source:"); + System.err.print(newSource); + assertTrue("precondition was supposed to pass but was " + checkInputResult.toString(), false); + } + + performChange(ref, false); + + String newSource = cu.getSource(); + + assertEqualLines(getName() + ": ", getFileContents(outputFileName), newSource); + } + + /** + * Tests the IntroduceFactoryRefactoring refactoring on a single input source file + * whose name is the test name (minus the "test" prefix and any trailing + * options indicator such as "_FFF"), and compares the transformed code + * to a source file whose name is the test name (minus the "test" prefix). + * Test files are assumed to be located in the resources directory. + * @param protectConstructor true iff IntroduceFactoryRefactoring should make the constructor private + * @throws Exception + */ + void singleUnitHelper(boolean protectConstructor) + throws Exception + { + ICompilationUnit cu= createCUForSimpleTest(getPackageP(), true, true); + + doSingleUnitTest(protectConstructor, cu, getTestFileName(true, false)); + } + + /** + * Tests the IntroduceFactoryRefactoring refactoring on a single input source file + * whose name is the test name (minus the "test" prefix and any trailing + * options indicator such as "_FFF"), and compares the transformed code + * to a source file whose name is the test name (minus the "test" prefix). + * Test files are assumed to be located in the resources directory. + * @param baseFileName the base file name + * @param protectConstructor true iff IntroduceFactoryRefactoring should make the constructor private + * @throws Exception + */ + protected void singleUnitBugHelper(String baseFileName, boolean protectConstructor) + throws Exception + { + ICompilationUnit cu= createCUForBugTestCase(null, getPackageP(), baseFileName, true); + + doSingleUnitTest(protectConstructor, cu, getBugTestFileName(null, getPackageP(), baseFileName, false)); + } + + /** + * Like singleUnitHelper(), but allows for the specification of the names of + * the generated factory method, class, and interface, as appropriate. + * @param factoryMethodName the name to use for the generated factory method + * @param factoryClassName the name of the factory class + * @throws Exception + */ + void namesHelper(String factoryMethodName, String factoryClassName) + throws Exception + { + ICompilationUnit cu= createCUForSimpleTest(getPackageP(), true, true); + ISourceRange selection= findSelectionInSource(cu.getSource()); + IntroduceFactoryRefactoring ref= new IntroduceFactoryRefactoring(cu, selection.getOffset(), selection.getLength()); + + RefactoringStatus activationResult= ref.checkInitialConditions(new NullProgressMonitor()); + + assertTrue("activation was supposed to be successful", activationResult.isOK()); + + if (factoryMethodName != null) + ref.setNewMethodName(factoryMethodName); + if (factoryClassName != null) + ref.setFactoryClass(factoryClassName); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + + assertTrue("precondition was supposed to pass but was " + checkInputResult.toString(), checkInputResult.isOK()); + + performChange(ref, false); + + String newSource = cu.getSource(); + + assertEqualLines(getName() + ": ", getFileContents(getTestFileName(true, false)), newSource); + } + + /** + * Creates a compilation unit for a source file with a given base name (plus + * "_in" suffix) in the given package. The source file is assumed to be + * located in the test resources directory.<br> + * Currently only handles positive tests. + * @param fileName the base name of the source file (minus the "_in" suffix) + * @param pack an IPackageFragment for the containing package + * @return the ICompilationUnit for the newly-created unit + * @throws Exception + */ + private ICompilationUnit createCUFromFileName(String fileName, IPackageFragment pack) throws Exception { + String fullName = TEST_PATH_PREFIX + getRefactoringPath() + "positive/" + fileName + "_in.java"; + + return createCU(pack, fileName + "_in.java", getFileContents(fullName)); + } + + private void doMultiUnitTest(ICompilationUnit[] CUs, String testPath, String[] outputFileBaseNames, String factoryClassName) throws Exception, JavaModelException, IOException { + ISourceRange selection= findSelectionInSource(CUs[0].getSource()); + IntroduceFactoryRefactoring ref= new IntroduceFactoryRefactoring(CUs[0], selection.getOffset(), selection.getLength()); + + RefactoringStatus activationResult= ref.checkInitialConditions(new NullProgressMonitor()); + + assertTrue("activation was supposed to be successful", activationResult.isOK()); + + if (factoryClassName != null) + ref.setFactoryClass(factoryClassName); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + + assertTrue("precondition was supposed to pass but was " + checkInputResult.toString(), checkInputResult.isOK()); + + performChange(ref, false); + + String testName= getName(); + + for (int i = 0; i < CUs.length; i++) { + int optIdx= testName.indexOf("_"); + String testOptions= (optIdx >= 0) ? testName.substring(optIdx) : ""; + String outFileName= testPath + outputFileBaseNames[i] + testOptions + "_out.java"; + String xformedSrc= CUs[i].getSource(); + String expectedSrc= getFileContents(outFileName); + + assertEqualLines(getName() + ": ", expectedSrc, xformedSrc); + } + } + + /** + * Tests the IntroduceFactoryRefactoring refactoring on a set of input source files + * whose names are supplied in the <code>fileBaseNames</code> argument, + * and compares the transformed code to source files whose names are + * the input base names plus the options suffix (e.g. "_FFF"). + * Test files are assumed to be located in the resources directory. + * @param staticFactoryMethod true iff IntroduceFactoryRefactoring should make the factory method static + * @param inputFileBaseNames an array of input source file base names + * @throws Exception + */ + void multiUnitHelper(boolean staticFactoryMethod, String[] inputFileBaseNames) + throws Exception + { + IPackageFragment pkg= getPackageP(); + ICompilationUnit CUs[]= new ICompilationUnit[inputFileBaseNames.length]; + + for (int i = 0; i < inputFileBaseNames.length; i++) + CUs[i] = createCUFromFileName(inputFileBaseNames[i], pkg); + + String testPath= TEST_PATH_PREFIX + getRefactoringPath() + "positive/"; + + doMultiUnitTest(CUs, testPath, inputFileBaseNames, null); + } + + /** + * Tests the IntroduceFactoryRefactoring refactoring on a set of input source files + * whose names are supplied in the <code>fileBaseNames</code> argument, + * and compares the transformed code to source files whose names are + * the input base names plus the options suffix (e.g. "_FFF"). + * Test files are assumed to be located in the resources directory. + * @param staticFactoryMethod true iff IntroduceFactoryRefactoring should make the factory method static + * @param inputFileBaseNames an array of input source file base names + * @param factoryClassName the fully-qualified name of the class to receive the factory method, or null + * if the factory method is to be placed on the class defining the given constructor + * @throws Exception + */ + void multiUnitBugHelper(boolean staticFactoryMethod, String[] inputFileBaseNames, String factoryClassName) + throws Exception + { + ICompilationUnit CUs[]= new ICompilationUnit[inputFileBaseNames.length]; + + for(int i= 0; i < inputFileBaseNames.length; i++) { + int pkgEnd= inputFileBaseNames[i].lastIndexOf('/')+1; + boolean explicitPkg= (pkgEnd > 0); + IPackageFragment pkg= explicitPkg ? getRoot().createPackageFragment(inputFileBaseNames[i].substring(0, pkgEnd-1), true, new NullProgressMonitor()) : getPackageP(); + + CUs[i]= createCUForBugTestCase(null, pkg, inputFileBaseNames[i].substring(pkgEnd), true); + } + + String testName= getName(); + String testNumber= testName.substring("test".length()); + String testPath= TEST_PATH_PREFIX + getRefactoringPath() + "Bugzilla/" + testNumber + "/"; + + doMultiUnitTest(CUs, testPath, inputFileBaseNames, factoryClassName); + } + + void multiProjectBugHelper(String[] inputFileBaseNames, String[] dependencies) throws Exception { + Map/*<String,Set<String>>*/ projName2PkgNames= collectProjectPackages(inputFileBaseNames); + Map/*<String,IJavaProject>*/ projName2Project= new HashMap(); + Map/*<IJavaProject,IPackageFragmentRoot>*/ proj2PkgRoot= new HashMap(); + + try { + createProjectPackageStructure(projName2PkgNames, projName2Project, proj2PkgRoot); + + ICompilationUnit[] CUs= createCUs(inputFileBaseNames, projName2Project, proj2PkgRoot); + + addProjectDependencies(dependencies, projName2Project); + + String testName= getName(); + String testNumber= testName.substring("test".length()); + String testPath= TEST_PATH_PREFIX + getRefactoringPath() + "Bugzilla/" + testNumber + "/"; + + doMultiUnitTest(CUs, testPath, inputFileBaseNames, null); + + } finally { + for (Iterator iter= proj2PkgRoot.keySet().iterator(); iter.hasNext();) { + IJavaProject project= (IJavaProject) iter.next(); + if (project.exists()) { + try { + project.getProject().delete(true, null); + } catch (CoreException e) { + // swallow exception to avoid destroying the original one + e.printStackTrace(); + } + } + } + } + } + + private ICompilationUnit[] createCUs(String[] inputFileBaseNames, Map projName2Project, Map proj2PkgRoot) throws Exception { + ICompilationUnit CUs[]= new ICompilationUnit[inputFileBaseNames.length]; + + for(int i= 0; i < inputFileBaseNames.length; i++) { + String filePath= inputFileBaseNames[i]; + + int projEnd= filePath.indexOf('/'); + int pkgEnd= filePath.lastIndexOf('/'); + int fileBegin= pkgEnd+1; + + String projName= filePath.substring(0, projEnd); + String pkgName= filePath.substring(projEnd+1, pkgEnd).replace('/', '.'); + + IJavaProject project= (IJavaProject) projName2Project.get(projName); + IPackageFragmentRoot root= (IPackageFragmentRoot) proj2PkgRoot.get(project); + IPackageFragment pkg= root.getPackageFragment(pkgName); + + CUs[i]= createCUForBugTestCase(project, pkg, filePath.substring(fileBegin), true); + } + return CUs; + } + + private void addProjectDependencies(String[] dependencies, Map projName2Project) throws JavaModelException { + for(int i= 0; i < dependencies.length; i++) { + // dependent:provider + String dependency= dependencies[i]; + int colonIdx= dependency.indexOf(':'); + String depName= dependency.substring(0, colonIdx); + String provName= dependency.substring(colonIdx+1); + + IJavaProject depProj= (IJavaProject) projName2Project.get(depName); + IJavaProject provProj= (IJavaProject) projName2Project.get(provName); + + JavaProjectHelper.addRequiredProject(depProj, provProj); + } + } + + private void createProjectPackageStructure(Map projName2PkgNames, Map projName2Project, Map proj2PkgRoot) throws CoreException, JavaModelException { + for(Iterator iter= projName2PkgNames.keySet().iterator(); iter.hasNext(); ) { + String projName= (String) iter.next(); + Set/*<String>*/ projPkgNames= (Set) projName2PkgNames.get(projName); + + IJavaProject project= JavaProjectHelper.createJavaProject(projName, "bin"); + IPackageFragmentRoot root= JavaProjectHelper.addSourceContainer(project, CONTAINER); + + JavaProjectHelper.addRTJar(project); + + Set/*<IPackageFragment>*/ pkgs= new HashSet(); + + projName2Project.put(projName, project); + proj2PkgRoot.put(project, root); + for(Iterator pkgIter= projPkgNames.iterator(); pkgIter.hasNext(); ) { + String pkgName= (String) pkgIter.next(); + + pkgs.add(root.createPackageFragment(pkgName, true, null)); + } + } + } + + private Map/*<String,Set<String>>*/ collectProjectPackages(String[] inputFileBaseNames) { + Map/*<String,Set<String>>*/ proj2Pkgs= new HashMap(); + + for(int i= 0; i < inputFileBaseNames.length; i++) { + String filePath= inputFileBaseNames[i]; + int projEnd= filePath.indexOf('/'); + String projName= filePath.substring(0, projEnd); + String pkgName= filePath.substring(projEnd+1, filePath.lastIndexOf('/')); + + Set/*<String>*/ projPkgs= (Set) proj2Pkgs.get(projName); + + if (projPkgs == null) + proj2Pkgs.put(projName, projPkgs= new HashSet()); + projPkgs.add(pkgName); + } + return proj2Pkgs; + } + + private void failHelper(int expectedStatus) throws Exception { + ICompilationUnit cu= createCUForSimpleTest(getPackageP(), false, true); + ISourceRange selection= findSelectionInSource(cu.getSource()); + IntroduceFactoryRefactoring ref= new IntroduceFactoryRefactoring(cu, selection.getOffset(), selection.getLength()); + RefactoringStatus result= performRefactoring(ref); + + assertNotNull("precondition was supposed to fail", result); + assertEquals("status", expectedStatus, result.getSeverity()); + } + + //--- TESTS + public void testStaticContext_FFF() throws Exception { + singleUnitHelper(false); + } + // + // ================================================================================ + // + public void testInstanceContext_FFF() throws Exception { + singleUnitHelper(false); + } + // + // ================================================================================ + // + static final String[] k_Names = { "createThing", "ThingFactory", "IThingFactory" }; + + public void testNames_FFF() throws Exception { + namesHelper(k_Names[0], null); + } + // + // ================================================================================ + // + public void testMultipleCallers_FFF() throws Exception { + singleUnitHelper(false); + } + // + // ================================================================================ + // + public void testSelectConstructor() throws Exception { + singleUnitHelper(false); + } + // + // ================================================================================ + // + public void testDifferentSigs() throws Exception { + singleUnitHelper(false); + } + + public void testDifferentArgs1() throws Exception { + singleUnitHelper(false); + } + + public void testDifferentArgs2() throws Exception { + singleUnitHelper(false); + } + + public void testDifferentArgs3() throws Exception { + singleUnitHelper(false); + } + // + // ================================================================================ + // + public void testUnmovableArg1() throws Exception { + singleUnitHelper(false); + } + + public void testUnmovableArg2() throws Exception { + singleUnitHelper(false); + } + + public void testDontMoveArgs1() throws Exception { + singleUnitHelper(false); + } + + public void testDontMoveArgs2() throws Exception { + singleUnitHelper(false); + } + // + // ================================================================================ + // + public void testProtectConstructor1() throws Exception { + singleUnitHelper(true); + } + + public void testProtectConstructor2() throws Exception { + singleUnitHelper(true); + } + // + // ================================================================================ + // + public void testStaticInstance() throws Exception { + singleUnitHelper(false); + } + // + // ================================================================================ + // + public void testCtorThrows() throws Exception { + singleUnitHelper(true); + } + // + // ================================================================================ + // + public void testJavadocRef() throws Exception { + singleUnitHelper(true); + } + // + // ================================================================================ + // + public void testNestedClass() throws Exception { + failHelper(RefactoringStatus.FATAL); + } + + + + // + // ================================================================================ + // Generics-related tests + public void testTypeParam() throws Exception { + singleUnitHelper(true); + } + + public void testTwoTypeParams() throws Exception { + singleUnitHelper(true); + } + + public void testBoundedTypeParam() throws Exception { + singleUnitHelper(true); + } + + public void testTwoBoundedTypeParams() throws Exception { + singleUnitHelper(true); + } + + public void testWildcardParam() throws Exception { + singleUnitHelper(true); + } + + public void testTypeParam2() throws Exception { + namesHelper(null, "p.Factory"); + } + // + // ================================================================================ + // Other J2SE 5.0 tests + public void testEnum() throws Exception { + failHelper(RefactoringStatus.FATAL); + } + + public void testAnnotation1() throws Exception { + singleUnitHelper(true); + } + + public void testAnnotation2() throws Exception { + singleUnitHelper(true); + } + + public void testAnnotation3() throws Exception { + singleUnitHelper(true); + } + + public void testVarArgsCtor() throws Exception { + // RMF - As of I20050202, search engine doesn't reliably find call sites to varargs methods + singleUnitHelper(true); + } + // + // ================================================================================ + // + public void testMultipleUnits_FFF() throws Exception { + multiUnitHelper(false, new String[] { "MultiUnit1A", "MultiUnit1B", "MultiUnit1C" }); + } + // + // ================================================================================ + // Bugzilla bug regression tests + // ================================================================================ + // + public void test45942() throws Exception { + multiUnitBugHelper(true, new String[] { "TestClass", "UseTestClass" }, null); + } + + public void test46189() throws Exception { + singleUnitBugHelper("TestClass", true); + } + + public void test46189B() throws Exception { + singleUnitBugHelper("TestClass", true); + } + + public void test46373() throws Exception { + singleUnitBugHelper("ImplicitCtor", false); + } + + public void test46374() throws Exception { + singleUnitBugHelper("QualifiedName", false); + } + + public void test46608() throws Exception { + multiUnitBugHelper(true, new String[] { "p1/TT", "p2/TT" }, null); + } + + public void test59284() throws Exception { + singleUnitBugHelper("ArgTypeImport", true); + } + + public void test59280() throws Exception { + singleUnitBugHelper("ExplicitSuperCtorCall", true); + } + + public void test48504() throws Exception { + multiUnitBugHelper(true, new String[] { "p1/A", "p1/B" }, "p1.B"); + } + + public void test58293() throws Exception { + singleUnitBugHelper("ImplicitSuperCtorCall", true); + } + + public void test59283() throws Exception { + multiProjectBugHelper(new String[] { "proj1/pA/A", "proj2/pB/B" }, + new String[] { "proj2:proj1" }); + } + + public void test84807() throws Exception { + singleUnitBugHelper("CtorOfParamType", true); + } + + public void test85465() throws Exception { + singleUnitBugHelper("Varargs1", true); + } + + public void test97507() throws Exception { + singleUnitBugHelper("CtorTypeArgBounds", true); + } + + public void test250660() throws Exception { + singleUnitBugHelper("HasAnonymous", true); + } + + public void test74759() throws Exception { + singleUnitBugHelper("Test", true); + } + + public void test298281() throws Exception { + singleUnitBugHelper("Thing", true); + } + + public void testFactoryClash() throws Exception { + failHelper(RefactoringStatus.ERROR); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceIndirectionTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceIndirectionTests.java new file mode 100644 index 000000000..425c1ba7f --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceIndirectionTests.java @@ -0,0 +1,302 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.IOException; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.internal.corext.refactoring.code.IntroduceIndirectionRefactoring; + +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +public class IntroduceIndirectionTests extends RefactoringTest { + + private static final Class clazz= IntroduceIndirectionTests.class; + private static final String REFACTORING_PATH= "IntroduceIndirection/"; + + public IntroduceIndirectionTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + /** + * + * Invokes the introduce indirection ref. Some pointers: + * + * @param topLevelName This is an array of fully qualified top level(!) type names with exactly one package prefix (e.g. "p.Foo"). + * Simple names must correspond to .java files. + * The first cu will be used for the invocation of the refactoring (see positioning) + * @param newName name of indirection method + * @param qTypeName qualified type name of the type for the indirection method. Should be one of the cus in topLevelName. + * @param startLine starting line of selection in topLevelName[0] + * @param startColumn starting column of selection in topLevelName[0] + * @param endLine ending line of selection in topLevelName[0] + * @param endColumn ending column of selection in topLevelName[0] + * @param updateReferences true if references should be updated + * @param shouldWarn if true, warnings will be expected in the result + * @param shouldError if true, errors will be expected in the result + * @param shouldFail if true, fatal errors will be expected in the result + * @throws Exception + * @throws JavaModelException + * @throws CoreException + * @throws IOException + */ + private void helper(String[] topLevelName, String newName, String qTypeName, int startLine, int startColumn, int endLine, int endColumn, boolean updateReferences, boolean shouldWarn, + boolean shouldError, boolean shouldFail) throws Exception, JavaModelException, CoreException, IOException { + ICompilationUnit[] cu= new ICompilationUnit[topLevelName.length]; + for (int i= 0; i < topLevelName.length; i++) { + String packName= topLevelName[i].substring(0, topLevelName[i].indexOf('.')); + String className= topLevelName[i].substring(topLevelName[i].indexOf('.') + 1); + IPackageFragment cPackage= getRoot().createPackageFragment(packName, true, null); + cu[i]= createCUfromTestFile(cPackage, className); + } + + ISourceRange selection= TextRangeUtil.getSelection(cu[0], startLine, startColumn, endLine, endColumn); + try { + IntroduceIndirectionRefactoring ref= new IntroduceIndirectionRefactoring(cu[0], selection.getOffset(), selection.getLength()); + ref.setEnableUpdateReferences(updateReferences); + if (qTypeName != null) + ref.setIntermediaryClassName(qTypeName); + if (newName != null) + ref.setIntermediaryMethodName(newName); + + boolean failed= false; + RefactoringStatus status= performRefactoringWithStatus(ref); + if (status.hasFatalError()) { + assertTrue("Failed but shouldn't: " + status.getMessageMatchingSeverity(RefactoringStatus.FATAL), shouldFail); + failed= true; + } else + assertFalse("Didn't fail although expected", shouldFail); + + if (!failed) { + + if (status.hasError()) + assertTrue("Had errors but shouldn't: " + status.getMessageMatchingSeverity(RefactoringStatus.ERROR), shouldError); + else + assertFalse("No error although expected", shouldError); + + if (status.hasWarning()) + assertTrue("Had warnings but shouldn't: " + status.getMessageMatchingSeverity(RefactoringStatus.WARNING), shouldWarn); + else + assertFalse("No warning although expected", shouldWarn); + + for (int i= 0; i < topLevelName.length; i++) { + String className= topLevelName[i].substring(topLevelName[i].indexOf('.') + 1); + assertEqualLines("invalid output.", getFileContents(getOutputTestFileName(className)), cu[i].getSource()); + } + } + } finally { + performDummySearch(); + for (int i= 0; i < topLevelName.length; i++) + cu[i].delete(true, null); + } + } + + private void helperPass(String[] topLevelName, String newName, String target, int startLine, int startColumn, int endLine, int endColumn) throws Exception { + helper(topLevelName, newName, target, startLine, startColumn, endLine, endColumn, true, false, false, false); + } + + private void helperWarn(String[] topLevelName, String newName, String target, int startLine, int startColumn, int endLine, int endColumn) throws Exception { + helper(topLevelName, newName, target, startLine, startColumn, endLine, endColumn, true, true, false, false); + } + + private void helperErr(String[] topLevelName, String newName, String target, int startLine, int startColumn, int endLine, int endColumn) throws Exception { + helper(topLevelName, newName, target, startLine, startColumn, endLine, endColumn, true, true, true, false); + } + + private void helperFail(String[] topLevelName, String newName, String target, int startLine, int startColumn, int endLine, int endColumn) throws Exception { + helper(topLevelName, newName, target, startLine, startColumn, endLine, endColumn, true, true, true, true); + } + + public void test01() throws Exception { + // very simple test + helperPass(new String[] { "p.Foo" }, "bar", "p.Foo", 7, 10, 7, 13); + } + + public void test02() throws Exception { + // warning if a super call is found + helperWarn(new String[] { "p.A", "p.B" }, "bar", "p.A", 8, 15, 8, 18); + } + + public void test03() throws Exception { + // add imports to target + helperPass(new String[] { "p.Foo", "p.Bar" }, "bar", "p.Bar", 8, 17, 8, 20); + } + + public void test04() throws Exception { + // this qualification with outer type, method declaration is in outer type. + helperPass(new String[] { "p.Foo" }, "bar", "p.Foo", 10, 17, 10, 20); + } + + public void test05() throws Exception { + // this qualification with outer type, method declaration is in + // super type of outer type + helperPass(new String[] { "p.Foo", "p.Bar" }, "bar", "p.Foo", 12, 17, 12, 27); + } + + public void test06() throws Exception { + // this qualification with the current type, method declaration is + // in super type of current type + helperPass(new String[] { "p.Foo", "p.Bar" }, "bar", "p.Foo", 10, 13, 10, 23); + } + + public void test07() throws Exception { + // test qualification with anonymous type (=> warning, don't update) + helperWarn(new String[] { "p.E1" }, "bar", "p.E1", 30, 16, 30, 19); + } + + public void test08() throws Exception { + // open hierarchy failure + helperFail(new String[] { "p.SeaLevel", "p.Eiger", "p.Moench" }, "bar", "p.SeaLevel", 13, 11, 13, 14); + } + + public void test09() throws Exception { + // create static intermediary + helperPass(new String[] { "p.Foo" }, "bar", "p.Foo", 7, 17, 7, 20); + } + + public void test10() throws Exception { + // error, method already exists + helperErr(new String[] { "p.Foo", "p.Bar" }, "foo", "p.Foo", 10, 19, 10, 22); + } + + public void test11() throws Exception { + // test name clash with existing argument + helperPass(new String[] { "p.Foo" }, "bar", "p.Foo", 12, 9, 12, 12); + } + + public void test12() throws Exception { + // cannot put the intermediary into an inner non-static type + helperFail(new String[] { "p.Foo" }, "bar", "p.Foo.Inner", 9, 10, 9, 13); + } + + public void test13() throws Exception { + // create intermediary inside nested static types + helperPass(new String[] { "p.Foo", "p.Bar" }, "bar", "p.Foo.Inner.MoreInner", 13, 10, 13, 13); + } + + public void test14() throws Exception { + // raise visibility of target so intermediary sees it. + helperWarn(new String[] { "p0.Foo", "p1.Bar" }, "bar", "p1.Bar", 8, 18, 8, 23); + } + + public void test15() throws Exception { + // raise visibility of intermediary type so + // existing references see it + helperWarn(new String[] { "p0.Foo", "p0.Bar", "p1.Third" }, "bar", "p0.Bar", 8, 17, 8, 20); + } + + public void test16() throws Exception { + // test non-reference mode with a method invocation selected + helper(new String[] { "p.Bar", "p.Foo" }, "bar", "p.Bar", 6, 19, 6, 22, false, false, false, false); + } + + public void test17() throws Exception { + // generic target method + helperPass(new String[] { "p.Foo" }, "bar", "p.Foo", 16, 9, 16, 12); + } + + public void test18() throws Exception { + // simple test with generic type, unused + helperPass(new String[] { "p.Foo" }, "bar", "p.Foo", 19, 11, 19, 14); + } + + public void test19() throws Exception { + // simple test with generic type, used + helperPass(new String[] { "p.Foo" }, "bar", "p.Foo", 19, 11, 19, 14); + } + + public void test20() throws Exception { + // complex case with generic type parameters and method parameters used + helperPass(new String[] { "p.Foo" }, "bar", "p.Foo", 11, 11, 11, 17); + } + + public void test21() throws Exception { + // no call updating if type arguments are used + helperWarn(new String[] { "p.Foo" }, "bar", "p.Foo", 9, 22, 9, 26); + } + + public void test22() throws Exception { + // method using type parameters from enclosing types as well + helperPass(new String[] { "p.Foo" }, "bar", "p.Foo", 16, 24, 16, 27); + } + + public void test23() throws Exception { + // warn about incorrect qualified static calls and don't update them. + helperWarn(new String[] { "p.Foo" }, "bar", "p.Foo", 11, 25, 11, 28); + } + + public void test24() throws Exception { + // assure common super type is used even if the hierarchy branches downwards + helperPass(new String[] { "p.Foo" }, "bar", "p.Foo", 11, 11, 11, 14); + } + + public void test25() throws Exception { + // increase visibility of overridden methods as well + helperWarn(new String[] { "p0.Foo", "p0.SubFoo", "p1.Bar" }, "bar", "p1.Bar", 8, 20, 8, 23); + } + + public void test26() throws Exception { + // ensure exceptions are copied + helperPass(new String[] { "p.Foo" }, "bar", "p.Foo", 7, 24, 7, 27); + } + + public void test27() throws Exception { + // complex visibility adjustment case + // target method is not inside target type, and is overridden + // target type must be increased, and all overridden methods must be increased. + helperWarn(new String[] { "p0.Foo", "p0.RealFoo", "p0.NonOriginalSubFoo", "p0.VerySuperFoo", "p1.Bar" }, "bar", "p1.Bar", 7, 13, 7, 16); + } + + public void test28() throws Exception { + // the template for the intermediary must be the method inside the real + // target (for parameter names and exceptions) + helperWarn(new String[] { "p.Foo", "p.Bar",}, "bar", "p.Foo", 10, 9, 10, 12); + } + + public void test29() throws Exception { + // don't adjust visibility twice + helperWarn(new String[] { "p0.Test", "p1.Other" }, "bar", "p1.Other", 5, 35, 5, 44); + } + + public void test30() throws Exception { + // multiple generic instantiations + helperPass(new String[] { "p.MultiGenerics" }, "bar", "p.MultiGenerics", 7, 16, 7, 26); + } + + public void test31() throws Exception { + // test for bug 127665 + helperPass(new String[] { "p.Test" }, "foo", "p.Test0", 13, 20, 13, 23); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceParameterObjectTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceParameterObjectTests.java new file mode 100644 index 000000000..6a2e66aa9 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceParameterObjectTests.java @@ -0,0 +1,410 @@ +/******************************************************************************* + * Copyright (c) 2005, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.IOException; +import java.util.Hashtable; +import java.util.Map; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.jface.preference.IPreferenceStore; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.refactoring.descriptors.IntroduceParameterObjectDescriptor; +import org.eclipse.jdt.core.refactoring.descriptors.IntroduceParameterObjectDescriptor.Parameter; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; +import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatusCodes; + +import org.eclipse.jdt.ui.PreferenceConstants; + +import org.eclipse.jdt.internal.ui.JavaPlugin; + +public class IntroduceParameterObjectTests extends RefactoringTest { + + private static final Class CLAZZ= IntroduceParameterObjectTests.class; + private static final String DEFAULT_SUB_DIR= "sub"; + private static final String REFACTORING_PATH= "IntroduceParameterObject/"; + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(CLAZZ)); + } + + private IPackageFragment fPack; + private IntroduceParameterObjectDescriptor fDescriptor; + + public IntroduceParameterObjectTests(String name) { + super(name); + } + + private void checkAdditionalFile(String subdir, String fileName) throws Exception, JavaModelException, IOException { + IPackageFragment pack= getSubPackage(subdir); + ICompilationUnit cu= pack.getCompilationUnit(fileName+".java"); + assertNotNull(cu); + assertTrue(cu.getPath() + " does not exist", cu.exists()); + String actual= cu.getSource(); + String expected= getFileContents(getOutputTestFileName(fileName)); + assertEqualLines(expected, actual); + } + + private void checkCaller(String subdir) throws Exception { + checkAdditionalFile(subdir, getCUName(true)); + } + + private void createAdditionalFile(String subDir, String fileName) throws Exception { + IPackageFragment pack= getSubPackage(subDir); + ICompilationUnit cu= createCUfromTestFile(pack, fileName, true); + assertNotNull(cu); + assertTrue(cu.exists()); + } + + private void createCaller(String subDir) throws Exception { + createAdditionalFile(subDir, getCUName(true)); + } + + private String getCUFileName(boolean caller) { + StringBuffer sb= new StringBuffer(); + sb.append(getCUName(caller)); + sb.append(".java"); + return sb.toString(); + } + + private String getCUName(boolean caller) { + StringBuffer sb= new StringBuffer(); + sb.append(Character.toUpperCase(getName().charAt(0)) + getName().substring(1)); + if (caller) + sb.append("Caller"); + return sb.toString(); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + private IPackageFragment getSubPackage(String subDir) throws Exception { + IPackageFragment pack= getPackageP(); + if (subDir != null) { + String packageName= pack.getElementName() + "." + subDir; + pack= getRoot().getPackageFragment(packageName); + if (!pack.exists()) { + IPackageFragment create= getRoot().createPackageFragment(packageName, true, new NullProgressMonitor()); + assertNotNull(create); + assertTrue(create.exists()); + return create; + } + } + return pack; + } + + private void runRefactoring(boolean expectError, boolean useSuggestedMethod) throws Exception { + RefactoringStatus status= performRefactoring(fDescriptor); + if (expectError) { + assertNotNull(status); + if (useSuggestedMethod){ + final RefactoringStatusEntry entry= status.getEntryMatchingSeverity(RefactoringStatus.FATAL); + if (entry.getCode() == RefactoringStatusCodes.OVERRIDES_ANOTHER_METHOD || entry.getCode() == RefactoringStatusCodes.METHOD_DECLARED_IN_INTERFACE) { + final Object element= entry.getData(); + fDescriptor.setMethod((IMethod) element); + status= performRefactoring(fDescriptor); + } + } else { + return; + } + } + assertNull(status+"",status); + String expected= getFileContents(getOutputTestFileName(getCUName(false))); + assertNotNull(expected); + ICompilationUnit resultCU= fPack.getCompilationUnit(getCUFileName(false)); + assertNotNull(resultCU); + assertTrue(resultCU.exists()); + String result= resultCU.getSource(); + assertNotNull(result); + assertEqualLines(expected, result); + if (fDescriptor.isTopLevel()){ + String packageName= fDescriptor.getPackageName(); + if (packageName!=null) + fPack=getRoot().getPackageFragment(packageName); + assertNotNull(fPack); + String parameterClassFile= fDescriptor.getClassName()+".java"; + ICompilationUnit unit= fPack.getCompilationUnit(parameterClassFile); + assertNotNull(unit); + assertTrue(unit.exists()); + expected=getFileContents(getOutputTestFileName(fDescriptor.getClassName())); + result=unit.getSource(); + assertNotNull(result); + assertEqualLines(expected, result); + } + + assertParticipant(fDescriptor.getMethod().getDeclaringType()); + } + + private void assertParticipant(IType typeOfMethod) throws JavaModelException { + TestChangeMethodSignaturParticipant.testParticipant(typeOfMethod); + } + + protected void setUp() throws Exception { + super.setUp(); + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false); + fDescriptor= RefactoringSignatureDescriptorFactory.createIntroduceParameterObjectDescriptor(); + fPack= getPackageP(); + } + + private IMethod setupMethod() throws Exception, JavaModelException { + ICompilationUnit cu= createCUfromTestFile(fPack, getCUName(false), true); + IType type= cu.getType(getCUName(false)); + assertNotNull(type); + assertTrue(type.exists()); + IMethod fooMethod= null; + IMethod[] methods= type.getMethods(); + for (int i= 0; i < methods.length; i++) { + IMethod method= methods[i]; + if ("foo".equals(method.getElementName())) { + fooMethod= method; + } + } + assertNotNull(fooMethod); + assertTrue(fooMethod.exists()); + return fooMethod; + } + + private void setupPackage(String inputPackage) throws JavaModelException { + fPack= getRoot().createPackageFragment(inputPackage,true,null); + } + + protected void tearDown() throws Exception { + super.tearDown(); + fDescriptor=null; + fPack=null; + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + store.setToDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS); + } + + public void testBodyUpdate() throws Exception { + fDescriptor.setMethod(setupMethod()); + fDescriptor.setTopLevel(false); + runRefactoring(false, true); + } + + public void testDefaultPackagePoint() throws Exception { + setupPackage(""); + fDescriptor.setMethod(setupMethod()); + fDescriptor.setClassName("ArrayList"); + fDescriptor.setTopLevel(false); + runRefactoring(false, true); + } + + public void testDefaultPackagePointTopLevel() throws Exception { + setupPackage(""); + fDescriptor.setMethod(setupMethod()); + fDescriptor.setClassName("ArrayList"); + fDescriptor.setTopLevel(true); + runRefactoring(false, true); + } + + public void testDelegateCreation() throws Exception { + fDescriptor.setMethod(setupMethod()); + fDescriptor.setGetters(true); + fDescriptor.setTopLevel(false); + fDescriptor.setSetters(true); + fDescriptor.setDelegate(true); + + Parameter[] parameters= IntroduceParameterObjectDescriptor.createParameters(fDescriptor.getMethod()); + parameters[1].setFieldName("newA"); + parameters[2].setFieldName("newB"); + parameters[3].setFieldName("newD"); + fDescriptor.setParameters(parameters); + runRefactoring(false, true); + } + + public void testDelegateCreationCodeStyle() throws Exception { + IJavaProject javaProject= getRoot().getJavaProject(); + Map originalOptions= javaProject.getOptions(false); + try { + Hashtable newOptions= new Hashtable(); + newOptions.put(JavaCore.CODEASSIST_FIELD_PREFIXES, "f"); + newOptions.put(JavaCore.CODEASSIST_FIELD_SUFFIXES, "G"); + javaProject.setOptions(newOptions); + + fDescriptor.setMethod(setupMethod()); + fDescriptor.setGetters(true); + fDescriptor.setSetters(true); + fDescriptor.setDelegate(true); + fDescriptor.setTopLevel(false); + + Parameter[] parameters= IntroduceParameterObjectDescriptor.createParameters(fDescriptor.getMethod()); + parameters[3].setFieldName("newD"); + fDescriptor.setParameters(parameters); + runRefactoring(false, true); + } finally { + javaProject.setOptions(originalOptions); + } + } + + public void testImportAddEnclosing() throws Exception { + createCaller(null); + fDescriptor.setMethod(setupMethod()); + fDescriptor.setTopLevel(false); + + Parameter[] parameters= IntroduceParameterObjectDescriptor.createParameters(fDescriptor.getMethod()); + parameters[1].setFieldName("permissions"); + fDescriptor.setParameters(parameters); + runRefactoring(false, true); + checkCaller(null); + } + + public void testImportAddTopLevel() throws Exception { + createCaller(DEFAULT_SUB_DIR); + fDescriptor.setMethod(setupMethod()); + fDescriptor.setTopLevel(true); + fDescriptor.setClassName("TestImportAddTopLevelParameter"); + fDescriptor.setPackageName("p.parameters"); + runRefactoring(false, true); + checkCaller(DEFAULT_SUB_DIR); + } + + public void testImportNameSimple() throws Exception { + fDescriptor.setMethod(setupMethod()); + fDescriptor.setClassName("ArrayList"); + fDescriptor.setParameterName("p"); + fDescriptor.setTopLevel(true); + runRefactoring(false, true); + } + + public void testInlineRename() throws Exception { + fDescriptor.setMethod(setupMethod()); + fDescriptor.setTopLevel(false); + + Parameter[] parameters= IntroduceParameterObjectDescriptor.createParameters(fDescriptor.getMethod()); + parameters[3].setCreateField(false); + fDescriptor.setParameters(parameters); + runRefactoring(false, true); + } + + public void testSubclassInCU() throws Exception { + // test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=259095 + fDescriptor.setMethod(setupMethod()); + fDescriptor.setTopLevel(true); + fDescriptor.setClassName("FooParameter"); + + runRefactoring(false, true); + } + + public void testInterfaceMethod() throws Exception { + createAdditionalFile(null, "TestInterfaceMethod2Impl"); + createAdditionalFile(null, "ITestInterfaceMethod"); + fDescriptor.setMethod(setupMethod()); + fDescriptor.setTopLevel(true); + fDescriptor.setClassName("FooParameter"); + runRefactoring(true, false); + runRefactoring(true, true); + checkAdditionalFile(null, "ITestInterfaceMethod"); + checkAdditionalFile(null, "TestInterfaceMethod2Impl"); + } + + public void testRecursiveReordered() throws Exception { + fDescriptor.setMethod(setupMethod()); + fDescriptor.setTopLevel(false); + + Parameter[] parameters= IntroduceParameterObjectDescriptor.createParameters(fDescriptor.getMethod()); + Parameter temp=parameters[1]; + parameters[1]=parameters[2]; + parameters[2]=temp; + fDescriptor.setParameters(parameters); + runRefactoring(false, true); + } + + public void testRecursiveSimple() throws Exception { + fDescriptor.setMethod(setupMethod()); + fDescriptor.setTopLevel(false); + runRefactoring(false, true); + } + + public void testRecursiveSimpleReordered() throws Exception { + fDescriptor.setMethod(setupMethod()); + fDescriptor.setTopLevel(false); + runRefactoring(false, true); + } + + + public void testReorderGetter() throws Exception{ + fDescriptor.setMethod(setupMethod()); + fDescriptor.setGetters(true); + fDescriptor.setTopLevel(false); + Parameter[] parameters= IntroduceParameterObjectDescriptor.createParameters(fDescriptor.getMethod()); + Parameter temp=parameters[3]; + parameters[3]=parameters[2]; + parameters[2]=parameters[1]; + parameters[1]=temp; + fDescriptor.setParameters(parameters); + runRefactoring(false, true); + } + + public void testSimpleEnclosing() throws Exception{ + fDescriptor.setMethod(setupMethod()); + fDescriptor.setTopLevel(false); + runRefactoring(false, true); + } + + public void testSimpleEnclosingCodeStyle() throws Exception { + IJavaProject javaProject= getRoot().getJavaProject(); + Map originalOptions= javaProject.getOptions(false); + try { + Hashtable newOptions= new Hashtable(); + newOptions.put(JavaCore.CODEASSIST_FIELD_PREFIXES, "f"); + newOptions.put(JavaCore.CODEASSIST_FIELD_SUFFIXES, "G"); + newOptions.put(JavaCore.CODEASSIST_ARGUMENT_PREFIXES, "a"); + newOptions.put(JavaCore.CODEASSIST_ARGUMENT_SUFFIXES, "M"); + javaProject.setOptions(newOptions); + + fDescriptor.setMethod(setupMethod()); + fDescriptor.setTopLevel(false); + runRefactoring(false, true); + } finally { + javaProject.setOptions(originalOptions); + } + } + + public void testVarArgsNotReordered() throws Exception{ + fDescriptor.setMethod(setupMethod()); + fDescriptor.setTopLevel(false); + runRefactoring(false, true); + } + + public void testVarArgsReordered() throws Exception{ + fDescriptor.setMethod(setupMethod()); + fDescriptor.setTopLevel(false); + + Parameter[] parameters= IntroduceParameterObjectDescriptor.createParameters(fDescriptor.getMethod()); + Parameter temp=parameters[1]; + parameters[1]=parameters[2]; + parameters[2]=temp; + fDescriptor.setParameters(parameters); + runRefactoring(false, true); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceParameterTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceParameterTests.java new file mode 100644 index 000000000..84cfd7237 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceParameterTests.java @@ -0,0 +1,195 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.StringTokenizer; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.ISourceRange; + +import org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring; + +public class IntroduceParameterTests extends LineColumnSelectionTestCase { + + private static final String SLASH_OUT= "/out"; + public IntroduceParameterTests(String name) { + super(name); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + public static Test suite() { + if (true) { + return new RefactoringTestSetup(new TestSuite(IntroduceParameterTests.class)); + } else { + System.err.println("*** Running only parts of IntroduceParameterTests!"); + TestSuite suite= new TestSuite(); + suite.addTest(new IntroduceParameterTests("testSimple_StaticGetter1")); + return new RefactoringTestSetup(suite); + } + } + + protected String getResourceLocation() { + return "IntroduceParameter/"; + } + + /** + * get names from comment in source "//name: guessedName -> nameToUse" + * <br>relies on tabwidth == 4 + * @param cu + * @return {"guessedName", "nameToUse"} or null iff no name comment found + * @throws Exception + */ + private String[] getNames(ICompilationUnit cu) throws Exception { + String source= cu.getSource(); + String name= "//name:"; + int namStart= source.indexOf(name); + if (namStart == -1) + return null; + + int dataStart= namStart + name.length(); + StringTokenizer tokenizer= new StringTokenizer(source.substring(dataStart), " ->\t\r\n"); + String[] result= {tokenizer.nextToken(), tokenizer.nextToken()}; + return result; + } + + private void performOK() throws Exception { + perform(RefactoringStatus.OK, RefactoringStatus.OK); + } + + private void performInvalidSelection() throws Exception { + perform(RefactoringStatus.FATAL, RefactoringStatus.FATAL); + } + + private void perform(int expectedActivationStatus, int expectedInputStatus) throws Exception { + String packageName= adaptPackage(getName()); + IPackageFragment packageFragment= RefactoringTestSetup.getDefaultSourceFolder().createPackageFragment(packageName, true , null); + ICompilationUnit cu= createCU(packageFragment, getName()); + + ISourceRange selection= getSelection(cu); + IntroduceParameterRefactoring refactoring= new IntroduceParameterRefactoring(cu, selection.getOffset(), selection.getLength()); + + NullProgressMonitor pm= new NullProgressMonitor(); + RefactoringStatus status= refactoring.checkInitialConditions(pm); + assertEquals("wrong activation status", expectedActivationStatus, status.getSeverity()); + if (! status.isOK()) + return; + + String[] names= getNames(cu); + if (names == null) { + refactoring.setParameterName(refactoring.guessedParameterName()); + } else { + assertEquals("incorrectly guessed parameter name", names[0], refactoring.guessedParameterName()); + refactoring.setParameterName(names[1]); + } + + status.merge(refactoring.checkFinalConditions(pm)); + assertEquals("wrong input status", expectedInputStatus, status.getSeverity()); + if (status.getSeverity() == RefactoringStatus.FATAL) + return; + + String out= getProofedContent(packageName + SLASH_OUT, getName()); + performTest(cu, refactoring, out); + } + +// --- + + public void testInvalid_NotInMethod1() throws Exception { + performInvalidSelection(); + } + public void testInvalid_NotInMethod2() throws Exception { + performInvalidSelection(); + } + public void testInvalid_NotInMethod3() throws Exception { + performInvalidSelection(); + } + + public void testInvalid_PartName1() throws Exception { + performInvalidSelection(); + } + + public void testInvalid_PartString() throws Exception { + performInvalidSelection(); + } + + public void testInvalid_NoMethodBinding() throws Exception { + performInvalidSelection(); + } + + public void testInvalid_NoExpression1() throws Exception { + performInvalidSelection(); + } + + // --- + + public void testSimple_Capture() throws Exception { + performOK(); + } + + public void testSimple_ConstantExpression1() throws Exception { + performOK(); + } + + public void testSimple_ConstantExpression2() throws Exception { + performOK(); + } + + public void testSimple_NewInstance1() throws Exception { + performOK(); + } + + public void testSimple_NewInstanceImport() throws Exception { + performOK(); + } + + public void testSimple_StaticGetter1() throws Exception { + performOK(); + } + + public void testSimple_Formatting1() throws Exception { + performOK(); + } + + public void testSimple_Javadoc1() throws Exception { + performOK(); + } + + public void testSimple_Javadoc2() throws Exception { + performOK(); + } + + public void testSimple_Constructor1() throws Exception { + performOK(); + } + + public void testSimple_Vararg1() throws Exception { + performOK(); + } + + public void testSimple_Wildcard1() throws Exception { + performOK(); + } + + public void testSimple_Wildcard2() throws Exception { + performOK(); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/Java15Setup.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/Java15Setup.java new file mode 100644 index 000000000..cbf8eefa8 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/Java15Setup.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2000, 2005 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +/** + * TODO: replace by RefactoringTestSetup + */ +public class Java15Setup extends RefactoringTestSetup { + + public Java15Setup(Test test) { + super(test); + } + + protected void setUp() throws Exception { + super.setUp(); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/Java16Setup.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/Java16Setup.java new file mode 100644 index 000000000..1e61ef538 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/Java16Setup.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +public class Java16Setup extends RefactoringTestSetup { + + public Java16Setup(Test test) { + super(test); + } + + /* + * @see org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSetup#addRTJar(org.eclipse.jdt.core.IJavaProject) + */ + protected IPackageFragmentRoot addRTJar(IJavaProject project) throws CoreException { + return JavaProjectHelper.addRTJar16(project); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/LineColumnSelectionTestCase.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/LineColumnSelectionTestCase.java new file mode 100644 index 000000000..38541c763 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/LineColumnSelectionTestCase.java @@ -0,0 +1,113 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.IOException; +import java.io.InputStream; +import java.util.StringTokenizer; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.core.resources.IWorkspaceRunnable; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.Refactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.JavaCore; + +import org.eclipse.jdt.ui.tests.refactoring.infra.AbstractCUTestCase; +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringTestPlugin; +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +/** + * Test Naming Convention:<p> + * - testSimple_A() -> package 'simple', file 'A.java'; result in package 'simple.out'<br> + * - testSuch_ALongName17() -> package 'such', file 'ALongName17.java' + */ +public class LineColumnSelectionTestCase extends AbstractCUTestCase { + + public LineColumnSelectionTestCase(String name) { + super(name); + } + + protected InputStream getFileInputStream(String fileName) throws IOException { + return RefactoringTestPlugin.getDefault().getTestResourceStream(fileName); + } + + /** + * @param name e.g. "testSuch_ALongName17" + * @return e.g. "ALongName17" + */ + protected String adaptName(String name) { + int separator= name.indexOf('_'); + assertTrue(separator != -1); + assertTrue(separator >= 5); + return name.substring(separator + 1) + ".java"; + } + + /** + * @param name e.g. "testSuch_ALongName17" + * @return e.g. "such" + */ + protected String adaptPackage(String name) { + int separator= name.indexOf('_'); + assertTrue(separator != -1); + assertTrue(separator >= 5); + return Character.toLowerCase(name.charAt(4)) + + name.substring(5, separator); + } + + /* + * get selection from comment in source "//selection: line, col, line, col" + * <br>relies on tabwidth == 4 + */ + protected ISourceRange getSelection(ICompilationUnit cu) throws Exception { + String source= cu.getSource(); + String selection= "//selection:"; + int selStart= source.indexOf(selection); + assertTrue(selStart != -1); + + int dataStart= selStart + selection.length(); + StringTokenizer tokenizer= new StringTokenizer(source.substring(dataStart), " ,\t\r\n"); + int line1= Integer.parseInt(tokenizer.nextToken()); + int col1= Integer.parseInt(tokenizer.nextToken()); + int line2= Integer.parseInt(tokenizer.nextToken()); + int col2= Integer.parseInt(tokenizer.nextToken()); + return TextRangeUtil.getSelection(cu, line1, col1, line2, col2); + } + + /* @require refactoring.checkActivation().isOK() */ + protected void performTest(final ICompilationUnit unit, final Refactoring refactoring, final String out) throws Exception { + JavaCore.run(new IWorkspaceRunnable() { + public void run(IProgressMonitor monitor) throws CoreException { + String original= unit.getSource(); + final Change change= refactoring.createChange(monitor); + assertNotNull(change); + change.initializeValidationData(new NullProgressMonitor()); + assertTrue(!change.isValid(new NullProgressMonitor()).hasFatalError()); + Change undo= change.perform(monitor); + change.dispose(); + assertNotNull(undo); + compareSource(unit.getSource(), out); + undo.initializeValidationData(new NullProgressMonitor()); + assertTrue(!undo.isValid(new NullProgressMonitor()).hasFatalError()); + undo.perform(monitor); + undo.dispose(); + compareSource(unit.getSource(), original); + } + }, new NullProgressMonitor()); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveInnerToTopLevelTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveInnerToTopLevelTests.java new file mode 100644 index 000000000..bea53e81f --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveInnerToTopLevelTests.java @@ -0,0 +1,544 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.IOException; +import java.util.Hashtable; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; +import org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; + +public class MoveInnerToTopLevelTests extends RefactoringTest { + + private static final String FIELD_COMMENT= "/** Comment */"; + private static final Class clazz= MoveInnerToTopLevelTests.class; + private static final String REFACTORING_PATH= "MoveInnerToTopLevel/"; + + private static final int NOT_AVAILABLE= 1001; + + private Object fCompactPref; + + public MoveInnerToTopLevelTests(String name) { + super(name); + } + + public static Test suite() { + return new Java15Setup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new Java15Setup(someTest); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + protected void setUp() throws Exception { + super.setUp(); + StubUtility.setCodeTemplate(CodeTemplateContextType.FIELDCOMMENT_ID, FIELD_COMMENT, null); + StubUtility.setCodeTemplate(CodeTemplateContextType.NEWTYPE_ID, + "${package_declaration}" + + System.getProperty("line.separator", "\n") + + "${type_declaration}", null); + + Hashtable options= JavaCore.getOptions(); + + String setting= DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR; + fCompactPref= options.get(setting); + options.put(setting, DefaultCodeFormatterConstants.TRUE); + JavaCore.setOptions(options); + } + + protected void tearDown() throws Exception { + super.tearDown(); + Hashtable options= JavaCore.getOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR, fCompactPref); + JavaCore.setOptions(options); + } + + + private IType getClassFromTestFile(IPackageFragment pack, String className) throws Exception{ + return getType(createCUfromTestFile(pack, className), className); + } + + private void validatePassingTest(String parentClassName, String className, String packageName, String[] cuNames, String[] packageNames, String enclosingInstanceName, boolean makeFinal, boolean possible, boolean mandatory, boolean createFieldIfPossible) throws Exception { + IType parentClas= getClassFromTestFile(getPackage(packageName), parentClassName); + IType clas= parentClas.getType(className); + validatePassingTest(className, clas, cuNames, packageNames, enclosingInstanceName, makeFinal, possible, mandatory, createFieldIfPossible); + } + + private void validatePassingTest(String parentClassName, String parentClassNameInParent, String className, String packageName, String[] cuNames, String[] packageNames, String enclosingInstanceName, boolean makeFinal, boolean possible, boolean mandatory, boolean createFieldIfPossible) throws Exception { + IType parentClas= getClassFromTestFile(getPackage(packageName), parentClassName); + IType parent2 = parentClas.getType(parentClassNameInParent); + IType clas = parent2.getType(className); + validatePassingTest(className, clas, cuNames, packageNames, enclosingInstanceName, makeFinal, possible, mandatory, createFieldIfPossible); + } + + private void validatePassingTest(String className, IType clas, String[] cuNames, String[] packageNames, String enclosingInstanceName, boolean makeFinal, boolean possible, boolean mandatory, boolean createFieldIfPossible) throws JavaModelException, CoreException, Exception, IOException { + assertTrue("should be enabled", RefactoringAvailabilityTester.isMoveInnerAvailable(clas)); + MoveInnerToTopRefactoring ref= ((RefactoringAvailabilityTester.isMoveInnerAvailable(clas)) ? new MoveInnerToTopRefactoring(clas, JavaPreferencesSettings.getCodeGenerationSettings(clas.getJavaProject())) : null); + RefactoringStatus preconditionResult= ref.checkInitialConditions(new NullProgressMonitor()); + assertTrue("activation was supposed to be successful" + preconditionResult.toString(), preconditionResult.isOK()); + + assertEquals("reference creation possible", possible, ref.isCreatingInstanceFieldPossible()); + assertEquals("reference creation mandatory", mandatory, ref.isCreatingInstanceFieldMandatory()); + if (ref.isCreatingInstanceFieldPossible() && ! ref.isCreatingInstanceFieldMandatory()) + ref.setCreateInstanceField(createFieldIfPossible); + if (enclosingInstanceName != null){ + ref.setEnclosingInstanceName(enclosingInstanceName); + assertTrue("name should be ok ", ref.checkEnclosingInstanceName(enclosingInstanceName).isOK()); + } + ref.setMarkInstanceFieldAsFinal(makeFinal); + ICompilationUnit[] cus= new ICompilationUnit[cuNames.length]; + for (int i= 0; i < cuNames.length; i++) { + if (cuNames[i].equals(clas.getCompilationUnit().findPrimaryType().getElementName())) + cus[i]= clas.getCompilationUnit(); + else + cus[i]= createCUfromTestFile(getPackage(packageNames[i]), cuNames[i]); + } + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to pass", !checkInputResult.hasError()); + performChange(ref, false); + + for (int i= 0; i < cus.length; i++) { + String actual= cus[i].getSource(); + String expected= getFileContents(getOutputTestFileName(cuNames[i])); + assertEqualLines(cus[i].getElementName(), expected, actual); + } + ICompilationUnit newCu= clas.getPackageFragment().getCompilationUnit(className + ".java"); + String expected= getFileContents(getOutputTestFileName(className)); + String actual= newCu.getSource(); + assertEqualLines("new Cu:", expected, actual); + } + + + private void validatePassingTest(String parentClassName, String className, String[] cuNames, String[] packageNames, String enclosingInstanceName, boolean possible, boolean mandatory) throws Exception { + validatePassingTest(parentClassName, className, "p", cuNames, packageNames, enclosingInstanceName, false, possible, mandatory, true); + } + + private void validateFailingTest(String parentClassName, String className, String[] cuNames, String[] packageNames, String enclosingInstanceName, int expectedSeverity) throws Exception { + IType parentClas= getClassFromTestFile(getPackageP(), parentClassName); + IType clas= parentClas.getType(className); + + MoveInnerToTopRefactoring ref= ((RefactoringAvailabilityTester.isMoveInnerAvailable(clas)) ? new MoveInnerToTopRefactoring(clas, JavaPreferencesSettings.getCodeGenerationSettings(clas.getJavaProject())) : null); + if (expectedSeverity == NOT_AVAILABLE && ref == null) + return; + assertEquals("refactoring availability not as expected", expectedSeverity == NOT_AVAILABLE, ref == null); + + RefactoringStatus preconditionResult= ref.checkInitialConditions(new NullProgressMonitor()); + + if (enclosingInstanceName != null){ + ref.setEnclosingInstanceName(enclosingInstanceName); + } + ref.setMarkInstanceFieldAsFinal(false); + ICompilationUnit[] cus= new ICompilationUnit[cuNames.length]; + for (int i= 0; i < cuNames.length; i++) { + if (cuNames[i].equals(clas.getCompilationUnit().findPrimaryType().getElementName())) + cus[i]= clas.getCompilationUnit(); + else + cus[i]= createCUfromTestFile(getPackage(packageNames[i]), cuNames[i]); + } + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + + RefactoringStatus result= new RefactoringStatus(); + result.merge(preconditionResult); + result.merge(checkInputResult); + assertEquals("different severity expected", expectedSeverity, result.getSeverity()); + } + private IPackageFragment getPackage(String name) throws JavaModelException { + if ("p".equals(name)) + return getPackageP(); + IPackageFragment pack= getRoot().getPackageFragment(name); + if (pack.exists()) + return pack; + return getRoot().createPackageFragment(name, false, new NullProgressMonitor()); + } + + + //-- tests + + public void test0() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test1() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test2() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test3() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test4() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test5() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test6() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + public void test7() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test8() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + public void test9() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test10() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + public void test11() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test12() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + public void test13() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test14() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test15() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A", "A1"}, new String[]{"p", "p1"}, null, false, false); + } + + public void test16() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A", "A1"}, new String[]{"p", "p1"}, null, false, false); + } + + public void test17() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test18() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A", "A1"}, new String[]{"p", "p1"}, null, false, false); + } + + public void test19() throws Exception{ + printTestDisabledMessage("bug 23078"); +// validatePassingTest("A", "Inner", new String[]{"A", "A1"}, new String[]{"p", "p1"}, null, false, false); + } + + public void test20() throws Exception{ +// printTestDisabledMessage("bug 23077 "); + validatePassingTest("A", "Inner", new String[]{"A", "A1"}, new String[]{"p", "p1"}, null, false, false); + } + + public void test21() throws Exception{ +// printTestDisabledMessage("bug 23627"); + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + public void test22() throws Exception{ +// printTestDisabledMessage("bug 23627"); + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test23() throws Exception{ +// printTestDisabledMessage("bug 24576 "); + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test24() throws Exception{ +// printTestDisabledMessage("bug 28816 "); + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, null, false, false); + } + + public void test25() throws Exception{ +// printTestDisabledMessage("bug 39716"); + validatePassingTest("A", "Inner", "", new String[]{"A"}, new String[]{""}, null, false, false, false, true); + } + + public void test26() throws Exception{ + validatePassingTest("A", "Inner", "", new String[]{"A"}, new String[]{""}, null, false, true, true, true); + } + + public void test30() throws Exception{ + validatePassingTest("A", "Inner", "", new String[]{"A"}, new String[]{""}, null, false, true, true, true); + } + + public void test31() throws Exception{ + printTestDisabledMessage("disabled due to missing support for statically imported methods"); + // validatePassingTest("A", "Inner", "", new String[]{"A"}, new String[]{""}, null, false, true, true, true); + } + + // ---- Visibility issues with the moved member itself and its parents + + // Move inner class; enclosing class must remain private if not used + public void test32() throws Exception{ + validatePassingTest("A", "Inner", "MoreInner", "p1", new String[]{"A"}, new String[]{"p1"}, null, false, false, false, false); + } + + // Move inner class which has access to enclosing private class, enclosing class must be increased in visibility + public void test33() throws Exception{ + validatePassingTest("A", "Inner", "MoreInner", "p2", new String[]{"A"}, new String[]{"p2"}, null, false, false, false, false); + } + + // --- Visibility issues with members of moved members + + // Move inner class which has private members, which are accessed from enclosing types. + public void test34() throws Exception { + validatePassingTest("A", "SomeClass", "p", new String[] { "A"}, new String[] { "p"}, null, false, true, false, false); + } + + // Move inner class which has private members, but they are unused (and must remain private) + public void test35() throws Exception { + validatePassingTest("A", "Inner", "p", new String[] { "A"}, new String[] { "p"}, null, false, true, false, false); + } + + // Move inner class which has access private members, and accessing private members of + // enclosing class (4 visibility increments) + public void test36() throws Exception { + validatePassingTest("A", "SomeInner", "Inner", "p", new String[] { "A"}, new String[] { "p"}, null, false, false, false, false); + } + + // Move inner class with some private used and some private non-used members. + // used members go default, non-used stay private + // bug 97411 + 117465 (comment #1) + public void test37() throws Exception { + validatePassingTest("A", "SomeInner", "p", new String[] { "A"}, new String[] { "p"}, null, false, false, false, false); + } + + public void test38() throws Exception { + validatePassingTest("A", "B", "p", new String[] { "A"}, new String[] { "p"}, null, false, false, false, false); + } + + // --- Non static + + public void test_nonstatic_0() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + + public void test_nonstatic_1() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_2() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_3() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_4() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_5() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_6() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_7() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_8() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_9() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_10() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_11() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_12() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, true); + } + public void test_nonstatic_13() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, true); + } + public void test_nonstatic_14() throws Exception{ +// printTestDisabledMessage("bug 23488"); + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_15() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_16() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_17() throws Exception{ +// printTestDisabledMessage("bug 23488"); + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_18() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_19() throws Exception{ +// printTestDisabledMessage("bug 23464 "); + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_20() throws Exception{ +// printTestDisabledMessage("bug 23464 "); + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_21() throws Exception{ +// printTestDisabledMessage("must fix - consequence of fix for 23464"); + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_22() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_23() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_24() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_25() throws Exception{ +// printTestDisabledMessage("bug 23464 "); + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_26() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_27() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_28() throws Exception{ +// printTestDisabledMessage("test for bug 23725"); + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_29() throws Exception{ + printTestDisabledMessage("test for bug 23724"); +// validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + public void test_nonstatic_30() throws Exception{ +// printTestDisabledMessage("test for bug 23715"); + validatePassingTest("A", "Inner", "p", new String[]{"A"}, new String[]{"p"}, "a", true, true, false, true); + } + + public void test_nonstatic_31() throws Exception{ +// printTestDisabledMessage("test for bug 25537"); + validatePassingTest("A", "Inner", "p", new String[]{"A"}, new String[]{"p"}, "a", true, true, true, true); + } + + public void test_nonstatic_32() throws Exception{ +// printTestDisabledMessage("test for bug 25537"); + validatePassingTest("A", "Inner", "p", new String[]{"A"}, new String[]{"p"}, "a", true, true, true, true); + } + + public void test_nonstatic_33() throws Exception{ +// printTestDisabledMessage("test for bug 26252"); + validatePassingTest("A", "I", "p", new String[]{"A"}, new String[]{"p"}, "a", true, true, false, true); + } + + public void test_nonstatic_34() throws Exception{ +// printTestDisabledMessage("test for bug 31861"); + validatePassingTest("A", "Inner", "p", new String[]{"A"}, new String[]{"p"}, "a", true, true, true, true); + } + + public void test_nonstatic_35() throws Exception{ + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, false); + } + + public void test_nonstatic_36() throws Exception{ +// printTestDisabledMessage("test for bug 34591"); + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, true); + } + + public void test_nonstatic_37() throws Exception{ +// printTestDisabledMessage("test for bug 38114"); + validatePassingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", true, true); + } + + public void test_nonstatic_38() throws Exception{ +// printTestDisabledMessage("test for bug 37540"); + validatePassingTest("A", "Inner", "p", new String[]{"A"}, new String[]{"p"}, "a", false, true, false, false); + } + + public void test_nonstatic_39() throws Exception{ +// printTestDisabledMessage("test for bug 37540"); + validatePassingTest("A", "Inner", "p", new String[]{"A"}, new String[]{"p"}, "a", false, true, false, false); + } + + public void test_nonstatic_40() throws Exception{ +// printTestDisabledMessage("test for bug 77083"); + validatePassingTest("A", "Inner", "p", new String[]{"A"}, new String[]{"p"}, "a", false, true, false, false); + } + + public void test_nonstatic_41() throws Exception{ + validatePassingTest("A", "Inner", "p", new String[]{"A"}, new String[]{"p"}, "a", false, true, false, false); + } + + public void test_nonstatic_42() throws Exception{ + printTestDisabledMessage("disabled due to missing support for statically imported methods"); +// validatePassingTest("A", "Inner", "p", new String[]{"A"}, new String[]{"p"}, "a", false, true, false, false); + } + + // Using member of enclosing type, non-static edition + public void test_nonstatic_43() throws Exception{ + validatePassingTest("A", "Inner", "MoreInner", "p5", new String[]{"A"}, new String[]{"p5"}, "inner", true, true, true, true); + } + + // Move inner class and create field; enclosing class must be changed to use default visibility. + public void test_nonstatic_44() throws Exception{ + validatePassingTest("A", "Inner", "MoreInner", "p2", new String[]{"A"}, new String[]{"p2"}, "p", true, true, false, true); + } + + public void testFail_nonstatic_0() throws Exception{ + validateFailingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", RefactoringStatus.ERROR); + } + public void testFail_nonstatic_1() throws Exception{ + validateFailingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", RefactoringStatus.ERROR); + } + public void testFail_nonstatic_2() throws Exception{ + validateFailingTest("A", "Inner", new String[]{"A"}, new String[]{"p"}, "a", RefactoringStatus.ERROR); + } + + public void testFail_nonstatic_3() throws Exception{ + IType parentClas= getClassFromTestFile(getPackageP(), "A"); + int offset= TextRangeUtil.getOffset(parentClas.getCompilationUnit(), 5, 25); + IType nestedLocal= (IType) parentClas.getCompilationUnit().codeSelect(offset, 0)[0]; + + MoveInnerToTopRefactoring ref= ((RefactoringAvailabilityTester.isMoveInnerAvailable(nestedLocal)) ? new MoveInnerToTopRefactoring(nestedLocal, JavaPreferencesSettings.getCodeGenerationSettings(parentClas.getJavaProject())) : null); + assertNull("refactoring was not supposed to be available", ref); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveInstanceMethodTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveInstanceMethodTests.java new file mode 100644 index 000000000..86683a71d --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveInstanceMethodTests.java @@ -0,0 +1,540 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.Assert; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.MoveRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.dom.IVariableBinding; + +import org.eclipse.jdt.internal.corext.refactoring.structure.MoveInstanceMethodProcessor; + +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; + +public class MoveInstanceMethodTests extends RefactoringTest { + + private static final Class clazz= MoveInstanceMethodTests.class; + + public static final int FIELD= 1; + + public static final int PARAMETER= 0; + + private static final String REFACTORING_PATH= "MoveInstanceMethod/"; + + public static void chooseNewTarget(MoveInstanceMethodProcessor processor, int newTargetType, String newTargetName) { + IVariableBinding target= null; + IVariableBinding[] targets= processor.getPossibleTargets(); + for (int i= 0; i < targets.length; i++) { + IVariableBinding candidate= targets[i]; + if (candidate.getName().equals(newTargetName) && typeMatches(newTargetType, candidate)) { + target= candidate; + break; + } + } + assertNotNull("Expected new target not available.", target); + processor.setTarget(target); + } + + private static IMethod getMethod(ICompilationUnit cu, ISourceRange sourceRange) throws JavaModelException { + IJavaElement[] jes= cu.codeSelect(sourceRange.getOffset(), sourceRange.getLength()); + if (jes.length != 1 || !(jes[0] instanceof IMethod)) + return null; + return (IMethod) jes[0]; + } + + public static Test setUpTest(Test someTest) { + return new Java15Setup(someTest); + } + + public static Test suite() { + return new Java15Setup(new TestSuite(clazz)); + } + + private static boolean typeMatches(int newTargetType, IVariableBinding newTarget) { + return newTargetType == PARAMETER && !newTarget.isField() || newTargetType == FIELD && newTarget.isField(); + } + + private boolean toSucceed; + + public MoveInstanceMethodTests(String name) { + super(name); + } + + private ICompilationUnit[] createCUs(String[] qualifiedNames) throws Exception { + ICompilationUnit[] cus= new ICompilationUnit[qualifiedNames.length]; + for (int i= 0; i < qualifiedNames.length; i++) { + Assert.isNotNull(qualifiedNames[i]); + cus[i]= createCUfromTestFile(getRoot().createPackageFragment(getQualifier(qualifiedNames[i]), true, null), getSimpleName(qualifiedNames[i])); + } + return cus; + } + + private void failHelper1(String cuQName, int startLine, int startColumn, int endLine, int endColumn, int newReceiverType, String newReceiverName, boolean inlineDelegator, boolean removeDelegator) throws Exception { + failHelper1(new String[] { cuQName}, cuQName, startLine, startColumn, endLine, endColumn, newReceiverType, newReceiverName, inlineDelegator, removeDelegator); + } + + private void failHelper1(String[] cuQNames, int selectionCuIndex, int startLine, int startColumn, int endLine, int endColumn, int newReceiverType, String newReceiverName, String newMethodName, String newTargetName, boolean inlineDelegator, boolean removeDelegator) throws Exception { + Assert.isTrue(0 <= selectionCuIndex && selectionCuIndex < cuQNames.length); + + toSucceed= false; + + ICompilationUnit[] cus= createCUs(cuQNames); + ICompilationUnit selectionCu= cus[selectionCuIndex]; + + ISourceRange selection= TextRangeUtil.getSelection(selectionCu, startLine, startColumn, endLine, endColumn); + IMethod method= getMethod(selectionCu, selection); + assertNotNull(method); + MoveInstanceMethodProcessor processor= new MoveInstanceMethodProcessor(method, JavaPreferencesSettings.getCodeGenerationSettings(selectionCu.getJavaProject())); + Refactoring ref= new MoveRefactoring(processor); + RefactoringStatus result= ref.checkInitialConditions(new NullProgressMonitor()); + if (!result.isOK()) + return; + else { + chooseNewTarget(processor, newReceiverType, newReceiverName); + + if (newTargetName != null) + processor.setTargetName(newTargetName); + processor.setInlineDelegator(inlineDelegator); + processor.setRemoveDelegator(removeDelegator); + processor.setDeprecateDelegates(false); + if (newMethodName != null) + processor.setMethodName(newMethodName); + + result.merge(ref.checkFinalConditions(new NullProgressMonitor())); + + assertTrue("precondition checking is expected to fail.", !result.isOK()); + } + } + + private void failHelper1(String[] cuQNames, String selectionCuQName, int startLine, int startColumn, int endLine, int endColumn, int newReceiverType, String newReceiverName, boolean inlineDelegator, boolean removeDelegator) throws Exception { + int selectionCuIndex= firstIndexOf(selectionCuQName, cuQNames); + Assert.isTrue(selectionCuIndex != -1, "parameter selectionCuQName must match some String in cuQNames."); + failHelper1(cuQNames, selectionCuIndex, startLine, startColumn, endLine, endColumn, newReceiverType, newReceiverName, null, null, inlineDelegator, removeDelegator); + } + + private void failHelper2(String[] cuQNames, String selectionCuQName, int startLine, int startColumn, int endLine, int endColumn, int newReceiverType, String newReceiverName, String originalReceiverParameterName, boolean inlineDelegator, boolean removeDelegator) throws Exception { + int selectionCuIndex= firstIndexOf(selectionCuQName, cuQNames); + Assert.isTrue(selectionCuIndex != -1, "parameter selectionCuQName must match some String in cuQNames."); + failHelper1(cuQNames, selectionCuIndex, startLine, startColumn, endLine, endColumn, newReceiverType, newReceiverName, null, originalReceiverParameterName, inlineDelegator, removeDelegator); + } + + private int firstIndexOf(String one, String[] others) { + for (int i= 0; i < others.length; i++) + if (one == null && others[i] == null || one.equals(others[i])) + return i; + return -1; + } + + private String getQualifier(String qualifiedName) { + int dot= qualifiedName.lastIndexOf('.'); + return qualifiedName.substring(0, dot != -1 ? dot : 0); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH + successPath(); + } + + private String getSimpleName(String qualifiedName) { + return qualifiedName.substring(qualifiedName.lastIndexOf('.') + 1); + } + + private void helper1(String[] cuQNames, int selectionCuIndex, int startLine, int startColumn, int endLine, int endColumn, int newTargetType, String newTargetName, String newMethodName, boolean inlineDelegator, boolean removeDelegator) throws Exception { + Assert.isTrue(0 <= selectionCuIndex && selectionCuIndex < cuQNames.length); + + toSucceed= true; + + ICompilationUnit[] cus= createCUs(cuQNames); + ICompilationUnit selectionCu= cus[selectionCuIndex]; + + ISourceRange selection= TextRangeUtil.getSelection(selectionCu, startLine, startColumn, endLine, endColumn); + IMethod method= getMethod(selectionCu, selection); + assertNotNull(method); + MoveInstanceMethodProcessor processor= new MoveInstanceMethodProcessor(method, JavaPreferencesSettings.getCodeGenerationSettings(selectionCu.getJavaProject())); + Refactoring ref= new MoveRefactoring(processor); + + assertNotNull("refactoring should be created", ref); + RefactoringStatus preconditionResult= ref.checkInitialConditions(new NullProgressMonitor()); + + assertTrue("activation was supposed to be successful", preconditionResult.isOK()); + + chooseNewTarget(processor, newTargetType, newTargetName); + + processor.setInlineDelegator(inlineDelegator); + processor.setRemoveDelegator(removeDelegator); + processor.setDeprecateDelegates(false); + if (newMethodName != null) + processor.setMethodName(newMethodName); + + preconditionResult.merge(ref.checkFinalConditions(new NullProgressMonitor())); + + assertTrue("precondition was supposed to pass", !preconditionResult.hasError()); + + performChange(ref, false); + + for (int i= 0; i < cus.length; i++) { + String outputTestFileName= getOutputTestFileName(getSimpleName(cuQNames[i])); + assertEqualLines("Incorrect inline in " + outputTestFileName, getFileContents(outputTestFileName), cus[i].getSource()); + } + } + + private void helper1(String[] cuQNames, int selectionCuIndex, int startLine, int startColumn, int endLine, int endColumn, int newTargetType, String newTargetName, String newMethodName, boolean inlineDelegator, boolean removeDelegator, boolean deprecate) throws Exception { + Assert.isTrue(0 <= selectionCuIndex && selectionCuIndex < cuQNames.length); + + toSucceed= true; + + ICompilationUnit[] cus= createCUs(cuQNames); + ICompilationUnit selectionCu= cus[selectionCuIndex]; + + ISourceRange selection= TextRangeUtil.getSelection(selectionCu, startLine, startColumn, endLine, endColumn); + IMethod method= getMethod(selectionCu, selection); + assertNotNull(method); + MoveInstanceMethodProcessor processor= new MoveInstanceMethodProcessor(method, JavaPreferencesSettings.getCodeGenerationSettings(selectionCu.getJavaProject())); + Refactoring ref= new MoveRefactoring(processor); + + assertNotNull("refactoring should be created", ref); + RefactoringStatus preconditionResult= ref.checkInitialConditions(new NullProgressMonitor()); + + assertTrue("activation was supposed to be successful", preconditionResult.isOK()); + + chooseNewTarget(processor, newTargetType, newTargetName); + + processor.setInlineDelegator(inlineDelegator); + processor.setRemoveDelegator(removeDelegator); + processor.setDeprecateDelegates(deprecate); + if (newMethodName != null) + processor.setMethodName(newMethodName); + + preconditionResult.merge(ref.checkFinalConditions(new NullProgressMonitor())); + + assertTrue("precondition was supposed to pass", !preconditionResult.hasError()); + + performChange(ref, false); + + for (int i= 0; i < cus.length; i++) { + String outputTestFileName= getOutputTestFileName(getSimpleName(cuQNames[i])); + assertEqualLines("Incorrect inline in " + outputTestFileName, getFileContents(outputTestFileName), cus[i].getSource()); + } + } + + private void helper1(String[] cuQNames, String selectionCuQName, int startLine, int startColumn, int endLine, int endColumn, int newReceiverType, String newReceiverName, boolean inlineDelegator, boolean removeDelegator) throws Exception { + int selectionCuIndex= firstIndexOf(selectionCuQName, cuQNames); + Assert.isTrue(selectionCuIndex != -1, "parameter selectionCuQName must match some String in cuQNames."); + helper1(cuQNames, selectionCuIndex, startLine, startColumn, endLine, endColumn, newReceiverType, newReceiverName, null, inlineDelegator, removeDelegator); + } + + private void helper1(String[] cuQNames, String selectionCuQName, int startLine, int startColumn, int endLine, int endColumn, int newReceiverType, String newReceiverName, boolean inlineDelegator, boolean removeDelegator, boolean deprecate) throws Exception { + int selectionCuIndex= firstIndexOf(selectionCuQName, cuQNames); + Assert.isTrue(selectionCuIndex != -1, "parameter selectionCuQName must match some String in cuQNames."); + helper1(cuQNames, selectionCuIndex, startLine, startColumn, endLine, endColumn, newReceiverType, newReceiverName, null, inlineDelegator, removeDelegator, deprecate); + } + + private String successPath() { + return toSucceed ? "/canMove/" : "/cannotMove/"; + } + + // --- TESTS + + // Move mA1 to parameter b, do not inline delegator + public void test0() throws Exception { + helper1(new String[] { "p1.A", "p2.B", "p3.C"}, "p1.A", 11, 17, 11, 20, PARAMETER, "b", false, false); + } + + // Move mA1 to parameter b, inline delegator + public void test1() throws Exception { + // printTestDisabledMessage("not implemented yet"); + helper1(new String[] { "p1.A", "p2.B", "p3.C"}, "p1.A", 11, 17, 11, 20, PARAMETER, "b", true, false); + } + + // multiple parameters, some left of new receiver parameter, some right of it, + // "this" is NOT passed as argument, (since it's not used in the method) + public void test10() throws Exception { + helper1(new String[] { "p1.A", "p2.B"}, "p1.A", 14, 17, 14, 17, PARAMETER, "b", false, false); + } + + // move to field, method has parameters, choice of fields, some non-class type fields + // ("this" is passed as argument) + public void test11() throws Exception { + helper1(new String[] { "p1.A", "p2.B"}, "p1.A", 17, 17, 17, 17, FIELD, "fB", false, false); + } + + // move to field - do not pass 'this' because it's unneeded + public void test12() throws Exception { + helper1(new String[] { "p1.A", "p2.B"}, "p1.A", 14, 17, 14, 20, FIELD, "fB", false, false); + } + + // junit case + public void test13() throws Exception { + helper1(new String[] { "p1.TR", "p1.TC", "p1.P"}, "p1.TR", 9, 20, 9, 23, PARAMETER, "test", false, false); + } + + // simplified junit case + public void test14() throws Exception { + helper1(new String[] { "p1.TR", "p1.TC"}, "p1.TR", 9, 20, 9, 23, PARAMETER, "test", false, false); + } + + // move to type in same cu + public void test15() throws Exception { + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=40120 + helper1(new String[] { "p.A"}, "p.A", 17, 18, 17, 18, PARAMETER, "s", false, false); + } + + // move to inner type in same cu + public void test16() throws Exception { + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=40120 + helper1(new String[] { "p.B"}, "p.B", 15, 17, 15, 22, PARAMETER, "s", false, false); + } + + // don't generate parameter for unused field (bug 38310) + public void test17() throws Exception { + helper1(new String[] { "p.Shape", "p.Rectangle"}, "p.Shape", 11, 16, 11, 20, FIELD, "fBounds", false, false); + } + + // generate parameter for used field (bug 38310) + public void test18() throws Exception { + helper1(new String[] { "p.Shape", "p.Rectangle"}, "p.Shape", 17, 22, 17, 22, FIELD, "fInnerBounds", false, false); + } + + // generate parameter for used field (bug 38310) + public void test19() throws Exception { + helper1(new String[] { "p.Shape", "p.Rectangle"}, "p.Shape", 22, 20, 22, 33, PARAMETER, "rect", false, false); + } + + // // Move mA1 to parameter b, inline delegator, remove delegator + public void test2() throws Exception { + // printTestDisabledMessage("not implemented yet"); + helper1(new String[] { "p1.A", "p2.B", "p3.C"}, "p1.A", 12, 17, 12, 20, PARAMETER, "b", true, true); + } + + // Can move if "super" is used in inner class + public void test20() throws Exception { + helper1(new String[] { "p.A", "p.B", "p.StarDecorator"}, "p.A", 14, 17, 14, 22, PARAMETER, "b", false, false); + } + + // Arguments of method calls preserved in moved body (bug 41468) + public void test21() throws Exception { + helper1(new String[] { "p.A", "p.Second"}, "p.A", 5, 17, 5, 22, FIELD, "s", false, false); + } + + // arguments of method calls preserved in moved body (bug 41468), + // use "this" instead of field (bug 38310) + public void test22() throws Exception { + helper1(new String[] { "p.A", "p.Second"}, "p.A", 5, 17, 5, 22, FIELD, "s", false, false); + } + + // "this"-qualified field access: this.s -> this (bug 41597) + public void test23() throws Exception { + helper1(new String[] { "p.A", "p.Second"}, "p.A", 5, 17, 5, 22, FIELD, "s", false, false); + } + + // move local class (41530) + public void test24() throws Exception { + helper1(new String[] { "p1.A", "p1.B", "p1.StarDecorator"}, "p1.A", 9, 17, 9, 22, PARAMETER, "b", false, false); + } + + // extended junit case + public void test25() throws Exception { + helper1(new String[] { "p1.TR", "p1.TC", "p1.P"}, "p1.TR", 4, 20, 4, 23, PARAMETER, "test", false, false); + } + + // extended junit case with generics (bug 77653) + public void test26() throws Exception { + helper1(new String[] { "p1.TR", "p1.TC", "p1.P"}, "p1.TR", 9, 20, 9, 23, PARAMETER, "test", false, false); + } + + // extended junit case with generics and deprecation message + public void test27() throws Exception { + helper1(new String[] { "p1.TR", "p1.TC", "p1.P"}, "p1.TR", 9, 20, 9, 23, PARAMETER, "test", false, false, true); + } + + // extended junit case with generics, enums and deprecation message + public void test28() throws Exception { + helper1(new String[] { "p1.TR", "p1.TC", "p1.P"}, "p1.TR", 9, 20, 9, 23, PARAMETER, "test", false, false, true); + } + + // extended junit case with generics, enums and deprecation message + public void test29() throws Exception { + helper1(new String[] { "p1.TR", "p1.TC", "p1.P"}, "p1.TR", 9, 20, 9, 23, PARAMETER, "test", false, false, true); + } + + // extended junit case with generics, enums, static imports and deprecation message + public void test30() throws Exception { + helper1(new String[] { "p1.TR", "p1.TC", "p1.P"}, "p1.TR", 10, 21, 10, 21, PARAMETER, "test", false, false, true); + } + + // extended junit case with generics, enums, static imports and deprecation message + public void test31() throws Exception { + printTestDisabledMessage("disabled due to missing support for statically imported methods"); +// helper1(new String[] { "p1.TR", "p1.TC", "p1.P"}, "p1.TR", 10, 21, 10, 21, PARAMETER, "test", false, false, true); + } + + public void test32() throws Exception { + helper1(new String[] { "p1.A"}, "p1.A", 9, 25, 9, 26, PARAMETER, "p", true, true); + } + + // Test visibility of a target field is not affected. + public void test33() throws Exception { + helper1(new String[] { "p.Foo", "p.Bar" }, "p.Foo", 6, 18, 6, 21, FIELD, "_bar", false, false); + } + + // Test visibility of target field is changed to public + // in case a caller is in another package (bug 117465). + public void test34() throws Exception { + helper1(new String[] { "test1.TestTarget", "test1.Test1", "test2.Test2"}, "test1.Test1", 3, 21, 3, 33, FIELD, "target", true, true); + } + + // Test visibility of target field is changed to default + // in case a caller is in the same package (bug 117465). + public void test35() throws Exception { + helper1(new String[] { "test1.TestTarget", "test1.Test1", "test1.Test2"}, "test1.Test1", 3, 21, 3, 33, FIELD, "target", true, true); + } + + // Test search engine for secondary types (bug 108030). + public void test36() throws Exception { + helper1(new String[] { "p.A", "p.B" }, "p.A", 9, 17, 9, 27, FIELD, "fB", false, false); + } + + // Test name conflicts in the moved method between fields and parameters (bug 227876) + public void test37() throws Exception { + helper1(new String[] { "p.A", "p.B" }, "p.A", 4, 17, 4, 42, FIELD, "destination", true, true); + } + + // Test problem with parameter order (bug 165697) + public void test38() throws Exception { + helper1(new String[] { "p.A", "p.B" }, "p.A", 4, 17, 4, 35, FIELD, "target", true, true); + } + + // Test problem with qualified accesses (bug 149316) + public void test39() throws Exception { + helper1(new String[] { "p.A", "p.B" }, "p.A", 4, 13, 4, 25, PARAMETER, "p", true, true); + } + + // Test problem with qualified accesses (bug 149316) + public void test40() throws Exception { + helper1(new String[] { "p.A", "p.B" }, "p.A", 4, 13, 4, 25, PARAMETER, "p", true, true); + } + + // Move mA1 to field fB, do not inline delegator + public void test3() throws Exception { + helper1(new String[] { "p1.A", "p2.B", "p3.C"}, "p1.A", 9, 17, 9, 20, FIELD, "fB", false, false); + } + + // // Move mA1 to field fB, inline delegator, remove delegator + public void test4() throws Exception { + // printTestDisabledMessage("not implemented yet"); + helper1(new String[] { "p1.A", "p2.B", "p3.C"}, "p1.A", 9, 17, 9, 20, FIELD, "fB", true, true); + } + + // Move mA1 to field fB, unqualified static member references are qualified + public void test5() throws Exception { + helper1(new String[] { "p1.A", "p2.B"}, "p1.A", 15, 19, 15, 19, FIELD, "fB", false, false); + } + + // class qualify referenced type name to top level, original receiver not used in method + public void test6() throws Exception { + helper1(new String[] { "p1.Nestor", "p2.B"}, "p1.Nestor", 11, 17, 11, 17, PARAMETER, "b", false, false); + } + + public void test7() throws Exception { + helper1(new String[] { "p1.A", "p2.B", "p3.N1"}, "p1.A", 8, 17, 8, 18, PARAMETER, "b", false, false); + } + + // access to fields, non-void return type + public void test8() throws Exception { + helper1(new String[] { "p1.A", "p2.B"}, "p1.A", 15, 19, 15, 20, PARAMETER, "b", false, false); + } + + // multiple parameters, some left of new receiver parameter, some right of it, + // "this" is passed as argument + public void test9() throws Exception { + helper1(new String[] { "p1.A", "p2.B"}, "p1.A", 6, 17, 6, 17, PARAMETER, "b", false, false); + } + + // Cannot move interface method declaration + public void testFail0() throws Exception { + failHelper1("p1.IA", 5, 17, 5, 20, PARAMETER, "b", true, true); + } + + // Cannot move abstract method declaration + public void testFail1() throws Exception { + failHelper1("p1.A", 5, 26, 5, 29, PARAMETER, "b", true, true); + } + + // Cannot move method if there's no new potential receiver + public void testFail10() throws Exception { + failHelper1(new String[] { "p1.A", "p2.B", "p3.C"}, "p1.A", 8, 17, 8, 20, PARAMETER, "b", true, true); + } + + // Cannot move method - parameter name conflict + public void testFail11() throws Exception { + failHelper2(new String[] { "p1.A", "p2.B"}, "p1.A", 7, 17, 7, 20, PARAMETER, "b", "a", true, true); + } + + // Cannot move method if there's no new potential receiver (because of null bindings here) + public void testFail12() throws Exception { + // printTestDisabledMessage("bug 39871"); + failHelper1(new String[] { "p1.A"}, "p1.A", 5, 10, 5, 16, PARAMETER, "b", true, true); + } + + // Cannot move method - annotations are not supported + public void testFail13() throws Exception { + printTestDisabledMessage("disabled - jcore does not have elements for annotation members"); +// failHelper2(new String[] { "p1.A", "p2.B"}, "p1.A", 5, 12, 5, 13, PARAMETER, "b", "a", true, true); + } + + // Cannot move static method + public void testFail2() throws Exception { + failHelper1(new String[] { "p1.A", "p2.B"}, "p1.A", 6, 23, 6, 24, PARAMETER, "b", true, true); + } + + // Cannot move native method + public void testFail3() throws Exception { + failHelper1(new String[] { "p1.A", "p2.B"}, "p1.A", 6, 23, 6, 24, PARAMETER, "b", true, true); + } + + // Cannot move method that references "super" + public void testFail4() throws Exception { + failHelper1(new String[] { "p1.A", "p2.B"}, "p1.A", 11, 20, 11, 21, PARAMETER, "b", true, true); + } + + // Cannot move method that references an enclosing instance + public void testFail5() throws Exception { + failHelper1(new String[] { "p1.A", "p2.B"}, "p1.A", 8, 21, 8, 21, PARAMETER, "b", true, true); + } + + // Cannot move potentially directly recursive method + public void testFail6() throws Exception { + failHelper1(new String[] { "p1.A", "p2.B"}, "p1.A", 6, 16, 6, 17, PARAMETER, "b", true, true); + } + + // Cannot move synchronized method + public void testFail8() throws Exception { + failHelper1(new String[] { "p1.A", "p2.B"}, "p1.A", 6, 29, 6, 29, PARAMETER, "b", true, true); + } + + // Cannot move method if there's no new potential receiver + public void testFail9() throws Exception { + failHelper1(new String[] { "p1.A", "p2.B", "p3.C"}, "p1.A", 7, 17, 7, 20, PARAMETER, "b", true, true); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveMembersTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveMembersTests.java new file mode 100644 index 000000000..6cf053371 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveMembersTests.java @@ -0,0 +1,739 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.MoveArguments; +import org.eclipse.ltk.core.refactoring.participants.MoveRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; +import org.eclipse.jdt.internal.corext.refactoring.structure.MoveStaticMembersProcessor; +import org.eclipse.jdt.internal.corext.refactoring.tagging.IDelegateUpdating; + +import org.eclipse.jdt.ui.tests.refactoring.infra.DebugUtils; + +import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; + +public class MoveMembersTests extends RefactoringTest { + + private static final Class clazz= MoveMembersTests.class; + + private static final String REFACTORING_PATH= "MoveMembers/"; + + public MoveMembersTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + //--- + private static MoveRefactoring createRefactoring(IMember[] members, IType destination) throws JavaModelException{ + return createRefactoring(members, destination.getFullyQualifiedName()); + } + + private static MoveRefactoring createRefactoring(IMember[] members, String destination) throws JavaModelException{ + IJavaProject project= null; + if (members != null && members.length > 0) + project= members[0].getJavaProject(); + MoveStaticMembersProcessor processor= (RefactoringAvailabilityTester.isMoveStaticMembersAvailable(members) ? new MoveStaticMembersProcessor(members, JavaPreferencesSettings.getCodeGenerationSettings(project)) : null); + if (processor == null) + return null; + processor.setDestinationTypeFullyQualifiedName(destination); + return new MoveRefactoring(processor); + } + + protected void setUp() throws Exception { + if (fIsVerbose) + DebugUtils.dump("--------- " + getName() + " ---------------"); + super.setUp(); + fIsPreDeltaTest= true; + } + + private void fieldMethodTypePackageHelper_passing(String[] fieldNames, String[] methodNames, String[][] signatures, String[] typeNames, IPackageFragment packForA, IPackageFragment packForB, boolean addDelegate) throws Exception { + ParticipantTesting.reset(); + ICompilationUnit cuA= createCUfromTestFile(packForA, "A"); + ICompilationUnit cuB= createCUfromTestFile(packForB, "B"); + IType typeA= getType(cuA, "A"); + IType typeB= getType(cuB, "B"); + IField[] fields= getFields(typeA, fieldNames); + IMethod[] methods= getMethods(typeA, methodNames, signatures); + IType[] types= getMemberTypes(typeA, typeNames); + + IType destinationType= typeB; + IMember[] members= merge(methods, fields, types); + String[] handles= ParticipantTesting.createHandles(members); + MoveArguments[] args= new MoveArguments[handles.length]; + for (int i = 0; i < args.length; i++) { + args[i]= new MoveArguments(destinationType, true); + } + MoveRefactoring ref= createRefactoring(members, destinationType); + + IDelegateUpdating delUp= (IDelegateUpdating) ref.getProcessor().getAdapter(IDelegateUpdating.class); + delUp.setDelegateUpdating(addDelegate); + + RefactoringStatus result= performRefactoringWithStatus(ref); + assertTrue("precondition was supposed to pass", result.getSeverity() <= RefactoringStatus.WARNING); + ParticipantTesting.testMove(handles, args); + + String expected; + String actual; + + expected= getFileContents(getOutputTestFileName("A")); + actual= cuA.getSource(); + assertEqualLines("incorrect modification of A", expected, actual); + + expected= getFileContents(getOutputTestFileName("B")); + actual= cuB.getSource(); + assertEqualLines("incorrect modification of B", expected, actual); + //tearDown() deletes resources and does performDummySearch(); + } + + /* Move members from p.A to r.B */ + private void fieldMethodTypeABHelper_passing(String[] fieldNames, String[] methodNames, String[][] signatures, String[] typeNames) throws Exception { + IPackageFragment packageForB= getRoot().createPackageFragment("r", false, null); + fieldMethodTypePackageHelper_passing(fieldNames, methodNames, signatures, typeNames, getPackageP(), packageForB, false); + //tearDown() deletes resources and does performDummySearch(); + } + + private void fieldMethodTypeHelper_passing(String[] fieldNames, String[] methodNames, String[][] signatures, String[] typeNames, boolean addDelegates) throws Exception{ + IPackageFragment packForA= getPackageP(); + IPackageFragment packForB= getPackageP(); + fieldMethodTypePackageHelper_passing(fieldNames, methodNames, signatures, typeNames, packForA, packForB, addDelegates); + } + + private void fieldHelper_passing(String[] fieldNames) throws Exception { + fieldMethodTypeHelper_passing(fieldNames, new String[0], new String[0][0], new String[0], false); + } + + private void fieldHelperDelegate_passing(String[] fieldNames) throws Exception { + fieldMethodTypeHelper_passing(fieldNames, new String[0], new String[0][0], new String[0], true); + } + + private void methodHelper_passing(String[] methodNames, String[][] signatures) throws Exception { + fieldMethodTypeHelper_passing(new String[0], methodNames, signatures, new String[0], false); + } + + private void methodHelperDelegate_passing(String[] methodNames, String[][] signatures) throws Exception { + fieldMethodTypeHelper_passing(new String[0], methodNames, signatures, new String[0], true); + } + + private void typeHelper_passing(String[] typeNames) throws Exception { + fieldMethodTypeHelper_passing(new String[0], new String[0], new String[0][0], typeNames, false); + } + + private void fieldMethodTypePackageHelper_failing(String[] fieldNames, + String[] methodNames, String[][] signatures, + String[] typeNames, + int errorLevel, String destinationTypeName, + IPackageFragment packForA, + IPackageFragment packForB) throws Exception { + ICompilationUnit cuA= createCUfromTestFile(packForA, "A"); + ICompilationUnit cuB= createCUfromTestFile(packForB, "B"); + try{ + IType typeA= getType(cuA, "A"); + IField[] fields= getFields(typeA, fieldNames); + IMethod[] methods= getMethods(typeA, methodNames, signatures); + IType[] types= getMemberTypes(typeA, typeNames); + + MoveRefactoring ref= createRefactoring(merge(methods, fields, types), destinationTypeName); + if (ref == null){ + assertEquals(errorLevel, RefactoringStatus.FATAL); + return; + } + + RefactoringStatus result= performRefactoring(ref); + if (fIsVerbose) + DebugUtils.dump("status:" + result); + assertNotNull("precondition was supposed to fail", result); + assertEquals("precondition was supposed to fail", errorLevel, result.getSeverity()); + + } finally{ + performDummySearch(); + cuA.delete(false, null); + cuB.delete(false, null); + } + } + + private void fieldMethodTypeHelper_failing(String[] fieldNames, + String[] methodNames, String[][] signatures, + String[] typeNames, + int errorLevel, String destinationTypeName) throws Exception { + IPackageFragment packForA= getPackageP(); + IPackageFragment packForB= getPackageP(); + fieldMethodTypePackageHelper_failing(fieldNames, methodNames, signatures, typeNames, + errorLevel, destinationTypeName, packForA, packForB); + } + + + //--- + + public void test0() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test1() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test2() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test3() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test4() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test5() throws Exception{ + fieldHelper_passing(new String[]{"f"}); + } + + public void test6() throws Exception{ + fieldHelper_passing(new String[]{"f"}); + } + + public void test7() throws Exception{ + fieldHelper_passing(new String[]{"f"}); + } + + public void test8() throws Exception{ +// printTestDisabledMessage("36835"); + IPackageFragment packageForB= null; + try{ + packageForB= getRoot().createPackageFragment("r", false, null); + fieldMethodTypePackageHelper_passing(new String[]{"f"}, new String[0], new String[0][0], new String[0], getPackageP(), packageForB, false); + } finally{ + performDummySearch(); + if (packageForB != null) + packageForB.delete(true, null); + } + } + + public void test9() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test10() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test11() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test12() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test13() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test14() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test15() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test16() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test17() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test18() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test19() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test20() throws Exception{ + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test21() throws Exception{ + printTestDisabledMessage("not currently handling visibility issues induced by moving more than one static member"); + //fieldHelper_passing(new String[]{"F", "i"}); + } + + public void test22() throws Exception{ + fieldHelper_passing(new String[]{"i"}); + } + + public void test23() throws Exception{ + fieldHelper_passing(new String[]{"FRED"}); + } + + public void test24() throws Exception{ + fieldHelper_passing(new String[]{"FRED"}); + } + + public void test25() throws Exception{ + //printTestDisabledMessage("test for 27098"); + fieldHelper_passing(new String[]{"FRED"}); + } + + public void test26() throws Exception{ + IPackageFragment packageForB= null; + try{ + packageForB= getRoot().createPackageFragment("r", false, null); + fieldMethodTypePackageHelper_passing(new String[0], new String[]{"n"}, new String[][]{new String[0]}, new String[0], getPackageP(), packageForB, false); + } finally{ + performDummySearch(); + if (packageForB != null) + packageForB.delete(true, null); + } + } + + public void test27() throws Exception{ + IPackageFragment packageForB= null; + try{ + packageForB= getRoot().createPackageFragment("r", false, null); + fieldMethodTypePackageHelper_passing(new String[0], new String[]{"n"}, new String[][]{new String[0]}, new String[0], getPackageP(), packageForB, false); + } finally{ + performDummySearch(); + if (packageForB != null) + packageForB.delete(true, null); + } + } + + public void test28() throws Exception{ + methodHelper_passing(new String[]{"m", "n"}, new String[][]{new String[0], new String[0]}); + } + + public void test29() throws Exception{ //test for bug 41691 + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test30() throws Exception{ //test for bug 41691 + fieldHelper_passing(new String[]{"id"}); + } + + public void test31() throws Exception{ //test for bug 41691 + fieldHelper_passing(new String[]{"odd"}); + } + + public void test32() throws Exception{ //test for bug 41734, 41691 + printTestDisabledMessage("test for 41734"); + //methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test33() throws Exception{ //test for bug 28022 + fieldHelper_passing(new String[]{"i"}); + } + + public void test34() throws Exception{ //test for bug 28022 + fieldHelper_passing(new String[]{"i"}); + } + + public void test35() throws Exception{ //test for bug 28022 + fieldHelper_passing(new String[]{"i"}); + } + + //-- move types: + + public void test36() throws Exception { + typeHelper_passing(new String[]{"I"}); + } + + public void test37() throws Exception { + printTestDisabledMessage("qualified access to source"); +// typeHelper_passing(new String[] {"Inner"}); + } + + public void test38() throws Exception { + fieldMethodTypeABHelper_passing(new String[0], new String[0], new String[0][0], new String[]{"Inner"}); + } + + public void test39() throws Exception { + printTestDisabledMessage("complex imports - need more work"); +// fieldMethodType3CUsHelper_passing(new String[0], new String[0], new String[0][0], +// new String[]{"Inner"}); + } + + public void test40() throws Exception{ + fieldMethodTypeHelper_passing(new String[] {"f"}, new String[]{"m"}, new String[][]{new String[0]}, new String[0], false); + } + + public void test41() throws Exception{ + methodHelper_passing(new String[] {"m"}, new String[][]{new String[0]}); + } + + //-- Visibility issues in the moved member: + + public void test42() throws Exception{ + //former testFail9 + //Tests move of public static method m, which references private method f, into same package. + methodHelper_passing(new String[] {"m"}, new String[][]{new String[0]}); + } + + public void test43() throws Exception{ + //former testFail10 + //Tests move of public static method m, which references private field F, into same package + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test44() throws Exception{ + //former testFail11 + //Tests move of public static field i, which references private field F, into same package + fieldHelper_passing(new String[]{"i"}); + } + + public void test45() throws Exception{ + //former testFail12 + //Tests move of public static field i, which references private method m, into same package + fieldHelper_passing(new String[]{"i"}); + } + + public void test46() throws Exception{ + //former testFail13 + //Tests move of public static method m, which gets referenced by a field, into same package + methodHelper_passing(new String[]{"m"}, new String[][]{new String[0]}); + } + + public void test47() throws Exception{ + //former testFail14 + //Tests move of public static field i, which gets referenced by a field, into same package + fieldHelper_passing(new String[]{"i"}); + } + + public void test48() throws Exception{ + //Move private unused method which calls another private method into another package + IPackageFragment packageForB= null; + try{ + packageForB= getRoot().createPackageFragment("r", false, null); + fieldMethodTypePackageHelper_passing(new String[0], new String[]{"bar"}, new String[][]{new String[0]}, new String[0], getPackageP(), packageForB, false); + } finally{ + performDummySearch(); + if (packageForB != null) + packageForB.delete(true, null); + } + } + + // --- Visibility issues of the moved member itself + + public void test49() throws Exception{ + //Move protected used field into another package + IPackageFragment packageForB= null; + try{ + packageForB= getRoot().createPackageFragment("r", false, null); + fieldMethodTypePackageHelper_passing(new String[]{"someVar"}, new String[0], new String[][]{new String[0]}, new String[0], getPackageP(), packageForB, false); + } finally{ + performDummySearch(); + if (packageForB != null) + packageForB.delete(true, null); + } + } + + public void test50() throws Exception{ + //Move private used method into subtype. + methodHelper_passing(new String[]{"foo"}, new String[][]{new String[0]}); + } + + public void test51() throws Exception { + //Move private static inner class with private field (but used in outer class) + //assure both class and field get their visibility increased + typeHelper_passing(new String[] { "Inner" }); + } + + public void test52() throws Exception { + // assure moved unused field keeps its visibility + fieldHelper_passing(new String[] { "a" }); + } + + public void test53() throws Exception { + // assure moved unusued class keeps its visibility + typeHelper_passing(new String[] { "C" }); + } + + public void test54() throws Exception { + // moved used method is changed in visibility + methodHelper_passing(new String[] { "b" }, new String[][]{new String[0]}); + } + + public void test55() throws Exception { + // moved used method is changed in visibility + typeHelper_passing(new String[] { "C" }); + } + + // --- Visibility of members of the moved type + + public void test56() throws Exception { + // Move an inner class with two USED members + typeHelper_passing(new String[] { "Inner" }); + } + + public void test57() throws Exception { + // Move an inner class with two UNUSED members + typeHelper_passing(new String[] { "Inner" }); + } + + // --- Visibility of used outer members + + public void test58() throws Exception { + // Move a type which references a field in an enclosing type + // and a field in a sibling + typeHelper_passing(new String[] { "Inner" }); + } + + public void test59() throws Exception { + // Move a type which references a field in an enclosing type, + // and the enclosing type is private + typeHelper_passing(new String[] { "SomeInner.Inner" }); + } + + public void test60() throws Exception{ + // Move a static private "getter" of a static field into another class + // only the field should be changed to public (bug 122490) + IPackageFragment packageForB= null; + try{ + packageForB= getRoot().createPackageFragment("e", false, null); + fieldMethodTypePackageHelper_passing(new String[0], new String[] { "getNAME" }, new String[][]{new String[0]}, new String[0], getPackageP(), packageForB, false); + } finally{ + performDummySearch(); + if (packageForB != null) + packageForB.delete(true, null); + } + } + + public void test61() throws Exception{ + // Move some method which references a field with a getter and a setter + // only the field should be changed to public (bug 122490) + IPackageFragment packageForB= null; + try{ + packageForB= getRoot().createPackageFragment("e", false, null); + fieldMethodTypePackageHelper_passing(new String[0], new String[] { "foo" }, new String[][]{new String[0]}, new String[0], getPackageP(), packageForB, false); + } finally{ + performDummySearch(); + if (packageForB != null) + packageForB.delete(true, null); + } + } + + // parameterized type references + + + public void test62() throws Exception { + // Move a type which references a field in an enclosing type + // and a field in a sibling + typeHelper_passing(new String[] { "SomeInner" }); + } + + //--- + public void testFail0() throws Exception{ + fieldMethodTypeHelper_failing(new String[0], + new String[]{"m"}, new String[][]{new String[0]}, + new String[0], + RefactoringStatus.FATAL, "p.B"); + } + + + public void testFail1() throws Exception{ + fieldMethodTypeHelper_failing(new String[0], + new String[]{"m"}, new String[][]{new String[0]}, + new String[0], + RefactoringStatus.ERROR, "p.B.X"); + } + + public void testFail2() throws Exception{ + fieldMethodTypeHelper_failing(new String[0], + new String[]{"m"}, new String[][]{new String[0]}, + new String[0], + RefactoringStatus.ERROR, "p.B"); + } + + public void testFail3() throws Exception{ + fieldMethodTypeHelper_failing(new String[0], + new String[]{"m"}, new String[][]{new String[]{"I", "I"}}, + new String[0], + RefactoringStatus.ERROR, "p.B"); + } + + public void testFail4() throws Exception{ + fieldMethodTypeHelper_failing(new String[0], + new String[]{"m"}, new String[][]{new String[]{"I", "I"}}, + new String[0], + RefactoringStatus.WARNING, "p.B"); + } + + public void testFail5() throws Exception{ + fieldMethodTypeHelper_failing(new String[0], + new String[]{"m"}, new String[][]{new String[]{"I", "I"}}, + new String[0], + RefactoringStatus.WARNING, "p.B"); + } + + public void testFail6() throws Exception{ + fieldMethodTypeHelper_failing(new String[]{"i"}, new String[0], new String[0][0], new String[0], + RefactoringStatus.ERROR, "p.B"); + } + + public void testFail7() throws Exception{ + fieldMethodTypeHelper_failing(new String[]{"i"}, new String[0], new String[0][0], new String[0], + RefactoringStatus.ERROR, "p.B"); + } + + public void testFail8() throws Exception{ + fieldMethodTypeHelper_failing(new String[]{"i"}, new String[0], new String[0][0], new String[0], + RefactoringStatus.ERROR, "p.B"); + } + + public void testFail15() throws Exception{ + fieldMethodTypeHelper_failing(new String[0], + new String[]{"m"}, new String[][]{new String[0]}, new String[0], + RefactoringStatus.WARNING, "p.B"); + } + + public void testFail16() throws Exception{ + IPackageFragment packageForB= null; + try{ + packageForB= getRoot().createPackageFragment("r", false, null); + fieldMethodTypePackageHelper_failing(new String[]{"f"}, new String[0], new String[0][0], new String[0], + RefactoringStatus.ERROR, "r.B", + getPackageP(), packageForB); + } finally{ + performDummySearch(); + if (packageForB != null) + packageForB.delete(true, null); + } + } + + public void testFail17() throws Exception{ + fieldMethodTypeHelper_failing(new String[0], + new String[]{"m"}, new String[][]{new String[0]}, new String[0], + RefactoringStatus.FATAL, "java.lang.Object"); + } + + public void testFail18() throws Exception{ + fieldMethodTypeHelper_failing(new String[0], + new String[]{"m"}, new String[][]{new String[0]}, new String[0], + RefactoringStatus.FATAL, "p.DontExist"); + } + + public void testFail19() throws Exception{ + fieldMethodTypeHelper_failing(new String[0], + new String[]{"m"}, new String[][]{new String[0]}, new String[0], + RefactoringStatus.ERROR, "p.B"); + } + + public void testFail20() throws Exception{ + // was same as test19 + } + + public void testFail21() throws Exception{ + fieldMethodTypeHelper_failing(new String[0], + new String[]{"m"}, new String[][]{new String[0]}, new String[0], + RefactoringStatus.FATAL, "p.B"); + } + + public void testFail22() throws Exception{ + //free slot + } + + public void testFail23() throws Exception{ + //free slot + } + + public void testFail24() throws Exception{ + fieldMethodTypeHelper_failing(new String[0], + new String[]{"m"}, new String[][]{new String[0]}, new String[0], + RefactoringStatus.FATAL, "p.B"); + } + + // Delegate creation + + public void testDelegate01() throws Exception { + // simple delegate method + methodHelperDelegate_passing(new String[] { "foo" }, new String[][]{new String[0]}); + } + + public void testDelegate02() throws Exception { + // increase visibility + methodHelperDelegate_passing(new String[] { "foo" }, new String[][]{new String[0]}); + } + + public void testDelegate03() throws Exception { + // ensure imports are removed correctly + methodHelperDelegate_passing(new String[] { "foo" }, new String[][]{new String[0]}); + } + + public void testDelegate04() throws Exception{ + // add import when moving to another package + IPackageFragment packageForB= null; + try{ + packageForB= getRoot().createPackageFragment("r", false, null); + fieldMethodTypePackageHelper_passing(new String[0], new String[] { "foo" }, new String[][]{new String[0]}, new String[0], getPackageP(), packageForB, true); + } finally{ + performDummySearch(); + if (packageForB != null) + packageForB.delete(true, null); + } + } + + public void testDelegate05() throws Exception { + // simple delegate field + fieldHelperDelegate_passing(new String[] { "FOO" }); + } + + public void testDelegate06() throws Exception { + // increase visibility + fieldHelperDelegate_passing(new String[] { "FOO" }); + } + + public void testDelegate07() throws Exception { + // remove imports correctly + fieldHelperDelegate_passing(new String[] { "FOO" }); + } + + public void testDelegate08() throws Exception{ + // add import when moving to another package + IPackageFragment packageForB= null; + try{ + packageForB= getRoot().createPackageFragment("r", false, null); + fieldMethodTypePackageHelper_passing(new String[] { "FOO" }, new String[0], new String[][]{new String[0]}, new String[0], getPackageP(), packageForB, true); + } finally{ + performDummySearch(); + if (packageForB != null) + packageForB.delete(true, null); + } + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/NullRefactoring.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/NullRefactoring.java new file mode 100644 index 000000000..4e42c3509 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/NullRefactoring.java @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.NullChange; +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +/** + * useful for tests + */ +public class NullRefactoring extends Refactoring { + + public Change createChange(IProgressMonitor pm) throws CoreException { + pm.beginTask("", 1); + pm.worked(1); + pm.done(); + return new NullChange("NullRefactoring"); + } + + + public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException { + pm.beginTask("", 1); + pm.worked(1); + pm.done(); + return new RefactoringStatus(); + } + + public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException { + pm.beginTask("", 1); + pm.worked(1); + pm.done(); + return new RefactoringStatus(); + } + + public String getName() { + return "Null Refactoring"; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ParticipantTesting.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ParticipantTesting.java new file mode 100644 index 000000000..e299044c0 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ParticipantTesting.java @@ -0,0 +1,168 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Assert; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.ltk.core.refactoring.participants.CopyArguments; +import org.eclipse.ltk.core.refactoring.participants.MoveArguments; +import org.eclipse.ltk.core.refactoring.participants.RenameArguments; + +import org.eclipse.jdt.core.IJavaElement; + +import org.eclipse.jdt.internal.corext.util.JavaElementResourceMapping; + + +public class ParticipantTesting { + + public static void reset() { + TestCreateParticipantShared.reset(); + TestDeleteParticipantShared.reset(); + TestMoveParticipantShared.reset(); + TestRenameParticipantShared.reset(); + TestCopyParticipantShared.reset(); + + TestCreateParticipantSingle.reset(); + TestDeleteParticipantSingle.reset(); + TestMoveParticipantSingle.reset(); + TestRenameParticipantSingle.reset(); + TestCopyParticipantSingle.reset(); + } + + public static String[] createHandles(Object object) { + return createHandles(new Object[] { object }); + } + + public static String[] createHandles(Object obj1, Object obj2) { + return createHandles(new Object[] { obj1, obj2 }); + } + + public static String[] createHandles(Object obj1, Object obj2, Object obj3) { + return createHandles(new Object[] { obj1, obj2, obj3 }); + } + + public static String[] createHandles(Object obj1, Object obj2, Object obj3, Object obj4) { + return createHandles(new Object[] { obj1, obj2, obj3, obj4 }); + } + + public static String[] createHandles(Object[] elements) { + List result= new ArrayList(); + for (int i= 0; i < elements.length; i++) { + Object element= elements[i]; + if (element instanceof IJavaElement) { + result.add(((IJavaElement)element).getHandleIdentifier()); + } else if (element instanceof IResource) { + result.add(((IResource)element).getFullPath().toString()); + } else if (element instanceof JavaElementResourceMapping) { + result.add(((JavaElementResourceMapping)element). + getJavaElement().getHandleIdentifier() + "_mapping"); + } + } + return (String[])result.toArray(new String[result.size()]); + } + + public static void testRename(String[] expectedHandles, RenameArguments[] args) { + Assert.assertEquals(expectedHandles.length, args.length); + if (expectedHandles.length == 0) { + TestRenameParticipantShared.testNumberOfElements(0); + TestRenameParticipantSingle.testNumberOfInstances(0); + } else { + testElementsShared(expectedHandles, TestRenameParticipantShared.fgInstance.fHandles); + TestRenameParticipantShared.testArguments(args); + + TestRenameParticipantSingle.testNumberOfInstances(expectedHandles.length); + TestRenameParticipantSingle.testElements(expectedHandles); + TestRenameParticipantSingle.testArguments(args); + } + } + + public static void testMove(String[] expectedHandles, MoveArguments[] args) { + Assert.assertEquals(expectedHandles.length, args.length); + if (expectedHandles.length == 0) { + TestMoveParticipantShared.testNumberOfElements(0); + TestMoveParticipantSingle.testNumberOfInstances(0); + } else { + testElementsShared(expectedHandles, TestMoveParticipantShared.fgInstance.fHandles); + TestMoveParticipantShared.testArguments(args); + + TestMoveParticipantSingle.testNumberOfInstances(expectedHandles.length); + TestMoveParticipantSingle.testElements(expectedHandles); + TestMoveParticipantSingle.testArguments(args); + } + } + + public static void testDelete(String[] expectedHandles) { + if (expectedHandles.length == 0) { + TestDeleteParticipantShared.testNumberOfElements(0); + TestDeleteParticipantSingle.testNumberOfInstances(0); + } else { + testElementsShared(expectedHandles, TestDeleteParticipantShared.fgInstance.fHandles); + + TestDeleteParticipantSingle.testNumberOfInstances(expectedHandles.length); + TestDeleteParticipantSingle.testElements(expectedHandles); + } + } + + public static void testCreate(String[] expectedHandles) { + if (expectedHandles.length == 0) { + TestCreateParticipantShared.testNumberOfElements(0); + TestCreateParticipantSingle.testNumberOfInstances(0); + } else { + testElementsShared(expectedHandles, TestCreateParticipantShared.fgInstance.fHandles); + + TestCreateParticipantSingle.testNumberOfInstances(expectedHandles.length); + TestCreateParticipantSingle.testElements(expectedHandles); + } + } + + public static void testCopy(String[] expectedHandles, CopyArguments[] arguments) { + if (expectedHandles.length == 0) { + TestCopyParticipantShared.testNumberOfElements(0); + TestCopyParticipantSingle.testNumberOfInstances(0); + } else { + testElementsShared(expectedHandles, TestCopyParticipantShared.fgInstance.fHandles); + TestCopyParticipantShared.testArguments(arguments); + + TestCopyParticipantSingle.testNumberOfInstances(expectedHandles.length); + TestCopyParticipantSingle.testElements(expectedHandles); + TestCopyParticipantSingle.testArguments(arguments); + } + } + + public static void testSimilarElements(List similarList, List similarNewNameList, List similarNewHandleList) { + Assert.assertEquals(similarList.size(), similarNewNameList.size()); + if (similarList.size() == 0) { + TestRenameParticipantShared.testNumberOfSimilarElements(0); + } else { + TestRenameParticipantShared.testSimilarElements(similarList, similarNewNameList, similarNewHandleList); + } + + } + + private static void testElementsShared(String[] expected, List actual) { + for (int i= 0; i < expected.length; i++) { + String handle= expected[i]; + Assert.assertTrue("Expected handle not found: " + handle, actual.contains(handle)); + } + testNumberOfElements(expected.length, actual); + } + + private static void testNumberOfElements(int expected, List actual) { + if (expected == 0 && actual == null) + return; + Assert.assertEquals(expected, actual.size()); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PathTransformationTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PathTransformationTests.java new file mode 100644 index 000000000..af9fa3453 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PathTransformationTests.java @@ -0,0 +1,111 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; + +public class PathTransformationTests extends TestCase { + + private static final Class clazz= PathTransformationTests.class; + public PathTransformationTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + private IPath createIPath(String p){ + return Path.EMPTY.append(p); + } + + private void check(String path, String oldName, String newName){ + IPath pOld= createIPath(path + "/" + oldName); + String extension= ""; + //if (oldName.lastIndexOf(".") != -1) + // extension= oldName.substring(oldName.lastIndexOf(".")); + IPath pNew= createIPath(path + "/" + newName + extension); + IPath newPath= pOld.removeLastSegments(1).append(newName); + + assertEquals(pNew.toString(), newPath.toString()); + } + +/************/ + + public void test0(){ + check("/s/p", "A.java", "B.java"); + } + + public void test1(){ + check("/s/p", "A.java", "A.java"); + } + + public void test2(){ + check("/s/p", "A.txt", "B.txt"); + } + + public void test3(){ + check("/s/p", "A", "B"); + } + + public void test4(){ + check("/s/p/p", "A.java", "B.java"); + } + + public void test5(){ + check("/s/p/p", "A.java", "A.java"); + } + + public void test6(){ + check("/s/p/p", "A.txt", "B.txt"); + } + + public void test7(){ + check("/s", "A", "B.java"); + } + + public void test8(){ + check("/s", "A.java", "B.java"); + } + + public void test9(){ + check("/s", "A.java", "A.java"); + } + + public void test10(){ + check("/s", "A.txt", "B.txt"); + } + + public void test11(){ + check("/s", "A", "B"); + } + + public void test12(){ + check("", "A.java", "B.java"); + } + + public void test13(){ + check("", "A.java", "A.java"); + } + + public void test14(){ + check("", "A.txt", "B.txt"); + } + + public void test15(){ + check("", "A", "B"); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PromoteTempToFieldTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PromoteTempToFieldTests.java new file mode 100644 index 000000000..b421c2d9c --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PromoteTempToFieldTests.java @@ -0,0 +1,714 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.Hashtable; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.dom.Modifier; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.refactoring.code.PromoteTempToFieldRefactoring; + +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +public class PromoteTempToFieldTests extends RefactoringTest{ + + private static final Class clazz= PromoteTempToFieldTests.class; + private static final String REFACTORING_PATH= "PromoteTempToField/"; + private Object fCompactPref; + + public PromoteTempToFieldTests(String name){ + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + protected void setUp() throws Exception { + super.setUp(); + Hashtable options= JavaCore.getOptions(); + + String setting= DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR; + fCompactPref= options.get(setting); + options.put(setting, DefaultCodeFormatterConstants.TRUE); + JavaCore.setOptions(options); + } + + protected void tearDown() throws Exception { + super.tearDown(); + Hashtable options= JavaCore.getOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_ASSIGNMENT_OPERATOR, fCompactPref); + JavaCore.setOptions(options); + } + + + + private String getSimpleTestFileName(boolean canRename, boolean input){ + String fileName = "A_" + getName(); + if (canRename) + fileName += input ? "_in": "_out"; + return fileName + ".java"; + } + + private String getSimpleEnablementTestFileName(){ + return "A_" + getName() + ".java"; + } + + private String getTestFileName(boolean canRename, boolean input){ + String fileName= TEST_PATH_PREFIX + getRefactoringPath(); + fileName += (canRename ? "canPromote/": "cannotPromote/"); + return fileName + getSimpleTestFileName(canRename, input); + } + + private String getEnablementTestFileName(){ + String fileName= TEST_PATH_PREFIX + getRefactoringPath(); + fileName += "testEnablement/"; + return fileName + getSimpleEnablementTestFileName(); + } + + + //------------ + protected final ICompilationUnit createCUfromTestFile(IPackageFragment pack, boolean canPromote, boolean input) throws Exception { + return createCU(pack, getSimpleTestFileName(canPromote, input), getFileContents(getTestFileName(canPromote, input))); + } + + protected final ICompilationUnit createCUfromEnablementTestFile(IPackageFragment pack) throws Exception { + return createCU(pack, getSimpleEnablementTestFileName(), getFileContents(getEnablementTestFileName())); + } + + private void passHelper(int startLine, int startColumn, int endLine, int endColumn, + String newName, + boolean declareStatic, + boolean declareFinal, + int initializeIn, + int accessModifier) throws Exception{ + + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + PromoteTempToFieldRefactoring ref= new PromoteTempToFieldRefactoring(cu, selection.getOffset(), selection.getLength()); + + RefactoringStatus activationResult= ref.checkInitialConditions(new NullProgressMonitor()); + assertTrue("activation was supposed to be successful", activationResult.isOK()); + + ref.setFieldName(newName); + ref.setDeclareFinal(declareFinal); + ref.setDeclareStatic(declareStatic); + ref.setInitializeIn(initializeIn); + ref.setVisibility(accessModifier); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to pass", checkInputResult.isOK()); + + performChange(ref, false); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + assertEqualLines("incorrect changes", getFileContents(getTestFileName(true, false)), newcu.getSource()); + } + + private void failHelper(int startLine, int startColumn, int endLine, int endColumn, + String newName, + boolean declareStatic, + boolean declareFinal, + int initializeIn, + int accessModifier, + int expectedSeverity) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), false, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + PromoteTempToFieldRefactoring ref= new PromoteTempToFieldRefactoring(cu, selection.getOffset(), selection.getLength()); + + RefactoringStatus result= ref.checkInitialConditions(new NullProgressMonitor()); + ref.setFieldName(newName); + ref.setDeclareFinal(declareFinal); + ref.setDeclareStatic(declareStatic); + ref.setInitializeIn(initializeIn); + ref.setVisibility(accessModifier); + result.merge(ref.checkFinalConditions(new NullProgressMonitor())); + if (result.isOK()) + result= null; + assertNotNull("precondition was supposed to fail",result); + + assertEquals("incorrect severity:", expectedSeverity, result.getSeverity()); + } + + private void enablementHelper(int startLine, int startColumn, int endLine, int endColumn, + String newName, + boolean declareStatic, + boolean declareFinal, + int initializeIn, + int accessModifier, + boolean expectedCanEnableSettingFinal, + boolean expectedCanEnableSettingStatic, + boolean expectedCanEnableInitInField, + boolean expectedCanEnableInitInMethod, + boolean expectedCanEnableInitInConstructors) throws Exception{ + ICompilationUnit cu= createCUfromEnablementTestFile(getPackageP()); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + PromoteTempToFieldRefactoring ref= new PromoteTempToFieldRefactoring(cu, selection.getOffset(), selection.getLength()); + RefactoringStatus result= ref.checkInitialConditions(new NullProgressMonitor()); + ref.setFieldName(newName); + ref.setDeclareFinal(declareFinal); + ref.setDeclareStatic(declareStatic); + ref.setInitializeIn(initializeIn); + ref.setVisibility(accessModifier); + + assertEquals("activation checking was supposed to pass", RefactoringStatus.OK, result.getSeverity()); + + assertEquals("incorrect in-constructor enablement", expectedCanEnableInitInConstructors, ref.canEnableSettingDeclareInConstructors()); + assertEquals("incorrect in-field enablement", expectedCanEnableInitInField, ref.canEnableSettingDeclareInFieldDeclaration()); + assertEquals("incorrect in-method enablement", expectedCanEnableInitInMethod, ref.canEnableSettingDeclareInMethod()); + assertEquals("incorrect static enablement", expectedCanEnableSettingStatic, ref.canEnableSettingStatic()); + assertEquals("incorrect final enablement", expectedCanEnableSettingFinal, ref.canEnableSettingFinal()); + } + private void enablementHelper1(int startLine, int startColumn, int endLine, int endColumn, + boolean expectedCanEnableSettingFinal, + boolean expectedCanEnableSettingStatic, + boolean expectedCanEnableInitInField, + boolean expectedCanEnableInitInMethod, + boolean expectedCanEnableInitInConstructors) throws Exception{ + enablementHelper(startLine, startColumn, endLine, endColumn, "i", false, false, PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD, Modifier.PRIVATE, + expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + ///---------------------- tests -------------------------// + + public void testEnablement0() throws Exception{ + boolean expectedCanEnableInitInConstructors = true; + boolean expectedCanEnableInitInMethod = true; + boolean expectedCanEnableInitInField = true; + boolean expectedCanEnableSettingStatic = true; + boolean expectedCanEnableSettingFinal = true; + + String newName= "i"; + boolean declareStatic = false; + boolean declareFinal= false; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_FIELD; + int accessModifier= Modifier.PRIVATE; + + enablementHelper(5, 13, 5, 14, newName, declareStatic, declareFinal, initializeIn, accessModifier, + expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + public void testEnablement1() throws Exception{ + boolean expectedCanEnableInitInConstructors = false; + boolean expectedCanEnableInitInMethod = false; + boolean expectedCanEnableInitInField = false; + boolean expectedCanEnableSettingStatic = true; + boolean expectedCanEnableSettingFinal = false; + enablementHelper1(5, 13, 5, 14, expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + public void testEnablement2() throws Exception{ + boolean expectedCanEnableInitInConstructors = false; + boolean expectedCanEnableInitInMethod = false; + boolean expectedCanEnableInitInField = false; + boolean expectedCanEnableSettingStatic = true; + boolean expectedCanEnableSettingFinal = false; + enablementHelper1(5, 13, 5, 14, expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + public void testEnablement3() throws Exception{ + boolean expectedCanEnableInitInConstructors = true; + boolean expectedCanEnableInitInMethod = true; + boolean expectedCanEnableInitInField = true; + boolean expectedCanEnableSettingStatic = true; + boolean expectedCanEnableSettingFinal = false; + enablementHelper1(5, 13, 5, 14, expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + public void testEnablement4() throws Exception{ + boolean expectedCanEnableInitInConstructors = false; + boolean expectedCanEnableInitInMethod = true; + boolean expectedCanEnableInitInField = true; + boolean expectedCanEnableSettingStatic = true; + boolean expectedCanEnableSettingFinal = true; + + String newName= "i"; + boolean declareStatic = false; + boolean declareFinal= false; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_FIELD; + int accessModifier= Modifier.PRIVATE; + + enablementHelper(5, 13, 5, 14, newName, declareStatic, declareFinal, initializeIn, accessModifier, + expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + public void testEnablement5() throws Exception{ + boolean expectedCanEnableInitInConstructors = false; + boolean expectedCanEnableInitInMethod = true; + boolean expectedCanEnableInitInField = true; + boolean expectedCanEnableSettingStatic = true; + boolean expectedCanEnableSettingFinal = true; + + String newName= "i"; + boolean declareStatic = false; + boolean declareFinal= false; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_FIELD; + int accessModifier= Modifier.PRIVATE; + + enablementHelper(7, 21, 7, 22, newName, declareStatic, declareFinal, initializeIn, accessModifier, + expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + public void testEnablement6() throws Exception{ + boolean expectedCanEnableInitInConstructors = false; + boolean expectedCanEnableInitInMethod = false; + boolean expectedCanEnableInitInField = false; + boolean expectedCanEnableSettingStatic = true; + boolean expectedCanEnableSettingFinal = false; + enablementHelper1(7, 21, 7, 22, expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + public void testEnablement7() throws Exception{ + boolean expectedCanEnableInitInConstructors = false; + boolean expectedCanEnableInitInMethod = true; + boolean expectedCanEnableInitInField = true; + boolean expectedCanEnableSettingStatic = false; + boolean expectedCanEnableSettingFinal = false; + enablementHelper1(5, 13, 5, 14, expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + public void testEnablement8() throws Exception{ + boolean expectedCanEnableInitInConstructors = true; + boolean expectedCanEnableInitInMethod = true; + boolean expectedCanEnableInitInField = true; + boolean expectedCanEnableSettingStatic = false; + boolean expectedCanEnableSettingFinal = true; + + String newName= "i"; + boolean declareStatic = false; + boolean declareFinal= false; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_CONSTRUCTOR; + int accessModifier= Modifier.PRIVATE; + + enablementHelper(4, 13, 4, 14, newName, declareStatic, declareFinal, initializeIn, accessModifier, + expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + public void testEnablement9() throws Exception{ + boolean expectedCanEnableInitInConstructors = false; + boolean expectedCanEnableInitInMethod = true; + boolean expectedCanEnableInitInField = true; + boolean expectedCanEnableSettingStatic = true; + boolean expectedCanEnableSettingFinal = false; + + String newName= "i"; + boolean declareStatic = true; + boolean declareFinal= false; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + int accessModifier= Modifier.PRIVATE; + + enablementHelper(4, 13, 4, 14, newName, declareStatic, declareFinal, initializeIn, accessModifier, + expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + public void testEnablement10() throws Exception{ + boolean expectedCanEnableInitInConstructors = false; + boolean expectedCanEnableInitInMethod = true; + boolean expectedCanEnableInitInField = false; + boolean expectedCanEnableSettingStatic = false; + boolean expectedCanEnableSettingFinal = false; + + String newName= "fMyT"; + boolean declareStatic = false; + boolean declareFinal= false; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + int accessModifier= Modifier.PRIVATE; + + enablementHelper(6, 12, 6, 12, newName, declareStatic, declareFinal, initializeIn, accessModifier, + expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + public void testEnablement11() throws Exception{ + boolean expectedCanEnableInitInConstructors = false; + boolean expectedCanEnableInitInMethod = true; + boolean expectedCanEnableInitInField = false; + boolean expectedCanEnableSettingStatic = true; + boolean expectedCanEnableSettingFinal = false; + + String newName= "fTarget"; + boolean declareStatic = false; + boolean declareFinal= false; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + int accessModifier= Modifier.PRIVATE; + + enablementHelper(6, 21, 6, 27, newName, declareStatic, declareFinal, initializeIn, accessModifier, + expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + public void testEnablement12() throws Exception{ + boolean expectedCanEnableInitInConstructors = false; + boolean expectedCanEnableInitInMethod = true; + boolean expectedCanEnableInitInField = false; + boolean expectedCanEnableSettingStatic = true; + boolean expectedCanEnableSettingFinal = false; + + String newName= "i"; + boolean declareStatic = false; + boolean declareFinal= false; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + int accessModifier= Modifier.PRIVATE; + + enablementHelper(5, 16, 5, 17, newName, declareStatic, declareFinal, initializeIn, accessModifier, + expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + public void testEnablement13() throws Exception{ + boolean expectedCanEnableInitInConstructors = false; + boolean expectedCanEnableInitInMethod = true; + boolean expectedCanEnableInitInField = false; + boolean expectedCanEnableSettingStatic = true; + boolean expectedCanEnableSettingFinal = false; + + String newName= "i"; + boolean declareStatic = false; + boolean declareFinal= false; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + int accessModifier= Modifier.PRIVATE; + + enablementHelper(4, 18, 4, 19, newName, declareStatic, declareFinal, initializeIn, accessModifier, + expectedCanEnableSettingFinal, expectedCanEnableSettingStatic, expectedCanEnableInitInField, expectedCanEnableInitInMethod, expectedCanEnableInitInConstructors); + } + + + ///---- test failing preconditions -------------- + + public void testFail0() throws Exception{ + failHelper(3, 16, 3, 17, "i", false, false, PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD, Modifier.PRIVATE, RefactoringStatus.FATAL); + } + + public void testFail1() throws Exception{ + failHelper(5, 28, 5, 29, "i", false, false, PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD, Modifier.PRIVATE, RefactoringStatus.FATAL); + } + + public void testFail2() throws Exception{ + failHelper(5, 15, 5, 16, "i", false, false, PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD, Modifier.PRIVATE, RefactoringStatus.FATAL); + } + + public void testFail4() throws Exception{ + failHelper(7, 13, 7, 14, "i", false, false, PromoteTempToFieldRefactoring.INITIALIZE_IN_CONSTRUCTOR, Modifier.PRIVATE, RefactoringStatus.FATAL); + } + + public void testFail5() throws Exception{ + failHelper(6, 13, 6, 14, "i", false, false, PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD, Modifier.PRIVATE, RefactoringStatus.FATAL); + } + + public void testFailGenerics1() throws Exception{ + failHelper(6, 12, 6, 12, "fYou", false, false, PromoteTempToFieldRefactoring.INITIALIZE_IN_CONSTRUCTOR, Modifier.PRIVATE, RefactoringStatus.FATAL); + } + + ///----------- tests of transformation ------------ + + public void test0() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(5, 13, 5, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test1() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_FIELD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(5, 13, 5, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test2() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_CONSTRUCTOR; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(7, 13, 7, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test3() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_CONSTRUCTOR; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(9, 13, 9, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test4() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_CONSTRUCTOR; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(5, 13, 5, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test5() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(6, 21, 6, 22, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test6() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_FIELD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(6, 21, 6, 22, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test7() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_FIELD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(4, 13, 4, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test8() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(4, 13, 4, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test9() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(5, 13, 5, 14, "field", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test10() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_CONSTRUCTOR; + boolean declareFinal= true; + boolean declareStatic= false; + passHelper(7, 13, 7, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test11() throws Exception{ + int accessModifier= Modifier.PUBLIC; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(7, 13, 7, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test12() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= true; + passHelper(5, 13, 5, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test13() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= true; + passHelper(5, 13, 5, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test14() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= true; + passHelper(5, 19, 5, 20, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test15() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= true; + passHelper(5, 19, 5, 20, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test16() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_CONSTRUCTOR; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(10, 13, 10, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test17() throws Exception{ + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(4, 13, 4, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test18() throws Exception{ + //printTestDisabledMessage("regression test for bug 39363"); + if (true) return; + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_CONSTRUCTOR; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(5, 13, 5, 14, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test19() throws Exception{ //test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=49840 + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(4, 13, 4, 22, "fSomeArray", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test20() throws Exception{ //test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=49840 + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(4, 24, 4, 24, "fDoubleDim", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test21() throws Exception{ //test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=47798 + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_FIELD; + boolean declareFinal= true; + boolean declareStatic= true; + passHelper(4, 17, 4, 18, "fgX", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test22() throws Exception{ //test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=54444 + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, 4, 34, 4, 37); + PromoteTempToFieldRefactoring ref= new PromoteTempToFieldRefactoring(cu, selection.getOffset(), selection.getLength()); + ref.checkInitialConditions(new NullProgressMonitor()); + assertEquals("fSortByDefiningTypeAction", ref.guessFieldNames()[0]); + } + + public void test23() throws Exception{ //syntax error + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_FIELD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(5, 31, 5, 31, "fCount", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test24() throws Exception{ //syntax error + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(4, 33, 4, 33, "fFinisheds", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void test25() throws Exception{ //test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=136911 + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(7, 22, 7, 22, "i", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void testGenerics01() throws Exception { + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_FIELD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(9, 9, 9, 11, "fVt", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void testGenerics02() throws Exception { + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(6, 12, 6, 12, "fMyT", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void testEnum1() throws Exception { + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_CONSTRUCTOR; + boolean declareFinal= true; + boolean declareStatic= false; + passHelper(6, 13, 6, 16, "fVar", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void testEnum2() throws Exception { + int accessModifier= Modifier.PUBLIC; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_FIELD; + boolean declareFinal= true; + boolean declareStatic= true; + passHelper(10, 21, 10, 21, "fM", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void testMultiVariableDeclFragment01() throws Exception { + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(6, 29, 6, 29, "fA", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void testMultiVariableDeclFragment02() throws Exception { + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(5, 29, 5, 29, "fB", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void testMultiVariableDeclFragment03() throws Exception { + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(5, 72, 5, 72, "fC", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void testMultiVariableDeclFragment04() throws Exception { + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(5, 41, 5, 41, "fD", declareStatic, declareFinal, initializeIn, accessModifier); + } + + public void testDeclaringMethodBindingUnavailable01() throws Exception { + int accessModifier= Modifier.PRIVATE; + int initializeIn= PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD; + boolean declareFinal= false; + boolean declareStatic= false; + passHelper(9, 14, 9, 18, "fDate", declareStatic, declareFinal, initializeIn, accessModifier); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PullUpTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PullUpTests.java new file mode 100644 index 000000000..633f12d9c --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PullUpTests.java @@ -0,0 +1,1925 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Benjamin Muskalla - 228950: [pull up] exception if target calls super with multiple parameters + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; +import org.eclipse.jdt.internal.corext.refactoring.structure.PullUpRefactoringProcessor; +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; + +import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; + +public class PullUpTests extends RefactoringTest { + + private static final boolean BUG_91542= true; + + private static final Class clazz= PullUpTests.class; + + private static final String REFACTORING_PATH= "PullUp/"; + + public PullUpTests(String name) { + super(name); + } + + public static Test suite() { + return new Java15Setup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new Java15Setup(someTest); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + //------------------- + + private static PullUpRefactoringProcessor createRefactoringProcessor(IMember[] methods) throws JavaModelException{ + IJavaProject project= null; + if (methods != null && methods.length > 0) + project= methods[0].getJavaProject(); + if (RefactoringAvailabilityTester.isPullUpAvailable(methods)) { + PullUpRefactoringProcessor processor= new PullUpRefactoringProcessor(methods, JavaPreferencesSettings.getCodeGenerationSettings(project)); + new ProcessorBasedRefactoring(processor); + return processor; + } + return null; + } + + private void fieldMethodHelper1(String[] fieldNames, String[] methodNames, String[][] signatures, boolean deleteAllInSourceType, boolean deleteAllMatchingMethods) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + try{ + IType type= getType(cu, "B"); + IField[] fields= getFields(type, fieldNames); + IMethod[] methods= getMethods(type, methodNames, signatures); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(merge(methods, fields)); + + Refactoring ref= processor.getRefactoring(); + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + setSuperclassAsTargetClass(processor); + + if (deleteAllInSourceType) + processor.setDeletedMethods(methods); + if (deleteAllMatchingMethods) + processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to pass", !checkInputResult.hasError()); + performChange(ref, false); + + String expected= getFileContents(getOutputTestFileName("A")); + String actual= cu.getSource(); + assertEqualLines(expected, actual); + } finally{ + performDummySearch(); + cu.delete(false, null); + } + } + + private IType[] getPossibleTargetClasses(PullUpRefactoringProcessor processor) throws JavaModelException { + return processor.getCandidateTypes(new RefactoringStatus(), new NullProgressMonitor()); + } + + private void setSuperclassAsTargetClass(PullUpRefactoringProcessor processor) throws JavaModelException { + IType[] possibleClasses= getPossibleTargetClasses(processor); + processor.setDestinationType(possibleClasses[possibleClasses.length - 1]); + } + + private void setTargetClass(PullUpRefactoringProcessor processor, int targetClassIndex) throws JavaModelException { + IType[] possibleClasses= getPossibleTargetClasses(processor); + processor.setDestinationType(getPossibleTargetClasses(processor)[possibleClasses.length - 1 - targetClassIndex]); + } + + private void addRequiredMembersHelper(String[] fieldNames, String[] methodNames, String[][] methodSignatures, String[] expectedFieldNames, String[] expectedMethodNames, String[][] expectedMethodSignatures) throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + try{ + IType type= getType(cu, "B"); + IField[] fields= getFields(type, fieldNames); + IMethod[] methods= getMethods(type, methodNames, methodSignatures); + + IMember[] members= merge(methods, fields); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(members); + Refactoring ref= processor.getRefactoring(); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + setSuperclassAsTargetClass(processor); + + List additionalRequired= Arrays.asList(processor.getAdditionalRequiredMembersToPullUp(new NullProgressMonitor())); + List required= new ArrayList(); + required.addAll(additionalRequired); + required.addAll(Arrays.asList(members)); + IField[] expectedFields= getFields(type, expectedFieldNames); + IMethod[] expectedMethods= getMethods(type, expectedMethodNames, expectedMethodSignatures); + List expected= Arrays.asList(merge(expectedFields, expectedMethods)); + assertEquals("incorrect size", expected.size(), required.size()); + for (Iterator iter= expected.iterator(); iter.hasNext();) { + Object each= iter.next(); + assertTrue ("required does not contain " + each, required.contains(each)); + } + for (Iterator iter= required.iterator(); iter.hasNext();) { + Object each= iter.next(); + assertTrue ("expected does not contain " + each, expected.contains(each)); + } + } finally{ + performDummySearch(); + cu.delete(false, null); + } + } + + private void fieldHelper1(String[] fieldNames, int targetClassIndex) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + try{ + IType type= getType(cu, "B"); + IField[] fields= getFields(type, fieldNames); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(fields); + Refactoring ref= processor.getRefactoring(); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + setTargetClass(processor, targetClassIndex); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to pass", !checkInputResult.hasError()); + performChange(ref, false); + + String expected= getFileContents(getOutputTestFileName("A")); + String actual= cu.getSource(); + assertEqualLines(expected, actual); + } finally{ + performDummySearch(); + cu.delete(false, null); + } + } + + private void fieldHelper2(String[] fieldNames, int targetClassIndex) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + try{ + IType type= getType(cu, "B"); + IField[] fields= getFields(type, fieldNames); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(fields); + Refactoring ref= processor.getRefactoring(); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + setTargetClass(processor, targetClassIndex); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to fail", !checkInputResult.isOK()); + } finally{ + performDummySearch(); + cu.delete(false, null); + } + } + + private static IMethod[] getMethods(IMember[] members){ + List l= Arrays.asList(JavaElementUtil.getElementsOfType(members, IJavaElement.METHOD)); + return (IMethod[]) l.toArray(new IMethod[l.size()]); + } + + private Refactoring createRefactoringPrepareForInputCheck(String[] selectedMethodNames, String[][] selectedMethodSignatures, + String[] selectedFieldNames, + String[] selectedTypeNames, String[] namesOfMethodsToPullUp, + String[][] signaturesOfMethodsToPullUp, + String[] namesOfFieldsToPullUp, String[] namesOfTypesToPullUp, + String[] namesOfMethodsToDeclareAbstract, String[][] signaturesOfMethodsToDeclareAbstract, + boolean deleteAllPulledUpMethods, boolean deleteAllMatchingMethods, int targetClassIndex, ICompilationUnit cu) throws CoreException { + IType type= getType(cu, "B"); + IMethod[] selectedMethods= getMethods(type, selectedMethodNames, selectedMethodSignatures); + IField[] selectedFields= getFields(type, selectedFieldNames); + IType[] selectedTypes= getMemberTypes(type, selectedTypeNames); + IMember[] selectedMembers= merge(selectedFields, selectedMethods, selectedTypes); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(selectedMembers); + Refactoring ref= processor.getRefactoring(); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + + setTargetClass(processor, targetClassIndex); + + IMethod[] methodsToPullUp= findMethods(selectedMethods, namesOfMethodsToPullUp, signaturesOfMethodsToPullUp); + IField[] fieldsToPullUp= findFields(selectedFields, namesOfFieldsToPullUp); + IType[] typesToPullUp= findTypes(selectedTypes, namesOfTypesToPullUp); + IMember[] membersToPullUp= merge(methodsToPullUp, fieldsToPullUp, typesToPullUp); + + IMethod[] methodsToDeclareAbstract= findMethods(selectedMethods, namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract); + + processor.setMembersToMove(membersToPullUp); + processor.setAbstractMethods(methodsToDeclareAbstract); + if (deleteAllPulledUpMethods && methodsToPullUp.length != 0) + processor.setDeletedMethods(methodsToPullUp); + if (deleteAllMatchingMethods && methodsToPullUp.length != 0) + processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); + return ref; + } + + private void declareAbstractFailHelper(String[] selectedMethodNames, String[][] selectedMethodSignatures, + String[] selectedFieldNames, + String[] selectedTypeNames, String[] namesOfMethodsToPullUp, + String[][] signaturesOfMethodsToPullUp, String[] namesOfFieldsToPullUp, + String[] namesOfMethodsToDeclareAbstract, + String[][] signaturesOfMethodsToDeclareAbstract, String[] namesOfTypesToPullUp, + boolean deleteAllPulledUpMethods, boolean deleteAllMatchingMethods, int targetClassIndex) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + try{ + Refactoring ref= createRefactoringPrepareForInputCheck(selectedMethodNames, selectedMethodSignatures, selectedFieldNames, selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, namesOfFieldsToPullUp, namesOfTypesToPullUp, namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, deleteAllPulledUpMethods, + deleteAllMatchingMethods, targetClassIndex, cu); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to fail", !checkInputResult.isOK()); + } finally{ + performDummySearch(); + cu.delete(false, null); + } + } + + private void declareAbstractHelper(String[] selectedMethodNames, String[][] selectedMethodSignatures, + String[] selectedFieldNames, + String[] selectedTypeNames, String[] namesOfMethodsToPullUp, + String[][] signaturesOfMethodsToPullUp, String[] namesOfFieldsToPullUp, + String[] namesOfMethodsToDeclareAbstract, + String[][] signaturesOfMethodsToDeclareAbstract, String[] namesOfTypesToPullUp, + boolean deleteAllPulledUpMethods, boolean deleteAllMatchingMethods, int targetClassIndex) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + try{ + Refactoring ref= createRefactoringPrepareForInputCheck(selectedMethodNames, selectedMethodSignatures, selectedFieldNames, selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, namesOfFieldsToPullUp, namesOfTypesToPullUp, namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, deleteAllPulledUpMethods, + deleteAllMatchingMethods, targetClassIndex, cu); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to pass", !checkInputResult.hasError()); + performChange(ref, false); + + String expected= getFileContents(getOutputTestFileName("A")); + String actual= cu.getSource(); + assertEqualLines(expected, actual); + } finally{ + performDummySearch(); + cu.delete(false, null); + } + } + + private void helper1(String[] methodNames, String[][] signatures, boolean deleteAllInSourceType, boolean deleteAllMatchingMethods, int targetClassIndex) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + try{ + IType type= getType(cu, "B"); + IMethod[] methods= getMethods(type, methodNames, signatures); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); + Refactoring ref= processor.getRefactoring(); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + + setTargetClass(processor, targetClassIndex); + + if (deleteAllInSourceType) + processor.setDeletedMethods(methods); + if (deleteAllMatchingMethods) + processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to pass", !checkInputResult.hasError()); + performChange(ref, false); + + String expected= getFileContents(getOutputTestFileName("A")); + String actual= cu.getSource(); + assertEqualLines(expected, actual); + } finally{ + performDummySearch(); + cu.delete(false, null); + } + } + + private void helper2(String[] methodNames, String[][] signatures, boolean deleteAllInSourceType, boolean deleteAllMatchingMethods, int targetClassIndex) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + try{ + IType type= getType(cu, "B"); + IMethod[] methods= getMethods(type, methodNames, signatures); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); + Refactoring ref= processor.getRefactoring(); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + setTargetClass(processor, targetClassIndex); + + if (deleteAllInSourceType) + processor.setDeletedMethods(methods); + if (deleteAllMatchingMethods) + processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to fail", !checkInputResult.isOK()); + } finally{ + performDummySearch(); + cu.delete(false, null); + } + } + + private void helper3(String[] methodNames, String[][] signatures, boolean deleteAllInSourceType, boolean deleteAllMatchingMethods, int targetClassIndex, boolean shouldActivationCheckPass) throws Exception { + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); + try{ + IType type= getType(cuB, "B"); + IMethod[] methods= getMethods(type, methodNames, signatures); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); + Refactoring ref= processor.getRefactoring(); + + assertEquals("activation", shouldActivationCheckPass, ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + if (! shouldActivationCheckPass) + return; + setTargetClass(processor, targetClassIndex); + + if (deleteAllInSourceType) + processor.setDeletedMethods(methods); + if (deleteAllMatchingMethods) + processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to fail", !checkInputResult.isOK()); + } finally{ + performDummySearch(); + cuA.delete(false, null); + cuB.delete(false, null); + } + } + + //------------------ tests ------------- + + public void test0() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test1() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test2() throws Exception{ + helper1(new String[]{"mmm", "n"}, new String[][]{new String[0], new String[0]}, true, false, 0); + } + + public void test3() throws Exception{ + helper1(new String[]{"mmm", "n"}, new String[][]{new String[0], new String[0]}, true, true, 0); + } + + public void test4() throws Exception{ + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); + + try{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[]{"QList;"}}; + + IType type= getType(cuB, "B"); + IMethod[] methods= getMethods(type, methodNames, signatures); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); + Refactoring ref= processor.getRefactoring(); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + setSuperclassAsTargetClass(processor); + + processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); + + RefactoringStatus result= performRefactoring(ref); + assertTrue("precondition was supposed to pass", result == null || !result.hasError()); + + assertEqualLines("A", cuA.getSource(), getFileContents(getOutputTestFileName("A"))); + assertEqualLines("B", cuB.getSource(), getFileContents(getOutputTestFileName("B"))); + } finally{ + performDummySearch(); + cuA.delete(false, null); + cuB.delete(false, null); + } + } + + public void test5() throws Exception{ + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); + + try{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + + IType type= getType(cuB, "B"); + IMethod[] methods= getMethods(type, methodNames, signatures); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); + Refactoring ref= processor.getRefactoring(); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + setSuperclassAsTargetClass(processor); + + processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); + + RefactoringStatus result= performRefactoring(ref); + assertTrue("precondition was supposed to pass", result == null || !result.hasError()); + + assertEqualLines("A", cuA.getSource(), getFileContents(getOutputTestFileName("A"))); + assertEqualLines("B", cuB.getSource(), getFileContents(getOutputTestFileName("B"))); + } finally{ + performDummySearch(); + cuA.delete(false, null); + cuB.delete(false, null); + } + } + + public void test6() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test7() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test8() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test9() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test10() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test11() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test12() throws Exception{ + //printTestDisabledMessage("bug#6779 searchDeclarationsOfReferencedTyped - missing exception types"); + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); + + try{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + + IType type= getType(cuB, "B"); + IMethod[] methods= getMethods(type, methodNames, signatures); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); + Refactoring ref= processor.getRefactoring(); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + setSuperclassAsTargetClass(processor); + + processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); + + RefactoringStatus result= performRefactoring(ref); + assertTrue("precondition was supposed to pass", result == null || !result.hasError()); + + assertEqualLines("A", cuA.getSource(), getFileContents(getOutputTestFileName("A"))); + assertEqualLines("B", cuB.getSource(), getFileContents(getOutputTestFileName("B"))); + } finally{ + performDummySearch(); + cuA.delete(false, null); + cuB.delete(false, null); + } + } + + public void test13() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test14() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test15() throws Exception{ + printTestDisabledMessage("must fix - incorrect error"); +// helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false); + } + + public void test16() throws Exception{ + printTestDisabledMessage("must fix - incorrect error"); +// helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false); + } + + public void test17() throws Exception{ + printTestDisabledMessage("must fix - incorrect error with static method access"); +// helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false); + } + + public void test18() throws Exception{ + printTestDisabledMessage("must fix - incorrect error with static field access"); +// helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false); + } + + public void test19() throws Exception{ +// printTestDisabledMessage("bug 18438"); +// printTestDisabledMessage("bug 23324 "); + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test20() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 1); + } + + public void test21() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 1); + } + + public void test22() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test23() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test24() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test25() throws Exception{ +// printTestDisabledMessage("bug in ASTRewrite - extra dimensions 29553"); + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void test26() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void test27() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void test28() throws Exception{ +// printTestDisabledMessage("unimplemented (increase method visibility if declare abstract in superclass)"); + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void test29() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[]{"[I"}}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void test30() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[]{"[I"}}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void test31() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[]{"[I"}}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void test32() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void test33() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= selectedMethodNames; + String[][] signaturesOfMethodsToPullUp= selectedMethodSignatures; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {new String[0]}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void test34() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void test35() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void test36() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void test37() throws Exception{ + String[] selectedMethodNames= {"m", "f"}; + String[][] selectedMethodSignatures= {new String[0], new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {"m"}; + String[][] signaturesOfMethodsToPullUp= {new String[0]}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= {"f"}; + String[][] signaturesOfMethodsToDeclareAbstract= {new String[0]}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void test38() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {"A"}; + String[] namesOfMethodsToPullUp= {"m"}; + String[][] signaturesOfMethodsToPullUp= {new String[0]}; + String[] namesOfFieldsToPullUp= {"A"}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void test39() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {"A"}; + String[] selectedTypeNames= {"X", "Y"}; + String[] namesOfMethodsToPullUp= {"m"}; + String[][] signaturesOfMethodsToPullUp= {new String[0]}; + String[] namesOfFieldsToPullUp= {"A"}; + String[] namesOfTypesToPullUp= {"X", "Y"}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, true, 0); + } + + public void test40() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] selectedTypeNames= {}; + String[] namesOfMethodsToPullUp= {"m"}; + String[][] signaturesOfMethodsToPullUp= {new String[0]}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfTypesToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, true, 0); + } + + public void test41() throws Exception{ + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {"i"}; + String[] selectedTypeNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {"i"}; + String[] namesOfTypesToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, true, 0); + } + + public void test42() throws Exception{ + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {"i", "j"}; + String[] selectedTypeNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {"i", "j"}; + String[] namesOfTypesToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, true, 0); + } + + public void test43() throws Exception{ +// printTestDisabledMessage("bug 35562 Method pull up wrongly indents javadoc comment [refactoring]"); + + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] selectedTypeNames= {}; + String[] namesOfMethodsToPullUp= selectedMethodNames; + String[][] signaturesOfMethodsToPullUp= selectedMethodSignatures; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfTypesToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, true, 0); + } + + public void test44() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {"A"}; + String[] selectedTypeNames= {"X", "Y"}; + String[] namesOfMethodsToPullUp= {"m"}; + String[][] signaturesOfMethodsToPullUp= {new String[0]}; + String[] namesOfFieldsToPullUp= {"A"}; + String[] namesOfTypesToPullUp= {"X", "Y"}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, true, 0); + } + + public void test45() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {"A"}; + String[] selectedTypeNames= {"X", "Y"}; + String[] namesOfMethodsToPullUp= {"m"}; + String[][] signaturesOfMethodsToPullUp= {new String[0]}; + String[] namesOfFieldsToPullUp= {"A"}; + String[] namesOfTypesToPullUp= {"X", "Y"}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, true, 0); + } + + public void test46() throws Exception{ + // for bug 196635 + + String[] selectedMethodNames= {"getConst"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {"CONST"}; + String[] selectedTypeNames= {}; + String[] namesOfMethodsToPullUp= {"getConst"}; + String[][] signaturesOfMethodsToPullUp= {new String[0]}; + String[] namesOfFieldsToPullUp= {"CONST"}; + String[] namesOfTypesToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, true, 0); + } + + public void test47() throws Exception{ + // for bug 211491 + + String[] selectedMethodNames= {"method"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] selectedTypeNames= {}; + String[] namesOfMethodsToPullUp= {"method"}; + String[][] signaturesOfMethodsToPullUp= {new String[0]}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfTypesToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, true, 0); + } + + public void test48() throws Exception{ + // for bug 211491, but with a super class + + String[] selectedMethodNames= {"method"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] selectedTypeNames= {}; + String[] namesOfMethodsToPullUp= {"method"}; + String[][] signaturesOfMethodsToPullUp= {new String[0]}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfTypesToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, false, false, 0); + } + + public void test49() throws Exception{ + // for bug 228950 + + String[] selectedMethodNames= {"g"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] selectedTypeNames= {}; + String[] namesOfMethodsToPullUp= {"g"}; + String[][] signaturesOfMethodsToPullUp= {new String[0]}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfTypesToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + declareAbstractHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, false, 0); + } + + public void testFail0() throws Exception{ +// printTestDisabledMessage("6538: searchDeclarationsOf* incorrect"); + helper2(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void testFail1() throws Exception{ + printTestDisabledMessage("overloading - current limitation"); +// helper2(new String[]{"m"}, new String[][]{new String[0]}, true, false); + } + + public void testFail2() throws Exception{ +// printTestDisabledMessage("6538: searchDeclarationsOf* incorrect"); + helper2(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void testFail3() throws Exception{ +// printTestDisabledMessage("6538: searchDeclarationsOf* incorrect"); + helper2(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void testFail4() throws Exception{ +// printTestDisabledMessage("6538: searchDeclarationsOf* incorrect"); + helper2(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void testFail6() throws Exception{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + boolean deleteAllInSourceType= true; + boolean deleteAllMatchingMethods= false; + + helper3(methodNames, signatures, deleteAllInSourceType, deleteAllMatchingMethods, 0, true); + } + + public void testFail7() throws Exception{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + boolean deleteAllInSourceType= true; + boolean deleteAllMatchingMethods= false; + helper3(methodNames, signatures, deleteAllInSourceType, deleteAllMatchingMethods, 0, false); + } + + public void testFail8() throws Exception{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + boolean deleteAllInSourceType= true; + boolean deleteAllMatchingMethods= false; + helper3(methodNames, signatures, deleteAllInSourceType, deleteAllMatchingMethods, 0, true); + } + + public void testFail9() throws Exception{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + boolean deleteAllInSourceType= true; + boolean deleteAllMatchingMethods= false; + helper3(methodNames, signatures, deleteAllInSourceType, deleteAllMatchingMethods, 0, true); + } + + public void testFail10() throws Exception{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + boolean deleteAllInSourceType= true; + boolean deleteAllMatchingMethods= false; + helper3(methodNames, signatures, deleteAllInSourceType, deleteAllMatchingMethods, 0, false); + } + + public void testFail11() throws Exception{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + boolean deleteAllInSourceType= true; + boolean deleteAllMatchingMethods= false; + helper3(methodNames, signatures, deleteAllInSourceType, deleteAllMatchingMethods, 0, true); + } + + public void testFail12() throws Exception{ + printTestDisabledMessage("overloading - current limitation"); +// String[] methodNames= new String[]{"m"}; +// String[][] signatures= new String[][]{new String[0]}; +// boolean deleteAllInSourceType= true; +// boolean deleteAllMatchingMethods= false; +// helper3(methodNames, signatures, deleteAllInSourceType, deleteAllMatchingMethods); + } + + public void testFail13() throws Exception{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + boolean deleteAllInSourceType= true; + boolean deleteAllMatchingMethods= false; + helper2(methodNames, signatures, deleteAllInSourceType, deleteAllMatchingMethods, 0); + } + + public void testFail14() throws Exception{ + //removed - this (pulling up classes) is allowed now + } + + public void testFail15() throws Exception{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + boolean deleteAllInSourceType= true; + boolean deleteAllMatchingMethods= false; + helper2(methodNames, signatures, deleteAllInSourceType, deleteAllMatchingMethods, 1); + } + + public void testFail16() throws Exception{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + boolean deleteAllInSourceType= true; + boolean deleteAllMatchingMethods= false; + helper2(methodNames, signatures, deleteAllInSourceType, deleteAllMatchingMethods, 1); + } + + public void testFail17() throws Exception{ + printTestDisabledMessage("unimplemented test - see bug 29522"); +// String[] methodNames= new String[]{"m"}; +// String[][] signatures= new String[][]{new String[0]}; +// boolean deleteAllInSourceType= true; +// boolean deleteAllMatchingMethods= false; +// helper2(methodNames, signatures, deleteAllInSourceType, deleteAllMatchingMethods, 1); + } + + public void testFail18() throws Exception{ + printTestDisabledMessage("unimplemented test - see bug 29522"); +// String[] methodNames= new String[]{"m"}; +// String[][] signatures= new String[][]{new String[0]}; +// boolean deleteAllInSourceType= true; +// boolean deleteAllMatchingMethods= false; +// helper2(methodNames, signatures, deleteAllInSourceType, deleteAllMatchingMethods, 0); + } + + public void testFail19() throws Exception{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[0]}; + boolean deleteAllInSourceType= true; + boolean deleteAllMatchingMethods= false; + helper2(methodNames, signatures, deleteAllInSourceType, deleteAllMatchingMethods, 1); + } + + public void testFail20() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractFailHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void testFail21() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractFailHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void testFail22() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractFailHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void testFail23() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractFailHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void testFail24() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractFailHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + new String[0], namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, new String[0], true, true, 0); + } + + public void testFail25() throws Exception{ + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {}; + String[] selectedTypeNames= {"Test"}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfTypesToPullUp= {"Test"}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractFailHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, true, 0); + } + + public void testFail26() throws Exception{ + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {}; + String[] selectedTypeNames= {"Test"}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfTypesToPullUp= {"Test"}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractFailHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, true, 0); + } + + public void testFail27() throws Exception{ + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {}; + String[] selectedTypeNames= {"A"}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfTypesToPullUp= {"A"}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractFailHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, true, 0); + } + + public void testFail28() throws Exception{ + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {}; + String[] selectedTypeNames= {"Test"}; + String[] namesOfMethodsToPullUp= {}; + String[][] signaturesOfMethodsToPullUp= {}; + String[] namesOfFieldsToPullUp= {}; + String[] namesOfTypesToPullUp= {"Test"}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + declareAbstractFailHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + selectedTypeNames, namesOfMethodsToPullUp, + signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract, namesOfTypesToPullUp, true, true, 0); + } + + public void testFail29() throws Exception { + helper2(new String[] {"stop"}, new String[][]{new String[0]}, true, false, 0); + } + + //---------------------------------------------------------- + public void testField0() throws Exception{ + fieldHelper1(new String[]{"i"}, 0); + } + + public void testFieldFail0() throws Exception{ + fieldHelper2(new String[]{"x"}, 0); + } + + public void testFieldFail1() throws Exception{ + fieldHelper2(new String[]{"x"}, 0); + } + + public void testFieldFail2() throws Exception{ + fieldHelper2(new String[]{"f"}, 1); + } + + //--------------------------------------------------------- + public void testFieldMethod0() throws Exception{ +// printTestDisabledMessage("bug 23324 "); + fieldMethodHelper1(new String[]{"f"}, new String[]{"m"}, new String[][]{new String[0]}, true, false); + } + + //---- + public void testAddingRequiredMembers0() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= methodNames; + String[][] expectedMethodSignatures= methodSignatures; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers1() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= methodNames; + String[][] expectedMethodSignatures= methodSignatures; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers2() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= methodNames; + String[][] expectedMethodSignatures= methodSignatures; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers3() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= {"m", "y"}; + String[][] expectedMethodSignatures= {new String[0], new String[0]}; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers4() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= {"m", "y"}; + String[][] expectedMethodSignatures= {new String[0], new String[0]}; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers5() throws Exception{ + String[] fieldNames= {"y"}; + String[] methodNames= {}; + String[][] methodSignatures= {}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= {"m"}; + String[][] expectedMethodSignatures= {new String[0]}; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers6() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= methodNames; + String[][] expectedMethodSignatures= methodSignatures; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers7() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= methodNames; + String[][] expectedMethodSignatures= methodSignatures; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers8() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= {"m", "foo"}; + String[][] expectedMethodSignatures= {new String[0], new String[0]}; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers9() throws Exception{ + String[] fieldNames= {"m"}; + String[] methodNames= {}; + String[][] methodSignatures= {}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= methodNames; + String[][] expectedMethodSignatures= methodSignatures; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers10() throws Exception{ + String[] fieldNames= {"m"}; + String[] methodNames= {}; + String[][] methodSignatures= {}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= {"foo"}; + String[][] expectedMethodSignatures= {new String[0]}; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers11() throws Exception{ + String[] fieldNames= {"m"}; + String[] methodNames= {}; + String[][] methodSignatures= {}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= {"foo"}; + String[][] expectedMethodSignatures= {new String[0]}; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers12() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= {"foo", "m"}; + String[][] expectedMethodSignatures= {new String[0], new String[0]}; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testEnablement0() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement1() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IType typeD= cu.getType("D"); + IMember[] members= {typeB, typeD}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement2() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("Outer").getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement3() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement4() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement5() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement6() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement7() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement8() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("Outer").getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement9() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("Outer").getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement10() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("Outer").getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement11() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("Outer").getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement12() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("Outer").getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement13() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IType typeD= cu.getType("D"); + IMember[] members= {typeB, typeD}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement14() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IType typeD= cu.getType("D"); + IMember[] members= {typeB, typeD}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement15() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IType typeD= cu.getType("D"); + IMember[] members= {typeB, typeD}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement16() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IType typeD= cu.getType("D"); + IMember[] members= {typeB, typeD}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement17() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement18() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement19() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement20() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement21() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement22() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement23() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + public void testEnablement24() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeB}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPullUpAvailable(members)); + } + + //------------------ tests ------------- + + public void testStaticImports0() throws Exception{ + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); + + try{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[] {"QS;"}}; + + IType type= getType(cuB, "B"); + IMethod[] methods= getMethods(type, methodNames, signatures); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); + Refactoring ref= processor.getRefactoring(); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + setSuperclassAsTargetClass(processor); + + processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); + + RefactoringStatus result= performRefactoring(ref); + assertTrue("precondition was supposed to pass", result == null || !result.hasError()); + + assertEqualLines("A", cuA.getSource(), getFileContents(getOutputTestFileName("A"))); + assertEqualLines("B", cuB.getSource(), getFileContents(getOutputTestFileName("B"))); + } finally{ + performDummySearch(); + cuA.delete(false, null); + cuB.delete(false, null); + } + } + + public void testStaticImports1() throws Exception{ + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); + + try{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[] {"QS;"}}; + + IType type= getType(cuB, "B"); + IMethod[] methods= getMethods(type, methodNames, signatures); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); + Refactoring ref= processor.getRefactoring(); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + setSuperclassAsTargetClass(processor); + + processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); + + RefactoringStatus result= performRefactoring(ref); + assertTrue("precondition was supposed to pass", result == null || !result.hasError()); + + assertEqualLines("A", cuA.getSource(), getFileContents(getOutputTestFileName("A"))); + assertEqualLines("B", cuB.getSource(), getFileContents(getOutputTestFileName("B"))); + } finally{ + performDummySearch(); + cuA.delete(false, null); + cuB.delete(false, null); + } + } + + public void testGenerics0() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void testGenerics1() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void testGenerics2() throws Exception{ + helper1(new String[]{"mmm", "n"}, new String[][]{new String[] {"QT;"}, new String[0]}, true, false, 0); + } + + public void testGenerics3() throws Exception{ + helper1(new String[]{"mmm", "n"}, new String[][]{new String[] {"QT;"}, new String[0]}, true, true, 0); + } + + public void testGenerics4() throws Exception{ + printTestDisabledMessage("see bug 75642"); + +// ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); +// ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); +// +// try{ +// String[] methodNames= new String[]{"m"}; +// String[][] signatures= new String[][]{new String[]{"QList<QT;>;"}}; +// +// IType type= getType(cuB, "B"); +// IMethod[] methods= getMethods(type, methodNames, signatures); +// PullUpRefactoring ref= createRefactoring(methods); +// assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); +// setSuperclassAsTargetClass(ref); +// +// ref.setMethodsToDelete(getMethods(ref.getMatchingElements(new NullProgressMonitor(), false))); +// +// RefactoringStatus result= performRefactoring(ref); +// assertEquals("precondition was supposed to pass", null, result); +// +// assertEqualLines("A", cuA.getSource(), getFileContents(getOutputTestFileName("A"))); +// assertEqualLines("B", cuB.getSource(), getFileContents(getOutputTestFileName("B"))); +// } finally{ +// performDummySearch(); +// cuA.delete(false, null); +// cuB.delete(false, null); +// } + } + + public void testGenerics5() throws Exception{ + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); + + try{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[] {"QS;"}}; + + IType type= getType(cuB, "B"); + IMethod[] methods= getMethods(type, methodNames, signatures); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); + Refactoring ref= processor.getRefactoring(); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + setSuperclassAsTargetClass(processor); + + processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); + + RefactoringStatus result= performRefactoring(ref); + assertTrue("precondition was supposed to pass", result == null || !result.hasError()); + + assertEqualLines("A", cuA.getSource(), getFileContents(getOutputTestFileName("A"))); + assertEqualLines("B", cuB.getSource(), getFileContents(getOutputTestFileName("B"))); + } finally{ + performDummySearch(); + cuA.delete(false, null); + cuB.delete(false, null); + } + } + + public void testGenerics6() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void testGenerics7() throws Exception{ + printTestDisabledMessage("Disabled because of bug "); + + if (!BUG_91542) + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void testGenerics8() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void testGenerics9() throws Exception{ + printTestDisabledMessage("Disabled because of bug "); + + if (!BUG_91542) + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void testGenerics10() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void testGenerics11() throws Exception{ + helper1(new String[]{"m"}, new String[][]{new String[0]}, true, false, 0); + } + + public void testGenerics12() throws Exception{ + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); + + try{ + String[] methodNames= new String[]{"m"}; + String[][] signatures= new String[][]{new String[]{"QT;"}}; + + IType type= getType(cuB, "B"); + IMethod[] methods= getMethods(type, methodNames, signatures); + + PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); + Refactoring ref= processor.getRefactoring(); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + setSuperclassAsTargetClass(processor); + + processor.setDeletedMethods(getMethods(processor.getMatchingElements(new NullProgressMonitor(), false))); + + RefactoringStatus result= performRefactoring(ref); + assertTrue("precondition was supposed to pass", result == null || !result.hasError()); + + assertEqualLines("A", cuA.getSource(), getFileContents(getOutputTestFileName("A"))); + assertEqualLines("B", cuB.getSource(), getFileContents(getOutputTestFileName("B"))); + } finally{ + performDummySearch(); + cuA.delete(false, null); + cuB.delete(false, null); + } + } + + public void testGenerics13() throws Exception { + helper1(new String[] { "m"}, new String[][] { new String[0]}, true, false, 0); + } + + public void testGenerics14() throws Exception { + helper1(new String[] { "m"}, new String[][] { new String[0]}, true, false, 0); + } + + public void testGenerics15() throws Exception { + helper1(new String[] { "m"}, new String[][] { new String[0]}, true, false, 0); + } + + public void testGenericsFail0() throws Exception { + helper2(new String[] { "m"}, new String[][] { new String[] {"QT;"}}, true, false, 0); + } + + public void testGenericsFail1() throws Exception { + helper2(new String[] { "m"}, new String[][] { new String[]{"QS;"}}, true, false, 0); + } + + public void testGenericsFail2() throws Exception { + helper2(new String[] { "m"}, new String[][] { new String[]{"QT;"}}, true, false, 0); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PushDownTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PushDownTests.java new file mode 100644 index 000000000..ba716de50 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PushDownTests.java @@ -0,0 +1,1676 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; + +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; +import org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoringProcessor; +import org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoringProcessor.MemberActionInfo; + +public class PushDownTests extends RefactoringTest { + + private static final Class clazz= PushDownTests.class; + + private static final String REFACTORING_PATH= "PushDown/"; + + public PushDownTests(String name) { + super(name); + } + + public static Test suite() { + return new Java15Setup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new Java15Setup(someTest); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + private Refactoring createRefactoringPrepareForInputCheck(String[] selectedMethodNames, String[][] selectedMethodSignatures, + String[] selectedFieldNames, + String[] namesOfMethodsToPullUp, String[][] signaturesOfMethodsToPullUp, + String[] namesOfFieldsToPullUp, + String[] namesOfMethodsToDeclareAbstract, String[][] signaturesOfMethodsToDeclareAbstract, + ICompilationUnit cu) throws CoreException { + + IType type= getType(cu, "A"); + IMethod[] selectedMethods= getMethods(type, selectedMethodNames, selectedMethodSignatures); + IField[] selectedFields= getFields(type, selectedFieldNames); + IMember[] selectedMembers= merge(selectedFields, selectedMethods); + + assertTrue(RefactoringAvailabilityTester.isPushDownAvailable(selectedMembers)); + PushDownRefactoringProcessor processor= new PushDownRefactoringProcessor(selectedMembers); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + + prepareForInputCheck(processor, selectedMethods, selectedFields, namesOfMethodsToPullUp, signaturesOfMethodsToPullUp, namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, + signaturesOfMethodsToDeclareAbstract); + return ref; + } + + private void prepareForInputCheck(PushDownRefactoringProcessor processor, IMethod[] selectedMethods, IField[] selectedFields, String[] namesOfMethodsToPullUp, String[][] signaturesOfMethodsToPullUp, String[] namesOfFieldsToPullUp, String[] namesOfMethodsToDeclareAbstract, String[][] signaturesOfMethodsToDeclareAbstract) { + IMethod[] methodsToPushDown= findMethods(selectedMethods, namesOfMethodsToPullUp, signaturesOfMethodsToPullUp); + IField[] fieldsToPushDown= findFields(selectedFields, namesOfFieldsToPullUp); + List membersToPushDown= Arrays.asList(merge(methodsToPushDown, fieldsToPushDown)); + List methodsToDeclareAbstract= Arrays.asList(findMethods(selectedMethods, namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract)); + + MemberActionInfo[] infos= processor.getMemberActionInfos(); + for (int i= 0; i < infos.length; i++) { + if (membersToPushDown.contains(infos[i].getMember())){ + infos[i].setAction(MemberActionInfo.PUSH_DOWN_ACTION); + assertTrue(! methodsToDeclareAbstract.contains(infos[i].getMember())); + } + if (methodsToDeclareAbstract.contains(infos[i].getMember())){ + infos[i].setAction(MemberActionInfo.PUSH_ABSTRACT_ACTION); + assertTrue(! membersToPushDown.contains(infos[i].getMember())); + } + } + } + + private void helper(String[] selectedMethodNames, String[][] selectedMethodSignatures, + String[] selectedFieldNames, + String[] namesOfMethodsToPullUp, String[][] signaturesOfMethodsToPullUp, + String[] namesOfFieldsToPullUp, String[] namesOfMethodsToDeclareAbstract, + String[][] signaturesOfMethodsToDeclareAbstract, String[] additionalCuNames, String[] additionalPackNames) throws Exception{ + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + + IPackageFragment[] addtionalPacks= createAdditionalPackages(additionalCuNames, additionalPackNames); + ICompilationUnit[] additonalCus= createAdditionalCus(additionalCuNames, addtionalPacks); + + try{ + Refactoring ref= createRefactoringPrepareForInputCheck(selectedMethodNames, selectedMethodSignatures, selectedFieldNames, namesOfMethodsToPullUp, signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, cuA); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertTrue("precondition was supposed to pass but got " + checkInputResult.toString(), !checkInputResult.hasError()); + performChange(ref, false); + + String expected= getFileContents(getOutputTestFileName("A")); + String actual= cuA.getSource(); + assertEqualLines("A.java", expected, actual); + + for (int i= 0; i < additonalCus.length; i++) { + ICompilationUnit unit= additonalCus[i]; + String expectedS= getFileContents(getOutputTestFileName(additionalCuNames[i])); + String actualS= unit.getSource(); + assertEqualLines(unit.getElementName(), expectedS, actualS); + } + + } finally{ + performDummySearch(); + cuA.delete(false, null); + for (int i= 0; i < additonalCus.length; i++) { + additonalCus[i].delete(false, null); + } + for (int i= 0; i < addtionalPacks.length; i++) { + if (! addtionalPacks[i].equals(getPackageP())) + addtionalPacks[i].delete(false, null); + } + } + } + + private ICompilationUnit[] createAdditionalCus(String[] additionalCuNames, IPackageFragment[] addtionalPacks) throws Exception { + ICompilationUnit[] additonalCus= new ICompilationUnit[0]; + if (additionalCuNames != null){ + additonalCus= new ICompilationUnit[additionalCuNames.length]; + for (int i= 0; i < additonalCus.length; i++) { + additonalCus[i]= createCUfromTestFile(addtionalPacks[i], additionalCuNames[i]); + } + } + return additonalCus; + } + + private IPackageFragment[] createAdditionalPackages(String[] additionalCuNames, String[] additionalPackNames) { + IPackageFragment[] additionalPacks= new IPackageFragment[0]; + if (additionalPackNames != null){ + additionalPacks= new IPackageFragment[additionalPackNames.length]; + assertTrue(additionalPackNames.length == additionalCuNames.length); + for (int i= 0; i < additionalPackNames.length; i++) { + additionalPacks[i]= getRoot().getPackageFragment(additionalPackNames[i]); + } + } + return additionalPacks; + } + + private void failActivationHelper(String[] selectedMethodNames, String[][] selectedMethodSignatures, + String[] selectedFieldNames, + String[] namesOfMethodsToPullUp, String[][] signaturesOfMethodsToPullUp, + String[] namesOfFieldsToPullUp, String[] namesOfMethodsToDeclareAbstract, + String[][] signaturesOfMethodsToDeclareAbstract, + int expectedSeverity) throws Exception{ + + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + try{ + IType type= getType(cu, "A"); + IMethod[] selectedMethods= getMethods(type, selectedMethodNames, selectedMethodSignatures); + IField[] selectedFields= getFields(type, selectedFieldNames); + IMember[] selectedMembers= merge(selectedFields, selectedMethods); + + assertTrue(RefactoringAvailabilityTester.isPushDownAvailable(selectedMembers)); + PushDownRefactoringProcessor processor= new PushDownRefactoringProcessor(selectedMembers); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + assertEquals("activation was expected to fail", expectedSeverity, ref.checkInitialConditions(new NullProgressMonitor()).getSeverity()); + } finally{ + performDummySearch(); + cu.delete(false, null); + } + } + + private void failInputHelper(String[] selectedMethodNames, String[][] selectedMethodSignatures, + String[] selectedFieldNames, + String[] namesOfMethodsToPullUp, String[][] signaturesOfMethodsToPullUp, + String[] namesOfFieldsToPullUp, String[] namesOfMethodsToDeclareAbstract, + String[][] signaturesOfMethodsToDeclareAbstract, + int expectedSeverity) throws Exception{ + + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + try{ + + + Refactoring ref= createRefactoringPrepareForInputCheck(selectedMethodNames, selectedMethodSignatures, selectedFieldNames, namesOfMethodsToPullUp, signaturesOfMethodsToPullUp, + namesOfFieldsToPullUp, namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, cu); + RefactoringStatus checkInputResult= ref.checkFinalConditions(new NullProgressMonitor()); + assertEquals("precondition was expected to fail", expectedSeverity, checkInputResult.getSeverity()); + } finally{ + performDummySearch(); + cu.delete(false, null); + } + } + + private void addRequiredMembersHelper(String[] fieldNames, String[] methodNames, String[][] methodSignatures, String[] expectedFieldNames, String[] expectedMethodNames, String[][] expectedMethodSignatures) throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + try{ + IType type= getType(cu, "A"); + IField[] fields= getFields(type, fieldNames); + IMethod[] methods= getMethods(type, methodNames, methodSignatures); + + IMember[] members= merge(methods, fields); + assertTrue(RefactoringAvailabilityTester.isPushDownAvailable(members)); + PushDownRefactoringProcessor processor= new PushDownRefactoringProcessor(members); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + assertTrue("activation", ref.checkInitialConditions(new NullProgressMonitor()).isOK()); + + processor.computeAdditionalRequiredMembersToPushDown(new NullProgressMonitor()); + List required= getMembersToPushDown(processor); + processor.getMemberActionInfos(); + IField[] expectedFields= getFields(type, expectedFieldNames); + IMethod[] expectedMethods= getMethods(type, expectedMethodNames, expectedMethodSignatures); + List expected= Arrays.asList(merge(expectedFields, expectedMethods)); + assertEquals("incorrect size", expected.size(), required.size()); + for (Iterator iter= expected.iterator(); iter.hasNext();) { + Object each= iter.next(); + assertTrue ("required does not contain " + each, required.contains(each)); + } + for (Iterator iter= required.iterator(); iter.hasNext();) { + Object each= iter.next(); + assertTrue ("expected does not contain " + each, expected.contains(each)); + } + } finally{ + performDummySearch(); + cu.delete(false, null); + } + } + + private static List getMembersToPushDown(PushDownRefactoringProcessor processor) { + MemberActionInfo[] infos= processor.getMemberActionInfos(); + List result= new ArrayList(infos.length); + for (int i= 0; i < infos.length; i++) { + if (infos[i].isToBePushedDown()) + result.add(infos[i].getMember()); + } + return result; + } + + //-------------------------------------------------------- + + public void test0() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test1() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test2() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test3() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test4() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test5() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test6() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test7() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test8() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test9() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test10() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test11() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test12() throws Exception{ + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {"f"}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {"f"}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test13() throws Exception{ + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {"f"}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {"f"}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test14() throws Exception{ + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test15() throws Exception{ + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test16() throws Exception{ + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test17() throws Exception{ + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test18() throws Exception{ + String[] selectedMethodNames= {"f", "m"}; + String[][] selectedMethodSignatures= {new String[0], new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test19() throws Exception{ + String[] selectedMethodNames= {"f", "m"}; + String[][] selectedMethodSignatures= {new String[0], new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test20() throws Exception{ + String[] selectedMethodNames= {"f", "m"}; + String[][] selectedMethodSignatures= {new String[0], new String[0]}; + String[] selectedFieldNames= {"i"}; + String[] namesOfMethodsToPushDown= {"f"}; + String[][] signaturesOfMethodsToPushDown= {new String[0]}; + String[] namesOfFieldsToPushDown= {"i"}; + String[] namesOfMethodsToDeclareAbstract= {"m"}; + String[][] signaturesOfMethodsToDeclareAbstract= {new String[0]}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, + new String[]{"B"}, new String[]{"p"}); + } + + public void test21() throws Exception{ + String[] selectedMethodNames= {"f", "m"}; + String[][] selectedMethodSignatures= {new String[0], new String[0]}; + String[] selectedFieldNames= {"i"}; + String[] namesOfMethodsToPushDown= {"f", "m"}; + String[][] signaturesOfMethodsToPushDown= {new String[0], new String[0]}; + String[] namesOfFieldsToPushDown= {"i"}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, + new String[]{"B", "C"}, new String[]{"p", "p"}); + } + + public void test22() throws Exception{ + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {"bar"}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= selectedFieldNames; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test23() throws Exception{ + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {"bar"}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= selectedFieldNames; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test24() throws Exception{ + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {"foo", "bar"}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= selectedFieldNames; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test25() throws Exception{ + String[] selectedMethodNames= {"foo"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test26() throws Exception{ + String[] selectedMethodNames= {"bar"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test27() throws Exception{ + String[] selectedMethodNames= {"bar"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test28() throws Exception{ +// if (true){ +// printTestDisabledMessage("37175"); +// return; +// } + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {"i", "j"}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {"i", "j"}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test29() throws Exception{ + String[] selectedMethodNames= {"foo"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test30() throws Exception{ + String[] selectedMethodNames= {"foo"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test31() throws Exception{ + String[] selectedMethodNames= {"foo"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test32() throws Exception{ + String[] selectedMethodNames= {"foo"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void test33() throws Exception{ + String[] selectedMethodNames= {"f", "m"}; + String[][] selectedMethodSignatures= {new String[0], new String[0]}; + String[] selectedFieldNames= {"i"}; + String[] namesOfMethodsToPushDown= {"f", "m"}; + String[][] signaturesOfMethodsToPushDown= {new String[0], new String[0]}; + String[] namesOfFieldsToPushDown= {"i"}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, + new String[]{"B", "C"}, new String[]{"p", "p"}); + } + + public void test34() throws Exception{ + printTestDisabledMessage("disabled due to missing support for statically imported methods"); + +// String[] selectedMethodNames= {"f", "m"}; +// String[][] selectedMethodSignatures= {new String[0], new String[0]}; +// String[] selectedFieldNames= {"i"}; +// String[] namesOfMethodsToPushDown= {"f", "m"}; +// String[][] signaturesOfMethodsToPushDown= {new String[0], new String[0]}; +// String[] namesOfFieldsToPushDown= {"i"}; +// String[] namesOfMethodsToDeclareAbstract= {}; +// String[][] signaturesOfMethodsToDeclareAbstract= {}; +// +// helper(selectedMethodNames, selectedMethodSignatures, +// selectedFieldNames, +// namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, +// namesOfFieldsToPushDown, +// namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, +// new String[]{"B", "C"}, new String[]{"p", "p"}); + } + + public void testFail0() throws Exception { + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + failActivationHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, + RefactoringStatus.FATAL); + } + + public void testFail1() throws Exception { + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + failActivationHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, + RefactoringStatus.FATAL); + } + + public void testFail2() throws Exception { + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + failInputHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, + RefactoringStatus.ERROR); + } + + public void testFail3() throws Exception { + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {"i"}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= selectedFieldNames; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + failInputHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, + RefactoringStatus.ERROR); + } + + public void testVisibility1() throws Exception { + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testVisibility2() throws Exception { + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testVisibility3() throws Exception { + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testFail7() throws Exception { + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + failInputHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, + RefactoringStatus.ERROR); + } + + public void testFail8() throws Exception { + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + failInputHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, + RefactoringStatus.ERROR); + } + + public void testFail9() throws Exception { + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {"f"}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= selectedFieldNames; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + failInputHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, + RefactoringStatus.ERROR); + } + + public void testFail10() throws Exception { + String[] selectedMethodNames= {"foo"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + failInputHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, + RefactoringStatus.ERROR); + } + + public void testFail11() throws Exception { + String[] selectedMethodNames= {"foo"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + failInputHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, + RefactoringStatus.ERROR); + } + + public void testFail12() throws Exception { + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {"bar"}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= selectedFieldNames; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + failInputHelper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, + RefactoringStatus.ERROR); + } + + public void testVisibility0() throws Exception { + String[] selectedMethodNames= {"foo"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testAddingRequiredMembers0() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= methodNames; + String[][] expectedMethodSignatures= methodSignatures; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers1() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= methodNames; + String[][] expectedMethodSignatures= methodSignatures; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers2() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= methodNames; + String[][] expectedMethodSignatures= methodSignatures; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers3() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= {"m", "f"}; + String[][] expectedMethodSignatures= {new String[0], new String[0]}; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers4() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m", "f"}; + String[][] methodSignatures= {new String[0], new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= methodNames; + String[][] expectedMethodSignatures= methodSignatures; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers5() throws Exception{ + String[] fieldNames= {}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= {"f"}; + String[] expectedMethodNames= methodNames; + String[][] expectedMethodSignatures= methodSignatures; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers6() throws Exception{ + String[] fieldNames= {"f"}; + String[] methodNames= {"m"}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= methodNames; + String[][] expectedMethodSignatures= methodSignatures; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers7() throws Exception{ + String[] fieldNames= {"f"}; + String[] methodNames= {}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= fieldNames; + String[] expectedMethodNames= {"m"}; + String[][] expectedMethodSignatures= {new String[0]}; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers8() throws Exception{ + String[] fieldNames= {"f"}; + String[] methodNames= {}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= {"f", "m"}; + String[] expectedMethodNames= {}; + String[][] expectedMethodSignatures= {new String[0]}; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testAddingRequiredMembers9() throws Exception{ + String[] fieldNames= {"f"}; + String[] methodNames= {}; + String[][] methodSignatures= {new String[0]}; + + String[] expectedFieldNames= {"f", "m"}; + String[] expectedMethodNames= {}; + String[][] expectedMethodSignatures= {new String[0]}; + addRequiredMembersHelper(fieldNames, methodNames, methodSignatures, expectedFieldNames, expectedMethodNames, expectedMethodSignatures); + } + + public void testEnablement0() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeA= cu.getType("A"); + IMember[] members= {typeA}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement1() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeA= cu.getType("A"); + IMember[] members= {typeA}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement2() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("Outer").getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement3() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeA= cu.getType("A"); + IType typeB= cu.getType("B"); + IMember[] members= {typeA, typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement4() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeA= cu.getType("A"); + IMember[] members= {typeA}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement5() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeA= cu.getType("A"); + IMember[] members= {typeA}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement6() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeA= cu.getType("A"); + IMember[] members= {typeA}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement7() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeA= cu.getType("A"); + IMember[] members= {typeA}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement8() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeA= cu.getType("A"); + IMember[] members= {typeA}; + assertTrue("should be enabled", RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement9() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeA= cu.getType("A"); + IMember[] members= {typeA}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement10() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeA= cu.getType("A"); + IMember[] members= {typeA}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement11() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeA= cu.getType("A"); + IMember[] members= {typeA}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement12() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("Outer").getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement13() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("Outer").getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement14() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("Outer").getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testEnablement15() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType typeB= cu.getType("Outer").getType("B"); + IMember[] members= {typeB}; + assertTrue("should be disabled", ! RefactoringAvailabilityTester.isPushDownAvailable(members)); + } + + public void testGenerics0() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics1() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics2() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics3() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics4() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics5() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics6() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics7() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics8() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics9() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics10() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics11() throws Exception{ + String[] selectedMethodNames= {"m"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics12() throws Exception{ + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {"f"}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {"f"}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics13() throws Exception{ + String[] selectedMethodNames= {}; + String[][] selectedMethodSignatures= {}; + String[] selectedFieldNames= {"f"}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {"f"}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics14() throws Exception{ + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics15() throws Exception{ + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics16() throws Exception{ + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics17() throws Exception{ + String[] selectedMethodNames= {"f"}; + String[][] selectedMethodSignatures= {new String[0]}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics18() throws Exception{ + String[] selectedMethodNames= {"f", "m"}; + String[][] selectedMethodSignatures= {new String[0], new String[] {"QT;"}}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= selectedMethodNames; + String[][] signaturesOfMethodsToPushDown= selectedMethodSignatures; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= {}; + String[][] signaturesOfMethodsToDeclareAbstract= {}; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } + + public void testGenerics19() throws Exception{ + String[] selectedMethodNames= {"f", "m"}; + String[][] selectedMethodSignatures= {new String[0], new String[]{"QT;"}}; + String[] selectedFieldNames= {}; + String[] namesOfMethodsToPushDown= {}; + String[][] signaturesOfMethodsToPushDown= {}; + String[] namesOfFieldsToPushDown= {}; + String[] namesOfMethodsToDeclareAbstract= selectedMethodNames; + String[][] signaturesOfMethodsToDeclareAbstract= selectedMethodSignatures; + + helper(selectedMethodNames, selectedMethodSignatures, + selectedFieldNames, + namesOfMethodsToPushDown, signaturesOfMethodsToPushDown, + namesOfFieldsToPushDown, + namesOfMethodsToDeclareAbstract, signaturesOfMethodsToDeclareAbstract, null, null); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringScannerTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringScannerTests.java new file mode 100644 index 000000000..0d429e06d --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringScannerTests.java @@ -0,0 +1,115 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.Set; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringScanner; +import org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringScanner.TextMatch; + +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +public class RefactoringScannerTests extends RefactoringTest{ + + private static class Position { + private final int fLine; + private final int fColumn; + Position(int line, int column) { + fLine= line; + fColumn= column; + } + } + + + public RefactoringScannerTests(String name){ + super(name); + } + + private RefactoringScanner fScanner; + private static Class clazz= RefactoringScannerTests.class; + + protected String getRefactoringPath() { + return "RefactoringScanner/"; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + protected void setUp() throws Exception { + //no need to call super.setUp(); + fScanner= new RefactoringScanner("TestPattern", "org.eclipse"); + } + + protected void tearDown() throws Exception { + //no need to call super.tearDown(); + } + + private void helper(String fileName, int expectedMatchCount) throws Exception{ + String text= getFileContents(getRefactoringPath() + fileName); + fScanner.scan(text); + assertEquals("results.length", expectedMatchCount, fScanner.getMatches().size()); + } + + private void helper2(String fileName, Position[] expectedMatches) throws Exception{ + String text= getFileContents(getRefactoringPath() + fileName); + fScanner.scan(text); + + ArrayList expectedMatchesList= new ArrayList(expectedMatches.length); + for (int i= 0; i < expectedMatches.length; i++) + expectedMatchesList.add(new Integer(TextRangeUtil.getOffset(text, expectedMatches[i].fLine, expectedMatches[i].fColumn))); + ArrayList matchesList= new ArrayList(); + Set matches= fScanner.getMatches(); + for (Iterator iter= matches.iterator(); iter.hasNext();) { + TextMatch element= (TextMatch) iter.next(); + matchesList.add(new Integer(element.getStartPosition())); + } + Collections.sort(matchesList); + assertEquals("results", expectedMatchesList.toString(), matchesList.toString()); + } + + //-- tests + public void test0() throws Exception{ + String text= ""; + fScanner.scan(text); + assertEquals("results.length", 0, fScanner.getMatches().size()); + } + + public void test1() throws Exception{ + helper("A.java", 8); + } + + public void testWord1() throws Exception{ + helper("B.java", 6); + } + + public void testQualifier() throws Exception{ + helper2("C.java", new Position[] { + new Position(4, 21), + new Position(17, 21), + + new Position(28, 21), + new Position(29, 20), + + new Position(32, 20), + + new Position(37, 21), + new Position(38, 20), + }); + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTest.java new file mode 100644 index 000000000..dafca38cd --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTest.java @@ -0,0 +1,625 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import junit.framework.TestCase; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.IResourceChangeListener; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.ChangeDescriptor; +import org.eclipse.ltk.core.refactoring.CheckConditionsOperation; +import org.eclipse.ltk.core.refactoring.CreateChangeOperation; +import org.eclipse.ltk.core.refactoring.IUndoManager; +import org.eclipse.ltk.core.refactoring.PerformChangeOperation; +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor; +import org.eclipse.ltk.core.refactoring.RefactoringContribution; +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.ISourceManipulation; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.refactoring.descriptors.JavaRefactoringDescriptor; +import org.eclipse.jdt.core.search.IJavaSearchConstants; +import org.eclipse.jdt.core.search.SearchEngine; +import org.eclipse.jdt.core.search.SearchPattern; +import org.eclipse.jdt.core.search.TypeNameRequestor; + +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; +import org.eclipse.jdt.internal.corext.util.Strings; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringTestPlugin; + +public abstract class RefactoringTest extends TestCase { + + /** + * If <code>true</code> a descriptor is created from the change. + * The new descriptor is then used to create the refactoring again + * and run the refactoring. As this is very time consuming this should + * be <code>false</code> by default. + */ + private static final boolean DESCRIPTOR_TEST= false; + + private IPackageFragmentRoot fRoot; + private IPackageFragment fPackageP; + + public boolean fIsVerbose= false; + public boolean fIsPreDeltaTest= false; + + public static final String TEST_PATH_PREFIX= ""; + + protected static final String TEST_INPUT_INFIX= "/in/"; + protected static final String TEST_OUTPUT_INFIX= "/out/"; + protected static final String CONTAINER= "src"; + + protected static final List/*<String>*/ PROJECT_RESOURCE_CHILDREN= Arrays.asList(new String[] { + ".project", ".classpath", ".settings" }); + + public RefactoringTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + fRoot= RefactoringTestSetup.getDefaultSourceFolder(); + fPackageP= RefactoringTestSetup.getPackageP(); + fIsPreDeltaTest= false; + + if (fIsVerbose){ + System.out.println("\n---------------------------------------------"); + System.out.println("\nTest:" + getClass() + "." + getName()); + } + RefactoringCore.getUndoManager().flush(); + } + + protected void performDummySearch() throws Exception { + performDummySearch(getPackageP()); + } + + /** + * Removes contents of {@link #getPackageP()}, of {@link #getRoot()} (except for p) and of the + * Java project (except for src and the JRE library). + * + * @throws Exception in case of errors + */ + protected void tearDown() throws Exception { + refreshFromLocal(); + performDummySearch(); + + if (getPackageP().exists()){ + tryDeletingAllJavaChildren(getPackageP()); + tryDeletingAllNonJavaChildResources(getPackageP()); + } + + if (getRoot().exists()){ + IJavaElement[] packages= getRoot().getChildren(); + for (int i= 0; i < packages.length; i++){ + IPackageFragment pack= (IPackageFragment)packages[i]; + if (!pack.equals(getPackageP()) && pack.exists() && !pack.isReadOnly()) + if (pack.isDefaultPackage()) + pack.delete(true, null); + else + JavaProjectHelper.delete(pack.getResource()); // also delete packages with subpackages + } + } + + restoreTestProject(); + } + + private void restoreTestProject() throws Exception { + IJavaProject javaProject= getRoot().getJavaProject(); + if (javaProject.exists()) { + IClasspathEntry srcEntry= getRoot().getRawClasspathEntry(); + IClasspathEntry jreEntry= RefactoringTestSetup.getJRELibrary().getRawClasspathEntry(); + IClasspathEntry[] cpes= javaProject.getRawClasspath(); + ArrayList newCPEs= new ArrayList(); + boolean cpChanged= false; + for (int i= 0; i < cpes.length; i++) { + IClasspathEntry cpe= cpes[i]; + if (cpe.equals(srcEntry) || cpe.equals(jreEntry)) { + newCPEs.add(cpe); + } else { + cpChanged= true; + } + } + if (cpChanged) { + IClasspathEntry[] newCPEsArray= (IClasspathEntry[]) newCPEs.toArray(new IClasspathEntry[newCPEs.size()]); + javaProject.setRawClasspath(newCPEsArray, null); + } + + Object[] nonJavaResources= javaProject.getNonJavaResources(); + for (int i= 0; i < nonJavaResources.length; i++) { + Object kid= nonJavaResources[i]; + if (kid instanceof IResource) { + IResource resource= (IResource) kid; + if (! PROJECT_RESOURCE_CHILDREN.contains(resource.getName())) { + JavaProjectHelper.delete(resource); + } + } + } + } + } + + private void refreshFromLocal() throws CoreException { + if (getRoot().exists()) + getRoot().getResource().refreshLocal(IResource.DEPTH_INFINITE, null); + else if (getPackageP().exists())//don't refresh package if root already refreshed + getPackageP().getResource().refreshLocal(IResource.DEPTH_INFINITE, null); + } + + private static void tryDeletingAllNonJavaChildResources(IPackageFragment pack) throws CoreException { + Object[] nonJavaKids= pack.getNonJavaResources(); + for (int i= 0; i < nonJavaKids.length; i++) { + if (nonJavaKids[i] instanceof IResource) { + IResource resource= (IResource)nonJavaKids[i]; + JavaProjectHelper.delete(resource); + } + } + } + + private static void tryDeletingAllJavaChildren(IPackageFragment pack) throws CoreException { + IJavaElement[] kids= pack.getChildren(); + for (int i= 0; i < kids.length; i++){ + if (kids[i] instanceof ISourceManipulation){ + if (kids[i].exists() && !kids[i].isReadOnly()) + JavaProjectHelper.delete(kids[i]); + } + } + } + + protected IPackageFragmentRoot getRoot() { + return fRoot; + } + + protected IPackageFragment getPackageP() { + return fPackageP; + } + + protected final RefactoringStatus performRefactoring(RefactoringDescriptor descriptor) throws Exception { + return performRefactoring(descriptor, true); + } + + protected final RefactoringStatus performRefactoring(RefactoringDescriptor descriptor, boolean providesUndo) throws Exception { + Refactoring refactoring= createRefactoring(descriptor); + return performRefactoring(refactoring, providesUndo); + } + + protected final Refactoring createRefactoring(RefactoringDescriptor descriptor) throws CoreException { + RefactoringStatus status= new RefactoringStatus(); + Refactoring refactoring= descriptor.createRefactoring(status); + assertNotNull("refactoring should not be null", refactoring); + assertTrue("status should be ok", status.isOK()); + return refactoring; + } + + protected final RefactoringStatus performRefactoring(Refactoring ref) throws Exception { + return performRefactoring(ref, true); + } + + protected final RefactoringStatus performRefactoring(Refactoring ref, boolean providesUndo) throws Exception { + performDummySearch(); + IUndoManager undoManager= getUndoManager(); + if (DESCRIPTOR_TEST){ + final CreateChangeOperation create= new CreateChangeOperation( + new CheckConditionsOperation(ref, CheckConditionsOperation.ALL_CONDITIONS), + RefactoringStatus.FATAL); + create.run(new NullProgressMonitor()); + RefactoringStatus checkingStatus= create.getConditionCheckingStatus(); + if (!checkingStatus.isOK()) + return checkingStatus; + Change change= create.getChange(); + ChangeDescriptor descriptor= change.getDescriptor(); + if (descriptor instanceof RefactoringChangeDescriptor) { + RefactoringChangeDescriptor rcd= (RefactoringChangeDescriptor) descriptor; + RefactoringDescriptor refactoringDescriptor= rcd.getRefactoringDescriptor(); + if (refactoringDescriptor instanceof JavaRefactoringDescriptor) { + JavaRefactoringDescriptor jrd= (JavaRefactoringDescriptor) refactoringDescriptor; + RefactoringStatus validation= jrd.validateDescriptor(); + if (!validation.isOK()) + return validation; + RefactoringStatus refactoringStatus= new RefactoringStatus(); + Class expected= jrd.getClass(); + RefactoringContribution contribution= RefactoringCore.getRefactoringContribution(jrd.getID()); + jrd= (JavaRefactoringDescriptor) contribution.createDescriptor(jrd.getID(), jrd.getProject(), jrd.getDescription(), jrd.getComment(), contribution.retrieveArgumentMap(jrd), jrd.getFlags()); + assertEquals(expected, jrd.getClass()); + ref= jrd.createRefactoring(refactoringStatus); + if (!refactoringStatus.isOK()) + return refactoringStatus; + TestRenameParticipantSingle.reset(); + TestCreateParticipantSingle.reset(); + TestMoveParticipantSingle.reset(); + TestDeleteParticipantSingle.reset(); + } + } + } + final CreateChangeOperation create= new CreateChangeOperation( + new CheckConditionsOperation(ref, CheckConditionsOperation.ALL_CONDITIONS), + RefactoringStatus.FATAL); + final PerformChangeOperation perform= new PerformChangeOperation(create); + perform.setUndoManager(undoManager, ref.getName()); + IWorkspace workspace= ResourcesPlugin.getWorkspace(); + if (fIsPreDeltaTest) { + IResourceChangeListener listener= new IResourceChangeListener() { + public void resourceChanged(IResourceChangeEvent event) { + if (create.getConditionCheckingStatus().isOK() && perform.changeExecuted()) { + TestModelProvider.assertTrue(event.getDelta()); + } + } + }; + try { + TestModelProvider.clearDelta(); + workspace.checkpoint(false); + workspace.addResourceChangeListener(listener); + executePerformOperation(perform, workspace); + } finally { + workspace.removeResourceChangeListener(listener); + } + } else { + executePerformOperation(perform, workspace); + } + RefactoringStatus status= create.getConditionCheckingStatus(); + if (!status.isOK()) + return status; + assertTrue("Change wasn't executed", perform.changeExecuted()); + Change undo= perform.getUndoChange(); + if (providesUndo) { + assertNotNull("Undo doesn't exist", undo); + assertTrue("Undo manager is empty", undoManager.anythingToUndo()); + } else { + assertNull("Undo manager contains undo but shouldn't", undo); + } + return null; + } + + protected void executePerformOperation(final PerformChangeOperation perform, IWorkspace workspace) throws CoreException { + workspace.run(perform, new NullProgressMonitor()); + } + + public RefactoringStatus performRefactoringWithStatus(Refactoring ref) throws Exception, CoreException { + RefactoringStatus status= performRefactoring(ref); + if (status == null) + return new RefactoringStatus(); + return status; + } + + protected final Change performChange(Refactoring refactoring, boolean storeUndo) throws Exception { + CreateChangeOperation create= new CreateChangeOperation(refactoring); + PerformChangeOperation perform= new PerformChangeOperation(create); + if (storeUndo) { + perform.setUndoManager(getUndoManager(), refactoring.getName()); + } + ResourcesPlugin.getWorkspace().run(perform, new NullProgressMonitor()); + assertTrue("Change wasn't executed", perform.changeExecuted()); + return perform.getUndoChange(); + } + + protected final Change performChange(final Change change) throws Exception { + PerformChangeOperation perform= new PerformChangeOperation(change); + ResourcesPlugin.getWorkspace().run(perform, new NullProgressMonitor()); + assertTrue("Change wasn't executed", perform.changeExecuted()); + return perform.getUndoChange(); + } + + protected IUndoManager getUndoManager() { + IUndoManager undoManager= RefactoringCore.getUndoManager(); + undoManager.flush(); + return undoManager; + } + + /* =================== helpers ================= */ + protected IType getType(ICompilationUnit cu, String name) throws JavaModelException { + IType[] types= cu.getAllTypes(); + for (int i= 0; i < types.length; i++) + if (types[i].getTypeQualifiedName('.').equals(name) || + types[i].getElementName().equals(name)) + return types[i]; + return null; + } + + /* + * subclasses override to inform about the location of their test cases + */ + protected String getRefactoringPath() { + return ""; + } + + /* + * example "RenameType/" + */ + protected String getTestPath() { + return TEST_PATH_PREFIX + getRefactoringPath(); + } + + protected String createTestFileName(String cuName, String infix) { + return getTestPath() + getName() + infix + cuName + ".java"; + } + + protected String getInputTestFileName(String cuName) { + return createTestFileName(cuName, TEST_INPUT_INFIX); + } + + /* + * @param subDirName example "p/" or "org/eclipse/jdt/" + */ + protected String getInputTestFileName(String cuName, String subDirName) { + return createTestFileName(cuName, TEST_INPUT_INFIX + subDirName); + } + + protected String getOutputTestFileName(String cuName) { + return createTestFileName(cuName, TEST_OUTPUT_INFIX); + } + + /* + * @param subDirName example "p/" or "org/eclipse/jdt/" + */ + protected String getOutputTestFileName(String cuName, String subDirName) { + return createTestFileName(cuName, TEST_OUTPUT_INFIX + subDirName); + } + + protected ICompilationUnit createCUfromTestFile(IPackageFragment pack, String cuName) throws Exception { + return createCUfromTestFile(pack, cuName, true); + } + + protected ICompilationUnit createCUfromTestFile(IPackageFragment pack, String cuName, String subDirName) throws Exception { + return createCUfromTestFile(pack, cuName, subDirName, true); + } + + protected ICompilationUnit createCUfromTestFile(IPackageFragment pack, String cuName, boolean input) throws Exception { + String contents= input + ? getFileContents(getInputTestFileName(cuName)) + : getFileContents(getOutputTestFileName(cuName)); + return createCU(pack, cuName + ".java", contents); + } + + protected ICompilationUnit createCUfromTestFile(IPackageFragment pack, String cuName, String subDirName, boolean input) throws Exception { + String contents= input + ? getFileContents(getInputTestFileName(cuName, subDirName)) + : getFileContents(getOutputTestFileName(cuName, subDirName)); + + return createCU(pack, cuName + ".java", contents); + } + + protected void printTestDisabledMessage(String explanation){ + System.out.println("\n" +getClass().getName() + "::"+ getName() + " disabled (" + explanation + ")"); + } + + //----------------------- + public static InputStream getStream(String content){ + return new ByteArrayInputStream(content.getBytes()); + } + + public static IPackageFragmentRoot getSourceFolder(IJavaProject javaProject, String name) throws JavaModelException{ + IPackageFragmentRoot[] roots= javaProject.getPackageFragmentRoots(); + for (int i= 0; i < roots.length; i++) { + if (! roots[i].isArchive() && roots[i].getElementName().equals(name)) + return roots[i]; + } + return null; + } + + public String getFileContents(String fileName) throws IOException { + return getContents(getFileInputStream(fileName)); + } + + public static String getContents(IFile file) throws IOException, CoreException { + return getContents(file.getContents()); + } + + public static ICompilationUnit createCU(IPackageFragment pack, String name, String contents) throws Exception { + assertTrue(!pack.getCompilationUnit(name).exists()); + ICompilationUnit cu= pack.createCompilationUnit(name, contents, true, null); + cu.save(null, true); + return cu; + } + + public static String getContents(InputStream in) throws IOException { + BufferedReader br= new BufferedReader(new InputStreamReader(in)); + + StringBuffer sb= new StringBuffer(300); + try { + int read= 0; + while ((read= br.read()) != -1) + sb.append((char) read); + } finally { + br.close(); + } + return sb.toString(); + } + + public static InputStream getFileInputStream(String fileName) throws IOException { + return RefactoringTestPlugin.getDefault().getTestResourceStream(fileName); + } + + public static String removeExtension(String fileName) { + return fileName.substring(0, fileName.lastIndexOf('.')); + } + + public static void performDummySearch(IJavaElement element) throws Exception{ + new SearchEngine().searchAllTypeNames( + null, + SearchPattern.R_EXACT_MATCH, + "XXXXXXXXX".toCharArray(), // make sure we search a concrete name. This is faster according to Kent + SearchPattern.R_EXACT_MATCH, + IJavaSearchConstants.CLASS, + SearchEngine.createJavaSearchScope(new IJavaElement[]{element}), + new Requestor(), + IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, + null); + } + + public static IMember[] merge(IMember[] a1, IMember[] a2, IMember[] a3){ + return JavaElementUtil.merge(JavaElementUtil.merge(a1, a2), a3); + } + + public static IMember[] merge(IMember[] a1, IMember[] a2){ + return JavaElementUtil.merge(a1, a2); + } + + public static IField[] getFields(IType type, String[] names) { + if (names == null ) + return new IField[0]; + Set fields= new HashSet(); + for (int i = 0; i < names.length; i++) { + IField field= type.getField(names[i]); + assertTrue("field " + field.getElementName() + " does not exist", field.exists()); + fields.add(field); + } + return (IField[]) fields.toArray(new IField[fields.size()]); + } + + public static IType[] getMemberTypes(IType type, String[] names) { + if (names == null ) + return new IType[0]; + Set memberTypes= new HashSet(); + for (int i = 0; i < names.length; i++) { + IType memberType; + if (names[i].indexOf('.') != -1) { + String[] path= names[i].split("\\."); + memberType= type.getType(path[0]); + for (int j= 1; j < path.length; j++) { + memberType= memberType.getType(path[j]); + } + } else + memberType= type.getType(names[i]); + assertTrue("member type " + memberType.getElementName() + " does not exist", memberType.exists()); + memberTypes.add(memberType); + } + return (IType[]) memberTypes.toArray(new IType[memberTypes.size()]); + } + + public static IMethod[] getMethods(IType type, String[] names, String[][] signatures) { + if (names == null || signatures == null) + return new IMethod[0]; + List methods= new ArrayList(names.length); + for (int i = 0; i < names.length; i++) { + IMethod method= type.getMethod(names[i], signatures[i]); + assertTrue("method " + method.getElementName() + " does not exist", method.exists()); + if (!methods.contains(method)) + methods.add(method); + } + return (IMethod[]) methods.toArray(new IMethod[methods.size()]); + } + + public static IType[] findTypes(IType[] types, String[] namesOfTypesToPullUp) { + List found= new ArrayList(types.length); + for (int i= 0; i < types.length; i++) { + IType type= types[i]; + for (int j= 0; j < namesOfTypesToPullUp.length; j++) { + String name= namesOfTypesToPullUp[j]; + if (type.getElementName().equals(name)) + found.add(type); + } + } + return (IType[]) found.toArray(new IType[found.size()]); + } + + public static IField[] findFields(IField[] fields, String[] namesOfFieldsToPullUp) { + List found= new ArrayList(fields.length); + for (int i= 0; i < fields.length; i++) { + IField field= fields[i]; + for (int j= 0; j < namesOfFieldsToPullUp.length; j++) { + String name= namesOfFieldsToPullUp[j]; + if (field.getElementName().equals(name)) + found.add(field); + } + } + return (IField[]) found.toArray(new IField[found.size()]); + } + + public static IMethod[] findMethods(IMethod[] selectedMethods, String[] namesOfMethods, String[][] signaturesOfMethods){ + List found= new ArrayList(selectedMethods.length); + for (int i= 0; i < selectedMethods.length; i++) { + IMethod method= selectedMethods[i]; + String[] paramTypes= method.getParameterTypes(); + for (int j= 0; j < namesOfMethods.length; j++) { + String methodName= namesOfMethods[j]; + if (! methodName.equals(method.getElementName())) + continue; + String[] methodSig= signaturesOfMethods[j]; + if (! areSameSignatures(paramTypes, methodSig)) + continue; + found.add(method); + } + } + return (IMethod[]) found.toArray(new IMethod[found.size()]); + } + + private static boolean areSameSignatures(String[] s1, String[] s2){ + if (s1.length != s2.length) + return false; + for (int i= 0; i < s1.length; i++) { + if (! s1[i].equals(s2[i])) + return false; + } + return true; + } + + /** + * Line-based version of junit.framework.Assert.assertEquals(String, String) + * without considering line delimiters. + * @param expected the expected value + * @param actual the actual value + */ + public static void assertEqualLines(String expected, String actual) { + assertEqualLines("", expected, actual); + } + + /** + * Line-based version of junit.framework.Assert.assertEquals(String, String, String) + * without considering line delimiters. + * @param message the message + * @param expected the expected value + * @param actual the actual value + */ + public static void assertEqualLines(String message, String expected, String actual) { + String[] expectedLines= Strings.convertIntoLines(expected); + String[] actualLines= Strings.convertIntoLines(actual); + + String expected2= (expectedLines == null ? null : Strings.concatenate(expectedLines, "\n")); + String actual2= (actualLines == null ? null : Strings.concatenate(actualLines, "\n")); + assertEquals(message, expected2, actual2); + } + + private static class Requestor extends TypeNameRequestor { + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTestSetup.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTestSetup.java new file mode 100644 index 000000000..b5337b8e7 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTestSetup.java @@ -0,0 +1,101 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Technical University Berlin - adapted for Object Teams + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +import org.eclipse.jdt.ui.tests.refactoring.infra.AbstractRefactoringTestSetup; + +import org.eclipse.jdt.internal.ui.JavaPlugin; + +/** + * Sets up an 1.5 project with rtstubs15.jar and compiler, code formatting, code generation, and template options. + */ +public class RefactoringTestSetup extends AbstractRefactoringTestSetup { + + public RefactoringTestSetup(Test test) { + super(test); + } + + public static final String CONTAINER= "src"; + private static IPackageFragmentRoot fgRoot; + private static IPackageFragment fgPackageP; + private static IJavaProject fgJavaTestProject; + private static IPackageFragmentRoot fgJRELibrary; + + public static IPackageFragmentRoot getDefaultSourceFolder() throws Exception { + if (fgRoot != null) + return fgRoot; + throw new Exception(RefactoringTestSetup.class.getName() + " not initialized"); + } + + public static IPackageFragmentRoot getJRELibrary() throws Exception { + if (fgJRELibrary != null) + return fgJRELibrary; + throw new Exception(RefactoringTestSetup.class.getName() + " not initialized"); + } + + public static IJavaProject getProject()throws Exception { + if (fgJavaTestProject != null) + return fgJavaTestProject; + throw new Exception(RefactoringTestSetup.class.getName() + " not initialized"); + } + + public static IPackageFragment getPackageP()throws Exception { + if (fgPackageP != null) + return fgPackageP; + throw new Exception(RefactoringTestSetup.class.getName() + " not initialized"); + } + + protected void setUp() throws Exception { + super.setUp(); + if (JavaPlugin.getActivePage() != null) + JavaPlugin.getActivePage().close(); // Closed perspective is NOT restored in tearDown()! + + if (fgJavaTestProject != null && fgJavaTestProject.exists()) { + int breakpointTarget= 0; breakpointTarget++; + } +//{ObjectTeams: hookable +/* orig: + fgJavaTestProject= JavaProjectHelper.createJavaProject("TestProject"+System.currentTimeMillis(), "bin"); + :giro */ + fgJavaTestProject= createJavaProject("TestProject"+System.currentTimeMillis(), "bin"); +// SH} + fgJRELibrary= addRTJar(fgJavaTestProject); + fgRoot= JavaProjectHelper.addSourceContainer(fgJavaTestProject, CONTAINER); + fgPackageP= fgRoot.createPackageFragment("p", true, null); + } + +//{ObjectTeams: hook + protected IJavaProject createJavaProject(String string, String string2) throws CoreException { + return JavaProjectHelper.createJavaProject("TestProject"+System.currentTimeMillis(), "bin"); + } +// SH} + + protected IPackageFragmentRoot addRTJar(IJavaProject project) throws CoreException { + return JavaProjectHelper.addRTJar(project); + } + + protected void tearDown() throws Exception { + JavaProjectHelper.delete(fgJavaTestProject); + super.tearDown(); + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameFieldTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameFieldTests.java new file mode 100644 index 000000000..b6eed1138 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameFieldTests.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class RenameFieldTests { + + private static final Class clazz= RenameFieldTests.class; + + public static Test suite() { + TestSuite suite= new TestSuite(clazz.getName()); + suite.addTest(RenameNonPrivateFieldTests.suite()); + suite.addTest(RenamePrivateFieldTests.suite()); + return suite; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameJavaProjectTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameJavaProjectTests.java new file mode 100644 index 000000000..94617a2f0 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameJavaProjectTests.java @@ -0,0 +1,222 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.Path; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.RenameArguments; +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.IAccessRule; +import org.eclipse.jdt.core.IClasspathAttribute; +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; + +public class RenameJavaProjectTests extends RefactoringTest { + + private static final Class clazz= RenameJavaProjectTests.class; + + public RenameJavaProjectTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + protected void setUp() throws Exception { + super.setUp(); + fIsPreDeltaTest= true; + } + + public void test0() throws Exception { + IJavaProject p1= null; + IJavaProject referencing1= null; + IJavaProject referencing2= null; + try { + ParticipantTesting.reset(); + String newProjectName= "newName"; + p1= JavaProjectHelper.createJavaProject("p1", "bin"); + referencing1= JavaProjectHelper.createJavaProject("p2", "bin"); + referencing2= JavaProjectHelper.createJavaProject("p3", "bin"); + + JavaProjectHelper.addRTJar(referencing1); + JavaProjectHelper.addRequiredProject(referencing1, p1); + JavaProjectHelper.addSourceContainer(referencing1, "src"); + + JavaProjectHelper.addRTJar(referencing2); + JavaProjectHelper.addRequiredProject(referencing2, p1); + JavaProjectHelper.addSourceContainer(referencing2, "src"); + + JavaProjectHelper.addRTJar(p1); + + ParticipantTesting.reset(); + String[] handles= ParticipantTesting.createHandles(p1, p1.getResource()); + + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_JAVA_PROJECT); + descriptor.setJavaElement(p1); + descriptor.setUpdateReferences(true); + descriptor.setNewName(newProjectName); + + RenameRefactoring ref= (RenameRefactoring) createRefactoring(descriptor); + assertTrue(ref.isApplicable()); + + RefactoringStatus result= performRefactoring(ref); + + assertEquals("not expected to fail", null, result); + assertTrue("p1 is gone", !p1.exists()); + + ParticipantTesting.testRename(handles, + new RenameArguments[] { + new RenameArguments(newProjectName, true), + new RenameArguments(newProjectName, true)}); + + p1= referencing1.getJavaModel().getJavaProject(newProjectName); + assertTrue("p1 exists", p1.exists()); + + //check entries in referencing1 + IClasspathEntry[] entries= referencing1.getRawClasspath(); + assertEquals("expected entries", 3, entries.length); + for (int i= 0; i < entries.length; i++) { + IClasspathEntry iClassPathEntry= entries[i]; + if (i == 1) { + assertEquals("expected entry name", p1.getProject().getFullPath(), iClassPathEntry.getPath()); + assertEquals("expected entry kind", IClasspathEntry.CPE_PROJECT, iClassPathEntry.getEntryKind()); + } + } + + //check entries in referencing2 + entries= referencing2.getRawClasspath(); + assertEquals("expected entries", 3, entries.length); + for (int i= 0; i < entries.length; i++) { + IClasspathEntry iClassPathEntry= entries[i]; + if (i == 1) { + assertEquals("expected entry name", p1.getProject().getFullPath(), iClassPathEntry.getPath()); + assertEquals("expected entry kind", IClasspathEntry.CPE_PROJECT, iClassPathEntry.getEntryKind()); + } + } + + } finally { + performDummySearch(); + + if (referencing1 != null && referencing1.exists()) + JavaProjectHelper.removeSourceContainer(referencing1, "src"); + if (referencing2 != null && referencing2.exists()) + JavaProjectHelper.removeSourceContainer(referencing2, "src"); + + if (p1 != null && p1.exists()) + JavaProjectHelper.delete(p1); + if (referencing1 != null && referencing1.exists()) + JavaProjectHelper.delete(referencing1); + if (referencing2 != null && referencing2.exists()) + JavaProjectHelper.delete(referencing2); + } + } + + public void test1() throws Exception { + IJavaProject p1= null; + IJavaProject referencing1= null; + IJavaProject referencing2= null; + try { + ParticipantTesting.reset(); + String newProjectName= "newName"; + p1= JavaProjectHelper.createJavaProject("p1", "bin"); + referencing1= JavaProjectHelper.createJavaProject("p2", "bin"); + referencing2= JavaProjectHelper.createJavaProject("p3", "bin"); + + JavaProjectHelper.addRTJar(referencing1); + IClasspathEntry cpe1= JavaCore.newProjectEntry(p1.getProject().getFullPath(), true); + JavaProjectHelper.addToClasspath(referencing1, cpe1); + JavaProjectHelper.addSourceContainer(referencing1, "src"); + + JavaProjectHelper.addRTJar(referencing2); + IAccessRule[] accessRules2= new IAccessRule[] { + JavaCore.newAccessRule(new Path("accessible"), IAccessRule.K_ACCESSIBLE) + }; + IClasspathAttribute[] extraAttributes2= new IClasspathAttribute[] { + JavaCore.newClasspathAttribute("myTestAttribute", "val") + }; + IClasspathEntry cpe2= JavaCore.newProjectEntry(p1.getProject().getFullPath(), accessRules2, true, extraAttributes2, false); + JavaProjectHelper.addToClasspath(referencing2, cpe2); + JavaProjectHelper.addSourceContainer(referencing2, "src"); + + JavaProjectHelper.addRTJar(p1); + + ParticipantTesting.reset(); + String[] handles= ParticipantTesting.createHandles(p1, p1.getResource()); + + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_JAVA_PROJECT); + descriptor.setJavaElement(p1); + descriptor.setUpdateReferences(true); + descriptor.setNewName(newProjectName); + + RenameRefactoring ref= (RenameRefactoring) createRefactoring(descriptor); + assertTrue(ref.isApplicable()); + + RefactoringStatus result= performRefactoring(ref); + + assertEquals("not expected to fail", null, result); + assertTrue("p1 is gone", !p1.exists()); + + ParticipantTesting.testRename(handles, + new RenameArguments[] { + new RenameArguments(newProjectName, true), + new RenameArguments(newProjectName, true)}); + + p1= referencing1.getJavaModel().getJavaProject(newProjectName); + assertTrue("p1 exists", p1.exists()); + + //check entries in referencing1 + IClasspathEntry[] entries= referencing1.getRawClasspath(); + assertEquals("expected entries", 3, entries.length); + IClasspathEntry iClassPathEntry= entries[1]; + assertEquals("expected entry name", p1.getProject().getFullPath(), iClassPathEntry.getPath()); + assertEquals("expected entry kind", IClasspathEntry.CPE_PROJECT, iClassPathEntry.getEntryKind()); + assertEquals("expected entry isExported", true, iClassPathEntry.isExported()); + assertEquals("expected entry combineAccessRules", true, iClassPathEntry.combineAccessRules()); + assertEquals("expected entry accessRules count", 0, iClassPathEntry.getAccessRules().length); + assertEquals("expected entry accessRules getExtraAttributes", 0, iClassPathEntry.getExtraAttributes().length); + + //check entries in referencing2 + entries= referencing2.getRawClasspath(); + assertEquals("expected entries", 3, entries.length); + iClassPathEntry= entries[1]; + assertEquals("expected entry name", p1.getProject().getFullPath(), iClassPathEntry.getPath()); + assertEquals("expected entry kind", IClasspathEntry.CPE_PROJECT, iClassPathEntry.getEntryKind()); + assertEquals("expected entry isExported", false, iClassPathEntry.isExported()); + assertEquals("expected entry combineAccessRules", true, iClassPathEntry.combineAccessRules()); + assertEquals("expected entry accessRules count", accessRules2.length, iClassPathEntry.getAccessRules().length); + assertEquals("expected entry accessRules getExtraAttributes", extraAttributes2.length, iClassPathEntry.getExtraAttributes().length); + + } finally { + performDummySearch(); + + if (p1 != null && p1.exists()) + JavaProjectHelper.delete(p1); + if (referencing1 != null && referencing1.exists()) + JavaProjectHelper.delete(referencing1); + if (referencing2 != null && referencing2.exists()) + JavaProjectHelper.delete(referencing2); + } + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameMethodInInterfaceTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameMethodInInterfaceTests.java new file mode 100644 index 000000000..42cdd6113 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameMethodInInterfaceTests.java @@ -0,0 +1,455 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.RenameProcessor; +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.Signature; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; +import org.eclipse.jdt.internal.corext.refactoring.rename.RenameVirtualMethodProcessor; + +public class RenameMethodInInterfaceTests extends RefactoringTest { + + private static final Class clazz= RenameMethodInInterfaceTests.class; + private static final String REFACTORING_PATH= "RenameMethodInInterface/"; + private static final String[] NO_ARGUMENTS= new String[0]; + + public RenameMethodInInterfaceTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + private void helper1_not_available(String methodName, String[] signatures) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType interfaceI= getType(cu, "I"); + + RenameProcessor processor= new RenameVirtualMethodProcessor(interfaceI.getMethod(methodName, signatures)); + RenameRefactoring ref= new RenameRefactoring(processor); + assertTrue(! ref.isApplicable()); + } + private void helper1_0(String methodName, String newMethodName, String[] signatures) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType interfaceI= getType(cu, "I"); + IMethod method= interfaceI.getMethod(methodName, signatures); + + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_METHOD); + descriptor.setJavaElement(method); + descriptor.setUpdateReferences(true); + descriptor.setNewName(newMethodName); + + RefactoringStatus result= performRefactoring(descriptor); + assertNotNull("precondition was supposed to fail", result); + } + + private void helper1() throws Exception{ + helper1_0("m", "k", NO_ARGUMENTS); + } + + private void helper2_0(String methodName, String newMethodName, String[] signatures, boolean shouldPass, boolean updateReferences, boolean createDelegate) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType interfaceI= getType(cu, "I"); + IMethod method= interfaceI.getMethod(methodName, signatures); + + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_METHOD); + descriptor.setJavaElement(method); + descriptor.setUpdateReferences(updateReferences); + descriptor.setNewName(newMethodName); + descriptor.setKeepOriginal(createDelegate); + descriptor.setDeprecateDelegate(true); + + assertEquals("was supposed to pass", null, performRefactoring(descriptor)); + if (!shouldPass){ + assertTrue("incorrect renaming because of a java model bug", ! getFileContents(getOutputTestFileName("A")).equals(cu.getSource())); + return; + } + assertEqualLines("incorrect renaming", getFileContents(getOutputTestFileName("A")), cu.getSource()); + + assertTrue("anythingToUndo", RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("! anythingToRedo", !RefactoringCore.getUndoManager().anythingToRedo()); + //assertEquals("1 to undo", 1, Refactoring.getUndoManager().getRefactoringLog().size()); + + RefactoringCore.getUndoManager().performUndo(null, new NullProgressMonitor()); + assertEqualLines("invalid undo", getFileContents(getInputTestFileName("A")), cu.getSource()); + + assertTrue("! anythingToUndo", !RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("anythingToRedo", RefactoringCore.getUndoManager().anythingToRedo()); + //assertEquals("1 to redo", 1, Refactoring.getUndoManager().getRedoStack().size()); + + RefactoringCore.getUndoManager().performRedo(null, new NullProgressMonitor()); + assertEqualLines("invalid redo", getFileContents(getOutputTestFileName("A")), cu.getSource()); + } + + private void helper2(boolean updateReferences) throws Exception{ + helper2_0("m", "k", NO_ARGUMENTS, true, updateReferences, false); + } + + private void helper2() throws Exception{ + helper2(true); + } + + private void helperDelegate() throws Exception{ + helper2_0("m", "k", NO_ARGUMENTS, true, true, true); + } + +// -------------------------------------------------------------------------- + + public void testAnnotation0() throws Exception{ + helper2_0("name", "ident", NO_ARGUMENTS, true, true, false); + } + + public void testAnnotation1() throws Exception{ + helper2_0("value", "number", NO_ARGUMENTS, true, true, false); + } + + public void testAnnotation2() throws Exception{ + helper2_0("thing", "value", NO_ARGUMENTS, true, true, false); + } + + public void testAnnotation3() throws Exception{ + helper2_0("value", "num", NO_ARGUMENTS, true, true, false); + } + + public void testAnnotation4() throws Exception{ + // see also bug 83064 + helper2_0("value", "num", NO_ARGUMENTS, true, true, false); + } + + public void testGenerics01() throws Exception { + helper2_0("getXYZ", "zYXteg", new String[] {"QList<QSet<QRunnable;>;>;"}, true, true, false); + } + + public void testFail0() throws Exception{ + helper1(); + } + public void testFail1() throws Exception{ + helper1(); + } + public void testFail3() throws Exception{ + helper1(); + } + public void testFail4() throws Exception{ + helper1(); + } + public void testFail5() throws Exception{ + helper1(); + } + public void testFail6() throws Exception{ + helper1(); + } + public void testFail7() throws Exception{ + helper1(); + } + public void testFail8() throws Exception{ + helper1_0("m", "k", new String[]{Signature.SIG_INT}); + } + public void testFail9() throws Exception{ + helper1(); + } + public void testFail10() throws Exception{ + helper1(); + } + public void testFail11() throws Exception{ + helper1(); + } + public void testFail12() throws Exception{ + helper1(); + } + public void testFail13() throws Exception{ + helper1(); + } + public void testFail14() throws Exception{ + helper1(); + } + public void testFail15() throws Exception{ + helper1(); + } + public void testFail16() throws Exception{ + helper1(); + } + public void testFail17() throws Exception{ + helper1(); + } + public void testFail18() throws Exception{ + helper1(); + } + public void testFail19() throws Exception{ + helper1(); + } + public void testFail20() throws Exception{ + helper1(); + } + public void testFail21() throws Exception{ + helper1_0("m", "k", new String[]{"QString;"}); + } + public void testFail22() throws Exception{ + helper1_0("m", "k", new String[]{"QObject;"}); + } + public void testFail23() throws Exception{ + helper1_not_available("toString", NO_ARGUMENTS); + } + public void testFail24() throws Exception{ + helper1(); + } + public void testFail25() throws Exception{ + helper1(); + } + public void testFail26() throws Exception{ + helper1(); + } + public void testFail27() throws Exception{ + helper1(); + } + public void testFail28() throws Exception{ + helper1(); + } + public void testFail29() throws Exception{ + helper1(); + } + + public void testFail30() throws Exception{ + helper1_not_available("toString", NO_ARGUMENTS); + } + + public void testFail31() throws Exception{ + helper1_not_available("toString", NO_ARGUMENTS); + } + + public void testFail32() throws Exception{ + helper1_0("m", "toString", NO_ARGUMENTS); + } + + public void testFail33() throws Exception{ + helper1_0("m", "toString", NO_ARGUMENTS); + } + + public void testFail34() throws Exception{ + helper1_0("m", "equals", new String[]{"QObject;"}); + } + + public void testFail35() throws Exception{ + helper1_0("m", "equals", new String[]{"Qjava.lang.Object;"}); + } + + public void testFail36() throws Exception{ + helper1_0("m", "getClass", NO_ARGUMENTS); + } + + public void testFail37() throws Exception{ + helper1_0("m", "hashCode", NO_ARGUMENTS); + } + + public void testFail38() throws Exception{ + helper1_0("m", "notify", NO_ARGUMENTS); + } + + public void testFail39() throws Exception{ + helper1_0("m", "notifyAll", NO_ARGUMENTS); + } + + public void testFail40() throws Exception{ + helper1_0("m", "wait", new String[]{Signature.SIG_LONG, Signature.SIG_INT}); + } + + public void testFail41() throws Exception{ + helper1_0("m", "wait", new String[]{Signature.SIG_LONG}); + } + + public void testFail42() throws Exception{ + helper1_0("m", "wait", NO_ARGUMENTS); + } + + public void testFail43() throws Exception{ + helper1_0("m", "wait", NO_ARGUMENTS); + } + + + public void test0() throws Exception{ + helper2(); + } + public void test1() throws Exception{ + helper2(); + } + public void test2() throws Exception{ + helper2(); + } + public void test3() throws Exception{ + helper2(); + } + public void test4() throws Exception{ + helper2(); + } + public void test5() throws Exception{ + helper2(); + } + public void test6() throws Exception{ + helper2(); + } + public void test7() throws Exception{ + helper2(); + } + public void test10() throws Exception{ + helper2(); + } + public void test11() throws Exception{ + helper2(); + } + public void test12() throws Exception{ + helper2(); + } + + //test13 became testFail45 + //public void test13() throws Exception{ + // helper2(); + //} + public void test14() throws Exception{ + helper2(); + } + public void test15() throws Exception{ + helper2(); + } + public void test16() throws Exception{ + helper2(); + } + public void test17() throws Exception{ + helper2(); + } + public void test18() throws Exception{ + helper2(); + } + public void test19() throws Exception{ + helper2(); + } + public void test20() throws Exception{ + helper2(); + } + //anonymous inner class + public void test21() throws Exception{ + printTestDisabledMessage("must fix - incorrect warnings"); + //helper2_fail(); + } + public void test22() throws Exception{ + helper2(); + } + + //test23 became testFail45 + //public void test23() throws Exception{ + // helper2(); + //} + + public void test24() throws Exception{ + helper2(); + } + public void test25() throws Exception{ + helper2(); + } + public void test26() throws Exception{ + helper2(); + } + public void test27() throws Exception{ + helper2(); + } + public void test28() throws Exception{ + helper2(); + } + public void test29() throws Exception{ + helper2(); + } + public void test30() throws Exception{ + helper2(); + } + //anonymous inner class + public void test31() throws Exception{ + helper2(); + } + //anonymous inner class + public void test32() throws Exception{ + helper2(); + } + public void test33() throws Exception{ + helper2(); + } + public void test34() throws Exception{ + helper2(); + } + public void test35() throws Exception{ + helper2(); + } + public void test36() throws Exception{ + helper2(); + } + public void test37() throws Exception{ + helper2(); + } + public void test38() throws Exception{ + helper2(); + } + public void test39() throws Exception{ + helper2(); + } + public void test40() throws Exception{ + helper2(); + } + public void test41() throws Exception{ + helper2(); + } + public void test42() throws Exception{ + helper2(); + } + public void test43() throws Exception{ + helper2(); + } + public void test44() throws Exception{ + helper2(); + } + public void test45() throws Exception{ + helper2(); + } + public void test46() throws Exception{ + helper2(false); + } + public void test47() throws Exception{ + helper2(); + } + + public void testDelegate01() throws Exception { + // simple delegate + helperDelegate(); + } + public void testDelegate02() throws Exception { + // "overridden" delegate + helperDelegate(); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameMethodTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameMethodTests.java new file mode 100644 index 000000000..63068f771 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameMethodTests.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class RenameMethodTests { + private static final Class clazz= RenameMethodTests.class; + + public static Test suite() { + TestSuite suite= new TestSuite(clazz.getName()); + suite.addTest(RenameVirtualMethodInClassTests.suite()); + suite.addTest(RenameMethodInInterfaceTests.suite()); + suite.addTest(RenamePrivateMethodTests.suite()); + suite.addTest(RenameStaticMethodTests.suite()); + suite.addTest(RippleMethodFinderTests.suite()); + return suite; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameNonPrivateFieldTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameNonPrivateFieldTests.java new file mode 100644 index 000000000..31d2f305b --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameNonPrivateFieldTests.java @@ -0,0 +1,498 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; + +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.RenameArguments; +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; +import org.eclipse.jdt.internal.corext.refactoring.rename.RenameFieldProcessor; +import org.eclipse.jdt.internal.corext.util.JdtFlags; + +public class RenameNonPrivateFieldTests extends RefactoringTest{ + + private static final Class clazz= RenameNonPrivateFieldTests.class; + private static final String REFACTORING_PATH= "RenameNonPrivateField/"; + + private static final boolean BUG_79990_CORE_SEARCH_METHOD_DECL= true; + + private Object fPrefixPref; + + //Test methods can configure these fields: + private boolean fUpdateReferences= true; + private boolean fUpdateTextualMatches= false; + private boolean fRenameGetter= false; + private boolean fRenameSetter= false; + + + public RenameNonPrivateFieldTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + protected void setUp() throws Exception { + super.setUp(); + Hashtable options= JavaCore.getOptions(); + fPrefixPref= options.get(JavaCore.CODEASSIST_FIELD_PREFIXES); + options.put(JavaCore.CODEASSIST_FIELD_PREFIXES, getPrefixes()); + JavaCore.setOptions(options); + fIsPreDeltaTest= true; + } + + protected void tearDown() throws Exception { + super.tearDown(); + Hashtable options= JavaCore.getOptions(); + options.put(JavaCore.CODEASSIST_FIELD_PREFIXES, fPrefixPref); + JavaCore.setOptions(options); + } + + private String getPrefixes(){ + return ""; + } + + private void helper1_0(String fieldName, String newFieldName) throws Exception{ + IType classA= getType(createCUfromTestFile(getPackageP(), "A"), "A"); + IField field= classA.getField(fieldName); + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_FIELD); + descriptor.setJavaElement(field); + descriptor.setUpdateReferences(true); + descriptor.setNewName(newFieldName); + RefactoringStatus result= performRefactoring(descriptor); + assertNotNull("precondition was supposed to fail", result); + } + + private void helper1() throws Exception{ + helper1_0("f", "g"); + } + + /** + * Configure options by setting instance fields to non-default values. + * @param fieldName + * @param newFieldName + * @throws Exception + */ + private void helper2(String fieldName, String newFieldName) throws Exception{ + helper2(fieldName, newFieldName, false); + } + + private void helper2(String fieldName, String newFieldName, boolean createDelegates) throws Exception{ + ParticipantTesting.reset(); + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType classA= getType(cu, "A"); + IField field= classA.getField(fieldName); + boolean isEnum= JdtFlags.isEnum(field); + String id= isEnum ? IJavaRefactorings.RENAME_ENUM_CONSTANT : IJavaRefactorings.RENAME_FIELD; + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(id); + descriptor.setJavaElement(field); + descriptor.setNewName(newFieldName); + descriptor.setUpdateReferences(fUpdateReferences); + descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches); + if (!isEnum) { + descriptor.setRenameGetters(fRenameGetter); + descriptor.setRenameSetters(fRenameSetter); + descriptor.setKeepOriginal(createDelegates); + descriptor.setDeprecateDelegate(true); + } + RenameRefactoring refactoring= (RenameRefactoring) createRefactoring(descriptor); + RenameFieldProcessor processor= (RenameFieldProcessor) refactoring.getProcessor(); + + int numbers= 1; + List elements= new ArrayList(); + elements.add(field); + List args= new ArrayList(); + args.add(new RenameArguments(newFieldName, fUpdateReferences)); + if (fRenameGetter) { + elements.add(processor.getGetter()); + args.add(new RenameArguments(processor.getNewGetterName(), fUpdateReferences)); + numbers++; + } + if (fRenameSetter) { + elements.add(processor.getSetter()); + args.add(new RenameArguments(processor.getNewSetterName(), fUpdateReferences)); + numbers++; + } + String[] renameHandles= ParticipantTesting.createHandles(elements.toArray()); + + RefactoringStatus result= performRefactoring(refactoring); + assertEquals("was supposed to pass", null, result); + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName("A")), cu.getSource()); + + ParticipantTesting.testRename( + renameHandles, + (RenameArguments[]) args.toArray(new RenameArguments[args.size()])); + + assertTrue("anythingToUndo", RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("! anythingToRedo", !RefactoringCore.getUndoManager().anythingToRedo()); + + RefactoringCore.getUndoManager().performUndo(null, new NullProgressMonitor()); + assertEqualLines("invalid undo", getFileContents(getInputTestFileName("A")), cu.getSource()); + + assertTrue("! anythingToUndo", !RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("anythingToRedo", RefactoringCore.getUndoManager().anythingToRedo()); + + RefactoringCore.getUndoManager().performRedo(null, new NullProgressMonitor()); + assertEqualLines("invalid redo", getFileContents(getOutputTestFileName("A")), cu.getSource()); + } + + private void helper2() throws Exception{ + helper2("f", "g"); + } + + //--------- tests ---------- + public void testFail0() throws Exception{ + helper1(); + } + + public void testFail1() throws Exception{ + helper1(); + } + + public void testFail2() throws Exception{ + helper1(); + } + + public void testFail3() throws Exception{ + helper1(); + } + + public void testFail4() throws Exception{ + helper1(); + } + + public void testFail5() throws Exception{ + helper1(); + } + + public void testFail6() throws Exception{ + helper1(); + } + + public void testFail7() throws Exception{ + helper1(); + } + + public void testFail8() throws Exception{ + helper1(); + } + + public void testFail9() throws Exception{ + helper1(); + } + + public void testFail10() throws Exception{ + helper1(); + } + + public void testFail11() throws Exception{ + helper1(); + } + + public void testFail12() throws Exception{ + helper1(); + } + + public void testFail13() throws Exception{ + //printTestDisabledMessage("1GKZ8J6: ITPJCORE:WIN2000 - search: missing field occurrecnces"); + helper1(); + } + + public void testFail14() throws Exception{ + //printTestDisabledMessage("1GKZ8J6: ITPJCORE:WIN2000 - search: missing field occurrecnces"); + helper1(); + } + + // ------ + public void test0() throws Exception{ + helper2(); + } + + public void test1() throws Exception{ + helper2(); + } + + public void test2() throws Exception{ + helper2(); + } + + public void test3() throws Exception{ + helper2(); + } + + public void test4() throws Exception{ + helper2(); + //printTestDisabledMessage("1GKZ8J6: ITPJCORE:WIN2000 - search: missing field occurrecnces"); + } + + public void test5() throws Exception{ + helper2(); + } + + public void test6() throws Exception{ + //printTestDisabledMessage("1GKB9YH: ITPJCORE:WIN2000 - search for field refs - incorrect results"); + helper2(); + } + + public void test7() throws Exception{ + helper2(); + } + + public void test8() throws Exception{ + //printTestDisabledMessage("1GD79XM: ITPJCORE:WINNT - Search - search for field references - not all found"); + helper2(); + } + + public void test9() throws Exception{ + helper2(); + } + + public void test10() throws Exception{ + helper2(); + } + + public void test11() throws Exception{ + helper2(); + } + + public void test12() throws Exception{ + //System.out.println("\nRenameNonPrivateField::" + name() + " disabled (1GIHUQP: ITPJCORE:WINNT - search for static field should be more accurate)"); + helper2(); + } + + public void test13() throws Exception{ + //System.out.println("\nRenameNonPrivateField::" + name() + " disabled (1GIHUQP: ITPJCORE:WINNT - search for static field should be more accurate)"); + helper2(); + } + + public void test14() throws Exception{ + fUpdateReferences= false; + fUpdateTextualMatches= false; + helper2(); + } + + public void test15() throws Exception{ + fUpdateReferences= false; + fUpdateTextualMatches= false; + helper2(); + } + + public void test16() throws Exception{ +// printTestDisabledMessage("text for bug 20693"); + helper2(); + } + + public void test17() throws Exception{ +// printTestDisabledMessage("test for bug 66250, 79131 (corner case: reference "A.f" to p.A#f)"); + fUpdateReferences= false; + fUpdateTextualMatches= true; + helper2("f", "g"); + } + + public void test18() throws Exception{ +// printTestDisabledMessage("test for 79131 (corner case: reference "A.f" to p.A#f)"); + fUpdateReferences= false; + fUpdateTextualMatches= true; + helper2("field", "member"); + } + +//--- test 1.5 features: --- + public void test19() throws Exception{ + fRenameGetter= true; + fRenameSetter= true; + helper2("list", "items"); + } + + public void test20() throws Exception{ + helper2("list", "items"); + } + + public void test21() throws Exception{ + helper2("fValue", "fOrdinal"); + } + + public void test22() throws Exception{ + fRenameGetter= true; + fRenameSetter= true; + helper2("tee", "thing"); + } + + public void test23() throws Exception{ + fRenameGetter= true; + fRenameSetter= true; + helper2(); + } + +//--- end test 1.5 features. --- + + public void testBug5821() throws Exception{ + helper2("test", "test1"); + } + + public void testStaticImport() throws Exception{ + //bug 77622 + IPackageFragment test1= getRoot().createPackageFragment("test1", true, null); + ICompilationUnit cuC= null; + try { + ICompilationUnit cuB= createCUfromTestFile(test1, "B"); + cuC= createCUfromTestFile(getRoot().getPackageFragment(""), "C"); + + helper2("PI", "e"); + + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName("B")), cuB.getSource()); + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName("C")), cuC.getSource()); + } finally { + if (test1.exists()) + test1.delete(true, null); + if (cuC != null && cuC.exists()) + cuC.delete(true, null); + } + } + + public void testEnumConst() throws Exception { + //bug 77619 + IPackageFragment test1= getRoot().createPackageFragment("test1", true, null); + ICompilationUnit cuC= null; + try { + ICompilationUnit cuB= createCUfromTestFile(test1, "B"); + cuC= createCUfromTestFile(getRoot().getPackageFragment(""), "C"); + + helper2("RED", "REDDISH"); + + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName("B")), cuB.getSource()); + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName("C")), cuC.getSource()); + } finally { + if (test1.exists()) + test1.delete(true, null); + if (cuC != null && cuC.exists()) + cuC.delete(true, null); + } + + } + + public void testGenerics1() throws Exception { + helper2(); + } + + public void testGenerics2() throws Exception { + fRenameSetter= true; + fRenameGetter= true; + helper2(); + } + + public void testGenerics3() throws Exception { + if (BUG_79990_CORE_SEARCH_METHOD_DECL) { + printTestDisabledMessage("BUG_79990_CORE_SEARCH_METHOD_DECL"); + return; + } + fRenameSetter= true; + fRenameGetter= true; + helper2(); + } + + public void testGenerics4() throws Exception { + fRenameSetter= true; + fRenameGetter= true; + helper2("count", "number"); + } + + public void testEnumField() throws Exception { + fRenameSetter= true; + fRenameGetter= true; + helper2("buddy", "other"); + } + + public void testAnnotation1() throws Exception { + helper2("ZERO", "ZORRO"); + } + + public void testAnnotation2() throws Exception { + helper2("ZERO", "ZORRO"); + } + + public void testDelegate01() throws Exception { + // a simple delegate + helper2("f", "g", true); + } + + public void testDelegate02() throws Exception { + // nonstatic field, getter and setter + fRenameSetter= true; + fRenameGetter= true; + helper2("f", "g", true); + } + + public void testDelegate03() throws Exception { + // create delegates for the field and a getter + fRenameGetter= true; + helper2("f", "g", true); + } + + public void testRenameNLSAccessor01() throws Exception { + IFile file= createPropertiesFromTestFile("messages"); + + helper2("f", "g"); + + assertEqualLines(getExpectedFileConent("messages"), getContents(file)); + } + + private String getExpectedFileConent(String propertyName) throws IOException { + String fileName= getOutputTestFileName(propertyName); + fileName= fileName.substring(0, fileName.length() - ".java".length()) + ".properties"; + return getContents(getFileInputStream(fileName)); + } + + private IFile createPropertiesFromTestFile(String propertyName) throws IOException, CoreException { + IFolder pack= (IFolder) getPackageP().getResource(); + IFile file= pack.getFile(propertyName + ".properties"); + + String fileName= getInputTestFileName(propertyName); + fileName= fileName.substring(0, fileName.length() - ".java".length()) + ".properties"; + InputStream inputStream= getFileInputStream(fileName); + file.create(inputStream, true, null); + + return file; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenamePackageTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenamePackageTests.java new file mode 100644 index 000000000..31961fed0 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenamePackageTests.java @@ -0,0 +1,1458 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipInputStream; + +import junit.framework.Assert; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.JavaTestPlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Path; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourceAttributes; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.CheckConditionsOperation; +import org.eclipse.ltk.core.refactoring.CreateChangeOperation; +import org.eclipse.ltk.core.refactoring.IResourceMapper; +import org.eclipse.ltk.core.refactoring.IUndoManager; +import org.eclipse.ltk.core.refactoring.PerformChangeOperation; +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry; +import org.eclipse.ltk.core.refactoring.participants.MoveArguments; +import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring; +import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor; +import org.eclipse.ltk.core.refactoring.participants.RenameArguments; +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaModel; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.refactoring.IJavaElementMapper; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; +import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatusCodes; +import org.eclipse.jdt.internal.corext.refactoring.rename.RenamePackageProcessor; +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; + +import org.eclipse.jdt.ui.tests.refactoring.infra.DebugUtils; +import org.eclipse.jdt.ui.tests.refactoring.infra.ZipTools; + +import org.eclipse.jdt.internal.ui.util.CoreUtility; + + +public class RenamePackageTests extends RefactoringTest { + private static final boolean BUG_6054= false; + private static final boolean BUG_54962_71267= false; + + private static final Class clazz= RenamePackageTests.class; + private static final String REFACTORING_PATH= "RenamePackage/"; + + private boolean fUpdateReferences; + private boolean fUpdateTextualMatches; + private String fQualifiedNamesFilePatterns; + private boolean fRenameSubpackages; + + public RenamePackageTests(String name) { + super(name); + } + + public static Test suite() { + return new Java15Setup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new Java15Setup(someTest); + } + +// public void run(TestResult result) { +// System.out.println("--- " + getName() + " - RenamePackageTests ---"); +// super.run(result); +// } + + protected void setUp() throws Exception { + super.setUp(); + fUpdateReferences= true; + fUpdateTextualMatches= false; + fQualifiedNamesFilePatterns= null; + fRenameSubpackages= false; + // fIsPreDeltaTest= true; + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + // ------------- + private RenameJavaElementDescriptor createRefactoringDescriptor(IPackageFragment pack, String newName) { + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_PACKAGE); + descriptor.setJavaElement(pack); + descriptor.setNewName(newName); + descriptor.setUpdateReferences(true); + return descriptor; + } + + /* non java-doc + * the 0th one is the one to rename + */ + private void helper1(String packageNames[], String[][] packageFiles, String newPackageName) throws Exception{ + try{ + IPackageFragment[] packages= new IPackageFragment[packageNames.length]; + for (int i= 0; i < packageFiles.length; i++){ + packages[i]= getRoot().createPackageFragment(packageNames[i], true, null); + for (int j= 0; j < packageFiles[i].length; j++){ + createCUfromTestFile(packages[i], packageFiles[i][j], packageNames[i].replace('.', '/') + "/"); + //DebugUtils.dump(cu.getElementName() + "\n" + cu.getSource()); + } + } + IPackageFragment thisPackage= packages[0]; + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(thisPackage, newPackageName)); + assertNotNull("precondition was supposed to fail", result); + if (fIsVerbose) + DebugUtils.dump("" + result); + } finally{ + performDummySearch(); + + for (int i= 0; i < packageNames.length; i++){ + IPackageFragment pack= getRoot().getPackageFragment(packageNames[i]); + if (pack.exists()) + pack.delete(true, null); + } + } + } + + private void helper1() throws Exception{ + helper1(new String[]{"r"}, new String[][]{{"A"}}, "p1"); + } + + private RenamePackageProcessor helper2(String[] packageNames, String[][] packageFileNames, String newPackageName) throws Exception{ + ParticipantTesting.reset(); + IPackageFragment[] packages= new IPackageFragment[packageNames.length]; + ICompilationUnit[][] cus= new ICompilationUnit[packageFileNames.length][packageFileNames[0].length]; + for (int i= 0; i < packageNames.length; i++){ + packages[i]= getRoot().createPackageFragment(packageNames[i], true, null); + for (int j= 0; j < packageFileNames[i].length; j++){ + cus[i][j]= createCUfromTestFile(packages[i], packageFileNames[i][j], packageNames[i].replace('.', '/') + "/"); + } + } + IPackageFragment thisPackage= packages[0]; + boolean hasSubpackages= thisPackage.hasSubpackages(); + + IPath path= thisPackage.getParent().getPath(); + path= path.append(newPackageName.replace('.', '/')); + IFolder target= ResourcesPlugin.getWorkspace().getRoot().getFolder(path); + boolean targetExists= target.exists(); + boolean isRename= !targetExists && !thisPackage.hasSubpackages() && thisPackage.getResource().getParent().equals(target.getParent()); + + String[] createHandles= null; + String[] moveHandles= null; + String[] deleteHandles= null; + boolean doDelete= true; + + String[] renameHandles= null; + if (isRename) { + renameHandles= ParticipantTesting.createHandles(thisPackage, thisPackage.getResource()); + } else { + renameHandles= ParticipantTesting.createHandles(thisPackage); + IContainer loop= target; + List handles= new ArrayList(); + while (loop != null && !loop.exists()) { + handles.add(ParticipantTesting.createHandles(loop)[0]); + loop= loop.getParent(); + } + createHandles= (String[]) handles.toArray(new String[handles.size()]); + IFolder source= (IFolder)thisPackage.getResource(); + deleteHandles= ParticipantTesting.createHandles(source); + IResource members[]= source.members(); + List movedObjects= new ArrayList(); + for (int i= 0; i < members.length; i++) { + if (members[i] instanceof IFolder) { + doDelete= false; + } else { + movedObjects.add(members[i]); + } + } + moveHandles= ParticipantTesting.createHandles(movedObjects.toArray()); + } + RenameJavaElementDescriptor descriptor= createRefactoringDescriptor(thisPackage, newPackageName); + descriptor.setUpdateReferences(fUpdateReferences); + descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches); + setFilePatterns(descriptor); + Refactoring refactoring= createRefactoring(descriptor); + RefactoringStatus result= performRefactoring(refactoring); + assertEquals("preconditions were supposed to pass", null, result); + + if (isRename) { + ParticipantTesting.testRename(renameHandles, + new RenameArguments[] { + new RenameArguments(newPackageName, fUpdateReferences), + new RenameArguments(target.getName(), fUpdateReferences) + } + ); + } else { + ParticipantTesting.testRename(renameHandles, + new RenameArguments[] { + new RenameArguments(newPackageName, fUpdateReferences)}); + + ParticipantTesting.testCreate(createHandles); + + List args= new ArrayList(); + for (int i= 0; i < packageFileNames[0].length; i++) { + args.add(new MoveArguments(target, fUpdateReferences)); + } + ParticipantTesting.testMove(moveHandles, (MoveArguments[]) args.toArray(new MoveArguments[args.size()])); + + if (doDelete) { + ParticipantTesting.testDelete(deleteHandles); + } else { + ParticipantTesting.testDelete(new String[0]); + } + } + + //--- + + if (hasSubpackages) { + assertTrue("old package does not exist anymore", getRoot().getPackageFragment(packageNames[0]).exists()); + } else { + assertTrue("package not renamed", ! getRoot().getPackageFragment(packageNames[0]).exists()); + } + IPackageFragment newPackage= getRoot().getPackageFragment(newPackageName); + assertTrue("new package does not exist", newPackage.exists()); + + for (int i= 0; i < packageFileNames.length; i++){ + String packageName= (i == 0) + ? newPackageName.replace('.', '/') + "/" + : packageNames[i].replace('.', '/') + "/"; + for (int j= 0; j < packageFileNames[i].length; j++){ + String s1= getFileContents(getOutputTestFileName(packageFileNames[i][j], packageName)); + ICompilationUnit cu= + (i == 0) + ? newPackage.getCompilationUnit(packageFileNames[i][j] + ".java") + : cus[i][j]; + //DebugUtils.dump("cu:" + cu.getElementName()); + String s2= cu.getSource(); + + //DebugUtils.dump("expected:" + s1); + //DebugUtils.dump("was:" + s2); + assertEqualLines("invalid update in file " + cu.getElementName(), s1, s2); + } + } + RefactoringProcessor processor= ((ProcessorBasedRefactoring) refactoring).getProcessor(); + return (RenamePackageProcessor) processor; + } + + class PackageRename { + String[] fPackageNames; + final String[][] fPackageFileNames; + final String fNewPackageName; + final boolean fTestWithDummyFiles; + + final IPackageFragment[] fPackages; + final ICompilationUnit[][] fCus; + + public PackageRename (String[] packageNames, String[][] packageFileNames, String newPackageName) throws Exception { + this(packageNames, packageFileNames, newPackageName, false); + } + + public PackageRename(String[] packageNames, String[][] packageFileNames, String newPackageName, boolean testWithDummyFiles) throws Exception { + fPackageNames= packageNames; + fPackageFileNames= packageFileNames; + fNewPackageName= newPackageName; + fTestWithDummyFiles= testWithDummyFiles; + + fPackages= new IPackageFragment[packageNames.length]; + fCus= new ICompilationUnit[packageFileNames.length][]; + for (int i= 0; i < packageFileNames.length; i++){ + fPackages[i]= getRoot().createPackageFragment(packageNames[i], true, null); + fCus[i]= new ICompilationUnit[packageFileNames[i].length]; + for (int j= 0; j < packageFileNames[i].length; j++){ + if (testWithDummyFiles) { + fCus[i][j]= createDummyCU(fPackages[i], packageFileNames[i][j]); + } else { + fCus[i][j]= createCUfromTestFile(fPackages[i], packageFileNames[i][j], packageNames[i].replace('.', '/') + "/"); + } + } + } + } + + private ICompilationUnit createDummyCU(IPackageFragment packageFragment, String typeName) throws JavaModelException { + String contents= getDummyContents(packageFragment.getElementName(), typeName); + return packageFragment.createCompilationUnit(typeName + ".java", contents, true, null); + } + + private String getDummyContents(String packName, String typeName) { + StringBuffer contents= new StringBuffer(); + if (packName.length() != 0) + contents.append("package ").append(packName).append(";\n"); + contents.append("public class ").append(typeName).append(" { }\n"); + return contents.toString(); + } + + public void createAndPerform(int expectedSeverity) throws CoreException, Exception { + IPackageFragment thisPackage= fPackages[0]; + RenameJavaElementDescriptor descriptor= createRefactoringDescriptor(thisPackage, fNewPackageName); + descriptor.setUpdateReferences(fUpdateReferences); + descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches); + setFilePatterns(descriptor); + descriptor.setUpdateHierarchy(fRenameSubpackages); + RefactoringStatus result= performRefactoring(descriptor); + if (expectedSeverity == RefactoringStatus.OK) + assertEquals("preconditions were supposed to pass", null, result); + else + assertEquals(expectedSeverity, result.getSeverity()); + } + + public void execute() throws Exception { + createAndPerform(RefactoringStatus.OK); + + IPackageFragment oldPackage= getRoot().getPackageFragment(fPackageNames[0]); + assertTrue("package not renamed: " + fPackageNames[0], ! oldPackage.exists()); + IPackageFragment newPackage= getRoot().getPackageFragment(fNewPackageName); + assertTrue("new package does not exist", newPackage.exists()); + + checkExpectedState(); + } + + public void checkExpectedState() throws IOException, JavaModelException { + for (int i= 0; i < fPackageFileNames.length; i++){ + String packageName= getNewPackageName(fPackageNames[i]); + String packagePath= packageName.replace('.', '/') + "/"; + + for (int j= 0; j < fPackageFileNames[i].length; j++){ + String expected; + if (fTestWithDummyFiles) { + expected= getDummyContents(packageName, fPackageFileNames[i][j]); + } else { + expected= getFileContents(getOutputTestFileName(fPackageFileNames[i][j], packagePath)); + } + ICompilationUnit cu= getRoot().getPackageFragment(packageName).getCompilationUnit(fPackageFileNames[i][j] + ".java"); + String actual= cu.getSource(); + assertEqualLines("invalid update in file " + cu.getElementName(), expected, actual); + } + } + } + + public String getNewPackageName(String oldPackageName) { + if (oldPackageName.equals(fPackageNames[0])) + return fNewPackageName; + + if (fRenameSubpackages && oldPackageName.startsWith(fPackageNames[0] + ".")) + return fNewPackageName + oldPackageName.substring(fPackageNames[0].length()); + + return oldPackageName; + } + + public void checkOriginalState() throws Exception { + IJavaElement[] rootChildren= getRoot().getChildren(); + ArrayList existingPacks= new ArrayList(); + for (int i= 0; i < rootChildren.length; i++) { + existingPacks.add(rootChildren[i].getElementName()); + } + assertEqualSets(Arrays.asList(fPackageNames), existingPacks); + + for (int i= 0; i < fPackageFileNames.length; i++){ + String packageName= fPackageNames[i]; + String packagePath= packageName.replace('.', '/') + "/"; + IPackageFragment pack= getRoot().getPackageFragment(packageName); + + IJavaElement[] packChildren= pack.getChildren(); + ArrayList existingCUs= new ArrayList(); + for (int j= 0; j < packChildren.length; j++) { + String cuName= packChildren[j].getElementName(); + existingCUs.add(cuName.substring(0, cuName.length() - 5)); + } + assertEqualSets(Arrays.asList(fPackageFileNames[i]), existingCUs); + + for (int j= 0; j < fPackageFileNames[i].length; j++){ + String expected; + if (fTestWithDummyFiles) { + expected= getDummyContents(packageName, fPackageFileNames[i][j]); + } else { + expected= getFileContents(getInputTestFileName(fPackageFileNames[i][j], packagePath)); + } + ICompilationUnit cu= pack.getCompilationUnit(fPackageFileNames[i][j] + ".java"); + String actual= cu.getSource(); + assertEqualLines("invalid undo in file " + cu.getElementName(), expected, actual); + } + } + + } + + private void assertEqualSets(Collection expected, Collection actual) { + HashSet expectedSet= new HashSet(expected); + expectedSet.removeAll(actual); + assertEquals("not all expected in actual", "[]", expectedSet.toString()); + + HashSet actualSet= new HashSet(actual); + actualSet.removeAll(expected); + assertEquals("not all actual in expected", "[]", actualSet.toString()); + } + } + + private void performUndo() throws Exception { + IUndoManager um= RefactoringCore.getUndoManager(); + assertTrue(um.anythingToUndo()); + um.performUndo(null, new NullProgressMonitor()); + assertFalse(um.anythingToUndo()); + assertTrue(um.anythingToRedo()); + } + + /** + * Custom project and source folder structure. + * @param roots source folders + * @param packageNames package names per root + * @param newPackageName the new package name for packageNames[0][0] + * @param cuNames cu names per package + * @throws Exception + */ + private void helperMultiProjects(IPackageFragmentRoot[] roots, String[][] packageNames, String newPackageName, String[][][] cuNames) throws Exception{ + ICompilationUnit[][][] cus=new ICompilationUnit[roots.length][][]; + IPackageFragment thisPackage= null; + + for (int r= 0; r < roots.length; r++) { + IPackageFragment[] packages= new IPackageFragment[packageNames[r].length]; + cus[r]= new ICompilationUnit[packageNames[r].length][]; + for (int pa= 0; pa < packageNames[r].length; pa++){ + packages[pa]= roots[r].createPackageFragment(packageNames[r][pa], true, null); + cus[r][pa]= new ICompilationUnit[cuNames[r][pa].length]; + if (r == 0 && pa == 0) + thisPackage= packages[pa]; + for (int typ= 0; typ < cuNames[r][pa].length; typ++){ + cus[r][pa][typ]= createCUfromTestFile(packages[pa], cuNames[r][pa][typ], + roots[r].getElementName() + "/" + packageNames[r][pa].replace('.', '/') + "/"); + } + } + } + + RenameJavaElementDescriptor descriptor= createRefactoringDescriptor(thisPackage, newPackageName); + descriptor.setUpdateReferences(fUpdateReferences); + descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches); + setFilePatterns(descriptor); + descriptor.setUpdateHierarchy(fRenameSubpackages); + RefactoringStatus result= performRefactoring(descriptor); + assertEquals("preconditions were supposed to pass", null, result); + + assertTrue("package not renamed", ! roots[0].getPackageFragment(packageNames[0][0]).exists()); + IPackageFragment newPackage= roots[0].getPackageFragment(newPackageName); + assertTrue("new package does not exist", newPackage.exists()); + + for (int r = 0; r < cuNames.length; r++) { + for (int pa= 0; pa < cuNames[r].length; pa++){ + String packageName= roots[r].getElementName() + "/" + + ((r == 0 && pa == 0) ? newPackageName : packageNames[r][pa]).replace('.', '/') + "/"; + for (int typ= 0; typ < cuNames[r][pa].length; typ++){ + String s1= getFileContents(getOutputTestFileName(cuNames[r][pa][typ], packageName)); + ICompilationUnit cu= (r == 0 && pa == 0) + ? newPackage.getCompilationUnit(cuNames[r][pa][typ] + ".java") + : cus[r][pa][typ]; + //DebugUtils.dump("cu:" + cu.getElementName()); + String s2= cu.getSource(); + + //DebugUtils.dump("expected:" + s1); + //DebugUtils.dump("was:" + s2); + assertEqualLines("invalid update in file " + cu.toString(), s1, s2); + } + } + } + } + + /** + * 2 Projects with a root each: + * Project RenamePack2 (root: srcTest) requires project RenamePack1 (root: srcPrg). + * @param packageNames package names per root + * @param newPackageName the new package name for packageNames[0][0] + * @param cuNames cu names per package + * @throws Exception + */ + private void helperProjectsPrgTest(String[][] packageNames, String newPackageName, String[][][] cuNames) throws Exception{ + IJavaProject projectPrg= null; + IJavaProject projectTest= null; + try { + projectPrg= JavaProjectHelper.createJavaProject("RenamePack1", "bin"); + assertNotNull(JavaProjectHelper.addRTJar(projectPrg)); + IPackageFragmentRoot srcPrg= JavaProjectHelper.addSourceContainer(projectPrg, "srcPrg"); + Map optionsPrg= projectPrg.getOptions(false); + JavaProjectHelper.set15CompilerOptions(optionsPrg); + projectPrg.setOptions(optionsPrg); + + projectTest= JavaProjectHelper.createJavaProject("RenamePack2", "bin"); + assertNotNull(JavaProjectHelper.addRTJar(projectTest)); + IPackageFragmentRoot srcTest= JavaProjectHelper.addSourceContainer(projectTest, "srcTest"); + Map optionsTest= projectTest.getOptions(false); + JavaProjectHelper.set15CompilerOptions(optionsTest); + projectTest.setOptions(optionsTest); + + JavaProjectHelper.addRequiredProject(projectTest, projectPrg); + + helperMultiProjects(new IPackageFragmentRoot[] { srcPrg, srcTest }, packageNames, newPackageName, cuNames); + } finally { + JavaProjectHelper.delete(projectPrg); + JavaProjectHelper.delete(projectTest); + } + } + + /* + * Multiple source folders in the same project. + * @param newPackageName the new package name for packageNames[0][0] + */ + private void helperMultiRoots(String[] rootNames, String[][] packageNames, String newPackageName, String[][][] typeNames) throws Exception{ + IPackageFragmentRoot[] roots= new IPackageFragmentRoot[rootNames.length]; + try { + for (int r= 0; r < roots.length; r++) + roots[r]= JavaProjectHelper.addSourceContainer(getRoot().getJavaProject(), rootNames[r]); + helperMultiProjects(roots, packageNames, newPackageName, typeNames); + } catch (CoreException e) { + } + for (int r= 0; r < roots.length; r++) + JavaProjectHelper.removeSourceContainer(getRoot().getJavaProject(), rootNames[r]); + } + + private void setFilePatterns(RenameJavaElementDescriptor descriptor) { + descriptor.setUpdateQualifiedNames(fQualifiedNamesFilePatterns != null); + if (fQualifiedNamesFilePatterns != null) + descriptor.setFileNamePatterns(fQualifiedNamesFilePatterns); + } + + private void checkMappingUnchanged(IJavaElementMapper jm, IResourceMapper rm, Object[] resOrJEs) { + for (int i= 0; i < resOrJEs.length; i++) { + Object resOrJE= resOrJEs[i]; + if (resOrJE instanceof IJavaElement) { + IJavaElement javaElement= (IJavaElement) resOrJE; + resOrJE= javaElement.getResource(); + assertEquals(javaElement, jm.getRefactoredJavaElement(javaElement)); + } + if (resOrJE instanceof IResource) { + IResource resource= (IResource) resOrJE; + assertEquals(resource, rm.getRefactoredResource(resource)); + } + } + } + + private void checkMappingChanged(IJavaElementMapper jm, IResourceMapper rm, Object[][] resOrJeToChangeds) { + for (int i= 0; i < resOrJeToChangeds.length; i++) { + Object[] resOrJeToChanged= resOrJeToChangeds[i]; + Object resOrJE= resOrJeToChanged[0]; + Object changed= resOrJeToChanged[1]; + if (resOrJE instanceof IJavaElement) { + IJavaElement javaElement= (IJavaElement) resOrJE; + assertEquals(changed, jm.getRefactoredJavaElement(javaElement)); + resOrJE= javaElement.getResource(); + changed= ((IJavaElement) resOrJeToChanged[1]).getResource(); + } + if (resOrJE instanceof IResource) { + IResource resource= (IResource) resOrJE; + assertEquals(changed, rm.getRefactoredResource(resource)); + } + } + } + + // ---------- tests ------------- + + + public void testPackageRenameWithResource1() throws Exception { + IPackageFragment fragment= getRoot().createPackageFragment("org.test", true, null); + + StringBuffer buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class MyClass {\n"); + buf.append(" org.test.MyClass me;\n"); + buf.append("}\n"); + fragment.createCompilationUnit("MyClass.java", buf.toString(), true, null); + + IFile file= ((IFolder) getRoot().getResource()).getFile("x.properties"); + byte[] content= "This is about 'org.test' and more".getBytes(); + file.create(new ByteArrayInputStream(content), true, null); + file.refreshLocal(IResource.DEPTH_ONE, null); + + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_PACKAGE); + descriptor.setJavaElement(fragment); + descriptor.setNewName("org.test2"); + descriptor.setUpdateReferences(true); + descriptor.setUpdateQualifiedNames(true); + descriptor.setFileNamePatterns("*.properties"); + Refactoring refactoring= createRefactoring(descriptor); + RefactoringStatus status= performRefactoring(refactoring); + if (status != null) + assertTrue(status.toString(), status.isOK()); + + RefactoringProcessor processor= ((RenameRefactoring) refactoring).getProcessor(); + IResourceMapper rm= (IResourceMapper) processor.getAdapter(IResourceMapper.class); + IJavaElementMapper jm= (IJavaElementMapper) processor.getAdapter(IJavaElementMapper.class); + checkMappingUnchanged(jm, rm, new Object[] { getRoot().getJavaProject(), getRoot(), file }); + IFile newFile= ((IContainer) getRoot().getResource()).getFile(new Path("x.properties")); + assertEquals("This is about 'org.test2' and more", getContents(newFile)); + checkMappingChanged(jm, rm, new Object[][] { + { fragment, getRoot().getPackageFragment("org.test2") } + }); + } + + public void testPackageRenameWithResource2() throws Exception { + IPackageFragment fragment= getRoot().createPackageFragment("org.test", true, null); + + StringBuffer buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class MyClass {\n"); + buf.append("}\n"); + fragment.createCompilationUnit("MyClass.java", buf.toString(), true, null); + + IFile file= ((IFolder) fragment.getResource()).getFile("x.properties"); + byte[] content= "This is about 'org.test' and more".getBytes(); + file.create(new ByteArrayInputStream(content), true, null); + file.refreshLocal(IResource.DEPTH_ONE, null); + + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_PACKAGE); + descriptor.setJavaElement(fragment); + descriptor.setNewName("org.test2"); + descriptor.setUpdateReferences(true); + descriptor.setUpdateQualifiedNames(true); + descriptor.setFileNamePatterns("*.properties"); + Refactoring refactoring= createRefactoring(descriptor); + RefactoringStatus status= performRefactoring(refactoring); + if (status != null) + assertTrue(status.toString(), status.isOK()); + + RefactoringProcessor processor= ((RenameRefactoring) refactoring).getProcessor(); + IResourceMapper rm= (IResourceMapper) processor.getAdapter(IResourceMapper.class); + IJavaElementMapper jm= (IJavaElementMapper) processor.getAdapter(IJavaElementMapper.class); + checkMappingUnchanged(jm, rm, new Object[] { getRoot().getJavaProject(), getRoot() }); + IPackageFragment newFragment= getRoot().getPackageFragment("org.test2"); + IFile newFile= ((IContainer) newFragment.getResource()).getFile(new Path("x.properties")); + assertEquals("This is about 'org.test2' and more", getContents(newFile)); + checkMappingChanged(jm, rm, new Object[][] { + { fragment, newFragment }, + { file, newFile }, + }); + } + + public void testPackageRenameWithResource3() throws Exception { + // regression test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=108019 + fIsPreDeltaTest= true; + + fQualifiedNamesFilePatterns= "*.txt"; + String textFileName= "Textfile.txt"; + + String textfileContent= getFileContents(getTestPath() + getName() + TEST_INPUT_INFIX + "my/pack/" + textFileName); + IFolder myPackFolder= getRoot().getJavaProject().getProject().getFolder("my").getFolder("pack"); + CoreUtility.createFolder(myPackFolder, true, true, null); + IFile textfile= myPackFolder.getFile(textFileName); + textfile.create(new ByteArrayInputStream(textfileContent.getBytes()), true, null); + + helper2(new String[]{"my.pack", "my"}, new String[][]{{}, {}}, "my"); + + InputStreamReader reader= new InputStreamReader(textfile.getContents(true)); + StringBuffer newContent= new StringBuffer(); + try { + int ch; + while((ch= reader.read()) != -1) + newContent.append((char)ch); + } finally { + reader.close(); + } + String definedContent= getFileContents(getTestPath() + getName() + TEST_OUTPUT_INFIX + "my/" + textFileName); + assertEqualLines("invalid updating", definedContent, newContent.toString()); + } + + public void testHierarchical01() throws Exception { + fRenameSubpackages= true; + + PackageRename rename= new PackageRename(new String[]{"my", "my.a", "my.b"}, new String[][]{{"MyA"},{"ATest"},{"B"}}, "your"); + IPackageFragment thisPackage= rename.fPackages[0]; + + ParticipantTesting.reset(); + List toRename= new ArrayList(Arrays.asList(JavaElementUtil.getPackageAndSubpackages(thisPackage))); + toRename.add(thisPackage.getResource()); + String[] renameHandles= ParticipantTesting.createHandles(toRename.toArray()); + + rename.execute(); + + ParticipantTesting.testRename(renameHandles, new RenameArguments[] { + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[0]), true), + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[1]), true), + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[2]), true), + new RenameArguments("your", true) + }); + } + + public void testHierarchical02() throws Exception { + if (true) { + printTestDisabledMessage("package can't be renamed to a package that already exists."); + return; + } + fRenameSubpackages= true; + + PackageRename rename= new PackageRename(new String[]{"my", "my.a", "my.b", "your"}, new String[][]{{"MyA"},{"ATest"},{"B"}, {"Y"}}, "your"); + IPackageFragment thisPackage= rename.fPackages[0]; + IPath srcPath= thisPackage.getParent().getPath(); + IFolder target= ResourcesPlugin.getWorkspace().getRoot().getFolder(srcPath.append("your")); + + ParticipantTesting.reset(); + String[] createHandles= ParticipantTesting.createHandles(target.getFolder("a"), target.getFolder("b")); + String[] deleteHandles= ParticipantTesting.createHandles(thisPackage.getResource()); + String[] moveHandles= ParticipantTesting.createHandles(new Object[] { + rename.fCus[0][0].getResource(), + rename.fCus[1][0].getResource(), + rename.fCus[2][0].getResource(), + }); + String[] renameHandles= ParticipantTesting.createHandles(JavaElementUtil.getPackageAndSubpackages(thisPackage)); + + rename.execute(); + + ParticipantTesting.testCreate(createHandles); + ParticipantTesting.testDelete(deleteHandles); + ParticipantTesting.testMove(moveHandles, new MoveArguments[] { + new MoveArguments(target, true), + new MoveArguments(target.getFolder("a"), true), + new MoveArguments(target.getFolder("b"), true), + }); + ParticipantTesting.testRename(renameHandles, new RenameArguments[] { + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[0]), true), + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[1]), true), + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[2]), true), + }); + } + + public void testHierarchical03() throws Exception { + fRenameSubpackages= true; + fUpdateTextualMatches= true; + + PackageRename rename= new PackageRename(new String[]{"my", "my.pack"}, new String[][]{{},{"C"}}, "your"); + IPackageFragment thisPackage= rename.fPackages[0]; + + ParticipantTesting.reset(); + + List toRename= new ArrayList(Arrays.asList(JavaElementUtil.getPackageAndSubpackages(thisPackage))); + toRename.add(thisPackage.getResource()); + String[] createHandles= {}; + String[] deleteHandles= {}; + String[] moveHandles= {}; + String[] renameHandles= ParticipantTesting.createHandles(toRename.toArray()); + + rename.execute(); + + ParticipantTesting.testCreate(createHandles); + ParticipantTesting.testDelete(deleteHandles); + ParticipantTesting.testMove(moveHandles, new MoveArguments[] { + + }); + ParticipantTesting.testRename(renameHandles, new RenameArguments[] { + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[0]), true), + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[1]), true), + new RenameArguments("your", true) + }); + } + + public void testHierarchicalToSubpackage() throws Exception { + fRenameSubpackages= true; + + PackageRename rename= new PackageRename( + new String[]{"a", "a.b", "a.b.c", "a.b.c.d", "p"}, + new String[][]{{},{"B"},{"C"},{"D"}}, + "a.b", + true + ); + IPackageFragment thisPackage= rename.fPackages[0]; + + IFolder src= (IFolder) getRoot().getResource(); + IFolder ab= src.getFolder("a/b"); + IFolder abc= ab.getFolder("c"); + IFolder abcd= abc.getFolder("d"); + + IFolder abb= ab.getFolder("b"); + IFolder abbc= abb.getFolder("c"); + IFolder abbcd= abbc.getFolder("d"); + + ParticipantTesting.reset(); + + String[] createHandles= ParticipantTesting.createHandles(abb, abbc, abbcd); + String[] deleteHandles= {}; + String[] moveHandles= ParticipantTesting.createHandles(ab.getFile("B.java"), abc.getFile("C.java"), abcd.getFile("D.java")); + String[] renameHandles= ParticipantTesting.createHandles(JavaElementUtil.getPackageAndSubpackages(thisPackage)); + + rename.createAndPerform(RefactoringStatus.WARNING); + rename.checkExpectedState(); + + ParticipantTesting.testCreate(createHandles); + ParticipantTesting.testDelete(deleteHandles); + ParticipantTesting.testMove(moveHandles, new MoveArguments[] { + new MoveArguments(abb, true), + new MoveArguments(abbc, true), + new MoveArguments(abbcd, true), + }); + ParticipantTesting.testRename(renameHandles, new RenameArguments[] { + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[0]), true), + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[1]), true), + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[2]), true), + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[3]), true), + }); + + performUndo(); + rename.checkOriginalState(); + } + + public void testHierarchicalToSuperpackage() throws Exception { + fRenameSubpackages= true; + + PackageRename rename= new PackageRename( + new String[]{"a.b", "a.b.b", "a", "p"}, + new String[][]{{"B"},{"BB"},{}}, + "a", + true + ); + IPackageFragment thisPackage= rename.fPackages[0]; + IFolder src= (IFolder) getRoot().getResource(); + IFolder a= src.getFolder("a"); + IFolder ab= src.getFolder("a/b"); + IFolder abb= src.getFolder("a/b/b"); + + ParticipantTesting.reset(); + + String[] createHandles= {}; + String[] deleteHandles= {}; + String[] moveHandles= ParticipantTesting.createHandles(ab.getFile("B.java"), abb.getFile("BB.java")); + String[] renameHandles= ParticipantTesting.createHandles(JavaElementUtil.getPackageAndSubpackages(thisPackage)); + + rename.createAndPerform(RefactoringStatus.OK); + rename.checkExpectedState(); + + ParticipantTesting.testCreate(createHandles); + ParticipantTesting.testDelete(deleteHandles); + ParticipantTesting.testMove(moveHandles, new MoveArguments[] { + new MoveArguments(a, true), + new MoveArguments(ab, true), + }); + ParticipantTesting.testRename(renameHandles, new RenameArguments[] { + new RenameArguments("a", true), + new RenameArguments("a.b", true), + }); + + performUndo(); + rename.checkOriginalState(); + } + + public void testHierarchicalToSuperpackage2() throws Exception { + fRenameSubpackages= true; + + PackageRename rename= new PackageRename( + new String[]{"a.b", "a.b.c", "a.c", "p"}, + new String[][]{{"B"},{"BC"},{}}, + "a", + true + ); + IPackageFragment thisPackage= rename.fPackages[0]; + IFolder src= (IFolder) getRoot().getResource(); + IFolder a= src.getFolder("a"); + IFolder ab= src.getFolder("a/b"); + IFolder ac= src.getFolder("a/c"); + IFolder abc= src.getFolder("a/b/c"); + + ParticipantTesting.reset(); + + String[] createHandles= {}; + String[] deleteHandles= ParticipantTesting.createHandles(ab); + String[] moveHandles= ParticipantTesting.createHandles(ab.getFile("B.java"), abc.getFile("BC.java")); + String[] renameHandles= ParticipantTesting.createHandles(JavaElementUtil.getPackageAndSubpackages(thisPackage)); + + rename.createAndPerform(RefactoringStatus.OK); + rename.checkExpectedState(); + + ParticipantTesting.testCreate(createHandles); + ParticipantTesting.testDelete(deleteHandles); + ParticipantTesting.testMove(moveHandles, new MoveArguments[] { + new MoveArguments(a, true), + new MoveArguments(ac, true), + }); + ParticipantTesting.testRename(renameHandles, new RenameArguments[] { + new RenameArguments("a", true), + new RenameArguments("a.c", true), + }); + + performUndo(); + rename.fPackageNames= new String[] {"a.b", "a.b.c", "a", "p"};// empty package is not recreated, but that's OK + rename.checkOriginalState(); + } + + public void testHierarchicalToSuperpackageFail() throws Exception { + fRenameSubpackages= true; + + PackageRename rename= new PackageRename( + new String[]{"a.b", "a.b.c", "a.c", "a", "p"}, + new String[][]{{"B"},{"BC"},{"AC"}}, + "a", + true + ); + + rename.createAndPerform(RefactoringStatus.FATAL); + rename.checkOriginalState(); + } + + public void testHierarchicalDisabledImport() throws Exception { + fRenameSubpackages= true; + fUpdateTextualMatches= true; + + PackageRename rename= new PackageRename(new String[]{"my", "my.pack"}, new String[][]{{},{"C"}}, "your"); + IPackageFragment thisPackage= rename.fPackages[0]; + + ParticipantTesting.reset(); + + List toRename= new ArrayList(Arrays.asList(JavaElementUtil.getPackageAndSubpackages(thisPackage))); + toRename.add(thisPackage.getResource()); + String[] renameHandles= ParticipantTesting.createHandles(toRename.toArray()); + + rename.execute(); + + ParticipantTesting.testRename(renameHandles, new RenameArguments[] { + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[0]), true), + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[1]), true), + new RenameArguments("your", true) + }); + } + + public void testHierarchicalJUnit() throws Exception { + fRenameSubpackages= true; + + File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC_381); + Assert.assertTrue(junitSrcArchive != null && junitSrcArchive.exists()); + IPackageFragmentRoot src= JavaProjectHelper.addSourceContainerWithImport(getRoot().getJavaProject(), "src", junitSrcArchive, JavaProjectHelper.JUNIT_SRC_ENCODING); + + String[] packageNames= new String[]{"junit", "junit.extensions", "junit.framework", "junit.runner", "junit.samples", "junit.samples.money", "junit.tests", "junit.tests.extensions", "junit.tests.framework", "junit.tests.runner", "junit.textui"}; + ICompilationUnit[][] cus= new ICompilationUnit[packageNames.length][]; + for (int i= 0; i < cus.length; i++) { + cus[i]= src.getPackageFragment(packageNames[i]).getCompilationUnits(); + } + IPackageFragment thisPackage= src.getPackageFragment("junit"); + + ParticipantTesting.reset(); + PackageRename rename= new PackageRename(packageNames, new String[packageNames.length][0],"jdiverge"); + + RenameArguments[] renameArguments= new RenameArguments[packageNames.length + 1]; + for (int i= 0; i < packageNames.length; i++) { + renameArguments[i]= new RenameArguments(rename.getNewPackageName(packageNames[i]), true); + } + renameArguments[packageNames.length]= new RenameArguments("jdiverge", true); + String[] renameHandles= new String[packageNames.length + 1]; + System.arraycopy(ParticipantTesting.createHandles(JavaElementUtil.getPackageAndSubpackages(thisPackage)), 0, renameHandles, 0, packageNames.length); + renameHandles[packageNames.length]= ParticipantTesting.createHandles(thisPackage.getResource())[0]; + + // --- execute: + RenameJavaElementDescriptor descriptor= createRefactoringDescriptor(thisPackage, "jdiverge"); + descriptor.setUpdateReferences(fUpdateReferences); + descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches); + setFilePatterns(descriptor); + descriptor.setUpdateHierarchy(fRenameSubpackages); + Refactoring ref= createRefactoring(descriptor); + + performDummySearch(); + IUndoManager undoManager= getUndoManager(); + CreateChangeOperation create= new CreateChangeOperation( + new CheckConditionsOperation(ref, CheckConditionsOperation.ALL_CONDITIONS), + RefactoringStatus.FATAL); + PerformChangeOperation perform= new PerformChangeOperation(create); + perform.setUndoManager(undoManager, ref.getName()); + ResourcesPlugin.getWorkspace().run(perform, new NullProgressMonitor()); + RefactoringStatus status= create.getConditionCheckingStatus(); + assertTrue("Change wasn't executed", perform.changeExecuted()); + Change undo= perform.getUndoChange(); + assertNotNull("Undo doesn't exist", undo); + assertTrue("Undo manager is empty", undoManager.anythingToUndo()); + + assertFalse(status.hasError()); + assertTrue(status.hasWarning()); + RefactoringStatusEntry[] statusEntries= status.getEntries(); + for (int i= 0; i < statusEntries.length; i++) { + RefactoringStatusEntry entry= statusEntries[i]; + assertTrue(entry.isWarning()); + assertTrue(entry.getCode() == RefactoringStatusCodes.MAIN_METHOD); + } + + assertTrue("package not renamed: " + rename.fPackageNames[0], ! src.getPackageFragment(rename.fPackageNames[0]).exists()); + IPackageFragment newPackage= src.getPackageFragment(rename.fNewPackageName); + assertTrue("new package does not exist", newPackage.exists()); + // --- + + ParticipantTesting.testRename(renameHandles, renameArguments); + + PerformChangeOperation performUndo= new PerformChangeOperation(undo); + ResourcesPlugin.getWorkspace().run(performUndo, new NullProgressMonitor()); + + assertTrue("new package still exists", ! newPackage.exists()); + assertTrue("original package does not exist: " + rename.fPackageNames[0], src.getPackageFragment(rename.fPackageNames[0]).exists()); + + ZipInputStream zis= new ZipInputStream(new BufferedInputStream(new FileInputStream(junitSrcArchive))); + ZipTools.compareWithZipped(src, zis, JavaProjectHelper.JUNIT_SRC_ENCODING); + } + + public void testFail0() throws Exception{ + helper1(new String[]{"r"}, new String[][]{{"A"}}, "9"); + } + + public void testFail1() throws Exception{ + printTestDisabledMessage("needs revisiting"); + //helper1(new String[]{"r.p1"}, new String[][]{{"A"}}, "r"); + } + + public void testFail3() throws Exception{ + helper1(new String[]{"r"}, new String[][]{{"A"}}, "fred"); + } + + public void testFail4() throws Exception{ + helper1(); + } + + public void testFail5() throws Exception{ + helper1(); + } + + public void testFail6() throws Exception{ + helper1(); + } + + public void testFail7() throws Exception{ + //printTestDisabledMessage("1GK90H4: ITPJCORE:WIN2000 - search: missing package reference"); + printTestDisabledMessage("corner case - name obscuring"); +// helper1(new String[]{"r", "p1"}, new String[][]{{"A"}, {"A"}}, "fred"); + } + + public void testFail8() throws Exception{ + printTestDisabledMessage("corner case - name obscuring"); +// helper1(new String[]{"r", "p1"}, new String[][]{{"A"}, {"A"}}, "fred"); + } + + //native method used r.A as a parameter + public void testFail9() throws Exception{ + printTestDisabledMessage("corner case - qualified name used as a parameter of a native method"); + //helper1(new String[]{"r", "p1"}, new String[][]{{"A"}, {"A"}}, "fred"); + } + + public void testFail10() throws Exception{ + helper1(new String[]{"r.p1", "r"}, new String[][]{{"A"}, {"A"}}, "r"); + } + + //------- + public void test0() throws Exception{ + if (BUG_54962_71267) { + printTestDisabledMessage("bugs 54962, 71267"); + return; + } + fIsPreDeltaTest= true; + } + + public void test1() throws Exception{ + fIsPreDeltaTest= true; + RenamePackageProcessor proc= helper2(new String[]{"r"}, new String[][]{{"A"}}, "p1"); + IJavaElementMapper jm= (IJavaElementMapper) proc.getAdapter(IJavaElementMapper.class); + IResourceMapper rm= (IResourceMapper) proc.getAdapter(IResourceMapper.class); + + IJavaModel javaModel= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); + IJavaProject project= getRoot().getJavaProject(); + IFile _project= project.getProject().getFile(".project"); + checkMappingUnchanged(jm, rm, new Object[] {javaModel, project, _project, getRoot(), getPackageP(), + getRoot().getPackageFragment("inexistent"), getRoot().getPackageFragment("r.inexistent"), + getRoot().getPackageFragment("p1.inexistent")}); + + IPackageFragment r= getRoot().getPackageFragment("r"); + ICompilationUnit r_A= r.getCompilationUnit("A.java"); + IType r_A_A= r_A.getType("A"); + IField r_A_A_a= r_A_A.getField("a"); + IPackageFragment p1= getRoot().getPackageFragment("p1"); + ICompilationUnit p1_A= p1.getCompilationUnit("A.java"); + IType p1_A_A= p1_A.getType("A"); + IField p1_A_A_a= p1_A_A.getField("a"); + checkMappingChanged(jm, rm, new Object[][] { + { r, p1}, + { r_A, p1_A}, + { r_A_A, p1_A_A}, + { r_A_A_a, p1_A_A_a}, + }); + } + + public void test2() throws Exception{ + fIsPreDeltaTest= true; + RenamePackageProcessor processor= helper2(new String[]{"r", "fred"}, new String[][]{{"A"}, {"A"}}, "p1"); + + // test that participants are correctly informed after '< Back': https://bugs.eclipse.org/bugs/show_bug.cgi?id=280068 + performUndo(); + + ParticipantTesting.reset(); + String secondName= "pipapo"; + processor.setNewElementName(secondName); + String[] renameHandles= ParticipantTesting.createHandles(new Object[] { + processor.getPackage(), + processor.getPackage().getResource() + }); + + RenameRefactoring refactoring= (RenameRefactoring)processor.getRefactoring(); + refactoring.checkFinalConditions(new NullProgressMonitor()); + refactoring.createChange(new NullProgressMonitor()); + + ParticipantTesting.testRename(renameHandles, new RenameArguments[] { + new RenameArguments(secondName, true), + new RenameArguments(secondName, true) + }); + } + + public void test3() throws Exception{ + fIsPreDeltaTest= true; + helper2(new String[]{"fred", "r.r"}, new String[][]{{"A"}, {"B"}}, "r"); + } + + public void test4() throws Exception{ + fIsPreDeltaTest= true; + + fQualifiedNamesFilePatterns= "*.txt"; + String textFileName= "Textfile.txt"; + + String textfileContent= getFileContents(getTestPath() + getName() + TEST_INPUT_INFIX + textFileName); + IFile textfile= getRoot().getJavaProject().getProject().getFile(textFileName); + textfile.create(new ByteArrayInputStream(textfileContent.getBytes()), true, null); + + helper2(new String[]{"r.p1", "r"}, new String[][]{{"A"}, {"A"}}, "q"); + + InputStreamReader reader= new InputStreamReader(textfile.getContents(true)); + StringBuffer newContent= new StringBuffer(); + try { + int ch; + while((ch= reader.read()) != -1) + newContent.append((char)ch); + } finally { + reader.close(); + } + String definedContent= getFileContents(getTestPath() + getName() + TEST_OUTPUT_INFIX + textFileName); + assertEqualLines("invalid updating", definedContent, newContent.toString()); + } + + public void test5() throws Exception{ + fUpdateReferences= false; + fIsPreDeltaTest= true; + helper2(new String[]{"r"}, new String[][]{{"A"}}, "p1"); + } + + public void test6() throws Exception{ //bug 66250 + fUpdateReferences= false; + fUpdateTextualMatches= true; + fIsPreDeltaTest= true; + helper2(new String[]{"r"}, new String[][]{{"A"}}, "p1"); + } + + public void test7() throws Exception{ + helper2(new String[]{"r", "r.s"}, new String[][]{{"A"}, {"B"}}, "q"); + } + + public void test8() throws Exception{ + helper2(new String[]{"java.lang.reflect"}, new String[][]{{"Klass"}}, "nonjava"); + } + + public void testToEmptyPack() throws Exception{ + helper2(new String[]{"r.p1", "fred"}, new String[][] {{"A"}, {}}, "fred"); + } + + public void testToEmptySubPack() throws Exception{ + fRenameSubpackages= true; + + PackageRename rename= new PackageRename(new String[]{"p", "p.q"}, new String[][] {{}, {}}, "p.q"); + IPackageFragment p= rename.fPackages[0]; + IPackageFragment pq= rename.fPackages[1]; + + ParticipantTesting.reset(); + String[] renameHandles= ParticipantTesting.createHandles(p, pq); + + rename.createAndPerform(RefactoringStatus.OK); + assertTrue(p.exists()); + assertTrue(pq.exists()); + IPackageFragment ppq= getRoot().getPackageFragment("p.q.q"); + assertTrue(ppq.exists()); + + ParticipantTesting.testRename(renameHandles, new RenameArguments[] { + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[0]), true), + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[1]), true), + }); + ParticipantTesting.testCreate(ParticipantTesting.createHandles( + ppq.getResource() + )); + } + + public void testWithEmptySubPack() throws Exception{ + fRenameSubpackages= true; + + PackageRename rename= new PackageRename(new String[]{"p", "p.q"}, new String[][] {{}, {}}, "p1"); + IPackageFragment p= rename.fPackages[0]; + IPackageFragment pq= rename.fPackages[1]; + + ParticipantTesting.reset(); + String[] renameHandles= ParticipantTesting.createHandles(p, pq, p.getResource()); + + rename.createAndPerform(RefactoringStatus.OK); + assertFalse(p.exists()); + assertFalse(pq.exists()); + IPackageFragment p1= getRoot().getPackageFragment("p1"); + IPackageFragment p1q= getRoot().getPackageFragment("p1.q"); + assertTrue(p1.exists()); + assertTrue(p1q.exists()); + + ParticipantTesting.testRename(renameHandles, new RenameArguments[] { + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[0]), true), + new RenameArguments(rename.getNewPackageName(rename.fPackageNames[1]), true), + new RenameArguments("p1", true) + }); + } + + public void testReadOnly() throws Exception{ + if (BUG_6054) { + printTestDisabledMessage("see bug#6054 (renaming a read-only package resets the read-only flag)"); + return; + } + + fIsPreDeltaTest= true; + String[] packageNames= new String[]{"r"}; + String[][] packageFileNames= new String[][]{{"A"}}; + String newPackageName= "p1"; + IPackageFragment[] packages= new IPackageFragment[packageNames.length]; + + ICompilationUnit[][] cus= new ICompilationUnit[packageFileNames.length][packageFileNames[0].length]; + for (int i= 0; i < packageNames.length; i++){ + packages[i]= getRoot().createPackageFragment(packageNames[i], true, null); + for (int j= 0; j < packageFileNames[i].length; j++){ + cus[i][j]= createCUfromTestFile(packages[i], packageFileNames[i][j], packageNames[i].replace('.', '/') + "/"); + } + } + IPackageFragment thisPackage= packages[0]; + final IResource resource= thisPackage.getCorrespondingResource(); + final ResourceAttributes attributes= resource.getResourceAttributes(); + if (attributes != null) + attributes.setReadOnly(true); + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(thisPackage, newPackageName)); + assertEquals("preconditions were supposed to pass", null, result); + + assertTrue("package not renamed", ! getRoot().getPackageFragment(packageNames[0]).exists()); + IPackageFragment newPackage= getRoot().getPackageFragment(newPackageName); + assertTrue("new package does not exist", newPackage.exists()); + assertTrue("new package should be read-only", attributes == null || attributes.isReadOnly()); + } + + public void testImportFromMultiRoots1() throws Exception { + fUpdateTextualMatches= true; + helperProjectsPrgTest( + new String[][] { + new String[] { "p.p" }, new String[] { "p.p", "tests" } + }, + "q", + new String[][][] { + new String[][] { new String[] { "A" }}, + new String[][] { new String[] { "ATest" }, new String[] { "AllTests" }} + }); + } + + public void testImportFromMultiRoots2() throws Exception { + helperProjectsPrgTest( + new String[][] { + new String[]{"p.p"}, + new String[]{"p.p", "tests"} + }, + "q", + new String[][][] { + new String[][] {new String[]{"A"}}, + new String[][] {new String[]{"ATest", "TestHelper"}, new String[]{"AllTests", "QualifiedTests"}} + } + ); + } + + public void testImportFromMultiRoots3() throws Exception { + helperMultiRoots(new String[]{"srcPrg", "srcTest"}, + new String[][] { + new String[]{"p.p"}, + new String[]{"p.p"} + }, + "q", + new String[][][] { + new String[][] {new String[]{"ToQ"}}, + new String[][] {new String[]{"Ref"}} + } + ); + } + + public void testImportFromMultiRoots4() throws Exception { + //circular buildpath references + IJavaProject projectPrg= null; + IJavaProject projectTest= null; + Hashtable options= JavaCore.getOptions(); + Object cyclicPref= JavaCore.getOption(JavaCore.CORE_CIRCULAR_CLASSPATH); + try { + projectPrg= JavaProjectHelper.createJavaProject("RenamePack1", "bin"); + assertNotNull(JavaProjectHelper.addRTJar(projectPrg)); + IPackageFragmentRoot srcPrg= JavaProjectHelper.addSourceContainer(projectPrg, "srcPrg"); + + projectTest= JavaProjectHelper.createJavaProject("RenamePack2", "bin"); + assertNotNull(JavaProjectHelper.addRTJar(projectTest)); + IPackageFragmentRoot srcTest= JavaProjectHelper.addSourceContainer(projectTest, "srcTest"); + + options.put(JavaCore.CORE_CIRCULAR_CLASSPATH, JavaCore.WARNING); + JavaCore.setOptions(options); + JavaProjectHelper.addRequiredProject(projectTest, projectPrg); + JavaProjectHelper.addRequiredProject(projectPrg, projectTest); + + helperMultiProjects(new IPackageFragmentRoot[] {srcPrg, srcTest}, + new String[][] { + new String[]{"p"}, + new String[]{"p"} + }, + "a.b.c", + new String[][][] { + new String[][] {new String[]{"A", "B"}}, + new String[][] {new String[]{"ATest"}} + } + ); + } finally { + options.put(JavaCore.CORE_CIRCULAR_CLASSPATH, cyclicPref); + JavaCore.setOptions(options); + JavaProjectHelper.delete(projectPrg); + JavaProjectHelper.delete(projectTest); + } + } + + public void testImportFromMultiRoots5() throws Exception { + //rename srcTest-p.p to q => ATest now must import p.p.A + IJavaProject projectPrg= null; + IJavaProject projectTest= null; + try { + projectPrg= JavaProjectHelper.createJavaProject("RenamePack1", "bin"); + assertNotNull(JavaProjectHelper.addRTJar(projectPrg)); + IPackageFragmentRoot srcPrg= JavaProjectHelper.addSourceContainer(projectPrg, "srcPrg"); + + projectTest= JavaProjectHelper.createJavaProject("RenamePack2", "bin"); + assertNotNull(JavaProjectHelper.addRTJar(projectTest)); + IPackageFragmentRoot srcTest= JavaProjectHelper.addSourceContainer(projectTest, "srcTest"); + + JavaProjectHelper.addRequiredProject(projectTest, projectPrg); + + helperMultiProjects(new IPackageFragmentRoot[] { srcTest, srcPrg }, + new String[][] { + new String[] {"p.p"}, new String[] {"p.p"} + }, + "q", + new String[][][] { + new String[][] {new String[] {"ATest"}}, + new String[][] {new String[] {"A"}} + } + ); + } finally { + JavaProjectHelper.delete(projectPrg); + JavaProjectHelper.delete(projectTest); + } + + } + + public void testImportFromMultiRoots6() throws Exception { + //rename srcTest-p.p to a.b.c => ATest must retain import p.p.A + helperMultiRoots(new String[]{"srcTest", "srcPrg"}, + new String[][] { + new String[]{"p.p"}, + new String[]{"p.p"} + }, + "cheese", + new String[][][] { + new String[][] {new String[]{"ATest"}}, + new String[][] {new String[]{"A"}} + } + ); + } + + public void testImportFromMultiRoots7() throws Exception { + IJavaProject prj= null; + IJavaProject prjRef= null; + IJavaProject prjOther= null; + try { + prj= JavaProjectHelper.createJavaProject("prj", "bin"); + assertNotNull(JavaProjectHelper.addRTJar(prj)); + IPackageFragmentRoot srcPrj= JavaProjectHelper.addSourceContainer(prj, "srcPrj"); //$NON-NLS-1$ + + prjRef= JavaProjectHelper.createJavaProject("prj.ref", "bin"); + assertNotNull(JavaProjectHelper.addRTJar(prjRef)); + IPackageFragmentRoot srcPrjRef= JavaProjectHelper.addSourceContainer(prjRef, "srcPrj.ref"); //$NON-NLS-1$ + + prjOther= JavaProjectHelper.createJavaProject("prj.other", "bin"); + assertNotNull(JavaProjectHelper.addRTJar(prjOther)); + IPackageFragmentRoot srcPrjOther= JavaProjectHelper.addSourceContainer(prjRef, "srcPrj.other"); //$NON-NLS-1$ + + JavaProjectHelper.addRequiredProject(prjRef, prj); + JavaProjectHelper.addRequiredProject(prjRef, prjOther); + + helperMultiProjects( + new IPackageFragmentRoot[] { srcPrj, srcPrjRef, srcPrjOther }, + new String[][] { + new String[] {"pack"}, + new String[] {"pack", "pack.man"}, + new String[] {"pack"} + }, + "com.packt", + new String[][][] { + new String[][] {new String[] {"DingsDa"}}, + new String[][] {new String[] {"Referer"}, new String[] {"StarImporter"}}, + new String[][] {new String[] {"Namesake"}} + } + ); + } finally { + JavaProjectHelper.delete(prj); + JavaProjectHelper.delete(prjRef); + JavaProjectHelper.delete(prjOther); + } + } + + public void testStatic1() throws Exception { + helper2(new String[]{"s1.j.l", "s1"}, new String[][]{{"S"},{"B"}}, "s1.java.lang"); + } + + public void testStaticMultiRoots1() throws Exception { + helperProjectsPrgTest( + new String[][] { + new String[] { "p.p" }, new String[] { "p.p", "tests" } + }, + "q", + new String[][][] { + new String[][] { new String[] { "A" }}, + new String[][] { new String[] { "ATest" }, new String[] { "AllTests" }} + }); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameParametersTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameParametersTests.java new file mode 100644 index 000000000..6703d2562 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameParametersTests.java @@ -0,0 +1,368 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.Iterator; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; + +import org.eclipse.jdt.internal.corext.refactoring.ParameterInfo; +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; +import org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureProcessor; + +public class RenameParametersTests extends RefactoringTest{ + + private static final Class clazz= RenameParametersTests.class; + private static final String REFACTORING_PATH= "RenameParameters/"; + + public RenameParametersTests(String name){ + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + private String getSimpleTestFileName(boolean canRename, boolean input){ + String fileName = "A_" + getName(); + if (canRename) + fileName += input ? "_in": "_out"; + return fileName + ".java"; + } + + private String getTestFileName(boolean canRename, boolean input){ + String fileName= TEST_PATH_PREFIX + getRefactoringPath(); + fileName += (canRename ? "canRename/": "cannotRename/"); + return fileName + getSimpleTestFileName(canRename, input); + } + + //------------ + protected ICompilationUnit createCUfromTestFile(IPackageFragment pack, boolean canRename, boolean input) throws Exception { + return createCU(pack, getSimpleTestFileName(canRename, input), getFileContents(getTestFileName(canRename, input))); + } + + private void helper1(String[] newNames, String[] signature) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + IType classA= getType(cu, "A"); + IMethod method= classA.getMethod("m", signature); + assertTrue("refactoring not available", RefactoringAvailabilityTester.isChangeSignatureAvailable(method)); + ChangeSignatureProcessor processor= new ChangeSignatureProcessor(method); + Refactoring ref= new ProcessorBasedRefactoring(processor); + //ref.setUpdateReferences(updateReferences); + //ref.setNewParameterNames(newNames); + //ref.setNewNames(createRenamings(method, newNames)); + modifyInfos(processor.getParameterInfos(), newNames); + + RefactoringStatus result= performRefactoring(ref); + assertEquals("precondition was supposed to pass", null, result); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + assertEquals("invalid renaming", getFileContents(getTestFileName(true, false)).length(), newcu.getSource().length()); + assertEqualLines("invalid renaming", getFileContents(getTestFileName(true, false)), newcu.getSource()); + } + + private void helper2(String[] newNames, String[] signature) throws Exception{ + IType classA= getType(createCUfromTestFile(getPackageP(), false, false), "A"); + //DebugUtils.dump("classA" + classA); + IMethod method= classA.getMethod("m", signature); + assertTrue("refactoring not available", RefactoringAvailabilityTester.isChangeSignatureAvailable(method)); + ChangeSignatureProcessor processor= new ChangeSignatureProcessor(method); + Refactoring ref= new ProcessorBasedRefactoring(processor); + modifyInfos(processor.getParameterInfos(), newNames); + + RefactoringStatus result= performRefactoring(ref); + assertNotNull("precondition was supposed to fail", result); + } + + private void modifyInfos(List list, String[] newNames) { + int i= 0; + for (Iterator iter= list.iterator(); iter.hasNext(); i++) { + ParameterInfo info= (ParameterInfo) iter.next(); + info.setNewName(newNames[i]); + } + } + + + public void test0() throws Exception{ + helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test1() throws Exception{ + helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test2() throws Exception{ + helper1(new String[]{"j", "k"}, new String[]{"I", "I"}); + } + + public void test3() throws Exception{ + helper1(new String[]{"j", "j1"}, new String[]{"I", "I"}); + } + + public void test4() throws Exception{ + helper1(new String[]{"k"}, new String[]{"QA;"}); + } + + public void test5() throws Exception{ + helper1(new String[]{"k"}, new String[]{"I"}); + } + + public void test6() throws Exception{ + helper1(new String[]{"k"}, new String[]{"I"}); + } + + public void test7() throws Exception{ + helper1(new String[]{"k"}, new String[]{"QA;"}); + } + + public void test8() throws Exception{ + helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test9() throws Exception{ + helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test10() throws Exception{ + helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test11() throws Exception{ + printTestDisabledMessage("revisit in the context of anonymous types in type hierarchies"); + // helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test12() throws Exception{ + helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test13() throws Exception{ + helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test14() throws Exception{ + helper1(new String[]{"j"}, new String[]{"QA;"}); + } + + public void test15() throws Exception{ + helper1(new String[]{"j", "i"}, new String[]{"I", "I"}); + } + + public void test16() throws Exception{ + helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test17() throws Exception{ + helper1(new String[]{"j", "i", "k"}, new String[]{"I", "I", "I"}); + } + + public void test18() throws Exception{ + helper1(new String[]{"j"}, new String[]{"QObject;"}); + } + + public void test19() throws Exception{ + helper1(new String[]{"j"}, new String[]{"QA;"}); + } + + public void test20() throws Exception{ + helper1(new String[]{"j"}, new String[]{"Qi;"}); + } + + public void test21() throws Exception{ + helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test22() throws Exception{ + helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test23() throws Exception{ + helper1(new String[]{"j", "i"}, new String[]{"I", "I"}); + } + + public void test24() throws Exception{ + helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test25() throws Exception{ + helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test26() throws Exception{ + printTestDisabledMessage("revisit in the context of anonymous types in type hierarchies"); + //helper1(new String[]{"j"}, new String[]{"I"}); + } + +//removed - see testFail21 +// public void test27() throws Exception{ +// helper1(new String[]{"j"}, new String[]{"I"}); +// } + + public void test28() throws Exception{ + helper1(new String[]{"j"}, new String[]{"[I"}); + } + + public void test29() throws Exception{ + helper1(new String[]{"b"}, new String[]{"QA;"}); + } + + public void test30() throws Exception{ + helper1(new String[]{"i", "k"}, new String[]{"I", "I"}); + } + + public void test31() throws Exception{ + helper1(new String[]{"kk", "j"}, new String[]{"I", "I"}); + } + + public void test32() throws Exception{ + printTestDisabledMessage("must do - constructor params"); + } + + public void test33() throws Exception{ + printTestDisabledMessage("revisit - removed the 'no ref update' option"); +// helper1(new String[]{"b"}, new String[]{"QA;"}, false); + } + + public void test34() throws Exception{ +// printTestDisabledMessage("regression test for bug#9001"); + helper1(new String[]{"test2"}, new String[]{"Z"}); + } + + public void test35() throws Exception{ + printTestDisabledMessage("regression test for bug#6224"); +// helper1(new String[]{"j"}, new String[]{"I"}); + } + + public void test36() throws Exception{ +// printTestDisabledMessage("regression test for bug#21163"); + helper1(new String[]{"j"}, new String[]{"I"}); + } + + // ----- + + public void testFail0() throws Exception{ + printTestDisabledMessage("must fix - name collision with an instance var"); +// helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail1() throws Exception{ + helper2(new String[0], new String[0]); + } + + public void testFail2() throws Exception{ + helper2(new String[]{"i", "i"}, new String[]{"I", "I"}); + } + + public void testFail3() throws Exception{ + helper2(new String[]{"i", "9"}, new String[]{"I", "I"}); + } + + public void testFail4() throws Exception{ + helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail5() throws Exception{ + helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail6() throws Exception{ + printTestDisabledMessage("must fix - name collision with an instance var"); +// helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail7() throws Exception{ + printTestDisabledMessage("waiting for better conflict detection story from DB"); +// helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail8() throws Exception{ + printTestDisabledMessage("waiting for better conflict detection story from DB"); +// helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail9() throws Exception{ + printTestDisabledMessage("waiting for better conflict detection story from DB"); +// helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail10() throws Exception{ + helper2(new String[]{"j", "j"}, new String[]{"I", "I"}); + } + + public void testFail11() throws Exception{ + helper2(new String[]{"j", "j"}, new String[]{"I", "I"}); + } + + public void testFail12() throws Exception{ + printTestDisabledMessage("waiting for better conflict detection story from DB"); + // helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail13() throws Exception{ + printTestDisabledMessage("waiting for better conflict detection story from DB"); +// helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail14() throws Exception{ + printTestDisabledMessage("waiting for better conflict detection story from DB"); +// helper2(new String[]{"j"}, new String[]{"QA;"}); + } + + public void testFail15() throws Exception{ + helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail16() throws Exception{ + helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail17() throws Exception{ + helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail18() throws Exception{ + helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail19() throws Exception{ + printTestDisabledMessage("waiting for better conflict detection story from DB"); +// helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail20() throws Exception{ + printTestDisabledMessage("waiting for better conflict detection story from DB"); +// helper2(new String[]{"j"}, new String[]{"I"}); + } + + public void testFail21() throws Exception{ + printTestDisabledMessage("Disabled since 1.4 compliance level doesn't produce error message"); + // helper2(new String[]{"j"}, new String[]{"I"}); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenamePrivateFieldTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenamePrivateFieldTests.java new file mode 100644 index 000000000..efbbadbbf --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenamePrivateFieldTests.java @@ -0,0 +1,284 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.RenameArguments; +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; +import org.eclipse.jdt.internal.corext.refactoring.rename.RenameFieldProcessor; + +public class RenamePrivateFieldTests extends RefactoringTest { + + private static final Class clazz= RenamePrivateFieldTests.class; + private static final String REFACTORING_PATH= "RenamePrivateField/"; + + private static final boolean BUG_75642_GENERIC_METHOD_SEARCH= true; + private static final boolean BUG_81084= true; + + private Object fPrefixPref; + public RenamePrivateFieldTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup( new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + protected void setUp() throws Exception { + super.setUp(); + Hashtable options= JavaCore.getOptions(); + fPrefixPref= options.get(JavaCore.CODEASSIST_FIELD_PREFIXES); + options.put(JavaCore.CODEASSIST_FIELD_PREFIXES, getPrefixes()); + JavaCore.setOptions(options); + fIsPreDeltaTest= true; + } + + protected void tearDown() throws Exception { + super.tearDown(); + Hashtable options= JavaCore.getOptions(); + options.put(JavaCore.CODEASSIST_FIELD_PREFIXES, fPrefixPref); + JavaCore.setOptions(options); + } + + private String getPrefixes(){ + return "f"; + } + + private void helper1_0(String fieldName, String newFieldName, String typeName, boolean renameGetter, boolean renameSetter) throws Exception{ + IType declaringType= getType(createCUfromTestFile(getPackageP(), "A"), typeName); + IField field= declaringType.getField(fieldName); + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_FIELD); + descriptor.setJavaElement(field); + descriptor.setNewName(newFieldName); + descriptor.setUpdateReferences(true); + descriptor.setRenameGetters(renameGetter); + descriptor.setRenameSetters(renameSetter); + RefactoringStatus result= performRefactoring(descriptor); + assertNotNull("precondition was supposed to fail", result); + } + + private void helper1_0(String fieldName, String newFieldName) throws Exception{ + helper1_0(fieldName, newFieldName, "A", false, false); + } + + private void helper1() throws Exception{ + helper1_0("f", "g"); + } + + private void helper2(String fieldName, String newFieldName, boolean updateReferences, boolean updateTextualMatches, + boolean renameGetter, boolean renameSetter, + boolean expectedGetterRenameEnabled, boolean expectedSetterRenameEnabled) throws Exception{ + ParticipantTesting.reset(); + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType classA= getType(cu, "A"); + IField field= classA.getField(fieldName); + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_FIELD); + descriptor.setJavaElement(field); + descriptor.setNewName(newFieldName); + descriptor.setUpdateReferences(updateReferences); + descriptor.setUpdateTextualOccurrences(updateTextualMatches); + descriptor.setRenameGetters(renameGetter); + descriptor.setRenameSetters(renameSetter); + + RenameRefactoring refactoring= (RenameRefactoring) createRefactoring(descriptor); + RenameFieldProcessor processor= (RenameFieldProcessor) refactoring.getProcessor(); + assertEquals("getter rename enabled", expectedGetterRenameEnabled, processor.canEnableGetterRenaming() == null); + assertEquals("setter rename enabled", expectedSetterRenameEnabled, processor.canEnableSetterRenaming() == null); + + String newGetterName= processor.getNewGetterName(); + String newSetterName= processor.getNewSetterName(); + + int numbers= 1; + List elements= new ArrayList(); + elements.add(field); + List args= new ArrayList(); + args.add(new RenameArguments(newFieldName, updateReferences)); + if (renameGetter && expectedGetterRenameEnabled) { + elements.add(processor.getGetter()); + args.add(new RenameArguments(newGetterName, updateReferences)); + numbers++; + } + if (renameSetter && expectedSetterRenameEnabled) { + elements.add(processor.getSetter()); + args.add(new RenameArguments(newSetterName, updateReferences)); + numbers++; + } + String[] renameHandles= ParticipantTesting.createHandles(elements.toArray()); + + RefactoringStatus result= performRefactoring(refactoring); + assertEquals("was supposed to pass", null, result); + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName("A")), cu.getSource()); + + ParticipantTesting.testRename( + renameHandles, + (RenameArguments[]) args.toArray(new RenameArguments[args.size()])); + + assertTrue("anythingToUndo", RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("! anythingToRedo", !RefactoringCore.getUndoManager().anythingToRedo()); + + RefactoringCore.getUndoManager().performUndo(null, new NullProgressMonitor()); + assertEqualLines("invalid undo", getFileContents(getInputTestFileName("A")), cu.getSource()); + + assertTrue("! anythingToUndo", !RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("anythingToRedo", RefactoringCore.getUndoManager().anythingToRedo()); + + RefactoringCore.getUndoManager().performRedo(null, new NullProgressMonitor()); + assertEqualLines("invalid redo", getFileContents(getOutputTestFileName("A")), cu.getSource()); + } + + private void helper2(boolean updateReferences) throws Exception{ + helper2("f", "g", updateReferences, false, false, false, false, false); + } + + private void helper2() throws Exception{ + helper2(true); + } + + //--------- tests ---------- + public void testFail0() throws Exception{ + helper1(); + } + + public void testFail1() throws Exception{ + helper1(); + } + + public void testFail2() throws Exception{ + helper1(); + } + + public void testFail3() throws Exception{ + helper1(); + } + + public void testFail4() throws Exception{ + helper1(); + } + + public void testFail5() throws Exception{ + helper1(); + } + + public void testFail6() throws Exception{ + helper1(); + } + + public void testFail7() throws Exception{ + helper1(); + } + + public void testFail8() throws Exception{ + helper1_0("gg", "f", "A", false, false); + } + + public void testFail9() throws Exception{ + helper1_0("y", "e", "getE", true, true); + } + + public void testFail10() throws Exception{ + helper1_0("y", "e", "setE", true, true); + } + + // ------ + public void test0() throws Exception{ + helper2(); + } + + public void test1() throws Exception{ + helper2(); + } + + public void test2() throws Exception{ + helper2(false); + } + + public void test3() throws Exception{ + helper2("f", "gg", true, true, false, false, false, false); + } + + public void test4() throws Exception{ + helper2("fMe", "fYou", true, false, true, true, true, true); + } + + public void test5() throws Exception{ + //regression test for 9895 + helper2("fMe", "fYou", true, false, true, false, true, false); + } + + public void test6() throws Exception{ + //regression test for 9895 - opposite case + helper2("fMe", "fYou", true, false, false, true, false, true); + } + + public void test7() throws Exception{ + //regression test for 21292 + helper2("fBig", "fSmall", true, false, true, true, true, true); + } + + public void test8() throws Exception{ + //regression test for 26769 + helper2("f", "g", true, false, true, false, true, false); + } + + public void test9() throws Exception{ + //regression test for 30906 + helper2("fBig", "fSmall", true, false, true, true, true, true); + } + + public void test10() throws Exception{ + //regression test for 81084 + if (BUG_81084) { + printTestDisabledMessage("BUG_81084"); + return; + } + helper2("fList", "fElements", true, false, false, false, false, false); + } + + public void test11() throws Exception{ + if (BUG_75642_GENERIC_METHOD_SEARCH) { + printTestDisabledMessage("BUG_75642_GENERIC_METHOD_SEARCH"); + return; + } + helper2("fList", "fElements", true, false, true, true, true, true); + } + + public void testUnicode01() throws Exception{ + //regression test for 180331 + helper2("field", "feel", true, false, true, true, true, true); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenamePrivateMethodTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenamePrivateMethodTests.java new file mode 100644 index 000000000..1578fe731 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenamePrivateMethodTests.java @@ -0,0 +1,217 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.RenameArguments; +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; + +import org.eclipse.jdt.internal.corext.refactoring.rename.RenameMethodProcessor; +import org.eclipse.jdt.internal.corext.refactoring.rename.RenameNonVirtualMethodProcessor; + +public class RenamePrivateMethodTests extends RefactoringTest { + + private static final Class clazz= RenamePrivateMethodTests.class; + private static final String REFACTORING_PATH= "RenamePrivateMethod/"; + + public RenamePrivateMethodTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + private void helper1_0(String methodName, String newMethodName, String[] signatures) throws Exception{ + IType classA= getType(createCUfromTestFile(getPackageP(), "A"), "A"); + RenameMethodProcessor processor= new RenameNonVirtualMethodProcessor(classA.getMethod(methodName, signatures)); + RenameRefactoring refactoring= new RenameRefactoring(processor); + processor.setNewElementName(newMethodName); + RefactoringStatus result= performRefactoring(refactoring); + assertNotNull("precondition was supposed to fail", result); + } + + private void helper1() throws Exception{ + helper1_0("m", "k", new String[0]); + } + + private void helper2_0(String methodName, String newMethodName, String[] signatures, boolean updateReferences, boolean createDelegate) throws Exception{ + ParticipantTesting.reset(); + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType classA= getType(cu, "A"); + IMethod method= classA.getMethod(methodName, signatures); + String[] handles= ParticipantTesting.createHandles(method); + RenameMethodProcessor processor= new RenameNonVirtualMethodProcessor(method); + RenameRefactoring refactoring= new RenameRefactoring(processor); + processor.setUpdateReferences(updateReferences); + processor.setNewElementName(newMethodName); + processor.setDelegateUpdating(createDelegate); + assertEquals("was supposed to pass", null, performRefactoring(refactoring)); + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName("A")), cu.getSource()); + + ParticipantTesting.testRename( + handles, + new RenameArguments[] { + new RenameArguments(newMethodName, updateReferences)}); + + assertTrue("anythingToUndo", RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("! anythingToRedo", !RefactoringCore.getUndoManager().anythingToRedo()); + //assertEquals("1 to undo", 1, Refactoring.getUndoManager().getRefactoringLog().size()); + + RefactoringCore.getUndoManager().performUndo(null, new NullProgressMonitor()); + assertEqualLines("invalid undo", getFileContents(getInputTestFileName("A")), cu.getSource()); + + assertTrue("! anythingToUndo", !RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("anythingToRedo", RefactoringCore.getUndoManager().anythingToRedo()); + //assertEquals("1 to redo", 1, Refactoring.getUndoManager().getRedoStack().size()); + + RefactoringCore.getUndoManager().performRedo(null, new NullProgressMonitor()); + assertEqualLines("invalid redo", getFileContents(getOutputTestFileName("A")), cu.getSource()); + } + + private void helper2_0(String methodName, String newMethodName, String[] signatures) throws Exception{ + helper2_0(methodName, newMethodName, signatures, true, false); + } + + private void helper2(boolean updateReferences) throws Exception{ + helper2_0("m", "k", new String[0], updateReferences, false); + } + + private void helper2() throws Exception{ + helper2(true); + } + + private void helperDelegate() throws Exception{ + helper2_0("m", "k", new String[0], true, true); + } + + public void testFail0() throws Exception{ + helper1(); + } + + public void testFail1() throws Exception{ + helper1(); + } + + public void testFail2() throws Exception{ + helper1(); + } + + public void testFail5() throws Exception{ + helper1(); + } + + public void test0() throws Exception{ + helper2(); + } + + public void test10() throws Exception{ + helper2(); + } + + public void test11() throws Exception{ + helper2(); + } + + public void test12() throws Exception{ + helper2(); + } + + public void test13() throws Exception{ + helper2(); + } + + public void test14() throws Exception{ + helper2(); + } + + public void test15() throws Exception{ + helper2_0("m", "k", new String[]{"I"}); + } + + public void test16() throws Exception{ + helper2_0("m", "fred", new String[]{"I"}); + } + + public void test17() throws Exception{ + helper2_0("m", "kk", new String[]{"I"}); + } + + public void test18() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuC= createCUfromTestFile(getPackageP(), "C"); + + IType classB= getType(cu, "B"); + RenameMethodProcessor processor= new RenameNonVirtualMethodProcessor(classB.getMethod("m", new String[]{"I"})); + RenameRefactoring refactoring= new RenameRefactoring(processor); + processor.setNewElementName("kk"); + + assertEquals("was supposed to pass", null, performRefactoring(refactoring)); + assertEqualLines("invalid renaming A", getFileContents(getOutputTestFileName("A")), cu.getSource()); + assertEqualLines("invalid renaming C", getFileContents(getOutputTestFileName("C")), cuC.getSource()); + + } + + public void test2() throws Exception{ + helper2_0("m", "fred", new String[0]); + } + + public void test20() throws Exception{ + helper2_0("m", "fred", new String[]{"I"}); + } + + public void test23() throws Exception{ + helper2_0("m", "k", new String[0]); + } + + public void test24() throws Exception{ + helper2_0("m", "k", new String[]{"QString;"}); + } + + public void test25() throws Exception{ + helper2_0("m", "k", new String[]{"[QString;"}); + } + + public void test26() throws Exception{ + helper2_0("m", "k", new String[0]); + } + + public void test27() throws Exception{ + helper2_0("m", "k", new String[0], false, false); + } + + public void testAnon0() throws Exception{ + helper2(); + } + + public void testDelegate01() throws Exception { + // simple static delegate + helperDelegate(); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameResourceChangeTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameResourceChangeTests.java new file mode 100644 index 000000000..caa2fc014 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameResourceChangeTests.java @@ -0,0 +1,235 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspaceRoot; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.resource.RenameResourceChange; + +public class RenameResourceChangeTests extends RefactoringTest { + + private static final Class clazz= RenameResourceChangeTests.class; + public RenameResourceChangeTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + public void testFile0() throws Exception{ + IFolder folder= (IFolder)getPackageP().getCorrespondingResource(); + String newName= "b.txt"; + try{ + + String oldName= "a.txt"; + IFile file= folder.getFile(oldName); + assertTrue("should not exist", ! file.exists()); + String content= "aaaaaaaaa"; + file.create(getStream(content), true, new NullProgressMonitor()); + assertTrue("should exist", file.exists()); + + Change change= new RenameResourceChange(file.getFullPath(), newName); + change.initializeValidationData(new NullProgressMonitor()); + performChange(change); + assertTrue("after: should exist", folder.getFile(newName).exists()); + assertTrue("after: old should not exist", ! folder.getFile(oldName).exists()); + } finally{ + performDummySearch(); + folder.getFile(newName).delete(true, false, new NullProgressMonitor()); + } + } + + public void testFile1() throws Exception{ + + IFolder folder= (IFolder)getPackageP().getCorrespondingResource(); + String newName= "b.txt"; + try{ + String oldName= "a.txt"; + IFile file= folder.getFile(oldName); + assertTrue("should not exist", ! file.exists()); + String content= ""; + file.create(getStream(content), true, new NullProgressMonitor()); + assertTrue("should exist", file.exists()); + + + Change change= new RenameResourceChange(file.getFullPath(), newName); + change.initializeValidationData(new NullProgressMonitor()); + performChange(change); + assertTrue("after: should exist", folder.getFile(newName).exists()); + assertTrue("after: old should not exist", ! folder.getFile(oldName).exists()); + } finally{ + performDummySearch(); + folder.getFile(newName).delete(true, false, new NullProgressMonitor()); + } + } + + public void testFile2() throws Exception{ + IFolder folder= (IFolder)getPackageP().getCorrespondingResource(); + String oldName= "a.txt"; + String newName= "b.txt"; + try{ + IFile file= folder.getFile(oldName); + assertTrue("should not exist", ! file.exists()); + String content= "aaaaaaaaa"; + file.create(getStream(content), true, new NullProgressMonitor()); + assertTrue("should exist", file.exists()); + + Change change= new RenameResourceChange(file.getFullPath(), newName); + change.initializeValidationData(new NullProgressMonitor()); + Change undo= performChange(change); + assertTrue("after: should exist", folder.getFile(newName).exists()); + assertTrue("after: old should not exist", ! folder.getFile(oldName).exists()); + //------ + + assertTrue("should be undoable", undo != null); + undo.initializeValidationData(new NullProgressMonitor()); + performChange(undo); + assertTrue("after undo: should exist", folder.getFile(oldName).exists()); + assertTrue("after undo: old should not exist", ! folder.getFile(newName).exists()); + } finally{ + performDummySearch(); + folder.getFile(oldName).delete(true, false, new NullProgressMonitor()); + } + } + + + public void testFolder0() throws Exception{ + IFolder folder= (IFolder)getPackageP().getCorrespondingResource(); + String newName= "b"; + try{ + String oldName= "a"; + IFolder subFolder= folder.getFolder(oldName); + assertTrue("should not exist", ! subFolder.exists()); + subFolder.create(true, true, null); + assertTrue("should exist", subFolder.exists()); + + + Change change= new RenameResourceChange(subFolder.getFullPath(), newName); + change.initializeValidationData(new NullProgressMonitor()); + performChange(change); + assertTrue("after: should exist", folder.getFolder(newName).exists()); + assertTrue("after: old should not exist", ! folder.getFolder(oldName).exists()); + } finally{ + performDummySearch(); + folder.getFolder(newName).delete(true, false, new NullProgressMonitor()); + } + } + + public void testFolder1() throws Exception{ + IFolder folder= (IFolder)getPackageP().getCorrespondingResource(); + String newName= "b"; + + try{ + String oldName= "a"; + IFolder subFolder= folder.getFolder(oldName); + assertTrue("should not exist", ! subFolder.exists()); + subFolder.create(true, true, null); + IFile file1= subFolder.getFile("a.txt"); + IFile file2= subFolder.getFile("b.txt"); + file1.create(getStream("123"), true, null); + file2.create(getStream("123345"), true, null); + + assertTrue("should exist", subFolder.exists()); + assertTrue("file1 should exist", file1.exists()); + assertTrue("file2 should exist", file2.exists()); + + Change change= new RenameResourceChange(subFolder.getFullPath(), newName); + change.initializeValidationData(new NullProgressMonitor()); + performChange(change); + assertTrue("after: should exist", folder.getFolder(newName).exists()); + assertTrue("after: old should not exist", ! folder.getFolder(oldName).exists()); + assertEquals("after: child count", 2, folder.getFolder(newName).members().length); + } finally{ + performDummySearch(); + folder.getFolder(newName).delete(true, false, new NullProgressMonitor()); + } + } + + public void testFolder2() throws Exception{ + IFolder folder= (IFolder)getPackageP().getCorrespondingResource(); + String oldName= "a"; + String newName= "b"; + try{ + IFolder subFolder= folder.getFolder(oldName); + assertTrue("should not exist", ! subFolder.exists()); + subFolder.create(true, true, null); + assertTrue("should exist", subFolder.exists()); + + + Change change= new RenameResourceChange(subFolder.getFullPath(), newName); + change.initializeValidationData(new NullProgressMonitor()); + Change undo= performChange(change); + assertTrue("after: should exist", folder.getFolder(newName).exists()); + assertTrue("after: old should not exist", ! folder.getFolder(oldName).exists()); + + //--- + assertTrue("should be undoable", undo != null); + undo.initializeValidationData(new NullProgressMonitor()); + performChange(undo); + assertTrue("after undo: should exist", folder.getFolder(oldName).exists()); + assertTrue("after undo: old should not exist", ! folder.getFolder(newName).exists()); + } finally{ + performDummySearch(); + folder.getFolder(oldName).delete(true, false, new NullProgressMonitor()); + } + } + + public void testJavaProject01() throws Exception { + String oldName= "RenameResourceChangeTest"; + String newName= "RenameResourceChangeTest2"; + String linkName= "link"; + + IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot(); + IProject project= workspaceRoot.getProject(oldName); + IProject project2= workspaceRoot.getProject(newName); + try { + getPackageP().createCompilationUnit("A.java", "package p;\nclass A{}\n", false, null); + + project.create(null); + project.open(null); + IFolder link= project.getFolder(linkName); + link.createLink(getPackageP().getResource().getRawLocation(), IResource.NONE, null); + assertTrue(link.exists()); + + RenameResourceChange change= new RenameResourceChange(project.getFullPath(), newName); + change.initializeValidationData(new NullProgressMonitor()); + performChange(change); + + assertTrue("after: linked folder should exist", project2.getFolder(linkName).exists()); + assertTrue("after: linked folder should be linked", project2.getFolder(linkName).isLinked()); + assertTrue("after: linked folder should contain cu", project2.getFolder(linkName).getFile("A.java").exists()); + } finally { + performDummySearch(); + if (project.exists()) + project.delete(true, null); + if (project2.exists()) + project2.delete(true, null); + } + + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameSourceFolderChangeTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameSourceFolderChangeTests.java new file mode 100644 index 000000000..ded3231e3 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameSourceFolderChangeTests.java @@ -0,0 +1,132 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Path; + +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; + +import org.eclipse.jdt.internal.corext.refactoring.changes.RenameSourceFolderChange; + + +public class RenameSourceFolderChangeTests extends RefactoringTest { + + private static final Class clazz= RenameSourceFolderChangeTests.class; + + public RenameSourceFolderChangeTests(String name){ + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + public void test0() throws Exception { + String oldName= "oldName"; + String newName= "newName"; + + try{ + IJavaProject testProject= RefactoringTestSetup.getProject(); + IPackageFragmentRoot oldRoot= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), oldName); + + assertTrue("old folder should exist here", oldRoot.exists()); + + RenameSourceFolderChange change= new RenameSourceFolderChange(oldRoot, newName); + change.initializeValidationData(new NullProgressMonitor()); + performChange(change); + + assertTrue("old folder should not exist", ! oldRoot.exists()); + assertEquals("expected 3 pfr's", 3, testProject.getPackageFragmentRoots().length); + IPackageFragmentRoot[] newRoots= testProject.getPackageFragmentRoots(); + for (int i= 0; i < newRoots.length; i++){ + assertTrue("should exist " + i, newRoots[i].exists()); + } + } finally{ + JavaProjectHelper.removeSourceContainer(RefactoringTestSetup.getProject(), newName); + } + } + + public void test1() throws Exception { + String oldName1= "oldName1"; + String oldName2= "oldName2"; + String newName1= "newName"; + + try{ + + IJavaProject testProject= RefactoringTestSetup.getProject(); + IPackageFragmentRoot oldRoot1= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), oldName1); + IPackageFragmentRoot oldRoot2= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), oldName2); + + assertTrue("old folder should exist here", oldRoot1.exists()); + assertTrue("old folder 2 should exist here", oldRoot2.exists()); + + RenameSourceFolderChange change= new RenameSourceFolderChange(oldRoot1, newName1); + change.initializeValidationData(new NullProgressMonitor()); + performChange(change); + + assertTrue("old folder should not exist", ! oldRoot1.exists()); + assertEquals("expected 4 pfr's", 4, testProject.getPackageFragmentRoots().length); + IPackageFragmentRoot[] newRoots= testProject.getPackageFragmentRoots(); + for (int i= 0; i < newRoots.length; i++){ + //DebugUtils.dump(newRoots[i].getElementName()); + assertTrue("should exist " + i, newRoots[i].exists()); + if (i == 2) + assertEquals("3rd position should be:" + newName1, newName1, newRoots[i].getElementName()); + } + }finally{ + JavaProjectHelper.removeSourceContainer(RefactoringTestSetup.getProject(), newName1); + JavaProjectHelper.removeSourceContainer(RefactoringTestSetup.getProject(), oldName2); + } + } + + public void testBug129991() throws Exception { + IJavaProject project= JavaProjectHelper.createJavaProject("RenameSourceFolder", "bin"); + + try { + IPath projectPath= project.getPath(); + + IPath[] exclusion= new IPath[] { new Path("src/") }; + JavaProjectHelper.addToClasspath(project, JavaCore.newSourceEntry(projectPath, exclusion)); + IPackageFragmentRoot src= JavaProjectHelper.addSourceContainer(project, "src"); + + RenameSourceFolderChange change= new RenameSourceFolderChange(src, "src2"); + change.initializeValidationData(new NullProgressMonitor()); + performChange(change); + + assertTrue("src should not exist", ! src.exists()); + assertEquals("expected 2 pfr's", 2, project.getPackageFragmentRoots().length); + + IClasspathEntry[] rawClasspath= project.getRawClasspath(); + assertEquals(projectPath, rawClasspath[0].getPath()); + + assertEquals("src2/", rawClasspath[0].getExclusionPatterns()[0].toString()); + assertEquals(projectPath.append("src2/"), rawClasspath[1].getPath()); + } finally { + project.getProject().delete(true, null); + } + } + +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameStaticMethodTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameStaticMethodTests.java new file mode 100644 index 000000000..896c059ac --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameStaticMethodTests.java @@ -0,0 +1,284 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.Signature; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; + +public class RenameStaticMethodTests extends RefactoringTest { + private static final Class clazz= RenameStaticMethodTests.class; + private static final String REFACTORING_PATH= "RenameStaticMethod/"; + + private static final boolean BUG_83332_SPLIT_SINGLE_IMPORT= true; + + public RenameStaticMethodTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + private void helper1_0(String methodName, String newMethodName, String[] signatures) throws Exception{ + IType classA= getType(createCUfromTestFile(getPackageP(), "A"), "A"); + try{ + IMethod method= classA.getMethod(methodName, signatures); + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_METHOD); + descriptor.setJavaElement(method); + descriptor.setNewName(newMethodName); + descriptor.setUpdateReferences(true); + RefactoringStatus result= performRefactoring(descriptor); + assertNotNull("precondition was supposed to fail", result); + } finally{ + performDummySearch(); + classA.getCompilationUnit().delete(true, null); + } + } + + private void helper1() throws Exception{ + helper1_0("m", "k", new String[0]); + } + + private void helper2_0(String methodName, String newMethodName, String[] signatures, boolean updateReferences, boolean createDelegate) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + try{ + IType classA= getType(cu, "A"); + IMethod method= classA.getMethod(methodName, signatures); + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_METHOD); + descriptor.setUpdateReferences(updateReferences); + descriptor.setJavaElement(method); + descriptor.setNewName(newMethodName); + descriptor.setKeepOriginal(createDelegate); + descriptor.setDeprecateDelegate(true); + + assertEquals("was supposed to pass", null, performRefactoring(descriptor)); + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName("A")), cu.getSource()); + + assertTrue("anythingToUndo", RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("! anythingToRedo", !RefactoringCore.getUndoManager().anythingToRedo()); + //assertEquals("1 to undo", 1, Refactoring.getUndoManager().getRefactoringLog().size()); + + RefactoringCore.getUndoManager().performUndo(null, new NullProgressMonitor()); + assertEqualLines("invalid undo", getFileContents(getInputTestFileName("A")), cu.getSource()); + + assertTrue("! anythingToUndo", !RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("anythingToRedo", RefactoringCore.getUndoManager().anythingToRedo()); + //assertEquals("1 to redo", 1, Refactoring.getUndoManager().getRedoStack().size()); + + RefactoringCore.getUndoManager().performRedo(null, new NullProgressMonitor()); + assertEqualLines("invalid redo", getFileContents(getOutputTestFileName("A")), cu.getSource()); + } finally{ + performDummySearch(); + cu.delete(true, null); + } + } + private void helper2_0(String methodName, String newMethodName, String[] signatures) throws Exception{ + helper2_0(methodName, newMethodName, signatures, true, false); + } + + private void helper2(boolean updateReferences) throws Exception{ + helper2_0("m", "k", new String[0], updateReferences, false); + } + + private void helper2() throws Exception{ + helper2(true); + } + + private void helperDelegate() throws Exception{ + helper2_0("m", "k", new String[0], true, true); + } + + public void testFail0() throws Exception { + helper1(); + } + + public void testFail1() throws Exception{ + helper1(); + } + + public void testFail2() throws Exception{ + helper1(); + } + + //testFail3 deleted + + public void testFail4() throws Exception{ + helper1(); + } + + public void testFail5() throws Exception{ + helper1(); + } + + public void testFail6() throws Exception{ + helper1(); + } + + public void testFail7() throws Exception{ + helper1(); + } + + public void testFail8() throws Exception{ + helper1(); + } + + public void test0() throws Exception{ + helper2(); + } + + public void test1() throws Exception{ + helper2(); + } + + public void test2() throws Exception{ + helper2(); + } + + public void test3() throws Exception{ + helper2(); + } + + public void test4() throws Exception{ + helper2(); + } + + public void test5() throws Exception{ + helper2(); + } + + public void test6() throws Exception{ + helper2(); + } + + public void test7() throws Exception{ + helper2_0("m", "k", new String[]{Signature.SIG_INT}); + } + + public void test8() throws Exception{ + helper2_0("m", "k", new String[]{Signature.SIG_INT}); + } + + public void test9() throws Exception{ + helper2_0("m", "k", new String[]{Signature.SIG_INT}, false, false); + } + + public void test10() throws Exception{ +// printTestDisabledMessage("bug 40628"); +// if (true) return; + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); + + IType classB= getType(cuB, "B"); + IMethod method= classB.getMethod("method", new String[0]); + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_METHOD); + descriptor.setUpdateReferences(true); + descriptor.setJavaElement(method); + descriptor.setNewName("newmethod"); + + assertEquals("was supposed to pass", null, performRefactoring(descriptor)); + assertEqualLines("invalid renaming in A", getFileContents(getOutputTestFileName("A")), cuA.getSource()); + assertEqualLines("invalid renaming in B", getFileContents(getOutputTestFileName("B")), cuB.getSource()); + } + + public void test11() throws Exception{ +// printTestDisabledMessage("bug 40452"); +// if (true) return; + IPackageFragment packageA= getRoot().createPackageFragment("a", false, new NullProgressMonitor()); + IPackageFragment packageB= getRoot().createPackageFragment("b", false, new NullProgressMonitor()); + try { + ICompilationUnit cuA= createCUfromTestFile(packageA, "A"); + ICompilationUnit cuB= createCUfromTestFile(packageB, "B"); + + IType classA= getType(cuA, "A"); + IMethod method= classA.getMethod("method2", new String[0]); + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_METHOD); + descriptor.setUpdateReferences(true); + descriptor.setJavaElement(method); + descriptor.setNewName("fred"); + + assertEquals("was supposed to pass", null, performRefactoring(descriptor)); + assertEqualLines("invalid renaming in A", getFileContents(getOutputTestFileName("A")), cuA.getSource()); + assertEqualLines("invalid renaming in B", getFileContents(getOutputTestFileName("B")), cuB.getSource()); + } finally{ + packageA.delete(true, new NullProgressMonitor()); + packageB.delete(true, new NullProgressMonitor()); + } + } + + public void testUnicode01() throws Exception{ + helper2_0("e", "f", new String[]{}); + } + + public void testStaticImportFail0() throws Exception { + helper1(); + } + + public void testStaticImport1() throws Exception { + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "C"); + helper2(); + assertEqualLines("invalid renaming in C", getFileContents(getOutputTestFileName("C")), cuA.getSource()); + } + + public void testStaticImport2() throws Exception { + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "C"); + helper2(); + assertEqualLines("invalid renaming in C", getFileContents(getOutputTestFileName("C")), cuA.getSource()); + } + + public void testStaticImport3() throws Exception { + if (BUG_83332_SPLIT_SINGLE_IMPORT) { + printTestDisabledMessage("BUG_83332_SPLIT_SINGLE_IMPORT"); + return; + } + helper2(); + } + + public void testStaticImport4() throws Exception { + helper2(); + } + + public void testStaticImport5() throws Exception { + if (BUG_83332_SPLIT_SINGLE_IMPORT) { + printTestDisabledMessage("BUG_83332_SPLIT_SINGLE_IMPORT"); + return; + } + helper2(); + } + + public void testDelegate01() throws Exception { + // simple static delegate + helperDelegate(); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTempTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTempTests.java new file mode 100644 index 000000000..73e05db0e --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTempTests.java @@ -0,0 +1,580 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.ILocalVariable; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.SourceRange; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; + +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +public class RenameTempTests extends RefactoringTest{ + private static final boolean BUG_checkDeclInNestedClass= true; + private static final boolean BUG_checkShadowing= true; + + private static final Class clazz= RenameTempTests.class; + private static final String REFACTORING_PATH= "RenameTemp/"; + + + public RenameTempTests(String name){ + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + private String getSimpleTestFileName(boolean canRename, boolean input){ + String fileName = "A_" + getName(); + if (canRename) + fileName += input ? "_in": "_out"; + return fileName + ".java"; + } + + private String getTestFileName(boolean canRename, boolean input){ + String fileName= TEST_PATH_PREFIX + getRefactoringPath(); + fileName += (canRename ? "canRename/": "cannotRename/"); + return fileName + getSimpleTestFileName(canRename, input); + } + + //------------ + protected ICompilationUnit createCUfromTestFile(IPackageFragment pack, boolean canRename, boolean input) throws Exception { + return createCU(pack, getSimpleTestFileName(canRename, input), getFileContents(getTestFileName(canRename, input))); + } + + private ISourceRange getSelection(ICompilationUnit cu) throws Exception{ + String source= cu.getSource(); + //Warning: this *includes* the SQUARE_BRACKET_OPEN! + int offset= source.indexOf(AbstractSelectionTestCase.SQUARE_BRACKET_OPEN); + int end= source.indexOf(AbstractSelectionTestCase.SQUARE_BRACKET_CLOSE); + return new SourceRange(offset, end - offset); + } + + private void helper1(String newName, boolean updateReferences, ISourceRange selection, ICompilationUnit cu) throws Exception { + IJavaElement[] elements= cu.codeSelect(selection.getOffset(), selection.getLength()); + assertEquals(1, elements.length); + assertTrue(elements[0].getClass().toString(), elements[0] instanceof ILocalVariable); + + final RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_LOCAL_VARIABLE); + descriptor.setJavaElement(elements[0]); + descriptor.setNewName(newName); + descriptor.setUpdateReferences(updateReferences); + + final RefactoringStatus status= new RefactoringStatus(); + final Refactoring refactoring= descriptor.createRefactoring(status); + assertTrue("status should be ok", status.isOK()); + assertNotNull("refactoring should not be null", refactoring); + + RefactoringStatus result= performRefactoring(refactoring); + assertEquals("precondition was supposed to pass", null, result); + + IPackageFragment pack= (IPackageFragment) cu.getParent(); + String newCuName= getSimpleTestFileName(true, true); + ICompilationUnit newcu= pack.getCompilationUnit(newCuName); + assertTrue(newCuName + " does not exist", newcu.exists()); + assertEqualLines("incorrect renaming", getFileContents(getTestFileName(true, false)), newcu.getSource()); + } + + private void helper1(String newName, boolean updateReferences) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + helper1(newName, updateReferences, getSelection(cu), cu); + } + + private void helper1(String newName, boolean updateReferences, int startLine, int startColumn, int endLine, int endColumn) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + helper1(newName, updateReferences, selection, cu); + } + + private void helper1(String newName) throws Exception{ + helper1(newName, true); + } + + private void failHelperNoElement() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), false, true); + ISourceRange selection= getSelection(cu); + IJavaElement[] elements= cu.codeSelect(selection.getOffset(), selection.getLength()); + assertEquals(0, elements.length); + } + + private void failTestHelper(String newName, boolean updateReferences, ICompilationUnit cu, ISourceRange selection) throws Exception { + IJavaElement[] elements= cu.codeSelect(selection.getOffset(), selection.getLength()); + assertEquals(1, elements.length); + assertTrue(elements[0].getClass().toString(), elements[0] instanceof ILocalVariable); + + final RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_LOCAL_VARIABLE); + descriptor.setJavaElement(elements[0]); + descriptor.setNewName(newName); + descriptor.setUpdateReferences(updateReferences); + + final RefactoringStatus status= new RefactoringStatus(); + final Refactoring refactoring= descriptor.createRefactoring(status); + assertTrue("status should be ok", status.isOK()); + assertNotNull("refactoring should not be null", refactoring); + + RefactoringStatus result= performRefactoring(refactoring); + assertNotNull("precondition was supposed to fail", result); + } + + private void helper2(String newName, boolean updateReferences) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), false, true); + ISourceRange selection= getSelection(cu); + failTestHelper(newName, updateReferences, cu, selection); + } + + private void helper2(String newName) throws Exception{ + helper2(newName, true); + } + + public void test0() throws Exception{ + helper1("j"); + } + + public void test1() throws Exception{ + helper1("j"); + } + +// public void test2() throws Exception{ +// Map renaming= new HashMap(); +// renaming.put("x", "j"); +// renaming.put("y", "k"); +// helper1(renaming, new String[0]); +// } + + public void test3() throws Exception{ + helper1("j1"); + } + + public void test4() throws Exception{ + helper1("k"); + } + + public void test5() throws Exception{ + helper1("k"); + } + + public void test6() throws Exception{ + helper1("k"); + } + + public void test7() throws Exception{ + helper1("k"); + } +// +// //8, 9, 10 removed +// +// + public void test11() throws Exception{ + helper1("j"); + } + + public void test12() throws Exception{ + helper1("j"); + } + + public void test13() throws Exception{ + helper1("j"); + } + + public void test14() throws Exception{ + helper1("j"); + } + +// disabled +// public void test15() throws Exception{ +// Map renaming= new HashMap(); +// renaming.put("i", "j"); +// renaming.put("j", "i"); +// helper1(renaming, new String[0]); +// } +// + public void test16() throws Exception{ + helper1("j"); + } + +// disabled +// public void test17() throws Exception{ +// Map renaming= new HashMap(); +// renaming.put("i", "j"); +// renaming.put("j", "i"); +// helper1(renaming, new String[0]); +// } +// + public void test18() throws Exception{ + helper1("j"); + } + + public void test19() throws Exception{ + helper1("j"); + } + + public void test20() throws Exception{ + helper1("j"); + } + + public void test21() throws Exception{ + helper1("j"); + } + + public void test22() throws Exception{ + helper1("j"); + } + +// disabled +// public void test23() throws Exception{ +// Map renaming= new HashMap(); +// renaming.put("i", "j"); +// renaming.put("j", "i"); +// helper1(renaming, new String[0]); +// } + + public void test24() throws Exception{ + helper1("j"); + } + + public void test25() throws Exception{ + helper1("j"); + } + + public void test26() throws Exception{ + helper1("j"); + } + +// deleted - incorrect. see testFail26 +// public void test27() throws Exception{ +// helper1("j"); +// } + + public void test28() throws Exception{ + helper1("j"); + } + + public void test29() throws Exception{ + helper1("b"); + } + + public void test30() throws Exception{ + helper1("k"); + } + + public void test31() throws Exception{ + helper1("kk"); + } + + public void test32() throws Exception{ + helper1("j"); + } + + public void test33() throws Exception{ + helper1("b", false); + } + + public void test34() throws Exception{ + helper1("j"); + } + + public void test35() throws Exception{ +// printTestDisabledMessage("regression test for bug#9001"); + helper1("test2"); + } + + public void test36() throws Exception{ +// printTestDisabledMessage("regression test for bug#7630"); + helper1("j", true, 5, 13, 5, 14); + } + + public void test37() throws Exception{ +// printTestDisabledMessage("regression test for bug#7630"); + helper1("j", true, 5, 16, 5, 17); + } + + public void test38() throws Exception{ +// printTestDisabledMessage("regression test for Bug#11453"); + helper1("i", true, 7, 12, 7, 13); + } + + public void test39() throws Exception{ +// printTestDisabledMessage("regression test for Bug#11440"); + helper1("j", true, 7, 16, 7, 18); + } + + public void test40() throws Exception{ +// printTestDisabledMessage("regression test for Bug#10660"); + helper1("j", true, 4, 16, 4, 17); + } + + public void test41() throws Exception{ +// printTestDisabledMessage("regression test for Bug#10660"); + helper1("j", true, 3, 17, 3, 18); + } + + public void test42() throws Exception{ +// printTestDisabledMessage("regression test for Bug#10660"); + helper1("j", true, 3, 25, 3, 26); + } + + public void test43() throws Exception{ +// printTestDisabledMessage("regression test for Bug#10660"); + helper1("j", true, 4, 23, 4, 24); + } + + public void test44() throws Exception{ +// printTestDisabledMessage("regression test for Bug#12200"); + helper1("j", true, 6, 11, 6, 14); + } + + public void test45() throws Exception{ +// printTestDisabledMessage("regression test for Bug#12210"); + helper1("j", true, 4, 14, 4, 14); + } + + public void test46() throws Exception{ +// printTestDisabledMessage("regression test for Bug#12210"); + helper1("j", true, 5, 18, 5, 18); + } + + public void test47() throws Exception{ +// printTestDisabledMessage("regression test for Bug#17922"); + helper1("newname", true, 7, 13, 7, 17); + } + + public void test48() throws Exception{ +// printTestDisabledMessage("regression test for Bug#22938"); + helper1("newname", true, 4, 16, 4, 20); + } + + public void test49() throws Exception{ +// printTestDisabledMessage("regression test for Bug#30923 "); + helper1("newname", true, 4, 16, 4, 20); + } + + public void test50() throws Exception{ +// printTestDisabledMessage("regression test for Bug#30923 "); + helper1("newname", true, 4, 16, 4, 20); + } + + public void test51() throws Exception { +// printTestDisabledMessage("regression test for Bug#47822"); + helper1("qwerty", true, 5, 19, 5, 20); + } + + public void test52() throws Exception{ + helper1("j"); + } + + public void test53() throws Exception{ +// printTestDisabledMessage("bug#19851"); + helper1("locker"); + } + + public void test54() throws Exception{ + helper1("obj"); + } + + public void test55() throws Exception{ + helper1("t"); + } + + public void test56() throws Exception{ + helper1("param"); + } + + public void test57() throws Exception{ + helper1("param"); + } + + public void test58() throws Exception{ + helper1("param"); + } + + public void test59() throws Exception{ + helper1("thing"); + } + + public void test60() throws Exception{ + helper1("param"); + } + + public void test61() throws Exception{ + helper1("x"); + } + + public void test62() throws Exception { +// printTestDisabledMessage("bug#47822"); + helper1("xxx"); + } + + public void test63() throws Exception { + // regression test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=144426 + helper1("xxx"); + } + + public void test64() throws Exception { + // regression test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=144426 + helper1("xxx"); + } + +// ----- + public void testFail0() throws Exception{ + if (BUG_checkDeclInNestedClass) { + printTestDisabledMessage("fails - must revisit"); + return; + } + helper2("j"); + } + + public void testFail1() throws Exception{ + failHelperNoElement(); + } + + public void testFail2() throws Exception{ + helper2("i"); + } + + public void testFail3() throws Exception{ + helper2("9"); + } + + public void testFail4() throws Exception{ + helper2("j"); + } + + public void testFail5() throws Exception{ + helper2("j"); + } + + public void testFail6() throws Exception{ + if (BUG_checkDeclInNestedClass) { + printTestDisabledMessage("fails - must revisit"); + return; + } + helper2("j"); + } + + public void testFail7() throws Exception{ + helper2("j"); + } + + public void testFail8() throws Exception{ + helper2("j"); + } + + public void testFail9() throws Exception{ + helper2("j"); + } + + public void testFail10() throws Exception{ + failHelperNoElement(); + } + +// disabled - it's allowed now +// public void testFail11() throws Exception{ +// helper2("uu"); +// } + + public void testFail12() throws Exception{ +// printTestDisabledMessage("http://dev.eclipse.org/bugs/show_bug.cgi?id=11638"); + helper2("j"); + } + + public void testFail13() throws Exception{ + helper2("j"); + } + + public void testFail14() throws Exception{ + helper2("j"); + } + + public void testFail15() throws Exception{ + helper2("j"); + } + + public void testFail16() throws Exception{ + helper2("j"); + } + + public void testFail17() throws Exception{ + helper2("j"); + } + + public void testFail18() throws Exception{ + helper2("j"); + } + + public void testFail19() throws Exception{ + helper2("j"); + } + + public void testFail20() throws Exception{ + helper2("j"); + } + +// disabled - it's allowed now +// public void testFail21() throws Exception{ +// helper2("j"); +// } + + public void testFail22() throws Exception{ + failHelperNoElement(); + } + +// disabled - it's allowed now +// public void testFail23() throws Exception{ +// helper2("j"); +// } + + public void testFail24() throws Exception{ + //printTestDisabledMessage("compile errors are ok now"); + helper2("t"); //name collision + } + + public void testFail25() throws Exception{ + helper2("j"); + } + + public void testFail26() throws Exception{ + if (BUG_checkShadowing) { + printTestDisabledMessage("Test disabled until it is clear how 1.4 treats this"); + return; + } + helper2("j"); + } + + public void testFail27() throws Exception{ + helper2("j"); + } + + public void testFail28() throws Exception{ + helper2("j"); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTests.java new file mode 100644 index 000000000..044b1c7f4 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTests.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + + +public class RenameTests { + + private static final Class clazz= RenameTests.class; + + public static Test suite() { + TestSuite suite= new TestSuite(clazz.getName()); + + suite.addTest(RefactoringScannerTests.suite()); + suite.addTest(RenamingNameSuggestorTests.suite()); + + suite.addTest(RenameVirtualMethodInClassTests.suite()); + suite.addTest(RenameMethodInInterfaceTests.suite()); + suite.addTest(RenamePrivateMethodTests.suite()); + suite.addTest(RenameStaticMethodTests.suite()); + suite.addTest(RenameParametersTests.suite()); + suite.addTest(RenameTypeTests.suite()); + suite.addTest(RenamePackageTests.suite()); + suite.addTest(RenamePrivateFieldTests.suite()); + suite.addTest(RenameTypeParameterTests.suite()); + suite.addTest(RenameNonPrivateFieldTests.suite()); + suite.addTest(RenameJavaProjectTests.suite()); + + return suite; + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTypeParameterTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTypeParameterTests.java new file mode 100644 index 000000000..cd36432a5 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTypeParameterTests.java @@ -0,0 +1,216 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.ITypeParameter; + +import org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeParameterProcessor; + +public class RenameTypeParameterTests extends RefactoringTest { + + private static final Class clazz= RenameTypeParameterTests.class; + + private static final String REFACTORING_PATH= "RenameTypeParameter/"; + + public static Test setUpTest(Test someTest) { + return new Java15Setup(someTest); + } + + public static Test suite() { + return new Java15Setup(new TestSuite(clazz)); + } + + public RenameTypeParameterTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + private void helper1(String parameterName, String newParameterName, String typeName, boolean references) throws Exception { + IType declaringType= getType(createCUfromTestFile(getPackageP(), "A"), typeName); + RenameTypeParameterProcessor processor= new RenameTypeParameterProcessor(declaringType.getTypeParameter(parameterName)); + RenameRefactoring refactoring= new RenameRefactoring(processor); + processor.setNewElementName(newParameterName); + processor.setUpdateReferences(references); + RefactoringStatus result= performRefactoring(refactoring); + assertNotNull("precondition was supposed to fail", result); + } + + private void helper1(String parameterName, String newParameterName, String typeName, String methodName, String[] methodSignature, boolean references) throws Exception { + IType declaringType= getType(createCUfromTestFile(getPackageP(), "A"), typeName); + IMethod[] declaringMethods= getMethods(declaringType, new String[] { methodName}, new String[][] { methodSignature}); + RenameTypeParameterProcessor processor= new RenameTypeParameterProcessor(declaringMethods[0].getTypeParameter(parameterName)); + RenameRefactoring refactoring= new RenameRefactoring(processor); + processor.setNewElementName(newParameterName); + processor.setUpdateReferences(references); + RefactoringStatus result= performRefactoring(refactoring); + assertNotNull("precondition was supposed to fail", result); + } + + private void helper2(String parameterName, String newParameterName, String typeName, boolean references) throws Exception { + ParticipantTesting.reset(); + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType declaringType= getType(cu, typeName); + ITypeParameter typeParameter= declaringType.getTypeParameter(parameterName); + RenameTypeParameterProcessor processor= new RenameTypeParameterProcessor(typeParameter); + RenameRefactoring refactoring= new RenameRefactoring(processor); + processor.setNewElementName(newParameterName); + processor.setUpdateReferences(references); + + RefactoringStatus result= performRefactoring(refactoring); + assertEquals("was supposed to pass", null, result); + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName("A")), cu.getSource()); + + assertTrue("anythingToUndo", RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("! anythingToRedo", !RefactoringCore.getUndoManager().anythingToRedo()); + + RefactoringCore.getUndoManager().performUndo(null, new NullProgressMonitor()); + assertEqualLines("invalid undo", getFileContents(getInputTestFileName("A")), cu.getSource()); + + assertTrue("! anythingToUndo", !RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("anythingToRedo", RefactoringCore.getUndoManager().anythingToRedo()); + + RefactoringCore.getUndoManager().performRedo(null, new NullProgressMonitor()); + assertEqualLines("invalid redo", getFileContents(getOutputTestFileName("A")), cu.getSource()); + } + + private void helper2(String parameterName, String newParameterName, String typeName, String methodName, String[] methodSignature, boolean references) throws Exception { + ParticipantTesting.reset(); + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType declaringType= getType(cu, typeName); + IMethod[] declaringMethods= getMethods(declaringType, new String[] { methodName}, new String[][] { methodSignature}); + ITypeParameter typeParameter= declaringMethods[0].getTypeParameter(parameterName); + RenameTypeParameterProcessor processor= new RenameTypeParameterProcessor(typeParameter); + RenameRefactoring refactoring= new RenameRefactoring(processor); + processor.setNewElementName(newParameterName); + processor.setUpdateReferences(references); + + RefactoringStatus result= performRefactoring(refactoring); + assertEquals("was supposed to pass", null, result); + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName("A")), cu.getSource()); + + assertTrue("anythingToUndo", RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("! anythingToRedo", !RefactoringCore.getUndoManager().anythingToRedo()); + + RefactoringCore.getUndoManager().performUndo(null, new NullProgressMonitor()); + assertEqualLines("invalid undo", getFileContents(getInputTestFileName("A")), cu.getSource()); + + assertTrue("! anythingToUndo", !RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("anythingToRedo", RefactoringCore.getUndoManager().anythingToRedo()); + + RefactoringCore.getUndoManager().performRedo(null, new NullProgressMonitor()); + assertEqualLines("invalid redo", getFileContents(getOutputTestFileName("A")), cu.getSource()); + } + + public void test0() throws Exception { + helper2("T", "S", "A", true); + } + + public void test1() throws Exception { + helper2("T", "S", "A", true); + } + + public void test2() throws Exception { + helper2("T", "S", "A", false); + } + + public void test3() throws Exception { + helper2("T", "S", "A", true); + } + + public void test4() throws Exception { + helper2("T", "S", "A", false); + } + + public void test5() throws Exception { + helper2("T", "S", "A", true); + } + + public void test6() throws Exception { + helper2("S", "T", "A", true); + } + + public void test7() throws Exception { + helper2("T", "S", "A", false); + } + + public void test8() throws Exception { + helper2("S", "T", "A", false); + } + + public void test9() throws Exception { + helper2("T", "S", "A", "f", new String[] { "QT;"}, true); + } + + public void test10() throws Exception { + helper2("T", "S", "B", "f", new String[] { "QT;"}, true); + } + + public void test11() throws Exception { + helper2("T", "S", "A", "f", new String[] { "QT;"}, false); + } + + public void test12() throws Exception { + helper2("T", "S", "B", "f", new String[] { "QT;"}, false); + } + + public void test13() throws Exception { + helper2("T", "S", "A", true); + } + + public void test14() throws Exception { + helper2("ELEMENT", "E", "A", true); + } + + public void test15() throws Exception { + helper2("T", "S", "A", true); + } + +// ------------------------------------------------ + + public void testFail0() throws Exception { + helper1("T", "S", "A", true); + } + + public void testFail1() throws Exception { + helper1("T", "S", "A", true); + } + + public void testFail2() throws Exception { + helper1("T", "S", "A", true); + } + + public void testFail3() throws Exception { + helper1("T", "S", "A", true); + } + + public void testFail4() throws Exception { + helper1("T", "S", "A", true); + } + + public void testFail5() throws Exception { + helper1("T", "S", "B", "f", new String[] { "QT;"}, true); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTypeTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTypeTests.java new file mode 100644 index 000000000..3c10d78b6 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTypeTests.java @@ -0,0 +1,1671 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Platform; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.RenameArguments; +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.ILocalVariable; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.refactoring.IJavaElementMapper; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; +import org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor; +import org.eclipse.jdt.internal.corext.refactoring.rename.RenamingNameSuggestor; +import org.eclipse.jdt.internal.corext.refactoring.tagging.INameUpdating; + +import org.eclipse.jdt.ui.tests.refactoring.infra.DebugUtils; + +public class RenameTypeTests extends RefactoringTest { + + private static final Class clazz= RenameTypeTests.class; + private static final String REFACTORING_PATH= "RenameType/"; + + public RenameTypeTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + private IType getClassFromTestFile(IPackageFragment pack, String className) throws Exception{ + return getType(createCUfromTestFile(pack, className), className); + } + + private RenameJavaElementDescriptor createRefactoringDescriptor(IType type, String newName) { + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_TYPE); + descriptor.setJavaElement(type); + descriptor.setNewName(newName); + descriptor.setUpdateReferences(true); + return descriptor; + } + + private void helper1_0(String className, String newName) throws Exception { + IType classA= getClassFromTestFile(getPackageP(), className); + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, newName)); + assertNotNull("precondition was supposed to fail", result); + if (fIsVerbose) + DebugUtils.dump("result: " + result); + } + + private void helper1() throws Exception{ + helper1_0("A", "B"); + } + + private String[] helperWithTextual(String oldCuName, String oldName, String newName, String newCUName, boolean updateReferences, boolean updateTextualMatches) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), oldCuName); + IType classA= getType(cu, oldName); + IJavaElement[] classAMembers= classA.getChildren(); + + IPackageFragment pack= (IPackageFragment)cu.getParent(); + String[] renameHandles= null; + if (classA.getDeclaringType() == null && cu.getElementName().startsWith(classA.getElementName())) { + renameHandles= ParticipantTesting.createHandles(classA, cu, cu.getResource()); + } else { + renameHandles= ParticipantTesting.createHandles(classA); + } + RenameJavaElementDescriptor descriptor= createRefactoringDescriptor(classA, newName); + descriptor.setUpdateReferences(updateReferences); + descriptor.setUpdateTextualOccurrences(updateTextualMatches); + Refactoring refactoring= createRefactoring(descriptor); + assertEquals("was supposed to pass", null, performRefactoring(refactoring)); + ICompilationUnit newcu= pack.getCompilationUnit(newCUName + ".java"); + assertTrue("cu " + newcu.getElementName()+ " does not exist", newcu.exists()); + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName(newCUName)), newcu.getSource()); + + INameUpdating nameUpdating= ((INameUpdating)refactoring.getAdapter(INameUpdating.class)); + IType newElement = (IType) nameUpdating.getNewElement(); + assertTrue("new element does not exist:\n" + newElement.toString(), newElement.exists()); + + checkMappers(refactoring, classA, newCUName + ".java", classAMembers); + + return renameHandles; + } + + private String[] helper2_0(String oldName, String newName, String newCUName, boolean updateReferences) throws Exception{ + return helperWithTextual(oldName, oldName, newName, newCUName, updateReferences, false); + } + + private void helper2(String oldName, String newName, boolean updateReferences) throws Exception{ + helper2_0(oldName, newName, newName, updateReferences); + } + + private String[] helper2(String oldName, String newName) throws Exception{ + return helper2_0(oldName, newName, newName, true); + } + + // <--------------------- Similarly named elements ----------------------------> + + protected void setUp() throws Exception { + super.setUp(); + setSomeFieldOptions(getPackageP().getJavaProject(), "f", "Suf1", false); + setSomeFieldOptions(getPackageP().getJavaProject(), "fs", "_suffix", true); + setSomeLocalOptions(getPackageP().getJavaProject(), "lv", "_lv"); + setSomeArgumentOptions(getPackageP().getJavaProject(), "pm", "_pm"); + fIsPreDeltaTest= true; + } + + private void helper3(String oldName, String newName, boolean updateRef, boolean updateTextual, boolean updateSimilar) throws JavaModelException, CoreException, IOException, Exception { + helper3(oldName, newName, updateRef, updateTextual, updateSimilar, null); + } + + private void helper3(String oldName, String newName, boolean updateRef, boolean updateTextual, boolean updateSimilar, String nonJavaFiles) throws JavaModelException, CoreException, IOException, Exception { + RefactoringDescriptor descriptor= initWithAllOptions(oldName, oldName, newName, updateRef, updateTextual, updateSimilar, nonJavaFiles, RenamingNameSuggestor.STRATEGY_EMBEDDED); + Refactoring ref= createRefactoring(descriptor); + RefactoringStatus status= performRefactoring(ref); + assertNull("was supposed to pass", status); + checkResultInClass(newName); + checkMappedSimilarElementsExist(ref); + } + + private void helper3_inner(String oldName, String oldInnerName, String newName, String innerNewName, boolean updateRef, boolean updateTextual, boolean updateSimilar, String nonJavaFiles) throws JavaModelException, CoreException, IOException, Exception { + RefactoringDescriptor descriptor= initWithAllOptions(oldName, oldInnerName, innerNewName, updateRef, updateTextual, updateSimilar, nonJavaFiles, RenamingNameSuggestor.STRATEGY_EMBEDDED); + Refactoring ref= createRefactoring(descriptor); + assertNull("was supposed to pass", performRefactoring(ref)); + checkResultInClass(newName); + checkMappedSimilarElementsExist(ref); + } + + private void checkMappedSimilarElementsExist(Refactoring ref) { + RenameTypeProcessor rtp= (RenameTypeProcessor) ((RenameRefactoring) ref).getProcessor(); + IJavaElementMapper mapper= (IJavaElementMapper) rtp.getAdapter(IJavaElementMapper.class); + IJavaElement[] similarElements= rtp.getSimilarElements(); + if (similarElements == null) + return; + for (int i= 0; i < similarElements.length; i++) { + IJavaElement element= similarElements[i]; + if (! (element instanceof ILocalVariable)) { + IJavaElement newElement= mapper.getRefactoredJavaElement(element); + assertTrue(newElement.exists()); + assertFalse(element.exists()); + } + } + + } + + private void helper3_fail(String oldName, String newName, boolean updateSimilar, boolean updateTextual, boolean updateRef, int matchStrategy) throws JavaModelException, CoreException, IOException, Exception { + RefactoringDescriptor descriptor= initWithAllOptions(oldName, oldName, newName, updateRef, updateTextual, updateSimilar, null, matchStrategy); + assertNotNull("was supposed to fail", performRefactoring(descriptor)); + } + + private void helper3_fail(String oldName, String newName, boolean updateSimilar, boolean updateTextual, boolean updateRef) throws JavaModelException, CoreException, IOException, Exception { + RefactoringDescriptor descriptor= initWithAllOptions(oldName, oldName, newName, updateRef, updateTextual, updateSimilar, null, RenamingNameSuggestor.STRATEGY_SUFFIX); + assertNotNull("was supposed to fail", performRefactoring(descriptor)); + } + + private RefactoringDescriptor initWithAllOptions(String oldName, String innerOldName, String innerNewName, boolean updateReferences, boolean updateTextualMatches, boolean updateSimilar, String nonJavaFiles, int matchStrategy) throws Exception, JavaModelException, CoreException { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), oldName); + IType classA= getType(cu, innerOldName); + RenameJavaElementDescriptor descriptor= createRefactoringDescriptor(classA, innerNewName); + setTheOptions(descriptor, updateReferences, updateTextualMatches, updateSimilar, nonJavaFiles, matchStrategy); + return descriptor; + } + + private void setTheOptions(RenameJavaElementDescriptor descriptor, boolean updateReferences, boolean updateTextualMatches, boolean updateSimilar, String nonJavaFiles, int matchStrategy) { + descriptor.setUpdateReferences(updateReferences); + descriptor.setUpdateTextualOccurrences(updateTextualMatches); + if (nonJavaFiles!=null) { + descriptor.setUpdateQualifiedNames(true); + descriptor.setFileNamePatterns(nonJavaFiles); + } + descriptor.setUpdateSimilarDeclarations(updateSimilar); + descriptor.setMatchStrategy(matchStrategy); + } + + private void checkResultInClass(String typeName) throws JavaModelException, IOException { + ICompilationUnit newcu= getPackageP().getCompilationUnit(typeName + ".java"); + assertTrue("cu " + newcu.getElementName()+ " does not exist", newcu.exists()); + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName(typeName)), newcu.getSource()); + } + + private void setSomeFieldOptions(IJavaProject project, String prefixes, String suffixes, boolean forStatic) { + if (forStatic) { + project.setOption(JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES, prefixes); + project.setOption(JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES, suffixes); + } + else { + project.setOption(JavaCore.CODEASSIST_FIELD_PREFIXES, prefixes); + project.setOption(JavaCore.CODEASSIST_FIELD_SUFFIXES, suffixes); + } + } + + private void setSomeLocalOptions(IJavaProject project, String prefixes, String suffixes) { + project.setOption(JavaCore.CODEASSIST_LOCAL_PREFIXES, prefixes); + project.setOption(JavaCore.CODEASSIST_LOCAL_SUFFIXES, suffixes); + } + + private void setSomeArgumentOptions(IJavaProject project, String prefixes, String suffixes) { + project.setOption(JavaCore.CODEASSIST_ARGUMENT_PREFIXES, prefixes); + project.setOption(JavaCore.CODEASSIST_ARGUMENT_SUFFIXES, suffixes); + } + + // </------------------------------------ Similarly named elements ---------------------------------> + + public void testIllegalInnerClass() throws Exception { + helper1(); + } + + public void testIllegalTypeName1() throws Exception { + helper1_0("A", "X "); + } + + public void testIllegalTypeName2() throws Exception { + helper1_0("A", " X"); + } + + public void testIllegalTypeName3() throws Exception { + helper1_0("A", "34"); + } + + public void testIllegalTypeName4() throws Exception { + helper1_0("A", "this"); + } + + public void testIllegalTypeName5() throws Exception { + helper1_0("A", "fred"); + } + + public void testIllegalTypeName6() throws Exception { + helper1_0("A", "class"); + } + + public void testIllegalTypeName7() throws Exception { + helper1_0("A", "A.B"); + } + + public void testIllegalTypeName8() throws Exception { + helper1_0("A", "A$B"); + } + + public void testIllegalTypeName9() throws Exception { + if (Platform.getOS().equals(Platform.OS_WIN32)) + helper1_0("A", "aux"); + } + + public void testNoOp() throws Exception { + helper1_0("A", "A"); + } + + public void testWrongArg1() throws Exception { + IllegalArgumentException result= null; + try { + helper1_0("A", ""); + } catch (IllegalArgumentException exception) { + result= exception; + } + assertNotNull("empty name was supposed to trigger IAE", result); + } + + public void testFail0() throws Exception { + helper1(); + } + + public void testFail1() throws Exception { + helper1(); + } + + public void testFail2() throws Exception { + helper1(); + } + + public void testFail3() throws Exception { + helper1(); + } + + public void testFail4() throws Exception { + IType classA= getClassFromTestFile(getPackageP(), "A"); + getClassFromTestFile(getPackageP(), "B"); + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail5() throws Exception { + IType classA= getClassFromTestFile(getPackageP(), "A"); + getClassFromTestFile(getPackageP(), "B"); + getClassFromTestFile(getPackageP(), "C"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail6() throws Exception { + IType classA= getClassFromTestFile(getPackageP(), "A"); + getClassFromTestFile(getPackageP(), "B"); + getClassFromTestFile(getPackageP(), "C"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail7() throws Exception { + helper1(); + } + + public void testFail8() throws Exception { + IType classA= getClassFromTestFile(getPackageP(), "A"); + getClassFromTestFile(getPackageP(), "B"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail9() throws Exception { + helper1(); + } + + public void testFail10() throws Exception { + helper1(); + } + + public void testFail11() throws Exception { + helper1(); + } + + public void testFail12() throws Exception { + helper1(); + } + + public void testFail16() throws Exception { + helper1(); + } + + public void testFail17() throws Exception { + helper1(); + } + + public void testFail18() throws Exception { + helper1(); + } + + public void testFail19() throws Exception { + helper1(); + } + + public void testFail20() throws Exception { + IPackageFragment packageP1= getRoot().createPackageFragment("p1", true, null); + IPackageFragment packageP2= getRoot().createPackageFragment("p2", true, null); + + IType classA= getClassFromTestFile(packageP1, "A"); + getClassFromTestFile(packageP2, "AA"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail22() throws Exception { + IType classA= getClassFromTestFile(getPackageP(), "A"); + getClassFromTestFile(getPackageP(), "B"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail23() throws Exception { + IPackageFragment packageP1= getRoot().createPackageFragment("p1", true, null); + IPackageFragment packageP2= getRoot().createPackageFragment("p2", true, null); + IPackageFragment packageP3= getRoot().createPackageFragment("p3", true, null); + + IType classA= getClassFromTestFile(packageP1, "A"); + getClassFromTestFile(packageP3, "B"); + getClassFromTestFile(packageP2, "Bogus"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail24() throws Exception { + IPackageFragment packageP1= getRoot().createPackageFragment("p1", true, null); + IPackageFragment packageP2= getRoot().createPackageFragment("p2", true, null); + + IType classA= getClassFromTestFile(packageP1, "A"); + getClassFromTestFile(packageP2, "B"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail25() throws Exception { + IPackageFragment packageP1= getRoot().createPackageFragment("p1", true, null); + IPackageFragment packageP2= getRoot().createPackageFragment("p2", true, null); + + IType classA= getClassFromTestFile(packageP1, "A"); + getClassFromTestFile(packageP2, "B"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail26() throws Exception { + IPackageFragment packageP1= getRoot().createPackageFragment("p1", true, null); + IPackageFragment packageP2= getRoot().createPackageFragment("p2", true, null); + + IType classA= getClassFromTestFile(packageP1, "A"); + getClassFromTestFile(packageP2, "B"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail27() throws Exception { + IPackageFragment packageP1= getRoot().createPackageFragment("p1", true, null); + IPackageFragment packageP2= getRoot().createPackageFragment("p2", true, null); + + IType classA= getClassFromTestFile(packageP1, "A"); + getClassFromTestFile(packageP2, "B"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail28() throws Exception { + printTestDisabledMessage("obscuring"); +// helper1(); + } + + public void testFail29() throws Exception { + printTestDisabledMessage("obscuring"); +// helper1(); + } + + public void testFail30() throws Exception { + printTestDisabledMessage("obscuring"); +// helper1(); + } + + public void testFail31() throws Exception { + IPackageFragment packageP1= getRoot().createPackageFragment("p1", true, null); + IPackageFragment packageP2= getRoot().createPackageFragment("p2", true, null); + IPackageFragment packageP3= getRoot().createPackageFragment("p3", true, null); + + IType classA= getClassFromTestFile(packageP1, "A"); + getClassFromTestFile(packageP2, "B"); + getClassFromTestFile(packageP3, "C"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail32() throws Exception { + IType classA= getClassFromTestFile(getPackageP(), "A"); + IPackageFragment packageP1= getRoot().createPackageFragment("p1", true, null); + getClassFromTestFile(packageP1, "B"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail33() throws Exception { + helper1(); + } + + public void testFail34() throws Exception { + printTestDisabledMessage("obscuring"); +// helper1(); + } + + public void testFail35() throws Exception { + printTestDisabledMessage("obscuring"); +// helper1(); + } + + public void testFail36() throws Exception { + printTestDisabledMessage("obscuring"); +// helper1(); + } + + public void testFail37() throws Exception { + IType classA= getClassFromTestFile(getPackageP(), "A"); + getClassFromTestFile(getPackageP(), "B"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(classA, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void testFail38() throws Exception { + helper1(); + } + + public void testFail39() throws Exception { + helper1(); + } + + public void testFail40() throws Exception { + helper1(); + } + + public void testFail41() throws Exception { + printTestDisabledMessage("obscuring"); +// helper1(); + } + + public void testFail42() throws Exception { + printTestDisabledMessage("obscuring"); +// helper1(); + } + + public void testFail43() throws Exception { + printTestDisabledMessage("obscuring"); +// helper1(); + } + + public void testFail44() throws Exception { + printTestDisabledMessage("obscuring"); +// helper1(); + } + + public void testFail45() throws Exception { + printTestDisabledMessage("obscuring"); +// helper1(); + } + + public void testFail46() throws Exception { + printTestDisabledMessage("obscuring"); +// helper1(); + } + + public void testFail47() throws Exception { + printTestDisabledMessage("obscuring"); +// helper1(); + } + + public void testFail48() throws Exception { + helper1(); + } + + public void testFail49() throws Exception { + helper1(); + } + + public void testFail50() throws Exception { + helper1(); + } + + public void testFail51() throws Exception { + helper1(); + } + + public void testFail52() throws Exception { + helper1(); + } + + public void testFail53() throws Exception { + helper1(); + } + + public void testFail54() throws Exception { + helper1(); + } + + public void testFail55() throws Exception { + helper1(); + } + + public void testFail56() throws Exception { + helper1(); + } + + public void testFail57() throws Exception { + helper1(); + } + + public void testFail58() throws Exception { + helper1(); + } + + public void testFail59() throws Exception { + helper1(); + } + + public void testFail60() throws Exception { + helper1(); + } + + public void testFail61() throws Exception { + helper1(); + } + + public void testFail62() throws Exception { + helper1(); + } + + public void testFail63() throws Exception { + helper1(); + } + + public void testFail64() throws Exception { + helper1(); + } + + public void testFail65() throws Exception { + helper1(); + } + + public void testFail66() throws Exception { + helper1(); + } + + public void testFail67() throws Exception { + helper1(); + } + + public void testFail68() throws Exception { + helper1(); + } + + public void testFail69() throws Exception { + helper1(); + } + + public void testFail70() throws Exception { + helper1(); + } + + public void testFail71() throws Exception { + helper1(); + } + + public void testFail72() throws Exception { + helper1(); + } + + public void testFail73() throws Exception { + helper1(); + } + + public void testFail74() throws Exception { + helper1(); + } + + public void testFail75() throws Exception { + helper1(); + } + + public void testFail76() throws Exception { + helper1(); + } + + public void testFail77() throws Exception { + helper1(); + } + + public void testFail78() throws Exception { + helper1(); + } + + public void testFail79() throws Exception { + helper1(); + } + + public void testFail80() throws Exception { + helper1(); + } + + public void testFail81() throws Exception { + helper1(); + } + + public void testFail82() throws Exception { + helper1(); + } + + public void testFail83() throws Exception { + helper1_0("A", "Cloneable"); + } + + public void testFail84() throws Exception { + helper1_0("A", "List"); + } + + public void testFail85() throws Exception { + helper1(); + } + + public void testFail86() throws Exception { + printTestDisabledMessage("native method with A as parameter (same CU)"); +// helper1(); + } + + public void testFail87() throws Exception { + printTestDisabledMessage("native method with A as parameter (same CU)"); +// helper1(); + } + + public void testFail88() throws Exception { + helper1(); + } + + public void testFail89() throws Exception { + helper1(); + } + + public void testFail90() throws Exception { + helper1(); + } + + public void testFail91() throws Exception { + helper1(); + } + + public void testFail92() throws Exception { +// printTestDisabledMessage("needs fixing - double nested local type named B"); + helper1(); + } + + public void testFail93() throws Exception { +// printTestDisabledMessage("needs fixing - double nested local type named B"); + helper1(); + } + + public void testFail94() throws Exception { + helper1(); + } + + public void testFail95() throws Exception { + helper1(); + } + + public void testFail00() throws Exception { + helper1(); + } + + public void testFail01() throws Exception { + helper1_0("A", "B"); + } + + public void testFail02() throws Exception { + helper1(); + } + + public void testFail03() throws Exception { + helper1_0("A", "C"); + } + + public void testFail04() throws Exception { + helper1_0("A", "A"); + } + + public void testFailRegression1GCRKMQ() throws Exception { + IPackageFragment myPackage= getRoot().createPackageFragment("", true, new NullProgressMonitor()); + IType myClass= getClassFromTestFile(myPackage, "Blinky"); + + RefactoringStatus result= performRefactoring(createRefactoringDescriptor(myClass, "B")); + assertNotNull("precondition was supposed to fail", result); + } + + public void test0() throws Exception { + ParticipantTesting.reset(); + String newName= "B"; + String[] renameHandles= helper2("A", newName); + ParticipantTesting.testRename( + renameHandles, + new RenameArguments[] { + new RenameArguments(newName, true), + new RenameArguments(newName + ".java", true), + new RenameArguments(newName + ".java", true)}); + } + + public void test1() throws Exception { + helper2("A", "B"); + } + + public void test10() throws Exception { + helper2("A", "B"); + } + + public void test12() throws Exception { + helper2("A", "B"); + } + + public void test13() throws Exception { + helper2("A", "B"); + } + + public void test14() throws Exception { + helper2("A", "B"); + } + + public void test15() throws Exception { + helper2("A", "B"); + } + + public void test16() throws Exception { + helper2("A", "B"); + } + + public void test17() throws Exception { + helper2("A", "B"); + } + + public void test18() throws Exception { + helper2("A", "B"); + } + + public void test19() throws Exception { + helper2("A", "B"); + } + + public void test2() throws Exception { + helper2("A", "B"); + } + + public void test20() throws Exception { + //printTestDisabledMessage("failb because of bug#9479"); + //if (true) + // return; + IPackageFragment packageA= getRoot().createPackageFragment("A", true, null); + + ICompilationUnit cu= createCUfromTestFile(packageA, "A"); + IType classA= getType(cu, "A"); + + assertEquals("was supposed to pass", null, performRefactoring(createRefactoringDescriptor(classA, "B"))); + + ICompilationUnit newcu= packageA.getCompilationUnit("B.java"); + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName("B")), newcu.getSource()); + } + + public void test21() throws Exception { + helper2("A", "B"); + } + + public void test22() throws Exception { + helper2("A", "B"); + } + + public void test23() throws Exception { + helper2("A", "B"); + } + + public void test24() throws Exception { + helper2("A", "B"); + } + + public void test25() throws Exception { + helper2("A", "B"); + } + + public void test26() throws Exception { + helper2("A", "B"); + } + + public void test27() throws Exception { + helper2("A", "B"); + } + + public void test28() throws Exception { + helper2("A", "B"); + } + + public void test29() throws Exception { + IPackageFragment packageP1= getRoot().createPackageFragment("p1", true, null); + createCUfromTestFile(packageP1, "C"); + + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType classA= getType(cu, "A"); + + assertEquals("was supposed to pass", null, performRefactoring(createRefactoringDescriptor(classA, "B"))); + + ICompilationUnit newcu= getPackageP().getCompilationUnit("B.java"); + ICompilationUnit newcuC= packageP1.getCompilationUnit("C.java"); + assertEqualLines("invalid renaming A", getFileContents(getOutputTestFileName("B")), newcu.getSource()); + assertEqualLines("invalid renaming C", getFileContents(getOutputTestFileName("C")), newcuC.getSource()); + + } + + public void test3() throws Exception { + helper2("A", "B"); + } + + public void test30() throws Exception { + createCUfromTestFile(getPackageP(), "AA"); + + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType classA= getType(cu, "A"); + + assertEquals("was supposed to pass", null, performRefactoring(createRefactoringDescriptor(classA, "B"))); + + ICompilationUnit newcu= getPackageP().getCompilationUnit("B.java"); + ICompilationUnit newcuAA= getPackageP().getCompilationUnit("AA.java"); + assertEqualLines("invalid renaming A", getFileContents(getOutputTestFileName("B")), newcu.getSource()); + assertEqualLines("invalid renaming AA", getFileContents(getOutputTestFileName("AA")), newcuAA.getSource()); + } + public void test31() throws Exception { + createCUfromTestFile(getPackageP(), "AA"); + + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType classA= getType(cu, "A"); + + assertEquals("was supposed to pass", null, performRefactoring(createRefactoringDescriptor(classA, "B"))); + + ICompilationUnit newcu= getPackageP().getCompilationUnit("B.java"); + ICompilationUnit newcuAA= getPackageP().getCompilationUnit("AA.java"); + assertEqualLines("invalid renaming A", getFileContents(getOutputTestFileName("B")), newcu.getSource()); + assertEqualLines("invalid renaming AA", getFileContents(getOutputTestFileName("AA")), newcuAA.getSource()); + } + public void test32() throws Exception { + helper2("A", "B"); + } + + public void test33() throws Exception { + helper2("A", "B"); + } + + public void test34() throws Exception { + helper2("A", "B"); + } + + public void test35() throws Exception { + helper2("A", "B"); + } + + public void test36() throws Exception { + helper2("A", "B"); + } + + public void test37() throws Exception { + helper2("A", "B"); + } + + public void test38() throws Exception { + helper2("A", "B"); + } + + public void test39() throws Exception { + helper2("A", "B"); + } + + public void test4() throws Exception { + helper2("A", "B"); + } + + public void test40() throws Exception { + //printTestDisabledMessage("search engine bug"); + helper2("A", "B"); + } + + public void test41() throws Exception { + helper2("A", "B"); + } + + public void test42() throws Exception { + helper2("A", "B"); + } + + public void test43() throws Exception { + helper2("A", "B"); + } + + public void test44() throws Exception { + helper2("A", "B"); + } + + public void test45() throws Exception { + helper2("A", "B"); + } + + public void test46() throws Exception { + IPackageFragment packageP1= getRoot().createPackageFragment("p1", true, null); + createCUfromTestFile(packageP1, "C"); + + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType classA= getType(cu, "A"); + + assertEquals("was supposed to pass", null, performRefactoring(createRefactoringDescriptor(classA, "B"))); + + ICompilationUnit newcu= getPackageP().getCompilationUnit("B.java"); + ICompilationUnit newcuC= packageP1.getCompilationUnit("C.java"); + assertEqualLines("invalid renaming A", getFileContents(getOutputTestFileName("B")), newcu.getSource()); + assertEqualLines("invalid renaming C", getFileContents(getOutputTestFileName("C")), newcuC.getSource()); + } + + public void test47() throws Exception { + helper2("A", "B"); + } + + public void test48() throws Exception { + helper2("A", "B"); + } + + public void test49() throws Exception { + helper2("A", "B"); + } + + public void test50() throws Exception { + printTestDisabledMessage("https://bugs.eclipse.org/bugs/show_bug.cgi?id=54948"); + if (false) + helper2("A", "B"); + } + + public void test51() throws Exception { + IPackageFragment packageP1= getRoot().createPackageFragment("p1", true, null); + createCUfromTestFile(packageP1, "C"); + + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType classA= getType(cu, "A"); + + assertEquals("was supposed to pass", null, performRefactoring(createRefactoringDescriptor(classA, "B"))); + + ICompilationUnit newcu= getPackageP().getCompilationUnit("B.java"); + ICompilationUnit newcuC= packageP1.getCompilationUnit("C.java"); + assertEqualLines("invalid renaming A", getFileContents(getOutputTestFileName("B")), newcu.getSource()); + assertEqualLines("invalid renaming C", getFileContents(getOutputTestFileName("C")), newcuC.getSource()); + } + + public void test52() throws Exception { + //printTestDisabledMessage("1GJY2XN: ITPJUI:WIN2000 - rename type: error when with reference"); + helper2("A", "B"); + } + + public void test53() throws Exception { + helper2("A", "B", false); + } + + public void test54() throws Exception { + //printTestDisabledMessage("waiting for: 1GKAQJS: ITPJCORE:WIN2000 - search: incorrect results for nested types"); + helperWithTextual("A", "X", "XYZ", "A", true, false); + } + + public void test55() throws Exception { + //printTestDisabledMessage("waiting for: 1GKAQJS: ITPJCORE:WIN2000 - search: incorrect results for nested types"); + helperWithTextual("A", "X", "XYZ", "A", false, false); + } + + public void test57() throws Exception { + helperWithTextual("A", "A", "B", "B", true, true); + } + + public void test58() throws Exception { + //printTestDisabledMessage("bug#16751"); + helper2("A", "B"); + } + + public void test59() throws Exception { +// printTestDisabledMessage("bug#22938"); + helper2("A", "B"); + } + + public void test60() throws Exception { +// printTestDisabledMessage("test for bug 24740"); + helperWithTextual("A", "A", "B", "B", true, true); + } + + public void test61() throws Exception { + ParticipantTesting.reset(); + String[] renameHandles= helperWithTextual("A" , "Inner", "InnerB", "A", true, false); + ParticipantTesting.testRename(renameHandles, + new RenameArguments[] { + new RenameArguments("InnerB", true), + }); + } + + public void test62() throws Exception { +// printTestDisabledMessage("test for bug 66250"); + helperWithTextual("A", "A", "B", "B", false, true); + } + + public void test63() throws Exception { +// printTestDisabledMessage("test for bug 79131"); + IPackageFragment anotherP= getRoot().createPackageFragment("another.p", true, null); + String folder= "anotherp/"; + String type= "A"; + ICompilationUnit cu= createCUfromTestFile(anotherP, type, folder); + + helperWithTextual(type, type, "B", "B", true, true); + + assertEqualLines("invalid renaming in another.p.A", getFileContents(getOutputTestFileName(type, folder)), cu.getSource()); + } + + public void test64() throws Exception { +// printTestDisabledMessage("test for bug 79131"); + IPackageFragment p2= getRoot().createPackageFragment("p2", true, null); + String folder= "p2/"; + String type= "A"; + ICompilationUnit cu= createCUfromTestFile(p2, type, folder); + + helperWithTextual(type, type, "B", "B", true, true); + + assertEqualLines("invalid renaming in p2.A", getFileContents(getOutputTestFileName(type, folder)), cu.getSource()); + } + + public void test5() throws Exception { + helper2("A", "B"); + } + + public void test6() throws Exception { + helper2("A", "B"); + } + + public void test7() throws Exception { + helper2("A", "B"); + } + + public void test8() throws Exception { + helper2("A", "B"); + } + + public void test9() throws Exception { + helper2("A", "B"); + } + + public void testUnicode01() throws Exception { + helper2("B", "C"); + //TODO: test undo! + } + + public void testQualifiedName1() throws Exception { + helperQualifiedName("A", "B", "build.xml", "*.xml"); + } + + public void testQualifiedName2() throws Exception { + helperQualifiedName("Transient", "TransientEquipment", "mapping.hbm.xml", "*.xml"); + } + + private void helperQualifiedName(String oldName, String newName, String textFileName, String filePatterns) throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), oldName); + IType classA= getType(cu, oldName); + + String content= getFileContents(getTestPath() + getName() + TEST_INPUT_INFIX + textFileName); + IProject project= classA.getJavaProject().getProject(); + IFile file= project.getFile(textFileName); + file.create(new ByteArrayInputStream(content.getBytes()), true, null); + + RenameJavaElementDescriptor descriptor= createRefactoringDescriptor(classA, newName); + descriptor.setUpdateQualifiedNames(true); + descriptor.setFileNamePatterns(filePatterns); + + assertEquals("was supposed to pass", null, performRefactoring(descriptor)); + + ICompilationUnit newcu= getPackageP().getCompilationUnit(newName + ".java"); + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName(newName)), newcu.getSource()); + InputStreamReader reader= new InputStreamReader(file.getContents(true)); + StringBuffer newContent= new StringBuffer(); + try { + int ch; + while((ch= reader.read()) != -1) + newContent.append((char)ch); + } finally { + reader.close(); + } + String definedContent= getFileContents(getTestPath() + getName() + TEST_OUTPUT_INFIX + textFileName); + assertEqualLines("invalid updating", definedContent, newContent.toString()); + } + + public void testGenerics1() throws Exception { + helper2("A", "B"); + } + + public void testGenerics2() throws Exception { + helper2("A", "B"); + } + + public void testGenerics3() throws Exception { + helper2("A", "B"); + } + + public void testGenerics4() throws Exception { + helper2("A", "B"); + } + + public void testEnum1() throws Exception { + IPackageFragment p2= getRoot().createPackageFragment("p2", true, null); + String folder= "p2/"; + String type= "A"; + ICompilationUnit cu= createCUfromTestFile(p2, type, folder); + + helper2("A", "B"); + + assertEqualLines("invalid renaming in p2.A", getFileContents(getOutputTestFileName(type, folder)), cu.getSource()); + } + + public void testEnum2() throws Exception { + helper2("A", "B"); + } + + public void testEnum3() throws Exception { + ICompilationUnit enumbered= createCUfromTestFile(getPackageP(), "Enumbered"); + helper2("A", "B"); + assertEqualLines("invalid renaming in Enumbered", getFileContents(getOutputTestFileName("Enumbered")), enumbered.getSource()); + } + + public void testEnum4() throws Exception { + helperWithTextual("A" , "A", "B", "A", true, false); + } + + public void testEnum5() throws Exception { + helper2("A", "B"); + } + + public void testAnnotation1() throws Exception { + helper2("A", "B"); + } + + public void testAnnotation2() throws Exception { + helper2("A", "B"); + } + + public void testAnnotation3() throws Exception { + helperWithTextual("A" , "A", "B", "A", true, true); + } + + // --------------- Similarly named elements ----------------- + + public void testSimilarElements00() throws Exception { + // Very basic test, one field, two methods + helper3("SomeClass", "SomeClass2", true, false, true); + } + + public void testSimilarElements01() throws Exception { + // Already existing field with new name, shadow-error from field refac + helper3_fail("SomeClass", "SomeClass2", true, false, true); + } + + public void testSimilarElements02() throws Exception { + // Already existing method + helper3_fail("SomeClass", "SomeDifferentClass", true, false, true); + } + + public void testSimilarElements03() throws Exception { + // more methods + helper3("SomeClass", "SomeClass2", true, false, true); + } + public void testSimilarElements04() throws Exception { + //Additional field with exactly the same name and getters and setters in another class + getClassFromTestFile(getPackageP(), "SomeOtherClass"); + helper3("SomeClass", "SomeClass2", true, false, true); + checkResultInClass("SomeOtherClass"); + } + + public void testSimilarElements05() throws Exception { + //qualified name updating + //includes textual updating + String content= getFileContents(getTestPath() + "testSimilarElements05/in/test.html"); + IProject project= getPackageP().getJavaProject().getProject(); + IFile file= project.getFile("test.html"); + file.create(new ByteArrayInputStream(content.getBytes()), true, null); + + helper3("SomeClass", "SomeDifferentClass", true, true, true, "test.html"); + + InputStreamReader reader= new InputStreamReader(file.getContents(true)); + StringBuffer newContent= new StringBuffer(); + try { + int ch; + while((ch= reader.read()) != -1) + newContent.append((char)ch); + } finally { + reader.close(); + } + String definedContent= getFileContents(getTestPath() + "testSimilarElements05/out/test.html"); + assertEqualLines("invalid updating test.html", newContent.toString(), definedContent); + + } + + public void testSimilarElements06() throws Exception { + //Additional field with exactly the same name and getters and setters in another class + //includes textual updating + // printTestDisabledMessage("potential matches in comments issue (bug 111891)"); + getClassFromTestFile(getPackageP(), "SomeNearlyIdenticalClass"); + helper3("SomeClass", "SomeOtherClass", true, true, true); + checkResultInClass("SomeNearlyIdenticalClass"); + } + + public void testSimilarElements07() throws Exception { + //Test 4 fields in one file, different suffixes/prefixes, incl. 2x setters/getters + //includes textual updating + helper3("SomeClass", "SomeDiffClass", true, true, true); + } + + public void testSimilarElements08() throws Exception { + //Interface renaming fun, this time without textual + helper3("ISomeIf", "ISomeIf2", true, false, true); + } + + public void testSimilarElements09() throws Exception { + //Some inner types + //includes textual updating + getClassFromTestFile(getPackageP(), "SomeOtherClass"); + helper3_inner("SomeClass", "SomeInnerClass", "SomeClass", "SomeNewInnerClass", true, true, true, null); + checkResultInClass("SomeOtherClass"); + } + + public void testSimilarElements10() throws Exception { + //Two static fields + getClassFromTestFile(getPackageP(), "SomeOtherClass"); + helper3("SomeClass", "SomeClass2", true, false, true, null); + checkResultInClass("SomeOtherClass"); + } + + public void testSimilarElements11() throws Exception { + //Assure participants get notified of normal stuff (type rename + //and resource changes) AND similarly named elements. + ParticipantTesting.reset(); + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "SomeClass"); + IType someClass= getType(cu, "SomeClass"); + IType other= getClassFromTestFile(getPackageP(), "SomeOtherClass"); + + List handleList= new ArrayList(); + List argumentList= new ArrayList(); + + List similarOldHandleList= new ArrayList(); + List similarNewNameList= new ArrayList(); + List similarNewHandleList= new ArrayList(); + + final String newName= "SomeNewClass"; + + // f-Field + getters/setters + IField f3= other.getField("fSomeClass"); + similarOldHandleList.add(f3.getHandleIdentifier()); + similarNewHandleList.add("Lp/SomeOtherClass;.fSomeNewClass"); + similarNewNameList.add("fSomeNewClass"); + + IMethod m3= other.getMethod("getSomeClass", new String[0]); + similarOldHandleList.add(m3.getHandleIdentifier()); + similarNewNameList.add("getSomeNewClass"); + similarNewHandleList.add("Lp/SomeOtherClass;.getSomeNewClass()V"); + IMethod m4= other.getMethod("setSomeClass", new String[] {"QSomeClass;"}); + similarOldHandleList.add(m4.getHandleIdentifier()); + similarNewNameList.add("setSomeNewClass"); + similarNewHandleList.add("Lp/SomeOtherClass;.setSomeNewClass(QSomeNewClass;)V"); + + // non-f-field + getter/setters + IField f1= someClass.getField("someClass"); + similarOldHandleList.add(f1.getHandleIdentifier()); + similarNewNameList.add("someNewClass"); + similarNewHandleList.add("Lp/SomeNewClass;.someNewClass"); + IMethod m1= someClass.getMethod("getSomeClass", new String[0]); + similarOldHandleList.add(m1.getHandleIdentifier()); + similarNewNameList.add("getSomeNewClass"); + similarNewHandleList.add("Lp/SomeNewClass;.getSomeNewClass()V"); + IMethod m2= someClass.getMethod("setSomeClass", new String[] {"QSomeClass;"}); + similarOldHandleList.add(m2.getHandleIdentifier()); + similarNewNameList.add("setSomeNewClass"); + similarNewHandleList.add("Lp/SomeNewClass;.setSomeNewClass(QSomeNewClass;)V"); + + // fs-field + IField f2= someClass.getField("fsSomeClass"); + similarOldHandleList.add(f2.getHandleIdentifier()); + similarNewNameList.add("fsSomeNewClass"); + similarNewHandleList.add("Lp/SomeNewClass;.fsSomeNewClass"); + + // Type Stuff + handleList.add(someClass); + argumentList.add(new RenameArguments(newName, true)); + handleList.add(cu); + argumentList.add(new RenameArguments(newName + ".java", true)); + handleList.add(cu.getResource()); + argumentList.add(new RenameArguments(newName + ".java", true)); + + String[] handles= ParticipantTesting.createHandles(handleList.toArray()); + RenameArguments[] arguments= (RenameArguments[])argumentList.toArray(new RenameArguments[0]); + + RenameJavaElementDescriptor descriptor= createRefactoringDescriptor(someClass, newName); + setTheOptions(descriptor, true, false, true, null, RenamingNameSuggestor.STRATEGY_EMBEDDED); + RefactoringStatus status= performRefactoring(descriptor); + assertNull("was supposed to pass", status); + + checkResultInClass(newName); + checkResultInClass("SomeOtherClass"); + + ParticipantTesting.testRename(handles, arguments); + ParticipantTesting.testSimilarElements(similarOldHandleList, similarNewNameList, similarNewHandleList); + } + + public void testSimilarElements12() throws Exception { + // Test updating of references + helper3("SomeFieldClass", "SomeOtherFieldClass", true, false, true); + } + + public void testSimilarElements13() throws Exception { + // Test various locals and parameters with and without prefixes. + // tests not renaming parameters with local prefixes and locals with parameter prefixes + helper3("SomeClass", "SomeOtherClass", true, false, true); + } + + public void testSimilarElements14() throws Exception { + // Test for loop variables + helper3("SomeClass2", "SomeOtherClass2", true, false, true); + } + + public void testSimilarElements15() throws Exception { + // Test catch block variables (exceptions) + helper3("SomeClass3", "SomeOtherClass3", true, false, true); + } + + public void testSimilarElements16() throws Exception { + // Test updating of references + helper3("SomeClass4", "SomeOtherClass4", true, false, true); + } + + public void testSimilarElements17() throws Exception { + // Local with this name already exists - do not pass. + helper3_fail("SomeClass6", "SomeOtherClass6", true, false, true); + } + + public void testSimilarElements18() throws Exception { + // factory method + helper3("SomeClass", "SomeOtherClass", true, false, true); + } + + public void testSimilarElements19() throws Exception { + // Test detection of same target + helper3_fail("ThreeHunkClass", "TwoHunk", true, false, true, RenamingNameSuggestor.STRATEGY_SUFFIX); + } + + public void testSimilarElements20() throws Exception { + // Overridden method, check both are renamed + getClassFromTestFile(getPackageP(), "OtherClass"); + helper3("OverriddenMethodClass", "ThirdClass", true, false, true); + checkResultInClass("OtherClass"); + } + + public void testSimilarElements21() throws Exception { + // Constructors may not be renamed + getClassFromTestFile(getPackageP(), "SomeClassSecond"); + helper3("SomeClass", "SomeNewClass", true, false, true); + checkResultInClass("SomeClassSecond"); + } + + public void testSimilarElements22() throws Exception { + // Test transplanter for fields in types inside of initializers + + ParticipantTesting.reset(); + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "SomeClass"); + IType someClass= getType(cu, "SomeClass"); + + List handleList= new ArrayList(); + List argumentList= new ArrayList(); + + List similarOldHandleList= new ArrayList(); + List similarNewNameList= new ArrayList(); + List similarNewHandleList= new ArrayList(); + + final String newName= "SomeNewClass"; + + // field in class in initializer + IField inInitializer= someClass.getInitializer(1).getType("InInitializer", 1).getField("someClassInInitializer"); + similarOldHandleList.add(inInitializer.getHandleIdentifier()); + similarNewNameList.add("someNewClassInInitializer"); + similarNewHandleList.add("Lp/SomeNewClass$InInitializer;.someNewClassInInitializer"); + + // Type Stuff + handleList.add(someClass); + argumentList.add(new RenameArguments(newName, true)); + handleList.add(cu); + argumentList.add(new RenameArguments(newName + ".java", true)); + handleList.add(cu.getResource()); + argumentList.add(new RenameArguments(newName + ".java", true)); + + String[] handles= ParticipantTesting.createHandles(handleList.toArray()); + RenameArguments[] arguments= (RenameArguments[])argumentList.toArray(new RenameArguments[0]); + + RenameJavaElementDescriptor descriptor= createRefactoringDescriptor(someClass, newName); + setTheOptions(descriptor, true, false, true, null, RenamingNameSuggestor.STRATEGY_EMBEDDED); + RefactoringStatus status= performRefactoring(descriptor); + assertNull("was supposed to pass", status); + + checkResultInClass(newName); + + ParticipantTesting.testRename(handles, arguments); + ParticipantTesting.testSimilarElements(similarOldHandleList, similarNewNameList, similarNewHandleList); + + } + + public void testSimilarElements23() throws Exception { + // Test transplanter for elements inside types inside fields + + ParticipantTesting.reset(); + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "SomeClass"); + IType someClass= getType(cu, "SomeClass"); + + List handleList= new ArrayList(); + List argumentList= new ArrayList(); + + List similarOldHandleList= new ArrayList(); + List similarNewNameList= new ArrayList(); + List similarNewHandleList= new ArrayList(); + + final String newName= "SomeNewClass"; + + // some field + IField anotherSomeClass= someClass.getField("anotherSomeClass"); + similarOldHandleList.add(anotherSomeClass.getHandleIdentifier()); + similarNewNameList.add("anotherSomeNewClass"); + similarNewHandleList.add("Lp/SomeNewClass;.anotherSomeNewClass"); + + // field in class in method in field declaration ;) + IField inInner= anotherSomeClass.getType("", 1).getMethod("foo", new String[0]).getType("X", 1).getField("someClassInInner"); + similarOldHandleList.add(inInner.getHandleIdentifier()); + similarNewNameList.add("someNewClassInInner"); + similarNewHandleList.add("Lp/SomeNewClass$1$X;.someNewClassInInner"); + + // Type Stuff + handleList.add(someClass); + argumentList.add(new RenameArguments(newName, true)); + handleList.add(cu); + argumentList.add(new RenameArguments(newName + ".java", true)); + handleList.add(cu.getResource()); + argumentList.add(new RenameArguments(newName + ".java", true)); + + String[] handles= ParticipantTesting.createHandles(handleList.toArray()); + RenameArguments[] arguments= (RenameArguments[])argumentList.toArray(new RenameArguments[0]); + + RenameJavaElementDescriptor descriptor= createRefactoringDescriptor(someClass, newName); + setTheOptions(descriptor, true, false, true, null, RenamingNameSuggestor.STRATEGY_EMBEDDED); + RefactoringStatus status= performRefactoring(descriptor); + assertNull("was supposed to pass", status); + + checkResultInClass(newName); + + ParticipantTesting.testRename(handles, arguments); + ParticipantTesting.testSimilarElements(similarOldHandleList, similarNewNameList, similarNewHandleList); + } + + public void testSimilarElements24() throws Exception { + // Test transplanter for ICompilationUnit and IFile + + ParticipantTesting.reset(); + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "SomeClass"); + IType someClass= getType(cu, "SomeClass"); + IJavaElement[] someClassMembers= someClass.getChildren(); + + RenameJavaElementDescriptor descriptor= createRefactoringDescriptor(someClass, "SomeNewClass"); + setTheOptions(descriptor, true, false, true, null, RenamingNameSuggestor.STRATEGY_EMBEDDED); + Refactoring ref= createRefactoring(descriptor); + RefactoringStatus status= performRefactoring(ref); + assertNull("was supposed to pass", status); + + checkResultInClass("SomeNewClass"); + + checkMappers(ref, someClass, "SomeNewClass.java", someClassMembers); + } + + private void checkMappers(Refactoring refactoring, IType type, String newCUName, IJavaElement[] someClassMembers) { + RenameTypeProcessor rtp= (RenameTypeProcessor)((RenameRefactoring) refactoring).getProcessor(); + + ICompilationUnit newUnit= (ICompilationUnit)rtp.getRefactoredJavaElement(type.getCompilationUnit()); + assertTrue(newUnit.exists()); + assertTrue(newUnit.getElementName().equals(newCUName)); + + IFile newFile= (IFile)rtp.getRefactoredResource(type.getResource()); + assertTrue(newFile.exists()); + assertTrue(newFile.getName().equals(newCUName)); + + if ((type.getParent().getElementType() == IJavaElement.COMPILATION_UNIT) + && type.getCompilationUnit().getElementName().equals(type.getElementName() + ".java")) { + assertFalse(type.getCompilationUnit().exists()); + assertFalse(type.getResource().exists()); + } + + IPackageFragment oldPackage= (IPackageFragment)type.getCompilationUnit().getParent(); + IPackageFragment newPackage= (IPackageFragment)rtp.getRefactoredJavaElement(oldPackage); + assertEquals(oldPackage, newPackage); + + for (int i= 0; i < someClassMembers.length; i++) { + IMember member= (IMember) someClassMembers[i]; + IJavaElement refactoredMember= rtp.getRefactoredJavaElement(member); + if (member instanceof IMethod && member.getElementName().equals(type.getElementName())) + continue; // constructor + assertTrue(refactoredMember.exists()); + assertEquals(member.getElementName(), refactoredMember.getElementName()); + assertFalse(refactoredMember.equals(member)); + } + } + + public void testSimilarElements25() throws Exception { + // Test renaming of several-in-one field declarations + helper3("ScrewUp", "ScrewDown", true, false, true); + } + + public void testSimilarElements26() throws Exception { + // Test renaming of several-in-one local variable declarations + helper3("ScrewUp", "ScrewDown", true, false, true); + } + + public void testSimilarElements27() throws Exception { + // Test methods are not renamed if the match is + // not either a parameter or a return type + helper3("ScrewUp", "ScrewDown", true, false, true); + } + + public void testSimilarElements28() throws Exception { + // Test local variables are not renamed if the match is + // not the type of the local variable itself + helper3("ScrewUp", "ScrewDown", true, false, true); + } + + public void testSimilarElements29() throws Exception { + // Test fields are not renamed if the match is + // not the type of the field itself + helper3("ScrewUp", "ScrewDown", true, false, true); + } + + public void testSimilarElements30() throws Exception { + // Test local variables in initializers + helper3("SomeClass", "SomeNewClass", true, false, true); + } + + public void testSimilarElements31() throws Exception { + // Test references and textual references to local elements + helper3("SomeClass", "SomeDiffClass", true, true, true); + } + + public void testSimilarElements32() throws Exception { + // Test whether local variable problem reporting still works + helper3_fail("SomeClass", "SomeDifferentClass", true, false, true); + } + + public void testSimilarElements33() throws Exception { + // Test two local variables inside anonymous types do not generate warnings + helper3("Why", "WhyNot", true, false, true); + } + + public void testSimilarElements34() throws Exception { + // Test references in annotations and type parameters + helper3("Try", "Bla", true, false, true); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameVirtualMethodInClassTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameVirtualMethodInClassTests.java new file mode 100644 index 000000000..dda5c9b3d --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameVirtualMethodInClassTests.java @@ -0,0 +1,545 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.Signature; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; +import org.eclipse.jdt.internal.corext.refactoring.rename.RenameMethodProcessor; +import org.eclipse.jdt.internal.corext.refactoring.rename.RenameVirtualMethodProcessor; + +public class RenameVirtualMethodInClassTests extends RefactoringTest { + + private static final Class clazz= RenameVirtualMethodInClassTests.class; + private static final String REFACTORING_PATH= "RenameVirtualMethodInClass/"; + + private static final boolean BUG_83217_IMPLICIT_ENUM_METHODS= true; + + public RenameVirtualMethodInClassTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + protected String getRefactoringPath(){ + return REFACTORING_PATH; + } + + private void helper1_not_available(String methodName, String[] signatures) throws Exception{ + IType classA= getType(createCUfromTestFile(getPackageP(), "A"), "A"); + RenameMethodProcessor processor= new RenameVirtualMethodProcessor(classA.getMethod(methodName, signatures)); + RenameRefactoring ref= new RenameRefactoring(processor); + assertTrue(! ref.isApplicable()); + } + + private void helper1_0(String methodName, String newMethodName, String[] signatures) throws Exception{ + IType classA= getType(createCUfromTestFile(getPackageP(), "A"), "A"); + RenameMethodProcessor processor= new RenameVirtualMethodProcessor(classA.getMethod(methodName, signatures)); + RenameRefactoring ref= new RenameRefactoring(processor); + processor.setNewElementName(newMethodName); + RefactoringStatus result= performRefactoring(ref); + assertNotNull("precondition was supposed to fail", result); + } + + private void helper1() throws Exception{ + helper1_0("m", "k", new String[0]); + } + + private void helper2_0(String methodName, String newMethodName, String[] signatures, boolean shouldPass, boolean updateReferences, boolean createDelegate) throws Exception{ + final ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + final IType classA= getType(cu, "A"); + final IMethod method= classA.getMethod(methodName, signatures); + final RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_METHOD); + descriptor.setJavaElement(method); + descriptor.setNewName(newMethodName); + descriptor.setUpdateReferences(updateReferences); + descriptor.setKeepOriginal(createDelegate); + descriptor.setDeprecateDelegate(createDelegate); + final RefactoringStatus status= new RefactoringStatus(); + final Refactoring refactoring= descriptor.createRefactoring(status); + assertNotNull("Refactoring should not be null", refactoring); + assertTrue("status should be ok", status.isOK()); + assertEquals("was supposed to pass", null, performRefactoring(refactoring)); + if (!shouldPass){ + assertTrue("incorrect renaming because of java model", ! getFileContents(getOutputTestFileName("A")).equals(cu.getSource())); + return; + } + String expectedRenaming= getFileContents(getOutputTestFileName("A")); + String actuaRenaming= cu.getSource(); + assertEqualLines("incorrect renaming", expectedRenaming, actuaRenaming); + + assertTrue("anythingToUndo", RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("! anythingToRedo", !RefactoringCore.getUndoManager().anythingToRedo()); + //assertEquals("1 to undo", 1, Refactoring.getUndoManager().getRefactoringLog().size()); + + RefactoringCore.getUndoManager().performUndo(null, new NullProgressMonitor()); + assertEqualLines("invalid undo", getFileContents(getInputTestFileName("A")), cu.getSource()); + + assertTrue("! anythingToUndo", !RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("anythingToRedo", RefactoringCore.getUndoManager().anythingToRedo()); + //assertEquals("1 to redo", 1, Refactoring.getUndoManager().getRedoStack().size()); + + RefactoringCore.getUndoManager().performRedo(null, new NullProgressMonitor()); + assertEqualLines("invalid redo", getFileContents(getOutputTestFileName("A")), cu.getSource()); + } + + private void helper2_0(String methodName, String newMethodName, String[] signatures, boolean shouldPass) throws Exception{ + helper2_0(methodName, newMethodName, signatures, shouldPass, true, false); + } + + private void helper2_0(String methodName, String newMethodName, String[] signatures) throws Exception{ + helper2_0(methodName, newMethodName, signatures, true); + } + + private void helper2(boolean updateReferences) throws Exception{ + helper2_0("m", "k", new String[0], true, updateReferences, false); + } + + private void helper2() throws Exception{ + helper2(true); + } + + private void helperDelegate() throws Exception{ + helper2_0("m", "k", new String[0], true, true, true); + } + + private void helper2_fail() throws Exception{ + helper2_0("m", "k", new String[0], false); + } + +// ---------------------------------------------------------------- + + public void testEnum1() throws Exception { + helper2_0("getNameLength", "getNameSize", new String[0]); + } + + public void testEnum2() throws Exception { + helper2_0("getSquare", "get2ndPower", new String[0]); + } + + public void testEnum3() throws Exception { + helper2_0("getSquare", "get2ndPower", new String[0]); + } + + public void testEnumFail1() throws Exception { + if (BUG_83217_IMPLICIT_ENUM_METHODS) + return; + helper1_0("value", "valueOf", new String[]{"QString;"}); + } + + public void testGenerics1() throws Exception { + helper2_0("m", "k", new String[]{"QG;"}); + } + + public void testGenerics2() throws Exception { + helper2_0("add", "addIfPositive", new String[]{"QE;"}); + } + + public void testGenerics3() throws Exception { + helper2_0("add", "addIfPositive", new String[]{"QT;"}); + } + + public void testGenerics4() throws Exception { + helper2_0("takeANumber", "doit", new String[]{"QNumber;"}); + } + + public void testGenerics5() throws Exception { + helper2_0("covariant", "variant", new String[0]); + } + + public void testVarargs1() throws Exception { + helper2_0("runall", "runThese", new String[]{"[QRunnable;"}); + } + + public void testVarargs2() throws Exception { + helper2_0("m", "k", new String[]{"[QString;"}); + } + + public void testFail0() throws Exception{ + helper1(); + } + + public void testFail1() throws Exception{ + helper1_not_available("toString", new String[0]); + } + + public void testFail2() throws Exception{ + helper1(); + } + + public void testFail3() throws Exception{ + helper1(); + } + + public void testFail4() throws Exception{ + helper1(); + } + + public void testFail5() throws Exception{ + helper1(); + } + + public void testFail6() throws Exception{ + helper1(); + } + + public void testFail7() throws Exception{ + helper1(); + } + + public void testFail8() throws Exception{ + helper1(); + } + + public void testFail9() throws Exception{ + helper1_0("m", "k", new String[]{Signature.SIG_INT}); + } + + public void testFail10() throws Exception{ + helper1(); + } + + public void testFail11() throws Exception{ + helper1(); + } + + public void testFail12() throws Exception{ + helper1(); + } + + public void testFail13() throws Exception{ + helper1(); + } + + public void testFail14() throws Exception{ + helper1_0("m", "k", new String[]{Signature.SIG_INT}); + } + + public void testFail15() throws Exception{ + helper1(); + } + + public void testFail17() throws Exception{ + helper1(); + } + + public void testFail18() throws Exception{ + helper1(); + } + + public void testFail19() throws Exception{ + helper1(); + } + + public void testFail20() throws Exception{ + helper1(); + } + + public void testFail21() throws Exception{ + helper1(); + } + + public void testFail22() throws Exception{ + helper1(); + } + + public void testFail23() throws Exception{ + helper1(); + } + + public void testFail24() throws Exception{ + helper1(); + } + + public void testFail25() throws Exception{ + helper1(); + } + + public void testFail26() throws Exception{ + helper1(); + } + + public void testFail27() throws Exception{ + helper1(); + } + + public void testFail28() throws Exception{ + helper1(); + } + + public void testFail29() throws Exception{ + helper1(); + } + + public void testFail30() throws Exception{ + helper1(); + } + + public void testFail31() throws Exception{ + helper1_0("m", "k", new String[]{"QString;"}); + } + + public void testFail32() throws Exception{ + helper1_0("m", "k", new String[]{"QObject;"}); + } + + public void testFail33() throws Exception{ + helper1_not_available("toString", new String[0]); + } + + public void testFail34() throws Exception{ + helper1_0("m", "k", new String[]{"QString;"}); + } + +// //test removed - was invalid +// public void testFail35() throws Exception{ +// } + + public void testFail36() throws Exception{ + helper1(); + } + + public void testFail37() throws Exception{ + helper1(); + } + + public void testFail38() throws Exception{ + //printTestDisabledMessage("must fix - nested type"); + helper1(); + } + + public void testFail39() throws Exception{ + helper1(); + } + + public void testFail40() throws Exception{ + //Autoboxing -> calls to methods can be redirected due to overloading + helper1_0("m", "k", new String[]{Signature.SIG_INT}); + } + + public void testFail41() throws Exception{ + helper1(); + } + + public void test1() throws Exception{ + ParticipantTesting.reset(); + helper2(); + } + + public void test10() throws Exception{ + helper2(); + } + + public void test11() throws Exception{ + helper2(); + } + + public void test12() throws Exception{ + helper2(); + } + + public void test13() throws Exception{ + helper2(); + } + + public void test14() throws Exception{ + helper2(); + } + + public void test15() throws Exception{ + helper2_0("m", "k", new String[]{Signature.SIG_INT}); + } + + public void test16() throws Exception{ + helper2_0("m", "fred", new String[]{Signature.SIG_INT}); + } + + public void test17() throws Exception{ + //printTestDisabledMessage("overloading"); + helper2_0("m", "kk", new String[]{Signature.SIG_INT}); + } + + public void test18() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuC= createCUfromTestFile(getPackageP(), "C"); + + IType classB= getType(cu, "B"); + IMethod method= classB.getMethod("m", new String[]{"I"}); + + final RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_METHOD); + descriptor.setJavaElement(method); + descriptor.setNewName("kk"); + descriptor.setUpdateReferences(true); + final RefactoringStatus status= new RefactoringStatus(); + final Refactoring refactoring= descriptor.createRefactoring(status); + assertNotNull("Refactoring should not be null", refactoring); + assertTrue("status should be ok", status.isOK()); + + assertEquals("was supposed to pass", null, performRefactoring(refactoring)); + assertEqualLines("invalid renaming A", getFileContents(getOutputTestFileName("A")), cu.getSource()); + assertEqualLines("invalid renaming C", getFileContents(getOutputTestFileName("C")), cuC.getSource()); + } + + public void test19() throws Exception{ + helper2_0("m", "fred", new String[0]); + } + + public void test2() throws Exception{ + helper2_0("m", "fred", new String[0]); + } + + public void test20() throws Exception{ + helper2_0("m", "fred", new String[]{Signature.SIG_INT}); + } + + public void test21() throws Exception{ + helper2_0("m", "fred", new String[]{Signature.SIG_INT}); + } + + public void test22() throws Exception{ + helper2(); + } + + //anonymous inner class + public void test23() throws Exception{ + helper2_fail(); + } + + public void test24() throws Exception{ + helper2_0("m", "k", new String[]{"QString;"}); + } + + public void test25() throws Exception{ + //printTestDisabledMessage("waiting for 1GIIBC3: ITPJCORE:WINNT - search for method references - missing matches"); + helper2(); + } + + public void test26() throws Exception{ + helper2(); + } + + public void test27() throws Exception{ + helper2(); + } + + public void test28() throws Exception{ + helper2(); + } + + public void test29() throws Exception{ + helper2(); + } + + public void test30() throws Exception{ + helper2(); + } + + public void test31() throws Exception{ + helper2(); + } + + public void test32() throws Exception{ + helper2(false); + } + + public void test33() throws Exception{ + helper2(); + } + + public void test34() throws Exception{ + printTestDisabledMessage("test for bug#18553"); +// helper2_0("A", "foo", new String[0], true, true); + } + + public void test35() throws Exception{ + helper2_0("foo", "bar", new String[] {"QObject;"}, true); + } + + public void test36() throws Exception{ + helper2_0("foo", "bar", new String[] {"QString;"}, true); + } + + public void test37() throws Exception{ + helper2_0("foo", "bar", new String[] {"QA;"}, true); + } + + public void test38() throws Exception { + printTestDisabledMessage("difficult to set up test in current testing framework"); +// helper2(); + } + + public void test39() throws Exception { + helper2(); + } + + public void test40() throws Exception { // test for bug 68592 + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType localClass= cu.getType("A").getMethod("doit", new String[0]).getType("LocalClass", 1); + IMethod method= localClass.getMethod("method", new String[]{"I"}); + + final RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_METHOD); + descriptor.setJavaElement(method); + descriptor.setNewName("method2"); + descriptor.setUpdateReferences(true); + final RefactoringStatus status= new RefactoringStatus(); + final Refactoring refactoring= descriptor.createRefactoring(status); + assertNotNull("Refactoring should not be null", refactoring); + assertTrue("status should be ok", status.isOK()); + + assertEquals("was supposed to pass", null, performRefactoring(refactoring)); + assertEqualLines("invalid renaming A", getFileContents(getOutputTestFileName("A")), cu.getSource()); + } + + //anonymous inner class + public void testAnon0() throws Exception{ + helper2(); + } + + public void testLocal0() throws Exception{ + helper2(); + } + + public void testDelegate01() throws Exception { + // simple delegate + helperDelegate(); + } + + public void testDelegate02() throws Exception { + // overridden delegates with abstract mix-in + helperDelegate(); + } + + public void testDelegate03() throws Exception { + // overridden delegates in local type + helperDelegate(); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenamingNameSuggestorTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenamingNameSuggestorTests.java new file mode 100644 index 000000000..2530b1c06 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenamingNameSuggestorTests.java @@ -0,0 +1,303 @@ +/******************************************************************************* + * Copyright (c) 2005, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.internal.corext.refactoring.rename.RenamingNameSuggestor; + +public class RenamingNameSuggestorTests extends TestCase { + + public static Test suite() { + return new TestSuite(RenamingNameSuggestorTests.class); + } + + String[] fPrefixes; + String[] fSuffixes; + RenamingNameSuggestor fSuggestor; + + private String fHelper(String oldFieldName, String oldTypeName, String newTypeName) { + return fSuggestor.suggestNewVariableName(fPrefixes, fSuffixes, oldFieldName, oldTypeName, newTypeName); + } + + private String mHelper(String oldFieldName, String oldTypeName, String newTypeName) { + return fSuggestor.suggestNewMethodName(oldFieldName, oldTypeName, newTypeName); + } + + public void mh(String orig, String changed, String oldT, String newT) { + assertEquals(changed, mHelper(orig, oldT, newT)); + } + + public void mhf(String orig, String oldT, String newT) { + assertEquals(null, mHelper(orig, oldT, newT)); + } + + public void fh(String orig, String changed, String oldT, String newT) { + assertEquals(changed, fHelper(orig, oldT, newT)); + } + + public void fhf(String orig, String oldT, String newT) { + assertEquals(null, fHelper(orig, oldT, newT)); + } + + public void setStrategy(int strategy) { + fSuggestor= new RenamingNameSuggestor(strategy); + } + + public void testOnlyPrefix() { + + fPrefixes= new String[] { "f", "q" }; + fSuffixes= new String[0]; + setStrategy(RenamingNameSuggestor.STRATEGY_EXACT); + + // Prefix can, but need not be specified. + assertEquals("fSomeOtherClass", fHelper("fSomeClass", "SomeClass", "SomeOtherClass")); + assertEquals("qSomeOtherClass", fHelper("qSomeClass", "SomeClass", "SomeOtherClass")); + assertEquals("someOtherClass", fHelper("someClass", "SomeClass", "SomeOtherClass")); + + //Interface names + assertEquals("fNewJavaElement", fHelper("fJavaElement", "IJavaElement", "INewJavaElement")); + assertEquals("newJavaElement", fHelper("javaElement", "IJavaElement", "INewJavaElement")); + + // Unrelated stuff + assertNull(fHelper("fSomeClass", "Unrelated", "Unrelated2")); + + } + + public void testPrefixAndSuffix() { + + fPrefixes= new String[] { "f", "q" }; + fSuffixes= new String[] { "Suf1" }; + setStrategy(RenamingNameSuggestor.STRATEGY_EXACT); + + // Suffix and Prefix can, but need not be specified. + assertEquals("fSomeOtherSuf1", fHelper("fSomeSuf1", "Some", "SomeOther")); + assertEquals("someOtherSuf1", fHelper("someSuf1", "Some", "SomeOther")); + assertEquals("fSomeOther", fHelper("fSome", "Some", "SomeOther")); + assertEquals("someOther", fHelper("some", "Some", "SomeOther")); + + //Interface names + assertEquals("fNewJavaElementSuf1", fHelper("fJavaElementSuf1", "IJavaElement", "INewJavaElement")); + assertEquals("newJavaElement", fHelper("javaElement", "IJavaElement", "INewJavaElement")); + } + + public void testOnlySuffix() { + + fPrefixes= new String[0]; + fSuffixes= new String[] { "Suf1" }; + setStrategy(RenamingNameSuggestor.STRATEGY_EXACT); + + //Suffix can, but need not be specified + assertEquals("someOtherClassSuf1", fHelper("someClassSuf1", "SomeClass", "SomeOtherClass")); + assertEquals("someOtherClass", fHelper("someClass", "SomeClass", "SomeOtherClass")); + + //Interface names + assertEquals("newJavaElementSuf1", fHelper("javaElementSuf1", "IJavaElement", "INewJavaElement")); + assertEquals("newJavaElement", fHelper("javaElement", "IJavaElement", "INewJavaElement")); + + } + + public void testVeryShortNames() { + + fPrefixes= new String[] { "f", "q" }; + fSuffixes= new String[] { "_" }; + setStrategy(RenamingNameSuggestor.STRATEGY_SUFFIX); + + assertEquals("fB", fHelper("fA", "A", "B")); + assertEquals("qB", fHelper("qA", "A", "B")); + assertEquals("b", fHelper("a", "A", "B")); + + assertEquals("b_", fHelper("a_", "A", "B")); + + fh("mAHahAHa", "mBHahAHa", "A", "B"); // match first occurrence + + } + + public void testEmbeddedMatching() { + + fPrefixes= new String[0]; + fSuffixes= new String[0]; + setStrategy(RenamingNameSuggestor.STRATEGY_EMBEDDED); + + mh("getJavaElement", "getNewJavaElement", "JavaElement", "NewJavaElement"); + mh("javaElement", "newJavaElement", "JavaElement", "NewJavaElement"); + + mh("createjavaElement", "createnewJavaElement", "JavaElement", "NewJavaElement"); + mh("getJavaElement", "getNewJavaElement", "IJavaElement", "INewJavaElement"); + + mhf("createJavaElementcache", "JavaElement", "NewJavaElement"); + + // match with "_" or "$" and other non-letters and non-digits at the next hunk + mh("someClass_pm", "someDifferentClass_pm", "SomeClass", "SomeDifferentClass"); + mh("someClass$$", "someDifferentClass$$", "SomeClass", "SomeDifferentClass"); + + // match a second type name + fh("createelementsecondElement", "createelementsecondMember", "Element", "Member"); + fh("createelementsecondelement", "createelementsecondmember", "Element", "Member"); + fhf("createelementsecondelementnomore", "Element", "Member"); + } + + public void testCamelCaseMatching() { + + fPrefixes= new String[0]; + fSuffixes= new String[0]; + setStrategy(RenamingNameSuggestor.STRATEGY_SUFFIX); + + // only the last camel case match + mh("getElement", "getMember", "JavaElement", "JavaMember"); + mh("getElement", "getMember", "IJavaElement", "IJavaMember"); + mh("getElement", "getMember", "AVeryLongJavaElement", "AVeryLongJavaMember"); + + // two + mh("getJavaElement", "getJavaMember", "SimpleJavaElement", "SimpleJavaMember"); + mh("getJavaElement", "getGeneralElement", "SimpleJavaElement", "SimpleGeneralElement"); + + //three + mh("getVeryLongJavaElement", "getSomeCompletelyDifferentName", "ExtremelyVeryLongJavaElement", "ExtremelySomeCompletelyDifferentName"); + + //some fields + fh("element", "member", "JavaElement", "JavaMember"); + fh("element", "member", "IJavaElement", "IJavaMember"); + + fh("javaElement", "javaMember", "JavaElement", "JavaMember"); + fh("cachedJavaElement", "cachedJavaMember", "JavaElement", "JavaMember"); + + fh("javaElement", "nonjavaMember", "JavaElement", "NonjavaMember"); + + // some methods + mh("getFreakyClass", "getLast", "FreakyClass", "Last"); + mh("Element", "Member", "SomeFreakyElement", "SomeFreakyMember"); + mh("createMyASTNode", "createMyNode", "MyASTNode", "MyNode"); + + // freaky stuff + + mh("getASTNode", "getASTElement", "ASTNode", "ASTElement"); + mh("getASTNode", "getTreeNode", "ASTNode", "TreeNode"); // ;) + mh("getASTHeaven2", "getNoBrainer", "ASTHeaven2", "NoBrainer"); + + fh("java$Element$", "javaElement", "Java$Element$", "JavaElement"); + + // suffixes inside the name + fh("theElementToUse", "theThingToUse", "JavaElement", "JavaThing"); + + // only match last hunk + mh("getJavaSomeElement", "getJavaSomeMember", "JavaElement", "JavaMember"); + mhf("getJavaSome", "JavaElement", "JavaMember"); + + // failures + + mhf("getElement", "JavaElementLabel", "JavaMemberLabel"); + mhf("getElementlabel", "JavaElement", "JavaMember"); + + fhf("myClass", "A", "B"); + + // avoid "silly" name suggestions + + fhf("fElement", "SomeLongElement", "AnotherDifferentElement"); //-> don't suggest renaming fElement to fElement! + + } + + public void testUpperCaseCamelCaseMatching() { + + fPrefixes= new String[] { "f" }; + fSuffixes= new String[0]; + + setStrategy(RenamingNameSuggestor.STRATEGY_EXACT); + + // complete uppercase camel case hunks + fh("fAST", "fAbstractSyntaxTree", "AST", "AbstractSyntaxTree"); + fh("AST", "AbstractSyntaxTree", "AST", "AbstractSyntaxTree"); + + // complete uppercase camel case hunks, but lowercased + fh("fAst", "fAbstractSyntaxTree", "AST", "AbstractSyntaxTree"); + fh("ast", "abstractSyntaxTree", "AST", "AbstractSyntaxTree"); + fh("aST", "abstractSyntaxTree", "AST", "AbstractSyntaxTree"); + + fh("fASTNode", "fAbstractSTNode", "ASTNode", "AbstractSTNode"); + fh("fASTNode", "fASTreeNode", "ASTNode", "ASTreeNode"); + + /* + * do not match: + * fh("fAstNode", "fAbstractSTNode", "ASTNode", "AbstractSTNode"); + * fh("fAstNode", "fAsTreeNode", "ASTNode", "ASTreeNode"); + * + * When changing all-uppercase hunks in exact or embedded mode, it is unclear + * which hunk in the new type name corresponds to the custom-lowercased hunk + * in the old variable name. Rather than guessing the hunk, we only + * proceed hunk-by-hunk in suffix mode. + */ + + setStrategy(RenamingNameSuggestor.STRATEGY_EMBEDDED); + + fh("fAst2", "fAbstractSyntaxTree2", "AST", "AbstractSyntaxTree"); + fh("aST2", "abstractSyntaxTree2", "AST", "AbstractSyntaxTree"); + + setStrategy(RenamingNameSuggestor.STRATEGY_SUFFIX); + + // partial uppercase camel case hunks + fh("fAST", "fMUST", "PersonalAST", "PersonalMUST"); + + // "downgrading" the new hunks + fh("fAst", "fMust", "PersonalAST", "PersonalMUST"); + fh("fHUNKPowered", "fMONKPowered", "ReallyHUNKPowered", "ReallyMONKPowered"); + + fh("fHunkPowered", "fMonkPowered", "ReallyHUNKPowered", "ReallyMONKPowered"); + fh("fHunkPowered", "fMonkPowered", "ReallyHUNKPowered", "ReallyMonkPowered"); + + fh("fHunkPowered", "fHunk2Powered", "HunkPowered", "Hunk2Powered"); + fh("powered", "powered2", "HunkPOWERED", "MonkPOWERED2"); + + // adapted middle hunks + fh("astNode", "fastNode", "ASTNode", "FASTNode"); + mh("createMyASTNode", "createMySECONDNode", "MyASTNode", "MySECONDNode"); + mh("createMyAstNode", "createMySecondNode", "MyASTNode", "MySECONDNode"); + + // some more methods + mh("createAST", "createAbstractSyntaxTree", "AST", "AbstractSyntaxTree"); + + // match new hunks + + fh("fASTNode", "fMyASTNode", "ASTNode", "MyASTNode"); + fh("fAstNode", "fMyAstNode", "ASTNode", "MyASTNode"); + fh("fDifferentAstNode", "fDifferentMyAstNode", "ASTNode", "MyASTNode"); + fh("fDifferentAstNodeToUse", "fDifferentMyAstNodeToUse", "ASTNode", "MyASTNode"); + + // propagating lowercased front + fh("astNode", "myAstNode", "ASTNode", "MyASTNode"); + + } + + public void testPluralS() { + + fPrefixes= new String[0]; + fSuffixes= new String[0]; + setStrategy(RenamingNameSuggestor.STRATEGY_EXACT); + fh("items", "things", "Item", "Thing"); + fh("handies", "mobilePhones", "Handy", "MobilePhone"); + fh("handy", "mobilePhone", "Handy", "MobilePhone"); + fh("mobilePhones", "handies", "MobilePhone", "Handy"); + fh("mobilePhone", "handy", "MobilePhone", "Handy"); + fh("handies", "mandies", "Handy", "Mandy"); + setStrategy(RenamingNameSuggestor.STRATEGY_EMBEDDED); + fh("itemsOnLoan", "thingsOnLoan", "Item", "Thing"); + fh("itemStuff", "thingStuff", "Item", "Thing"); //-> no plural s! + fh("someHandiesOnLoan", "someMobilePhonesOnLoan", "Handy", "MobilePhone"); + fh("someHandiesOnLoan", "someMandiesOnLoan", "Handy", "Mandy"); + setStrategy(RenamingNameSuggestor.STRATEGY_SUFFIX); + fh("someItemsOnLoan", "someThingsOnLoan", "ASTItem", "NOASTThing"); + fh("someHandiesOnLoan", "someMandiesOnLoan", "Handy", "Mandy"); + fh("someHandiesOnLoan", "someMobilePhonesOnLoan", "Handy", "MobilePhone"); + fh("somePhonesOnLoan", "someHandiesOnLoan", "MobilePhone", "Handy"); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ReplaceInvocationsTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ReplaceInvocationsTests.java new file mode 100644 index 000000000..02e7ba42b --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ReplaceInvocationsTests.java @@ -0,0 +1,101 @@ +/******************************************************************************* + * Copyright (c) 2006, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.Comment; +import org.eclipse.jdt.core.dom.CompilationUnit; + +import org.eclipse.jdt.internal.corext.refactoring.code.ReplaceInvocationsRefactoring; +import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser; + +public class ReplaceInvocationsTests extends AbstractSelectionTestCase { + private static RewriteMethodInvocationsTestSetup fgTestSetup; + + public ReplaceInvocationsTests(String name) { + super(name, true); + } + + public static Test suite() { + fgTestSetup= new RewriteMethodInvocationsTestSetup(new TestSuite(ReplaceInvocationsTests.class)); + return fgTestSetup; + } + + public static Test setUpTest(Test someTest) { + fgTestSetup= new RewriteMethodInvocationsTestSetup(someTest); + return fgTestSetup; + } + + protected void setUp() throws Exception { + super.setUp(); + fIsPreDeltaTest= true; + } + + protected String getResourceLocation() { + return "ReplaceInvocationsWorkspace/ReplaceInvocations/"; + } + + protected String adaptName(String name) { + return Character.toUpperCase(name.charAt(0)) + name.substring(1) + ".java"; + } + + private void performTestRewriteInvocations(IPackageFragment packageFragment, String id, int mode, String outputFolder) throws Exception { + ICompilationUnit unit= createCU(packageFragment, id); + int[] selection= getSelection(); + + CompilationUnit compilationUnit= new RefactoringASTParser(AST.JLS3).parse(unit, false); + Comment comment= (Comment) compilationUnit.getCommentList().get(0); + String commentString= unit.getBuffer().getText(comment.getStartPosition(), comment.getLength()); + Matcher matcher= Pattern.compile("(?s)/\\*\\s*params:[^\\r\\n&&\\s]*" + "([^\\r\\n]*)" + "(\\r\\n?|\\n)" + "(.+)" + "\\*/").matcher(commentString); + assertTrue(matcher.find()); + String paramsString= matcher.group(1); + String[] params= paramsString.length() == 0 ? new String[0] : paramsString.split("[\\s,]+"); + String body= matcher.group(3); + + ReplaceInvocationsRefactoring refactoring= new ReplaceInvocationsRefactoring(unit, selection[0], selection[1]); + refactoring.setBody(body, params); + + String out= null; + switch (mode) { + case COMPARE_WITH_OUTPUT: + out= getProofedContent(outputFolder, id); + break; + } + performTest(unit, refactoring, mode, out, true); + } + + /* *********************** Rewrite Invocations Tests ******************************* */ + + private void performRewriteTest() throws Exception { + performTestRewriteInvocations(fgTestSetup.getRewritePackage(), getName(), COMPARE_WITH_OUTPUT, "rewrite_out"); + } + + public void testSwitchParameters() throws Exception { + performRewriteTest(); + } + + public void testClassFile() throws Exception { + performRewriteTest(); + } + + public void testMultiple() throws Exception { + performRewriteTest(); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RewriteMethodInvocationsTestSetup.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RewriteMethodInvocationsTestSetup.java new file mode 100644 index 000000000..949d3316f --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RewriteMethodInvocationsTestSetup.java @@ -0,0 +1,36 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +public class RewriteMethodInvocationsTestSetup extends RefactoringTestSetup { + + private IPackageFragment fRewrite; + + public RewriteMethodInvocationsTestSetup(Test test) { + super(test); + } + + protected void setUp() throws Exception { + super.setUp(); + + IPackageFragmentRoot root= getDefaultSourceFolder(); + fRewrite= root.createPackageFragment("rewrite_in", true, null); + } + + public IPackageFragment getRewritePackage() { + return fRewrite; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RippleMethodFinderTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RippleMethodFinderTests.java new file mode 100644 index 000000000..d4de64d17 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RippleMethodFinderTests.java @@ -0,0 +1,143 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; + +import org.eclipse.jdt.internal.corext.refactoring.rename.RippleMethodFinder2; + +import org.eclipse.jdt.ui.tests.refactoring.infra.AbstractCUTestCase; +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringTestPlugin; + + +public class RippleMethodFinderTests extends AbstractCUTestCase { + + private final static boolean BUG_96761_core_finds_non_overriding= true; + + private static final Class clazz= RippleMethodFinderTests.class; + private static final String REFACTORING_PATH= "RippleMethodFinder/"; + private static final String TARGET= "/*target*/"; + private static final String RIPPLE= "/*ripple*/"; + + public RippleMethodFinderTests(String name) { + super(name); + } + + protected String getResourceLocation() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + protected InputStream getFileInputStream(String fileName) throws IOException { + return RefactoringTestPlugin.getDefault().getTestResourceStream(fileName); + } + + private void perform() throws Exception { + ICompilationUnit cu= null; + try { + IPackageFragment pack= RefactoringTestSetup.getPackageP(); + String name= adaptName("A_" + getName()); + cu= createCU(pack, name, getFileInputStream(getResourceLocation() + "/" + name)); + + String contents= cu.getBuffer().getContents(); + + IJavaElement[] elements= cu.codeSelect(contents.indexOf(TARGET) + TARGET.length(), 0); + assertEquals(1, elements.length); + IMethod target= (IMethod) elements[0]; + + List/*<IMethod>*/ rippleMethods= new ArrayList(); + rippleMethods.add(target); + int start= 0; + while (start < contents.length()) { + start= contents.indexOf(RIPPLE, start); + if (start == -1) + break; + elements= cu.codeSelect(start + RIPPLE.length(), 0); + assertEquals(1, elements.length); + IMethod rippleMethod= (IMethod) elements[0]; + rippleMethods.add(rippleMethod); + start++; + } + + IMethod[] result= RippleMethodFinder2.getRelatedMethods(target, new NullProgressMonitor(), null); + for (int i= 0; i < result.length; i++) { + IMethod method= result[i]; + assertTrue("method not found: " + method, rippleMethods.remove(method)); + } + assertEquals("found wrong ripple methods: " + rippleMethods, 0, rippleMethods.size()); + } finally { + if (cu != null) + cu.delete(true, null); + } + } + + public void test1() throws Exception { + perform(); + } + public void test2() throws Exception { + perform(); + } + public void test3() throws Exception { + perform(); + } + public void test4() throws Exception { + perform(); + } + public void test5() throws Exception { + perform(); + } + public void test6() throws Exception { + perform(); + } + public void test7() throws Exception { + perform(); + } + public void test8() throws Exception { + perform(); + } + public void test9() throws Exception { + perform(); + } + public void test10() throws Exception { + perform(); + } + public void test11() throws Exception { + if (BUG_96761_core_finds_non_overriding) + return; + perform(); + } + public void test12() throws Exception { + if (BUG_96761_core_finds_non_overriding) + return; + perform(); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SefTestSetup.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SefTestSetup.java new file mode 100644 index 000000000..c92d18094 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SefTestSetup.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +public class SefTestSetup extends RefactoringTestSetup { + + private IPackageFragment fBaseTypes; + private IPackageFragment fObjectTypes; + private IPackageFragment fInvalid; + private IPackageFragment fStatic; + private IPackageFragment fStaticRef; + private IPackageFragment fExistingMethod; + + public SefTestSetup(Test test) { + super(test); + } + + protected void setUp() throws Exception { + super.setUp(); + + IPackageFragmentRoot root= getDefaultSourceFolder(); + + fBaseTypes= root.createPackageFragment("base_in", true, null); + fObjectTypes= root.createPackageFragment("object_in", true, null); + fInvalid= root.createPackageFragment("invalid", true, null); + fStatic= root.createPackageFragment("static_in", true, null); + fStaticRef= root.createPackageFragment("static_ref_in", true, null); + fExistingMethod= root.createPackageFragment("existingmethods_in", true, null); + } + + public IPackageFragment getBasePackage() { + return fBaseTypes; + } + + public IPackageFragment getObjectPackage() { + return fObjectTypes; + } + + public IPackageFragment getInvalidPackage() { + return fInvalid; + } + + public IPackageFragment getStaticPackage() { + return fStatic; + } + + public IPackageFragment getStaticRefPackage() { + return fStaticRef; + } + + public IPackageFragment getExistingMethodPackage(){ + return fExistingMethod; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SefTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SefTests.java new file mode 100644 index 000000000..bb49d762f --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SefTests.java @@ -0,0 +1,308 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for + * bug Encapuslate field can fail when two variables in one variable declaration (see + * https://bugs.eclipse.org/bugs/show_bug.cgi?id=51540). + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.Hashtable; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.internal.corext.refactoring.Checks; +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; +import org.eclipse.jdt.internal.corext.refactoring.sef.SelfEncapsulateFieldRefactoring; + +public class SefTests extends AbstractSelectionTestCase { + + private static SefTestSetup fgTestSetup; + + public SefTests(String name) { + super(name); + } + + public static Test suite() { + fgTestSetup= new SefTestSetup(new TestSuite(SefTests.class)); + return fgTestSetup; + } + + public static Test setUpTest(Test test) { + fgTestSetup= new SefTestSetup(test); + return fgTestSetup; + } + + protected void setUp() throws Exception { + super.setUp(); + fIsPreDeltaTest= true; + } + + protected String getResourceLocation() { + return "SefWorkSpace/SefTests/"; + } + + protected String adaptName(String name) { + return Character.toUpperCase(name.charAt(0)) + name.substring(1) + ".java"; + } + + protected void performTest(IPackageFragment packageFragment, String id, String outputFolder, String fieldName) throws Exception { + ICompilationUnit unit= createCU(packageFragment, id); + IField field= getField(unit, fieldName); + assertNotNull(field); + + initializePreferences(); + + SelfEncapsulateFieldRefactoring refactoring= ((Checks.checkAvailability(field).hasFatalError() || !RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field)) ? null : new SelfEncapsulateFieldRefactoring(field)); + performTest(unit, refactoring, COMPARE_WITH_OUTPUT, getProofedContent(outputFolder, id), true); + } + + protected void performInvalidTest(IPackageFragment packageFragment, String id, String fieldName) throws Exception { + ICompilationUnit unit= createCU(packageFragment, id); + IField field= getField(unit, fieldName); + assertNotNull(field); + + initializePreferences(); + + SelfEncapsulateFieldRefactoring refactoring= ((Checks.checkAvailability(field).hasFatalError() || !RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field)) ? null : new SelfEncapsulateFieldRefactoring(field)); + if (refactoring != null) { + RefactoringStatus status= refactoring.checkAllConditions(new NullProgressMonitor()); + assertTrue(status.hasError()); + } + } + + private void initializePreferences() { + Hashtable options= new Hashtable(); + options.put(JavaCore.CODEASSIST_FIELD_PREFIXES, ""); + options.put(JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES, ""); + options.put(JavaCore.CODEASSIST_FIELD_SUFFIXES, ""); + options.put(JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES, ""); + JavaCore.setOptions(options); + } + + private static IField getField(ICompilationUnit unit, String fieldName) throws Exception { + IField result= null; + IType[] types= unit.getAllTypes(); + for (int i= 0; i < types.length; i++) { + IType type= types[i]; + result= type.getField(fieldName); + if (result != null && result.exists()) + break; + } + return result; + } + + private void objectTest(String fieldName) throws Exception { + performTest(fgTestSetup.getObjectPackage(), getName(), "object_out", fieldName); + } + + private void baseTest(String fieldName) throws Exception { + performTest(fgTestSetup.getBasePackage(), getName(), "base_out", fieldName); + } + + private void invalidTest(String fieldName) throws Exception { + performInvalidTest(fgTestSetup.getInvalidPackage(), getName(), fieldName); + } + + private void existingTest(String fieldName) throws Exception { + performTest(fgTestSetup.getExistingMethodPackage(), getName(), "existingmethods_out", fieldName); + } + //===================================================================================== + // Invalid + //===================================================================================== + + public void testPostfixExpression() throws Exception { + invalidTest("field"); + } + + public void testInvalidOverwrite() throws Exception { + invalidTest("field"); + } + + public void testAnnotation() throws Exception { + invalidTest("field"); + } + + //===================================================================================== + // Primitiv Data Test + //===================================================================================== + + public void testPrefixInt() throws Exception { + baseTest("field"); + } + + public void testPrefixBoolean() throws Exception { + baseTest("field"); + } + + public void testPostfixInt() throws Exception { + baseTest("field"); + } + + public void testThisExpression() throws Exception { + baseTest("field"); + } + + public void testThisExpressionInner() throws Exception { + baseTest("field"); + } + + public void testFinal() throws Exception { + baseTest("field"); + } + + public void testTwoFragments() throws Exception { + baseTest("field"); + } + + //===================================================================================== + // Basic Object Test + //===================================================================================== + + public void testSimpleRead() throws Exception { + objectTest("field"); + } + + public void testSimpleWrite() throws Exception { + objectTest("field"); + } + + public void testSimpleReadWrite() throws Exception { + objectTest("field"); + } + + public void testEnumRead() throws Exception { + objectTest("field"); + } + + public void testEnumReadWrite() throws Exception { + objectTest("field"); + } + + public void testNestedRead() throws Exception { + objectTest("field"); + } + + public void testArrayRead() throws Exception { + objectTest("field"); + } + + public void testCStyleArrayRead() throws Exception { + objectTest("field"); + } + + + public void testSetterInAssignment() throws Exception { + objectTest("field"); + } + + public void testSetterInExpression() throws Exception { + objectTest("field"); + } + + public void testSetterInInitialization() throws Exception { + objectTest("field"); + } + + public void testSetterAsReceiver() throws Exception { + objectTest("field"); + } + + public void testCompoundWrite() throws Exception { + objectTest("field"); + } + + public void testCompoundWrite2() throws Exception { + objectTest("field"); + } + + public void testCompoundWrite3() throws Exception { + objectTest("field"); + } + + public void testFinalField() throws Exception { + objectTest("field"); + } + + public void testGenericRead() throws Exception { + objectTest("field"); + } + + public void testGenericRead2() throws Exception { + objectTest("field"); + } + + public void testGenericReadWrite() throws Exception { + objectTest("field"); + } + + //===================================================================================== + // static import tests + //===================================================================================== + + private void performStaticImportTest(String referenceName) throws Exception, JavaModelException { + ICompilationUnit provider= createCU(fgTestSetup.getStaticPackage(), getName()); + ICompilationUnit reference= createCU(fgTestSetup.getStaticRefPackage(), referenceName); + + IField field= getField(provider, "x"); + assertNotNull(field); + + initializePreferences(); + + SelfEncapsulateFieldRefactoring refactoring= ((Checks.checkAvailability(field).hasFatalError() || !RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field)) ? null : new SelfEncapsulateFieldRefactoring(field)); + performTest(provider, refactoring, COMPARE_WITH_OUTPUT, getProofedContent("static_out", getName()), false); + String refContentOut= getProofedContent("static_ref_out", referenceName); + refContentOut= refContentOut.replaceAll("import static static_out", "import static static_in"); + compareSource(reference.getSource(), refContentOut); + } + + public void testStaticImportRead() throws Exception { + performStaticImportTest("StaticImportReadReference"); + } + + public void testStaticImportWrite() throws Exception { + performStaticImportTest("StaticImportWriteReference"); + } + + public void testStaticImportReadWrite() throws Exception { + performStaticImportTest("StaticImportReadWriteReference"); + } + + public void testStaticImportNone() throws Exception { + performStaticImportTest("StaticImportNoReference"); + } + + //===================================================================================== + // existing getter/setter + //===================================================================================== + + public void testThisExpressionInnerWithSetter() throws Exception { + existingTest("field"); + } + + public void testThisExpressionWithGetterSetter() throws Exception { + existingTest("field"); + } + + public void testTwoFragmentsWithSetter() throws Exception { + existingTest("field"); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTestSetup.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTestSetup.java new file mode 100644 index 000000000..97590ee92 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTestSetup.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.Hashtable; + +import junit.extensions.TestSetup; +import junit.framework.Test; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.ltk.core.refactoring.RefactoringCore; + +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +import org.eclipse.jdt.internal.ui.JavaPlugin; +import org.eclipse.jdt.internal.ui.util.CoreUtility; + + +public class SurroundWithTestSetup extends TestSetup { + + private IJavaProject fJavaProject; + private IPackageFragmentRoot fRoot; + private static final String CONTAINER= "src"; + + private IPackageFragment fTryCatchPackage; + + public SurroundWithTestSetup(Test test) { + super(test); + } + + public IPackageFragmentRoot getRoot() { + return fRoot; + } + + protected void setUp() throws Exception { + super.setUp(); + + Hashtable options= TestOptions.getDefaultOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.TAB); + options.put(DefaultCodeFormatterConstants.FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE, "0"); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); + JavaCore.setOptions(options); + TestOptions.initializeCodeGenerationOptions(); + JavaPlugin.getDefault().getCodeTemplateStore().load(); + + fJavaProject= JavaProjectHelper.createJavaProject("TestProject", "bin"); + JavaProjectHelper.addRTJar(fJavaProject); + fRoot= JavaProjectHelper.addSourceContainer(fJavaProject, CONTAINER); + + RefactoringCore.getUndoManager().flush(); + CoreUtility.setAutoBuilding(false); + + fTryCatchPackage= getRoot().createPackageFragment("trycatch_in", true, null); + StubUtility.setCodeTemplate(CodeTemplateContextType.CATCHBLOCK_ID, "", null); + } + + protected void tearDown() throws Exception { + super.tearDown(); + RefactoringTest.performDummySearch(fJavaProject); + JavaProjectHelper.delete(fJavaProject); + } + + public IPackageFragment getTryCatchPackage() { + return fTryCatchPackage; + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTests.java new file mode 100644 index 000000000..afb3f427a --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTests.java @@ -0,0 +1,212 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring; + +public class SurroundWithTests extends AbstractSelectionTestCase { + + private static SurroundWithTestSetup fgTestSetup; + + public SurroundWithTests(String name) { + super(name); + } + + public static Test suite() { + fgTestSetup= new SurroundWithTestSetup(new TestSuite(SurroundWithTests.class)); + return fgTestSetup; + } + + public static Test setUpTest(Test someTest) { + fgTestSetup= new SurroundWithTestSetup(someTest); + return fgTestSetup; + } + + protected IPackageFragmentRoot getRoot() { + return fgTestSetup.getRoot(); + } + + protected String getResourceLocation() { + return "SurroundWithWorkSpace/SurroundWithTests/"; + } + + protected String adaptName(String name) { + return Character.toUpperCase(name.charAt(0)) + name.substring(1) + ".java"; + } + + protected void performTest(IPackageFragment packageFragment, String name, String outputFolder, int mode) throws Exception { + ICompilationUnit unit= createCU(packageFragment, name); + SurroundWithTryCatchRefactoring refactoring= SurroundWithTryCatchRefactoring.create(unit, getTextSelection()); + String out= null; + if (mode == COMPARE_WITH_OUTPUT) + out= getProofedContent(outputFolder, name); + performTest(unit, refactoring, mode, out, true); + } + + protected void tryCatchInvalidTest() throws Exception { + performTest(fgTestSetup.getTryCatchPackage(), getName(), "trycatch_out", INVALID_SELECTION); + } + + protected void tryCatchTest() throws Exception { + performTest(fgTestSetup.getTryCatchPackage(), getName(), "trycatch_out", COMPARE_WITH_OUTPUT); + } + + public void testNoException() throws Exception { + tryCatchTest(); + } + + public void testAlreadyCaught() throws Exception { + tryCatchTest(); + } + + public void testInvalidParent1() throws Exception { + tryCatchInvalidTest(); + } + + public void testInvalidParent2() throws Exception { + tryCatchInvalidTest(); + } + + public void testThisConstructorCall() throws Exception { + tryCatchInvalidTest(); + } + + public void testSuperConstructorCall() throws Exception { + tryCatchInvalidTest(); + } + + public void testSimple() throws Exception { + tryCatchTest(); + } + + public void testOneLine() throws Exception { + tryCatchTest(); + } + + public void testMultiLine() throws Exception { + tryCatchTest(); + } + + public void testExceptionOrder() throws Exception { + tryCatchTest(); + } + + public void testWrappedLocal1() throws Exception { + tryCatchTest(); + } + + public void testWrappedLocal2() throws Exception { + tryCatchTest(); + } + + public void testWrappedLocal3() throws Exception { + tryCatchTest(); + } + + public void testWrappedLocal4() throws Exception { + tryCatchTest(); + } + + public void testWrappedLocal5() throws Exception { + tryCatchTest(); + } + + public void testWrappedLocal6() throws Exception { + tryCatchTest(); + } + + public void testWrappedLocal7() throws Exception { + tryCatchTest(); + } + + public void testWrappedLocal8() throws Exception { + tryCatchTest(); + } + + public void testInitializerThrowsException() throws Exception { + tryCatchTest(); + } + + public void testThrowInCatch() throws Exception { + tryCatchTest(); + } + + public void testExpression() throws Exception { + tryCatchTest(); + } + + public void testExpressionStatement() throws Exception { + tryCatchTest(); + } + + public void testInitializer() throws Exception { + tryCatchTest(); + } + + public void testSuperCall() throws Exception { + tryCatchTest(); + } + + public void testRuntimeException1() throws Exception { + tryCatchTest(); + } + + public void testNested() throws Exception { + tryCatchTest(); + } + + public void testRuntimeException2() throws Exception { + tryCatchTest(); + } + + public void testStaticField() throws Exception { + tryCatchInvalidTest(); + } + + public void testDeclarationInitializer() throws Exception { + tryCatchTest(); + } + + public void testThenStatement() throws Exception { + tryCatchTest(); + } + + public void testEnum1() throws Exception { + tryCatchTest(); + } + + public void testEnum2() throws Exception { + tryCatchTest(); + } + + public void testGeneric1() throws Exception { + tryCatchTest(); + } + + public void testGeneric2() throws Exception { + tryCatchTest(); + } + + public void testMethodThrowsException() throws Exception { + tryCatchTest(); + } + + public void testMethodThrowsException1() throws Exception { + tryCatchTest(); + } +}
\ No newline at end of file diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestChangeMethodSignaturParticipant.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestChangeMethodSignaturParticipant.java new file mode 100644 index 000000000..5e74f89e1 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestChangeMethodSignaturParticipant.java @@ -0,0 +1,119 @@ +/******************************************************************************* + * Copyright (c) 2007, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Assert; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.OperationCanceledException; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; + +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.Signature; +import org.eclipse.jdt.core.refactoring.participants.ChangeMethodSignatureArguments; +import org.eclipse.jdt.core.refactoring.participants.ChangeMethodSignatureParticipant; +import org.eclipse.jdt.core.refactoring.participants.ChangeMethodSignatureArguments.Parameter; +import org.eclipse.jdt.core.refactoring.participants.ChangeMethodSignatureArguments.ThrownException; + +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; +import org.eclipse.jdt.internal.corext.util.JdtFlags; + +public class TestChangeMethodSignaturParticipant extends ChangeMethodSignatureParticipant { + + static TestChangeMethodSignaturParticipant fgInstance; + + public static void testParticipant(IType type) throws JavaModelException { + Assert.assertNotNull(fgInstance); + fgInstance.test(type); + } + + private void test(IType type) throws JavaModelException { + Assert.assertNotNull(fElement); + Assert.assertNotNull(fArguments); + + JavaModelUtil.reconcile(type.getCompilationUnit()); + + String name= fArguments.getNewName(); + Parameter[] newParameters= fArguments.getNewParameters(); + String[] parameterTypesSigs= new String[newParameters.length]; + for (int i= 0; i < parameterTypesSigs.length; i++) { + parameterTypesSigs[i]= newParameters[i].getType(); + } + + IMethod newMethod= JavaModelUtil.findMethod(name, parameterTypesSigs, fIsConstructor, type); + Assert.assertNotNull(newMethod); + + assertEqualSignature(newMethod.getReturnType(), fArguments.getNewReturnType()); + Assert.assertEquals(JdtFlags.getVisibilityCode(newMethod), fArguments.getNewVisibility()); + + String[] parameterNames= newMethod.getParameterNames(); + for (int i= 0; i < newParameters.length; i++) { + Assert.assertEquals(parameterNames[i], newParameters[i].getName()); + } + + ThrownException[] thrownExceptions= fArguments.getThrownExceptions(); + String[] exceptionTypes= newMethod.getExceptionTypes(); + Assert.assertEquals(exceptionTypes.length, thrownExceptions.length); + + for (int i= 0; i < exceptionTypes.length; i++) { + assertEqualSignature(exceptionTypes[i], thrownExceptions[i].getType()); + } + } + + private static void assertEqualSignature(String expected, String actual) { + if (!expected.equals(actual)) { + String t1= Signature.getSimpleName(Signature.toString(expected)); + String t2= Signature.getSimpleName(Signature.toString(actual)); + if (!t1.equals(t2)) { + Assert.assertEquals(expected, actual); + } + } + } + + private Object fElement; + private boolean fIsConstructor; + private ChangeMethodSignatureArguments fArguments; + + public TestChangeMethodSignaturParticipant() { + } + + public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) throws OperationCanceledException { + return new RefactoringStatus(); + } + + public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { + return null; + } + + public String getName() { + return getClass().getName(); + } + + protected boolean initialize(Object element) { + fgInstance= this; + fElement= element; + fArguments= getArguments(); + try { + fIsConstructor= ((IMethod) element).isConstructor(); + } catch (JavaModelException e) { + e.printStackTrace(); + } + + return true; + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestCopyParticipantShared.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestCopyParticipantShared.java new file mode 100644 index 000000000..ac739f971 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestCopyParticipantShared.java @@ -0,0 +1,125 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Assert; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; +import org.eclipse.ltk.core.refactoring.participants.CopyArguments; +import org.eclipse.ltk.core.refactoring.participants.CopyParticipant; +import org.eclipse.ltk.core.refactoring.participants.ISharableParticipant; +import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments; +import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog; + +import org.eclipse.jdt.core.IJavaElement; + +import org.eclipse.jdt.internal.corext.util.JavaElementResourceMapping; + +public class TestCopyParticipantShared extends CopyParticipant implements ISharableParticipant { + + static TestCopyParticipantShared fgInstance; + + List fElements= new ArrayList(3); + List fHandles= new ArrayList(3); + List fArguments= new ArrayList(3); + + public boolean initialize(Object element) { + fgInstance= this; + fElements.add(element); + fArguments.add(getArguments()); + if (element instanceof IJavaElement) { + fHandles.add(((IJavaElement)element).getHandleIdentifier()); + } else if (element instanceof IResource) { + fHandles.add(((IResource)element).getFullPath().toString()); + } else if (element instanceof JavaElementResourceMapping) { + fHandles.add(((JavaElementResourceMapping)element). + getJavaElement().getHandleIdentifier() + "_mapping"); + } + return true; + } + + public void addElement(Object element, RefactoringArguments args) { + fElements.add(element); + fArguments.add(args); + if (element instanceof IJavaElement) { + fHandles.add(((IJavaElement)element).getHandleIdentifier()); + } else if (element instanceof IResource) { + fHandles.add(((IResource)element).getFullPath().toString()); + } else if (element instanceof JavaElementResourceMapping) { + fHandles.add(((JavaElementResourceMapping)element).getJavaElement().getHandleIdentifier() + "_mapping"); + } + } + + public String getName() { + return getClass().getName(); + } + + public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) { + return new RefactoringStatus(); + } + + public Change createChange(IProgressMonitor pm) throws CoreException { + return null; + } + + public static void testNumberOfElements(int expected) { + if (expected == 0) { + Assert.assertTrue(fgInstance == null); + } else { + Assert.assertEquals(expected, fgInstance.fElements.size()); + Assert.assertEquals(expected, fgInstance.fArguments.size()); + } + } + + public static void testArguments(CopyArguments[] args) { + testNumberOfElements(args.length); + for (int i= 0; i < args.length; i++) { + CopyArguments expected= args[i]; + CopyArguments actual= (CopyArguments)fgInstance.fArguments.get(i); + compareArguments(expected, actual); + } + } + + public static void compareArguments(CopyArguments expected, CopyArguments actual) { + Assert.assertEquals("Destination: ", expected.getDestination(), actual.getDestination()); + compareExecutionLog(expected.getExecutionLog(), actual.getExecutionLog()); + } + + private static void compareExecutionLog(ReorgExecutionLog expected, ReorgExecutionLog actual) { + Assert.assertEquals("Canceled: ", expected.isCanceled(), actual.isCanceled()); + Object[] expectedRenamed= expected.getRenamedElements(); + Object[] actualRenamed= actual.getRenamedElements(); + Assert.assertEquals(expectedRenamed.length, actualRenamed.length); + for (int j= 0; j < expectedRenamed.length; j++) { + Assert.assertEquals(expected.getNewName(expectedRenamed[j]), actual.getNewName(actualRenamed[j])); + } + Object[] expectedProcessed= expected.getProcessedElements(); + Object[] actualProcessed= actual.getProcessedElements(); + Assert.assertEquals(expectedProcessed.length, actualProcessed.length); + for (int j= 0; j < expectedProcessed.length; j++) { + Assert.assertEquals(expectedProcessed[j], actualProcessed[j]); + } + } + + public static void reset() { + fgInstance= null; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestCopyParticipantSingle.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestCopyParticipantSingle.java new file mode 100644 index 000000000..ba3965213 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestCopyParticipantSingle.java @@ -0,0 +1,99 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import junit.framework.Assert; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; +import org.eclipse.ltk.core.refactoring.participants.CopyArguments; +import org.eclipse.ltk.core.refactoring.participants.CopyParticipant; + +import org.eclipse.jdt.core.IJavaElement; + +import org.eclipse.jdt.internal.corext.util.JavaElementResourceMapping; + +public class TestCopyParticipantSingle extends CopyParticipant { + + static List fgInstances= new ArrayList(); + + private Object fElement; + private String fHandle; + + public boolean initialize(Object element) { + fgInstances.add(this); + fElement= element; + ref(fElement); + if (fElement instanceof IJavaElement) { + fHandle= ((IJavaElement)fElement).getHandleIdentifier(); + } else if (fElement instanceof IResource) { + fHandle= ((IResource)fElement).getFullPath().toString(); + } else if (element instanceof JavaElementResourceMapping) { + fHandle= ((JavaElementResourceMapping)element). + getJavaElement().getHandleIdentifier() + "_mapping"; + } + return true; + } + + public String getName() { + return getClass().getName(); + } + + public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) { + return new RefactoringStatus(); + } + + public Change createChange(IProgressMonitor pm) throws CoreException { + return null; + } + + public static void testNumberOfInstances(int instances) { + Assert.assertEquals(instances, fgInstances.size()); + } + + public static void testElements(String[] handles) { + testNumberOfInstances(handles.length); + List l1= new ArrayList(Arrays.asList(handles)); + for (int i= 0; i < l1.size(); i++) { + Assert.assertTrue(l1.contains(getInstance(i).fHandle)); + } + } + + public static void testArguments(CopyArguments[] args) { + testNumberOfInstances(args.length); + for (int i= 0; i < args.length; i++) { + CopyArguments expected= args[i]; + CopyArguments actual= getInstance(i).getArguments(); + TestCopyParticipantShared.compareArguments(expected, actual); + } + } + + public static void reset() { + fgInstances= new ArrayList(); + } + + private static TestCopyParticipantSingle getInstance(int i) { + return ((TestCopyParticipantSingle)fgInstances.get(i)); + } + + /* package */ void ref(Object element) { + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestCreateParticipantShared.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestCreateParticipantShared.java new file mode 100644 index 000000000..5bfdb4c21 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestCreateParticipantShared.java @@ -0,0 +1,88 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Assert; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; +import org.eclipse.ltk.core.refactoring.participants.CreateParticipant; +import org.eclipse.ltk.core.refactoring.participants.ISharableParticipant; +import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments; + +import org.eclipse.jdt.core.IJavaElement; + +public class TestCreateParticipantShared extends CreateParticipant implements ISharableParticipant { + + static TestCreateParticipantShared fgInstance; + + List fElements= new ArrayList(3); + List fHandles= new ArrayList(3); + List fArguments= new ArrayList(3); + + public boolean initialize(Object element) { + fgInstance= this; + fElements.add(element); + fArguments.add(getArguments()); + if (element instanceof IJavaElement) + fHandles.add(((IJavaElement)element).getHandleIdentifier()); + else + fHandles.add(((IResource)element).getFullPath().toString()); + return true; + } + + public void addElement(Object element, RefactoringArguments args) { + fElements.add(element); + fArguments.add(args); + if (element instanceof IJavaElement) + fHandles.add(((IJavaElement)element).getHandleIdentifier()); + else + fHandles.add(((IResource)element).getFullPath().toString()); + } + + public String getName() { + return getClass().getName(); + } + + public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) { + return new RefactoringStatus(); + } + + public Change createChange(IProgressMonitor pm) throws CoreException { + return null; + } + + public static void testNumberOfElements(int expected) { + if (expected == 0) { + Assert.assertTrue(fgInstance == null); + } else { + Assert.assertEquals(expected, fgInstance.fElements.size()); + Assert.assertEquals(expected, fgInstance.fArguments.size()); + } + } + + public static void reset() { + fgInstance= null; + } + + public static boolean isLoaded() { + return fgInstance != null; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestCreateParticipantSingle.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestCreateParticipantSingle.java new file mode 100644 index 000000000..2809ae47e --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestCreateParticipantSingle.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import junit.framework.Assert; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; +import org.eclipse.ltk.core.refactoring.participants.CreateParticipant; + +import org.eclipse.jdt.core.IJavaElement; + +public class TestCreateParticipantSingle extends CreateParticipant { + + private static List fgInstances= new ArrayList(); + + private Object fElement; + private String fHandle; + + public boolean initialize(Object element) { + fgInstances.add(this); + fElement= element; + ref(fElement); + if (fElement instanceof IJavaElement) { + fHandle= ((IJavaElement)fElement).getHandleIdentifier(); + } else { + fHandle= ((IResource)fElement).getFullPath().toString(); + } + return true; + } + + public String getName() { + return getClass().getName(); + } + + public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) { + return new RefactoringStatus(); + } + + public Change createChange(IProgressMonitor pm) throws CoreException { + return null; + } + + public static void testNumberOfInstances(int instances) { + Assert.assertEquals(instances, fgInstances.size()); + } + + public static void testElements(Class[] classes) { + testNumberOfInstances(classes.length); + for (int i= 0; i < classes.length; i++) { + Assert.assertTrue(classes[i].isInstance(getInstance(i).fElement)); + } + } + + public static void testElements(String[] handles) { + testNumberOfInstances(handles.length); + List l1= new ArrayList(Arrays.asList(handles)); + for (int i= 0; i < l1.size(); i++) { + Assert.assertTrue(l1.contains(getInstance(i).fHandle)); + } + } + + public static void reset() { + fgInstances= new ArrayList(); + } + + private static TestCreateParticipantSingle getInstance(int i) { + return ((TestCreateParticipantSingle)fgInstances.get(i)); + } + + /* package */ void ref(Object element) { + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestDeleteParticipantShared.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestDeleteParticipantShared.java new file mode 100644 index 000000000..d2dc137c7 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestDeleteParticipantShared.java @@ -0,0 +1,88 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Assert; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; +import org.eclipse.ltk.core.refactoring.participants.DeleteParticipant; +import org.eclipse.ltk.core.refactoring.participants.ISharableParticipant; +import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments; + +import org.eclipse.jdt.core.IJavaElement; + +public class TestDeleteParticipantShared extends DeleteParticipant implements ISharableParticipant { + + static TestDeleteParticipantShared fgInstance; + + List fElements= new ArrayList(3); + List fHandles= new ArrayList(3); + List fArguments= new ArrayList(3); + + public boolean initialize(Object element) { + fgInstance= this; + fElements.add(element); + fArguments.add(getArguments()); + if (element instanceof IJavaElement) + fHandles.add(((IJavaElement)element).getHandleIdentifier()); + else + fHandles.add(((IResource)element).getFullPath().toString()); + return true; + } + + public void addElement(Object element, RefactoringArguments args) { + fElements.add(element); + fArguments.add(args); + if (element instanceof IJavaElement) + fHandles.add(((IJavaElement)element).getHandleIdentifier()); + else + fHandles.add(((IResource)element).getFullPath().toString()); + } + + public String getName() { + return getClass().getName(); + } + + public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) { + return new RefactoringStatus(); + } + + public Change createChange(IProgressMonitor pm) throws CoreException { + return null; + } + + public static void testNumberOfElements(int expected) { + if (expected == 0) { + Assert.assertTrue(fgInstance == null); + } else { + Assert.assertEquals(expected, fgInstance.fElements.size()); + Assert.assertEquals(expected, fgInstance.fArguments.size()); + } + } + + public static void reset() { + fgInstance= null; + } + + public static boolean isLoaded() { + return fgInstance != null; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestDeleteParticipantSingle.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestDeleteParticipantSingle.java new file mode 100644 index 000000000..4d9e6e8a0 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestDeleteParticipantSingle.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import junit.framework.Assert; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; +import org.eclipse.ltk.core.refactoring.participants.DeleteParticipant; + +import org.eclipse.jdt.core.IJavaElement; + +public class TestDeleteParticipantSingle extends DeleteParticipant { + + private static List fgInstances= new ArrayList(); + + private Object fElement; + private String fHandle; + + public boolean initialize(Object element) { + fgInstances.add(this); + fElement= element; + ref(fElement); + if (fElement instanceof IJavaElement) { + fHandle= ((IJavaElement)fElement).getHandleIdentifier(); + } else { + fHandle= ((IResource)fElement).getFullPath().toString(); + } + return true; + } + + public String getName() { + return getClass().getName(); + } + + public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) { + return new RefactoringStatus(); + } + + public Change createChange(IProgressMonitor pm) throws CoreException { + return null; + } + + public static void testNumberOfInstances(int instances) { + Assert.assertEquals(instances, fgInstances.size()); + } + + public static void testElements(Class[] classes) { + testNumberOfInstances(classes.length); + for (int i= 0; i < classes.length; i++) { + Assert.assertTrue(classes[i].isInstance(getInstance(i).fElement)); + } + } + + public static void testElements(String[] handles) { + testNumberOfInstances(handles.length); + List l1= new ArrayList(Arrays.asList(handles)); + for (int i= 0; i < l1.size(); i++) { + Assert.assertTrue(l1.contains(getInstance(i).fHandle)); + } + } + + public static void reset() { + fgInstances= new ArrayList(); + } + + private static TestDeleteParticipantSingle getInstance(int i) { + return ((TestDeleteParticipantSingle)fgInstances.get(i)); + } + + /* package */ void ref(Object element) { + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestModelProvider.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestModelProvider.java new file mode 100644 index 000000000..f456fd1a7 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestModelProvider.java @@ -0,0 +1,285 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +import junit.framework.Assert; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.resources.IResourceDeltaVisitor; +import org.eclipse.core.resources.mapping.ModelProvider; + +public class TestModelProvider extends ModelProvider { + + private static class Sorter implements Comparator { + public int compare(Object o1, Object o2) { + IResourceDelta d1= (IResourceDelta) o1; + IResourceDelta d2= (IResourceDelta) o2; + return d1.getResource().getFullPath().toPortableString().compareTo( + d2.getResource().getFullPath().toPortableString()); + } + } + + private static final Comparator COMPARATOR= new Sorter(); + + public static IResourceDelta LAST_DELTA; + public static boolean IS_COPY_TEST; + + private static final int PRE_DELTA_FLAGS= IResourceDelta.CONTENT | IResourceDelta.MOVED_TO | + IResourceDelta.MOVED_FROM | IResourceDelta.OPEN; + + public static void clearDelta() { + LAST_DELTA= null; + } + + public IStatus validateChange(IResourceDelta delta, IProgressMonitor pm) { + LAST_DELTA= delta; + return super.validateChange(delta, pm); + } + + public static void assertTrue(IResourceDelta expected) { + Assert.assertNotNull(LAST_DELTA); + boolean res= assertTrue(expected, LAST_DELTA); + if (!res) { + Assert.assertEquals(printDelta(expected), printDelta(LAST_DELTA)); + } + + LAST_DELTA= null; + } + + private static boolean assertTrue(IResourceDelta expected, IResourceDelta actual) { + assertEqual(expected.getResource(), actual.getResource()); + int actualKind= actual.getKind(); + int actualFlags= actual.getFlags(); + // The real delta can't combine kinds so we remove it from the received one as well. + if ((actualKind & (IResourceDelta.ADDED | IResourceDelta.REMOVED)) != 0) { + actualKind= actualKind & ~IResourceDelta.CHANGED; + } + + // The expected delta doesn't support copy from flag. So remove it + actualFlags= actualFlags & ~IResourceDelta.COPIED_FROM; + + int expectKind= expected.getKind(); + int expectedFlags= expected.getFlags() & PRE_DELTA_FLAGS; + if ((expectKind & IResourceDelta.ADDED) != 0 && (expectedFlags & IResourceDelta.MOVED_FROM) != 0) { + expectedFlags= expectedFlags & ~IResourceDelta.OPEN; + } + if (expectKind != actualKind || expectedFlags != actualFlags) { + return false; + } + IResourceDelta[] expectedChildren= getExpectedChildren(expected); + IResourceDelta[] actualChildren= getActualChildren(actual, expectedChildren); + if (expectedChildren.length != actualChildren.length) { + return false; + } + Arrays.sort(expectedChildren, COMPARATOR); + Arrays.sort(actualChildren, COMPARATOR); + for (int i= 0; i < expectedChildren.length; i++) { + boolean res= assertTrue(expectedChildren[i], actualChildren[i]); + if (!res) { + Assert.assertEquals(printDelta(expected), printDelta(actual)); + } + } + return true; + } + + private static String printDelta(IResourceDelta delta) { + StringBuffer buf= new StringBuffer(); + appendDelta(delta, 0, buf); + return buf.toString(); + } + + private static StringBuffer appendDelta(IResourceDelta delta, int indent, StringBuffer buf) { + for (int i= 0; i < indent; i++) { + buf.append(" "); + } + buf.append(delta.getResource().toString()); + buf.append("-").append(getKindString(delta.getKind())); + int flags= delta.getKind(); + if (flags != 0) { + buf.append("-").append(getFlagString(flags)).append('\n'); + } + + IResourceDelta[] affectedChildren= delta.getAffectedChildren(); + Arrays.sort(affectedChildren, COMPARATOR); + + for (int i= 0; i < affectedChildren.length; i++) { + appendDelta(affectedChildren[i], indent + 1, buf); + } + return buf; + } + + + + private static String getKindString(int kind) { + switch (kind) { + case IResourceDelta.CHANGED: + return "CHANGED"; + case IResourceDelta.ADDED: + return "ADDED"; + case IResourceDelta.REMOVED: + return "REMOVED"; + case IResourceDelta.ADDED_PHANTOM: + return "ADDED_PHANTOM"; + case IResourceDelta.REMOVED_PHANTOM: + return "REMOVED_PHANTOM"; + default: + return "NULL"; + } + } + + private static String getFlagString(int flags) { + StringBuffer buf= new StringBuffer(); + appendFlag(flags, IResourceDelta.CONTENT, "CONTENT", buf); + appendFlag(flags, IResourceDelta.DESCRIPTION, "DESCRIPTION", buf); + appendFlag(flags, IResourceDelta.ENCODING, "ENCODING", buf); + appendFlag(flags, IResourceDelta.OPEN, "OPEN", buf); + appendFlag(flags, IResourceDelta.MOVED_TO, "MOVED_TO", buf); + appendFlag(flags, IResourceDelta.MOVED_FROM, "MOVED_FROM", buf); + appendFlag(flags, IResourceDelta.TYPE, "TYPE", buf); + appendFlag(flags, IResourceDelta.SYNC, "SYNC", buf); + appendFlag(flags, IResourceDelta.MARKERS, "MARKERS", buf); + appendFlag(flags, IResourceDelta.REPLACED, "REPLACED", buf); + return buf.toString(); + } + + private static void appendFlag(int flags, int flag, String name, StringBuffer res) { + if ((flags & flag) != 0) { + if (res.length() > 0) { + res.append("-"); + } + res.append(name); + } + } + + + + private static void assertEqual(IResource expected, IResource actual) { + // This is a simple approach to deal with renamed resources in the deltas. + // However it will not work if there is more than on child per delta since + // the children will be sorted and their order might change. + if (IS_COPY_TEST) { + IPath expectedPath= expected.getFullPath(); + IPath actualPath= actual.getFullPath(); + Assert.assertEquals("Same path length", expectedPath.segmentCount(), actualPath.segmentCount()); + for(int i= 0; i < expectedPath.segmentCount(); i++) { + String expectedSegment= expectedPath.segment(i); + if (expectedSegment.startsWith("UnusedName") || expectedSegment.equals("unusedName")) + continue; + Assert.assertEquals("Different path segment", expectedSegment, actualPath.segment(i)); + } + } else { + Assert.assertEquals("Same resource", expected, actual); + } + } + + private static IResourceDelta[] getExpectedChildren(IResourceDelta delta) { + List result= new ArrayList(); + IResourceDelta[] children= delta.getAffectedChildren(); + for (int i= 0; i < children.length; i++) { + IResourceDelta child= children[i]; + IResource resource= child.getResource(); + if (resource != null && isIgnorable(resource)) + continue; + if (child.getAffectedChildren().length > 0) { + result.add(child); + } else { + int flags= child.getFlags(); + if (flags == 0 || (flags & PRE_DELTA_FLAGS) != 0) { + result.add(child); + } + } + } + return (IResourceDelta[]) result.toArray(new IResourceDelta[result.size()]); + } + + private static boolean isIgnorable(IResource resource) { + final String name= resource.getName(); + if (resource.getType() != IResource.FOLDER) + return false; + return name.startsWith("."); + } + + private static IResourceDelta[] getActualChildren(IResourceDelta delta, IResourceDelta[] expectedChildren) { + List result= new ArrayList(); + if (!IS_COPY_TEST) { + IResourceDelta[] children= delta.getAffectedChildren(); + for (int i= 0; i < children.length; i++) { + IResourceDelta child= children[i]; + IResource resource= child.getResource(); + if (resource != null && isIgnorable(resource)) + continue; + result.add(child); + } + } else { + IResourceDelta[] candidates= delta.getAffectedChildren(); + for (int i= 0; i < candidates.length; i++) { + IResourceDelta candidate= candidates[i]; + IResource resource= candidate.getResource(); + if (resource != null && isIgnorable(resource)) + continue; + if (contains(expectedChildren, candidate)) { + result.add(candidate); + } else { + assertCopySource(candidate); + } + } + } + return (IResourceDelta[]) result.toArray(new IResourceDelta[result.size()]); + } + + private static boolean contains(IResourceDelta[] expectedChildren, IResourceDelta actualDelta) { + IResource actualResource= actualDelta.getResource(); + for (int i= 0; i < expectedChildren.length; i++) { + if (isSameResourceInCopy(expectedChildren[i].getResource(), actualResource)) + return true; + } + return false; + } + + private static boolean isSameResourceInCopy(IResource expected, IResource actual) { + IPath expectedPath= expected.getFullPath(); + IPath actualPath= actual.getFullPath(); + if (expectedPath.segmentCount()!= actualPath.segmentCount()) + return false; + for(int i= 0; i < expectedPath.segmentCount(); i++) { + String expectedSegment= expectedPath.segment(i); + if (expectedSegment.startsWith("UnusedName") || expectedSegment.equals("unusedName")) + continue; + if (!expectedSegment.equals(actualPath.segment(i))) + return false; + } + return true; + } + + private static void assertCopySource(IResourceDelta delta) { + try { + delta.accept(new IResourceDeltaVisitor() { + public boolean visit(IResourceDelta d) throws CoreException { + Assert.assertTrue("Not a copy delta", (d.getKind() & ~IResourceDelta.CHANGED) == 0); + return true; + } + }); + } catch (CoreException e) { + Assert.assertTrue("Shouldn't happen", false); + } + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestMoveParticipantShared.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestMoveParticipantShared.java new file mode 100644 index 000000000..c642487eb --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestMoveParticipantShared.java @@ -0,0 +1,95 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Assert; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; +import org.eclipse.ltk.core.refactoring.participants.ISharableParticipant; +import org.eclipse.ltk.core.refactoring.participants.MoveArguments; +import org.eclipse.ltk.core.refactoring.participants.MoveParticipant; +import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments; + +import org.eclipse.jdt.core.IJavaElement; + +public class TestMoveParticipantShared extends MoveParticipant implements ISharableParticipant { + + static TestMoveParticipantShared fgInstance; + + List fElements= new ArrayList(3); + List fHandles= new ArrayList(3); + List fArguments= new ArrayList(3); + + public boolean initialize(Object element) { + fgInstance= this; + fElements.add(element); + fArguments.add(getArguments()); + if (element instanceof IJavaElement) + fHandles.add(((IJavaElement)element).getHandleIdentifier()); + else + fHandles.add(((IResource)element).getFullPath().toString()); + return true; + } + + public void addElement(Object element, RefactoringArguments args) { + fElements.add(element); + fArguments.add(args); + if (element instanceof IJavaElement) + fHandles.add(((IJavaElement)element).getHandleIdentifier()); + else + fHandles.add(((IResource)element).getFullPath().toString()); + } + + public String getName() { + return getClass().getName(); + } + + public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) { + return new RefactoringStatus(); + } + + public Change createChange(IProgressMonitor pm) throws CoreException { + return null; + } + + public static void testNumberOfElements(int expected) { + if (expected == 0) { + Assert.assertTrue(fgInstance == null); + } else { + Assert.assertEquals(expected, fgInstance.fElements.size()); + Assert.assertEquals(expected, fgInstance.fArguments.size()); + } + } + + public static void testArguments(MoveArguments[] args) { + testNumberOfElements(args.length); + for (int i= 0; i < args.length; i++) { + MoveArguments expected= args[i]; + MoveArguments actual= (MoveArguments)fgInstance.fArguments.get(i); + Assert.assertEquals(expected.getDestination(), actual.getDestination()); + Assert.assertEquals(expected.getUpdateReferences(), actual.getUpdateReferences()); + } + } + + public static void reset() { + fgInstance= null; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestMoveParticipantSingle.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestMoveParticipantSingle.java new file mode 100644 index 000000000..f52458917 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestMoveParticipantSingle.java @@ -0,0 +1,95 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import junit.framework.Assert; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; +import org.eclipse.ltk.core.refactoring.participants.MoveArguments; +import org.eclipse.ltk.core.refactoring.participants.MoveParticipant; + +import org.eclipse.jdt.core.IJavaElement; + +public class TestMoveParticipantSingle extends MoveParticipant { + + static List fgInstances= new ArrayList(); + + private Object fElement; + private String fHandle; + + public boolean initialize(Object element) { + fgInstances.add(this); + fElement= element; + ref(fElement); + if (fElement instanceof IJavaElement) { + fHandle= ((IJavaElement)fElement).getHandleIdentifier(); + } else { + fHandle= ((IResource)fElement).getFullPath().toString(); + } + return true; + } + + public String getName() { + return getClass().getName(); + } + + public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) { + return new RefactoringStatus(); + } + + public Change createChange(IProgressMonitor pm) throws CoreException { + return null; + } + + public static void testNumberOfInstances(int instances) { + Assert.assertEquals(instances, fgInstances.size()); + } + + public static void testElements(String[] handles) { + testNumberOfInstances(handles.length); + List l1= new ArrayList(Arrays.asList(handles)); + for (int i= 0; i < l1.size(); i++) { + Assert.assertTrue(l1.contains(getInstance(i).fHandle)); + } + } + + public static void testArguments(MoveArguments[] args) { + testNumberOfInstances(args.length); + for (int i= 0; i < args.length; i++) { + MoveArguments expected= args[i]; + MoveArguments actual= getInstance(i).getArguments(); + Assert.assertEquals(expected.getDestination(), actual.getDestination()); + Assert.assertEquals(expected.getUpdateReferences(), actual.getUpdateReferences()); + } + } + + public static void reset() { + fgInstances= new ArrayList(); + } + + private static TestMoveParticipantSingle getInstance(int i) { + return ((TestMoveParticipantSingle)fgInstances.get(i)); + } + + /* package */ void ref(Object element) { + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestRenameParticipantShared.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestRenameParticipantShared.java new file mode 100644 index 000000000..d66d95e1f --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestRenameParticipantShared.java @@ -0,0 +1,149 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import junit.framework.Assert; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; +import org.eclipse.ltk.core.refactoring.participants.ISharableParticipant; +import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments; +import org.eclipse.ltk.core.refactoring.participants.RenameArguments; +import org.eclipse.ltk.core.refactoring.participants.RenameParticipant; + +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.refactoring.IJavaElementMapper; +import org.eclipse.jdt.core.refactoring.RenameTypeArguments; + +public class TestRenameParticipantShared extends RenameParticipant implements ISharableParticipant { + + static TestRenameParticipantShared fgInstance; + List fElements= new ArrayList(3); + List fHandles= new ArrayList(3); + List fArguments= new ArrayList(3); + Map fSimilarToHandle= new HashMap(); + Map fSimilarToNewName= new HashMap(); + + public boolean initialize(Object element) { + fgInstance= this; + fElements.add(element); + fArguments.add(getArguments()); + if (element instanceof IJavaElement) + fHandles.add(((IJavaElement)element).getHandleIdentifier()); + else + fHandles.add(((IResource)element).getFullPath().toString()); + + IJavaElementMapper updating= (IJavaElementMapper)getProcessor().getAdapter(IJavaElementMapper.class); + if ((updating != null) && getArguments() instanceof RenameTypeArguments) { + RenameTypeArguments arguments= (RenameTypeArguments)getArguments(); + if (arguments.getUpdateSimilarDeclarations()) { + IJavaElement[] elements= arguments.getSimilarDeclarations(); + for (int i= 0; i < elements.length; i++) { + IJavaElement updated= updating.getRefactoredJavaElement(elements[i]); + if (updated!=null) { + fSimilarToHandle.put(elements[i].getHandleIdentifier(), getKey(updated)); + fSimilarToNewName.put(elements[i].getHandleIdentifier(), updated.getElementName()); + } + } + } + } + + return true; + } + + private String getKey(IJavaElement updated) { + if (updated instanceof IType) + return ((IType)updated).getKey(); + else if (updated instanceof IMethod) + return ((IMethod)updated).getKey(); + else if (updated instanceof IField) + return ((IField)updated).getKey(); + return ""; + } + + public void addElement(Object element, RefactoringArguments args) { + fElements.add(element); + fArguments.add(args); + if (element instanceof IJavaElement) + fHandles.add(((IJavaElement)element).getHandleIdentifier()); + else + fHandles.add(((IResource)element).getFullPath().toString()); + } + + public String getName() { + return getClass().getName(); + } + + public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) { + return new RefactoringStatus(); + } + + public Change createChange(IProgressMonitor pm) throws CoreException { + return null; + } + + public static void testNumberOfElements(int expected) { + if (expected == 0) { + Assert.assertTrue(fgInstance == null); + } else { + Assert.assertEquals(expected, fgInstance.fElements.size()); + Assert.assertEquals(expected, fgInstance.fArguments.size()); + } + } + + public static void testArguments(RenameArguments[] args) { + testNumberOfElements(args.length); + for (int i= 0; i < args.length; i++) { + RenameArguments expected= args[i]; + RenameArguments actual= (RenameArguments)fgInstance.fArguments.get(i); + Assert.assertEquals(expected.getNewName(), actual.getNewName()); + Assert.assertEquals(expected.getUpdateReferences(), actual.getUpdateReferences()); + } + } + + public static void reset() { + fgInstance= null; + } + + public static void testNumberOfSimilarElements(int expected) { + if (expected == 0) + Assert.assertTrue(fgInstance == null); + else + Assert.assertEquals(expected, fgInstance.fSimilarToHandle.size()); + } + + public static void testSimilarElements(List similarList, List similarNewNameList, List similarNewHandleList) { + for (int i=0; i< similarList.size(); i++) { + String handle= (String) similarList.get(i); + String newHandle= (String)similarNewHandleList.get(i); + String newName= (String)similarNewNameList.get(i); + String actualNewHandle= (String)fgInstance.fSimilarToHandle.get(handle); + String actualNewName= (String)fgInstance.fSimilarToNewName.get(handle); + Assert.assertEquals("New element handle not as expected", newHandle, actualNewHandle); + Assert.assertEquals("New element name not as expected", newName, actualNewName); + } + Assert.assertEquals(similarList.size(), fgInstance.fSimilarToHandle.size()); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestRenameParticipantSingle.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestRenameParticipantSingle.java new file mode 100644 index 000000000..e34670e1f --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/TestRenameParticipantSingle.java @@ -0,0 +1,95 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import junit.framework.Assert; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.ltk.core.refactoring.Change; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; +import org.eclipse.ltk.core.refactoring.participants.RenameArguments; +import org.eclipse.ltk.core.refactoring.participants.RenameParticipant; + +import org.eclipse.jdt.core.IJavaElement; + +public class TestRenameParticipantSingle extends RenameParticipant { + + private static List fgInstances= new ArrayList(); + + private Object fElement; + private String fHandle; + + public boolean initialize(Object element) { + fgInstances.add(this); + fElement= element; + ref(fElement); + if (fElement instanceof IJavaElement) { + fHandle= ((IJavaElement)fElement).getHandleIdentifier(); + } else { + fHandle= ((IResource)fElement).getFullPath().toString(); + } + return true; + } + + public String getName() { + return getClass().getName(); + } + + public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context) { + return new RefactoringStatus(); + } + + public Change createChange(IProgressMonitor pm) throws CoreException { + return null; + } + + public static void testNumberOfInstances(int instances) { + Assert.assertEquals(instances, fgInstances.size()); + } + + public static void testElements(String[] handles) { + testNumberOfInstances(handles.length); + List l1= new ArrayList(Arrays.asList(handles)); + for (int i= 0; i < l1.size(); i++) { + Assert.assertTrue(l1.contains(getInstance(i).fHandle)); + } + } + + public static void testArguments(RenameArguments[] args) { + testNumberOfInstances(args.length); + for (int i= 0; i < args.length; i++) { + RenameArguments expected= args[i]; + RenameArguments actual= getInstance(i).getArguments(); + Assert.assertEquals(expected.getNewName(), actual.getNewName()); + Assert.assertEquals(expected.getUpdateReferences(), actual.getUpdateReferences()); + } + } + + public static void reset() { + fgInstances= new ArrayList(); + } + + private static TestRenameParticipantSingle getInstance(int i) { + return ((TestRenameParticipantSingle)fgInstances.get(i)); + } + + /* package */ void ref(Object element) { + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/UndoManagerTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/UndoManagerTests.java new file mode 100644 index 000000000..36038d704 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/UndoManagerTests.java @@ -0,0 +1,158 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.IUndoManager; +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.internal.core.refactoring.UndoManager2; + +public class UndoManagerTests extends RefactoringTest { + + private static final Class clazz= UndoManagerTests.class; + public UndoManagerTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + private void checkState(boolean undo, boolean redo, int undoCount, int redoCount){ + checkState(0, undo, redo, undoCount, redoCount); + } + + protected IUndoManager getUndoManager() { + return RefactoringCore.getUndoManager(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + RefactoringCore.getUndoManager().flush(); + } + + private void checkState(int iterationCount, boolean undo, boolean redo, int undoCount, int redoCount){ + assertTrue(iterationCount + " undo", undo == RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue(iterationCount + " redo", redo == RefactoringCore.getUndoManager().anythingToRedo()); + testCounts(iterationCount, undoCount, redoCount); + } + + private void testCounts(int iterationCount, int undoCount, int redoCount) { + IUndoManager undoManager= RefactoringCore.getUndoManager(); + if (undoManager instanceof UndoManager2) { + UndoManager2 manager= (UndoManager2)undoManager; + assertTrue(iterationCount + "undo stack", manager.testHasNumberOfUndos(undoCount)); + assertTrue(iterationCount + "redo stack", manager.testHasNumberOfRedos(redoCount)); + } + } + + private void performUndo() throws Exception { + RefactoringCore.getUndoManager().performUndo(null, new NullProgressMonitor()); + } + + private void performRedo() throws Exception { + RefactoringCore.getUndoManager().performRedo(null, new NullProgressMonitor()); + } + + public void test0() throws Exception{ + checkState(false, false, 0, 0); + } + + public void test1() throws Exception{ + performRefactoring(new NullRefactoring()); + checkState(true, false, 1, 0); + } + + public void test2() throws Exception{ + performRefactoring(new NullRefactoring()); + performUndo(); + checkState(false, true, 0, 1); + } + + public void test3() throws Exception{ + performRefactoring(new NullRefactoring()); + performUndo(); + performRedo(); + checkState(true, false, 1, 0); + } + + public void test4() throws Exception{ + performRefactoring(new NullRefactoring()); + performUndo(); + performRedo(); + performUndo(); + checkState(false, true, 0, 1); + } + + public void test5() throws Exception{ + performRefactoring(new NullRefactoring()); + performUndo(); + performRedo(); + performRefactoring(new NullRefactoring()); + checkState(true, false, 2, 0); + } + + public void test6() throws Exception{ + performRefactoring(new NullRefactoring()); + performUndo(); + performRedo(); + performRefactoring(new NullRefactoring()); + performUndo(); + performUndo(); + checkState(false, true, 0, 2); + } + + public void test7() throws Exception{ + performRefactoring(new NullRefactoring()); + performUndo(); + performRedo(); + performRefactoring(new NullRefactoring()); + performUndo(); + checkState(true, true, 1, 1); + } + + public void test8() throws Exception{ + // limit is 5 since the stack is limited to 5 entries + int limit= 5; + for (int i= 0; i < limit; i++){ + checkState(i, i != 0, false, i, 0); + performRefactoring(new NullRefactoring()); + } + for (int i= 0; i < limit; i++){ + checkState(i, i != limit, i != 0, limit - i, i); + performUndo(); + } + + for (int i= 0; i < limit; i++){ + checkState(i, i != 0, i != limit, i, limit - i); + performRedo(); + } + } + + + public void test9() throws Exception{ + performRefactoring(new NullRefactoring()); + performUndo(); + performRedo(); + performRefactoring(new NullRefactoring()); + performUndo(); + RefactoringCore.getUndoManager().flush(); + checkState(false, false, 0, 0); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/UseSupertypeWherePossibleTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/UseSupertypeWherePossibleTests.java new file mode 100644 index 000000000..31a622b0a --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/UseSupertypeWherePossibleTests.java @@ -0,0 +1,493 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.IProgressMonitor; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.refactoring.descriptors.UseSupertypeDescriptor; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +public class UseSupertypeWherePossibleTests extends RefactoringTest { + + private static final Class clazz= UseSupertypeWherePossibleTests.class; + private static final String REFACTORING_PATH= "UseSupertypeWherePossible/"; + + public UseSupertypeWherePossibleTests(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + protected void setUp() throws Exception { + super.setUp(); + StubUtility.setCodeTemplate(CodeTemplateContextType.NEWTYPE_ID, + "${package_declaration}" + + System.getProperty("line.separator", "\n") + + "${"+ CodeTemplateContextType.TYPE_COMMENT+"}" + + System.getProperty("line.separator", "\n") + + "${type_declaration}", null); + + StubUtility.setCodeTemplate(CodeTemplateContextType.TYPECOMMENT_ID, "/** typecomment template*/", null); + } + + private IType getClassFromTestFile(IPackageFragment pack, String className) throws Exception{ + return getType(createCUfromTestFile(pack, className), className); + } + + private void validatePassingTest(String className, String[] cuNames, String superTypeFullName, boolean replaceInstanceOf) throws Exception { + final IType subType= getClassFromTestFile(getPackageP(), className); + final ICompilationUnit[] units= new ICompilationUnit[cuNames.length]; + for (int i= 0; i < cuNames.length; i++) { + if (cuNames[i].equals(subType.getCompilationUnit().findPrimaryType().getElementName())) + units[i]= subType.getCompilationUnit(); + else + units[i]= createCUfromTestFile(subType.getPackageFragment(), cuNames[i]); + + } + final IType superType= subType.getJavaProject().findType(superTypeFullName, (IProgressMonitor) null); + final UseSupertypeDescriptor descriptor= RefactoringSignatureDescriptorFactory.createUseSupertypeDescriptor(); + descriptor.setSubtype(subType); + descriptor.setSupertype(superType); + descriptor.setReplaceInstanceof(replaceInstanceOf); + final RefactoringStatus status= new RefactoringStatus(); + final Refactoring refactoring= descriptor.createRefactoring(status); + assertTrue("status should be ok", status.isOK()); + assertNotNull("refactoring should not be null", refactoring); + assertEquals("was supposed to pass", null, performRefactoring(refactoring)); + + for (int i= 0; i < units.length; i++) { + String expected= getFileContents(getOutputTestFileName(cuNames[i])); + String actual= units[i].getSource(); + String message= "incorrect changes in " + units[i].getElementName(); + assertEqualLines(message, expected, actual); + } + } + + private void validatePassingTest(String className, String[] cuNames, String superTypeFullName) throws Exception { + validatePassingTest(className, cuNames, superTypeFullName, false); + } + + //---------------tests ---------------------- + + public void testNew0() throws Exception{ + validatePassingTest("A", new String[]{"A"}, "java.lang.Object"); + } + + public void testNew1() throws Exception{ +// printTestDisabledMessage("bug 23597 "); + validatePassingTest("A", new String[]{"A"}, "java.lang.Object"); + } + + public void testNew2() throws Exception{ + validatePassingTest("A", new String[]{"A"}, "java.lang.Object"); + } + + public void testNew3() throws Exception{ + validatePassingTest("A", new String[]{"A"}, "java.lang.Object"); + } + + public void testNew4() throws Exception{ + validatePassingTest("A", new String[]{"A", "Test"}, "java.lang.Object"); + } + + public void testNew5() throws Exception{ + validatePassingTest("A", new String[]{"A", "Test"}, "java.lang.Object"); + } + + public void testNew6() throws Exception{ + validatePassingTest("A", new String[]{"A", "Test"}, "java.lang.Object"); + } + + public void testNew7() throws Exception{ + validatePassingTest("A", new String[]{"A", "Test", "B"}, "p.B"); + } + + public void testNew8() throws Exception{ + validatePassingTest("A", new String[]{"A", "Test", "B"}, "p.B"); + } + + public void testNew9() throws Exception{ + validatePassingTest("A", new String[]{"A", "Test"}, "java.lang.Object"); + } + + public void testNew10() throws Exception{ + validatePassingTest("A", new String[]{"A", "Test", "B"}, "p.B"); + } + + public void testNew11() throws Exception{ + validatePassingTest("A", new String[]{"A", "Test", "B"}, "p.B"); + } + + public void testNew12() throws Exception{ + validatePassingTest("A", new String[]{"A", "Test", "B"}, "p.B"); + } + + public void testNew13() throws Exception{ + validatePassingTest("A", new String[]{"A", "Test", "B"}, "p.B"); + } + + public void testNew14() throws Exception{ + validatePassingTest("A", new String[]{"A", "Test", "B"}, "p.B"); + } + + public void testNew15() throws Exception{ + validatePassingTest("A", new String[]{"A", "Test", "B"}, "p.B"); + } + + public void testNew16() throws Exception{ +// printTestDisabledMessage("instanceof "); + validatePassingTest("A", new String[]{"A", "Test", "B"}, "p.B"); + } + + public void testNew17() throws Exception{ + validatePassingTest("A", new String[]{"A"}, "p.C"); + } + + public void testNew18() throws Exception{ + validatePassingTest("A", new String[]{"A"}, "p.B"); + } + + public void testNew19() throws Exception{ + validatePassingTest("A", new String[]{"A"}, "p.I"); + } + + public void testNew20() throws Exception{ +// printTestDisabledMessage("http://dev.eclipse.org/bugs/show_bug.cgi?id=23829"); + validatePassingTest("A", new String[]{"A"}, "p.B"); + } + + public void testNew21() throws Exception{ + validatePassingTest("A", new String[]{"A"}, "java.lang.Object"); + } + + public void testNew22() throws Exception{ + validatePassingTest("A", new String[]{"A", "B", "Test"}, "p.B"); + } + + public void testNew23() throws Exception{ + validatePassingTest("A", new String[]{"A", "B", "Test"}, "java.lang.Object"); + } + + public void testNew24() throws Exception{ + validatePassingTest("A", new String[]{"A", "B"}, "java.lang.Object"); + } + + public void testNew25() throws Exception{ + validatePassingTest("A", new String[]{"A", "B", "C"}, "java.lang.Object"); + } + + public void testNew26() throws Exception{ + validatePassingTest("A", new String[]{"A", "B"}, "java.lang.Object"); + } + + public void testNew27() throws Exception{ + validatePassingTest("A", new String[]{"A", "B"}, "p.B"); + } + + public void testNew28() throws Exception{ + validatePassingTest("A", new String[]{"A", "B"}, "p.B"); + } + + public void testNew29() throws Exception{ +// printTestDisabledMessage("bug 24278"); + validatePassingTest("A", new String[]{"A"}, "p.B"); + } + + public void testNew30() throws Exception{ +// printTestDisabledMessage("bug 24278"); + validatePassingTest("A", new String[]{"A"}, "p.B"); + } + + public void testNew31() throws Exception{ +// printTestDisabledMessage("bug 24278"); + validatePassingTest("A", new String[]{"A"}, "p.B"); + } + + public void testNew32() throws Exception{ +// printTestDisabledMessage(); + validatePassingTest("A", new String[]{"A"}, "p.B"); + } + + public void testNew33() throws Exception{ + // printTestDisabledMessage("bug 26282"); + validatePassingTest("A", new String[]{"A"}, "java.util.Vector"); + } + + public void testNew34() throws Exception{ + // printTestDisabledMessage("bug 26282"); + validatePassingTest("A", new String[]{"A"}, "java.util.Vector"); + } + + public void testNew35() throws Exception{ + // printTestDisabledMessage("bug 26282"); + validatePassingTest("A", new String[]{"A"}, "java.util.Vector"); + } + + public void testNew36() throws Exception{ + // printTestDisabledMessage("bug 26288"); + validatePassingTest("A", new String[]{"A"}, "p.B"); + } + + public void testNew37() throws Exception{ + // printTestDisabledMessage("bug 26288"); + validatePassingTest("A", new String[]{"A"}, "p.B"); + } + + public void testNew38() throws Exception{ + // printTestDisabledMessage("bug 40373"); + validatePassingTest("A", new String[]{"A"}, "p.B"); + } + + public void testNew39() throws Exception{ + // printTestDisabledMessage("bug 169608"); + validatePassingTest("C", new String[]{"C"}, "p.B"); + } + + /* i had to rename tests 0-15 because of cvs problems*/ + + + public void test0_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test1_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test2_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test3_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test4_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test5_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test6_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test7_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test8_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test9_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test10_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test11_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test12_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test13_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test14_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test15_() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test16() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test17() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test18() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test19() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test20() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test21() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test22() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test23() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test24() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test25() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test26() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test27() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test28() throws Exception{ +// printTestDisabledMessage("bug 22883"); + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test29() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test30() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test31() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test32() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test33() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test34() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test35() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test36() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test37() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test38() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test39() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test40() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test41() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test42() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test43() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test44() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test45() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test46() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test47() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test48() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test49() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test50() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test51() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test52() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test53() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test54() throws Exception{ + validatePassingTest("A", new String[]{"A", "A1", "I"}, "p.I"); + } + public void test55() throws Exception{ + validatePassingTest("A", new String[]{"A", "A1", "I"}, "p.I"); + } + public void test56() throws Exception{ + validatePassingTest("A", new String[]{"A", "A1", "I"}, "p.I"); + } + public void test57() throws Exception{ + validatePassingTest("A", new String[]{"A", "A1", "I"}, "p.I"); + } + public void test58() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test59() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test60() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test61() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test62() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test63() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test64() throws Exception{ + validatePassingTest("A", new String[]{"A", "I", "Inter"}, "p.I"); + } + public void test65() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test66() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test67() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } + public void test68() throws Exception{ + validatePassingTest("A", new String[]{"A", "As", "I"}, "p.I"); + } + public void test69() throws Exception{ + validatePassingTest("A", new String[]{"A", "As", "I"}, "p.I"); + } + public void test70() throws Exception{ + validatePassingTest("A", new String[]{"A", "I"}, "p.I"); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ValidateEditTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ValidateEditTests.java new file mode 100644 index 000000000..0fb27f6c2 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ValidateEditTests.java @@ -0,0 +1,438 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.io.ByteArrayInputStream; +import java.util.Collection; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.team.core.RepositoryProvider; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourceAttributes; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CopyRefactoring; +import org.eclipse.ltk.core.refactoring.participants.MoveRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; +import org.eclipse.jdt.internal.corext.refactoring.reorg.JavaCopyProcessor; +import org.eclipse.jdt.internal.corext.refactoring.reorg.JavaMoveProcessor; +import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgDestinationFactory; +import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory; +import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgPolicy.ICopyPolicy; +import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy; + +import org.eclipse.jdt.ui.tests.refactoring.ccp.MockReorgQueries; +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringTestRepositoryProvider; + + +public class ValidateEditTests extends RefactoringTest { + + private static final Class clazz= ValidateEditTests.class; + + public ValidateEditTests(String name) { + super(name); + } + + public static Test suite() { + return new Java15Setup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new Java15Setup(someTest); + } + + protected void setUp() throws Exception { + super.setUp(); + RepositoryProvider.map(getRoot().getJavaProject().getProject(), RefactoringTestRepositoryProvider.PROVIDER_ID); + } + + protected void tearDown() throws Exception { + RepositoryProvider.unmap(getRoot().getJavaProject().getProject()); + super.tearDown(); + } + + public void testPackageRename1() throws Exception { + IPackageFragment fragment= getRoot().createPackageFragment("org.test", true, null); + + StringBuffer buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("class A {\n"); + buf.append("}\n"); + ICompilationUnit cu1= fragment.createCompilationUnit("A.java", buf.toString(), true, null); + setReadOnly(cu1); + + buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("class B {\n"); + buf.append("}\n"); + ICompilationUnit cu2= fragment.createCompilationUnit("B.java", buf.toString(), true, null); + setReadOnly(cu2); + + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_PACKAGE); + descriptor.setJavaElement(fragment); + descriptor.setNewName("org.test2"); + descriptor.setUpdateReferences(true); + RefactoringStatus status= performRefactoring(descriptor); + if (status != null) + assertTrue(status.toString(), status.isOK()); + + Collection validatedEditPaths= RefactoringTestRepositoryProvider.getValidatedEditPaths(getRoot().getJavaProject().getProject()); + assertEquals(2, validatedEditPaths.size()); + assertTrue(validatedEditPaths.contains(cu1.getPath())); + assertTrue(validatedEditPaths.contains(cu2.getPath())); + } + + public void testPackageRename2() throws Exception { + // A readonly and moved, B moved, C changes + + IPackageFragment fragment= getRoot().createPackageFragment("org.test", true, null); + + StringBuffer buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class A {\n"); + buf.append("}\n"); + ICompilationUnit cu1= fragment.createCompilationUnit("A.java", buf.toString(), true, null); + setReadOnly(cu1); + + buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class B {\n"); + buf.append("}\n"); + fragment.createCompilationUnit("B.java", buf.toString(), true, null); + // not read only + + IPackageFragment fragment2= getRoot().createPackageFragment("org.other", true, null); + + buf= new StringBuffer(); + buf.append("package org.other;\n"); + buf.append("public class C extends org.test.A {\n"); + buf.append("}\n"); + ICompilationUnit cu3= fragment2.createCompilationUnit("C.java", buf.toString(), true, null); + setReadOnly(cu3); + + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_PACKAGE); + descriptor.setJavaElement(fragment); + descriptor.setNewName("org.test2"); + descriptor.setUpdateReferences(true); + RefactoringStatus status= performRefactoring(descriptor); + if (status != null) + assertTrue(status.toString(), status.isOK()); + + Collection validatedEditPaths= RefactoringTestRepositoryProvider.getValidatedEditPaths(getRoot().getJavaProject().getProject()); + assertEquals(2, validatedEditPaths.size()); + assertTrue(validatedEditPaths.contains(cu1.getPath())); + assertTrue(validatedEditPaths.contains(cu3.getPath())); + } + + public void testPackageRenameWithResource() throws Exception { + // MyClass readonly and moved, x.properties readonly moved + + IPackageFragment fragment= getRoot().createPackageFragment("org.test", true, null); + + StringBuffer buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class MyClass {\n"); + buf.append("}\n"); + ICompilationUnit cu1= fragment.createCompilationUnit("MyClass.java", buf.toString(), true, null); + setReadOnly(cu1); + + IFile file= ((IFolder) fragment.getResource()).getFile("x.properties"); + String content= "A file with no references"; + file.create(getStream(content), true, null); + setReadOnly(file); + + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_PACKAGE); + descriptor.setJavaElement(fragment); + descriptor.setNewName("org.test2"); + descriptor.setUpdateReferences(true); + RefactoringStatus status= performRefactoring(descriptor); + if (status != null) + assertTrue(status.toString(), status.isOK()); + + Collection validatedEditPaths= RefactoringTestRepositoryProvider.getValidatedEditPaths(getRoot().getJavaProject().getProject()); + assertEquals(1, validatedEditPaths.size()); + assertTrue(validatedEditPaths.contains(cu1.getPath())); + } + + + public void testPackageRenameWithResource2() throws Exception { + // MyClass readonly and moved, x.properties readonly moved + + IPackageFragment fragment= getRoot().createPackageFragment("org.test", true, null); + + StringBuffer buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class MyClass {\n"); + buf.append("}\n"); + ICompilationUnit cu1= fragment.createCompilationUnit("MyClass.java", buf.toString(), true, null); + setReadOnly(cu1); + + IFile file= ((IFolder) fragment.getResource()).getFile("x.properties"); + byte[] content= "This is about 'org.test' and more".getBytes(); + file.create(new ByteArrayInputStream(content), true, null); + file.refreshLocal( IResource.DEPTH_ONE, null); + setReadOnly(file); + + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_PACKAGE); + descriptor.setJavaElement(fragment); + descriptor.setNewName("org.test2"); + descriptor.setUpdateReferences(true); + descriptor.setUpdateQualifiedNames(true); + descriptor.setFileNamePatterns("*.properties"); + RefactoringStatus status= performRefactoring(descriptor); + if (status != null) + assertTrue(status.toString(), status.isOK()); + + Collection validatedEditPaths= RefactoringTestRepositoryProvider.getValidatedEditPaths(getRoot().getJavaProject().getProject()); + assertEquals(2, validatedEditPaths.size()); + assertTrue(validatedEditPaths.contains(cu1.getPath())); + assertTrue(validatedEditPaths.contains(file.getFullPath())); + } + + public void testCURename() throws Exception { + + IPackageFragment fragment= getRoot().createPackageFragment("org.test", true, null); + + StringBuffer buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class MyClass {\n"); + buf.append("}\n"); + ICompilationUnit cu1= fragment.createCompilationUnit("MyClass.java", buf.toString(), true, null); + setReadOnly(cu1); + + buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class C extends MyClass {\n"); + buf.append("}\n"); + ICompilationUnit cu2= fragment.createCompilationUnit("C.java", buf.toString(), true, null); + setReadOnly(cu2); + + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_COMPILATION_UNIT); + descriptor.setJavaElement(cu1); + descriptor.setNewName("MyClass2.java"); + descriptor.setUpdateReferences(true); + RefactoringStatus status= performRefactoring(descriptor); + if (status != null) + assertTrue(status.toString(), status.isOK()); + + Collection validatedEditPaths= RefactoringTestRepositoryProvider.getValidatedEditPaths(getRoot().getJavaProject().getProject()); + assertEquals(2, validatedEditPaths.size()); + assertTrue(validatedEditPaths.contains(cu1.getPath())); + assertTrue(validatedEditPaths.contains(cu2.getPath())); + } + + public void testTypeRename() throws Exception { + + IPackageFragment fragment= getRoot().createPackageFragment("org.test", true, null); + + StringBuffer buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class MyClass {\n"); + buf.append("}\n"); + ICompilationUnit cu1= fragment.createCompilationUnit("MyClass.java", buf.toString(), true, null); + setReadOnly(cu1); + + buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class C extends MyClass {\n"); + buf.append("}\n"); + ICompilationUnit cu2= fragment.createCompilationUnit("C.java", buf.toString(), true, null); + setReadOnly(cu2); + + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_TYPE); + descriptor.setJavaElement(cu1.findPrimaryType()); + descriptor.setNewName("MyClass2"); + descriptor.setUpdateReferences(true); + RefactoringStatus status= performRefactoring(descriptor); + if (status != null) + assertTrue(status.toString(), status.isOK()); + + Collection validatedEditPaths= RefactoringTestRepositoryProvider.getValidatedEditPaths(getRoot().getJavaProject().getProject()); + assertEquals(2, validatedEditPaths.size()); + assertTrue(validatedEditPaths.contains(cu1.getPath())); + assertTrue(validatedEditPaths.contains(cu2.getPath())); + } + + public void testMoveCU2() throws Exception { + // Move CU and file: Only CU be validated as file doesn't change + + IPackageFragment fragment= getRoot().createPackageFragment("org.test", true, null); + IPackageFragment otherFragment= getRoot().createPackageFragment("org.test1", true, null); + + StringBuffer buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class MyClass {\n"); + buf.append("}\n"); + ICompilationUnit cu1= fragment.createCompilationUnit("MyClass.java", buf.toString(), true, null); + setReadOnly(cu1); + + IFile file= ((IFolder) fragment.getResource()).getFile("x.properties"); + String content= "A file with no references"; + file.create(getStream(content), true, null); + setReadOnly(file); + + buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class C extends MyClass {\n"); + buf.append("}\n"); + ICompilationUnit cu2= fragment.createCompilationUnit("C.java", buf.toString(), true, null); + setReadOnly(cu2); + + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(new IResource[] { file } , new IJavaElement[] { cu1 }); + assertTrue(policy.canEnable()); + + JavaMoveProcessor javaMoveProcessor= new JavaMoveProcessor(policy); + javaMoveProcessor.setDestination(ReorgDestinationFactory.createDestination(otherFragment)); + javaMoveProcessor.setReorgQueries(new MockReorgQueries()); + RefactoringStatus status= performRefactoring(new MoveRefactoring(javaMoveProcessor)); + if (status != null) + assertTrue(status.toString(), status.isOK()); + + Collection validatedEditPaths= RefactoringTestRepositoryProvider.getValidatedEditPaths(getRoot().getJavaProject().getProject()); + assertEquals(2, validatedEditPaths.size()); + assertTrue(validatedEditPaths.contains(cu1.getPath())); // moved and changed + assertTrue(validatedEditPaths.contains(cu2.getPath())); // changed + } + + public void testMoveFileWithReplace() throws Exception { + // Move file to a existing location + + IPackageFragment fragment= getRoot().createPackageFragment("org.test", true, null); + IPackageFragment otherFragment= getRoot().createPackageFragment("org.test1", true, null); + + IFile file= ((IFolder) fragment.getResource()).getFile("x.properties"); + String content= "A file with no references"; + file.create(getStream(content), true, null); + setReadOnly(file); + + IFile file2= ((IFolder) otherFragment.getResource()).getFile("x.properties"); + file2.create(getStream(content), true, null); + setReadOnly(file2); + + + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(new IResource[] { file }, new IJavaElement[] {}); + assertTrue(policy.canEnable()); + + JavaMoveProcessor javaMoveProcessor= new JavaMoveProcessor(policy); + javaMoveProcessor.setDestination(ReorgDestinationFactory.createDestination(otherFragment)); + javaMoveProcessor.setReorgQueries(new MockReorgQueries()); + RefactoringStatus status= performRefactoring(new MoveRefactoring(javaMoveProcessor), true); + if (status != null) + assertTrue(status.toString(), status.isOK()); + + Collection validatedEditPaths= RefactoringTestRepositoryProvider.getValidatedEditPaths(getRoot().getJavaProject().getProject()); + assertEquals(1, validatedEditPaths.size()); + assertTrue(validatedEditPaths.contains(file2.getFullPath())); // replaced + } + + public void testMoveCuWithReplace() throws Exception { + // Move CU to an existing location + + IPackageFragment fragment= getRoot().createPackageFragment("org.test", true, null); + IPackageFragment otherFragment= getRoot().createPackageFragment("org.test1", true, null); + + StringBuffer buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class MyClass {\n"); + buf.append("}\n"); + ICompilationUnit cu1= fragment.createCompilationUnit("MyClass.java", buf.toString(), true, null); + setReadOnly(cu1); + + + buf= new StringBuffer(); + buf.append("package org.test1;\n"); + buf.append("public class MyClass {\n"); + buf.append("}\n"); + ICompilationUnit cu2= otherFragment.createCompilationUnit("MyClass.java", buf.toString(), true, null); + setReadOnly(cu2); + + + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(new IResource[0], new IJavaElement[] { cu1 }); + assertTrue(policy.canEnable()); + + JavaMoveProcessor javaMoveProcessor= new JavaMoveProcessor(policy); + javaMoveProcessor.setDestination(ReorgDestinationFactory.createDestination(otherFragment)); + javaMoveProcessor.setReorgQueries(new MockReorgQueries()); + RefactoringStatus status= performRefactoring(new MoveRefactoring(javaMoveProcessor), false); + if (status != null) + assertTrue(status.toString(), status.isOK()); + + Collection validatedEditPaths= RefactoringTestRepositoryProvider.getValidatedEditPaths(getRoot().getJavaProject().getProject()); + assertEquals(2, validatedEditPaths.size()); + assertTrue(validatedEditPaths.contains(cu1.getPath())); // moved and changed + assertTrue(validatedEditPaths.contains(cu2.getPath())); // replaced + } + + public void testCopyCuWithReplace() throws Exception { + // Copy CU to a existing location + + IPackageFragment fragment= getRoot().createPackageFragment("org.test", true, null); + IPackageFragment otherFragment= getRoot().createPackageFragment("org.test1", true, null); + + StringBuffer buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("public class MyClass {\n"); + buf.append("}\n"); + ICompilationUnit cu1= fragment.createCompilationUnit("MyClass.java", buf.toString(), true, null); + setReadOnly(cu1); + + buf= new StringBuffer(); + buf.append("package org.test1;\n"); + buf.append("public class MyClass {\n"); + buf.append("}\n"); + ICompilationUnit cu2= otherFragment.createCompilationUnit("MyClass.java", buf.toString(), true, null); + setReadOnly(cu2); + + ICopyPolicy policy= ReorgPolicyFactory.createCopyPolicy(new IResource[0], new IJavaElement[] { cu1 }); + assertTrue(policy.canEnable()); + + JavaCopyProcessor javaCopyProcessor= new JavaCopyProcessor(policy); + javaCopyProcessor.setDestination(ReorgDestinationFactory.createDestination(otherFragment)); + javaCopyProcessor.setReorgQueries(new MockReorgQueries()); + javaCopyProcessor.setNewNameQueries(new MockReorgQueries()); + RefactoringStatus status= performRefactoring(new CopyRefactoring(javaCopyProcessor), false); + if (status != null) + assertTrue(status.toString(), status.isOK()); + + Collection validatedEditPaths= RefactoringTestRepositoryProvider.getValidatedEditPaths(getRoot().getJavaProject().getProject()); + assertEquals(1, validatedEditPaths.size()); + assertTrue(validatedEditPaths.contains(cu2.getPath())); // replaced + } + + + private static void setReadOnly(ICompilationUnit cu) throws CoreException { + setReadOnly(cu.getResource()); + } + + + private static void setReadOnly(IResource resource) throws CoreException { + ResourceAttributes resourceAttributes = resource.getResourceAttributes(); + if (resourceAttributes != null) { + resourceAttributes.setReadOnly(true); + resource.setResourceAttributes(resourceAttributes); + } + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/AllTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/AllTests.java new file mode 100644 index 000000000..d9778df9e --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/AllTests.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.actions; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class AllTests { + + public static Test suite ( ) { + TestSuite suite= new TestSuite("All Action Tests"); + + suite.addTest(StructureSelectionActionTests.suite()); + suite.addTest(GoToNextPreviousMemberActionTests.suite()); + return suite; + } + +} + + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/GoToNextPreviousMemberActionTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/GoToNextPreviousMemberActionTests.java new file mode 100644 index 000000000..31009e74d --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/GoToNextPreviousMemberActionTests.java @@ -0,0 +1,117 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.actions; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.ISourceRange; + +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSetup; +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction; + +public class GoToNextPreviousMemberActionTests extends RefactoringTest{ + + private static final Class clazz= GoToNextPreviousMemberActionTests.class; + private static final String REFACTORING_PATH= "GoToNextPreviousMemberAction/"; + public GoToNextPreviousMemberActionTests(String name){ + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + private String getSimpleTestFileName(){ + return "A_" + getName() + ".java"; + } + + private String getTestFileName(){ + return TEST_PATH_PREFIX + getRefactoringPath() + getSimpleTestFileName(); + } + + //------------ + protected ICompilationUnit createCUfromTestFile() throws Exception { + return createCU(getPackageP(), getSimpleTestFileName(), getFileContents(getTestFileName())); + } + + private void helper(int startLine, int startColumn, int endLine, int endColumn, + int expectedStartLine, int expectedStartColumn, boolean isSelectNext) throws Exception { + ICompilationUnit cu= createCUfromTestFile(); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ISourceRange actualNewRange= new GoToNextPreviousMemberAction(isSelectNext).getNewSelectionRange(selection, cu.getAllTypes()); + ISourceRange expectedNewRange= TextRangeUtil.getSelection(cu, expectedStartLine, expectedStartColumn, expectedStartLine, expectedStartColumn); + assertEquals("incorrect selection offset", expectedNewRange.getOffset(), actualNewRange.getOffset()); + assertEquals("incorrect selection length", expectedNewRange.getLength(), actualNewRange.getLength()); + } + + private void helperNext(int startLine, int startColumn, int expectedStartLine, int expectedStartColumn) throws Exception{ + helper(startLine, startColumn, startLine, startColumn, expectedStartLine, expectedStartColumn, true); + } + + private void helperPrevious(int startLine, int startColumn, int expectedStartLine, int expectedStartColumn) throws Exception{ + helper(startLine, startColumn, startLine, startColumn, expectedStartLine, expectedStartColumn, false); + } + + //---- + public void testPrevious0() throws Exception{ + helperPrevious(6, 5, 5, 11); + } + + public void testPrevious1() throws Exception{ + helperPrevious(8, 5, 7, 6); + } + + public void testPrevious2() throws Exception{ + helperPrevious(3, 1, 3, 1); + } + + public void testPrevious3() throws Exception{ + helperPrevious(15, 9, 13, 6); + } + + public void testPrevious4() throws Exception{ + helperPrevious(19, 1, 18, 9); + } + + public void testPrevious5() throws Exception{ + helperPrevious(31, 10, 27, 10); + } + + public void testPrevious6() throws Exception{ + helperPrevious(35, 3, 34, 2); + } + + public void testNext0() throws Exception{ + helperNext(3, 1, 4, 7); + } + + public void testNext1() throws Exception{ + helperNext(27, 10, 31, 10); + } + + public void testNext2() throws Exception{ + helperNext(35, 2, 35, 2); + } + + public void testNext3() throws Exception{ + helperNext(19, 1, 20, 13); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/StructureSelectionActionTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/StructureSelectionActionTests.java new file mode 100644 index 000000000..c53056046 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/StructureSelectionActionTests.java @@ -0,0 +1,415 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.actions; + +import java.io.IOException; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.SourceRange; + +import org.eclipse.jdt.ui.tests.refactoring.AbstractSelectionTestCase; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSetup; +import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; + +import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction; +import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction; +import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction; + +public class StructureSelectionActionTests extends RefactoringTest{ + + private static final Class clazz= StructureSelectionActionTests.class; + private static final String REFACTORING_PATH= "StructureSelectionAction/"; + + public StructureSelectionActionTests(String name){ + super(name); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + private String getSimpleTestFileName(boolean input){ + String fileName = "A_" + getName(); + fileName += input ? "": "_out"; + fileName += input ? ".java": ".txt"; + return fileName; + } + + private String getTestFileName(boolean input){ + return TEST_PATH_PREFIX + getRefactoringPath() + getSimpleTestFileName(input); + } + + //------------ + protected ICompilationUnit createCUfromTestFile(IPackageFragment pack, boolean input) throws Exception { + String cuName= getSimpleTestFileName(input); + ICompilationUnit cu= pack.getCompilationUnit(cuName); + if (cu.exists()) + return cu; + return createCU(pack, cuName, getFileContents(getTestFileName(input))); + } + + private ISourceRange getSelection(ICompilationUnit cu) throws Exception{ + String source= cu.getSource(); + int offset= source.indexOf(AbstractSelectionTestCase.SQUARE_BRACKET_OPEN); + int end= source.indexOf(AbstractSelectionTestCase.SQUARE_BRACKET_CLOSE); + return new SourceRange(offset, end - offset); + } + + private void check(ICompilationUnit cu, ISourceRange newRange) throws IOException, JavaModelException { + String expected= getFileContents(getTestFileName(false)); + String actual= cu.getSource().substring(newRange.getOffset(), newRange.getOffset() + newRange.getLength()); +// assertEquals("selection incorrect length", expected.length(), actual.length()); + assertEqualLines("selection incorrect", expected, actual); + } + + private void helperSelectUp() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true); + ISourceRange selection= getSelection(cu); + + ISourceRange newRange= new StructureSelectEnclosingAction().getNewSelectionRange(selection, cu); + + check(cu, newRange); + } + + private void helperSelectUp(int startLine, int startColumn, int endLine, int endColumn) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + ISourceRange newRange= new StructureSelectEnclosingAction().getNewSelectionRange(selection, cu); + + check(cu, newRange); + } + + private void helperSelectNext(int startLine, int startColumn, int endLine, int endColumn) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + + ISourceRange newRange= new StructureSelectNextAction().getNewSelectionRange(selection, cu); + check(cu, newRange); + } + + private void helperSelectPrevious(int startLine, int startColumn, int endLine, int endColumn) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true); + ISourceRange selection= TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn); + + ISourceRange newRange= new StructureSelectPreviousAction().getNewSelectionRange(selection, cu); + check(cu, newRange); + } + + private void helperZeroLength(int line, int column) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true); + ISourceRange selection= new SourceRange(TextRangeUtil.getOffset(cu, line, column), 1); + + //DebugUtils.dump(name() + ":<" + cu.getSource().substring(selection.getOffset()) + "/>"); + + ISourceRange newRange= new StructureSelectEnclosingAction().getNewSelectionRange(selection, cu); + check(cu, newRange); + } + + private void offsetTest(int line, int column, int expected) throws Exception{ + String filePath= TEST_PATH_PREFIX + getRefactoringPath() + "OffsetTest.java"; + ICompilationUnit cu= createCU(getPackageP(), "OffsetTest.java", getFileContents(filePath)); + assertEquals("incorrect offset", expected, TextRangeUtil.getOffset(cu, line, column)); + } + + + // ---- tests --- + + public void test0() throws Exception{ + helperSelectUp(4, 9, 4, 13); + } + + public void test1() throws Exception{ + helperSelectUp(); + } + + public void test2() throws Exception{ + helperSelectUp(4, 16, 4, 21); + } + + public void test3() throws Exception{ + helperSelectUp(4, 9, 4, 21); + } + + public void test4() throws Exception{ + helperSelectUp(); + } + + public void test5() throws Exception{ + helperSelectUp(); + } + + public void test6() throws Exception{ + helperSelectUp(); + } + + public void test7() throws Exception{ + //helper1(); + helperSelectUp(3, 10, 3, 14); + } + + public void test8() throws Exception{ + helperSelectUp(3, 16, 3, 18); + } + + public void test9() throws Exception{ + helperSelectUp(3, 10, 3, 11); + } + + public void test10() throws Exception{ + helperSelectUp(4, 18, 4, 21); + } + + public void test11() throws Exception{ + helperSelectUp(4, 20, 4, 21); + } + + public void test12() throws Exception{ + helperSelectUp(4, 16, 4, 19); + } + + public void test13() throws Exception{ + helperSelectUp(4, 13, 4, 16); + } + + public void test14() throws Exception{ + helperSelectUp(4, 16, 4, 21); + } + + public void test15() throws Exception{ + // identical to test9 ??? + helperSelectUp(3, 10, 3, 11); + } + + public void test16() throws Exception{ + helperSelectUp(3, 16, 3, 17); + } + + public void test17() throws Exception{ + helperSelectUp(3, 5, 7, 6); + } + + public void test18() throws Exception{ + helperSelectUp(3, 5, 4, 6); + } + + public void test19() throws Exception{ + helperSelectUp(7, 14, 7, 16); + } + + public void test20() throws Exception{ + helperSelectUp(4, 18, 4, 19); + } + + public void test21() throws Exception{ + //regression test for bug#10182 + //printTestDisabledMessage("regression test for bug#11151"); + helperSelectNext(3, 21, 3, 28); + } + + public void test22() throws Exception{ + //regression test for bug#10182 + //printTestDisabledMessage("regression test for bug#11151"); + helperSelectPrevious(3, 21, 3, 28); + } + + public void test23() throws Exception{ +// printTestDisabledMessage("regression test for bug#10570"); + helperSelectPrevious(5, 30, 7, 10); + } + + public void test24() throws Exception{ + //regression test for bug#11424 + helperSelectPrevious(3, 13, 5, 6); + } + + public void test25() throws Exception{ + //regression test for bug#11879 + helperSelectNext(5, 5, 6, 6); + } + + public void test26() throws Exception{ + //regression test for bug#11879 + helperSelectPrevious(5, 5, 6, 6); + } + + public void test27() throws Exception{ + //regression test for bug#11879 + helperSelectNext(4, 1, 4, 10); + } + + public void test28() throws Exception{ + //regression test for bug#11879 + helperSelectPrevious(4, 1, 4, 10); + } + + public void test29() throws Exception{ +// printTestDisabledMessage("regression test for bug#16051"); + helperSelectUp(5, 13, 5, 17); + } + + public void test30() throws Exception{ +// printTestDisabledMessage("regression test for bug#80345 (not 22082)"); + helperSelectUp(3, 10, 3, 10); + } + + public void test31() throws Exception{ +// printTestDisabledMessage("regression test for bug#80345 (not 22082)"); + helperSelectUp(3, 10, 3, 10); + } + + public void test32() throws Exception{ +// printTestDisabledMessage("regression test for bug#22939"); + helperSelectUp(4, 18, 4, 18); + } + + public void test33() throws Exception{ +// printTestDisabledMessage("regression test for bug#22939"); + helperSelectUp(5, 23, 5, 23); + } + + public void test34() throws Exception{ +// printTestDisabledMessage("regression test for bug#23118"); + helperSelectUp(5, 14, 5, 14); + } + + public void test35() throws Exception{ +// printTestDisabledMessage("regression test for bug#23118"); + helperSelectUp(5, 14, 5, 14); + } + + public void test36() throws Exception{ +// printTestDisabledMessage("regression test for bug#23259"); + helperSelectUp(5, 14, 5, 14); + } + + public void test37() throws Exception{ +// printTestDisabledMessage("regression test for bug#23259"); + helperSelectUp(7, 14, 7, 14); + } + + public void test38() throws Exception{ +// printTestDisabledMessage("regression test for bug#23263"); + helperSelectPrevious(4, 5, 5, 16); + } + + public void test39() throws Exception{ +// printTestDisabledMessage("regression test for bug#23464"); + helperSelectPrevious(6, 13, 6, 20); + } + + public void test40() throws Exception{ +// printTestDisabledMessage("regression test for bug#23464 "); + helperSelectPrevious(7, 13, 7, 20); + } + + public void test41() throws Exception{ + helperSelectPrevious(4, 1, 4, 29); + } + + public void test42() throws Exception{ + helperSelectNext(4, 1, 4, 29); + } + + public void test43() throws Exception{ + helperSelectNext(4, 1, 4, 32); + } + + public void testZeroLength0() throws Exception{ + //printTestDisabledMessage(""); + helperZeroLength(4, 20); + } + + public void testZeroLength1() throws Exception{ + helperSelectNext(4, 16, 4, 16); + helperSelectPrevious(4, 17, 4, 17); + } + + public void testZeroLength2() throws Exception{ + helperSelectNext(4, 20, 4, 20); + helperSelectPrevious(4, 21, 4, 21); + } + + public void testZeroLength3() throws Exception{ + helperSelectNext(3, 10, 3, 10); + helperSelectPrevious(3, 11, 3, 11); + } + + public void testZeroLength4() throws Exception{ + helperSelectNext(4, 9, 4, 9); + helperSelectPrevious(4, 10, 4, 10); + } + + public void testZeroLength5() throws Exception{ + helperSelectNext(4, 11, 4, 11); + helperSelectPrevious(4, 14, 4, 14); + } + + public void testWholeCu() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), true); + ISourceRange selection= cu.getSourceRange(); + + ISourceRange newRange= new StructureSelectEnclosingAction().getNewSelectionRange(selection, cu); + + String expected= getFileContents(getTestFileName(false)); + String actual= cu.getSource().substring(newRange.getOffset(), newRange.getOffset() + newRange.getLength()); + assertEqualLines("selection incorrect", expected, actual); + } + + //--- offset calculation tests + + public void testOffset0() throws Exception{ + offsetTest(4, 20, 47); + } + + public void testOffset1() throws Exception{ + offsetTest(5, 9, 53); + } + + public void testOffset2() throws Exception{ + offsetTest(7, 13, 81); + } + + public void testTabCount0(){ + int t= TextRangeUtil.calculateTabCountInLine("\t\t1", 9); + assertEquals(2, t); + } + + public void testTabCount1(){ + int t= TextRangeUtil.calculateTabCountInLine("\t\tint i= 1 + 1;", 20); + assertEquals(2, t); + } + + public void testTabCount2(){ + int t= TextRangeUtil.calculateTabCountInLine("\t\t\treturn;", 13); + assertEquals(3, t); + } + + public void testTabCount3(){ + int t= TextRangeUtil.calculateTabCountInLine("\tvoid m(){m();", 18); + assertEquals(1, t); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/all/AllAllRefactoringTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/all/AllAllRefactoringTests.java new file mode 100644 index 000000000..9531fadf8 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/all/AllAllRefactoringTests.java @@ -0,0 +1,31 @@ +/******************************************************************************* + * Copyright (c) 2000, 2007 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.all; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.TestOptionsSetup; + +public class AllAllRefactoringTests { + public static Test suite ( ) { + TestSuite suite= new TestSuite("All All Refactoring Tests"); + suite.addTest(org.eclipse.jdt.ui.tests.refactoring.actions.AllTests.suite()); + suite.addTest(org.eclipse.jdt.ui.tests.refactoring.nls.AllTests.suite()); + suite.addTest(org.eclipse.jdt.ui.tests.refactoring.AllTests.suite()); + suite.addTest(org.eclipse.jdt.ui.tests.refactoring.extensions.AllTests.suite()); + suite.addTest(org.eclipse.jdt.ui.tests.refactoring.changes.AllTests.suite()); + suite.addTest(org.eclipse.jdt.ui.tests.refactoring.ccp.AllTests.suite()); + suite.addTest(org.eclipse.jdt.ui.tests.refactoring.typeconstraints.AllTests.suite()); + return new TestOptionsSetup(suite); + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/all/AllRefactoringPerformanceTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/all/AllRefactoringPerformanceTests.java new file mode 100644 index 000000000..99510c11e --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/all/AllRefactoringPerformanceTests.java @@ -0,0 +1,29 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + package org.eclipse.jdt.ui.tests.refactoring.all; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.ui.tests.refactoring.reorg.AllReorgPerformanceTests; +import org.eclipse.jdt.ui.tests.refactoring.type.AllTypeConstraintsPerformanceTests; + +public class AllRefactoringPerformanceTests extends TestCase { + + public static Test suite() { + TestSuite suite= new TestSuite("All Refactoring Performance Tests"); //$NON-NLS-1$ + suite.addTest(AllReorgPerformanceTests.suite()); + suite.addTest(AllTypeConstraintsPerformanceTests.suite()); + return suite; + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/AllTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/AllTests.java new file mode 100644 index 000000000..0af5612cc --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/AllTests.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.ccp; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class AllTests { + + public static Test suite ( ) { + TestSuite suite= new TestSuite("All Reorg Tests"); + suite.addTest(DeleteTest.suite()); + suite.addTest(CopyToClipboardActionTest.suite()); + suite.addTest(PasteActionTest.suite()); + suite.addTest(CopyTest.suite()); + suite.addTest(MoveTest.suite()); + suite.addTest(MultiMoveTest.suite()); + + //------old reorg tests + suite.addTest(CopyResourcesToClipboardActionTest.suite()); + + return suite; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/CopyResourcesToClipboardActionTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/CopyResourcesToClipboardActionTest.java new file mode 100644 index 000000000..da1a18ce7 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/CopyResourcesToClipboardActionTest.java @@ -0,0 +1,200 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.ccp; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.swt.dnd.Clipboard; +import org.eclipse.swt.widgets.Display; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.ISourceManipulation; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.ui.actions.SelectionDispatchAction; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSetup; +import org.eclipse.jdt.ui.tests.refactoring.infra.MockClipboard; +import org.eclipse.jdt.ui.tests.refactoring.infra.MockWorkbenchSite; + +import org.eclipse.jdt.internal.ui.refactoring.reorg.CopyToClipboardAction; + +public class CopyResourcesToClipboardActionTest extends RefactoringTest{ + + private static final Class clazz= CopyResourcesToClipboardActionTest.class; + + private ICompilationUnit fCuA; + private ICompilationUnit fCuB; + private IPackageFragment fPackageQ; + private IPackageFragment fPackageQ_R; + private IPackageFragment fDefaultPackage; + private static final String CU_A_NAME= "A"; + private static final String CU_B_NAME= "B"; + private IFile faTxt; + + private Clipboard fClipboard; + + public CopyResourcesToClipboardActionTest(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + private IFile createFile(IFolder folder, String fileName) throws Exception { + IFile file= folder.getFile(fileName); + file.create(getStream("aa"), true, null); + return file; + } + + protected void setUp() throws Exception { + super.setUp(); + fClipboard= new MockClipboard(Display.getDefault()); + fDefaultPackage= RefactoringTestSetup.getDefaultSourceFolder().createPackageFragment("", true, null); + + fCuA= createCU(getPackageP(), CU_A_NAME + ".java", "package p; class A{}"); + + fPackageQ= RefactoringTestSetup.getDefaultSourceFolder().createPackageFragment("q", true, null); + fCuB= createCU(fPackageQ, CU_B_NAME + ".java", "package q; class B{}"); + + fPackageQ_R= RefactoringTestSetup.getDefaultSourceFolder().createPackageFragment("q.r", true, null); + + faTxt= createFile((IFolder)getPackageP().getUnderlyingResource(), "a.txt"); + + assertTrue("A.java does not exist", fCuA.exists()); + assertTrue("B.java does not exist", fCuB.exists()); + assertTrue("q does not exist", fPackageQ.exists()); + assertTrue("q.r does not exist", fPackageQ_R.exists()); + assertTrue(faTxt.exists()); + } + + protected void tearDown() throws Exception { + super.tearDown(); + performDummySearch(); + fClipboard.dispose(); + delete(fCuA); + delete(fCuB); + delete(fPackageQ_R); + delete(fPackageQ); + delete(faTxt); + } + + private static void delete(ISourceManipulation element) { + try { + if (element != null && ((IJavaElement)element).exists()) + element.delete(false, null); + } catch(JavaModelException e) { + //ignore, we must keep going + } + } + private static void delete(IFile element) { + try { + element.delete(true, false, null); + } catch(CoreException e) { + //ignore, we must keep going + } + } + + private void checkEnabled(Object[] elements) { + SelectionDispatchAction copyAction= new CopyToClipboardAction(new MockWorkbenchSite(elements), fClipboard); + copyAction.update(copyAction.getSelection()); + assertTrue("action should be enabled", copyAction.isEnabled()); + } + + private void checkDisabled(Object[] elements) { + SelectionDispatchAction copyAction= new CopyToClipboardAction(new MockWorkbenchSite(elements), fClipboard); + copyAction.update(copyAction.getSelection()); + assertTrue("action should not be enabled", ! copyAction.isEnabled()); + } + + public void testEnabled0() throws Exception{ + checkEnabled(new Object[]{fCuA}); + } + + public void testEnabled1() throws Exception{ + checkEnabled(new Object[]{getRoot().getJavaProject()}); + } + + public void testEnabled2() throws Exception{ + checkEnabled(new Object[]{getPackageP()}); + } + + public void testEnabled3() throws Exception{ + checkEnabled(new Object[]{getPackageP(), fPackageQ, fPackageQ_R}); + } + + public void testEnabled4() throws Exception{ + checkEnabled(new Object[]{faTxt}); + } + + public void testEnabled5() throws Exception{ + checkEnabled(new Object[]{getRoot()}); + } + + public void testDisabled0() throws Exception{ + checkDisabled(new Object[]{}); + } + + public void testDisabled1() throws Exception{ + checkDisabled(new Object[]{getRoot().getJavaProject(), fCuA}); + } + + public void testDisabled2() throws Exception{ + checkDisabled(new Object[]{getRoot().getJavaProject(), fPackageQ}); + } + + public void testDisabled3() throws Exception{ + checkDisabled(new Object[]{getRoot().getJavaProject(), faTxt}); + } + + public void testDisabled4() throws Exception{ + checkDisabled(new Object[]{getPackageP(), fCuA}); + } + + public void testDisabled5() throws Exception{ + checkDisabled(new Object[]{getRoot(), fCuA}); + } + + public void testDisabled6() throws Exception{ + checkDisabled(new Object[]{getRoot(), fPackageQ}); + } + + public void testDisabled7() throws Exception{ + checkDisabled(new Object[]{getRoot(), faTxt}); + } + + public void testDisabled8() throws Exception{ + checkDisabled(new Object[]{getRoot(), getRoot().getJavaProject()}); + } + + public void testDisabled9() throws Exception{ + checkDisabled(new Object[]{RefactoringTestSetup.getProject().getPackageFragmentRoots()}); + } + + public void testDisabled10() throws Exception{ + checkDisabled(new Object[]{fCuA, fCuB}); + } + + public void testDisabled11() throws Exception{ + checkDisabled(new Object[]{fDefaultPackage}); + } + + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/CopyTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/CopyTest.java new file mode 100644 index 000000000..78e1cb31d --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/CopyTest.java @@ -0,0 +1,3350 @@ +/******************************************************************************* + * Copyright (c) 2000, 2010 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.ccp; + +import java.io.IOException; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.OperationCanceledException; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.resources.mapping.ResourceMapping; + +import org.eclipse.core.filebuffers.FileBuffers; +import org.eclipse.core.filebuffers.ITextFileBuffer; +import org.eclipse.core.filebuffers.LocationKind; + +import org.eclipse.ltk.core.refactoring.PerformChangeOperation; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.CopyArguments; +import org.eclipse.ltk.core.refactoring.participants.CopyRefactoring; +import org.eclipse.ltk.core.refactoring.participants.ReorgExecutionLog; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IImportContainer; +import org.eclipse.jdt.core.IImportDeclaration; +import org.eclipse.jdt.core.IInitializer; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; +import org.eclipse.jdt.internal.corext.refactoring.reorg.INewNameQueries; +import org.eclipse.jdt.internal.corext.refactoring.reorg.INewNameQuery; +import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgDestination; +import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgQueries; +import org.eclipse.jdt.internal.corext.refactoring.reorg.JavaCopyProcessor; +import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgDestinationFactory; +import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory; +import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils; +import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgPolicy.ICopyPolicy; +import org.eclipse.jdt.internal.corext.util.JavaElementResourceMapping; + +import org.eclipse.jdt.ui.tests.refactoring.ParticipantTesting; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSetup; +import org.eclipse.jdt.ui.tests.refactoring.TestModelProvider; + + +public class CopyTest extends RefactoringTest { + + private static final Class clazz= CopyTest.class; + private static final String REFACTORING_PATH= "Copy/"; + + public CopyTest(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test test) { + return new RefactoringTestSetup(test); + } + + protected void setUp() throws Exception { + super.setUp(); + fIsPreDeltaTest= true; + } + + protected void executePerformOperation(PerformChangeOperation perform, IWorkspace workspace) throws CoreException { + if (fIsPreDeltaTest) { + try { + TestModelProvider.IS_COPY_TEST= true; + super.executePerformOperation(perform, workspace); + } finally { + TestModelProvider.IS_COPY_TEST= false; + } + } else { + super.executePerformOperation(perform, workspace); + } + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + private void verifyDisabled(IResource[] resources, IJavaElement[] javaElements) throws JavaModelException { + assertTrue("copy should be disabled", ! RefactoringAvailabilityTester.isCopyAvailable(resources, javaElements)); + assertTrue(!ReorgPolicyFactory.createCopyPolicy(resources, javaElements).canEnable()); + } + + private JavaCopyProcessor verifyEnabled(IResource[] resources, IJavaElement[] javaElements, INewNameQueries newNameQueries, IReorgQueries reorgQueries) throws JavaModelException { + assertTrue("copy should be enabled", RefactoringAvailabilityTester.isCopyAvailable(resources, javaElements)); + ICopyPolicy copyPolicy= ReorgPolicyFactory.createCopyPolicy(resources, javaElements); + assertTrue(copyPolicy.canEnable()); + JavaCopyProcessor processor= new JavaCopyProcessor(copyPolicy); + if (newNameQueries != null) + processor.setNewNameQueries(newNameQueries); + if (reorgQueries != null) + processor.setReorgQueries(reorgQueries); + return processor; + } + + private IReorgQueries createReorgQueries(){ + return new MockReorgQueries(); + } + + private void verifyInvalidDestination(JavaCopyProcessor processor, Object destination) throws Exception { + RefactoringStatus status= processor.setDestination(ReorgDestinationFactory.createDestination(destination)); + + assertEquals("destination was expected to be not valid", RefactoringStatus.FATAL, status.getSeverity()); + } + + private void verifyValidDestination(JavaCopyProcessor processor, Object destination) throws Exception { + verifyValidDestination(processor, destination, IReorgDestination.LOCATION_ON); + } + + private void verifyValidDestination(JavaCopyProcessor processor, Object destination, int location) throws Exception { + RefactoringStatus status= processor.setDestination(ReorgDestinationFactory.createDestination(destination, location)); + + assertEquals("destination was expected to be valid: " + status.getMessageMatchingSeverity(status.getSeverity()), RefactoringStatus.OK, status.getSeverity()); + } + + private void verifyCopyingOfSubCuElements(ICompilationUnit[] cus, Object destination, IJavaElement[] javaElements) throws JavaModelException, Exception, IOException { + verifyCopyingOfSubCuElements(cus, destination, IReorgDestination.LOCATION_ON, javaElements); + } + + private void verifyCopyingOfSubCuElements(ICompilationUnit[] cus, Object destination, int location, IJavaElement[] javaElements) throws JavaModelException, Exception, IOException { + JavaCopyProcessor processor= verifyEnabled(new IResource[0], javaElements, new MockNewNameQueries(), createReorgQueries()); + verifyValidDestination(processor, destination, location); + RefactoringStatus status= performRefactoring(new CopyRefactoring(processor), false); + assertNull("failed precondition", status); + for (int i= 0; i < cus.length; i++) { + assertEqualLines("different source in " + cus[i].getElementName(), getFileContents(getOutputTestFileName(removeExtension(cus[i].getElementName()))), cus[i].getSource()); + } + } + + private final RefactoringStatus performRefactoring(JavaCopyProcessor processor, boolean providesUndo) throws Exception { + return performRefactoring(new CopyRefactoring(processor), providesUndo); + } + + private static class MockNewNameQueries implements INewNameQueries{ + + private static final String NEW_PACKAGE_NAME= "unusedName"; + private static final String NEW_PACKAGE_FOLDER_NAME= "unusedName"; + private static final String NEW_PACKAGE_FRAGMENT_ROOT_NAME= "UnusedName"; + private static final String NEW_FILE_NAME= "UnusedName.gif"; + private static final String NEW_FOLDER_NAME= "UnusedName"; + private static final String NEW_CU_NAME= "UnusedName"; + + public INewNameQuery createNewCompilationUnitNameQuery(ICompilationUnit cu, String s) { + return createStaticQuery(NEW_CU_NAME); + } + + public INewNameQuery createNewResourceNameQuery(IResource res, String s) { + if (res instanceof IFile) + return createStaticQuery(NEW_FILE_NAME); + else + return createStaticQuery(NEW_FOLDER_NAME); + } + + public INewNameQuery createNewPackageNameQuery(IPackageFragment pack, String s) { + return createStaticQuery(NEW_PACKAGE_NAME); + } + + public INewNameQuery createNullQuery() { + return createStaticQuery(null); + } + + public INewNameQuery createStaticQuery(final String newName) { + return new INewNameQuery(){ + public String getNewName() { + return newName; + } + }; + } + + public INewNameQuery createNewPackageFragmentRootNameQuery(IPackageFragmentRoot root, String initialSuggestedName) { + return createStaticQuery(NEW_PACKAGE_FRAGMENT_ROOT_NAME); + } + } + + private static class MockCancelNameQueries implements INewNameQueries{ + public INewNameQuery createNewCompilationUnitNameQuery(ICompilationUnit cu, String s) { + return createNullQuery(); + } + public INewNameQuery createNewResourceNameQuery(IResource res, String s) { + return createNullQuery(); + } + public INewNameQuery createNewPackageNameQuery(IPackageFragment pack, String s) { + return createNullQuery(); + } + public INewNameQuery createNullQuery() { + return new INewNameQuery() { + public String getNewName() { + throw new OperationCanceledException(); + } + }; + } + public INewNameQuery createStaticQuery(final String newName) { + return createNullQuery(); + } + public INewNameQuery createNewPackageFragmentRootNameQuery(IPackageFragmentRoot root, String initialSuggestedName) { + return createNullQuery(); + } + } + + //--------------- + + public void test_field_declared_in_multi_yes_type() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IField field= cu.getType("A").getField("bar"); + IType type= cu.getType("A"); + IJavaElement[] javaElements= { field }; + Object destination= type; + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_fields_declared_in_multi_yes_type() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IField field1= cu.getType("A").getField("bar"); + IField field2= cu.getType("A").getField("baz"); + IType type= cu.getType("A"); + IJavaElement[] javaElements= { field1, field2 }; + Object destination= type; + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_fields_declared_in_multi_yes_type_1() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IField field1= cu.getType("A").getField("var11"); + IField field2= cu.getType("A").getField("var2"); + IField field3= cu.getType("A").getField("var3"); + IType type= cu.getType("A"); + IJavaElement[] javaElements= { field1, field2, field3}; + Object destination= type; + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDisabled_empty() throws Exception { + IJavaElement[] javaElements= {}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_null_element() throws Exception { + IJavaElement[] javaElements= {null}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_null_resource() throws Exception { + IJavaElement[] javaElements= {}; + IResource[] resources= {null}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_javaProject() throws Exception { + IJavaElement[] javaElements= {RefactoringTestSetup.getProject()}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_defaultPackage() throws Exception { + IPackageFragment defaultPackage= getRoot().getPackageFragment(""); + assertTrue(defaultPackage.exists()); + IJavaElement[] javaElements= {defaultPackage}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_project() throws Exception { + IJavaElement[] javaElements= {}; + IResource[] resources= {RefactoringTestSetup.getProject().getProject()}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_notExistingElement() throws Exception { + ICompilationUnit notExistingCu= getPackageP().getCompilationUnit("NotMe.java"); + assertTrue(! notExistingCu.exists()); + IJavaElement[] javaElements= {notExistingCu}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_notExistingResource() throws Exception { + IFolder folder= (IFolder)getPackageP().getResource(); + IFile notExistingFile= folder.getFile("a.txt"); + + IJavaElement[] javaElements= {}; + IResource[] resources= {notExistingFile}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_noCommonParent0() throws Exception { + IJavaElement[] javaElements= {getPackageP(), getRoot()}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_noCommonParent1() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + try { + IType classA= cu.getType("A"); + IMethod methodFoo= classA.getMethod("foo", new String[0]); + IJavaElement[] javaElements= { classA, methodFoo }; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + +// public void testDisabled_noCommonParent2() throws Exception { +// ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); +// try { +// IType classA= cu.getType("A"); +// IJavaElement[] javaElements= { classA, cu}; +// IResource[] resources= {}; +// verifyDisabled(resources, javaElements); +// } finally { +// performDummySearch(); +// cu.delete(true, new NullProgressMonitor()); +// } +// } + + public void testDisabled_noCommonParent3() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + try { + IJavaElement[] javaElements= {cu, getPackageP()}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDisabled_noCommonParent5() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + try { + IJavaElement[] javaElements= {cu, getRoot()}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDisabled_noCommonParent6() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + try { + IJavaElement[] javaElements= {cu, getRoot()}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDisabled_noCommonParent7() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{class Inner{}}", false, new NullProgressMonitor()); + try { + IType classA= cu.getType("A"); + IType classInner= classA.getType("Inner"); + IJavaElement[] javaElements= { classA, classInner}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDisabled_noCommonParent8() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try { + IType classA= cu.getType("A"); + IMethod methodFoo= classA.getMethod("foo", new String[0]); + IJavaElement[] javaElements= { methodFoo, classA}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testEnabled_cu() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try { + IJavaElement[] javaElements= { cu}; + IResource[] resources= {}; + verifyEnabled(resources, javaElements, null, createReorgQueries()); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testEnabled_package() throws Exception { + IJavaElement[] javaElements= { getPackageP()}; + IResource[] resources= {}; + verifyEnabled(resources, javaElements, null, createReorgQueries()); + } + + public void testEnabled_packageRoot() throws Exception { + IJavaElement[] javaElements= { getRoot()}; + IResource[] resources= {}; + verifyEnabled(resources, javaElements, null, createReorgQueries()); + } + + public void testEnabled_archivePackageRoot() throws Exception { + IJavaProject project= RefactoringTestSetup.getProject(); + IProject projectFolder= project.getProject(); + IFile archiveFile= projectFolder.getFile("archive.jar"); + archiveFile.create(getStream(""), true, null); + + IPackageFragmentRoot root= JavaProjectHelper.addLibrary(project, archiveFile.getFullPath()); + IJavaElement[] javaElements= { root}; + IResource[] resources= {}; + verifyEnabled(resources, javaElements, null, createReorgQueries()); + } + + public void testEnabled_file() throws Exception { + IFolder folder= (IFolder)getPackageP().getResource(); + IFile file= folder.getFile("a.txt"); + file.create(getStream("123"), true, null); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + verifyEnabled(resources, javaElements, null, createReorgQueries()); + } finally{ + performDummySearch(); + file.delete(true, false, null); + } + } + + public void testEnabled_folder() throws Exception{ + IFolder folder= (IFolder)getPackageP().getResource(); + + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + verifyEnabled(resources, javaElements, null, createReorgQueries()); + } + + public void testEnabled_fileFolder() throws Exception { + IFolder superFolder= (IFolder)getPackageP().getResource(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file, folder}; + verifyEnabled(resources, javaElements, null, createReorgQueries()); + } finally{ + performDummySearch(); + file.delete(true, false, null); + folder.delete(true, false, null); + } + } + + public void testEnabled_fileFolderCu() throws Exception { + IFolder superFolder= (IFolder)getPackageP().getResource(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file, folder}; + verifyEnabled(resources, javaElements, null, createReorgQueries()); + } finally{ + performDummySearch(); + file.delete(true, false, null); + folder.delete(true, false, null); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_package_no_1() throws Exception{ + IJavaElement[] javaElements= { getPackageP()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + verifyInvalidDestination(ref, RefactoringTestSetup.getProject()); + } + + public void testDestination_package_no_2() throws Exception{ + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + try { + IJavaElement[] javaElements= { getPackageP()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination=cu; + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_package_no_3() throws Exception{ + IFolder superFolder= (IFolder)getPackageP().getResource(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + try { + IJavaElement[] javaElements= { getPackageP()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= file; + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + file.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_package_no_4() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + try { + IJavaElement[] javaElements= { getPackageP()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= folder; + verifyValidDestination(ref, destination); + } finally { + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_cu_no_1() throws Exception{ + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + IProject closedProject= ResourcesPlugin.getWorkspace().getRoot().getProject("mySImpleProject"); + closedProject.create(null); + assertTrue(! closedProject.isOpen()); + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= closedProject; + verifyInvalidDestination(ref, destination); + }finally{ + performDummySearch(); + cu1.delete(true, new NullProgressMonitor()); + closedProject.delete(true, true, null); + } + } + + public void testDestination_folder_no_0() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= folder;//same folder + verifyInvalidDestination(ref, destination); + }finally{ + performDummySearch(); + folder.delete(true, false, null); + } + } + + public void testDestination_folder_no_1() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IFolder childFolder= folder.getFolder("folder"); + childFolder.create(true, true, null); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= childFolder; + verifyInvalidDestination(ref, destination); + }finally{ + performDummySearch(); + folder.delete(true, false, null); + childFolder.delete(true, false, null); + } + } + + public void testDestination_folder_no_2() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IFile childFile= folder.getFile("a.txt"); + childFile.create(getStream("123"), true, null); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= childFile; + verifyInvalidDestination(ref, destination); + }finally{ + performDummySearch(); + folder.delete(true, false, null); + childFile.delete(true, false, null); + } + } + + public void testDestination_folder_no_3() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IProject simpleProject= ResourcesPlugin.getWorkspace().getRoot().getProject("mySImpleProject"); + simpleProject.create(null); + assertTrue(! simpleProject.isOpen()); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= simpleProject; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + simpleProject.delete(true, true, new NullProgressMonitor()); + } + } + + + public void testDestination_root_no_0() throws Exception{ + IJavaElement[] javaElements= {getRoot()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= getPackageP(); + verifyInvalidDestination(ref, destination); + } + + public void testDestination_root_no_1() throws Exception{ + ICompilationUnit cu= getPackageP().createCompilationUnit("B.java", "package p;class B{}", false, new NullProgressMonitor()); + + try { + IJavaElement[] javaElements= { getRoot()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= cu; + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_root_no_2() throws Exception{ + ICompilationUnit cu= getPackageP().createCompilationUnit("B.java", "package p;class B{}", false, new NullProgressMonitor()); + + try { + IJavaElement[] javaElements= { getRoot()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + IType classB= cu.getType("B"); + Object destination= classB; + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_root_no_3() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + try { + IJavaElement[] javaElements= { getRoot()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= file; + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + file.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_root_no_4() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + try { + IJavaElement[] javaElements= { getRoot()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= folder; + verifyValidDestination(ref, destination); + } finally { + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_cu_yes_0() throws Exception{ + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + Object destination= cu1; + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + cu1.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_cu_yes_1() throws Exception{ + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= getPackageP(); + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + cu1.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_cu_yes_2() throws Exception{ + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + IPackageFragment otherPackage= getRoot().createPackageFragment("otherPackage", true, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= otherPackage; + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + cu1.delete(true, new NullProgressMonitor()); + otherPackage.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_cu_yes_3() throws Exception{ + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= getRoot(); + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + cu1.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_cu_yes_4() throws Exception{ + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= RefactoringTestSetup.getProject(); + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + cu1.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_cu_yes_5() throws Exception{ + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + IProject simpleProject= ResourcesPlugin.getWorkspace().getRoot().getProject("mySImpleProject"); + simpleProject.create(null); + simpleProject.open(null); + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= simpleProject; + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + cu1.delete(true, new NullProgressMonitor()); + simpleProject.delete(true, true, null); + } + } + + public void testDestination_cu_yes_6() throws Exception{ + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= file; + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + cu1.delete(true, new NullProgressMonitor()); + file.delete(true, false, null); + } + } + + public void testDestination_cu_yes_7() throws Exception{ + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= folder; + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + cu1.delete(true, new NullProgressMonitor()); + folder.delete(true, false, null); + } + } + + public void testDestination_cu_yes_8() throws Exception{ + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + ICompilationUnit cu2= getPackageP().createCompilationUnit("B.java", "package p;class B{}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= cu2; + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + cu1.delete(true, new NullProgressMonitor()); + cu2.delete(true, new NullProgressMonitor()); + } + } + + + public void testDestination_file_yes_0() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= file; + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + file.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_file_yes_1() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + IFile otherFile= superFolder.getFile("b.txt"); + otherFile.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= otherFile; + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + file.delete(true, new NullProgressMonitor()); + otherFile.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_file_yes_3() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= folder; + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + file.delete(true, new NullProgressMonitor()); + folder.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_file_yes_4() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= cu1; + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + file.delete(true, new NullProgressMonitor()); + cu1.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_file_yes_5() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= getPackageP(); + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + file.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_file_yes_6() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= getRoot(); + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + file.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_file_yes_7() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= RefactoringTestSetup.getProject(); + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + file.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_file_yes_8() throws Exception{ + IFolder parentFolder= (IFolder) getPackageP().getResource(); + IFile file= parentFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= parentFolder; + verifyValidDestination(ref, destination); + }finally{ + performDummySearch(); + file.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_file_yes_9() throws Exception{ + IFolder superFolder= (IFolder)getPackageP().getResource(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + ICompilationUnit cu2= getPackageP().createCompilationUnit("B.java", "package p;class B{}", false, new NullProgressMonitor()); + try { + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= cu2; + verifyValidDestination(ref, destination); + } finally { + performDummySearch(); + file.delete(true, new NullProgressMonitor()); + cu2.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_folder_yes_0() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IFolder otherFolder= superFolder.getFolder("otherfolder"); + otherFolder.create(true, true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= otherFolder; + verifyValidDestination(ref, destination); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + otherFolder.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_folder_yes_1() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= RefactoringTestSetup.getProject(); + verifyValidDestination(ref, destination); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_folder_yes_2() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= getRoot(); + verifyValidDestination(ref, destination); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_folder_yes_3() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= getPackageP(); + verifyValidDestination(ref, destination); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_folder_yes_4() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IFolder otherFolder= superFolder.getFolder("otherfolder"); + otherFolder.create(true, true, null); + IFile fileInAnotherFolder= otherFolder.getFile("f.tex"); + fileInAnotherFolder.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= fileInAnotherFolder; + verifyValidDestination(ref, destination); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + otherFolder.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_folder_yes_5() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= cu; + verifyValidDestination(ref, destination); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_folder_yes_6() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IProject simpleProject= ResourcesPlugin.getWorkspace().getRoot().getProject("mySImpleProject"); + simpleProject.create(null); + simpleProject.open(null); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= simpleProject; + verifyValidDestination(ref, destination); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + simpleProject.delete(true, true, new NullProgressMonitor()); + } + } + + public void testDestination_package_yes_0() throws Exception{ + IJavaElement[] javaElements= {getPackageP()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= getRoot(); + verifyValidDestination(ref, destination); + } + + public void testDestination_package_yes_1() throws Exception{ + IJavaElement[] javaElements= { getPackageP()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + verifyValidDestination(ref, getPackageP()); + } + + public void testDestination_package_yes_2() throws Exception{ + IPackageFragment otherPackage= getRoot().createPackageFragment("other.pack", true, new NullProgressMonitor()); + try { + IJavaElement[] javaElements= { getPackageP()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= otherPackage; + verifyValidDestination(ref, destination); + } finally { + performDummySearch(); + otherPackage.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_root_yes_0() throws Exception{ + IJavaElement[] javaElements= {getRoot()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= getRoot().getJavaProject(); + verifyValidDestination(ref, destination); + } + + public void testDestination_root_yes_1() throws Exception{ + IJavaProject otherJavaProject= JavaProjectHelper.createJavaProject("other", "bin"); + + try { + IJavaElement[] javaElements= { getRoot()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= otherJavaProject; + verifyValidDestination(ref, destination); + } finally { + performDummySearch(); + JavaProjectHelper.delete(otherJavaProject); + } + } + + public void testDestination_method_no_package() throws Exception{ + ICompilationUnit cu= null; + try { + cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= getPackageP(); + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_method_no_file() throws Exception{ + ICompilationUnit cu= null; + IFolder parentFolder= (IFolder) getPackageP().getResource(); + String fileName= "a.txt"; + IFile file= parentFolder.getFile(fileName); + file.create(getStream("123"), true, null); + + try { + cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= file; + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + file.delete(true, false, null); + } + } + + public void testDestination_method_no_folder() throws Exception{ + ICompilationUnit cu= null; + IProject parentFolder= RefactoringTestSetup.getProject().getProject(); + String folderName= "folder"; + IFolder folder= parentFolder.getFolder(folderName); + folder.create(true, true, null); + + try { + cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= folder; + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + folder.delete(true, false, null); + } + } + + public void testDestination_method_no_root() throws Exception{ + ICompilationUnit cu= null; + try { + cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= getRoot(); + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_method_no_java_project() throws Exception{ + ICompilationUnit cu= null; + try { + cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= RefactoringTestSetup.getProject(); + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_method_no_simple_project() throws Exception{ + ICompilationUnit cu= null; + IProject simpleProject= ResourcesPlugin.getWorkspace().getRoot().getProject("mySImpleProject"); + simpleProject.create(null); + simpleProject.open(null); + try { + cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= simpleProject; + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + simpleProject.delete(true, true, null); + } + } + + public void testDestination_method_no_import_container() throws Exception{ + ICompilationUnit cu= null; + try { + cu= getPackageP().createCompilationUnit("A.java", "import java.util.*;package p;class A{void foo(){}}", false, new NullProgressMonitor()); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + IImportContainer importContainer= cu.getImportContainer(); + Object destination= importContainer; + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_method_no_import_declaration() throws Exception{ + ICompilationUnit cu= null; + try { + cu= getPackageP().createCompilationUnit("A.java", "import java.util.*;package p;class A{void foo(){}}", false, new NullProgressMonitor()); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + IImportDeclaration importDeclaration= cu.getImport("java.util.*"); + Object destination= importDeclaration; + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_method_no_package_declaration() throws Exception{ + ICompilationUnit cu= null; + try { + cu= getPackageP().createCompilationUnit("A.java", "import java.util.*;package p;class A{void foo(){}}", false, new NullProgressMonitor()); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= cu.getPackageDeclaration("p"); + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_method_yes_itself() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + Object destination= method; + + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_method_yes_cu_with_main_type() throws Exception{ + ICompilationUnit cu= null; + ICompilationUnit otherCu= createCUfromTestFile(getPackageP(), "C"); + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + Object destination= otherCu; + + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu, otherCu}, destination, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + otherCu.delete(true, new NullProgressMonitor()); + } + } + + public void test_method_yes_other_method() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IMethod otherMethod= cu.getType("A").getMethod("bar", new String[0]); + IJavaElement[] javaElements= { method }; + Object destination= otherMethod; + + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, IReorgDestination.LOCATION_AFTER, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_method_yes_other_method_back() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IMethod otherMethod= cu.getType("A").getMethod("bar", new String[0]); + IJavaElement[] javaElements= { method }; + Object destination= otherMethod; + + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, IReorgDestination.LOCATION_BEFORE, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_method_yes_field() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IField field= cu.getType("A").getField("bar"); + IJavaElement[] javaElements= { method }; + Object destination= field; + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, IReorgDestination.LOCATION_AFTER, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_method_yes_field_back() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IField field= cu.getType("A").getField("bar"); + IJavaElement[] javaElements= { method }; + Object destination= field; + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, IReorgDestination.LOCATION_BEFORE, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_method_yes_type() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + Object destination= cu.getType("A"); + + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_method_yes_initializer() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + Object destination= cu.getType("A").getInitializer(1); + + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, IReorgDestination.LOCATION_AFTER, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_method_yes_initializer_back() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + Object destination= cu.getType("A").getInitializer(1); + + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, IReorgDestination.LOCATION_BEFORE, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_field_yes_field() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IField field= cu.getType("A").getField("bar"); + IField otherField= cu.getType("A").getField("baz"); + IJavaElement[] javaElements= { field }; + Object destination= otherField; + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, IReorgDestination.LOCATION_AFTER, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_field_yes_field_back() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IField field= cu.getType("A").getField("bar"); + IField otherField= cu.getType("A").getField("baz"); + IJavaElement[] javaElements= { field }; + Object destination= otherField; + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, IReorgDestination.LOCATION_BEFORE, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_inner_type_yes_cu() throws Exception{ + ICompilationUnit cu= null; + ICompilationUnit otherCu= createCUfromTestFile(getPackageP(), "C"); + + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IType type= cu.getType("A").getType("Inner"); + IJavaElement[] javaElements= { type }; + Object destination= otherCu; + verifyCopyingOfSubCuElements(new ICompilationUnit[]{otherCu, cu}, destination, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + otherCu.delete(true, new NullProgressMonitor()); + } + } + + public void test_type_yes_package() throws Exception{ + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{}", true, new NullProgressMonitor()); + ICompilationUnit newCu= null; + try { + ParticipantTesting.reset(); + IType type= cu.getType("A"); + IJavaElement[] javaElements= { type }; + IResource[] resources= {}; + ResourceMapping mapping= JavaElementResourceMapping.create(type.getCompilationUnit()); + String[] handles= ParticipantTesting.createHandles(type.getCompilationUnit(), mapping); + IPackageFragment destination= getPackageP(); + INewNameQueries queries= new MockNewNameQueries(); + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + verifyValidDestination(ref, destination); + assertTrue("source cu does not exist before copying", cu.exists()); + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + assertTrue("source cu does not exist after copying", cu.exists()); + newCu= getPackageP().getCompilationUnit(MockNewNameQueries.NEW_CU_NAME + ".java"); + assertTrue("new cu does not exist after copying", newCu.exists()); + ReorgExecutionLog executionLog= new ReorgExecutionLog(); + executionLog.setNewName(type.getCompilationUnit(), MockNewNameQueries.NEW_CU_NAME + ".java"); + executionLog.setNewName(mapping, MockNewNameQueries.NEW_CU_NAME + ".java"); + executionLog.markAsProcessed(type.getCompilationUnit()); + executionLog.markAsProcessed(mapping); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, executionLog), + new CopyArguments(destination.getResource(), executionLog) + }); + } finally { + performDummySearch(); + if (newCu != null && newCu.exists()) + newCu.delete(true, new NullProgressMonitor()); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_type_canel_package() throws Exception{ + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{}", true, new NullProgressMonitor()); + try { + ParticipantTesting.reset(); + IType type= cu.getType("A"); + IJavaElement[] javaElements= { type }; + IResource[] resources= {}; + ResourceMapping mapping= JavaElementResourceMapping.create(type.getCompilationUnit()); + String[] handles= ParticipantTesting.createHandles(type.getCompilationUnit(), mapping); + IPackageFragment destination= getPackageP(); + INewNameQueries queries= new MockCancelNameQueries(); + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + verifyValidDestination(ref, destination); + assertTrue("source cu does not exist before copying", cu.exists()); + try { + performRefactoring(ref, false); + } catch (OperationCanceledException e) { + } + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsCanceled(); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log), + new CopyArguments(destination.getResource(), log) + }); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_type_yes_other_package() throws Exception{ + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{}", true, new NullProgressMonitor()); + IPackageFragment otherPackage= getRoot().createPackageFragment("other", true, new NullProgressMonitor()); + ICompilationUnit newCu= null; + try { + ParticipantTesting.reset(); + + IType type= cu.getType("A"); + IJavaElement[] javaElements= { type }; + IResource[] resources= {}; + IPackageFragment destination= otherPackage; + ResourceMapping mapping= JavaElementResourceMapping.create(type.getCompilationUnit()); + String[] handles= ParticipantTesting.createHandles(type.getCompilationUnit(), mapping); + + INewNameQueries queries= new MockNewNameQueries(); + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + verifyValidDestination(ref, destination); + assertTrue("source cu does not exist before copying", cu.exists()); + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + assertTrue("source cu does not exist after copying", cu.exists()); + newCu= otherPackage.getCompilationUnit(cu.getElementName()); + assertTrue("new cu does not exist after copying", newCu.exists()); + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsProcessed(type.getCompilationUnit()); + log.markAsProcessed(mapping); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log), + new CopyArguments(destination.getResource(), log) + }); + + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + if (newCu != null && newCu.exists()) + newCu.delete(true, new NullProgressMonitor()); + otherPackage.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_initializer_no_package() throws Exception{ + ICompilationUnit cu= null; + try { + cu= getPackageP().createCompilationUnit("A.java", "import java.util.*;package p;class A{void foo(){}{}}", false, new NullProgressMonitor()); + IInitializer initializer= cu.getType("A").getInitializer(1); + IJavaElement[] javaElements= { initializer }; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= getPackageP(); + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_initializer_yes_type() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IInitializer initializer= cu.getType("A").getInitializer(1); + IJavaElement[] javaElements= { initializer }; + Object destination= cu.getType("A"); + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_initializer_yes_method() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IInitializer initializer= cu.getType("A").getInitializer(1); + IJavaElement[] javaElements= { initializer }; + Object destination= cu.getType("A").getMethod("foo", new String[0]); + + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, IReorgDestination.LOCATION_AFTER, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_initializer_yes_method_back() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IInitializer initializer= cu.getType("A").getInitializer(1); + IJavaElement[] javaElements= { initializer }; + Object destination= cu.getType("A").getMethod("foo", new String[0]); + + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu}, destination, IReorgDestination.LOCATION_BEFORE, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDestination_import_container_no_package() throws Exception{ + ICompilationUnit cu= null; + try { + cu= getPackageP().createCompilationUnit("A.java", "import java.util.*;package p;class A{void foo(){}{}}", false, new NullProgressMonitor()); + IImportContainer container= cu.getImportContainer(); + IJavaElement[] javaElements= { container }; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, null, createReorgQueries()); + + Object destination= getPackageP(); + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_import_container_yes_type_in_different_cu() throws Exception{ + ICompilationUnit cu= null; + ICompilationUnit otherCu= createCUfromTestFile(getPackageP(), "C"); + + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IImportContainer container= cu.getImportContainer(); + IJavaElement[] javaElements= { container }; + Object destination= otherCu; + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu, otherCu}, destination, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + otherCu.delete(true, new NullProgressMonitor()); + } + } + + public void test_import_container_yes_method_in_different_cu() throws Exception{ + ICompilationUnit cu= null; + ICompilationUnit otherCu= createCUfromTestFile(getPackageP(), "C"); + + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IImportContainer container= cu.getImportContainer(); + IJavaElement[] javaElements= { container }; + Object destination= otherCu; + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu, otherCu}, destination, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + otherCu.delete(true, new NullProgressMonitor()); + } + } + + public void test_import_container_yes_cu() throws Exception{ + ICompilationUnit cu= null; + ICompilationUnit otherCu= createCUfromTestFile(getPackageP(), "C"); + + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IImportContainer container= cu.getImportContainer(); + IJavaElement[] javaElements= { container }; + Object destination= otherCu; + verifyCopyingOfSubCuElements(new ICompilationUnit[]{cu, otherCu}, destination, javaElements); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + otherCu.delete(true, new NullProgressMonitor()); + } + } + + + public void testCopy_File_to_Folder() throws Exception { + ParticipantTesting.reset(); + IFolder parentFolder= (IFolder) getPackageP().getResource(); + String fileName= "a.txt"; + IFile file= parentFolder.getFile(fileName); + file.create(getStream("123"), true, null); + + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder destinationFolder= superFolder.getFolder("folder"); + destinationFolder.create(true, true, null); + + IFile newFile= null; + try { + + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {}; + IResource[] resources= { file }; + String[] handles= ParticipantTesting.createHandles(file); + + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= destinationFolder; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", file.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", file.exists()); + + newFile= destinationFolder.getFile(fileName); + assertTrue("new file does not exist after copying", newFile.exists()); + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsProcessed(file); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log) + }); + } finally { + performDummySearch(); + file.delete(true, false, null); + destinationFolder.delete(true, false, null); + if (newFile != null) + newFile.delete(true, false, null); + } + } + + public void testCopy_File_to_Same_Folder() throws Exception { + ParticipantTesting.reset(); + IFolder parentFolder= (IFolder) getPackageP().getResource(); + String fileName= "a.txt"; + IFile file= parentFolder.getFile(fileName); + file.create(getStream("123"), true, null); + + IFolder destinationFolder= parentFolder; + + IFile newFile= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {}; + IResource[] resources= { file }; + String[] handles= ParticipantTesting.createHandles(file); + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= destinationFolder; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", file.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", file.exists()); + + newFile= destinationFolder.getFile(MockNewNameQueries.NEW_FILE_NAME); + assertTrue("new file does not exist after copying", newFile.exists()); + ReorgExecutionLog log= new ReorgExecutionLog(); + log.setNewName(file, MockNewNameQueries.NEW_FILE_NAME); + log.markAsProcessed(file); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log) + }); + } finally { + performDummySearch(); + file.delete(true, false, null); + if (newFile != null) + newFile.delete(true, false, null); + } + } + + public void testCopy_File_to_Same_Folder_Cancel() throws Exception { + ParticipantTesting.reset(); + IFolder parentFolder= (IFolder) getPackageP().getResource(); + String fileName= "a.txt"; + IFile file= parentFolder.getFile(fileName); + file.create(getStream("123"), true, null); + + IFolder destinationFolder= parentFolder; + + try { + INewNameQueries queries= new MockCancelNameQueries(); + + IJavaElement[] javaElements= {}; + IResource[] resources= { file }; + String[] handles= ParticipantTesting.createHandles(file); + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= destinationFolder; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", file.exists()); + + try { + performRefactoring(ref, false); + } catch(OperationCanceledException e) { + } + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsCanceled(); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log) + }); + } finally { + performDummySearch(); + file.delete(true, false, null); + } + } + + public void testCopy_File_to_Itself() throws Exception { + IFolder parentFolder= (IFolder) getPackageP().getResource(); + String fileName= "a.txt"; + IFile file= parentFolder.getFile(fileName); + file.create(getStream("123"), true, null); + + IFile newFile= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {}; + IResource[] resources= { file }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= file; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", file.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", file.exists()); + + newFile= parentFolder.getFile(MockNewNameQueries.NEW_FILE_NAME); + assertTrue("new file does not exist after copying", newFile.exists()); + } finally { + performDummySearch(); + file.delete(true, false, null); + if (newFile != null) + newFile.delete(true, false, null); + } + } + + public void testCopy_File_to_AnotherFile() throws Exception { + IFolder parentFolder= (IFolder) getPackageP().getResource(); + String fileName= "a.txt"; + IFile file= parentFolder.getFile(fileName); + file.create(getStream("123"), true, null); + + IFile otherFile= RefactoringTestSetup.getProject().getProject().getFile("b.txt"); + otherFile.create(getStream("123"), true, null); + + IFile newFile= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {}; + IResource[] resources= { file }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= otherFile; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", file.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", file.exists()); + + newFile= RefactoringTestSetup.getProject().getProject().getFile(fileName); + assertTrue("new file does not exist after copying", newFile.exists()); + } finally { + performDummySearch(); + file.delete(true, false, null); + otherFile.delete(true, false, null); + if (newFile != null) + newFile.delete(true, false, null); + } + } + + public void testCopy_File_to_Package() throws Exception { + IFolder parentFolder= (IFolder) getPackageP().getResource(); + String fileName= "a.txt"; + IFile file= parentFolder.getFile(fileName); + file.create(getStream("123"), true, null); + + IPackageFragment otherPackage= getRoot().createPackageFragment("other.pack", true, new NullProgressMonitor()); + IFile newFile= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {}; + IResource[] resources= { file }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= otherPackage; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", file.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", file.exists()); + + newFile= ((IFolder)otherPackage.getResource()).getFile(fileName); + assertTrue("new file does not exist after copying", newFile.exists()); + } finally { + performDummySearch(); + file.delete(true, false, null); + otherPackage.delete(true, new NullProgressMonitor()); + if (newFile != null) + newFile.delete(true, false, null); + } + } + + public void testCopy_File_to_DefaultPackage() throws Exception { + IFolder parentFolder= (IFolder) getPackageP().getResource(); + String fileName= "a.txt"; + IFile file= parentFolder.getFile(fileName); + file.create(getStream("123"), true, null); + + IPackageFragment defaultPackage= getRoot().getPackageFragment(""); + assertTrue(defaultPackage.exists()); + assertTrue(defaultPackage.isDefaultPackage()); + IFile newFile= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {}; + IResource[] resources= { file }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= defaultPackage; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", file.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", file.exists()); + + newFile= ((IFolder)defaultPackage.getResource()).getFile(fileName); + assertTrue("new file does not exist after copying", newFile.exists()); + } finally { + performDummySearch(); + file.delete(true, false, null); + if (newFile != null) + newFile.delete(true, false, null); + } + } + + public void testCopy_File_to_SourceFolder() throws Exception { + IFolder parentFolder= (IFolder) getPackageP().getResource(); + String fileName= "a.txt"; + IFile file= parentFolder.getFile(fileName); + file.create(getStream("123"), true, null); + + IFile newFile= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {}; + IResource[] resources= { file }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= getRoot(); + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", file.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", file.exists()); + + newFile= ((IFolder)getRoot().getResource()).getFile(fileName); + assertTrue("new file does not exist after copying", newFile.exists()); + } finally { + performDummySearch(); + file.delete(true, false, null); + if (newFile != null) + newFile.delete(true, false, null); + } + } + + public void testCopy_File_to_JavaProject() throws Exception { + IFolder parentFolder= (IFolder) getPackageP().getResource(); + String fileName= "a.txt"; + IFile file= parentFolder.getFile(fileName); + file.create(getStream("123"), true, null); + + IFile newFile= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {}; + IResource[] resources= { file }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= RefactoringTestSetup.getProject(); + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", file.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", file.exists()); + + newFile= RefactoringTestSetup.getProject().getProject().getFile(fileName); + assertTrue("new file does not exist after copying", newFile.exists()); + } finally { + performDummySearch(); + file.delete(true, false, null); + if (newFile != null) + newFile.delete(true, false, null); + } + } + + public void testCopy_File_to_Cu() throws Exception { + IFolder parentFolder= (IFolder) getPackageP().getResource(); + String fileName= "a.txt"; + IFile file= parentFolder.getFile(fileName); + file.create(getStream("123"), true, null); + + IFile newFile= null; + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {}; + IResource[] resources= { file }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= cu; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", file.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", file.exists()); + + newFile= parentFolder.getFile(MockNewNameQueries.NEW_FILE_NAME); + assertTrue("new file does not exist after copying", newFile.exists()); + } finally { + performDummySearch(); + file.delete(true, false, null); + cu.delete(true, new NullProgressMonitor()); + if (newFile != null) + newFile.delete(true, false, null); + } + } + + public void testCopy_File_to_SimpleProject() throws Exception { + IFolder parentFolder= (IFolder) getPackageP().getResource(); + String fileName= "a.txt"; + IFile file= parentFolder.getFile(fileName); + file.create(getStream("123"), true, null); + + IFile newFile= null; + IProject simpleProject= ResourcesPlugin.getWorkspace().getRoot().getProject("mySImpleProject"); + simpleProject.create(null); + simpleProject.open(null); + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {}; + IResource[] resources= { file }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= simpleProject; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", file.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", file.exists()); + + newFile= simpleProject.getFile(fileName); + assertTrue("new file does not exist after copying", newFile.exists()); + } finally { + performDummySearch(); + file.delete(true, false, null); + simpleProject.delete(true, new NullProgressMonitor()); + if (newFile != null) + newFile.delete(true, false, null); + } + } + + public void testCopy_Cu_to_Folder() throws Exception { + String fileName= "A.java"; + ICompilationUnit cu= getPackageP().createCompilationUnit(fileName, "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder destinationFolder= superFolder.getFolder("folder"); + destinationFolder.create(true, true, null); + + IFile newFile= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {cu}; + IResource[] resources= { }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= destinationFolder; + verifyValidDestination(ref, destination); + + assertTrue("source cu does not exist before copying", cu.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source cu does not exist after copying", cu.exists()); + + newFile= destinationFolder.getFile(fileName); + assertTrue("new cu does not exist after copying", newFile.exists()); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + destinationFolder.delete(true, false, null); + if (newFile != null) + newFile.delete(true, false, null); + } + } + + public void testCopy_Bug67124() throws Exception { + String fileName= "A.java"; + ICompilationUnit cu= getPackageP().createCompilationUnit(fileName, "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + IPath cuPath= cu.getResource().getFullPath(); + + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder destinationFolder= superFolder.getFolder("folder"); + destinationFolder.create(true, true, null); + + IFile newFile= null; + try { + FileBuffers.getTextFileBufferManager().connect(cuPath, LocationKind.IFILE, null); + ITextFileBuffer buffer= FileBuffers.getTextFileBufferManager().getTextFileBuffer(cuPath, LocationKind.IFILE); + buffer.getDocument().replace(0, 0, "Dirty"); + + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {cu}; + IResource[] resources= { }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= destinationFolder; + verifyValidDestination(ref, destination); + + assertTrue("source cu does not exist before copying", cu.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source cu does not exist after copying", cu.exists()); + + newFile= destinationFolder.getFile(fileName); + assertTrue("new cu does not exist after copying", newFile.exists()); + + IPath newFilePath= newFile.getFullPath(); + try { + FileBuffers.getTextFileBufferManager().connect(newFilePath, LocationKind.IFILE, null); + ITextFileBuffer newBuffer= FileBuffers.getTextFileBufferManager().getTextFileBuffer(newFilePath, LocationKind.IFILE); + assertEquals(buffer.getDocument().get(), newBuffer.getDocument().get()); + } finally { + FileBuffers.getTextFileBufferManager().disconnect(newFilePath, LocationKind.IFILE, null); + } + } finally { + performDummySearch(); + + FileBuffers.getTextFileBufferManager().disconnect(cuPath, LocationKind.IFILE, null); + + cu.delete(true, new NullProgressMonitor()); + destinationFolder.delete(true, false, null); + if (newFile != null) + newFile.delete(true, false, null); + + } + } + + public void testCopy_Cu_to_Same_Package() throws Exception { + ParticipantTesting.reset(); + String fileName= "A.java"; + ICompilationUnit cu= getPackageP().createCompilationUnit(fileName, "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + ICompilationUnit newCu= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {cu}; + IResource[] resources= { }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + ResourceMapping mapping= JavaElementResourceMapping.create(cu); + String[] handles= ParticipantTesting.createHandles(cu, mapping); + + IPackageFragment destination= getPackageP(); + verifyValidDestination(ref, destination); + + assertTrue("source cu does not exist before copying", cu.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source cu does not exist after copying", cu.exists()); + + String newName= MockNewNameQueries.NEW_CU_NAME + ".java"; + newCu= getPackageP().getCompilationUnit(newName); + assertTrue("new cu does not exist after copying", newCu.exists()); + ReorgExecutionLog log= new ReorgExecutionLog(); + log.setNewName(cu, newName); + log.setNewName(mapping, newName); + log.markAsProcessed(cu); + log.markAsProcessed(mapping); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log), new CopyArguments(destination.getResource(), log) + }); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + if (newCu != null && newCu.exists()){ + newCu.delete(true, new NullProgressMonitor()); + } + } + } + + public void testCopy_Cu_to_Same_Package_Cancel() throws Exception { + ParticipantTesting.reset(); + String fileName= "A.java"; + ICompilationUnit cu= getPackageP().createCompilationUnit(fileName, "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + try { + INewNameQueries queries= new MockCancelNameQueries(); + + IJavaElement[] javaElements= {cu}; + IResource[] resources= { }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + ResourceMapping mapping= JavaElementResourceMapping.create(cu); + String[] handles= ParticipantTesting.createHandles(cu, mapping); + + IPackageFragment destination= getPackageP(); + verifyValidDestination(ref, destination); + + assertTrue("source cu does not exist before copying", cu.exists()); + + try { + performRefactoring(ref, false); + } catch (OperationCanceledException e) { + } + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsCanceled(); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log), new CopyArguments(destination.getResource(), log) + }); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void test_type_yes_type() throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit otherCu= createCUfromTestFile(getPackageP(), "C"); + + ICompilationUnit newCu= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {cu}; + IResource[] resources= { }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= otherCu; + verifyValidDestination(ref, destination); + + assertTrue("source cu does not exist before copying", cu.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source cu does not exist after copying", cu.exists()); + + newCu= getPackageP().getCompilationUnit(MockNewNameQueries.NEW_CU_NAME + ".java"); + assertTrue("new cu does not exist after copying", newCu.exists()); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + if (newCu != null && newCu.exists()){ + newCu.delete(true, new NullProgressMonitor()); + } + if (otherCu != null && otherCu.exists()){ + otherCu.delete(true, new NullProgressMonitor()); + } + } + } + + public void testCopy_Cu_to_Itself() throws Exception { + String fileName= "A.java"; + ICompilationUnit cu= getPackageP().createCompilationUnit(fileName, "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + ICompilationUnit newCu= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {cu}; + IResource[] resources= { }; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= cu; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", cu.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", cu.exists()); + + newCu= getPackageP().getCompilationUnit(MockNewNameQueries.NEW_CU_NAME + ".java"); + assertTrue("new file does not exist after copying", newCu.exists()); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + if (newCu != null && newCu.exists()){ + newCu.delete(true, new NullProgressMonitor()); + } + } + } + + public void testCopy_Cu_to_OtherPackage() throws Exception { + ParticipantTesting.reset(); + String fileName= "A.java"; + ICompilationUnit cu= getPackageP().createCompilationUnit(fileName, "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + IPackageFragment otherPackage= getRoot().createPackageFragment("other.pack", true, new NullProgressMonitor()); + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {cu}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + ResourceMapping mapping= JavaElementResourceMapping.create(cu); + String[] handles= ParticipantTesting.createHandles(cu, mapping); + + IPackageFragment destination= otherPackage; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", cu.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", cu.exists()); + + ICompilationUnit newCu= otherPackage.getCompilationUnit(fileName); + assertTrue("new file does not exist after copying", newCu.exists()); + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsProcessed(cu); + log.markAsProcessed(mapping); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log), new CopyArguments(destination.getResource(), log) + }); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + otherPackage.delete(true, new NullProgressMonitor()); + } + } + + public void testCopy_Cu_to_DefaultPackage() throws Exception { + ParticipantTesting.reset(); + String fileName= "A.java"; + ICompilationUnit cu= getPackageP().createCompilationUnit(fileName, "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + IPackageFragment defaultPackage= getRoot().getPackageFragment(""); + assertTrue(defaultPackage.exists()); + assertTrue(defaultPackage.isDefaultPackage()); + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {cu}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + ResourceMapping mapping= JavaElementResourceMapping.create(cu); + String[] handles= ParticipantTesting.createHandles(cu, mapping); + + IPackageFragment destination= defaultPackage; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", cu.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", cu.exists()); + + ICompilationUnit newCu= defaultPackage.getCompilationUnit(fileName); + assertTrue("new file does not exist after copying", newCu.exists()); + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsProcessed(cu); + log.markAsProcessed(mapping); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log), new CopyArguments(destination.getResource(), log) + }); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testCopy_Cu_to_SourceFolder() throws Exception { + String fileName= "A.java"; + ICompilationUnit cu= getPackageP().createCompilationUnit(fileName, "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + ICompilationUnit newCu= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {cu}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= getRoot(); + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", cu.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", cu.exists()); + + newCu= getRoot().getPackageFragment("").getCompilationUnit(fileName); + assertTrue("new file does not exist after copying", newCu.exists()); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testCopy_Cu_to_JavaProject() throws Exception { + String fileName= "A.java"; + ICompilationUnit cu= getPackageP().createCompilationUnit(fileName, "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + IFile newFile= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {cu}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= RefactoringTestSetup.getProject(); + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", cu.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", cu.exists()); + + newFile= RefactoringTestSetup.getProject().getProject().getFile(fileName); + assertTrue("new file does not exist after copying", newFile.exists()); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + if (newFile != null) + newFile.delete(true, false, null); + } + } + + public void testCopy_Cu_to_File_In_Package() throws Exception { + String fileName= "A.java"; + ICompilationUnit cu= getPackageP().createCompilationUnit(fileName, "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + IFolder parentFolder= (IFolder) getPackageP().getResource(); + IFile file= parentFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + assertTrue(file.exists()); + + ICompilationUnit newCu= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {cu}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= file; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", cu.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", cu.exists()); + + newCu= getPackageP().getCompilationUnit(MockNewNameQueries.NEW_CU_NAME + ".java"); + assertTrue("new file does not exist after copying", newCu.exists()); + + String expectedSource= "package p;class "+ MockNewNameQueries.NEW_CU_NAME +"{void foo(){}class Inner{}}"; + assertEqualLines("source compare failed", expectedSource, newCu.getSource()); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + file.delete(true, false, null); + if (newCu != null && newCu.exists()){ + newCu.delete(true, new NullProgressMonitor()); + } + } + } + + public void testCopy_Cu_to_File_In_Resource_Folder() throws Exception { + String fileName= "A.java"; + ICompilationUnit cu= getPackageP().createCompilationUnit(fileName, "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + IProject parentFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= parentFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + IFile newFile= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {cu}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= file; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", cu.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", cu.exists()); + + newFile= RefactoringTestSetup.getProject().getProject().getFile(fileName); + assertTrue("new file does not exist after copying", newFile.exists()); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + file.delete(true, false, null); + newFile.delete(true, false, null); + } + } + + public void testCopy_Cu_to_SimpleProject() throws Exception { + String fileName= "A.java"; + ICompilationUnit cu= getPackageP().createCompilationUnit(fileName, "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + IProject simpleProject= ResourcesPlugin.getWorkspace().getRoot().getProject("mySImpleProject"); + simpleProject.create(null); + simpleProject.open(null); + + IFile newFile= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {cu}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= simpleProject; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before copying", cu.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source file does not exist after copying", cu.exists()); + + newFile= simpleProject.getFile(fileName); + assertTrue("new file does not exist after copying", newFile.exists()); + } finally { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + simpleProject.delete(true, false, null); + newFile.delete(true, false, null); + } + } + + public void testCopy_Package_to_Its_Root() throws Exception { + ParticipantTesting.reset(); + IPackageFragment newPackage= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {getPackageP()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + ResourceMapping mapping= JavaElementResourceMapping.create(getPackageP()); + String[] handles= ParticipantTesting.createHandles(getPackageP(), mapping); + + IPackageFragmentRoot destination= getRoot(); + verifyValidDestination(ref, destination); + + assertTrue("source package does not exist before copying", getPackageP().exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source package does not exist after copying", getPackageP().exists()); + + newPackage= getRoot().getPackageFragment(MockNewNameQueries.NEW_PACKAGE_NAME); + assertTrue("new package does not exist after copying", newPackage.exists()); + ReorgExecutionLog log= new ReorgExecutionLog(); + log.setNewName(getPackageP(), MockNewNameQueries.NEW_PACKAGE_NAME); + log.setNewName(mapping, MockNewNameQueries.NEW_PACKAGE_NAME); + log.markAsProcessed(getPackageP()); + log.markAsProcessed(mapping); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log), + new CopyArguments(destination.getResource(), log) + }); + } finally { + performDummySearch(); + if (newPackage != null) + newPackage.delete(true, new NullProgressMonitor()); + } + } + + public void testCopy_Package_to_Its_Root_Cancel() throws Exception { + ParticipantTesting.reset(); + try { + INewNameQueries queries= new MockCancelNameQueries(); + + IJavaElement[] javaElements= {getPackageP()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + ResourceMapping mapping= JavaElementResourceMapping.create(getPackageP()); + String[] handles= ParticipantTesting.createHandles(getPackageP(), mapping); + + IPackageFragmentRoot destination= getRoot(); + verifyValidDestination(ref, destination); + + assertTrue("source package does not exist before copying", getPackageP().exists()); + + try { + performRefactoring(ref, false); + } catch(OperationCanceledException e) { + } + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsCanceled(); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log), + new CopyArguments(destination.getResource(), log) + }); + } finally { + performDummySearch(); + } + } + + public void testCopy_Package_to_Itself() throws Exception { + ParticipantTesting.reset(); + IPackageFragment newPackage= null; + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {getPackageP()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + ResourceMapping mapping= JavaElementResourceMapping.create(getPackageP()); + String[] handles= ParticipantTesting.createHandles(getPackageP(), mapping); + + IPackageFragment destination= getPackageP(); + verifyValidDestination(ref, destination); + + assertTrue("source package does not exist before copying", getPackageP().exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source package does not exist after copying", getPackageP().exists()); + + newPackage= getRoot().getPackageFragment(MockNewNameQueries.NEW_PACKAGE_NAME); + assertTrue("new package does not exist after copying", newPackage.exists()); + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsProcessed(getPackageP()); + log.markAsProcessed(mapping); + log.setNewName(getPackageP(), MockNewNameQueries.NEW_PACKAGE_NAME); + log.setNewName(mapping, MockNewNameQueries.NEW_PACKAGE_FOLDER_NAME); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination.getParent(), log), + new CopyArguments(destination.getParent().getResource(), log) + }); + } finally { + performDummySearch(); + if (newPackage != null && newPackage.exists()) + newPackage.delete(true, new NullProgressMonitor()); + } + } + + public void testCopy_Package_to_Another_Root() throws Exception { + IPackageFragmentRoot otherRoot= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "otherRoot"); + IPackageFragment newPackage= null; + String packageName= getPackageP().getElementName(); + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {getPackageP()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= otherRoot; + verifyValidDestination(ref, destination); + + assertTrue("source package does not exist before copying", getPackageP().exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source package does not exist after copying", getPackageP().exists()); + + newPackage= otherRoot.getPackageFragment(packageName); + assertTrue("new package does not exist after copying", newPackage.exists()); + } finally { + performDummySearch(); + newPackage.delete(true, new NullProgressMonitor()); + otherRoot.delete(0, 0, new NullProgressMonitor()); + } + } + + public void testCopy_Package_to_JavaProject_That_Is_Root() throws Exception { + IJavaProject otherProject= JavaProjectHelper.createJavaProject("otherProject", null); + JavaProjectHelper.addSourceContainer(otherProject, null); + try { + INewNameQueries queries= new MockNewNameQueries(); + + IJavaElement[] javaElements= {getPackageP()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, queries, createReorgQueries()); + + Object destination= otherProject; + verifyValidDestination(ref, destination); + + assertTrue("source package does not exist before copying", getPackageP().exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source package does not exist after copying", getPackageP().exists()); + + IPackageFragment newPackage= null; + IPackageFragmentRoot[] roots= otherProject.getAllPackageFragmentRoots(); + for (int i= 0; i < roots.length; i++) { + if (ReorgUtils.isSourceFolder(roots[i])){ + newPackage= roots[i].getPackageFragment(getPackageP().getElementName()); + assertTrue("new package does not exist after copying", newPackage.exists()); + } + } + assertNotNull(newPackage); + } finally { + performDummySearch(); + JavaProjectHelper.delete(otherProject); + } + } + + public void testCopy_folder_to_other_folder() throws Exception { + ParticipantTesting.reset(); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + String folderName= "folder"; + IFolder folder= superFolder.getFolder(folderName); + folder.create(true, true, null); + + IFolder otherFolder= superFolder.getFolder("otherfolder"); + otherFolder.create(true, true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, new MockNewNameQueries(), createReorgQueries()); + String[] handles= ParticipantTesting.createHandles(folder); + + Object destination= otherFolder; + verifyValidDestination(ref, destination); + + assertTrue("source does not exist before copying", folder.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source does not exist after copying", folder.exists()); + assertTrue("copied folder does not exist after copying", otherFolder.getFolder(folderName).exists()); + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsProcessed(folder); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log) + }); + + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + otherFolder.delete(true, new NullProgressMonitor()); + } + } + + public void testCopy_folder_to_same_container() throws Exception { + ParticipantTesting.reset(); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + String folderName= "folder"; + IFolder folder= superFolder.getFolder(folderName); + folder.create(true, true, null); + IFolder newFolder= null; + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, new MockNewNameQueries(), createReorgQueries()); + String[] handles= ParticipantTesting.createHandles(folder); + + Object destination= superFolder; + verifyValidDestination(ref, destination); + + assertTrue("source does not exist before copying", folder.exists()); + + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source does not exist after copying", folder.exists()); + newFolder= superFolder.getFolder(MockNewNameQueries.NEW_FOLDER_NAME); + assertTrue("copied folder does not exist after copying", newFolder.exists()); + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsProcessed(folder); + log.setNewName(folder, MockNewNameQueries.NEW_FOLDER_NAME); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log) + }); + + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + newFolder.delete(true, new NullProgressMonitor()); + } + } + + public void testCopy_folder_to_same_container_cancel() throws Exception { + ParticipantTesting.reset(); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + String folderName= "folder"; + IFolder folder= superFolder.getFolder(folderName); + folder.create(true, true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, new MockCancelNameQueries(), createReorgQueries()); + String[] handles= ParticipantTesting.createHandles(folder); + + Object destination= superFolder; + verifyValidDestination(ref, destination); + + assertTrue("source does not exist before copying", folder.exists()); + + try { + performRefactoring(ref, false); + } catch (OperationCanceledException e) { + } + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsCanceled(); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log) + }); + + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + } + } + + public void testCopy_folder_Java_project() throws Exception { + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + String folderName= "folder"; + IFolder folder= superFolder.getFolder(folderName); + folder.create(true, true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, new MockNewNameQueries(), createReorgQueries()); + + Object destination= RefactoringTestSetup.getProject(); + verifyValidDestination(ref, destination); + + assertTrue("source does not exist before copying", folder.exists()); + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source does not exist after copying", folder.exists()); + + assertTrue("copied folder does not exist after copying", RefactoringTestSetup.getProject().getProject().getFolder(folderName).exists()); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + } + } + + public void testCopy_folder_to_source_folder() throws Exception { + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + String folderName= "folder"; + IFolder folder= superFolder.getFolder(folderName); + folder.create(true, true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, new MockNewNameQueries(), createReorgQueries()); + + Object destination= getRoot(); + verifyValidDestination(ref, destination); + + assertTrue("source does not exist before copying", folder.exists()); + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source does not exist after copying", folder.exists()); + + assertTrue("copied folder does not exist after copying", ((IFolder)getRoot().getResource()).getFolder(folderName).exists()); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + } + } + + public void testCopy_folder_to_package() throws Exception { + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + String folderName= "folder"; + IFolder folder= superFolder.getFolder(folderName); + folder.create(true, true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, new MockNewNameQueries(), createReorgQueries()); + + IPackageFragment destination= getPackageP(); + verifyValidDestination(ref, destination); + assertTrue("source does not exist before copying", folder.exists()); + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source does not exist after copying", folder.exists()); + assertTrue("copied folder does not exist after copying", ((IFolder)destination.getResource()).getFolder(folderName).exists()); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + } + + } + public void testCopy_folder_to_file_in_another_folder() throws Exception { + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + String folderName= "folder"; + IFolder folder= superFolder.getFolder(folderName); + folder.create(true, true, null); + + IFolder otherFolder= superFolder.getFolder("otherfolder"); + otherFolder.create(true, true, null); + IFile fileInAnotherFolder= otherFolder.getFile("f.tex"); + fileInAnotherFolder.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, new MockNewNameQueries(), createReorgQueries()); + + Object destination= fileInAnotherFolder; + verifyValidDestination(ref, destination); + assertTrue("source does not exist before copying", folder.exists()); + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source does not exist after copying", folder.exists()); + assertTrue("copied folder does not exist after copying", otherFolder.getFolder(folderName).exists()); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + otherFolder.delete(true, new NullProgressMonitor()); + } + } + + public void testCopy_folder_to_cu() throws Exception { + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + String folderName= "folder"; + IFolder folder= superFolder.getFolder(folderName); + folder.create(true, true, null); + + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, new MockNewNameQueries(), createReorgQueries()); + + ICompilationUnit destination= cu; + verifyValidDestination(ref, destination); + assertTrue("source does not exist before copying", folder.exists()); + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source does not exist after copying", folder.exists()); + assertTrue("copied folder does not exist after copying", ((IFolder)getPackageP().getResource()).getFolder(folderName).exists()); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testCopy_folder_to_simple_project() throws Exception { + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + String folderName= "folder"; + IFolder folder= superFolder.getFolder(folderName); + folder.create(true, true, null); + + IProject simpleProject= ResourcesPlugin.getWorkspace().getRoot().getProject("mySImpleProject"); + simpleProject.create(null); + simpleProject.open(null); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, new MockNewNameQueries(), createReorgQueries()); + + Object destination= simpleProject; + verifyValidDestination(ref, destination); + assertTrue("source does not exist before copying", folder.exists()); + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source does not exist after copying", folder.exists()); + assertTrue("copied folder does not exist after copying", simpleProject.getFolder(folderName).exists()); + } finally{ + performDummySearch(); + folder.delete(true, new NullProgressMonitor()); + simpleProject.delete(true, true, new NullProgressMonitor()); + } + } + + public void testCopy_root_to_same_Java_project() throws Exception { + ParticipantTesting.reset(); + IPackageFragmentRoot newRoot= null; + try { + // Delete the unnamed folder so that the delta is a ADD not a CHANGED + IResource folder= RefactoringTestSetup.getProject().getProject().findMember(MockNewNameQueries.NEW_PACKAGE_FRAGMENT_ROOT_NAME); + if (folder != null) { + folder.delete(IResource.FORCE, null); + } + + IJavaElement[] javaElements= { getRoot() }; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, new MockNewNameQueries(), createReorgQueries()); + ResourceMapping mapping= JavaElementResourceMapping.create(getRoot()); + String[] handles= ParticipantTesting.createHandles(getRoot(), mapping); + + IJavaProject destination= getRoot().getJavaProject(); + verifyValidDestination(ref, destination); + assertTrue("source does not exist before copying", getRoot().exists()); + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source does not exist after copying", getRoot().exists()); + String newName= MockNewNameQueries.NEW_PACKAGE_FRAGMENT_ROOT_NAME; + newRoot= getSourceFolder(RefactoringTestSetup.getProject(), newName); + assertNotNull("copied folder does not exist after copying", newRoot); + assertTrue("copied folder does not exist after copying", newRoot.exists()); + ReorgExecutionLog log= new ReorgExecutionLog(); + log.setNewName(getRoot(), newName); + log.setNewName(mapping, newName); + log.markAsProcessed(getRoot()); + log.markAsProcessed(mapping); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log), new CopyArguments(destination.getResource(), log) + }); + } finally { + performDummySearch(); + if (newRoot != null && newRoot.exists()) + newRoot.delete(0, 0, new NullProgressMonitor()); + } + } + + public void testCopy_root_to_same_Java_project_cancel() throws Exception { + ParticipantTesting.reset(); + try { + IJavaElement[] javaElements= { getRoot()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, new MockCancelNameQueries(), createReorgQueries()); + ResourceMapping mapping= JavaElementResourceMapping.create(getRoot()); + String[] handles= ParticipantTesting.createHandles(getRoot(), mapping); + + IJavaProject destination= getRoot().getJavaProject(); + verifyValidDestination(ref, destination); + assertTrue("source does not exist before copying", getRoot().exists()); + try { + performRefactoring(ref, false); + } catch (OperationCanceledException e) { + } + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsCanceled(); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log), new CopyArguments(destination.getResource(), log) + }); + } finally { + performDummySearch(); + } + } + + public void testCopy_root_to_other_Java_project() throws Exception { + ParticipantTesting.reset(); + IJavaProject otherJavaProject= JavaProjectHelper.createJavaProject("other", "bin"); + try { + IJavaElement[] javaElements= { getRoot()}; + IResource[] resources= {}; + JavaCopyProcessor ref= verifyEnabled(resources, javaElements, new MockNewNameQueries(), createReorgQueries()); + ResourceMapping mapping= JavaElementResourceMapping.create(getRoot()); + String[] handles= ParticipantTesting.createHandles(getRoot(), mapping); + + IJavaProject destination= otherJavaProject; + verifyValidDestination(ref, destination); + assertTrue("source does not exist before copying", getRoot().exists()); + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + + assertTrue("source does not exist after copying", getRoot().exists()); + String newName= getRoot().getElementName(); + IPackageFragmentRoot newRoot= getSourceFolder(otherJavaProject, newName); + assertNotNull("copied folder does not exist after copying", newRoot); + assertTrue("copied folder does not exist after copying", newRoot.exists()); + ReorgExecutionLog log= new ReorgExecutionLog(); + log.markAsProcessed(getRoot()); + log.markAsProcessed(mapping); + ParticipantTesting.testCopy(handles, new CopyArguments[] { + new CopyArguments(destination, log), new CopyArguments(destination.getProject(), log) + }); + } finally { + performDummySearch(); + JavaProjectHelper.delete(otherJavaProject); + } + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/CopyToClipboardActionTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/CopyToClipboardActionTest.java new file mode 100644 index 000000000..271400c9f --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/CopyToClipboardActionTest.java @@ -0,0 +1,603 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.ccp; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.swt.dnd.Clipboard; +import org.eclipse.swt.dnd.FileTransfer; +import org.eclipse.swt.dnd.TextTransfer; +import org.eclipse.swt.widgets.Display; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; + +import org.eclipse.jface.viewers.ILabelProvider; + +import org.eclipse.ui.part.ResourceTransfer; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.ISourceManipulation; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.internal.corext.refactoring.TypedSource; +import org.eclipse.jdt.internal.corext.refactoring.reorg.JavaElementTransfer; +import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils; +import org.eclipse.jdt.internal.corext.util.Strings; + +import org.eclipse.jdt.ui.JavaElementLabelProvider; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSetup; +import org.eclipse.jdt.ui.tests.refactoring.infra.MockClipboard; +import org.eclipse.jdt.ui.tests.refactoring.infra.MockWorkbenchSite; + +import org.eclipse.jdt.internal.ui.refactoring.reorg.CopyToClipboardAction; +import org.eclipse.jdt.internal.ui.refactoring.reorg.TypedSourceTransfer; + + +public class CopyToClipboardActionTest extends RefactoringTest{ + + private ILabelProvider fLabelProvider; + + private static final Class clazz= CopyToClipboardActionTest.class; + + private Clipboard fClipboard; + + private ICompilationUnit fCuA; + private ICompilationUnit fCuB; + private IPackageFragment fPackageQ; + private IPackageFragment fPackageQ_R; + private IPackageFragment fDefaultPackage; + private static final String CU_A_NAME= "A"; + private static final String CU_B_NAME= "B"; + private IFile faTxt; + private IFolder fOlder; + + public CopyToClipboardActionTest(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + protected void setUp() throws Exception { + super.setUp(); + fClipboard= new MockClipboard(Display.getDefault()); + fDefaultPackage= RefactoringTestSetup.getDefaultSourceFolder().createPackageFragment("", true, null); + + fCuA= createCU(getPackageP(), CU_A_NAME + ".java", + "package p;" + + "import java.util.List;" + + "class A{" + + "int f;" + + "{}" + + "void foo(){}" + + "class Inner{}" + + "}"); + + fPackageQ= RefactoringTestSetup.getDefaultSourceFolder().createPackageFragment("q", true, null); + fCuB= createCU(fPackageQ, CU_B_NAME + ".java", + "package q;" + + "import java.util.Set;" + + "class B{" + + "int x;" + + "void bar(){}" + + "class InnerB{}" + + "}"); + + fPackageQ_R= RefactoringTestSetup.getDefaultSourceFolder().createPackageFragment("q.r", true, null); + + faTxt= createFile((IFolder)getPackageP().getUnderlyingResource(), "a.txt"); + fOlder= createFolder(RefactoringTestSetup.getProject().getProject(), "fOlder"); + + fLabelProvider= new JavaElementLabelProvider( JavaElementLabelProvider.SHOW_VARIABLE + + JavaElementLabelProvider.SHOW_PARAMETERS + + JavaElementLabelProvider.SHOW_TYPE); + assertTrue("A.java does not exist", fCuA.exists()); + assertTrue("B.java does not exist", fCuB.exists()); + assertTrue("q does not exist", fPackageQ.exists()); + assertTrue("q.r does not exist", fPackageQ_R.exists()); + assertTrue("a.txt does not exist", faTxt.exists()); + assertTrue("fOlder does not exist", fOlder.exists()); + } + + protected void tearDown() throws Exception { + super.tearDown(); + performDummySearch(); + fClipboard.dispose(); + fLabelProvider.dispose(); + delete(fCuA); + delete(fCuB); + delete(fPackageQ_R); + delete(fPackageQ); + delete(faTxt); + delete(fOlder); + } + + private IFile createFile(IFolder folder, String fileName) throws Exception { + IFile file= folder.getFile(fileName); + file.create(getStream("aa"), true, null); + return file; + } + + private IFolder createFolder(IProject project, String name) throws CoreException{ + IFolder folder= project.getFolder(name); + folder.create(true, true, null); + return folder; + } + + private static void delete(ISourceManipulation element) { + try { + if (element != null && ((IJavaElement)element).exists()) + element.delete(true, null); + } catch(JavaModelException e) { + //ignore, we must keep going + } + } + private static void delete(IFile element) { + try { + element.delete(true, false, null); + } catch(CoreException e) { + //ignore, we must keep going + } + } + + private static void delete(IFolder element) { + try { + element.delete(true, false, null); + } catch(CoreException e) { + //ignore, we must keep going + } + } + + private void checkDisabled(Object[] elements){ + CopyToClipboardAction copyAction= new CopyToClipboardAction(new MockWorkbenchSite(elements), fClipboard); + copyAction.setAutoRepeatOnFailure(true); + copyAction.update(copyAction.getSelection()); + assertTrue("action should be disabled", ! copyAction.isEnabled()); + } + + private void checkEnabled(Object[] elements) throws Exception{ + CopyToClipboardAction copyAction= new CopyToClipboardAction(new MockWorkbenchSite(elements), fClipboard); + copyAction.setAutoRepeatOnFailure(true); + copyAction.update(copyAction.getSelection()); + assertTrue("action should be enabled", copyAction.isEnabled()); + copyAction.run(); + checkClipboard(elements); + } + + private void checkClipboard(Object[] elementsCopied) throws Exception { + IResource[] resourcesCopied= getResources(elementsCopied); + IJavaElement[] javaElementsCopied= getJavaElements(elementsCopied); + IType[] mainTypesCopied= ReorgUtils.getMainTypes(javaElementsCopied); + + IResource[] resourcesExpected= computeResourcesExpectedInClipboard(resourcesCopied, mainTypesCopied, javaElementsCopied); + IJavaElement[] javaElementsExpected= computeJavaElementsExpectedInClipboard(javaElementsCopied, mainTypesCopied); + + String[] clipboardFiles= getClipboardFiles(); + IResource[] clipboardResources= getClipboardResources(); + String clipboardText= getClipboardText(); + IJavaElement[] clipboardJavaElements= getClipboardJavaElements(); + TypedSource[] clipboardTypedSources= getClipboardTypedSources(); + + checkNames(resourcesCopied, javaElementsCopied, clipboardText); + checkFiles(resourcesCopied, javaElementsCopied, mainTypesCopied, clipboardFiles); + checkTypedSources(javaElementsCopied, clipboardTypedSources); + checkElements(resourcesExpected, clipboardResources); + checkElements(javaElementsExpected, clipboardJavaElements); + } + + private void checkTypedSources(IJavaElement[] javaElementsCopied, TypedSource[] clipboardTypedSources) throws Exception { + TypedSource[] typedSources= TypedSource.createTypedSources(javaElementsCopied); + assertEquals("different number", typedSources.length, clipboardTypedSources.length); + TypedSource.sortByType(typedSources); + TypedSource.sortByType(clipboardTypedSources); + for (int i= 0; i < typedSources.length; i++) { + assertEquals("different typed sources", typedSources[i], clipboardTypedSources[i]); + } + } + + private IResource[] computeResourcesExpectedInClipboard(IResource[] resourcesCopied, IType[] mainTypesCopied, IJavaElement[] javaElementsCopied) throws JavaModelException { + IResource[] cuResources= ReorgUtils.getResources(getCompilationUnits(javaElementsCopied)); + return ReorgUtils.union(cuResources, ReorgUtils.union(resourcesCopied, ReorgUtils.getResources(ReorgUtils.getCompilationUnits(mainTypesCopied)))); + } + + private static IJavaElement[] computeJavaElementsExpectedInClipboard(IJavaElement[] javaElementsExpected, IType[] mainTypesCopied) throws JavaModelException { + return ReorgUtils.union(javaElementsExpected, ReorgUtils.getCompilationUnits(mainTypesCopied)); + } + + private String getName(IResource resource){ + return fLabelProvider.getText(resource); + } + private String getName(IJavaElement javaElement){ + return fLabelProvider.getText(javaElement); + } + + private static void checkElements(Object[] copied, Object[] retreivedFromClipboard) { + assertEquals("different number of elements", copied.length, retreivedFromClipboard.length); + sortByName(copied); + sortByName(retreivedFromClipboard); + for (int i= 0; i < retreivedFromClipboard.length; i++) { + Object retreived= retreivedFromClipboard[i]; + assertTrue("element does not exist", exists(retreived)); + assertTrue("different copied " + getName(copied[i]) + " retreived: " + getName(retreived) , copied[i].equals(retreivedFromClipboard[i])); + } + } + + private static boolean exists(Object element) { + if (element instanceof IJavaElement) + return ((IJavaElement)element).exists(); + if (element instanceof IResource) + return ((IResource)element).exists(); + assertTrue(false); + return false; + } + + private static String getName(Object object) { + if (object instanceof IJavaElement) + return ((IJavaElement)object).getElementName(); + if (object instanceof IResource) + return ((IResource)object).getName(); + return object == null ? null : object.toString(); + } + + private static void sortByName(Object[] copied) { + Arrays.sort(copied, new Comparator(){ + public int compare(Object arg0, Object arg1) { + return getName(arg0).compareTo(getName(arg1)); + } + }); + } + + private void checkNames(IResource[] resourcesCopied, IJavaElement[] javaElementsCopied, String clipboardText){ + List stringLines= Arrays.asList(Strings.convertIntoLines(clipboardText)); + assertEquals("different number of names", resourcesCopied.length + javaElementsCopied.length, stringLines.size()); + for (int i= 0; i < resourcesCopied.length; i++) { + String name= getName(resourcesCopied[i]); + assertTrue("name not in set:" + name, stringLines.contains(name)); + } + for (int i= 0; i < javaElementsCopied.length; i++) { + IJavaElement element= javaElementsCopied[i]; + if (! ReorgUtils.isInsideCompilationUnit(element)){ + String name= getName(element); + assertTrue("name not in set:" + name, stringLines.contains(name)); + } + } + } + + private static void checkFiles(IResource[] resourcesCopied, IJavaElement[] javaElementsCopied, IType[] mainTypes, String[] clipboardFiles) { + int expected= 0; + expected += resourcesCopied.length; + expected += countResources(javaElementsCopied); + expected += mainTypes.length; + + //we cannot compare file names here because they're absolute and depend on the worspace location + assertEquals("different number of files in clipboard", expected, clipboardFiles.length); + } + + private static int countResources(IJavaElement[] javaElementsCopied) { + int count= 0; + for (int i= 0; i < javaElementsCopied.length; i++) { + IJavaElement element= javaElementsCopied[i]; + switch (element.getElementType()) { + case IJavaElement.JAVA_PROJECT : + case IJavaElement.PACKAGE_FRAGMENT_ROOT : + case IJavaElement.PACKAGE_FRAGMENT : + case IJavaElement.COMPILATION_UNIT : + case IJavaElement.CLASS_FILE : + count++; + } + } + return count; + } + + private static IJavaElement[] getCompilationUnits(IJavaElement[] javaElements) { + List cus= ReorgUtils.getElementsOfType(javaElements, IJavaElement.COMPILATION_UNIT); + return (ICompilationUnit[]) cus.toArray(new ICompilationUnit[cus.size()]); + } + + private static IResource[] getResources(Object[] elements) { + return ReorgUtils.getResources(Arrays.asList(elements)); + } + + private static IJavaElement[] getJavaElements(Object[] elements) { + return ReorgUtils.getJavaElements(Arrays.asList(elements)); + } + + private IJavaElement[] getClipboardJavaElements() { + IJavaElement[] elements= (IJavaElement[])fClipboard.getContents(JavaElementTransfer.getInstance()); + return elements == null ? new IJavaElement[0]: elements; + } + + private String[] getClipboardFiles() { + String[] files= (String[])fClipboard.getContents(FileTransfer.getInstance()); + return files == null ? new String[0]: files; + } + + private IResource[] getClipboardResources() { + IResource[] resources= (IResource[])fClipboard.getContents(ResourceTransfer.getInstance()); + return resources == null ? new IResource[0]: resources; + } + + private TypedSource[] getClipboardTypedSources() { + TypedSource[] typedSources= (TypedSource[])fClipboard.getContents(TypedSourceTransfer.getInstance()); + return typedSources == null ? new TypedSource[0]: typedSources; + } + + private String getClipboardText() { + return (String)fClipboard.getContents(TextTransfer.getInstance()); + } + + ///---------tests + + public void testDisabled0() { + Object[] elements= {}; + checkDisabled(elements); + } + + public void testDisabled1() throws Exception { + Object[] elements= {null}; + checkDisabled(elements); + } + + public void testDisabled2() throws Exception { + Object[] elements= {this}; + checkDisabled(elements); + } + + public void testDisabled3() throws Exception { + Object[] elements= {RefactoringTestSetup.getProject(), getPackageP()}; + checkDisabled(elements); + } + + public void testDisabled4() throws Exception{ + checkDisabled(new Object[]{getPackageP(), fCuA}); + } + + public void testDisabled5() throws Exception{ + checkDisabled(new Object[]{getRoot(), fCuA}); + } + + public void testDisabled6() throws Exception{ + checkDisabled(new Object[]{getRoot(), fPackageQ}); + } + + public void testDisabled7() throws Exception{ + checkDisabled(new Object[]{getRoot(), faTxt}); + } + + public void testDisabled8() throws Exception{ + checkDisabled(new Object[]{getRoot(), getRoot().getJavaProject()}); + } + + public void testDisabled9() throws Exception{ + checkDisabled(new Object[]{RefactoringTestSetup.getProject().getPackageFragmentRoots()}); + } + + public void testDisabled10() throws Exception{ + checkDisabled(new Object[]{fCuA, fCuB}); + } + + public void testDisabled11() throws Exception{ + checkDisabled(new Object[]{fDefaultPackage}); + } + + public void testDisabled12() throws Exception{ + checkDisabled(new Object[]{getRoot().getJavaProject(), fCuA}); + } + + public void testDisabled13() throws Exception{ + checkDisabled(new Object[]{getRoot().getJavaProject(), fPackageQ}); + } + + public void testDisabled14() throws Exception{ + checkDisabled(new Object[]{getRoot().getJavaProject(), faTxt}); + } + + public void testDisabled15() throws Exception { + Object fieldF= fCuA.getType("A").getField("f"); + Object classA= fCuA.getType("A"); + Object[] elements= {fieldF, classA}; + checkDisabled(elements); + } + + public void testDisabled16() throws Exception { + Object fieldF= fCuA.getType("A").getField("f"); + Object[] elements= {fieldF, fCuA}; + checkDisabled(elements); + } + + public void testDisabled17() throws Exception { + Object fieldF= fCuA.getType("A").getField("f"); + Object[] elements= {fieldF, fDefaultPackage}; + checkDisabled(elements); + } + + public void testDisabled18() throws Exception { + Object fieldF= fCuA.getType("A").getField("f"); + Object[] elements= {fieldF, fPackageQ}; + checkDisabled(elements); + } + + public void testDisabled19() throws Exception { + Object fieldF= fCuA.getType("A").getField("f"); + Object[] elements= {fieldF, faTxt}; + checkDisabled(elements); + } + + public void testDisabled20() throws Exception { + Object fieldF= fCuA.getType("A").getField("f"); + Object[] elements= {fieldF, getRoot()}; + checkDisabled(elements); + } + + public void testDisabled21() throws Exception { + Object fieldF= fCuA.getType("A").getField("f"); + Object[] elements= {fieldF, RefactoringTestSetup.getProject()}; + checkDisabled(elements); + } + + public void testDisabled22() throws Exception { + Object typeA= fCuA.getType("A"); + Object typeB= fCuB.getType("B"); + Object[] elements= {typeA, typeB}; + checkDisabled(elements); + } + + public void testDisabled23() throws Exception{ + checkDisabled(new Object[]{faTxt, fCuB}); + } + + public void testEnabled0() throws Exception { + Object[] elements= {RefactoringTestSetup.getProject()}; + checkEnabled(elements); + } + + public void testEnabled1() throws Exception { + Object[] elements= {getPackageP()}; + checkEnabled(elements); + } + + public void testEnabled2() throws Exception { + Object[] elements= {getRoot()}; + checkEnabled(elements); + } + + public void testEnabled3() throws Exception { + Object[] elements= {RefactoringTestSetup.getDefaultSourceFolder()}; + checkEnabled(elements); + } + + public void testEnabled4() throws Exception{ + checkEnabled(new Object[]{faTxt}); + } + + public void testEnabled5() throws Exception{ + checkEnabled(new Object[]{getRoot()}); + } + + public void testEnabled6() throws Exception{ + checkEnabled(new Object[]{fCuA}); + } + + public void testEnabled7() throws Exception{ + checkEnabled(new Object[]{getRoot().getJavaProject()}); + } + + public void testEnabled8() throws Exception{ + checkEnabled(new Object[]{getPackageP()}); + } + + public void testEnabled9() throws Exception{ + checkEnabled(new Object[]{getPackageP(), fPackageQ, fPackageQ_R}); + } + + public void testEnabled10() throws Exception{ + Object packDecl= fCuA.getPackageDeclarations()[0]; + Object[] elements= {packDecl}; + checkEnabled(elements); + } + + public void testEnabled11() throws Exception{ + Object importD= fCuA.getImports()[0]; + Object[] elements= {importD}; + checkEnabled(elements); + } + + public void testEnabled12() throws Exception{ +// printTestDisabledMessage("disabled due to bug 37750"); +// if (true) +// return; + IJavaElement importContainer= fCuA.getImportContainer(); + Object[] elements= {importContainer}; + checkEnabled(elements); + } + + public void testEnabled13() throws Exception{ + Object classA= fCuA.getType("A"); + Object[] elements= {classA}; + checkEnabled(elements); + } + + public void testEnabled14() throws Exception{ + Object methodFoo= fCuA.getType("A").getMethod("foo", new String[0]); + Object[] elements= {methodFoo}; + checkEnabled(elements); + } + + public void testEnabled15() throws Exception{ + Object fieldF= fCuA.getType("A").getField("f"); + Object[] elements= {fieldF}; + checkEnabled(elements); + } + + public void testEnabled16() throws Exception{ + Object initializer= fCuA.getType("A").getInitializer(1); + Object[] elements= {initializer}; + checkEnabled(elements); + } + + public void testEnabled17() throws Exception{ + Object innerClass= fCuA.getType("A").getType("Inner"); + Object[] elements= {innerClass}; + checkEnabled(elements); + } + + public void testEnabled18() throws Exception{ + Object fieldF= fCuA.getType("A").getField("f"); + Object methodFoo= fCuA.getType("A").getMethod("foo", new String[0]); + Object innerClass= fCuA.getType("A").getType("Inner"); + Object initializer= fCuA.getType("A").getInitializer(1); + Object[] elements= {fieldF, methodFoo, initializer, innerClass}; + checkEnabled(elements); + } + + public void testEnabled19() throws Exception{ +// printTestDisabledMessage("disabled due to bug 37750"); +// if (true) +// return; + + Object classA= fCuA.getType("A"); + Object importContainer= fCuA.getImportContainer(); + Object packDecl= fCuA.getPackageDeclarations()[0]; + Object[] elements= {classA, importContainer, packDecl}; + checkEnabled(elements); + } + + public void testEnabled20() throws Exception{ + checkEnabled(new Object[]{faTxt, fCuA}); + } + + public void testEnabled21() throws Exception{ + checkEnabled(new Object[]{fOlder}); + } + + public void testEnabled22() throws Exception{ +// printTestDisabledMessage("bug 39410"); + Object classA= fCuA.getType("A"); + Object packDecl= fCuA.getPackageDeclarations()[0]; + Object[] elements= {classA, packDecl}; + checkEnabled(elements); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/DeleteTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/DeleteTest.java new file mode 100644 index 000000000..cdc9c0113 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/DeleteTest.java @@ -0,0 +1,1263 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.ccp; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.TreeMap; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.JavaTestPlugin; + +import org.eclipse.core.commands.operations.IOperationHistory; +import org.eclipse.core.commands.operations.IUndoContext; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Path; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IResource; + +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.operations.IWorkbenchOperationSupport; + +import org.eclipse.ltk.core.refactoring.IUndoManager; +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.DeleteRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgQueries; +import org.eclipse.jdt.internal.corext.refactoring.reorg.JavaDeleteProcessor; + +import org.eclipse.jdt.ui.tests.refactoring.ParticipantTesting; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSetup; + + +public class DeleteTest extends RefactoringTest{ + + private static final Class clazz= DeleteTest.class; + private static final String REFACTORING_PATH= "Delete/"; + + public DeleteTest(String name) { + super(name); + } + + public static Test suite() { + TestSuite classSuite= new TestSuite(clazz); + + // Last tests need to delete package p. Make sure they are really last to run: + TreeMap lastTests= new TreeMap(); // sorted by name + TestSuite suite= new TestSuite(classSuite.getName()); + for (Enumeration e= classSuite.tests(); e.hasMoreElements(); ) { + TestCase test= (TestCase) e.nextElement(); + String name= test.getName(); + if (name.startsWith("test_END_DeletePackageSub")) { + lastTests.put(name, test); + } else { + suite.addTest(test); + } + } + for (Iterator iter= lastTests.values().iterator(); iter.hasNext();) { + suite.addTest((Test) iter.next()); + } + return new RefactoringTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + protected void setUp() throws Exception { + super.setUp(); + fIsPreDeltaTest= true; + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + private void verifyDisabled(Object[] elements) throws CoreException { + JavaDeleteProcessor processor= new JavaDeleteProcessor(elements); + DeleteRefactoring ref= new DeleteRefactoring(processor); + assertTrue("delete should be disabled", !ref.isApplicable()); + } + + private void verifyEnabled(Object[] elements) throws CoreException { + JavaDeleteProcessor processor= new JavaDeleteProcessor(elements); + DeleteRefactoring ref= new DeleteRefactoring(processor); + assertTrue("delete should be enabled", ref.isApplicable()); + } + + private IPackageFragmentRoot getArchiveRoot() throws JavaModelException, Exception { + IPackageFragmentRoot[] roots= RefactoringTestSetup.getProject().getPackageFragmentRoots(); + IPackageFragmentRoot archive= null; + for (int i= 0; i < roots.length; i++) { + IPackageFragmentRoot root= roots[i]; + if (root.isArchive() && root.isExternal()) + archive= root; + } + return archive; + } + + private ICompilationUnit fCuA; + private static final String CU_NAME= "A"; + + private void loadFileSetup() throws Exception{ + fCuA= createCUfromTestFile(getPackageP(), CU_NAME); + assertTrue("A.java does not exist", fCuA.exists()); + } + + private void checkDelete(IJavaElement[] elems, boolean deleteCu) throws JavaModelException, Exception { + ICompilationUnit newCuA= null; + try { + DeleteRefactoring refactoring= createRefactoring(elems); + assertNotNull(refactoring); + RefactoringStatus status= performRefactoring(refactoring, true); + assertEquals("precondition was supposed to pass", null, status); + + newCuA= getPackageP().getCompilationUnit(CU_NAME + ".java"); + assertTrue("A.java does not exist", newCuA.exists() == !deleteCu); + if (! deleteCu) + assertEqualLines("incorrect content of A.java", getFileContents(getOutputTestFileName(CU_NAME)), newCuA.getSource()); + } finally { + performDummySearch(); + if (newCuA != null && newCuA.exists()) + newCuA.delete(true, null); + if (fCuA != null && fCuA.exists()){ + fCuA.delete(true, null); + fCuA= null; + } + } + } + + private DeleteRefactoring createRefactoring(Object[] elements) { + JavaDeleteProcessor processor= new JavaDeleteProcessor(elements); + DeleteRefactoring result= new DeleteRefactoring(processor); + processor.setQueries(createReorgQueries()); + return result; + } + + // package helpers + + private IPackageFragment[] createPackagePath(int no) throws JavaModelException { + IPackageFragment[] frags= new IPackageFragment[no]; + for (int i=0; i<no; i++) { + frags[i]= getRoot().createPackageFragment(getPackageName(i), true, new NullProgressMonitor()); + } + return frags; + } + + private String getPackageName(int i) { + StringBuffer buf= new StringBuffer(); + for (int j= 0; j <= i; j++) { + if (j>0) + buf.append("."); + buf.append("a"); + buf.append(j); + } + return buf.toString(); + } + + private void executeDeletePackage(Object[] markedForDelete, IPackageFragment[] packsToBeDeleted, Object[] othersToBeDeleted) throws CoreException, Exception { + executeDeletePackage(markedForDelete, packsToBeDeleted, othersToBeDeleted, false); + } + + /** + * Execute a package delete. + * @param markedForDelete The elements selected for deletion ("in the UI") + * @param packsToBeDeleted First half of elements which must be deleted after the refactoring + * @param othersToBeDeleted Second half (halfs will be merged). + * @param deleteSubs true if subpackages should be deleted as well. + * @throws CoreException + * @throws Exception + */ + private void executeDeletePackage(Object[] markedForDelete, IPackageFragment[] packsToBeDeleted, Object[] othersToBeDeleted, boolean deleteSubs) throws CoreException, Exception { + + List allList= new ArrayList(); + allList.addAll(Arrays.asList(packsToBeDeleted)); + allList.addAll(Arrays.asList(othersToBeDeleted)); + + Object[] all= allList.toArray(); + + ParticipantTesting.reset(); + String[] deleteHandles= ParticipantTesting.createHandles(all); + + verifyEnabled(markedForDelete); + performDummySearch(); + DeleteRefactoring ref= createRefactoring(markedForDelete); + ((JavaDeleteProcessor)ref.getProcessor()).setDeleteSubPackages(deleteSubs); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals("expected to pass", null, status); + + // assure participants got notified of everything. + ParticipantTesting.testDelete(deleteHandles); + } + + private void doTestUndoRedo(Object[] dontExist, Object[] exist) throws CoreException { + assertExist(exist, true); + assertExist(dontExist, false); + + IUndoManager undoManager= RefactoringCore.getUndoManager(); + undoManager.performUndo(null, new NullProgressMonitor()); + assertExist(exist, true); + assertExist(dontExist, true); + + undoManager.performRedo(null, new NullProgressMonitor()); + assertExist(exist, true); + assertExist(dontExist, false); + } + + private void assertExist(Object[] resourceOrElements, boolean exists) { + if (resourceOrElements != null) { + for (int i= 0; i < resourceOrElements.length; i++) { + assertExists(resourceOrElements[i], exists); + } + } + } + + private void assertExists(Object resourceOrElement, boolean exists) { + if (resourceOrElement instanceof IResource) { + IResource resource= (IResource) resourceOrElement; + if (exists) { + assertTrue("expected to exist: " + resource.getFullPath(), resource.exists()); + } else { + assertTrue("expected NOT to exist: " + resource.getFullPath(), ! resource.exists()); + } + } else if (resourceOrElement instanceof IJavaElement) { + IJavaElement javaElement= (IJavaElement) resourceOrElement; + if (exists) { + assertTrue("expected to exist: " + javaElement.getHandleIdentifier(), javaElement.exists()); + } else { + assertTrue("expected NOT to exist: " + javaElement.getHandleIdentifier(), ! javaElement.exists()); + IResource resource= javaElement.getResource(); + assertTrue("expected NOT to exist: " + resource.getFullPath(), ! resource.exists()); + } + } + } + + //---- tests + + private IReorgQueries createReorgQueries() { + return new MockReorgQueries(); + } + + public void testDisabled_emptySelection() throws Exception{ + verifyDisabled(new Object[] {}); + } + + public void testDisabled_projectAndNonProject() throws Exception{ + IJavaElement[] javaElements= {RefactoringTestSetup.getProject(), getPackageP()}; + verifyDisabled(javaElements); + } + + public void testDisabled_nonExistingResource() throws Exception{ + IFolder folder= (IFolder)getPackageP().getResource(); + IFile file= folder.getFile("a.txt"); + + IResource[] resources= {file}; + verifyDisabled(resources); + } + + public void testDisabled_nonExistingJavaElement() throws Exception{ + IJavaElement notExistingCu= getPackageP().getCompilationUnit("V.java"); + + IJavaElement[] javaElements= {notExistingCu}; + verifyDisabled(javaElements); + } + + public void testDisabled_nullResource() throws Exception{ + Object[] elements= {RefactoringTestSetup.getProject(), null}; + verifyDisabled(elements); + } + + public void testDisabled_nullJavaElement() throws Exception{ + Object[] elements= {getPackageP(), null}; + verifyDisabled(elements); + } + + public void testDisabled_archiveElement() throws Exception{ + IPackageFragmentRoot archive= getArchiveRoot(); + assertNotNull(archive); + + Object[] elements= archive.getChildren(); + verifyDisabled(elements); + } + + public void testDisabled_externalArchive() throws Exception{ + IPackageFragmentRoot archive= getArchiveRoot(); + assertNotNull(archive); + + Object[] elements= {archive}; + verifyDisabled(elements); + } + + public void testDisabled_archiveFromAnotherProject() throws Exception{ + //TODO implement me + } + + public void testDisabled_binaryMember() throws Exception{ + //TODO implement me + } + + public void testDisabled_javaProject() throws Exception{ + Object[] elements= {RefactoringTestSetup.getProject()}; + verifyDisabled(elements); + } + + public void testEnabled_defaultPackage() throws Exception{ + IPackageFragment defaultPackage= getRoot().getPackageFragment(""); + ICompilationUnit cu= defaultPackage.createCompilationUnit("A.java", "", false, new NullProgressMonitor()); + + try{ + Object[] elements= {defaultPackage}; + verifyEnabled(elements); + } finally{ + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testDisabled_simpleProject() throws Exception{ + Object[] elements= {RefactoringTestSetup.getProject().getProject()}; + verifyDisabled(elements); + } + + public void testEnabled_cu() throws Exception{ + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "", false, new NullProgressMonitor()); + + try{ + Object[] elements= {cu}; + verifyEnabled(elements); + } finally{ + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testEnabled_sourceReferences1() throws Exception{ + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "", false, new NullProgressMonitor()); + try{ + IJavaElement importD= cu.createImport("java.lang.*", null, new NullProgressMonitor()); + IJavaElement packageD= cu.createPackageDeclaration("p", new NullProgressMonitor()); + IJavaElement type= cu.createType("class A{}", null, false, new NullProgressMonitor()); + + Object[] elements= {packageD, importD, type}; + verifyEnabled(elements); + } finally{ + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + public void testEnabled_sourceReferences2() throws Exception{ + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "", false, new NullProgressMonitor()); + try{ + IType type= cu.createType("class A{}", null, false, new NullProgressMonitor()); + IJavaElement field= type.createField("int i;", null, false, new NullProgressMonitor()); + IJavaElement method= type.createMethod("void f(){}", null, false, new NullProgressMonitor()); + IJavaElement initializer= type.createInitializer("{ int k= 0;}", null, new NullProgressMonitor()); + IJavaElement innerType= type.createType("class Inner{}", null, false, new NullProgressMonitor()); + + Object[] elements= {field, method, initializer, innerType}; + verifyEnabled(elements); + } finally{ + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } + } + + + public void testEnabled_file() throws Exception{ + IFolder folder= (IFolder)getPackageP().getResource(); + IFile file= folder.getFile("a.txt"); + file.create(getStream("123"), true, null); + try{ + Object[] elements= {file}; + verifyEnabled(elements); + } finally{ + performDummySearch(); + file.delete(true, false, null); + } + } + + public void testEnabled_folder() throws Exception{ + IFolder folder= (IFolder)getPackageP().getResource(); + + Object[] elements= {folder}; + verifyEnabled(elements); + } + + public void testEnabled_readOnlyCu() throws Exception{ + //TODO implement me + } + + public void testEnabled_readOnlyFile() throws Exception{ + //TODO implement me + } + + public void testEnabled_package() throws Exception{ + Object[] elements= {getPackageP()}; + verifyEnabled(elements); + } + + public void testEnabled_sourceFolder() throws Exception{ + Object[] elements= {getRoot()}; + verifyEnabled(elements); + } + + public void testEnabled_linkedFile() throws Exception{ + //TODO implement me + } + + public void testEnabled_linkedFolder() throws Exception{ + //TODO implement me + } + + public void testEnabled_linkedPackage() throws Exception{ + //TODO implement me + } + + public void testEnabled_linkedSourceFolder() throws Exception{ + //TODO implement me + } + + public void testDeleteWithinCu0() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getField("i"); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu1() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A"); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(fCuA, elem0, fCuA.getResource()); + + checkDelete(elems, true); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu2() throws Exception{ + loadFileSetup(); + ParticipantTesting.reset(); + IJavaElement elem0= fCuA.getType("A").getField("i"); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu3() throws Exception{ + loadFileSetup(); + ParticipantTesting.reset(); + IJavaElement elem0= fCuA.getType("A").getField("i"); + IJavaElement elem1= fCuA.getType("A").getField("j"); + IJavaElement[] elems= new IJavaElement[]{elem0, elem1}; + String[] handles= ParticipantTesting.createHandles(elem0, elem1); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu4() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getField("i"); + IJavaElement elem1= fCuA.getType("A").getField("k"); + IJavaElement[] elems= new IJavaElement[]{elem0, elem1}; + String[] handles= ParticipantTesting.createHandles(elem0, elem1); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu5() throws Exception{ + loadFileSetup(); + ParticipantTesting.reset(); + IJavaElement elem0= fCuA.getType("A").getField("j"); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu6() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getField("j"); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu7() throws Exception{ + //exposes bug#9381 IPackageDeclaration is not ISourceManipulation + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getPackageDeclaration("p"); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu8() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getMethod("m", new String[0]); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu9() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getInitializer(1); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu10() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getInitializer(1); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu11() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getImport("java.util.List"); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu12() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getType("B"); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu13() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getType("B"); + IJavaElement elem1= fCuA.getType("A"); + IJavaElement[] elems= new IJavaElement[]{elem0, elem1}; + String[] handles= ParticipantTesting.createHandles(fCuA, fCuA.getTypes()[0], fCuA.getResource()); + + checkDelete(elems, true); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu14() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getType("B"); + IJavaElement elem1= fCuA.getType("A"); + IJavaElement elem2= fCuA.getPackageDeclaration("p"); + IJavaElement[] elems= new IJavaElement[]{elem0, elem1, elem2}; + String[] handles= ParticipantTesting.createHandles(fCuA, fCuA.getTypes()[0], fCuA.getResource()); + + checkDelete(elems, true); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu15() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getField("field"); + IJavaElement getter= fCuA.getType("A").getMethod("getField", new String[] {}); + IJavaElement setter= fCuA.getType("A").getMethod("setField", new String[] {"I"}); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0, getter, setter); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu16() throws Exception{ + if (true) { + printTestDisabledMessage("testDeleteWithinCu16 disabled for bug#55221"); + return; + } + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("Test"); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu17() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getMethod("f", new String[0]); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu18() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getMethod("fs", new String[0]); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu19() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getImportContainer(); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu20() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getField("fEmpty"); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu21() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("A").getField("var11"); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu22() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IJavaElement elem0= fCuA.getType("B"); + IJavaElement[] elems= new IJavaElement[]{elem0}; + String[] handles= ParticipantTesting.createHandles(elem0); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu23() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + IType typeA= fCuA.getType("A"); + IJavaElement[] elems= new IJavaElement[]{ + typeA.getField("nestingDepth"), typeA.getField("openOnRun"), + typeA.getMethod("getNestingDepth", new String[0]), typeA.getMethod("getOpenOnRun", new String[0]) + }; + String[] handles= ParticipantTesting.createHandles(elems); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu24() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + + int indexOf= fCuA.getSource().indexOf("Thread"); + IType type= (IType) fCuA.getElementAt(indexOf); + IJavaElement[] elems= new IJavaElement[] { type }; + + String[] handles= ParticipantTesting.createHandles(elems); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu25() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + + int indexOf= fCuA.getSource().indexOf("Thread"); + IType type= (IType) fCuA.getElementAt(indexOf); + IJavaElement[] elems= new IJavaElement[] { type }; + + String[] handles= ParticipantTesting.createHandles(elems); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteWithinCu26() throws Exception{ + ParticipantTesting.reset(); + loadFileSetup(); + + int indexOf= fCuA.getSource().indexOf("Y"); + IType type= (IType) fCuA.getElementAt(indexOf); + IJavaElement[] elems= new IJavaElement[] { type }; + + String[] handles= ParticipantTesting.createHandles(elems); + + checkDelete(elems, false); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteFile() throws Exception{ + ParticipantTesting.reset(); + IFolder folder= (IFolder)getPackageP().getResource(); + String content= "123"; + IFile file= folder.getFile("a.txt"); + file.create(getStream(content), true, null); + assertTrue("file does not exist", file.exists()); + Object[] elem= {file}; + verifyEnabled(elem); + performDummySearch(); + + String[] handles= ParticipantTesting.createHandles(file); + + DeleteRefactoring ref= createRefactoring(elem); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals("expected to pass", null, status); + assertTrue("file not deleted", ! file.exists()); + ParticipantTesting.testDelete(handles); + + IUndoManager undoManager= RefactoringCore.getUndoManager(); + assertTrue(! undoManager.anythingToRedo()); + assertTrue(undoManager.anythingToUndo()); + undoManager.performUndo(null, new NullProgressMonitor()); + assertTrue(file.exists()); + assertEquals(content, getContents(file)); + + assertTrue(undoManager.anythingToRedo()); + undoManager.performRedo(null, new NullProgressMonitor()); + assertTrue(! file.exists()); + } + + public void testDeleteFolder() throws Exception{ + ParticipantTesting.reset(); + IFolder folder= (IFolder)getPackageP().getResource(); + IFolder subFolder= folder.getFolder("subFolder"); + subFolder.create(true, true, null); + + assertTrue("folder does not exist", subFolder.exists()); + Object[] elements= {subFolder}; + verifyEnabled(elements); + performDummySearch(); + + String[] handles= ParticipantTesting.createHandles(subFolder); + DeleteRefactoring ref= createRefactoring(elements); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals("expected to pass", null, status); + assertTrue("folder not deleted", ! subFolder.exists()); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteNestedFolders() throws Exception{ + ParticipantTesting.reset(); + IFolder folder= (IFolder)getPackageP().getResource(); + IFolder subFolder= folder.getFolder("subFolder"); + subFolder.create(true, true, null); + IFolder subsubFolder= subFolder.getFolder("subSubFolder"); + subsubFolder.create(true, true, null); + + assertTrue("folder does not exist", subFolder.exists()); + assertTrue("folder does not exist", subsubFolder.exists()); + Object[] elements= {subFolder, subsubFolder}; + verifyEnabled(elements); + performDummySearch(); + + String[] handles= ParticipantTesting.createHandles(subFolder); + DeleteRefactoring ref= createRefactoring(elements); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals("expected to pass", null, status); + assertTrue("folder not deleted", ! subFolder.exists()); + assertTrue("folder not deleted", ! subsubFolder.exists()); + ParticipantTesting.testDelete(handles); + + IUndoManager undoManager= RefactoringCore.getUndoManager(); + assertTrue(! undoManager.anythingToRedo()); + assertTrue(undoManager.anythingToUndo()); + undoManager.performUndo(null, new NullProgressMonitor()); + assertTrue(subFolder.exists()); + assertTrue(subsubFolder.exists()); + + assertTrue(undoManager.anythingToRedo()); + undoManager.performRedo(null, new NullProgressMonitor()); + assertTrue(! subFolder.exists()); + assertTrue(! subsubFolder.exists()); + } + + public void testDeleteCu() throws Exception{ + ParticipantTesting.reset(); + final String contents= "package p; class X{}"; + ICompilationUnit newCU= getPackageP().createCompilationUnit("X.java", contents, true, new NullProgressMonitor()); + assertTrue("cu not created", newCU.exists()); + + Object[] elements= {newCU}; + String[] handles= ParticipantTesting.createHandles(newCU, newCU.getTypes()[0], newCU.getResource()); + + verifyEnabled(elements); + performDummySearch(); + + DeleteRefactoring ref= createRefactoring(elements); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals("expected to pass", null, status); + assertTrue("cu not deleted", ! newCU.exists()); + ParticipantTesting.testDelete(handles); + + IWorkbenchOperationSupport operationSupport= PlatformUI.getWorkbench().getOperationSupport(); + IOperationHistory operationHistory= operationSupport.getOperationHistory(); + IUndoContext undoContext= operationSupport.getUndoContext(); + + assertTrue(! operationHistory.canRedo(undoContext)); + assertTrue(operationHistory.canUndo(undoContext)); + operationHistory.undo(undoContext, null, null); + assertTrue(newCU.exists()); + assertEquals(contents, newCU.getSource()); + + assertTrue(operationHistory.canRedo(undoContext)); + operationHistory.redo(undoContext, null, null); + assertTrue(! newCU.exists()); + } + + public void testDeleteSourceFolder() throws Exception{ + ParticipantTesting.reset(); + IPackageFragmentRoot fredRoot= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "fred"); + assertTrue("not created", fredRoot.exists()); + + Object[] elements= {fredRoot}; + verifyEnabled(elements); + performDummySearch(); + String[] handles= ParticipantTesting.createHandles(fredRoot, fredRoot.getResource()); + DeleteRefactoring ref= createRefactoring(elements); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals("expected to pass", null, status); + assertTrue("not deleted", ! fredRoot.exists()); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteInternalJAR() throws Exception{ + ParticipantTesting.reset(); + File lib= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.MYLIB); + assertTrue("lib does not exist", lib.exists()); + IPackageFragmentRoot internalJAR= JavaProjectHelper.addLibraryWithImport(RefactoringTestSetup.getProject(), Path.fromOSString(lib.getPath()), null, null); + + Object[] elements= {internalJAR}; + verifyEnabled(elements); + performDummySearch(); + String[] handles= ParticipantTesting.createHandles(internalJAR, internalJAR.getResource()); + + DeleteRefactoring ref= createRefactoring(elements); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals("expected to pass", null, status); + assertTrue("not deleted", ! internalJAR.exists()); + ParticipantTesting.testDelete(handles); + } + + public void testDeleteClassFile() throws Exception{ + //TODO implement me - how do i get a handle to a class file? + } + + public void testDeletePackage() throws Exception{ + // newPackage <- delete + // newPackage.A + // newPackage.file + // all three items must be deleted. + // Notification of package delete and folder delete + ParticipantTesting.reset(); + IPackageFragment newPackage= getRoot().createPackageFragment("newPackage", true, new NullProgressMonitor()); + assertTrue("package not created", newPackage.exists()); + String cuContents= "public class A {}"; + ICompilationUnit cu= newPackage.createCompilationUnit("A.java", cuContents, false, null); + IFile file= ((IContainer)newPackage.getResource()).getFile(new Path("Z.txt")); + file.create(getStream("123"), true, null); + + Object[] elements= {newPackage}; + verifyEnabled(elements); + performDummySearch(); + String[] deleteHandles= ParticipantTesting.createHandles(newPackage, newPackage.getResource()); + + DeleteRefactoring ref= createRefactoring(elements); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals("expected to pass", null, status); + assertTrue("package not deleted", ! newPackage.exists()); + + ParticipantTesting.testDelete(deleteHandles); + + IUndoManager undoManager= RefactoringCore.getUndoManager(); + undoManager.performUndo(null, new NullProgressMonitor()); + assertTrue(newPackage.exists()); + assertTrue(file.exists()); + assertEquals(cuContents, cu.getSource()); + undoManager.performRedo(null, new NullProgressMonitor()); + assertTrue(! newPackage.exists()); + } + + public void testDeletePackage2() throws Exception{ + // p1 <- delete + // p1.A + // p1.file + // p1.p2 + // this tests cleaning of packages (p2 is not deleted) + ParticipantTesting.reset(); + IPackageFragment p1= getRoot().createPackageFragment("p1", true, new NullProgressMonitor()); + IPackageFragment p1p2= getRoot().createPackageFragment("p1.p2", true, new NullProgressMonitor()); + assertTrue("package not created", p1.exists()); + String cuContents= "public class A {}"; + ICompilationUnit cu= p1.createCompilationUnit("A.java", cuContents, false, null); + IFile file= ((IContainer)p1.getResource()).getFile(new Path("Z.txt")); + file.create(getStream("123"), true, null); + + Object[] elements= {p1}; + verifyEnabled(elements); + performDummySearch(); + String[] deleteHandles= ParticipantTesting.createHandles(p1, cu.getResource(), file); + + DeleteRefactoring ref= createRefactoring(elements); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals("expected to pass", null, status); + //Package is not delete since it had sub packages + assertTrue("package deleted", p1.exists()); + assertEquals(0, p1.getChildren().length); + assertTrue(p1p2.exists()); + assertTrue(! file.exists()); + assertTrue(! cu.exists()); + + ParticipantTesting.testDelete(deleteHandles); + + IUndoManager undoManager= RefactoringCore.getUndoManager(); + undoManager.performUndo(null, new NullProgressMonitor()); + assertTrue(p1.exists()); + assertTrue(p1p2.exists()); + assertTrue(file.exists()); + assertEquals(cuContents, cu.getSource()); + undoManager.performRedo(null, new NullProgressMonitor()); + assertTrue(p1p2.exists()); + assertTrue(! file.exists()); + assertTrue(! cu.exists()); + } + + public void testDeletePackage3() throws Exception { + // a0.a1.a2.a3 <- delete + // a0.a1.a2.a3.A + // all packages must be removed; folder a0 must be removed. + IPackageFragment[] frags= createPackagePath(4); + ICompilationUnit a= frags[3].createCompilationUnit("A.java", "public class A {}", false, null); + executeDeletePackage(new Object[] { frags[3] }, frags, new Object[] { frags[0].getResource() } ); + Object[] deleted= new Object[]{frags[0], frags[1], frags[2], frags[3], a}; + doTestUndoRedo(deleted, null); + } + + public void testDeletePackage4() throws Exception { + // a0.a1.a2.a3 <- delete + // a0.a1.a2.a3.A <- delete + // all packages must be removed; folder a0 must be removed. + IPackageFragment[] frags= createPackagePath(4); + ICompilationUnit a= frags[3].createCompilationUnit("A.java", "public class A {}", false, null); + executeDeletePackage(new Object[] { frags[3], a }, frags, new Object[] { frags[0].getResource() } ); + Object[] deleted= new Object[]{frags[0], frags[1], frags[2], frags[3], a}; + doTestUndoRedo(deleted, null); + } + + public void testDeletePackage5() throws Exception { + // a0.a1.a2.A <- not deleted + // a0.a1.a2.a3.a4.a5 <- delete + // only a3, a4, a5 are to be deleted; folder a3 must be removed. + IPackageFragment[] frags= createPackagePath(6); + ICompilationUnit a= frags[2].createCompilationUnit("A.java", "public class A {}", false, null); + executeDeletePackage(new Object[] { frags[5] }, new IPackageFragment[] { frags[5], frags[4], frags[3] }, new Object[] { frags[3].getResource() }); + Object[] deleted= new Object[]{frags[5], frags[4], frags[3]}; + Object[] exist= new Object[]{frags[2], frags[1], frags[0], a}; + doTestUndoRedo(deleted, exist); + } + + public void testDeletePackage6() throws Exception { + // a0.a1.a2.anotherPackage + // a0.a1.a2.a3.a4.a5 <- delete + // only a3, a4, a5 are to be deleted; folder a3 must be removed + IPackageFragment[] frags= createPackagePath(6); + IPackageFragment another= getRoot().createPackageFragment("a0.a1.a2.anotherPackage", true, null); + executeDeletePackage(new Object[] { frags[5] }, new IPackageFragment[] { frags[5], frags[4], frags[3] }, new Object[] { frags[3].getResource() }); + Object[] deleted= new Object[]{frags[5], frags[4], frags[3]}; + Object[] exist= new Object[]{frags[2], frags[1], frags[0], another}; + doTestUndoRedo(deleted, exist); + } + + public void testDeletePackage7() throws Exception { + // a0.a1.a2.A <- delete + // a0.a1.a2.a3.a4.a5 <- delete + // all packages must be deleted; folder a0 must be removed + IPackageFragment[] frags= createPackagePath(6); + ICompilationUnit a= frags[2].createCompilationUnit("A.java", "public class A {}", false, null); + executeDeletePackage(new Object[] { frags[5], a }, frags, new Object[] { frags[0].getResource() }); + Object[] deleted= new Object[]{frags[5], frags[4], frags[3], frags[2], frags[1], frags[0], a}; + Object[] exist= null; + doTestUndoRedo(deleted, exist); + } + + public void testDeletePackage8() throws Exception { + // a0.a1.a2.A <- delete + // a0.a1.a2.a3.Z <- don't delete + // a0.a1.a2.a3.a4.a5 <- delete + // only someFile, a4, and a5 are to be deleted; notification about a4, a5, A + IPackageFragment[] frags= createPackagePath(6); + ICompilationUnit a= frags[2].createCompilationUnit("A.java", "public class A {}", false, null); + IFile file= ((IContainer)frags[3].getResource()).getFile(new Path("Z.txt")); + file.create(getStream("123"), true, null); + executeDeletePackage(new Object[] { frags[5], a }, new IPackageFragment[] { frags[5], frags[4] }, new Object[] { frags[4].getResource(), a.getResource(), a, a.getType("A") }); + Object[] deleted= new Object[]{frags[5], frags[4], a}; + Object[] exist= new Object[]{frags[3], frags[2], frags[1], frags[0], file}; + doTestUndoRedo(deleted, exist); + } + + public void testDeletePackage9() throws Exception { + // a0.a1.a2.A <- delete + // a0.a1.a2.a3.Z <- delete + // a0.a1.a2.a3.a4.a5 <- delete + // all packages must be removed; folder a0 must be removed + IPackageFragment[] frags= createPackagePath(6); + ICompilationUnit a= frags[2].createCompilationUnit("A.java", "public class A {}", false, null); + IFile file= ((IContainer)frags[3].getResource()).getFile(new Path("Z.txt")); + file.create(getStream("123"), true, null); + executeDeletePackage(new Object[] { frags[5], a, file }, frags, new Object[] { frags[0].getResource() }); + Object[] deleted= new Object[]{frags[5], frags[4], frags[3], frags[2], frags[1], frags[0], a, file}; + Object[] exist= null; + doTestUndoRedo(deleted, exist); + } + + public void testDeletePackage10() throws Exception { + // a0.a1.a2 <- delete + // a0.a1.a2.A <- delete + // a0.a1.a2.a3 <- do not delete + // only A must be removed + // This tests "cleaning" of packages -> folder a0.a1.a2 does NOT get removed. + IPackageFragment[] frags= createPackagePath(4); + ICompilationUnit a= frags[2].createCompilationUnit("A.java", "public class A {}", false, null); + + ParticipantTesting.reset(); + final Object[] markedForDelete= new Object[] { frags[2], a.getResource() }; + String[] deleteHandles= ParticipantTesting.createHandles(markedForDelete); + + verifyEnabled(markedForDelete); + performDummySearch(); + DeleteRefactoring ref= createRefactoring(markedForDelete); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals("expected to pass", null, status); + + // test handles (!! only the package, not the resource) + ParticipantTesting.testDelete(deleteHandles); + // Package is not deleted since it had sub packages + Object[] deleted= new Object[]{a}; + Object[] exist= new Object[]{frags[3], frags[2], frags[1], frags[0]}; + doTestUndoRedo(deleted, exist); + } + + public void testDeletePackage11() throws Exception { + // Test deletion of default package of a project which is its own source folder + // (default) <- delete + // (default).A + // (default) x.txt <- don't delete + // expected: x.txt must not be deleted + + IJavaProject newJavaProject= JavaProjectHelper.createJavaProject("TestProject"+System.currentTimeMillis(), "bin"); + JavaProjectHelper.addRTJar(newJavaProject); + IPackageFragmentRoot root= JavaProjectHelper.addSourceContainer(newJavaProject, null); + + IPackageFragment defaultP= root.getPackageFragment(""); + IFile file= ((IContainer)defaultP.getResource()).getFile(new Path("Z.txt")); + file.create(getStream("123"), true, null); + + ICompilationUnit a= defaultP.createCompilationUnit("A.java", "public class A {}", false, null); + + ParticipantTesting.reset(); + final Object[] markedForDelete= new Object[] { defaultP }; + String[] deleteHandles= ParticipantTesting.createHandles(new Object[] { defaultP, a.getResource() }); + + verifyEnabled(markedForDelete); + performDummySearch(); + DeleteRefactoring ref= createRefactoring(markedForDelete); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals("expected to pass", null, status); + + ParticipantTesting.testDelete(deleteHandles); + Object[] deleted= new Object[]{a}; + Object[] exist= new Object[]{defaultP, file}; + doTestUndoRedo(deleted, exist); + } + + public void testDeletePackage12() throws Exception { + // a0 <- delete + // a0.a1 <- delete + // a0.a1.a2 + // a0 and a1 are to be cleaned, do not report any folder deletions + IPackageFragment[] frags= createPackagePath(3); + executeDeletePackage(new Object[] { frags[0], frags[1] }, new IPackageFragment[] { frags[0], frags[1] }, new Object[] { }); + Object[] deleted= null; + Object[] exist= new Object[]{frags[2], frags[1], frags[0]}; + doTestUndoRedo(deleted, exist); + } + + /* Don't rename! See #suite() */ + public void test_END_DeletePackageSub1() throws Exception { + // a0.a1.a2 <-delete with subs + // a0.a1.a2.a3 + // a0.a1.a2.a3.file + // a0.a1.a2.a3.A + // a0.a1.a2.a3.a4 + // expected: everything deleted + IPackageFragment[] frags= createPackagePath(5); + ICompilationUnit a= frags[3].createCompilationUnit("A.java", "public class A {}", false, null); + IFile file= ((IContainer)frags[3].getResource()).getFile(new Path("Z.txt")); + file.create(getStream("123"), true, null); + executeDeletePackage(new Object[] { frags[2] }, frags, new Object[] { frags[0].getResource() }, true); + Object[] deleted= new Object[]{frags[3], frags[2], frags[1], frags[0], a, file}; + Object[] exist= null; + doTestUndoRedo(deleted, exist); + } + + /* Don't rename! See #suite() */ + public void test_END_DeletePackageSub2() throws Exception { + // (default) <- delete + // a0 + // a0.a1 + // expected: nothing deleted; no notification about deletion + IPackageFragment[] frags= createPackagePath(2); + IPackageFragment p= getRoot().getPackageFragment("p"); + if (p.exists()) p.delete(true, null); + final IPackageFragment defaultPackage= getRoot().getPackageFragment(""); + executeDeletePackage(new Object[] { defaultPackage }, new IPackageFragment[] { defaultPackage }, new Object[0], true); + Object[] deleted= null; + Object[] exist= new Object[]{frags[1], frags[0], defaultPackage}; + doTestUndoRedo(deleted, exist); + } + + /* Don't rename! See #suite() */ + public void test_END_DeletePackageSub3() throws Exception { + // (default) <- delete + // (default).A + // (default)/file.txt + // a0 + // a0.a1 + // expected: A deleted; notification about deletion of: + // PackageFragments: <default> + // Folders: - + // Files: A.java (NOT other files in root, like file.txt). + IPackageFragment[] frags= createPackagePath(2); + final IPackageFragment defaultPackage= getRoot().getPackageFragment(""); + IPackageFragment p= getRoot().getPackageFragment("p"); + if (p.exists()) p.delete(true, null); + ICompilationUnit a= defaultPackage.createCompilationUnit("A.java", "public class A {}", false, null); + IFile file= ((IContainer)defaultPackage.getResource()).getFile(new Path("file.txt")); + file.create(getStream("123"), true, null); + executeDeletePackage(new Object[] { defaultPackage }, new IPackageFragment[0], new Object[] { defaultPackage, a.getResource() } , true); + Object[] deleted= new Object[]{a}; + Object[] exist= new Object[]{frags[1], frags[0], defaultPackage, file}; + doTestUndoRedo(deleted, exist); + } + + /* Don't rename! See #suite() */ + public void test_END_DeletePackageSub4() throws Exception { + // (default) + // a0 <- delete + // a0.a1 + // expected: everything deleted; notification about deletion of: + // PackageFragments: a0, a0.a1 + // Folders: a0 (NOT the folder of the default package) + IPackageFragment[] frags= createPackagePath(2); + IPackageFragment p= getRoot().getPackageFragment("p"); + if (p.exists()) p.delete(true, null); + executeDeletePackage(new Object[] { frags[0] }, frags, new Object[] { frags[0].getResource() } , true); + Object[] deleted= new Object[]{frags[1], frags[0]}; + Object[] exist= null; + doTestUndoRedo(deleted, exist); + } + + /* Don't rename! See #suite() */ + public void test_END_DeletePackageSub5() throws Exception { + // (default) <- delete + // (default).A + // a0 <- delete + // a0.a1 + // expected: everything deleted; notification about deletion of: + // PackageFragments: a0, a0.a1, <default> + // Folders: a0 (NOT the folder of the default package) + // Files: A.java (NOT other files in root, like .classpath). + IPackageFragment[] frags= createPackagePath(2); + final IPackageFragment defaultPackage= getRoot().getPackageFragment(""); + IPackageFragment p= getRoot().getPackageFragment("p"); + if (p.exists()) p.delete(true, null); + ICompilationUnit a= defaultPackage.createCompilationUnit("A.java", "public class A {}", false, null); + executeDeletePackage(new Object[] { defaultPackage, frags[0] }, frags, new Object[] { defaultPackage, a.getResource(), frags[0].getResource() } , true); + Object[] deleted= new Object[]{frags[1], frags[0], a}; + Object[] exist= null; + doTestUndoRedo(deleted, exist); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/MockReorgQueries.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/MockReorgQueries.java new file mode 100644 index 000000000..3aa349da4 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/MockReorgQueries.java @@ -0,0 +1,100 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.ccp; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.OperationCanceledException; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +import org.eclipse.jdt.internal.corext.refactoring.reorg.IConfirmQuery; +import org.eclipse.jdt.internal.corext.refactoring.reorg.INewNameQueries; +import org.eclipse.jdt.internal.corext.refactoring.reorg.INewNameQuery; +import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgQueries; + +public class MockReorgQueries implements IReorgQueries, INewNameQueries { + private final List fQueriesRun= new ArrayList(); + + public IConfirmQuery createYesNoQuery(String queryTitle, boolean allowCancel, int queryID) { + run(queryID); + return yesQuery; + } + + public IConfirmQuery createYesYesToAllNoNoToAllQuery(String queryTitle, boolean allowCancel, int queryID) { + run(queryID); + return yesQuery; + } + + private void run(int queryID) { + fQueriesRun.add(new Integer(queryID)); + } + + //List<Integer> + public List getRunQueryIDs() { + return fQueriesRun; + } + + private final IConfirmQuery yesQuery= new IConfirmQuery() { + public boolean confirm(String question) throws OperationCanceledException { + return true; + } + + public boolean confirm(String question, Object[] elements) throws OperationCanceledException { + return true; + } + }; + + public IConfirmQuery createSkipQuery(String queryTitle, int queryID) { + run(queryID); + return yesQuery; + } + + private static class NewNameQuery implements INewNameQuery { + private final String fName; + public NewNameQuery(String name) { + fName= name; + } + public String getNewName() throws OperationCanceledException { + return fName; + } + } + + + public INewNameQuery createNewCompilationUnitNameQuery(ICompilationUnit cu, String initialSuggestedName) throws OperationCanceledException { + return new NewNameQuery(initialSuggestedName + '1'); + } + + public INewNameQuery createNewPackageFragmentRootNameQuery(IPackageFragmentRoot root, String initialSuggestedName) throws OperationCanceledException { + return new NewNameQuery(initialSuggestedName + '1'); + } + + public INewNameQuery createNewPackageNameQuery(IPackageFragment pack, String initialSuggestedName) throws OperationCanceledException { + return new NewNameQuery(initialSuggestedName + '1'); + } + + public INewNameQuery createNewResourceNameQuery(IResource res, String initialSuggestedName) throws OperationCanceledException { + return new NewNameQuery(initialSuggestedName + '1'); + } + + public INewNameQuery createNullQuery() { + return new NewNameQuery(null); + } + + public INewNameQuery createStaticQuery(String newName) throws OperationCanceledException { + return new NewNameQuery(newName); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/MoveTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/MoveTest.java new file mode 100644 index 000000000..f3f68c4c2 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/MoveTest.java @@ -0,0 +1,2172 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.ccp; + +import java.io.IOException; +import java.util.Map; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.OperationCanceledException; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.ui.PlatformUI; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.MoveArguments; +import org.eclipse.ltk.core.refactoring.participants.MoveRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IInitializer; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; +import org.eclipse.jdt.internal.corext.refactoring.reorg.IConfirmQuery; +import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgDestination; +import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgQueries; +import org.eclipse.jdt.internal.corext.refactoring.reorg.JavaMoveProcessor; +import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgDestinationFactory; +import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory; +import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy; + +import org.eclipse.jdt.ui.tests.refactoring.ParticipantTesting; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSetup; + +import org.eclipse.jdt.internal.ui.refactoring.reorg.CreateTargetQueries; + + +public class MoveTest extends RefactoringTest { + + private static final class ConfirmAllQuery implements IReorgQueries { + public IConfirmQuery createSkipQuery(String queryTitle, int queryID) { + return new IConfirmQuery() { + public boolean confirm(String question) throws OperationCanceledException { + return false; + } + public boolean confirm(String question, Object[] elements) throws OperationCanceledException { + return false; + } + }; + } + + public IConfirmQuery createYesNoQuery(String queryTitle, boolean allowCancel, int queryID) { + return new IConfirmQuery() { + public boolean confirm(String question) throws OperationCanceledException { + return true; + } + public boolean confirm(String question, Object[] elements) throws OperationCanceledException { + return true; + } + }; + } + + public IConfirmQuery createYesYesToAllNoNoToAllQuery(String queryTitle, boolean allowCancel, int queryID) { + return new IConfirmQuery() { + public boolean confirm(String question) throws OperationCanceledException { + return true; + } + public boolean confirm(String question, Object[] elements) throws OperationCanceledException { + return true; + } + }; + } + } + + private static final class ConfirmNoneQuery implements IReorgQueries { + public IConfirmQuery createSkipQuery(String queryTitle, int queryID) { + return new IConfirmQuery() { + public boolean confirm(String question) throws OperationCanceledException { + return false; + } + public boolean confirm(String question, Object[] elements) throws OperationCanceledException { + return false; + } + }; + } + + public IConfirmQuery createYesNoQuery(String queryTitle, boolean allowCancel, int queryID) { + return new IConfirmQuery() { + public boolean confirm(String question) throws OperationCanceledException { + return false; + } + public boolean confirm(String question, Object[] elements) throws OperationCanceledException { + return false; + } + }; + } + + public IConfirmQuery createYesYesToAllNoNoToAllQuery(String queryTitle, boolean allowCancel, int queryID) { + return new IConfirmQuery() { + public boolean confirm(String question) throws OperationCanceledException { + return false; + } + public boolean confirm(String question, Object[] elements) throws OperationCanceledException { + return false; + } + }; + } + } + + public MoveTest(String name) { + super(name); + } + + private static final Class clazz= MoveTest.class; + private static final String REFACTORING_PATH= "Move/"; + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + protected void setUp() throws Exception { + super.setUp(); + fIsPreDeltaTest= true; + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + private IReorgQueries createReorgQueries(){ + return new MockReorgQueries(); + } + + private RefactoringStatus performRefactoring(JavaMoveProcessor processor, boolean providesUndo) throws Exception { + return performRefactoring(new MoveRefactoring(processor), providesUndo); + } + + private void verifyDisabled(IResource[] resources, IJavaElement[] javaElements) throws JavaModelException { + assertTrue("move should be disabled", ! RefactoringAvailabilityTester.isMoveAvailable(resources, javaElements)); + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(resources, javaElements); + JavaMoveProcessor processor= policy.canEnable() ? new JavaMoveProcessor(policy) : null; + assertTrue(processor == null); + } + + private JavaMoveProcessor verifyEnabled(IResource[] resources, IJavaElement[] javaElements, IReorgQueries reorgQueries) throws JavaModelException { + assertTrue("move should be enabled", RefactoringAvailabilityTester.isMoveAvailable(resources, javaElements)); + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(resources, javaElements); + JavaMoveProcessor processor= policy.canEnable() ? new JavaMoveProcessor(policy) : null; + if (reorgQueries != null) + processor.setReorgQueries(reorgQueries); + assertNotNull(processor); + return processor; + } + + private void verifyValidDestination(JavaMoveProcessor ref, Object destination) throws Exception { + RefactoringStatus status= ref.setDestination(ReorgDestinationFactory.createDestination(destination)); + + int severity= status.getSeverity(); + if (severity == RefactoringStatus.INFO) // see ReorgPolicyFactory.MoveFilesFoldersAndCusPolicy.verifyDestination(..) + return; + + assertEquals("destination was expected to be valid: " + status.getMessageMatchingSeverity(severity), RefactoringStatus.OK, severity); + } + + private void verifyInvalidDestination(JavaMoveProcessor ref, Object destination) throws Exception { + RefactoringStatus status= ref.setDestination(ReorgDestinationFactory.createDestination(destination)); + + assertEquals("destination was expected to be not valid", RefactoringStatus.FATAL, status.getSeverity()); + } + + private void safeDelete(ICompilationUnit cu) throws JavaModelException { + if (cu != null && cu.exists()) + cu.delete(true, new NullProgressMonitor()); + } + private void safeDelete(IPackageFragment pack) throws JavaModelException { + if (pack != null && pack.exists()) + pack.delete(true, new NullProgressMonitor()); + } + private void safeDelete(IResource res) throws CoreException { + if (res != null && res.exists()) + res.delete(true, null); + } + + + public void testDisabled_empty() throws Exception { + IJavaElement[] javaElements= {}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_null_element() throws Exception { + IJavaElement[] javaElements= {null}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_null_resource() throws Exception { + IJavaElement[] javaElements= {}; + IResource[] resources= {null}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_javaProject() throws Exception { + IJavaElement[] javaElements= {RefactoringTestSetup.getProject()}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_defaultPackage() throws Exception { + IPackageFragment defaultPackage= getRoot().getPackageFragment(""); + assertTrue(defaultPackage.exists()); + IJavaElement[] javaElements= {defaultPackage}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_project() throws Exception { + IJavaElement[] javaElements= {}; + IResource[] resources= {RefactoringTestSetup.getProject().getProject()}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_notExistingElement() throws Exception { + ICompilationUnit notExistingCu= getPackageP().getCompilationUnit("NotMe.java"); + assertTrue(! notExistingCu.exists()); + IJavaElement[] javaElements= {notExistingCu}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_notExistingResource() throws Exception { + IFolder folder= (IFolder)getPackageP().getResource(); + IFile notExistingFile= folder.getFile("a.txt"); + + IJavaElement[] javaElements= {}; + IResource[] resources= {notExistingFile}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_noCommonParent0() throws Exception { + IJavaElement[] javaElements= {getPackageP(), getRoot()}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } + + public void testDisabled_noCommonParent1() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + try { + IType classA= cu.getType("A"); + IMethod methodFoo= classA.getMethod("foo", new String[0]); + IJavaElement[] javaElements= { classA, methodFoo }; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } finally { + performDummySearch(); + safeDelete(cu); + } + } + +// public void testDisabled_noCommonParent2() throws Exception { +// ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); +// try { +// IType classA= cu.getType("A"); +// IJavaElement[] javaElements= { classA, cu}; +// IResource[] resources= {}; +// verifyDisabled(resources, javaElements); +// } finally { +// performDummySearch(); +// cu.delete(true, new NullProgressMonitor()); +// } +// } + + public void testDisabled_noCommonParent3() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + try { + IJavaElement[] javaElements= {cu, getPackageP()}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } finally { + performDummySearch(); + safeDelete(cu); + } + } + + public void testDisabled_noCommonParent5() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + try { + IJavaElement[] javaElements= {cu, getRoot()}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } finally { + performDummySearch(); + safeDelete(cu); + } + } + + public void testDisabled_noCommonParent6() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}}", false, new NullProgressMonitor()); + try { + IJavaElement[] javaElements= {cu, getRoot()}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } finally { + performDummySearch(); + safeDelete(cu); + } + } + + public void testDisabled_noCommonParent7() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{class Inner{}}", false, new NullProgressMonitor()); + try { + IType classA= cu.getType("A"); + IType classInner= classA.getType("Inner"); + IJavaElement[] javaElements= { classA, classInner}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } finally { + performDummySearch(); + safeDelete(cu); + } + } + + public void testDisabled_noCommonParent8() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try { + IType classA= cu.getType("A"); + IMethod methodFoo= classA.getMethod("foo", new String[0]); + IJavaElement[] javaElements= { methodFoo, classA}; + IResource[] resources= {}; + verifyDisabled(resources, javaElements); + } finally { + performDummySearch(); + safeDelete(cu); + } + } + + public void testDestination_no_fileToItself() throws Exception { + IFolder superFolder= (IFolder)getPackageP().getResource(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= file; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + file.delete(true, false, null); + } + } + + public void testDestination_no_fileToSiblingFile() throws Exception { + IFolder superFolder= (IFolder)getPackageP().getResource(); + IFile file1= superFolder.getFile("a.txt"); + file1.create(getStream("123"), true, null); + IFile file2= superFolder.getFile("b.txt"); + file2.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file1}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= file2; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + file1.delete(true, false, null); + file2.delete(true, false, null); + } + } + + public void testDestination_no_folderToItsef() throws Exception { + IFolder superFolder= (IFolder)getPackageP().getResource(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= folder; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + folder.delete(true, false, null); + } + } + + public void testDestination_no_cuToItsef() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= {cu}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= cu; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(cu); + } + } + + public void testDestination_no_cuToSiblingCu() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + ICompilationUnit cu1= getPackageP().createCompilationUnit("B.java", "package p;class A{}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= {cu}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= cu1; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(cu); + safeDelete(cu1); + } + } + + public void testDestination_no_cuToSiblingFile() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + IFolder superFolder= (IFolder)getPackageP().getResource(); + IFile file1= superFolder.getFile("a.txt"); + file1.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {cu}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= file1; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(cu); + safeDelete(file1); + } + } + + public void testDestination_no_packageToItsef() throws Exception { + IJavaElement[] javaElements= {getPackageP()}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getPackageP(); + verifyInvalidDestination(ref, destination); + } + + public void testDestination_no_sourceFolderToItsef() throws Exception { + IJavaElement[] javaElements= {getRoot()}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getRoot(); + verifyInvalidDestination(ref, destination); + } + + public void testDestination_no_methodToItsef() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= {method}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= method; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(cu); + } + } + + public void testDestination_no_fileToParentFolder() throws Exception { + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + IFile file= folder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= folder; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + folder.delete(true, false, null); + file.delete(true, false, null); + } + } + + public void testDestination_no_fileToParentPackage() throws Exception { + IFolder superFolder= (IFolder)getPackageP().getResource(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getPackageP(); + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + file.delete(true, false, null); + } + } + + public void testDestination_no_fileToParentSourceFolder() throws Exception { + IFolder superFolder= (IFolder)getRoot().getResource(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getRoot(); + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + file.delete(true, false, null); + } + } + + public void testDestination_no_folderToParentFolder() throws Exception { + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + + IFolder parentFolder= superFolder.getFolder("folder"); + parentFolder.create(true, true, null); + IFolder folder= parentFolder.getFolder("subfolder"); + folder.create(true, true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {parentFolder}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= parentFolder; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + parentFolder.delete(true, false, null); + } + } + + public void testDestination_no_cuToParentPackage() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= {cu}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= cu.getParent(); + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(cu); + } + } + + public void testDestination_no_packageToParentSourceFolder() throws Exception { + IJavaElement[] javaElements= {getPackageP()}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getRoot(); + verifyInvalidDestination(ref, destination); + } + + public void testDestination_no_sourceFolderToParentProject() throws Exception { + IJavaElement[] javaElements= {getRoot()}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getRoot().getParent(); + verifyInvalidDestination(ref, destination); + } + + public void testDestination_no_methodToParentType() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= {method}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= cu.getType("A"); + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(cu); + } + } + + public void testDestination_no_cuToMethod() throws Exception { + IPackageFragment pack1= getRoot().createPackageFragment("q", true, new NullProgressMonitor()); + ICompilationUnit cu= pack1.createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + ICompilationUnit cu1= getPackageP().createCompilationUnit("B.java", "package p;class B{}", false, new NullProgressMonitor()); + try{ + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= {cu1}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= method; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(pack1); + safeDelete(cu1); + } + } + + public void testDestination_no_packageToCu() throws Exception { + IPackageFragment pack1= getRoot().createPackageFragment("q", true, new NullProgressMonitor()); + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= {pack1}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= cu; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(pack1); + } + } + + public void testDestination_no_packageToFile() throws Exception { + IPackageFragment pack1= getRoot().createPackageFragment("q", true, new NullProgressMonitor()); + IFolder superFolder= (IFolder)getRoot().getResource(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {pack1}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= file; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(pack1); + file.delete(true, false, null); + } + } + + public void testDestination_no_packageToFolder() throws Exception { + IPackageFragment pack1= getRoot().createPackageFragment("q", true, new NullProgressMonitor()); + IFolder superFolder= (IFolder)getRoot().getResource(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + try{ + IJavaElement[] javaElements= {pack1}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= folder; + verifyValidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(pack1); + folder.delete(true, false, null); + } + } + + public void testDestination_no_packageToSimpleProject() throws Exception { + IProject simpleProject= ResourcesPlugin.getWorkspace().getRoot().getProject("mySImpleProject"); + simpleProject.create(null); + simpleProject.open(null); + + IPackageFragment pack1= getRoot().createPackageFragment("q", true, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= {pack1}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= simpleProject; + verifyValidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(pack1); + simpleProject.delete(true, true, null); + } + } + +// public void testDestination_no_packageToJavaProjectWithNoSourceFolders() throws Exception { +// IJavaProject otherProject= JavaProjectHelper.createJavaProject("otherProject", null); +// JavaProjectHelper.addSourceContainer(otherProject, null); +// IPackageFragment pack1= getRoot().createPackageFragment("q", true, new NullProgressMonitor()); +// try{ +// IJavaElement[] javaElements= {pack1}; +// IResource[] resources= {}; +// JavaMoveProcessor2 ref= verifyEnabled(resources, javaElements, createReorgQueries()); +// +// Object destination= otherProject; +// verifyInvalidDestination(ref, destination); +// } finally{ +// performDummySearch(); +// pack1.delete(true, new NullProgressMonitor()); +// JavaProjectHelper.delete(otherProject); +// } +// } + + public void testDestination_no_packageToSiblingPackage() throws Exception { + IPackageFragment pack1= getRoot().createPackageFragment("q", true, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= {getPackageP()}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= pack1; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(pack1); + } + } + + public void testDestination_no_sourceFolderToCu() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "src2"); + try{ + IJavaElement[] javaElements= {sourceFolder}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= cu; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(cu); + sourceFolder.delete(0, 0, new NullProgressMonitor()); + } + } + + public void testDestination_no_sourceFolderToPackage() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "src2"); + try{ + IJavaElement[] javaElements= {sourceFolder}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getPackageP(); + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + sourceFolder.delete(0, 0, new NullProgressMonitor()); + } + } + + public void testDestination_no_sourceFolderToFile() throws Exception { + IFolder superFolder= (IFolder)getRoot().getResource(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "src2"); + try{ + IJavaElement[] javaElements= {sourceFolder}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= file; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + sourceFolder.delete(0, 0, new NullProgressMonitor()); + file.delete(true, false, null); + } + } + + public void testDestination_no_sourceFolderToFolder() throws Exception { + IFolder superFolder= (IFolder)getRoot().getResource(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "src2"); + try{ + IJavaElement[] javaElements= {sourceFolder}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= folder; + verifyValidDestination(ref, destination); + } finally{ + performDummySearch(); + sourceFolder.delete(0, 0, new NullProgressMonitor()); + folder.delete(true, false, null); + } + } + + public void testDestination_no_sourceFolderToSourceFolder() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "src2"); + try{ + IJavaElement[] javaElements= {sourceFolder}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getRoot(); + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + sourceFolder.delete(0, 0, new NullProgressMonitor()); + } + } + + public void testDestination_no_sourceFolderToSimpleProject() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "src2"); + IProject simpleProject= ResourcesPlugin.getWorkspace().getRoot().getProject("mySImpleProject"); + simpleProject.create(null); + simpleProject.open(null); + + try{ + IJavaElement[] javaElements= {sourceFolder}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= simpleProject; + verifyValidDestination(ref, destination); + } finally{ + performDummySearch(); + sourceFolder.delete(0, 0, new NullProgressMonitor()); + simpleProject.delete(true, true, null); + } + } + + public void testDestination_no_sourceFolderToJavaProjecteWithNoSourceFolder() throws Exception { + IJavaProject otherProject= JavaProjectHelper.createJavaProject("otherProject", null); + JavaProjectHelper.addSourceContainer(otherProject, null); + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "src2"); + + try{ + IJavaElement[] javaElements= {sourceFolder}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= otherProject; + verifyInvalidDestination(ref, destination); + }finally{ + performDummySearch(); + sourceFolder.delete(0, 0, new NullProgressMonitor()); + JavaProjectHelper.delete(otherProject); + } + } + + public void testDestination_yes_methodToCu() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){/*impl*/}}", false, new NullProgressMonitor()); + ICompilationUnit cu1= getPackageP().createCompilationUnit("B.java", "package p;class B{}", false, new NullProgressMonitor()); + try{ + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= {method}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= cu1; + verifyValidDestination(ref, destination); + + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + + assertTrue("source method not moved", ! method.exists()); + + IType typeB= cu1.getType("B"); + IMethod methodBfoo= typeB.getMethod("foo", new String[0]); + assertTrue("method does not exist after", methodBfoo.exists()); + + assertEquals("void foo(){/*impl*/}", methodBfoo.getSource()); + + } finally{ + performDummySearch(); + safeDelete(cu); + safeDelete(cu1); + } + } + + public void testDestination_no_methodToFile() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + IFolder superFolder= (IFolder)getRoot().getResource(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + try{ + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= {method}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= file; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(cu); + file.delete(true, false, null); + } + } + + public void testDestination_no_methodToFolder() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + IFolder superFolder= (IFolder)getRoot().getResource(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + try{ + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= {method}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= folder; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(cu); + folder.delete(true, false, null); + } + } + + public void testDestination_no_methodToPackage() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= {method}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getPackageP(); + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(cu); + } + } + + public void testDestination_no_methodToSourceFolder() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= {method}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getRoot(); + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(cu); + } + } + + public void testDestination_no_methodToJavaProject() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= {method}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= RefactoringTestSetup.getProject(); + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(cu); + } + } + + public void testDestination_no_methodToSimpleProject() throws Exception { + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + IProject simpleProject= ResourcesPlugin.getWorkspace().getRoot().getProject("mySImpleProject"); + simpleProject.create(null); + simpleProject.open(null); + try{ + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= {method}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= simpleProject; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(cu); + simpleProject.delete(true, true, null); + } + } + + public void testDestination_no_cuToItself() throws Exception{ + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + Object destination= cu1; + verifyInvalidDestination(ref, destination); + }finally{ + performDummySearch(); + safeDelete(cu1); + } + } + + public void testDestination_yes_cuToOtherPackage() throws Exception{ + IPackageFragment otherPackage= getRoot().createPackageFragment("otherPackage", true, new NullProgressMonitor()); + String oldSource= "package p;class A{void foo(){}class Inner{}}"; + String newSource= "package otherPackage;class A{void foo(){}class Inner{}}"; + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", oldSource, false, new NullProgressMonitor()); + try{ + ParticipantTesting.reset(); + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + String[] handles= ParticipantTesting.createHandles(new Object[] {cu1, cu1.getTypes()[0], cu1.getResource()}); + JavaMoveProcessor processor= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= otherPackage; + verifyValidDestination(processor, destination); + + assertTrue("source file does not exist before moving", cu1.exists()); + RefactoringStatus status= performRefactoring(processor, true); + assertEquals(null, status); + assertTrue("source file exists after moving", ! cu1.exists()); + ICompilationUnit newCu= otherPackage.getCompilationUnit(cu1.getElementName()); + assertTrue("new file does not exist after moving", newCu.exists()); + assertEqualLines("source differs", newSource, newCu.getSource()); + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(otherPackage, processor.getUpdateReferences()), + new MoveArguments(otherPackage, processor.getUpdateReferences()), + new MoveArguments(otherPackage.getResource(), processor.getUpdateReferences())}); + }finally{ + performDummySearch(); + safeDelete(otherPackage); + } + } + + public void testDestination_yes_cuToOtherPackageWithMultiRoot() throws Exception { + ParticipantTesting.reset(); + //regression test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=47788 + IPackageFragment otherPackage= getRoot().createPackageFragment("otherPackage", true, new NullProgressMonitor()); + String oldA= "package p;public class A{}"; + String newA= "package otherPackage;public class A{}"; + ICompilationUnit cuA= getPackageP().createCompilationUnit("A.java", oldA, false, new NullProgressMonitor()); + + IPackageFragmentRoot testSrc= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "testSrc"); + IPackageFragment testP= testSrc.createPackageFragment("p", true, new NullProgressMonitor()); + String oldRef= "package p;\npublic class Ref { A t = new A(); }"; + String newRef= "package p;\n\nimport otherPackage.A;\n\npublic class Ref { A t = new A(); }"; + ICompilationUnit cuRef= testP.createCompilationUnit("Ref.java", oldRef, false, new NullProgressMonitor()); + try{ + IJavaElement[] javaElements= {cuA}; + IResource[] resources= {}; + String[] handles= ParticipantTesting.createHandles(new Object[] {cuA, cuA.getTypes()[0], cuA.getResource()}); + JavaMoveProcessor processor= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= otherPackage; + verifyValidDestination(processor, destination); + + assertTrue("source file does not exist before moving", cuA.exists()); + RefactoringStatus status= performRefactoring(processor, true); + assertEquals(null, status); + assertTrue("source file exists after moving", ! cuA.exists()); + ICompilationUnit newCu= otherPackage.getCompilationUnit(cuA.getElementName()); + assertTrue("new file does not exist after moving", newCu.exists()); + assertEqualLines("source differs", newA, newCu.getSource()); + assertEqualLines("Ref differs", newRef, cuRef.getSource()); + + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(otherPackage, processor.getUpdateReferences()), + new MoveArguments(otherPackage, processor.getUpdateReferences()), + new MoveArguments(otherPackage.getResource(), processor.getUpdateReferences())}); + }finally{ + performDummySearch(); + safeDelete(otherPackage); + JavaProjectHelper.removeSourceContainer(RefactoringTestSetup.getProject(), testSrc.getElementName()); + } + } + + public void testDestination_yes_cuToOtherPackageWithMultiRootBug109145() throws Exception { + ParticipantTesting.reset(); + + StringBuffer buf= new StringBuffer(); + buf.append("package p;\n"); + buf.append("public class Class2 {\n"); + buf.append(" Class1 c;\n"); + buf.append("}\n"); + ICompilationUnit toMove= getPackageP().createCompilationUnit("Class2.java", buf.toString(), false, new NullProgressMonitor()); + + IPackageFragmentRoot testSrc= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "testSrc"); + IPackageFragment testP= testSrc.createPackageFragment("p", true, new NullProgressMonitor()); + buf= new StringBuffer(); + buf.append("package p;\n"); + buf.append("public class Class1 {\n"); + buf.append("}\n"); + ICompilationUnit reference= testP.createCompilationUnit("Class1.java", buf.toString(), false, new NullProgressMonitor()); + IPackageFragment destination= testSrc.createPackageFragment("p2", true, new NullProgressMonitor()); + + try { + String[] handles= ParticipantTesting.createHandles(new Object[] { toMove, toMove.getTypes()[0], toMove.getResource() }); + JavaMoveProcessor processor= verifyEnabled(new IResource[] {}, new IJavaElement[] { toMove }, createReorgQueries()); + + verifyValidDestination(processor, destination); + + assertTrue("source file does not exist before moving", toMove.exists()); + RefactoringStatus status= performRefactoring(processor, true); + assertEquals(null, status); + assertTrue("source file exists after moving", !toMove.exists()); + ICompilationUnit newCu= destination.getCompilationUnit(toMove.getElementName()); + assertTrue("new file does not exist after moving", newCu.exists()); + + buf= new StringBuffer(); + buf.append("package p2;\n"); + buf.append("\n"); + buf.append("import p.Class1;\n"); + buf.append("\n"); + buf.append("public class Class2 {\n"); + buf.append(" Class1 c;\n"); + buf.append("}\n"); + assertEqualLines(buf.toString(), newCu.getSource()); + + buf= new StringBuffer(); + buf.append("package p;\n"); + buf.append("public class Class1 {\n"); + buf.append("}\n"); + assertEqualLines(buf.toString(), reference.getSource()); + + ParticipantTesting.testMove(handles, new MoveArguments[] { new MoveArguments(destination, processor.getUpdateReferences()), + new MoveArguments(destination, processor.getUpdateReferences()), new MoveArguments(destination.getResource(), processor.getUpdateReferences()) }); + } finally { + performDummySearch(); + JavaProjectHelper.removeSourceContainer(RefactoringTestSetup.getProject(), testSrc.getElementName()); + } + } + + public void testDestination_yes_cuToRoot() throws Exception{ + ParticipantTesting.reset(); + String newSource= "package p;class A{void foo(){}class Inner{}}"; + String oldSource= "package p;class A{void foo(){}class Inner{}}"; + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", oldSource, false, new NullProgressMonitor()); + IPackageFragmentRoot destination= JavaProjectHelper.addSourceContainer(getRoot().getJavaProject(), "src2"); + ICompilationUnit newCu= null; + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + String[] handles= ParticipantTesting.createHandles(new Object[] {cu1, cu1.getTypes()[0], cu1.getResource()}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before moving", cu1.exists()); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + assertTrue("source file exists after moving", ! cu1.exists()); + newCu= destination.getPackageFragment("p").getCompilationUnit(cu1.getElementName()); + assertTrue("new file does not exist after moving", newCu.exists()); + assertEqualLines("source differs", newSource, newCu.getSource()); + + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(destination.getPackageFragment("p"), ref.getUpdateReferences()), + new MoveArguments(destination.getPackageFragment("p"), ref.getUpdateReferences()), + new MoveArguments(destination.getPackageFragment("p").getResource(), ref.getUpdateReferences()) }); + + }finally{ + performDummySearch(); + safeDelete(newCu); + } + } + + public void testDestination_yes_cuFromRoot() throws Exception{ + ParticipantTesting.reset(); + + //import statement with type from default package - only <= java 1.3 + IJavaProject javaProject= getRoot().getJavaProject(); + Map originalOptions= javaProject.getOptions(false); + Map newOptions= javaProject.getOptions(false); + newOptions.put(JavaCore.COMPILER_COMPLIANCE, "1.3"); + newOptions.put(JavaCore.COMPILER_SOURCE, "1.3"); + javaProject.setOptions(newOptions); + + String oldD= "import org.test.Reference;public class Default {Reference ref;}"; + String oldRef= "package org.test;import Default;public class Reference{Default d;}"; + String newD= "package org;\nimport org.test.Reference;public class Default {Reference ref;}"; + String newRef= "package org.test;import org.Default;\npublic class Reference{Default d;}"; + ICompilationUnit cuD= getRoot().getPackageFragment("").createCompilationUnit("Default.java", oldD, false, new NullProgressMonitor()); + IPackageFragment orgTest= getRoot().createPackageFragment("org.test", false, new NullProgressMonitor()); + ICompilationUnit cuRef= orgTest.createCompilationUnit("Reference.java", oldRef, false, new NullProgressMonitor()); + IPackageFragment org= getRoot().getPackageFragment("org"); + ICompilationUnit newCuD= org.getCompilationUnit(cuD.getElementName()); + try{ + IJavaElement[] javaElements= { cuD }; + IResource[] resources= {}; + String[] handles= ParticipantTesting.createHandles(new Object[] {cuD, cuD.getTypes()[0], cuD.getResource()}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + verifyValidDestination(ref, org); + + assertTrue("source file Default.java does not exist before moving", cuD.exists()); + assertTrue("source file Reference.java does not exist before moving", cuRef.exists()); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + assertTrue("source file Default.java exists after moving", ! cuD.exists()); + assertTrue("new file Default.java does not exist after moving", newCuD.exists()); + assertTrue("source file Reference.java does not exist after moving", cuRef.exists()); + assertEqualLines("Default.java differs", newD, newCuD.getSource()); + assertEqualLines("Reference.java differs", newRef, cuRef.getSource()); + + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(org, ref.getUpdateReferences()), + new MoveArguments(org, ref.getUpdateReferences()), + new MoveArguments(org.getResource(), ref.getUpdateReferences())}); + }finally{ + performDummySearch(); + safeDelete(newCuD); + safeDelete(orgTest); + safeDelete(org); + javaProject.setOptions(originalOptions); + } + } + + public void testDestination_no_cuFromRoot() throws Exception{ + //import statement with type from default package - only <= java 1.3 + IJavaProject javaProject= getRoot().getJavaProject(); + Map originalOptions= javaProject.getOptions(false); + Map newOptions= javaProject.getOptions(false); + newOptions.put(JavaCore.COMPILER_COMPLIANCE, "1.4"); //will cause error (potential match) + newOptions.put(JavaCore.COMPILER_SOURCE, "1.4"); //will cause error (potential match) + javaProject.setOptions(newOptions); + + String oldD= "import org.test.Reference;public class Default {Reference ref;}"; + String oldRef= "package org.test;import Default;public class Reference{Default d;}"; + String newD= "package org;\nimport org.test.Reference;public class Default {Reference ref;}"; + String newRef= "package org.test;import org.Default;\npublic class Reference{Default d;}"; + ICompilationUnit cuD= getRoot().getPackageFragment("").createCompilationUnit("Default.java", oldD, false, new NullProgressMonitor()); + IPackageFragment orgTest= getRoot().createPackageFragment("org.test", false, new NullProgressMonitor()); + ICompilationUnit cuRef= orgTest.createCompilationUnit("Reference.java", oldRef, false, new NullProgressMonitor()); + IPackageFragment org= getRoot().getPackageFragment("org"); + ICompilationUnit newCuD= org.getCompilationUnit(cuD.getElementName()); + try{ + IJavaElement[] javaElements= { cuD }; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + verifyValidDestination(ref, org); + + assertTrue("source file Default.java does not exist before moving", cuD.exists()); + assertTrue("source file Reference.java does not exist before moving", cuRef.exists()); + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(RefactoringStatus.ERROR, status.getSeverity()); + assertTrue("source file Default.java exists after moving", ! cuD.exists()); + assertTrue("new file Default.java does not exist after moving", newCuD.exists()); + assertTrue("source file Reference.java does not exist after moving", cuRef.exists()); + assertEqualLines("Default.java differs", newD, newCuD.getSource()); + assertEqualLines("Reference.java differs", newRef, cuRef.getSource()); + + }finally{ + performDummySearch(); + safeDelete(newCuD); + safeDelete(orgTest); + safeDelete(org); + javaProject.setOptions(originalOptions); + } + } + + public void testDestination_yes_cuToProject() throws Exception{ + ParticipantTesting.reset(); + String oldSource= "package p;class A{void foo(){}class Inner{}}"; + String newSource= oldSource; + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", oldSource, false, new NullProgressMonitor()); + IFile newFile= null; + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + String[] handles= ParticipantTesting.createHandles(new Object[] {cu1, cu1.getTypes()[0], cu1.getResource()}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + IJavaProject project= RefactoringTestSetup.getProject(); + Object destination= project; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before moving", cu1.exists()); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + assertTrue("source file exists after moving", ! cu1.exists()); + newFile= project.getProject().getFile(cu1.getElementName()); + assertEqualLines("source differs", newSource, getContents(newFile)); + + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(project.getProject(), ref.getUpdateReferences()), + new MoveArguments(project.getProject(), ref.getUpdateReferences()), + new MoveArguments(project.getResource(), ref.getUpdateReferences())}); + }finally{ + performDummySearch(); + safeDelete(newFile); + } + } + + public void testDestination_yes_cuToSimpleProject() throws Exception{ + ParticipantTesting.reset(); + String oldSource= "package p;class A{void foo(){}class Inner{}}"; + String newSource= oldSource; + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", oldSource, false, new NullProgressMonitor()); + IProject simpleProject= ResourcesPlugin.getWorkspace().getRoot().getProject("mySImpleProject"); + simpleProject.create(null); + simpleProject.open(null); + IFile newFile= null; + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + String[] handles= ParticipantTesting.createHandles(new Object[] {cu1, cu1.getTypes()[0], cu1.getResource()}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= simpleProject; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before moving", cu1.exists()); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + assertTrue("source file exists after moving", ! cu1.exists()); + newFile= simpleProject.getFile(cu1.getElementName()); + assertEqualLines("source differs", newSource, getContents(newFile)); + + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(simpleProject, ref.getUpdateReferences()), + new MoveArguments(simpleProject, ref.getUpdateReferences()), + new MoveArguments(simpleProject, ref.getUpdateReferences())}); + }finally{ + performDummySearch(); + safeDelete(simpleProject); + } + } + + public void testDestination_yes_cuToFileInDifferentPackage() throws Exception{ + ParticipantTesting.reset(); + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + IPackageFragment otherPackage= getRoot().createPackageFragment("other", true, new NullProgressMonitor()); + IFolder superFolder= (IFolder) otherPackage.getResource(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + ICompilationUnit newCu= null; + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + String[] handles= ParticipantTesting.createHandles(new Object[] {cu1, cu1.getTypes()[0], cu1.getResource()}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= file; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before", cu1.exists()); + + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + + assertTrue("source file not moved", ! cu1.exists()); + + newCu= otherPackage.getCompilationUnit(cu1.getElementName()); + assertTrue("new file does not exist after", newCu.exists()); + + String expectedSource= "package other;class A{void foo(){}class Inner{}}"; + assertEqualLines("source compare failed", expectedSource, newCu.getSource()); + + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(otherPackage, ref.getUpdateReferences()), + new MoveArguments(otherPackage, ref.getUpdateReferences()), + new MoveArguments(otherPackage.getResource(), ref.getUpdateReferences())}); + }finally{ + performDummySearch(); + safeDelete(otherPackage); + safeDelete(newCu); + safeDelete(file); + } + } + + public void testDestination_yes_cuToFolder() throws Exception{ + ParticipantTesting.reset(); + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IFile newFile= null; + try{ + IJavaElement[] javaElements= { cu1}; + IResource[] resources= {}; + String[] handles= ParticipantTesting.createHandles(new Object[] {cu1, cu1.getTypes()[0], cu1.getResource()}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= folder; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before", cu1.exists()); + String expectedSource= cu1.getSource(); + + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + + assertTrue("source file not moved", ! cu1.exists()); + + newFile= folder.getFile(cu1.getElementName()); + assertTrue("new file does not exist after", newFile.exists()); + + assertEqualLines("source compare failed", expectedSource, getContents(newFile)); + + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(destination, ref.getUpdateReferences()), + new MoveArguments(destination, ref.getUpdateReferences()), + new MoveArguments(folder, ref.getUpdateReferences())}); + }finally{ + performDummySearch(); + safeDelete(newFile); + safeDelete(folder); + } + } + + public void testDestination_yes_fileToSiblingFolder() throws Exception{ + ParticipantTesting.reset(); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IFile newFile= null; + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + String[] handles= ParticipantTesting.createHandles(new Object[] {file}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= folder; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before", file.exists()); + + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + + assertTrue("source file not moved", ! file.exists()); + + newFile= folder.getFile(file.getName()); + assertTrue("new file does not exist after", newFile.exists()); + + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(folder, ref.getUpdateReferences())}); + }finally{ + performDummySearch(); + safeDelete(newFile); + safeDelete(folder); + } + } + + public void testDestination_yes_fileToCu() throws Exception{ + ParticipantTesting.reset(); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + ICompilationUnit cu1= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + IFile newFile= null; + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + String[] handles= ParticipantTesting.createHandles(new Object[] {file}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= cu1; + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before", file.exists()); + + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + + assertTrue("source file not moved", ! file.exists()); + + newFile= ((IFolder)cu1.getParent().getResource()).getFile(file.getName()); + assertTrue("new file does not exist after", newFile.exists()); + + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(getPackageP().getResource(), ref.getUpdateReferences())}); + }finally{ + performDummySearch(); + safeDelete(newFile); + safeDelete(cu1); + } + } + + public void testDestination_yes_fileToPackage() throws Exception{ + ParticipantTesting.reset(); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + IFile newFile= null; + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + String[] handles= ParticipantTesting.createHandles(new Object[] {file}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getPackageP(); + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before", file.exists()); + + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + + assertTrue("source file not moved", ! file.exists()); + + newFile= ((IFolder)getPackageP().getResource()).getFile(file.getName()); + assertTrue("new file does not exist after", newFile.exists()); + + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(getPackageP().getResource(), ref.getUpdateReferences())}); + }finally{ + performDummySearch(); + safeDelete(newFile); + } + } + + public void testDestination_no_fileToMethod() throws Exception { + IFolder superFolder= (IFolder)getRoot().getResource(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + try{ + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= method; + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(file); + safeDelete(cu); + } + } + + public void testDestination_yes_fileToRoot() throws Exception{ + ParticipantTesting.reset(); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + IFile newFile= null; + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + String[] handles= ParticipantTesting.createHandles(new Object[] {file}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getRoot(); + verifyValidDestination(ref, destination); + + assertTrue("source file does not exist before", file.exists()); + + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + + assertTrue("source file not moved", ! file.exists()); + + newFile= ((IFolder)getRoot().getResource()).getFile(file.getName()); + assertTrue("new file does not exist after", newFile.exists()); + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(getRoot().getResource(), ref.getUpdateReferences())}); + }finally{ + performDummySearch(); + safeDelete(newFile); + } + } + + public void testDestination_no_fileToParentProject() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFile file= superFolder.getFile("a.txt"); + file.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= RefactoringTestSetup.getProject(); + verifyInvalidDestination(ref, destination); + }finally{ + performDummySearch(); + safeDelete(file); + } + } + + public void testDestination_yes_folderToSiblingFolder() throws Exception{ + ParticipantTesting.reset(); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IFolder otherFolder= superFolder.getFolder("otherfolder"); + otherFolder.create(true, true, null); + + IFolder newFolder= null; + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + String[] handles= ParticipantTesting.createHandles(new Object[] {folder}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= otherFolder; + verifyValidDestination(ref, destination); + + assertTrue("folder does not exist before", folder.exists()); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + assertTrue("folder not moved", ! folder.exists()); + newFolder= otherFolder.getFolder(folder.getName()); + assertTrue("new folder does not exist after", newFolder.exists()); + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(destination, ref.getUpdateReferences())}); + } finally{ + performDummySearch(); + safeDelete(newFolder); + safeDelete(otherFolder); + } + } + + public void testDestination_no_folderToParentProject() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= RefactoringTestSetup.getProject(); + verifyInvalidDestination(ref, destination); + } finally{ + performDummySearch(); + safeDelete(folder); + } + } + + public void testDestination_yes_folderToSiblingRoot() throws Exception{ + ParticipantTesting.reset(); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IPackageFragment newPackage= null; + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + String[] handles= ParticipantTesting.createHandles(new Object[] {folder}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getRoot(); + verifyValidDestination(ref, destination); + + assertTrue("folder does not exist before", folder.exists()); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + assertTrue("folder not moved", ! folder.exists()); + newPackage= getRoot().getPackageFragment(folder.getName()); + assertTrue("new folder does not exist after", newPackage.exists()); + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(getRoot().getResource(), ref.getUpdateReferences())}); + } finally{ + performDummySearch(); + safeDelete(newPackage); + } + } + + public void testDestination_yes_folderToPackage() throws Exception{ + ParticipantTesting.reset(); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IPackageFragment newPackage= null; + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + String[] handles= ParticipantTesting.createHandles(new Object[] {folder}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= getPackageP(); + verifyValidDestination(ref, destination); + + assertTrue("folder does not exist before", folder.exists()); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + assertTrue("folder not moved", ! folder.exists()); + newPackage= getRoot().getPackageFragment(getPackageP().getElementName() + "." + folder.getName()); + assertTrue("new package does not exist after", newPackage.exists()); + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(getPackageP().getResource(), ref.getUpdateReferences())}); + } finally{ + performDummySearch(); + safeDelete(newPackage); + } + } + + public void testDestination_yes_folderToFileInAnotherFolder() throws Exception{ + ParticipantTesting.reset(); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IFolder otherFolder= superFolder.getFolder("otherfolder"); + otherFolder.create(true, true, null); + IFile fileInAnotherFolder= otherFolder.getFile("f.tex"); + fileInAnotherFolder.create(getStream("123"), true, null); + + IFolder newFolder= null; + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + String[] handles= ParticipantTesting.createHandles(new Object[] {folder}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= fileInAnotherFolder; + verifyValidDestination(ref, destination); + + assertTrue("folder does not exist before", folder.exists()); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + assertTrue("folder not moved", ! folder.exists()); + newFolder= otherFolder.getFolder(folder.getName()); + assertTrue("new folder does not exist after", newFolder.exists()); + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(otherFolder, ref.getUpdateReferences())}); + } finally{ + performDummySearch(); +// folder.delete(true, new NullProgressMonitor()); + safeDelete(otherFolder); + } + } + + public void testDestination_yes_folderToCu() throws Exception{ + ParticipantTesting.reset(); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + ICompilationUnit cu= getPackageP().createCompilationUnit("A.java", "package p;class A{void foo(){}class Inner{}}", false, new NullProgressMonitor()); + + IPackageFragment newPackage= null; + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + String[] handles= ParticipantTesting.createHandles(new Object[] {folder}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= cu; + verifyValidDestination(ref, destination); + + assertTrue("folder does not exist before", folder.exists()); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + assertTrue("folder not moved", ! folder.exists()); + newPackage= getRoot().getPackageFragment(getPackageP().getElementName() + "." + folder.getName()); + assertTrue("new package does not exist after", newPackage.exists()); + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(cu.getParent().getResource(), ref.getUpdateReferences())}); + } finally{ + performDummySearch(); + safeDelete(newPackage); + safeDelete(cu); + } + } + + public void testDestination_yes_folderToSimpleProject() throws Exception{ + ParticipantTesting.reset(); + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("folder"); + folder.create(true, true, null); + + IProject simpleProject= ResourcesPlugin.getWorkspace().getRoot().getProject("mySImpleProject"); + simpleProject.create(null); + simpleProject.open(null); + + IFolder newFolder= null; + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {folder}; + String[] handles= ParticipantTesting.createHandles(new Object[] {folder}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= simpleProject; + verifyValidDestination(ref, destination); + + assertTrue("folder does not exist before", folder.exists()); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + assertTrue("folder not moved", ! folder.exists()); + newFolder= simpleProject.getFolder(folder.getName()); + assertTrue("new folder does not exist after", newFolder.exists()); + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(simpleProject, ref.getUpdateReferences())}); + } finally{ + performDummySearch(); + safeDelete(folder); + simpleProject.delete(true, true, new NullProgressMonitor()); + } + } + + public void testDestination_yes_sourceFolderToOtherProject() throws Exception{ + ParticipantTesting.reset(); + IJavaProject otherJavaProject= JavaProjectHelper.createJavaProject("other", "bin"); + + IPackageFragmentRoot oldRoot= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "newSrc"); + IPackageFragmentRoot newRoot= null; + try { + IJavaElement[] javaElements= { oldRoot }; + IResource[] resources= {}; + String[] handles= ParticipantTesting.createHandles(new Object[] {oldRoot, oldRoot.getResource()}); + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + + Object destination= otherJavaProject; + verifyValidDestination(ref, destination); + + assertTrue("folder does not exist before", oldRoot.exists()); + RefactoringStatus status= performRefactoring(ref, false); + assertEquals(null, status); + assertTrue("folder not moved", ! oldRoot.exists()); + newRoot= getSourceFolder(otherJavaProject, oldRoot.getElementName()); + assertTrue("new folder does not exist after", newRoot.exists()); + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(otherJavaProject, ref.getUpdateReferences()), + new MoveArguments(otherJavaProject.getResource(), ref.getUpdateReferences())}); + } finally { + performDummySearch(); + JavaProjectHelper.delete(otherJavaProject); + } + } + + public void testDestination_no_methodToItself() throws Exception{ + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + Object destination= method; + verifyInvalidDestination(ref, destination); + } finally { + performDummySearch(); + safeDelete(cu); + } + } + + public void testDestination_yes_methodToOtherType() throws Exception{ + ParticipantTesting.reset(); + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IMethod method= cu.getType("A").getMethod("foo", new String[0]); + IJavaElement[] javaElements= { method }; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + IType otherType= cu.getType("B"); + Object destination= otherType; + verifyValidDestination(ref, destination); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + + String expected= getFileContents(getOutputTestFileName(removeExtension(cu.getElementName()))); + assertEqualLines("source differs", expected, cu.getSource()); + ParticipantTesting.testMove(new String[] {},new MoveArguments[] {} ); + } finally { + performDummySearch(); + safeDelete(cu); + } + } + + public void testDestination_yes_fieldToOtherType() throws Exception{ + ParticipantTesting.reset(); + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IField field= cu.getType("A").getField("f"); + IJavaElement[] javaElements= { field }; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + IType otherType= cu.getType("B"); + Object destination= otherType; + verifyValidDestination(ref, destination); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + + String expected= getFileContents(getOutputTestFileName(removeExtension(cu.getElementName()))); + assertEqualLines("source differs", expected, cu.getSource()); + ParticipantTesting.testMove(new String[] {},new MoveArguments[] {} ); + } finally { + performDummySearch(); + safeDelete(cu); + } + } + + public void testDestination_yes_initializerToOtherType() throws Exception{ + ParticipantTesting.reset(); + ICompilationUnit cu= null; + try { + cu= createCUfromTestFile(getPackageP(), "A"); + IInitializer initializer= cu.getType("A").getInitializer(1); + IJavaElement[] javaElements= { initializer }; + IResource[] resources= {}; + JavaMoveProcessor ref= verifyEnabled(resources, javaElements, createReorgQueries()); + IType otherType= cu.getType("B"); + Object destination= otherType; + verifyValidDestination(ref, destination); + RefactoringStatus status= performRefactoring(ref, true); + assertEquals(null, status); + + String expected= getFileContents(getOutputTestFileName(removeExtension(cu.getElementName()))); + assertEqualLines("source differs", expected, cu.getSource()); + ParticipantTesting.testMove(new String[] {},new MoveArguments[] {} ); + } finally { + performDummySearch(); + safeDelete(cu); + } + } + + public void testDestination_bug79318() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder= superFolder.getFolder("bar"); + folder.create(true, true, null); + IFile file= folder.getFile("bar"); + file.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + + move(javaElements, resources, superFolder, null, IReorgDestination.LOCATION_ON, true, true); + + assertIsParent(folder, file); + assertIsParent(superFolder, folder); + }finally{ + performDummySearch(); + safeDelete(file); + } + } + + public void testDestination_bug196303() throws Exception{ + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder folder1= superFolder.getFolder("bar"); + folder1.create(true, true, null); + + IFolder folder= superFolder.getFolder("foo"); + folder.create(true, true, null); + IFile file= folder.getFile("bar"); + file.create(getStream("123"), true, null); + + try{ + IJavaElement[] javaElements= {}; + IResource[] resources= {file}; + + move(javaElements, resources, superFolder, null, IReorgDestination.LOCATION_ON, false, true); + + assertIsParent(folder, file); + assertIsParent(superFolder, folder); + }finally{ + performDummySearch(); + safeDelete(file); + } + } + + public void testDestination_fieldWithImport() throws Exception { + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + try { + IType typeA= cuA.getType("A"); + IJavaElement fieldF= typeA.getField("f"); + IJavaElement fieldG= typeA.getField("g"); + + move(new IJavaElement[] {fieldF} , new IResource[0], null, fieldG, IReorgDestination.LOCATION_AFTER, true, true); + + compareContents("A"); + } finally{ + delete(cuA); + } + } + + public void testDestination_fieldWithImport_back() throws Exception { + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + try { + IType typeA= cuA.getType("A"); + IJavaElement fieldF= typeA.getField("f"); + IJavaElement fieldG= typeA.getField("g"); + + move(new IJavaElement[] {fieldF} , new IResource[0], null, fieldG, IReorgDestination.LOCATION_BEFORE, true, true); + + compareContents("A"); + } finally{ + delete(cuA); + } + } + + public void testDestination_fieldWithImportMoveAcross() throws Exception { + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); + try { + IType typeA= cuA.getType("A"); + IJavaElement fieldF= typeA.getField("f"); + + IType typeB= cuB.getType("B"); + + move(new IJavaElement[] {fieldF} , new IResource[0], null, typeB, IReorgDestination.LOCATION_ON, true, true); + + compareContents("A"); + compareContents("B"); + } finally{ + delete(cuA); + } + } + + public void testDestination_bug31125() throws Exception { + IProject superFolder= RefactoringTestSetup.getProject().getProject(); + IFolder destination= superFolder.getFolder("folder"); + destination.create(true, true, null); + + IFile file= superFolder.getFile("archive.jar"); + file.create(getStream("123"), true, null); + + IPackageFragmentRoot source= JavaProjectHelper.addLibrary(RefactoringTestSetup.getProject(), file.getFullPath()); + + move(new IJavaElement[] {source} , new IResource[] {}, destination, null, IReorgDestination.LOCATION_ON, true, false); + + assertTrue(destination.findMember(file.getName()).exists()); + } + + private static void assertIsParent(IContainer parent, IResource child) { + assertTrue(child.getParent().equals(parent)); + } + + public void move(IJavaElement[] javaElements, IResource[] resources, IResource destination, IJavaElement javaDestination, int location, boolean confirmAll, boolean providesUndo) throws Exception { + assertNotNull(javaElements); + assertNotNull(resources); + assertTrue((destination != null || javaDestination != null) && (destination == null || javaDestination == null)); + + if (javaDestination != null) { + assertTrue(javaDestination.exists()); + } else { + assertTrue(destination.exists()); + } + for (int i= 0; i < resources.length; i++) { + assertTrue(resources[i].exists()); + } + + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(resources, javaElements); + assertTrue(policy.canEnable()); + + JavaMoveProcessor processor= new JavaMoveProcessor(policy); + if (javaDestination != null) { + assertTrue(processor.setDestination(ReorgDestinationFactory.createDestination(javaDestination, location)).isOK()); + } else { + RefactoringStatus status= processor.setDestination(ReorgDestinationFactory.createDestination(destination, location)); + assertTrue(status.getSeverity() <= RefactoringStatus.INFO); + } + + Refactoring ref= new MoveRefactoring(processor); + + processor.setCreateTargetQueries(new CreateTargetQueries(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell())); + if (confirmAll) { + processor.setReorgQueries(new ConfirmAllQuery()); + } else { + processor.setReorgQueries(new ConfirmNoneQuery()); + } + + performRefactoring(ref, providesUndo); + } + + private void delete(ICompilationUnit cu) throws Exception { + try { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } catch (JavaModelException e) { + e.printStackTrace(); + //ingore and keep going + } + } + + private void compareContents(String cuName) throws JavaModelException, IOException { + assertEqualLines(cuName, getFileContents(getOutputTestFileName(cuName)), getPackageP().getCompilationUnit(cuName + ".java").getSource()); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/MultiMoveTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/MultiMoveTest.java new file mode 100644 index 000000000..1df2dfdd1 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/MultiMoveTest.java @@ -0,0 +1,484 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.ccp; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; + +import org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.MoveArguments; +import org.eclipse.ltk.core.refactoring.participants.MoveRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.internal.corext.refactoring.reorg.JavaMoveProcessor; +import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgDestinationFactory; +import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory; +import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy; + +import org.eclipse.jdt.ui.tests.refactoring.ParticipantTesting; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSetup; + + +public class MultiMoveTest extends RefactoringTest { + + private static final Class clazz= MultiMoveTest.class; + private static final String REFACTORING_PATH= "MultiMove/"; + + public MultiMoveTest(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + protected void setUp() throws Exception { + super.setUp(); + fIsPreDeltaTest= true; + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + //--- + private IPackageFragment createPackage(String name) throws Exception{ + return getRoot().createPackageFragment(name, true, null); + } + + private ICompilationUnit createCu(IPackageFragment pack, String cuPath, String cuName) throws Exception{ + return createCU(pack, cuName, getFileContents(getRefactoringPath() + cuPath)); + } + + private void delete(IPackageFragment pack) throws Exception { + performDummySearch(); + try { + if (pack != null && pack.exists()) + pack.delete(true, null); + } catch(JavaModelException e) { + //ignore, we should keep going + e.printStackTrace(); + } + } + + private void delete(IPackageFragmentRoot root) throws Exception { + performDummySearch(); + try { + if (root != null && root.exists()) + root.delete(IResource.FORCE, IPackageFragmentRoot.ORIGINATING_PROJECT_CLASSPATH, null); + } catch(JavaModelException e) { + //ignore, we should keep going + e.printStackTrace(); + } + } + + //-------- + public void test0() throws Exception{ + ParticipantTesting.reset(); + IPackageFragment packP1= null; + IPackageFragment packP2= null; + try { + final String p1Name= "p1"; + final String inDir= "/in/"; + final String outDir= "/out/"; + + packP1= createPackage(p1Name); + ICompilationUnit p1A= createCu(packP1, getName() + inDir + p1Name + "/A.java", "A.java"); + ICompilationUnit p1B= createCu(packP1, getName() + inDir + p1Name + "/B.java", "B.java"); + + String p2Name= "p2"; + packP2= createPackage(p2Name); + ICompilationUnit p2C= createCu(packP2, getName() + inDir + p2Name + "/C.java", "C.java"); + + String[] handles= ParticipantTesting.createHandles(new Object[] { + p1A, p1A.getTypes()[0], + p1B, p1B.getTypes()[0], + p1A.getResource(), p1B.getResource()}); + + IResource[] resources= {}; + IJavaElement[] javaElements= {p1A, p1B}; + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(resources, javaElements); + JavaMoveProcessor processor= (policy.canEnable() ? new JavaMoveProcessor(policy) : null); + processor.setReorgQueries(new MockReorgQueries()); + processor.setDestination(ReorgDestinationFactory.createDestination(packP2)); + processor.setUpdateReferences(true); + performDummySearch(); + RefactoringStatus status= performRefactoring(processor, true); + + //-- checks + assertEquals("status should be ok here", null, status); + + assertEquals("p1 files", 0, packP1.getChildren().length); + assertEquals("p2 files", 3, packP2.getChildren().length); + + String expectedSource= getFileContents(getRefactoringPath() + getName() + outDir + p2Name + "/A.java"); + assertEqualLines("incorrect update of A", expectedSource, packP2.getCompilationUnit("A.java").getSource()); + + expectedSource= getFileContents(getRefactoringPath() + getName() + outDir + p2Name + "/B.java"); + assertEqualLines("incorrect update of B", expectedSource, packP2.getCompilationUnit("B.java").getSource()); + + expectedSource= getFileContents(getRefactoringPath() + getName() + outDir + p2Name + "/C.java"); + assertEqualLines("incorrect update of C", expectedSource, p2C.getSource()); + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(packP2, processor.getUpdateReferences()), + new MoveArguments(packP2, processor.getUpdateReferences()), + new MoveArguments(packP2, processor.getUpdateReferences()), + new MoveArguments(packP2, processor.getUpdateReferences()), + new MoveArguments(packP2.getResource(), processor.getUpdateReferences()), + new MoveArguments(packP2.getResource(), processor.getUpdateReferences()) + }); + + } finally { + delete(packP1); + delete(packP2); + } + } + + + public void test1() throws Exception{ + ParticipantTesting.reset(); + IPackageFragment packP1= null; + IPackageFragment packP2= null; + try { + final String p1Name= "p1"; + final String inDir= "/in/"; + final String outDir= "/out/"; + + packP1= createPackage(p1Name); + ICompilationUnit p1A= createCu(packP1, getName() + inDir + p1Name + "/A.java", "A.java"); + ICompilationUnit p1B= createCu(packP1, getName() + inDir + p1Name + "/B.java", "B.java"); + + String p2Name= "p2"; + packP2= createPackage(p2Name); + ICompilationUnit p2C= createCu(packP2, getName() + inDir + p2Name + "/C.java", "C.java"); + + String[] handles= ParticipantTesting.createHandles(new Object[] { + p1A, p1A.getTypes()[0], + p1B, p1B.getTypes()[0], + p1A.getResource(), p1B.getResource()}); + + IResource[] resources= {}; + IJavaElement[] javaElements= {p1A, p1B}; + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(resources, javaElements); + JavaMoveProcessor processor= (policy.canEnable() ? new JavaMoveProcessor(policy) : null); + processor.setReorgQueries(new MockReorgQueries()); + processor.setDestination(ReorgDestinationFactory.createDestination(packP2)); + processor.setUpdateReferences(true); + performDummySearch(); + RefactoringStatus status= performRefactoring(processor, true); + + //-- checks + assertEquals("status should be ok here", null, status); + + assertEquals("p1 files", 0, packP1.getChildren().length); + assertEquals("p2 files", 3, packP2.getChildren().length); + + String expectedSource= getFileContents(getRefactoringPath() + getName() + outDir + p2Name + "/A.java"); + assertEqualLines("incorrect update of A", expectedSource, packP2.getCompilationUnit("A.java").getSource()); + + expectedSource= getFileContents(getRefactoringPath() + getName() + outDir + p2Name + "/B.java"); + assertEqualLines("incorrect update of B", expectedSource, packP2.getCompilationUnit("B.java").getSource()); + + expectedSource= getFileContents(getRefactoringPath() + getName() + outDir + p2Name + "/C.java"); + assertEqualLines("incorrect update of C", expectedSource, p2C.getSource()); + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(packP2, processor.getUpdateReferences()), + new MoveArguments(packP2, processor.getUpdateReferences()), + new MoveArguments(packP2, processor.getUpdateReferences()), + new MoveArguments(packP2, processor.getUpdateReferences()), + new MoveArguments(packP2.getResource(), processor.getUpdateReferences()), + new MoveArguments(packP2.getResource(), processor.getUpdateReferences()) + }); + } finally { + delete(packP1); + delete(packP2); + } + } + + public void test2() throws Exception{ + ParticipantTesting.reset(); + IPackageFragment packP1= null; + IPackageFragment packP2= null; + try { + final String p1Name= "p1"; + final String inDir= "/in/"; + final String outDir= "/out/"; + + packP1= createPackage(p1Name); + ICompilationUnit p1A= createCu(packP1, getName() + inDir + p1Name + "/A.java", "A.java"); + createCu(packP1, getName() + inDir + p1Name + "/B.java", "B.java"); + + String p2Name= "p2"; + packP2= createPackage(p2Name); + ICompilationUnit p2C= createCu(packP2, getName() + inDir + p2Name + "/C.java", "C.java"); + + String[] handles= ParticipantTesting.createHandles(new Object[] { + p1A, p1A.getTypes()[0], + p1A.getResource()}); + + IResource[] resources= {}; + IJavaElement[] javaElements= {p1A}; + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(resources, javaElements); + JavaMoveProcessor processor= (policy.canEnable() ? new JavaMoveProcessor(policy) : null); + processor.setReorgQueries(new MockReorgQueries()); + processor.setDestination(ReorgDestinationFactory.createDestination(packP2)); + processor.setUpdateReferences(true); + performDummySearch(); + RefactoringStatus status= performRefactoring(processor, true); + + //-- checks + assertEquals("status should be ok here", null, status); + + assertEquals("p1 files", 1, packP1.getChildren().length); + assertEquals("p2 files", 2, packP2.getChildren().length); + + String expectedSource= getFileContents(getRefactoringPath() + getName() + outDir + p2Name + "/A.java"); + assertEqualLines("incorrect update of A", expectedSource, packP2.getCompilationUnit("A.java").getSource()); + + expectedSource= getFileContents(getRefactoringPath() + getName() + outDir + p1Name + "/B.java"); + assertEqualLines("incorrect update of B", expectedSource, packP1.getCompilationUnit("B.java").getSource()); + + expectedSource= getFileContents(getRefactoringPath() + getName() + outDir + p2Name + "/C.java"); + assertEqualLines("incorrect update of C", expectedSource, p2C.getSource()); + + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(packP2, processor.getUpdateReferences()), + new MoveArguments(packP2, processor.getUpdateReferences()), + new MoveArguments(packP2.getResource(), processor.getUpdateReferences()), + }); + } finally { + delete(packP1); + delete(packP2); + } + } + + public void test3() throws Exception{ + ParticipantTesting.reset(); + IPackageFragment packP1= null; + IPackageFragment packP3= null; + IPackageFragment packP2= null; + try { + final String p1Name= "p1"; + final String p3Name= "p3"; + final String inDir= "/in/"; + final String outDir= "/out/"; + + packP1= createPackage(p1Name); + packP3= createPackage(p3Name); + ICompilationUnit p1A= createCu(packP1, getName() + inDir + p1Name + "/Outer.java", "Outer.java"); + createCu(packP3, getName() + inDir + p3Name + "/Test.java", "Test.java"); + + String p2Name= "p2"; + packP2= createPackage(p2Name); + + String[] handles= ParticipantTesting.createHandles(new Object[] { + p1A, p1A.getTypes()[0], + p1A.getResource()}); + + IResource[] resources= {}; + IJavaElement[] javaElements= {p1A}; + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(resources, javaElements); + JavaMoveProcessor processor= (policy.canEnable() ? new JavaMoveProcessor(policy) : null); + processor.setReorgQueries(new MockReorgQueries()); + processor.setDestination(ReorgDestinationFactory.createDestination(packP2)); + processor.setUpdateReferences(true); + performDummySearch(); + RefactoringStatus status= performRefactoring(processor, true); + + //-- checks + assertEquals("status should be ok here", null, status); + + assertEquals("p1 files", 0, packP1.getChildren().length); + assertEquals("p2 files", 1, packP2.getChildren().length); + assertEquals("p1 files", 1, packP3.getChildren().length); + + String expectedSource= getFileContents(getRefactoringPath() + getName() + outDir + p2Name + "/Outer.java"); + assertEqualLines("incorrect update of Outer", expectedSource, packP2.getCompilationUnit("Outer.java").getSource()); + + expectedSource= getFileContents(getRefactoringPath() + getName() + outDir + p3Name + "/Test.java"); + assertEqualLines("incorrect update of Test", expectedSource, packP3.getCompilationUnit("Test.java").getSource()); + ParticipantTesting.testMove( + handles, + new MoveArguments[] { + new MoveArguments(packP2, processor.getUpdateReferences()), + new MoveArguments(packP2, processor.getUpdateReferences()), + new MoveArguments(packP2.getResource(), processor.getUpdateReferences()), + }); + + } finally { + delete(packP1); + delete(packP2); + delete(packP3); + } + } + + public void testPackageMoveParticipants() throws Exception { + ParticipantTesting.reset(); + IPackageFragmentRoot r1= null; + IPackageFragmentRoot r2= null; + try { + r1= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "src1"); + r2= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "src2"); + IPackageFragment p1= r1.createPackageFragment("p1", true, null); + p1.createCompilationUnit("A.java", "public class A {}", true, null); + p1.createCompilationUnit("B.java", "public class B {}", true, null); + + String[] moveHandes= ParticipantTesting.createHandles(new Object[] {p1, p1.getResource()}); + + IResource[] resources= {}; + IJavaElement[] javaElements= {p1}; + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(resources, javaElements); + JavaMoveProcessor processor= (policy.canEnable() ? new JavaMoveProcessor(policy) : null); + processor.setReorgQueries(new MockReorgQueries()); + processor.setDestination(ReorgDestinationFactory.createDestination(r2)); + performDummySearch(); + RefactoringStatus status= performRefactoring(processor, false); + + //-- checks + assertEquals("status should be ok here", null, status); + + ParticipantTesting.testMove( + moveHandes, + new MoveArguments[] { + new MoveArguments(r2, processor.getUpdateReferences()), + new MoveArguments(r2.getResource(), processor.getUpdateReferences()), + }); + } finally { + delete(r1); + delete(r2); + } + } + + public void testPackageMoveParticipants2() throws Exception { + fIsPreDeltaTest= false; + ParticipantTesting.reset(); + IPackageFragmentRoot r1= null; + IPackageFragmentRoot r2= null; + try { + r1= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "src1"); + r2= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "src2"); + IPackageFragment p1= r1.createPackageFragment("p1", true, null); + r1.createPackageFragment("p1.p2", true, null); + ICompilationUnit c1= p1.createCompilationUnit("A.java", "public class A {}", true, null); + IFile file= ((IContainer)p1.getResource()).getFile(new Path("Z.txt")); + file.create(getStream("123"), true, null); + + String[] moveHandles= ParticipantTesting.createHandles(new Object[] { + p1, c1.getResource(), file }); + + IResource[] resources= {}; + IJavaElement[] javaElements= {p1}; + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(resources, javaElements); + JavaMoveProcessor processor= (policy.canEnable() ? new JavaMoveProcessor(policy) : null); + processor.setReorgQueries(new MockReorgQueries()); + processor.setDestination(ReorgDestinationFactory.createDestination(r2)); + performDummySearch(); + RefactoringStatus status= performRefactoring(processor, false); + + //-- checks + assertEquals("status should be ok here", null, status); + + IPath path= r2.getResource().getFullPath(); + path= path.append(p1.getElementName().replace('.', '/')); + IFolder target= ResourcesPlugin.getWorkspace().getRoot().getFolder(path); + String[] createHandles= ParticipantTesting.createHandles(new Object[] {target}); + + ParticipantTesting.testCreate(createHandles); + + ParticipantTesting.testMove( + moveHandles, + new MoveArguments[] { + new MoveArguments(r2, processor.getUpdateReferences()), + new MoveArguments(target, processor.getUpdateReferences()), + new MoveArguments(target, processor.getUpdateReferences()), + }); + } finally { + delete(r1); + delete(r2); + } + } + + public void testPackageMoveParticipants3() throws Exception { + ParticipantTesting.reset(); + IPackageFragmentRoot r1= null; + IPackageFragmentRoot r2= null; + try { + r1= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "src1"); + r2= JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(), "src2"); + IPackageFragment p1= r1.createPackageFragment("p1", true, null); + r2.createPackageFragment("p1", true, null); + ICompilationUnit c1= p1.createCompilationUnit("A.java", "public class A {}", true, null); + + String[] moveHandles= ParticipantTesting.createHandles(new Object[] { + p1, c1.getResource()}); + String[] deleteHandles= ParticipantTesting.createHandles(new Object[] {p1.getResource()}); + + IResource[] resources= {}; + IJavaElement[] javaElements= {p1}; + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy(resources, javaElements); + JavaMoveProcessor processor= (policy.canEnable() ? new JavaMoveProcessor(policy) : null); + processor.setReorgQueries(new MockReorgQueries()); + processor.setDestination(ReorgDestinationFactory.createDestination(r2)); + performDummySearch(); + RefactoringStatus status= performRefactoring(processor, false); + + //-- checks + assertEquals("status should be ok here", null, status); + + IPath path= r2.getResource().getFullPath(); + path= path.append(p1.getElementName().replace('.', '/')); + IFolder target= ResourcesPlugin.getWorkspace().getRoot().getFolder(path); + + ParticipantTesting.testDelete(deleteHandles); + + ParticipantTesting.testMove( + moveHandles, + new MoveArguments[] { + new MoveArguments(r2, processor.getUpdateReferences()), + new MoveArguments(target, processor.getUpdateReferences()), + }); + } finally { + delete(r1); + delete(r2); + } + } + + private RefactoringStatus performRefactoring(JavaMoveProcessor processor, boolean providesUndo) throws Exception { + return performRefactoring(new MoveRefactoring(processor), providesUndo); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/PasteActionTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/PasteActionTest.java new file mode 100644 index 000000000..55758ff49 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/PasteActionTest.java @@ -0,0 +1,453 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.ccp; + +import java.io.IOException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.swt.SWTError; +import org.eclipse.swt.dnd.Clipboard; +import org.eclipse.swt.dnd.DND; +import org.eclipse.swt.dnd.Transfer; +import org.eclipse.swt.widgets.Display; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IResource; + +import org.eclipse.jface.viewers.IStructuredSelection; + +import org.eclipse.ui.IWorkingSet; +import org.eclipse.ui.PlatformUI; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IImportContainer; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.internal.corext.refactoring.TypedSource; + +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSetup; +import org.eclipse.jdt.ui.tests.refactoring.infra.MockClipboard; +import org.eclipse.jdt.ui.tests.refactoring.infra.MockWorkbenchSite; + +import org.eclipse.jdt.internal.ui.refactoring.reorg.CopyToClipboardAction; +import org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction; +import org.eclipse.jdt.internal.ui.refactoring.reorg.TypedSourceTransfer; + + +public class PasteActionTest extends RefactoringTest{ + + private Clipboard fClipboard; + private static final Class clazz= PasteActionTest.class; + private static final String REFACTORING_PATH= "Paste/"; + + public PasteActionTest(String name) { + super(name); + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + protected void setUp() throws Exception { + super.setUp(); + fClipboard= new MockClipboard(Display.getDefault()); + } + protected void tearDown() throws Exception { + super.tearDown(); + fClipboard.dispose(); + } + + private static Object[] merge(Object[] array1, Object[] array2) { + Set elements= new HashSet(array1.length + array2.length); + elements.addAll(Arrays.asList(array1)); + elements.addAll(Arrays.asList(array2)); + return elements.toArray(); + } + + private PasteAction verifyEnabled(IResource[] copySelectedResources, IJavaElement[] copySelectedJavaElements, IResource[] pasteSelectedResources, IJavaElement[] pasteSelectedJavaElements) throws JavaModelException { + PasteAction pasteAction= new PasteAction(new MockWorkbenchSite(merge(pasteSelectedResources, pasteSelectedJavaElements)), fClipboard); + CopyToClipboardAction copyToClipboardAction= new CopyToClipboardAction(new MockWorkbenchSite(merge(copySelectedResources, copySelectedJavaElements)), fClipboard); + copyToClipboardAction.setAutoRepeatOnFailure(true); + copyToClipboardAction.update(copyToClipboardAction.getSelection()); + assertTrue("copy not enabled", copyToClipboardAction.isEnabled()); + copyToClipboardAction.run(); + + pasteAction.update(pasteAction.getSelection()); + assertTrue("paste should be enabled", pasteAction.isEnabled()); + return pasteAction; + } + + private PasteAction verifyEnabled(IResource[] copySelectedResources, IJavaElement[] copySelectedJavaElements, IWorkingSet pasteSelectedWorkingSet) throws JavaModelException { + PasteAction pasteAction= new PasteAction(new MockWorkbenchSite(new Object[] {pasteSelectedWorkingSet}), fClipboard); + CopyToClipboardAction copyToClipboardAction= new CopyToClipboardAction(new MockWorkbenchSite(merge(copySelectedResources, copySelectedJavaElements)), fClipboard); + copyToClipboardAction.setAutoRepeatOnFailure(true); + copyToClipboardAction.update(copyToClipboardAction.getSelection()); + assertTrue("copy not enabled", copyToClipboardAction.isEnabled()); + copyToClipboardAction.run(); + + pasteAction.update(pasteAction.getSelection()); + assertTrue("paste should be enabled", pasteAction.isEnabled()); + return pasteAction; + } + + public void testEnabled_javaProject() throws Exception { + IJavaElement[] javaElements= {RefactoringTestSetup.getProject()}; + IResource[] resources= {}; + verifyEnabled(resources, javaElements, new IResource[0], new IJavaElement[0]); + } + + public void testEnabled_project() throws Exception { + IJavaElement[] javaElements= {}; + IResource[] resources= {RefactoringTestSetup.getProject().getProject()}; + verifyEnabled(resources, javaElements, new IResource[0], new IJavaElement[0]); + } + + public void testEnabled_workingSet() throws Exception { + IWorkingSet ws= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSet("Test", new IAdaptable[] {}); + try { + verifyEnabled(new IResource[0], new IJavaElement[] {RefactoringTestSetup.getProject()}, ws); + } finally { + PlatformUI.getWorkbench().getWorkingSetManager().removeWorkingSet(ws); + } + } + + private void compareContents(String cuName) throws JavaModelException, IOException { + assertEqualLines(cuName, getFileContents(getOutputTestFileName(cuName)), getPackageP().getCompilationUnit(cuName + ".java").getSource()); + } + + private void delete(ICompilationUnit cu) throws Exception { + try { + performDummySearch(); + cu.delete(true, new NullProgressMonitor()); + } catch (JavaModelException e) { + e.printStackTrace(); + //ingore and keep going + } + } + + public void test0() throws Exception{ + if (true) { + printTestDisabledMessage("not implemented yet"); + return; + } + + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); + + try { + IType typeA= cuA.getType("A"); + IType typeB= cuB.getType("B"); + + assertTrue("A does not exist", typeA.exists()); + assertTrue("B does not exist", typeB.exists()); + + IJavaElement[] copyJavaElements= {typeA}; + IResource[] copyResources= {}; + IJavaElement[] pasteJavaElements= {typeB}; + IResource[] pasteResources= {}; + PasteAction paste= verifyEnabled(copyResources, copyJavaElements, pasteResources, pasteJavaElements); + paste.run((IStructuredSelection)paste.getSelection()); + compareContents("A"); + compareContents("B"); + } finally{ + delete(cuA); + delete(cuB); + } + } + + public void test2() throws Exception{ + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); + + try { + IField fieldY= cuA.getType("A").getField("y"); + IType typeB= cuB.getType("B"); + + assertTrue("y does not exist", fieldY.exists()); + assertTrue("B does not exist", typeB.exists()); + + IJavaElement[] copyJavaElements= {fieldY}; + IResource[] copyResources= {}; + IJavaElement[] pasteJavaElements= {typeB}; + IResource[] pasteResources= {}; + PasteAction paste= verifyEnabled(copyResources, copyJavaElements, pasteResources, pasteJavaElements); + paste.run((IStructuredSelection)paste.getSelection()); + compareContents("A"); + compareContents("B"); + } finally{ + delete(cuA); + delete(cuB); + } + } + + public void test3() throws Exception{ +// printTestDisabledMessage("test for bug#19007"); + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + ICompilationUnit cuB= createCUfromTestFile(getPackageP(), "B"); + + try { + IJavaElement elem0= cuA.getImport("java.lang.*"); + IImportContainer importContainer= cuB.getImportContainer(); + + assertTrue("y does not exist", elem0.exists()); + assertTrue("B does not exist", importContainer.exists()); + + IJavaElement[] copyJavaElements= {elem0}; + IResource[] copyResources= {}; + IJavaElement[] pasteJavaElements= {importContainer}; + IResource[] pasteResources= {}; + PasteAction paste= verifyEnabled(copyResources, copyJavaElements, pasteResources, pasteJavaElements); + paste.run((IStructuredSelection)paste.getSelection()); + compareContents("A"); + compareContents("B"); + } finally{ + delete(cuA); + delete(cuB); + } + } + + public void test4() throws Exception{ +// printTestDisabledMessage("test for bug 20151"); + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + try { + IJavaElement elem0= cuA.getType("A").getMethod("f", new String[0]); + IMethod method= cuA.getType("A").getMethod("f1", new String[0]); + + assertTrue("y does not exist", elem0.exists()); + assertTrue("B does not exist", method.exists()); + + IJavaElement[] copyJavaElements= {elem0}; + IResource[] copyResources= {}; + IJavaElement[] pasteJavaElements= {method}; + IResource[] pasteResources= {}; + PasteAction paste= verifyEnabled(copyResources, copyJavaElements, pasteResources, pasteJavaElements); + paste.run((IStructuredSelection)paste.getSelection()); + compareContents("A"); + } finally{ + delete(cuA); + } + } + + public void testPastingJavaElementIntoWorkingSet() throws Exception { + IWorkingSet ws= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSet("Test", new IAdaptable[] {}); + try { + IResource[] resources= {}; + IJavaElement[] jElements= {RefactoringTestSetup.getProject()}; + PasteAction paste= verifyEnabled(resources , jElements, ws); + paste.run((IStructuredSelection)paste.getSelection()); + assertEquals("Only one element", 1, ws.getElements().length); + assertEquals(RefactoringTestSetup.getProject(), ws.getElements()[0]); + } finally { + PlatformUI.getWorkbench().getWorkingSetManager().removeWorkingSet(ws); + } + } + + public void testPastingResourceIntoWorkingSet() throws Exception { + IWorkingSet ws= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSet("Test", new IAdaptable[] {}); + IFolder folder= RefactoringTestSetup.getProject().getProject().getFolder("folder"); + folder.create(true, true, null); + try { + IResource[] resources= {folder}; + IJavaElement[] jElements= {}; + PasteAction paste= verifyEnabled(resources , jElements, ws); + paste.run((IStructuredSelection)paste.getSelection()); + assertEquals("Only one element", 1, ws.getElements().length); + assertEquals(folder, ws.getElements()[0]); + } finally { + performDummySearch(); + PlatformUI.getWorkbench().getWorkingSetManager().removeWorkingSet(ws); + folder.delete(true, false, null); + } + } + + public void testPastingJavaElementAsResourceIntoWorkingSet() throws Exception { + IWorkingSet ws= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSet("Test", new IAdaptable[] {}); + try { + IResource[] resources= {RefactoringTestSetup.getProject().getProject()}; + IJavaElement[] jElements= {}; + PasteAction paste= verifyEnabled(resources , jElements, ws); + paste.run((IStructuredSelection)paste.getSelection()); + assertEquals("Only one element", 1, ws.getElements().length); + assertEquals(RefactoringTestSetup.getProject(), ws.getElements()[0]); + } finally { + PlatformUI.getWorkbench().getWorkingSetManager().removeWorkingSet(ws); + } + } + + public void testPastingExistingElementIntoWorkingSet() throws Exception { + IWorkingSet ws= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSet("Test", + new IAdaptable[] {RefactoringTestSetup.getProject()}); + try { + IResource[] resources= {}; + IJavaElement[] jElements= {RefactoringTestSetup.getProject()}; + PasteAction paste= verifyEnabled(resources , jElements, ws); + paste.run((IStructuredSelection)paste.getSelection()); + assertEquals("Only one element", 1, ws.getElements().length); + assertEquals(RefactoringTestSetup.getProject(), ws.getElements()[0]); + } finally { + PlatformUI.getWorkbench().getWorkingSetManager().removeWorkingSet(ws); + } + } + + public void testPastingChildJavaElementIntoWorkingSet() throws Exception { + IWorkingSet ws= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSet("Test", + new IAdaptable[] {RefactoringTestSetup.getProject()}); + try { + IResource[] resources= {}; + IJavaElement[] jElements= {getPackageP()}; + PasteAction paste= verifyEnabled(resources , jElements, ws); + paste.run((IStructuredSelection)paste.getSelection()); + assertEquals("Only one element", 1, ws.getElements().length); + assertEquals(RefactoringTestSetup.getProject(), ws.getElements()[0]); + } finally { + PlatformUI.getWorkbench().getWorkingSetManager().removeWorkingSet(ws); + } + } + + public void testPastingChildResourceIntoWorkingSet() throws Exception { + IFolder folder= RefactoringTestSetup.getProject().getProject().getFolder("folder"); + folder.create(true, true, null); + IWorkingSet ws= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSet("Test", + new IAdaptable[] {folder}); + IFolder sub= folder.getFolder("sub"); + sub.create(true, true, null); + try { + IResource[] resources= {sub}; + IJavaElement[] jElements= {}; + PasteAction paste= verifyEnabled(resources , jElements, ws); + paste.run((IStructuredSelection)paste.getSelection()); + assertEquals("Only one element", 1, ws.getElements().length); + assertEquals(folder, ws.getElements()[0]); + } finally { + performDummySearch(); + folder.delete(true, false, null); + sub.delete(true, false, null); + PlatformUI.getWorkbench().getWorkingSetManager().removeWorkingSet(ws); + } + } + + public void testPastingChildResourceIntoWorkingSetContainingParent() throws Exception { + IWorkingSet ws= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSet("Test", + new IAdaptable[] {RefactoringTestSetup.getProject()}); + IFolder folder= RefactoringTestSetup.getProject().getProject().getFolder("folder"); + folder.create(true, true, null); + try { + IResource[] resources= {folder}; + IJavaElement[] jElements= {}; + PasteAction paste= verifyEnabled(resources , jElements, ws); + paste.run((IStructuredSelection)paste.getSelection()); + assertEquals("Only one element", 1, ws.getElements().length); + assertEquals(RefactoringTestSetup.getProject(), ws.getElements()[0]); + } finally { + performDummySearch(); + folder.delete(true, false, null); + PlatformUI.getWorkbench().getWorkingSetManager().removeWorkingSet(ws); + } + } + + private void setClipboardContents(TypedSource[] typedSources, int repeat) { + final int maxRepeat= 10; + try { + fClipboard.setContents(new Object[] {typedSources}, new Transfer[] {TypedSourceTransfer.getInstance()}); + } catch (SWTError e) { + if (e.code != DND.ERROR_CANNOT_SET_CLIPBOARD || repeat >= maxRepeat) + throw e; + setClipboardContents(typedSources, repeat+1); + } + } + + private void copyAndPasteTypedSources(IJavaElement[] elemsForClipboard, IJavaElement[] pasteSelectedJavaElements, boolean pasteEnabled) throws CoreException { + setClipboardContents(TypedSource.createTypedSources(elemsForClipboard), 0); + PasteAction pasteAction= new PasteAction(new MockWorkbenchSite(pasteSelectedJavaElements), fClipboard); + pasteAction.update(pasteAction.getSelection()); + assertEquals("action enablement", pasteEnabled, pasteAction.isEnabled()); + if (pasteEnabled) + pasteAction.run((IStructuredSelection)pasteAction.getSelection()); + } + + public void testPastingTypedResources0() throws Exception { + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + try { + IJavaElement methodM= cuA.getType("A").getMethod("m", new String[0]); + IJavaElement[] elemsForClipboard= {methodM}; + IJavaElement[] pasteSelectedJavaElements= {methodM}; + boolean enabled= true; + copyAndPasteTypedSources(elemsForClipboard, pasteSelectedJavaElements, enabled); + compareContents("A"); + } finally{ + delete(cuA); + } + } + + public void testPastingTypedResources1() throws Exception { + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + try { + IType typeA= cuA.getType("A"); + IJavaElement fieldF= typeA.getField("f"); + IJavaElement[] elemsForClipboard= {fieldF}; + IJavaElement[] pasteSelectedJavaElements= {typeA}; + boolean enabled= true; + copyAndPasteTypedSources(elemsForClipboard, pasteSelectedJavaElements, enabled); + compareContents("A"); + } finally{ + delete(cuA); + } + } + + public void testPastingTypedResources2() throws Exception { + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + try { + IType typeA= cuA.getType("A"); + IJavaElement fieldF= typeA.getField("f"); + IJavaElement[] elemsForClipboard= {fieldF}; + IJavaElement[] pasteSelectedJavaElements= {typeA}; + boolean enabled= true; + copyAndPasteTypedSources(elemsForClipboard, pasteSelectedJavaElements, enabled); + compareContents("A"); + } finally{ + delete(cuA); + } + } + + public void testPastingTypedResources3() throws Exception { + ICompilationUnit cuA= createCUfromTestFile(getPackageP(), "A"); + try { + IType typeA= cuA.getType("A"); + IJavaElement fieldF= typeA.getField("f"); + IJavaElement fieldG= typeA.getField("g"); + IJavaElement[] elemsForClipboard= {fieldF, fieldG}; + IJavaElement[] pasteSelectedJavaElements= {typeA}; + boolean enabled= true; + copyAndPasteTypedSources(elemsForClipboard, pasteSelectedJavaElements, enabled); + compareContents("A"); + } finally{ + delete(cuA); + } + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/AllTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/AllTests.java new file mode 100644 index 000000000..116d1f114 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/AllTests.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.changes; + + +import junit.framework.Test; +import junit.framework.TestSuite; + + +public class AllTests { + + public static Test suite ( ) { + TestSuite suite= new TestSuite("All Change Tests"); + suite.addTest(TrackPositionTest.suite()); + suite.addTest(TextDiffContentTest.suite()); + return suite; + } +} + + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TextDiffContentTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TextDiffContentTest.java new file mode 100644 index 000000000..5fce433c2 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TextDiffContentTest.java @@ -0,0 +1,193 @@ +/******************************************************************************* + * Copyright (c) 2006, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Ed Swartz <ed.swartz@nokia.com> - initial API and implementation + * (bug 157203: [ltk] [patch] TextEditBasedChange/TextChange provides incorrect diff when one side is empty) + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.changes; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.text.edits.MultiTextEdit; +import org.eclipse.text.edits.ReplaceEdit; +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IRegion; + +import org.eclipse.ltk.core.refactoring.DocumentChange; +import org.eclipse.ltk.core.refactoring.TextEditChangeGroup; + +/** + * Ensure that the diffs between text edits do not include + * spurious context lines when source or target regions are + * empty. Otherwise, the current content and preview content + * have differing affected ranges and spurious changes appear. + */ +public class TextDiffContentTest extends TestCase { + + private static final String MODIFIED_SOURCE_CONTENTS = + "// my file\n"+ + "\n"+ + "CMyClass::CMyClass()\n"+ + "\t{\n"+ + "\tGoodCall();\n"+ + "\tDumbCall();\n"+ + "\t// [[[ begin\n"+ + "\tMagicCall();\n"+ + "\t// ]]] end\n"+ + "\t}\n"+ + "\n"+ + "// other stuff\n"; + + public static Test suite() { + return new TestSuite(TextDiffContentTest.class); + } + + private DocumentChange fDocumentChange; + + private Document fDocument; + + private ReplaceEdit fEdit1; + + private ReplaceEdit fEdit2; + + private TextEditChangeGroup fChange1; + + private TextEditChangeGroup fChange2; + + private ReplaceEdit fEdit3; + + private TextEditChangeGroup fChange3; + + protected void setUp() throws Exception { + super.setUp(); + fDocument = new Document(MODIFIED_SOURCE_CONTENTS); + fDocumentChange = new DocumentChange("Changes to document", fDocument); + + // store one unified change for the document + MultiTextEdit multiEdit = new MultiTextEdit(); + fDocumentChange.setEdit(multiEdit); + + int offset; + TextEditGroup group; + ///// + + offset = MODIFIED_SOURCE_CONTENTS.indexOf("\t}\n"); + fEdit1 = new ReplaceEdit( + offset, 0, + "\tFinalCall();\n"); + + group = new TextEditGroup("Change 1"); + group.addTextEdit(fEdit1); + fChange1 = new TextEditChangeGroup(fDocumentChange, group); + fDocumentChange.addTextEditChangeGroup(fChange1); + multiEdit.addChild(fEdit1); + + ///// + offset = 0; + fEdit2 = new ReplaceEdit( + offset, 0, + "// add comment\n"); + + group = new TextEditGroup("Change 2"); + group.addTextEdit(fEdit2); + fChange2 = new TextEditChangeGroup(fDocumentChange, group); + fDocumentChange.addTextEditChangeGroup(fChange2); + multiEdit.addChild(fEdit2); + + /// + offset = MODIFIED_SOURCE_CONTENTS.indexOf("\tDumb"); + int endOffset = MODIFIED_SOURCE_CONTENTS.indexOf("\t// [[[ begin", offset); + fEdit3 = new ReplaceEdit( + offset, endOffset - offset, ""); + + group = new TextEditGroup("Change 3"); + group.addTextEdit(fEdit3); + fChange3 = new TextEditChangeGroup(fDocumentChange, group); + fDocumentChange.addTextEditChangeGroup(fChange3); + multiEdit.addChild(fEdit3); + + } + + private String getSource(IRegion region, int context) throws CoreException { + return fDocumentChange.getCurrentContent(region, true, context, new NullProgressMonitor()); + } + private String getPreview(TextEditChangeGroup group, int context) throws CoreException { + return fDocumentChange.getPreviewContent( + new TextEditChangeGroup[] { group }, + group.getRegion(), true, context, new NullProgressMonitor()); + } + + public void testEmptySourceRangeNoContext() throws Exception { + String src = getSource(fEdit1.getRegion(), 0); + String preview = getPreview(fChange1, 0); + assertEquals("", src); + assertEquals("\tFinalCall();", preview); + + } + public void testEmptySourceRangeNoContext2() throws Exception { + String src = getSource(fEdit2.getRegion(), 0); + String preview = getPreview(fChange2, 0); + assertEquals("", src); + assertEquals("// add comment", preview); + + } + public void testEmptySourceRangeContext() throws Exception { + String src = getSource(fEdit1.getRegion(), 2); + String preview = getPreview(fChange1, 2); + assertEquals("\tMagicCall();\n" + + "\t// ]]] end\n" + + "\t}\n", + src); + assertEquals(" MagicCall();\n" + + " // ]]] end\n" + + " FinalCall();\n" + + " }\n", + preview); + } + public void testEmptySourceRangeContext2() throws Exception { + String src = getSource(fEdit2.getRegion(), 2); + String preview = getPreview(fChange2, 2); + assertEquals("// my file\n", + src); + assertEquals("// add comment\n"+ + "// my file\n", + preview); + } + + public void testEmptyTargetRangeNoContext() throws Exception { + String src = getSource(fEdit3.getRegion(), 0); + String preview = getPreview(fChange3, 0); + assertEquals("\tDumbCall();", src); + assertEquals("", preview); + + } + public void testEmptyTargetRangeContext() throws Exception { + String src = getSource(fEdit3.getRegion(), 2); + String preview = getPreview(fChange3, 2); + assertEquals("\t{\n"+"\tGoodCall();\n"+ + "\tDumbCall();\n"+ + "\t// [[[ begin\n"+ + "\tMagicCall();", + src); + assertEquals("\t{\n"+"\tGoodCall();\n"+ + "\t// [[[ begin\n"+ + "\tMagicCall();", + preview); + + } + +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TrackPositionTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TrackPositionTest.java new file mode 100644 index 000000000..565dc0d25 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TrackPositionTest.java @@ -0,0 +1,86 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.changes; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.text.edits.ReplaceEdit; +import org.eclipse.text.edits.TextEdit; + +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; + +import org.eclipse.ltk.core.refactoring.DocumentChange; + +import org.eclipse.jdt.internal.corext.refactoring.changes.TextChangeCompatibility; + +public class TrackPositionTest extends TestCase { + + private static final Class THIS= TrackPositionTest.class; + private static final String NN= "N.N"; + + private IDocument fDocument; + private DocumentChange fChange; + + public TrackPositionTest(String name) { + super(name); + } + + public static Test suite() { + return new TestSuite(THIS); + } + + protected void setUp() throws Exception { + fDocument= new Document("0123456789"); + fChange= new DocumentChange(NN, fDocument); + fChange.setKeepPreviewEdits(true); + fChange.initializeValidationData(new NullProgressMonitor()); + } + + protected void tearDown() throws Exception { + fChange= null; + } + + public void test1() throws Exception { + TextEdit edit= new ReplaceEdit(2, 2, "xyz"); + TextChangeCompatibility.addTextEdit(fChange, NN, edit); + executeChange(); + assertEquals(edit.getRegion(), 2, 3); + } + + public void test2() throws Exception { + TextEdit edit= new ReplaceEdit(5, 3, "xy"); + TextChangeCompatibility.addTextEdit(fChange, NN, edit); + IDocument preview= fChange.getPreviewDocument(new NullProgressMonitor()); + assertEquals(fDocument.get(), "0123456789"); + assertEquals(preview.get(), "01234xy89"); + assertEquals(fChange.getPreviewEdit(edit).getRegion(), 5, 2); + } + + private void executeChange() throws Exception { + try { + assertTrue(!fChange.isValid(new NullProgressMonitor()).hasFatalError()); + fChange.perform(new NullProgressMonitor()); + } finally { + fChange.dispose(); + } + } + + private static void assertEquals(IRegion r, int offset, int length) { + assertEquals("Offset", offset, r.getOffset()); + assertEquals("Length", length, r.getLength()); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/AllTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/AllTests.java new file mode 100644 index 000000000..696af08e6 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/AllTests.java @@ -0,0 +1,24 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.extensions; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class AllTests { + + public static Test suite() { + TestSuite suite= new TestSuite(AllTests.class.getName()); + suite.addTest(ExtensionPointTests.suite()); + return suite; + } +} + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/ExtensionPointTestSetup.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/ExtensionPointTestSetup.java new file mode 100644 index 000000000..4e40f4e82 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/ExtensionPointTestSetup.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.extensions; + +import junit.extensions.TestSetup; +import junit.framework.Test; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +import org.eclipse.jdt.internal.ui.util.CoreUtility; + + +public class ExtensionPointTestSetup extends TestSetup { + + private IJavaProject fJavaProject; + private IPackageFragmentRoot fRoot; + private static final String CONTAINER= "src"; + + public ExtensionPointTestSetup(Test test) { + super(test); + } + + public IPackageFragmentRoot getRoot() { + return fRoot; + } + + protected void setUp() throws Exception { + super.setUp(); + + fJavaProject= JavaProjectHelper.createJavaProject("TestProject", "bin"); + JavaProjectHelper.addRTJar(fJavaProject); + fRoot= JavaProjectHelper.addSourceContainer(fJavaProject, CONTAINER); + + CoreUtility.setAutoBuilding(false); + + getRoot().createPackageFragment("test", true, null); + } + + protected void tearDown() throws Exception { + super.tearDown(); + JavaProjectHelper.delete(fJavaProject); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/ExtensionPointTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/ExtensionPointTests.java new file mode 100644 index 000000000..5c6f4ff5e --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/ExtensionPointTests.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.extensions; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Path; + +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.ltk.core.refactoring.RefactoringStatusContext; +import org.eclipse.ltk.internal.ui.refactoring.StatusContextViewerDescriptor; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.SourceRange; + +import org.eclipse.jdt.internal.corext.refactoring.base.JavaStatusContext; +import org.eclipse.jdt.internal.corext.refactoring.base.JavaStringStatusContext; + + +public class ExtensionPointTests extends TestCase { + + public static Test suite() { + return new ExtensionPointTestSetup(new TestSuite(ExtensionPointTests.class)); + } + + public void testJavaStringStatusContextViewer() throws Exception { + JavaStringStatusContext context= new JavaStringStatusContext("test", new SourceRange(0, 0)); + StatusContextViewerDescriptor descriptor= StatusContextViewerDescriptor.get(context); + assertNotNull(descriptor); + assertNotNull(descriptor.createViewer()); + } + + public void testJavaStatusContextViewer() throws Exception { + IPackageFragment pack= getTestPackage(); + ICompilationUnit unit= pack.createCompilationUnit( + "A.java", + "package test; class A { }", + true, null); + RefactoringStatusContext context= JavaStatusContext.create(unit); + StatusContextViewerDescriptor descriptor= StatusContextViewerDescriptor.get(context); + assertNotNull(descriptor); + assertNotNull(descriptor.createViewer()); + JavaProjectHelper.performDummySearch(); + unit.delete(true, new NullProgressMonitor()); + } + + private IPackageFragment getTestPackage() { + IFolder folder= ResourcesPlugin.getWorkspace().getRoot().getFolder( + new Path("/TestProject/src/test")); + return (IPackageFragment)JavaCore.create(folder); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/AbstractCUTestCase.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/AbstractCUTestCase.java new file mode 100644 index 000000000..3925c67ab --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/AbstractCUTestCase.java @@ -0,0 +1,98 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +import junit.framework.TestCase; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; + +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; + +public abstract class AbstractCUTestCase extends TestCase { + + public AbstractCUTestCase(String name) { + super(name); + } + + protected String getFileContents(InputStream in) throws IOException { + BufferedReader br= new BufferedReader(new InputStreamReader(in)); + + StringBuffer sb= new StringBuffer(); + try { + int read= 0; + while ((read= br.read()) != -1) + sb.append((char) read); + } finally { + br.close(); + } + return sb.toString(); + } + + protected ICompilationUnit createCU(IPackageFragment pack, String name, String contents) throws Exception { + ICompilationUnit cu= pack.createCompilationUnit(name, contents, true, null); + cu.save(null, true); + return cu; + } + + protected ICompilationUnit createCU(IPackageFragment pack, String name, InputStream contents) throws Exception { + return createCU(pack, name, getFileContents(contents)); + } + + //--- creating a compilation unit from a resource folder relative to a plugin ---------------------------------- + + protected abstract InputStream getFileInputStream(String fileName) throws IOException; + + protected String getResourceLocation() { + return ""; + } + + protected ICompilationUnit createCU(IPackageFragment pack, String name) throws Exception { + name= adaptName(name); + return createCU(pack, name, getFileInputStream(getFilePath(pack, name))); + } + + protected String adaptName(String name) { + return name + ".java"; + } + + protected String getProofedContent(String folder, String name) throws Exception { + name= adaptName(name); + return getFileContents(getFileInputStream(getFilePath(folder, name))); + } + + private String getFilePath(String path, String name) { + return getResourceLocation() + path + "/" + name; + } + + private String getFilePath(IPackageFragment pack, String name) { + return getFilePath(pack.getElementName(), name); + } + + //---- helper to compare two file without considering the package statement + + public static void compareSource(String refactored, String proofed) { + compareSource(refactored, proofed, true); + } + + public static void compareSource(String refactored, String proofed, boolean skipPackageDeclaration) { + int index= skipPackageDeclaration ? refactored.indexOf(';'): 0; + refactored= refactored.substring(index); + index= skipPackageDeclaration ? proofed.indexOf(';') : 0; + proofed= proofed.substring(index); + RefactoringTest.assertEqualLines(proofed, refactored); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/AbstractRefactoringTestSetup.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/AbstractRefactoringTestSetup.java new file mode 100644 index 000000000..44f0abeff --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/AbstractRefactoringTestSetup.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import java.util.Hashtable; + +import junit.extensions.TestSetup; +import junit.framework.Test; + +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +import org.eclipse.jdt.internal.ui.JavaPlugin; +import org.eclipse.jdt.internal.ui.util.CoreUtility; + + +public class AbstractRefactoringTestSetup extends TestSetup { + + private boolean fWasAutobuild; + + public AbstractRefactoringTestSetup(Test test) { + super(test); + } + + protected void setUp() throws Exception { + super.setUp(); + fWasAutobuild= CoreUtility.setAutoBuilding(false); + if (JavaPlugin.getActivePage() != null) + JavaPlugin.getActivePage().close(); + + Hashtable options= TestOptions.getDefaultOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.TAB); + options.put(DefaultCodeFormatterConstants.FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE, "0"); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); + options.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, String.valueOf(9999)); + + JavaCore.setOptions(options); + TestOptions.initializeCodeGenerationOptions(); + JavaPlugin.getDefault().getCodeTemplateStore().load(); + + StringBuffer comment= new StringBuffer(); + comment.append("/**\n"); + comment.append(" * ${tags}\n"); + comment.append(" */"); + StubUtility.setCodeTemplate(CodeTemplateContextType.CONSTRUCTORCOMMENT_ID, comment.toString(), null); + } + + protected void tearDown() throws Exception { + CoreUtility.setAutoBuilding(fWasAutobuild); + /* + * ensure the workbench state gets saved when running with the Automated Testing Framework + * TODO: remove when https://bugs.eclipse.org/bugs/show_bug.cgi?id=71362 is fixed + */ + /* Not needed for JDT/UI tests right now. + StackTraceElement[] elements= new Throwable().getStackTrace(); + for (int i= 0; i < elements.length; i++) { + StackTraceElement element= elements[i]; + if (element.getClassName().equals("org.eclipse.test.EclipseTestRunner")) { + PlatformUI.getWorkbench().close(); + break; + } + } + */ + super.tearDown(); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/DebugUtils.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/DebugUtils.java new file mode 100644 index 000000000..67aa606f6 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/DebugUtils.java @@ -0,0 +1,154 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IImportDeclaration; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; + +public final class DebugUtils { + + private DebugUtils(){ + } + + public static void dumpCharCharArray(String msg, char[][] o){ + dump("DUMPING char[][]:" + msg); //$NON-NLS-1$ + for (int i= 0; i < o.length; i++){ + dump(new String(o[i])); + } + } + + public static void dumpArray(String msg, Object[] refs){ + System.out.println("DUMPING array: "+ msg); //$NON-NLS-1$ + if (refs == null){ + System.out.println("null"); //$NON-NLS-1$ + return; + } + for (int i= 0; i < refs.length; i++) + System.out.println(refs[i].toString()); + } + + public static void dumpCollectionCollection(String msg, Collection c){ + for (Iterator iter= c.iterator(); iter.hasNext(); ){ + dumpCollection("", (List)iter.next()); //$NON-NLS-1$ + } + } + + public static void dumpCollection(String msg, Collection c){ + System.out.println("DUMPING collection: "+ msg); //$NON-NLS-1$ + if (c == null){ + System.out.println("null"); //$NON-NLS-1$ + return; + } + for (Iterator iter= c.iterator(); iter.hasNext(); ){ + System.out.println(iter.next().toString()); + } + } + + public static void dumpIMethod(IMethod method){ + try{ + if (method == null){ + System.out.println("DUMPING method: null"); //$NON-NLS-1$ + return; + } + System.out.println("DUMPING method:" + method.getElementName() + "\n " + method.getSignature() + "\n declared in " + method.getDeclaringType().getFullyQualifiedName('.') //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ + + "\nreturnType:" + method.getReturnType() ); //$NON-NLS-1$ + dumpArray("paramTypes:", method.getParameterTypes()); //$NON-NLS-1$ + dumpArray("exceptions:", method.getExceptionTypes()); //$NON-NLS-1$ + }catch (JavaModelException e){ + System.out.println("JavaModelException: "+ e.getMessage()); //$NON-NLS-1$ + } + } + + public static void dumpIMethodList(String msg, List l){ + System.out.println("DUMPING IMethodList: "+ msg); //$NON-NLS-1$ + if (l == null){ + System.out.println("null"); //$NON-NLS-1$ + return; + } + Iterator iter= l.iterator(); + while(iter.hasNext()){ + dumpIMethod((IMethod)iter.next()); + } + } + + public static void dumpIType(String msg, IType type){ + System.out.println("DUMPING IType:"+ msg); //$NON-NLS-1$ + System.out.println("exists:" + type.exists()); //$NON-NLS-1$ + try{ + System.out.println("correspondingResource:" + type.getCorrespondingResource()); //$NON-NLS-1$ + System.out.println("underResource:" + type.getUnderlyingResource()); //$NON-NLS-1$ + System.out.println("source:\n" + type.getSource()); //$NON-NLS-1$ + + //System.out.println("cu.orig.under" + type.getCompilationUnit().getOriginalElement().getUnderlyingResource()); + System.out.println("cu:" + type.getCompilationUnit().getSource()); //$NON-NLS-1$ + }catch (JavaModelException e){ + System.out.println("JavaModelException: "+ e.getMessage()); //$NON-NLS-1$ + } + + } + + public static void dumpIResource(String msg, IResource res){ + System.out.println("DUMPING IResource:"+ msg); //$NON-NLS-1$ + System.out.println("name:" + res.getFullPath().toString()); //$NON-NLS-1$ + System.out.println("exists" + res.exists()); //$NON-NLS-1$ + } + + public static void dump(Object o){ + if (o == null) + dump("null"); //$NON-NLS-1$ + else + dump(o.toString()); + } + public static void dump(String msg){ + System.out.println("DUMP:" + msg); //$NON-NLS-1$ + } + + public static void dumpImports(ICompilationUnit cu) throws JavaModelException{ + IImportDeclaration[] imports= cu.getImports(); + if (imports == null) + return; + DebugUtils.dump("Compilation Unit: " + cu.getElementName()); //$NON-NLS-1$ + for (int k= 0; k < imports.length; k ++){ + DebugUtils.dump("import " + imports[k].getElementName() + " on demand: " + imports[k].isOnDemand()); //$NON-NLS-2$ //$NON-NLS-1$ + } + } + + public static void dumpImports(IPackageFragment pack) throws JavaModelException{ + ICompilationUnit[] cus= pack.getCompilationUnits(); + if (cus == null) + return; + //DebugUtils.dump("Package " + pack.getElementName()); + for (int j= 0; j < cus.length; j++){ + dumpImports(cus[j]); + } + } + + public static void dumpImports(IJavaProject project) throws JavaModelException{ + IPackageFragment[] packages= project.getPackageFragments(); + if (packages == null) + return; + //DebugUtils.dump("Project " + project.getElementName()); + for (int i= 0; i < packages.length; i++){ + dumpImports(packages[i]); + } + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/MockClipboard.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/MockClipboard.java new file mode 100644 index 000000000..9351ac2b8 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/MockClipboard.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.dnd.Clipboard; +import org.eclipse.swt.dnd.DND; +import org.eclipse.swt.dnd.Transfer; +import org.eclipse.swt.dnd.TransferData; +import org.eclipse.swt.widgets.Display; + + +//have to create this class because of bug 40095 +public class MockClipboard extends Clipboard{ + + private Map fContents; //Transfer -> Object + + public MockClipboard(Display display) { + super(display); + fContents= new HashMap(); + } + + protected void checkSubclass() { + //do nothing + } + + public TransferData[] getAvailableTypes() { + Set result= new HashSet(); + for (Iterator iter= fContents.keySet().iterator(); iter.hasNext();) { + Transfer transfer= (Transfer)iter.next(); + result.addAll(Arrays.asList(transfer.getSupportedTypes())); + } + return (TransferData[]) result.toArray(new TransferData[result.size()]); + } + + public Object getContents(Transfer transfer) { + return fContents.get(transfer); + } + + public void setContents(Object[] data, Transfer[] dataTypes) { + if (data == null || dataTypes == null || data.length != dataTypes.length) { + DND.error(SWT.ERROR_INVALID_ARGUMENT); + } + fContents.clear(); + for (int i= 0; i < dataTypes.length; i++) { + fContents.put(dataTypes[i], data[i]); + } + } + + public void dispose() { + fContents.clear(); + super.dispose(); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/MockWorkbenchSite.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/MockWorkbenchSite.java new file mode 100644 index 000000000..ad8b6c6e2 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/MockWorkbenchSite.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import java.util.List; + +import org.eclipse.swt.widgets.Shell; + +import org.eclipse.core.runtime.Assert; +import org.eclipse.core.runtime.PlatformObject; + +import org.eclipse.jface.viewers.ISelectionProvider; + +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchSite; +import org.eclipse.ui.IWorkbenchWindow; + +import org.eclipse.jdt.internal.ui.JavaPlugin; + +public class MockWorkbenchSite extends PlatformObject implements IWorkbenchSite { + + private ISelectionProvider fProvider; + + public MockWorkbenchSite(ISelectionProvider provider){ + setSelectionProvider(provider); + } + + public MockWorkbenchSite(Object[] elements){ + this(new SimpleSelectionProvider(elements)); + } + + public MockWorkbenchSite(List elements){ + this(new SimpleSelectionProvider(elements)); + } + + public IWorkbenchPage getPage() { + return null; + } + + public ISelectionProvider getSelectionProvider() { + return fProvider; + } + + public Shell getShell() { + return JavaPlugin.getActiveWorkbenchShell(); + } + + public IWorkbenchWindow getWorkbenchWindow() { + return null; + } + + public void setSelectionProvider(ISelectionProvider provider) { + Assert.isNotNull(provider); + fProvider= provider; + } + + /* (non-Javadoc) + * @see org.eclipse.ui.services.IServiceLocator#getService(java.lang.Class) + */ + public Object getService(Class key) { + return null; + } + + /* (non-Javadoc) + * @see org.eclipse.ui.services.IServiceLocator#hasService(java.lang.Class) + */ + public boolean hasService(Class key) { + return false; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringHeapTestCase.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringHeapTestCase.java new file mode 100644 index 000000000..259eba0b8 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringHeapTestCase.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (c) 2005 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.ltk.core.refactoring.CheckConditionsOperation; +import org.eclipse.ltk.core.refactoring.PerformRefactoringOperation; +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringCore; + +public abstract class RefactoringHeapTestCase extends RefactoringPerformanceTestCase { + + public RefactoringHeapTestCase() { + super(); + } + + public RefactoringHeapTestCase(String name) { + super(name); + } + + protected void executeRefactoring(Refactoring refactoring, boolean measure, int maxSeverity, boolean checkUndo) throws Exception { + PerformRefactoringOperation operation= new PerformRefactoringOperation(refactoring, CheckConditionsOperation.ALL_CONDITIONS); + joinBackgroudActivities(); + // Flush the undo manager to not count any already existing undo objects + // into the heap consumption + RefactoringCore.getUndoManager().flush(); + System.gc(); + if (measure) + startMeasuring(); + ResourcesPlugin.getWorkspace().run(operation, null); + if (checkUndo) + assertNotNull(operation.getUndoChange()); + assertEquals(true, operation.getConditionStatus().getSeverity() <= maxSeverity); + assertEquals(true, operation.getValidationStatus().isOK()); + RefactoringCore.getUndoManager().flush(); + System.gc(); + if (measure) + finishMeasurements(); + } +}
\ No newline at end of file diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringPerformanceTestCase.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringPerformanceTestCase.java new file mode 100644 index 000000000..50ef344b6 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringPerformanceTestCase.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.ltk.core.refactoring.CheckConditionsOperation; +import org.eclipse.ltk.core.refactoring.PerformRefactoringOperation; +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.ui.tests.performance.JdtPerformanceTestCase; + +public abstract class RefactoringPerformanceTestCase extends JdtPerformanceTestCase { + + public RefactoringPerformanceTestCase() { + super(); + } + + public RefactoringPerformanceTestCase(String name) { + super(name); + } + + protected void executeRefactoring(Refactoring refactoring, boolean measure) throws Exception { + executeRefactoring(refactoring, measure, RefactoringStatus.WARNING); + } + + protected void executeRefactoring(Refactoring refactoring, boolean measure, int maxSeverity) throws Exception { + executeRefactoring(refactoring, measure, maxSeverity, true); + } + + protected void executeRefactoring(Refactoring refactoring, boolean measure, int maxSeverity, boolean checkUndo) throws Exception { + PerformRefactoringOperation operation= new PerformRefactoringOperation(refactoring, CheckConditionsOperation.ALL_CONDITIONS); + joinBackgroudActivities(); + // Flush the undo manager to not count any already existing undo objects + // into the heap consumption + RefactoringCore.getUndoManager().flush(); + System.gc(); + if (measure) + startMeasuring(); + ResourcesPlugin.getWorkspace().run(operation, null); + if (measure) + finishMeasurements(); + assertEquals(true, operation.getConditionStatus().getSeverity() <= maxSeverity); + assertEquals(true, operation.getValidationStatus().isOK()); + if (checkUndo) { + assertNotNull(operation.getUndoChange()); + } + RefactoringCore.getUndoManager().flush(); + System.gc(); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringPerformanceTestSetup.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringPerformanceTestSetup.java new file mode 100644 index 000000000..89ab2024a --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringPerformanceTestSetup.java @@ -0,0 +1,20 @@ +/******************************************************************************* + * Copyright (c) 2000, 2005 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import junit.framework.Test; + +public class RefactoringPerformanceTestSetup extends AbstractRefactoringTestSetup { + + public RefactoringPerformanceTestSetup(Test test) { + super(test); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringTestPlugin.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringTestPlugin.java new file mode 100644 index 000000000..bb1fd7eb0 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringTestPlugin.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.Plugin; + +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.ResourcesPlugin; + + +public class RefactoringTestPlugin extends Plugin { + + private static RefactoringTestPlugin fgDefault; + + public RefactoringTestPlugin() { + fgDefault= this; + } + + public static RefactoringTestPlugin getDefault() { + return fgDefault; + } + + public static IWorkspace getWorkspace() { + return ResourcesPlugin.getWorkspace(); + } + + public InputStream getTestResourceStream(String fileName) throws IOException { + IPath path= new Path("resources").append(fileName); + URL url= new URL(getBundle().getEntry("/"), path.toString()); + return url.openStream(); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringTestRepositoryProvider.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringTestRepositoryProvider.java new file mode 100644 index 000000000..5c92d6dee --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/RefactoringTestRepositoryProvider.java @@ -0,0 +1,130 @@ +/******************************************************************************* + * Copyright (c) 2005, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; + +import org.eclipse.team.core.RepositoryProvider; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IWorkspaceRunnable; +import org.eclipse.core.resources.ResourceAttributes; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.resources.team.FileModificationValidationContext; +import org.eclipse.core.resources.team.FileModificationValidator; + +public class RefactoringTestRepositoryProvider extends RepositoryProvider { + + public static final String PROVIDER_ID= "org.eclipse.jdt.ui.tests.refactoring.refactoringTestRepositoryProvider"; + + private static HashMap/*IProject, RefactoringTestFileModificationValidator*/ fgValidators= new HashMap(); + + public static Collection getValidatedEditPaths(IProject project) { + RefactoringTestFileModificationValidator validator= (RefactoringTestFileModificationValidator) fgValidators.get(project); + if (validator != null) { + return validator.getValidatedEditPaths(); + } + return null; + } + + public static Collection getValidatedSavePaths(IProject project) { + RefactoringTestFileModificationValidator validator= (RefactoringTestFileModificationValidator) fgValidators.get(project); + if (validator != null) { + return validator.getValidatedSavePaths(); + } + return null; + } + + private static class RefactoringTestFileModificationValidator extends FileModificationValidator { + + private ArrayList fValidatedEditPaths; + private ArrayList fValidatedSavePaths; + + public RefactoringTestFileModificationValidator() { + fValidatedEditPaths= new ArrayList(); + fValidatedSavePaths= new ArrayList(); + } + + public Collection/*IPath*/ getValidatedEditPaths() { + return fValidatedEditPaths; + } + + public Collection/*IPath*/ getValidatedSavePaths() { + return fValidatedSavePaths; + } + + public IStatus validateEdit(IFile[] files, FileModificationValidationContext context) { + for (int i= 0; i < files.length; i++) { + fValidatedEditPaths.add(files[i].getFullPath()); + } + return makeWritable(files); + } + + public IStatus validateSave(IFile file) { + fValidatedSavePaths.add(file.getFullPath()); + return makeWritable(new IFile[] { file }); + } + + private IStatus makeWritable(final IFile[] resources) { + try { + ResourcesPlugin.getWorkspace().run( + new IWorkspaceRunnable() { + public void run(IProgressMonitor monitor) throws CoreException { + for (int i= 0; i < resources.length; i++) { + IFile resource= resources[i]; + ResourceAttributes resourceAttributes = resource.getResourceAttributes(); + if (resourceAttributes != null) { + resourceAttributes.setReadOnly(false); + resource.setResourceAttributes(resourceAttributes); + } + } + } + }, + null); + } catch (CoreException e) { + e.printStackTrace(); + return e.getStatus(); + } + return Status.OK_STATUS; + } + } + + private RefactoringTestFileModificationValidator fValidator; + + public RefactoringTestRepositoryProvider() { + fValidator= new RefactoringTestFileModificationValidator(); + } + + public String getID() { + return PROVIDER_ID; + } + + public FileModificationValidator getFileModificationValidator2() { + return fValidator; + } + + public void configureProject() throws CoreException { + fgValidators.put(getProject(), fValidator); + } + + public void deconfigure() throws CoreException { + fgValidators.remove(getProject()); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/SWTProjectTestSetup.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/SWTProjectTestSetup.java new file mode 100644 index 000000000..a078ef303 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/SWTProjectTestSetup.java @@ -0,0 +1,34 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import junit.framework.Test; + +import org.eclipse.jdt.ui.tests.performance.SWTTestProject; + +public class SWTProjectTestSetup extends RefactoringPerformanceTestSetup { + + private SWTTestProject fTestProject; + + public SWTProjectTestSetup(Test test) { + super(test); + } + + protected void setUp() throws Exception { + super.setUp(); + fTestProject= new SWTTestProject(); + } + + protected void tearDown() throws Exception { + fTestProject.delete(); + super.tearDown(); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/SimpleSelectionProvider.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/SimpleSelectionProvider.java new file mode 100644 index 000000000..2675deb13 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/SimpleSelectionProvider.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import java.util.Collection; + +import org.eclipse.core.runtime.Assert; + +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.ISelectionProvider; +import org.eclipse.jface.viewers.StructuredSelection; + +public class SimpleSelectionProvider implements ISelectionProvider { + private ISelection fSelection; + + public SimpleSelectionProvider(Collection collection) { + this(collection.toArray()); + } + + public SimpleSelectionProvider(Object[] elements) { + Assert.isNotNull(elements); + fSelection= new StructuredSelection(elements); + } + + public void addSelectionChangedListener(ISelectionChangedListener listener) { + } + + public ISelection getSelection() { + return fSelection; + } + + public void removeSelectionChangedListener(ISelectionChangedListener listener) { + } + + public void setSelection(ISelection selection) { + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/TextRangeUtil.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/TextRangeUtil.java new file mode 100644 index 000000000..6e3b3fb48 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/TextRangeUtil.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IRegion; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.SourceRange; + + +public class TextRangeUtil { + + //no instances + private TextRangeUtil(){} + + public static ISourceRange getSelection(ICompilationUnit cu, int startLine, int startColumn, int endLine, int endColumn) throws Exception { + IDocument document= new Document(cu.getSource()); + int offset= getOffset(document, startLine, startColumn); + int end= getOffset(document, endLine, endColumn); + return new SourceRange(offset, end - offset); + } + + public static int getOffset(ICompilationUnit cu, int line, int column) throws Exception { + IDocument document= new Document(cu.getSource()); + return getOffset(document, line, column) ; + } + + public static int getOffset(String source, int line, int column) throws BadLocationException { + IDocument document= new Document(source); + return getOffset(document, line, column); + } + + private static int getOffset(IDocument document, int line, int column) throws BadLocationException { + int r= document.getLineInformation(line - 1).getOffset(); + IRegion region= document.getLineInformation(line - 1); + int lineTabCount= calculateTabCountInLine(document.get(region.getOffset(), region.getLength()), column); + r += (column - 1) - (lineTabCount * getTabWidth()) + lineTabCount; + return r; + } + + private static final int getTabWidth(){ + return 4; + } + + public static int calculateTabCountInLine(String lineSource, int lastCharOffset){ + int acc= 0; + int charCount= 0; + for(int i= 0; charCount < lastCharOffset - 1; i++){ + if ('\t' == lineSource.charAt(i)){ + acc++; + charCount += getTabWidth(); + } else + charCount += 1; + } + return acc; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/ZipTools.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/ZipTools.java new file mode 100644 index 000000000..c8d7d3890 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/ZipTools.java @@ -0,0 +1,96 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.infra; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import junit.framework.Assert; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; + +public class ZipTools { + + private static String getSourceFileName(String fileName) { + if (fileName.lastIndexOf('/') == -1){ + return fileName; + } else { + return fileName.substring(fileName.lastIndexOf('/')+1); + } + } + + private static String getPackageName(String fileName) { + String packageName= null; + if (fileName.lastIndexOf('/') == -1){ + packageName= ""; + } else { + packageName= fileName.substring(0, fileName.lastIndexOf('/')).replace('/', '.'); + } + return packageName; + } + + public static void compareWithZipped(IPackageFragmentRoot src, ZipInputStream zipInputStream, String zipFileEncoding) throws IOException, UnsupportedEncodingException, JavaModelException { + try { + ArrayList zipCus= new ArrayList(); + ZipEntry ze; + while ((ze= zipInputStream.getNextEntry()) != null){ + String fileName = ze.getName(); + if (fileName.endsWith(".java")){ + String packageName = getPackageName(fileName); + String sourceFileName= getSourceFileName(fileName); + zipCus.add(packageName + "/" + sourceFileName); + + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + byte data[] = new byte[10000]; + int count = -1; + while ( (count = zipInputStream.read(data, 0, data.length)) != -1) { + bout.write(data, 0, count); + } + String zipContents= bout.toString(zipFileEncoding); + + IPackageFragment pack= src.getPackageFragment(packageName); + ICompilationUnit cu= pack.getCompilationUnit(sourceFileName); + String cuContents= cu.getSource(); + + RefactoringTest.assertEqualLines(packageName + "/" + sourceFileName, zipContents, cuContents); + } else { + //TODO: compare binary files + } + } + + IJavaElement[] packageFragments= src.getChildren(); + for (int i= 0; i < packageFragments.length; i++) { + IPackageFragment packageFragment= (IPackageFragment) packageFragments[i]; + ICompilationUnit[] cus= packageFragment.getCompilationUnits(); + for (int j= 0; j < cus.length; j++) { + ICompilationUnit cu= cus[j]; + String cuDescr= packageFragment.getElementName() + "/" + cu.getElementName(); + Assert.assertTrue(cuDescr, zipCus.remove(cuDescr)); + } + } + Assert.assertEquals(zipCus.toString(), 0, zipCus.size()); + + } finally { + zipInputStream.close(); + } + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/AllTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/AllTests.java new file mode 100644 index 000000000..8f9699312 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/AllTests.java @@ -0,0 +1,43 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + + +import junit.framework.Test; +import junit.framework.TestSuite; + + +public class AllTests { + + public static Test suite ( ) { + TestSuite suite = new TestSuite(); + // old + suite.addTest(NLSElementTester.suite()); + suite.addTest(NLSScannerTester.suite()); + suite.addTest(CellEditorTester.suite()); + + // new + suite.addTest(NlsRefactoringCheckInitialConditionsTest.allTests()); + suite.addTest(NlsRefactoringCheckFinalConditionsTest.allTests()); + suite.addTest(NlsRefactoringCreateChangeTest.allTests()); + suite.addTest(NLSSourceModifierTest.allTests()); + suite.addTest(NLSHintTest.allTests()); + suite.addTest(NLSHintHelperTest.suite()); + suite.addTest(PropertyFileDocumentModellTest.suite()); + suite.addTest(SimpleLineReaderTest.suite()); + suite.addTest(NLSHolderTest.suite()); + suite.addTest(NLSSubstitutionTest.suite()); + + return suite; + } +} + + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/CellEditorTester.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/CellEditorTester.java new file mode 100644 index 000000000..8d90f474c --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/CellEditorTester.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.internal.ui.refactoring.nls.MultiStateCellEditor; + + +public class CellEditorTester extends TestCase { + + public CellEditorTester(String name) { + super(name); + } + + public static void main (String[] args) { + junit.textui.TestRunner.run (suite()); + } + + public static Test suite() { + return new TestSuite(CellEditorTester.class); + } + + public void test0(){ + MultiStateCellEditor ce= new MultiStateCellEditor(null, 3, 0); + assertTrue(ce.getValue().equals(new Integer(0))); + } + + public void test1(){ + MultiStateCellEditor ce= new MultiStateCellEditor(null, 3, 0); + ce.activate(); + assertTrue(ce.getValue().equals(new Integer(1))); + } + public void test2(){ + MultiStateCellEditor ce= new MultiStateCellEditor(null, 3, 0); + ce.activate(); + ce.activate(); + assertTrue(ce.getValue().equals(new Integer(2))); + } + + public void test3(){ + MultiStateCellEditor ce= new MultiStateCellEditor(null, 3, 0); + ce.activate(); + ce.activate(); + ce.activate(); + assertTrue(ce.getValue().equals(new Integer(0))); + } + + public void test4(){ + MultiStateCellEditor ce= new MultiStateCellEditor(null, 3, 0); + ce.setValue(new Integer(1)); + assertTrue(ce.getValue().equals(new Integer(1))); + } + + public void test5(){ + MultiStateCellEditor ce= new MultiStateCellEditor(null, 3, 0); + ce.setValue(new Integer(2)); + ce.activate(); + assertTrue(ce.getValue().equals(new Integer(0))); + } +} + + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSElementTester.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSElementTester.java new file mode 100644 index 000000000..f23f49714 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSElementTester.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSElement; + + +public class NLSElementTester extends TestCase{ + + public NLSElementTester(String name) { + super(name); + } + + private NLSElement fEl; + private int fOff, fLen; + private String fVal; + + + public static void main (String[] args) { + junit.textui.TestRunner.run (suite()); + } + + public static Test suite() { + return new TestSuite(NLSElementTester.class); + } + + protected void setUp(){ + fOff= 3; + fLen= 5; + fVal= "test"; //$NON-NLS-1$ + fEl= new NLSElement(fVal, fOff, fLen, 0, false); + } + + protected void tearDown(){ + } + + public void test0(){ + assertEquals("Position offset", fOff, fEl.getPosition().getOffset()); //$NON-NLS-1$ + } + + public void test1(){ + assertEquals("Position length", fLen, fEl.getPosition().getLength()); //$NON-NLS-1$ + } + + public void test2(){ + assertEquals("value", fVal, fEl.getValue()); //$NON-NLS-1$ + } + + public void test3(){ + assertEquals("tagposition", null, fEl.getTagPosition()); //$NON-NLS-1$ + } + + public void test3a(){ + fEl.setTagPosition(1, 2); + assertEquals("tagposition.length", 2, fEl.getTagPosition().getLength()); //$NON-NLS-1$ + assertEquals("tagposition.offset", 1, fEl.getTagPosition().getOffset()); //$NON-NLS-1$ + } + + + public void test4(){ + assertEquals("hastag", false, fEl.hasTag()); //$NON-NLS-1$ + } + + public void test4a(){ + fEl.setTagPosition(1, 2); + assertEquals("hastag", true, fEl.hasTag()); //$NON-NLS-1$ + } + +} + + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHintHelperTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHintHelperTest.java new file mode 100644 index 000000000..9848bb1e0 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHintHelperTest.java @@ -0,0 +1,429 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.jdt.ui.tests.refactoring.nls; + +import java.io.File; +import java.util.Properties; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.JavaTestPlugin; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.core.filebuffers.FileBuffers; +import org.eclipse.core.filebuffers.ITextFileBuffer; +import org.eclipse.core.filebuffers.ITextFileBufferManager; +import org.eclipse.core.filebuffers.LocationKind; + +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.Region; + +import org.eclipse.jdt.core.IClassFile; +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.NodeFinder; +import org.eclipse.jdt.core.dom.TypeDeclaration; + +import org.eclipse.jdt.internal.corext.refactoring.nls.AccessorClassReference; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSHintHelper; + +import org.eclipse.jdt.ui.SharedASTProvider; +import org.eclipse.jdt.ui.tests.core.ProjectTestSetup; + + +/** + * Tests the NLSHintHelper. + * + * @since 3.1 + */ +public class NLSHintHelperTest extends TestCase { + + private IJavaProject fJProject; + private IPackageFragmentRoot fLibrary; + + + public static Test suite() { + return new ProjectTestSetup(new TestSuite(NLSHintHelperTest.class)); + } + + + protected void setUp() throws Exception { + fJProject= ProjectTestSetup.getProject(); + File lib= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.NLS_LIB); + assertTrue("lib does not exist", lib != null && lib.exists()); + fLibrary= JavaProjectHelper.addLibrary(fJProject, Path.fromOSString(lib.getPath())); // add library to project + } + + public void testFindInJAR() { + try { + assertNotNull(NLSHintHelper.getResourceBundle(fLibrary, "pkg", "Messages.properties")); + } catch (JavaModelException e) { + fail(); + } + IPackageFragment pkg= fLibrary.getPackageFragment("pkg"); + IClassFile classFile= pkg.getClassFile("Client.class"); + IRegion region= new Region(648, 4); + CompilationUnit ast= SharedASTProvider.getAST(classFile, SharedASTProvider.WAIT_YES, null); + AccessorClassReference accessor= NLSHintHelper.getAccessorClassReference(ast, region); + assertNotNull(accessor); + Properties properties= NLSHintHelper.getProperties(fJProject, accessor); + assertNotNull(properties); + assertEquals("Hello World", properties.get("test")); + try { + assertNotNull(NLSHintHelper.getResourceBundle(fJProject, accessor)); + } catch (JavaModelException e1) { + fail(); + } + + } + + public void testDoNotFindInJAR() { + try { + assertNull(NLSHintHelper.getResourceBundle(fJProject, "pkg", "Messages.properties")); + } catch (JavaModelException e) { + fail(); + } + } + + public void testFindInDirtyBuffer() { + ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager(); + assertNotNull(manager); + + IPath nonExistentPath= fJProject.getProject().getFullPath().append("" + System.currentTimeMillis()); + try { + manager.connect(nonExistentPath, LocationKind.NORMALIZE, null); + } catch (CoreException e) { + fail(); + } + try { + ITextFileBuffer buffer= manager.getTextFileBuffer(nonExistentPath, LocationKind.NORMALIZE); + buffer.getDocument().set("newKey= newValue"); + + IFile nonExistentFile= ResourcesPlugin.getWorkspace().getRoot().getFile(nonExistentPath); + + Properties properties= NLSHintHelper.getProperties(nonExistentFile); + String newValue= properties.getProperty("newKey"); + assertEquals("newValue", newValue); + } finally { + try { + manager.disconnect(nonExistentPath, LocationKind.NORMALIZE, null); + } catch (CoreException e1) { + // ignore: test itself was already successful + } + } + } + + public void testDoNotFindDirtyBuffer() { + ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager(); + assertNotNull(manager); + + IPath nonExistentPath= fJProject.getProject().getFullPath().append("" + System.currentTimeMillis()); + try { + manager.connect(nonExistentPath, LocationKind.NORMALIZE, null); + } catch (CoreException e) { + fail(); + } + try { + ITextFileBuffer buffer= manager.getTextFileBuffer(nonExistentPath, LocationKind.NORMALIZE); + buffer.getDocument().set("newKey= newValue"); + + IFile nonExistentFile= ResourcesPlugin.getWorkspace().getRoot().getFile(nonExistentPath); + + Properties properties= NLSHintHelper.getProperties(nonExistentFile); + String newValue= properties.getProperty("nonExistingValue"); + assertEquals(newValue, null); + } finally { + try { + manager.disconnect(nonExistentPath, LocationKind.NORMALIZE, null); + } catch (CoreException e1) { + // ignore: test itself was already successful + } + } + } + + public void testFindInFile() { + ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager(); + assertNotNull(manager); + + String fileName= "" + System.currentTimeMillis(); + IPath nonExistentPath= fJProject.getProject().getFullPath().append(fileName); + IPath nonExistentLocation= fJProject.getProject().getLocation().append(fileName); + + try { + manager.connect(nonExistentLocation, LocationKind.NORMALIZE, null); + } catch (CoreException e) { + fail(); + } + try { + ITextFileBuffer buffer= manager.getTextFileBuffer(nonExistentLocation, LocationKind.NORMALIZE); + buffer.getDocument().set("newKey= newValue"); + buffer.commit(null, false); + + fJProject.getProject().refreshLocal(IResource.DEPTH_ONE, null); + + IFile existentFile= ResourcesPlugin.getWorkspace().getRoot().getFile(nonExistentPath); + assertEquals(true, existentFile.exists()); + + Properties properties= NLSHintHelper.getProperties(existentFile); + String newValue= properties.getProperty("newKey"); + assertEquals("newValue", newValue); + } catch (CoreException ex) { + fail(); + } finally { + try { + manager.disconnect(nonExistentPath, LocationKind.NORMALIZE, null); + } catch (CoreException e1) { + // ignore: test itself was already successful + } + } + } + + public void testDoNotFindInFile() { + ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager(); + assertNotNull(manager); + + String fileName= "" + System.currentTimeMillis(); + IPath nonExistentPath= fJProject.getProject().getFullPath().append(fileName); + IPath nonExistentLocation= fJProject.getProject().getLocation().append(fileName); + try { + manager.connect(nonExistentLocation, LocationKind.NORMALIZE, null); + } catch (CoreException e) { + fail(); + } + try { + ITextFileBuffer buffer= manager.getTextFileBuffer(nonExistentLocation, LocationKind.NORMALIZE); + buffer.getDocument().set("newKey= newValue"); + buffer.commit(null, false); + + fJProject.getProject().refreshLocal(IResource.DEPTH_ONE, null); + + IFile existentFile= ResourcesPlugin.getWorkspace().getRoot().getFile(nonExistentPath); + assertEquals(true, existentFile.exists()); + + Properties properties= NLSHintHelper.getProperties(existentFile); + String newValue= properties.getProperty("nonExistingValue"); + assertEquals(newValue, null); + } catch (CoreException ex) { + fail(); + } finally { + try { + manager.disconnect(nonExistentPath, LocationKind.NORMALIZE, null); + } catch (CoreException e1) { + // ignore: test itself was already successful + } + } + } + + public void testFindResourceBundleName1f() throws Exception { + String source= + "package test;\n" + + "public class TestMessages {\n" + + " private static final String BUNDLE_NAME = \"test.test\";\n" + + " public static String getString(String s) {" + + " return \"\";\n" + + " }\n" + + "}\n"; + + + assertEquals("test.test", getResourceBundleName(source, "TestMessages", "test")); + } + + public void testFindResourceBundleName1s() throws Exception { + String source= + "package test;\n" + + "public class TestMessages {\n" + + " private static String BUNDLE_NAME;\n" + + " static {\n" + + " BUNDLE_NAME= \"test.test\";\n" + + " }\n" + + " public static String getString(String s) {" + + " return \"\";\n" + + " }\n" + + "}\n"; + + + assertEquals("test.test", getResourceBundleName(source, "TestMessages", "test")); + } + + public void testFindResourceBundleName2f() throws Exception { + String source= + "package test;\n" + + "public class TestMessages {\n" + + " private static final String BUNDLE_NAME = TestMessages.class.getName();\n" + + " public static String getString(String s) {\n" + + " return \"\";\n" + + " }\n" + + "}\n"; + + assertEquals("test.TestMessages", getResourceBundleName(source, "TestMessages", "test")); + } + + public void testFindResourceBundleName2s() throws Exception { + String source= + "package test;\n" + + "public class TestMessages {\n" + + " private static String BUNDLE_NAME;\n" + + " static {\n" + + " BUNDLE_NAME = TestMessages.class.getName();\n" + + " }\n" + + " public static String getString(String s) {\n" + + " return \"\";\n" + + " }\n" + + "}\n"; + + assertEquals("test.TestMessages", getResourceBundleName(source, "TestMessages", "test")); + } + + public void testFindResourceBundleName3f() throws Exception { + String source= + "package test;\n" + + "import java.util.ResourceBundle;\n" + + "public class TestMessages {\n" + + " private static final ResourceBundle b= ResourceBundle.getBundle(TestMessages.class.getName());\n" + + " public static String getString(String s) {\n" + + " return \"\";\n" + + " }\n" + + "}\n"; + + assertEquals("test.TestMessages", getResourceBundleName(source, "TestMessages", "test")); + } + + public void testFindResourceBundleName3s() throws Exception { + String source= + "package test;\n" + + "import java.util.ResourceBundle;\n" + + "public class TestMessages {\n" + + " private static ResourceBundle b;\n" + + " static {\n" + + " b= ResourceBundle.getBundle(TestMessages.class.getName());\n" + + " }\n" + + " public static String getString(String s) {\n" + + " return \"\";\n" + + " }\n" + + "}\n"; + + assertEquals("test.TestMessages", getResourceBundleName(source, "TestMessages", "test")); + } + + public void testFindResourceBundleName4f() throws Exception { + String source= + "package test;\n" + + "import java.util.ResourceBundle;\n" + + "public class TestMessages {\n" + + " private static final ResourceBundle b= ResourceBundle.getBundle(\"test.test\");\n" + + " public static String getString(String s) {\n" + + " return \"\";\n" + + " }\n" + + "}\n"; + + assertEquals("test.test", getResourceBundleName(source, "TestMessages", "test")); + } + + public void testFindResourceBundleName4s() throws Exception { + String source= + "package test;\n" + + "import java.util.ResourceBundle;\n" + + "public class TestMessages {\n" + + " private static ResourceBundle b;\n" + + " static {\n" + + " b= ResourceBundle.getBundle(\"test.test\");\n" + + " }\n" + + " public static String getString(String s) {\n" + + " return \"\";\n" + + " }\n" + + "}\n"; + + assertEquals("test.test", getResourceBundleName(source, "TestMessages", "test")); + } + + public void testFindResourceBundleName5f() throws Exception { + String source= + "package test;\n" + + "import java.util.ResourceBundle;\n" + + "public class TestMessages {\n" + + " private static final String RESOURCE_BUNDLE= TestMessages.class.getName();\n" + + " private static final ResourceBundle b= ResourceBundle.getBundle(RESOURCE_BUNDLE);\n" + + " public static String getString(String s) {\n" + + " return \"\";\n" + + " }\n" + + "}\n"; + + assertEquals("test.TestMessages", getResourceBundleName(source, "TestMessages", "test")); + } + + public void testFindResourceBundleName5s() throws Exception { + String source= + "package test;\n" + + "import java.util.ResourceBundle;\n" + + "public class TestMessages {\n" + + " private static final String RESOURCE_BUNDLE= TestMessages.class.getName();\n" + + " private static ResourceBundle b;\n" + + " static {\n" + + " b= ResourceBundle.getBundle(RESOURCE_BUNDLE);\n" + + " }\n" + + " public static String getString(String s) {\n" + + " return \"\";\n" + + " }\n" + + "}\n"; + + assertEquals("test.TestMessages", getResourceBundleName(source, "TestMessages", "test")); + } + + public void testFindResourceBundleName6() throws Exception { + String source= + "package test;\n" + + "import java.util.ResourceBundle;\n" + + "public class TestMessages {\n" + + " private static final String RESOURCE_BUNDLE= TestMessages.class.getName();\n" + + " private static ResourceBundle fgResourceBundle= ResourceBundle.getBundle(RESOURCE_BUNDLE);\n" + + " public static String getString(String s) {\n" + + " return \"\";\n" + + " }\n" + + "}\n"; + + assertEquals("test.TestMessages", getResourceBundleName(source, "TestMessages", "test")); + } + + private String getResourceBundleName(String source, String className, String packageName) throws Exception { + // Create CU + IPackageFragmentRoot sourceFolder = JavaProjectHelper.addSourceContainer(fJProject, "src"); + IPackageFragment pack = sourceFolder.createPackageFragment(packageName, false, null); + ICompilationUnit cu= pack.createCompilationUnit(className + ".java", source, false, null); + + // Get type binding + CompilationUnit ast= SharedASTProvider.getAST(cu, SharedASTProvider.WAIT_YES, null); + ASTNode node= NodeFinder.perform(ast, cu.getType(className).getSourceRange()); + ITypeBinding typeBinding= ((TypeDeclaration)node).resolveBinding(); + + return NLSHintHelper.getResourceBundleName(typeBinding); + } + + protected void tearDown() throws Exception { + JavaProjectHelper.clear(fJProject, ProjectTestSetup.getDefaultClasspath()); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHintTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHintTest.java new file mode 100644 index 000000000..62177a18f --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHintTest.java @@ -0,0 +1,310 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.dom.CompilationUnit; + +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSHint; +import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.ASTCreator; + +import org.eclipse.jdt.ui.tests.core.ProjectTestSetup; + +public class NLSHintTest extends TestCase { + + private IJavaProject javaProject; + + private IPackageFragmentRoot fSourceFolder; + + private final static String TEST_KLAZZ = + "public class Test {" + + " private String str=TestMessages.getString(\"whateverKey\");//$NON-NLS-1$\n" + + "}\n"; + + private final static String ACCESSOR_KLAZZ = + "public class TestMessages {\n" + + " private static final String BUNDLE_NAME = \"test.test\";//$NON-NLS-1$\n" + + " public static String getString(String s) {" + + " return \"\";\n" + + " }\n" + + "}\n"; + + private static final boolean ALL_TESTS= true; + + + public NLSHintTest(String arg) { + super(arg); + } + + public static Test allTests() { + if (ALL_TESTS) { + return new ProjectTestSetup(new TestSuite(NLSHintTest.class)); + } else { + TestSuite suite= new TestSuite(); + suite.addTest(new NLSHintTest("testResourceBundleHint")); + return new ProjectTestSetup(suite); + } + } + + public static Test suite() { + return allTests(); + } + + protected void setUp() throws Exception { + javaProject = ProjectTestSetup.getProject(); + fSourceFolder = JavaProjectHelper.addSourceContainer(javaProject, "src"); + } + + protected void tearDown() throws Exception { + JavaProjectHelper.clear(javaProject, ProjectTestSetup.getDefaultClasspath()); + } + + /* + * documents bug 57622. + */ + public void testNlsedButNotTranslated() throws Exception { + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + String klazz = + "package test;\n" + + "public class Test {" + + " private String str=\"whateverKey\";//$NON-NLS-1$\n" + + "}\n"; + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + NLSHint hint = createNLSHint(cu); + assertEquals("Messages", hint.getAccessorClassName()); + } + + /* + * documents bug 59074 + */ + public void testLooksLikeAccessor() throws Exception { + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + String klazz = + "package test;\n" + + "public class Test {\n" + + " String[] foo = {\"ab\", String.valueOf(Boolean.valueOf(\"cd\")), \"de\"}; //$NON-NLS-1$ //$NON-NLS-2$\n" + + "}\n"; + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + NLSHint hint = createNLSHint(cu); + assertEquals("Messages", hint.getAccessorClassName()); + assertEquals(pack, hint.getAccessorClassPackage()); + assertEquals("messages.properties", hint.getResourceBundleName()); + assertEquals(pack, hint.getResourceBundlePackage()); + } + + /* + * nlsed-String must be an argument of method. + */ + public void testNoAccessorClassHint1() throws Exception { + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + String klazz = + "package test;\n" + + "public class Test {" + + " private String str=\"whateverKey\".toString();//$NON-NLS-1$\n" + + "}\n"; + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + NLSHint hint = createNLSHint(cu); + assertEquals("Messages", hint.getAccessorClassName()); + } + + /* + * method has no necessary static modifier. + */ + public void testNoAccessorClassHint2() throws Exception { + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + String klazz = + "package test;\n" + + "public class Test {" + + " private String str=new Wrong().meth(\"whatever\");//$NON-NLS-1$\n" + + "}\n"; + + String klazz2 = + "package test;\n" + + "public class Wrong {\n" + + " public void meth(String str) {};\n" + + "}\n"; + ICompilationUnit cu= pack.createCompilationUnit("Wrong.java", klazz2, false, null); + cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + NLSHint hint = createNLSHint(cu); + assertEquals("Messages", hint.getAccessorClassName()); + } + + /* + * accessor class does not exist. + */ + public void testNoAccessorClassHint3() throws Exception { + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + String klazz = "package test;\n" + TEST_KLAZZ; + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + NLSHint hint = createNLSHint(cu); + assertEquals("Messages", hint.getAccessorClassName()); + } + + public void testAccessorClassAndPackageHint() throws Exception { + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + String klazz = "package test;\n" + TEST_KLAZZ; + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + klazz = "package test;\n" + ACCESSOR_KLAZZ; + pack.createCompilationUnit("TestMessages.java", klazz, false, null); + + NLSHint hint = createNLSHint(cu); + assertEquals("TestMessages", hint.getAccessorClassName()); + assertEquals(pack, hint.getAccessorClassPackage()); + } + + public void testPackageHintWithNoPackage() throws Exception { + IPackageFragment pack = fSourceFolder.createPackageFragment("", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", TEST_KLAZZ, false, null); + + pack.createCompilationUnit("TestMessages.java", ACCESSOR_KLAZZ, false, null); + + NLSHint hint = createNLSHint(cu); + assertEquals(pack, hint.getAccessorClassPackage()); + } + + public void testPackageHintWithDifferentPackages() throws Exception { + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + String klazz = + "package test;\n" + + "import test.foo.TestMessages;\n" + + TEST_KLAZZ; + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + IPackageFragment fooPackage = fSourceFolder.createPackageFragment("test.foo", false, null); + klazz = "package test.foo;\n" + ACCESSOR_KLAZZ; + fooPackage.createCompilationUnit("TestMessages.java", klazz, false, null); + + NLSHint hint = createNLSHint(cu); + assertEquals(fooPackage, hint.getAccessorClassPackage()); + } + + public void testResourceBundleHint() throws Exception { + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + String klazz = "package test;\n" + TEST_KLAZZ; + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + klazz = "package test;\n" +ACCESSOR_KLAZZ; + pack.createCompilationUnit("TestMessages.java", klazz, false, null); + NLSHint hint = createNLSHint(cu); + assertEquals("test.properties", hint.getResourceBundleName()); + } + + public void testResourceBundleHintWithDifferentPackagesAndClassGetName() throws Exception { + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + String klazz = + "package test;\n" + + "import test.foo.TestMessages;\n" + + TEST_KLAZZ; + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + IPackageFragment fooPackage = fSourceFolder.createPackageFragment("test.foo", false, null); + klazz = + "package test.foo;\n" + + "public class TestMessages {\n" + + " private static final String BUNDLE_NAME = TestMessages.class.getName();\n" + + " public static String getString(String s) {\n" + + " return \"\"\n;" + + " }\n" + + "}\n"; + fooPackage.createCompilationUnit("TestMessages.java", klazz, false, null); + + NLSHint hint = createNLSHint(cu); + assertEquals("TestMessages.properties", hint.getResourceBundleName()); + } + + public void testResourceBundlePackageHint() throws Exception { + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + String klazz = + "package test;\n" + + "import test.foo.TestMessages;\n" + + TEST_KLAZZ; + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + IPackageFragment fooPackage = fSourceFolder.createPackageFragment("test.foo", false, null); + fooPackage.createCompilationUnit("TestMessages.java", klazz, false, null); + + createResource(pack, "test.properties", "a=0"); + NLSHint hint = createNLSHint(cu); + assertEquals(pack, hint.getResourceBundlePackage()); + } + + public void testResourceBundlePackageHintWithClassGetName() throws Exception { + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + String klazz = + "package test;\n" + + "import test.foo.TestMessages;\n" + + TEST_KLAZZ; + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + IPackageFragment fooPackage = fSourceFolder.createPackageFragment("test.foo", false, null); + klazz = + "package test.foo;\n" + + "public class TestMessages {\n" + + " private static final String BUNDLE_NAME = TestMessages.class.getName();\n" + + " public static String getString(String s) {\n" + + " return \"\"\n;" + + " }\n" + + "}\n"; + fooPackage.createCompilationUnit("TestMessages.java", klazz, false, null); + + createResource(fooPackage, "TestMessages.properties", "a=0"); + NLSHint hint = createNLSHint(cu); + assertEquals(fooPackage, hint.getResourceBundlePackage()); + } + + + + + public void testPackageHintWithoutPreviousNLSing() throws Exception { + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + String klazz = "package test;\n" + TEST_KLAZZ; + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + NLSHint hint = createNLSHint(cu); + assertEquals(pack, hint.getAccessorClassPackage()); + assertEquals(pack, hint.getResourceBundlePackage()); + } + + private IFile createResource(IPackageFragment pack, String resourceName, String content) throws Exception { + IPath path = pack.getPath().append(resourceName); + IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path); + InputStream is = new ByteArrayInputStream(content.getBytes()); + file.create(is, true, new NullProgressMonitor()); + is.close(); + return file; + } + + private NLSHint createNLSHint(ICompilationUnit cu) { + CompilationUnit unit= ASTCreator.createAST(cu, null); + return new NLSHint(cu, unit); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHolderTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHolderTest.java new file mode 100644 index 000000000..a39cddd5d --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHolderTest.java @@ -0,0 +1,72 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.dom.CompilationUnit; + +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSHint; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSSubstitution; +import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.ASTCreator; + +import org.eclipse.jdt.ui.tests.core.ProjectTestSetup; + +public class NLSHolderTest extends TestCase { + + private IJavaProject javaProject; + + private IPackageFragmentRoot fSourceFolder; + + private final static String ACCESSOR_KLAZZ= "package test;\n" + "public class TestMessages {\n" + " private static final String BUNDLE_NAME = \"test.test\";//$NON-NLS-1$\n" + " public static String getString(String s) {" + " return \"\";\n" + " }\n" + "}\n"; + + public NLSHolderTest(String arg) { + super(arg); + } + + public static Test allTests() { + return new ProjectTestSetup(new TestSuite(NLSHolderTest.class)); + } + + public static Test suite() { + return allTests(); + } + + protected void setUp() throws Exception { + javaProject= ProjectTestSetup.getProject(); + fSourceFolder= JavaProjectHelper.addSourceContainer(javaProject, "src"); + } + + protected void tearDown() throws Exception { + JavaProjectHelper.clear(javaProject, ProjectTestSetup.getDefaultClasspath()); + } + + public void testSubstitutionWithAccessor() throws Exception { + String klazz= "package test;\n" + "public class Test {" + " private String str=TestMessages.getString(\"Key.5\");//$NON-NLS-1$\n" + "}\n"; + IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + pack.createCompilationUnit("TestMessages.java", ACCESSOR_KLAZZ, false, null); + + CompilationUnit astRoot= ASTCreator.createAST(cu, null); + NLSHint hint= new NLSHint(cu, astRoot); + NLSSubstitution[] substitution= hint.getSubstitutions(); + assertEquals(substitution.length, 1); + assertEquals(substitution[0].getKey(), "Key.5"); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSScannerTester.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSScannerTester.java new file mode 100644 index 000000000..b2a30ca5c --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSScannerTester.java @@ -0,0 +1,391 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Benjamin Muskalla <b.muskalla@gmx.net> - [nls tooling] Externalize Strings Wizard should not touch annotation arguments - https://bugs.eclipse.org/bugs/show_bug.cgi?id=102132 + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSElement; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSLine; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSScanner; + + +public class NLSScannerTester extends TestCase { + + + public NLSScannerTester(String name) { + super(name); + } + + public static void main (String[] args) { + junit.textui.TestRunner.run (suite()); + } + + public static Test suite() { + return new TestSuite(NLSScannerTester.class); + } + + public void test0() throws Exception{ + String text= "fred"; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + assertEquals("empty", true, l.length == 0); //$NON-NLS-1$ + } + + public void test1() throws Exception{ + String text= "fred\"x\""; + NLSLine[] l= NLSScanner.scan(text); + assertEquals("1 line", 1, l.length); + } + + public void test1a() throws Exception{ + String text= "fred\n\"x\""; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + assertEquals("1 line", 1,l.length); //$NON-NLS-1$ + } + + public void test2() throws Exception{ + String text= "fred\"x\"\n\"xx\""; + NLSLine[] l= NLSScanner.scan(text); + assertEquals("2 line", 2,l.length); + } + + public void test2a() throws Exception{ + String text= "fred\n\"x\" \"xx\""; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + assertEquals("1 lines", 1,l.length); //$NON-NLS-1$ + } + + public void test3() throws Exception{ + String text= "fred\"x\"\n \"xx\""; + NLSLine[] l= NLSScanner.scan(text); + assertEquals("2 lines", 2,l.length); + } + + + public void test4() throws Exception{ + String text= "fred\n \"xx\""; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + assertEquals("1 line", 1,l.length); //$NON-NLS-1$ + } + + public void test5() throws Exception{ + String text= "\n \"xx\""; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + NLSLine line=l[0]; + assertEquals("1 string", 1, line.size()); //$NON-NLS-1$ + } + + public void test6() throws Exception{ + String text= "\n \"xx\" \"dff\""; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + NLSLine line=l[0]; + assertEquals("2 string", 2, line.size()); //$NON-NLS-1$ + } + + public void test7() throws Exception{ + String text= "\n \"xx\" \n\"dff\""; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + NLSLine line=l[0]; + assertEquals("1 string A", 1, line.size()); //$NON-NLS-1$ + + line= l[1]; + assertEquals("1 string B", 1, line.size()); //$NON-NLS-1$ + } + + + public void test8() throws Exception{ + String text= "\n \"xx\" \n\"dff\" \"ccc\""; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + NLSLine line=l[0]; + assertEquals("1 string A", 1, line.size()); //$NON-NLS-1$ + + line= l[1]; + assertEquals("2 strings B", 2, line.size()); //$NON-NLS-1$ + } + + public void test9() throws Exception{ + String text= "fred\n \"xx\"" + NLSElement.createTagText(1) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ + NLSLine[] l= NLSScanner.scan(text); + NLSLine line=l[0]; + NLSElement el= line.get(0); + assertEquals("has tag", true, el.hasTag()); //$NON-NLS-1$ + } + + + public void test10() throws Exception{ + String text= "fred\n \"xx\"\n"; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + NLSLine line=l[0]; + NLSElement el= line.get(0); + assertEquals("has tag", false, el.hasTag()); //$NON-NLS-1$ + } + + public void test11() throws Exception{ + String text= + "\n\"x\" \"y\"" //$NON-NLS-1$ + + NLSElement.createTagText(2) + + NLSElement.createTagText(1) + + "\n"; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + NLSLine line=l[0]; + assertEquals("2 strings", 2, line.size()); //$NON-NLS-1$ + + NLSElement el= line.get(0); + assertEquals("0 has tag", true, el.hasTag()); //$NON-NLS-1$ + + el= line.get(1); + assertEquals("1 has tag", true, el.hasTag()); //$NON-NLS-1$ + } + + public void test12() throws Exception{ + String text= + "\n\"x\" \"y\"" //$NON-NLS-1$ + + NLSElement.createTagText(1) + + NLSElement.createTagText(2) + + "\n"; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + NLSLine line=l[0]; + assertEquals("2 strings", 2, line.size()); //$NON-NLS-1$ + + NLSElement el= line.get(0); + assertEquals("0 has tag", true, el.hasTag()); //$NON-NLS-1$ + + el= line.get(1); + assertEquals("1 has tag", true, el.hasTag()); //$NON-NLS-1$ + } + + public void test13() throws Exception{ + String text= + "\n\"x\" \"y\"" //$NON-NLS-1$ + + NLSElement.createTagText(1) + + "\n"; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + NLSLine line=l[0]; + assertEquals("2 strings", 2, line.size()); //$NON-NLS-1$ + + NLSElement el= line.get(0); + assertEquals("0 has tag", true, el.hasTag()); //$NON-NLS-1$ + + el= line.get(1); + assertEquals("1 has no tag", false, el.hasTag()); //$NON-NLS-1$ + } + + public void test14() throws Exception{ + String text= + "\n\"x\" \"y\"" //$NON-NLS-1$ + + NLSElement.createTagText(2) + + "\n"; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + NLSLine line=l[0]; + assertEquals("2 strings", 2, line.size()); //$NON-NLS-1$ + + NLSElement el= line.get(0); + assertEquals("0 has no tag", false, el.hasTag()); //$NON-NLS-1$ + + el= line.get(1); + assertEquals("1 has tag", true, el.hasTag()); //$NON-NLS-1$ + } + + // test for bug 102132 + public void test15() throws Exception { + String text= "\nfoo\n@Annotation(\"bar\")\n\"baz\""; + NLSLine[] l= NLSScanner.scan(text); + + assertEquals(1, l.length); + NLSLine line= l[0]; + assertEquals(1, line.size()); + assertEquals(3, line.getLineNumber()); + assertEquals("\"baz\"", line.get(0).getValue()); + } + + // test for bug 102132 + public void test16() throws Exception { + String text = "\nfoo\n@Annotation(\n{\"bar\",\n\"baz\"})\n\"baz\""; + NLSLine[] l= NLSScanner.scan(text); + + assertEquals(1, l.length); + NLSLine line= l[0]; + assertEquals(1, line.size()); + assertEquals(5, line.getLineNumber()); + assertEquals("\"baz\"", line.get(0).getValue()); + } + + // test for bug 102132 + public void test17() throws Exception { + String text= "\n@Annotation(a= @Nested(\"Hello\"), b= \"World\")\n@Annotation2(a= (1 + 2) * 3, b= \"xx\")"; + NLSLine[] l= NLSScanner.scan(text); + assertEquals(0, l.length); + } + + // test for bug 102132 + public void test18() throws Exception { + String text= "@interface Annotation { String a= \"translate me\"; }"; + NLSLine[] l= NLSScanner.scan(text); + + assertEquals(1, l.length); + NLSLine line= l[0]; + assertEquals(1, line.size()); + assertEquals(0, line.getLineNumber()); + assertEquals("\"translate me\"", line.get(0).getValue()); + } + + // test for bug 102132 + public void test19() throws Exception { + String text= + "@interface Annotation {\r\n" + + " String a() default \"a\" + \"b\";\r\n" + + " String b() default \"bee\";\r\n" + + " String c() default true ? \"x\" : \"y\";\r\n" + + "}\r\n"; + NLSLine[] l= NLSScanner.scan(text); + assertEquals(0, l.length); + } + + // test for bug 102132 + public void test20() throws Exception { + String text= + "class C {\r\n" + + " void m() {\r\n" + + " switch (42) {\r\n" + + " default: String s= \"x\";\r\n" + + " }\r\n" + + " switch (1) {\r\n" + + " default /*standard*/: String s= \"x\";\r\n" + + " }\r\n" + + " }\r\n" + + "}"; + NLSLine[] l= NLSScanner.scan(text); + + assertEquals(2, l.length); + + NLSLine line= l[0]; + assertEquals(1, line.size()); + assertEquals(3, line.getLineNumber()); + assertEquals("\"x\"", line.get(0).getValue()); + line= l[1]; + assertEquals(1, line.size()); + assertEquals(6, line.getLineNumber()); + assertEquals("\"x\"", line.get(0).getValue()); + } + + // test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=227482 + public void test21() throws Exception { + String text= + "class C {\r\n" + + " void m() {\r\n" + + " System.out.println(new Object() {\r\n" + + " @Override\r\n" + + " public String toString() {\r\n" + + " return \"me\";\r\n" + + " };\r\n" + + " });\r\n" + + " }\r\n" + + "}"; + NLSLine[] l= NLSScanner.scan(text); + + assertEquals(1, l.length); + + NLSLine line= l[0]; + assertEquals(1, line.size()); + assertEquals(5, line.getLineNumber()); + assertEquals("\"me\"", line.get(0).getValue()); + } + + // test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=227482 + public void test22() throws Exception { + String text= + "class C {\r\n" + + " void m() {\r\n" + + " Object var= ((((new Object() {\r\n" + + " @Override\r\n" + + " public String toString() {\r\n" + + " return \"me\";\r\n" + + " };\r\n" + + " }))));\r\n" + + " }\r\n" + + "}"; + NLSLine[] l= NLSScanner.scan(text); + + assertEquals(1, l.length); + + NLSLine line= l[0]; + assertEquals(1, line.size()); + assertEquals(5, line.getLineNumber()); + assertEquals("\"me\"", line.get(0).getValue()); + } + + // test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=227482 + public void test23() throws Exception { + String text= + "class C {\r\n" + + " Object field= (new Object() {\r\n" + + " @java.lang.Override\r\n" + + " public String toString() {\r\n" + + " return \"me\";\r\n" + + " };\r\n" + + " });\r\n" + + "}"; + NLSLine[] l= NLSScanner.scan(text); + + assertEquals(1, l.length); + + NLSLine line= l[0]; + assertEquals(1, line.size()); + assertEquals(4, line.getLineNumber()); + assertEquals("\"me\"", line.get(0).getValue()); + } + + // test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=227482 + public void test24() throws Exception { + String text= + "class C {\r\n" + + " @java.lang.Deprecated int field2= (\"me\").length();\r\n" + + "}"; + NLSLine[] l= NLSScanner.scan(text); + + assertEquals(1, l.length); + + NLSLine line= l[0]; + assertEquals(1, line.size()); + assertEquals(1, line.getLineNumber()); + assertEquals("\"me\"", line.get(0).getValue()); + } + + // test for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=233905 + public void test25() throws Exception { + String text= + "@SuppressWarnings(\"unchecked\") //$NON-NLS-1$\r\n" + + "public class B {}\r\n" + + "\r\n"; + NLSLine[] l= NLSScanner.scan(text); + assertEquals(0, l.length); + } + + //regression test for bug 12600 + public void test54() throws Exception{ + String text= + "\n\"x\"" //$NON-NLS-1$ + + NLSElement.TAG_PREFIX + 1 + + "\n"; //$NON-NLS-1$ + NLSLine[] l= NLSScanner.scan(text); + NLSLine line=l[0]; + assertEquals("1 strings", 1, line.size()); //$NON-NLS-1$ + + NLSElement el= line.get(0); + assertEquals("0 has no tag", false, el.hasTag()); //$NON-NLS-1$ + } + +} + + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSSourceModifierTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSSourceModifierTest.java new file mode 100644 index 000000000..364aa618b --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSSourceModifierTest.java @@ -0,0 +1,1401 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + +import java.util.Hashtable; +import java.util.Properties; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.StringAsserts; +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.jface.preference.IPreferenceStore; + +import org.eclipse.jface.text.Document; + +import org.eclipse.ltk.core.refactoring.TextChange; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.refactoring.nls.AccessorClassCreator; +import org.eclipse.jdt.internal.corext.refactoring.nls.AccessorClassModifier; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSHint; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSSourceModifier; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSSubstitution; +import org.eclipse.jdt.internal.corext.refactoring.nls.changes.CreateTextFileChange; +import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.ASTCreator; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +import org.eclipse.jdt.ui.PreferenceConstants; +import org.eclipse.jdt.ui.tests.core.ProjectTestSetup; + +import org.eclipse.jdt.internal.ui.JavaPlugin; + +public class NLSSourceModifierTest extends TestCase { + + private IJavaProject javaProject; + + private IPackageFragmentRoot fSourceFolder; + + public static Test allTests() { + return new ProjectTestSetup(new TestSuite(NLSSourceModifierTest.class)); + } + + public static Test suite() { + return allTests(); + } + + protected void setUp() throws Exception { + Hashtable options= TestOptions.getDefaultOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); + + options.put(JavaCore.CODEASSIST_FIELD_PREFIXES, ""); + options.put(JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES, ""); + options.put(JavaCore.CODEASSIST_FIELD_SUFFIXES, ""); + options.put(JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES, ""); + + JavaCore.setOptions(options); + + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false); + store.setValue(PreferenceConstants.CODEGEN_KEYWORD_THIS, false); + + StubUtility.setCodeTemplate(CodeTemplateContextType.METHODSTUB_ID, "//TODO\n${body_statement}", null); + + javaProject = ProjectTestSetup.getProject(); + fSourceFolder = JavaProjectHelper.addSourceContainer(javaProject, "src"); + } + + protected void tearDown() throws Exception { + JavaProjectHelper.clear(javaProject, ProjectTestSetup.getDefaultClasspath()); + } + + public NLSSourceModifierTest(String name) { + super(name); + } + + public void testFromSkippedToTranslated() throws Exception { + + String klazz = + "public class Test {\n" + + " private String str=\"whatever\";\n" + + "}\n"; + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[0].setPrefix("key."); + nlsSubstitutions[0].generateKey(nlsSubstitutions, new Properties()); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", false); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "public class Test {\n" + + " private String str=Accessor.getString(\"key.0\"); //$NON-NLS-1$\n" + + "}\n", + doc.get()); + } + + public void testFromSkippedToTranslatedEclipseNew() throws Exception { + + String klazz = + "public class Test {\n" + + " private String str=\"whatever\";\n" + + "}\n"; + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[0].setPrefix("key_"); + nlsSubstitutions[0].generateKey(nlsSubstitutions, new Properties()); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "public class Test {\n" + + " private String str=Accessor.key_0;\n" + + "}\n", + doc.get()); + + CreateTextFileChange accessorChange= (CreateTextFileChange)AccessorClassCreator.create(cu, "Accessor", pack.getPath().append("Accessor.java"), pack, pack.getPath().append("test.properties"), true, nlsSubstitutions, defaultSubst, null); + String accessor= accessorChange.getPreview(); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append(" public static String key_0;\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected= buf.toString(); + StringAsserts.assertEqualStringIgnoreDelim(accessor, expected); + } + + public void testFromSkippedToNotTranslated() throws Exception { + + String klazz = + "public class Test {\n" + + " private String str=\"whatever\";\n" + + "}\n"; + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setPrefix("key."); + nlsSubstitutions[0].setState(NLSSubstitution.IGNORED); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", false); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "public class Test {\n" + + " private String str=\"whatever\"; //$NON-NLS-1$\n" + + "}\n", + doc.get()); + } + + public void testFromSkippedToNotTranslatedEclipse() throws Exception { + + String klazz = + "public class Test {\n" + + " private String str=\"whatever\";\n" + + "}\n"; + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setPrefix("key_"); + nlsSubstitutions[0].setState(NLSSubstitution.IGNORED); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "public class Test {\n" + + " private String str=\"whatever\"; //$NON-NLS-1$\n" + + "}\n", + doc.get()); + + CreateTextFileChange accessorChange= (CreateTextFileChange)AccessorClassCreator.create(cu, "Accessor", pack.getPath().append("Accessor.java"), pack, pack.getPath().append("test.properties"), true, nlsSubstitutions, NLSRefactoring.DEFAULT_SUBST_PATTERN, null); + String accessor= accessorChange.getPreview(); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append("\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected= buf.toString(); + StringAsserts.assertEqualStringIgnoreDelim(accessor, expected); + } + + /* + * TODO: the key should be 0 + */ + public void testFromNotTranslatedToTranslated() throws Exception { + + String klazz = + "public class Test {\n" + + " private String str=\"whatever\"; //$NON-NLS-1$\n" + + "}\n"; + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[0].setPrefix("key."); + nlsSubstitutions[0].generateKey(nlsSubstitutions, new Properties()); + + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", false); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "public class Test {\n" + + " private String str=Accessor.getString(\"key.0\"); //$NON-NLS-1$\n" + + "}\n", + doc.get()); + } + + public void testFromNotTranslatedToTranslatedEclipse() throws Exception { + + String klazz = + "public class Test {\n" + + " private String str=\"whatever\"; //$NON-NLS-1$\n" + + "}\n"; + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[0].setPrefix("key_"); + nlsSubstitutions[0].generateKey(nlsSubstitutions, new Properties()); + + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "public class Test {\n" + + " private String str=Accessor.key_0; \n" + + "}\n", + doc.get()); + + CreateTextFileChange accessorChange= (CreateTextFileChange)AccessorClassCreator.create(cu, "Accessor", pack.getPath().append("Accessor.java"), pack, pack.getPath().append("test.properties"), true, nlsSubstitutions, NLSRefactoring.DEFAULT_SUBST_PATTERN, null); + + String accessor= accessorChange.getPreview(); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append(" public static String key_0;\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected= buf.toString(); + StringAsserts.assertEqualStringIgnoreDelim(accessor, expected); + } + + public void testFromNotTranslatedToSkipped() throws Exception { + + String klazz = + "public class Test {\n" + + " private String str=\"whatever\"; //$NON-NLS-1$\n" + + "}\n"; + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setPrefix("key."); + nlsSubstitutions[0].setState(NLSSubstitution.INTERNALIZED); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", false); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "public class Test {\n" + + " private String str=\"whatever\"; \n" + + "}\n", + doc.get()); + } + + public void testFromNotTranslatedToSkippedEclipse() throws Exception { + + String klazz = + "public class Test {\n" + + " private String str=\"whatever\"; //$NON-NLS-1$\n" + + "}\n"; + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setPrefix("key_"); + nlsSubstitutions[0].setState(NLSSubstitution.INTERNALIZED); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "public class Test {\n" + + " private String str=\"whatever\"; \n" + + "}\n", + doc.get()); + + CreateTextFileChange accessorChange= (CreateTextFileChange)AccessorClassCreator.create(cu, "Accessor", pack.getPath().append("Accessor.java"), pack, pack.getPath().append("test.properties"), true, nlsSubstitutions, NLSRefactoring.DEFAULT_SUBST_PATTERN, null); + String accessor= accessorChange.getPreview(); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append("\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected= buf.toString(); + StringAsserts.assertEqualStringIgnoreDelim(accessor, expected); + } + + private NLSSubstitution[] getSubstitutions(ICompilationUnit cu, CompilationUnit astRoot) { + NLSHint hint= new NLSHint(cu, astRoot); + return hint.getSubstitutions(); + } + + public void testFromTranslatedToNotTranslated() throws Exception { + + String klazz = + "package test;\n" + + "public class Test {\n" + + " private String str=Accessor.getString(\"key.0\"); //$NON-NLS-1$\n" + + "}\n"; + + String accessorKlazz = + "package test;\n" + + "public class Accessor {\n" + + " private static final String BUNDLE_NAME = \"test.test\";//$NON-NLS-1$\n" + + " public static String getString(String s) {\n" + + " return \"\";\n" + + " }\n" + + "}\n"; + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Accessor.java", accessorKlazz, false, null); + cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setValue("whatever"); + nlsSubstitutions[0].setPrefix("key."); + nlsSubstitutions[0].setState(NLSSubstitution.IGNORED); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", false); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "package test;\n" + + "public class Test {\n" + + " private String str=\"whatever\"; //$NON-NLS-1$\n" + + "}\n", + doc.get()); + } + + public void testFromTranslatedToNotTranslatedEclipse() throws Exception { + + String klazz = + "package test;\n" + + "public class Test {\n" + + " private String str=Accessor.k_0;\n" + + "}\n"; + + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append("\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append(" public static String k_0;\n"); + buf.append("}\n"); + String accessorKlazz= buf.toString(); + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit accessorCu= pack.createCompilationUnit("Accessor.java", accessorKlazz, false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + IPackageFragment nlspack= fSourceFolder.createPackageFragment("org.eclipse.osgi.util", false, null); + nlspack.createCompilationUnit("NLS.java", "public class NLS {}", false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setValue("whatever"); + nlsSubstitutions[0].setPrefix("k_"); + nlsSubstitutions[0].setState(NLSSubstitution.IGNORED); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "package test;\n" + + "public class Test {\n" + + " private String str=\"whatever\"; //$NON-NLS-1$\n" + + "}\n", + doc.get()); + + TextChange accessorChange= (TextChange)AccessorClassModifier.create(accessorCu, nlsSubstitutions); + Document accessorDoc= new Document(accessorKlazz); + accessorChange.getEdit().apply(accessorDoc); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append("\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected= buf.toString(); + + assertEquals(expected, accessorDoc.get()); + } + + public void testFromTranslatedToSkipped() throws Exception { + + String klazz = + "package test;\n" + + "public class Test {\n" + + " private String str=Accessor.getString(\"key.0\"); //$NON-NLS-1$\n" + + "}\n"; + + String accessorKlazz = + "package test;\n" + + "public class Accessor {\n" + + " private static final String BUNDLE_NAME = \"test.test\";//$NON-NLS-1$\n" + + " public static String getString(String s) {\n" + + " return \"\";\n" + + " }\n" + + "}\n"; + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Accessor.java", accessorKlazz, false, null); + cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setValue("whatever"); + nlsSubstitutions[0].setState(NLSSubstitution.INTERNALIZED); + nlsSubstitutions[0].setPrefix("key."); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", false); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "package test;\n" + + "public class Test {\n" + + " private String str=\"whatever\"; \n" + + "}\n", + doc.get()); + } + + public void testFromTranslatedToSkippedEclipse() throws Exception { + + String klazz = + "package test;\n" + + "public class Test {\n" + + " private String str=Accessor.key_0;\n" + + "}\n"; + + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append("\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append(" public static String key_0;\n"); + buf.append("}\n"); + String accessorKlazz= buf.toString(); + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit accessorCu= pack.createCompilationUnit("Accessor.java", accessorKlazz, false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + IPackageFragment nlspack= fSourceFolder.createPackageFragment("org.eclipse.osgi.util", false, null); + nlspack.createCompilationUnit("NLS.java", "public class NLS {}", false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setValue("whatever"); + nlsSubstitutions[0].setState(NLSSubstitution.INTERNALIZED); + nlsSubstitutions[0].setPrefix("key_"); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "package test;\n" + + "public class Test {\n" + + " private String str=\"whatever\";\n" + + "}\n", + doc.get()); + + TextChange accessorChange= (TextChange)AccessorClassModifier.create(accessorCu, nlsSubstitutions); + Document accessorDoc= new Document(accessorKlazz); + accessorChange.getEdit().apply(accessorDoc); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append("\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected= buf.toString(); + + assertEquals(expected, accessorDoc.get()); + } + + public void testReplacementOfKey() throws Exception { + String klazz = + "package test;\n" + + "public class Test {\n" + + " private String str=Accessor.getString(\"key.0\"); //$NON-NLS-1$\n" + + "}\n"; + + String accessorKlazz = + "package test;\n" + + "public class Accessor {\n" + + " private static final String BUNDLE_NAME = \"test.test\";//$NON-NLS-1$\n" + + " public static String getString(String s) {\n" + + " return \"\";\n" + + " }\n" + + "}\n"; + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Accessor.java", accessorKlazz, false, null); + cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setPrefix("key."); + nlsSubstitutions[0].setKey("nls.0"); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", false); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "package test;\n" + + "public class Test {\n" + + " private String str=Accessor.getString(\"nls.0\"); //$NON-NLS-1$\n" + + "}\n", + doc.get()); + } + + public void testReplacementOfKeyEclipse() throws Exception { + String klazz = + "package test;\n" + + "public class Test {\n" + + " private String str=Accessor.key_0; \n" + + "}\n"; + + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append("\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append(" public static String key_0;\n"); + buf.append("}\n"); + String accessorKlazz= buf.toString(); + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit accessorCu= pack.createCompilationUnit("Accessor.java", accessorKlazz, false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + IPackageFragment nlspack= fSourceFolder.createPackageFragment("org.eclipse.osgi.util", false, null); + nlspack.createCompilationUnit("NLS.java", "public class NLS {}", false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setInitialValue("whatever"); + nlsSubstitutions[0].setValue("whatever"); + nlsSubstitutions[0].setPrefix("nls_"); + nlsSubstitutions[0].setKey("nls_0"); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "package test;\n" + + "public class Test {\n" + + " private String str=Accessor.nls_0; \n" + + "}\n", + doc.get()); + + TextChange accessorChange= (TextChange)AccessorClassModifier.create(accessorCu, nlsSubstitutions); + Document accessorDoc= new Document(accessorKlazz); + accessorChange.getEdit().apply(accessorDoc); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append("\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append(" public static String nls_0;\n"); + buf.append("}\n"); + String expected= buf.toString(); + + assertEquals(expected, accessorDoc.get()); + } + + //https://bugs.eclipse.org/bugs/show_bug.cgi?id=223865 + public void testReplacementOfKeysBug223865() throws Exception { + + String klazz= + "package test;\n" + + "public class Test {\n" + + " private String str=Accessor.key_0;\n" + + " private String str=Accessor.key_1;\n" + + "}\n"; + + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append("\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append(" public static String key_0;\n"); + buf.append(" public static String key_1;\n"); + buf.append("}\n"); + String accessorKlazz= buf.toString(); + + IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit accessorCu= pack.createCompilationUnit("Accessor.java", accessorKlazz, false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + IPackageFragment nlspack= fSourceFolder.createPackageFragment("org.eclipse.osgi.util", false, null); + nlspack.createCompilationUnit("NLS.java", "public class NLS {}", false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions= getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setValue("whatever"); + nlsSubstitutions[0].setInitialValue("whatever"); + nlsSubstitutions[0].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[0].setPrefix("key_"); + nlsSubstitutions[0].setKey("key_0"); + nlsSubstitutions[1].setValue("whatever"); + nlsSubstitutions[1].setInitialValue("whatever"); + nlsSubstitutions[1].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[1].setPrefix("key_"); + nlsSubstitutions[1].setKey("key_0"); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change= (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc= new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "package test;\n" + + "public class Test {\n" + + " private String str=Accessor.key_0;\n" + + " private String str=Accessor.key_0;\n" + + "}\n", doc.get()); + + TextChange accessorChange= (TextChange) AccessorClassModifier.create(accessorCu, nlsSubstitutions); + Document accessorDoc= new Document(accessorKlazz); + accessorChange.getEdit().apply(accessorDoc); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append("\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append(" public static String key_0;\n"); + buf.append("}\n"); + String expected= buf.toString(); + + assertEquals(expected, accessorDoc.get()); + } + + public void testBug95708_1() throws Exception { + String klazz = + "public class Test {\n" + + " private String str1=\"whatever\";\n" + + " private String str2=\"whatever\";\n" + + "}\n"; + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[0].setPrefix("key_"); + nlsSubstitutions[0].setKey("0"); + nlsSubstitutions[1].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[1].setPrefix("key_"); + nlsSubstitutions[1].setKey("0"); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "public class Test {\n" + + " private String str1=Accessor.key_0;\n" + + " private String str2=Accessor.key_0;\n" + + "}\n", + doc.get()); + + CreateTextFileChange accessorChange= (CreateTextFileChange)AccessorClassCreator.create(cu, "Accessor", pack.getPath().append("Accessor.java"), pack, pack.getPath().append("test.properties"), true, nlsSubstitutions, NLSRefactoring.DEFAULT_SUBST_PATTERN, null); + String accessor= accessorChange.getPreview(); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append(" public static String key_0;\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected= buf.toString(); + StringAsserts.assertEqualStringIgnoreDelim(accessor, expected); + } + + public void testBug95708_2() throws Exception { + String klazz = + "public class Test {\n" + + " private String str1=Accessor.key_0;\n" + + " private String str2=Accessor.key_0;\n" + + "}\n"; + + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append(" public static String key_0;\n"); + buf.append("}\n"); + String accessorKlazz= buf.toString(); + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit accessorCu= pack.createCompilationUnit("Accessor.java", accessorKlazz, false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + IPackageFragment nlspack= fSourceFolder.createPackageFragment("org.eclipse.osgi.util", false, null); + nlspack.createCompilationUnit("NLS.java", "public class NLS {}", false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setInitialValue("whatever"); + nlsSubstitutions[0].setValue("whatever"); + nlsSubstitutions[0].setPrefix("nls_"); + nlsSubstitutions[0].setKey("nls_0"); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "public class Test {\n" + + " private String str1=Accessor.nls_0;\n" + + " private String str2=Accessor.key_0;\n" + + "}\n", + doc.get()); + + TextChange accessorChange= (TextChange)AccessorClassModifier.create(accessorCu, nlsSubstitutions); + Document accessorDoc= new Document(accessorKlazz); + accessorChange.getEdit().apply(accessorDoc); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append(" public static String key_0;\n"); + buf.append(" public static String nls_0;\n"); + buf.append("}\n"); + String expected= buf.toString(); + + assertEquals(expected, accessorDoc.get()); + } + + public void testInsertionOrder1() throws Exception { + String klazz = + "public class Test {\n" + + " private String str1=Accessor.key_b;\n" + + " private String str2=Accessor.key_y;\n" + + " private String str3=\"h\";\n" + + " private String str4=\"a\";\n" + + " private String str5=\"z\";\n" + + "}\n"; + + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" public static String key_b;\n"); + buf.append(" public static String key_y;\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append("}\n"); + String accessorKlazz= buf.toString(); + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit accessorCu= pack.createCompilationUnit("Accessor.java", accessorKlazz, false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + IPackageFragment nlspack= fSourceFolder.createPackageFragment("org.eclipse.osgi.util", false, null); + nlspack.createCompilationUnit("NLS.java", "public class NLS {}", false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[4].setInitialValue("b"); + nlsSubstitutions[3].setInitialValue("y"); + nlsSubstitutions[2].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[2].setPrefix("key_"); + nlsSubstitutions[2].setKey("z"); + nlsSubstitutions[1].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[1].setPrefix("key_"); + nlsSubstitutions[1].setKey("a"); + nlsSubstitutions[0].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[0].setPrefix("key_"); + nlsSubstitutions[0].setKey("h"); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "public class Test {\n" + + " private String str1=Accessor.key_b;\n" + + " private String str2=Accessor.key_y;\n" + + " private String str3=Accessor.key_h;\n" + + " private String str4=Accessor.key_a;\n" + + " private String str5=Accessor.key_z;\n" + + "}\n", + doc.get()); + + TextChange accessorChange= (TextChange)AccessorClassModifier.create(accessorCu, nlsSubstitutions); + Document accessorDoc= new Document(accessorKlazz); + accessorChange.getEdit().apply(accessorDoc); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" public static String key_a;\n"); + buf.append(" public static String key_b;\n"); + buf.append(" public static String key_h;\n"); + buf.append(" public static String key_y;\n"); + buf.append(" public static String key_z;\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected= buf.toString(); + + assertEquals(expected, accessorDoc.get()); + } + + public void testInsertionOrder2() throws Exception { + String klazz = + "public class Test {\n" + + " private String str1=Accessor.key_b;\n" + + " private String str2=Accessor.key_y;\n" + + " private String str3=\"h\";\n" + + " private String str4=\"a\";\n" + + " private String str5=\"z\";\n" + + "}\n"; + + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" public static String key_b;\n"); + buf.append(" public static String key_y;\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append("}\n"); + String accessorKlazz= buf.toString(); + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit accessorCu= pack.createCompilationUnit("Accessor.java", accessorKlazz, false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + IPackageFragment nlspack= fSourceFolder.createPackageFragment("org.eclipse.osgi.util", false, null); + nlspack.createCompilationUnit("NLS.java", "public class NLS {}", false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[4].setInitialValue("b"); + nlsSubstitutions[4].setKey("key_i"); + nlsSubstitutions[3].setInitialValue("y"); + nlsSubstitutions[3].setKey("key_g"); + nlsSubstitutions[2].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[2].setPrefix("key_"); + nlsSubstitutions[2].setKey("z"); + nlsSubstitutions[1].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[1].setPrefix("key_"); + nlsSubstitutions[1].setKey("a"); + nlsSubstitutions[0].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[0].setPrefix("key_"); + nlsSubstitutions[0].setKey("h"); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "public class Test {\n" + + " private String str1=Accessor.key_g;\n" + + " private String str2=Accessor.key_i;\n" + + " private String str3=Accessor.key_h;\n" + + " private String str4=Accessor.key_a;\n" + + " private String str5=Accessor.key_z;\n" + + "}\n", + doc.get()); + + TextChange accessorChange= (TextChange)AccessorClassModifier.create(accessorCu, nlsSubstitutions); + Document accessorDoc= new Document(accessorKlazz); + accessorChange.getEdit().apply(accessorDoc); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" public static String key_a;\n"); + buf.append(" public static String key_g;\n"); + buf.append(" public static String key_h;\n"); + buf.append(" public static String key_i;\n"); + buf.append(" public static String key_z;\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected= buf.toString(); + + assertEquals(expected, accessorDoc.get()); + } + + public void testInsertionOrder3() throws Exception { + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" private String str1= Accessor.Test_A_1;\n"); + buf.append(" private String str2= Accessor.Test_B_1;\n"); + buf.append(" private String str3= \"str3\";\n"); + buf.append("}\n"); + String klazz= buf.toString(); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append("\n"); + buf.append(" public static String Test_B_1;\n"); + buf.append("\n"); + buf.append(" public static String Test_A_1;\n"); + buf.append("\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append("}\n"); + String accessorKlazz= buf.toString(); + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit accessorCu= pack.createCompilationUnit("Accessor.java", accessorKlazz, false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + IPackageFragment nlspack= fSourceFolder.createPackageFragment("org.eclipse.osgi.util", false, null); + nlspack.createCompilationUnit("NLS.java", "public class NLS {}", false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[2].setInitialValue("str2"); + nlsSubstitutions[2].setKey("Test_B_1"); + nlsSubstitutions[1].setInitialValue("str1"); + nlsSubstitutions[1].setKey("Test_A_1"); + nlsSubstitutions[0].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[0].setPrefix("Test_"); + nlsSubstitutions[0].setKey("B_2"); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" private String str1= Accessor.Test_A_1;\n"); + buf.append(" private String str2= Accessor.Test_B_1;\n"); + buf.append(" private String str3= Accessor.Test_B_2;\n"); + buf.append("}\n"); + String expectedKlazz= buf.toString(); + + assertEquals(expectedKlazz, doc.get()); + + TextChange accessorChange= (TextChange)AccessorClassModifier.create(accessorCu, nlsSubstitutions); + Document accessorDoc= new Document(accessorKlazz); + accessorChange.getEdit().apply(accessorDoc); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append("\n"); + buf.append(" public static String Test_B_1;\n"); + buf.append("\n"); + buf.append(" public static String Test_B_2;\n"); + buf.append("\n"); + buf.append(" public static String Test_A_1;\n"); + buf.append("\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected= buf.toString(); + + assertEquals(expected, accessorDoc.get()); + } + + public void testInsertionOrder4() throws Exception { + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" private String str1= Accessor.Test_A_a;\n"); + buf.append(" private String str2= Accessor.Test_A_b;\n"); + buf.append(" private String str3= \"str3\";\n"); + buf.append(" private String str4= \"str4\";\n"); + buf.append(" private String str5= Accessor.Test_B_b;\n"); + buf.append(" private String str6= Accessor.Test_B_c;\n"); + buf.append("}\n"); + String klazz= buf.toString(); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append("\n"); + buf.append(" public static String Test_A_a;\n"); + buf.append(" public static String Test_A_b;\n"); + buf.append("\n"); + buf.append(" public static String Test_B_b;\n"); + buf.append(" public static String Test_B_c;\n"); + buf.append("\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append("}\n"); + String accessorKlazz= buf.toString(); + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit accessorCu= pack.createCompilationUnit("Accessor.java", accessorKlazz, false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + IPackageFragment nlspack= fSourceFolder.createPackageFragment("org.eclipse.osgi.util", false, null); + nlspack.createCompilationUnit("NLS.java", "public class NLS {}", false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[0].setPrefix("Test_"); + nlsSubstitutions[0].setKey("A_z"); + nlsSubstitutions[1].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[1].setPrefix("Test_"); + nlsSubstitutions[1].setKey("B_a"); + nlsSubstitutions[2].setInitialValue("str1"); + nlsSubstitutions[2].setKey("Test_A_a"); + nlsSubstitutions[3].setInitialValue("str2"); + nlsSubstitutions[3].setKey("Test_A_b"); + nlsSubstitutions[4].setInitialValue("str5"); + nlsSubstitutions[4].setKey("Test_B_b"); + nlsSubstitutions[5].setInitialValue("str6"); + nlsSubstitutions[5].setKey("Test_B_c"); + + String defaultSubst= NLSRefactoring.DEFAULT_SUBST_PATTERN; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, defaultSubst, pack, "Accessor", true); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" private String str1= Accessor.Test_A_a;\n"); + buf.append(" private String str2= Accessor.Test_A_b;\n"); + buf.append(" private String str3= Accessor.Test_A_z;\n"); + buf.append(" private String str4= Accessor.Test_B_a;\n"); + buf.append(" private String str5= Accessor.Test_B_b;\n"); + buf.append(" private String str6= Accessor.Test_B_c;\n"); + buf.append("}\n"); + String expectedKlazz= buf.toString(); + + assertEquals(expectedKlazz, doc.get()); + + TextChange accessorChange= (TextChange)AccessorClassModifier.create(accessorCu, nlsSubstitutions); + Document accessorDoc= new Document(accessorKlazz); + accessorChange.getEdit().apply(accessorDoc); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import org.eclipse.osgi.util.NLS;\n"); + buf.append("public class Accessor extends NLS {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append("\n"); + buf.append(" public static String Test_A_a;\n"); + buf.append(" public static String Test_A_b;\n"); + buf.append(" public static String Test_A_z;\n"); + buf.append("\n"); + buf.append(" public static String Test_B_a;\n"); + buf.append(" public static String Test_B_b;\n"); + buf.append(" public static String Test_B_c;\n"); + buf.append("\n"); + buf.append(" static {\n"); + buf.append(" // initialize resource bundle\n"); + buf.append(" NLS.initializeMessages(BUNDLE_NAME, Accessor.class);\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected= buf.toString(); + + assertEquals(expected, accessorDoc.get()); + } + + public void testBug131323() throws Exception { + + String klazz = + "public class Test {\n" + + " private String str=\"whatever\";\n" + + "}\n"; + + IPackageFragment pack = fSourceFolder.createPackageFragment("test", false, null); + ICompilationUnit cu= pack.createCompilationUnit("Test.java", klazz, false, null); + + CompilationUnit astRoot= createAST(cu); + NLSSubstitution[] nlsSubstitutions = getSubstitutions(cu, astRoot); + nlsSubstitutions[0].setState(NLSSubstitution.EXTERNALIZED); + nlsSubstitutions[0].setPrefix("key."); + nlsSubstitutions[0].generateKey(nlsSubstitutions, new Properties()); + + String subpattern= "getFoo(${key})"; + TextChange change = (TextChange) NLSSourceModifier.create(cu, nlsSubstitutions, subpattern, pack, "Accessor", false); + + Document doc = new Document(klazz); + change.getEdit().apply(doc); + + assertEquals( + "public class Test {\n" + + " private String str=Accessor.getFoo(\"key.0\"); //$NON-NLS-1$\n" + + "}\n", + doc.get()); + + CreateTextFileChange accessorChange= (CreateTextFileChange)AccessorClassCreator.create(cu, "Accessor", pack.getPath().append("Accessor.java"), pack, pack.getPath().append("test.properties"), false, nlsSubstitutions, subpattern, null); + String accessor= accessorChange.getPreview(); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("\n"); + buf.append("import java.util.MissingResourceException;\n"); + buf.append("import java.util.ResourceBundle;\n"); + buf.append("\n"); + buf.append("public class Accessor {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.test\"; //$NON-NLS-1$\n"); + buf.append("\n"); + buf.append(" private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle\n"); + buf.append(" .getBundle(BUNDLE_NAME);\n"); + buf.append("\n"); + buf.append(" private Accessor() {\n"); + buf.append(" }\n"); + buf.append(" public static String getFoo(String key) {\n"); + buf.append(" try {\n"); + buf.append(" return RESOURCE_BUNDLE.getString(key);\n"); + buf.append(" } catch (MissingResourceException e) {\n"); + buf.append(" return '!' + key + '!';\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected= buf.toString(); + StringAsserts.assertEqualStringIgnoreDelim(accessor, expected); + } + + private CompilationUnit createAST(ICompilationUnit cu) { + return ASTCreator.createAST(cu, null); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSSubstitutionTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSSubstitutionTest.java new file mode 100644 index 000000000..e6c7e37d1 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSSubstitutionTest.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + +import java.util.Properties; + +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSSubstitution; + +public class NLSSubstitutionTest extends TestCase { + + public NLSSubstitutionTest(String name) { + super(name); + } + + public static TestSuite suite() { + return new TestSuite(NLSSubstitutionTest.class); + } + + public void testGeneratedKey() { + NLSSubstitution[] substitutions = { + new NLSSubstitution(NLSSubstitution.EXTERNALIZED, "key.0", "v1", null, null), + new NLSSubstitution(NLSSubstitution.EXTERNALIZED, "key.2", "v2", null, null) + }; + setPrefix("key.", substitutions); + + NLSSubstitution subs = new NLSSubstitution(NLSSubstitution.IGNORED, "v1", null); + subs.setState(NLSSubstitution.EXTERNALIZED); + subs.setPrefix("key."); + subs.generateKey(substitutions, new Properties()); + assertEquals("key.1", subs.getKey()); + } + + public void testGeneratedKey2() { + NLSSubstitution[] substitutions = { + new NLSSubstitution(NLSSubstitution.EXTERNALIZED, "key.0", "v1", null, null), + new NLSSubstitution(NLSSubstitution.INTERNALIZED, "v2", null) + }; + substitutions[1].setState(NLSSubstitution.EXTERNALIZED); + setPrefix("key.", substitutions); + substitutions[1].generateKey(substitutions, new Properties()); + + NLSSubstitution subs = new NLSSubstitution(NLSSubstitution.IGNORED, "v1", null); + subs.setState(NLSSubstitution.EXTERNALIZED); + subs.setPrefix("key."); + subs.generateKey(substitutions, new Properties()); + assertEquals("key.2", subs.getKey()); + } + + public void testGeneratedKeyBug202815() { + NLSSubstitution substitution= new NLSSubstitution(NLSSubstitution.IGNORED, "v1", null); + substitution.setState(NLSSubstitution.EXTERNALIZED); + substitution.setPrefix("key."); + + Properties properties= new Properties(); + properties.put("key.0", "v0"); + + substitution.generateKey(new NLSSubstitution[] { substitution }, properties); + assertEquals("key.1", substitution.getKey()); + } + + public void testGetKeyWithoutPrefix() { + NLSSubstitution substitution = new NLSSubstitution(NLSSubstitution.EXTERNALIZED, "key", "value", null, null); + substitution.setPrefix("test."); + assertEquals("key", substitution.getKey()); + } + + public void testGetKeyWithPrefix() { + NLSSubstitution substitution = new NLSSubstitution(NLSSubstitution.INTERNALIZED, "value", null); + substitution.setState(NLSSubstitution.EXTERNALIZED); + substitution.setKey("key"); + substitution.setPrefix("test."); + assertEquals("test.key", substitution.getKey()); + } + + private void setPrefix(String prefix, NLSSubstitution[] subs) { + for (int i= 0; i < subs.length; i++) + subs[i].setPrefix(prefix); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringCheckFinalConditionsTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringCheckFinalConditionsTest.java new file mode 100644 index 000000000..082c749ba --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringCheckFinalConditionsTest.java @@ -0,0 +1,190 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + +import java.util.Properties; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.core.resources.IFile; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; + +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSMessages; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSSubstitution; +import org.eclipse.jdt.internal.corext.util.Messages; + +import org.eclipse.jdt.ui.tests.core.ProjectTestSetup; + +import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; + +public class NlsRefactoringCheckFinalConditionsTest extends TestCase { + + //private IPath fPropertyFilePath; + private IPackageFragment fAccessorPackage; + private String fAccessorClassName; + private String fSubstitutionPattern; + private NlsRefactoringTestHelper fHelper; + private IJavaProject javaProject; + private IPackageFragment fResourceBundlePackage; + private String fResourceBundleName; + + public NlsRefactoringCheckFinalConditionsTest(String name) { + super(name); + } + + public static Test allTests() { + return new ProjectTestSetup(new TestSuite(NlsRefactoringCheckFinalConditionsTest.class)); + } + + public static Test suite() { + return allTests(); + } + + protected void setUp() throws Exception { + javaProject= ProjectTestSetup.getProject(); + fHelper= new NlsRefactoringTestHelper(javaProject); + } + + protected void tearDown() throws Exception { + JavaProjectHelper.clear(javaProject, ProjectTestSetup.getDefaultClasspath()); + } + + public void testCheckInputWithoutExistingPropertiesFile() throws Exception { + ICompilationUnit cu= fHelper.getCu("/TestSetupProject/src1/p/WithStrings.java"); + IFile propertyFile= fHelper.getFile("/TestSetupProject/src2/p/test.properties"); + propertyFile.delete(false, fHelper.fNpm); + initDefaultValues(); + + RefactoringStatus res= createCheckInputStatus(cu); + + assertFalse("should info about properties", res.isOK()); + + assertEquals("one info", 1, res.getEntries().length); + RefactoringStatusEntry help= res.getEntryAt(0); + assertEquals("info", RefactoringStatus.INFO, help.getSeverity()); + assertEquals(Messages.format(NLSMessages.NLSRefactoring_will_be_created, BasicElementLabels.getPathLabel(propertyFile.getFullPath(), false)), help.getMessage()); + } + + /* + * no substitutions -> nothing to do + */ + public void testCheckInputWithNoSubstitutions() throws Exception { + ICompilationUnit cu= fHelper.getCu("/TestSetupProject/src1/p/WithoutStrings.java"); //$NON-NLS-1$ + initDefaultValues(); + + checkNothingToDo(createCheckInputStatus(cu)); + } + + /* + * substitution checks + */ + public void testCheckInputWithSubstitutionPatterns() throws Exception { + ICompilationUnit cu= fHelper.getCu("/TestSetupProject/src1/p/WithStrings.java"); //$NON-NLS-1$ + initDefaultValues(); + + fSubstitutionPattern= ""; //$NON-NLS-1$ + + RefactoringStatus res= createCheckInputStatus(cu); + + RefactoringStatusEntry[] results= res.getEntries(); + + assertEquals("substitution pattern must be given", 2, results.length); //$NON-NLS-1$ + assertEquals("first is fatal", RefactoringStatus.ERROR, results[0].getSeverity()); //$NON-NLS-1$ + assertEquals("right fatal message", //$NON-NLS-1$ + NLSMessages.NLSRefactoring_pattern_empty, + results[0].getMessage()); + + assertEquals("warning no key given", RefactoringStatus.WARNING, //$NON-NLS-1$ + results[1].getSeverity()); + assertEquals("right warning message", //$NON-NLS-1$ + Messages.format(NLSMessages.NLSRefactoring_pattern_does_not_contain, + "${key}"), results[1].getMessage()); //$NON-NLS-1$ + + fSubstitutionPattern= "blabla${key}"; //$NON-NLS-1$ + res= createCheckInputStatus(cu); + assertTrue("substitution pattern ok", res.isOK()); //$NON-NLS-1$ + + fSubstitutionPattern= "${key}blabla${key}"; //$NON-NLS-1$ + res= createCheckInputStatus(cu); + assertFalse("substitution pattern ko", res.isOK()); //$NON-NLS-1$ + + results= res.getEntries(); + assertEquals("one warning", 1, results.length); //$NON-NLS-1$ + assertEquals("warning", RefactoringStatus.WARNING, results[0].getSeverity()); //$NON-NLS-1$ + assertEquals("warning message", //$NON-NLS-1$ + Messages.format(NLSMessages.NLSRefactoring_Only_the_first_occurrence_of, + "${key}"), results[0].getMessage()); //$NON-NLS-1$ + + // check for duplicate keys???? + // check for keys already defined + // check for keys + } + + private RefactoringStatus createCheckInputStatus(ICompilationUnit cu) throws CoreException { + NLSRefactoring refac= prepareRefac(cu); + RefactoringStatus res= refac.checkFinalConditions(fHelper.fNpm); + return res; + } + + private void initDefaultValues() { + //fPropertyFilePath= fHelper.getFile("/TestSetupProject/src2/p/test.properties").getFullPath(); //$NON-NLS-1$ + fResourceBundlePackage= fHelper.getPackageFragment("/TestSetupProject/src2/p"); + fResourceBundleName= "test.properties"; + fAccessorPackage= fHelper.getPackageFragment("/TestSetupProject/src1/p"); //$NON-NLS-1$ + fAccessorClassName= "Help"; //$NON-NLS-1$ + fSubstitutionPattern= "${key}"; //$NON-NLS-1$ + } + + private NLSRefactoring prepareRefac(ICompilationUnit cu) { + NLSRefactoring refac= NLSRefactoring.create(cu); + NLSSubstitution[] subs= refac.getSubstitutions(); + refac.setPrefix(""); + for (int i= 0; i < subs.length; i++) { + subs[i].setState(NLSSubstitution.EXTERNALIZED); + subs[i].generateKey(subs, new Properties()); + } + fillInValues(refac); + return refac; + } + + private void checkNothingToDo(RefactoringStatus status) { + assertEquals("fatal error expected", 1, status.getEntries().length); //$NON-NLS-1$ + + RefactoringStatusEntry fatalError= status.getEntryAt(0); + assertEquals("fatalerror", RefactoringStatus.FATAL, fatalError.getSeverity()); //$NON-NLS-1$ + assertEquals("errormessage", //$NON-NLS-1$ + NLSMessages.NLSRefactoring_nothing_to_do, + fatalError.getMessage()); + } + + private void fillInValues(NLSRefactoring refac) { + refac.setAccessorClassPackage(fAccessorPackage); + //refac.setPropertyFilePath(fPropertyFilePath); + refac.setResourceBundleName(fResourceBundleName); + refac.setResourceBundlePackage(fResourceBundlePackage); + refac.setAccessorClassName(fAccessorClassName); + refac.setSubstitutionPattern(fSubstitutionPattern); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringCheckInitialConditionsTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringCheckInitialConditionsTest.java new file mode 100644 index 000000000..cc9c99b98 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringCheckInitialConditionsTest.java @@ -0,0 +1,74 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; + +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring; + +import org.eclipse.jdt.ui.tests.core.ProjectTestSetup; + +public class NlsRefactoringCheckInitialConditionsTest extends TestCase { + + private NlsRefactoringTestHelper fHelper; + private IJavaProject javaProject; + + public NlsRefactoringCheckInitialConditionsTest(String name) { + super(name); + } + + public static Test allTests() { + return new ProjectTestSetup(new TestSuite(NlsRefactoringCheckInitialConditionsTest.class)); + } + + public static Test suite() { + return allTests(); + } + + protected void setUp() throws Exception { + javaProject= ProjectTestSetup.getProject(); + fHelper= new NlsRefactoringTestHelper(javaProject); + } + + protected void tearDown() throws Exception { + JavaProjectHelper.clear(javaProject, ProjectTestSetup.getDefaultClasspath()); + } + + protected String getRefactoringPath() { + return "nls/"; //$NON-NLS-1$ + } + + public void testActivationWithoutStrings() throws Exception { + ICompilationUnit cu= fHelper.getCu("/TestSetupProject/src1/p/WithoutStrings.java"); //$NON-NLS-1$ + Refactoring refac= NLSRefactoring.create(cu); + + RefactoringStatus res= refac.checkInitialConditions(fHelper.fNpm); + assertFalse("no nls needed", res.isOK()); //$NON-NLS-1$ + } + + public void testActivationWithStrings() throws Exception { + ICompilationUnit cu= fHelper.getCu("/TestSetupProject/src1/p/WithStrings.java"); //$NON-NLS-1$ + Refactoring refac= NLSRefactoring.create(cu); + + RefactoringStatus res= refac.checkInitialConditions(fHelper.fNpm); + assertTrue("nls needed", res.isOK()); //$NON-NLS-1$ + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringCreateChangeTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringCreateChangeTest.java new file mode 100644 index 000000000..990c6abc5 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringCreateChangeTest.java @@ -0,0 +1,706 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.Properties; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; + +import org.eclipse.ltk.core.refactoring.Change; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaModelException; + +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring; +import org.eclipse.jdt.internal.corext.refactoring.nls.NLSSubstitution; + +import org.eclipse.jdt.ui.tests.core.ProjectTestSetup; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; + +public class NlsRefactoringCreateChangeTest extends TestCase { + + private NlsRefactoringTestHelper fHelper; + private IJavaProject fJavaProject; + private IPackageFragmentRoot fSourceFolder; + + public NlsRefactoringCreateChangeTest(String name) { + super(name); + } + + public static Test allTests() { + return setUpTest(new TestSuite(NlsRefactoringCreateChangeTest.class)); + } + + public static Test setUpTest(Test test) { + return new ProjectTestSetup(test); + } + + public static Test suite() { + return allTests(); + } + + protected void setUp() throws Exception { + fJavaProject= ProjectTestSetup.getProject(); + fSourceFolder= JavaProjectHelper.addSourceContainer(fJavaProject, "src"); + fHelper= new NlsRefactoringTestHelper(fJavaProject); + } + + protected void tearDown() throws Exception { + JavaProjectHelper.clear(fJavaProject, ProjectTestSetup.getDefaultClasspath()); + } + + public void testWithoutPreviousNlsing() throws Exception { + + fHelper.createPackageFragment("p2", "/TestSetupProject/src2"); //$NON-NLS-1$//$NON-NLS-2$ + + ICompilationUnit cu= RefactoringTest.createCU(fHelper.getPackageFragment("/TestSetupProject/src1/p"), "Test.java", //$NON-NLS-1$//$NON-NLS-2$ + "package p;\r\nclass Test {String hello=\"helloworld\";}"); //$NON-NLS-1$ + + NLSRefactoring nls= createDefaultNls(cu); + nls.setAccessorClassPackage(fHelper.getPackageFragment("/TestSetupProject/src2/p2")); //$NON-NLS-1$ + + performChange(nls); + + checkContentOfCu("manipulated class", cu, "package p;\r\n\r\nimport p2.Messages;\r\n\r\nclass Test {String hello=Messages.getString(\"test0\");} //$NON-NLS-1$"); //$NON-NLS-1$ //$NON-NLS-2$ + checkContentOfFile("properties", fHelper.getFile("/TestSetupProject/src2/p/test.properties"), "test0=helloworld\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + + public void testCreateChangeWithCollidingImport() throws Exception { + String testClass= "package p;\n" + "import p.another.Messages;\n" + "class Test {" + "String hello=\"helloworld\";\r\n" + "}"; + ICompilationUnit cu= RefactoringTest.createCU(fHelper.getPackageFragment("/TestSetupProject/src1/p"), "Test.java", testClass); //$NON-NLS-1$ //$NON-NLS-2$ + + NLSRefactoring nls= createDefaultNls(cu); + + performChange(nls); + + checkContentOfCu("manipulated class", cu, "package p;\n" + "import p.another.Messages;\n" + "class Test {" + "String hello=p.Messages.getString(\"test0\"); //$NON-NLS-1$\n" + "}"); + checkContentOfFile("properties", fHelper.getFile("/TestSetupProject/src2/p/test.properties"), "test0=helloworld\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + + // BUG 59156 + public void testCreateChangeWithExistingAccessorclassInDifferentPackage() throws Exception { + String accessorKlazz= "package test;\n" + "public class Accessor {\n" + " private static final String BUNDLE_NAME = \"test.test\";//$NON-NLS-1$\n" + " public static String getString(String s) {\n" + " return \"\";\n" + " }\n" + "}\n"; + RefactoringTest.createCU(fHelper.getPackageFragment("/TestSetupProject/src1/p"), "Accessor.java", accessorKlazz); + + String nlsMe= "package test;\n" + "class Test {\n" + " String hello=\"helloworld\";\n" + "}\n"; + fHelper.createPackageFragment("test", "/TestSetupProject/src1"); + ICompilationUnit testClass= RefactoringTest.createCU(fHelper.getPackageFragment("/TestSetupProject/src1/test"), "AClass.java", nlsMe); + + NLSRefactoring nls= NLSRefactoring.create(testClass); + + nls.setAccessorClassPackage(fHelper.getPackageFragment("/TestSetupProject/src1/p")); + nls.setResourceBundlePackage(fHelper.getPackageFragment("/TestSetupProject/src2/p")); + nls.setResourceBundleName("test.properties"); + nls.setAccessorClassName("Accessor"); + + NLSSubstitution[] substitutions= nls.getSubstitutions(); + nls.setPrefix("test"); + substitutions[0].setState(NLSSubstitution.EXTERNALIZED); + substitutions[0].generateKey(substitutions, new Properties()); + + performChange(nls); + + checkContentOfCu("manipulated class", testClass, "package test;\n\n" + "import p.Accessor;\n\n" + "class Test {\n" + " String hello=Accessor.getString(\"test0\"); //$NON-NLS-1$\n" + "}\n"); + } + + public void testCreateChangeWithNonDefaultSubstitution() throws Exception { + ICompilationUnit cu= RefactoringTest.createCU(fHelper.getPackageFragment("/TestSetupProject/src1/p"), "Test.java", //$NON-NLS-1$ //$NON-NLS-2$ + "package p;\nimport p.another.Messages;\nclass Test {String hello=\"helloworld\";}"); //$NON-NLS-1$ + NLSRefactoring nls= createDefaultNls(cu); + + String string= "nonDefault(" + NLSRefactoring.KEY + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + nls.setSubstitutionPattern(string); + + performChange(nls); + checkContentOfCu("manipulated class", //$NON-NLS-1$ + cu, "package p;\nimport p.another.Messages;\nclass Test {String hello=p.Messages.nonDefault(\"test0\");} //$NON-NLS-1$"); //$NON-NLS-1$ + checkContentOfFile("properties", fHelper.getFile("/TestSetupProject/src2/p/test.properties"), "test0=helloworld\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } + + private void createDefaultAccessor(IPackageFragment pack1) throws JavaModelException { + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Accessor {\n"); + buf.append(" private static final String BUNDLE_NAME = \"test.Accessor\";//$NON-NLS-1$\n"); + buf.append(" public static String getString(String s) {\n"); + buf.append(" return null;\n"); + buf.append(" }\n"); + buf.append("}\n"); + pack1.createCompilationUnit("Accessor.java", buf.toString(), false, null); + } + + public void testExternalizedToIgnore() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + + // Accessor class + createDefaultAccessor(pack1); + + // property file + StringBuffer buf= new StringBuffer(); + buf.append("A.1=Hello1\n"); + buf.append("A.2=Hello2\n"); + buf.append("A.3=Hello3\n"); + IFile file= createPropertyFile(pack1, "Accessor.properties", buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"A.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"A.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= Accessor.getString(\"A.3\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + ICompilationUnit cu = pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + NLSRefactoring nls= NLSRefactoring.create(cu); + + NLSSubstitution[] substitutions= nls.getSubstitutions(); + assertEquals("number of substitutions", 3, substitutions.length); + substitutions[0].setState(NLSSubstitution.IGNORED); + + performChange(nls); + + buf= new StringBuffer(); + buf.append("A.2=Hello2\n"); + buf.append("A.3=Hello3\n"); + checkContentOfFile("property file", file, buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= \"Hello1\"; //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"A.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= Accessor.getString(\"A.3\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + checkContentOfCu("nls file", cu, buf.toString()); + } + + public void testInsertToDuplicate() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + + // Accessor class + createDefaultAccessor(pack1); + + // property file + StringBuffer buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + IFile file= createPropertyFile(pack1, "Accessor.properties", buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= \"Hello1\";\n"); + buf.append("}\n"); + ICompilationUnit cu = pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + NLSRefactoring nls= NLSRefactoring.create(cu); + + NLSSubstitution[] substitutions= nls.getSubstitutions(); + assertEquals("number of substitutions", 3, substitutions.length); + NLSSubstitution sub= substitutions[2]; + + sub.setState(NLSSubstitution.EXTERNALIZED); + sub.setKey("1"); + + performChange(nls); + + buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + checkContentOfFile("property file", file, buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + checkContentOfCu("nls file", cu, buf.toString()); + } + + public void testRenameToDuplicate() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + + // Accessor class + createDefaultAccessor(pack1); + + // property file + StringBuffer buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + buf.append("Test.3=Hello3\n"); + IFile file= createPropertyFile(pack1, "Accessor.properties", buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= Accessor.getString(\"Test.3\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + ICompilationUnit cu = pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + NLSRefactoring nls= NLSRefactoring.create(cu); + + NLSSubstitution[] substitutions= nls.getSubstitutions(); + assertEquals("number of substitutions", 3, substitutions.length); + NLSSubstitution sub= substitutions[2]; + sub.setKey("Test.1"); + sub.setValue("Hello1"); + + performChange(nls); + + buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + checkContentOfFile("property file", file, buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + checkContentOfCu("nls file", cu, buf.toString()); + } + + public void testRenameDuplicate() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + + // Accessor class + createDefaultAccessor(pack1); + + // property file + StringBuffer buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + IFile file= createPropertyFile(pack1, "Accessor.properties", buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + ICompilationUnit cu = pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + NLSRefactoring nls= NLSRefactoring.create(cu); + + NLSSubstitution[] substitutions= nls.getSubstitutions(); + assertEquals("number of substitutions", 3, substitutions.length); + NLSSubstitution sub= substitutions[2]; + sub.setKey("Test.3"); + sub.setValue("Hello3"); + + performChange(nls); + + buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + buf.append("Test.3=Hello3\n"); + checkContentOfFile("property file", file, buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= Accessor.getString(\"Test.3\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + checkContentOfCu("nls file", cu, buf.toString()); + } + + public void testInternalizeDuplicate() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + + // Accessor class + createDefaultAccessor(pack1); + + // property file + StringBuffer buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + IFile file= createPropertyFile(pack1, "Accessor.properties", buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + ICompilationUnit cu = pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + NLSRefactoring nls= NLSRefactoring.create(cu); + + NLSSubstitution[] substitutions= nls.getSubstitutions(); + assertEquals("number of substitutions", 3, substitutions.length); + NLSSubstitution sub= substitutions[2]; + sub.setState(NLSSubstitution.INTERNALIZED); + + performChange(nls); + + buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + checkContentOfFile("property file", file, buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= \"Hello1\"; \n"); + buf.append("}\n"); + checkContentOfCu("nls file", cu, buf.toString()); + } + + public void testInternalizeAndInsert() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + + // Accessor class + createDefaultAccessor(pack1); + + // property file + StringBuffer buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + IFile file= createPropertyFile(pack1, "Accessor.properties", buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= \"Hello1\";\n"); + buf.append("}\n"); + ICompilationUnit cu = pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + NLSRefactoring nls= NLSRefactoring.create(cu); + + NLSSubstitution[] substitutions= nls.getSubstitutions(); + assertEquals("number of substitutions", 3, substitutions.length); + NLSSubstitution sub= substitutions[0]; + sub.setState(NLSSubstitution.INTERNALIZED); + + NLSSubstitution sub2= substitutions[2]; + sub2.setState(NLSSubstitution.EXTERNALIZED); + sub2.setKey("1"); + + performChange(nls); + + buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + checkContentOfFile("property file", file, buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= \"Hello1\"; \n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + checkContentOfCu("nls file", cu, buf.toString()); + } + + + public void testAddMissing1() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + + // Accessor class + createDefaultAccessor(pack1); + + // property file + StringBuffer buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + IFile file= createPropertyFile(pack1, "Accessor.properties", buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= Accessor.getString(\"Test.3\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + ICompilationUnit cu = pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + NLSRefactoring nls= NLSRefactoring.create(cu); + + NLSSubstitution[] substitutions= nls.getSubstitutions(); + assertEquals("number of substitutions", 3, substitutions.length); + NLSSubstitution sub= substitutions[2]; + sub.setValue("Hello3"); + + performChange(nls); + + buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + buf.append("Test.3=Hello3\n"); + checkContentOfFile("property file", file, buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= Accessor.getString(\"Test.3\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + checkContentOfCu("nls file", cu, buf.toString()); + } + + public void testAddMissing2() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + + // Accessor class + createDefaultAccessor(pack1); + + // property file + StringBuffer buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + IFile file= createPropertyFile(pack1, "Accessor.properties", buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= Accessor.getString(\"Test.3\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + ICompilationUnit cu = pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + NLSRefactoring nls= NLSRefactoring.create(cu); + + NLSSubstitution[] substitutions= nls.getSubstitutions(); + assertEquals("number of substitutions", 3, substitutions.length); + NLSSubstitution sub= substitutions[1]; + sub.setValue("Hello22"); + + NLSSubstitution sub2= substitutions[2]; + sub2.setValue("Hello3"); + + performChange(nls); + + buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello22\n"); + buf.append("Test.3=Hello3\n"); + checkContentOfFile("property file", file, buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello3= Accessor.getString(\"Test.3\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + checkContentOfCu("nls file", cu, buf.toString()); + } + + public void testNoNewLineAtEnd() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + + // Accessor class + createDefaultAccessor(pack1); + + // property file + StringBuffer buf= new StringBuffer(); + buf.append("Test.1=Hello1"); + IFile file= createPropertyFile(pack1, "Accessor.properties", buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= \"Hello2\";\n"); + buf.append("}\n"); + ICompilationUnit cu = pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + NLSRefactoring nls= NLSRefactoring.create(cu); + + NLSSubstitution[] substitutions= nls.getSubstitutions(); + assertEquals("number of substitutions", 2, substitutions.length); + NLSSubstitution sub= substitutions[1]; + sub.setState(NLSSubstitution.EXTERNALIZED); + sub.setKey("2"); + + performChange(nls); + + buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + checkContentOfFile("property file", file, buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + checkContentOfCu("nls file", cu, buf.toString()); + } + + public void testTwoInsertsNoNewLineAtEnd() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + + // Accessor class + createDefaultAccessor(pack1); + + // property file + StringBuffer buf= new StringBuffer(); + buf.append("Test.1=Hello1"); + IFile file= createPropertyFile(pack1, "Accessor.properties", buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= \"Hello2\";\n"); + buf.append(" String hello2= \"Hello3\";\n"); + buf.append("}\n"); + ICompilationUnit cu = pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + NLSRefactoring nls= NLSRefactoring.create(cu); + + NLSSubstitution[] substitutions= nls.getSubstitutions(); + assertEquals("number of substitutions", 3, substitutions.length); + NLSSubstitution sub= substitutions[1]; + sub.setState(NLSSubstitution.EXTERNALIZED); + sub.setKey("2"); + + sub= substitutions[2]; + sub.setState(NLSSubstitution.EXTERNALIZED); + sub.setKey("3"); + + performChange(nls); + + buf= new StringBuffer(); + buf.append("Test.1=Hello1\n"); + buf.append("Test.2=Hello2\n"); + buf.append("Test.3=Hello3\n"); + checkContentOfFile("property file", file, buf.toString()); + + // class to NLS + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" String hello1= Accessor.getString(\"Test.1\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.2\"); //$NON-NLS-1$\n"); + buf.append(" String hello2= Accessor.getString(\"Test.3\"); //$NON-NLS-1$\n"); + buf.append("}\n"); + checkContentOfCu("nls file", cu, buf.toString()); + } + + private IFile createPropertyFile(IPackageFragment pack, String name, String content) throws UnsupportedEncodingException, CoreException { + ByteArrayInputStream is= new ByteArrayInputStream(content.getBytes("8859_1")); + IFile file= ((IFolder) pack.getResource()).getFile(name); + file.create(is, false, null); + return file; + } + + private void checkContentOfCu(String message, ICompilationUnit cu, String content) throws Exception { + RefactoringTest.assertEqualLines(message, content, cu.getBuffer().getContents()); + } + + private void checkContentOfFile(String message, IFile file, String content) throws Exception { + InputStream in= file.getContents(); + try { + String realContent= copyToString(in); + RefactoringTest.assertEqualLines(message, content, realContent); + } finally { + in.close(); + } + } + + private String copyToString(InputStream in) throws Exception { + ByteArrayOutputStream out= new ByteArrayOutputStream(); + int read= in.read(); + while (read != -1) { + out.write(read); + read= in.read(); + } + out.close(); + return out.toString(); + } + + private NLSRefactoring createDefaultNls(ICompilationUnit cu) { + NLSRefactoring nls= NLSRefactoring.create(cu); + + nls.setAccessorClassPackage(fHelper.getPackageFragment("/TestSetupProject/src1/p")); //$NON-NLS-1$ + nls.setResourceBundlePackage(fHelper.getPackageFragment("/TestSetupProject/src2/p")); + nls.setResourceBundleName("test.properties"); + //nls.setPropertyFilePath(fHelper.getFile("/TestSetupProject/src2/p/test.properties").getFullPath()); //$NON-NLS-1$ + nls.setAccessorClassName("Messages"); //$NON-NLS-1$ + + NLSSubstitution[] substitutions= nls.getSubstitutions(); + nls.setPrefix("test"); + substitutions[0].setState(NLSSubstitution.EXTERNALIZED); + substitutions[0].generateKey(substitutions, new Properties()); + return nls; + } + + private void performChange(NLSRefactoring nls) throws CoreException { + nls.checkInitialConditions(fHelper.fNpm); + nls.checkFinalConditions(fHelper.fNpm); + Change c= nls.createChange(fHelper.fNpm); + c.initializeValidationData(fHelper.fNpm); + try { + c.perform(fHelper.fNpm); + } finally { + c.dispose(); + } + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringTestHelper.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringTestHelper.java new file mode 100644 index 000000000..d01017f2b --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NlsRefactoringTestHelper.java @@ -0,0 +1,121 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.HashMap; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +/** + * Helper class for the nls-tests. + * + * often used functionality is located here to get around extending testcases + * from testcases (just for code reuse). + */ +public class NlsRefactoringTestHelper { + + NullProgressMonitor fNpm; + + private HashMap fWorkSpaceElements = new HashMap(); + private IJavaProject fJavaProject; + + public NlsRefactoringTestHelper(IJavaProject javaProject) throws Exception { + fJavaProject = javaProject; + fNpm = new NullProgressMonitor(); + fWorkSpaceElements = new HashMap(); + setupTestSpace(); + } + + private InputStream getInputStream(String input) { + return new ByteArrayInputStream(input.getBytes()); + } + + private void setupTestSpace() throws Exception { + fWorkSpaceElements.put(fJavaProject.getPath().toString(), fJavaProject); + + createPackageFragmentRoot(fJavaProject, "src1"); + createPackageFragmentRoot(fJavaProject, "src2"); + + createPackageFragment("p", "/TestSetupProject/src1"); + createPackageFragment("p", "/TestSetupProject/src2"); + + createFile("/TestSetupProject/src2/p", "test.properties", ""); + createCu("/TestSetupProject/src1/p", "WithStrings.java", "package p;class WithStrings {String s1=\"test1\";String s2=\"test2\";}"); + createCu("/TestSetupProject/src1/p", "WithoutStrings.java", "package p;class WithoutStrings {}"); + + String newFileTemplate= "${package_declaration}\n\n${type_declaration}"; + StubUtility.setCodeTemplate(CodeTemplateContextType.NEWTYPE_ID, newFileTemplate, null); + StubUtility.setCodeTemplate(CodeTemplateContextType.TYPECOMMENT_ID, "", null); + + } + + private void createFile(String packageFragmentName, String fileName, String content) throws Exception { + IPackageFragment fragment = (IPackageFragment) fWorkSpaceElements.get(packageFragmentName); + IPath p = fragment.getPath().append(fileName); + IFile file = createFile(p, content); + fWorkSpaceElements.put(file.getFullPath().toString(), file); + } + + private IFile createFile(IPath path, String content) throws Exception { + IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path); + InputStream iS = getInputStream(content); + file.create(iS, true, fNpm); + iS.close(); + return file; + } + + public void createPackageFragment(String packageName, String fragmentRootName) throws Exception { + IPackageFragmentRoot fragmentRoot = (IPackageFragmentRoot) fWorkSpaceElements.get(fragmentRootName); + IPackageFragment newPackageFragment = fragmentRoot.createPackageFragment(packageName, false, fNpm); + fWorkSpaceElements.put(newPackageFragment.getPath().toString(), newPackageFragment); + } + + public void createPackageFragmentRoot(IJavaProject project, String string) throws CoreException { + IPackageFragmentRoot srcRoot1 = JavaProjectHelper.addSourceContainer(project, string); + fWorkSpaceElements.put(srcRoot1.getPath().toString(), srcRoot1); + } + + public IPackageFragment getPackageFragment(String path) { + return (IPackageFragment) fWorkSpaceElements.get(path); + } + + public IFile getFile(String string) { + return (IFile) fWorkSpaceElements.get(string); + } + + public ICompilationUnit createCu(String path, String name, String content) throws Exception { + IPackageFragment f = (IPackageFragment) fWorkSpaceElements.get(path); + ICompilationUnit res = f.createCompilationUnit(name, content, false, fNpm); + fWorkSpaceElements.put(res.getPath().toString(), res); + return res; + } + + public ICompilationUnit getCu(String string) { + return (ICompilationUnit) fWorkSpaceElements.get(string); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/PropertyFileDocumentModellTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/PropertyFileDocumentModellTest.java new file mode 100644 index 000000000..cfe8784e6 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/PropertyFileDocumentModellTest.java @@ -0,0 +1,340 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.text.edits.DeleteEdit; +import org.eclipse.text.edits.ReplaceEdit; + +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; + +import org.eclipse.ltk.core.refactoring.DocumentChange; + +import org.eclipse.jdt.internal.corext.refactoring.nls.KeyValuePair; +import org.eclipse.jdt.internal.corext.refactoring.nls.PropertyFileDocumentModel; + +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; + +public class PropertyFileDocumentModellTest extends TestCase { + + public PropertyFileDocumentModellTest(String name) { + super(name); + } + + public static TestSuite suite() { + return new TestSuite(PropertyFileDocumentModellTest.class); + } + + private static void insert(IDocument document, String key, String value) throws CoreException { + insert(document, new KeyValuePair[] {new KeyValuePair(key, value)}); + } + + private static void insert(IDocument document, KeyValuePair[] pairs) throws CoreException { + PropertyFileDocumentModel model= new PropertyFileDocumentModel(document); + + for (int i= 0; i < pairs.length; i++) { + KeyValuePair pair= pairs[i]; + pair.setValue(PropertyFileDocumentModel.unwindValue(pair.getValue()) + model.getLineDelimiter()); + pair.setKey(PropertyFileDocumentModel.unwindEscapeChars(pair.getKey())); + } + + DocumentChange change= new DocumentChange("", document); + model.insert(pairs, change); + change.perform(new NullProgressMonitor()); + } + + public void testInsertIntoEmptyDoc() throws Exception { + Document props= new Document(); + + insert(props, "key", "value"); + + RefactoringTest.assertEqualLines( + "key=value\n", props.get()); + } + + public void testInsertIntoDoc() throws Exception { + Document props= new Document( + "org.eclipse.nls.1=value\n" + + "org.eclipse=value\n"); + + insert(props, "org.eclipse.nls.2", "value"); + + assertEquals( + "org.eclipse.nls.1=value\n" + + "org.eclipse.nls.2=value\n" + + "org.eclipse=value\n", props.get()); + } + + public void testInsertIntoDoc2() throws Exception { + Document props= new Document( + "org.1=value\n" + + "org.2=value\n"); + + insert(props, "arg.1", "value"); + + assertEquals( + "arg.1=value\n" + + "org.1=value\n" + + "org.2=value\n", props.get()); + } + + public void testInsertIntoDoc3() throws Exception { + Document props= new Document( + "Test_B_1=value\n" + + "Test_A_1=value\n"); + + insert(props, "Test_B_2", "value"); + + assertEquals( + "Test_B_1=value\n" + + "Test_B_2=value\n" + + "Test_A_1=value\n", props.get()); + } + + public void testInsertIntoDoc4() throws Exception { + Document props= new Document( + "Test_Aa=value\n" + + "Test_Ab=value\n" + + "\n" + + "Test_Bb=\n" + + "Test_Bc="); + + insert(props, new KeyValuePair[] {new KeyValuePair("Test_Ba", ""), new KeyValuePair("Test_Az", "")}); + + assertEquals("Test_Aa=value\n" + + "Test_Ab=value\n" + + "Test_Az=\n" + + "\n" + + "Test_Ba=\n" + + "Test_Bb=\n" + + "Test_Bc=", props.get()); + } + + public void testManyInsertsIntoDoc() throws Exception { + Document props= new Document( + "org.eclipse.nls.1=value\n" + + "\n" + + "org.eclipse.2=value\n"); + + insert(props, new KeyValuePair[] { + new KeyValuePair("org.eclipse.nls.2", "value"), + new KeyValuePair("org.eclipse.nls", "value"), + new KeyValuePair("org.apache", "value"), + new KeyValuePair("org.xenon", "value"), + new KeyValuePair("org.eclipse", "value"), + new KeyValuePair("org.eclipse.xyzblabla.pipapo", "value")}); + + assertEquals( + "org.apache=value\n" + + "org.eclipse.nls=value\n" + + "org.eclipse.nls.1=value\n" + + "org.eclipse.nls.2=value\n" + + "\n" + + "org.eclipse=value\n" + + "org.eclipse.2=value\n" + + "org.eclipse.xyzblabla.pipapo=value\n" + + "org.xenon=value\n", + props.get()); + } + + public void testManyInsertsIntoDoc2() throws Exception { + Document props= new Document( + "key_b=value\n" + + "\n" + + "key_y=value\n"); + + insert(props, new KeyValuePair[] {new KeyValuePair("key_c", "value"), new KeyValuePair("key_a", "value"), new KeyValuePair("key_z", "value")}); + + assertEquals( + "key_a=value\n" + + "key_b=value\n" + + "key_c=value\n" + + "\n" + + "key_y=value\n" + + "key_z=value\n", props.get()); + } + + public void testManyInsertsIntoDoc3() throws Exception { + Document props= new Document( + "key_a=value\n" + + "\n" + + "key_b_2=value\n"); + + insert(props, new KeyValuePair[] {new KeyValuePair("key_b_1", "value"), new KeyValuePair("key_b_0", "value")}); + + assertEquals( + "key_a=value\n" + + "\n" + + "key_b_0=value\n" + + "key_b_1=value\n" + + "key_b_2=value\n", props.get()); + } + + public void testManyInsertsIntoDoc4() throws Exception { + Document props= new Document( + "Clazz.Pong=Pong\n" + + "Clazz.Ping=Ping\n"); + + insert(props, new KeyValuePair[] { + new KeyValuePair("Clazz.Pizza", "value"), + new KeyValuePair("Clazz.Posers", "value")}); + + assertEquals( + "Clazz.Pong=Pong\n" + + "Clazz.Posers=value\n" + + "Clazz.Ping=Ping\n" + + "Clazz.Pizza=value\n", props.get()); + } + + public void testManyInsertsIntoDoc5() throws Exception { + Document props= new Document( + "Clazz.Pong=Pong\n" + + "Clazz.Ping=Ping\n"); + + insert(props, new KeyValuePair[] { + new KeyValuePair("Clazz.P", "p"), + new KeyValuePair("Clazz.PosersWithAVeryLongName", "p")}); + + assertEquals( + "Clazz.P=p\n" + + "Clazz.Pong=Pong\n" + + "Clazz.PosersWithAVeryLongName=p\n" + + "Clazz.Ping=Ping\n", props.get()); + } + + public void testBlockInsertsIntoDoc() throws Exception { + Document props= new Document( + "org.eclipse.1=value\n" + + "org.eclipse.2=value\n"); + + insert(props, new KeyValuePair[] {new KeyValuePair("org.eclipse.nls.1", "value"), new KeyValuePair("org.eclipse.nls.2", "value")}); + + assertEquals( + "org.eclipse.1=value\n" + + "org.eclipse.2=value\n" + + "org.eclipse.nls.1=value\n" + + "org.eclipse.nls.2=value\n", props.get()); + } + + public void testInsertIntoDocWithBlankLines1() throws Exception { + Document props= new Document( + "org.eclipse=value\n" + + "\n" + + "org.eclipse.test=value\n"); + + insert(props, "org.eclipse.test", "value2"); + + assertEquals( + "org.eclipse=value\n" + + "\n" + + "org.eclipse.test=value\n" + + "org.eclipse.test=value2\n", props.get()); + } + + public void testInsertIntoDocWithBlankLines2() throws Exception { + Document props= new Document( + "a.b=v\n" + + "\n" + + "org.eclipse.test=value\n"); + + insert(props, "a.c", "v"); + + assertEquals( + "a.b=v\n" + + "a.c=v\n" + + "\n" + + "org.eclipse.test=value\n", props.get()); + } + + public void testInsertIntoDocWithDifferentSeperationChar() throws Exception { + Document props= new Document( + "org.eclipse.ok:value\n" + + "org.eclipse.what value\n"); + + insert(props, "org.eclipse.nix", "value"); + + assertEquals( + "org.eclipse.nix=value\n" + + "org.eclipse.ok:value\n" + + "org.eclipse.what value\n", props.get()); + } + + public void testRemovingOfKey() throws Exception { + Document props= new Document("org.eclipse.1=value1\n" + "org.eclipse.2=value2\n" + "org.eclipse.3=value3\n"); + PropertyFileDocumentModel modell= new PropertyFileDocumentModel(props); + + DeleteEdit deleteEdit= modell.remove("org.eclipse.2"); + deleteEdit.apply(props); + + assertEquals("org.eclipse.1=value1\n" + "org.eclipse.3=value3\n", props.get()); + } + + public void testRemovingOfLastKey() throws Exception { + Document props= new Document("org.eclipse.1=value1\n" + "org.eclipse.2=value2\n" + "org.eclipse.3=value3\n"); + PropertyFileDocumentModel modell= new PropertyFileDocumentModel(props); + + DeleteEdit deleteEdit= modell.remove("org.eclipse.3"); + deleteEdit.apply(props); + + assertEquals("org.eclipse.1=value1\n" + "org.eclipse.2=value2\n", props.get()); + } + + public void testReplacementOfKeyValuePair() throws Exception { + Document props= new Document("org.eclipse.1=value1\n" + "org.eclipse.2=value2\n" + "org.eclipse.3=value3\n"); + PropertyFileDocumentModel modell= new PropertyFileDocumentModel(props); + + ReplaceEdit replaceEdit= modell.replace(new KeyValuePair("org.eclipse.2", "value\n"), new KeyValuePair("org.1", "value\n")); + replaceEdit.apply(props); + + assertEquals("org.eclipse.1=value1\n" + "org.1=value\n" + "org.eclipse.3=value3\n", props.get()); + } + + // Escaping stuff + public void testEscapingOfComments() throws Exception { + Document props= new Document(); + + insert(props, "key", "value!please escape"); + + RefactoringTest.assertEqualLines( + "key=value\\!please escape\n", props.get()); + } + + public void testEscapingOfLineBreaks() throws Exception { + Document props= new Document(); + + insert(props, "key", "value1\nvalue2\r"); + + RefactoringTest.assertEqualLines( + "key=value1\\nvalue2\\r\n", props.get()); + } + + public void testEscapingOfUniCode() throws Exception { + Document props= new Document(); + + insert(props, "key", "\u00ea"); + + RefactoringTest.assertEqualLines("key=\\u00EA\n", props.get()); + } + + public void testEscapingOfLeadingWhiteSpaces() throws Exception { + Document props= new Document(); + + insert(props, "key", " test"); + + RefactoringTest.assertEqualLines("key=\\ \\ test\n", props.get()); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/SimpleLineReaderTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/SimpleLineReaderTest.java new file mode 100644 index 000000000..6ad483c25 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/SimpleLineReaderTest.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.nls; + +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jface.text.Document; + +import org.eclipse.jdt.internal.corext.refactoring.nls.SimpleLineReader; + +public class SimpleLineReaderTest extends TestCase { + + public static TestSuite suite() { + return new TestSuite(SimpleLineReaderTest.class); + } + + public void testSimpleLineReader() throws Exception { + SimpleLineReader reader = new SimpleLineReader(new Document("aha\noho\r\n\r\n\n")); + assertEquals("aha\n", reader.readLine()); + assertEquals("oho\r\n", reader.readLine()); + assertEquals("\r\n", reader.readLine()); + assertEquals("\n", reader.readLine()); + assertEquals(null, reader.readLine()); + } + + public void testSimpleLineReaderWithEmptyString() { + SimpleLineReader simpleLineReader = new SimpleLineReader(new Document("")); + assertEquals(null, simpleLineReader.readLine()); + } + + public void testSimpleLineReaderWithEscapedLF() { + SimpleLineReader simpleLineReader = new SimpleLineReader(new Document("a\nb\\nc\n")); + assertEquals("a\n", simpleLineReader.readLine()); + assertEquals("b\\nc\n", simpleLineReader.readLine()); + assertEquals(null, simpleLineReader.readLine()); + } + + public void testSimpleLineReaderWithEscapedCR() { + SimpleLineReader simpleLineReader = new SimpleLineReader(new Document("a\nb\\rc\r")); + assertEquals("a\n", simpleLineReader.readLine()); + assertEquals("b\\rc\r", simpleLineReader.readLine()); + assertEquals(null, simpleLineReader.readLine()); + } + + public void testSimpleLineReaderWithCR() { + SimpleLineReader simpleLineReader = new SimpleLineReader(new Document("a\rb\r")); + assertEquals("a\r", simpleLineReader.readLine()); + assertEquals("b\r", simpleLineReader.readLine()); + assertEquals(null, simpleLineReader.readLine()); + } + + public void testSimpleLineReaderWithoutNL() { + SimpleLineReader simpleLineReader = new SimpleLineReader(new Document("=")); + assertEquals("=", simpleLineReader.readLine()); + assertEquals(null, simpleLineReader.readLine()); + } + + public void testSimpleLineReaderWithMissingNL() { + SimpleLineReader simpleLineReader = new SimpleLineReader(new Document("a\rb")); + assertEquals("a\r", simpleLineReader.readLine()); + assertEquals("b", simpleLineReader.readLine()); + assertEquals(null, simpleLineReader.readLine()); + } + + public void testSimpleLineReaderWithLineContinue1() { + SimpleLineReader simpleLineReader = new SimpleLineReader(new Document("aaa\\\nbbb\nccc\n")); + assertEquals("aaa\\\nbbb\n", simpleLineReader.readLine()); + assertEquals("ccc\n", simpleLineReader.readLine()); + assertEquals(null, simpleLineReader.readLine()); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractMoveCompilationUnitPrefTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractMoveCompilationUnitPrefTest.java new file mode 100644 index 000000000..ea36e0c99 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractMoveCompilationUnitPrefTest.java @@ -0,0 +1,72 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.MoveRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IPackageFragment; + +import org.eclipse.jdt.internal.corext.refactoring.reorg.JavaMoveProcessor; +import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgDestinationFactory; +import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory; +import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy; + +import org.eclipse.jdt.ui.tests.refactoring.ccp.MockReorgQueries; + + +public class AbstractMoveCompilationUnitPrefTest extends RepeatingRefactoringPerformanceTestCase { + + public AbstractMoveCompilationUnitPrefTest(String name) { + super(name); + } + + protected void doExecuteRefactoring(int numberOfCus, int numberOfRefs, boolean measure) throws Exception { + ICompilationUnit cunit= generateSources(numberOfCus, numberOfRefs); + IMovePolicy policy= ReorgPolicyFactory.createMovePolicy((new IResource[0]), (new IJavaElement[] {cunit})); + JavaMoveProcessor processor= (policy.canEnable() ? new JavaMoveProcessor(policy) : null); + IPackageFragment destination= fTestProject.getSourceFolder().createPackageFragment("destination", false, null); + processor.setDestination(ReorgDestinationFactory.createDestination(destination)); + processor.setReorgQueries(new MockReorgQueries()); + processor.setUpdateReferences(true); + executeRefactoring(new MoveRefactoring(processor), measure, RefactoringStatus.WARNING, false); + } + + private ICompilationUnit generateSources(int numberOfCus, int numberOfRefs) throws Exception { + IPackageFragment source= fTestProject.getSourceFolder().createPackageFragment("source", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package source;\n"); + buf.append("public class A {\n"); + buf.append("}\n"); + ICompilationUnit result= source.createCompilationUnit("A.java", buf.toString(), false, null); + + IPackageFragment references= fTestProject.getSourceFolder().createPackageFragment("ref", false, null); + for(int i= 0; i < numberOfCus; i++) { + createReferenceCu(references, i, numberOfRefs); + } + return result; + } + + private static void createReferenceCu(IPackageFragment pack, int index, int numberOfRefs) throws Exception { + StringBuffer buf= new StringBuffer(); + buf.append("package " + pack.getElementName() + ";\n"); + buf.append("public class Ref" + index + " {\n"); + for (int i= 0; i < numberOfRefs - 1; i++) { + buf.append(" source.A field" + i +";\n"); + } + buf.append("}\n"); + pack.createCompilationUnit("Ref" + index + ".java", buf.toString(), false, null); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractMoveStaticMemberPrefTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractMoveStaticMemberPrefTest.java new file mode 100644 index 000000000..277e04f76 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractMoveStaticMemberPrefTest.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import org.eclipse.ltk.core.refactoring.participants.MoveRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; + +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; +import org.eclipse.jdt.internal.corext.refactoring.structure.MoveStaticMembersProcessor; + +import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; + + +public class AbstractMoveStaticMemberPrefTest extends RepeatingRefactoringPerformanceTestCase { + + public AbstractMoveStaticMemberPrefTest(String name) { + super(name); + } + + protected void doExecuteRefactoring(int numberOfCus, int numberOfRefs, boolean measure) throws Exception { + ICompilationUnit cunit= generateSources(numberOfCus, numberOfRefs); + IType type= cunit.findPrimaryType(); + IMember member= type.getField("VALUE"); + IMember[] elements= new IMember[] {member}; + MoveStaticMembersProcessor processor= (RefactoringAvailabilityTester.isMoveStaticMembersAvailable(elements) ? new MoveStaticMembersProcessor(elements, JavaPreferencesSettings.getCodeGenerationSettings(cunit.getJavaProject())) : null); + IPackageFragment destPack= fTestProject.getSourceFolder().createPackageFragment("destination", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package destination;\n"); + buf.append("public class Dest {\n"); + buf.append("}\n"); + ICompilationUnit destination= destPack.createCompilationUnit("Dest.java", buf.toString(), false, null); + + processor.setDestinationTypeFullyQualifiedName(destination.findPrimaryType().getFullyQualifiedName()); + executeRefactoring(new MoveRefactoring(processor), measure); + } + + private ICompilationUnit generateSources(int numberOfCus, int numberOfRefs) throws Exception { + IPackageFragment source= fTestProject.getSourceFolder().createPackageFragment("source", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package source;\n"); + buf.append("public class A {\n"); + buf.append(" public static final int VALUE= 10;\n"); + buf.append("}\n"); + ICompilationUnit result= source.createCompilationUnit("A.java", buf.toString(), false, null); + + IPackageFragment references= fTestProject.getSourceFolder().createPackageFragment("ref", false, null); + for(int i= 0; i < numberOfCus; i++) { + createReferenceCu(references, i, numberOfRefs); + } + return result; + } + + private static void createReferenceCu(IPackageFragment pack, int index, int numberOfRefs) throws Exception { + StringBuffer buf= new StringBuffer(); + buf.append("package " + pack.getElementName() + ";\n"); + buf.append("import source.A;\n"); + buf.append("public class Ref" + index + " {\n"); + for (int i= 0; i < numberOfRefs - 1; i++) { + buf.append(" int field" + i +"= A.VALUE;\n"); + } + buf.append("}\n"); + pack.createCompilationUnit("Ref" + index + ".java", buf.toString(), false, null); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractRenameMethodPerfTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractRenameMethodPerfTest.java new file mode 100644 index 000000000..20f1e3e30 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractRenameMethodPerfTest.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; + +import org.eclipse.jdt.internal.corext.refactoring.rename.RenameVirtualMethodProcessor; + + +public class AbstractRenameMethodPerfTest extends RepeatingRefactoringPerformanceTestCase { + + public AbstractRenameMethodPerfTest(String name) { + super(name); + } + + protected void doExecuteRefactoring(int numberOfCus, int numberOfRefs, boolean measure) throws Exception { + ICompilationUnit cunit= generateSources(numberOfCus, numberOfRefs); + IMethod method= cunit.findPrimaryType().getMethod("foo", new String[0]); + RenameVirtualMethodProcessor processor= new RenameVirtualMethodProcessor(method); + processor.setNewElementName("foo2"); + executeRefactoring(new RenameRefactoring(processor), measure); + } + + private ICompilationUnit generateSources(int numberOfCus, int numberOfRefs) throws Exception { + IPackageFragment definition= fTestProject.getSourceFolder().createPackageFragment("def", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package def;\n"); + buf.append("public class A {\n"); + buf.append(" public void foo() {\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit result= definition.createCompilationUnit("A.java", buf.toString(), false, null); + + IPackageFragment references= fTestProject.getSourceFolder().createPackageFragment("ref", false, null); + for(int i= 0; i < numberOfCus; i++) { + createReferenceCu(references, i, numberOfRefs); + } + return result; + } + + private void createReferenceCu(IPackageFragment pack, int index, int numberOfRefs) throws Exception { + StringBuffer buf= new StringBuffer(); + buf.append("package " + pack.getElementName() + ";\n"); + buf.append("import def.A;\n"); + buf.append("public class Ref" + index + " {\n"); + buf.append(" public void ref(A a) {\n"); + for (int i= 0; i < numberOfRefs; i++) { + buf.append(" a.foo();\n"); + } + buf.append(" }\n"); + buf.append("}\n"); + pack.createCompilationUnit("Ref" + index + ".java", buf.toString(), false, null); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractRenamePackagePerfTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractRenamePackagePerfTest.java new file mode 100644 index 000000000..33b2a7400 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractRenamePackagePerfTest.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.IPackageFragment; + +import org.eclipse.jdt.internal.corext.refactoring.rename.RenamePackageProcessor; + +public class AbstractRenamePackagePerfTest extends RepeatingRefactoringPerformanceTestCase { + + public AbstractRenamePackagePerfTest(String name) { + super(name); + } + + protected void doExecuteRefactoring(int numberOfCus, int numberOfRefs, boolean measure) throws Exception { + IPackageFragment pack= generateSources(numberOfCus, numberOfRefs); + RenamePackageProcessor processor= new RenamePackageProcessor(pack); + processor.setNewElementName("pack2"); + executeRefactoring(new RenameRefactoring(processor), measure); + } + + private IPackageFragment generateSources(int numberOfCus, int numberOfRefs) throws Exception { + IPackageFragment pack= fTestProject.getSourceFolder().createPackageFragment("pack", false, null); + for (int i= 0; i < numberOfRefs; i++) { + StringBuffer buf= new StringBuffer(); + buf.append("package pack;\n"); + buf.append("public class A" + i + " {\n"); + buf.append("}\n"); + pack.createCompilationUnit("A" + i + ".java", buf.toString(), false, null); + } + + IPackageFragment references= fTestProject.getSourceFolder().createPackageFragment("ref", false, null); + for(int i= 0; i < numberOfCus; i++) { + createReferenceCu(references, i, numberOfRefs); + } + return pack; + } + + private static void createReferenceCu(IPackageFragment pack, int index, int numberOfRefs) throws Exception { + StringBuffer buf= new StringBuffer(); + buf.append("package " + pack.getElementName() + ";\n"); + for (int i= 0; i < numberOfRefs; i++) { + buf.append("import pack.A" + i + ";\n"); + } + buf.append("public class Ref" + index + " {\n"); + buf.append("}\n"); + pack.createCompilationUnit("Ref" + index + ".java", buf.toString(), false, null); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractRenameTypePerfTest.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractRenameTypePerfTest.java new file mode 100644 index 000000000..976aeed50 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AbstractRenameTypePerfTest.java @@ -0,0 +1,62 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IType; + +import org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor; + + +public class AbstractRenameTypePerfTest extends RepeatingRefactoringPerformanceTestCase { + + public AbstractRenameTypePerfTest(String name) { + super(name); + } + + protected void doExecuteRefactoring(int numberOfCus, int numberOfRefs, boolean measure) throws Exception { + ICompilationUnit cunit= generateSources(numberOfCus, numberOfRefs); + IType type= cunit.findPrimaryType(); + RenameTypeProcessor processor= new RenameTypeProcessor(type); + processor.setNewElementName("B"); + executeRefactoring(new RenameRefactoring(processor), measure); + } + + private ICompilationUnit generateSources(int numberOfCus, int numberOfRefs) throws Exception { + IPackageFragment definition= fTestProject.getSourceFolder().createPackageFragment("def", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package def;\n"); + buf.append("public class A {\n"); + buf.append("}\n"); + ICompilationUnit result= definition.createCompilationUnit("A.java", buf.toString(), false, null); + + IPackageFragment references= fTestProject.getSourceFolder().createPackageFragment("ref", false, null); + for(int i= 0; i < numberOfCus; i++) { + createReferenceCu(references, i, numberOfRefs); + } + return result; + } + + private void createReferenceCu(IPackageFragment pack, int index, int numberOfRefs) throws Exception { + StringBuffer buf= new StringBuffer(); + buf.append("package " + pack.getElementName() + ";\n"); + buf.append("import def.A;\n"); + buf.append("public class Ref" + index + " {\n"); + for (int i= 0; i < numberOfRefs - 1; i++) { + buf.append(" A field" + i +";\n"); + } + buf.append("}\n"); + pack.createCompilationUnit("Ref" + index + ".java", buf.toString(), false, null); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AllReorgPerformanceTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AllReorgPerformanceTests.java new file mode 100644 index 000000000..bdb2cdeda --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/AllReorgPerformanceTests.java @@ -0,0 +1,41 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class AllReorgPerformanceTests { + + public static Test suite() { + TestSuite suite= new TestSuite("All Reorg Performance Tests"); //$NON-NLS-1$ + suite.addTest(RenamePackagePerfTests1.suite()); + suite.addTest(RenamePackagePerfTests2.suite()); + + suite.addTest(RenameTypePerfAcceptanceTests.suite()); + suite.addTest(RenameTypePerfTests1.suite()); + suite.addTest(RenameTypePerfTests2.suite()); + + suite.addTest(RenameMethodPerfTests1.suite()); + suite.addTest(RenameMethodPerfTests2.suite()); + suite.addTest(RenameMethodWithOverloadPerfTests.suite()); + + suite.addTest(MoveCompilationUnitPerfTests1.suite()); + suite.addTest(MoveCompilationUnitPerfTests2.suite()); + + suite.addTest(MoveStaticMembersPerfTests1.suite()); + suite.addTest(MoveStaticMembersPerfTests2.suite()); + + suite.addTest(IntroduceIndirectionPerfAcceptanceTests.suite()); + + return suite; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/IntroduceIndirectionPerfAcceptanceTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/IntroduceIndirectionPerfAcceptanceTests.java new file mode 100644 index 000000000..d0eae9e75 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/IntroduceIndirectionPerfAcceptanceTests.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Assert; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; + +import org.eclipse.jdt.internal.corext.refactoring.code.IntroduceIndirectionRefactoring; + +import org.eclipse.jdt.ui.tests.performance.SWTTestProject; +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestCase; +import org.eclipse.jdt.ui.tests.refactoring.infra.SWTProjectTestSetup; + +public class IntroduceIndirectionPerfAcceptanceTests extends RefactoringPerformanceTestCase { + + private IJavaProject fProject; + private IntroduceIndirectionRefactoring fRefactoring; + + public static Test suite() { + TestSuite suite= new TestSuite("IntroduceIndirectionPerfAcceptanceTests"); + suite.addTest(new IntroduceIndirectionPerfAcceptanceTests("testIntroduceIndirection")); + return new SWTProjectTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new SWTProjectTestSetup(someTest); + } + + public IntroduceIndirectionPerfAcceptanceTests(String test) { + super(test); + } + + protected void setUp() throws Exception { + super.setUp(); + fProject= (IJavaProject)JavaCore.create( + ResourcesPlugin.getWorkspace().getRoot().findMember(SWTTestProject.PROJECT)); + + IType control= fProject.findType("org.eclipse.swt.widgets.Widget"); + IMethod m= control.getMethod("getDisplay", new String[0]); + Assert.assertTrue(m != null && m.exists()); + fRefactoring= new IntroduceIndirectionRefactoring(m); + fRefactoring.setEnableUpdateReferences(true); + fRefactoring.setIntermediaryClassName("org.eclipse.swt.widgets.Widget"); + fRefactoring.setIntermediaryMethodName("bar"); + } + + public void testIntroduceIndirection() throws Exception { + executeRefactoring(fRefactoring, true); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/MoveCompilationUnitPerfTests1.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/MoveCompilationUnitPerfTests1.java new file mode 100644 index 000000000..5b581f4b0 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/MoveCompilationUnitPerfTests1.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.test.performance.Dimension; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestSetup; + +public class MoveCompilationUnitPerfTests1 extends AbstractMoveCompilationUnitPrefTest { + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("MoveCompilationUnitPerfTests1"); + suite.addTest(new MoveCompilationUnitPerfTests1("testCold_10_10")); + suite.addTest(new MoveCompilationUnitPerfTests1("test_10_10")); + suite.addTest(new MoveCompilationUnitPerfTests1("test_100_10")); + suite.addTest(new MoveCompilationUnitPerfTests1("test_1000_10")); + return new RefactoringPerformanceTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringPerformanceTestSetup(someTest); + } + + public MoveCompilationUnitPerfTests1(String name) { + super(name); + } + + public void testCold_10_10() throws Exception { + executeRefactoring(10, 10, false, 3); + } + + public void test_10_10() throws Exception { + executeRefactoring(10, 10, true, 3); + } + + public void test_100_10() throws Exception { + executeRefactoring(100, 10, true, 1); + } + + public void test_1000_10() throws Exception { + tagAsSummary("Move compilation units - 1000 CUs, 10 Refs", Dimension.ELAPSED_PROCESS); + executeRefactoring(1000, 10, true, 1); + } + + protected void assertMeasurements() { + assertPerformanceInRelativeBand(Dimension.CPU_TIME, -100, +10); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/MoveCompilationUnitPerfTests2.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/MoveCompilationUnitPerfTests2.java new file mode 100644 index 000000000..1f055ec47 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/MoveCompilationUnitPerfTests2.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.test.performance.Dimension; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestSetup; + +public class MoveCompilationUnitPerfTests2 extends AbstractMoveCompilationUnitPrefTest { + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("MoveCompilationUnitPerfTests2"); + suite.addTest(new MoveCompilationUnitPerfTests2("testCold_10_10")); + suite.addTest(new MoveCompilationUnitPerfTests2("test_10_10")); + suite.addTest(new MoveCompilationUnitPerfTests2("test_10_100")); + suite.addTest(new MoveCompilationUnitPerfTests2("test_10_1000")); + return new RefactoringPerformanceTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringPerformanceTestSetup(someTest); + } + + public MoveCompilationUnitPerfTests2(String name) { + super(name); + } + + public void testCold_10_10() throws Exception { + executeRefactoring(10, 10, false, 3); + } + + public void test_10_10() throws Exception { + executeRefactoring(10, 10, true, 3); + } + + public void test_10_100() throws Exception { + executeRefactoring(10, 100, true, 1); + } + + public void test_10_1000() throws Exception { + tagAsSummary("Move compilation units - 10 CUs, 1000 Refs", Dimension.ELAPSED_PROCESS); + executeRefactoring(10, 1000, true, 1); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/MoveStaticMembersPerfTests1.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/MoveStaticMembersPerfTests1.java new file mode 100644 index 000000000..4c129d4c6 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/MoveStaticMembersPerfTests1.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.test.performance.Dimension; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestSetup; + +public class MoveStaticMembersPerfTests1 extends AbstractMoveStaticMemberPrefTest { + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("MoveStaticMembersPerfTests1"); + suite.addTest(new MoveStaticMembersPerfTests1("testCold_10_10")); + suite.addTest(new MoveStaticMembersPerfTests1("test_10_10")); + suite.addTest(new MoveStaticMembersPerfTests1("test_100_10")); + suite.addTest(new MoveStaticMembersPerfTests1("test_1000_10")); + return new RefactoringPerformanceTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringPerformanceTestSetup(someTest); + } + + public MoveStaticMembersPerfTests1(String name) { + super(name); + } + + public void testCold_10_10() throws Exception { + executeRefactoring(10, 10, false, 3); + } + + public void test_10_10() throws Exception { + executeRefactoring(10, 10, true, 3); + } + + public void test_100_10() throws Exception { + executeRefactoring(100, 10, true, 1); + } + + public void test_1000_10() throws Exception { + tagAsSummary("Move static members - 1000 CUs, 10 Refs", Dimension.ELAPSED_PROCESS); + executeRefactoring(1000, 10, true, 1); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/MoveStaticMembersPerfTests2.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/MoveStaticMembersPerfTests2.java new file mode 100644 index 000000000..28c7d3882 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/MoveStaticMembersPerfTests2.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.test.performance.Dimension; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestSetup; + +public class MoveStaticMembersPerfTests2 extends AbstractMoveStaticMemberPrefTest { + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("MoveStaticMembersPerfTests2"); + suite.addTest(new MoveStaticMembersPerfTests2("testCold_10_10")); + suite.addTest(new MoveStaticMembersPerfTests2("test_10_10")); + suite.addTest(new MoveStaticMembersPerfTests2("test_10_100")); + suite.addTest(new MoveStaticMembersPerfTests2("test_10_1000")); + return new RefactoringPerformanceTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringPerformanceTestSetup(someTest); + } + + public MoveStaticMembersPerfTests2(String name) { + super(name); + } + + public void testCold_10_10() throws Exception { + executeRefactoring(10, 10, false, 3); + } + + public void test_10_10() throws Exception { + executeRefactoring(10, 10, true, 3); + } + + public void test_10_100() throws Exception { + executeRefactoring(10, 100, true, 1); + } + + public void test_10_1000() throws Exception { + tagAsSummary("Move static members - 10 CUs, 1000 Refs", Dimension.ELAPSED_PROCESS); + executeRefactoring(10, 1000, true, 1); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameMethodPerfTests1.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameMethodPerfTests1.java new file mode 100644 index 000000000..c77bd0abd --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameMethodPerfTests1.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.test.performance.Dimension; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestSetup; + + +public class RenameMethodPerfTests1 extends AbstractRenameMethodPerfTest { + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("RenameTypePerfAcceptanceTests1"); + suite.addTest(new RenameMethodPerfTests1("testCold_10_10")); + suite.addTest(new RenameMethodPerfTests1("test_10_10")); + suite.addTest(new RenameMethodPerfTests1("test_100_10")); + suite.addTest(new RenameMethodPerfTests1("test_1000_10")); + return new RefactoringPerformanceTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringPerformanceTestSetup(someTest); + } + + public RenameMethodPerfTests1(String name) { + super(name); + } + + public void testCold_10_10() throws Exception { + executeRefactoring(10, 10, false, 3); + } + + public void test_10_10() throws Exception { + executeRefactoring(10, 10, true, 10); + } + + public void test_100_10() throws Exception { + executeRefactoring(100, 10, true, 10); + } + + public void test_1000_10() throws Exception { + tagAsSummary("Rename method - 1000 CUs, 10 Refs", Dimension.ELAPSED_PROCESS); + executeRefactoring(1000, 10, true, 10); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameMethodPerfTests2.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameMethodPerfTests2.java new file mode 100644 index 000000000..ee09144dd --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameMethodPerfTests2.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.test.performance.Dimension; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestSetup; + + +public class RenameMethodPerfTests2 extends AbstractRenameMethodPerfTest { + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("RenameTypePerfAcceptanceTests2"); + suite.addTest(new RenameMethodPerfTests2("testCold_10_10")); + suite.addTest(new RenameMethodPerfTests2("test_10_10")); + suite.addTest(new RenameMethodPerfTests2("test_10_100")); + suite.addTest(new RenameMethodPerfTests2("test_10_1000")); + return new RefactoringPerformanceTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringPerformanceTestSetup(someTest); + } + + public RenameMethodPerfTests2(String name) { + super(name); + } + + public void testCold_10_10() throws Exception { + executeRefactoring(10, 10, false, 3); + } + + public void test_10_10() throws Exception { + executeRefactoring(10, 10, true, 10); + } + + public void test_10_100() throws Exception { + executeRefactoring(10, 100, true, 10); + } + + public void test_10_1000() throws Exception { + tagAsSummary("Rename method - 10 CUs, 1000 Refs", Dimension.ELAPSED_PROCESS); + executeRefactoring(10, 1000, true, 10); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameMethodWithOverloadPerfTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameMethodWithOverloadPerfTests.java new file mode 100644 index 000000000..70bdb822e --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameMethodWithOverloadPerfTests.java @@ -0,0 +1,113 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.test.performance.Dimension; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; + +import org.eclipse.jdt.internal.corext.refactoring.rename.RenameVirtualMethodProcessor; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestSetup; + +public class RenameMethodWithOverloadPerfTests extends RepeatingRefactoringPerformanceTestCase { + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("RenameMethodWithOverloadPerfTests"); + suite.addTest(new RenameMethodWithOverloadPerfTests("testCold_10_10")); + suite.addTest(new RenameMethodWithOverloadPerfTests("test_10_10")); + suite.addTest(new RenameMethodWithOverloadPerfTests("test_100_10")); + suite.addTest(new RenameMethodWithOverloadPerfTests("test_1000_10")); + return new RefactoringPerformanceTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringPerformanceTestSetup(someTest); + } + + public RenameMethodWithOverloadPerfTests(String name) { + super(name); + } + + public void testCold_10_10() throws Exception { + executeRefactoring(10, 10, false, 10); + } + + public void test_10_10() throws Exception { + executeRefactoring(10, 10, true, 10); + } + + public void test_100_10() throws Exception { + tagAsSummary("Rename method with overloading", Dimension.ELAPSED_PROCESS); + executeRefactoring(100, 10, true, 10); + } + + public void test_1000_10() throws Exception { + executeRefactoring(1000, 10, true, 10); + } + + protected void doExecuteRefactoring(int numberOfCus, int numberOfRefs, boolean measure) throws Exception { + ICompilationUnit cunit= generateSources(numberOfCus, numberOfRefs); + IMethod method= cunit.findPrimaryType().getMethod("setString", new String[] {"QString;"}); + RenameVirtualMethodProcessor processor= new RenameVirtualMethodProcessor(method); + processor.setNewElementName("set"); + executeRefactoring(new RenameRefactoring(processor), measure, RefactoringStatus.FATAL); + } + + private ICompilationUnit generateSources(int numberOfCus, int numberOfRefs) throws Exception { + IPackageFragment definition= getTestProject().getSourceFolder().createPackageFragment("def", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package def;\n"); + buf.append("public class A {\n"); + buf.append(" public void set(Object s) {\n"); + buf.append(" }\n"); + buf.append(" public void setString(String s) {\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit result= definition.createCompilationUnit("A.java", buf.toString(), false, null); + + IPackageFragment references= getTestProject().getSourceFolder().createPackageFragment("ref", false, null); + for(int i= 0; i < numberOfCus; i++) { + createReferenceCu(references, i, numberOfRefs); + } + return result; + } + + private void createReferenceCu(IPackageFragment pack, int index, int numberOfRefs) throws Exception { + StringBuffer buf= new StringBuffer(); + buf.append("package " + pack.getElementName() + ";\n"); + buf.append("import def.A;\n"); + buf.append("public class Ref" + index + " {\n"); + buf.append(" public void ref(A a) {\n"); + buf.append(" String s= \"Eclipse\";\n"); + for (int i= 0; i < numberOfRefs; i++) { + buf.append(" a.set(s);\n"); + buf.append(" a.setString(s);\n"); + } + buf.append(" }\n"); + buf.append("}\n"); + pack.createCompilationUnit("Ref" + index + ".java", buf.toString(), false, null); + } + + protected void assertMeasurements() { + assertPerformanceInRelativeBand(Dimension.CPU_TIME, -100, +10); + } + +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenamePackagePerfTests1.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenamePackagePerfTests1.java new file mode 100644 index 000000000..b60333ead --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenamePackagePerfTests1.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestSetup; + + +public class RenamePackagePerfTests1 extends AbstractRenamePackagePerfTest { + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("RenamePackagePerfTests1"); + suite.addTest(new RenamePackagePerfTests1("testCold_10_10")); + suite.addTest(new RenamePackagePerfTests1("test_10_10")); + suite.addTest(new RenamePackagePerfTests1("test_100_10")); + suite.addTest(new RenamePackagePerfTests1("test_1000_10")); + return new RefactoringPerformanceTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringPerformanceTestSetup(someTest); + } + + public RenamePackagePerfTests1(String name) { + super(name); + } + + public void testCold_10_10() throws Exception { + executeRefactoring(10, 10, false, 3); + } + + public void test_10_10() throws Exception { + executeRefactoring(10, 10, true, 10); + } + + public void test_100_10() throws Exception { + executeRefactoring(100, 10, true, 10); + } + + public void test_1000_10() throws Exception { + // XXX: Removing from fingerprint due to: https://bugs.eclipse.org/bugs/show_bug.cgi?id=266886 +// tagAsSummary("Rename package - 1000 CUs, 10 Refs", Dimension.ELAPSED_PROCESS); + executeRefactoring(1000, 10, true, 10); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenamePackagePerfTests2.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenamePackagePerfTests2.java new file mode 100644 index 000000000..80d1237c3 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenamePackagePerfTests2.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.test.performance.Dimension; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestSetup; + + +public class RenamePackagePerfTests2 extends AbstractRenamePackagePerfTest { + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("RenamePackagePerfTests2"); + suite.addTest(new RenamePackagePerfTests2("testCold_10_10")); + suite.addTest(new RenamePackagePerfTests2("test_10_10")); + suite.addTest(new RenamePackagePerfTests2("test_10_100")); + suite.addTest(new RenamePackagePerfTests2("test_10_1000")); + return new RefactoringPerformanceTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringPerformanceTestSetup(someTest); + } + + public RenamePackagePerfTests2(String name) { + super(name); + } + + public void testCold_10_10() throws Exception { + executeRefactoring(10, 10, false, 3); + } + + public void test_10_10() throws Exception { + executeRefactoring(10, 10, true, 10); + } + + public void test_10_100() throws Exception { + executeRefactoring(10, 100, true, 10); + } + + public void test_10_1000() throws Exception { + tagAsSummary("Rename package - 10 CUs, 1000 Refs", Dimension.ELAPSED_PROCESS); + executeRefactoring(10, 1000, true, 10); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameTypePerfAcceptanceTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameTypePerfAcceptanceTests.java new file mode 100644 index 000000000..324a3fd64 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameTypePerfAcceptanceTests.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.test.performance.Dimension; + +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; + +import org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor; + +import org.eclipse.jdt.ui.tests.performance.SWTTestProject; +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestCase; +import org.eclipse.jdt.ui.tests.refactoring.infra.SWTProjectTestSetup; + +public class RenameTypePerfAcceptanceTests extends RefactoringPerformanceTestCase { + + private IJavaProject fProject; + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("RenameTypePerfAcceptanceTests"); + suite.addTest(new RenameTypePerfAcceptanceTests("testCold")); + suite.addTest(new RenameTypePerfAcceptanceTests("testWarm")); + return new SWTProjectTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new SWTProjectTestSetup(someTest); + } + + public RenameTypePerfAcceptanceTests(String test) { + super(test); + } + + protected void setUp() throws Exception { + super.setUp(); + fProject= (IJavaProject)JavaCore.create( + ResourcesPlugin.getWorkspace().getRoot().findMember(SWTTestProject.PROJECT)); + } + + protected void finishMeasurements() { + stopMeasuring(); + commitMeasurements(); + assertPerformanceInRelativeBand(Dimension.CPU_TIME, -100, +10); + } + + public void testCold() throws Exception { + IType control= fProject.findType("org.eclipse.swt.widgets.Control"); + RenameTypeProcessor processor= new RenameTypeProcessor(control); + processor.setNewElementName("Control2"); + executeRefactoring(new RenameRefactoring(processor), false); + } + + public void testWarm() throws Exception { + tagAsSummary("Rename of Control", Dimension.ELAPSED_PROCESS); + IType control= fProject.findType("org.eclipse.swt.widgets.Control2"); + RenameTypeProcessor processor= new RenameTypeProcessor(control); + processor.setNewElementName("Control"); + executeRefactoring(new RenameRefactoring(processor), true); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameTypePerfTests1.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameTypePerfTests1.java new file mode 100644 index 000000000..2507736f1 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameTypePerfTests1.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.test.performance.Dimension; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestSetup; + + +public class RenameTypePerfTests1 extends AbstractRenameTypePerfTest { + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("RenameTypePerfTests1"); + suite.addTest(new RenameTypePerfTests1("testCold_10_10")); + suite.addTest(new RenameTypePerfTests1("test_10_10")); + suite.addTest(new RenameTypePerfTests1("test_100_10")); + suite.addTest(new RenameTypePerfTests1("test_1000_10")); + return new RefactoringPerformanceTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringPerformanceTestSetup(someTest); + } + + public RenameTypePerfTests1(String name) { + super(name); + } + + public void testCold_10_10() throws Exception { + executeRefactoring(10, 10, false, 3); + } + + public void test_10_10() throws Exception { + executeRefactoring(10, 10, true, 10); + } + + public void test_100_10() throws Exception { + executeRefactoring(100, 10, true, 10); + } + + public void test_1000_10() throws Exception { + tagAsSummary("Rename type - 1000 CUs, 10 Refs", Dimension.ELAPSED_PROCESS); + executeRefactoring(1000, 10, true, 10); + } + + protected void assertMeasurements() { + assertPerformanceInRelativeBand(Dimension.CPU_TIME, -100, +10); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameTypePerfTests2.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameTypePerfTests2.java new file mode 100644 index 000000000..d67c219c6 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RenameTypePerfTests2.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.test.performance.Dimension; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestSetup; + + +public class RenameTypePerfTests2 extends AbstractRenameTypePerfTest { + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("RenameTypePerfTests2"); + suite.addTest(new RenameTypePerfTests2("testCold_10_10")); + suite.addTest(new RenameTypePerfTests2("test_10_10")); + suite.addTest(new RenameTypePerfTests2("test_10_100")); + suite.addTest(new RenameTypePerfTests2("test_10_1000")); + return new RefactoringPerformanceTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringPerformanceTestSetup(someTest); + } + + public RenameTypePerfTests2(String name) { + super(name); + } + + public void testCold_10_10() throws Exception { + executeRefactoring(10, 10, false, 3); + } + + public void test_10_10() throws Exception { + executeRefactoring(10, 10, true, 10); + } + + public void test_10_100() throws Exception { + executeRefactoring(10, 100, true, 10); + } + + public void test_10_1000() throws Exception { + tagAsSummary("Rename type - 10 CUs, 1000 Refs", Dimension.ELAPSED_PROCESS); + executeRefactoring(10, 1000, true, 10); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RepeatingRefactoringPerformanceTestCase.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RepeatingRefactoringPerformanceTestCase.java new file mode 100644 index 000000000..1c4dd0444 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/RepeatingRefactoringPerformanceTestCase.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (c) 2000, 2009 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import org.eclipse.test.performance.Dimension; + +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestCase; + + +public abstract class RepeatingRefactoringPerformanceTestCase extends RefactoringPerformanceTestCase { + + protected TestProject fTestProject; + + public RepeatingRefactoringPerformanceTestCase(String name) { + super(name); + } + + public TestProject getTestProject() { + return fTestProject; + } + + protected void executeRefactoring(int numberOfCus, int numberOfRefs, boolean measure, int sampleCount) throws Exception { + for (int i= 0; i < sampleCount; i++) { + try { + fTestProject= new TestProject(); + doExecuteRefactoring(numberOfCus, numberOfRefs, measure); + } finally { + fTestProject.delete(); + } + } + if (measure) { + commitMeasurements(); + assertMeasurements(); + } + } + + protected void finishMeasurements() { + stopMeasuring(); + } + + protected void assertMeasurements() { + assertPerformanceInRelativeBand(Dimension.ELAPSED_PROCESS, -100, +10); + } + + protected abstract void doExecuteRefactoring(int numberOfCus, int numberOfRefs, boolean measure) throws Exception; +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/TestProject.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/TestProject.java new file mode 100644 index 000000000..da3aab17f --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/reorg/TestProject.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.reorg; + +import junit.framework.Assert; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragmentRoot; + + +public class TestProject { + + private IJavaProject fTestProject; + private IPackageFragmentRoot fSourceFolder; + + public TestProject() throws Exception { + this("TestProject"); + } + + public TestProject(String name) throws Exception { + fTestProject= JavaProjectHelper.createJavaProject(name, "bin"); + // we must make sure that the performance test are compatible to 2.1.3 & 3.0 so use rt13 + Assert.assertTrue("rt not found", JavaProjectHelper.addRTJar13(fTestProject) != null); + fSourceFolder= JavaProjectHelper.addSourceContainer(fTestProject, "src"); + } + + public IJavaProject getProject() { + return fTestProject; + } + + public IPackageFragmentRoot getSourceFolder() { + return fSourceFolder; + } + + public void delete() throws Exception { + if (fTestProject != null && fTestProject.exists()) + JavaProjectHelper.delete(fTestProject); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/type/AllTypeConstraintsPerformanceTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/type/AllTypeConstraintsPerformanceTests.java new file mode 100644 index 000000000..a6943c2f4 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/type/AllTypeConstraintsPerformanceTests.java @@ -0,0 +1,23 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.type; + +import junit.framework.Test; +import junit.framework.TestSuite; + +public class AllTypeConstraintsPerformanceTests { + + public static Test suite() { + TestSuite suite= new TestSuite("All Type constraint Performance Tests"); //$NON-NLS-1$ + suite.addTest(ExtractInterfacePerfAcceptanceTests.suite()); + return suite; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/type/ExtractInterfaceHeapAcceptanceTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/type/ExtractInterfaceHeapAcceptanceTests.java new file mode 100644 index 000000000..915e74c93 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/type/ExtractInterfaceHeapAcceptanceTests.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (c) 2005, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.type; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring; + +import org.eclipse.jdt.core.Flags; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; + +import org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor; + +import org.eclipse.jdt.ui.tests.performance.SWTTestProject; +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringHeapTestCase; +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestSetup; + +import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; + +public class ExtractInterfaceHeapAcceptanceTests extends RefactoringHeapTestCase { + + private SWTTestProject fProject; + private Refactoring fRefactoring; + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("ExtractInterfaceHeapAcceptanceTests"); + suite.addTest(new ExtractInterfaceHeapAcceptanceTests("testExtractControl")); + return new RefactoringPerformanceTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringPerformanceTestSetup(someTest); + } + + public ExtractInterfaceHeapAcceptanceTests(String test) { + super(test); + } + + protected void setUp() throws Exception { + super.setUp(); + fProject= new SWTTestProject(); + IType control= fProject.getProject().findType("org.eclipse.swt.widgets.Control"); + + ExtractInterfaceProcessor processor= new ExtractInterfaceProcessor(control, JavaPreferencesSettings.getCodeGenerationSettings(fProject.getProject())); + fRefactoring= new ProcessorBasedRefactoring(processor); + + IMethod[] methods= control.getMethods(); + List extractedMembers= new ArrayList(); + for (int i= 0; i < methods.length; i++) { + IMethod method= methods[i]; + int flags= method.getFlags(); + if (Flags.isPublic(flags) && !Flags.isStatic(flags) && !method.isConstructor()) { + extractedMembers.add(method); + } + } + processor.setTypeName("IControl"); + processor.setExtractedMembers((IMember[])extractedMembers.toArray(new IMember[extractedMembers.size()])); + processor.setReplace(true); + } + + protected void tearDown() throws Exception { + fProject.delete(); + super.tearDown(); + } + + public void testExtractControl() throws Exception { + executeRefactoring(fRefactoring, true); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/type/ExtractInterfacePerfAcceptanceTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/type/ExtractInterfacePerfAcceptanceTests.java new file mode 100644 index 000000000..d7ff2300e --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/type/ExtractInterfacePerfAcceptanceTests.java @@ -0,0 +1,88 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.type; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.test.performance.Dimension; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring; + +import org.eclipse.jdt.core.Flags; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IType; + +import org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor; + +import org.eclipse.jdt.ui.tests.performance.SWTTestProject; +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestCase; +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringPerformanceTestSetup; + +import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; + +public class ExtractInterfacePerfAcceptanceTests extends RefactoringPerformanceTestCase { + + private SWTTestProject fProject; + private Refactoring fRefactoring; + + public static Test suite() { + // we must make sure that cold is executed before warm + TestSuite suite= new TestSuite("ExtractInterfacePerfAcceptanceTests"); + suite.addTest(new ExtractInterfacePerfAcceptanceTests("testExtractControl")); + return new RefactoringPerformanceTestSetup(suite); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringPerformanceTestSetup(someTest); + } + + public ExtractInterfacePerfAcceptanceTests(String test) { + super(test); + } + + protected void setUp() throws Exception { + super.setUp(); + fProject= new SWTTestProject(); + IType control= fProject.getProject().findType("org.eclipse.swt.widgets.Control"); + + ExtractInterfaceProcessor processor= new ExtractInterfaceProcessor(control, JavaPreferencesSettings.getCodeGenerationSettings(fProject.getProject())); + fRefactoring= new ProcessorBasedRefactoring(processor); + + IMethod[] methods= control.getMethods(); + List extractedMembers= new ArrayList(); + for (int i= 0; i < methods.length; i++) { + IMethod method= methods[i]; + int flags= method.getFlags(); + if (Flags.isPublic(flags) && !Flags.isStatic(flags) && !method.isConstructor()) { + extractedMembers.add(method); + } + } + processor.setTypeName("IControl"); + processor.setExtractedMembers((IMember[])extractedMembers.toArray(new IMember[extractedMembers.size()])); + processor.setReplace(true); + } + + protected void tearDown() throws Exception { + fProject.delete(); + super.tearDown(); + } + + public void testExtractControl() throws Exception { + tagAsSummary("Extract Interface - Elapsed Process", Dimension.ELAPSED_PROCESS); + executeRefactoring(fRefactoring, true); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/AllTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/AllTests.java new file mode 100644 index 000000000..95c9e931d --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/AllTests.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.typeconstraints; + + +import junit.framework.Test; +import junit.framework.TestSuite; + + +public class AllTests { + + public static Test suite ( ) { + TestSuite suite= new TestSuite("All Type constraints Tests"); + suite.addTest(TypeConstraintTests.suite()); + suite.addTest(TypeEnvironmentTests.suite()); + return suite; + } +} + + diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/PrettySignatures.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/PrettySignatures.java new file mode 100644 index 000000000..26d81a030 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/PrettySignatures.java @@ -0,0 +1,150 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.typeconstraints; + +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.dom.ITypeBinding; + +public class PrettySignatures { + + public static String get(ITypeBinding binding) { + if (binding.isTypeVariable()) { + return getTypeVariable(binding); + } + return getPlain(binding); + } + + private static String getPlain(ITypeBinding binding) { + if (binding.isPrimitive()) { + return binding.getName(); + } else if (binding.isArray()) { + return getPlainArrayType(binding); + } else if (binding.isRawType()) { + return getPlainRawType(binding); + } else if (binding.isGenericType()) { + return getPlainGenericType(binding); + } else if (binding.isParameterizedType()) { + return getPlainParameterizedType(binding); + } else if (binding.isTypeVariable()) { + return getPlainTypeVariable(binding); + } else if (binding.isWildcardType()) { + if (binding.isUpperbound()) { + return getPlainExtendsWildCardType(binding); + } else { + return getPlainSuperWildCardType(binding); + } + } else if (binding.isCapture()) { + return getPlainCaptureType(binding); + } + return getPlainStandardType(binding); + } + + private static String getPlainCaptureType(ITypeBinding binding) { + StringBuffer result= new StringBuffer("capture-of "); + result.append(PrettySignatures.getPlain(binding.getWildcard())); + return result.toString(); + } + + private static String getPlainSuperWildCardType(ITypeBinding binding) { + StringBuffer result= new StringBuffer("?"); + ITypeBinding bound= binding.getBound(); + if (bound != null) { + result.append(" super "); + result.append(PrettySignatures.getPlain(bound)); + } + return result.toString(); + } + + private static String getPlainExtendsWildCardType(ITypeBinding binding) { + StringBuffer result= new StringBuffer("?"); + ITypeBinding bound= binding.getBound(); + if (bound != null) { + result.append(" extends "); + result.append(PrettySignatures.getPlain(bound)); + } + return result.toString(); + } + + private static String getPlainParameterizedType(ITypeBinding binding) { + StringBuffer result= new StringBuffer(getQualifiedName(binding)); + ITypeBinding[] typeArguments= binding.getTypeArguments(); + result.append("<"); //$NON-NLS-1$ + result.append(PrettySignatures.getPlain(typeArguments[0])); + for (int i= 1; i < typeArguments.length; i++) { + result.append(", "); //$NON-NLS-1$ + result.append(PrettySignatures.getPlain(typeArguments[i])); + } + result.append(">"); //$NON-NLS-1$ + return result.toString(); + } + + private static String getPlainGenericType(ITypeBinding binding) { + StringBuffer result= new StringBuffer(getQualifiedName(binding)); + ITypeBinding[] typeParameters= binding.getTypeParameters(); + result.append("<"); //$NON-NLS-1$ + result.append(PrettySignatures.get(typeParameters[0])); + for (int i= 1; i < typeParameters.length; i++) { + result.append(", "); //$NON-NLS-1$ + result.append(PrettySignatures.get(typeParameters[i])); + } + result.append(">"); //$NON-NLS-1$ + return result.toString(); + } + + private static String getTypeVariable(ITypeBinding binding) { + ITypeBinding[] bounds= binding.getTypeBounds(); + if (bounds.length == 1 && bounds[0].getQualifiedName().equals("java.lang.Object")) + return binding.getName(); + + StringBuffer result= new StringBuffer(binding.getName()); + if (bounds.length > 0) { + result.append(" extends "); //$NON-NLS-1$ + result.append(PrettySignatures.getPlain(bounds[0])); + for (int i= 1; i < bounds.length; i++) { + result.append(" & "); //$NON-NLS-1$ + result.append(PrettySignatures.getPlain(bounds[i])); + } + } + return result.toString(); + } + + private static String getPlainTypeVariable(ITypeBinding binding) { + return binding.getName(); + } + + private static String getPlainRawType(ITypeBinding binding) { + return getQualifiedName(binding); + } + + private static String getPlainArrayType(ITypeBinding binding) { + StringBuffer result= new StringBuffer(PrettySignatures.getPlain(binding.getElementType())); + for (int i= 0; i < binding.getDimensions(); i++) { + result.append("[]"); + } + return result.toString(); + } + + private static String getPlainStandardType(ITypeBinding binding) { + return getQualifiedName(binding); + } + + private static String getQualifiedName(ITypeBinding binding) { + if (binding.isLocal()) + return ((IType)binding.getJavaElement()).getFullyQualifiedName('.'); + String result= binding.getQualifiedName(); + if (binding.isParameterizedType()) { + int index= result.indexOf('<'); + if (index != -1) + return result.substring(0, index); + } + return result; + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/TypeConstraintTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/TypeConstraintTests.java new file mode 100644 index 000000000..77346d796 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/TypeConstraintTests.java @@ -0,0 +1,254 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.typeconstraints; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.dom.CompilationUnit; + +import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.ASTCreator; +import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.ConstraintCollector; +import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.ConstraintOperator; +import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.ConstraintVariable; +import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.ConstraintVariableFactory; +import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.FullConstraintCreator; +import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.ITypeConstraint; +import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.TypeConstraintFactory; + +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTest; +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSetup; + +public class TypeConstraintTests extends RefactoringTest { + + private static final Class clazz= TypeConstraintTests.class; + private static final String PATH= "TypeConstraints/"; + + public TypeConstraintTests(String name) { + super(name); + } + + protected String getRefactoringPath() { + return PATH; + } + + public static Test suite() { + return new RefactoringTestSetup(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new RefactoringTestSetup(someTest); + } + + private String getSimpleTestFileName(){ + return "A_" + getName() + ".java"; + } + + private String getTestFileName(){ + return TEST_PATH_PREFIX + getRefactoringPath() + getSimpleTestFileName(); + } + + private ICompilationUnit createCUfromTestFile(IPackageFragment pack) throws Exception { + return createCU(pack, getSimpleTestFileName(), getFileContents(getTestFileName())); + } + + private CompilationUnit getCuNode() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP()); + return ASTCreator.createAST(cu, null); + } + + private void numberHelper(int number) throws Exception { + CompilationUnit cuNode= getCuNode(); + ConstraintCollector collector= getCollector(); + cuNode.accept(collector); + ITypeConstraint[] constraints= collector.getConstraints(); + assertEquals(Arrays.asList(constraints).toString(), number, constraints.length); + } + + public void testNumber0() throws Exception{ + numberHelper(2); + } + + public void testNumber1() throws Exception{ + numberHelper(3); + } + + public void testNumber2() throws Exception{ + numberHelper(10); + } + + private ConstraintCollector getCollector() { + TypeConstraintFactory factory = new TypeConstraintFactory(){ + public boolean filter(ConstraintVariable v1, ConstraintVariable v2, ConstraintOperator o){ + return false; + } + }; + ConstraintCollector collector= new ConstraintCollector(new FullConstraintCreator(new ConstraintVariableFactory(), factory)); + return collector; + } + + private static List allToStrings(Object[] elements) { + String[] strings= new String[elements.length]; + for (int i= 0; i < elements.length; i++) { + strings[i]= elements[i].toString(); + } + return new ArrayList(Arrays.asList(strings));//want to be able to remove stuff from it + } + + private void testConstraints(String[] constraintStrings) throws Exception{ + CompilationUnit cuNode= getCuNode(); + ConstraintCollector collector= getCollector(); + cuNode.accept(collector); + ITypeConstraint[] constraints= collector.getConstraints(); + + List externals= allToStrings(constraints); + assertEquals("length", constraintStrings.length, constraints.length); + for (int i= 0; i < constraintStrings.length; i++) { + assertTrue("missing constraint:" + constraintStrings[i], externals.remove(constraintStrings[i])); + } + } + + public void testConstraints0() throws Exception{ + String[] strings= {"[null] <= [a0]", "[a0] <= [a1]", "[a0] =^= A", "[a1] =^= A", "Decl(A:f()) =^= p.A"}; + testConstraints(strings); + } + + public void testConstraints1() throws Exception{ + String[] strings= {"[null] <= [a0]", "[a0] == [a1]", "[a0] =^= A", "[a1] =^= A", "Decl(A:a0) =^= p.A", "Decl(A:a1) =^= p.A"}; + testConstraints(strings); + } + + public void testConstraints2() throws Exception{ + String[] strings= {"[null] <= [a0]", "[(A)a0] =^= A", "[(A)a0] <= [a1]", "[a0] <= [(A)a0] or [(A)a0] <= [a0]", "[a0] =^= A", "[a1] =^= A", "Decl(A:f()) =^= p.A"}; + testConstraints(strings); + } + + public void testConstraints3() throws Exception{ + String[] strings= {"[null] <= [a]", "[null] <= [b]", "[a] == [b]", "[a] =^= A", "[b] =^= A", "Decl(A:f()) =^= p.A"}; + testConstraints(strings); + } + + public void testConstraints4() throws Exception{ + String[] strings= {"[as0] =^= A[]", "[a0] <= A", "[{a0}] <= [as0]", "Decl(A:f()) =^= p.A", "[null] <= [a0]", "[a0] =^= A"}; + testConstraints(strings); + } + + public void testConstraints5() throws Exception{ + String[] strings= {"[as0] =^= A[]", "Decl(A:f()) =^= p.A", "[a0] <= A", "[a0] =^= A", "[null] <= [a0]", "[new A[]{a0}] <= [as0]"}; + testConstraints(strings); + } + + public void testConstraints6() throws Exception{ + String[] strings= {"Decl(A:f()) =^= p.A", "Decl(A:A(A)) =^= p.A", "[new A(a0)] =^= p.A", "[a0] <= [Parameter(0,A:A(A))]", "[a1] =^= A", "[a] =^= A", "[a0] =^= A", "[null] <= [a0]", "[new A(a0)] <= [a1]", "[Parameter(0,A:A(A))] =^= [a]"}; + testConstraints(strings); + } + + public void testConstraints7() throws Exception{ + String[] strings= {"Decl(A:A()) =^= p.A", "Decl(A:A(A)) =^= p.A", "[null] <= [Parameter(0,A:A(A))]", "[Parameter(0,A:A(A))] =^= [a]", "[a] =^= A"}; + testConstraints(strings); + } + + public void testConstraints8() throws Exception{ + String[] strings= {"Decl(A:x) =^= p.A", "Decl(A:f()) =^= p.A", "[x] =^= java.lang.Object", "Decl(A:aField) =^= p.A", "[this] <= [x]", "[aField] =^= A", "[x] =^= Object", "[this] =^= p.A", "[aField] <= Decl(A:x)"}; + testConstraints(strings); + } + + public void testConstraints9() throws Exception{ + String[] strings= {"Decl(A:f()) =^= p.A", "[a] =^= A", "[x] =^= boolean", "[a instanceof A] <= [x]", "[null] <= [a]", "[a] <= A or A <= [a]"}; + testConstraints(strings); + } + + public void testConstraints10() throws Exception{ + String[] strings= {"[null] <= [A:f1()]_returnType", "Decl(A:f1()) =^= p.A", "[A:f1()]_returnType =^= A[]"}; + testConstraints(strings); + } + + public void testConstraints11() throws Exception{ + String[] strings= {"[null] <= [A:f(A, Object)]_returnType", "[Parameter(1,B:f(A, Object))] =^= [a4]", + "[B:f(A, Object)]_returnType =^= A", "Decl(B:f(A, Object)) < Decl(A:f(A, Object))", + "[Parameter(1,A:f(A, Object))] == [Parameter(1,B:f(A, Object))]", + "[Parameter(0,A:f(A, Object))] == [Parameter(0,B:f(A, Object))]", + "[A:f(A, Object)]_returnType == [B:f(A, Object)]_returnType", + "[Parameter(0,B:f(A, Object))] =^= [a3]", + "[Parameter(0,A:f(A, Object))] =^= [a0]", "Decl(A:f(A, Object)) =^= p.A", + "[null] <= [B:f(A, Object)]_returnType", "[Parameter(1,A:f(A, Object))] =^= [a1]", + "[A:f(A, Object)]_returnType =^= A", "Decl(B:f(A, Object)) =^= p.B", + "[a3] =^= A", "[a0] =^= A", "[a1] =^= Object", "[a4] =^= Object"}; + testConstraints(strings); + } + + public void testConstraints12() throws Exception{ + String[] strings= { "Decl(B:f(A, Object)) =^= p.B", "[Parameter(1,B:f(A, Object))] =^= [a4]", "[B:f(A, Object)]_returnType =^= A", "[null] <= [B:f(A, Object)]_returnType", "[A:f(A, Object)]_returnType =^= A", "[Parameter(1,A:f(A, Object))] =^= [a1]", "Decl(A:f(A, Object)) =^= p.A", "[Parameter(0,B:f(A, Object))] =^= [a3]", "[null] <= [A:f(A, Object)]_returnType", "[Parameter(0,A:f(A, Object))] =^= [a0]", "[a3] =^= A", "[a0] =^= A", "[a1] =^= Object", "[a4] =^= Object" }; + testConstraints(strings); + } + + public void testConstraints13() throws Exception{ + String[] strings= {"Decl(B:f(A, Object)) =^= p.B", "[Parameter(1,B:f(A, Object))] =^= [a4]", "[B:f(A, Object)]_returnType =^= A", "[null] <= [B:f(A, Object)]_returnType", "[A:f(A, Object)]_returnType =^= A", "[Parameter(1,A:f(A, Object))] =^= [a1]", "Decl(A:f(A, Object)) =^= p.A", "[Parameter(0,B:f(A, Object))] =^= [a3]", "[null] <= [A:f(A, Object)]_returnType", "[Parameter(0,A:f(A, Object))] =^= [a0]", "[a3] =^= A", "[a0] =^= A", "[a1] =^= Object", "[a4] =^= Object"}; + testConstraints(strings); + } + + public void testConstraints14() throws Exception{ + String[] strings= {"[A:f(A)]_returnType == [B:f(A)]_returnType", "[Parameter(0,A:f(A))] == [Parameter(0,B:f(A))]", "[B:f(A)]_returnType =^= A", "Decl(B:f(A)) < Decl(A:f(A))", "[A:f(A)]_returnType =^= A", "Decl(B:f(A)) < Decl(I:f(A))", "[null] <= [A:f(A)]_returnType", "[Parameter(0,A:f(A))] =^= [a0]", "[I:f(A)]_returnType =^= A", "Decl(A:f(A)) =^= p.A", "[ax] =^= B", "[Parameter(0,B:f(A))] =^= [a3]", "[null] <= [B:f(A)]_returnType", "[a3] <= [Parameter(0,B:f(A))]", "[ax.f(a3)] =^= [B:f(A)]_returnType", "[ax] <= Decl(I:f(A)) or [ax] <= Decl(A:f(A))", "Decl(B:f(A)) =^= p.B", "[I:f(A)]_returnType == [B:f(A)]_returnType", "[Parameter(0,I:f(A))] == [Parameter(0,B:f(A))]", "[null] <= [ax]", "[Parameter(0,I:f(A))] =^= [ai]", "Decl(I:f(A)) =^= p.I", "[a3] =^= A", "[a0] =^= A", "[ai] =^= A"}; + testConstraints(strings); + } + + public void testConstraints15() throws Exception{ + String[] strings= {"[Parameter(0,A:f(A))] =^= [a0]", "[I:f(A)]_returnType == [B:f(A)]_returnType", "[Parameter(0,I:f(A))] == [Parameter(0,B:f(A))]", "[null] <= [A:f(A)]_returnType", "[A:f(A)]_returnType == [B:f(A)]_returnType", "[Parameter(0,A:f(A))] == [Parameter(0,B:f(A))]", "Decl(B:f(A)) < Decl(A:f(A))", "[super.f(a3)] =^= [A:f(A)]_returnType", "Decl(A:f(A)) =^= p.A", "[null] <= [B:f(A)]_returnType", "[Parameter(0,I:f(A))] =^= [ai]", "[Parameter(0,B:f(A))] =^= [a3]", "[A:f(A)]_returnType =^= A", "Decl(B:f(A)) =^= p.B", "Decl(I:f(A)) =^= p.I", "Decl(B:f(A)) < Decl(I:f(A))", "[a3] <= [Parameter(0,A:f(A))]", "[I:f(A)]_returnType =^= A", "[B:f(A)]_returnType =^= A", "[a3] =^= A", "[a0] =^= A", "[ai] =^= A"}; + testConstraints(strings); + } + + public void testConstraints16() throws Exception{ + String[] strings= {"Decl(A:aField) =^= p.A", "Decl(A:f()) =^= p.A", "[this] =^= p.A", "[this] =^= p.A", "[this] <= [aTemp]", "[this] <= [aField]", "[this] <= [a]", "[a] =^= A", "[aField] =^= A", "[aTemp] =^= A", "[this] =^= p.A"}; + testConstraints(strings); + } + + public void testConstraints17() throws Exception{ + String[] strings= {"Decl(A:f()) =^= p.A", "[null] <= [a]", "[A:f()]_returnType =^= A", "[a] =^= A", "[a] <= [A:f()]_returnType"}; + testConstraints(strings); + } + + public void testConstraints18() throws Exception{ + String[] strings= {"[Parameter(0,B:B(A))] =^= [a1]", "Decl(B:B(A)) =^= p.B", "[Parameter(0,A:A(A))] =^= [a0]", "Decl(A:A(A)) =^= p.A", "[a1] <= [Parameter(0,A:A(A))]", "[a1] =^= A", "[a0] =^= A"}; + testConstraints(strings); + } + + public void testConstraints19() throws Exception{ + String[] strings= {"[aField] =^= p.A", "[a] =^= A", "Decl(B:f()) =^= p.B", "[a] <= [aField]", "[null] <= [a]", "Decl(A:aField) =^= p.A", "[aField] =^= A"}; + testConstraints(strings); + } + + public void testConstraints20() throws Exception{ + String[] strings= {"Decl(B:aField) =^= p.B", "Decl(A:aField) =^= p.A", "Decl(B:aField) < Decl(A:aField)", "[aField] =^= A", "[aField] =^= A"}; + testConstraints(strings); + } + + public void testConstraints21() throws Exception{ + String[] strings= {"Decl(A:f2(A[])) =^= p.A", "[Parameter(0,A:f2(A[]))] =^= [as]", "[as] =^= A[]"}; + testConstraints(strings); + } + + public void testConstraints22() throws Exception{ + String[] strings= {"[null] <= [A:f(A, Object)]_returnType", "[Parameter(0,A:f(A, Object))] =^= [a0]", "[Parameter(1,A:f(A, Object))] =^= [a1]", "[A:f(A, Object)]_returnType =^= A", "Decl(A:f(A, Object)) =^= p.A", "[a1] =^= Object", "[a0] =^= A"}; + testConstraints(strings); + } + + public void testConstraints23() throws Exception{ + //test for bug 41271 NullPointerException dumping set of ITypeConstraints to System.out + String[] strings= {"[args.length] =^= int", "[0] <= [i]", "[i] =^= int", "[args] <= Decl((array type):length)", "[args] =^= String[]", "[Parameter(0,Test1:main(String[]))] =^= [args]", "Decl(Test1:main(String[])) =^= p.Test1"}; + testConstraints(strings); + } +} diff --git a/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/TypeEnvironmentTests.java b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/TypeEnvironmentTests.java new file mode 100644 index 000000000..4c5004976 --- /dev/null +++ b/testplugins/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/TypeEnvironmentTests.java @@ -0,0 +1,368 @@ +/******************************************************************************* + * Copyright (c) 2000, 2008 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring.typeconstraints; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ASTParser; +import org.eclipse.jdt.core.dom.ASTVisitor; +import org.eclipse.jdt.core.dom.Assignment; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.Expression; +import org.eclipse.jdt.core.dom.FieldDeclaration; +import org.eclipse.jdt.core.dom.IBinding; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.SimpleName; +import org.eclipse.jdt.core.dom.VariableDeclarationFragment; + +import org.eclipse.jdt.internal.corext.dom.HierarchicalASTVisitor; +import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.types.TType; +import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.types.TypeEnvironment; + +import org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSetup; +import org.eclipse.jdt.ui.tests.refactoring.infra.AbstractCUTestCase; +import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringTestPlugin; + +public class TypeEnvironmentTests extends AbstractCUTestCase { + + private static final boolean BUG_83616_core_wildcard_assignments= true; + + private static class MyTestSetup extends RefactoringTestSetup { + private static IPackageFragment fSignaturePackage; + private static IPackageFragment fGenericPackage; + public MyTestSetup(Test test) { + super(test); + } + protected void setUp() throws Exception { + super.setUp(); + fSignaturePackage= getDefaultSourceFolder().createPackageFragment("signature", true, null); + fGenericPackage= getDefaultSourceFolder().createPackageFragment("generic", true, null); + } + public static IPackageFragment getSignaturePackage() { + return fSignaturePackage; + } + public static IPackageFragment getGenericPackage() { + return fGenericPackage; + } + } + + private static class CreationChecker extends HierarchicalASTVisitor { + private TypeEnvironment fTypeEnvironment; + public CreationChecker() { + fTypeEnvironment= new TypeEnvironment(); + } + public boolean visit(SimpleName node) { + IBinding binding= node.resolveBinding(); + if (!(binding instanceof ITypeBinding)) + return true; + checkTypeBinding(binding); + return true; + } + private void checkTypeBinding(IBinding binding) { + ITypeBinding type= (ITypeBinding)binding; + if (!(type.isPrimitive() && type.getName().equals("void"))) { + TType refType= fTypeEnvironment.create(type); + assertNotNull("Refactoring type is null", refType); + assertEquals("Not same name", type.getName(), refType.getName()); + assertEquals("Not same signature", PrettySignatures.get(type), refType.getPrettySignature()); + assertTrue("Not same type", refType == fTypeEnvironment.create(type)); + } + } + public boolean visit(org.eclipse.jdt.core.dom.Type node) { + checkTypeBinding(node.resolveBinding()); + return true; + } + } + + private static class TypeBindingCollector extends ASTVisitor { + private List fResult= new ArrayList(); + private List fWildcards= new ArrayList(); + public boolean visit(FieldDeclaration node) { + VariableDeclarationFragment fragment= (VariableDeclarationFragment)node.fragments().get(0); + if (fragment.getName().getIdentifier().equals("NullType")) { + fResult.add(fragment.getInitializer().resolveTypeBinding()); + } else { + fResult.add(fragment.resolveBinding().getType()); + } + return false; + } + public void endVisit(CompilationUnit node) { + for (Iterator iter= fResult.iterator(); iter.hasNext();) { + ITypeBinding binding= (ITypeBinding)iter.next(); + if (binding.isParameterizedType()) { + ITypeBinding[] args= binding.getTypeArguments(); + for (int i= 0; i < args.length; i++) { + if (args[i].isWildcardType()) { + fWildcards.add(args[i]); + } + } + } + } + } + public ITypeBinding[] getResult() { + return (ITypeBinding[])fResult.toArray(new ITypeBinding[fResult.size()]); + } + public ITypeBinding[] getWildcards() { + return (ITypeBinding[])fWildcards.toArray(new ITypeBinding[fWildcards.size()]); + } + } + + private static class CaptureTypeBindingCollector extends ASTVisitor { + private List fResult= new ArrayList(); + public boolean visit(Assignment node) { + Expression expression= node.getRightHandSide(); + ITypeBinding typeBinding= expression.resolveTypeBinding(); + fResult.add(typeBinding); + collectTypeArgumentBindings(typeBinding, fResult); + return false; + } + private void collectTypeArgumentBindings(ITypeBinding typeBinding, List result) { + if (! typeBinding.isParameterizedType()) + return; + ITypeBinding[] typeArguments= typeBinding.getTypeArguments(); + for (int i= 0; i < typeArguments.length; i++) { + ITypeBinding typeArgument= typeArguments[i]; + if (BUG_83616_core_wildcard_assignments && typeArgument.isParameterizedType() && typeArgument.getTypeArguments()[0].isWildcardType()) + continue; + result.add(typeArgument); + collectTypeArgumentBindings(typeArgument, result); + } + } + public ITypeBinding[] getResult() { + return (ITypeBinding[])fResult.toArray(new ITypeBinding[fResult.size()]); + } + } + + + public TypeEnvironmentTests(String name) { + super(name); + } + + public static Test suite() { + return new MyTestSetup(new TestSuite(TypeEnvironmentTests.class)); + } + + public static Test setUpTest(Test someTest) { + return new MyTestSetup(someTest); + } + + protected InputStream getFileInputStream(String fileName) throws IOException { + return RefactoringTestPlugin.getDefault().getTestResourceStream(fileName); + } + + protected String getResourceLocation() { + return "TypeEnvironment/TestProject/"; + } + + protected String adaptName(String name) { + return Character.toUpperCase(name.charAt(0)) + name.substring(1) + ".java"; + } + + private ASTNode createAST(IPackageFragment pack) throws Exception { + IJavaProject project= pack.getJavaProject(); + ASTParser parser= ASTParser.newParser(AST.JLS3); + parser.setProject(project); + parser.setResolveBindings(true); + ICompilationUnit unit= createCU(pack, getName()); + parser.setSource(unit); + return parser.createAST(null); + } + + //---- creation ---------------------------------------------------------- + + private void performCreationTest() throws Exception { + createAST(MyTestSetup.getSignaturePackage()).accept(new CreationChecker()); + } + + public void testArrays() throws Exception { + performCreationTest(); + } + + public void testStandardTypes() throws Exception { + performCreationTest(); + } + + public void testRawTypes() throws Exception { + performCreationTest(); + } + + public void testGenericTypes() throws Exception { + performCreationTest(); + } + + public void testWildcardTypes() throws Exception { + performCreationTest(); + } + + public void testPrimitiveTypes() throws Exception { + performCreationTest(); + } + + public void testTypeVariables() throws Exception { + performCreationTest(); + } + + //---- generic assigment test ---------------------------------------------- + + private void performGenericAssignmentTest() throws Exception { + ASTNode node= createAST(MyTestSetup.getGenericPackage()); + TypeBindingCollector collector= new TypeBindingCollector(); + node.accept(collector); + testBindings(collector.getResult()); + testAssignment(collector.getWildcards()); + } + + private void testBindings(ITypeBinding[] bindings) throws Exception { + TType[] types= new TType[bindings.length]; + TypeEnvironment environment= new TypeEnvironment(); + for (int i= 0; i < bindings.length; i++) { + types[i]= environment.create(bindings[i]); + assertEquals("Not same name", bindings[i].getName(), types[i].getName()); + assertEquals("Not same signature", PrettySignatures.get(bindings[i]), types[i].getPrettySignature()); + assertEquals("Not same modifiers", bindings[i].getModifiers(), types[i].getModifiers()); + testFlags(bindings[i], types[i]); + assertTrue("Not same erasure", types[i].getErasure().isEqualTo(bindings[i].getErasure())); + assertTrue("Not same type declaration", types[i].getTypeDeclaration().isEqualTo(bindings[i].getTypeDeclaration())); + assertTrue("Not same type", types[i] == environment.create(bindings[i])); + + } + for (int o= 0; o < bindings.length; o++) { + for (int i= 0; i < bindings.length; i++) { + checkCanAssignTo(bindings[o], bindings[i], types[o], types[i]); + } + } + TypeEnvironment secondEnvironment= new TypeEnvironment(); + for (int i= 0; i < bindings.length; i++) { + assertTrue("Equal to second environment", types[i].equals(secondEnvironment.create(bindings[i]))); + } + ITypeBinding[] restoredBindings= TypeEnvironment.createTypeBindings(types, RefactoringTestSetup.getProject()); + assertEquals("Not same length", restoredBindings.length, bindings.length); + for (int i= 0; i < restoredBindings.length; i++) { + assertTrue("Not same binding", bindings[i].isEqualTo(restoredBindings[i])); + } + } + + private void checkCanAssignTo(ITypeBinding rhsBinding, ITypeBinding lhsBinding, TType rhs, TType lhs) { + boolean coreResult= rhsBinding.isAssignmentCompatible(lhsBinding); + boolean uiResult= rhs.canAssignTo(lhs); + if (coreResult != uiResult) { + if (lhs.isCaptureType() || rhs.isCaptureType()) { // see bug 93082 + System.out.println("Different assignment rule(" + + PrettySignatures.get(lhsBinding) + "= " + PrettySignatures.get(rhsBinding) + + "): Bindings<" + coreResult + + "> TType<" + uiResult + ">"); + return; + } + } + + assertEquals("Different assignment rule(" + + PrettySignatures.get(lhsBinding) + "= " + PrettySignatures.get(rhsBinding) + + "): ", coreResult, uiResult); + } + + private void testAssignment(ITypeBinding[] bindings) { + TType[] types= new TType[bindings.length]; + TypeEnvironment environment= new TypeEnvironment(); + for (int i= 0; i < bindings.length; i++) { + types[i]= environment.create(bindings[i]); + } + for (int o= 0; o < bindings.length; o++) { + for (int i= 0; i < bindings.length; i++) { + ITypeBinding oBinding= bindings[o]; + ITypeBinding iBinding= bindings[i]; + boolean coreResult= oBinding.isAssignmentCompatible(iBinding); + TType oType= types[o]; + TType iType= types[i]; + boolean uiResult= oType.canAssignTo(iType); + if (coreResult != uiResult && !oType.isWildcardType() && ! BUG_83616_core_wildcard_assignments) { // see bug 83616 + System.out.println("Different assignment rule(" + + PrettySignatures.get(iBinding) + "= " + PrettySignatures.get(oBinding) + + "): Bindings<" + coreResult + + "> TType<" + uiResult + ">"); + } + } + } + } + + private void testFlags(ITypeBinding binding, TType type) { + assertEquals("Different class flag", binding.isClass(), type.isClass()); + assertEquals("Different enum flag", binding.isEnum(), type.isEnum()); + assertEquals("Different interface flag", binding.isInterface(), type.isInterface()); + assertEquals("Different annotation flag", binding.isAnnotation(), type.isAnnotation()); + + assertEquals("Different top level flag", binding.isTopLevel(), type.isTopLevel()); + assertEquals("Different nested flag", binding.isNested(), type.isNested()); + assertEquals("Different local flag", binding.isLocal(), type.isLocal()); + assertEquals("Different member flag", binding.isMember(), type.isMember()); + assertEquals("Different anonymous flag", binding.isAnonymous(), type.isAnonymous()); + } + + public void testStandardAssignments() throws Exception { + performGenericAssignmentTest(); + } + + public void testWildcardAssignments() throws Exception { + performGenericAssignmentTest(); + } + + public void testTypeVariableAssignments() throws Exception { + performGenericAssignmentTest(); + } + + public void testCaptureAssignments() throws Exception { + ASTNode node= createAST(MyTestSetup.getGenericPackage()); + CaptureTypeBindingCollector collector= new CaptureTypeBindingCollector(); + node.accept(collector); + testBindings(collector.getResult()); + } + + public void _testAssignment() throws Exception { + ASTNode node= createAST(MyTestSetup.getGenericPackage()); + TypeBindingCollector collector= new TypeBindingCollector(); + node.accept(collector); + ITypeBinding[] bindings= collector.getResult(); + TType[] types= new TType[bindings.length]; + TypeEnvironment environment= new TypeEnvironment(); + for (int i= 0; i < bindings.length; i++) { + types[i]= environment.create(bindings[i]); + } + System.out.println(PrettySignatures.get(bindings[0]) + "= " + PrettySignatures.get(bindings[1]) + + ": " + bindings[1].isAssignmentCompatible(bindings[0])); + // types[1].canAssignTo(types[0]); + } + + public void _testParameterizedToGeneric() throws Exception { + ASTNode node= createAST(MyTestSetup.getGenericPackage()); + TypeBindingCollector collector= new TypeBindingCollector(); + node.accept(collector); + ITypeBinding[] bindings= collector.getResult(); + bindings[0]= bindings[0].getTypeDeclaration(); + System.out.println(PrettySignatures.get(bindings[0]) + "= " + PrettySignatures.get(bindings[1]) + + ": " + bindings[1].isAssignmentCompatible(bindings[0])); + System.out.println(PrettySignatures.get(bindings[0]) + "= " + PrettySignatures.get(bindings[0]) + + ": " + bindings[0].isAssignmentCompatible(bindings[0])); + bindings[1]= bindings[1].getTypeDeclaration(); + System.out.println(PrettySignatures.get(bindings[0]) + "= " + PrettySignatures.get(bindings[1]) + + ": " + bindings[1].isAssignmentCompatible(bindings[0])); + } +} |