Search in sources :

Example 1 with Xpect

use of org.eclipse.xpect.runner.Xpect in project n4js by eclipse.

the class HyperlinkXpectMethod method hyperlinks.

/**
 * @param expectation
 *            a list of expected URIs to jump to by this hyperlink
 * @param resource
 *            the resource under test
 * @param region
 *            the offset where hyperlinking should be invoked
 * @throws Exception
 *             some exceptions
 */
@ParameterParser(syntax = "('at' arg2=STRING)?")
@Xpect
public void hyperlinks(// arg0
@CommaSeparatedValuesExpectation ICommaSeparatedValuesExpectation expectation, // arg1
@ThisResource XtextResource resource, // arg2
RegionWithCursor region) throws Exception {
    ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper.createTestBuilderForResource(resource);
    String currentModelToParse = resource.getParseResult().getRootNode().getText();
    IXtextDocument xtextDocument = fixture.getDocument(resource, currentModelToParse);
    // in case of cross-file hyperlinks, we have to make sure the target resources are fully resolved
    final ResourceSet resSet = resource.getResourceSet();
    for (Resource currRes : new ArrayList<>(resSet.getResources())) N4JSResource.postProcess(currRes);
    ITextViewer sourceViewer = fixture.getSourceViewer(currentModelToParse, xtextDocument);
    IHyperlink[] hyperlinks = hyperlinkDetector.detectHyperlinks(sourceViewer, new Region(region.getGlobalCursorOffset(), 0), true);
    // cleaned up resource, otherwise #createTestBuilder() above will fail next time this method is called
    XtextResourceCleanUtil.cleanXtextResource(resource);
    ArrayList<String> result = Lists.newArrayList();
    if (hyperlinks != null) {
        for (IHyperlink hyperlink : hyperlinks) {
            result.add(getTargetDescription(resource, hyperlink));
        }
    }
    expectation.assertEquals(result);
}
Also used : ContentAssistProcessorTestBuilder(org.eclipse.xtext.ui.testing.ContentAssistProcessorTestBuilder) IHyperlink(org.eclipse.jface.text.hyperlink.IHyperlink) ThisResource(org.eclipse.xpect.xtext.lib.setup.ThisResource) XtextResource(org.eclipse.xtext.resource.XtextResource) N4JSResource(org.eclipse.n4js.resource.N4JSResource) Resource(org.eclipse.emf.ecore.resource.Resource) ArrayList(java.util.ArrayList) Region(org.eclipse.jface.text.Region) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) ITextViewer(org.eclipse.jface.text.ITextViewer) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 2 with Xpect

use of org.eclipse.xpect.runner.Xpect in project n4js by eclipse.

the class ProposalXpectMethod method checkProposals.

/**
 * Iterates over all proposed completion entries at the given offset and checks whether its application would cause
 * validation issues in the resource.
 *
 * @param expectation
 *            the expected proposals causing validation errors
 * @param resource
 *            the resource under test
 * @param offset
 *            the offset of where to invoke content assist (note: it must be named arg2 as Xpect injects the
 *            parameter values by position)
 * @throws Exception
 *             some exception
 */
@ParameterParser(syntax = "'at' arg2=STRING")
@Xpect
public void checkProposals(@CommaSeparatedValuesExpectation ICommaSeparatedValuesExpectation expectation, @ThisResource XtextResource resource, RegionWithCursor offset) throws Exception {
    N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper.createTestBuilderForResource(resource);
    ICompletionProposal[] computeCompletionProposals = allProposalsAt(offset, fixture);
    List<String> proposalsWithError = Lists.newArrayList();
    for (int proposal = 0; proposal < computeCompletionProposals.length; proposal++) {
        fixture = fixture.reset();
        String content = resource.getParseResult().getRootNode().getText();
        fixture = fixture.append(content);
        IXtextDocument document = fixture.getDocument(resource, content);
        int index = proposal;
        String newContent = applyProposal(computeCompletionProposals[index], document);
        IXtextDocument newXtextDocument = fixture.getDocument(getNewResource(newContent, resource.getURI()), content);
        newXtextDocument.readOnly(new IUnitOfWork<Object, XtextResource>() {

            @Override
            public Object exec(XtextResource state) throws Exception {
                EcoreUtil.resolveAll(state);
                if (!state.getErrors().isEmpty()) {
                    proposalsWithError.add(computeCompletionProposals[index].getDisplayString());
                } else if (!state.validateConcreteSyntax().isEmpty()) {
                    proposalsWithError.add(computeCompletionProposals[index].getDisplayString());
                }
                return null;
            }
        });
    }
    expectation.assertEquals(proposalsWithError);
}
Also used : ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) N4ContentAssistProcessorTestBuilder(org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilder) XtextResource(org.eclipse.xtext.resource.XtextResource) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 3 with Xpect

use of org.eclipse.xpect.runner.Xpect in project n4js by eclipse.

the class QuickFixXpectMethod method quickFixList.

/*-
	contentAssistList kind 'smart' at 'a.<|>methodA'       display   'methodA2'            --> 'methodA2(): any - A'
	quickFix                       at 'a.<|>method'        apply     'methodA2'  fileValid --> a.<|>methodA2();
	                    kind        offset              checkType  selected    mode
	                                arg2                arg3       arg4        arg5
	 */
/**
 * Example: {@code // XPECT quickFixList  at 'a.<|>method' --> 'import A','do other things' }
 *
 * @param expectation
 *            comma separated strings, which are proposed as quick fix
 * @param resource
 *            injected xtext-file
 * @param offset
 *            cursor position at '<|>'
 * @param checkType
 *            'display': verify list of provided proposals comparing their user-displayed strings.
 * @param selected
 *            which proposal to pick
 * @param mode
 *            modus of operation
 * @param offset2issue
 *            mapping of offset(!) to issues.
 * @throws Exception
 *             if failing
 */
@Xpect
@ParameterParser(syntax = "('at' (arg2=STRING (arg3=ID  (arg4=STRING)?  (arg5=ID)? )? )? )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void quickFixList(// arg0
@CommaSeparatedValuesExpectation(quoted = true, ordered = true) ICommaSeparatedValuesExpectation expectation, // arg1
@ThisResource XtextResource resource, // arg2
RegionWithCursor offset, // arg3
String checkType, // arg4
String selected, // arg5
String mode, @IssuesByLine Multimap<Integer, Issue> offset2issue) throws Exception {
    List<IssueResolution> resolutions = collectAllResolutions(resource, offset, offset2issue);
    List<String> resolutionNames = Lists.newArrayList();
    for (IssueResolution resolution : resolutions) {
        resolutionNames.add(resolution.getLabel());
    }
    expectation.assertEquals(resolutionNames);
}
Also used : IssueResolution(org.eclipse.xtext.ui.editor.quickfix.IssueResolution) ConsumedIssues(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 4 with Xpect

use of org.eclipse.xpect.runner.Xpect in project n4js by eclipse.

the class QuickFixXpectMethod method quickFixAndRun.

/*-
	contentAssistList kind 'smart' at 'a.<|>methodA'       display   'methodA2'            --> 'methodA2(): any - A'
	quickFix                       at 'a.<|>method'        apply     'methodA2'  fileValid --> a.<|>methodA2();
	quickFixAndRun                 at 'a.<|>method'        apply     'methodHelloWorld' --> Hello World
	                        kind        offset             checkType  selected    mode
	                                    arg2                          arg3
	 */
/**
 * Apply quick fix, compile and run the result. Compares the generated stdout-result to the expectation on the right
 * hand side.
 *
 * @param expectation
 *            - expected output of running script, just stdout no error-stream. Expecting the error-stream to be
 *            empty.
 * @param resource
 *            - injected resource
 * @param offset
 *            - parsed arg2 - cursor position
 * @param selected
 *            - parsed arg3 - selection from list of expectations
 * @param offset2issue
 *            - injected Map of issues
 * @param init
 *            - injected xpect-initizalizer
 * @param fileSetupContext
 *            - injected xpect meta-info about file under test.
 * @throws Exception
 *             in failure case
 */
@Xpect
@ParameterParser(syntax = "('at' arg2=STRING)? ('apply'  arg3=STRING )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void quickFixAndRun(// arg0
@StringExpectation(caseSensitive = true) IStringExpectation expectation, // arg1
@ThisResource XtextResource resource, // arg2
RegionWithCursor offset, // arg3
String selected, @IssuesByLine Multimap<Integer, Issue> offset2issue, ISetupInitializer<Object> init, FileSetupContext fileSetupContext) throws Exception {
    try {
        long timeStart = System.currentTimeMillis();
        logger.info("Execution started: " + new Date(timeStart));
        // System.out.println(
        // "##-Qr-## we got it selected='" + selected + "' at " + offset + " in " + resource.toString() + "");
        String executionResult;
        ExecutionResult exRes = new ExecutionResult();
        ResourceTweaker resourceTweaker = resourceToTweak -> {
            try {
                quickFix(null, resourceToTweak, offset, selected, "fileValid", "", offset2issue, false);
            } catch (Exception e) {
                Exceptions.sneakyThrow(e);
            }
        };
        Display.getDefault().syncExec(() -> exRes.result = compileAndExecute(resource, init, fileSetupContext, resourceTweaker));
        executionResult = exRes.result;
        long timeEnd = System.currentTimeMillis();
        logger.info("Execution finished: " + new Date(timeEnd));
        logger.info("Execution took " + (timeEnd - timeStart + 0.0) / 1000.0 + " seconds.");
        expectation.assertEquals(executionResult);
        // Reset resource after quick fix application and code execution
        resource.reparse(getContentForResourceUri(resource.getURI()));
    } finally {
        logger.info("Closing all editors");
        EditorsUtil.forceCloseAllEditors();
    }
    logger.info("Successful End of Execution");
}
Also used : VarDef(org.eclipse.n4js.xpect.config.VarDef) EditorsUtil(org.eclipse.n4js.tests.util.EditorsUtil) Exceptions(org.eclipse.xtext.xbase.lib.Exceptions) ISetupInitializer(org.eclipse.xpect.setup.ISetupInitializer) Date(java.util.Date) IssueResolutionProvider(org.eclipse.xtext.ui.editor.quickfix.IssueResolutionProvider) Inject(com.google.inject.Inject) ICommaSeparatedValuesExpectation(org.eclipse.xpect.expectation.ICommaSeparatedValuesExpectation) IStringDiffExpectation(org.eclipse.xpect.expectation.IStringDiffExpectation) ILeafNode(org.eclipse.xtext.nodemodel.ILeafNode) N4JSActivator(org.eclipse.n4js.ui.internal.N4JSActivator) Logger(org.apache.log4j.Logger) Config(org.eclipse.n4js.xpect.config.Config) XtextEditor(org.eclipse.xtext.ui.editor.XtextEditor) ConsumedIssues(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues) StringDiffExpectation(org.eclipse.xpect.expectation.StringDiffExpectation) RegionWithCursor(org.eclipse.n4js.xpect.ui.methods.contentassist.RegionWithCursor) EObject(org.eclipse.emf.ecore.EObject) Display(org.eclipse.swt.widgets.Display) ICompositeNode(org.eclipse.xtext.nodemodel.ICompositeNode) IssueResolution(org.eclipse.xtext.ui.editor.quickfix.IssueResolution) TestingResourceValidator(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.TestingResourceValidator) List(java.util.List) XpEnvironmentData(org.eclipse.n4js.xpect.config.XpEnvironmentData) Path(org.eclipse.core.runtime.Path) Optional(java.util.Optional) Xpect(org.eclipse.xpect.runner.Xpect) CheckMode(org.eclipse.xtext.validation.CheckMode) ResourcesPlugin(org.eclipse.core.resources.ResourcesPlugin) URI(org.eclipse.emf.common.util.URI) ThisResource(org.eclipse.xpect.xtext.lib.setup.ThisResource) ResourceTweaker(org.eclipse.n4js.xpect.common.ResourceTweaker) StringExpectation(org.eclipse.xpect.expectation.StringExpectation) IssuesByLine(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.IssuesByLine) Multimap(com.google.common.collect.Multimap) NodeModelUtils(org.eclipse.xtext.nodemodel.util.NodeModelUtils) ValidationTestModuleSetup(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup) Lists(com.google.common.collect.Lists) CancelIndicator(org.eclipse.xtext.util.CancelIndicator) IFile(org.eclipse.core.resources.IFile) QuickFixTestHelper(org.eclipse.n4js.xpect.ui.common.QuickFixTestHelper) XpectImport(org.eclipse.xpect.XpectImport) ParameterParser(org.eclipse.xpect.parameter.ParameterParser) CommaSeparatedValuesExpectation(org.eclipse.xpect.expectation.CommaSeparatedValuesExpectation) GeneratorOption(org.eclipse.n4js.generator.GeneratorOption) XtextResource(org.eclipse.xtext.resource.XtextResource) N4JSOffsetAdapter(org.eclipse.n4js.xpect.common.N4JSOffsetAdapter) Severity(org.eclipse.xtext.diagnostics.Severity) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) XpectN4JSES5TranspilerHelper(org.eclipse.n4js.xpect.ui.common.XpectN4JSES5TranspilerHelper) XpectCommentRemovalUtil(org.eclipse.n4js.xpect.common.XpectCommentRemovalUtil) Issue(org.eclipse.xtext.validation.Issue) FileSetupContext(org.eclipse.xpect.xtext.lib.setup.FileSetupContext) ITokenAdapter(org.eclipse.xpect.expectation.IStringDiffExpectation.ITokenAdapter) Collections(java.util.Collections) IStringExpectation(org.eclipse.xpect.expectation.IStringExpectation) Assert.assertEquals(org.junit.Assert.assertEquals) SystemLoaderInfo(org.eclipse.n4js.runner.SystemLoaderInfo) ResourceTweaker(org.eclipse.n4js.xpect.common.ResourceTweaker) Date(java.util.Date) IOException(java.io.IOException) ConsumedIssues(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 5 with Xpect

use of org.eclipse.xpect.runner.Xpect in project n4js by eclipse.

the class ElementKeywordXpectMethod method elementKeyword.

/**
 * Test the element keyword of an element. Examples of element keyword are getter, setter, field etc.
 */
@ParameterParser(syntax = "('at' arg1=OFFSET)?")
@Xpect
public void elementKeyword(@StringExpectation IStringExpectation expectation, IEObjectCoveringRegion offset) {
    EObject context = offset.getEObject();
    // Identical behavior as in hover in the IDE! See class N4JSHoverProvider
    // Get the cross-referenced element at the offset.
    EObject element = offsetHelper.resolveCrossReferencedElementAt((XtextResource) context.eResource(), offset.getOffset());
    // If not a cross-reference element, use context instead
    if (element == null)
        element = context;
    String actual = calculateElementKeyword(element);
    expectation.assertEquals(actual);
}
Also used : EObject(org.eclipse.emf.ecore.EObject) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Aggregations

ParameterParser (org.eclipse.xpect.parameter.ParameterParser)30 Xpect (org.eclipse.xpect.runner.Xpect)30 EObject (org.eclipse.emf.ecore.EObject)11 ControlFlowElement (org.eclipse.n4js.n4JS.ControlFlowElement)9 LinkedList (java.util.LinkedList)6 IXtextDocument (org.eclipse.xtext.ui.editor.model.IXtextDocument)6 ConsumedIssues (org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues)5 ICrossEReferenceAndEObject (org.eclipse.xpect.xtext.lib.util.XtextOffsetAdapter.ICrossEReferenceAndEObject)5 XtextResource (org.eclipse.xtext.resource.XtextResource)5 URI (org.eclipse.emf.common.util.URI)4 ICompletionProposal (org.eclipse.jface.text.contentassist.ICompletionProposal)4 List (java.util.List)3 Resource (org.eclipse.emf.ecore.resource.Resource)3 N4JSResource (org.eclipse.n4js.resource.N4JSResource)3 ThisResource (org.eclipse.xpect.xtext.lib.setup.ThisResource)3 ICompositeNode (org.eclipse.xtext.nodemodel.ICompositeNode)3 Lists (com.google.common.collect.Lists)2 Inject (com.google.inject.Inject)2 ArrayList (java.util.ArrayList)2 Optional (java.util.Optional)2