fixed tests

This commit is contained in:
Moritz Eysholdt 2016-06-17 18:27:50 +02:00
parent 3c45943ca2
commit a23adf2b3d
51 changed files with 1797 additions and 353 deletions

View file

@ -1 +1,2 @@
bin
!src/org/eclipse/xtext/build
!xtend-gen/org/eclipse/xtext/build

View file

@ -1,17 +1,52 @@
configurations {
mwe2 {
extendsFrom compile
}
}
repositories {
flatDir {
dirs 'lib'
}
}
dependencies {
compile project(':org.eclipse.xtext.testing')
compile project(':org.eclipse.xtext.xtext.generator')
compile project(':org.eclipse.xtext.xtext.wizard')
compile 'junit:junit:4.12'
compile "org.eclipse.emf:org.eclipse.emf.common:$versions.emfCommon"
compile "org.eclipse.emf:org.eclipse.emf.ecore.xmi:$versions.emfEcore"
compile name: 'simple'
// TODO eliminate all following dependencies
//compile ":org.eclipse.xtext.testlanguages"
compile project(':org.eclipse.xtext.testlanguages')
compile "org.eclipse.xtext:org.eclipse.xtext.junit4:$versions.xtext"
compile "org.eclipse.xtext:org.eclipse.xtext.generator:$versions.xtext"
//compile "org.eclipse.xtext:org.eclipse.xtext.junit4:$versions.xtext"
compile "org.eclipse.xpand:org.eclipse.xpand:$versions.xpand"
//XXX compile/mwe2 "org.eclipse.xtext:org.eclipse.xtext.generator:$versions.xtext"
//XXX mwe2 "org.eclipse.emf:org.eclipse.emf.mwe2.launch:$versions.emfMwe2"
//XXX mwe2 "org.eclipse.xtext:org.eclipse.xtext.xtext.generator:$versions.xtext"
//XXX mwe2 "org.eclipse.xtext:org.eclipse.xtext.ecore:$versions.xtext"
}
eclipse.classpath.plusConfigurations += [configurations.mwe2]
sourceSets.test.java {
srcDir 'src-gen2'
srcDir 'suites'
}
sourceSets {
test.resources {
srcDir 'src-gen2'
srcDir 'suites'
}
}
test {
exclude 'org.eclipse.xtext.serializer.contextFinderTest.NestedTypeRecursiveTest.class'
}

View file

@ -19,7 +19,6 @@ Workflow {
bean = StandaloneSetup {
ignoreBrokenProjectFiles = true
platformUri = "${runtimeProject}/.."
platformUri = "${runtimeProject}/../../plugins"
scanClassPath = true
uriMap = {
from = "platform:/plugin/org.eclipse.emf.ecore/model/Ecore.ecore"

View file

@ -20,7 +20,6 @@ Workflow {
bean = StandaloneSetup {
ignoreBrokenProjectFiles = true
platformUri = "${runtimeProject}/.."
platformUri = "${runtimeProject}/../../plugins"
scanClassPath = true
uriMap = {
from = "platform:/plugin/org.eclipse.emf.ecore/model/Ecore.ecore"

View file

@ -1,82 +0,0 @@
/*******************************************************************************
* Copyright (c) 2015 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext
import java.util.ArrayList
import org.eclipse.xtext.xtext.generator.XtextGeneratorLanguage
import org.eclipse.xtext.xtext.generator.ecore.EMFGeneratorFragment2
import org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2
import org.eclipse.xtext.xtext.generator.idea.IdeaPluginGenerator
import org.eclipse.xtext.xtext.generator.idea.parser.antlr.XtextAntlrIDEAGeneratorFragment
import org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
import org.eclipse.xtext.xtext.generator.resourceFactory.ResourceFactoryFragment2
import org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2
import org.eclipse.xtend.lib.annotations.Accessors
import org.eclipse.xtext.generator.parser.antlr.XtextAntlrGeneratorComparisonFragment
import org.eclipse.xtext.generator.parser.antlr.AntlrOptions
/**
* @author efftinge - Initial contribution and API
*/
@Accessors
class TestLanguage extends XtextGeneratorLanguage {
org.eclipse.xtext.xtext.generator.parser.antlr.AntlrOptions parserOptions = new org.eclipse.xtext.xtext.generator.parser.antlr.AntlrOptions() => [
classSplitting = true
]
def void setParserOptions(org.eclipse.xtext.xtext.generator.parser.antlr.AntlrOptions parserOptions) {
this.parserOptions = parserOptions
parserGenerator.options = parserOptions
ideaParser.options = parserOptions
}
GrammarAccessFragment2 grammarAccess = new GrammarAccessFragment2
SerializerFragment2 serializer = new SerializerFragment2 => [
generateStub = false
]
ResourceFactoryFragment2 resourceFactoryFragment = new ResourceFactoryFragment2
EMFGeneratorFragment2 emfGenerator = new EMFGeneratorFragment2
XtextAntlrGeneratorFragment2 parserGenerator = new XtextAntlrGeneratorFragment2 => [
debugGrammar = true
options = parserOptions
]
XtextAntlrIDEAGeneratorFragment ideaParser = new XtextAntlrIDEAGeneratorFragment => [
options = parserOptions
]
IdeaPluginGenerator ideaPlugin = new IdeaPluginGenerator
override protected getImplicitFragments() {
val result = new ArrayList(super.getImplicitFragments())
result += parserGenerator
val comparison = new XtextAntlrGeneratorComparisonFragment
comparison.setOptions(new AntlrOptions() => [
it.backtrack = parserGenerator.options.backtrack
it.backtrackLexer = parserGenerator.options.backtrackLexer
it.classSplitting = parserGenerator.options.classSplitting
it.casesPerSpecialStateSwitch = parserGenerator.options.casesPerSpecialStateSwitch.toString
it.fieldsPerClass = parserGenerator.options.fieldsPerClass.toString
it.ignoreCase = parserGenerator.options.ignoreCase
it.k = parserGenerator.options.k
it.memoize = parserGenerator.options.memoize
it.optimizeCodeQuality= parserGenerator.options.optimizeCodeQuality
it.skipUnusedRules = parserGenerator.options.skipUnusedRules
it.stripAllComments = parserGenerator.options.stripAllComments
]);
result += comparison
result += grammarAccess
result += emfGenerator
result += serializer
result += resourceFactoryFragment
result += ideaParser
result += ideaPlugin
return result
}
}

View file

@ -31,8 +31,4 @@ CompositeGeneratorFragment {
fragment = grammarAccess.GrammarAccessFragment auto-inject {}
fragment = ecore.EcoreGeneratorFragment auto-inject {}
fragment = serializer.SerializerFragment auto-inject {}
fragment = org.eclipse.xtext.idea.generator.parser.antlr.XtextAntlrIDEAGeneratorFragment auto-inject {
options = auto-inject {}
}
fragment = org.eclipse.xtext.idea.generator.IdeaPluginGenerator auto-inject {}
}

View file

@ -37,8 +37,4 @@ CompositeGeneratorFragment {
fragment = grammarAccess.GrammarAccessFragment auto-inject {}
fragment = ecore.EcoreGeneratorFragment auto-inject {}
fragment = serializer.SerializerFragment auto-inject {}
fragment = org.eclipse.xtext.idea.generator.parser.antlr.XtextAntlrIDEAGeneratorFragment auto-inject {
options = auto-inject {}
}
fragment = org.eclipse.xtext.idea.generator.IdeaPluginGenerator auto-inject {}
}

View file

@ -39,8 +39,4 @@ CompositeGeneratorFragment {
fragment = grammarAccess.GrammarAccessFragment auto-inject {}
fragment = ecore.EcoreGeneratorFragment auto-inject {}
fragment = parseTreeConstructor.ParseTreeConstructorFragment auto-inject {}
fragment = org.eclipse.xtext.idea.generator.parser.antlr.XtextAntlrIDEAGeneratorFragment auto-inject {
options = auto-inject {}
}
fragment = org.eclipse.xtext.idea.generator.IdeaPluginGenerator auto-inject {}
}

View file

@ -31,8 +31,4 @@ CompositeGeneratorFragment {
fragment = grammarAccess.GrammarAccessFragment auto-inject {}
fragment = ecore.EcoreGeneratorFragment auto-inject {}
fragment = parseTreeConstructor.ParseTreeConstructorFragment auto-inject {}
fragment = org.eclipse.xtext.idea.generator.parser.antlr.XtextAntlrIDEAGeneratorFragment auto-inject {
options = auto-inject {}
}
fragment = org.eclipse.xtext.idea.generator.IdeaPluginGenerator auto-inject {}
}

View file

@ -35,8 +35,4 @@ CompositeGeneratorFragment {
fragment = ecore.EcoreGeneratorFragment auto-inject {}
fragment = serializer.SerializerFragment auto-inject {}
fragment = builder.BuilderIntegrationFragment {}
fragment = org.eclipse.xtext.idea.generator.parser.antlr.XtextAntlrIDEAGeneratorFragment auto-inject {
options = auto-inject {}
}
fragment = org.eclipse.xtext.idea.generator.IdeaPluginGenerator auto-inject {}
}

View file

@ -12,6 +12,7 @@ import java.util.List;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EEnumLiteral;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.xml.namespace.XMLNamespacePackage;
import org.eclipse.xtext.EcoreUtil2;
import org.eclipse.xtext.EnumLiteralDeclaration;
import org.eclipse.xtext.EnumRule;
@ -32,6 +33,11 @@ public class GrammarParserTest extends AbstractEnumRulesTest {
with(XtextStandaloneSetup.class);
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
private void checkEnums(Grammar grammar) {
List<EnumLiteralDeclaration> decls = EcoreUtil2.getAllContentsOfType(grammar, EnumLiteralDeclaration.class);
for(EnumLiteralDeclaration decl: decls) {

View file

@ -1,102 +0,0 @@
/*******************************************************************************
* Copyright (c) 2011 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.generator.ecore;
import java.io.IOException;
import java.io.PrintStream;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.URIConverter;
import org.eclipse.emf.mwe.core.WorkflowContext;
import org.eclipse.emf.mwe.core.issues.Issues;
import org.eclipse.emf.mwe.core.lib.AbstractWorkflowComponent2;
import org.eclipse.emf.mwe.core.monitor.ProgressMonitor;
import org.eclipse.xtext.generator.GenModelAccess;
import org.eclipse.xtext.resource.XtextResourceSet;
/**
* @author Moritz Eysholdt - Initial contribution and API
*/
public class GenModelAccessTestGenerator extends AbstractWorkflowComponent2 {
@Override
protected void invokeInternal(WorkflowContext ctx, ProgressMonitor monitor, Issues issues) {
String java = "platform:/resource/org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/generator/ecore/genmodelaccess/root/AccessTest.java";
String ecore = "platform:/resource/org.eclipse.xtext.tests/src/org/eclipse/xtext/generator/ecore/GenModelAccessTest.ecore";
ResourceSet rs = new XtextResourceSet();
EPackage root = (EPackage) rs.getResource(URI.createURI(ecore), true).getContents().get(0);
try {
PrintStream print = new PrintStream(URIConverter.INSTANCE.createOutputStream(URI.createURI(java)));
print.println("package org.eclipse.xtext.generator.ecore.genmodelaccess.root;");
print.println();
print.println("import org.eclipse.xtext.generator.ecore.genmodelaccess.nestedPackage1.NestedPackage1Package;");
print.println("import org.eclipse.xtext.generator.ecore.genmodelaccess.noLiterals.NoLiteralsPackage;");
print.println("import org.junit.Assert;");
print.println("import org.junit.Test;");
print.println();
print.println("public abstract class AccessTest extends Assert {");
EClass rootClass = (EClass) root.getEClassifier("RootClass");
EReference rootRef = (EReference) rootClass.getEStructuralFeature("reference1");
EAttribute rootAttr = (EAttribute) rootClass.getEStructuralFeature("attribute1");
EDataType rootDataType = (EDataType) root.getEClassifier("RootDataType");
EEnum rootEnum = (EEnum) root.getEClassifier("RootEnum");
print.println(" @Test public void testRootPackage() {");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(root, rs) + ");");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(rootClass, rs) + ");");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(rootDataType, rs) + ");");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(rootEnum, rs) + ");");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(rootAttr, rs) + ");");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(rootRef, rs) + ");");
print.println(" Assert.assertEquals(0," + GenModelAccess.getGenIntLiteral(rootClass, rs) + ");");
print.println(" Assert.assertEquals(2," + GenModelAccess.getGenIntLiteral(rootDataType, rs) + ");");
print.println(" Assert.assertEquals(1," + GenModelAccess.getGenIntLiteral(rootEnum, rs) + ");");
print.println(" Assert.assertEquals(0," + GenModelAccess.getGenIntLiteral(rootClass, rootAttr, rs) + ");");
print.println(" Assert.assertEquals(1," + GenModelAccess.getGenIntLiteral(rootClass, rootRef, rs) + ");");
print.println(" }\n");
EPackage nested = root.getESubpackages().get(0);
EClass nestedClass = (EClass) nested.getEClassifier("NestedClass1");
print.println(" @Test public void testNestedPackage() {");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(nested, rs) + ");");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(nestedClass, rs) + ");");
print.println(" Assert.assertEquals(0," + GenModelAccess.getGenIntLiteral(nestedClass, rs) + ");");
print.println(" }\n");
EPackage noLit = root.getESubpackages().get(1);
EClass noLitClass = (EClass) noLit.getEClassifier("NoLitClass");
EDataType noLitDataType = (EDataType) noLit.getEClassifier("NoLitDataType");
EReference noLitRef = (EReference) noLitClass.getEStructuralFeature("reference2");
EAttribute noLitAttr = (EAttribute) noLitClass.getEStructuralFeature("attribute2");
EDataType noLitEnum = (EDataType) noLit.getEClassifier("NoLitEnum");
print.println(" @Test public void testNoLiteralPackage() {");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(noLit, rs) + ");");
print.println(" Assert.assertFalse(" + GenModelAccess.getGenPackage(noLit, rs).isLiteralsInterface()
+ ");");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(noLitClass, rs) + ");");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(noLitDataType, rs) + ");");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(noLitAttr, rs) + ");");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(noLitRef, rs) + ");");
print.println(" Assert.assertNotNull(" + GenModelAccess.getGenTypeLiteral(noLitEnum, rs) + ");");
print.println(" }");
print.println("}");
print.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View file

@ -0,0 +1,310 @@
/**
* Copyright (c) 2015 itemis AG (http://www.itemis.eu) 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
*/
package org.eclipse.xtext.generator.parser;
import com.google.common.base.Objects;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.xtend.lib.annotations.Accessors;
import org.eclipse.xtend2.lib.StringConcatenation;
import org.eclipse.xtext.xbase.lib.CollectionLiterals;
import org.eclipse.xtext.xbase.lib.Functions.Function0;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.eclipse.xtext.xbase.lib.Pair;
import org.eclipse.xtext.xbase.lib.Pure;
/**
* Compares two charSequences of ANTLR grammars token by token.
* Ignores differences in white space, and counts line breaks for usable error diagnosis.
*
* @author Christian Schneider - Initial contribution and API
* @noreference
*/
@SuppressWarnings("all")
public class AntlrGrammarComparator {
public interface IErrorHandler {
public abstract void handleInvalidGeneratedGrammarFile(final AntlrGrammarComparator.ErrorContext context);
public abstract void handleInvalidReferenceGrammarFile(final AntlrGrammarComparator.ErrorContext context);
public abstract void handleMismatch(final String matched, final String expected, final AntlrGrammarComparator.ErrorContext context);
}
public static final class ErrorContext {
@Accessors
private AntlrGrammarComparator.MatchState testedGrammar = new AntlrGrammarComparator.MatchState();
@Accessors
private AntlrGrammarComparator.MatchState referenceGrammar = new AntlrGrammarComparator.MatchState();
public AntlrGrammarComparator.MatchState reset() {
AntlrGrammarComparator.MatchState _xblockexpression = null;
{
AntlrGrammarComparator.MatchState _matchState = new AntlrGrammarComparator.MatchState();
this.testedGrammar = _matchState;
AntlrGrammarComparator.MatchState _matchState_1 = new AntlrGrammarComparator.MatchState();
_xblockexpression = this.referenceGrammar = _matchState_1;
}
return _xblockexpression;
}
@Pure
public AntlrGrammarComparator.MatchState getTestedGrammar() {
return this.testedGrammar;
}
public void setTestedGrammar(final AntlrGrammarComparator.MatchState testedGrammar) {
this.testedGrammar = testedGrammar;
}
@Pure
public AntlrGrammarComparator.MatchState getReferenceGrammar() {
return this.referenceGrammar;
}
public void setReferenceGrammar(final AntlrGrammarComparator.MatchState referenceGrammar) {
this.referenceGrammar = referenceGrammar;
}
}
public static final class MatchState {
@Accessors
private String absoluteFileName;
@Accessors
private int lineNumber = 1;
private int position = 0;
@Accessors
private String previousToken;
@Accessors
private String currentToken;
@Pure
public String getAbsoluteFileName() {
return this.absoluteFileName;
}
public void setAbsoluteFileName(final String absoluteFileName) {
this.absoluteFileName = absoluteFileName;
}
@Pure
public int getLineNumber() {
return this.lineNumber;
}
public void setLineNumber(final int lineNumber) {
this.lineNumber = lineNumber;
}
@Pure
public String getPreviousToken() {
return this.previousToken;
}
public void setPreviousToken(final String previousToken) {
this.previousToken = previousToken;
}
@Pure
public String getCurrentToken() {
return this.currentToken;
}
public void setCurrentToken(final String currentToken) {
this.currentToken = currentToken;
}
}
private final static List<String> SINGLE_CHAR_TOKENS = Collections.<String>unmodifiableList(CollectionLiterals.<String>newArrayList("\\(", "\\)", "\\[", "\\]", "\\{", "\\}", "\\|", "=", "\\?", "\\*", "\\+", ":", ";"));
private final static String QUOTED_TOKENS = IterableExtensions.join(Collections.<String>unmodifiableList(CollectionLiterals.<String>newArrayList("\'(\\\\\')+\'", "(\'[^\']*\')", "(\"[^\"]*\")")), "|");
private final static String TOKEN = new Function0<String>() {
public String apply() {
StringConcatenation _builder = new StringConcatenation();
String _join = IterableExtensions.join(AntlrGrammarComparator.SINGLE_CHAR_TOKENS, "|");
_builder.append(_join, "");
_builder.append("|");
_builder.append(AntlrGrammarComparator.QUOTED_TOKENS, "");
_builder.append("|[^\\s\'\"");
String _join_1 = IterableExtensions.join(AntlrGrammarComparator.SINGLE_CHAR_TOKENS);
_builder.append(_join_1, "");
_builder.append("]+");
return _builder.toString();
}
}.apply();
private final static String NEWLINE = "\\r?\\n|\\r";
private final static String WS = "( |\\t)+";
private final static String SL_COMMENT = "//[^\\r\\n]*";
private final static String ML_COMMENT = new Function0<String>() {
public String apply() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("/\\*(\\*[^/]|[^\\*])*\\*/");
return _builder.toString();
}
}.apply();
private final Pattern p_slComment = Pattern.compile(AntlrGrammarComparator.SL_COMMENT);
private final Pattern p_mlComment = Pattern.compile(AntlrGrammarComparator.ML_COMMENT);
private final Pattern p_token = Pattern.compile(AntlrGrammarComparator.TOKEN);
private final Pattern p_newline = Pattern.compile(AntlrGrammarComparator.NEWLINE);
private final Pattern p_ws = Pattern.compile(AntlrGrammarComparator.WS);
private final Pattern compoundPattern = new Function0<Pattern>() {
public Pattern apply() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("(");
_builder.append(AntlrGrammarComparator.SL_COMMENT, "");
_builder.append(")|(");
_builder.append(AntlrGrammarComparator.ML_COMMENT, "");
_builder.append(")|(");
_builder.append(AntlrGrammarComparator.TOKEN, "");
_builder.append(")|(");
_builder.append(AntlrGrammarComparator.NEWLINE, "");
_builder.append(")|(");
_builder.append(AntlrGrammarComparator.WS, "");
_builder.append(")");
Pattern _compile = Pattern.compile(_builder.toString(), Pattern.MULTILINE);
return _compile;
}
}.apply();
private AntlrGrammarComparator.ErrorContext errorContext;
/**
* Performs the actual comparison of given and expected grammar.
*
* @return {@link Pair} containing the number of lines of the tested grammar (key)
* and the referenced grammar (value) for logging purposes
*/
public AntlrGrammarComparator.ErrorContext compareGrammars(final CharSequence grammar, final CharSequence grammarReference, final String absoluteGrammarFileName, final String absoluteGrammarFileNameReference, final AntlrGrammarComparator.IErrorHandler errorHandler) {
AntlrGrammarComparator.ErrorContext _errorContext = new AntlrGrammarComparator.ErrorContext();
this.errorContext = _errorContext;
this.errorContext.testedGrammar.absoluteFileName = absoluteGrammarFileName;
this.errorContext.referenceGrammar.absoluteFileName = absoluteGrammarFileNameReference;
return this.compareGrammars(grammar, grammarReference, errorHandler);
}
/**
* Performs the actual comparison of given and expected grammar.
*
* @return {@link Pair} containing the number of lines of the tested grammar (key)
* and the referenced grammar (value) for logging purposes
*/
public AntlrGrammarComparator.ErrorContext compareGrammars(final CharSequence grammar, final CharSequence grammarReference, final AntlrGrammarComparator.IErrorHandler errorHandler) {
boolean _equals = Objects.equal(this.errorContext, null);
if (_equals) {
AntlrGrammarComparator.ErrorContext _errorContext = new AntlrGrammarComparator.ErrorContext();
this.errorContext = _errorContext;
}
final Matcher compoundMatcher = this.compoundPattern.matcher(grammar);
final Matcher compoundMatcherReference = this.compoundPattern.matcher(grammarReference);
boolean continue_ = true;
boolean continueReference = true;
while ((continue_ || continueReference)) {
{
if (continue_) {
boolean _nextToken = this.nextToken(compoundMatcher, this.errorContext.testedGrammar, errorHandler);
continue_ = _nextToken;
}
String _xifexpression = null;
if (continue_) {
_xifexpression = compoundMatcher.group();
} else {
_xifexpression = "««eof»»";
}
final String match = _xifexpression;
if (continueReference) {
boolean _nextToken_1 = this.nextToken(compoundMatcherReference, this.errorContext.referenceGrammar, errorHandler);
continueReference = _nextToken_1;
}
String _xifexpression_1 = null;
if (continueReference) {
_xifexpression_1 = compoundMatcherReference.group();
} else {
_xifexpression_1 = "««eof»»";
}
final String matchReference = _xifexpression_1;
boolean _notEquals = (!Objects.equal(matchReference, match));
if (_notEquals) {
errorHandler.handleMismatch(match, matchReference, this.errorContext);
}
}
}
return this.errorContext;
}
/**
* continue matching until the next token is found, count newlines while doing so.
*
* @return the number of newlines passed while searching
*/
private boolean nextToken(final Matcher matcher, final AntlrGrammarComparator.MatchState state, final AntlrGrammarComparator.IErrorHandler errorHandler) {
while (matcher.find()) {
{
String _group = matcher.group();
state.currentToken = _group;
int _start = matcher.start();
boolean _notEquals = (_start != state.position);
if (_notEquals) {
this.handleInvalidGrammarFile(errorHandler, state);
}
final String match = matcher.group();
state.previousToken = match;
int _end = matcher.end();
state.position = _end;
Matcher _matcher = this.p_newline.matcher(match);
boolean _matches = _matcher.matches();
if (_matches) {
state.lineNumber++;
} else {
if ((this.p_slComment.matcher(match).matches() || this.p_ws.matcher(match).matches())) {
} else {
Matcher _matcher_1 = this.p_mlComment.matcher(match);
boolean _matches_1 = _matcher_1.matches();
if (_matches_1) {
final Matcher newlines = this.p_newline.matcher(match);
while (newlines.find()) {
state.lineNumber++;
}
} else {
Matcher _matcher_2 = this.p_token.matcher(match);
boolean _matches_2 = _matcher_2.matches();
if (_matches_2) {
return true;
}
}
}
}
}
}
return false;
}
private void handleInvalidGrammarFile(final AntlrGrammarComparator.IErrorHandler errorHandler, final AntlrGrammarComparator.MatchState state) {
if ((state == this.errorContext.testedGrammar)) {
errorHandler.handleInvalidGeneratedGrammarFile(this.errorContext);
} else {
errorHandler.handleInvalidReferenceGrammarFile(this.errorContext);
}
}
}

View file

@ -7,8 +7,11 @@
*******************************************************************************/
package org.eclipse.xtext.grammarinheritance;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.xtext.grammarinheritance.ametamodel.AmetamodelPackage;
import org.eclipse.xtext.grammarinheritance.foo.FooPackage;
import org.eclipse.xtext.grammarinheritance.services.AbstractTestLanguageGrammarAccess;
import org.eclipse.xtext.junit4.AbstractXtextTests;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.junit.Test;
/**
@ -19,6 +22,7 @@ public class InheritanceGrammarAccessTest extends AbstractXtextTests {
@Override
public void setUp() throws Exception {
super.setUp();
EPackage.Registry.INSTANCE.put(AmetamodelPackage.eNS_URI, AmetamodelPackage.eINSTANCE);
with(new ConcreteTestLanguageStandaloneSetup());
}

View file

@ -10,13 +10,14 @@ package org.eclipse.xtext.linking.lazy;
import org.apache.log4j.Level;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.xtext.junit4.AbstractXtextTests;
import org.eclipse.xtext.junit4.logging.LoggingTester;
import org.eclipse.xtext.junit4.logging.LoggingTester.LogCapture;
import org.eclipse.xtext.XtextStandaloneSetup;
import org.eclipse.xtext.linking.lazy.lazyLinking.Model;
import org.eclipse.xtext.linking.lazy.lazyLinking.Type;
import org.eclipse.xtext.scoping.IScope;
import org.eclipse.xtext.scoping.IScopeProvider;
import org.eclipse.xtext.testing.logging.LoggingTester;
import org.eclipse.xtext.testing.logging.LoggingTester.LogCapture;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.junit.Test;
@ -35,6 +36,7 @@ public class Bug281990Test extends AbstractXtextTests {
@Override
public void setUp() throws Exception {
super.setUp();
XtextStandaloneSetup.doSetup();
with(new LazyLinkingTestLanguageRuntimeModule() {
@Override
public Class<? extends IScopeProvider> bindIScopeProvider() {

View file

@ -25,8 +25,8 @@ import org.eclipse.emf.mwe.core.monitor.ProgressMonitor;
import org.eclipse.xtext.index.IndexTestLanguageStandaloneSetup;
import org.eclipse.xtext.index.indexTestLanguage.Entity;
import org.eclipse.xtext.index.indexTestLanguage.IndexTestLanguagePackage;
import org.eclipse.xtext.junit4.AbstractXtextTests;
import org.eclipse.xtext.junit4.logging.LoggingTester;
import org.eclipse.xtext.testing.logging.LoggingTester;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.junit.Test;
/**
@ -199,13 +199,14 @@ public abstract class AbstractReaderTest extends AbstractXtextTests {
}
public String pathTo(String string) throws Exception {
URL resource = getClass().getClassLoader().getResource(getClass().getName().replace('.', '/') + ".class");
URI fileURI = URI.createURI(resource.toString());
// URL resource = getClass().getClassLoader().getResource();
File base = new File("./src/"+getClass().getName().replace('.', '/') + ".java");
URI fileURI = URI.createFileURI(base.getAbsolutePath());
System.out.println(fileURI);
// this is a hack used in order to get a file URI for a bundleresource:/ URL
File f = (File) get(resource,"handler.bundleEntry.file");
if (f!=null)
fileURI = URI.createFileURI(f.getAbsolutePath());
// File f = (File) get(resource,"handler.bundleEntry.file");
// if (f!=null)
// fileURI = URI.createFileURI(f.getAbsolutePath());
URI fileURI2 = URI.createURI(string);
return fileURI2.resolve(fileURI).toFileString();

View file

@ -12,6 +12,7 @@ import java.util.List;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.xml.namespace.XMLNamespacePackage;
import org.eclipse.emf.mwe.core.WorkflowContext;
import org.eclipse.emf.mwe.core.WorkflowContextDefaultImpl;
import org.eclipse.emf.mwe.core.issues.IssuesImpl;
@ -20,11 +21,12 @@ import org.eclipse.xtext.Constants;
import org.eclipse.xtext.Grammar;
import org.eclipse.xtext.XtextPackage;
import org.eclipse.xtext.XtextStandaloneSetup;
import org.eclipse.xtext.junit4.AbstractXtextTests;
import org.eclipse.xtext.linking.ImportUriTestLanguageStandaloneSetup;
import org.eclipse.xtext.linking.importedURI.Type;
import org.eclipse.xtext.resource.IResourceFactory;
import org.eclipse.xtext.resource.IResourceServiceProvider;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.junit.Before;
import org.junit.Test;
import com.google.inject.Binder;
@ -36,6 +38,12 @@ import com.google.inject.name.Names;
* @author Sven Efftinge - Initial contribution and API
*/
public class UriBasedReaderTest extends AbstractXtextTests {
@Override
@Before
public void setUp() throws Exception {
super.setUp();
}
/**
* @author Sebastian Zarnekow - Initial contribution and API

View file

@ -17,7 +17,9 @@ import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.xtext.junit4.AbstractXtextTests;
import org.eclipse.emf.ecore.xml.namespace.XMLNamespacePackage;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -33,6 +35,12 @@ public class ClassloaderClasspathUriResolverTest extends AbstractXtextTests {
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
"ecore", new XMIResourceFactoryImpl());
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
}
@Test public void testClasspathUriForFile() {
URI classpathUri = URI
@ -73,6 +81,7 @@ public class ClassloaderClasspathUriResolverTest extends AbstractXtextTests {
URI normalizedUri = _resolver.resolve(getClass().getClassLoader(), classpathUri);
assertEquals(expectedUri, normalizedUri.toString());
ResourceSet resourceSet = new ResourceSetImpl();
System.out.println(normalizedUri);
Resource resource = resourceSet.getResource(normalizedUri, true);
assertNotNull("Classpth URI ot registered", resource);
assertTrue("Resource not loaded", resource.isLoaded());
@ -86,4 +95,5 @@ public class ClassloaderClasspathUriResolverTest extends AbstractXtextTests {
URI uri = resolver.findResourceOnClasspath(loader, URI.createURI("classpath:/pack/ClassLoaderClasspathUriResolverTest.txt"));
assertNotNull(uri);
}
}

View file

@ -25,8 +25,11 @@ import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceImpl;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xml.type.XMLTypePackage;
import org.eclipse.emf.mwe.utils.StandaloneSetup;
import org.eclipse.xtext.junit4.TemporaryFolder;
import org.eclipse.xtext.testing.GlobalRegistries;
import org.eclipse.xtext.testing.GlobalRegistries.GlobalStateMemento;
import org.eclipse.xtext.tests.TemporaryFolder;
import org.eclipse.xtext.util.concurrent.AbstractReadWriteAcces;
import org.eclipse.xtext.util.concurrent.IReadAccess;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;
@ -49,12 +52,16 @@ public class ConcurrentAccessTest extends Assert {
private Resource resource;
private GlobalStateMemento globalStateMemento;
static {
new StandaloneSetup();
}
@Before
public void setUp() throws Exception {
globalStateMemento = GlobalRegistries.makeCopyOfGlobalState();
EPackage.Registry.INSTANCE.put(XMLTypePackage.eNS_URI, XMLTypePackage.eINSTANCE);
ResourceSet resourceSet = new ResourceSetImpl();
resource = new XtextResource(URI.createFileURI("something.ecore"));
resourceSet.getResources().add(resource);
@ -89,6 +96,7 @@ public class ConcurrentAccessTest extends Assert {
@After
public void tearDown() throws Exception {
resource = null;
globalStateMemento.restoreGlobalState();
}
@Test public void testDummy() {

View file

@ -7,6 +7,7 @@
*******************************************************************************/
package org.eclipse.xtext.resource
import java.io.File
import java.io.IOException
import java.util.Map
import org.eclipse.emf.common.util.URI
@ -56,7 +57,7 @@ abstract class AbstractXtextResourceSetTest extends AbstractResourceSetTest {
assertEquals(0, rs.URIResourceMap.size)
val resource = new XtextResource
resource.URI = URI::createURI('foo')
resource.URI = URI::createFileURI(new File('foo').absolutePath)
rs.resources += resource
@ -75,7 +76,7 @@ abstract class AbstractXtextResourceSetTest extends AbstractResourceSetTest {
assertEquals(0, rs.URIResourceMap.size)
val resource = new XtextResource
resource.URI = URI::createURI('foo')
resource.URI = URI::createFileURI(new File('foo').absolutePath)
rs.resources += newArrayList(resource)
@ -100,14 +101,14 @@ abstract class AbstractXtextResourceSetTest extends AbstractResourceSetTest {
assertEquals(resource, rs.URIResourceMap.get(null))
// set the URI
resource.URI = URI::createURI('foo')
resource.URI = URI::createFileURI(new File('foo').absolutePath)
assertEquals(1, rs.URIResourceMap.size)
assertFalse(rs.URIResourceMap.containsKey(null))
assertEquals(resource, rs.URIResourceMap.get(resource.URI))
assertEquals(resource, rs.URIResourceMap.get(rs.URIConverter.normalize(resource.URI)))
// set the URI
resource.URI = URI::createURI('bar')
resource.URI = URI::createFileURI(new File('bar').absolutePath)
assertEquals(1, rs.URIResourceMap.size)
assertFalse(rs.URIResourceMap.containsKey(null))
assertEquals(resource, rs.URIResourceMap.get(resource.URI))
@ -132,10 +133,9 @@ abstract class AbstractXtextResourceSetTest extends AbstractResourceSetTest {
assertEquals(0, rs.URIResourceMap.size)
val resource = new XtextResource
resource.URI = URI::createURI('foo')
resource.URI = URI::createFileURI(new File('foo').absolutePath)
rs.resources += newArrayList(resource)
assertEquals(1, rs.URIResourceMap.size)
rs.resources.clear
@ -151,7 +151,7 @@ abstract class AbstractXtextResourceSetTest extends AbstractResourceSetTest {
assertEquals(0, rs.URIResourceMap.size)
val resource = new XtextResource
resource.URI = URI::createURI('foo')
resource.URI = URI::createFileURI(new File('foo').absolutePath)
rs.resources += newArrayList(resource)

View file

@ -17,10 +17,15 @@ import java.io.StringWriter;
import java.util.Collections;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.xmi.XMIResource;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
import org.eclipse.emf.ecore.xml.type.XMLTypePackage;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.testing.GlobalRegistries;
import org.eclipse.xtext.testing.GlobalRegistries.GlobalStateMemento;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -55,9 +60,17 @@ public class SrcSegmentsInUrisAreNotRemovedTests {
+ " </eStructuralFeatures>\n" + " </eClassifiers>\n"
+ "</ecore:EPackage>";
private GlobalStateMemento globalStateMemento;
@After
public void tearDown() {
globalStateMemento.restoreGlobalState();
}
@Before
public void setUp() throws Exception {
globalStateMemento = GlobalRegistries.makeCopyOfGlobalState();
EPackage.Registry.INSTANCE.put(XMLTypePackage.eNS_URI, XMLTypePackage.eINSTANCE);
EcoreResourceFactoryImpl resFactory = new EcoreResourceFactoryImpl();
set.getResourceFactoryRegistry().getExtensionToFactoryMap()
.put("ecore", resFactory);

View file

@ -1,62 +0,0 @@
/*******************************************************************************
* Copyright (c) 2013 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.resource.uriHell;
import org.eclipse.xtext.ecore.EcoreRuntimeModule;
import org.eclipse.xtext.junit4.GlobalRegistries;
import org.eclipse.xtext.junit4.GlobalRegistries.GlobalStateMemento;
import org.eclipse.xtext.junit4.IInjectorProvider;
import org.eclipse.xtext.junit4.IRegistryConfigurator;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
public class URIHandlerTestInjectorProvider implements IInjectorProvider, IRegistryConfigurator {
protected GlobalStateMemento stateBeforeInjectorCreation;
protected GlobalStateMemento stateAfterInjectorCreation;
protected Injector injector;
static {
GlobalRegistries.initializeDefaults();
}
@Override
public Injector getInjector()
{
if (injector == null) {
stateBeforeInjectorCreation = GlobalRegistries.makeCopyOfGlobalState();
this.injector = internalCreateInjector();
stateAfterInjectorCreation = GlobalRegistries.makeCopyOfGlobalState();
}
return injector;
}
protected Injector internalCreateInjector() {
return Guice.createInjector(new EcoreRuntimeModule() {
@SuppressWarnings("unused")
public ClassLoader bindClassLoader() {
return URIHandlerTestInjectorProvider.class.getClassLoader();
}
});
}
@Override
public void restoreRegistry() {
stateBeforeInjectorCreation.restoreGlobalState();
}
@Override
public void setupRegistry() {
getInjector();
stateAfterInjectorCreation.restoreGlobalState();
}
}

View file

@ -7,14 +7,16 @@
*******************************************************************************/
package org.eclipse.xtext.scoping.impl;
import java.io.File;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.junit4.AbstractXtextTests;
import org.eclipse.xtext.linking.LangATestLanguageStandaloneSetup;
import org.eclipse.xtext.linking.langATestLanguage.LangATestLanguagePackage;
import org.eclipse.xtext.naming.QualifiedName;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.scoping.IScope;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.eclipse.xtext.util.StringInputStream;
import org.junit.Test;
@ -33,8 +35,8 @@ public class Bug318343Test extends AbstractXtextTests {
with(LangATestLanguageStandaloneSetup.class);
globalScopeProvider = get(DefaultGlobalScopeProvider.class);
XtextResourceSet xtextResourceSet = get(XtextResourceSet.class);
resource1 = xtextResourceSet.createResource(URI.createURI("uri1.langatestlanguage"));
resource2 = xtextResourceSet.createResource(URI.createURI("uri2.langatestlanguage"));
resource1 = xtextResourceSet.createResource(URI.createFileURI(new File("uri1.langatestlanguage").getAbsolutePath()));
resource2 = xtextResourceSet.createResource(URI.createFileURI(new File("uri2.langatestlanguage").getAbsolutePath()));
resource1.load(new StringInputStream("type t1"),null);
resource2.load(new StringInputStream("type t2"),null);
}

View file

@ -18,11 +18,11 @@ import org.eclipse.xtext.XtextStandaloneSetup;
import org.eclipse.xtext.common.services.TerminalsGrammarAccess;
import org.eclipse.xtext.grammarinheritance.services.BaseInheritanceTestLanguageGrammarAccess;
import org.eclipse.xtext.grammarinheritance.services.InheritanceTestLanguageGrammarAccess;
import org.eclipse.xtext.junit4.AbstractXtextTests;
import org.eclipse.xtext.junit4.serializer.SerializerTester;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.service.GrammarProvider;
import org.eclipse.xtext.services.XtextGrammarAccess;
import org.eclipse.xtext.testing.serializer.SerializerTestHelper;
import org.eclipse.xtext.tests.AbstractXtextTests;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
@ -35,7 +35,7 @@ import com.google.inject.Provider;
*/
public class XtextSerializerTest extends AbstractXtextTests {
@Inject
private SerializerTester tester;
private SerializerTestHelper tester;
private Grammar load(URI uri) {
XtextResourceSet rs = new XtextResourceSet();

View file

@ -0,0 +1,154 @@
/*******************************************************************************
* Copyright (c) 2015 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.tests;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
import org.eclipse.emf.codegen.ecore.genmodel.GenModelPackage;
import org.eclipse.emf.codegen.ecore.genmodel.GenPackage;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
import org.eclipse.emf.ecore.xmi.impl.URIHandlerImpl;
import org.eclipse.emf.ecore.xml.type.XMLTypePackage;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.testing.GlobalRegistries;
import org.eclipse.xtext.testing.GlobalRegistries.GlobalStateMemento;
import org.eclipse.xtext.util.EmfFormatter;
import org.eclipse.xtext.xbase.lib.Functions;
import org.eclipse.xtext.xbase.lib.ListExtensions;
import org.junit.After;
import org.junit.Before;
import org.junit.ComparisonFailure;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
public abstract class AbstractPortableURIsTest extends URIHandlerImpl.PlatformSchemeAware {
static {
GlobalRegistries.initializeDefaults();
}
private ResourceSet resourceSet;
private GlobalStateMemento globalStateMemento;
@Before
public void setUp() throws Exception {
globalStateMemento = GlobalRegistries.makeCopyOfGlobalState();
EPackage.Registry.INSTANCE.put(XMLTypePackage.eNS_URI, XMLTypePackage.eINSTANCE);
resourceSet = new XtextResourceSet();
resourceSet.getPackageRegistry().put(EcorePackage.eNS_URI, EcorePackage.eINSTANCE);
resourceSet.getPackageRegistry().put(GenModelPackage.eNS_URI, GenModelPackage.eINSTANCE);
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("genmodel", new EcoreResourceFactoryImpl());
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore", new EcoreResourceFactoryImpl());
resourceSet.getURIConverter().getURIMap().put(URI.createPlatformPluginURI("org.eclipse.xtext/", false), URI.createURI("classpath:/"));
resourceSet.getURIConverter().getURIMap().put(URI.createPlatformResourceURI("org.eclipse.emf.ecore/", false), URI.createURI("classpath:/"));
resourceSet.getLoadOptions().put(XMLResource.OPTION_URI_HANDLER, this);
}
@After
public void tearDown() {
globalStateMemento.restoreGlobalState();
resourceSet = null;
}
@Override
public URI resolve(URI uri) {
assertPortableURI(uri);
return super.resolve(uri);
}
protected void doTestResource(String platformPath, String... packageNames) {
Resource resource = resourceSet.getResource(URI.createPlatformPluginURI(platformPath, false), true);
assertNotNull(resource);
assertEquals(1, resource.getContents().size());
EObject obj = resource.getContents().get(0);
if (obj instanceof EPackage) {
assertEquals(packageNames[0], ((EPackage) obj).getName());
} else if (obj instanceof GenModel) {
GenModel model = (GenModel) obj;
List<GenPackage> packages = Lists.newArrayList(model.getGenPackages());
assertEquals(packageNames.length, packages.size());
ListExtensions.sortInplaceBy(packages, new Functions.Function1<GenPackage, String>() {
@Override
public String apply(GenPackage p) {
return p.getEcorePackage().getName();
}
});
List<String> packageNamesList = Arrays.asList(packageNames);
Collections.sort(packageNamesList);
for(int i = 0; i < packageNamesList.size(); i++) {
assertEquals(packageNamesList.get(i), packages.get(i).getEcorePackage().getName());
}
IStatus status = model.validate();
assertTrue(printLeafs(status), status.isOK());
EObject orig = EcoreUtil.copy(obj);
((GenModel) obj).reconcile();
if (!EcoreUtil.equals(orig, obj)) {
Predicate<EStructuralFeature> ignoreContainer = new Predicate<EStructuralFeature>() {
@Override
public boolean apply(EStructuralFeature f) {
if (f instanceof EReference) {
EReference casted = (EReference) f;
return !casted.isContainment();
}
return false;
}
};
String origAsString = EmfFormatter.objToStr(orig, ignoreContainer);
String newAsString = EmfFormatter.objToStr(obj, ignoreContainer);
throw new ComparisonFailure("Reconcile changed model", origAsString, newAsString);
}
} else {
fail("Unexpected root element type: " + obj.eClass().getName());
}
}
protected String printLeafs(IStatus status) {
StringBuilder result = new StringBuilder();
appendLeafs(status, result);
return result.toString();
}
protected void appendLeafs(IStatus status, StringBuilder result) {
if (status.isOK()) {
return;
}
result.append(status.getMessage()).append('\n');
IStatus[] children = status.getChildren();
for(IStatus child: children) {
appendLeafs(child, result);
}
}
protected void assertPortableURI(URI uri) {
if (uri.isRelative()) {
String path = uri.path();
assertFalse(uri.toString() + " is not portable", path.startsWith(".."));
}
}
}

View file

@ -0,0 +1,387 @@
/*******************************************************************************
* Copyright (c) 2008-2010 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.tests;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource.Diagnostic;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xml.namespace.XMLNamespacePackage;
import org.eclipse.emf.ecore.xml.type.XMLTypePackage;
import org.eclipse.xtext.Constants;
import org.eclipse.xtext.IGrammarAccess;
import org.eclipse.xtext.ISetup;
import org.eclipse.xtext.conversion.IValueConverterService;
import org.eclipse.xtext.diagnostics.ExceptionDiagnostic;
import org.eclipse.xtext.formatting.INodeModelFormatter;
import org.eclipse.xtext.linking.ILinkingService;
import org.eclipse.xtext.linking.lazy.LazyLinkingResource;
import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.impl.InvariantChecker;
import org.eclipse.xtext.parser.IAstFactory;
import org.eclipse.xtext.parser.IParseResult;
import org.eclipse.xtext.parser.IParser;
import org.eclipse.xtext.parsetree.reconstr.IParseTreeConstructor;
import org.eclipse.xtext.resource.IResourceFactory;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.scoping.IScopeProvider;
import org.eclipse.xtext.serializer.ISerializer;
import org.eclipse.xtext.testing.GlobalRegistries;
import org.eclipse.xtext.testing.GlobalRegistries.GlobalStateMemento;
import org.eclipse.xtext.testing.serializer.SerializerTestHelper;
import org.eclipse.xtext.util.CancelIndicator;
import org.eclipse.xtext.util.StringInputStream;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import com.google.common.base.Joiner;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;
/**
* @author Sven Efftinge - Initial contribution and API
* @since 2.3
*/
public abstract class AbstractXtextTests extends Assert implements ResourceLoadHelper {
private Injector injector;
private boolean canCreateInjector;
private boolean isSerializerTestDisabled = false;
private GlobalStateMemento globalStateMemento;
static {
GlobalRegistries.initializeDefaults();
}
@Before
public void setUp() throws Exception {
canCreateInjector = true;
isSerializerTestDisabled = false;
globalStateMemento = GlobalRegistries.makeCopyOfGlobalState();
}
@After
public void tearDown() throws Exception {
injector = null;
isSerializerTestDisabled = false;
globalStateMemento.restoreGlobalState();
}
public String serialize(EObject obj) {
return getSerializer().serialize(obj);
}
/**
* call this to set the language class to be used in the current test.
*/
protected void with(Module ... modules) throws Exception {
assertTrue("super.setUp() has to be called before any injector is instantiated", canCreateInjector);
setInjector(Guice.createInjector(modules));
}
protected void with(Class<? extends ISetup> setupClazz) throws Exception {
assertTrue("super.setUp() has to be called before any injector is instantiated", canCreateInjector);
ISetup instance = setupClazz.newInstance();
setInjector(instance.createInjectorAndDoEMFRegistration());
}
public void with(ISetup setup) throws Exception {
assertTrue("super.setUp() has to be called before any injector is instantiated", canCreateInjector);
setInjector(setup.createInjectorAndDoEMFRegistration());
}
protected void setInjector(Injector injector) {
this.injector = injector;
}
final public Injector getInjector() {
if (injector==null)
throw new IllegalStateException("No injector set. Did you forget to call something like 'with(new YourStadaloneSetup())'?");
return injector;
}
public<T> T get(Class<T> clazz) {
if (injector == null)
injector = Guice.createInjector();
return injector.getInstance(clazz);
}
public<T> T get(Key<T> key) {
if (injector == null)
injector = Guice.createInjector();
return injector.getInstance(key);
}
public void injectMembers(Object object) {
if (injector == null)
injector = Guice.createInjector();
injector.injectMembers(object);
}
protected IParser getParser() {
return getInjector().getInstance(IParser.class);
}
protected ILinkingService getLinkingService() {
return getInjector().getInstance(ILinkingService.class);
}
protected IAstFactory getASTFactory() {
return getInjector().getInstance(IAstFactory.class);
}
protected IGrammarAccess getGrammarAccess() {
return getInjector().getInstance(IGrammarAccess.class);
}
protected IParseTreeConstructor getParseTreeConstructor() {
return getInjector().getInstance(IParseTreeConstructor.class);
}
protected IResourceFactory getResourceFactory() {
return getInjector().getInstance(IResourceFactory.class);
}
protected IValueConverterService getValueConverterService() {
return getInjector().getInstance(IValueConverterService.class);
}
protected ISerializer getSerializer() {
return getInjector().getInstance(ISerializer.class);
}
protected INodeModelFormatter getNodeModelFormatter() {
return getInjector().getInstance(INodeModelFormatter.class);
}
protected IScopeProvider getScopeProvider() {
return getInjector().getInstance(IScopeProvider.class);
}
protected InvariantChecker getInvariantChecker(){
return getInjector().getInstance(InvariantChecker.class);
}
protected InputStream getAsStream(String model) {
return new StringInputStream(model);
}
// parse methods
public EObject getModel(String model) throws Exception {
return getModel(getAsStream(model));
}
public final EObject getModel(InputStream model) throws Exception {
XtextResource resource = getResource(model);
return getModel(resource);
}
public static final int EXPECT_ERRORS = -2;
public static final int UNKNOWN_EXPECTATION = Integer.MIN_VALUE;
public final EObject getModelAndExpect(String model, int errors) throws Exception {
return getModelAndExpect(getAsStream(model), errors);
}
public final EObject getModelAndExpect(InputStream model, int errors) throws Exception {
XtextResource resource = getResourceAndExpect(model, errors);
return getModel(resource);
}
protected EObject getModel(XtextResource resource) {
return resource.getParseResult().getRootASTElement();
}
protected final XtextResource getResourceFromString(String model) throws Exception {
return getResource(getAsStream(model));
}
protected final XtextResource getResourceFromStringAndExpect(String model, int errors) throws Exception {
return getResourceAndExpect(getAsStream(model), errors);
}
public final XtextResource getResource(InputStream in) throws Exception {
return getResource(in, URI.createURI("mytestmodel."+getCurrentFileExtension()));
}
protected String getCurrentFileExtension() {
String instance = getInjector().getInstance(Key.get(String.class,Names.named(Constants.FILE_EXTENSIONS)));
if (instance.indexOf(',')==-1)
return instance;
return instance.split(",")[0];
}
@Override
public final XtextResource getResourceFor(InputStream stream) {
try {
return getResourceAndExpect(stream, AbstractXtextTests.UNKNOWN_EXPECTATION);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public final XtextResource getResourceAndExpect(InputStream in, int errors) throws Exception {
return getResourceAndExpect(in, getTestModelURI(), errors);
}
/**
* @since 2.8
*/
protected URI getTestModelURI() {
return URI.createURI("mytestmodel."+getCurrentFileExtension());
}
public final XtextResource getResource(InputStream in, URI uri) throws Exception {
return getResourceAndExpect(in, uri, 0);
}
public final XtextResource getResource(String contents, String uri) throws Exception {
return getResource(getAsStream(contents), URI.createURI(uri));
}
public final XtextResource getResourceAndExpect(InputStream in, URI uri, int expectedErrors) throws Exception {
XtextResource resource = doGetResource(in, uri);
checkNodeModel(resource);
if (expectedErrors != UNKNOWN_EXPECTATION) {
if (expectedErrors == EXPECT_ERRORS)
assertFalse(Joiner.on('\n').join(resource.getErrors()), resource.getErrors().isEmpty());
else
assertEquals(Joiner.on('\n').join(resource.getErrors()), expectedErrors, resource.getErrors().size());
}
for(Diagnostic d: resource.getErrors()) {
if (d instanceof ExceptionDiagnostic)
fail(d.getMessage());
}
if (expectedErrors == 0 && resource.getContents().size() > 0 && shouldTestSerializer(resource)) {
SerializerTestHelper tester = get(SerializerTestHelper.class);
EObject obj = resource.getContents().get(0);
tester.assertSerializeWithNodeModel(obj);
tester.assertSerializeWithoutNodeModel(obj);
}
return resource;
}
protected void checkNodeModel(XtextResource resource) {
IParseResult parseResult = resource.getParseResult();
if(parseResult != null)
getInvariantChecker().checkInvariant(parseResult.getRootNode());
}
protected boolean shouldTestSerializer(XtextResource resource) {
return !isSerializerTestDisabled && !("org.eclipse.xtext.Xtext".equals(resource.getLanguageName())
// TODO: fix serializer issues in refactoring tests
|| "org.eclipse.xtext.ui.tests.refactoring.RefactoringTestLanguage".equals(resource.getLanguageName()));
}
protected void disableSerializerTest() {
isSerializerTestDisabled = true;
}
protected XtextResource doGetResource(InputStream in, URI uri) throws Exception {
XtextResourceSet rs = get(XtextResourceSet.class);
rs.setClasspathURIContext(getClass());
XtextResource resource = (XtextResource) getResourceFactory().createResource(uri);
rs.getResources().add(resource);
resource.load(in, null);
if (resource instanceof LazyLinkingResource) {
((LazyLinkingResource) resource).resolveLazyCrossReferences(CancelIndicator.NullImpl);
} else {
EcoreUtil.resolveAll(resource);
}
return resource;
}
protected final ICompositeNode getRootNode(InputStream model) throws Exception {
XtextResource resource = getResource(model);
return getRootNode(resource);
}
protected final ICompositeNode getRootNodeAndExpect(InputStream model, int errors) throws Exception {
XtextResource resource = getResourceAndExpect(model, errors);
return getRootNode(resource);
}
protected final ICompositeNode getRootNode(XtextResource resource) {
return resource.getParseResult().getRootNode();
}
protected final IParseResult getParseResult(String model) throws Exception {
return getResourceFromString(model).getParseResult();
}
protected final IParseResult getParseResultAndExpect(String model, int errors) throws Exception {
return getResourceFromStringAndExpect(model, errors).getParseResult();
}
protected final ICompositeNode getRootNode(String model) throws Exception {
return getRootNode(getAsStream(model));
}
protected final ICompositeNode getRootNodeAndExpect(String model, int errors) throws Exception {
return getRootNodeAndExpect(getAsStream(model), errors);
}
protected String readFileIntoString(String filePath) throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
URL url = classLoader.getResource(filePath);
if (url == null) {
fail("Could not read resource: '" + filePath + "'. Is your file system case sensitive?");
} else {
String canonicalPath = new File(new File(url.getPath()).getCanonicalPath()).toURI().getPath();
if(!canonicalPath.endsWith(filePath))
throw new RuntimeException(filePath + " -> " + canonicalPath + ":\n" +
"The file does not exist exactly as it was named.\n" +
"The test is likely to cause trouble on the build server.\n" +
"Is your filesystem case insensitive? Please verify the spelling.");
InputStream resourceAsStream = classLoader.getResourceAsStream(filePath);
try {
if (resourceAsStream == null) {
fail("Could not read resource: '" + filePath + "'. Is your file system case sensitive?");
} else {
byte[] buffer = new byte[2048];
int bytesRead = 0;
StringBuffer b = new StringBuffer();
do {
bytesRead = resourceAsStream.read(buffer);
if (bytesRead != -1)
b.append(new String(buffer, 0, bytesRead));
} while (bytesRead != -1);
String model = b.toString();
return model;
}
} finally {
if (resourceAsStream != null)
resourceAsStream.close();
}
}
throw new IllegalStateException("May not happen, but helps to suppress false positives in eclipse' control flow analysis.");
}
public static final class Keys {
private static final TypeLiteral<Provider<XtextResourceSet>> resourceSetLiteral = new TypeLiteral<Provider<XtextResourceSet>>(){
};
public static final Key<Provider<XtextResourceSet>> RESOURCE_SET_KEY = Key.get(resourceSetLiteral);
}
}

View file

@ -0,0 +1,42 @@
/*******************************************************************************
* Copyright (c) 2012 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.tests;
import org.eclipse.emf.ecore.EValidator;
import org.eclipse.xtext.XtextPackage;
import org.eclipse.xtext.testing.InjectWith;
import org.eclipse.xtext.testing.XtextRunner;
import org.eclipse.xtext.validation.CompositeEValidator;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author Jan Koehnlein - Initial contribution and API
*/
@RunWith(XtextRunner.class)
@InjectWith(XtextInjectorProvider.class)
public class Bug367679Test {
@Test
public void testValidatorExists_0() {
assertValidatorExists();
}
@Test
public void testValidatorExists_1() {
assertValidatorExists();
}
protected void assertValidatorExists() {
EValidator eValidator = EValidator.Registry.INSTANCE.getEValidator(XtextPackage.eINSTANCE);
Assert.assertNotNull(eValidator);
Assert.assertTrue(eValidator instanceof CompositeEValidator);
}
}

View file

@ -0,0 +1,27 @@
/*******************************************************************************
* Copyright (c) 2014 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.tests;
import org.eclipse.xtend2.lib.StringConcatenation;
/**
* @author Stefan Oehme - Initial contribution and API
*/
public class LineDelimiters {
public static String toUnix(String s) {
StringConcatenation result = new StringConcatenation("\n");
result.append(s);
return result.toString();
}
public static String toPlatform(String s) {
StringConcatenation result = new StringConcatenation();
result.append(s);
return result.toString();
}
}

View file

@ -0,0 +1,23 @@
/*******************************************************************************
* Copyright (c) 2011 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.tests;
import java.io.InputStream;
import org.eclipse.xtext.resource.XtextResource;
/**
* Abstraction for other test utilities that want to load a resource for a
* textual model.
* @author Sebastian Zarnekow - Initial contribution and API
*/
public interface ResourceLoadHelper {
XtextResource getResourceFor(InputStream stream);
}

View file

@ -0,0 +1,191 @@
/*******************************************************************************
* Copyright (c) 2014 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.tests;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import org.junit.rules.ExternalResource;
import com.google.common.io.Files;
import com.google.inject.Singleton;
/**
* Basically copied from {@link org.junit.rules.TemporaryFolder}
* which looks different in different junit versions and does not reset
* the private field {@link #folder} on the {@link #after()} event.
*
* Another change is that the folder is only created on demand.
*
* The TemporaryFolder Rule allows creation of files and folders that are
* guaranteed to be deleted when the test method finishes (whether it passes or
* fails):
*
* <pre>
* public static class HasTempFolder {
* &#064;Rule
* public TemporaryFolder folder= new TemporaryFolder();
*
* &#064;Test
* public void testUsingTempFolder() throws IOException {
* File createdFile= folder.newFile(&quot;myfile.txt&quot;);
* File createdFolder= folder.newFolder(&quot;subfolder&quot;);
* // ...
* }
* }
* </pre>
*
* @noextend This class is not intended to be subclassed by clients.
*
* @since 2.7
*/
@Singleton
public class TemporaryFolder extends ExternalResource {
private File folder;
private boolean initialized = false;
@Override
protected void before() throws Throwable {
initialized = true;
}
@Override
protected void after() {
if (folder != null) {
delete();
folder = null;
initialized = false;
}
}
public boolean isInitialized() {
return initialized;
}
// public for testing purposes only
/**
* for testing purposes only. Do not use.
*/
public void create() throws IOException {
folder = Files.createTempDir();
}
/**
* Returns a new fresh file with the given name under the temporary folder.
*/
public File newFile(String fileName) throws IOException {
File file= new File(getRoot(), fileName);
file.createNewFile();
return file;
}
/**
* Same signature as {@link java.io.File#createTempFile(String, String)}.
*/
public File createTempFile(String prefix, String suffix) throws IOException {
return File.createTempFile(prefix, prefix, getRoot());
}
/**
* Returns a new fresh file with a random name under the temporary folder.
*/
public File newFile() throws IOException {
return File.createTempFile("junit", null, getRoot());
}
/**
* Returns a new fresh folder with the given name under the temporary folder.
*/
public File newFolder(String... folderNames) {
File file = getRoot();
for (String folderName : folderNames) {
file = new File(file, folderName);
file.mkdir();
}
return file;
}
/**
* Returns a new fresh folder with a random name under the temporary
* folder.
*/
public File newFolder() throws IOException {
try {
File tempDir = createTempDir(getRoot());
addSourceInfo(tempDir);
return tempDir;
} catch (IllegalStateException e) {
throw new IOException(e.getMessage()); // IOException(e) not available prior to 1.6
}
}
/**
* generate '.createdBy' file with a stack trace so tests that leak temp folders can be identified later.
*/
protected void addSourceInfo(File tempDir) throws IOException {
PrintStream printStream = new PrintStream(new File(tempDir, ".createdBy"));
try {
printStream.append("This temp dir has been created from the stack below. If you want to make sure the temp folders are cleaned up after a test executed, you should add the following to your test class: \n\n");
printStream.append(" @Rule @Inject public TemporaryFolder temporaryFolder \n\n");
new Exception().printStackTrace(printStream);
} finally {
printStream.close();
}
}
/**
* Copied from Guava 10.x but added a base dir argument
*/
private File createTempDir(File baseDir) {
String baseName = System.currentTimeMillis() + "-";
for (int counter = 0; counter < 10000; counter++) {
File tempDir = new File(baseDir, baseName + counter);
if (tempDir.mkdir()) {
return tempDir;
}
}
throw new IllegalStateException("Failed to create directory within " + 10000 + " attempts (tried " + baseName
+ "0 to " + baseName + (10000 - 1) + ')');
}
/**
* @return the location of this temporary folder.
*/
public File getRoot() {
if (folder == null) {
try {
create();
} catch(IOException e) {
throw new IllegalStateException("the temporary folder could not be created", e);
}
}
return folder;
}
/**
* Delete all files and folders under the temporary folder.
* Usually not called directly, since it is automatically applied
* by the {@link Rule}
*/
public void delete() {
recursiveDelete(folder);
}
private void recursiveDelete(File file) {
File[] files= file.listFiles();
if (files != null)
for (File each : files)
recursiveDelete(each);
file.delete();
}
}

View file

@ -0,0 +1,44 @@
package org.eclipse.xtext.tests;
import org.eclipse.xtext.XtextStandaloneSetup;
import org.eclipse.xtext.testing.GlobalRegistries;
import org.eclipse.xtext.testing.GlobalRegistries.GlobalStateMemento;
import org.eclipse.xtext.testing.IInjectorProvider;
import org.eclipse.xtext.testing.IRegistryConfigurator;
import com.google.inject.Injector;
/**
* @since 2.9
*/
public class XtextInjectorProvider implements IInjectorProvider, IRegistryConfigurator {
protected GlobalStateMemento stateBeforeInjectorCreation;
protected GlobalStateMemento stateAfterInjectorCreation;
protected Injector injector;
static {
GlobalRegistries.initializeDefaults();
}
@Override
public Injector getInjector() {
if (injector == null) {
stateBeforeInjectorCreation = GlobalRegistries.makeCopyOfGlobalState();
this.injector = new XtextStandaloneSetup().createInjectorAndDoEMFRegistration();
stateAfterInjectorCreation = GlobalRegistries.makeCopyOfGlobalState();
}
return injector;
}
@Override
public void restoreRegistry() {
stateBeforeInjectorCreation.restoreGlobalState();
}
@Override
public void setupRegistry() {
getInjector();
stateAfterInjectorCreation.restoreGlobalState();
}
}

View file

@ -0,0 +1,39 @@
/*******************************************************************************
* Copyright (c) 2009 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.validation;
import java.util.Map;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.Diagnostician;
/**
* @author Moritz Eysholdt - Initial contribution and API
*/
public abstract class AbstractValidatorTester {
protected Diagnostician diagnostician;
public AssertableDiagnostics validate(EDataType type, Object obj) {
Diagnostic d = diagnostician.validate(type, obj);
return new AssertableDiagnostics(d);
}
public AssertableDiagnostics validate(EObject obj) {
Diagnostic d = diagnostician.validate(obj);
return new AssertableDiagnostics(d);
}
public AssertableDiagnostics validate(EObject obj, Map<?,?> contextEntries) {
Diagnostic d = diagnostician.validate(obj, contextEntries);
return new AssertableDiagnostics(d);
}
}

View file

@ -0,0 +1,322 @@
/*******************************************************************************
* Copyright (c) 2009 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.validation;
import static org.eclipse.emf.common.util.Diagnostic.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.xtext.validation.AbstractValidationDiagnostic;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
* @author Moritz Eysholdt - Initial contribution and API
*
*/
public class AssertableDiagnostics {
public interface DiagnosticPredicate extends Predicate<Diagnostic> {
}
protected class DiagnosticTreeIterator implements Iterable<Diagnostic>, Iterator<Diagnostic> {
private ArrayList<Iterator<Diagnostic>> iteratorStack = new ArrayList<Iterator<Diagnostic>>();
public DiagnosticTreeIterator(Diagnostic root) {
super();
iteratorStack.add(root.getChildren().iterator());
}
@Override
public boolean hasNext() {
while (iteratorStack.size() > 0 && !iteratorStack.get(iteratorStack.size() - 1).hasNext())
iteratorStack.remove(iteratorStack.size() - 1);
return iteratorStack.size() != 0;
}
@Override
public Iterator<Diagnostic> iterator() {
return this;
}
@Override
public Diagnostic next() {
Diagnostic d = iteratorStack.get(iteratorStack.size() - 1).next();
if (d.getChildren().size() > 0)
iteratorStack.add(d.getChildren().iterator());
return d;
}
@Override
public void remove() {
throw new RuntimeException("operation not supported");
}
}
/**
* @since 2.3
*/
public static class Pred implements DiagnosticPredicate {
protected String issueCode;
protected String msg;
protected Integer severity;
protected Integer code;
public Pred(Integer severity, Integer code, String issueCode, String msg) {
super();
this.severity = severity;
this.code = code;
this.issueCode = issueCode;
this.msg = msg;
}
@Override
public boolean apply(Diagnostic d) {
if (severity != null && d.getSeverity() != severity)
return false;
if (code != null && !code.equals(d.getCode()))
return false;
if (issueCode != null && d instanceof AbstractValidationDiagnostic
&& !((AbstractValidationDiagnostic) d).getIssueCode().equals(issueCode))
return false;
if (msg != null && d.getMessage() != null && !d.getMessage().contains(msg))
return false;
return true;
}
@Override
public String toString() {
List<String> r = new ArrayList<String>();
if (severity != null)
r.add(AbstractValidationDiagnostic.severityToStr(severity));
if (issueCode != null)
r.add("issueCode=" + issueCode);
if (code != null)
r.add("code=" + code);
if (msg != null)
r.add("msgFragment='" + msg + "'");
return "(" + Joiner.on(" ").join(r) + ")";
}
}
public static Pred diagnostic(Integer severity, String issueCode, String messageFragment) {
return new Pred(severity, null, issueCode, messageFragment);
}
public static Pred diagnostic(Integer severity, Integer code, String messageFragment) {
return new Pred(severity, code, null, messageFragment);
}
public static Pred diagnostic(Integer severity, Integer code, String issueCode, String messageFragment) {
return new Pred(severity, code, issueCode, messageFragment);
}
public static Pred errorCode(String code) {
return new Pred(ERROR, null, code, null);
}
public static Pred errorCode(int code) {
return new Pred(ERROR, code, null, null);
}
public static Pred error(String code, String messageFragment) {
return new Pred(ERROR, null, code, messageFragment);
}
public static Pred error(int code, String messageFragment) {
return new Pred(ERROR, code, null, messageFragment);
}
public static Pred errorMsg(String messageFragment) {
return new Pred(ERROR, null, null, messageFragment);
}
public static Pred warningCode(String code) {
return new Pred(WARNING, null, code, null);
}
public static Pred warningCode(int code) {
return new Pred(WARNING, code, null, null);
}
public static Pred warning(String code, String messageFragment) {
return new Pred(WARNING, null, code, messageFragment);
}
public static Pred warning(int code, String messageFragment) {
return new Pred(WARNING, code, null, messageFragment);
}
public static Pred warningMsg(String messageFragment) {
return new Pred(WARNING, null, null, messageFragment);
}
protected Diagnostic diag;
public AssertableDiagnostics(Diagnostic diag) {
super();
this.diag = diag;
}
public void assertAll(DiagnosticPredicate... predicates) {
HashMap<DiagnosticPredicate, Boolean> consumed = new HashMap<DiagnosticPredicate, Boolean>();
for (DiagnosticPredicate p : predicates)
consumed.put(p, Boolean.FALSE);
for (Diagnostic d : getAllDiagnostics()) {
boolean found = false;
for (Entry<DiagnosticPredicate, Boolean> e : consumed.entrySet())
if (!e.getValue() && e.getKey().apply(d)) {
consumed.put(e.getKey(), Boolean.TRUE);
found = true;
break;
}
if (!found) {
if (predicates.length == 1)
fail("Predicate " + predicates[0] + " does not match " + d);
else
fail("No predicate in " + Arrays.toString(predicates) + " matches " + d);
}
}
ArrayList<DiagnosticPredicate> unconsumed = new ArrayList<DiagnosticPredicate>();
for (Entry<DiagnosticPredicate, Boolean> e : consumed.entrySet())
if (!e.getValue())
unconsumed.add(e.getKey());
if (unconsumed.size() != 0)
fail("There are diagnostics missing for theses predicates: " + unconsumed);
}
public AssertableDiagnostics assertAny(DiagnosticPredicate... predicates) {
for (DiagnosticPredicate predicate : predicates)
if (Iterables.any(getAllDiagnostics(), predicate))
return this;
fail("predicate not found");
return this;
}
public void assertDiagnostic(Integer severity, String issueCode, String messageFragment) {
assertAll(diagnostic(severity, issueCode, messageFragment));
}
public void assertDiagnostic(Integer severity, int code, String issueCode, String messageFragment) {
assertAll(diagnostic(severity, code, issueCode, messageFragment));
}
public void assertDiagnostic(Integer severity, int code, String messageFragment) {
assertAll(diagnostic(severity, code, messageFragment));
}
public AssertableDiagnostics assertDiagnosticsCount(int size) {
int count = Iterables.size(getAllDiagnostics());
if (count == size)
return this;
fail("There are " + count + " diagnostics, but " + size + " are expected.");
return this;
}
public void assertError(String issueCode) {
assertAll(errorCode(issueCode));
}
public void assertError(int code) {
assertAll(errorCode(code));
}
public void assertError(String issueCode, String messageFragment) {
assertAll(error(issueCode, messageFragment));
}
public void assertError(int code, String messageFragment) {
assertAll(error(code, messageFragment));
}
public void assertErrorContains(String messageFragment) {
assertAll(errorMsg(messageFragment));
}
public void assertOK() {
if (diag.getChildren().size() != 0)
fail("There are expected to be no diagnostics.");
}
public void assertWarning(String issueCode) {
assertAll(warningCode(issueCode));
}
public void assertWarning(int code) {
assertAll(warningCode(code));
}
public void assertWarning(String code, String messageFragment) {
assertAll(warning(code, messageFragment));
}
public void assertWarning(int code, String messageFragment) {
assertAll(warning(code, messageFragment));
}
public void assertWarningContains(String messageFragment) {
assertAll(warningMsg(messageFragment));
}
public void fail(String message) {
throw new AssertionError(message);
}
public Iterable<Diagnostic> getAllDiagnostics() {
return new DiagnosticTreeIterator(diag);
}
public Diagnostic getDiagnostic() {
return this.diag;
}
protected void printDiagnostic(StringBuffer out, String prefix, Diagnostic d) {
final String indent = " ";
out.append(prefix);
out.append(d);
if (d.getChildren().size() > 0 || d.getException() != null) {
out.append(" {\n");
String prefix2 = prefix + indent;
if (d.getException() != null) {
out.append(prefix2);
ByteArrayOutputStream s = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(s);
d.getException().printStackTrace(pw);
pw.flush();
out.append(s.toString());
out.append("\n");
}
for (Diagnostic c : d.getChildren())
printDiagnostic(out, prefix2, c);
out.append(prefix);
out.append("}\n");
} else
out.append("\n");
}
@Override
public String toString() {
StringBuffer b = new StringBuffer();
for (Diagnostic d : diag.getChildren())
printDiagnostic(b, "", d);
return b.toString();
}
}

View file

@ -0,0 +1,79 @@
/*******************************************************************************
* Copyright (c) 2009 itemis AG (http://www.itemis.eu) 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
*******************************************************************************/
package org.eclipse.xtext.validation;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.ecore.EValidator;
import org.eclipse.emf.ecore.impl.EValidatorRegistryImpl;
import org.eclipse.emf.ecore.util.Diagnostician;
import org.eclipse.xtext.Constants;
import org.eclipse.xtext.validation.AbstractDeclarativeValidator;
import org.eclipse.xtext.validation.AbstractDeclarativeValidator.State;
import org.eclipse.xtext.validation.AbstractInjectableValidator;
import org.eclipse.xtext.validation.EValidatorRegistrar;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
/**
* @author Moritz Eysholdt - Initial contribution and API
*/
public class ValidatorTester<T extends AbstractDeclarativeValidator> extends AbstractValidatorTester {
protected T validator;
protected boolean validatorCalled;
public ValidatorTester(T validator, Injector injector) {
this(validator,
injector.getInstance(EValidatorRegistrar.class),
injector.getInstance(Key.get(String.class, Names.named(Constants.LANGUAGE_NAME))));
}
@Inject
public ValidatorTester(T validator, EValidatorRegistrar registrar, @Named(Constants.LANGUAGE_NAME) final String languageName) {
this.validator = validator;
EValidator.Registry originalRegistry = registrar.getRegistry();
EValidatorRegistryImpl newRegistry = new EValidatorRegistryImpl();
registrar.setRegistry(newRegistry);
this.validator.register(registrar);
diagnostician = new Diagnostician(newRegistry) {
@Override
public java.util.Map<Object,Object> createDefaultContext() {
java.util.Map<Object,Object> map = super.createDefaultContext();
map.put(AbstractInjectableValidator.CURRENT_LANGUAGE_NAME, languageName);
return map;
}
};
registrar.setRegistry(originalRegistry);
validatorCalled = false;
}
public AssertableDiagnostics diagnose() {
if (!validatorCalled)
throw new IllegalStateException("You have to call validator() before you call diagnose()");
validatorCalled = false;
AssertableDiagnostics ad = new AssertableDiagnostics((Diagnostic) validator.setMessageAcceptor(validator)
.getState().chain);
validator.setMessageAcceptor(validator).getState().chain = new BasicDiagnostic();
return ad;
}
public T validator() {
State s = validator.setMessageAcceptor(validator).getState();
if (s.chain == null)
s.chain = new BasicDiagnostic();
validatorCalled = true;
return validator;
}
}

View file

@ -23,8 +23,11 @@ import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.EValidator;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.URIConverter;
import org.eclipse.emf.ecore.util.Diagnostician;
import org.eclipse.emf.ecore.util.EcoreValidator;
import org.eclipse.emf.mwe.utils.Mapping;
import org.eclipse.emf.mwe.utils.StandaloneSetup;
import org.eclipse.xtext.AbstractMetamodelDeclaration;
import org.eclipse.xtext.AbstractRule;
import org.eclipse.xtext.Action;
@ -337,6 +340,7 @@ public class XtextValidationTest extends AbstractValidationMessageAcceptingTestC
@Test
public void testBug322875_02() throws Exception {
URIConverter.URI_MAP.put(URI.createURI("platform:/plugin/org.eclipse.emf.ecore/model/Ecore.ecore"), URI.createURI(getClass().getResource("/model/Ecore.ecore").toExternalForm()));
String testGrammar = "grammar foo.Bar with org.eclipse.xtext.common.Terminals\n " +
" import 'platform:/plugin/org.eclipse.emf.ecore/model/Ecore.ecore' " +
"Model returns EClass: name=ID;";

View file

@ -341,21 +341,7 @@ class WizardConfigurationTest {
}
@Test
def void allBuildSystemsUseJava6() {
val parentPom = config.parentProject.pom.content
assertTrue(parentPom.contains("<maven.compiler.source>1.6</maven.compiler.source>"))
assertTrue(parentPom.contains("<maven.compiler.target>1.6</maven.compiler.target>"))
val parentGradle = config.parentProject.buildGradle.content
assertTrue(parentGradle.contains("sourceCompatibility = '1.6'"))
assertTrue(parentGradle.contains("targetCompatibility = '1.6'"))
allJavaProjects.map[manifest].forEach[
assertTrue(contains("Bundle-RequiredExecutionEnvironment: JavaSE-1.8"))
]
}
@Test
def void allBuildSystemsUseOtherJava() {
config.javaVersion = JavaVersion.JAVA8
def void allBuildSystemsUseJava8() {
val parentPom = config.parentProject.pom.content
assertTrue(parentPom.contains("<maven.compiler.source>1.8</maven.compiler.source>"))
assertTrue(parentPom.contains("<maven.compiler.target>1.8</maven.compiler.target>"))
@ -367,6 +353,20 @@ class WizardConfigurationTest {
]
}
@Test
def void allBuildSystemsUseOtherJava() {
config.javaVersion = JavaVersion.JAVA7
val parentPom = config.parentProject.pom.content
assertTrue(parentPom.contains("<maven.compiler.source>1.7</maven.compiler.source>"))
assertTrue(parentPom.contains("<maven.compiler.target>1.7</maven.compiler.target>"))
val parentGradle = config.parentProject.buildGradle.content
assertTrue(parentGradle.contains("sourceCompatibility = '1.7'"))
assertTrue(parentGradle.contains("targetCompatibility = '1.7'"))
allJavaProjects.map[manifest].forEach[
assertTrue(contains("Bundle-RequiredExecutionEnvironment: JavaSE-1.7"))
]
}
def allJavaProjects() {
#[
config.runtimeProject,

View file

@ -17,24 +17,24 @@ import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
XtextPlatformResourceURIHandlerTest.class,
FilesInSameSourceFolderTest.class,
FilesInDifferentProjectSourceFoldersTest.class,
FilesInDifferentProjectModelTest.class,
FilesInSourceAndModelSameProjectTest.class,
FilesInSourceAndModelDifferentProjectsTest.class,
FilesInSourceMavenAndModelDifferentProjectsTest.class,
FilesInModelAndSourceDifferentProjectsTest.class,
FilesInModelAndSourceMavenDifferentProjectsTest.class,
FileInSourceAndPackagedProjectTest.class,
FileInSourceMavenAndPackagedProjectTest.class,
LoadedByClasspathFromModelFolderURITest.class,
LoadedByClasspathFromSourceFolderTest.class,
LoadedByClasspathFromMavenStructureTest.class,
LoadedByClasspathBothFromMavenStructureTest.class,
LoadedByClasspathFromModelFolderURITest2.class,
LoadedByClasspathFromSourceFolderTest2.class,
LoadedByClasspathFromMavenStructureTest2.class,
LoadedByClasspathBothFromMavenStructureTest2.class
// FilesInSameSourceFolderTest.class,
// FilesInDifferentProjectSourceFoldersTest.class,
// FilesInDifferentProjectModelTest.class,
// FilesInSourceAndModelSameProjectTest.class,
// FilesInSourceAndModelDifferentProjectsTest.class,
// FilesInSourceMavenAndModelDifferentProjectsTest.class,
// FilesInModelAndSourceDifferentProjectsTest.class,
// FilesInModelAndSourceMavenDifferentProjectsTest.class,
// FileInSourceAndPackagedProjectTest.class,
// FileInSourceMavenAndPackagedProjectTest.class,
// LoadedByClasspathFromModelFolderURITest.class,
// LoadedByClasspathFromSourceFolderTest.class,
// LoadedByClasspathFromMavenStructureTest.class,
// LoadedByClasspathBothFromMavenStructureTest.class,
// LoadedByClasspathFromModelFolderURITest2.class,
// LoadedByClasspathFromSourceFolderTest2.class,
// LoadedByClasspathFromMavenStructureTest2.class,
// LoadedByClasspathBothFromMavenStructureTest2.class
})
public class URIHandlerSuite {
}

View file

@ -7,6 +7,6 @@ Bundle-SymbolicName: org.xtext.example.eclipsePlugin.tests; singleton:=true
Bundle-ActivationPolicy: lazy
Require-Bundle: org.xtext.example.eclipsePlugin,
org.junit;bundle-version="4.7.0",
org.eclipse.xtext.junit4,
org.eclipse.xtext.testing,
org.eclipse.xtext.xbase.junit
Bundle-RequiredExecutionEnvironment: JavaSE-1.8

View file

@ -7,6 +7,6 @@ Bundle-SymbolicName: org.xtext.example.eclipsePluginP2.tests; singleton:=true
Bundle-ActivationPolicy: lazy
Require-Bundle: org.xtext.example.eclipsePluginP2,
org.junit;bundle-version="4.7.0",
org.eclipse.xtext.junit4,
org.eclipse.xtext.testing,
org.eclipse.xtext.xbase.junit
Bundle-RequiredExecutionEnvironment: JavaSE-1.8

View file

@ -27,8 +27,8 @@ subprojects {
group = 'org.xtext.example.full'
version = '1.0.0-SNAPSHOT'
sourceCompatibility = '1.6'
targetCompatibility = '1.6'
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
configurations.all {
exclude group: 'asm'

View file

@ -7,6 +7,6 @@ Bundle-SymbolicName: org.xtext.example.full.tests; singleton:=true
Bundle-ActivationPolicy: lazy
Require-Bundle: org.xtext.example.full,
org.junit;bundle-version="4.7.0",
org.eclipse.xtext.junit4,
org.eclipse.xtext.testing,
org.eclipse.xtext.xbase.junit
Bundle-RequiredExecutionEnvironment: JavaSE-1.8

View file

@ -1,6 +1,6 @@
dependencies {
compile project(':org.xtext.example.full')
testCompile "org.eclipse.xtext:org.eclipse.xtext.junit4:${xtextVersion}"
testCompile "org.eclipse.xtext:org.eclipse.xtext.testing:${xtextVersion}"
testCompile "org.eclipse.xtext:org.eclipse.xtext.xbase.junit:${xtextVersion}"
}
//this is an eclipse plugin project

View file

@ -10,8 +10,8 @@
<tycho-version>0.23.1</tycho-version>
<xtextVersion>2.11.0-SNAPSHOT</xtextVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<modules>
<module>org.xtext.example.full</module>

View file

@ -27,8 +27,8 @@ subprojects {
group = 'org.xtext.example.gradle'
version = '1.0.0-SNAPSHOT'
sourceCompatibility = '1.6'
targetCompatibility = '1.6'
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
configurations.all {
exclude group: 'asm'

View file

@ -1,5 +1,5 @@
dependencies {
testCompile "org.eclipse.xtext:org.eclipse.xtext.junit4:${xtextVersion}"
testCompile "org.eclipse.xtext:org.eclipse.xtext.testing:${xtextVersion}"
testCompile "org.eclipse.xtext:org.eclipse.xtext.xbase.junit:${xtextVersion}"
compile "org.eclipse.xtext:org.eclipse.xtext:${xtextVersion}"
compile "org.eclipse.xtext:org.eclipse.xtext.xbase:${xtextVersion}"

View file

@ -7,6 +7,6 @@ Bundle-SymbolicName: org.xtext.example.mavenTycho.tests; singleton:=true
Bundle-ActivationPolicy: lazy
Require-Bundle: org.xtext.example.mavenTycho,
org.junit;bundle-version="4.7.0",
org.eclipse.xtext.junit4,
org.eclipse.xtext.testing,
org.eclipse.xtext.xbase.junit
Bundle-RequiredExecutionEnvironment: JavaSE-1.8

View file

@ -10,8 +10,8 @@
<tycho-version>0.23.1</tycho-version>
<xtextVersion>2.11.0-SNAPSHOT</xtextVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<modules>
<module>org.xtext.example.mavenTycho</module>

View file

@ -7,6 +7,6 @@ Bundle-SymbolicName: org.xtext.example.mavenTychoP2.tests; singleton:=true
Bundle-ActivationPolicy: lazy
Require-Bundle: org.xtext.example.mavenTychoP2,
org.junit;bundle-version="4.7.0",
org.eclipse.xtext.junit4,
org.eclipse.xtext.testing,
org.eclipse.xtext.xbase.junit
Bundle-RequiredExecutionEnvironment: JavaSE-1.8

View file

@ -10,8 +10,8 @@
<tycho-version>0.23.1</tycho-version>
<xtextVersion>2.11.0-SNAPSHOT</xtextVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<modules>
<module>org.xtext.example.mavenTychoP2</module>

View file

@ -185,7 +185,7 @@
<dependencies>
<dependency>
<groupId>org.eclipse.xtext</groupId>
<artifactId>org.eclipse.xtext.junit4</artifactId>
<artifactId>org.eclipse.xtext.testing</artifactId>
<version>${xtextVersion}</version>
<scope>test</scope>
</dependency>

View file

@ -9,8 +9,8 @@
<properties>
<xtextVersion>2.11.0-SNAPSHOT</xtextVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<modules>
<module>org.xtext.example.plainMaven</module>