Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 5d9a3d5f7d83d926aa8aa1a2f5d8172290867646 (plain) (blame)
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*
 * Copyright (c) 2014, 2016 CEA, Christian W. Damus, 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:
 *   Christian W. Damus (CEA) - Initial API and implementation
 *   Christian W. Damus - bug 485212
 *
 */
package org.eclipse.papyrus.infra.services.edit.tests.edit.advice;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.regex.Pattern;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IMarkerDelta;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EValidator;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.gmf.runtime.common.core.command.ICommand;
import org.eclipse.gmf.runtime.diagram.ui.commands.CommandProxy;
import org.eclipse.gmf.runtime.diagram.ui.requests.EditCommandRequestWrapper;
import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest;
import org.eclipse.gmf.runtime.emf.type.core.requests.IEditCommandRequest;
import org.eclipse.papyrus.commands.wrappers.GMFtoEMFCommandWrapper;
import org.eclipse.papyrus.infra.services.edit.internal.advice.MarkerDeletionAdvice;
import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils;
import org.eclipse.papyrus.infra.services.edit.service.IElementEditService;
import org.eclipse.papyrus.infra.services.validation.IPapyrusDiagnostician;
import org.eclipse.papyrus.infra.services.validation.ValidationTool;
import org.eclipse.papyrus.infra.services.validation.internal.EValidatorAdapter;
import org.eclipse.papyrus.infra.services.validation.internal.EcoreDiagnostician;
import org.eclipse.papyrus.junit.framework.classification.tests.AbstractPapyrusTest;
import org.eclipse.papyrus.junit.utils.rules.HouseKeeper;
import org.eclipse.papyrus.junit.utils.rules.PapyrusEditorFixture;
import org.eclipse.papyrus.junit.utils.rules.PluginResource;
import org.eclipse.swt.widgets.Display;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.LoopNode;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.UMLPackage;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;


/**
 * Test suite for the {@link MarkerDeletionAredvice} class.
 */
@SuppressWarnings("restriction")
@PluginResource("model/MarkerDeletionModel.di")
public class MarkerDeletionAdviceTest extends AbstractPapyrusTest {

	@Rule
	public final HouseKeeper houseKeeper = new HouseKeeper();

	@Rule
	public final PapyrusEditorFixture editor = new PapyrusEditorFixture();

	public MarkerDeletionAdviceTest() {
		super();
	}

	@Test
	public void testDeleteMarkers() {
		MarkerAssertion markers = new MarkerAssertion().add(markerIs("required feature '[^']+' of '<Loop Node> LoopNode'", IMarker.SEVERITY_ERROR));

		LoopNode loopNode = findElement(LoopNode.class);
		IEditCommandRequest request = new DestroyElementRequest(loopNode, false);

		execute(new MarkerDeletionAdvice().getBeforeEditCommand(request));

		markers.assertMarkersRemoved();

		undo();

		markers.assertMarkersAdded();

		redo();

		markers.assertMarkersRemoved();
	}

	@Test
	public void testDeleteMarkers_integration() {
		MarkerAssertion markers = new MarkerAssertion().add(markerIs("required feature '[^']+' of '<Loop Node> LoopNode'", IMarker.SEVERITY_ERROR));

		LoopNode loopNode = findElement(LoopNode.class);

		execute(getDestroyCommand(loopNode));

		markers.assertMarkersRemoved();

		undo();

		markers.assertMarkersAdded();

		redo();

		markers.assertMarkersRemoved();
	}

	@Test
	@PluginResource("model/AssociationModel.di")
	public void testDeleteMarkers_relatedElements() {
		MarkerAssertion markers = new MarkerAssertion().add(markerIs("Subsetting property '<Property> employer : Company'", IMarker.SEVERITY_WARNING));

		// This is a class-owned association end (not association-owned), so deleting it
		// deletes the association as a dependent element
		Property associationEnd = findElement(Property.class, "employee");

		execute(getDestroyCommand(associationEnd));

		markers.assertMarkersRemoved();

		undo();

		markers.assertMarkersAdded();

		redo();

		markers.assertMarkersRemoved();
	}

	@Test
	public void testDeleteMarkers_relatedElements_diagram() {
		MarkerAssertion markers = new MarkerAssertion().add(markerIs("subsetting property '<Property> employee : Person \\Q[0..*]\\E'", IMarker.SEVERITY_WARNING));

		Association association = findElement(Association.class, "A_employer_employee");
		EditPart editPart = editor.activateDiagram("classes").findEditPart(association);

		execute(new CommandProxy(editPart.getCommand(new EditCommandRequestWrapper(new DestroyElementRequest(false)))));

		markers.assertMarkersRemoved();

		undo();

		markers.assertMarkersAdded();

		redo();

		markers.assertMarkersRemoved();
	}

	//
	// Test framework
	//

	@Before
	public void validateModel() {
		// Open the editor
		editor.open();

		// Validate the model
		IPapyrusDiagnostician diagnostician = new EcoreDiagnostician(new EValidatorAdapter((EValidator) EValidator.Registry.INSTANCE.get(UMLPackage.eINSTANCE)));
		diagnostician.initialize(((AdapterFactoryEditingDomain) editor.getEditingDomain()).getAdapterFactory(), new NullProgressMonitor());
		BasicDiagnostic diagnostic = diagnostician.createDefaultDiagnostic(editor.getModel());
		diagnostician.validate(editor.getModel(), diagnostic, diagnostician.createDefaultContext());

		// Create the markers
		ValidationTool tool = new ValidationTool(editor.getModel());
		tool.createMarkers(diagnostic, new NullProgressMonitor());
	}

	<T extends NamedElement> T findElement(Class<T> type) {
		return findElement(type, null);
	}

	<T extends NamedElement> T findElement(Class<T> type, String name) {
		T result = null;

		for (Iterator<?> iter = editor.getModelResource().getAllContents(); iter.hasNext();) {
			Object next = iter.next();
			if (type.isInstance(next) && ((name == null) || name.equals(((NamedElement) next).getName()))) {
				result = type.cast(next);
				break;
			}
		}

		return result;
	}

	ICommand getDestroyCommand(EObject object) {
		IElementEditService edit = ElementEditServiceUtils.getCommandProvider(object);
		DestroyElementRequest req = new DestroyElementRequest(object, false);

		return edit.getEditCommand(req);
	}

	void execute(ICommand command) {
		editor.getEditingDomain().getCommandStack().execute(GMFtoEMFCommandWrapper.wrap(command));
		letMarkerCacheClearOut();
	}

	void undo() {
		editor.getEditingDomain().getCommandStack().undo();
		letMarkerCacheClearOut();
	}

	void redo() {
		editor.getEditingDomain().getCommandStack().redo();
		letMarkerCacheClearOut();
	}

	private void letMarkerCacheClearOut() {
		Display display = Display.getCurrent();
		if (display != null) {
			while (display.readAndDispatch()) {
				// Pass
			}
		}
	}

	Matcher<IMarkerDelta> markerIs(String messageRegex, int severity) {
		final int markerSeverity = severity;
		final Pattern messagePattern = Pattern.compile(messageRegex, Pattern.CASE_INSENSITIVE);

		return new BaseMatcher<IMarkerDelta>() {

			public void describeTo(Description description) {
				description.appendText("marker of ");

				switch (markerSeverity) {
				case IMarker.SEVERITY_INFO:
					description.appendText("INFO");
					break;
				case IMarker.SEVERITY_WARNING:
					description.appendText("WARNING");
					break;
				default:
					description.appendText("ERROR");
					break;
				}
				description.appendText(" severity with message like '");
				description.appendText(messagePattern.pattern());
				description.appendText("'");
			}

			public boolean matches(Object item) {
				boolean result = item instanceof IMarkerDelta;

				if (result) {
					IMarkerDelta markerDelta = (IMarkerDelta) item;
					result = (markerDelta.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR) == markerSeverity) //
							&& messagePattern.matcher(markerDelta.getAttribute(IMarker.MESSAGE, "")).find();
				}

				return result;
			}
		};
	}

	public class MarkerAssertion implements IResourceChangeListener {

		private final IWorkspace ws = ResourcesPlugin.getWorkspace();

		private IFile file;

		private Collection<Matcher<? super IMarkerDelta>> markerAssertions = new ArrayList<Matcher<? super IMarkerDelta>>();

		boolean markersRemoved;

		boolean markersAdded;

		MarkerAssertion() {
			super();

			ws.addResourceChangeListener(this);
			houseKeeper.cleanUpLater(this);

			file = editor.getProject().getFile(editor.getModelResourceURI());

			try {
				IMarker[] markers = file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_ZERO);
				assertThat("No problem markers on model", markers.length > 0, is(true));
			} catch (CoreException e) {
				e.printStackTrace();
				fail("Could not access model resource markers: " + e.getLocalizedMessage());
			}
		}

		public void dispose() {
			ws.removeResourceChangeListener(this);
		}

		MarkerAssertion add(Matcher<? super IMarkerDelta> assertion) {
			markerAssertions.add(assertion);
			return this;
		}

		public void resourceChanged(IResourceChangeEvent event) {
			try {
				event.getDelta().accept(new IResourceDeltaVisitor() {

					public boolean visit(IResourceDelta delta) throws CoreException {
						if (file.equals(delta.getResource()) && ((delta.getFlags() & IResourceDelta.MARKERS) != 0)) {
							for (IMarkerDelta markerDelta : delta.getMarkerDeltas()) {
								switch (markerDelta.getKind()) {
								case IResourceDelta.ADDED:
									markersAdded = markersAdded || anyAssertionMatches(markerDelta);
									break;
								case IResourceDelta.REMOVED:
									markersRemoved = markersRemoved || anyAssertionMatches(markerDelta);
									break;
								}
							}
						}
						return true;
					}
				});
			} catch (CoreException e) {
				e.printStackTrace();
			}
		}

		void reset() {
			markersRemoved = false;
			markersAdded = false;
		}

		void assertMarkersRemoved() {
			boolean test = markersRemoved;
			reset();
			assertThat("No markers were removed", test, is(true));
		}

		void assertMarkersAdded() {
			boolean test = markersAdded;
			reset();
			assertThat("No markers were added", test, is(true));
		}

		private boolean anyAssertionMatches(IMarkerDelta markerDelta) {
			boolean result = false;

			for (Matcher<? super IMarkerDelta> next : markerAssertions) {
				result = next.matches(markerDelta);
				if (result) {
					break;
				}
			}

			return result;
		}
	}
}

Back to the top