errors = Lists.newArrayList();
- int run = 0;
- int succeeded = 0;
- while (run < testRuns || (testRuns == 1 && succeeded == 0 && run < thisTestRetries + 1)) {
- try {
- run++;
- methodBlock(method).evaluate();
- succeeded++;
- } catch (AssumptionViolatedException e) {
- throw e;
- } catch (AssertionError exception) {
- failures.add(exception);
- problems.addProblem(exception);
- // CHECKSTYLE:CHECK-OFF IllegalCatch // we want to catch all possible errors
- } catch (Throwable throwable) {
- // CHECKSTYLE:CHECK-ON IllegalCatch
- errors.add(throwable);
- problems.addProblem(throwable);
- }
- }
- final String testCase = getTestClass().getJavaClass().getSimpleName() + '.' + method.getName();
- if (run > 1) {
- logRepeatedTestResult(testCase, run, succeeded, failures.size(), errors.size());
- }
- if (succeeded == 0) {
- problems.assertEmpty();
- }
- if (problems.hasProblems()) {
- if (unstableFail) {
- problems.assertEmpty();
- } else {
- final StringWriter stringWriter = new StringWriter();
- problems.printStackTrace(new PrintWriter(stringWriter));
- LOGGER.info(stringWriter.toString());
- }
- }
- } catch (AssumptionViolatedException e) { // NOPMD ExceptionAsFlowControl
- eachNotifier.addFailedAssumption(e);
- // CHECKSTYLE:CHECK-OFF IllegalCatch // we want to catch all possible errors
- } catch (Throwable e) {
- // CHECKSTYLE:CHECK-ON IllegalCatch
- eachNotifier.addFailure(e);
- } finally {
- eachNotifier.fireTestFinished();
- }
- }
-
- /**
- * Logs the repeated test result.
- *
- * @param testCase
- * the test case, must not be {@code null}
- * @param runs
- * the number of runs
- * @param succeeded
- * the number of succeeded runs
- * @param failures
- * the number of failed runs
- * @param errors
- * the number of errored runs
- */
- public void logRepeatedTestResult(final String testCase, final int runs, final int succeeded, final int failures, final int errors) {
- final StringBuilder testResult = new StringBuilder(testCase).append(" Repeated Test Result: "); //$NON-NLS-1$
- if (succeeded == runs) {
- testResult.append("SUCCESS"); //$NON-NLS-1$
- } else if (succeeded == 0) {
- testResult.append("FAILURE"); //$NON-NLS-1$
- } else {
- testResult.append("UNSTABLE"); //$NON-NLS-1$
- }
- testResult.append(" (").append(succeeded).append(" of ").append(runs).append(" succeeded"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- if (failures > 0) {
- testResult.append(", ").append(failures).append(" failed"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- if (errors > 0) {
- testResult.append(", ").append(errors).append(" errored"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- testResult.append(')');
- LOGGER.info(testResult.toString());
- }
-
- /**
- * Creates a notifier for each test.
- *
- * @param method
- * the {@link FrameworkMethod}, must not be {@code null}
- * @param notifier
- * the {@link RunNotifier}, must not be {@code null}
- * @return an instance of {@link EachTestNotifier}, never {@code null}
- */
- private EachTestNotifier createNotifier(final FrameworkMethod method, final RunNotifier notifier) {
- return new EachTestNotifier(notifier, describeChild(method));
- }
-
- /**
- * Adds any @BeforeAll methods to be run before the normal @Before annotated methods for the first test method only.
- *
- * {@inheritDoc}
- */
- @Override
- protected Statement withBefores(final FrameworkMethod method, final Object target, final Statement stmt) {
- ensureInitialized();
- Statement statement = super.withBefores(method, target, stmt); // NOPMD.CloseResource
- if (method.equals(expectedMethods.get(0))) {
- // reverse BeforeAll method order to get a 'runs top to bottom' order
- final List befores = Lists.reverse(getTestClass().getAnnotatedMethods(BeforeAll.class));
- statement = befores.isEmpty() ? statement : new RunBefores(statement, befores, target);
- }
- return statement;
- }
-
- /**
- * Adds any @AfterAll methods to be run after the normal @After annotated methods for the last test method only.
- *
- * {@inheritDoc}
- */
- @Override
- protected Statement withAfters(final FrameworkMethod method, final Object target, final Statement stmt) {
- ensureInitialized();
- Statement statement = super.withAfters(method, target, stmt); // NOPMD.CloseResource
- if (method.equals(Iterables.getLast(expectedMethods))) {
- final List afters = getTestClass().getAnnotatedMethods(AfterAll.class);
- statement = afters.isEmpty() ? statement : new RunAfters(statement, afters, target);
- }
- return statement;
- }
-
- /** {@inheritDoc} */
- @Override
- protected List computeTestMethods() {
- final Collection result = Sets.newHashSet();
- for (final Class extends Annotation> annotationClass : TEST_ANNOTATIONS) {
- result.addAll(getTestClass().getAnnotatedMethods(annotationClass));
- }
- return Lists.newArrayList(result);
- }
-}
diff --git a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/jvmmodel/AbstractJvmModelInferrerTest.java b/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/jvmmodel/AbstractJvmModelInferrerTest.java
deleted file mode 100644
index f48c475ba..000000000
--- a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/jvmmodel/AbstractJvmModelInferrerTest.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016 Avaloq Group AG 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:
- * Avaloq Group AG - initial API and implementation
- *******************************************************************************/
-package com.avaloq.tools.ddk.xtext.test.jvmmodel;
-
-import java.util.Set;
-
-import org.eclipse.emf.ecore.EObject;
-
-import com.avaloq.tools.ddk.xtext.test.modelinference.AbstractModelInferrerTest;
-
-
-/**
- * Base class for JVM model inference test implementations.
- */
-public abstract class AbstractJvmModelInferrerTest extends AbstractModelInferrerTest {
-
- @Override
- protected Set getInferredElements(final EObject sourceElement) {
- return InferredJvmModelUtil.getInferredElements(sourceElement);
- }
-
- /**
- * Returns an inferred element of specified name and type for a given source element.
- *
- * @param sourceElement
- * a source {@link EObject}, must not be {@code null}
- * @param name
- * the name of the element, must not be {@code null}
- * @param clazz
- * the type of the element, must not be {@code null}
- * @return an inferred element, or {@code null} if nothing has been found
- */
- @Override
- protected EObject getInferredElement(final EObject sourceElement, final String name, final Class extends EObject> clazz) {
- return InferredJvmModelUtil.getInferredElement(sourceElement, name, clazz);
- }
-}
diff --git a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/linking/AbstractLinkingTest.java b/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/linking/AbstractLinkingTest.java
deleted file mode 100644
index 0f3e18ea3..000000000
--- a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/linking/AbstractLinkingTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016 Avaloq Group AG 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:
- * Avaloq Group AG - initial API and implementation
- *******************************************************************************/
-package com.avaloq.tools.ddk.xtext.test.linking;
-
-import static org.junit.Assert.assertEquals;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.util.EcoreUtil;
-
-import com.avaloq.tools.ddk.xtext.test.AbstractXtextTest;
-
-
-/**
- * Test linking of a given input file.
- */
-@SuppressWarnings("PMD.AbstractClassWithoutAnyMethod")
-public abstract class AbstractLinkingTest extends AbstractXtextTest {
- private static final String NOT_RESOLVED_MESSAGE = "Cross-reference has not been resolved."; //$NON-NLS-1$
-
- /**
- * Asserts that the actualObject equals the expectedObject.
- *
- * @param expectedObject
- * the expected object
- * @param actualObject
- * the actual object
- */
- protected void assertReferenceResolved(final EObject expectedObject, final EObject actualObject) {
- assertEquals(NOT_RESOLVED_MESSAGE, EcoreUtil.getURI(expectedObject), EcoreUtil.getURI(actualObject));
- }
-}
diff --git a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/modelinference/AbstractModelInferrerTest.java b/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/modelinference/AbstractModelInferrerTest.java
deleted file mode 100644
index 919ac60d1..000000000
--- a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/modelinference/AbstractModelInferrerTest.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016 Avaloq Group AG 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:
- * Avaloq Group AG - initial API and implementation
- *******************************************************************************/
-package com.avaloq.tools.ddk.xtext.test.modelinference;
-
-import static org.junit.Assert.assertTrue;
-
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.util.EcoreUtil;
-
-import com.avaloq.tools.ddk.typesystem.typemodel.INamedElement;
-import com.avaloq.tools.ddk.xtext.test.AbstractXtextMarkerBasedTest;
-import com.google.common.collect.Lists;
-
-
-/**
- * Abstract base class for model inference test implementations.
- */
-public abstract class AbstractModelInferrerTest extends AbstractXtextMarkerBasedTest {
-
- private boolean oldAutoBuildState;
-
- @Override
- protected void beforeAllTests() {
- super.beforeAllTests();
- oldAutoBuildState = getTestProjectManager().setAutobuild(true);
- }
-
- @Override
- protected void afterAllTests() {
- getTestProjectManager().setAutobuild(oldAutoBuildState);
- super.afterAllTests();
- }
-
- /**
- * Returns the inferred elements for the given source element.
- *
- * @param sourceElement
- * a source {@link EObject}, must not be {@code null} *
- * @return the inferred elements for the given source element, never {@code null}
- */
- protected abstract Set getInferredElements(EObject sourceElement);
-
- /**
- * Validates the list of sources for correctness.
- *
- * @param sourceNames
- * list of sources, must not be {@code null}
- */
- protected void validateSources(final String... sourceNames) {
- for (String sourceName : sourceNames) {
- getXtextTestUtil().validateSource(sourceName, getTestProjectManager().getTestSource(sourceName).getContent());
- }
- }
-
- @Override
- protected List getRequiredSourceFileNames() {
- return Lists.newArrayList(); // Override the behavior of the parent
- }
-
- /**
- * Builds the workspace or waits until it is built. Updates the {@link TestState} after that.
- */
- protected void build() {
- getTestProjectManager().build();
- }
-
- /**
- * Asserts that nothing has been inferred for the tagged element.
- *
- * @param tag
- * A tag for an element
- */
- protected void assertNoInference(final int tag) {
- assertNoInference(getObjectForTag(tag));
- }
-
- /**
- * Asserts that nothing has been inferred for a given source element.
- *
- * @param sourceElement
- * a source {@link EObject}, must not be {@code null}
- */
- protected void assertNoInference(final EObject sourceElement) {
- final Set inferredElements = getInferredElements(sourceElement);
- assertTrue("Unexpected inferred elements found: " + inferredElements.toString(), inferredElements.isEmpty()); //$NON-NLS-1$
- }
-
- /**
- * Returns an inferred element of specified name and type for a given tag.
- *
- * Note: Returns the first encountered, if multiple elements have the same name.
- *
- *
- * @param tag
- * the tag for the element that should infer an element, must not be {@code null}
- * @param name
- * the name of the element, must not be {@code null}
- * @param clazz
- * the type of the element, must not be {@code null}
- * @return an inferred element, or {@code null} if nothing has been found
- */
- protected EObject getInferredElement(final int tag, final String name, final Class extends EObject> clazz) {
- return getInferredElement(getObjectForTag(tag), name, clazz);
- }
-
- /**
- * Returns an inferred element of specified name and type for a given source element.
- *
- * @param sourceElement
- * a source {@link EObject}, must not be {@code null}
- * @param name
- * the name of the element, must not be {@code null}
- * @param clazz
- * the type of the element, must not be {@code null}
- * @return an inferred element, or {@code null} if nothing has been found
- */
- protected EObject getInferredElement(final EObject sourceElement, final String name, final Class extends EObject> clazz) {
- final Set inferredElements = getInferredElements(sourceElement);
- EObject target = null;
- for (final EObject obj : inferredElements) {
- if (clazz.isAssignableFrom(obj.getClass()) && ((INamedElement) obj).getName().equals(name)) {
- target = EcoreUtil.resolve(obj, sourceElement);
- break;
- }
- }
- return target;
- }
-}
diff --git a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/resource/AbstractResourceDescriptionManagerTest.xtend b/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/resource/AbstractResourceDescriptionManagerTest.xtend
deleted file mode 100644
index 8f0c29679..000000000
--- a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/resource/AbstractResourceDescriptionManagerTest.xtend
+++ /dev/null
@@ -1,198 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016 Avaloq Group AG 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:
- * Avaloq Group AG - initial API and implementation
- *******************************************************************************/
-package com.avaloq.tools.ddk.xtext.test.resource;
-
-import com.avaloq.tools.ddk.xtext.test.AbstractXtextTest;
-import org.eclipse.xtext.resource.IResourceDescription
-import com.avaloq.tools.ddk.xtext.resource.AbstractCachingResourceDescriptionManager
-import org.eclipse.xtext.resource.IResourceDescriptions
-import org.eclipse.emf.common.util.URI
-import java.util.Collection
-import org.eclipse.xtext.resource.IResourceDescription.Delta
-import com.google.common.collect.HashMultiset
-import org.junit.Assert
-import com.google.common.collect.Sets
-import com.avaloq.tools.ddk.xtext.test.TestSource
-
-/**
- * Abstract base class for {@link AbstractCachingResourceDescriptionManager} tests.
- */
-abstract class AbstractResourceDescriptionManagerTest extends AbstractXtextTest {
-
- /**
- * Simple unchanged {@link Delta} implementation with {@link URI}.
- */
- static class UnchangedDelta implements Delta {
-
- val URI uri;
-
- new(URI uri) {
- this.uri = uri;
- }
-
- override getNew() {
- null
- }
-
- override getOld() {
- null
- }
-
- override getUri() {
- uri
- }
-
- override haveEObjectDescriptionsChanged() {
- false
- }
- }
-
- val AbstractCachingResourceDescriptionManager resourceDescriptionManager = testUtil.get(IResourceDescription.Manager) as AbstractCachingResourceDescriptionManager;
- val IResourceDescriptions index = testUtil.get(IResourceDescriptions);
-
- /**
- * Returns the {@link AbstractCachingResourceDescriptionManager) to use in the test.
- *
- * @return the {@link AbstractCachingResourceDescriptionManager) to use in the test, never {@code null}
- */
- def AbstractCachingResourceDescriptionManager getResourceDescriptionManager() {
- return resourceDescriptionManager;
- }
-
- /**
- * Returns the {@link IResourceDescriptions) to use in the test.
- *
- * @return the {@link IResourceDescriptions) to use in the test, never {@code null}
- */
- def IResourceDescriptions getResourceDescriptions() {
- return index;
- }
-
- /**
- * Returns the candidates for the affected resource computations.
- *
- * Note: By default, all registered sources are considered as candidates.
- *
- *
- * @return the candidates for the affected resource computation, never {@code null}
- */
- def Collection getCandidates() {
- var Collection candidates = testInformation.getTestObject(URI) as Collection;
- if (candidates === null) {
- candidates = Sets.newHashSet;
- testInformation.putTestObject(URI, candidates);
- }
- return candidates;
- }
-
- /**
- * Creates a {@link TestSource} and considers it as a candidate by default.
- *
- * @param sourceFileName
- * file name for the test source, must not be {@code null}
- * @param content
- * content of source, must not be {@code null}
- * @return a new {@link TestSource} with the given parameters, never {@code null}
- */
- override protected createTestSource(String sourceFileName, String content) {
- val testSource = super.createTestSource(sourceFileName, content);
- getCandidates().add(testSource.uri);
- return testSource;
- }
-
- /**
- * Creates a {@link Delta} for the given {@link URI}.
- *
- * Note: By default, the delta is an instance of {@link UnchangedDelta}
- *
- *
- * @param uri
- * the delta {@link URI}, must not be {@code null}
- * @return a new {@link Delta}, never {@code null}
- */
- def Delta createDelta(URI uri) {
- return new UnchangedDelta(uri);
- }
-
- /**
- * Returns the {@link URI} of the {@link TestSource} with the given file name.
- *
- * @param sourceFileName
- * file name for the test source, must not be {@code null}
- * @return the {@link URI} of the {@link TestSource} with the given file name, never {@code null}
- */
- def URI getUri(String sourceFileName) {
- return getTestSource(sourceFileName).uri;
- }
-
- /**
- * Asserts that the given delta causes the expected set of affected resources.
- *
- * Note: Uses the candidates returned by {@link #getCandidates()}.
- *
- *
- * @param deltaSourceName
- * the delta source name, must not be {@code null}
- * @param expectedSourceNames
- * the expected affected source names, must not be {@code null}
- */
- def assertAffectedResources(String deltaSourceName, String... expectedSourceNames) {
- val Collection expectedUris = Sets.newHashSet;
- for (sourceName : expectedSourceNames) {
- expectedUris.add(getUri(sourceName));
- }
- assertAffectedResources(Sets.newHashSet(getUri(deltaSourceName)), getCandidates(), expectedUris);
- }
-
- /**
- * Asserts that the given set of deltas causes the expected set of affected {@link URI}s.
- *
- * Note: Uses the candidates returned by {@link #getCandidates()}.
- *
- *
- * @param deltaUris
- * the delta {@link URI}s, must not be {@code null}
- * @param expectedUris
- * the expected affected {@link URI}s, must not be {@code null}
- */
- def assertAffectedResources(Collection deltaUris, Collection expectedUris) {
- assertAffectedResources(deltaUris, getCandidates(), expectedUris);
- }
-
- /**
- * Asserts that the given set of deltas causes the expected set of affected {@link URI}s.
- *
- * @param deltaUris
- * the delta {@link URI}s, must not be {@code null}
- * @param candidates
- * the potential candidates that can be affected, must not be {@code null}
- * @param expectedUris
- * the expected affected {@link URI}s, must not be {@code null}
- */
- def assertAffectedResources(Collection deltaUris, Collection candidates, Collection expectedUris) {
- assertDeltaAffectedResources(Sets.newHashSet(deltaUris.map[createDelta(it)]), candidates, expectedUris);
- }
-
- /**
- * Asserts that the given set of deltas causes the expected set of affected {@link URI}s.
- *
- * @param deltas
- * the {@link Delta}s, must not be {@code null}
- * @param candidates
- * the potential candidates that can be affected, must not be {@code null}
- * @param expectedUris
- * the expected affected {@link URI}s, must not be {@code null}
- */
- def assertDeltaAffectedResources(Collection deltas, Collection candidates, Collection expectedUris) {
- val result = getResourceDescriptionManager().getAffectedResources(deltas, candidates, getResourceDescriptions());
- Assert.assertEquals("Affected URIs must be correct.", HashMultiset.create(expectedUris), HashMultiset.create(result));
- }
-}
diff --git a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/scoping/AbstractScopingTest.java b/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/scoping/AbstractScopingTest.java
deleted file mode 100644
index 989fb29ce..000000000
--- a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/scoping/AbstractScopingTest.java
+++ /dev/null
@@ -1,877 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016 Avaloq Group AG 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:
- * Avaloq Group AG - initial API and implementation
- *******************************************************************************/
-package com.avaloq.tools.ddk.xtext.test.scoping;
-
-import static com.avaloq.tools.ddk.xtext.linking.AbstractFragmentProvider.REP_SEPARATOR;
-import static com.avaloq.tools.ddk.xtext.linking.AbstractFragmentProvider.SEGMENT_SEPARATOR;
-import static com.avaloq.tools.ddk.xtext.resource.AbstractSelectorFragmentProvider.EQ_OP;
-import static com.avaloq.tools.ddk.xtext.resource.AbstractSelectorFragmentProvider.SELECTOR_END;
-import static com.avaloq.tools.ddk.xtext.resource.AbstractSelectorFragmentProvider.SELECTOR_START;
-import static com.avaloq.tools.ddk.xtext.resource.AbstractSelectorFragmentProvider.UNIQUE;
-import static com.avaloq.tools.ddk.xtext.resource.AbstractSelectorFragmentProvider.VALUE_SEP;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.function.Supplier;
-import java.util.regex.Pattern;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.emf.common.util.EList;
-import org.eclipse.emf.common.util.URI;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.ecore.util.EObjectResolvingEList;
-import org.eclipse.emf.ecore.util.EcoreUtil;
-import org.eclipse.osgi.util.NLS;
-import org.eclipse.xtext.Assignment;
-import org.eclipse.xtext.CrossReference;
-import org.eclipse.xtext.EcoreUtil2;
-import org.eclipse.xtext.naming.QualifiedName;
-import org.eclipse.xtext.nodemodel.INode;
-import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
-import org.eclipse.xtext.resource.IEObjectDescription;
-import org.eclipse.xtext.resource.IResourceDescription;
-import org.eclipse.xtext.resource.IResourceServiceProvider;
-import org.eclipse.xtext.resource.XtextResource;
-import org.eclipse.xtext.scoping.IScope;
-import org.eclipse.xtext.scoping.IScopeProvider;
-import org.eclipse.xtext.util.Triple;
-import org.eclipse.xtext.xbase.lib.Pair;
-
-import com.avaloq.tools.ddk.caching.Regexps;
-import com.avaloq.tools.ddk.xtext.linking.AbstractFragmentProvider;
-import com.avaloq.tools.ddk.xtext.naming.QualifiedNames;
-import com.avaloq.tools.ddk.xtext.resource.IFingerprintComputer;
-import com.avaloq.tools.ddk.xtext.scoping.ContainerQuery;
-import com.avaloq.tools.ddk.xtext.scoping.IDomain;
-import com.avaloq.tools.ddk.xtext.test.AbstractXtextMarkerBasedTest;
-import com.google.common.base.Function;
-import com.google.common.base.Splitter;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-
-
-/**
- * Base class for scoping tests.
- */
-@SuppressWarnings("nls")
-public abstract class AbstractScopingTest extends AbstractXtextMarkerBasedTest {
- private static final String PARAMETER_EXPECTED_OBJECTS = "expectedObjects";
- private static final String PARAMETER_REFERENCE = "reference";
- private static final String PARAMETER_CONTEXT = "context";
- public static final String TOP_LEVEL_OBJECT_FRAGMENT = SEGMENT_SEPARATOR + "0" + SEGMENT_SEPARATOR + "1";
- public static final String TOP_LEVEL_SURROGATE_FRAGMENT = SEGMENT_SEPARATOR + "0" + REP_SEPARATOR + "2";
- public static final String INFERRED_DATA_DICTIONARY_FRAGMENT = SEGMENT_SEPARATOR + "1";
-
- private static final String NUMBER_OF_ELEMENTS_MESSAGE = "Incorrect number of elements in scope.";
- private static final Splitter FRAGMENT_SEGMENT_SPLITTER = Splitter.onPattern("(? expectedLinkAssertions = new ArrayList();
-
- /**
- * Creates a new instance of {@link AbstractScopingTest}.
- */
- public AbstractScopingTest() {
- this(new IDomain.NullMapper());
-
- }
-
- /**
- * Creates a new instance of {@link AbstractScopingTest}.
- *
- * @param domainMapper
- * the domainMapper to use
- */
- public AbstractScopingTest(final IDomain.Mapper domainMapper) {
- this.domainMapper = domainMapper;
- }
-
- /**
- * Returns all contents of the main {@link XtextTestResource}.
- *
- * @return all contents of the main {@link XtextTestResource}
- */
- @SuppressWarnings("unchecked")
- public Iterable getContents() {
- return (Iterable) getTestInformation().getTestObject(Iterable.class);
- }
-
- /**
- * Set up scoping.
- */
- @Override
- protected void beforeAllTests() {
- super.beforeAllTests();
- Iterable allContents = new Iterable() {
- @Override
- public Iterator iterator() {
- return getXtextTestResource().getAllContents();
- }
- };
- getTestInformation().putTestObject(Iterable.class, allContents);
- }
-
- @Override
- protected void afterEachTest() {
- assertTrue("Expected links were set with link(int) but testLinking(String, CharSequence) was never called", expectedLinkAssertions.isEmpty());
- super.afterEachTest();
- }
-
- /**
- * Returns the scope provider used for unit testing.
- *
- * @return the scope provider instance
- */
- protected IScopeProvider getScopeProvider() {
- return getXtextTestUtil().get(IScopeProvider.class);
- }
-
- /**
- * Check if scope expected is found in context provided.
- *
- * @param context
- * element from which an element shall be referenced
- * @param reference
- * to be used to filter the elements
- * @param expectedSourceName
- * (upper case!) name of scope element to look for (kernel source)
- * @param expectedSourceType
- * type of scope element to look for
- */
- protected void assertScope(final EObject context, final EReference reference, final String expectedSourceName, final String expectedSourceType) {
- assertScope(context, reference, QualifiedNames.safeQualifiedName(expectedSourceName), getTargetSourceUri(expectedSourceName + '.'
- + expectedSourceType).appendFragment(TOP_LEVEL_OBJECT_FRAGMENT));
- }
-
- /**
- * Check if scope expected is found in context provided.
- *
- * @param context
- * element from which an element shall be referenced
- * @param reference
- * to be used to filter the elements
- * @param expectedElementName
- * name of scope element to look for
- * @param expectedSourceName
- * (upper case!) name of the source within to look for the scope element
- * @param expectedSourceType
- * type of scope element to look for
- * @param referenceElementType
- * the type of the referenced element
- */
- @SuppressWarnings("PMD.UseObjectForClearerAPI")
- protected void assertScopeForElement(final EObject context, final EReference reference, final String expectedElementName, final String expectedSourceName, final String expectedSourceType, final String referenceElementType) {
- assertScope(context, reference, QualifiedNames.safeQualifiedName(expectedElementName), getTargetSourceUri(expectedSourceName + '.'
- + expectedSourceType).appendFragment(TOP_LEVEL_OBJECT_FRAGMENT + SEGMENT_SEPARATOR + referenceElementType));
- }
-
- /**
- * Check if scope expected is found in context provided.
- *
- * @param context
- * element from which an element shall be referenced
- * @param reference
- * to be used to filter the elements
- * @param expectedUris
- * of source referenced
- */
- protected void assertScope(final EObject context, final EReference reference, final URI... expectedUris) {
- assertScope(context, reference, Sets.newHashSet(expectedUris));
- }
-
- /**
- * Check if scope expected is found in context provided.
- *
- * @param context
- * element from which an element shall be referenced
- * @param reference
- * to be used to filter the elements
- * @param expectedUriSet
- * of source referenced
- */
- protected void assertScope(final EObject context, final EReference reference, final Set expectedUriSet) {
- IScope scope = getScopeProvider().getScope(context, reference);
- for (IEObjectDescription description : scope.getAllElements()) {
- expectedUriSet.remove(description.getEObjectURI());
- if (expectedUriSet.isEmpty()) {
- return;
- }
- }
- assertTrue("Expected URIs not found in scope: " + expectedUriSet, expectedUriSet.isEmpty());
- }
-
- /**
- * Checks if the given objects are in scope of the given reference for the given context.
- *
- * @param context
- * {@link EObject} element from which an element shall be referenced, must not be {@code null}
- * @param reference
- * the structural feature of {@code context} for which the scope should be asserted, must not be {@code null} and part of the context element
- * @param expectedObjects
- * for given scope, must not be {@code null}
- */
- protected void assertScopedObjects(final EObject context, final EReference reference, final EObject... expectedObjects) {
- Assert.isNotNull(expectedObjects, PARAMETER_EXPECTED_OBJECTS);
- assertScopedObjects(context, reference, Lists.newArrayList(expectedObjects));
- }
-
- /**
- * Checks if the given objects are in scope of the given reference for the given context.
- *
- * @param context
- * {@link EObject} element from which an element shall be referenced, must not be {@code null}
- * @param reference
- * the structural feature of {@code context} for which the scope should be asserted, must not be {@code null} and part of the context element
- * @param firstExpectedObjectCollection
- * for given scope, must not be {@code null}
- * @param furtherExpectedObjectCollections
- * for given scope, must not be {@code null}
- */
- @SuppressWarnings("unchecked")
- protected void assertScopedObjects(final EObject context, final EReference reference, final Collection extends EObject> firstExpectedObjectCollection, final Collection extends EObject>... furtherExpectedObjectCollections) {
- Assert.isNotNull(firstExpectedObjectCollection, "firstExpectedObjectCollection");
- Assert.isNotNull(furtherExpectedObjectCollections, "furtherExpectedObjectCollections");
- Collection consolidatedList = Lists.newArrayList(firstExpectedObjectCollection);
- for (Collection extends EObject> expectedObjects : furtherExpectedObjectCollections) {
- consolidatedList.addAll(expectedObjects);
- }
- assertScopedObjects(context, reference, consolidatedList);
- }
-
- /**
- * Checks if the scope of the given reference for the given context contains only the expected objects.
- * In addition, checks that the reference of the given context references at least one of the expected
- * objects. If the reference has multiplicity > 1, then every reference must reference at least
- * one of the expected objects.
- *
- * @param context
- * {@link EObject} from which the given objects shall be referenced, must not be {@code null}
- * @param reference
- * the structural feature of {@code context} for which the scope should be asserted, must not be {@code null} and part of the context element
- * @param expectedObjects
- * the objects expected in the scope, must not be {@code null}
- */
- protected void assertScopedObjects(final EObject context, final EReference reference, final Collection extends EObject> expectedObjects) {
- Assert.isNotNull(context, PARAMETER_CONTEXT);
- Assert.isNotNull(reference, PARAMETER_REFERENCE);
- Assert.isNotNull(expectedObjects, PARAMETER_EXPECTED_OBJECTS);
- Assert.isTrue(context.eClass().getEAllReferences().contains(reference), String.format("Contract for argument '%s' failed: Parameter is not within specified range (Expected: %s, Actual: %s).", PARAMETER_CONTEXT, "The context object must contain the given reference.", "Reference not contained by the context object!"));
- Set expectedUriSet = Sets.newHashSet();
- for (EObject object : expectedObjects) {
- expectedUriSet.add(EcoreUtil.getURI(object));
- }
- IScope scope = getScopeProvider().getScope(context, reference);
- Iterable allScopedElements = scope.getAllElements();
- Set scopedUriSet = Sets.newHashSet();
- for (IEObjectDescription description : allScopedElements) {
- URI uri = description.getEObjectURI();
- scopedUriSet.add(uri);
- }
- if (!expectedUriSet.equals(scopedUriSet)) {
- fail("The scope must exactly consist of the expected URIs. Missing " + Sets.difference(expectedUriSet, scopedUriSet) + " extra "
- + Sets.difference(scopedUriSet, expectedUriSet));
- }
- // test that link resolving worked
- boolean elementResolved;
- if (reference.isMany()) {
- @SuppressWarnings("unchecked")
- EList objects = (EList) context.eGet(reference, true);
- elementResolved = !objects.isEmpty(); // NOPMD
- for (Iterator objectIter = objects.iterator(); objectIter.hasNext() && elementResolved;) {
- EObject eObject = EcoreUtil.resolve(objectIter.next(), context);
- elementResolved = expectedUriSet.contains(EcoreUtil.getURI(eObject));
- }
- } else {
- EObject resolvedObject = (EObject) context.eGet(reference, true);
- elementResolved = expectedUriSet.contains(EcoreUtil.getURI(resolvedObject));
- }
- assertTrue("Linking must have resolved one of the expected objects.", elementResolved);
- }
-
- /**
- * Check if scope expected is found in context provided.
- *
- * @param context
- * element from which an element shall be referenced
- * @param reference
- * to be used to filter the elements
- * @param expectedName
- * name of scope element to look for
- * @param expectedUri
- * of source referenced
- */
- private void assertScope(final EObject context, final EReference reference, final QualifiedName expectedName, final URI expectedUri) {
- IScope scope = getScopeProvider().getScope(context, reference);
- Iterable descriptions = scope.getElements(expectedName);
- assertFalse("Description missing for: " + expectedName, Iterables.isEmpty(descriptions));
- URI currentUri = null;
- for (IEObjectDescription desc : descriptions) {
- currentUri = desc.getEObjectURI();
- if (currentUri.equals(expectedUri)) {
- return;
- }
- }
- assertEquals("Scope URI is not equal to expected URI", expectedUri, currentUri);
- }
-
- /**
- * Assert the scope for given elements.
- *
- * @param context
- * the context
- * @param reference
- * the reference
- * @param expectedSourceName
- * the name of the referenced source (without file extension)
- * @param expectedSourceType
- * type of scope element to look for
- * @param elementNames
- * array of tuples with the name and uri of each element
- */
- protected void assertScopeForElements(final EObject context, final EReference reference, final String expectedSourceName, final String expectedSourceType, final String[]... elementNames) {
- for (String[] elementName : elementNames) {
- assertScopeForElement(context, reference, elementName[0], expectedSourceName, expectedSourceType, elementName[1]);
- }
- int actualScopeSize = Iterables.size(getScopeProvider().getScope(context, reference).getAllElements());
- assertEquals(NUMBER_OF_ELEMENTS_MESSAGE, elementNames.length, actualScopeSize);
- }
-
- /**
- * Asserts the scope for the given context, reference, source type, and elements.
- *
- * @param context
- * the context object
- * @param reference
- * the reference feature
- * @param expectedSourceType
- * the source-type name
- * @param elements
- * list of triples with the expected elements, each triple ordered as: {element name, source name, URI fragment}
- */
- protected void assertScopeForElements(final EObject context, final EReference reference, final String expectedSourceType, final List> elements) {
- Iterable allElements = getScopeProvider().getScope(context, reference).getAllElements();
-
- // create a set containing the URIs (to avoid counting any duplicates the scope provider might have delivered)
- Set uris = new HashSet();
- for (IEObjectDescription d : allElements) {
- uris.add(d.getEObjectURI());
- }
-
- int actualScopeSizeWithoutDuplicates = uris.size();
- assertEquals(NUMBER_OF_ELEMENTS_MESSAGE, elements.size(), actualScopeSizeWithoutDuplicates);
- for (Triple elementName : elements) {
- assertScopeForElement(context, reference, elementName.getFirst(), elementName.getSecond(), expectedSourceType, elementName.getThird());
- }
- }
-
- /**
- * Asserts that the scope of the reference in the given context contains exactly the given sources.
- *
- * @param scopeContext
- * the context of the scope test
- * @param reference
- * the reference to check its scope for
- * @param modelElementClass
- * the {@link EClass} of the model element to find
- * @param sources
- * the array of sources
- */
- protected void assertScopeForSources(final EObject scopeContext, final EReference reference, final EClass modelElementClass, final String... sources) {
- assertScope(scopeContext, reference, getExpectedURIs(scopeContext, modelElementClass, sources));
- int actualScopeSize = Iterables.size(getScopeProvider().getScope(scopeContext, reference).getAllElements());
- assertEquals(NUMBER_OF_ELEMENTS_MESSAGE, sources.length, actualScopeSize);
- }
-
- /**
- * Returns the expected uris for the given sources in the given context.
- *
- * @param context
- * the context
- * @param modelElementClass
- * the class of the exported model element
- * @param sources
- * the sources to get the uris for
- * @return the expected uris for the given sources in the given context
- */
- private Set getExpectedURIs(final EObject context, final EClass modelElementClass, final String... sources) {
- Set expectedURIs = new HashSet();
- for (String source : sources) {
- expectedURIs.add(Iterables.get(getExportedObjects(context, modelElementClass, source), 0).getEObjectURI());
- }
- return expectedURIs;
- }
-
- /**
- * Gets the exported objects.
- *
- * @param context
- * the context
- * @param type
- * the type
- * @param resourcePattern
- * the resource pattern
- * @return the exported objects
- */
- public Iterable getExportedObjects(final EObject context, final EClass type, final String resourcePattern) {
- Pattern regexp = Regexps.fromGlob(URI.encodeSegment(resourcePattern, true));
- return Iterables.filter(ContainerQuery.newBuilder(domainMapper, type).execute(context), (o) -> regexp.matcher(o.getEObjectURI().lastSegment()).matches());
- }
-
- /**
- * Gets the exported names.
- *
- * @param execute
- * the execute
- * @return the exported names
- */
- public List getExportedNames(final Iterable execute) {
- return Lists.newArrayList(Iterables.transform(execute, new Function() {
- @Override
- public String apply(final IEObjectDescription from) {
- return from.getName().toString();
- }
- }));
- }
-
- /**
- * Checks if an object with given name (case sensitive) and type is exported.
- *
- * @param context
- * the context
- * @param name
- * the name
- * @param type
- * the type
- * @return true, if is exported
- */
- public boolean isExported(final EObject context, final String name, final EClass type) {
- return isExported(context, name, type, false);
- }
-
- /**
- * Checks if an object with given name, case sensitive or not, and type is exported.
- *
- * @param context
- * the context
- * @param name
- * the name
- * @param type
- * the type
- * @param ignoreCase
- * the ignore case
- * @return true, if is exported
- */
- public boolean isExported(final EObject context, final String name, final EClass type, final boolean ignoreCase) {
- List exportedNames = getExportedNames(ContainerQuery.newBuilder(domainMapper, type).execute(context));
- if (ignoreCase) {
- return Iterables.contains(Iterables.transform(exportedNames, new Function() {
- @Override
- public String apply(final String from) {
- return from.toLowerCase(); // NOPMD
- }
- }), name);
- } else {
- return exportedNames.contains(name);
- }
- }
-
- /**
- * Gets the resource description for a given Xtext resource.
- *
- * @param resource
- * the resource
- * @return the resource description
- */
- protected final IResourceDescription getResourceDescription(final XtextResource resource) {
- final IResourceServiceProvider resourceServiceProvider = resource.getResourceServiceProvider();
- final IResourceDescription.Manager descriptionManager = resourceServiceProvider.getResourceDescriptionManager();
- return descriptionManager.getResourceDescription(resource);
- }
-
- /**
- * Gets the fingerprint for a given resource description, returns null if resource description does not export any objects or if a non-existing
- * user data field was queried.
- *
- * @param description
- * the description
- * @return the fingerprint or null if no fingerprint found
- */
- protected String getFingerprint(final IResourceDescription description) {
- Iterable objects = description.getExportedObjects();
- if (!Iterables.isEmpty(objects)) {
- IEObjectDescription objectDescription = Iterables.get(objects, 0);
- return objectDescription.getUserData(IFingerprintComputer.RESOURCE_FINGERPRINT);
- }
- return null;
- }
-
- /**
- * Creates a top level URI fragment with a leading segment separator from the given segments
- * taking into account repetitions.
- *
- * @param segments
- * list of feature IDs, indexes (for multi valued features), and other fragment segments
- * @return URI fragment
- */
- public static String createTopLevelURIFragment(final Object... segments) {
- return createURIFragment(true, segments);
- }
-
- /**
- * Creates a URI fragment from the given segments taking into account repetitions.
- *
- * @param segments
- * list of feature IDs, indexes (for multi valued features), and other fragment segments
- * @return URI fragment
- */
- public static String createURIFragment(final Object... segments) {
- return createURIFragment(false, segments);
- }
-
- /**
- * Creates a URI fragment from the given segments taking into account repetitions.
- *
- * @param topLevel
- * whether the fragment is top level resulting in a leading segment separator.
- * @param segments
- * list of feature IDs, indexes (for multi valued features), and other fragment segments
- * @return URI fragment
- */
- @SuppressWarnings("PMD.UnusedPrivateMethod")
- private static String createURIFragment(final boolean topLevel, final Object... segments) {
- StringBuilder b = new StringBuilder();
- if (segments.length == 0) {
- return b.toString();
- }
- if (topLevel) {
- b.append(SEGMENT_SEPARATOR);
- }
- List parsedSegments = Lists.newArrayList();
- for (Object segment : segments) {
- Iterables.addAll(parsedSegments, FRAGMENT_SEGMENT_SPLITTER.split(segment.toString()));
- }
-
- String lastSegment = parsedSegments.get(0);
- int reps = 1;
- for (int i = 1; i < parsedSegments.size(); i++) {
- if (parsedSegments.get(i).equals(lastSegment)) {
- reps++;
- continue;
- }
- b.append(lastSegment);
- if (reps > 1) {
- b.append(REP_SEPARATOR).append(reps);
- reps = 1;
- }
- b.append(SEGMENT_SEPARATOR);
- lastSegment = parsedSegments.get(i);
- }
- b.append(lastSegment);
- if (reps > 1) {
- b.append(REP_SEPARATOR).append(reps);
- }
- return b.toString();
- }
-
- /**
- * Creates a URI fragment list segment for the given feature selection string and list index.
- *
- * @param feature
- * the feature selection string, must not be {@code null} or empty
- * @param index
- * the list index, must not be negative
- * @return the URI fragment list segment, never {@code null} or empty
- */
- public static String listFragmentSegment(final String feature, final int index) {
- return feature + AbstractFragmentProvider.LIST_SEPARATOR + index;
- }
-
- /**
- * Creates a URI fragment list segment for the given feature id and list index.
- *
- * @param featureId
- * the featureId, must not be negative
- * @param index
- * the list index, must not be negative
- * @return the URI fragment list segment, never {@code null} or empty
- */
- public static String listFragmentSegment(final int featureId, final int index) {
- return listFragmentSegment(String.valueOf(featureId), index);
- }
-
- /**
- * Creates a URI fragment segment to be used for languages using the {@code AbstractSelectorFragmentProvider}.
- *
- * @param containmentFeature
- * containment feature
- * @param selectorFeature
- * selector feature
- * @param value
- * value for selector feature
- * @param unique
- * if value is unique
- * @return URI fragment segment
- */
- public static String selectorFragmentSegment(final int containmentFeature, final int selectorFeature, final String value, final boolean unique) {
- StringBuilder builder = new StringBuilder();
- builder.append(containmentFeature).append(SELECTOR_START).append(selectorFeature).append(EQ_OP).append(VALUE_SEP).append(value).append(VALUE_SEP);
- if (unique) {
- builder.append(UNIQUE);
- }
- builder.append(SELECTOR_END);
- return builder.toString();
- }
-
- /**
- * Creates an expectation of a link. Use this method in tests to insert an expectation that a cross reference does actually point to the object tagged by the
- * target tag. Expectations can be tested by calling {@link #testExpectedLinking()}. Implicit items will be traversed.
- *
- * @see #mark(int)
- * @see #testLinking(String, CharSequence)
- * @param targetTag
- * Tag pointing to the destination object
- * @return Mark text to be inserted in the source file, never {@code null}
- */
- protected String link(final int targetTag) {
- return link(() -> getObjectForTag(targetTag));
- }
-
- /**
- * Creates an expectation of a link. Use this method in tests to insert an expectation that a cross reference does actually point to the object tagged by the
- * target tag. Expectations can be tested by calling {@link #testExpectedLinking()}. Implicit items will be traversed.
- *
- * @see #mark(int)
- * @see #testLinking(String, CharSequence)
- * @param getTargetObject
- * supplier to get the destination object, must not be {@code null}
- * @return Mark text to be inserted in the source file, never {@code null}
- */
- protected String link(final Supplier getTargetObject) {
- final int sourceTag = getTag();
- expectedLinkAssertions.add(() -> testLinking(sourceTag, getTargetObject.get()));
- return mark(sourceTag);
- }
-
- /**
- * Performs linking test. Checks expectations which were set in a source using {@link #link(int)} or {@link #link(Function, int).
- *
- * @see #link(int)
- * @see #link(Supplier)
- * @see #testLinking(int, EObject)
- * @param sourceFileNameAndContent
- * the file name and content, given as the key and value of the pair, respectively, must not be {@code null}
- */
- protected void testLinking(final Pair sourceFileNameAndContent) {
- testLinking(sourceFileNameAndContent.getKey(), sourceFileNameAndContent.getValue());
- }
-
- /**
- * Performs linking test. Checks expectations which were set in a source using {@link #link(int)} or {@link #link(Function, int).
- *
- * @see #link(int)
- * @see #link(Supplier)
- * @see #testLinking(int, EObject)
- * @param sourceFileName
- * the file name that should be associated with the parsed content, must not be {@code null}
- * @param sourceContent
- * source, must not be {@code null}
- */
- protected void testLinking(final String sourceFileName, final CharSequence sourceContent) {
- registerModel(sourceFileName, sourceContent);
- expectedLinkAssertions.forEach(Runnable::run);
- expectedLinkAssertions.clear();
- }
-
- /**
- * Performs linking test. Checks that given cross reference tagged with sourceTag does actually point to the object tagged by the target tag.
- * Detailed error reporting can be viewed in a compare view. Implicit items will be traversed.
- *
- * @param sourceTag
- * Tag pointing to cross reference
- * @param targetTag
- * Tag pointing to the destination object
- */
- protected void testLinking(final int sourceTag, final int targetTag) {
- testLinking(sourceTag, getObjectForTag(targetTag), true);
- }
-
- /**
- * Performs linking test. Checks that the cross reference marked with sourceTag does actually point to the object provided as the second argument. Implicit
- * items will be traversed.
- *
- * @param sourceTag
- * Tag pointing to a cross reference
- * @param targetObject
- * Expected target object
- */
- protected void testLinking(final int sourceTag, final EObject targetObject) {
- testLinking(sourceTag, targetObject, true);
- }
-
- /**
- * Performs linking test. Checks that the source object is the same as the object pointed by targetTag provided as the second argument. Implicit
- * items will be traversed.
- *
- * @param sourceObject
- * Source object
- * @param targetTag
- * Tag to the expected target object
- */
- protected void testLinking(final EObject sourceObject, final int targetTag) {
- testLinking(sourceObject, targetTag, true);
- }
-
- /**
- * Performs linking test. Checks that the cross reference marked with sourceTag does actually point to the object provided as the second argument.
- *
- * @param sourceTag
- * Tag pointing to a cross reference
- * @param targetObject
- * Expected target object, must not be {@code null}
- * @param traverseImplicitItems
- * If target of a reference is an implicit item and this parameter is set to true, the test will get and compare the original object from which this
- * implicit item was created
- */
- protected void testLinking(final int sourceTag, final EObject targetObject, final boolean traverseImplicitItems) {
- assertNotNull("Target object must not be null.", targetObject); //$NON-NLS-1$
- CrossReference crossReference = getMarkerTagsInfo().getCrossReference(sourceTag);
- EObject referencedSourceObject = getCrossReferencedObject(sourceTag, traverseImplicitItems, crossReference);
- assertEObjectsAreEqual(referencedSourceObject, targetObject, crossReference);
- }
-
- /**
- * Performs linking test. Checks that the source object is the same as the object pointed by targetTag provided as the second argument.
- * Does not deal with cross-referencing.
- *
- * @param sourceObject
- * Source object, must not be {@code null}
- * @param targetTag
- * Tag to the referenced target object
- * @param traverseImplicitItems
- * If target of a reference is an implicit item and this parameter is set to true, the test will get and compare the original object from which this
- * implicit item was created
- */
- @SuppressWarnings("PMD.UnusedFormalParameter")
- protected void testLinking(final EObject sourceObject, final int targetTag, final boolean traverseImplicitItems) {
- assertNotNull("Source object must not be null.", sourceObject); //$NON-NLS-1$
- EObject referencedTargetObject = getObjectForTag(targetTag);
- assertEObjectsAreEqual(sourceObject, referencedTargetObject, null);
- }
-
- /**
- * Asserts whether the two objects are equal.
- *
- * @param sourceObject
- * First object needed for comparison.
- * @param targetObject
- * Target object needed for comparison.
- * @param crossReference
- * CrossReference object, can be {@code null}
- */
- protected void assertEObjectsAreEqual(final EObject sourceObject, final EObject targetObject, final CrossReference crossReference) {
- StringBuilder expected = new StringBuilder(80);
- StringBuilder found = new StringBuilder(80);
- if (crossReference != null) {
- String crossReferenceText = "Cross reference:\n" + crossReference.toString() + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
- expected.append(crossReferenceText);
- found.append(crossReferenceText);
- }
- expected.append(LINKS_TO);
- found.append(LINKS_TO);
- URI targetUri = EcoreUtil.getURI(targetObject);
- expected.append(targetUri);
- String sourceObjectUri = EcoreUtil.getURI(sourceObject).toString();
- found.append(sourceObjectUri);
- expected.append(WHICH_CORRESPONDS_TO);
- INode node;
- node = NodeModelUtils.findActualNodeFor(targetObject);
- if (node != null) {
- expected.append(NodeModelUtils.getTokenText(node));
- } else {
- expected.append(NO_NODE_MODEL_COULD_BE_A_DERIVED_OBJECT);
- }
- found.append(WHICH_CORRESPONDS_TO);
- node = NodeModelUtils.findActualNodeFor(sourceObject);
- if (sourceObject.eIsProxy()) {
- found.append(UNRESOLVED_REFERENCE);
- } else if (node != null) {
- found.append(NodeModelUtils.getTokenText(node));
- } else {
- found.append(NO_NODE_MODEL_COULD_BE_A_DERIVED_OBJECT);
- }
- assertEquals("Errors found. Consider compare view.", expected.toString(), found.toString()); //$NON-NLS-1$
- }
-
- /**
- * Returns the referenced {@link EObject} pointed to by the cross reference.
- *
- * Note: For implicit item traversal to work, a custom implementation must be provided by overriding this method.
- *
- *
- * @param sourceTag
- * the source tag
- * @param traverseImplicitItems
- * If target of a reference is an implicit item and this parameter is set to true, the test will get and compare the original object from which this
- * implicit item was created.
- * @param crossReference
- * Cross reference to be resolved, must not be {@code null}
- * @return the referenced {@link EObject}, must not be {@code null}
- */
- @SuppressWarnings("PMD.UnusedFormalParameter")
- protected EObject getCrossReferencedObject(final int sourceTag, final boolean traverseImplicitItems, final CrossReference crossReference) {
- EObject context = getObjectForTag(sourceTag);
- if (crossReference == null) {
- throw new IllegalArgumentException(NLS.bind("Cross reference on object ''{0}'' could not be resolved.", context.toString())); //$NON-NLS-1$
- }
- // We only handle references in assignments
- Assignment assignment = EcoreUtil2.getContainerOfType(crossReference, Assignment.class);
- EObject sourceObject;
- String featureName = assignment.getFeature();
- EReference reference = (EReference) context.eClass().getEStructuralFeature(featureName);
- if (reference.isMany()) {
- Object featureValue = context.eGet(reference, false);
- assertTrue("List must be of type EObjectResolvingEList", featureValue instanceof EObjectResolvingEList); //$NON-NLS-1$
- @SuppressWarnings("unchecked")
- EList extends EObject> objects = (EObjectResolvingEList extends EObject>) context.eGet(reference, false);
- if (objects.size() == 1) {
- sourceObject = EcoreUtil.resolve(objects.get(0), context);
- } else {
- // TODO DSL-166: Handle this case when needed for tests.
- throw new AssertionError("Multiple references not supported yet"); //$NON-NLS-1$
- }
- } else {
- sourceObject = (EObject) context.eGet(reference, true);
- }
- assertNotNull("Bad test. Referenced object is null.", sourceObject); //$NON-NLS-1$
- return sourceObject;
- }
-}
diff --git a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/validation/AbstractValidationTest.java b/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/validation/AbstractValidationTest.java
deleted file mode 100644
index 7f529b690..000000000
--- a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/validation/AbstractValidationTest.java
+++ /dev/null
@@ -1,1221 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016 Avaloq Group AG 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:
- * Avaloq Group AG - initial API and implementation
- *******************************************************************************/
-package com.avaloq.tools.ddk.xtext.test.validation;
-
-import static org.eclipse.xtext.validation.ValidationMessageAcceptor.INSIGNIFICANT_INDEX;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-import org.eclipse.emf.common.util.BasicDiagnostic;
-import org.eclipse.emf.common.util.Diagnostic;
-import org.eclipse.emf.common.util.EList;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.osgi.util.NLS;
-import org.eclipse.xtext.EcoreUtil2;
-import org.eclipse.xtext.diagnostics.AbstractDiagnostic;
-import org.eclipse.xtext.linking.impl.XtextLinkingDiagnostic;
-import org.eclipse.xtext.nodemodel.ICompositeNode;
-import org.eclipse.xtext.nodemodel.INode;
-import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
-import org.eclipse.xtext.resource.XtextResource;
-import org.eclipse.xtext.resource.XtextSyntaxDiagnostic;
-import org.eclipse.xtext.util.CancelIndicator;
-import org.eclipse.xtext.validation.AbstractValidationDiagnostic;
-import org.eclipse.xtext.validation.FeatureBasedDiagnostic;
-import org.eclipse.xtext.validation.RangeBasedDiagnostic;
-import org.eclipse.xtext.xbase.lib.Pair;
-
-import com.avaloq.tools.ddk.xtext.test.AbstractXtextMarkerBasedTest;
-import com.avaloq.tools.ddk.xtext.test.XtextTestSource;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import com.google.inject.Provider;
-
-
-/**
- * Base class for validation tests.
- */
-@SuppressWarnings({"nls", "PMD.ExcessiveClassLength"})
-// CHECKSTYLE:CHECK-OFF MultipleStringLiterals
-// CHECKSTYLE:OFF MagicNumber
-public abstract class AbstractValidationTest extends AbstractXtextMarkerBasedTest {
-
- public static final int NO_ERRORS = 0;
-
- static final String NO_ERRORS_FOUND_ON_RESOURCE_MESSAGE = "Expecting no errors on resource";
-
- private static final int SEVERITY_UNDEFINED = -1;
- private static final Map CODE_TO_NAME = ImmutableMap.of(Diagnostic.INFO, "INFO", Diagnostic.WARNING, "WARNING", Diagnostic.ERROR, "ERROR");
-
- private static final String LINE_BREAK = "\n";
- private static final String DOT_AND_LINEBREAK = "'." + LINE_BREAK;
-
- /**
- * All diagnostics of the current testing file.
- */
- private Diagnostic fileDiagnostics;
-
- /**
- * During validation of a source we monitor diagnostics, that are found in the source but were not expected by the test.
- * If the validation test is strict, then we will display these unexpected diagnostics as test error.
- */
- private final Set unexpectedDiagnostics = Sets.newLinkedHashSet();
- private final Set unexpectedResourceDiagnostics = Sets.newLinkedHashSet();
-
- /**
- * validation results calculated during test setUp.
- *
- * @return the diagnostic for the primary test source file
- */
- private Diagnostic getPrimaryDiagnostics() {
- Object obj = getTestInformation().getTestObject(Diagnostic.class);
- assertNotNull("getPrimaryDiagnostics(): Diagnostics of primary source not null.", obj);
- return (Diagnostic) obj;
- }
-
- /**
- * Returns the unexpectedDiagnostics.
- *
- * @return the unexpectedDiagnostics
- */
- protected Set getUnexpectedDiagnostics() {
- return unexpectedDiagnostics;
- }
-
- /**
- * Returns the unexpectedDiagnostics.
- *
- * @return the unexpectedDiagnostics
- */
- protected Set getUnexpectedResourceDiagnostics() {
- return unexpectedResourceDiagnostics;
- }
-
- /**
- * Assertion testing for {@link AbstractValidationDiagnostic validation issues} at a given source position.
- */
- protected class XtextDiagnosticAssertion extends AbstractModelAssertion {
-
- /** Issue code of the diagnostic. */
- private final String issueCode;
- /** Issue message of the diagnostic. */
- private final String message;
- /**
- * Indicates whether the assertion must find the issue.
- * Assertion creates an error if the existence of issue code for the target eobject doesn't correspond to the value of issueMustBeFound.
- */
- private final boolean issueMustBeFound;
-
- private final int expectedSeverity;
-
- protected XtextDiagnosticAssertion(final String issueCode, final boolean issueMustBeFound) {
- this(issueCode, issueMustBeFound, SEVERITY_UNDEFINED, null);
- }
-
- protected XtextDiagnosticAssertion(final String issueCode, final boolean issueMustBeFound, final int severity, final String message) {
- this.issueCode = issueCode;
- this.issueMustBeFound = issueMustBeFound;
- this.expectedSeverity = severity;
- this.message = message;
- }
-
- /**
- * Check if the given issue code is found among issue codes for the object, located at the given position.
- *
- * @param root
- * root object of the document
- * @param pos
- * position to locate the target object
- */
- @Override
- public void apply(final EObject root, final Integer pos) {
- final Diagnostic diagnostics = validate(root);
- final BasicDiagnostic diagnosticsOnTargetPosition = new BasicDiagnostic();
- boolean issueFound = false;
- int actualSeverity = SEVERITY_UNDEFINED;
- boolean expectedSeverityMatches = false;
- boolean expectedMessageMatches = false;
- String actualMessage = "";
-
- for (AbstractValidationDiagnostic avd : Iterables.filter(diagnostics.getChildren(), AbstractValidationDiagnostic.class)) {
- if (diagnosticPositionEquals(pos, avd)) {
- // Add issue to the list of issues at the given position
- diagnosticsOnTargetPosition.add(avd);
- if (avd.getIssueCode().equals(issueCode)) {
- issueFound = true;
- actualSeverity = avd.getSeverity();
- // True if the expected severity is not set, or if matches with the actual one
- expectedSeverityMatches = expectedSeverity == SEVERITY_UNDEFINED || expectedSeverity == actualSeverity;
- actualMessage = avd.getMessage();
- // True if message matches with actual message or message is null
- expectedMessageMatches = message == null || actualMessage.equals(message);
- if (issueMustBeFound) {
- // Remove the diagnostic from the list of non-expected diagnostics
- getUnexpectedDiagnostics().remove(avd);
- // Don't need to display error messages
- if (expectedSeverityMatches && expectedMessageMatches) {
- return;
- }
- }
- }
- }
- }
-
- // Create error message
- createErrorMessage(pos, diagnosticsOnTargetPosition, issueFound, expectedSeverityMatches, actualSeverity, expectedMessageMatches, actualMessage);
- }
-
- /**
- * Create an error message (if needed) based on the given input parameters.
- *
- * @param pos
- * position in the source to associate the message with
- * @param diagnosticsOnTargetPosition
- * diagnostics on the specifies position
- * @param issueFound
- * specifies whether an issue has been found at the given position
- * @param expectedSeverityMatches
- * true if expected severity equals actual one, false otherwise
- * @param actualSeverity
- * actual severity
- * @param expectedMessageMatches
- * expected message matches
- * @param actualMessage
- * actual message
- */
- private void createErrorMessage(final Integer pos, final BasicDiagnostic diagnosticsOnTargetPosition, final boolean issueFound, final boolean expectedSeverityMatches, final int actualSeverity, final boolean expectedMessageMatches, final String actualMessage) {
- StringBuilder errorMessage = new StringBuilder(180);
- if (issueMustBeFound && !issueFound) {
- errorMessage.append("Expected issue not found. Code '").append(issueCode).append('\n');
- } else if (!issueMustBeFound && issueFound) {
- errorMessage.append("There should be no issue with the code '").append(issueCode).append(DOT_AND_LINEBREAK);
- }
- if (issueFound && !expectedMessageMatches) {
- errorMessage.append("Expected message does not match. Expected: '").append(message).append("', Actual: '").append(actualMessage).append('\n');
- }
- // If the expected issue has been found, but the actual severity does not match with expected one
- if (issueMustBeFound && issueFound && !expectedSeverityMatches) {
- errorMessage.append("Severity does not match. Expected: ").append(CODE_TO_NAME.get(expectedSeverity)).append(". Actual: ").append(CODE_TO_NAME.get(actualSeverity)).append(".\n");
- }
- // Memorize error message
- if (errorMessage.length() > 0) {
- if (!diagnosticsOnTargetPosition.getChildren().isEmpty()) {
- errorMessage.append(" All issues at this position:\n");
- errorMessage.append(diagnosticsToString(diagnosticsOnTargetPosition, false));
- }
- memorizeErrorOnPosition(pos, errorMessage.toString());
- }
- }
-
- /**
- * Compare if the position of the given diagnostic equals to the given position in text.
- *
- * @param pos
- * position in text
- * @param avd
- * diagnostic that we check, if it has the same position as the given position in text
- * @return
- * TRUE if diagnostic has the same position as the given one, FALSE otherwise.
- */
- protected boolean diagnosticPositionEquals(final Integer pos, final AbstractValidationDiagnostic avd) {
- if (avd instanceof FeatureBasedDiagnostic && ((FeatureBasedDiagnostic) avd).getFeature() != null) {
- List nodes = NodeModelUtils.findNodesForFeature(avd.getSourceEObject(), ((FeatureBasedDiagnostic) avd).getFeature());
- if (nodes.isEmpty()) {
- INode node = NodeModelUtils.getNode(avd.getSourceEObject());
- INode firstNonHiddenLeafNode = getXtextTestUtil().findFirstNonHiddenLeafNode(node);
- if (firstNonHiddenLeafNode == null) {
- return issueMustBeFound;
- } else if (firstNonHiddenLeafNode.getTotalOffset() == pos) {
- return true;
- }
- } else {
- int avdIndex = ((FeatureBasedDiagnostic) avd).getIndex();
- for (int i = 0; i < nodes.size(); i++) {
- if (avdIndex == INSIGNIFICANT_INDEX || avdIndex == i) {
- INode firstNonHiddenLeafNode = getXtextTestUtil().findFirstNonHiddenLeafNode(nodes.get(i));
- if (firstNonHiddenLeafNode == null) {
- return issueMustBeFound;
- } else if (firstNonHiddenLeafNode.getTotalOffset() == pos) {
- return true;
- }
- }
- }
- }
- } else if (avd instanceof RangeBasedDiagnostic) {
- if (((RangeBasedDiagnostic) avd).getOffset() == pos) {
- return true;
- }
- } else {
- INode node = NodeModelUtils.getNode(avd.getSourceEObject());
- INode firstNonHiddenLeafNode = getXtextTestUtil().findFirstNonHiddenLeafNode(node);
- if (firstNonHiddenLeafNode == null) {
- return issueMustBeFound;
- } else if (firstNonHiddenLeafNode.getTotalOffset() == pos) {
- return true;
- }
- }
- return false;
- }
- }
-
- /**
- * Assertion testing for {@link AbstractValidationDiagnostic validation issues} at a given source position.
- */
- private class ResourceDiagnosticAssertion extends AbstractModelAssertion {
-
- /** Issue code of the diagnostic. */
- private final String issueCode;
- /** Issue message of the diagnostic. */
- private final String message;
- /**
- * Indicates whether the assertion must find the issue.
- * Assertion creates an error if the existence of issue code for the target eobject doesn't correspond to the value of issueMustBeFound.
- */
- private final boolean issueMustBeFound;
-
- private final int expectedSeverity;
-
- protected ResourceDiagnosticAssertion(final String issueCode, final boolean issueMustBeFound, final int severity, final String message) {
- this.issueCode = issueCode;
- this.issueMustBeFound = issueMustBeFound;
- this.expectedSeverity = severity;
- this.message = message;
- }
-
- /**
- * Check if the given issue code is found among issue codes for the object, located at the given position.
- *
- * @param root
- * root object of the document
- * @param pos
- * position to locate the target object
- */
- @Override
- public void apply(final EObject root, final Integer pos) {
- Iterable diagnostics = null;
- switch (expectedSeverity) {
- case Diagnostic.ERROR:
- diagnostics = root.eResource().getErrors();
- break;
- case Diagnostic.WARNING:
- diagnostics = root.eResource().getWarnings();
- break;
- case SEVERITY_UNDEFINED:
- diagnostics = Iterables.concat(root.eResource().getErrors(), root.eResource().getWarnings());
- break;
- }
- final List diagnosticsOnTargetPosition = Lists.newArrayList();
- boolean issueFound = false;
- int actualSeverity = expectedSeverity;
- boolean expectedMessageMatches = false;
- String actualMessage = "";
-
- for (AbstractDiagnostic diag : Iterables.filter(diagnostics, AbstractDiagnostic.class)) {
- if (diagnosticPositionEquals(pos, diag)) {
- // Add issue to the list of issues at the given position
- diagnosticsOnTargetPosition.add(diag);
- if (diag.getCode() != null && diag.getCode().equals(issueCode)) {
- issueFound = true;
- if (expectedSeverity == SEVERITY_UNDEFINED) {
- actualSeverity = root.eResource().getErrors().contains(diag) ? Diagnostic.ERROR : Diagnostic.WARNING;
- }
- actualMessage = diag.getMessage();
- // True if message matches with actual message or message is null
- expectedMessageMatches = message == null || actualMessage.equals(message);
- // Don't need to display error messages
- if (issueMustBeFound) {
- // Remove the diagnostic from the list of non-expected diagnostics
- getUnexpectedResourceDiagnostics().remove(diag);
- // Don't need to display error messages
- if (expectedMessageMatches) {
- return;
- }
- }
- }
- }
- }
-
- // Create error message
- createErrorMessage(pos, diagnosticsOnTargetPosition, issueFound, true, actualSeverity, expectedMessageMatches, actualMessage);
- }
-
- /**
- * Create an error message (if needed) based on the given input parameters.
- *
- * @param pos
- * position in the source to associate the message with
- * @param diagnosticsOnTargetPosition
- * diagnostics on the specifies position
- * @param issueFound
- * specifies whether an issue has been found at the given position
- * @param expectedSeverityMatches
- * true if expected severity equals actual one, false otherwise
- * @param actualSeverity
- * actual severity
- * @param expectedMessageMatches
- * expected message matches
- * @param actualMessage
- * actual message
- */
- private void createErrorMessage(final Integer pos, final List diagnosticsOnTargetPosition, final boolean issueFound, final boolean expectedSeverityMatches, final int actualSeverity, final boolean expectedMessageMatches, final String actualMessage) {
- StringBuilder errorMessage = new StringBuilder(200);
- if (issueMustBeFound && !issueFound) {
- errorMessage.append("Expected issue not found. Code '").append(issueCode).append('\n');
- } else if (!issueMustBeFound && issueFound) {
- errorMessage.append("There should be no issue with the code '").append(issueCode).append(DOT_AND_LINEBREAK);
- }
- if (issueFound && !expectedMessageMatches) {
- errorMessage.append("Expected message does not match. Expected: '").append(message).append("', Actual: '").append(actualMessage).append('\n');
- }
- // If the expected issue has been found, but the actual severity does not match with expected one
- if (issueMustBeFound && issueFound && !expectedSeverityMatches) {
- errorMessage.append("Severity does not match. Expected: ").append(CODE_TO_NAME.get(expectedSeverity)).append(". Actual: ").append(CODE_TO_NAME.get(actualSeverity)).append(".\n");
- }
- // Memorize error message
- if (errorMessage.length() > 0) {
- if (!diagnosticsOnTargetPosition.isEmpty()) {
- errorMessage.append(" All issues at this position:\n");
- errorMessage.append(diagnosticsToString(diagnosticsOnTargetPosition, false));
- }
- memorizeErrorOnPosition(pos, errorMessage.toString());
- }
- }
-
- /**
- * Compare if the position of the given diagnostic equals to the given position in text.
- *
- * @param pos
- * position in text
- * @param diagnostic
- * diagnostic that we check, if it has the same position as the given position in text
- * @return
- * {@code true} if diagnostic has the same position as the given one, {@code false} otherwise.
- */
- private boolean diagnosticPositionEquals(final Integer pos, final AbstractDiagnostic diagnostic) {
- return diagnostic.getOffset() == pos;
- }
- }
-
- /**
- * Get a cached version of an object associated with the root object for a given key.
- *
- * @param
- * type of the associated object
- * @param root
- * root EObject
- * @param key
- * key identifying the type of the associated object
- * @param provider
- * provider to deliver an object if there is no cached version
- * @return
- * cached version of the associated object
- */
- protected T getCached(final EObject root, final String key, final Provider provider) {
- XtextResource res = (XtextResource) root.eResource();
- return res.getCache().get(key, res, provider);
- }
-
- /**
- * Validate the model.
- *
- * @param root
- * root EObject to validate
- * @return
- * validation results
- */
- protected Diagnostic validate(final EObject root) {
- return getCached(root, "DIAGNOSTIC", () -> getXtextTestUtil().getDiagnostician().validate(root));
- }
-
- /**
- * Display the path from root object to the target EObject.
- *
- * @param eObject
- * object to display the object path for
- * @param offset
- * string offset that is added in the beginning of each line
- * @return
- * object hierarchy as string (each object on a single line)
- */
- private String pathFromRootAsString(final EObject eObject, final String offset) {
- List hierarchy = Lists.newLinkedList();
-
- EObject currentObject = eObject;
- while (currentObject != null) {
- hierarchy.add(0, offset + currentObject.toString());
- currentObject = currentObject.eContainer();
- }
-
- return String.join("\n", hierarchy);
- }
-
- /**
- * Persist list diagnostics into string to display the list of issue codes.
- *
- * @param diagnostics
- * list of diagnostics
- * @param displayPathToTargetObject
- * if true, the path through the object hierarchy is printed out up to the root node
- * @return
- * string with list of issue codes, separated with a line break
- */
- // TODO (ACF-4153) generalize for all kinds of errors and move to AbstractXtextTest
- private String diagnosticsToString(final Diagnostic diagnostics, final boolean displayPathToTargetObject) {
- StringBuilder sb = new StringBuilder();
- for (Diagnostic diagnostic : diagnostics.getChildren()) {
- if (diagnostic instanceof AbstractValidationDiagnostic) {
- AbstractValidationDiagnostic avd = (AbstractValidationDiagnostic) diagnostic;
- sb.append(" ");
- sb.append(avd.getIssueCode());
- if (displayPathToTargetObject) {
- sb.append(" at line: ");
- ICompositeNode compositeNode = NodeModelUtils.findActualNodeFor(avd.getSourceEObject());
- if (compositeNode != null) {
- sb.append(compositeNode.getStartLine());
- } else {
- sb.append("Unknown");
- }
- sb.append(" on \n");
- sb.append(pathFromRootAsString(avd.getSourceEObject(), " "));
- }
- sb.append(LINE_BREAK);
- }
- }
- return sb.toString();
- }
-
- /**
- * Persist list diagnostics into string to display the list of issue codes.
- *
- * @param diagnostics
- * list of diagnostics
- * @param displayPathToTargetObject
- * if true, the path through the object hierarchy is printed out up to the root node
- * @return
- * string with list of issue codes, separated with a line break
- */
- // TODO (ACF-4153) generalize for all kinds of errors and move to AbstractXtextTest
- private String diagnosticsToString(final List diagnostics, final boolean displayPathToTargetObject) {
- StringBuilder sb = new StringBuilder(25);
- for (Resource.Diagnostic diagnostic : diagnostics) {
- if (diagnostic instanceof AbstractDiagnostic) {
- AbstractDiagnostic diag = (AbstractDiagnostic) diagnostic;
- sb.append(" ");
- sb.append(diag.getCode());
- if (displayPathToTargetObject) {
- sb.append(" at line: ");
- sb.append(diag.getLine());
- sb.append(" on \n");
- sb.append(" ");
- sb.append(diag.getUriToProblem());
- }
- sb.append(LINE_BREAK);
- }
- }
- return sb.toString();
- }
-
- @Override
- protected void beforeAllTests() {
- super.beforeAllTests();
- if (getTestSource() != null) {
- Diagnostic primaryDiagnostics = getXtextTestUtil().getDiagnostician().validate(getSemanticModel());
- getTestInformation().putTestObject(Diagnostic.class, primaryDiagnostics);
- }
- }
-
- /**
- * Register a new validation marker with the given issue code. Expects an info.
- *
- * @param issueCode
- * issue code (usually found as static constant of the JavaValidator class of the DSL being tested)
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String info(final String issueCode) {
- return info(issueCode, null);
- }
-
- /**
- * Register a new validation marker with the given issue code and message. Expects an info.
- *
- * @param issueCode
- * issue code (usually found as static constant of the JavaValidator class of the DSL being tested)
- * @param message
- * the expected issue message
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String info(final String issueCode, final String message) {
- return addAssertion(new XtextDiagnosticAssertion(issueCode, true, Diagnostic.INFO, message));
- }
-
- /**
- * Register a new validation marker with the given issue code. Expects a warning if the condition is {@code true}, no diagnostic otherwise.
- *
- * @param condition
- * the condition when the marker is expected
- * @param issueCode
- * issue code (usually found as static constant of the JavaValidator class of the DSL being tested)
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String warningIf(final boolean condition, final String issueCode) {
- if (condition) {
- return warning(issueCode);
- } else {
- return noDiagnostic(issueCode);
- }
- }
-
- /**
- * Register a new validation marker with the given issue code. Expects a warning.
- *
- * @param issueCode
- * issue code (usually found as static constant of the JavaValidator class of the DSL being tested)
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String warning(final String issueCode) {
- return warning(issueCode, null);
- }
-
- /**
- * Register a new validation marker with the given issue code and message. Expects a warning.
- *
- * @param issueCode
- * issue code (usually found as static constant of the JavaValidator class of the DSL being tested)
- * @param message
- * the expected issue message
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String warning(final String issueCode, final String message) {
- return addAssertion(new XtextDiagnosticAssertion(issueCode, true, Diagnostic.WARNING, message));
- }
-
- /**
- * Register a new validation marker with the given issue code. Expects an error if the condition is {@code true}, no diagnostic otherwise.
- *
- * @param condition
- * the condition when the marker is expected
- * @param issueCode
- * issue code (usually found as static constant of the JavaValidator class of the DSL being tested)
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String errorIf(final boolean condition, final String issueCode) {
- if (condition) {
- return error(issueCode);
- } else {
- return noDiagnostic(issueCode);
- }
- }
-
- /**
- * Register a new validation marker with the given issue code. Expects an error.
- *
- * @param issueCode
- * issue code (usually found as static constant of the JavaValidator class of the DSL being tested)
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String error(final String issueCode) {
- return error(issueCode, null);
- }
-
- /**
- * Register a new validation marker with the given issue code and message. Expects an error.
- *
- * @param issueCode
- * issue code (usually found as static constant of the JavaValidator class of the DSL being tested)
- * @param message
- * the expected issue message
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String error(final String issueCode, final String message) {
- return addAssertion(new XtextDiagnosticAssertion(issueCode, true, Diagnostic.ERROR, message));
- }
-
- /**
- * Register a new validation marker with the given issue code.
- * The issue is expected to be found in the test file.
- *
- * @param issueCode
- * issue code (usually found as static constant of the JavaValidator class of the DSL being tested)
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String diagnostic(final String issueCode) {
- return diagnostic(issueCode, null);
- }
-
- /**
- * Register a new validation marker with the given issue code and message.
- * The issue and message are expected to be found in the test file.
- *
- * @param issueCode
- * issue code (usually found as static constant of the JavaValidator class of the DSL being tested)
- * @param message
- * the expected issue message
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String diagnostic(final String issueCode, final String message) {
- return addAssertion(new XtextDiagnosticAssertion(issueCode, true, SEVERITY_UNDEFINED, message));
- }
-
- /**
- * Register a new linking error validation marker.
- * The issue is expected to be found in the test file.
- *
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String linkingError() {
- return linkingError(null);
- }
-
- /**
- * Register a new linking error validation marker with the given message.
- * The issue is expected to be found in the test file.
- *
- * @param message
- * issuethe expected issue message
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String linkingError(final String message) {
- return addAssertion(new ResourceDiagnosticAssertion(org.eclipse.xtext.diagnostics.Diagnostic.LINKING_DIAGNOSTIC, true, Diagnostic.ERROR, message));
- }
-
- /**
- * Register a new resource validation marker with the given issue code and message.
- * The issue is expected to be found in the test file.
- *
- * @param issueCode
- * issue code (usually found as static constant of the JavaValidator class of the DSL being tested)
- * @param message
- * the expected issue message
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String resourceDiagnostic(final String issueCode, final String message) {
- return addAssertion(new ResourceDiagnosticAssertion(issueCode, true, Diagnostic.ERROR, message));
- }
-
- /**
- * Register a new validation marker with the given issue code.
- * The issue is expected NOT to be found in the test file.
- *
- * @param issueCode
- * issue code (usually found as static constant of the JavaValidator class of the DSL being tested)
- * @return
- * unique marker that can be used in the input string to mark a position that should be validated
- */
- protected String noDiagnostic(final String issueCode) {
- return addAssertion(new XtextDiagnosticAssertion(issueCode, false));
- }
-
- @Override
- protected void beforeApplyAssertions(final XtextTestSource testSource) {
- super.beforeApplyAssertions(testSource);
- EObject root = testSource.getModel();
- // Get all diagnostics of the current testing file
- EcoreUtil2.resolveLazyCrossReferences(root.eResource(), CancelIndicator.NullImpl);
- fileDiagnostics = validate(root);
- getUnexpectedDiagnostics().addAll(fileDiagnostics.getChildren());
- getUnexpectedResourceDiagnostics().addAll(root.eResource().getErrors());
- getUnexpectedResourceDiagnostics().addAll(root.eResource().getWarnings());
- }
-
- @Override
- protected String getAdditionalErrorMessageInformation() {
- return diagnosticsToString(fileDiagnostics, true);
- }
-
- @Override
- protected void afterValidate() {
- super.afterValidate();
- // Garbage collection
- getUnexpectedDiagnostics().clear();
- getUnexpectedResourceDiagnostics().clear();
- }
-
- /**
- * Assert that diagnosticList contains a diagnostic of the given issueCode.
- *
- * @param issueCode
- * the code of the issue to look for
- */
- protected void assertDiagnostic(final String issueCode) {
- assertDiagnostic(getPrimaryDiagnostics(), issueCode);
- }
-
- /**
- * Assert that the given EObject model contains a diagnostic of the given issueCode.
- *
- * @param model
- * the model in which to look for issues, may be {@code null}
- * @param issueCode
- * the code of the issue to look for
- */
- protected void assertDiagnostic(final EObject model, final String issueCode) {
- assertNotNull("Issue with code '" + issueCode + "' cannot be found because the model is null", model);
- assertDiagnostic(getXtextTestUtil().getDiagnostician().validate(model), issueCode);
- }
-
- /**
- * Assert that diagnosticList does not contain a diagnostic of the given issueCode.
- *
- * @param issueCode
- * the code of the issue to look for
- */
- protected void assertNoDiagnostic(final String issueCode) {
- assertNoDiagnostic(getPrimaryDiagnostics(), issueCode);
- }
-
- /**
- * Assert that the given EObject model does not contain a diagnostic of the given issueCode.
- *
- * @param model
- * the model in which to look for issues, may be {@code null}
- * @param issueCode
- * the code of the issue to look for
- */
- protected void assertNoDiagnostic(final EObject model, final String issueCode) {
- assertNotNull("Issue with code '" + issueCode + "' cannot be found because the model is null", model);
- assertNoDiagnostic(getXtextTestUtil().getDiagnostician().validate(model), issueCode);
- }
-
- /**
- * Assert that diagnosticList does not contain any diagnostic.
- */
- protected void assertNoDiagnostics() {
- assertNoDiagnostics(getPrimaryDiagnostics());
- }
-
- /**
- * Assert that the given EObject model does not contain any diagnostic.
- *
- * @param model
- * the model in which to look for issues, may be {@code null}
- */
- protected void assertNoDiagnostics(final EObject model) {
- assertNotNull("Assertion cannot be checked because the model is null", model);
- assertNoDiagnostics(getXtextTestUtil().getDiagnostician().validate(model));
- }
-
- /**
- * Assert that diagnosticList contains a diagnostic with the given message.
- *
- * @param message
- * the message of the issue to look for
- */
- protected void assertDiagnosticMessage(final String message) {
- assertDiagnosticMessage(getPrimaryDiagnostics(), message);
- }
-
- /**
- * Assert that the given EObject model contains a diagnostic with the given message.
- *
- * @param model
- * the model in which to look for issues, may be {@code null}
- * @param message
- * the message of the issue to look for
- */
- protected void assertDiagnosticMessage(final EObject model, final String message) {
- assertNotNull("Message '" + message + "' cannot be found because the model is null", model);
- assertDiagnosticMessage(getXtextTestUtil().getDiagnostician().validate(model), message);
- }
-
- /**
- * Assert that diagnosticList contains a diagnostic with the given message.
- *
- * @param diagnostics
- * the diagnostic to check for issues
- * @param message
- * the message of the issue to look for
- */
- private static void assertDiagnosticMessage(final Diagnostic diagnostics, final String message) {
- for (Diagnostic diagnostic : diagnostics.getChildren()) {
- if (diagnostic.getMessage().equals(message)) {
- return;
- }
- }
- fail("Issue with message ' " + message + "' not found");
- }
-
- /**
- * Assert that diagnosticList contains a diagnostic of the given issueCode.
- *
- * @param diagnostics
- * the diagnostic to check for issues
- * @param issueCode
- * the code of the issue to look for
- */
- private void assertDiagnostic(final Diagnostic diagnostics, final String issueCode) {
- for (Diagnostic diagnostic : diagnostics.getChildren()) {
- if (diagnostic instanceof AbstractValidationDiagnostic && ((AbstractValidationDiagnostic) diagnostic).getIssueCode().equals(issueCode)) {
- return;
- }
- }
- fail("Issue with code '" + issueCode + "' not found");
- }
-
- /**
- * Assert that diagnosticList contains a diagnostic of the given issueCode on a given EObject.
- * For performance reasons one can validate the root object and afterwards use this method
- * to check that a particular diagnostic exists on one of the child objects of the validated model.
- *
- * @param diagnostics
- * the diagnostic to check for issues
- * @param targetObject
- * the object that should have a diagnostic with the given issueCode
- * @param issueCode
- * the code of the issue to look for
- */
- protected void assertDiagnosticOnObject(final Diagnostic diagnostics, final EObject targetObject, final String issueCode) {
- for (Diagnostic diagnostic : diagnostics.getChildren()) {
- if (diagnostic instanceof AbstractValidationDiagnostic) {
- AbstractValidationDiagnostic avd = (AbstractValidationDiagnostic) diagnostic;
- if (avd.getSourceEObject() == targetObject && avd.getIssueCode().equals(issueCode)) {
- return;
- }
- }
- }
- fail("Issue with code '" + issueCode + "' not found");
- }
-
- /**
- * Assert that diagnosticList does not contain a diagnostic of the given issueCode.
- *
- * @param diagnostics
- * the diagnostic to check for issues
- * @param issueCode
- * the code of the issue to look for
- */
- private void assertNoDiagnostic(final Diagnostic diagnostics, final String issueCode) {
- for (Diagnostic diagnostic : diagnostics.getChildren()) {
- if (((AbstractValidationDiagnostic) diagnostic).getIssueCode().equals(issueCode)) {
- fail("Issue with code '" + issueCode + "' found");
- return;
- }
- }
- }
-
- /**
- * Assert that diagnosticList does not contain any diagnostic.
- *
- * @param diagnostics
- * the diagnostic to check for issues
- */
- private void assertNoDiagnostics(final Diagnostic diagnostics) {
- assertEquals("Diagnostics should be in OK state.", diagnostics.getCode(), Diagnostic.OK);
- assertTrue("There should be no diagnostics. Instead found " + diagnostics.getChildren().size(), diagnostics.getChildren().isEmpty());
- }
-
- /**
- * Assert no errors on resource exist.
- *
- * @param object
- * the object
- */
- public static void assertNoErrorsOnResource(final EObject object) {
- final EList errors = object.eResource().getErrors();
- if (!errors.isEmpty()) {
- fail(AbstractValidationTest.NO_ERRORS_FOUND_ON_RESOURCE_MESSAGE + "; found " + Lists.transform(errors, Resource.Diagnostic::getMessage)); //$NON-NLS-1$
- }
- }
-
- /**
- * Assert no errors on resource with the given message exist.
- *
- * @param object
- * the object
- * @param messages
- * the messages
- */
- public static void assertNoErrorsOnResource(final EObject object, final String... messages) {
- List messageList = Arrays.asList(messages);
- final EList errors = object.eResource().getErrors();
- for (String errorMessage : Lists.transform(errors, Resource.Diagnostic::getMessage)) {
- assertFalse(NO_ERRORS_FOUND_ON_RESOURCE_MESSAGE + " with message '" + errorMessage + "'.", messageList.contains(errorMessage));
- }
- }
-
- /**
- * Assert no linking errors on resource with the given message exist.
- *
- * @param object
- * the object
- * @param referenceType
- * the type of the referenced elements
- * @param referenceNames
- * the names of the referenced elements
- */
- @SuppressWarnings("PMD.UnusedFormalParameter")
- public static void assertNoLinkingErrorsOnResource(final EObject object, final String referenceType, final String... referenceNames) {
- final List linkingErrors = object.eResource().getErrors().stream().filter(error -> error instanceof XtextLinkingDiagnostic).collect(Collectors.toList());
- final List errorMessages = Lists.transform(linkingErrors, Resource.Diagnostic::getMessage);
- for (final String referenceName : referenceNames) {
- boolean found = false;
- for (final String errMessage : errorMessages) {
- if (errMessage.startsWith(referenceName)) {
- found = true;
- break;
- }
- }
- assertFalse(NLS.bind("Expecting no linking errors on resource for \"{0}\".", referenceName), found);
- }
- }
-
- /**
- * Assert linking errors on resource with the given message exist.
- *
- * @param object
- * the object
- * @param referenceType
- * the type of the referenced elements
- * @param referenceNames
- * the names of the referenced elements
- */
- @SuppressWarnings("PMD.UnusedFormalParameter")
- public static void assertLinkingErrorsOnResourceExist(final EObject object, final String referenceType, final String... referenceNames) {
- final List linkingErrors = object.eResource().getErrors().stream().filter(error -> error instanceof XtextLinkingDiagnostic).collect(Collectors.toList());
- final List errorMessages = Lists.transform(linkingErrors, Resource.Diagnostic::getMessage);
- for (final String referenceName : referenceNames) {
- boolean found = false;
- for (final String errMessage : errorMessages) {
- if (errMessage.contains(referenceName)) {
- found = true;
- break;
- }
- }
- assertTrue(NLS.bind("Expected linking error on \"{0}\" but could not find it", referenceName), found);
- }
- }
-
- /**
- * Expect the given linking error messages on the resource of the given model.
- *
- * @param object
- * the object, must not be {@code null}
- * @param errorStrings
- * the expected linking error error messages, must not be {@code null}
- */
- public static void assertLinkingErrorsWithCustomMessageOnResourceExist(final EObject object, final String... errorStrings) {
- final List linkingErrors = object.eResource().getErrors().stream().filter(error -> error instanceof XtextLinkingDiagnostic).collect(Collectors.toList());
- final List errorMessages = Lists.transform(linkingErrors, Resource.Diagnostic::getMessage);
- for (final String s : errorStrings) {
- assertTrue(NLS.bind("Expected linking error \"{0}\" but could not find it", s), errorMessages.contains(s));
- }
- }
-
- /**
- * Assert no linking errors on resource with the given message exist.
- *
- * @param object
- * the object, must not be {@code null}
- * @param messages
- * the linking error messages, must not be {@code null}
- */
- public static void assertNoLinkingErrorsWithCustomMessageOnResource(final EObject object, final String... messages) {
- List messageList = Arrays.asList(messages);
- final List linkingErrors = object.eResource().getErrors().stream().filter(error -> error instanceof XtextLinkingDiagnostic).collect(Collectors.toList());
- for (String errorMessage : Lists.transform(linkingErrors, Resource.Diagnostic::getMessage)) {
- assertFalse(NLS.bind("Expecting no linking errors on resource with message \"{0}\".", errorMessage), messageList.contains(errorMessage));
- }
- }
-
- /**
- * Expect given error messages on the resource of given model.
- *
- * @param object
- * the object
- * @param errorStrings
- * the error strings
- */
- public static void assertErrorsOnResourceExist(final EObject object, final String... errorStrings) {
- final EList errors = object.eResource().getErrors();
- final List errorMessages = Lists.transform(errors, Resource.Diagnostic::getMessage);
- for (final String s : errorStrings) {
- assertTrue(NLS.bind("Expected error \"{0}\" but could not find it", s), errorMessages.contains(s));
- }
- }
-
- /**
- * Validates if there is a syntax error present in the source content.
- *
- * @param sourceFileName
- * the file name that should be associated with the parsed content, must not be {@code null}
- * @param sourceContent
- * source, must not be {@code null}
- */
- protected void assertNoSyntaxErrorsOnResource(final String sourceFileName, final CharSequence sourceContent) {
- final XtextTestSource testSource = createTestSource(sourceFileName, sourceContent.toString());
- final List errors = testSource.getModel().eResource().getErrors().stream().filter(error -> error instanceof XtextSyntaxDiagnostic).collect(Collectors.toList());
- if (!errors.isEmpty()) {
- StringBuilder sb = new StringBuilder("Syntax error is present in the test source.\nList of all found syntax errors:");
- errors.forEach(err -> sb.append("\n\t ").append(err.getMessage()));
- throw new AssertionError(sb.toString());
- }
- }
-
- /**
- * Memorize the position and issue code of each resource error that appears in the file.
- *
- * @param root
- * root node of the model to be analyzed
- */
- protected void memorizeUnexpectedResourceErrors() {
- for (Resource.Diagnostic diagnostic : getUnexpectedResourceDiagnostics()) {
- if (diagnostic instanceof AbstractDiagnostic) {
- AbstractDiagnostic diag = (AbstractDiagnostic) diagnostic;
- // Create error message
- StringBuilder sb = new StringBuilder(50);
- sb.append("Unexpected diagnostic found. Code '");
- sb.append(diag.getCode());
- sb.append(DOT_AND_LINEBREAK);
- // Retrieve the position and add the error
- memorizeErrorOnPosition(diag.getOffset(), sb.toString());
- } else {
- // Create error message
- StringBuilder sb = new StringBuilder(50);
- sb.append("Unexpected diagnostic found. '");
- sb.append(diagnostic.toString());
- sb.append(DOT_AND_LINEBREAK);
- // Add error message
- memorizeErrorOnPosition(0, sb.toString());
- }
- }
- }
-
- /**
- * Memorize the position and issue code of each unexpected diagnostic that appears in the file.
- * A diagnostic is considered as expected if a marker with the issue code in the test file was set.
- */
- protected void memorizeUnexpectedErrors() {
- for (Diagnostic diagnostic : getUnexpectedDiagnostics()) {
- if (diagnostic instanceof AbstractValidationDiagnostic) {
- AbstractValidationDiagnostic avd = (AbstractValidationDiagnostic) diagnostic;
- // Create error message
- StringBuilder sb = new StringBuilder(50);
- sb.append("Unexpected issue found. Code '");
- sb.append(avd.getIssueCode());
- sb.append(DOT_AND_LINEBREAK);
- // Retrieve the position and add the error
- if (avd instanceof FeatureBasedDiagnostic && ((FeatureBasedDiagnostic) avd).getFeature() != null) {
- List nodes = NodeModelUtils.findNodesForFeature(avd.getSourceEObject(), ((FeatureBasedDiagnostic) avd).getFeature());
- if (nodes.isEmpty()) {
- INode node = NodeModelUtils.getNode(avd.getSourceEObject());
- memorizeErrorOnPosition(getXtextTestUtil().findFirstNonHiddenLeafNode(node).getTotalOffset(), sb.toString());
- } else {
- for (INode node : nodes) {
- memorizeErrorOnPosition(getXtextTestUtil().findFirstNonHiddenLeafNode(node).getTotalOffset(), sb.toString());
- }
- }
- } else if (avd instanceof RangeBasedDiagnostic) {
- memorizeErrorOnPosition(((RangeBasedDiagnostic) avd).getOffset(), sb.toString());
- } else {
- memorizeErrorOnPosition(NodeModelUtils.getNode(avd.getSourceEObject()).getTotalOffset(), sb.toString());
- }
- } else {
- // Create error message
- StringBuilder sb = new StringBuilder(50);
- sb.append("Unexpected diagnostic found. '");
- sb.append(diagnostic.toString());
- sb.append(DOT_AND_LINEBREAK);
- // Add error message
- memorizeErrorOnPosition(0, sb.toString());
- }
- }
- }
-
- /**
- * Strictly validates a source given by a file name and content.
- *
- * @param sourceFileName
- * the file name that should be associated with the parsed content, must not be {@code null}
- * @param sourceType
- * defines if the source is a kernel or customer source, must not be {@code null}
- * @param sourceContent
- * source, must not be {@code null}
- */
- protected void validateStrictly(final String sourceFileName, final TestSourceType sourceType, final CharSequence sourceContent) {
- XtextTestSource testSource = processMarkers(sourceFileName, sourceType, sourceContent);
- memorizeUnexpectedErrors();
- memorizeUnexpectedResourceErrors();
- processErrorsFound(testSource.getContent());
- afterValidate();
- }
-
- /**
- * Strictly validate a kernel source given by a {@link Pair} of file name and content.
- * All not expected diagnostics are considered as an error.
- *
- * @param sourceFileNameAndContent
- * the file name and content, given as the key and value of the pair, respectively, must not be {@code null}
- */
- protected void validateKernelSourceStrictly(final Pair sourceFileNameAndContent) {
- validateKernelSourceStrictly(sourceFileNameAndContent.getKey(), sourceFileNameAndContent.getValue());
- }
-
- /**
- * Strictly validate a customer source given by a {@link Pair} of file name and content.
- * All not expected diagnostics are considered as an error.
- *
- * @param sourceFileNameAndContent
- * the file name and content, given as the key and value of the pair, respectively, must not be {@code null}
- */
- protected void validateCustomerSourceStrictly(final Pair sourceFileNameAndContent) {
- validateCustomerSourceStrictly(sourceFileNameAndContent.getKey(), sourceFileNameAndContent.getValue());
- }
-
- /**
- * Strictly validate a kernel source given by a file name and content.
- * All not expected diagnostics are considered as an error.
- *
- * @param sourceFileName
- * the file name that should be associated with the parsed content, must not be {@code null}
- * @param sourceContent
- * source, must not be {@code null}
- */
- protected void validateKernelSourceStrictly(final String sourceFileName, final CharSequence sourceContent) {
- validateStrictly(sourceFileName, TestSourceType.CLIENT_ALL, sourceContent);
- }
-
- /**
- * Strictly validate a customer source given by a file name and content.
- * All not expected diagnostics are considered as an error.
- *
- * @param sourceFileName
- * the file name that should be associated with the parsed content, must not be {@code null}
- * @param sourceContent
- * source, must not be {@code null}
- */
- protected void validateCustomerSourceStrictly(final String sourceFileName, final CharSequence sourceContent) {
- validateStrictly(sourceFileName, TestSourceType.CLIENT_CUSTOMER, sourceContent);
- }
-}
diff --git a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/validation/ValidationHelper.java b/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/validation/ValidationHelper.java
index 3acda5d55..3000474bb 100644
--- a/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/validation/ValidationHelper.java
+++ b/com.avaloq.tools.ddk.xtext.test.core/src/com/avaloq/tools/ddk/xtext/test/validation/ValidationHelper.java
@@ -10,20 +10,28 @@
*******************************************************************************/
package com.avaloq.tools.ddk.xtext.test.validation;
+import static org.junit.jupiter.api.Assertions.fail;
+
import java.util.List;
+import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
+import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.testing.validation.ValidationTestHelper;
import org.eclipse.xtext.ui.editor.model.IXtextDocument;
import org.eclipse.xtext.validation.CheckMode;
import org.eclipse.xtext.validation.Issue;
+import com.google.common.collect.Lists;
+
/**
* Helper methods relating to model validation.
*/
public class ValidationHelper extends ValidationTestHelper {
+ private static final String NO_ERRORS_FOUND_ON_RESOURCE_MESSAGE = "Expected no errors on resource"; //$NON-NLS-1$
+
/**
* Validates the provided document and returns a list of issues found.
*
@@ -42,7 +50,10 @@ public List getIssues(final IXtextDocument document) {
* the object to test for errors
*/
public void assertNoSyntaxOrLinkingErrors(final EObject obj) {
- AbstractValidationTest.assertNoErrorsOnResource(obj);
+ final EList errors = obj.eResource().getErrors();
+ if (!errors.isEmpty()) {
+ fail(NO_ERRORS_FOUND_ON_RESOURCE_MESSAGE + "; found " + Lists.transform(errors, Resource.Diagnostic::getMessage)); //$NON-NLS-1$
+ }
}
}
diff --git a/com.avaloq.tools.ddk.xtext.test/src/com/avaloq/tools/ddk/xtext/formatter/AbstractFormatterTest.java b/com.avaloq.tools.ddk.xtext.test/src/com/avaloq/tools/ddk/xtext/formatter/AbstractFormatterTest.java
deleted file mode 100644
index e1e12db5b..000000000
--- a/com.avaloq.tools.ddk.xtext.test/src/com/avaloq/tools/ddk/xtext/formatter/AbstractFormatterTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016 Avaloq Group AG 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:
- * Avaloq Group AG - initial API and implementation
- *******************************************************************************/
-package com.avaloq.tools.ddk.xtext.formatter;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.io.IOException;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.xtext.formatting.INodeModelFormatter;
-import org.eclipse.xtext.formatting.INodeModelFormatter.IFormattedRegion;
-import org.eclipse.xtext.nodemodel.ICompositeNode;
-import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
-import org.eclipse.xtext.resource.SaveOptions;
-import org.eclipse.xtext.serializer.ISerializer;
-
-import com.avaloq.tools.ddk.xtext.test.AbstractXtextTest;
-
-
-/**
- * Base class for formatting tests.
- * The assertXyz methods are essentially copied from {@link com.avaloq.tools.ddk.xtext.test.formatting.AbstractAcfFormattingTest}.
- */
-@SuppressWarnings("nls")
-public abstract class AbstractFormatterTest extends AbstractXtextTest {
-
- /**
- * Loads a model from a string representation of a source.
- *
- * @param input
- * String representing a serialized model
- * @return Loaded model
- */
- private EObject getModel(final String input) throws IOException {
- return getXtextTestUtil().getModel("mytestmodel." + getXtextTestUtil().getFileExtension(), input);
- }
-
- /**
- * Gets the Guice injected serializer.
- *
- * @return Serializer the DI serializer
- */
- protected ISerializer getSerializer() {
- return getXtextTestUtil().getSerializer();
- }
-
- // test formatting based on the ParseTreeConstructorin
- protected void assertFormattedPTC(final String expected, final String model) throws IOException {
- EObject m = getModel(model);
- String res = getSerializer().serialize(m, SaveOptions.newBuilder().format().getOptions());
- assertEquals(expected, res, "Serialization not equal");
- }
-
- protected void assertPreserved(final String model) throws IOException {
- EObject m = getModel(model);
- String res = getSerializer().serialize(m, SaveOptions.newBuilder().getOptions());
- assertEquals(model, res, "Preserved node model");
- }
-
- // test formatting based on the NodeModel
- protected void assertFormattedNM(final String expected, final String model, final int offset, final int length) throws IOException {
- ICompositeNode node = NodeModelUtils.getNode(getModel(model)).getRootNode();
- IFormattedRegion r = getXtextTestUtil().get(INodeModelFormatter.class).format(node, offset, length);
- String actual = model.substring(0, r.getOffset()) + r.getFormattedText() + model.substring(r.getLength() + r.getOffset());
- assertEquals(expected, actual, "Formatting based on the NodeModel");
- }
-
-}
diff --git a/com.avaloq.tools.ddk.xtext.test/src/com/avaloq/tools/ddk/xtext/formatter/FormatterTest.java b/com.avaloq.tools.ddk.xtext.test/src/com/avaloq/tools/ddk/xtext/formatter/FormatterTest.java
deleted file mode 100644
index b8e7b1041..000000000
--- a/com.avaloq.tools.ddk.xtext.test/src/com/avaloq/tools/ddk/xtext/formatter/FormatterTest.java
+++ /dev/null
@@ -1,507 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016 Avaloq Group AG 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:
- * Avaloq Group AG - initial API and implementation
- *******************************************************************************/
-package com.avaloq.tools.ddk.xtext.formatter;
-
-import java.io.IOException;
-
-import org.eclipse.xtext.resource.SaveOptions;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.api.Test;
-
-import com.avaloq.tools.ddk.xtext.formatter.formatterTestLanguage.Decl;
-import com.avaloq.tools.ddk.xtext.formatter.formatterTestLanguage.FormatterTestLanguageFactory;
-import com.avaloq.tools.ddk.xtext.formatter.formatterTestLanguage.TestLinewrapMinMax;
-import com.avaloq.tools.ddk.xtext.formatter.util.FormatterTestUtil;
-
-
-/**
- * This class tests the Acs Formatter framework. The tests are basically a copy
- * of the Xtext Formatter tests.
- */
-@SuppressWarnings("nls")
-public class FormatterTest extends AbstractFormatterTest {
- @Override
- protected FormatterTestUtil getXtextTestUtil() {
- return FormatterTestUtil.getInstance();
- }
-
- /**
- * This test class does not have a test source file. {@inheritDoc}
- */
- @Override
- protected String getTestSourceFileName() {
- return null;
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void linewrap() throws IOException {
- String model = "test linewrap float val; int x; double y;";
- String expected = "test linewrap\nfloat val;\nint x;\ndouble y;";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void keepComments() throws IOException {
- // String model = "test linewrap float val; int x; double y;";
- String model = "// begincomment \ntest linewrap// comment1\n" + "float val;//comment2\n" + "int x;" + "double y; //yoyoyo!\n// endcomment.";
- final String exp = "// begincomment \ntest linewrap// comment1\n" + "float val;//comment2\n" + "int x;\n" + "double y; //yoyoyo!\n// endcomment.";
- assertFormattedPTC(exp, model);
- assertFormattedNM(exp, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test verifies that {@link com.avaloq.tools.ddk.xtext.formatter.formatterTestLanguage.Line} elements are aligned at the specified column.
- *
- * @throws IOException
- */
- @Test
- public void column() throws IOException {
- String model = "test column item int x;";
- String expected = "test\n column\n\titem int x;";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test verifies that elements can be aligned at column 0 and also that
- * a minimum padding is always inserted.
- *
- * @throws IOException
- */
- @Test
- public void columnMinimumPadding() throws IOException {
- String model = " test column name item int x;";
- String expected = "test\n column name\n\n\titem int x;";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model.trim());
- }
-
- /**
- * This test verifies that {@link com.avaloq.tools.ddk.xtext.formatter.formatterTestLanguage.Line} elements are aligned with the specified offset.
- *
- * @throws IOException
- */
- @Test
- public void offset() throws IOException {
- String model = "test offset value v pair p1 p2";
- String expected = "test\noffset\n\tvalue v\n\t\tpair p1 p2";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test verifies right padding does pad and that there is always minimum padding " ".
- *
- * @throws IOException
- */
- @Test
- public void rightPadding() throws IOException {
- String model = "test padding long_name n2;";
- String expected = "test\npadding long_name n2 ;";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void indentation() throws IOException {
- String model = "test indentation { float val; double y; indentation { int x; } }";
- String expected = "test indentation {\n float val;\n double y;\n indentation {\n int x;\n }\n}";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void association() throws IOException {
- String model = "test indentation { var = [0,1,2,3,4]; }";
- String expected = "test indentation {\n var=[ 0, 1, 2, 3, 4 ];\n}";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void indentationAndComments() throws IOException {
- String model = "test /* xxx */ indentation { float val; // some float\n double /* oo */ y; indentation { // some block\n int x; // xxx\n } } // final comment";
- String expected = "test /* xxx */ indentation {\n float val; // some float\n double /* oo */ y;\n indentation { // some block\n int x; // xxx\n }\n} // final comment";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- * It has been adapted to
- *
- * @throws IOException
- */
- @Test
- public void indentationAndLineWrap() throws IOException {
- String model = "test indentation { void func(x:int,y:int,s:javalangString, foo:javasqlDate, blupp:mylongtype, msads:adshdjkhsakdasdkslajdlsask, x:x, a:b, c:d ); }";
- String expected = "test indentation {\n void func(x:int,y:int,\n\t\ts:javalangString,\n\t\tfoo:javasqlDate,\n\t\tblupp:mylongtype,\n\t\tmsads:adshdjkhsakdasdkslajdlsask,\n\t\tx:x,a:b,c:d);\n}";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void between1() throws IOException {
- String model = "test indentation { indentation { x x; }; }";
- String expected = "test indentation {\n indentation {\n x x;\n };\n}";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void between2() throws IOException {
- String model = "test indentation { indentation { x x; } }";
- String expected = "test indentation {\n indentation {\n x x;\n }\n}";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void linewrapDatatypeRule() throws IOException {
- String model = "test linewrap fqn ab; fqn xx.yy.zz;";
- String expected = "test linewrap\nfqn\nab;\nfqn\nxx.yy.zz;";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void linewrapDatatypeRulePartial1() throws IOException {
- String model = "test linewrap fqn ab . xx .yy .zz;";
- String expected = "test linewrap fqn ab.xx.yy.zz;";
- assertFormattedNM(expected, model, 22, 2);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void linewrapDatatypeRulePartial2() throws IOException {
- String model = "test linewrap fqn ab . xx .yy .zz;fqn xxx;";
- String expected = "test linewrap fqn\nab.xx.yy.zz;fqn xxx;";
- assertFormattedNM(expected, model, 15, 10);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void linewrapDatatypeRulePartial3() throws IOException {
- String model = "test linewrap fqn ab . xx .yy .zz;fqn xxx;";
- String expected = "test linewrap fqn ab.xx.yy.zz;\nfqn xxx;";
- assertFormattedNM(expected, model, 25, 12);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void formatSegment1() throws IOException {
- String model = "test\nindentation {\n indentation { x x ; } }";
- String expected = "test\nindentation {\n indentation {\n x x;\n } }";
- assertFormattedNM(expected, model, 30, 18);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void formatSegment2() throws IOException {
- String model = "test indentation {\n indentation { x x ; } }";
- // String expected =
- // "test\nindentation {\n indentation {\n x x;\n } }";
- assertFormattedNM(model, model, 7, 10);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void formatSegment3() throws IOException {
- String model = " test indentation {\n indentation { x x ; } }";
- String expected = "test indentation {\n indentation {\n x x;\n }\n}";
- assertFormattedNM(expected, model, 0, model.length());
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void linewrapDatatypeRuleRef1() throws IOException {
- String model = "test linewrap fqn ab .cd .ef; fqnref ab. cd. ef;";
- String expected = "test linewrap\nfqn\nab.cd.ef;\nfqnref\nab.cd.ef;";
- // assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void linewrapDatatypeRuleRef2() throws IOException {
- String model = "test linewrap fqn ab.cd.ef; fqnref ab.cd.ef;";
- String expected = "test linewrap\nfqn\nab.cd.ef;\nfqnref\nab.cd.ef;";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest but it is modified
- * because I think the expected behavior in the original test is wrong.
- *
- * @throws IOException
- */
- @Test
- public void linewrapDatatypeRuleComments() throws IOException {
- String model = "test linewrap/* 1 */fqn/* 2 */ab.cd.ef/* 3 */;/* 4 */fqnref/* 5 */ab.cd.ef/* 6 */;/* 7 */";
- // The expected model string differs from Xtext's -
- // Xtext does not expect a line wrap after the keyword "linewrap"
- // Xtext does not expect a line wrap prior to fqnref assignment
- // etc...
- String expected = "test linewrap/* 1 */ fqn/* 2 */\nab.cd.ef/* 3 */;/* 4 */ fqnref\n/* 5 */ ab.cd.ef/* 6 */;/* 7 */";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void enumeration() throws IOException {
- String model = "test linewrap enum lit1,lit2,lit3,lit1;";
- String expected = "test linewrap\nenum lit1 ,\nlit2,\nlit3,\nlit1;";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=312559
- @Test
- public void suppressedWhitespace() throws IOException {
- String model = "test linewrap `f%%a` post;";
- String expected = "test linewrap\n`f%< b >%a` post;";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- // TODO: investigate whether to include test or not - currently this test
- // would fail
- @Disabled
- public void suppressedLinewrap() throws IOException {
- String model = "test linewrap\n`foo%abcd%foo%< b\n>%abcd%foo%abcd%foo%abcd%" + "foo%abcd%foo%abcd%foo%abcd%foo%abcd%foo%abcd%foo%xx%foo%abcd%foo%abcd%"
- + "foo%abcd%foo%<\nb >%foo%abcd` post;";
- assertFormattedPTC(model, model);
- assertFormattedNM(model, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void linewrapMin() throws IOException {
- String model = "test wrapminmax foo bar;";
- String expected = "test wrapminmax\n\nfoo bar;";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void linewrapMax() throws IOException {
- String model = "test wrapminmax\n\n\n\n\n\n\n\n\n\n\n\n\nfoo bar;";
- String expected = "test wrapminmax\n\n\n\n\nfoo bar;";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void linewrapKeep() throws IOException {
- String model = "test wrapminmax\n\n\n\nfoo bar;";
- assertFormattedPTC(model, model);
- assertFormattedNM(model, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void linewrapDefault() {
- FormatterTestLanguageFactory f = FormatterTestLanguageFactory.eINSTANCE;
- TestLinewrapMinMax m = f.createTestLinewrapMinMax();
- Decl d = f.createDecl();
- d.getType().add("xxx");
- d.getName().add("yyy");
- m.getItems().add(d);
- String actual = getSerializer().serialize(m, SaveOptions.newBuilder().format().getOptions());
- String expected = "test wrapminmax\n\n\nxxx yyy;";
- Assertions.assertEquals(expected, actual, "Default Linewrap");
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void space() throws IOException {
- String model = "test linewrap space foo;";
- String expected = "test linewrap\nspace foo;";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-
- /**
- * This test is copied from
- * org.eclipse.xtext.nodemodel.impl.formatter.FormatterTest.
- *
- * @throws IOException
- */
- @Test
- public void datatypeRules() throws IOException {
- String model = "test linewrap datatypes abc kw1 bcd def kw3;";
- String expected = "test linewrap\ndatatypes abc\nkw1\nbcd\ndef\nkw3;";
- assertFormattedPTC(expected, model);
- assertFormattedNM(expected, model, 0, model.length());
- assertPreserved(model);
- }
-}
diff --git a/com.avaloq.tools.ddk.xtext.test/src/com/avaloq/tools/ddk/xtext/formatter/util/FormatterTestUtil.java b/com.avaloq.tools.ddk.xtext.test/src/com/avaloq/tools/ddk/xtext/formatter/util/FormatterTestUtil.java
deleted file mode 100644
index 02b6937a8..000000000
--- a/com.avaloq.tools.ddk.xtext.test/src/com/avaloq/tools/ddk/xtext/formatter/util/FormatterTestUtil.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016 Avaloq Group AG 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:
- * Avaloq Group AG - initial API and implementation
- *******************************************************************************/
-package com.avaloq.tools.ddk.xtext.formatter.util;
-
-import com.avaloq.tools.ddk.xtext.formatter.FormatterTestLanguageStandaloneSetup;
-import com.avaloq.tools.ddk.xtext.test.AbstractXtextTestUtil;
-import com.google.inject.Injector;
-
-
-public final class FormatterTestUtil extends AbstractXtextTestUtil {
- private final Injector injector = new FormatterTestLanguageStandaloneSetup().createInjectorAndDoEMFRegistration();
-
- private FormatterTestUtil() {
- // private constructor
- }
-
- /**
- * The singleton instance.
- */
- private static final class InstanceHolder {
- // Initialize-on-demand holder pattern.
- private static final FormatterTestUtil INSTANCE = new FormatterTestUtil();
-
- static FormatterTestUtil get() {
- return INSTANCE;
- }
- }
-
- public static FormatterTestUtil getInstance() {
- return InstanceHolder.get();
- }
-
- @Override
- protected Injector getInjector() {
- return injector;
- }
-
-}