You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by em...@apache.org on 2021/12/04 21:04:16 UTC
[groovy] branch GROOVY_3_0_X updated: tweak tests
This is an automated email from the ASF dual-hosted git repository.
emilles pushed a commit to branch GROOVY_3_0_X
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/GROOVY_3_0_X by this push:
new da2728c tweak tests
da2728c is described below
commit da2728cfea4aa66bf96d0e0693e8fe6663bf6e87
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Sat Dec 4 13:15:08 2021 -0600
tweak tests
---
.../codehaus/groovy/runtime/ConversionHandler.java | 21 +-
src/test/groovy/IllegalAccessTests.groovy | 6 +-
src/test/groovy/bugs/Groovy8815.groovy | 3 +-
src/test/groovy/bugs/Groovy9932.groovy | 24 +-
.../groovy/bugs/groovy9236/Groovy9236Bug.groovy | 193 ++++-----
.../util/GroovyScriptEngineReloadingTest.groovy | 430 +++++++++++----------
.../groovy/classgen/TransientMetaClassTest.groovy | 4 +-
.../groovy/runtime/InterfaceConversionTest.groovy | 29 +-
.../runtime/typehandling/NumberMathTest.groovy | 38 +-
9 files changed, 390 insertions(+), 358 deletions(-)
diff --git a/src/main/java/org/codehaus/groovy/runtime/ConversionHandler.java b/src/main/java/org/codehaus/groovy/runtime/ConversionHandler.java
index 04870c9..876cf05 100644
--- a/src/main/java/org/codehaus/groovy/runtime/ConversionHandler.java
+++ b/src/main/java/org/codehaus/groovy/runtime/ConversionHandler.java
@@ -30,7 +30,6 @@ import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -91,19 +90,22 @@ public abstract class ConversionHandler implements InvocationHandler, Serializab
* @see #invokeCustom(Object, Method, Object[])
* @see InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
*/
- public Object invoke(final Object proxy, Method method, Object[] args) throws Throwable {
+ public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
if (isDefaultMethod(method) && !defaultOverridden(method)) {
final VMPlugin plugin = VMPluginFactory.getPlugin();
- Object handle = handleCache.computeIfAbsent(method, m -> plugin.getInvokeSpecialHandle(m, proxy));
+ Object handle = handleCache.computeIfAbsent(method, m ->
+ plugin.getInvokeSpecialHandle(m, proxy)
+ );
return plugin.invokeHandle(handle, args);
}
if (!checkMethod(method)) {
try {
if (method.getDeclaringClass() == GroovyObject.class) {
- if ("getMetaClass".equals(method.getName())) {
+ switch (method.getName()) {
+ case "getMetaClass":
return getMetaClass(proxy);
- } else if ("setMetaClass".equals(method.getName())) {
+ case "setMetaClass":
return setMetaClass((MetaClass) args[0]);
}
}
@@ -120,16 +122,15 @@ public abstract class ConversionHandler implements InvocationHandler, Serializab
}
}
- private boolean defaultOverridden(Method method) {
+ private boolean defaultOverridden(final Method method) {
return delegate instanceof Map && ((Map) delegate).containsKey(method.getName());
}
- protected boolean isDefaultMethod(Method method) {
- return ((method.getModifiers() & (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)) ==
- Modifier.PUBLIC) && method.getDeclaringClass().isInterface();
+ protected boolean isDefaultMethod(final Method method) {
+ return method.isDefault();
}
- protected boolean checkMethod(Method method) {
+ protected boolean checkMethod(final Method method) {
return isCoreObjectMethod(method);
}
diff --git a/src/test/groovy/IllegalAccessTests.groovy b/src/test/groovy/IllegalAccessTests.groovy
index f0d1192..256bfe0 100644
--- a/src/test/groovy/IllegalAccessTests.groovy
+++ b/src/test/groovy/IllegalAccessTests.groovy
@@ -30,14 +30,14 @@ import static org.junit.Assume.assumeTrue
* Java via means such as reflection.
*
* In JDK versions < 9, Groovy supports permissive access and no warnings are given by the JDK.
- * In JDK versions >= 9, Groovy supports permissive access but the JDK gives illegal access warnings.
- * At some point, the JDK may further restrict permissive access and Groovy's support for this feature may be limited.
+ * In JDK versions in 9..15, Groovy supports permissive access but the JDK gives illegal access warnings.
+ * In JDK versions > 16, permissive access is restricted and Groovy's support for this feature is limited.
*/
final class IllegalAccessTests {
@Before
void setUp() {
- assumeTrue(isAtLeastJdk('9.0') && !Boolean.getBoolean('groovy.force.illegal.access'))
+ assumeTrue(!isAtLeastJdk('16.0') && isAtLeastJdk('9.0') && !Boolean.getBoolean('groovy.force.illegal.access'))
}
@Test
diff --git a/src/test/groovy/bugs/Groovy8815.groovy b/src/test/groovy/bugs/Groovy8815.groovy
index 8a8c9f4..facede1 100644
--- a/src/test/groovy/bugs/Groovy8815.groovy
+++ b/src/test/groovy/bugs/Groovy8815.groovy
@@ -30,7 +30,6 @@ final class Groovy8815 {
targetDirectory: File.createTempDir(),
jointCompilationOptions: [memStub: true]
)
-
def parentDir = File.createTempDir()
try {
def a = new File(parentDir, 'Event.groovy')
@@ -68,7 +67,7 @@ final class Groovy8815 {
def method = loader.loadClass('Service').getMethod('on', Class, Closure)
// should not contain unresolved type parameter 'T'
- assert method.genericSignature == '<E:LEvent<*>;>(Ljava/lang/Class;Lgroovy/lang/Closure;)LRegistration<Ljava/lang/Object;Ljava/util/function/Consumer<TE;>;>;'
+ assert method.genericReturnType.typeName == 'Registration<java.lang.Object, java.util.function.Consumer<E>>'
} finally {
parentDir.deleteDir()
config.targetDirectory.deleteDir()
diff --git a/src/test/groovy/bugs/Groovy9932.groovy b/src/test/groovy/bugs/Groovy9932.groovy
index 46bea95..cc91082 100644
--- a/src/test/groovy/bugs/Groovy9932.groovy
+++ b/src/test/groovy/bugs/Groovy9932.groovy
@@ -19,17 +19,21 @@
package groovy.bugs
import groovy.mock.interceptor.MockFor
+import org.codehaus.groovy.control.CompilerConfiguration
import org.junit.Test
+import static org.junit.Assume.assumeFalse
+
final class Groovy9932 {
+
@Test
void testCallCurrentOnMock() {
- def mockForHelper = new MockFor(Helper)
-
- mockForHelper.demand.helperMethod { -> 'intercepted' }
- mockForHelper.ignore('getMyString')
+ assumeFalse(CompilerConfiguration.DEFAULT.isIndyEnabled())
- mockForHelper.use {
+ new MockFor(Helper).tap {
+ demand.publicMethod { -> 'intercepted' }
+ ignore 'getMyString'
+ }.use {
def helper = new Helper()
assert helper.myString == 'intercepted'
}
@@ -39,16 +43,14 @@ final class Groovy9932 {
String myString
Helper() {
- myString = internalMethod()
+ myString = privateMethod()
}
- // separate method to ensure callCurrent is used.
- // in the constructor it uses a direct call without checking stMC
- private String internalMethod() {
- return helperMethod()
+ private String privateMethod() {
+ return publicMethod()
}
- String helperMethod() {
+ String publicMethod() {
return 'not intercepted'
}
}
diff --git a/src/test/groovy/bugs/groovy9236/Groovy9236Bug.groovy b/src/test/groovy/bugs/groovy9236/Groovy9236Bug.groovy
index 3ba9508..e2c7ec8 100644
--- a/src/test/groovy/bugs/groovy9236/Groovy9236Bug.groovy
+++ b/src/test/groovy/bugs/groovy9236/Groovy9236Bug.groovy
@@ -18,106 +18,115 @@
*/
package groovy.bugs.groovy9236
-import groovy.test.GroovyTestCase
-import org.apache.groovy.util.ScriptRunner
+import org.junit.Test
-class Groovy9236Bug extends GroovyTestCase {
- /* groovy-3.0.0-beta-3 will try to guess and load the following classes:
-Script1$_p_lambda1BeanInfo
-Script1$_p_lambda1Customizer
-Script1BeanInfo
-Script1Customizer
-groovy$transform$CompileStatic
-groovy.lang.GroovyObject$Collectors
-groovy.lang.GroovyObject$CompileStatic
-groovy.lang.GroovyObject$groovy$transform$CompileStatic
-groovy.lang.GroovyObject$java$util$stream$Collectors
-groovy.lang.GroovyObject$java$util$stream$Stream
-groovy.lang.groovy$transform$CompileStatic
-groovy.lang.java$util$stream$Collectors
-groovy.lang.java$util$stream$Stream
-groovy.transform$CompileStatic
-groovy.util.groovy$transform$CompileStatic
-groovy.util.java$util$stream$Collectors
-groovy.util.java$util$stream$Stream
-java$util$stream$Collectors
-java$util$stream$Stream
-java.io.groovy$transform$CompileStatic
-java.io.java$util$stream$Collectors
-java.io.java$util$stream$Stream
-java.lang.groovy$transform$CompileStatic
-java.lang.java$util$stream$Collectors
-java.lang.java$util$stream$Stream
-java.net.groovy$transform$CompileStatic
-java.net.java$util$stream$Collectors
-java.net.java$util$stream$Stream
-java.util$stream$Collectors
-java.util$stream$Stream
-java.util.groovy$transform$CompileStatic
-java.util.java$util$stream$Collectors
-java.util.java$util$stream$Stream
-java.util.stream$Collectors
-java.util.stream$Stream
+import static org.apache.groovy.util.ScriptRunner.runScript
+
+final class Groovy9236Bug {
+
+ /**
+ * groovy-3.0.0-beta-3 will try to guess and load the following classes:
+ * <pre>
+ * Script1$_p_lambda1BeanInfo
+ * Script1$_p_lambda1Customizer
+ * Script1BeanInfo
+ * Script1Customizer
+ * groovy$transform$CompileStatic
+ * groovy.lang.GroovyObject$Collectors
+ * groovy.lang.GroovyObject$CompileStatic
+ * groovy.lang.GroovyObject$groovy$transform$CompileStatic
+ * groovy.lang.GroovyObject$java$util$stream$Collectors
+ * groovy.lang.GroovyObject$java$util$stream$Stream
+ * groovy.lang.groovy$transform$CompileStatic
+ * groovy.lang.java$util$stream$Collectors
+ * groovy.lang.java$util$stream$Stream
+ * groovy.transform$CompileStatic
+ * groovy.util.groovy$transform$CompileStatic
+ * groovy.util.java$util$stream$Collectors
+ * groovy.util.java$util$stream$Stream
+ * java$util$stream$Collectors
+ * java$util$stream$Stream
+ * java.io.groovy$transform$CompileStatic
+ * java.io.java$util$stream$Collectors
+ * java.io.java$util$stream$Stream
+ * java.lang.groovy$transform$CompileStatic
+ * java.lang.java$util$stream$Collectors
+ * java.lang.java$util$stream$Stream
+ * java.net.groovy$transform$CompileStatic
+ * java.net.java$util$stream$Collectors
+ * java.net.java$util$stream$Stream
+ * java.util$stream$Collectors
+ * java.util$stream$Stream
+ * java.util.groovy$transform$CompileStatic
+ * java.util.java$util$stream$Collectors
+ * java.util.java$util$stream$Stream
+ * java.util.stream$Collectors
+ * java.util.stream$Stream
+ * </pre>
*/
+ @Test @groovy.transform.CompileStatic
void testAvoidUnnecessaryResolving() {
- def cl = new Groovy9236ClassLoader()
- def gs = new GroovyShell(cl)
- gs.evaluate('''
- import groovy.transform.CompileStatic
- import java.util.stream.Collectors
- import java.util.stream.Stream
-
- @CompileStatic
- void p() {
- assert [2, 3, 4] == [1, 2, 3].stream().map(e -> e.plus 1).collect(Collectors.toList())
- }
-
- p()
+ def guessedClassNameList = []
+
+ def loader = new GroovyClassLoader() {
+ @Override
+ protected Class<?> findClass(String name) throws ClassNotFoundException {
+ guessedClassNameList.add(name)
+ return super.findClass(name)
+ }
+ }
+
+ new GroovyShell(loader).evaluate('''
+ import groovy.transform.CompileStatic
+ import java.util.stream.Collectors
+ import java.util.stream.Stream
+
+ @CompileStatic
+ void p() {
+ assert [2, 3, 4] == [1, 2, 3].stream().map(e -> e.plus(1)).collect(Collectors.toList())
+ }
+
+ p()
''')
- final classNamesShouldAvoidToGuess = ['java.lang.java$util$stream$Collectors',
- 'java.util.java$util$stream$Collectors',
- 'java.io.java$util$stream$Collectors',
- 'java.net.java$util$stream$Collectors',
- 'groovy.lang.java$util$stream$Collectors',
- 'groovy.util.java$util$stream$Collectors',
- 'java$util$stream$Collectors',
- 'java.util$stream$Collectors',
- 'java.util.stream$Collectors',
- 'java.lang.groovy$transform$CompileStatic',
- 'java.util.groovy$transform$CompileStatic',
- 'java.io.groovy$transform$CompileStatic',
- 'java.net.groovy$transform$CompileStatic',
- 'groovy.lang.groovy$transform$CompileStatic',
- 'groovy.util.groovy$transform$CompileStatic',
- 'groovy$transform$CompileStatic',
- 'groovy.transform$CompileStatic',
- 'java.lang.java$util$stream$Stream',
- 'java.util.java$util$stream$Stream',
- 'java.io.java$util$stream$Stream',
- 'java.net.java$util$stream$Stream',
- 'groovy.lang.java$util$stream$Stream',
- 'groovy.util.java$util$stream$Stream',
- 'java$util$stream$Stream',
- 'java.util$stream$Stream',
- 'java.util.stream$Stream',
- 'groovy.lang.GroovyObject$java$util$stream$Collectors',
- 'groovy.lang.GroovyObject$groovy$transform$CompileStatic',
- 'groovy.lang.GroovyObject$java$util$stream$Stream']
+ List<String> classNamesShouldAvoidToGuess = [
+ 'java.lang.java$util$stream$Collectors',
+ 'java.util.java$util$stream$Collectors',
+ 'java.io.java$util$stream$Collectors',
+ 'java.net.java$util$stream$Collectors',
+ 'groovy.lang.java$util$stream$Collectors',
+ 'groovy.util.java$util$stream$Collectors',
+ 'java$util$stream$Collectors',
+ 'java.util$stream$Collectors',
+ 'java.util.stream$Collectors',
+ 'java.lang.groovy$transform$CompileStatic',
+ 'java.util.groovy$transform$CompileStatic',
+ 'java.io.groovy$transform$CompileStatic',
+ 'java.net.groovy$transform$CompileStatic',
+ 'groovy.lang.groovy$transform$CompileStatic',
+ 'groovy.util.groovy$transform$CompileStatic',
+ 'groovy$transform$CompileStatic',
+ 'groovy.transform$CompileStatic',
+ 'java.lang.java$util$stream$Stream',
+ 'java.util.java$util$stream$Stream',
+ 'java.io.java$util$stream$Stream',
+ 'java.net.java$util$stream$Stream',
+ 'groovy.lang.java$util$stream$Stream',
+ 'groovy.util.java$util$stream$Stream',
+ 'java$util$stream$Stream',
+ 'java.util$stream$Stream',
+ 'java.util.stream$Stream',
+ 'groovy.lang.GroovyObject$java$util$stream$Collectors',
+ 'groovy.lang.GroovyObject$groovy$transform$CompileStatic',
+ 'groovy.lang.GroovyObject$java$util$stream$Stream'
+ ]
- assert cl.guessedClassNameList.every(n -> !classNamesShouldAvoidToGuess.contains(n))
+ assert !guessedClassNameList.isEmpty()
+ assert guessedClassNameList.every(n -> !classNamesShouldAvoidToGuess.contains(n))
}
+ @Test
void testResolvingPrecedence() {
- ScriptRunner.runScript('/groovy/bugs/groovy9236/Main.groovy')
- }
-
- private static class Groovy9236ClassLoader extends GroovyClassLoader {
- def guessedClassNameList = []
-
- protected Class<?> findClass(final String name) throws ClassNotFoundException {
- guessedClassNameList << name
- super.findClass(name)
- }
+ runScript('/groovy/bugs/groovy9236/Main.groovy')
}
}
diff --git a/src/test/groovy/util/GroovyScriptEngineReloadingTest.groovy b/src/test/groovy/util/GroovyScriptEngineReloadingTest.groovy
index 3e655fa..cf00a99 100644
--- a/src/test/groovy/util/GroovyScriptEngineReloadingTest.groovy
+++ b/src/test/groovy/util/GroovyScriptEngineReloadingTest.groovy
@@ -18,17 +18,30 @@
*/
package groovy.util
-import groovy.test.GroovyTestCase
+import groovy.transform.AutoFinal
+import org.junit.Before
+import org.junit.BeforeClass
+import org.junit.Test
-import java.util.concurrent.ConcurrentHashMap
-import org.codehaus.groovy.control.CompilerConfiguration
+import static groovy.test.GroovyAssert.shouldFail
-class GroovyScriptEngineReloadingTest extends GroovyTestCase {
- GroovyScriptEngine gse
+@AutoFinal
+final class GroovyScriptEngineReloadingTest {
- void setUp() {
- MapFileSystem.instance.registerMapFileSystem()
- makeGSE(null)
+ private GroovyScriptEngine gse
+
+ @BeforeClass
+ static void setUpTestSuite() {
+ URL.setURLStreamHandlerFactory(protocol -> {
+ if (protocol == MapUrlConnection.PROTOCOL) {
+ return new MapUrlHandler()
+ }
+ })
+ }
+
+ @Before
+ void setUpTestCase() {
+ makeGSE()
}
private void makeGSE(ClassLoader parent) {
@@ -36,16 +49,18 @@ class GroovyScriptEngineReloadingTest extends GroovyTestCase {
gse = new GroovyScriptEngine([MapUrlConnection.URL_SCHEME] as String[]) {
long time = 1000
+ @Override
protected long getCurrentTime() {
- return time
+ time
}
}
} else {
gse = new GroovyScriptEngine([MapUrlConnection.URL_SCHEME] as String[], parent) {
long time = 1000
+ @Override
protected long getCurrentTime() {
- return time
+ time
}
}
}
@@ -73,22 +88,76 @@ class GroovyScriptEngineReloadingTest extends GroovyTestCase {
gse.run("s_1", binding)
assert binding.getVariable("val") == expected
+ }
+
+ /**
+ * The script passes the className of the class it's supposed to
+ * instantiate to this method, expecting a newly instantiated object
+ * in return. The reason this is not done in the script is that
+ * we want to ensure that no unforeseen problems occur if
+ * the instantiation is not actually done inside the script,
+ * since real-world usages will likely require delegating that
+ * job.
+ */
+ private Object instantiate(String className, ClassLoader classLoader) {
+ Class clazz = null;
+ try {
+ clazz = Class.forName(className, true, classLoader);
+ } catch (ClassNotFoundException ex) {
+ throw new RuntimeException("Class.forName failed for " + className, ex);
+ }
+ try {
+ return clazz.newInstance();
+ } catch (Exception ex) {
+ throw new RuntimeException("Could not instantiate object of class " + className, ex);
+ }
+ }
+
+ private void writeScript(int name) throws IOException {
+ def s = '''
+ def b = new Bean()
+ return b.getVal()
+ '''
+ MapFileSystem.instance.modFile("script${name}.groovy", s, gse.@time)
+ }
+ private void writeBean(int d) throws IOException {
+ def s = """
+ class Bean {
+ String prop0
+ String prop${d}
+ def getVal(){'$d'}
+ }
+ """
+ MapFileSystem.instance.modFile('Bean.groovy', s, gse.@time)
}
- // test to ensure new source is no picked up
+ private void writeClassBean() {
+ def s = '''
+ class Bean {
+ def getVal(){this.class.hashCode()}
+ }
+ '''
+ MapFileSystem.instance.modFile('Bean.groovy', s, gse.@time)
+ }
+
+ //--------------------------------------------------------------------------
+
+ @Test // ensures new source is no picked up
void testIsSourceNewer() {
execute(1000, 2000, 2)
execute(1000, 5000, 2)
execute(1000, 10000, 2)
}
- // test to ensure new source is ignored till minimumRecompilationIntervall is passed
+
+ @Test // ensures new source is ignored till minimumRecompilationIntervall is passed
void testRecompilationIntervall() {
execute(100000, 10000, 1)
execute(100000, 10000, 1)
execute(100000, 200000, 2)
}
+ @Test
void testRecompilingWithGenerics() {
MapFileSystem.instance.modFile('BaseClass.groovy', 'abstract class BaseClass<T> extends Script {}', gse.@time)
@@ -106,11 +175,12 @@ class GroovyScriptEngineReloadingTest extends GroovyTestCase {
sleep 1000
// make a change to the sub-class so that it gets recompiled
- MapFileSystem.instance.modFile('SubClass.groovy', subClassText + "\n", gse.@time)
+ MapFileSystem.instance.modFile('SubClass.groovy', subClassText + '\n', gse.@time)
gse.loadScriptByName('SubClass.groovy')
}
+ @Test
void testDeleteDependent() {
sleep 10000
MapFileSystem.instance.modFile('ClassA.groovy', 'DependentClass ic = new DependentClass()', gse.@time as long)
@@ -124,66 +194,60 @@ class GroovyScriptEngineReloadingTest extends GroovyTestCase {
assert clazz != null //classA is valid with dep removed
}
+ @Test
void testReloadWith2ScriptsDependentOnSameBeanAndReloadForSecond() {
gse.config.minimumRecompilationInterval = 1000
writeBean(1)
writeScript(1)
- def val1 = gse.run("script1.groovy", "")
- assert val1 == '1', "script1 should have returned 1"
+ def val1 = gse.run('script1.groovy', '')
+ assert val1 == '1', 'script1 should have returned 1'
sleep 1
writeBean(2)
writeScript(2)
- val1 = gse.run("script1.groovy", "")
- assert val1 == '1', "script1 should have returned 1"
+ val1 = gse.run('script1.groovy', '')
+ assert val1 == '1', 'script1 should have returned 1'
sleep 10000
- def val2 = gse.run("script2.groovy", "")
- assert val2 == '2', "script2 should have returned 2"
+ def val2 = gse.run('script2.groovy', '')
+ assert val2 == '2', 'script2 should have returned 2'
}
+ @Test
void testReloadWith2ScriptsDependentOnSameBean() {
gse.config.minimumRecompilationInterval = 1
writeBean(1)
writeScript(1)
writeScript(2)
- def val1 = gse.run("script2.groovy", "")
- assert val1 == '1', "script2 should have returned 1"
+ def val1 = gse.run('script2.groovy', '')
+ assert val1 == '1', 'script2 should have returned 1'
- def val2 = gse.run("script1.groovy", "")
- assert val2 == '1', "script1 should have returned 1"
+ def val2 = gse.run('script1.groovy', '')
+ assert val2 == '1', 'script1 should have returned 1'
sleep 10000
writeBean(2)
- def val3 = gse.run("script1.groovy", "")
+ def val3 = gse.run('script1.groovy', '')
assert val3 == '2', "script1 should have returned 2 after bean was modified but returned $val3"
- def val4 = gse.run("script2.groovy", "")
+ def val4 = gse.run('script2.groovy', '')
assert val4 == '2', "script2 should have returned 2 after bean was modified but returned $val4"
}
- private void writeClassBean() {
- def s = """
- class Bean {
- def getVal(){this.class.hashCode()}
- }
- """
- MapFileSystem.instance.modFile("Bean.groovy", s, gse.@time)
- }
-
+ @Test
void testDependencyReloadNotTooOften() {
gse.config.minimumRecompilationInterval = 1
writeClassBean()
writeScript(1)
writeScript(2)
- def beanClass1 = gse.run("script2.groovy", "")
- def beanClass2 = gse.run("script1.groovy", "")
- assert beanClass1 == beanClass2, "bean class should have been compiled only once"
+ def beanClass1 = gse.run('script2.groovy', '')
+ def beanClass2 = gse.run('script1.groovy', '')
+ assert beanClass1 == beanClass2, 'bean class should have been compiled only once'
def oldBeanClass = beanClass1
sleep 10000
@@ -191,204 +255,160 @@ class GroovyScriptEngineReloadingTest extends GroovyTestCase {
writeScript(1)
writeScript(2)
- beanClass1 = gse.run("script2.groovy", "")
- beanClass2 = gse.run("script1.groovy", "")
- assert beanClass1 == beanClass2, "bean class should have been compiled only once"
- assert beanClass1 != oldBeanClass, "bean class was not recompiled"
+ beanClass1 = gse.run('script2.groovy', '')
+ beanClass2 = gse.run('script1.groovy', '')
+ assert beanClass1 == beanClass2, 'bean class should have been compiled only once'
+ assert beanClass1 != oldBeanClass, 'bean class was not recompiled'
}
+ @Test
void testReloadWhenModifyingAllScripts() {
gse.config.minimumRecompilationInterval = 1
writeBean(1)
writeScript(1)
writeScript(2)
- def val1 = gse.run("script2.groovy", "")
- assert val1 == '1', "script2 should have returned 1"
+ def val1 = gse.run('script2.groovy', '')
+ assert val1 == '1', 'script2 should have returned 1'
- def val2 = gse.run("script1.groovy", "")
- assert val2 == '1', "script1 should have returned 1"
+ def val2 = gse.run('script1.groovy', '')
+ assert val2 == '1', 'script1 should have returned 1'
// write Scripts stay the same, timestamps updated
writeScript(1)
writeScript(2)
sleep 10000
- val1 = gse.run("script2.groovy", "")
- assert val1 == '1', "script2 should have returned 1"
- val2 = gse.run("script1.groovy", "")
- assert val2 == '1', "script1 should have returned 1"
+ val1 = gse.run('script2.groovy', '')
+ assert val1 == '1', 'script2 should have returned 1'
+ val2 = gse.run('script1.groovy', '')
+ assert val2 == '1', 'script1 should have returned 1'
// Modify Bean to return new value
sleep 10000
writeBean(2)
- def val3 = gse.run("script1.groovy", "")
+ def val3 = gse.run('script1.groovy', '')
assert val3 == '2', "script1 should have returned 2 after bean was modified but returned $val3"
- def val4 = gse.run("script2.groovy", "")
+ def val4 = gse.run('script2.groovy', '')
assert val4 == '2', "script2 should have returned 2 after bean was modified but returned $val4"
}
- void writeScript(int name) throws IOException {
- def s = """
- def b = new Bean()
- return b.getVal()
- """
- MapFileSystem.instance.modFile("script${name}.groovy", s, gse.@time)
- }
-
- void writeBean(int d) throws IOException {
- def s = """
- class Bean {
- String prop0
- String prop${d}
- def getVal(){"$d"}
+ @Test
+ void testDynamicInstantiation() {
+ MapFileSystem.instance.modFile('script.groovy', '''
+ def obj = dynaInstantiate.instantiate(className, getClass().getClassLoader())
+ obj.modifyWidth(dim, addThis)
+ returnedMessage = obj.message
+ ''', 0)
+
+ MapFileSystem.instance.modFile('com/company/MakeMeSuper.groovy', '''
+ package com.company
+ import com.company.util.*
+ class MakeMeSuper{
+ private HelperIntf helper = new Helper()
+ def getMessage() {
+ helper.getMessage()
+ }
}
- """
- MapFileSystem.instance.modFile("Bean.groovy", s, gse.@time)
- }
+ ''', 0)
- void testDynamicInstantiation() throws Exception {
- MapFileSystem.instance.modFile("script.groovy",
- """
- def obj = dynaInstantiate.instantiate(className, getClass().getClassLoader())
- obj.modifyWidth(dim, addThis)
- returnedMessage = obj.message
- """, 0)
-
- MapFileSystem.instance.modFile("com/company/MakeMeSuper.groovy",
- """
- package com.company
- import com.company.util.*
- class MakeMeSuper{
- private HelperIntf helper = new Helper()
- def getMessage(){
- helper.getMessage()
- }
- }
- """, 0)
-
- MapFileSystem.instance.modFile("com/company/MakeMe.groovy",
- """
+ MapFileSystem.instance.modFile('com/company/MakeMe.groovy',
+ '''
package com.company
class MakeMe extends MakeMeSuper{
def modifyWidth(dim, addThis){
dim.width += addThis
}
}
- """, 0)
+ ''', 0)
- MapFileSystem.instance.modFile("com/company/util/HelperIntf.groovy",
- """
+ MapFileSystem.instance.modFile('com/company/util/HelperIntf.groovy',
+ '''
package com.company.util
interface HelperIntf{
public String getMessage();
}
- """, 0)
+ ''', 0)
- MapFileSystem.instance.modFile("com/company/util/Helper.groovy",
- """
+ MapFileSystem.instance.modFile('com/company/util/Helper.groovy',
+ '''
package com.company.util
class Helper implements HelperIntf{
public String getMessage(){
'worked'
}
}
- """, 0)
+ ''', 0)
//Code run in the script will modify this dimension object.
MyDimension dim = new MyDimension();
Binding binding = new Binding();
- binding.setVariable("dim", dim);
- binding.setVariable("dynaInstantiate", this);
+ binding.setVariable('dim', dim);
+ binding.setVariable('dynaInstantiate', this);
- binding.setVariable("className", "com.company.MakeMe");
+ binding.setVariable('className', 'com.company.MakeMe');
int addThis = 3;
- binding.setVariable("addThis", addThis);
+ binding.setVariable('addThis', addThis);
- gse.run("script.groovy", binding);
+ gse.run('script.groovy', binding);
//The script instantiated com.company.MakeMe via our own
//instantiate method. The instantiated object modified the
//width of our Dimension object, adding the value of our
//'addThis' variable to it.
- assertEquals(new MyDimension(addThis, 0), dim);
-
- assertEquals('worked', binding.getVariable("returnedMessage"))
- }
+ assert dim == new MyDimension(addThis, 0)
- /**
- * The script passes the className of the class it's supposed to
- * instantiate to this method, expecting a newly instantiated object
- * in return. The reason this is not done in the script is that
- * we want to ensure that no unforeseen problems occur if
- * the instantiation is not actually done inside the script,
- * since real-world usages will likely require delegating that
- * job.
- */
- Object instantiate(String className, ClassLoader classLoader) {
- Class clazz = null;
- try {
- clazz = Class.forName(className, true, classLoader);
- } catch (ClassNotFoundException ex) {
- throw new RuntimeException("Class.forName failed for " + className, ex);
- }
- try {
- return clazz.newInstance();
- } catch (Exception ex) {
- throw new RuntimeException("Could not instantiate object of class " + className, ex);
- }
+ assert binding.getVariable('returnedMessage') == 'worked'
}
/**
* Test for GROOVY-3281, to ensure details passed through CompilerConfiguration are inherited by GSE.
*/
+ @Test
void testCompilerConfigurationInheritance() {
- CompilerConfiguration cc = new CompilerConfiguration();
- cc.scriptBaseClass = CustomBaseClass.name
-
- GroovyClassLoader cl = new GroovyClassLoader(this.class.getClassLoader(), cc)
- makeGSE(cl);
+ def cc = new org.codehaus.groovy.control.CompilerConfiguration(scriptBaseClass: CustomBaseClass.name)
+ def cl = new GroovyClassLoader(this.class.classLoader, cc)
+ makeGSE(cl)
MapFileSystem.instance.modFile(
- "groovyScriptEngineSampleScript.groovy",
+ 'groovyScriptEngineSampleScript.groovy',
'println "Hello Guillaume, is it a Groovy day?"', 0)
- def aScript = gse.createScript("groovyScriptEngineSampleScript.groovy", new Binding())
+ def aScript = gse.createScript('groovyScriptEngineSampleScript.groovy', new Binding())
assert aScript instanceof CustomBaseClass
}
/** GROOVY-3893 */
+ @Test
void testGSEWithNoScriptRoots() {
shouldFail ResourceException, {
String[] emptyScriptRoots = []
GroovyScriptEngine gse = new GroovyScriptEngine(emptyScriptRoots)
- gse.run("unknownScriptName", "")
+ gse.run('unknownScriptName', '')
}
}
/** GROOVY-6203 */
+ @Test
void testGSEBaseClass() {
- CompilerConfiguration cc = new CompilerConfiguration()
- cc.setScriptBaseClass(CustomBaseClass.name)
-
- makeGSE(null)
- gse.setConfig(cc)
+ gse.config = new org.codehaus.groovy.control.CompilerConfiguration(scriptBaseClass: CustomBaseClass.name)
MapFileSystem.instance.modFile(
- "Groovy6203Helper.groovy",
+ 'Groovy6203Helper.groovy',
'println "Hello Guillaume, is it a Groovy day?"', 0)
- def script = gse.createScript("Groovy6203Helper.groovy", new Binding())
+ def script = gse.createScript('Groovy6203Helper.groovy', new Binding())
assert script instanceof CustomBaseClass
}
/** GROOVY-4013 */
+ @Test
void testGSENoCachingOfInnerClasses() {
- MapFileSystem.instance.modFile("Groovy4013Helper.groovy",
- """
+ MapFileSystem.instance.modFile('Groovy4013Helper.groovy',
+ '''
import java.awt.event.*
import java.awt.*
class Groovy4013Helper
@@ -401,7 +421,7 @@ class GroovyScriptEngineReloadingTest extends GroovyTestCase {
})
}
}
- """, 0)
+ ''', 0)
def klazz = gse.loadScriptByName('Groovy4013Helper.groovy')
assert klazz.name == 'Groovy4013Helper'
@@ -411,41 +431,43 @@ class GroovyScriptEngineReloadingTest extends GroovyTestCase {
}
/** GROOVY-4234 */
+ @Test
void testGSERunningAScriptThatHasMultipleClasses() {
- MapFileSystem.instance.modFile("Groovy4234Helper.groovy",
- """
+ MapFileSystem.instance.modFile('Groovy4234Helper.groovy',
+ '''
class Foo4234 {
static main(args){
- //println "Running Foo4234 -> main()"
+ //println 'Running Foo4234 -> main()'
}
}
class Bar4234 { }
- """, 0)
+ ''', 0)
- //println "testGSELoadingAScriptThatHasMultipleClasses - Run 1"
- gse.run("Groovy4234Helper.groovy", new Binding())
+ //println 'testGSELoadingAScriptThatHasMultipleClasses - Run 1'
+ gse.run('Groovy4234Helper.groovy', new Binding())
- //println "testGSELoadingAScriptThatHasMultipleClasses - Run 2"
- gse.run("Groovy4234Helper.groovy", new Binding())
+ //println 'testGSELoadingAScriptThatHasMultipleClasses - Run 2'
+ gse.run('Groovy4234Helper.groovy', new Binding())
}
- /** GROOVY-2811 and GROOVY-4286 */
+ /** GROOVY-2811 and GROOVY-4286 */
+ @Test
void testReloadingInterval() {
gse.config.minimumRecompilationInterval = 1500
def binding = new Binding([:])
- def scriptName = "gse.groovy"
+ def scriptName = 'gse.groovy'
- MapFileSystem.instance.modFile(scriptName, "1", 0)
+ MapFileSystem.instance.modFile(scriptName, '1', 0)
sleep 1000
// first time, the script is compiled and cached
assert gse.run(scriptName, binding) == 1
- MapFileSystem.instance.modFile(scriptName, "12", gse.@time)
+ MapFileSystem.instance.modFile(scriptName, '12', gse.@time)
sleep 3000
// the file was updated, and we waited for more than the minRecompilationInterval
assert gse.run(scriptName, binding) == 12
- MapFileSystem.instance.modFile(scriptName, "123", gse.@time)
+ MapFileSystem.instance.modFile(scriptName, '123', gse.@time)
sleep 1000
// still the old result, as we didn't wait more than the minRecompilationInterval
assert gse.run(scriptName, binding) == 12
@@ -455,8 +477,9 @@ class GroovyScriptEngineReloadingTest extends GroovyTestCase {
assert gse.run(scriptName, binding) == 123
}
+ //--------------------------------------------------------------------------
- class MapFileEntry {
+ static class MapFileEntry {
String content
long lutime
@@ -467,17 +490,8 @@ class GroovyScriptEngineReloadingTest extends GroovyTestCase {
}
@Singleton
- class MapFileSystem {
-
- public final ConcurrentHashMap<String, MapFileEntry> fileCache = new ConcurrentHashMap<String, MapFileEntry>()
- private boolean registered = false
-
- void registerMapFileSystem() {
- if (!registered) {
- URL.setURLStreamHandlerFactory(new MapUrlFactory())
- registered = true
- }
- }
+ static class MapFileSystem {
+ public final Map<String, MapFileEntry> fileCache = new java.util.concurrent.ConcurrentHashMap<>()
void modFile(String name, String content, long lutime) {
if (fileCache.containsKey(name)) {
@@ -502,86 +516,75 @@ class GroovyScriptEngineReloadingTest extends GroovyTestCase {
}
}
- class MapUrlHandler extends URLStreamHandler {
-
- MapUrlHandler() {
- super()
- }
-
+ static class MapUrlHandler extends URLStreamHandler {
+ @Override
protected URLConnection openConnection(URL u) throws IOException {
return new MapUrlConnection(u)
}
+ @Override
protected void parseURL(URL u, String spec, int start, int limit) {
super.parseURL(u, spec, start, limit)
}
}
- class MapUrlConnection extends URLConnection {
+ static class MapUrlConnection extends URLConnection {
+
+ MapUrlConnection(URL url) {
+ super(url)
+ name = url.getFile()
+ if (name.startsWith('/')) {
+ name = name.substring(1)
+ }
+ }
+
+ @Override
String getContentEncoding() {
return CHARSET
}
+ @Override
Object getContent() throws IOException {
return super.content
}
- public static final String CHARSET = "UTF-8"
- public static final String URL_HOST = "local"
- public static final String PROTOCOL = "map"
- public static final String URL_SCHEME = PROTOCOL + "://" + URL_HOST + "/"
+ public static final String CHARSET = 'UTF-8'
+ public static final String URL_HOST = 'local'
+ public static final String PROTOCOL = 'map'
+ public static final String URL_SCHEME = PROTOCOL + '://' + URL_HOST + '/'
private String name
+ @Override
InputStream getInputStream() throws IOException {
- // System.out.println(name+"\t"+MapFileSystem.fileCache.get(name).content);
+ // System.out.println(name+'\t'+MapFileSystem.fileCache.get(name).content);
if (MapFileSystem.instance.fileCache.containsKey(name)) {
String content = MapFileSystem.instance.fileCache.get(name).content
return new ByteArrayInputStream(content.getBytes(CHARSET))
} else {
- throw new IOException("file not found" + name)
+ throw new IOException('file not found' + name)
}
}
+ @Override
long getLastModified() {
long lastmodified = 0
if (MapFileSystem.instance.fileCache.containsKey(name)) {
lastmodified = MapFileSystem.instance.fileCache.get(name).lutime
}
- // System.out.println(name+"\t"+lastmodified);
+ // System.out.println(name+'\t'+lastmodified);
return lastmodified
}
+ @Override
URL getURL() {
return super.getURL()
}
- MapUrlConnection(URL url) {
- super(url)
- name = url.getFile()
- if (name.startsWith("/")) {
- name = name.substring(1)
- }
- }
-
+ @Override
void connect() throws IOException {}
}
- class MapUrlFactory implements URLStreamHandlerFactory {
-
- MapUrlFactory() {
- super()
- }
-
- URLStreamHandler createURLStreamHandler(String protocol) {
- if (MapUrlConnection.PROTOCOL.equals(protocol)) {
- return new MapUrlHandler()
- } else {
- return null
- }
- }
- }
-
static class MyDimension {
int width
int height
@@ -596,10 +599,17 @@ class GroovyScriptEngineReloadingTest extends GroovyTestCase {
height = 0
}
- boolean equals(o) { o.width == width && o.height == height }
+ @Override
+ boolean equals(o) {
+ o.width == width && o.height == height
+ }
- int hashCode() { width + 13 * height }
+ @Override
+ int hashCode() {
+ width + 13 * height
+ }
}
- static abstract class CustomBaseClass extends Script {}
+ static abstract class CustomBaseClass extends Script {
+ }
}
diff --git a/src/test/org/codehaus/groovy/classgen/TransientMetaClassTest.groovy b/src/test/org/codehaus/groovy/classgen/TransientMetaClassTest.groovy
index 18265cf..cc14bfa 100644
--- a/src/test/org/codehaus/groovy/classgen/TransientMetaClassTest.groovy
+++ b/src/test/org/codehaus/groovy/classgen/TransientMetaClassTest.groovy
@@ -27,11 +27,11 @@ class TransientMetaClassTest extends GroovyTestCase {
def gcl = new GroovyClassLoader()
def fooClass = gcl.parseClass('class Foo {}')
def fooInfo = java.beans.Introspector.getBeanInfo(fooClass)
- assert fooInfo.propertyDescriptors.find{ it.name == 'metaClass' }.transient
+ assert fooInfo.propertyDescriptors.find{ it.name == 'metaClass' }.getValue('transient')
Closure c = { -> }
def cInfo = java.beans.Introspector.getBeanInfo(c.getClass())
- assert cInfo.propertyDescriptors.find{ it.name == 'metaClass' }.transient
+ assert cInfo.propertyDescriptors.find{ it.name == 'metaClass' }.getValue('transient')
'''
}
}
diff --git a/src/test/org/codehaus/groovy/runtime/InterfaceConversionTest.groovy b/src/test/org/codehaus/groovy/runtime/InterfaceConversionTest.groovy
index ffa9a0b..86678ac 100644
--- a/src/test/org/codehaus/groovy/runtime/InterfaceConversionTest.groovy
+++ b/src/test/org/codehaus/groovy/runtime/InterfaceConversionTest.groovy
@@ -21,6 +21,7 @@ package org.codehaus.groovy.runtime
import groovy.test.GroovyTestCase
import static groovy.test.GroovyAssert.isAtLeastJdk
+import static org.junit.Assume.assumeTrue
class InterfaceConversionTest extends GroovyTestCase {
@@ -43,19 +44,29 @@ class InterfaceConversionTest extends GroovyTestCase {
assert m2.b(null) == 2
}
- //GROOVY-7104
+ // GROOVY-7104
void testDefaultInterfaceMethodCallOnProxy() {
- // reversed is a default method within the Comparator interface for 1.8+
- if (!isAtLeastJdk("1.8")) return
- Comparator c1 = { a, b -> a <=> b }
- assert c1.compare("a", "b") == -1
- def c2 = c1.reversed()
- assert c2.compare("a", "b") == 1
+ assumeTrue(isAtLeastJdk("1.8"))
+ assertScript '''
+ Comparator<?> c = { a,b -> a <=> b }
+ assert c.compare("x","y") < 0
+ c = c.reversed() // default method
+ assert c.compare("x","y") > 0
+ '''
+ }
+
+ // GROOVY-10391
+ void testDefaultInterfaceMethodCallOnProxy2() {
+ assumeTrue(isAtLeastJdk("1.8"))
+ assertScript '''
+ java.util.function.Predicate<?> p = { q -> false }
+ def not = p.negate() // default method
+ assert not.test("x")
+ '''
}
}
interface InterfaceConversionTestFoo {
def a()
-
def b(Integer i)
-}
\ No newline at end of file
+}
diff --git a/src/test/org/codehaus/groovy/runtime/typehandling/NumberMathTest.groovy b/src/test/org/codehaus/groovy/runtime/typehandling/NumberMathTest.groovy
index dbf0d6a..2517e36 100644
--- a/src/test/org/codehaus/groovy/runtime/typehandling/NumberMathTest.groovy
+++ b/src/test/org/codehaus/groovy/runtime/typehandling/NumberMathTest.groovy
@@ -94,22 +94,22 @@ class NumberMathTest extends GroovyTestCase {
}
void testOperations() {
- def I1 = new Integer(1)
- def I2 = new Integer(2)
- def I3 = new Integer(3)
- def L1 = new Long(1)
- def L2 = new Long(2)
- def L3 = new Long(3)
- def F1 = new Float("1.0")
- def F2 = new Float("2.0")
- def D1 = new Double("1.0")
- def D2 = new Double("2.0")
+ def I1 = Integer.valueOf(1)
+ def I2 = Integer.valueOf(2)
+ def I3 = Integer.valueOf(3)
+ def L1 = Long.valueOf(1)
+ def L2 = Long.valueOf(2)
+ def L3 = Long.valueOf(3)
+ def F1 = Float.valueOf("1.0")
+ def F2 = Float.valueOf("2.0")
+ def D1 = Double.valueOf("1.0")
+ def D2 = Double.valueOf("2.0")
def BI1 = new BigInteger("1")
def BI2 = new BigInteger("2")
def BD1 = new BigDecimal("1.0")
def BD2 = new BigDecimal("2.0")
- def BD20 = new BigDecimal("2.00")
- def BD100 = new BigDecimal(new BigInteger(1), -2) // 100
+ def BD2_0 = new BigDecimal("2.00")
+ def BD100 = new BigDecimal(BigInteger.valueOf(1), -2, java.math.MathContext.DECIMAL32) // 1e2 aka 100
assert I1 / I2 instanceof BigDecimal
assert I1 / I2 == new BigDecimal("0.5")
@@ -142,24 +142,24 @@ class NumberMathTest extends GroovyTestCase {
assert I1 / BD2 instanceof BigDecimal
assert I1 / BD2 == new BigDecimal("0.5")
- assert I1 / BD20 instanceof BigDecimal
- assert I1 / BD20 == new BigDecimal("0.5")
+ assert I1 / BD2_0 instanceof BigDecimal
+ assert I1 / BD2_0 == 0.5g
assert BI1 / BD2 instanceof BigDecimal
- assert BI1 / BD2 == new BigDecimal("0.5")
+ assert BI1 / BD2 == 0.5g
assert I1 / BD100 instanceof BigDecimal
- assert I1 / BD100 == new BigDecimal("0.01")
+ assert I1 / BD100 == 0.01g
assert BI1 / BD100 instanceof BigDecimal
- assert BI1 / BD100 == new BigDecimal("0.01")
+ assert BI1 / BD100 == 0.01g
//Test keeping max scale of (L, R or 10)
def BBD1 = new BigDecimal("0.12345678901234567")
- assert BD1 + BBD1 == new BigDecimal("1.12345678901234567")
+ assert BD1 + BBD1 == 1.12345678901234567g
def BBD2 = new BigDecimal(".000000000000000008")
- assert BBD1 + BBD2 == new BigDecimal("0.123456789012345678")
+ assert BBD1 + BBD2 == 0.123456789012345678g
}
void testUnsupportedIntDivision() {