use of org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues 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);
}
use of org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues 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");
}
use of org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues 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;
}
}
}
use of org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues in project n4js by eclipse.
the class ContentAssistXpectMethod method contentAssistList.
/*-
contentAssistList at ’a.<|>methodA’ display ’methodA2’ --> ’methodA2(): any - A’
contentAssistList at 'a.<|>methodA' proposals --> <$objectProposals>, methodA2
contentAssistList at 'a.<|>methodA' proposals --> <$objectProposals>, methodA2
contentAssistList at 'a.<|>methodA' proposals --> methodA, methodA2
contentAssistList at 'a.<|>methodA' proposals contains --> methodA2
contentAssistList at 'a.<|>methodA' proposals exactly --> methodA, methodA2
contentAssistList at 'a.<|>methodA' proposals not --> methodB
contentAssistList at 'a.<|>methodA' proposals ordered --> methodA, methodA2
contentAssistList at 'a.<|>methodA' proposals unordered --> methodA2, methodA
contentAssistList at 'a.<|>methodA' display 'methodA2' --> 'methodA2(): any - A'
contentAssistList kind 'smart' at 'a.<|>methodA' display 'methodA2' --> 'methodA2(): any - A'
kind offset checkType selected mode
arg4 arg2 arg3 arg5 arg6
*/
/**
* Compares the expected list of expected display strings with the actual computed one by the proposal provider.
*
* @param expect
* injected from right hand side - a list expected display strings
* @param resource
* injected - the resource under test
* @param offset
* arg2 - the offset of where to invoke content assist given as string matching next line with cursor
* position
* @param checkType
* arg3 - one of {proposals | display }
* @param kind
* arg4 - contentAssist - cycling: current kind like 'n4js'(default) or 'recommenders'
* @param selected
* arg5 - chosen selection form the proposal list
* @param mode
* arg6 - depending on checkTye: apply->{insert(default)|override}, proposals->{contains,
* exactly(default), not}
* @param orderMod
* arg7 - for proposal-modes contains/exactly there are two mode available{ordered, unordered(default)}
* @throws Exception
* some exception
*/
@Xpect
@ParameterParser(syntax = "( ('kind' arg4=STRING)? 'at' (arg2=STRING (arg3=ID (arg5=STRING)? (arg6=ID (arg7=ID)? )? )? )? )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void contentAssistList(// arg0
@CommaSeparatedValuesExpectation(quoted = true) ICommaSeparatedValuesExpectation expect, // arg1
@ThisResource XtextResource resource, // arg2 //@ThisOffset is obsolete
RegionWithCursor offset, // arg3
String checkType, // arg4
String kind, // arg5
String selected, // arg6
String mode, // arg7
String orderMod, ISetupInitializer<XpEnvironmentData> uiTestRunInit) throws Exception {
XpEnvironmentData xpEnvData = new XpEnvironmentData();
uiTestRunInit.initialize(xpEnvData);
xpEnvData.setResourceUnderTest(resource);
// Expansion of Variables. This changes the original expectation:
CommaSeparatedValuesExpectationImpl csvE = (CommaSeparatedValuesExpectationImpl) expect;
Pair<CommaSeparatedValuesExpectationImpl, CharSequence> exptectationAndText = expandVariables(csvE, xpEnvData);
CommaSeparatedValuesExpectationImpl expectation = exptectationAndText.getKey();
CharSequence expectedText = exptectationAndText.getValue();
// System.out.println("---|" + expectedText + "|---");
List<String> proposals = getProposalDisplayStrings(resource, offset, kind);
if (("display").equals(checkType)) {
// TODO check original code, seems like errors wehn porting
// expectation exactly one string:
// pick the proposal, test that only one is Picked && verify with expectation.
List<String> candidates = proposals.stream().filter(p -> p.contains(selected)).collect(Collectors.toList());
if (candidates.size() > 1) {
StringBuilder sb = new StringBuilder();
sb.append("more then one proposal matches the selection '").append(selected).append("' matches:[");
candidates.forEach(m -> sb.append(m).append(","));
sb.append("]");
throw new RuntimeException(sb.toString());
}
if (candidates.size() == 0) {
StringBuilder sb = new StringBuilder();
sb.append("nothing matches the selection '").append(selected).append("' available are [");
candidates.forEach(m -> sb.append(m).append(","));
sb.append("]");
throw new RuntimeException(sb.toString());
}
// exactly one:
expectation.assertEquals(candidates);
return;
} else if ("proposals".equals(checkType)) {
// order-mode, default is 'unordered'
boolean ordered = ("ordered" == orderMod || "ordered" == mode);
if (mode == null) {
if (ordered) {
assertExactlyOrdered(proposals, separateOnCommaAndQuote(expectedText), expectation);
} else {
assertExactly(proposals, separateOnCommaAndQuote(expectedText), expectation);
}
return;
}
switch(mode) {
case "":
// just in case mode is default, then orderMod gets assigned to mode
case "ordered":
// just in case mode is default, then orderMod gets assigned to mode
case "unordered":
case // default case.
"exactly":
if (ordered) {
assertExactlyOrdered(proposals, separateOnCommaAndQuote(expectedText), expectation);
} else {
assertExactly(proposals, separateOnCommaAndQuote(expectedText), expectation);
}
return;
case "contains":
{
if (ordered) {
assertContainingMatchAllOrdered(proposals, separateOnCommaAndQuote(expectedText), expectation);
} else {
assertContainingMatchAll(proposals, separateOnCommaAndQuote(expectedText), expectation);
}
return;
}
case "not":
// ordered / unordered doesn't apply here
assertNoMatch(proposals, separateOnCommaAndQuote(expectedText), expectation);
return;
default:
throw new RuntimeException("unrecognized mode for proposal-test : '" + mode + "'");
}
} else {
throw new UnsupportedOperationException("unrecognized checktype: '" + checkType + "'");
}
}
use of org.eclipse.xpect.xtext.lib.tests.ValidationTestModuleSetup.ConsumedIssues in project n4js by eclipse.
the class ContentAssistXpectMethod method contentAssist.
/*-
contentAssist at ’a.<|>methodA’ ’methodA2’ --> a.methodA2() <|>methodA
contentAssist at ’a.<|><[>methodA<]>’ ’methodA2’ override --> a.methodA2()<|>
contentAssist at ’a.methodA’ ’methodA2’ --> a.methodA2() <|>methodA
contentAssist at ’var A<|> a’ ’A - import’ ---
contentAssist at 'a.<|>methodA' 'methodA2' --> a.methodA2()<|>methodA
contentAssist at 'a.<|>methodA' 'methodA2' insert --> a.methodA2()<|>methodA
contentAssist at 'a.<|>methodA' 'methodA2' override --> a.methodA2()<|>
contentAssist kind 'smart' at '<a|>methodA' 'methodA2' ---
kind offset selected mode
arg3 arg2 arg4 arg5
*/
/**
* Application of a content assist. The right hand side describes the expected modifications.
*
* Up to now only single-line changes are supported.
*
* @param expectation
* injected Applicaiton
* @param resource
* injected xtext resource
* @param offset
* parsed arg2 - Cursorposition and Selection
* @param kind
* parsed arg3 - named kind of assistence-provider 'recommenders',...
* @param selected
* parsed arg4 - string of things to select in proposal list.
* @param mode
* parsed arg5 - mode modifier
* @throws Exception
* in junit-error case
*/
@Xpect
@ParameterParser(syntax = "( ('kind' arg3=STRING)? 'at' (arg2=STRING ('apply' arg4=STRING)? (arg5=ID)? )? )?")
@ConsumedIssues({ Severity.INFO, Severity.ERROR, Severity.WARNING })
public void contentAssist(// arg0
IStringExpectation expectation, // arg1
@ThisResource XtextResource resource, // arg2 //@ThisOffset is obsolete
RegionWithCursor offset, // arg3
String kind, // arg4
String selected, // arg5
String mode) throws Exception {
N4ContentAssistProcessorTestBuilder fixture = n4ContentAssistProcessorTestBuilderHelper.createTestBuilderForResource(resource);
ICompletionProposal proposal = exactlyMatchingProposal(offset, fixture, selected);
String before = resource.getParseResult().getRootNode().getText();
// apply:
// so working with the fixture cannot get any selection information since these are mocked away.
IXtextDocument document = fixture.getDocument(XtextResourceCleanUtil.cleanXtextResource(resource), before);
Optional<String> optionalMode = Optional.ofNullable(mode);
if (optionalMode.isPresent() && optionalMode.get().trim() == "override") {
// TODO mode override: needs to have a real selectionprovider in the fixture.
// currently there is a mockup which doesn't support selection
// see org.eclipse.xtext.ui.testing.ContentAssistProcessorTestBuilder.getSourceViewer(String,
// IXtextDocument)
// val sv = fixture.getSourceViewer(null, document)
// sv.selectionProvider.selection = new TextSelection(..)
}
String after = applyProposal(proposal, document);
// Expecting change only in single line:
ChangeInfo changedLines = extractSingleChangedLine(before, after);
if (changedLines.isMoreThanOne()) {
throw new AssertionError("more then one line changed: " + changedLines.asString());
} else if (changedLines.isEmpty()) {
throw new AssertionError("Nothing changed.");
}
String exp = changedLines.first().getAfter();
Point selection = proposal.getSelection(document);
if (selection != null) {
IExpectationRegion region = ((AbstractExpectation) expectation).getRegion();
if (CursorMarkerHelper.exists(region.getRegionText(), CursorMarkerHelper.markerCursor)) {
int newPos = selection.x - changedLines.first().getAfterOffset();
exp = new StringBuilder(exp).insert(newPos, CursorMarkerHelper.markerCursor).toString();
}
}
// Single changed line:
expectation.assertEquals(exp);
// TODO up to now this only removes the locations for the cursor but doesn't check the location.
// TODO multilines must be supported.
// // before = replaceXPECT(before);
// // after = replaceXPECT(after);
// expectation.assertEquals(after)
// expectation.assertDiffEquals("a", "b - not implemented yet")
}
Aggregations