-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathScriptInfoTest.java
More file actions
436 lines (372 loc) · 14 KB
/
ScriptInfoTest.java
File metadata and controls
436 lines (372 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/*
* #%L
* SciJava Common shared library for SciJava software.
* %%
* Copyright (C) 2009 - 2020 SciJava developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package org.scijava.script;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.scijava.Context;
import org.scijava.ItemIO;
import org.scijava.ItemVisibility;
import org.scijava.MenuPath;
import org.scijava.Priority;
import org.scijava.log.LogService;
import org.scijava.module.ModuleItem;
import org.scijava.plugin.Plugin;
import org.scijava.test.TestUtils;
import org.scijava.util.DigestUtils;
import org.scijava.util.FileUtils;
import org.scijava.widget.WidgetStyle;
/**
* Tests {@link ScriptInfo}.
*
* @author Curtis Rueden
* @author Mark Hiner
*/
public class ScriptInfoTest {
private Context context;
private ScriptService scriptService;
// -- Test setup --
@Before
public void setUp() {
context = new Context();
scriptService = context.service(ScriptService.class);
}
@After
public void tearDown() {
context.dispose();
}
// -- Tests --
/** Tests script identifiers. */
@Test
public void testGetIdentifier() {
final String name = "strategerize";
final String namedPath = "victory.bsizes";
final String named = "" + //
"#@script(name = '" + name + "')\n" + //
"zxywvutsrqponmlkjihgfdcba\n";
final String unnamedPath = "alphabet.bsizes";
final String unnamed = "" + //
"ABCDEFGHIJKLMNOPQRSTUVWXYZ\n" + //
"0123456789\n";
// Test named, with explicit path.
assertEquals("script:" + name, id(namedPath, named));
// Test named, and no path given.
assertEquals("script:" + name, id(null, named));
// Test unnamed, with explicit path.
assertEquals("script:" + unnamedPath, id(unnamedPath, unnamed));
// Test unnamed, and no path given.
final String hex = DigestUtils.bestHex(unnamed);
assertEquals("script:<" + hex + ">", id(null, unnamed));
}
/** Tests whether new-style parameter syntax are parsed correctly. */
@Test
public void testNewStyle() throws Exception {
final String script = "" + //
"##########\n" + //
"# Inputs #\n" + //
"##########\n" + //
"#@input int stuff\n" + //
"#@input int things\n" + //
"\n" + //
"###########\n" + //
"# Credits #\n" + //
"###########\n" + //
"Brought to you by:\n" + //
"person@example.com\n" + //
"\n" + //
"###########\n" + //
"# Outputs #\n" + //
"###########\n" + //
"#@output String blackHoles\n" +
"#@output String revelations\n" +
"\n" + //
"THE END!\n";
final ScriptModule scriptModule =
scriptService.run("newStyle.bsizes", script, true).get();
final String expectedProcessed = script.replaceAll("#@.*", "");
final String actualProcessed = scriptModule.getInfo().getProcessedScript();
assertEquals(expectedProcessed, actualProcessed);
final Object output = scriptModule.getReturnValue();
if (output == null) fail("null result");
else if (!(output instanceof Integer)) {
fail("result is a " + output.getClass().getName());
}
else assertEquals(4, ((Integer) output).intValue());
}
/**
* Tests that the return value <em>is</em> appended as an extra output when no
* explicit outputs were declared.
*/
@Test
public void testReturnValueAppended() throws Exception {
final String script = "" + //
"% @LogService log\n" + //
"% @int value\n";
final ScriptModule scriptModule =
scriptService.run("include-return-value.bsizes", script, true).get();
final Map<String, Object> outputs = scriptModule.getOutputs();
assertEquals(1, outputs.size());
assertTrue(outputs.containsKey(ScriptModule.RETURN_VALUE));
}
/**
* Tests that the return value is <em>not</em> appended as an extra output
* when explicit outputs were declared.
*/
@Test
public void testReturnValueExcluded() throws Exception {
final String script = "" + //
"% @LogService log\n" + //
"% @OUTPUT int value\n";
final ScriptModule scriptModule =
scriptService.run("exclude-return-value.bsizes", script, true).get();
final Map<String, Object> outputs = scriptModule.getOutputs();
assertEquals(1, outputs.size());
assertTrue(outputs.containsKey("value"));
assertFalse(outputs.containsKey(ScriptModule.RETURN_VALUE));
}
/**
* Ensures parameters are parsed correctly from scripts, even in the presence
* of noise like e-mail addresses.
*/
@Test
public void testNoisyParameters() throws Exception {
final String script = "" + //
"% @LogService log\n" + //
"% @OUTPUT Integer output" + //
"% kraken@blah.net\n";
final ScriptModule scriptModule =
scriptService.run("hello.bsizes", script, true).get();
final Object output = scriptModule.getReturnValue();
if (output == null) fail("null result");
else if (!(output instanceof Integer)) {
fail("result is a " + output.getClass().getName());
}
else assertEquals(3, ((Integer) output).intValue());
}
/** Tests {@link ScriptInfo#getVersion()}. */
@Test
public void testVersion() throws IOException {
final String script = "" + //
"% @LogService log\n" + //
"% @OUTPUT int output";
// write script to a temporary directory on disk
final File tmpDir = TestUtils.createTemporaryDirectory("script-info-test-");
final String path = "hello.bsizes";
final File scriptFile = new File(tmpDir, path);
FileUtils.writeFile(scriptFile, DigestUtils.bytes(script));
// verify that the version is correct
final ScriptInfo info = new ScriptInfo(context, scriptFile);
final String version = info.getVersion();
final String sha1 = "28f4a2880d604774ac5d604d35f431047a087c9e";
assertTrue(version.matches("^" + sha1 + "$"));
// clean up the temporary directory
FileUtils.deleteRecursively(tmpDir);
}
/**
* Tests {@link ScriptInfo} parameter declarations, including
* {@link ScriptInfo#inputs()}, {@link ScriptInfo#outputs()},
* {@link ScriptInfo#getInput(String)} and
* {@link ScriptInfo#getOutput(String)}.
*/
@Test
public void testParameters() {
final String script = "" + //
"#@ LogService (required = false) log\n" + //
"#@ int (label=\"Slider Value\", softMin=5, softMax=15, " + //
"stepSize=3, value=11, style=\" slidEr,\") sliderValue\n" + //
"#@ String (persist = false, family='Carnivora', " + //
"choices={'quick brown fox', 'lazy dog'}) animal\n" + //
"#@ Double (autoFill = false) notAutoFilled\n" + //
"#@ String (visibility=MESSAGE) msg\n" + //
"#@BOTH java.lang.StringBuilder buffer";
final ScriptInfo info =
new ScriptInfo(context, "params.bsizes", new StringReader(script));
final List<?> noChoices = Collections.emptyList();
final ModuleItem<?> log = info.getInput("log");
assertItem("log", LogService.class, null, ItemIO.INPUT, false, true, null,
null, null, null, null, null, null, null, noChoices, log);
final ModuleItem<?> sliderValue = info.getInput("sliderValue");
assertItem("sliderValue", int.class, "Slider Value", ItemIO.INPUT, true,
true, null, " slidEr,", 11, null, null, 5, 15, 3.0, noChoices, sliderValue);
assertTrue("Case-insensitive trimmed style", WidgetStyle.isStyle(sliderValue, "slider"));
final ModuleItem<?> animal = info.getInput("animal");
final List<String> animalChoices = //
Arrays.asList("quick brown fox", "lazy dog");
assertItem("animal", String.class, null, ItemIO.INPUT, true, false,
null, null, null, null, null, null, null, null, animalChoices, animal);
assertEquals(animal.get("family"), "Carnivora"); // test custom attribute
final ModuleItem<?> notAutoFilled = info.getInput("notAutoFilled");
assertFalse(notAutoFilled.isAutoFill());
final ModuleItem<?> msg = info.getInput("msg");
assertSame(ItemVisibility.MESSAGE, msg.getVisibility());
final ModuleItem<?> buffer = info.getOutput("buffer");
assertItem("buffer", StringBuilder.class, null, ItemIO.BOTH, true, true,
null, null, null, null, null, null, null, null, noChoices, buffer);
int inputCount = 0;
final ModuleItem<?>[] inputs = { log, sliderValue, animal, notAutoFilled, msg, buffer };
for (final ModuleItem<?> inItem : info.inputs()) {
assertSame(inputs[inputCount++], inItem);
}
int outputCount = 0;
final ModuleItem<?>[] outputs = { buffer };
for (final ModuleItem<?> outItem : info.outputs()) {
assertSame(outputs[outputCount++], outItem);
}
}
/** Tests {@code #@script} directives. */
@Test
public void testScriptDirective() {
final String script = "" + //
"#@script(name = \"my_script\"" + //
", label = \"My Script\"" + //
", description = \"What a great script.\"" + //
", menuPath = \"Plugins > Do All The Things\"" + //
", menuRoot = \"special\"" + //
", iconPath = \"/path/to/myIcon.png\"" + //
", priority = \"extremely-high\"" + //
", headless = true" + //
", foo = \"bar\"" + //
")\n" +
"WOOT\n";
ScriptInfo info = null;
info =
new ScriptInfo(context, "scriptHeader.bsizes", new StringReader(script));
info.inputs(); // HACK: Force lazy initialization.
assertEquals("my_script", info.getName());
assertEquals("My Script", info.getLabel());
assertEquals("What a great script.", info.getDescription());
final MenuPath menuPath = info.getMenuPath();
assertEquals(2, menuPath.size());
assertEquals("Plugins", menuPath.get(0).getName());
assertEquals("Do All The Things", menuPath.get(1).getName());
assertEquals("/path/to/myIcon.png", info.getIconPath());
assertEquals(Priority.EXTREMELY_HIGH, info.getPriority(), 0.0);
assertTrue(info.canRunHeadless());
assertEquals("bar", info.get("foo"));
}
/**
* Ensures the ScriptInfos Reader can be reused for multiple executions of the
* script.
*/
@Test
public void testReaderSanity() throws Exception {
final String script = "" + //
"% @LogService log\n" + //
"% @OUTPUT Integer output";
final ScriptInfo info =
new ScriptInfo(context, "hello.bsizes", new StringReader(script));
final BufferedReader reader1 = info.getReader();
final BufferedReader reader2 = info.getReader();
assertEquals("Readers are not independent.", reader1.read(), reader2.read());
}
// -- Helper methods --
private String id(final String path, final String script) {
final ScriptInfo info = //
new ScriptInfo(context, path, new StringReader(script));
info.inputs(); // NB: Force parameter parsing.
return info.getIdentifier();
}
private void assertItem(final String name, final Class<?> type,
final String label, final ItemIO ioType, final boolean required,
final boolean persist, final String persistKey, final String style,
final Object value, final Object min, final Object max,
final Object softMin, final Object softMax, final Number stepSize,
final List<?> choices, final ModuleItem<?> item)
{
assertEquals(name, item.getName());
assertSame(type, item.getType());
assertEquals(label, item.getLabel());
assertSame(ioType, item.getIOType());
assertEquals(required, item.isRequired());
assertEquals(persist, item.isPersisted());
assertEquals(persistKey, item.getPersistKey());
assertEquals(style, item.getWidgetStyle());
assertEquals(value, item.getDefaultValue());
assertEquals(min, item.getMinimumValue());
assertEquals(max, item.getMaximumValue());
assertEquals(softMin, item.getSoftMinimum());
assertEquals(softMax, item.getSoftMaximum());
assertEquals(stepSize, item.getStepSize());
assertEquals(choices, item.getChoices());
}
@Plugin(type = ScriptLanguage.class)
public static class BindingSizes extends AbstractScriptLanguage {
@Override
public ScriptEngine getScriptEngine() {
return new BindingSizesEngine();
}
@Override
public List<String> getNames() {
return Arrays.asList("BindingSizes");
}
@Override
public List<String> getExtensions() {
return Arrays.asList("bsizes");
}
}
// -- Test script language --
private static class BindingSizesEngine extends AbstractScriptEngine {
{
engineScopeBindings = new BindingSizesBindings();
}
@Override
public Object eval(final String script) throws ScriptException {
return eval(new StringReader(script));
}
@Override
public Object eval(final Reader reader) throws ScriptException {
final Bindings bindings = getBindings(ScriptContext.ENGINE_SCOPE);
return bindings.size();
}
}
private static class BindingSizesBindings extends HashMap<String, Object>
implements Bindings
{
// NB: No implementation needed.
}
}