Search in sources :

Example 1 with N4ContentAssistProcessorTestBuilder

use of org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilder in project n4js by eclipse.

the class ProposalXpectMethod method exactlyMatchingProposal.

/**
 * Searches for the proposal matching to selected.
 *
 * Throws exception if there are more then one or no proposals matching 'selected' found.
 */
private ICompletionProposal exactlyMatchingProposal(RegionWithCursor offset, N4ContentAssistProcessorTestBuilder fixture, String selected) {
    ICompletionProposal[] computeCompletionProposals = allProposalsAt(offset, fixture);
    List<ICompletionProposal> candidates = Arrays.stream(computeCompletionProposals).filter(proposal -> proposal.getDisplayString().contains(selected)).collect(Collectors.toList());
    if (candidates.size() > 1) {
        throw new AssertionFailedError("The selection of contentassist is not precise enough more then one assist matched the selection '" + selected + "': " + asString2(candidates) + " Please be more precise.");
    } else if (candidates.size() < 1) {
        throw new AssertionFailedError("No content assist matching the selection '" + selected + "' found. Available are " + asString2(Arrays.asList(computeCompletionProposals)));
    }
    ICompletionProposal proposal = candidates.get(0);
    return proposal;
}
Also used : VarDef(org.eclipse.n4js.xpect.config.VarDef) Arrays(java.util.Arrays) URI(org.eclipse.emf.common.util.URI) ThisResource(org.eclipse.xpect.xtext.lib.setup.ThisResource) Inject(com.google.inject.Inject) ICommaSeparatedValuesExpectation(org.eclipse.xpect.expectation.ICommaSeparatedValuesExpectation) IStringDiffExpectation(org.eclipse.xpect.expectation.IStringDiffExpectation) ContentAssistXpectMethod(org.eclipse.n4js.xpect.ui.methods.contentassist.ContentAssistXpectMethod) AtomicReference(java.util.concurrent.atomic.AtomicReference) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) XtextResourceCleanUtil(org.eclipse.n4js.xpect.ui.common.XtextResourceCleanUtil) Logger(org.apache.log4j.Logger) Lists(com.google.common.collect.Lists) Config(org.eclipse.n4js.xpect.config.Config) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) TemplateProposal(org.eclipse.jface.text.templates.TemplateProposal) N4ContentAssistProcessorTestBuilder(org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilder) QuickFixXpectMethod(org.eclipse.n4js.xpect.ui.methods.quickfix.QuickFixXpectMethod) XpectImport(org.eclipse.xpect.XpectImport) ParameterParser(org.eclipse.xpect.parameter.ParameterParser) CommaSeparatedValuesExpectation(org.eclipse.xpect.expectation.CommaSeparatedValuesExpectation) IParseResult(org.eclipse.xtext.parser.IParseResult) XtextResource(org.eclipse.xtext.resource.XtextResource) StringDiffExpectation(org.eclipse.xpect.expectation.StringDiffExpectation) IUnitOfWork(org.eclipse.xtext.util.concurrent.IUnitOfWork) N4JSOffsetAdapter(org.eclipse.n4js.xpect.common.N4JSOffsetAdapter) QuickFixTestHelper.asString2(org.eclipse.n4js.xpect.ui.common.QuickFixTestHelper.asString2) RegionWithCursor(org.eclipse.n4js.xpect.ui.methods.contentassist.RegionWithCursor) EcoreUtil(org.eclipse.emf.ecore.util.EcoreUtil) N4ContentAssistProcessorTestBuilderHelper(org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilderHelper) AssertionFailedError(junit.framework.AssertionFailedError) Display(org.eclipse.swt.widgets.Display) IParser(org.eclipse.xtext.parser.IParser) Collectors(java.util.stream.Collectors) XpectCommentRemovalUtil(org.eclipse.n4js.xpect.common.XpectCommentRemovalUtil) List(java.util.List) Provider(com.google.inject.Provider) StringReader(java.io.StringReader) XpEnvironmentData(org.eclipse.n4js.xpect.config.XpEnvironmentData) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Xpect(org.eclipse.xpect.runner.Xpect) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) AssertionFailedError(junit.framework.AssertionFailedError)

Example 2 with N4ContentAssistProcessorTestBuilder

use of org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilder 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 N4ContentAssistProcessorTestBuilder

use of org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilder in project n4js by eclipse.

the class OrganizeImportXpectMethod method organizeImports.

/**
 * Give the result as a multiline diff. If cancellation due to multiple possible resolution is expected, provide the
 * expected Exception with 'XPECT organizeImports ambiguous "Exception-Message" -->'.
 *
 * If the parameter is not provided, always the first computed solution in the list will be taken
 *
 * @param ambiguous
 *            - String Expectation in {@link BreakException}
 */
@ParameterParser(syntax = "('ambiguous' arg0=STRING)?")
@Xpect
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void organizeImports(// arg0
String ambiguous, @StringDiffExpectation(whitespaceSensitive = false, allowSingleSegmentDiff = false, allowSingleLineDiff = false) IStringDiffExpectation expectation, @ThisResource XtextResource resource) throws Exception {
    logger.info("organize imports ...");
    boolean bAmbiguityCheck = ambiguous != null && ambiguous.trim().length() > 0;
    Interaction iaMode = bAmbiguityCheck ? Interaction.breakBuild : Interaction.takeFirst;
    try {
        if (expectation == null) /* || expectation.isEmpty() */
        {
            // Cannot access the region which could be asked for it's length.
            throw new AssertionFailedError("The test is missing a diff: // XPECT organizeImports --> [old string replaced|new string expected] ");
        }
        // capture text for comparison:
        String beforeApplication = resource.getParseResult().getRootNode().getText();
        N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper.createTestBuilderForResource(resource);
        IXtextDocument xtextDoc = fixture.getDocument(resource, beforeApplication);
        // 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);
        }
        // Calling organize imports
        Display.getDefault().syncExec(() -> imortsOrganizer.unsafeOrganizeDocument(xtextDoc, iaMode));
        if (bAmbiguityCheck) {
            // should fail if here
            assertEquals("Expected ambiguous resolution to break the organize import command.", ambiguous, "");
        }
        // checking that no errors are left.
        String textAfterApplication = xtextDoc.get();
        // compare with expectation, it's a multiline-diff expectation.
        String before = XpectCommentRemovalUtil.removeAllXpectComments(beforeApplication);
        String after = XpectCommentRemovalUtil.removeAllXpectComments(textAfterApplication);
        expectation.assertDiffEquals(before, after);
    } catch (Exception exc) {
        if (exc instanceof RuntimeException && exc.getCause() instanceof BreakException) {
            String breakMessage = exc.getCause().getMessage();
            assertEquals(ambiguous, breakMessage);
        } else {
            throw exc;
        }
    }
}
Also used : Interaction(org.eclipse.n4js.ui.organize.imports.Interaction) 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) BreakException(org.eclipse.n4js.ui.organize.imports.BreakException) N4ContentAssistProcessorTestBuilder(org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilder) ResourceSet(org.eclipse.emf.ecore.resource.ResourceSet) AssertionFailedError(junit.framework.AssertionFailedError) BreakException(org.eclipse.n4js.ui.organize.imports.BreakException) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) ConsumedIssues(org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Example 4 with N4ContentAssistProcessorTestBuilder

use of org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilder in project n4js by eclipse.

the class ProposalXpectMethod method proposalChange.

// @formatter:off
/**
 * Test the application of the given content assist entry. After applying the content assist there should be the
 * expected diff produced when comparing the document before and after applying the content assist.
 *
 * The diff has the following semantics:
 *
 * "  ": (whitespace) nothing changed
 * "+ ": line was added
 * "- ": line was deleted
 * "| ": line was modified, displayed as [oldText|newText]
 *
 * If the given expected content assist entry cannot be found, an error message is inserted at the offset resulting
 * in expectation mismatch and so also to a failing test.
 *
 * Also clf.
 * https://github.com/meysholdt/Xpect/tree/master/org.eclipse.xtext.example.domainmodel.xpect.tests/src/org
 * /eclipse/xtext/example/domainmodel/xpect/tests/modify for some more examples.
 *
 * /\* XPECT proposalChange 'methodA2' at 'methodA' ---
 *   (...)
 *  }
 * }
 * var A a = new A();
 * |a.[methodA|methodA2methodA]
 * --- *\/
 *
 * Please note, that the comparison always contains also some lines around the line that contains the diff.
 * Xpect currently doesn't allow to configure the number of those lines.
 *
 * @param expectation
 *            the expected diff comparing the document before and after applying the content assist
 * @param resource
 *            the resource under test
 * @param arg2
 *            the offset of where to invoke content assist (note: it must be named arg2 as Xpect injects the
 *            parameter values by position)
 * @param arg3
 *            the content assist entry to select
 * @throws Exception
 *             some exception
 */
// @formatter:on
@ParameterParser(syntax = "(arg3=STRING 'at' arg2=STRING)?")
@Xpect
public void proposalChange(@StringDiffExpectation IStringDiffExpectation expectation, @ThisResource XtextResource resource, /* @ThisOffset int */
RegionWithCursor arg2, String arg3) throws Exception {
    // val int offset = arg2;
    RegionWithCursor offset = arg2;
    String text = arg3;
    // println("proposal change with offset="+arg2+" selection="+arg3)
    N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper.createTestBuilderForResource(resource);
    ICompletionProposal proposal = exactlyMatchingProposal(offset, fixture, text);
    String before = resource.getParseResult().getRootNode().getText();
    if (proposal != null) {
        IXtextDocument document = fixture.getDocument(XtextResourceCleanUtil.cleanXtextResource(resource), before);
        String after = applyProposal(proposal, document);
        before = XpectCommentRemovalUtil.removeAllXpectComments(before);
        after = XpectCommentRemovalUtil.removeAllXpectComments(after);
        expectation.assertDiffEquals(before, after);
    }
}
Also used : RegionWithCursor(org.eclipse.n4js.xpect.ui.methods.contentassist.RegionWithCursor) ICompletionProposal(org.eclipse.jface.text.contentassist.ICompletionProposal) N4ContentAssistProcessorTestBuilder(org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilder) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument) Xpect(org.eclipse.xpect.runner.Xpect) ParameterParser(org.eclipse.xpect.parameter.ParameterParser)

Aggregations

N4ContentAssistProcessorTestBuilder (org.eclipse.n4js.xpect.ui.methods.contentassist.N4ContentAssistProcessorTestBuilder)4 ParameterParser (org.eclipse.xpect.parameter.ParameterParser)4 Xpect (org.eclipse.xpect.runner.Xpect)4 IXtextDocument (org.eclipse.xtext.ui.editor.model.IXtextDocument)4 ICompletionProposal (org.eclipse.jface.text.contentassist.ICompletionProposal)3 XtextResource (org.eclipse.xtext.resource.XtextResource)3 AssertionFailedError (junit.framework.AssertionFailedError)2 ResourceSet (org.eclipse.emf.ecore.resource.ResourceSet)2 RegionWithCursor (org.eclipse.n4js.xpect.ui.methods.contentassist.RegionWithCursor)2 ThisResource (org.eclipse.xpect.xtext.lib.setup.ThisResource)2 Lists (com.google.common.collect.Lists)1 Inject (com.google.inject.Inject)1 Provider (com.google.inject.Provider)1 StringReader (java.io.StringReader)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 List (java.util.List)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 Collectors (java.util.stream.Collectors)1 Logger (org.apache.log4j.Logger)1