-
Notifications
You must be signed in to change notification settings - Fork 86
/
CleanUpTestCase.java
358 lines (283 loc) · 13.5 KB
/
CleanUpTestCase.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*******************************************************************************
* Copyright (c) 2005, 2020 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.tests.quickfix;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.junit.After;
import org.junit.Before;
import org.junit.jupiter.api.Assertions;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.testplugin.TestOptions;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.CheckConditionsOperation;
import org.eclipse.ltk.core.refactoring.CompositeChange;
import org.eclipse.ltk.core.refactoring.CreateChangeOperation;
import org.eclipse.ltk.core.refactoring.GroupCategory;
import org.eclipse.ltk.core.refactoring.IUndoManager;
import org.eclipse.ltk.core.refactoring.PerformChangeOperation;
import org.eclipse.ltk.core.refactoring.RefactoringCore;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.TextEditBasedChange;
import org.eclipse.ltk.core.refactoring.TextEditBasedChangeGroup;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jdt.internal.core.manipulation.CodeTemplateContextType;
import org.eclipse.jdt.internal.core.manipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.IASTSharedValues;
import org.eclipse.jdt.internal.corext.fix.CleanUpConstants;
import org.eclipse.jdt.internal.corext.fix.CleanUpPreferenceUtil;
import org.eclipse.jdt.internal.corext.fix.CleanUpRefactoring;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.cleanup.CleanUpOptions;
import org.eclipse.jdt.ui.cleanup.ICleanUp;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.preferences.cleanup.CleanUpProfileVersioner;
import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager;
import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager.CustomProfile;
import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager.Profile;
import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileStore;
public abstract class CleanUpTestCase extends QuickFixTest {
protected static final String FIELD_COMMENT= "/* Test */";
protected IPackageFragmentRoot fSourceFolder;
private CustomProfile fProfile;
@Before
public void setUp() throws Exception {
Hashtable<String, String> options= TestOptions.getDefaultOptions();
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4");
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, true);
store.setValue(PreferenceConstants.CODEGEN_KEYWORD_THIS, false);
StubUtility.setCodeTemplate(CodeTemplateContextType.METHODSTUB_ID, "//TODO\n${body_statement}", null);
StubUtility.setCodeTemplate(CodeTemplateContextType.OVERRIDECOMMENT_ID, "/* comment */", null);
StubUtility.setCodeTemplate(CodeTemplateContextType.FIELDCOMMENT_ID, FIELD_COMMENT, null);
Preferences corePrefs= JavaPlugin.getJavaCorePluginPreferences();
corePrefs.setValue(JavaCore.CODEASSIST_FIELD_PREFIXES, "");
corePrefs.setValue(JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES, "");
corePrefs.setValue(JavaCore.CODEASSIST_FIELD_SUFFIXES, "");
corePrefs.setValue(JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES, "");
fSourceFolder= JavaProjectHelper.addSourceContainer(getProject(), "src");
Map<String, String> settings= new Hashtable<>();
fProfile= new ProfileManager.CustomProfile("testProfile", settings, CleanUpProfileVersioner.CURRENT_VERSION, CleanUpProfileVersioner.PROFILE_KIND);
InstanceScope.INSTANCE.getNode(JavaUI.ID_PLUGIN).put(CleanUpConstants.CLEANUP_PROFILE, fProfile.getID());
InstanceScope.INSTANCE.getNode(JavaUI.ID_PLUGIN).put(CleanUpConstants.SAVE_PARTICIPANT_PROFILE, fProfile.getID());
disableAll();
}
@After
public void tearDown() throws Exception {
JavaProjectHelper.clear(getProject(), getDefaultClasspath());
disableAll();
fSourceFolder= null;
fProfile= null;
}
protected abstract IJavaProject getProject();
protected abstract IClasspathEntry[] getDefaultClasspath() throws CoreException;
private void disableAll() throws CoreException {
Map<String, String> settings= fProfile.getSettings();
CleanUpOptions options= JavaPlugin.getDefault().getCleanUpRegistry().getDefaultOptions(CleanUpConstants.DEFAULT_CLEAN_UP_OPTIONS);
for (String key : options.getKeys()) {
settings.put(key, CleanUpOptions.FALSE);
}
commitProfile();
}
protected void disable(String key) throws CoreException {
fProfile.getSettings().put(key, CleanUpOptions.FALSE);
commitProfile();
}
protected void enable(String key) throws CoreException {
fProfile.getSettings().put(key, CleanUpOptions.TRUE);
commitProfile();
}
private void commitProfile() throws CoreException {
List<Profile> profiles= CleanUpPreferenceUtil.getBuiltInProfiles();
profiles.add(fProfile);
CleanUpProfileVersioner versioner= new CleanUpProfileVersioner();
ProfileStore profileStore= new ProfileStore(CleanUpConstants.CLEANUP_PROFILES, versioner);
profileStore.writeProfiles(profiles, InstanceScope.INSTANCE);
CleanUpPreferenceUtil.saveSaveParticipantOptions(InstanceScope.INSTANCE, fProfile.getSettings());
}
private void collectGroupCategories(Set<GroupCategory> result, Change change) {
if (change instanceof TextEditBasedChange) {
for (TextEditBasedChangeGroup group : ((TextEditBasedChange)change).getChangeGroups()) {
result.addAll(group.getGroupCategorySet().asList());
}
} else if (change instanceof CompositeChange) {
for (Change child : ((CompositeChange)change).getChildren()) {
collectGroupCategories(result, child);
}
}
}
/**
* @param cus The compilation units
* @param setOfExpectedGroupCategories The expected group categories
* @throws CoreException The core exception
* @deprecated Use assertRefactoringResultAsExpected(ICompilationUnit[] cus, String[] expected, Set<String> expectedGroupCategories) instead.
*/
@Deprecated
protected void assertGroupCategoryUsed(ICompilationUnit[] cus, Set<String> setOfExpectedGroupCategories) throws CoreException {
final CleanUpRefactoring ref= new CleanUpRefactoring();
ref.setUseOptionsFromProfile(true);
ICleanUp[] cleanUps= JavaPlugin.getDefault().getCleanUpRegistry().createCleanUps();
for (ICompilationUnit cu : cus) {
assertNotNull("No compilation unit should be null", cu);
ref.addCompilationUnit(cu);
}
for (ICleanUp cleanUp : cleanUps) {
ref.addCleanUp(cleanUp);
}
final CreateChangeOperation create= new CreateChangeOperation(
new CheckConditionsOperation(ref, CheckConditionsOperation.ALL_CONDITIONS),
RefactoringStatus.FATAL);
create.run(new NullProgressMonitor());
Change change= create.getChange();
Set<GroupCategory> actualCategories= new HashSet<>();
collectGroupCategories(actualCategories, change);
for (GroupCategory actualCategory : actualCategories) {
if (!setOfExpectedGroupCategories.contains(actualCategory.getName())) {
fail("Unexpected group category: " + actualCategory.getName() + ", should find: " + String.join(", ", setOfExpectedGroupCategories));
}
}
}
protected RefactoringStatus assertRefactoringResultAsExpected(ICompilationUnit[] cus, String[] expected) throws CoreException {
return assertRefactoringResultAsExpected(cus, expected, null);
}
protected RefactoringStatus assertRefactoringResultAsExpected(ICompilationUnit[] cus, String[] expected, Set<String> setOfExpectedGroupCategories) throws CoreException {
RefactoringStatus status= performRefactoring(cus, setOfExpectedGroupCategories);
String[] previews= new String[cus.length];
for (int i= 0; i < cus.length; i++) {
ICompilationUnit cu= cus[i];
previews[i]= cu.getBuffer().getContents();
}
assertEqualStringsIgnoreOrder(previews, expected);
return status;
}
protected void assertRefactoringResultAsExpectedIgnoreHashValue(ICompilationUnit[] cus, String[] expected) throws CoreException {
performRefactoring(cus, null);
Pattern regex= Pattern.compile("long serialVersionUID = .*L;");
String[] previews= new String[cus.length];
for (int i= 0; i < cus.length; i++) {
ICompilationUnit cu= cus[i];
previews[i]= cu.getBuffer().getContents().replaceAll(regex.pattern(), "long serialVersionUID = 1L;");
}
assertEqualStringsIgnoreOrder(previews, expected);
}
protected RefactoringStatus assertRefactoringHasNoChange(ICompilationUnit[] cus) throws CoreException {
for (ICompilationUnit cu : cus) {
assertNoCompilationError(cu);
}
return assertRefactoringHasNoChangeEventWithError(cus);
}
protected RefactoringStatus assertRefactoringHasNoChangeEventWithError(ICompilationUnit[] cus) throws CoreException {
String[] expected= new String[cus.length];
for (int i= 0; i < cus.length; i++) {
expected[i]= cus[i].getBuffer().getContents();
}
return assertRefactoringResultAsExpected(cus, expected, null);
}
protected CompilationUnit assertNoCompilationError(ICompilationUnit cu) {
ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
parser.setSource(cu);
parser.setResolveBindings(true);
CompilationUnit root= (CompilationUnit) parser.createAST(null);
IProblem[] problems= root.getProblems();
boolean hasProblems= false;
for (IProblem prob : problems) {
if (!prob.isWarning() && !prob.isInfo()) {
hasProblems= true;
break;
}
}
if (hasProblems) {
StringBuilder builder= new StringBuilder();
builder.append(cu.getElementName() + " has compilation problems: \n");
for (IProblem prob : problems) {
builder.append(prob.getMessage()).append('\n');
}
fail(builder.toString());
}
return root;
}
protected final RefactoringStatus performRefactoring(ICompilationUnit[] cus, Set<String> setOfExpectedGroupCategories) throws CoreException {
final CleanUpRefactoring ref= new CleanUpRefactoring();
ref.setUseOptionsFromProfile(true);
ICleanUp[] cleanUps= JavaPlugin.getDefault().getCleanUpRegistry().createCleanUps();
return performRefactoring(ref, cus, cleanUps, setOfExpectedGroupCategories);
}
protected RefactoringStatus performRefactoring(final CleanUpRefactoring ref, ICompilationUnit[] cus, ICleanUp[] cleanUps, Set<String> setOfExpectedGroupCategories) throws CoreException {
for (ICompilationUnit cu : cus) {
ref.addCompilationUnit(cu);
}
for (ICleanUp cleanUp : cleanUps) {
ref.addCleanUp(cleanUp);
}
IUndoManager undoManager= getUndoManager();
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();
executePerformOperation(perform, workspace);
RefactoringStatus status= create.getConditionCheckingStatus();
if (status.hasFatalError()) {
throw new CoreException(new StatusInfo(status.getSeverity(), status.getMessageMatchingSeverity(status.getSeverity())));
}
assertTrue("Change wasn't executed", perform.changeExecuted());
Change undo= perform.getUndoChange();
assertNotNull("Undo doesn't exist", undo);
assertTrue("Undo manager is empty", undoManager.anythingToUndo());
if (setOfExpectedGroupCategories != null) {
Change change= create.getChange();
Set<GroupCategory> actualCategories= new HashSet<>();
collectGroupCategories(actualCategories, change);
for (GroupCategory actualCategory : actualCategories) {
Assertions.assertTrue(setOfExpectedGroupCategories.contains(actualCategory.getName()),
() -> "Unexpected group category: " + actualCategory.getName() + ", should find: " + String.join(", ", setOfExpectedGroupCategories));
}
}
return status;
}
private IUndoManager getUndoManager() {
IUndoManager undoManager= RefactoringCore.getUndoManager();
undoManager.flush();
return undoManager;
}
private void executePerformOperation(final PerformChangeOperation perform, IWorkspace workspace) throws CoreException {
workspace.run(perform, new NullProgressMonitor());
}
}