cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ahu...@apache.org
Subject [52/56] [abbrv] Fixed up unit testing to use only an in class TestConfiguration
Date Mon, 06 May 2013 23:35:32 GMT
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3722d66a/server/test/com/cloud/vpc/VpcTestConfiguration.java
----------------------------------------------------------------------
diff --git a/server/test/com/cloud/vpc/VpcTestConfiguration.java b/server/test/com/cloud/vpc/VpcTestConfiguration.java
index b1f2f80..7ae83f3 100644
--- a/server/test/com/cloud/vpc/VpcTestConfiguration.java
+++ b/server/test/com/cloud/vpc/VpcTestConfiguration.java
@@ -19,6 +19,7 @@ package com.cloud.vpc;
 
 import java.io.IOException;
 
+import org.apache.cloudstack.test.utils.SpringUtils;
 import org.mockito.Mockito;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.ComponentScan;
@@ -91,7 +92,6 @@ import com.cloud.tags.dao.ResourceTagsDaoImpl;
 import com.cloud.user.AccountManager;
 import com.cloud.user.dao.AccountDaoImpl;
 import com.cloud.user.dao.UserStatisticsDaoImpl;
-import com.cloud.utils.component.SpringComponentScanUtils;
 import com.cloud.vm.UserVmManager;
 import com.cloud.vm.dao.DomainRouterDaoImpl;
 import com.cloud.vm.dao.NicDaoImpl;
@@ -236,7 +236,7 @@ public class VpcTestConfiguration {
         public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException
{
             mdr.getClassMetadata().getClassName();
             ComponentScan cs = VpcTestConfiguration.class.getAnnotation(ComponentScan.class);
-            return SpringComponentScanUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(),
cs);
+            return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(),
cs);
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3722d66a/server/test/org/apache/cloudstack/affinity/AffinityApiUnitTest.java
----------------------------------------------------------------------
diff --git a/server/test/org/apache/cloudstack/affinity/AffinityApiUnitTest.java b/server/test/org/apache/cloudstack/affinity/AffinityApiUnitTest.java
index f9c5728..484b044 100644
--- a/server/test/org/apache/cloudstack/affinity/AffinityApiUnitTest.java
+++ b/server/test/org/apache/cloudstack/affinity/AffinityApiUnitTest.java
@@ -24,6 +24,7 @@ import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.when;
 
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -32,13 +33,23 @@ import javax.naming.ConfigurationException;
 
 import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
 import org.apache.cloudstack.affinity.dao.AffinityGroupVMMapDao;
+import org.apache.cloudstack.test.utils.SpringUtils;
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Mockito;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScan.Filter;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.FilterType;
+import org.springframework.core.type.classreading.MetadataReader;
+import org.springframework.core.type.classreading.MetadataReaderFactory;
+import org.springframework.core.type.filter.TypeFilter;
 import org.springframework.test.context.ContextConfiguration;
 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.support.AnnotationConfigContextLoader;
 
 import com.cloud.event.EventUtils;
 import com.cloud.event.EventVO;
@@ -48,6 +59,7 @@ import com.cloud.exception.ResourceInUseException;
 import com.cloud.hypervisor.Hypervisor.HypervisorType;
 import com.cloud.user.Account;
 import com.cloud.user.AccountManager;
+import com.cloud.user.AccountService;
 import com.cloud.user.AccountVO;
 import com.cloud.user.UserContext;
 import com.cloud.user.dao.AccountDao;
@@ -57,7 +69,7 @@ import com.cloud.vm.VirtualMachine;
 import com.cloud.vm.dao.UserVmDao;
 
 @RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(locations = "classpath:/affinityContext.xml")
+@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
 public class AffinityApiUnitTest {
 
     @Inject
@@ -188,4 +200,57 @@ public class AffinityApiUnitTest {
         _affinityService.updateVMAffinityGroups(10L, affinityGroupIds);
     }
 
+    @Configuration
+    @ComponentScan(basePackageClasses = {AffinityGroupServiceImpl.class, EventUtils.class},
includeFilters = {@Filter(value = TestConfiguration.Library.class, type = FilterType.CUSTOM)},
useDefaultFilters = false)
+    public static class TestConfiguration extends SpringUtils.CloudStackTestConfiguration
{
+
+        @Bean
+        public AccountDao accountDao() {
+            return Mockito.mock(AccountDao.class);
+        }
+
+        @Bean
+        public AccountService accountService() {
+            return Mockito.mock(AccountService.class);
+        }
+
+        @Bean
+        public AffinityGroupProcessor affinityGroupProcessor() {
+            return Mockito.mock(AffinityGroupProcessor.class);
+        }
+
+        @Bean
+        public AffinityGroupDao affinityGroupDao() {
+            return Mockito.mock(AffinityGroupDao.class);
+        }
+
+        @Bean
+        public AffinityGroupVMMapDao affinityGroupVMMapDao() {
+            return Mockito.mock(AffinityGroupVMMapDao.class);
+        }
+
+        @Bean
+        public AccountManager accountManager() {
+            return Mockito.mock(AccountManager.class);
+        }
+
+        @Bean
+        public EventDao eventDao() {
+            return Mockito.mock(EventDao.class);
+        }
+
+        @Bean
+        public UserVmDao userVMDao() {
+            return Mockito.mock(UserVmDao.class);
+        }
+
+        public static class Library implements TypeFilter {
+
+            @Override
+            public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException
{
+                ComponentScan cs = TestConfiguration.class.getAnnotation(ComponentScan.class);
+                return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(),
cs);
+            }
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3722d66a/server/test/org/apache/cloudstack/networkoffering/ChildTestConfiguration.java
----------------------------------------------------------------------
diff --git a/server/test/org/apache/cloudstack/networkoffering/ChildTestConfiguration.java
b/server/test/org/apache/cloudstack/networkoffering/ChildTestConfiguration.java
index d47deaa..6f52397 100644
--- a/server/test/org/apache/cloudstack/networkoffering/ChildTestConfiguration.java
+++ b/server/test/org/apache/cloudstack/networkoffering/ChildTestConfiguration.java
@@ -27,6 +27,7 @@ import org.apache.cloudstack.acl.SecurityChecker;
 import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
 import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDaoImpl;
 import org.apache.cloudstack.storage.datastore.db.StoragePoolDetailsDao;
+import org.apache.cloudstack.test.utils.SpringUtils;
 import org.mockito.Mockito;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.ComponentScan;
@@ -94,7 +95,6 @@ import com.cloud.storage.swift.SwiftManager;
 import com.cloud.tags.dao.ResourceTagsDaoImpl;
 import com.cloud.user.dao.AccountDaoImpl;
 import com.cloud.user.dao.UserDaoImpl;
-import com.cloud.utils.component.SpringComponentScanUtils;
 import com.cloud.vm.dao.InstanceGroupDaoImpl;
 import com.cloud.vm.dao.NicDaoImpl;
 import com.cloud.vm.dao.NicSecondaryIpDaoImpl;
@@ -338,7 +338,7 @@ public class ChildTestConfiguration {
         public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException
{
             mdr.getClassMetadata().getClassName();
             ComponentScan cs = ChildTestConfiguration.class.getAnnotation(ComponentScan.class);
-            return SpringComponentScanUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(),
cs);
+            return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(),
cs);
         }
 
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3722d66a/server/test/resources/affinityContext.xml
----------------------------------------------------------------------
diff --git a/server/test/resources/affinityContext.xml b/server/test/resources/affinityContext.xml
deleted file mode 100644
index d41a63d..0000000
--- a/server/test/resources/affinityContext.xml
+++ /dev/null
@@ -1,42 +0,0 @@
-<!-- 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. -->
-<beans xmlns="http://www.springframework.org/schema/beans"
-  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
-  xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
-  xsi:schemaLocation="http://www.springframework.org/schema/beans
-                      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-                      http://www.springframework.org/schema/tx 
-                      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
-                      http://www.springframework.org/schema/aop
-                      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
-                      http://www.springframework.org/schema/context
-                      http://www.springframework.org/schema/context/spring-context-3.0.xsd">
-
-     <context:annotation-config />
-
-    <!-- @DB support -->
-	<bean id="componentContext" class="com.cloud.utils.component.ComponentContext" />
-	
-	  <bean id="transactionContextBuilder" class="com.cloud.utils.db.TransactionContextBuilder"
/>
-      <bean id="actionEventInterceptor" class="com.cloud.event.ActionEventInterceptor"
/>
-	  <bean id="instantiatePostProcessor" class="com.cloud.utils.component.ComponentInstantiationPostProcessor">
-	    <property name="Interceptors">
-	        <list>
-	            <ref bean="transactionContextBuilder" />
-	            <ref bean="actionEventInterceptor" />
-	        </list>
-	    </property>
-	  </bean>
-
-    <bean class="org.apache.cloudstack.affinity.AffinityApiTestConfiguration" />
-    
-
-</beans>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3722d66a/services/console-proxy/pom.xml
----------------------------------------------------------------------
diff --git a/services/console-proxy/pom.xml b/services/console-proxy/pom.xml
index 2c9e2e6..3aac7b2 100644
--- a/services/console-proxy/pom.xml
+++ b/services/console-proxy/pom.xml
@@ -23,9 +23,9 @@
   <packaging>pom</packaging>
   <parent>
     <groupId>org.apache.cloudstack</groupId>
-    <artifactId>cloudstack</artifactId>
+    <artifactId>cloudstack-services</artifactId>
     <version>4.2.0-SNAPSHOT</version>
-    <relativePath>../../pom.xml</relativePath>
+    <relativePath>../pom.xml</relativePath>
   </parent>
   <build>
     <defaultGoal>install</defaultGoal>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3722d66a/services/secondary-storage/pom.xml
----------------------------------------------------------------------
diff --git a/services/secondary-storage/pom.xml b/services/secondary-storage/pom.xml
index 0797c98..eb6c0ee 100644
--- a/services/secondary-storage/pom.xml
+++ b/services/secondary-storage/pom.xml
@@ -18,13 +18,13 @@
 -->
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
-  <artifactId>cloudstack-service-secondary-storage</artifactId>
+  <artifactId>cloud-secondary-storage</artifactId>
   <name>Apache CloudStack Secondary Storage Service</name>
   <parent>
     <groupId>org.apache.cloudstack</groupId>
-    <artifactId>cloudstack</artifactId>
+    <artifactId>cloudstack-services</artifactId>
     <version>4.2.0-SNAPSHOT</version>
-    <relativePath>../../pom.xml</relativePath>
+    <relativePath>../pom.xml</relativePath>
   </parent>
   <dependencies>
     <dependency>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3722d66a/tools/marvin/pom.xml
----------------------------------------------------------------------
diff --git a/tools/marvin/pom.xml b/tools/marvin/pom.xml
index c050566..25134a8 100644
--- a/tools/marvin/pom.xml
+++ b/tools/marvin/pom.xml
@@ -1,15 +1,14 @@
 <!-- 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. -->
+  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. -->
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <artifactId>cloud-marvin</artifactId>
   <name>Apache CloudStack marvin</name>
@@ -35,7 +34,7 @@
             </goals>
             <configuration>
               <target>
-                <delete dir="marvin/cloudstackAPI"/>
+                <delete dir="marvin/cloudstackAPI" />
                 <echo>Deleting ${project.artifactId} API sources</echo>
               </target>
             </configuration>
@@ -83,7 +82,7 @@
       </plugin>
     </plugins>
   </build>
-  <!-- Custom profiles for sync and integration tests-->
+  <!-- Custom profiles for sync and integration tests -->
   <profiles>
     <profile>
       <id>marvin.sync</id>
@@ -161,6 +160,26 @@
       <build>
         <plugins>
           <plugin>
+            <groupId>org.codehaus.gmaven</groupId>
+            <artifactId>gmaven-plugin</artifactId>
+            <version>1.5</version>
+            <executions>
+              <execution>
+                <id>setproperty</id>
+                <phase>validate</phase>
+                <goals>
+                  <goal>execute</goal>
+                </goals>
+                <configuration>
+                  <source>
+                    pom.properties['resolved.basedir']=project.basedir.absolutePath.replace('\','/').replace('D:','/cyg/d');
+                    pom.properties['resolved.userdir']='${user.dir}'.replace('\','/').replace('D:','/cyg/d');
+                  </source>
+                </configuration>
+              </execution>
+            </executions>
+          </plugin>
+          <plugin>
             <groupId>org.codehaus.mojo</groupId>
             <artifactId>exec-maven-plugin</artifactId>
             <version>1.2.1</version>
@@ -177,18 +196,18 @@
                   <arguments>
                     <argument>deployAndRun.py</argument>
                     <argument>-c</argument>
-                    <argument>${user.dir}/${marvin.config}</argument>
+                    <argument>${resolved.userdir}/${marvin.config}</argument>
                     <argument>-t</argument>
                     <argument>/tmp/t.log</argument>
                     <argument>-r</argument>
                     <argument>/tmp/r.log</argument>
                     <argument>-f</argument>
-                    <argument>${basedir}/marvin/testSetupSuccess.py</argument>
+                    <argument>${resolved.basedir}/marvin/testSetupSuccess.py</argument>
                   </arguments>
                 </configuration>
               </execution>
-              </executions>
-            </plugin>
+            </executions>
+          </plugin>
         </plugins>
       </build>
     </profile>

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3722d66a/usage/test/com/cloud/usage/UsageManagerTestConfiguration.java
----------------------------------------------------------------------
diff --git a/usage/test/com/cloud/usage/UsageManagerTestConfiguration.java b/usage/test/com/cloud/usage/UsageManagerTestConfiguration.java
index d7cf046..1d3ed7b 100644
--- a/usage/test/com/cloud/usage/UsageManagerTestConfiguration.java
+++ b/usage/test/com/cloud/usage/UsageManagerTestConfiguration.java
@@ -25,7 +25,8 @@ import com.cloud.usage.dao.*;
 import com.cloud.usage.parser.*;
 import com.cloud.user.dao.AccountDaoImpl;
 import com.cloud.user.dao.UserStatisticsDaoImpl;
-import com.cloud.utils.component.SpringComponentScanUtils;
+
+import org.apache.cloudstack.test.utils.SpringUtils;
 import org.mockito.Mockito;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.ComponentScan;
@@ -87,7 +88,7 @@ public class UsageManagerTestConfiguration {
         public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException
{
             mdr.getClassMetadata().getClassName();
             ComponentScan cs = UsageManagerTestConfiguration.class.getAnnotation(ComponentScan.class);
-            return SpringComponentScanUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(),
cs);
+            return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(),
cs);
         }
 
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3722d66a/utils/src/com/cloud/utils/AnnotationHelper.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/AnnotationHelper.java b/utils/src/com/cloud/utils/AnnotationHelper.java
index 954b870..e7a6166 100755
--- a/utils/src/com/cloud/utils/AnnotationHelper.java
+++ b/utils/src/com/cloud/utils/AnnotationHelper.java
@@ -20,40 +20,38 @@ import javax.persistence.Table;
 
 import org.apache.log4j.Logger;
 
-import com.cloud.utils.exception.CSExceptionErrorCode;
-
 
 public class AnnotationHelper extends Object {
 	// This class contains routines to help query annotation elements of objects.
-	
+
 	public static final Logger s_logger = Logger.getLogger(AnnotationHelper.class.getName());
-	
+
 	public static String getTableName(Object proxyObj) {
 		// The cglib class is generated by cglib during runtime.
-		
+
 		Class<?> curClass = proxyObj.getClass();
 		if (curClass == null) {
-			s_logger.info("\nCould not retrieve class information for proxy object\n");
+            s_logger.trace("Could not retrieve class information for proxy object");
 			return null;
 		}
-		
+
 		while (curClass.getSuperclass() != null && curClass.getSuperclass().getName() !=
"java.lang.Object") {
 			curClass = curClass.getSuperclass();
 		}
 		// At this point, curClass is the root base class of proxyObj's class, and curClass is
not java.lang.Object.
 
-		Table tabObj = (Table)curClass.getAnnotation(Table.class);
+		Table tabObj = curClass.getAnnotation(Table.class);
 
 		if (tabObj == null) {
-			s_logger.info("\n" + curClass + "does not have a Table annotation\n");
+            s_logger.trace(curClass + "does not have a Table annotation");
 			return null;
 		}
-		
+
 		return tabObj.name();
 	}
-	
+
 }
-		
-	 
-	 
-	
+
+
+
+

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3722d66a/utils/src/com/cloud/utils/component/SpringComponentScanUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/com/cloud/utils/component/SpringComponentScanUtils.java b/utils/src/com/cloud/utils/component/SpringComponentScanUtils.java
deleted file mode 100644
index 28b84e6..0000000
--- a/utils/src/com/cloud/utils/component/SpringComponentScanUtils.java
+++ /dev/null
@@ -1,41 +0,0 @@
-// 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
-// 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.cloud.utils.component;
-
-import org.springframework.context.annotation.ComponentScan;
-
-import com.cloud.utils.exception.CloudRuntimeException;
-
-public class SpringComponentScanUtils {
-
-    public static boolean includedInBasePackageClasses(String clazzName, ComponentScan cs)
{
-        Class<?> clazzToCheck;
-        try {
-            clazzToCheck = Class.forName(clazzName);
-        } catch (ClassNotFoundException e) {
-            throw new CloudRuntimeException("Unable to find " + clazzName);
-        }
-        Class<?>[] clazzes = cs.basePackageClasses();
-        for (Class<?> clazz : clazzes) {
-            if (clazzToCheck.isAssignableFrom(clazz)) {
-                return true;
-            }
-        }
-        return false;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/3722d66a/utils/src/org/apache/cloudstack/test/utils/SpringUtils.java
----------------------------------------------------------------------
diff --git a/utils/src/org/apache/cloudstack/test/utils/SpringUtils.java b/utils/src/org/apache/cloudstack/test/utils/SpringUtils.java
new file mode 100644
index 0000000..220bd80
--- /dev/null
+++ b/utils/src/org/apache/cloudstack/test/utils/SpringUtils.java
@@ -0,0 +1,113 @@
+// 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
+// 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 org.apache.cloudstack.test.utils;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+
+import com.cloud.utils.component.ComponentContext;
+import com.cloud.utils.component.ComponentInstantiationPostProcessor;
+import com.cloud.utils.component.ComponentMethodInterceptor;
+import com.cloud.utils.db.TransactionContextBuilder;
+import com.cloud.utils.exception.CloudRuntimeException;
+
+public class SpringUtils {
+
+    /**
+     * This method allows you to use @ComponentScan for your unit testing but
+     * it limits the scope of the classes found to the class specified in
+     * the @ComponentScan annotation.
+     *
+     * Without using this method, the default behavior of @ComponentScan is
+     * to actually scan in the package of the class specified rather than
+     * only the class. This can cause extra classes to be loaded which causes
+     * the classes these extra classes depend on to be loaded. The end effect
+     * is often most of the project gets loaded.
+     *
+     * In order to use this method properly, you must do the following: <li>
+     *   - Specify @ComponentScan with basePackageClasses, includeFilters, and
+     *     useDefaultFilters=true.  See the following example.
+     *
+     * <pre>
+     *     @ComponentScan(basePackageClasses={AffinityGroupServiceImpl.class, EventUtils.class},
+     *     includeFilters={@Filter(value=TestConfiguration.Library.class, type=FilterType.CUSTOM)},
+     *     useDefaultFilters=false)
+     * </pre>
+     *
+     *   - Create a Library class and use that to call this method.  See the
+     *     following example.  The Library class you define here is the Library
+     *     class being added in the filter above.
+     *
+     * <pre>
+     * public static class Library implements TypeFilter {
+     *      @Override
+     *      public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException
{
+     *          ComponentScan cs = TestConfiguration.class.getAnnotation(ComponentScan.class);
+     *          return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(),
cs);
+     *      }
+     * }
+     * </pre>
+     *
+     * @param clazzName name of the class that should be included in the Spring components
+     * @param cs ComponentScan annotation that was declared on the configuration
+     *
+     * @return
+     */
+    public static boolean includedInBasePackageClasses(String clazzName, ComponentScan cs)
{
+        Class<?> clazzToCheck;
+        try {
+            clazzToCheck = Class.forName(clazzName);
+        } catch (ClassNotFoundException e) {
+            throw new CloudRuntimeException("Unable to find " + clazzName);
+        }
+        Class<?>[] clazzes = cs.basePackageClasses();
+        for (Class<?> clazz : clazzes) {
+            if (clazzToCheck.isAssignableFrom(clazz)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public static class CloudStackTestConfiguration {
+
+        @Bean
+        public ComponentContext componentContext() {
+            return new ComponentContext();
+        }
+
+        @Bean
+        public TransactionContextBuilder transactionContextBuilder() {
+            return new TransactionContextBuilder();
+        }
+
+        @Bean
+        public ComponentInstantiationPostProcessor instantiatePostProcessor() {
+            ComponentInstantiationPostProcessor processor = new ComponentInstantiationPostProcessor();
+
+            List<ComponentMethodInterceptor> interceptors = new ArrayList<ComponentMethodInterceptor>();
+            interceptors.add(new TransactionContextBuilder());
+            processor.setInterceptors(interceptors);
+
+            return processor;
+        }
+    }
+}


Mime
View raw message