use of org.eclipse.xtext.validation.Issue in project n4js by eclipse.
the class XpectN4JSES5GeneratorHelper method registerErrors.
private boolean registerErrors(Resource dep, StringBuilder errorResult) {
boolean hasErrors = false;
List<Issue> issues = resourceValidator.validate(dep, CheckMode.ALL, CancelIndicator.NullImpl);
List<Issue> errorIssues = new ArrayList<>();
for (Issue issue : issues) {
if (Severity.ERROR == issue.getSeverity()) {
errorIssues.add(issue);
}
}
hasErrors = !errorIssues.isEmpty();
if (hasErrors) {
errorResult.append("Couldn't compile resource " + dep.getURI() + " because it contains errors: ");
for (Issue errorIssue : errorIssues) {
errorResult.append(NL + errorIssue.getMessage() + " at line " + errorIssue.getLineNumber());
}
}
return hasErrors;
}
use of org.eclipse.xtext.validation.Issue in project n4js by eclipse.
the class N4JSValidationTestHelper method assertNoIssuesExcept.
/**
* Asserts the given model to not have any issues except the ones specified by the exception issue codes parameter.
*
* @param model
* The model
* @param exceptionIssueCodes
* Issue codes which should be ignored
*/
public void assertNoIssuesExcept(EObject model, String... exceptionIssueCodes) {
Resource resource = model.eResource();
final List<Issue> issues = validate(resource);
if (removeIssuesWithCode(issues, exceptionIssueCodes).size() > 0) {
fail("Expected no issues, but got :" + getIssuesAsString(resource, issues, new StringBuilder()));
}
}
use of org.eclipse.xtext.validation.Issue in project n4js by eclipse.
the class QuickFixXpectMethod method quickFix.
/**
* Choose quick fix and apply
*
* @param expectation
* from right hand side - expected changes to code, especially cursor position.
* @param resource
* injected resource under test
* @param offset
* parsed arg2 offset cursor position
* @param selected
* parsed arg3 - chosen quick fix to apply
* @param mode
* parsed arg4 if 'fileValid' additional validation check after application
*
* @param specifiedResourcePath
* Specifies the relative path of the resource in which the quickfix applies
*
* @param reparseResource
* Specifies if the resource is reset after application of the quick fix or not.
*
* Note: In case of passing false the caller has to reset the resource on its own as it is essential for
* the following quick fix xpect method calls.
*
* @throws Exception
* in test failure.
*/
private void quickFix(IStringDiffExpectation expectation, XtextResource resource, RegionWithCursor offset, String selected, String mode, String specifiedResourcePath, Multimap<Integer, Issue> offset2issue, boolean reparseResource) throws Exception {
Optional<XtextEditor> editor = Optional.empty();
// Optional<XtextEditor> specifiedResourceEditor = Optional.empty();
try {
List<IssueResolution> resolutions = collectAllResolutions(resource, offset, offset2issue);
IssueResolution res = QuickFixTestHelper.selectSingleOrFail(resolutions, selected);
String beforeApplication;
URI targetResourceUri = resource.getURI();
// Get the content of the specified resource
if (specifiedResourcePath != null && !specifiedResourcePath.isEmpty()) {
URI specifiedURI = resource.getURI().trimSegments(1).appendSegments(specifiedResourcePath.split("/"));
targetResourceUri = specifiedURI;
beforeApplication = getContentForResourceUri(specifiedURI);
} else {
// capture text for comparison from disk:
//
beforeApplication = getContentForResourceUri(resource.getURI());
// beforeApplication = resource.getParseResult().getRootNode().getText();
}
Display.getDefault().syncExec(() -> res.apply());
// obtain new text from editor and reparse it into the resource, otherwise the resource is outdated.
// necessary if the resource is further used in compilation after this QF-Application.
editor = EditorsUtil.openXtextEditor(targetResourceUri, N4JSActivator.ORG_ECLIPSE_N4JS_N4JS);
assertTrue("No editor for provided resource " + targetResourceUri.path(), editor.isPresent());
String textAfterApplication = editor.get().getDocument().get();
// as it would replace the test code with the specified resource
if (specifiedResourcePath == null || specifiedResourcePath.isEmpty()) {
// reparse the text into the resource.
resource.reparse(textAfterApplication);
// in case of @IssuesByLine our Validator is of type:
TestingResourceValidator trVal = (TestingResourceValidator) resource.getResourceServiceProvider().getResourceValidator();
// Check for no other Issues
if ("fileValid".equals(mode)) {
List<Issue> remainingIssues = trVal.validateDelegate(resource, CheckMode.ALL, CancelIndicator.NullImpl, null);
assertEquals("Expecting all issues resolved, but got still left: " + remainingIssues, 0, remainingIssues.size());
}
}
if (reparseResource) {
// Reset resource after quick fix application
resource.reparse(getContentForResourceUri(resource.getURI()));
}
if (expectation != null) {
// TODO assert cursor position after application.
String before = XpectCommentRemovalUtil.removeAllXpectComments(beforeApplication);
String after = XpectCommentRemovalUtil.removeAllXpectComments(textAfterApplication);
if ("whitespaceSensitive".equals(mode)) {
LineBasedTokenizer tokenizer = new LineBasedTokenizer();
expectation.assertDiffEquals(tokenizer.apply(before), tokenizer.apply(after), new WSAwareTokenAdapter());
} else {
expectation.assertDiffEquals(before, after);
}
}
} finally {
// TODO initial state aware context
/*
* If editor was created it should be closed, but if it was opened before running tests, we should only undo
* changes (and get rid of dirty state), but we should not close editor
*/
editor.ifPresent(e -> EditorsUtil.forceCloseAllEditors());
// editor.ifPresent(e -> EditorsUtil.forceCloseEditor(e));
}
}
use of org.eclipse.xtext.validation.Issue 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.xtext.validation.Issue in project n4js by eclipse.
the class QuickFixXpectMethod method collectAllResolutions.
/**
* CollectAll resolutions under the cursor at offset.
*/
List<IssueResolution> collectAllResolutions(XtextResource resource, RegionWithCursor offset, Multimap<Integer, Issue> offset2issue) {
EObject script = resource.getContents().get(0);
ICompositeNode scriptNode = NodeModelUtils.getNode(script);
ILeafNode offsetNode = NodeModelUtils.findLeafNodeAtOffset(scriptNode, offset.getGlobalCursorOffset());
int offStartLine = offsetNode.getTotalStartLine();
List<Issue> allIssues = QuickFixTestHelper.extractAllIssuesInLine(offStartLine, offset2issue);
List<IssueResolution> resolutions = Lists.newArrayList();
for (Issue issue : allIssues) {
if (issue.getLineNumber() == offsetNode.getStartLine() && issue.getLineNumber() <= offsetNode.getEndLine()) {
Display.getDefault().syncExec(() -> resolutions.addAll(quickfixProvider.getResolutions(issue)));
}
}
return resolutions;
}
Aggregations