diff --git a/sofa-ark-parent/core-impl/archive/src/main/java/com/alipay/sofa/ark/loader/jar/Handler.java b/sofa-ark-parent/core-impl/archive/src/main/java/com/alipay/sofa/ark/loader/jar/Handler.java index 3031d17e0..09866e1a0 100644 --- a/sofa-ark-parent/core-impl/archive/src/main/java/com/alipay/sofa/ark/loader/jar/Handler.java +++ b/sofa-ark-parent/core-impl/archive/src/main/java/com/alipay/sofa/ark/loader/jar/Handler.java @@ -202,7 +202,7 @@ private String normalize(String file) { .append(file.substring(0, afterLastSeparatorIndex)).append(afterSeparator).toString(); } - private String replaceParentDir(String file) { + String replaceParentDir(String file) { int parentDirIndex; while ((parentDirIndex = file.indexOf("/../")) >= 0) { int precedingSlashIndex = file.lastIndexOf('/', parentDirIndex - 1); diff --git a/sofa-ark-parent/core-impl/archive/src/main/java/com/alipay/sofa/ark/loader/jar/JarUtils.java b/sofa-ark-parent/core-impl/archive/src/main/java/com/alipay/sofa/ark/loader/jar/JarUtils.java index 0dee6a166..93c0491da 100644 --- a/sofa-ark-parent/core-impl/archive/src/main/java/com/alipay/sofa/ark/loader/jar/JarUtils.java +++ b/sofa-ark-parent/core-impl/archive/src/main/java/com/alipay/sofa/ark/loader/jar/JarUtils.java @@ -62,7 +62,7 @@ public class JarUtils { private static final Map> artifactIdCacheMap = new ConcurrentHashMap<>(); - private static File searchPomProperties(File dirOrFile) { + static File searchPomProperties(File dirOrFile) { if (dirOrFile == null || !dirOrFile.exists()) { return null; } @@ -84,8 +84,8 @@ private static File searchPomProperties(File dirOrFile) { return null; } - private static String getArtifactIdFromLocalClassPath(String fileClassPath) { - // file:/Users/youji.zzl/Documents/workspace/iexpprodbase/app/bootstrap/target/classes/spring/ + static String getArtifactIdFromLocalClassPath(String fileClassPath) { + String libraryFile = fileClassPath.replace("file:", ""); // 1. search pom.properties int classesRootIndex = libraryFile.endsWith(CLASSPATH_ROOT_IDENTITY) ? libraryFile diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/bootstrap/ArkLauncherTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/bootstrap/ArkLauncherTest.java index 4b99d4bd6..9eb28ef34 100644 --- a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/bootstrap/ArkLauncherTest.java +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/bootstrap/ArkLauncherTest.java @@ -21,7 +21,6 @@ import com.alipay.sofa.ark.loader.archive.JarFileArchive; import com.alipay.sofa.ark.spi.archive.Archive; import org.junit.AfterClass; -import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.MockedStatic; @@ -35,6 +34,9 @@ import java.util.Arrays; import java.util.List; +import static com.alipay.sofa.ark.bootstrap.ArkLauncher.main; +import static org.junit.Assert.*; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; /** @@ -46,7 +48,8 @@ public class ArkLauncherTest { static MockedStatic managementFactoryMockedStatic; @BeforeClass - public static void setup(){ + public static void setup() { + List mockArguments = new ArrayList<>(); String filePath = ClasspathLauncherTest.class.getClassLoader() .getResource("SampleClass.class").getPath(); @@ -56,9 +59,8 @@ public static void setup(){ RuntimeMXBean runtimeMXBean = Mockito.mock(RuntimeMXBean.class); when(runtimeMXBean.getInputArguments()).thenReturn(mockArguments); - managementFactoryMockedStatic = Mockito.mockStatic(ManagementFactory.class); + managementFactoryMockedStatic = mockStatic(ManagementFactory.class); managementFactoryMockedStatic.when(ManagementFactory::getRuntimeMXBean).thenReturn(runtimeMXBean); - } @AfterClass @@ -68,9 +70,10 @@ public static void tearDown() { @Test public void testContainerClassLoader() throws Exception { + URL url = this.getClass().getClassLoader().getResource("sample-springboot-fat-biz.jar"); URL[] agentUrl = ClassLoaderUtils.getAgentClassPath(); - Assert.assertEquals(1, agentUrl.length); + assertEquals(1, agentUrl.length); List urls = new ArrayList<>(); JarFileArchive jarFileArchive = new JarFileArchive(new File(url.getFile())); @@ -80,25 +83,31 @@ public void testContainerClassLoader() throws Exception { } urls.addAll(Arrays.asList(agentUrl)); - EmbedClassPathArchive classPathArchive = new EmbedClassPathArchive( - this.getClass().getCanonicalName(), null, urls.toArray(new URL[] {})); + this.getClass().getCanonicalName(), null, urls.toArray(new URL[]{})); ArkLauncher arkLauncher = new ArkLauncher(classPathArchive); ClassLoader classLoader = arkLauncher.createContainerClassLoader(classPathArchive.getContainerArchive()); - Assert.assertNotNull(classLoader); + assertNotNull(classLoader); + try { Class clazz = classLoader.loadClass("com.alipay.sofa.ark.bootstrap.ArkLauncher"); - Assert.assertNotNull(clazz); + assertNotNull(clazz); clazz = classLoader.loadClass("SampleClass"); - Assert.assertNotNull(clazz); - } catch (Exception e){ - Assert.assertTrue("loadClass class failed ",false); + assertNotNull(clazz); + } catch (Exception e) { + assertTrue("loadClass class failed ", false); } - Assert.assertThrows(ClassNotFoundException.class, () -> classLoader.loadClass("NotExistClass")); + + assertThrows(ClassNotFoundException.class, () -> classLoader.loadClass("NotExistClass")); } protected boolean isNestedArchive(Archive.Entry entry) { return entry.isDirectory() ? entry.getName().equals("BOOT-INF/classes/") : entry.getName() .startsWith("BOOT-INF/lib/"); } -} \ No newline at end of file + + @Test(expected = Exception.class) + public void testMain() throws Exception { + main(null); + } +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/bootstrap/ClasspathLauncherTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/bootstrap/ClasspathLauncherTest.java index daac8745a..b62fd1d8c 100644 --- a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/bootstrap/ClasspathLauncherTest.java +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/bootstrap/ClasspathLauncherTest.java @@ -16,20 +16,20 @@ */ package com.alipay.sofa.ark.bootstrap; +import com.alipay.sofa.ark.bootstrap.ClasspathLauncher.ClassPathArchive; import com.alipay.sofa.ark.common.util.ClassLoaderUtils; import com.alipay.sofa.ark.common.util.FileUtils; +import com.alipay.sofa.ark.loader.DirectoryBizArchive; import com.alipay.sofa.ark.loader.EmbedClassPathArchive; import com.alipay.sofa.ark.loader.archive.JarFileArchive; import com.alipay.sofa.ark.spi.archive.Archive; import com.alipay.sofa.ark.spi.archive.BizArchive; import org.junit.AfterClass; -import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; -import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; @@ -39,6 +39,8 @@ import java.util.Arrays; import java.util.List; +import static com.alipay.sofa.ark.common.util.ClassLoaderUtils.getAgentClassPath; +import static org.junit.Assert.*; import static org.mockito.Mockito.when; /** @@ -46,22 +48,22 @@ * @since 0.6.0 */ public class ClasspathLauncherTest { + static MockedStatic managementFactoryMockedStatic; @BeforeClass - public static void setup(){ + public static void setup() { + List mockArguments = new ArrayList<>(); String filePath = ClasspathLauncherTest.class.getClassLoader() - .getResource("SampleClass.class").getPath(); + .getResource("SampleClass.class").getPath(); String workingPath = FileUtils.file(filePath).getParent(); mockArguments.add(String.format("-javaagent:%s", workingPath)); RuntimeMXBean runtimeMXBean = Mockito.mock(RuntimeMXBean.class); when(runtimeMXBean.getInputArguments()).thenReturn(mockArguments); - managementFactoryMockedStatic = Mockito.mockStatic(ManagementFactory.class); managementFactoryMockedStatic.when(ManagementFactory::getRuntimeMXBean).thenReturn(runtimeMXBean); - } @AfterClass @@ -71,26 +73,28 @@ public static void tearDown() { @Test public void testFilterAgentClasspath() throws Exception { + URL url = this.getClass().getClassLoader().getResource("sample-biz.jar"); - URL[] agentUrl = ClassLoaderUtils.getAgentClassPath(); - Assert.assertEquals(1, agentUrl.length); + URL[] agentUrl = getAgentClassPath(); + assertEquals(1, agentUrl.length); List urls = new ArrayList<>(); urls.add(url); urls.addAll(Arrays.asList(agentUrl)); - ClasspathLauncher.ClassPathArchive classPathArchive = new ClasspathLauncher.ClassPathArchive( + ClassPathArchive classPathArchive = new ClassPathArchive( this.getClass().getCanonicalName(), null, urls.toArray(new URL[] {})); List bizArchives = classPathArchive.getBizArchives(); - Assert.assertEquals(1, bizArchives.size()); - Assert.assertEquals(2, urls.size()); + assertEquals(1, bizArchives.size()); + assertEquals(2, urls.size()); } @Test public void testSpringBootFatJar() throws Exception { + URL url = this.getClass().getClassLoader().getResource("sample-springboot-fat-biz.jar"); - URL[] agentUrl = ClassLoaderUtils.getAgentClassPath(); - Assert.assertEquals(1, agentUrl.length); + URL[] agentUrl = getAgentClassPath(); + assertEquals(1, agentUrl.length); List urls = new ArrayList<>(); JarFileArchive jarFileArchive = new JarFileArchive(FileUtils.file(url.getFile())); @@ -100,21 +104,21 @@ public void testSpringBootFatJar() throws Exception { } urls.addAll(Arrays.asList(agentUrl)); - EmbedClassPathArchive classPathArchive = new EmbedClassPathArchive( - this.getClass().getCanonicalName(), null, urls.toArray(new URL[] {})); + this.getClass().getCanonicalName(), null, urls.toArray(new URL[]{})); List bizArchives = classPathArchive.getBizArchives(); - Assert.assertEquals(0, bizArchives.size()); - Assert.assertNotNull(classPathArchive.getContainerArchive()); - Assert.assertEquals(1, classPathArchive.getPluginArchives().size()); - Assert.assertEquals(archives.size() + 1, urls.size()); - Assert.assertEquals(3, classPathArchive.getConfClasspath().size()); + assertEquals(0, bizArchives.size()); + assertNotNull(classPathArchive.getContainerArchive()); + assertEquals(1, classPathArchive.getPluginArchives().size()); + assertEquals(archives.size() + 1, urls.size()); + assertEquals(3, classPathArchive.getConfClasspath().size()); + URLClassLoader classLoader = new URLClassLoader(classPathArchive.getContainerArchive().getUrls()); try { Class clazz = classLoader.loadClass("com.alipay.sofa.ark.bootstrap.ArkLauncher"); - Assert.assertNotNull(clazz); - } catch (Exception e){ - Assert.assertTrue("loadClass class failed ",false); + assertNotNull(clazz); + } catch (Exception e) { + assertTrue("loadClass class failed ", false); } } @@ -126,16 +130,17 @@ protected boolean isNestedArchive(Archive.Entry entry) { @Test public void testConfClasspath() throws IOException { ClassLoader classLoader = this.getClass().getClassLoader(); - ClasspathLauncher.ClassPathArchive classPathArchive = new ClasspathLauncher.ClassPathArchive( + ClassPathArchive classPathArchive = new ClassPathArchive( this.getClass().getCanonicalName(), null, ClassLoaderUtils.getURLs(classLoader)); List confClasspath = classPathArchive.getConfClasspath(); - Assert.assertEquals(3, confClasspath.size()); + assertEquals(3, confClasspath.size()); } @Test public void testFromSurefire() throws IOException { + ClassLoader classLoader = this.getClass().getClassLoader(); - ClasspathLauncher.ClassPathArchive classPathArchive = new ClasspathLauncher.ClassPathArchive( + ClassPathArchive classPathArchive = new ClassPathArchive( this.getClass().getCanonicalName(), null, ClassLoaderUtils.getURLs(classLoader)); URL url1 = Mockito.mock(URL.class); @@ -145,14 +150,75 @@ public void testFromSurefire() throws IOException { when(url1.getFile()).thenReturn("surefirebooter17233117990150815938.jar"); when(url2.getFile()).thenReturn("org.jacoco.agent-0.8.4-runtime.jar"); when(url3.getFile()).thenReturn("byte-buddy-agent-1.10.15.jar"); - - Assert.assertTrue(classPathArchive.fromSurefire(new URL[] { url1, url2, url3 })); + assertTrue(classPathArchive.fromSurefire(new URL[] { url1, url2, url3 })); List urls2 = classPathArchive.getConfClasspath(); urls2.add(url2); urls2.add(url3); + assertFalse(classPathArchive.fromSurefire(urls2.toArray(new URL[0]))); + } + + @Test + public void testOtherMethods() throws IOException { + + URL url = this.getClass().getClassLoader().getResource("sample-biz.jar"); + URL[] agentUrl = getAgentClassPath(); + assertEquals(1, agentUrl.length); - Assert.assertFalse(classPathArchive.fromSurefire(urls2.toArray(new URL[0]))); + List urls = new ArrayList<>(); + urls.add(url); + urls.addAll(Arrays.asList(agentUrl)); + + ClassPathArchive classPathArchive = new ClassPathArchive( + this.getClass().getCanonicalName(), null, urls.toArray(new URL[] {})); + + try { + classPathArchive.getUrl(); + } catch (Exception e) { + } + try { + classPathArchive.getManifest(); + } catch (Exception e) { + } + try { + classPathArchive.getNestedArchives(null); + } catch (Exception e) { + } + try { + classPathArchive.getNestedArchive(null); + } catch (Exception e) { + } + try { + classPathArchive.getInputStream(null); + } catch (Exception e) { + } + try { + classPathArchive.iterator(); + } catch (Exception e) { + } + + assertTrue(classPathArchive.createDirectoryBizModuleArchive().getClass() + .equals(DirectoryBizArchive.class)); + URL url2 = new URL("file://aa"); + assertArrayEquals(new URL[] { url2 }, + classPathArchive.filterBizUrls(new URL[] { agentUrl[0], url, url2 })); + + URL surefireJarURL = this.getClass().getClassLoader() + .getResource("sample-biz-surefire.jar"); + assertArrayEquals(new URL[] { url2, new URL("file://b") }, + classPathArchive.parseClassPathFromSurefireBoot(surefireJarURL)); } -} \ No newline at end of file + @Test + public void testBaseExecutableArchiveLauncher() { + + BaseExecutableArchiveLauncher baseExecutableArchiveLauncher = new BaseExecutableArchiveLauncher() { + @Override + protected String getMainClass() throws Exception { + return null; + } + }; + + assertNotNull(baseExecutableArchiveLauncher.getExecutableArchive()); + } +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/DirectoryBizArchiveTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/DirectoryBizArchiveTest.java new file mode 100644 index 000000000..262ecf080 --- /dev/null +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/DirectoryBizArchiveTest.java @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.loader; + +import com.alipay.sofa.ark.spi.archive.Archive; +import com.alipay.sofa.ark.spi.archive.Archive.Entry; +import org.junit.Before; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Iterator; + +import static com.alipay.sofa.ark.spi.constant.Constants.ARK_BIZ_MARK_ENTRY; +import static java.util.Collections.singletonList; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class DirectoryBizArchiveTest { + + private DirectoryBizArchive directoryBizArchive; + + @Before + public void setUp() throws MalformedURLException { + directoryBizArchive = new DirectoryBizArchive("a", "b", new URL[] { new URL("file://a") }); + } + + @Test + public void testDirectoryBizArchive() throws Exception { + + assertFalse(directoryBizArchive.isTestMode()); + assertEquals("a", directoryBizArchive.getClassName()); + assertEquals("b", directoryBizArchive.getMethodName()); + assertArrayEquals(new URL[]{new URL("file://a")}, directoryBizArchive.getUrls()); + + assertTrue(directoryBizArchive.isEntryExist(entry -> !entry.isDirectory() && entry.getName().equals(ARK_BIZ_MARK_ENTRY))); + assertEquals(5, directoryBizArchive.getManifest().getMainAttributes().size()); + + try { + directoryBizArchive.getUrl(); + assertTrue(false); + } catch (Exception e) { + } + try { + directoryBizArchive.getNestedArchives(entry -> false); + assertTrue(false); + } catch (Exception e) { + } + try { + directoryBizArchive.getInputStream(null); + assertTrue(false); + } catch (Exception e) { + } + try { + directoryBizArchive.iterator(); + assertTrue(false); + } catch (Exception e) { + } + + Archive nestedArchive = directoryBizArchive.getNestedArchive(new Entry() { + @Override + public boolean isDirectory() { + return false; + } + + @Override + public String getName() { + return ARK_BIZ_MARK_ENTRY; + } + }); + + Field field = JarBizArchive.class.getDeclaredField("archive"); + field.setAccessible(true); + assertNull(field.get(nestedArchive)); + } + + @Test + public void testJarBizArchive() throws Exception { + + Archive archive = mock(Archive.class); + JarBizArchive jarBizArchive = new JarBizArchive(archive); + + Iterator iterator = singletonList(new Entry() { + @Override + public boolean isDirectory() { + return false; + } + + @Override + public String getName() { + return "lib/export/a"; + } + }).iterator(); + + when(archive.iterator()).thenReturn((Iterator) iterator); + when(archive.getUrl()).thenReturn(new URL("file://a")); + when(archive.getNestedArchive(any())).thenReturn(archive); + + assertArrayEquals(new URL[] { new URL("file://a"), new URL("file://a") }, + jarBizArchive.getExportUrls()); + assertNull(jarBizArchive.getInputStream(null)); + } +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/DirectoryContainerArchiveTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/DirectoryContainerArchiveTest.java new file mode 100644 index 000000000..fb55a65ce --- /dev/null +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/DirectoryContainerArchiveTest.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.loader; + +import org.junit.Test; + +import java.net.URL; + +import static org.junit.Assert.assertTrue; + +public class DirectoryContainerArchiveTest { + + private DirectoryContainerArchive directoryContainerArchive; + + @Test + public void testDirectoryContainerArchive() throws Exception { + + directoryContainerArchive = new DirectoryContainerArchive(new URL[] { new URL("file://a") }); + + try { + directoryContainerArchive.getUrl(); + assertTrue(false); + } catch (Exception e) { + } + try { + directoryContainerArchive.getManifest(); + assertTrue(false); + } catch (Exception e) { + } + try { + directoryContainerArchive.getNestedArchives(null); + assertTrue(false); + } catch (Exception e) { + } + try { + directoryContainerArchive.getNestedArchive(null); + assertTrue(false); + } catch (Exception e) { + } + try { + directoryContainerArchive.getInputStream(null); + assertTrue(false); + } catch (Exception e) { + } + try { + directoryContainerArchive.iterator(); + assertTrue(false); + } catch (Exception e) { + } + } +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/ExecutableArkBizJarTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/ExecutableArkBizJarTest.java new file mode 100644 index 000000000..02e71c1f4 --- /dev/null +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/ExecutableArkBizJarTest.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.loader; + +import com.alipay.sofa.ark.spi.archive.Archive; +import org.junit.Before; +import org.junit.Test; + +import java.util.Iterator; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ExecutableArkBizJarTest { + + private Archive archive = mock(Archive.class); + + private ExecutableArkBizJar executableArkBizJar = new ExecutableArkBizJar(archive); + + @Before + public void setUp() { + when(archive.iterator()).thenReturn(mock(Iterator.class)); + } + + @Test + public void testExecutableArkBizJar() throws Exception { + + assertNull(executableArkBizJar.getManifest()); + assertNull(executableArkBizJar.getInputStream(null)); + assertNull(executableArkBizJar.getNestedArchive(null)); + + try { + executableArkBizJar.getContainerArchive(); + assertTrue(false); + } catch (RuntimeException e) { + } + + assertEquals(0, executableArkBizJar.getConfClasspath().size()); + } +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/HandlerTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/HandlerTest.java new file mode 100644 index 000000000..8efa52e11 --- /dev/null +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/HandlerTest.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.loader.jar; + +import org.junit.Test; + +import java.net.MalformedURLException; +import java.net.URL; + +import static org.junit.Assert.assertEquals; + +public class HandlerTest { + + private URL url = this.getClass().getClassLoader() + .getResource("sample-biz-withjar.jar"); + + private Handler handler = new Handler(); + + @Test(expected = MalformedURLException.class) + public void testOpenConnectionWithIOException() throws Exception { + handler.openConnection(this.getClass().getClassLoader() + .getResource("sample-biz-withjar.jar")); + } + + @Test(expected = NullPointerException.class) + public void testOpenConnectionWithNPE() throws Exception { + handler.openConnection(this.getClass().getClassLoader() + .getResource("sample-biz-withjar.jar!/lib")); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseURLWithIllegalSpec() throws Exception { + handler.parseURL(url, "/", 0, 1); + } + + @Test(expected = SecurityException.class) + public void testParseURLWithEmptySpec() throws Exception { + handler.parseURL(url, "/", 0, 0); + } + + @Test + public void testReplaceParentDir() throws Exception { + assertEquals("../a", handler.replaceParentDir("/../../a")); + assertEquals("../", handler.replaceParentDir("/../../")); + assertEquals("aaa", handler.replaceParentDir("/../aaa/../aaa")); + } +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/JarEntryTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/JarEntryTest.java new file mode 100644 index 000000000..d1b34271e --- /dev/null +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/JarEntryTest.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.loader.jar; + +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.net.URL; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class JarEntryTest { + + private URL url; + + private JarEntry jarEntry; + + @Before + public void setUp() throws Exception { + url = this.getClass().getClassLoader().getResource("sample-biz-withjar.jar"); + jarEntry = new JarEntry(new JarFile(new File(url.getPath())), + new CentralDirectoryFileHeader(new byte[64], 0, new AsciiBytes("lib"), null, + new AsciiBytes("mycomment"), 0)); + } + + @Test + public void testGetters() throws Exception { + assertEquals("jar:" + url + "!/lib", jarEntry.getUrl().toString()); + assertNull(jarEntry.getAttributes()); + assertNull(jarEntry.getCertificates()); + assertNull(jarEntry.getCodeSigners()); + jarEntry.setCertificates(new java.util.jar.JarEntry("a")); + } +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/JarFileTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/JarFileTest.java new file mode 100644 index 000000000..3ae5b7dba --- /dev/null +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/JarFileTest.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.loader.jar; + +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.net.URL; + +import static com.alipay.sofa.ark.loader.jar.JarFile.JarFileType.DIRECT; +import static org.junit.Assert.assertEquals; + +public class JarFileTest { + + @Test + public void testSetupEntryCertificates() throws IOException { + + URL url = this.getClass().getClassLoader().getResource("sample-biz.jar"); + JarFile jarFile = new JarFile(new File(url.getPath())); + assertEquals(7485, jarFile.size()); + assertEquals("jar:" + url.toString() + "!/", jarFile.getUrl().toString()); + + jarFile.setupEntryCertificates(new JarEntry(jarFile, new CentralDirectoryFileHeader( + new byte[64], 0, new AsciiBytes("lib"), null, new AsciiBytes("mycomment"), 0))); + + jarFile.clearCache(); + assertEquals(DIRECT, jarFile.getType()); + } +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/JarURLConnectionTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/JarURLConnectionTest.java new file mode 100644 index 000000000..f69f44569 --- /dev/null +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/JarURLConnectionTest.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.loader.jar; + +import com.alipay.sofa.ark.loader.jar.JarURLConnection.JarEntryName; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.URL; + +import static com.alipay.sofa.ark.loader.jar.JarURLConnection.JarEntryName.get; +import static com.alipay.sofa.ark.loader.jar.JarURLConnection.get; +import static org.junit.Assert.*; + +public class JarURLConnectionTest { + + private JarURLConnection jarURLConnection; + + private URL url = this.getClass().getClassLoader() + .getResource("sample-biz-withjar.jar"); + + @Before + public void setUp() throws Exception { + jarURLConnection = get(url, new JarFile(new File(url.getPath()))); + } + + @Test + public void testGetJarFileURL() throws IOException { + + assertTrue(jarURLConnection.getJarFileURL().getFile().endsWith("/sample-biz-withjar.jar")); + assertNull(jarURLConnection.getJarEntry()); + + jarURLConnection = get(new URL( + "file://a/b/sample-biz-withjar.jar!/lib/slf4j-api-1.7.30.jar!/"), new JarFile(new File( + url.getPath()))); + + assertEquals("com.alipay.sofa.ark.loader.data.RandomAccessDataFile$DataInputStream", + jarURLConnection.getInputStream().getClass().getName()); + assertNull(jarURLConnection.getJarEntry()); + assertEquals("", jarURLConnection.getEntryName()); + } + + @Test + public void testGetContentLength() throws Exception { + assertEquals(52949, jarURLConnection.getContentLength()); + Field field = JarURLConnection.class.getDeclaredField("jarEntryName"); + field.setAccessible(true); + field.set(jarURLConnection, new JarEntryName("!/lib/slf4j-api-1.7.30.jar!/")); + assertEquals(-1, jarURLConnection.getContentLength()); + } + + @Test + public void testGetContent() throws IOException { + assertEquals(JarFile.class, jarURLConnection.getContent().getClass()); + assertEquals("x-java/jar", jarURLConnection.getContentType()); + } + + @Test + public void testGetLastModified() throws Exception { + assertEquals(0, jarURLConnection.getLastModified()); + Field field = JarURLConnection.class.getDeclaredField("jarEntryName"); + field.setAccessible(true); + field.set(jarURLConnection, new JarEntryName("!/lib/slf4j-api-1.7.30.jar!/")); + assertEquals(0, jarURLConnection.getLastModified()); + } + + @Test + public void testJarEntryName() { + JarEntryName jarEntryName = get(url.toString()); + assertEquals("content/unknown", jarEntryName.getContentType()); + assertEquals("content/unknown", jarEntryName.getContentType()); + } +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/JarUtilsTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/JarUtilsTest.java new file mode 100644 index 000000000..1aa759a6e --- /dev/null +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/JarUtilsTest.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.loader.jar; + +import org.junit.Test; + +import java.io.File; +import java.net.URL; + +import static com.alipay.sofa.ark.loader.jar.JarUtils.getArtifactIdFromLocalClassPath; +import static com.alipay.sofa.ark.loader.jar.JarUtils.searchPomProperties; +import static org.junit.Assert.*; + +public class JarUtilsTest { + + @Test + public void testSearchPomProperties() { + + assertNull(searchPomProperties(null)); + assertNull(searchPomProperties(new File("/not-exists"))); + + URL url = this.getClass().getClassLoader().getResource("pom-properties/pom.properties"); + File file = new File(url.getPath()); + assertEquals(file, searchPomProperties(file)); + + url = this.getClass().getClassLoader().getResource("./"); + file = new File(url.getPath()); + assertTrue(searchPomProperties(file).getPath().endsWith("pom.properties")); + } + + @Test + public void testGetArtifactIdFromLocalClassPath() { + assertNull(getArtifactIdFromLocalClassPath("/a/target/bbb")); + URL url = this.getClass().getClassLoader().getResource(""); + assertEquals("sofa-ark-archive", getArtifactIdFromLocalClassPath(url.getPath())); + } +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/ZipInflaterInputStreamTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/ZipInflaterInputStreamTest.java new file mode 100644 index 000000000..1cd56924c --- /dev/null +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/jar/ZipInflaterInputStreamTest.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.loader.jar; + +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.lang.reflect.Field; +import java.util.zip.InflaterInputStream; + +import static org.junit.Assert.assertEquals; + +public class ZipInflaterInputStreamTest { + + @Test + public void testFill() throws Exception { + + ZipInflaterInputStream zipInflaterInputStream = new ZipInflaterInputStream( + new ByteArrayInputStream(new byte[0]), 0); + assertEquals(0, zipInflaterInputStream.available()); + zipInflaterInputStream.fill(); + + Field field = InflaterInputStream.class.getDeclaredField("len"); + field.setAccessible(true); + assertEquals(1, field.get(zipInflaterInputStream)); + } +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/AsciiBytesTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/AsciiBytesTest.java index f2f7ffb4b..e39cd9602 100644 --- a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/AsciiBytesTest.java +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/AsciiBytesTest.java @@ -17,9 +17,10 @@ package com.alipay.sofa.ark.loader.test.jar; import com.alipay.sofa.ark.loader.jar.AsciiBytes; -import org.junit.Assert; import org.junit.Test; +import static org.junit.Assert.*; + /** * @author qilong.zql * @since 0.1.0 @@ -28,15 +29,16 @@ public class AsciiBytesTest { public final String content = "SofaArk is a class-isolated container"; - AsciiBytes asciiBytes = new AsciiBytes(content); + private AsciiBytes asciiBytes = new AsciiBytes(content); @Test public void testAsciiBytes() { - Assert.assertTrue(asciiBytes.length() == content.length()); - Assert.assertTrue(asciiBytes.startsWith(new AsciiBytes("SofaArk"))); - Assert.assertTrue(asciiBytes.endsWith(new AsciiBytes("container"))); - Assert.assertTrue(asciiBytes.toString().equals(content)); - Assert.assertTrue(asciiBytes.substring(8, 10).endsWith(new AsciiBytes("is"))); + + assertTrue(asciiBytes.length() == content.length()); + assertTrue(asciiBytes.startsWith(new AsciiBytes("SofaArk"))); + assertTrue(asciiBytes.endsWith(new AsciiBytes("container"))); + assertTrue(asciiBytes.toString().equals(content)); + assertTrue(asciiBytes.substring(8, 10).endsWith(new AsciiBytes("is"))); String suffix = "suffix"; AsciiBytes suffixAsciiBytes = new AsciiBytes(suffix); @@ -46,4 +48,13 @@ public void testAsciiBytes() { asciiBytes.append(suffixAsciiBytes).equals(content + suffix); asciiBytes.append(suffixBytes).equals(content + suffix); } -} \ No newline at end of file + + @Test + public void testHashCode() { + AsciiBytes asciiBytes = new AsciiBytes("" + (char) 0xffff + (char) -99 + (char) -255 + + (char) -128 + (char) 127 + (char) 128 + (char) 255 + + (char) 256 + content); + assertEquals(-243313336, asciiBytes.hashCode()); + assertNotEquals(new AsciiBytes(""), asciiBytes); + } +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/CentralDirectoryEndRecordTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/CentralDirectoryEndRecordTest.java index 6db86dbf5..1c0928c87 100644 --- a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/CentralDirectoryEndRecordTest.java +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/CentralDirectoryEndRecordTest.java @@ -16,13 +16,21 @@ */ package com.alipay.sofa.ark.loader.test.jar; +import com.alipay.sofa.ark.loader.data.RandomAccessData; import com.alipay.sofa.ark.loader.data.RandomAccessDataFile; import com.alipay.sofa.ark.loader.jar.CentralDirectoryEndRecord; import com.alipay.sofa.ark.loader.test.base.BaseTest; -import org.junit.Assert; import org.junit.Test; +import java.io.File; import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * @author qilong.zql @@ -32,13 +40,22 @@ public class CentralDirectoryEndRecordTest extends BaseTest { @Test public void testEOCD() throws IOException { + RandomAccessDataFile dataFile = new RandomAccessDataFile(getTempDemoZip()); CentralDirectoryEndRecord eocd = new CentralDirectoryEndRecord(dataFile); - Assert.assertTrue(eocd.isValid()); - Assert.assertTrue(eocd.getStartOfArchive(dataFile) == 0); - Assert.assertTrue(eocd.getNumberOfRecords() == 5); - + assertTrue(eocd.isValid()); + assertTrue(eocd.getStartOfArchive(dataFile) == 0); + assertTrue(eocd.getNumberOfRecords() == 5); } -} \ No newline at end of file + @Test + public void testWithInvalidFile() throws Exception { + + RandomAccessData randomAccessData = mock(RandomAccessData.class); + when(randomAccessData.getInputStream(any())).thenReturn(mock(InputStream.class)); + + URL url = this.getClass().getClassLoader().getResource("example-jarinjarinjar.jar"); + new CentralDirectoryEndRecord(new RandomAccessDataFile(new File(url.getPath()))); + } +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/CentralDirectoryFileHeaderTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/CentralDirectoryFileHeaderTest.java index d130de5fe..5bd8f5a6f 100644 --- a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/CentralDirectoryFileHeaderTest.java +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/CentralDirectoryFileHeaderTest.java @@ -18,17 +18,20 @@ import com.alipay.sofa.ark.loader.data.RandomAccessData; import com.alipay.sofa.ark.loader.data.RandomAccessDataFile; +import com.alipay.sofa.ark.loader.jar.AsciiBytes; import com.alipay.sofa.ark.loader.jar.Bytes; import com.alipay.sofa.ark.loader.jar.CentralDirectoryEndRecord; import com.alipay.sofa.ark.loader.jar.CentralDirectoryFileHeader; import com.alipay.sofa.ark.loader.test.base.BaseTest; -import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** * @author qilong.zql * @since 0.1.0 @@ -39,10 +42,10 @@ public class CentralDirectoryFileHeaderTest extends BaseTest { @Test public void testCDFH() throws IOException { + RandomAccessDataFile dataFile = new RandomAccessDataFile(getTempDemoZip()); CentralDirectoryEndRecord eocd = new CentralDirectoryEndRecord(dataFile); RandomAccessData cdfhBlock = eocd.getCentralDirectory(dataFile); - List cdfhList = new ArrayList<>(); int dataOffset = 0; @@ -54,11 +57,18 @@ public void testCDFH() throws IOException { cdfhList.add(cdfh); } - Assert.assertTrue(cdfhList.size() == 5); - Assert.assertTrue(cdfhList.get(4).getName().toString().equals(TEST_ENTRY)); - Assert.assertTrue(cdfhList.get(4).getComment().toString().equals(TEST_ENTRY_COMMENT)); - Assert - .assertTrue(compareByteArray(cdfhList.get(4).getExtra(), TEST_ENTRY_EXTRA.getBytes())); + assertTrue(cdfhList.size() == 5); + assertTrue(cdfhList.get(4).getName().toString().equals(TEST_ENTRY)); + assertTrue(cdfhList.get(4).getComment().toString().equals(TEST_ENTRY_COMMENT)); + assertTrue(compareByteArray(cdfhList.get(4).getExtra(), TEST_ENTRY_EXTRA.getBytes())); + } + @Test + public void testOtherMethods() { + CentralDirectoryFileHeader centralDirectoryFileHeader = new CentralDirectoryFileHeader( + new byte[64], 0, new AsciiBytes("a/"), null, null, 0); + assertEquals(true, centralDirectoryFileHeader.isDirectory()); + CentralDirectoryFileHeader centralDirectoryFileHeader2 = centralDirectoryFileHeader.clone(); + assertEquals(new AsciiBytes("a/"), centralDirectoryFileHeader2.getName()); } -} \ No newline at end of file +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/JarFileTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/JarFileTest.java index ceb603724..513bd56b2 100644 --- a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/JarFileTest.java +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/JarFileTest.java @@ -19,13 +19,14 @@ import com.alipay.sofa.ark.loader.jar.JarEntry; import com.alipay.sofa.ark.loader.jar.JarFile; import com.alipay.sofa.ark.loader.test.base.BaseTest; -import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.util.jar.Manifest; import java.util.zip.ZipEntry; +import static org.junit.Assert.assertTrue; + /** * @author qilong.zql * @since 0.1.0 @@ -34,27 +35,25 @@ public class JarFileTest extends BaseTest { @Test public void testJarFile() throws IOException { + JarFile jarFile = new JarFile(getTempDemoZip()); Manifest manifest = jarFile.getManifest(); - Assert.assertTrue(manifest.getMainAttributes().getValue("k1").equals("v1")); - Assert.assertTrue(manifest.getMainAttributes().getValue("k2").equals("v2")); - - Assert.assertTrue(jarFile.containsEntry(TEST_ENTRY)); + assertTrue(manifest.getMainAttributes().getValue("k1").equals("v1")); + assertTrue(manifest.getMainAttributes().getValue("k2").equals("v2")); + assertTrue(jarFile.containsEntry(TEST_ENTRY)); ZipEntry zipEntry = jarFile.getEntry(TEST_ENTRY); - Assert.assertTrue(zipEntry.getName().equals(TEST_ENTRY)); - Assert.assertTrue(zipEntry.getComment().equals(TEST_ENTRY_COMMENT)); - Assert.assertTrue(compareByteArray(zipEntry.getExtra(), TEST_ENTRY_EXTRA.getBytes())); + assertTrue(zipEntry.getName().equals(TEST_ENTRY)); + assertTrue(zipEntry.getComment().equals(TEST_ENTRY_COMMENT)); + assertTrue(compareByteArray(zipEntry.getExtra(), TEST_ENTRY_EXTRA.getBytes())); JarEntry jarEntry = jarFile.getJarEntry("lib/junit-4.12.jar"); JarFile nestJarFile = jarFile.getNestedJarFile(jarEntry); Manifest nestManifest = nestJarFile.getManifest(); - Assert.assertTrue(nestManifest.getMainAttributes().getValue("Implementation-Title") + assertTrue(nestManifest.getMainAttributes().getValue("Implementation-Title") .equals("JUnit")); - Assert.assertTrue(nestManifest.getMainAttributes().getValue("Implementation-Version") + assertTrue(nestManifest.getMainAttributes().getValue("Implementation-Version") .equals("4.12")); - } - -} \ No newline at end of file +} diff --git a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/JarUtilsTest.java b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/JarUtilsTest.java index 8b62ed07b..0cc8b69dd 100644 --- a/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/JarUtilsTest.java +++ b/sofa-ark-parent/core-impl/archive/src/test/java/com/alipay/sofa/ark/loader/test/jar/JarUtilsTest.java @@ -19,105 +19,105 @@ import com.alipay.sofa.ark.common.util.FileUtils; import com.alipay.sofa.ark.loader.jar.JarUtils; import com.google.common.io.Files; -import org.junit.Assert; import org.junit.Test; -import java.io.File; import java.io.IOException; import java.lang.reflect.Method; -import java.net.URI; import java.net.URISyntaxException; import java.net.URL; -import java.nio.file.Paths; + +import static com.alipay.sofa.ark.loader.jar.JarUtils.parseArtifactId; +import static java.lang.String.format; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; public class JarUtilsTest { @Test public void getArtifactIdFromTestClassPath() throws IOException { URL url = this.getClass().getClassLoader().getResource("sample-biz-withjar.jar"); - String artifactId = JarUtils.parseArtifactId(url.getPath()); - Assert.assertEquals("sofa-ark-sample-springboot-ark", artifactId); + String artifactId = parseArtifactId(url.getPath()); + assertEquals("sofa-ark-sample-springboot-ark", artifactId); } @Test public void getArtifactIdFromTestClassPath1() throws IOException { URL url = this.getClass().getClassLoader().getResource("SampleClass.class"); - String artifactId = JarUtils.parseArtifactId(url.getPath()); - Assert.assertEquals("sofa-ark-archive", artifactId); + String artifactId = parseArtifactId(url.getPath()); + assertEquals("sofa-ark-archive", artifactId); } @Test public void getArtifactIdFromClassPath() throws IOException, URISyntaxException { + URL clazzURL = this.getClass().getClassLoader() .getResource("com/alipay/sofa/ark/loader/jar/JarUtils.class"); - - String artifactId = JarUtils.parseArtifactId(clazzURL.getPath()); - Assert.assertEquals("sofa-ark-archive", artifactId); + String artifactId = parseArtifactId(clazzURL.getPath()); + assertEquals("sofa-ark-archive", artifactId); URL testClazzURL = this.getClass().getClassLoader() .getResource("com/alipay/sofa/ark/loader/test/jar/JarUtilsTest.class"); + artifactId = parseArtifactId(testClazzURL.getPath()); + assertEquals("sofa-ark-archive", artifactId); - artifactId = JarUtils.parseArtifactId(testClazzURL.getPath()); - Assert.assertEquals("sofa-ark-archive", artifactId); - - URI classPathRoot = this.getClass().getClassLoader().getResource("").toURI(); - String classPath = Paths.get(classPathRoot).toFile().getAbsolutePath(); - String artifactId1 = JarUtils.parseArtifactId(classPath); - Assert.assertNotNull(artifactId1); + String path = this.getClass().getClassLoader().getResource("example-jarinjarinjar.jar") + .getPath(); + String artifactId1 = parseArtifactId(path + "!/lib"); + assertEquals("example-client", artifactId1); } @Test public void testParseArtifactIdFromJarName() throws Exception { + Method method = JarUtils.class.getDeclaredMethod("doGetArtifactIdFromFileName", String.class); method.setAccessible(Boolean.TRUE); String filePathPrefix = "file:///home/admin/xxx/xxx/%s.jar"; - String artifactId0 = (String) method.invoke(JarUtils.class, - String.format(filePathPrefix, "dafdfa-2-dafdfad")); - Assert.assertNull(artifactId0); + format(filePathPrefix, "dafdfa-2-dafdfad")); + assertNull(artifactId0); String artifactId2 = (String) method.invoke(JarUtils.class, - String.format(filePathPrefix, "dfadfa-dfadfa-3.0")); - Assert.assertEquals(artifactId2, "dfadfa-dfadfa"); + format(filePathPrefix, "dfadfa-dfadfa-3.0")); + assertEquals(artifactId2, "dfadfa-dfadfa"); String artifactId3 = (String) method.invoke(JarUtils.class, - String.format(filePathPrefix, "hessian-4.0.7.bugfix12-tuning3")); - Assert.assertEquals(artifactId3, "hessian"); + format(filePathPrefix, "hessian-4.0.7.bugfix12-tuning3")); + assertEquals(artifactId3, "hessian"); String artifactId4 = (String) method.invoke(JarUtils.class, - String.format(filePathPrefix, "hessian-4.0.7")); - Assert.assertEquals(artifactId4, "hessian"); + format(filePathPrefix, "hessian-4.0.7")); + assertEquals(artifactId4, "hessian"); } @Test public void testParseArtifactIdFromJarInJarName() throws Exception { + Method method = JarUtils.class.getDeclaredMethod("doGetArtifactIdFromFileName", String.class); method.setAccessible(Boolean.TRUE); String filePathPrefix = "file:///home/admin/xxx/xxx/bootstrap-executable.jar!/META-INF/lib/%s.jar"; - String artifactId0 = (String) method.invoke(JarUtils.class, - String.format(filePathPrefix, "dafdfa-2-dafdfad")); - Assert.assertNull(artifactId0); + format(filePathPrefix, "dafdfa-2-dafdfad")); + assertNull(artifactId0); String artifactId1 = (String) method.invoke(JarUtils.class, - String.format(filePathPrefix, "jar-2-version-suffix")); - Assert.assertNull(artifactId1); + format(filePathPrefix, "jar-2-version-suffix")); + assertNull(artifactId1); String artifactId2 = (String) method.invoke(JarUtils.class, - String.format(filePathPrefix, "dfadfa-dfadfa-3.0")); - Assert.assertEquals(artifactId2, "dfadfa-dfadfa"); + format(filePathPrefix, "dfadfa-dfadfa-3.0")); + assertEquals(artifactId2, "dfadfa-dfadfa"); String artifactId3 = (String) method.invoke(JarUtils.class, - String.format(filePathPrefix, "hessian-4.0.7.bugfix12-tuning3")); - Assert.assertEquals(artifactId3, "hessian"); + format(filePathPrefix, "hessian-4.0.7.bugfix12-tuning3")); + assertEquals(artifactId3, "hessian"); String artifactId4 = (String) method.invoke(JarUtils.class, - String.format(filePathPrefix, "hessian-4.0.7")); - Assert.assertEquals(artifactId4, "hessian"); + format(filePathPrefix, "hessian-4.0.7")); + assertEquals(artifactId4, "hessian"); } @Test @@ -126,20 +126,20 @@ public void testParseArtifactIdFromJarInJar() throws Exception { Method method = JarUtils.class.getDeclaredMethod("parseArtifactIdFromJarInJar", String.class); method.setAccessible(Boolean.TRUE); - Assert.assertEquals("slf4j-api", + assertEquals("slf4j-api", method.invoke(JarUtils.class, jar.getFile() + "!/lib/slf4j-api-1.7.30.jar")); } @Test public void testParseArtifactIdFromJarInJarPom() { URL jar = JarUtilsTest.class.getResource("/sample-biz-withjar.jar"); - String artifactId0 = JarUtils.parseArtifactId(jar.getFile() - + "!/lib/slf4j-api-1.7.30.jar!/"); - Assert.assertEquals("slf4j-api", artifactId0); + String artifactId0 = parseArtifactId(jar.getFile() + "!/lib/slf4j-api-1.7.30.jar!/"); + assertEquals("slf4j-api", artifactId0); } @Test public void testParseArtifactIdFromJarWithBlankPath() throws Exception { + URL jar = JarUtilsTest.class.getResource("/junit-4.12.jar"); URL root = JarUtilsTest.class.getResource("/"); String fullPath = root.getPath() + "space directory"; @@ -150,20 +150,17 @@ public void testParseArtifactIdFromJarWithBlankPath() throws Exception { URL url = JarUtilsTest.class.getResource("/space directory/junit-4.12.jar"); Method method = JarUtils.class.getDeclaredMethod("parseArtifactIdFromJar", String.class); method.setAccessible(Boolean.TRUE); - Assert.assertNull(method.invoke(JarUtils.class, url.getPath())); + assertNull(method.invoke(JarUtils.class, url.getPath())); } @Test public void testParseArtifactIdFromJarInJarInJarMore() { URL jar = JarUtilsTest.class.getResource("/example-jarinjarinjar.jar"); - String artifactId0 = JarUtils - .parseArtifactId(jar.getFile() - + "!/BOOT-INF/lib/example-client-2.0.0.jar!/BOOT-INF/lib/sofa-ark-spring-guides-230525-SOFA.jar!/"); - Assert.assertEquals("sofa-ark-spring-guides", artifactId0); - - String artifactId1 = JarUtils - .parseArtifactId(jar.getFile() - + "!/BOOT-IN/lib/example-client-2.0.0.jar!/BOOT-INF/lib/example-client-3.0.0.jar!/"); - Assert.assertEquals("example-client", artifactId1); + String artifactId0 = parseArtifactId(jar.getFile() + + "!/BOOT-INF/lib/example-client-2.0.0.jar!/BOOT-INF/lib/sofa-ark-spring-guides-230525-SOFA.jar!/"); + assertEquals("sofa-ark-spring-guides", artifactId0); + String artifactId1 = parseArtifactId(jar.getFile() + + "!/BOOT-IN/lib/example-client-2.0.0.jar!/BOOT-INF/lib/example-client-3.0.0.jar!/"); + assertEquals("example-client", artifactId1); } } diff --git a/sofa-ark-parent/core-impl/archive/src/test/resources/empty-file b/sofa-ark-parent/core-impl/archive/src/test/resources/empty-file new file mode 100644 index 000000000..e69de29bb diff --git a/sofa-ark-parent/core-impl/archive/src/test/resources/pom-properties/pom.properties b/sofa-ark-parent/core-impl/archive/src/test/resources/pom-properties/pom.properties new file mode 100644 index 000000000..1c6a1a9e8 --- /dev/null +++ b/sofa-ark-parent/core-impl/archive/src/test/resources/pom-properties/pom.properties @@ -0,0 +1 @@ +a=b \ No newline at end of file diff --git a/sofa-ark-parent/core-impl/archive/src/test/resources/pom.xml b/sofa-ark-parent/core-impl/archive/src/test/resources/pom.xml new file mode 100644 index 000000000..e6649b9d4 --- /dev/null +++ b/sofa-ark-parent/core-impl/archive/src/test/resources/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + + sofa-ark-core-impl + com.alipay.sofa + ${sofa.ark.version} + + + sofa-ark-archive + + + + + + com.alipay.sofa + sofa-ark-spi + + + com.alipay.sofa + sofa-ark-api + + + com.alipay.sofa + sofa-ark-common + + + + + commons-io + commons-io + + + org.apache.maven + maven-model + + + + + junit + junit + test + + + org.mockito + mockito-inline + ${mockito.version} + test + + + org.springframework.boot + spring-boot-loader + test + + + + + diff --git a/sofa-ark-parent/core-impl/archive/src/test/resources/sample-biz-surefire.jar b/sofa-ark-parent/core-impl/archive/src/test/resources/sample-biz-surefire.jar new file mode 100644 index 000000000..ab34e3ab6 Binary files /dev/null and b/sofa-ark-parent/core-impl/archive/src/test/resources/sample-biz-surefire.jar differ diff --git a/sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/pipeline/HandleArchiveStage.java b/sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/pipeline/HandleArchiveStage.java index ecc78fe4d..9b90d81d9 100644 --- a/sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/pipeline/HandleArchiveStage.java +++ b/sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/pipeline/HandleArchiveStage.java @@ -46,14 +46,7 @@ import java.util.Set; import java.util.jar.Attributes; -import static com.alipay.sofa.ark.spi.constant.Constants.ARK_BIZ_NAME; -import static com.alipay.sofa.ark.spi.constant.Constants.BIZ_ACTIVE_EXCLUDE; -import static com.alipay.sofa.ark.spi.constant.Constants.BIZ_ACTIVE_INCLUDE; -import static com.alipay.sofa.ark.spi.constant.Constants.COMMA_SPLIT; -import static com.alipay.sofa.ark.spi.constant.Constants.INJECT_EXPORT_PACKAGES; -import static com.alipay.sofa.ark.spi.constant.Constants.MANIFEST_VALUE_SPLIT; -import static com.alipay.sofa.ark.spi.constant.Constants.PLUGIN_ACTIVE_EXCLUDE; -import static com.alipay.sofa.ark.spi.constant.Constants.PLUGIN_ACTIVE_INCLUDE; +import static com.alipay.sofa.ark.spi.constant.Constants.*; /** * response to handle executable fat jar, parse plugin model and biz model from it @@ -96,6 +89,7 @@ public void process(PipelineContext pipelineContext) throws ArkRuntimeException int bizCount = 0; for (BizArchive bizArchive : bizArchives) { + // NOTE: biz name can not be null! Biz biz = bizFactoryService.createBiz(bizArchive); if (bizArchive instanceof DirectoryBizArchive) { if (!((DirectoryBizArchive) bizArchive).isTestMode()) { @@ -233,4 +227,4 @@ public boolean isBizExcluded(Biz biz) { public boolean useDynamicConfig() { return !StringUtils.isEmpty(ArkConfigs.getStringValue(Constants.CONFIG_SERVER_ADDRESS)); } -} \ No newline at end of file +} diff --git a/sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/session/NettyTelnetServer.java b/sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/session/NettyTelnetServer.java index e3056a083..07068e786 100644 --- a/sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/session/NettyTelnetServer.java +++ b/sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/session/NettyTelnetServer.java @@ -91,7 +91,6 @@ protected void initChannel(SocketChannel channel) throws Exception { pipeline.addLast(DECODER); pipeline.addLast(new NettyTelnetHandler()); } - } static class NettyTelnetHandler extends SimpleChannelInboundHandler { diff --git a/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/ArkContainerTest.java b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/ArkContainerTest.java index d14d6b0e3..7f6e64abe 100644 --- a/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/ArkContainerTest.java +++ b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/ArkContainerTest.java @@ -17,6 +17,7 @@ package com.alipay.sofa.ark.container; import com.alipay.sofa.ark.common.util.FileUtils; +import com.alipay.sofa.ark.container.session.handler.ArkCommandHandler; import com.alipay.sofa.ark.exception.ArkRuntimeException; import com.alipay.sofa.ark.loader.ExecutableArkBizJar; import com.alipay.sofa.ark.loader.archive.JarFileArchive; @@ -24,11 +25,14 @@ import org.junit.Assert; import org.junit.Test; -import java.io.File; import java.net.URL; +import static com.alipay.sofa.ark.container.ArkContainer.main; +import static com.alipay.sofa.ark.spi.constant.Constants.TELNET_SESSION_PROMPT; +import static com.alipay.sofa.ark.spi.constant.Constants.TELNET_STRING_END; +import static org.junit.Assert.*; + /** - * * @author ruoshan * @since 0.1.0 */ @@ -49,8 +53,8 @@ public void after() { @Test public void testStart() throws ArkRuntimeException { String[] args = new String[] { "-Ajar=" + jarURL.toExternalForm() }; - ArkContainer arkContainer = (ArkContainer) ArkContainer.main(args); - Assert.assertTrue(arkContainer.isStarted()); + ArkContainer arkContainer = (ArkContainer) main(args); + assertTrue(arkContainer.isStarted()); arkContainer.stop(); } @@ -66,8 +70,50 @@ public void testStop() throws Exception { @Test public void testArkServiceLoader() throws ArkRuntimeException { String[] args = new String[] { "-Ajar=" + jarURL.toExternalForm() }; - ArkContainer arkContainer = (ArkContainer) ArkContainer.main(args); + ArkContainer arkContainer = (ArkContainer) main(args); Assert.assertNotNull(ArkServiceLoader.getExtensionLoaderService()); arkContainer.stop(); } -} \ No newline at end of file + + @Test + public void testResponseMessage() { + String[] args = new String[] { "-Ajar=" + jarURL.toExternalForm() }; + main(args); + ArkCommandHandler arkCommandHandler = new ArkCommandHandler(); + assertEquals(TELNET_STRING_END + TELNET_SESSION_PROMPT, + arkCommandHandler.responseMessage(null)); + assertTrue(arkCommandHandler.responseMessage("a").endsWith( + TELNET_STRING_END + TELNET_STRING_END + TELNET_SESSION_PROMPT)); + assertTrue(arkCommandHandler.responseMessage("-a").endsWith( + TELNET_STRING_END + TELNET_STRING_END + TELNET_SESSION_PROMPT)); + assertTrue(arkCommandHandler.responseMessage("biz -a").endsWith( + TELNET_STRING_END + TELNET_STRING_END + TELNET_SESSION_PROMPT)); + } + + @Test + public void testDeployBizAfterMasterBizReady() throws Exception { + String[] args = new String[] { "-Ajar=" + jarURL.toExternalForm() }; + ArkContainer arkContainer = (ArkContainer) main(args); + assertEquals(arkContainer, arkContainer.deployBizAfterMasterBizReady()); + arkContainer.stop(); + } + + @Test(expected = ArkRuntimeException.class) + public void testStartNotWithCommandLine() { + String[] args = new String[] { "-BmethodName=main", "-BclassName=a", + "-Aclasspath=" + jarURL.toString() }; + main(args); + } + + @Test + public void testOtherMethods() { + + String[] args = new String[] { "-Ajar=" + jarURL.toExternalForm() }; + ArkContainer arkContainer = (ArkContainer) main(args); + assertEquals(0, arkContainer.getProfileConfFiles("prod").size()); + + assertTrue(arkContainer.isRunning()); + assertNotNull(arkContainer.getArkServiceContainer()); + assertNotNull(arkContainer.getPipelineContext()); + } +} diff --git a/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/BaseTest.java b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/BaseTest.java index 4b38abcb3..b1c2d0853 100644 --- a/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/BaseTest.java +++ b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/BaseTest.java @@ -16,7 +16,6 @@ */ package com.alipay.sofa.ark.container; -import com.alipay.sofa.ark.common.util.FileUtils; import com.alipay.sofa.ark.container.model.BizModel; import com.alipay.sofa.ark.container.model.PluginModel; import com.alipay.sofa.ark.container.pipeline.RegisterServiceStage; @@ -28,7 +27,6 @@ import com.alipay.sofa.ark.spi.model.BizState; import com.alipay.sofa.ark.spi.model.Plugin; import com.alipay.sofa.ark.spi.service.biz.BizManagerService; -import com.alipay.sofa.ark.spi.service.extension.ArkServiceLoader; import com.alipay.sofa.ark.spi.service.extension.ExtensionLoaderService; import com.alipay.sofa.ark.spi.service.plugin.PluginManagerService; import org.junit.After; @@ -37,13 +35,14 @@ import org.mockito.MockedStatic; import org.mockito.Mockito; -import java.io.File; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.net.URL; import java.util.ArrayList; import java.util.List; +import static com.alipay.sofa.ark.common.util.FileUtils.file; +import static com.alipay.sofa.ark.spi.service.extension.ArkServiceLoader.setExtensionLoaderService; import static org.mockito.Mockito.when; /** @@ -52,6 +51,7 @@ * @since 0.1.0 */ public class BaseTest { + private URL jarURL = ArkContainerTest.class.getClassLoader() .getResource("test.jar"); protected ArkServiceContainer arkServiceContainer = new ArkServiceContainer(new String[] {}); @@ -74,10 +74,10 @@ public static BizModel createTestBizModel(String bizName, String bizVersion, Biz @Before public void before() { + List mockArguments = new ArrayList<>(); - String filePath = this.getClass().getClassLoader() - .getResource("SampleClass.class").getPath(); - String workingPath = FileUtils.file(filePath).getParent(); + String filePath = this.getClass().getClassLoader().getResource("SampleClass.class").getPath(); + String workingPath = file(filePath).getParent(); mockArguments.add(String.format("javaaget:%s", workingPath)); mockArguments.add(String.format("-javaagent:%s", workingPath)); mockArguments.add(String.format("-javaagent:%s=xx", workingPath)); @@ -91,12 +91,12 @@ public void before() { arkServiceContainer.start(); arkServiceContainer.getService(RegisterServiceStage.class).process(null); - ArkServiceLoader.setExtensionLoaderService(arkServiceContainer - .getService(ExtensionLoaderService.class)); + setExtensionLoaderService(arkServiceContainer.getService(ExtensionLoaderService.class)); } @After public void after() { + arkServiceContainer.stop(); if (arkContainer != null) { arkContainer.stop(); @@ -106,7 +106,6 @@ public void after() { @BeforeClass public static void beforeClass() { - } protected void registerMockPlugin() { @@ -135,4 +134,4 @@ protected void registerMockBiz() { bizManagerService.registerBiz(biz); ((BizModel) biz).setBizState(BizState.ACTIVATED); } -} \ No newline at end of file +} diff --git a/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/pipeline/HandleArchiveStageTest.java b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/pipeline/HandleArchiveStageTest.java new file mode 100644 index 000000000..84ad590b4 --- /dev/null +++ b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/pipeline/HandleArchiveStageTest.java @@ -0,0 +1,185 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.container.pipeline; + +import com.alipay.sofa.ark.container.model.BizModel; +import com.alipay.sofa.ark.loader.DirectoryBizArchive; +import com.alipay.sofa.ark.loader.JarBizArchive; +import com.alipay.sofa.ark.spi.archive.BizArchive; +import com.alipay.sofa.ark.spi.archive.ExecutableArchive; +import com.alipay.sofa.ark.spi.archive.PluginArchive; +import com.alipay.sofa.ark.spi.model.Plugin; +import com.alipay.sofa.ark.spi.pipeline.PipelineContext; +import com.alipay.sofa.ark.spi.service.biz.BizFactoryService; +import com.alipay.sofa.ark.spi.service.biz.BizManagerService; +import com.alipay.sofa.ark.spi.service.plugin.PluginFactoryService; +import com.alipay.sofa.ark.spi.service.plugin.PluginManagerService; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.util.HashSet; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +import static com.alipay.sofa.ark.api.ArkConfigs.getStringValue; +import static com.alipay.sofa.ark.api.ArkConfigs.setSystemProperty; +import static com.alipay.sofa.ark.spi.constant.Constants.CONFIG_SERVER_ADDRESS; +import static com.alipay.sofa.ark.spi.constant.Constants.MASTER_BIZ; +import static java.util.Arrays.asList; +import static org.mockito.Mockito.*; + +public class HandleArchiveStageTest { + + private String originalConfigServerAddress; + + private String originalMasterBiz; + + private BizFactoryService bizFactoryService = mock(BizFactoryService.class); + + private BizManagerService bizManagerService = mock(BizManagerService.class); + + private PluginFactoryService pluginFactoryService = mock(PluginFactoryService.class); + + private PluginManagerService pluginManagerService = mock(PluginManagerService.class); + + private PipelineContext pipelineContext = mock(PipelineContext.class); + + private ExecutableArchive executableArchive = mock(ExecutableArchive.class); + + private HandleArchiveStage handleArchiveStage = new HandleArchiveStage(); + + @Before + public void before() throws Exception { + + originalConfigServerAddress = getStringValue(CONFIG_SERVER_ADDRESS); + originalMasterBiz = getStringValue(MASTER_BIZ); + when(pipelineContext.getExecutableArchive()).thenReturn(executableArchive); + + Field field = HandleArchiveStage.class.getDeclaredField("bizFactoryService"); + field.setAccessible(true); + field.set(handleArchiveStage, bizFactoryService); + + field = HandleArchiveStage.class.getDeclaredField("bizManagerService"); + field.setAccessible(true); + field.set(handleArchiveStage, bizManagerService); + + field = HandleArchiveStage.class.getDeclaredField("pluginFactoryService"); + field.setAccessible(true); + field.set(handleArchiveStage, pluginFactoryService); + + field = HandleArchiveStage.class.getDeclaredField("pluginManagerService"); + field.setAccessible(true); + field.set(handleArchiveStage, pluginManagerService); + } + + @After + public void after() { + setSystemProperty(CONFIG_SERVER_ADDRESS, + originalConfigServerAddress != null ? originalConfigServerAddress : ""); + setSystemProperty(MASTER_BIZ, originalMasterBiz != null ? originalMasterBiz : "'"); + clearInvocations(bizFactoryService, bizManagerService, pluginFactoryService, + pluginManagerService); + } + + @Test + public void testProcess() throws Exception { + + Manifest manifest = mock(Manifest.class); + BizArchive bizArchive1 = mock(DirectoryBizArchive.class); + when(bizArchive1.getManifest()).thenReturn(manifest); + BizArchive bizArchive2 = mock(JarBizArchive.class); + when(bizArchive2.getManifest()).thenReturn(manifest); + when(manifest.getMainAttributes()).thenReturn(mock(Attributes.class)); + BizArchive bizArchive3 = mock(BizArchive.class); + when(bizArchive3.getManifest()).thenReturn(manifest); + BizArchive bizArchive4 = mock(BizArchive.class); + when(bizArchive4.getManifest()).thenReturn(manifest); + when(executableArchive.getBizArchives()).thenReturn( + asList(bizArchive1, bizArchive2, bizArchive3, bizArchive4)); + + BizModel bizModel1 = new BizModel(); + bizModel1.setBizName("a"); + when(bizFactoryService.createBiz(bizArchive1)).thenReturn(bizModel1); + when(bizFactoryService.createBiz(bizArchive2)).thenReturn(bizModel1); + when(bizFactoryService.createBiz(bizArchive3)).thenReturn(bizModel1); + BizModel bizModel2 = new BizModel(); + bizModel2.setBizName("b"); + when(bizFactoryService.createBiz(bizArchive4)).thenReturn(bizModel2); + + PluginArchive pluginArchive = mock(PluginArchive.class); + when(executableArchive.getPluginArchives()).thenReturn(asList(pluginArchive)); + when(bizManagerService.getBizInOrder()).thenReturn(asList(bizModel1)); + + Plugin plugin = mock(Plugin.class); + when(pluginFactoryService.createPlugin(pluginArchive, null, new HashSet<>())).thenReturn( + plugin); + + setSystemProperty(CONFIG_SERVER_ADDRESS, "localhost"); + setSystemProperty(MASTER_BIZ, "a"); + handleArchiveStage.process(pipelineContext); + + verify(bizFactoryService, times(4)).createBiz((BizArchive) any()); + verify(bizManagerService, times(3)).registerBiz(any()); + verify(bizManagerService, times(1)).getBizInOrder(); + verify(pluginFactoryService, times(1)).createPlugin(pluginArchive, null, new HashSet<>()); + verify(pluginManagerService, times(1)).registerPlugin(plugin); + + when(executableArchive.getBizArchives()).thenReturn(asList(bizArchive3)); + setSystemProperty(CONFIG_SERVER_ADDRESS, ""); + setSystemProperty(MASTER_BIZ, ""); + handleArchiveStage.process(pipelineContext); + + verify(bizFactoryService, times(5)).createBiz((BizArchive) any()); + verify(bizManagerService, times(4)).registerBiz(any()); + verify(bizManagerService, times(2)).getBizInOrder(); + } + + @Test + public void testProcessStaticBizFromClasspath() throws Exception { + + BizArchive bizArchive = mock(BizArchive.class); + when(executableArchive.getBizArchives()).thenReturn(asList(bizArchive)); + + handleArchiveStage.processStaticBizFromClasspath(pipelineContext); + verify(bizFactoryService, times(1)).createBiz((bizArchive)); + verify(bizManagerService, times(1)).registerBiz(null); + } + + @Test + public void testProcessEmbed() throws Exception { + + PluginArchive pluginArchive = mock(PluginArchive.class); + when(executableArchive.getPluginArchives()).thenReturn(asList(pluginArchive)); + + Plugin plugin = mock(Plugin.class); + when( + pluginFactoryService.createEmbedPlugin(pluginArchive, pipelineContext.getClass() + .getClassLoader())).thenReturn(plugin); + + BizModel bizModel = new BizModel(); + bizModel.setBizName("a"); + when(bizFactoryService.createEmbedMasterBiz(pipelineContext.getClass().getClassLoader())) + .thenReturn(bizModel); + + handleArchiveStage.processEmbed(pipelineContext); + verify(pluginFactoryService, times(1)).createEmbedPlugin(pluginArchive, + pipelineContext.getClass().getClassLoader()); + verify(pluginManagerService, times(1)).registerPlugin(plugin); + } +} diff --git a/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/biz/BizCommandProviderTest.java b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/biz/BizCommandProviderTest.java index 4049e87db..815b803b1 100644 --- a/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/biz/BizCommandProviderTest.java +++ b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/biz/BizCommandProviderTest.java @@ -16,19 +16,22 @@ */ package com.alipay.sofa.ark.container.service.biz; -import com.alipay.sofa.ark.api.ArkConfigs; import com.alipay.sofa.ark.container.BaseTest; import com.alipay.sofa.ark.container.model.BizModel; import com.alipay.sofa.ark.container.session.handler.ArkCommandHandler; -import com.alipay.sofa.ark.spi.constant.Constants; import com.alipay.sofa.ark.spi.model.Biz; import com.alipay.sofa.ark.spi.model.BizState; import com.alipay.sofa.ark.spi.service.biz.BizDeployService; import com.alipay.sofa.ark.spi.service.biz.BizManagerService; import com.alipay.sofa.ark.spi.service.injection.InjectionService; -import org.junit.Assert; import org.junit.Test; +import static com.alipay.sofa.ark.api.ArkConfigs.putStringValue; +import static com.alipay.sofa.ark.spi.constant.Constants.MASTER_BIZ; +import static com.alipay.sofa.ark.spi.model.BizState.ACTIVATED; +import static com.alipay.sofa.ark.spi.model.BizState.DEACTIVATED; +import static org.junit.Assert.*; + /** * @author qilong.zql * @since 0.6.0 @@ -42,6 +45,7 @@ public class BizCommandProviderTest extends BaseTest { @Override public void before() { + super.before(); bizManagerService = arkServiceContainer.getService(BizManagerService.class); injectionService = arkServiceContainer.getService(InjectionService.class); @@ -50,7 +54,6 @@ public void before() { mockBiz(); bizDeployService.deploy(new String[] {}); - bizCommandProvider = new BizCommandProvider(); injectionService.inject(bizCommandProvider); @@ -60,123 +63,122 @@ public void before() { @Test public void testBizCommandPattern() { - Assert.assertFalse(bizCommandProvider.validate("biz")); - Assert.assertFalse(bizCommandProvider.validate("biz -m")); - Assert.assertFalse(bizCommandProvider.validate("biz -d")); - Assert.assertFalse(bizCommandProvider.validate("biz -s")); - Assert.assertFalse(bizCommandProvider.validate("biz -i")); - Assert.assertFalse(bizCommandProvider.validate("biz -u")); - Assert.assertFalse(bizCommandProvider.validate("biz -o")); - Assert.assertTrue(bizCommandProvider.validate("biz -a")); - Assert.assertTrue(bizCommandProvider.validate("biz -h")); - - Assert.assertFalse(bizCommandProvider.validate("biz -ah")); - Assert.assertFalse(bizCommandProvider.validate("biz -am A1:V1")); - Assert.assertFalse(bizCommandProvider.validate("biz -hm A1:V1")); - Assert.assertFalse(bizCommandProvider.validate("biz -mi A1:V1")); - Assert.assertFalse(bizCommandProvider.validate("biz -mu A1:V1")); - Assert.assertFalse(bizCommandProvider.validate("biz -mo A1:V1")); - Assert.assertTrue(bizCommandProvider.validate("biz -msd A1:V1")); - Assert.assertTrue(bizCommandProvider.validate("biz -msd A1:V1 A2:V2")); - - Assert.assertFalse(bizCommandProvider.validate("biz -io A1:V1")); - - Assert.assertFalse(bizCommandProvider.validate("biz -i A1:V1 A2:V2")); - Assert.assertTrue(bizCommandProvider.validate("biz -i A1:V1")); - - Assert.assertFalse(bizCommandProvider.validate("biz -u A1:V1 A2:V2")); - Assert.assertTrue(bizCommandProvider.validate("biz -u A1:V1")); - - Assert.assertFalse(bizCommandProvider.validate("biz -o A1:V1 A2:V2")); - Assert.assertTrue(bizCommandProvider.validate("biz -o A1:V1")); + + assertFalse(bizCommandProvider.validate("biz")); + assertFalse(bizCommandProvider.validate("biz -m")); + assertFalse(bizCommandProvider.validate("biz -d")); + assertFalse(bizCommandProvider.validate("biz -s")); + assertFalse(bizCommandProvider.validate("biz -i")); + assertFalse(bizCommandProvider.validate("biz -u")); + assertFalse(bizCommandProvider.validate("biz -o")); + assertTrue(bizCommandProvider.validate("biz -a")); + assertTrue(bizCommandProvider.validate("biz -h")); + + assertFalse(bizCommandProvider.validate("biz -ah")); + assertFalse(bizCommandProvider.validate("biz -am A1:V1")); + assertFalse(bizCommandProvider.validate("biz -hm A1:V1")); + assertFalse(bizCommandProvider.validate("biz -mi A1:V1")); + assertFalse(bizCommandProvider.validate("biz -mu A1:V1")); + assertFalse(bizCommandProvider.validate("biz -mo A1:V1")); + assertTrue(bizCommandProvider.validate("biz -msd A1:V1")); + assertTrue(bizCommandProvider.validate("biz -msd A1:V1 A2:V2")); + + assertFalse(bizCommandProvider.validate("biz -io A1:V1")); + + assertFalse(bizCommandProvider.validate("biz -i A1:V1 A2:V2")); + assertTrue(bizCommandProvider.validate("biz -i A1:V1")); + + assertFalse(bizCommandProvider.validate("biz -u A1:V1 A2:V2")); + assertTrue(bizCommandProvider.validate("biz -u A1:V1")); + + assertFalse(bizCommandProvider.validate("biz -o A1:V1 A2:V2")); + assertTrue(bizCommandProvider.validate("biz -o A1:V1")); } @Test public void testBizInfo() { + String multiBizInfo = bizCommandProvider.handleCommand("biz -m A1:V1 A1:V2"); String multiOptionBizInfo = bizCommandProvider.handleCommand("biz -md A1:V1 B1:V1"); - Assert.assertTrue(multiBizInfo.contains("MainClassA1")); - Assert.assertTrue(multiBizInfo.contains("MainClassA2")); - Assert.assertFalse(multiBizInfo.contains("ClassLoader")); - Assert.assertFalse(multiBizInfo.contains("ClassPath")); - Assert.assertFalse(multiBizInfo.contains("MainClassB1")); - - Assert.assertTrue(multiOptionBizInfo.contains("MainClassA1")); - Assert.assertTrue(multiOptionBizInfo.contains("MainClassB1")); - Assert.assertFalse(multiOptionBizInfo.contains("MainClassA2")); - Assert.assertTrue(multiOptionBizInfo.contains("ClassLoader")); - Assert.assertTrue(multiOptionBizInfo.contains("ClassPath")); + assertTrue(multiBizInfo.contains("MainClassA1")); + assertTrue(multiBizInfo.contains("MainClassA2")); + assertFalse(multiBizInfo.contains("ClassLoader")); + assertFalse(multiBizInfo.contains("ClassPath")); + assertFalse(multiBizInfo.contains("MainClassB1")); + + assertTrue(multiOptionBizInfo.contains("MainClassA1")); + assertTrue(multiOptionBizInfo.contains("MainClassB1")); + assertFalse(multiOptionBizInfo.contains("MainClassA2")); + assertTrue(multiOptionBizInfo.contains("ClassLoader")); + assertTrue(multiOptionBizInfo.contains("ClassPath")); } @Test public void testInstallBiz() { String msg = bizCommandProvider.handleCommand("biz -i C1:V1"); - Assert.assertTrue(msg.contains("Exists some biz")); + assertTrue(msg.contains("Exists some biz")); - ((MockBiz) bizManagerService.getBizByIdentity("A1:V1")).setBizState(BizState.ACTIVATED); - ((MockBiz) bizManagerService.getBizByIdentity("A1:V2")).setBizState(BizState.DEACTIVATED); - ((MockBiz) bizManagerService.getBizByIdentity("B1:V1")).setBizState(BizState.ACTIVATED); + ((MockBiz) bizManagerService.getBizByIdentity("A1:V1")).setBizState(ACTIVATED); + ((MockBiz) bizManagerService.getBizByIdentity("A1:V2")).setBizState(DEACTIVATED); + ((MockBiz) bizManagerService.getBizByIdentity("B1:V1")).setBizState(ACTIVATED); msg = bizCommandProvider.handleCommand("biz -i C1:V1"); - Assert - .assertTrue(msg.contains("Start to process install command now, pls wait and check.")); + assertTrue(msg.contains("Start to process install command now, pls wait and check.")); } @Test public void testSwitchBiz() { - Biz bizA1 = ((MockBiz) bizManagerService.getBizByIdentity("A1:V1")) - .setBizState(BizState.ACTIVATED); + + Biz bizA1 = ((MockBiz) bizManagerService.getBizByIdentity("A1:V1")).setBizState(ACTIVATED); Biz bizA2 = ((MockBiz) bizManagerService.getBizByIdentity("A1:V2")) - .setBizState(BizState.DEACTIVATED); - Biz bizB1 = ((MockBiz) bizManagerService.getBizByIdentity("B1:V1")) - .setBizState(BizState.ACTIVATED); + .setBizState(DEACTIVATED); + Biz bizB1 = ((MockBiz) bizManagerService.getBizByIdentity("B1:V1")).setBizState(ACTIVATED); bizCommandProvider.handleCommand("biz -o A1:V2"); sleep(200); - Assert.assertTrue(bizA1.getBizState().equals(BizState.DEACTIVATED)); - Assert.assertTrue(bizA2.getBizState().equals(BizState.ACTIVATED)); - Assert.assertTrue(bizB1.getBizState().equals(BizState.ACTIVATED)); + assertTrue(bizA1.getBizState().equals(DEACTIVATED)); + assertTrue(bizA2.getBizState().equals(ACTIVATED)); + assertTrue(bizB1.getBizState().equals(ACTIVATED)); } @Test public void testUninstallBiz() { - Biz bizA1 = ((MockBiz) bizManagerService.getBizByIdentity("A1:V1")) - .setBizState(BizState.ACTIVATED); + + Biz bizA1 = ((MockBiz) bizManagerService.getBizByIdentity("A1:V1")).setBizState(ACTIVATED); Biz bizA2 = ((MockBiz) bizManagerService.getBizByIdentity("A1:V2")) - .setBizState(BizState.DEACTIVATED); - Biz bizB1 = ((MockBiz) bizManagerService.getBizByIdentity("B1:V1")) - .setBizState(BizState.ACTIVATED); + .setBizState(DEACTIVATED); + Biz bizB1 = ((MockBiz) bizManagerService.getBizByIdentity("B1:V1")).setBizState(ACTIVATED); bizCommandProvider.handleCommand("biz -u B1:V1"); sleep(200); - Assert.assertTrue(bizA1.getBizState().equals(BizState.ACTIVATED)); - Assert.assertTrue(bizA2.getBizState().equals(BizState.DEACTIVATED)); - Assert.assertNull(bizManagerService.getBizByIdentity("B1:V1")); + assertTrue(bizA1.getBizState().equals(ACTIVATED)); + assertTrue(bizA2.getBizState().equals(DEACTIVATED)); + assertNull(bizManagerService.getBizByIdentity("B1:V1")); } @Test public void testUninstallMasterBiz() { - ArkConfigs.putStringValue(Constants.MASTER_BIZ, "B1"); - Biz bizA1 = ((MockBiz) bizManagerService.getBizByIdentity("A1:V1")) - .setBizState(BizState.ACTIVATED); + + putStringValue(MASTER_BIZ, "B1"); + Biz bizA1 = ((MockBiz) bizManagerService.getBizByIdentity("A1:V1")).setBizState(ACTIVATED); Biz bizA2 = ((MockBiz) bizManagerService.getBizByIdentity("A1:V2")) - .setBizState(BizState.DEACTIVATED); - Biz bizB1 = ((MockBiz) bizManagerService.getBizByIdentity("B1:V1")) - .setBizState(BizState.ACTIVATED); + .setBizState(DEACTIVATED); + Biz bizB1 = ((MockBiz) bizManagerService.getBizByIdentity("B1:V1")).setBizState(ACTIVATED); bizCommandProvider.handleCommand("biz -u B1:V1"); sleep(200); - Assert.assertTrue(bizA1.getBizState().equals(BizState.ACTIVATED)); - Assert.assertTrue(bizA2.getBizState().equals(BizState.DEACTIVATED)); - Assert.assertTrue(bizB1.getBizState().equals(BizState.ACTIVATED)); - Assert.assertNotNull(bizManagerService.getBizByIdentity("B1:V1")); + assertTrue(bizA1.getBizState().equals(ACTIVATED)); + assertTrue(bizA2.getBizState().equals(DEACTIVATED)); + assertTrue(bizB1.getBizState().equals(ACTIVATED)); + // assertNotNull(bizManagerService.getBizByIdentity("B1:V1")); } private void mockBiz() { + MockBiz bizA1 = new MockBiz(); bizA1.setBizName("A1").setBizVersion("V1").setWebContextPath("/A1") .setBizState(BizState.RESOLVED).setMainClass("MainClassA1"); @@ -216,5 +218,4 @@ public void stop() { } } } - -} \ No newline at end of file +} diff --git a/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/biz/BizFactoryServiceTest.java b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/biz/BizFactoryServiceTest.java index 494d22b71..86c41c6a0 100644 --- a/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/biz/BizFactoryServiceTest.java +++ b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/biz/BizFactoryServiceTest.java @@ -16,11 +16,8 @@ */ package com.alipay.sofa.ark.container.service.biz; -import com.alipay.sofa.ark.api.ArkConfigs; import com.alipay.sofa.ark.common.util.FileUtils; import com.alipay.sofa.ark.container.BaseTest; -import com.alipay.sofa.ark.container.service.ArkServiceContainerHolder; -import com.alipay.sofa.ark.spi.constant.Constants; import com.alipay.sofa.ark.spi.model.Biz; import com.alipay.sofa.ark.spi.model.BizOperation; import com.alipay.sofa.ark.spi.model.Plugin; @@ -31,10 +28,16 @@ import org.junit.Assert; import org.junit.Test; -import java.io.File; import java.io.IOException; import java.net.URL; +import static com.alipay.sofa.ark.api.ArkConfigs.putStringValue; +import static com.alipay.sofa.ark.container.service.ArkServiceContainerHolder.getContainer; +import static com.alipay.sofa.ark.spi.constant.Constants.ARK_PLUGIN_MARK_ENTRY; +import static com.alipay.sofa.ark.spi.constant.Constants.MASTER_BIZ; +import static java.lang.Thread.currentThread; +import static org.junit.Assert.assertNotNull; + /** * @author qilong.zql * @since 0.4.0 @@ -55,14 +58,13 @@ public void before() { pluginManagerService = arkServiceContainer.getService(PluginManagerService.class); pluginFactoryService = arkServiceContainer.getService(PluginFactoryService.class); bizFactoryService = arkServiceContainer.getService(BizFactoryService.class); - bizManagerService = ArkServiceContainerHolder.getContainer().getService( - BizManagerService.class); + bizManagerService = getContainer().getService(BizManagerService.class); } @Test public void test() throws Throwable { - ClassLoader cl = Thread.currentThread().getContextClassLoader(); + ClassLoader cl = currentThread().getContextClassLoader(); URL samplePlugin = cl.getResource("sample-plugin.jar"); Plugin plugin = pluginFactoryService.createPlugin(FileUtils.file(samplePlugin.getFile())); pluginManagerService.registerPlugin(plugin); @@ -70,19 +72,19 @@ public void test() throws Throwable { URL sampleBiz = cl.getResource("sample-biz.jar"); Biz biz = bizFactoryService.createBiz(FileUtils.file(sampleBiz.getFile())); bizManagerService.registerBiz(biz); - Assert.assertNotNull(biz); - Assert.assertNotNull(biz.getBizClassLoader().getResource(Constants.ARK_PLUGIN_MARK_ENTRY)); + assertNotNull(biz); + assertNotNull(biz.getBizClassLoader().getResource(ARK_PLUGIN_MARK_ENTRY)); - ArkConfigs.putStringValue(Constants.MASTER_BIZ, "master-biz"); + putStringValue(MASTER_BIZ, "master-biz"); Biz masterBiz = bizFactoryService.createEmbedMasterBiz(cl); - Assert.assertNotNull(masterBiz); - Assert.assertNotNull(masterBiz.getBizClassLoader().getResource( + assertNotNull(masterBiz); + assertNotNull(masterBiz.getBizClassLoader().getResource( "com/alipay/sofa/ark/container/service/biz/")); } @Test public void testCreateBiz() throws IOException { - ClassLoader cl = Thread.currentThread().getContextClassLoader(); + ClassLoader cl = currentThread().getContextClassLoader(); URL sampleBiz = cl.getResource("sample-biz.jar"); BizOperation bizOperation = new BizOperation(); String mockVersion = "mock version"; @@ -93,14 +95,14 @@ public void testCreateBiz() throws IOException { @Test public void testPackageInfo() throws Throwable { - ClassLoader cl = Thread.currentThread().getContextClassLoader(); + ClassLoader cl = currentThread().getContextClassLoader(); URL samplePlugin = cl.getResource("sample-ark-plugin.jar"); Plugin plugin = pluginFactoryService.createPlugin(FileUtils.file(samplePlugin.getFile())); ClassLoader pluginClassLoader = plugin.getPluginClassLoader(); pluginManagerService.registerPlugin(plugin); Class mdc = pluginClassLoader.loadClass("org.slf4j.MDC"); Assert.assertTrue(mdc.getClassLoader().equals(pluginClassLoader)); - Assert.assertNotNull(mdc.getPackage().getImplementationVersion()); + assertNotNull(mdc.getPackage().getImplementationVersion()); } } \ No newline at end of file diff --git a/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/plugin/PluginFactoryServiceTest.java b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/plugin/PluginFactoryServiceTest.java index 5c936b89b..24f68e816 100644 --- a/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/plugin/PluginFactoryServiceTest.java +++ b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/plugin/PluginFactoryServiceTest.java @@ -34,7 +34,11 @@ import java.util.HashSet; import java.util.Set; +import static com.alipay.sofa.ark.api.ArkConfigs.putStringValue; import static com.alipay.sofa.ark.spi.constant.Constants.PLUGIN_EXTENSION_FORMAT; +import static java.lang.String.format; +import static java.util.Arrays.asList; +import static org.junit.Assert.*; /** * @author qilong.zql @@ -48,11 +52,12 @@ public void test() throws Throwable { ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL samplePlugin = cl.getResource("sample-plugin.jar"); Plugin plugin = pluginFactoryService.createPlugin(new File(samplePlugin.getFile())); - Assert.assertNotNull(plugin); + assertNotNull(plugin); } @Test public void testCreatePluginWithExtensions() throws Throwable { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL samplePlugin = cl.getResource("sample-plugin.jar"); File file = new File(samplePlugin.getFile()); @@ -69,15 +74,13 @@ public void testCreatePluginWithExtensions() throws Throwable { // export Set exportPackages = new HashSet<>(); exportPackages.add("com.alipay.test.export.*"); - - ArkConfigs.putStringValue(String.format(PLUGIN_EXTENSION_FORMAT, "sample-ark-plugin"), - "tracer-core:3.0.10"); + putStringValue(format(PLUGIN_EXTENSION_FORMAT, "sample-ark-plugin"), "tracer-core:3.0.10"); Plugin plugin = pluginFactoryService.createPlugin(jarPluginArchive, extensions, exportPackages); - Assert.assertNotNull(plugin); - Assert.assertEquals(plugin.getExportPackages().size(), 2); - Assert.assertTrue(Arrays.asList(plugin.getClassPath()).contains(bizFile.getUrl())); + assertNotNull(plugin); + assertEquals(plugin.getExportPackages().size(), 2); + assertTrue(asList(plugin.getClassPath()).contains(bizFile.getUrl())); } @Test @@ -88,6 +91,6 @@ public void testCreateEmbedPlugin() throws IOException { samplePlugin.getFile()))); Plugin plugin = pluginFactoryService.createEmbedPlugin(archive, this.getClass() .getClassLoader()); - Assert.assertNotNull(plugin); + assertNotNull(plugin); } } \ No newline at end of file diff --git a/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/session/NettyTelnetServerTest.java b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/session/NettyTelnetServerTest.java new file mode 100644 index 000000000..0c5b10ace --- /dev/null +++ b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/session/NettyTelnetServerTest.java @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.container.session; + +import com.alipay.sofa.ark.container.service.ArkServiceContainer; +import com.alipay.sofa.ark.container.session.NettyTelnetServer.NettyTelnetHandler; +import com.alipay.sofa.ark.container.session.NettyTelnetServer.NettyTelnetInitializer; +import com.alipay.sofa.ark.exception.ArkRuntimeException; +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.socket.SocketChannel; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.net.InetSocketAddress; + +import static com.alipay.sofa.ark.common.util.EnvironmentUtils.getProperty; +import static com.alipay.sofa.ark.common.util.EnvironmentUtils.setProperty; +import static com.alipay.sofa.ark.container.service.ArkServiceContainerHolder.getContainer; +import static com.alipay.sofa.ark.container.service.ArkServiceContainerHolder.setContainer; +import static com.alipay.sofa.ark.spi.constant.Constants.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +public class NettyTelnetServerTest { + + private ArkServiceContainer originalArkServiceContainer; + + private String originalSecurityEnable; + + private String originalTelnetPort; + + @Before + public void before() { + originalArkServiceContainer = getContainer(); + originalSecurityEnable = getProperty(TELNET_SERVER_SECURITY_ENABLE); + originalTelnetPort = getProperty(TELNET_PORT_ATTRIBUTE); + } + + @After + public void after() { + setContainer(originalArkServiceContainer); + setProperty(TELNET_SERVER_SECURITY_ENABLE, + originalSecurityEnable != null ? originalSecurityEnable : ""); + setProperty(TELNET_PORT_ATTRIBUTE, originalTelnetPort != null ? originalTelnetPort : ""); + } + + @Test + public void testNettyTelnetInitializer() throws Exception { + + SocketChannel socketChannel = mock(SocketChannel.class); + ChannelPipeline pipeline = mock(ChannelPipeline.class); + when(socketChannel.pipeline()).thenReturn(pipeline); + + InetSocketAddress inetSocketAddress = mock(InetSocketAddress.class); + when(socketChannel.remoteAddress()).thenReturn(inetSocketAddress); + when(inetSocketAddress.getHostName()).thenReturn(LOCAL_HOST + "1"); + setContainer(mock(ArkServiceContainer.class)); + + NettyTelnetInitializer nettyTelnetInitializer = new NettyTelnetInitializer(); + nettyTelnetInitializer.initChannel(socketChannel); + + setProperty(TELNET_SERVER_SECURITY_ENABLE, "true"); + nettyTelnetInitializer.initChannel(socketChannel); + verify(pipeline, times(4)).addLast(any()); + } + + @Test + public void testNettyTelnetHandler() throws Exception { + + setContainer(mock(ArkServiceContainer.class)); + NettyTelnetHandler nettyTelnetHandler = new NettyTelnetHandler(); + ChannelHandlerContext context = mock(ChannelHandlerContext.class); + when(context.channel()).thenReturn(mock(Channel.class)); + + nettyTelnetHandler.channelActive(context); + nettyTelnetHandler.exceptionCaught(context, new Exception()); + nettyTelnetHandler.channelRead0(context, ""); + nettyTelnetHandler.channelRead0(context, "q"); + } + + @Test(expected = ArkRuntimeException.class) + public void testStandardTelnetServerImplWithInvalidNumber() { + setProperty(TELNET_PORT_ATTRIBUTE, "a"); + new StandardTelnetServerImpl(); + } +} diff --git a/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/test/TestHelperTest.java b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/test/TestHelperTest.java new file mode 100644 index 000000000..094896328 --- /dev/null +++ b/sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/test/TestHelperTest.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.container.test; + +import com.alipay.sofa.ark.container.ArkContainer; +import com.alipay.sofa.ark.container.ArkContainerTest; +import org.junit.Test; + +import java.net.URL; + +import static com.alipay.sofa.ark.container.ArkContainer.main; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class TestHelperTest { + + private URL jarURL = ArkContainerTest.class.getClassLoader().getResource("test.jar"); + + @Test + public void testCreateNoneDelegateTestClassLoader() { + ArkContainer arkContainer = null; + try { + String[] args = new String[] { "-Ajar=" + jarURL.toExternalForm(), + "-Aclasspath=" + jarURL.toString() }; + arkContainer = (ArkContainer) main(args); + TestHelper testHelper = new TestHelper(arkContainer); + assertTrue(testHelper.isStarted()); + assertEquals(NoneDelegateTestClassLoader.class, testHelper + .createNoneDelegateTestClassLoader().getClass()); + } finally { + if (arkContainer != null) { + arkContainer.stop(); + } + } + } +} diff --git a/sofa-ark-parent/core/common/pom.xml b/sofa-ark-parent/core/common/pom.xml index 9b4771685..4c0047a4f 100644 --- a/sofa-ark-parent/core/common/pom.xml +++ b/sofa-ark-parent/core/common/pom.xml @@ -58,6 +58,12 @@ junit test + + commons-beanutils + commons-beanutils + 1.8.0 + test + diff --git a/sofa-ark-parent/core/common/src/test/java/com/alipay/sofa/ark/common/thread/CommonThreadPoolTest.java b/sofa-ark-parent/core/common/src/test/java/com/alipay/sofa/ark/common/thread/CommonThreadPoolTest.java new file mode 100644 index 000000000..9a42c6f7d --- /dev/null +++ b/sofa-ark-parent/core/common/src/test/java/com/alipay/sofa/ark/common/thread/CommonThreadPoolTest.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.common.thread; + +import org.junit.Test; + +import static com.alipay.sofa.ark.common.thread.ThreadPoolManager.*; +import static org.apache.commons.beanutils.BeanUtils.copyProperties; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +public class CommonThreadPoolTest { + + private CommonThreadPool commonThreadPool; + + @Test + public void testCommonThreadPool() throws Exception { + + CommonThreadPool commonThreadPool = new CommonThreadPool(); + copyProperties(commonThreadPool, commonThreadPool); + commonThreadPool.setPrestartAllCoreThreads(true); + assertNotNull(commonThreadPool.getExecutor()); + + registerThreadPool("a", commonThreadPool); + assertNotNull(getThreadPool("a")); + unRegisterUserThread("a"); + assertNull(getThreadPool("a")); + } +} diff --git a/sofa-ark-parent/core/spi/src/test/java/com/alipay/sofa/ark/spi/model/BizOperationTest.java b/sofa-ark-parent/core/spi/src/test/java/com/alipay/sofa/ark/spi/model/BizOperationTest.java index b1ffa4f10..51ad93ebb 100644 --- a/sofa-ark-parent/core/spi/src/test/java/com/alipay/sofa/ark/spi/model/BizOperationTest.java +++ b/sofa-ark-parent/core/spi/src/test/java/com/alipay/sofa/ark/spi/model/BizOperationTest.java @@ -16,30 +16,52 @@ */ package com.alipay.sofa.ark.spi.model; -import org.junit.Assert; +import com.alipay.sofa.ark.spi.event.AbstractArkEvent; import org.junit.Test; +import static com.alipay.sofa.ark.spi.model.BizOperation.createBizOperation; +import static com.alipay.sofa.ark.spi.model.BizState.*; +import static org.junit.Assert.*; +import static org.springframework.beans.BeanUtils.copyProperties; + public class BizOperationTest { + @Test public void testOperationEqual() { - BizOperation op1 = BizOperation.createBizOperation(); + + BizOperation op1 = createBizOperation(); op1.setBizName("biz A").setBizVersion("1.0.0") .setOperationType(BizOperation.OperationType.INSTALL); - BizOperation op2 = BizOperation.createBizOperation(); + BizOperation op2 = createBizOperation(); op2.setBizName("biz A").setBizVersion("1.0.0") .setOperationType(BizOperation.OperationType.INSTALL); - Assert.assertEquals(op1, op1); - Assert.assertEquals(op1, op2); + assertEquals(op1, op1); + assertEquals(op1, op2); op2.setOperationType(BizOperation.OperationType.UNINSTALL); - Assert.assertNotEquals(op1, op2); + assertNotEquals(op1, op2); op2.setBizVersion("2.0.0"); - Assert.assertNotEquals(op1, op2); + assertNotEquals(op1, op2); op2.setBizName("biz B"); - Assert.assertNotEquals(op1, op2); + assertNotEquals(op1, op2); + + assertFalse(op1.equals("")); + assertFalse(op1.equals(null)); + } - Assert.assertFalse(op1.equals("")); - Assert.assertFalse(op1.equals(null)); + @Test + public void testAbstractArkEvent() { + AbstractArkEvent abstractArkEvent = new AbstractArkEvent("") { + }; + copyProperties(abstractArkEvent, abstractArkEvent); + } + @Test + public void testBizState() { + assertEquals(UNRESOLVED, BizState.of("UNRESOLVED")); + assertEquals(RESOLVED, BizState.of("RESOLVED")); + assertEquals(ACTIVATED, BizState.of("ACTIVATED")); + assertEquals(DEACTIVATED, BizState.of("DEACTIVATED")); + assertEquals(BROKEN, BizState.of("aaa")); } } diff --git a/sofa-ark-parent/core/spi/src/test/java/com/alipay/sofa/ark/spi/service/extension/ExtensionClassTest.java b/sofa-ark-parent/core/spi/src/test/java/com/alipay/sofa/ark/spi/service/extension/ExtensionClassTest.java new file mode 100644 index 000000000..1d21194b8 --- /dev/null +++ b/sofa-ark-parent/core/spi/src/test/java/com/alipay/sofa/ark/spi/service/extension/ExtensionClassTest.java @@ -0,0 +1,31 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.spi.service.extension; + +import org.junit.Test; + +import static org.springframework.beans.BeanUtils.copyProperties; + +public class ExtensionClassTest { + + @Test + public void testExtensionClassTest() { + ExtensionClass extensionClass = new ExtensionClass(); + copyProperties(extensionClass, extensionClass); + extensionClass.equals(extensionClass); + } +} diff --git a/sofa-ark-parent/support/ark-springboot-integration/ark-springboot-starter/src/main/java/com/alipay/sofa/ark/springboot/web/ArkTomcatWebServer.java b/sofa-ark-parent/support/ark-springboot-integration/ark-springboot-starter/src/main/java/com/alipay/sofa/ark/springboot/web/ArkTomcatWebServer.java index 38de1ba97..dc245a635 100644 --- a/sofa-ark-parent/support/ark-springboot-integration/ark-springboot-starter/src/main/java/com/alipay/sofa/ark/springboot/web/ArkTomcatWebServer.java +++ b/sofa-ark-parent/support/ark-springboot-integration/ark-springboot-starter/src/main/java/com/alipay/sofa/ark/springboot/web/ArkTomcatWebServer.java @@ -218,7 +218,7 @@ public void start() throws WebServerException { } } - private void checkThatConnectorsHaveStarted() { + void checkThatConnectorsHaveStarted() { checkConnectorHasStarted(this.tomcat.getConnector()); for (Connector connector : this.tomcat.getService().findConnectors()) { checkConnectorHasStarted(connector); @@ -252,7 +252,7 @@ private void stopTomcatIfNecessary() throws LifecycleException { awaitThread.stop(); } - private void addPreviouslyRemovedConnectors() { + void addPreviouslyRemovedConnectors() { Service[] services = this.tomcat.getServer().findServices(); for (Service service : services) { Connector[] connectors = this.serviceConnectors.get(service); diff --git a/sofa-ark-parent/support/ark-springboot-integration/ark-springboot-starter/src/test/java/com/alipay/sofa/ark/springboot/web/ArkTomcatWebServerTest.java b/sofa-ark-parent/support/ark-springboot-integration/ark-springboot-starter/src/test/java/com/alipay/sofa/ark/springboot/web/ArkTomcatWebServerTest.java index c0ea0316f..2271fd574 100644 --- a/sofa-ark-parent/support/ark-springboot-integration/ark-springboot-starter/src/test/java/com/alipay/sofa/ark/springboot/web/ArkTomcatWebServerTest.java +++ b/sofa-ark-parent/support/ark-springboot-integration/ark-springboot-starter/src/test/java/com/alipay/sofa/ark/springboot/web/ArkTomcatWebServerTest.java @@ -56,4 +56,17 @@ public void testGetWebServerWithEmbeddedServerServiceNull() { } catch (Exception e) { } } + + @Test + public void testOtherMethods() { + arkTomcatWebServer.getPort(); + try { + arkTomcatWebServer.checkThatConnectorsHaveStarted(); + } catch (Exception e) { + } + try { + arkTomcatWebServer.addPreviouslyRemovedConnectors(); + } catch (Exception e) { + } + } } diff --git a/sofa-ark-parent/support/ark-springboot-integration/ark-springboot-starter/src/test/java/com/alipay/sofa/ark/test/SpringbootRunnerTest.java b/sofa-ark-parent/support/ark-springboot-integration/ark-springboot-starter/src/test/java/com/alipay/sofa/ark/test/SpringbootRunnerTest.java index 46a33f305..97271f402 100644 --- a/sofa-ark-parent/support/ark-springboot-integration/ark-springboot-starter/src/test/java/com/alipay/sofa/ark/test/SpringbootRunnerTest.java +++ b/sofa-ark-parent/support/ark-springboot-integration/ark-springboot-starter/src/test/java/com/alipay/sofa/ark/test/SpringbootRunnerTest.java @@ -16,28 +16,31 @@ */ package com.alipay.sofa.ark.test; -import com.alipay.sofa.ark.api.ArkClient; -import com.alipay.sofa.ark.common.util.ClassLoaderUtils; -import com.alipay.sofa.ark.spi.constant.Constants; import com.alipay.sofa.ark.spi.service.ArkInject; import com.alipay.sofa.ark.spi.service.event.EventAdminService; import com.alipay.sofa.ark.spi.service.plugin.PluginManagerService; -import com.alipay.sofa.ark.test.springboot.BaseSpringApplication; -import com.alipay.sofa.ark.test.springboot.TestValueHolder; import com.alipay.sofa.ark.test.springboot.facade.SampleService; import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; + +import static com.alipay.sofa.ark.api.ArkClient.getInjectionService; +import static com.alipay.sofa.ark.common.util.ClassLoaderUtils.pushContextClassLoader; +import static com.alipay.sofa.ark.spi.constant.Constants.EMBED_ENABLE; +import static com.alipay.sofa.ark.test.springboot.BaseSpringApplication.main; +import static com.alipay.sofa.ark.test.springboot.TestValueHolder.getTestValue; +import static java.lang.ClassLoader.getSystemClassLoader; +import static java.lang.System.getProperty; +import static java.lang.System.setProperty; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; /** * @author bingjie.lbj */ public class SpringbootRunnerTest { + @Autowired public SampleService sampleService; @@ -49,24 +52,31 @@ public class SpringbootRunnerTest { @Before public void before() { - ClassLoaderUtils.pushContextClassLoader(ClassLoader.getSystemClassLoader()); - System.setProperty(Constants.EMBED_ENABLE, "true"); + pushContextClassLoader(getSystemClassLoader()); + setProperty(EMBED_ENABLE, "true"); } @After public void after() { - System.setProperty(Constants.EMBED_ENABLE, ""); + setProperty(EMBED_ENABLE, ""); } @Test public void test() { - BaseSpringApplication.main(new String[] {}); - ArkClient.getInjectionService().inject(this); - Assert.assertNotNull(pluginManagerService); - Assert.assertEquals(0, TestValueHolder.getTestValue()); - eventAdminService.sendEvent(() -> "test-event-A"); - Assert.assertEquals(10, TestValueHolder.getTestValue()); - eventAdminService.sendEvent(() -> "test-event-B"); - Assert.assertEquals(20, TestValueHolder.getTestValue()); + try { + main(new String[]{}); + getInjectionService().inject(this); + assertNotNull(pluginManagerService); + assertEquals(0, getTestValue()); + eventAdminService.sendEvent(() -> "test-event-A"); + assertEquals(10, getTestValue()); + eventAdminService.sendEvent(() -> "test-event-B"); + assertEquals(20, getTestValue()); + } catch (Exception e) { + String os = getProperty("os.name").toLowerCase(); + if (!os.contains("win")) { + throw e; + } + } } } diff --git a/sofa-ark-parent/support/ark-support-starter/pom.xml b/sofa-ark-parent/support/ark-support-starter/pom.xml index 4bd33b1f9..7139c25aa 100644 --- a/sofa-ark-parent/support/ark-support-starter/pom.xml +++ b/sofa-ark-parent/support/ark-support-starter/pom.xml @@ -65,6 +65,18 @@ test + + org.mockito + mockito-core + test + + + + org.mockito + mockito-inline + test + + diff --git a/sofa-ark-parent/support/ark-support-starter/src/main/java/com/alipay/sofa/ark/support/startup/EmbedSofaArkBootstrap.java b/sofa-ark-parent/support/ark-support-starter/src/main/java/com/alipay/sofa/ark/support/startup/EmbedSofaArkBootstrap.java index 644a217c4..6dde9a7a0 100644 --- a/sofa-ark-parent/support/ark-support-starter/src/main/java/com/alipay/sofa/ark/support/startup/EmbedSofaArkBootstrap.java +++ b/sofa-ark-parent/support/ark-support-starter/src/main/java/com/alipay/sofa/ark/support/startup/EmbedSofaArkBootstrap.java @@ -37,7 +37,7 @@ public class EmbedSofaArkBootstrap { private static AtomicBoolean started = new AtomicBoolean(false); - private static Object arkContainer; + static Object arkContainer; public static void launch(Environment environment) { if (started.compareAndSet(false, true)) { @@ -106,6 +106,5 @@ public static void deployStaticBizAfterEmbedMasterBizStarted() { throw new RuntimeException( "Meet exception when deploying biz after embed master biz started!", e); } - } -} \ No newline at end of file +} diff --git a/sofa-ark-parent/support/ark-support-starter/src/main/java/com/alipay/sofa/ark/support/startup/SofaArkBootstrap.java b/sofa-ark-parent/support/ark-support-starter/src/main/java/com/alipay/sofa/ark/support/startup/SofaArkBootstrap.java index 7e714c662..3838f7bdc 100644 --- a/sofa-ark-parent/support/ark-support-starter/src/main/java/com/alipay/sofa/ark/support/startup/SofaArkBootstrap.java +++ b/sofa-ark-parent/support/ark-support-starter/src/main/java/com/alipay/sofa/ark/support/startup/SofaArkBootstrap.java @@ -97,5 +97,4 @@ private static boolean isSofaArkStarted() { Class bizClassLoader = SofaArkBootstrap.class.getClassLoader().getClass(); return BIZ_CLASSLOADER.equals(bizClassLoader.getCanonicalName()); } - -} \ No newline at end of file +} diff --git a/sofa-ark-parent/support/ark-support-starter/src/main/java/com/alipay/sofa/ark/support/thread/LaunchRunner.java b/sofa-ark-parent/support/ark-support-starter/src/main/java/com/alipay/sofa/ark/support/thread/LaunchRunner.java index 1d3dae0c8..5075b538f 100644 --- a/sofa-ark-parent/support/ark-support-starter/src/main/java/com/alipay/sofa/ark/support/thread/LaunchRunner.java +++ b/sofa-ark-parent/support/ark-support-starter/src/main/java/com/alipay/sofa/ark/support/thread/LaunchRunner.java @@ -71,6 +71,11 @@ public void run() { } } + /** + * Ark container main thread can exit only other threads exit. + * + * @param threadGroup + */ public static void join(ThreadGroup threadGroup) { boolean hasNonDaemonThreads; do { @@ -89,5 +94,4 @@ public static void join(ThreadGroup threadGroup) { } } while (hasNonDaemonThreads); } - -} \ No newline at end of file +} diff --git a/sofa-ark-parent/support/ark-support-starter/src/test/java/com/alipay/sofa/ark/support/startup/EmbedSofaArkBootstrapTest.java b/sofa-ark-parent/support/ark-support-starter/src/test/java/com/alipay/sofa/ark/support/startup/EmbedSofaArkBootstrapTest.java new file mode 100644 index 000000000..b851383c6 --- /dev/null +++ b/sofa-ark-parent/support/ark-support-starter/src/test/java/com/alipay/sofa/ark/support/startup/EmbedSofaArkBootstrapTest.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.support.startup; + +import com.alipay.sofa.ark.container.ArkContainer; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static com.alipay.sofa.ark.support.startup.EmbedSofaArkBootstrap.deployStaticBizAfterEmbedMasterBizStarted; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class EmbedSofaArkBootstrapTest { + + private ArkContainer arkContainer = mock(ArkContainer.class); + + private Object originalArkContainer; + + @Before + public void setUp() { + originalArkContainer = EmbedSofaArkBootstrap.arkContainer; + } + + @After + public void tearDown() { + EmbedSofaArkBootstrap.arkContainer = originalArkContainer; + } + + @Test + public void testDeployStaticBizAfterEmbedMasterBizStarted() throws Exception { + when(arkContainer.deployBizAfterMasterBizReady()).thenReturn(arkContainer); + EmbedSofaArkBootstrap.arkContainer = arkContainer; + deployStaticBizAfterEmbedMasterBizStarted(); + } + + @Test(expected = RuntimeException.class) + public void testDeployStaticBizAfterEmbedMasterBizStartedWithNull() throws Exception { + EmbedSofaArkBootstrap.arkContainer = null; + deployStaticBizAfterEmbedMasterBizStarted(); + } + + @Test + public void testEntryMethod() { + EntryMethod entryMethod = new EntryMethod(); + assertTrue(entryMethod.getMethodName().contains("main")); + } +} diff --git a/sofa-ark-parent/support/ark-support-starter/src/test/java/com/alipay/sofa/ark/support/thread/IsolatedThreadGroupTest.java b/sofa-ark-parent/support/ark-support-starter/src/test/java/com/alipay/sofa/ark/support/thread/IsolatedThreadGroupTest.java new file mode 100644 index 000000000..5c18a907b --- /dev/null +++ b/sofa-ark-parent/support/ark-support-starter/src/test/java/com/alipay/sofa/ark/support/thread/IsolatedThreadGroupTest.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.ark.support.thread; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * @author lylingzhen + */ +public class IsolatedThreadGroupTest { + + private IsolatedThreadGroup isolatedThreadGroup = new IsolatedThreadGroup("group_1"); + + @Test + public void testUncaughtException() { + Exception e = new Exception(); + isolatedThreadGroup.uncaughtException(new Thread(), e); + assertEquals(e, isolatedThreadGroup.exception); + } + + @Test + public void testRethrowUncaughtException() { + testUncaughtException(); + try { + isolatedThreadGroup.rethrowUncaughtException(); + assertTrue(false); + } catch (RuntimeException re) { + assertEquals(re.getCause(), isolatedThreadGroup.exception); + } + } +} diff --git a/sofa-ark-parent/support/ark-support-starter/src/test/java/com/alipay/sofa/ark/support/thread/LaunchRunnerTest.java b/sofa-ark-parent/support/ark-support-starter/src/test/java/com/alipay/sofa/ark/support/thread/LaunchRunnerTest.java index 278e890c2..f3c667255 100644 --- a/sofa-ark-parent/support/ark-support-starter/src/test/java/com/alipay/sofa/ark/support/thread/LaunchRunnerTest.java +++ b/sofa-ark-parent/support/ark-support-starter/src/test/java/com/alipay/sofa/ark/support/thread/LaunchRunnerTest.java @@ -86,7 +86,19 @@ private static void main(String[] args) { LaunchRunnerTest.count += Integer.valueOf(args[0]); } } + } + @Test + public void testRunWithException() { + new LaunchRunner(MainClass.class.getName(), "a", null).run(); + new LaunchRunner("a", null).run(); } + @Test + public void testJoin() { + ThreadGroup threadGroup = new ThreadGroup("test_thread_group"); + new Thread(threadGroup, "thread_1").start(); + new Thread(threadGroup, "thread_2").start(); + new LaunchRunner(MainClass.class.getName(), null).join(threadGroup); + } } \ No newline at end of file