PageRenderTime 4998ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/plugins/org.grassaccords.emqcfg.junit/src/org/grassaccords/emqcfg/junit/AbstractXtextTests.java

https://gitlab.com/inetaborigine/emqcfg
Java | 369 lines | 289 code | 62 blank | 18 comment | 31 complexity | 6a188d1ab6b374864992fc6d38e8b141 MD5 | raw file
  1. /*******************************************************************************
  2. * Copyright (c) 2008 itemis AG (http://www.itemis.eu) and others.
  3. * All rights reserved. This program and the accompanying materials
  4. * are made available under the terms of the Eclipse Public License v1.0
  5. * which accompanies this distribution, and is available at
  6. * http://www.eclipse.org/legal/epl-v10.html
  7. *
  8. *******************************************************************************/
  9. package org.grassaccords.emqcfg.junit;
  10. import java.io.File;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.net.URL;
  14. import java.util.HashMap;
  15. import junit.framework.TestCase;
  16. import org.eclipse.emf.common.util.URI;
  17. import org.eclipse.emf.ecore.EObject;
  18. import org.eclipse.emf.ecore.EPackage;
  19. import org.eclipse.emf.ecore.EValidator;
  20. import org.eclipse.emf.ecore.resource.Resource;
  21. import org.eclipse.emf.ecore.resource.Resource.Diagnostic;
  22. import org.eclipse.emf.ecore.util.EcoreUtil;
  23. import org.eclipse.xtend.XtendFacade;
  24. import org.eclipse.xtend.expression.ExecutionContextImpl;
  25. import org.eclipse.xtend.typesystem.emf.EmfRegistryMetaModel;
  26. import org.eclipse.xtext.IGrammarAccess;
  27. import org.eclipse.xtext.ISetup;
  28. import org.eclipse.xtext.conversion.IValueConverterService;
  29. import org.eclipse.xtext.diagnostics.ExceptionDiagnostic;
  30. import org.eclipse.xtext.formatting.INodeModelFormatter;
  31. import org.eclipse.xtext.linking.ILinkingService;
  32. import org.eclipse.xtext.parser.IAstFactory;
  33. import org.eclipse.xtext.parser.IParser;
  34. import org.eclipse.xtext.parser.ISwitchingParser;
  35. import org.eclipse.xtext.parser.antlr.IAntlrParser;
  36. import org.eclipse.xtext.parser.packrat.IPackratParser;
  37. import org.eclipse.xtext.parsetree.CompositeNode;
  38. import org.eclipse.xtext.parsetree.reconstr.IParseTreeConstructor;
  39. import org.eclipse.xtext.parsetree.reconstr.SerializerUtil;
  40. import org.eclipse.xtext.resource.IResourceFactory;
  41. import org.eclipse.xtext.resource.XtextResource;
  42. import org.eclipse.xtext.resource.XtextResourceSet;
  43. import org.eclipse.xtext.scoping.IScopeProvider;
  44. import org.eclipse.xtext.util.StringInputStream;
  45. import com.google.inject.Guice;
  46. import com.google.inject.Injector;
  47. import com.google.inject.Key;
  48. import com.google.inject.Module;
  49. import com.google.inject.Provider;
  50. import com.google.inject.TypeLiteral;
  51. /**
  52. * @author Sven Efftinge - Initial contribution and API
  53. *
  54. */
  55. public abstract class AbstractXtextTests extends TestCase {
  56. private Injector injector;
  57. private HashMap<EPackage, Object> validatorReg;
  58. private HashMap<String, Object> epackageReg;
  59. private boolean canCreateInjector;
  60. static {
  61. //EMF Standalone setup
  62. if (!Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().containsKey("ecore"))
  63. Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
  64. "ecore", new org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl());
  65. if (!Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().containsKey("xmi"))
  66. Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
  67. "xmi", new org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl());
  68. if (!EPackage.Registry.INSTANCE.containsKey(org.eclipse.xtext.XtextPackage.eNS_URI))
  69. EPackage.Registry.INSTANCE.put(org.eclipse.xtext.XtextPackage.eNS_URI, org.eclipse.xtext.XtextPackage.eINSTANCE);
  70. }
  71. @Override
  72. protected void setUp() throws Exception {
  73. super.setUp();
  74. canCreateInjector = true;
  75. this.validatorReg = new HashMap<EPackage, Object>(EValidator.Registry.INSTANCE);
  76. this.epackageReg = new HashMap<String, Object>(EPackage.Registry.INSTANCE);
  77. }
  78. @Override
  79. protected void tearDown() throws Exception {
  80. injector = null;
  81. EValidator.Registry.INSTANCE.clear();
  82. EValidator.Registry.INSTANCE.putAll(validatorReg);
  83. EPackage.Registry.INSTANCE.clear();
  84. EPackage.Registry.INSTANCE.putAll(epackageReg);
  85. super.tearDown();
  86. }
  87. public String serialize(EObject obj) {
  88. return getSerializer().serialize(obj);
  89. }
  90. /**
  91. * call this to set the language class to be used in the current test.
  92. */
  93. protected void with(Module ... modules) throws Exception {
  94. assertTrue("super.setUp() has to be called before any injector is instantiated", canCreateInjector);
  95. injector = Guice.createInjector(modules);
  96. }
  97. protected void with(Class<? extends ISetup> setupClazz) throws Exception {
  98. assertTrue("super.setUp() has to be called before any injector is instantiated", canCreateInjector);
  99. ISetup instance = setupClazz.newInstance();
  100. injector = instance.createInjectorAndDoEMFRegistration();
  101. }
  102. public void with(ISetup setup) throws Exception {
  103. assertTrue("super.setUp() has to be called before any injector is instantiated", canCreateInjector);
  104. injector = setup.createInjectorAndDoEMFRegistration();
  105. }
  106. public<T> T get(Class<T> clazz) {
  107. if (injector == null)
  108. injector = Guice.createInjector();
  109. return injector.getInstance(clazz);
  110. }
  111. public<T> T get(Key<T> key) {
  112. if (injector == null)
  113. injector = Guice.createInjector();
  114. return injector.getInstance(key);
  115. }
  116. public void injectMembers(Object object) {
  117. if (injector == null)
  118. injector = Guice.createInjector();
  119. injector.injectMembers(object);
  120. }
  121. protected IParser getParser() {
  122. return injector.getInstance(ISwitchingParser.class);
  123. }
  124. protected IAntlrParser getAntlrParser() {
  125. return injector.getInstance(IAntlrParser.class);
  126. }
  127. protected IPackratParser getPackratParser() {
  128. return injector.getInstance(IPackratParser.class);
  129. }
  130. protected ILinkingService getLinkingService() {
  131. return injector.getInstance(ILinkingService.class);
  132. }
  133. protected IAstFactory getASTFactory() {
  134. return injector.getInstance(IAstFactory.class);
  135. }
  136. protected IGrammarAccess getGrammarAccess() {
  137. return injector.getInstance(IGrammarAccess.class);
  138. }
  139. protected IParseTreeConstructor getParseTreeConstructor() {
  140. return injector.getInstance(IParseTreeConstructor.class);
  141. }
  142. protected IResourceFactory getResourceFactory() {
  143. return injector.getInstance(IResourceFactory.class);
  144. }
  145. protected IValueConverterService getValueConverterService() {
  146. return injector.getInstance(IValueConverterService.class);
  147. }
  148. protected SerializerUtil getSerializer() {
  149. return injector.getInstance(SerializerUtil.class);
  150. }
  151. protected INodeModelFormatter getNodeModelFormatter() {
  152. return injector.getInstance(INodeModelFormatter.class);
  153. }
  154. protected IScopeProvider getScopeProvider() {
  155. return injector.getInstance(IScopeProvider.class);
  156. }
  157. // parse methods
  158. public final EObject getModel(String model) throws Exception {
  159. return getModel(new org.eclipse.xtext.util.StringInputStream(model));
  160. }
  161. public final EObject getModel(InputStream model) throws Exception {
  162. XtextResource resource = getResource(model);
  163. return getModel(resource);
  164. }
  165. public static final int EXPECT_ERRORS = -2;
  166. public static final int UNKNOWN_EXPECTATION = Integer.MIN_VALUE;
  167. public final EObject getModelAndExpect(String model, int errors) throws Exception {
  168. return getModelAndExpect(new org.eclipse.xtext.util.StringInputStream(model), errors);
  169. }
  170. public final EObject getModelAndExpect(InputStream model, int errors) throws Exception {
  171. XtextResource resource = getResourceAndExpect(model, errors);
  172. return getModel(resource);
  173. }
  174. protected final EObject getModel(XtextResource resource) {
  175. return resource.getParseResult().getRootASTElement();
  176. }
  177. protected final XtextResource getResourceFromString(String model) throws Exception {
  178. return getResource(new org.eclipse.xtext.util.StringInputStream(model));
  179. }
  180. protected final XtextResource getResourceFromStringAndExpect(String model, int errors) throws Exception {
  181. return getResourceAndExpect(new org.eclipse.xtext.util.StringInputStream(model), errors);
  182. }
  183. public final XtextResource getResource(InputStream in) throws Exception {
  184. return getResource(in, URI.createURI("mytestmodel.test"));
  185. }
  186. public final XtextResource getResourceAndExpect(InputStream in, int errors) throws Exception {
  187. return getResourceAndExpect(in, URI.createURI("mytestmodel.test"), errors);
  188. }
  189. public final XtextResource getResource(InputStream in, URI uri) throws Exception {
  190. return getResourceAndExpect(in, uri, 0);
  191. }
  192. public final XtextResource getResourceAndExpect(InputStream in, URI uri, int expectedErrors) throws Exception {
  193. XtextResource resource = doGetResource(in, uri);
  194. if (expectedErrors != UNKNOWN_EXPECTATION) {
  195. if (expectedErrors == EXPECT_ERRORS)
  196. assertFalse(resource.getErrors().toString(), resource.getErrors().isEmpty());
  197. else
  198. assertEquals(resource.getErrors().toString(), expectedErrors, resource.getErrors().size());
  199. }
  200. for(Diagnostic d: resource.getErrors()) {
  201. if (d instanceof ExceptionDiagnostic)
  202. fail(d.getMessage());
  203. }
  204. for(Diagnostic d: resource.getWarnings())
  205. System.out.println("Resource Warning: "+d);
  206. return resource;
  207. }
  208. protected XtextResource doGetResource(InputStream in, URI uri) throws Exception {
  209. XtextResourceSet rs = get(XtextResourceSet.class);
  210. rs.setClasspathURIContext(getClass());
  211. XtextResource resource = (XtextResource) getResourceFactory().createResource(uri);
  212. rs.getResources().add(resource);
  213. resource.load(in, null);
  214. EcoreUtil.resolveAll(resource);
  215. return resource;
  216. }
  217. protected final CompositeNode getRootNode(InputStream model) throws Exception {
  218. XtextResource resource = getResource(model);
  219. return getRootNode(resource);
  220. }
  221. protected final CompositeNode getRootNodeAndExpect(InputStream model, int errors) throws Exception {
  222. XtextResource resource = getResourceAndExpect(model, errors);
  223. return getRootNode(resource);
  224. }
  225. protected final CompositeNode getRootNode(XtextResource resource) {
  226. return resource.getParseResult().getRootNode();
  227. }
  228. protected final CompositeNode getRootNode(String model2) throws Exception {
  229. return getRootNode(new StringInputStream(model2));
  230. }
  231. protected final CompositeNode getRootNodeAndExpect(String model, int errors) throws Exception {
  232. return getRootNodeAndExpect(new StringInputStream(model), errors);
  233. }
  234. // Xtend helper methods
  235. protected void assertWithXtend(String left, String right, Object _this) {
  236. assertWithXtend(left + " != " + right, left, right, _this);
  237. }
  238. protected Object invokeWithXtend(String expression, Object _this) {
  239. XtendFacade f = getXtendFacade();
  240. f = f.cloneWithExtensions(getImportDeclarations() + "invoke(Object this) : " + expression + ";");
  241. return f.call("invoke", _this);
  242. }
  243. protected String[] importedExtensions() {
  244. return new String[0];
  245. }
  246. protected void assertWithXtend(String message, String left, String right, Object _this) {
  247. XtendFacade f = getXtendFacade();
  248. StringBuffer code = getImportDeclarations();
  249. code.append("__compare(Object this) : __left(this) == __right(this);__left(Object this) : " + left
  250. + "; __right(Object this) :" + right + ";");
  251. f = f.cloneWithExtensions(code.toString());
  252. Boolean result = (Boolean) f.call("__compare", _this);
  253. if (!result) {
  254. Object leftResult = f.call("__left", _this);
  255. Object rightResult = f.call("__right", _this);
  256. fail(message + " was : " + leftResult + "("
  257. + (leftResult != null ? leftResult.getClass().getSimpleName() : "") + ") != " + rightResult + "("
  258. + (leftResult != null ? leftResult.getClass().getSimpleName() : "") + ")");
  259. }
  260. }
  261. private StringBuffer getImportDeclarations() {
  262. StringBuffer code = new StringBuffer();
  263. for (String _import : importedExtensions()) {
  264. code.append("extension ").append(_import).append(";");
  265. }
  266. return code;
  267. }
  268. protected XtendFacade getXtendFacade() {
  269. ExecutionContextImpl ctx = new ExecutionContextImpl();
  270. ctx.registerMetaModel(new EmfRegistryMetaModel());
  271. return XtendFacade.create(ctx);
  272. }
  273. protected String readFileIntoString(String filePath) throws IOException {
  274. ClassLoader classLoader = getClass().getClassLoader();
  275. URL url = classLoader.getResource(filePath);
  276. if (url == null) {
  277. fail("Could not read resource: '" + filePath + "'. Is your file system case sensitive?");
  278. } else {
  279. if(!new File(url.getPath()).getCanonicalPath().endsWith(filePath))
  280. throw new RuntimeException(filePath + ":\n" +
  281. "The file does not exist exactly as it was named.\n" +
  282. "The test is likely to cause trouble on the build server.\n" +
  283. "Is your filesystem case insensitive? Please verify the spelling.");
  284. InputStream resourceAsStream = classLoader.getResourceAsStream(filePath);
  285. if (resourceAsStream == null) {
  286. fail("Could not read resource: '" + filePath + "'. Is your file system case sensitive?");
  287. } else {
  288. byte[] buffer = new byte[2048];
  289. int bytesRead = 0;
  290. StringBuffer b = new StringBuffer();
  291. do {
  292. bytesRead = resourceAsStream.read(buffer);
  293. if (bytesRead != -1)
  294. b.append(new String(buffer, 0, bytesRead));
  295. } while (bytesRead != -1);
  296. String model = b.toString();
  297. return model;
  298. }
  299. }
  300. throw new IllegalStateException("May not happen, but helps to suppress false positives in eclipse' control flow analysis.");
  301. }
  302. public static final class Keys {
  303. private static final TypeLiteral<Provider<XtextResourceSet>> resourceSetLiteral = new TypeLiteral<Provider<XtextResourceSet>>(){
  304. };
  305. public static final Key<Provider<XtextResourceSet>> RESOURCE_SET_KEY = Key.get(resourceSetLiteral);
  306. }
  307. }