### Question:
ScriptResource extends AbstractBrooklynRestResource implements ScriptApi { @SuppressWarnings("rawtypes") @Override public ScriptExecutionSummary groovy(HttpServletRequest request, String script) { log.info("Web REST executing user-supplied script"); if (log.isDebugEnabled()) { log.debug("Web REST user-supplied script contents:\n"+script); } Binding binding = new Binding(); binding.setVariable("mgmt", mgmt()); HttpSession session = request!=null ? request.getSession() : null; if (session!=null) { Map data = (Map) session.getAttribute(USER_DATA_MAP_SESSION_ATTRIBUTE); if (data==null) { data = new LinkedHashMap(); session.setAttribute(USER_DATA_MAP_SESSION_ATTRIBUTE, data); } binding.setVariable("data", data); Object last = session.getAttribute(USER_LAST_VALUE_SESSION_ATTRIBUTE); binding.setVariable("last", last); } GroovyShell shell = new GroovyShell(binding); OutputCapturingContext stdout = ThreadLocalPrintStream.stdout().captureTee(); OutputCapturingContext stderr = ThreadLocalPrintStream.stderr().captureTee(); Object value = null; Throwable problem = null; try { value = shell.evaluate(script); if (session!=null) session.setAttribute(USER_LAST_VALUE_SESSION_ATTRIBUTE, value); } catch (Throwable t) { log.warn("Problem in user-supplied script: "+t, t); problem = t; } finally { stdout.end(); stderr.end(); } if (log.isDebugEnabled()) { log.debug("Web REST user-supplied script completed:\n"+ (value!=null ? "RESULT: "+value.toString()+"\n" : "")+ (problem!=null ? "ERROR: "+problem.toString()+"\n" : "")+ (!stdout.isEmpty() ? "STDOUT: "+stdout.toString()+"\n" : "")+ (!stderr.isEmpty() ? "STDERR: "+stderr.toString()+"\n" : "")); } return new ScriptExecutionSummary( value!=null ? value.toString() : null, problem!=null ? problem.toString() : null, stdout.toString(), stderr.toString()); }  @SuppressWarnings("rawtypes") @Override ScriptExecutionSummary groovy(HttpServletRequest request, String script); static final String USER_DATA_MAP_SESSION_ATTRIBUTE; static final String USER_LAST_VALUE_SESSION_ATTRIBUTE; }### Answer:
@Test public void testGroovy() { ManagementContext mgmt = LocalManagementContextForTests.newInstance(); Application app = mgmt.getEntityManager().createEntity( EntitySpec.create(Application.class, RestMockApp.class) ); try { Entities.start(app, Collections.<Location>emptyList()); ScriptResource s = new ScriptResource(); s.setManagementContext(mgmt); ScriptExecutionSummary result = s.groovy(null, "def apps = []; mgmt.applications.each { println 'app:'+it; apps << it.id }; apps"); Assert.assertEquals(Collections.singletonList(app.getId()).toString(), result.getResult()); Assert.assertTrue(result.getStdout().contains("app:RestMockApp")); } finally { Entities.destroyAll(mgmt); } }