modules/core/plugin-container/pom.xml
| 15
modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResType.java
| 70 +
modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java
| 577 ++++------
modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeProgressHandlingTest.java
| 229 +--
modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
| 436 +++----
modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java
| 390 ------
modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerSetup.java
| 118 ++
modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerTest.java
| 397 ++++++
modules/plugins/pom.xml
| 15
modules/test-utils/pom.xml
| 8
modules/test-utils/src/main/java/org/rhq/test/JMockTest.java
| 134 ++
11 files changed, 1369 insertions(+), 1020 deletions(-)
New commits:
commit 712d0e14d2cd4edb2be070d8028f83c4552b50bb
Author: Lukas Krejci <lkrejci(a)redhat.com>
Date: Thu May 26 00:10:11 2011 +0200
Refactoring the way plugin container can be started up in the tests
and converted the resource upgrade tests to use this new approach.
When the test inherits from PluginContainerTest or uses it as an TestNG
listener, the plugin container can be configured declaratively using
an @PluginContainerSetup annotation. There is a couple of static methods
on the PluginContainerTest class to work with such preconfigured PC
(like starting it).
The JMockTest generic base class was augmented so that it can be used as both
a base class to tests and a TestNG listener.
diff --git a/modules/core/plugin-container/pom.xml
b/modules/core/plugin-container/pom.xml
index fd14685..8cb24a4 100644
--- a/modules/core/plugin-container/pom.xml
+++ b/modules/core/plugin-container/pom.xml
@@ -102,6 +102,8 @@
<type>zip</type>
</dependency>
+ <!-- Test dependencies -->
+
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>test-utils</artifactId>
@@ -360,7 +362,18 @@
-->
</configuration>
</plugin>
-
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>jar</goal>
+ <goal>test-jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResType.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResType.java
new file mode 100644
index 0000000..e2c7f5c
--- /dev/null
+++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResType.java
@@ -0,0 +1,70 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2011 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+package org.rhq.core.pc.upgrade;
+
+/**
+ * A helper class representing a resource type in a simplistic manner.
+ *
+ *
+ * @author Lukas Krejci
+ */
+class ResType {
+ private String resourceTypeName;
+ private String resourceTypePluginName;
+
+ public ResType(String resourceTypeName, String resourceTypePluginName) {
+ super();
+ this.resourceTypeName = resourceTypeName;
+ this.resourceTypePluginName = resourceTypePluginName;
+ }
+
+ public String getResourceTypeName() {
+ return resourceTypeName;
+ }
+
+ public String getResourceTypePluginName() {
+ return resourceTypePluginName;
+ }
+
+ @Override
+ public int hashCode() {
+ return resourceTypeName.hashCode() * resourceTypePluginName.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other == this) {
+ return true;
+ }
+
+ if (!(other instanceof ResType)) {
+ return false;
+ }
+
+ ResType o = (ResType)other;
+
+ return resourceTypeName.equals(o.getResourceTypeName()) &&
resourceTypePluginName.equals(o.getResourceTypePluginName());
+ }
+
+ @Override
+ public String toString() {
+ return "ResType[name='" + resourceTypeName + "',
plugin='" + resourceTypePluginName + "']";
+ }
+}
\ No newline at end of file
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java
index 5f493c9..6821b44 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java
@@ -27,7 +27,6 @@ import static org.testng.Assert.fail;
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@@ -36,25 +35,25 @@ import java.util.Map;
import java.util.Set;
import org.jmock.Expectations;
-import org.jmock.Mockery;
import org.testng.annotations.Test;
import org.rhq.core.clientapi.agent.PluginContainerException;
import org.rhq.core.clientapi.agent.discovery.InvalidPluginConfigurationClientException;
import org.rhq.core.clientapi.server.discovery.InvalidInventoryReportException;
import org.rhq.core.clientapi.server.discovery.InventoryReport;
-import org.rhq.core.clientapi.server.discovery.StaleTypeException;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.resource.ResourceErrorType;
import org.rhq.core.domain.resource.ResourceType;
import org.rhq.core.pc.PluginContainer;
+import org.rhq.core.pc.ServerServices;
import org.rhq.core.pc.inventory.InventoryManager;
import org.rhq.core.pc.inventory.ResourceContainer;
import org.rhq.core.pc.inventory.ResourceContainer.ResourceComponentState;
import org.rhq.core.pc.upgrade.plugins.multi.base.BaseResourceComponentInterface;
import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet;
+import org.rhq.test.pc.PluginContainerSetup;
/**
* The plugins and their resource types form the following dependency structure:
@@ -74,42 +73,29 @@ import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet;
*
* @author Lukas Krejci
*/
-@Test(sequential = true, invocationCount = 1)
+@Test(singleThreaded = true, invocationCount = 1)
public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase {
+ //test names
+ private static final String SUCCESS_TEST = "SUCCESS_TEST";
+ private static final String FAILURE_ON_LEAF_TEST = "FAILURE_ON_LEAF_TEST";
+ private static final String FAILURE_ON_DEPENDENCIES_TEST =
"FAILURE_ON_DEPENDENCIES_TEST";
+ private static final String
RESOURCES_REVERTED_TO_ORIGINAL_STATE_AFTER_FAILED_UPGRAGE_TEST =
"RESOURCES_REVERTED_TO_ORIGINAL_STATE_AFTER_FAILED_UPGRAGE_TEST";
+
//plugin names
- private static final String BASE_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-base-1.0.0.jar";
- private static final String PARENT_DEP_V1_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-parentdep-1.0.0.jar";
- private static final String PARENT_DEP_V2_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-parentdep-2.0.0.jar";
- private static final String PARENT_SIBLING_V1_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-parentsibling-1.0.0.jar";
- private static final String PARENT_SIBLING_V2_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-parentsibling-2.0.0.jar";
- private static final String ROOT_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-root-1.0.0.jar";
- private static final String SIBLING_V1_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-sibling-1.0.0.jar";
- private static final String SIBLING_V2_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-sibling-2.0.0.jar";
- private static final String TEST_V1_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-test-1.0.0.jar";
- private static final String TEST_V2_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-test-2.0.0.jar";
+ private static final String BASE_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-base-1.0.0.jar";
+ private static final String PARENT_DEP_V1_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-parentdep-1.0.0.jar";
+ private static final String PARENT_DEP_V2_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-parentdep-2.0.0.jar";
+ private static final String PARENT_SIBLING_V1_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-parentsibling-1.0.0.jar";
+ private static final String PARENT_SIBLING_V2_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-parentsibling-2.0.0.jar";
+ private static final String ROOT_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-root-1.0.0.jar";
+ private static final String SIBLING_V1_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-sibling-1.0.0.jar";
+ private static final String SIBLING_V2_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-sibling-2.0.0.jar";
+ private static final String TEST_V1_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-test-1.0.0.jar";
+ private static final String TEST_V2_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-test-2.0.0.jar";
private static final String UPGRADED_RESOURCE_KEY_PREFIX = "UPGRADED";
- private static final HashMap<String, List<String>> DEPS;
-
- static {
- DEPS = new HashMap<String, List<String>>();
-
- DEPS.put(BASE_PLUGIN_NAME, Collections.<String> emptyList());
- DEPS.put(PARENT_DEP_V1_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME,
ROOT_PLUGIN_NAME));
- DEPS.put(PARENT_DEP_V2_PLUGIN_NAME, DEPS.get(PARENT_DEP_V1_PLUGIN_NAME));
- DEPS.put(PARENT_SIBLING_V1_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME,
ROOT_PLUGIN_NAME));
- DEPS.put(PARENT_SIBLING_V2_PLUGIN_NAME,
DEPS.get(PARENT_SIBLING_V1_PLUGIN_NAME));
- DEPS.put(ROOT_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME));
- DEPS.put(SIBLING_V1_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME,
ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME));
- DEPS.put(SIBLING_V2_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME,
ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME));
- DEPS.put(TEST_V1_PLUGIN_NAME,
- Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME,
SIBLING_V1_PLUGIN_NAME));
- DEPS.put(TEST_V2_PLUGIN_NAME,
- Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME,
SIBLING_V2_PLUGIN_NAME));
- }
-
private static final ResType TEST_TYPE = new ResType("TestResource",
"test");
private static final ResType SIBLING_TYPE = new
ResType("TestResourceSibling", "test");
private static final ResType PARENT_TYPE = new
ResType("TestResourceParent", "test");
@@ -120,294 +106,276 @@ public class ResourceUpgradeFailureHandlingTest extends
ResourceUpgradeTestBase
private static List<ResType> ALL_TYPES = Arrays.asList(TEST_TYPE, SIBLING_TYPE,
PARENT_TYPE, PARENT_DEP_TYPE,
PARENT_DEP_SIBLING_TYPE, ROOT_TYPE);
- protected Collection<String> getRequiredPlugins() {
- return Arrays.asList(BASE_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME,
PARENT_DEP_V2_PLUGIN_NAME,
- PARENT_SIBLING_V1_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME,
ROOT_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME,
- SIBLING_V2_PLUGIN_NAME, TEST_V1_PLUGIN_NAME, TEST_V2_PLUGIN_NAME);
- }
-
@Test
- public void testSuccess() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
-
- //let it all run in v1
- executeTestWithPlugins(getAllDepsFor(TEST_V1_PLUGIN_NAME,
PARENT_SIBLING_V1_PLUGIN_NAME),
- new AbstractTestPayload(true, Collections.<ResType> emptyList()) {
- public void test(Map<ResType, Set<Resource>>
resourceUpgradeTestResources) {
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
-
- //now let's run with v2 plugins and check the layout of the inventory
- executeTestWithPlugins(getAllDepsFor(TEST_V2_PLUGIN_NAME,
PARENT_SIBLING_V2_PLUGIN_NAME),
- new AbstractTestPayload(false, ALL_TYPES) {
-
- public void test(Map<ResType, Set<Resource>> resources) {
- checkPresenceOfResourceTypes(resources, getExpectedResourceTypes());
-
- checkNumberOfResources(resources, ROOT_TYPE, 1);
- checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
-
- //check that the resources are upgraded
- checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
- checkResourcesUpgraded(resources.get(PARENT_TYPE), 3);
- checkResourcesUpgraded(resources.get(SIBLING_TYPE), 45);
- checkResourcesUpgraded(resources.get(TEST_TYPE), 45);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
+ @PluginContainerSetup(plugins = {TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME,
BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME},
+ sharedGroup = SUCCESS_TEST, clearDataDir = true, numberOfInitialDiscoveries = 3)
+ public void testSuccess_V1() throws Exception {
+ final FakeServerInventory inv = new FakeServerInventory();
+ setServerSideFake(SUCCESS_TEST, inv);
+
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inv, this);
+ }
+ });
+
+ //let the discovery run in V1
+ startConfiguredPluginContainer();
}
+
+ @Test(dependsOnMethods = "testSuccess_V1")
+ @PluginContainerSetup(plugins = {TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME,
BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME, SIBLING_V2_PLUGIN_NAME},
+ sharedGroup = SUCCESS_TEST, clearInventoryDat = false, numberOfInitialDiscoveries
= 3)
+ public void testSuccess_V2() throws Exception {
+ final FakeServerInventory inventory = (FakeServerInventory)
getServerSideFake(SUCCESS_TEST);
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
+ Map<ResType, Set<Resource>> resources =
getResourcesFromInventory(inventory, ALL_TYPES);
+
+ checkPresenceOfResourceTypes(resources, ALL_TYPES);
+
+ checkNumberOfResources(resources, ROOT_TYPE, 1);
+ checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
+ //check that the resources are upgraded
+ checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
+ checkResourcesUpgraded(resources.get(PARENT_TYPE), 3);
+ checkResourcesUpgraded(resources.get(SIBLING_TYPE), 45);
+ checkResourcesUpgraded(resources.get(TEST_TYPE), 45);
+
+ }
+
@Test
- public void testFailureOnLeaf() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
-
- executeTestWithPlugins(getAllDepsFor(TEST_V1_PLUGIN_NAME,
PARENT_SIBLING_V1_PLUGIN_NAME),
- new AbstractTestPayload(true, Collections.<ResType> emptyList()) {
- public void test(Map<ResType, Set<Resource>>
resourceUpgradeTestResources) {
- //in here we set up the failures that are going to happen when
- //the v2 plugins are run
-
- Resource parent0 = findResourceWithOrdinal(PARENT_TYPE, 0);
- assertNotNull(parent0, "Failed to find the parent to setup the
failures for.");
- Resource parent1 = findResourceWithOrdinal(PARENT_TYPE, 1);
- assertNotNull(parent1, "Failed to find the parent to setup the
failures for.");
-
- addChildrenToFail(parent0, TEST_TYPE, 1, 2);
- addChildrenToFail(parent1, SIBLING_TYPE, 1);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
-
- executeTestWithPlugins(getAllDepsFor(TEST_V2_PLUGIN_NAME,
PARENT_SIBLING_V2_PLUGIN_NAME),
- new AbstractTestPayload(false, ALL_TYPES) {
- public void test(Map<ResType, Set<Resource>> resources) {
- checkPresenceOfResourceTypes(resources, getExpectedResourceTypes());
-
- checkNumberOfResources(resources, ROOT_TYPE, 1);
- checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
-
- checkResourcesUpgraded(resources.get(PARENT_TYPE), 3);
- checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
-
- Resource parent0 = findResourceWithOrdinal(PARENT_TYPE, 0);
- Resource parent1 = findResourceWithOrdinal(PARENT_TYPE, 1);
- Resource parent2 = findResourceWithOrdinal(PARENT_TYPE, 2);
-
- Set<Resource> testsUnderParent0 =
filterResources(parent0.getChildResources(), TEST_TYPE);
- Set<Resource> siblingsUnderParent0 =
filterResources(parent0.getChildResources(), SIBLING_TYPE);
- Set<Resource> testsUnderParent1 =
filterResources(parent1.getChildResources(), TEST_TYPE);
- Set<Resource> siblingsUnderParent1 =
filterResources(parent1.getChildResources(), SIBLING_TYPE);
- Set<Resource> testsUnderParent2 =
filterResources(parent2.getChildResources(), TEST_TYPE);
- Set<Resource> siblingsUnderParent2 =
filterResources(parent2.getChildResources(), SIBLING_TYPE);
-
- //first check for the successful upgrades
- checkResourcesUpgraded(testsUnderParent2, 15);
- checkResourcesUpgraded(siblingsUnderParent2, 15);
- checkResourcesUpgraded(siblingsUnderParent0, 15);
- checkResourcesUpgraded(testsUnderParent1, 15);
-
- //there should be no newly discovered sibling resources of the failed
ones
- assertEquals(testsUnderParent0.size(), 10);
- assertEquals(siblingsUnderParent1.size(), 10);
-
- //check that the failed resources have the error attached to them
- //we find the resource instance from the map provided to this method
- //because that map contains the resources as found on the server-side
- //(i.e. they include error objects).
- Resource failedTest1 = getEqualFrom(resources.get(TEST_TYPE),
- findResourceWithOrdinal(testsUnderParent0, 1));
- Resource failedTest2 = getEqualFrom(resources.get(TEST_TYPE),
- findResourceWithOrdinal(testsUnderParent0, 2));
-
- checkResourceFailedUpgrade(failedTest1);
- checkResourceFailedUpgrade(failedTest2);
- checkOthersUpgraded(testsUnderParent0, failedTest1, failedTest2);
-
- Resource failedSibling = getEqualFrom(resources.get(SIBLING_TYPE),
- findResourceWithOrdinal(siblingsUnderParent1, 1));
-
- checkResourceFailedUpgrade(failedSibling);
- checkOthersUpgraded(siblingsUnderParent1, failedSibling);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
+ @PluginContainerSetup(plugins = {TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME,
BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME},
+ sharedGroup = FAILURE_ON_LEAF_TEST, clearDataDir = true,
numberOfInitialDiscoveries = 3)
+ public void testFailureOnLeaf_V1() throws Exception {
+ final FakeServerInventory inventory = new FakeServerInventory();
+ setServerSideFake(FAILURE_ON_LEAF_TEST, inventory);
+
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
+ //in here we set up the failures that are going to happen when
+ //the v2 plugins are run
+
+ Resource parent0 = findResourceWithOrdinal(PARENT_TYPE, 0);
+ assertNotNull(parent0, "Failed to find the parent to setup the failures
for.");
+ Resource parent1 = findResourceWithOrdinal(PARENT_TYPE, 1);
+ assertNotNull(parent1, "Failed to find the parent to setup the failures
for.");
+
+ addChildrenToFail(parent0, TEST_TYPE, 1, 2);
+ addChildrenToFail(parent1, SIBLING_TYPE, 1);
}
+ @Test(dependsOnMethods = "testFailureOnLeaf_V1")
+ @PluginContainerSetup(plugins = {TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME,
BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME, SIBLING_V2_PLUGIN_NAME},
+ sharedGroup = FAILURE_ON_LEAF_TEST, clearInventoryDat = false,
numberOfInitialDiscoveries = 3)
+ public void testFailureOnLeaf_V2() {
+ final FakeServerInventory inventory = (FakeServerInventory)
getServerSideFake(FAILURE_ON_LEAF_TEST);
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
+ Map<ResType, Set<Resource>> resources =
getResourcesFromInventory(inventory, ALL_TYPES);
+
+ checkPresenceOfResourceTypes(resources, ALL_TYPES);
+
+ checkNumberOfResources(resources, ROOT_TYPE, 1);
+ checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
+
+ checkResourcesUpgraded(resources.get(PARENT_TYPE), 3);
+ checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
+
+ Resource parent0 = findResourceWithOrdinal(PARENT_TYPE, 0);
+ Resource parent1 = findResourceWithOrdinal(PARENT_TYPE, 1);
+ Resource parent2 = findResourceWithOrdinal(PARENT_TYPE, 2);
+
+ Set<Resource> testsUnderParent0 =
filterResources(parent0.getChildResources(), TEST_TYPE);
+ Set<Resource> siblingsUnderParent0 =
filterResources(parent0.getChildResources(), SIBLING_TYPE);
+ Set<Resource> testsUnderParent1 =
filterResources(parent1.getChildResources(), TEST_TYPE);
+ Set<Resource> siblingsUnderParent1 =
filterResources(parent1.getChildResources(), SIBLING_TYPE);
+ Set<Resource> testsUnderParent2 =
filterResources(parent2.getChildResources(), TEST_TYPE);
+ Set<Resource> siblingsUnderParent2 =
filterResources(parent2.getChildResources(), SIBLING_TYPE);
+
+ //first check for the successful upgrades
+ checkResourcesUpgraded(testsUnderParent2, 15);
+ checkResourcesUpgraded(siblingsUnderParent2, 15);
+ checkResourcesUpgraded(siblingsUnderParent0, 15);
+ checkResourcesUpgraded(testsUnderParent1, 15);
+
+ //there should be no newly discovered sibling resources of the failed ones
+ assertEquals(testsUnderParent0.size(), 10);
+ assertEquals(siblingsUnderParent1.size(), 10);
+
+ //check that the failed resources have the error attached to them
+ //we find the resource instance from the map provided to this method
+ //because that map contains the resources as found on the server-side
+ //(i.e. they include error objects).
+ Resource failedTest1 = getEqualFrom(resources.get(TEST_TYPE),
+ findResourceWithOrdinal(testsUnderParent0, 1));
+ Resource failedTest2 = getEqualFrom(resources.get(TEST_TYPE),
+ findResourceWithOrdinal(testsUnderParent0, 2));
+
+ checkResourceFailedUpgrade(failedTest1);
+ checkResourceFailedUpgrade(failedTest2);
+ checkOthersUpgraded(testsUnderParent0, failedTest1, failedTest2);
+
+ Resource failedSibling = getEqualFrom(resources.get(SIBLING_TYPE),
+ findResourceWithOrdinal(siblingsUnderParent1, 1));
+
+ checkResourceFailedUpgrade(failedSibling);
+ checkOthersUpgraded(siblingsUnderParent1, failedSibling);
+ }
+
@Test
- public void testFailureOnDependencies() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
-
- executeTestWithPlugins(getAllDepsFor(TEST_V1_PLUGIN_NAME,
PARENT_SIBLING_V1_PLUGIN_NAME),
- new AbstractTestPayload(true, Collections.<ResType> emptyList()) {
- public void test(Map<ResType, Set<Resource>>
resourceUpgradeTestResources) {
- //in here we set up the failures that are going to happen when
- //the v2 plugins are run
-
- Resource parent = findResourceWithOrdinal(PARENT_DEP_TYPE, 0);
- assertNotNull(parent, "Failed to find the parent to setup the
failures for.");
-
- addChildrenToFail(parent, PARENT_TYPE, 0);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
-
- executeTestWithPlugins(getAllDepsFor(TEST_V2_PLUGIN_NAME,
PARENT_SIBLING_V2_PLUGIN_NAME),
- new AbstractTestPayload(false, ALL_TYPES) {
- public void test(Map<ResType, Set<Resource>> resources) {
- checkPresenceOfResourceTypes(resources, getExpectedResourceTypes());
-
- checkNumberOfResources(resources, ROOT_TYPE, 1);
- checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
- checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
-
- //check that the failed resources have the error attached to them
- //we find the resource instance from the map provided to this method
- //because that map contains the resources as found on the server-side
- //(i.e. they include error objects).
- Resource parent0 = getEqualFrom(resources.get(PARENT_TYPE),
findResourceWithOrdinal(PARENT_TYPE, 0));
- Resource parent1 = getEqualFrom(resources.get(PARENT_TYPE),
findResourceWithOrdinal(PARENT_TYPE, 1));
-
- //v2 plugin discovers 3 resources but because parent0 failed to
upgrade,
- //the discovery shouldn't have occurred leaving us with the 2
already existing resources.
- checkNumberOfResources(resources, PARENT_TYPE, 2);
- checkResourceFailedUpgrade(parent0);
- checkOthersUpgraded(resources.get(PARENT_TYPE), parent0);
-
- //parent1 upgraded ok, so discovering its children should have
executed.
- //this is v2, so we should find 15 of each.
- checkResourcesUpgraded(filterResources(parent1.getChildResources(),
TEST_TYPE), 15);
- checkResourcesUpgraded(filterResources(parent1.getChildResources(),
SIBLING_TYPE), 15);
-
- //these shouldn't have been upgraded. in v1 we had 10 resources
of TEST_TYPE
- //and 10 resources of SIBLING_TYPE and that's what we should be
seeing
- //now.
-
checkResourcesNotUpgraded(filterResources(parent0.getChildResources(), TEST_TYPE), 10);
-
checkResourcesNotUpgraded(filterResources(parent0.getChildResources(), SIBLING_TYPE),
10);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
+ @PluginContainerSetup(plugins = {TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME,
BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME},
+ sharedGroup = FAILURE_ON_DEPENDENCIES_TEST, clearDataDir = true,
numberOfInitialDiscoveries = 3)
+ public void testFailureOnDependencies_V1() throws Exception {
+ final FakeServerInventory inventory = new FakeServerInventory();
+ setServerSideFake(FAILURE_ON_DEPENDENCIES_TEST, inventory);
+
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
+ //in here we set up the failures that are going to happen when
+ //the v2 plugins are run
+
+ Resource parent = findResourceWithOrdinal(PARENT_DEP_TYPE, 0);
+ assertNotNull(parent, "Failed to find the parent to setup the failures
for.");
+
+ addChildrenToFail(parent, PARENT_TYPE, 0);
}
+
+ @Test(dependsOnMethods = "testFailureOnDependencies_V1")
+ @PluginContainerSetup(plugins = {TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME,
BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME, SIBLING_V2_PLUGIN_NAME},
+ sharedGroup = FAILURE_ON_DEPENDENCIES_TEST, clearInventoryDat = false,
numberOfInitialDiscoveries = 3)
+ public void testFailureOnDependencies_V2() throws Exception {
+ final FakeServerInventory inventory = (FakeServerInventory)
getServerSideFake(FAILURE_ON_DEPENDENCIES_TEST);
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
+ Map<ResType, Set<Resource>> resources =
getResourcesFromInventory(inventory, ALL_TYPES);
+
+ checkPresenceOfResourceTypes(resources, ALL_TYPES);
+
+ checkNumberOfResources(resources, ROOT_TYPE, 1);
+ checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
+ checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
+
+ //check that the failed resources have the error attached to them
+ //we find the resource instance from the map provided to this method
+ //because that map contains the resources as found on the server-side
+ //(i.e. they include error objects).
+ Resource parent0 = getEqualFrom(resources.get(PARENT_TYPE),
findResourceWithOrdinal(PARENT_TYPE, 0));
+ Resource parent1 = getEqualFrom(resources.get(PARENT_TYPE),
findResourceWithOrdinal(PARENT_TYPE, 1));
+
+ checkResourceFailedUpgrade(parent0);
+ checkOthersUpgraded(resources.get(PARENT_TYPE), parent0);
+ //v2 plugin discovers 3 resources but because parent0 failed to upgrade,
+ //the discovery shouldn't have occurred leaving us with the 2 already
existing resources.
+ checkNumberOfResources(resources, PARENT_TYPE, 2);
+
+ //parent1 upgraded ok, so discovering its children should have executed.
+ //this is v2, so we should find 15 of each.
+ checkResourcesUpgraded(filterResources(parent1.getChildResources(), TEST_TYPE),
15);
+ checkResourcesUpgraded(filterResources(parent1.getChildResources(),
SIBLING_TYPE), 15);
+
+ //these shouldn't have been upgraded. in v1 we had 10 resources of TEST_TYPE
+ //and 10 resources of SIBLING_TYPE and that's what we should be seeing
+ //now.
+ checkResourcesNotUpgraded(filterResources(parent0.getChildResources(),
TEST_TYPE), 10);
+ checkResourcesNotUpgraded(filterResources(parent0.getChildResources(),
SIBLING_TYPE), 10);
+ }
+
@Test
- public void testResourcesRevertedToOriginalStateAfterFailedUpgrade() throws Exception
{
- setCurrentServerSideInventory(new FakeServerInventory());
-
- //let it all run in v1
- executeTestWithPlugins(getAllDepsFor(TEST_V1_PLUGIN_NAME,
PARENT_SIBLING_V1_PLUGIN_NAME),
- new AbstractTestPayload(true, Collections.<ResType> emptyList()) {
- public void test(Map<ResType, Set<Resource>>
resourceUpgradeTestResources) {
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
-
- getCurrentServerSideInventory().setFailUpgrade(true);
+ @PluginContainerSetup(plugins = {TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME,
BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME},
+ sharedGroup = RESOURCES_REVERTED_TO_ORIGINAL_STATE_AFTER_FAILED_UPGRAGE_TEST,
clearDataDir = true, numberOfInitialDiscoveries = 3)
+ public void testResourcesRevertedToOriginalStateAfterFailedUpgrade_V1() throws
Exception {
+ final FakeServerInventory inventory = new FakeServerInventory();
+ setServerSideFake(RESOURCES_REVERTED_TO_ORIGINAL_STATE_AFTER_FAILED_UPGRAGE_TEST,
inventory);
- //now let's run with v2 plugins and check the layout of the inventory
- executeTestWithPlugins(getAllDepsFor(TEST_V2_PLUGIN_NAME,
PARENT_SIBLING_V2_PLUGIN_NAME),
- new AbstractTestPayload(false, ALL_TYPES) {
-
- public void test(Map<ResType, Set<Resource>> resources) {
- checkPresenceOfResourceTypes(resources, getExpectedResourceTypes());
-
- checkNumberOfResources(resources, ROOT_TYPE, 1);
- checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
-
- //check that the resources are upgraded
- checkResourcesNotUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE),
1);
- checkResourcesNotUpgraded(resources.get(PARENT_TYPE), 2);
- checkResourcesNotUpgraded(resources.get(SIBLING_TYPE), 20);
- checkResourcesNotUpgraded(resources.get(TEST_TYPE), 20);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
}
+
+ @Test(dependsOnMethods =
"testResourcesRevertedToOriginalStateAfterFailedUpgrade_V1")
+ @PluginContainerSetup(plugins = {TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME,
BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME, SIBLING_V2_PLUGIN_NAME},
+ sharedGroup = RESOURCES_REVERTED_TO_ORIGINAL_STATE_AFTER_FAILED_UPGRAGE_TEST,
clearInventoryDat = false, numberOfInitialDiscoveries = 3)
+ public void testResourcesRevertedToOriginalStateAfterFailedUpgrade_V2() throws
Exception {
+ final FakeServerInventory inventory = (FakeServerInventory)
getServerSideFake(RESOURCES_REVERTED_TO_ORIGINAL_STATE_AFTER_FAILED_UPGRAGE_TEST);
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ inventory.setFailUpgrade(true);
+
+ startConfiguredPluginContainer();
+
+ Map<ResType, Set<Resource>> resources =
getResourcesFromInventory(inventory, ALL_TYPES);
+ checkPresenceOfResourceTypes(resources, ALL_TYPES);
+
+ checkNumberOfResources(resources, ROOT_TYPE, 1);
+ checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
+
+ //check that the resources are not upgraded
+ checkResourcesNotUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
+ checkResourcesNotUpgraded(resources.get(PARENT_TYPE), 2);
+ checkResourcesNotUpgraded(resources.get(SIBLING_TYPE), 20);
+ checkResourcesNotUpgraded(resources.get(TEST_TYPE), 20);
+ }
@SuppressWarnings("unchecked")
- @Override
- protected void defineDefaultExpectations(Expectations expectations) {
- super.defineDefaultExpectations(expectations);
+ protected void defineDefaultExpectations(FakeServerInventory inventory, Expectations
expectations) {
+ super.defineDefaultExpectations(inventory, expectations);
try {
-
expectations.allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
+ ServerServices ss = pluginContainerConfiguration.getServerServices();
+ expectations.allowing(ss.getDiscoveryServerService()).mergeInventoryReport(
expectations.with(Expectations.any(InventoryReport.class)));
-
expectations.will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
+
expectations.will(inventory.mergeInventoryReport(InventoryStatus.COMMITTED));
- expectations.allowing(getCurrentDiscoveryServerService()).upgradeResources(
+ expectations.allowing(ss.getDiscoveryServerService()).upgradeResources(
expectations.with(Expectations.any(Set.class)));
- expectations.will(getCurrentServerSideInventory().upgradeResources());
+ expectations.will(inventory.upgradeResources());
} catch (InvalidInventoryReportException e) {
//this is not going to happen because we're mocking the invocation
}
}
- private Set<String> getAllDepsFor(String... plugins) {
- HashSet<String> deps = new HashSet<String>();
- for (String plugin : plugins) {
- deps.add(plugin);
- deps.addAll(DEPS.get(plugin));
- }
-
- return deps;
- }
-
- protected static void checkPresenceOfResourceTypes(Map<ResType,
Set<Resource>> resources, Set<ResType> expectedTypes) {
+ protected static void checkPresenceOfResourceTypes(Map<ResType,
Set<Resource>> resources, Collection<ResType> expectedTypes) {
for (ResType resType : expectedTypes) {
assertNotNull(resources.get(resType), "Expecting some resources of type
" + resType);
}
@@ -531,6 +499,21 @@ public class ResourceUpgradeFailureHandlingTest extends
ResourceUpgradeTestBase
return ret;
}
+
+ private Map<ResType, Set<Resource>>
getResourcesFromInventory(FakeServerInventory inventory, Collection<ResType> types)
{
+ Map<ResType, Set<Resource>> resources = new HashMap<ResType,
Set<Resource>>();
+
+ for(ResType type : types) {
+ ResourceType resType =
PluginContainer.getInstance().getPluginManager().getMetadataManager()
+ .getType(type.getResourceTypeName(), type.getResourceTypePluginName());
+
+ Set<Resource> rs = inventory.findResourcesByType(resType);
+ resources.put(type, rs);
+ }
+
+ return resources;
+ }
+
private static <T> T getEqualFrom(Collection<? extends T> collection, T
object) {
for (T other : collection) {
if (object.equals(other)) {
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeProgressHandlingTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeProgressHandlingTest.java
index 3234c30..65deac7 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeProgressHandlingTest.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeProgressHandlingTest.java
@@ -19,23 +19,14 @@
package org.rhq.core.pc.upgrade;
-import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertEquals;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import static org.testng.Assert.assertNotNull;
import org.jmock.Expectations;
-import org.jmock.Mockery;
import org.testng.annotations.Test;
import org.rhq.core.domain.resource.Resource;
+import org.rhq.test.pc.PluginContainerSetup;
/**
*
@@ -45,139 +36,113 @@ import org.rhq.core.domain.resource.Resource;
@Test
public class ResourceUpgradeProgressHandlingTest extends
ResourceUpgradeFailureHandlingTest {
- private static final String BASE_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-base-1.0.0.jar";
- private static final String PARENT_DEP_V1_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-parentdep-1.0.0.jar";
- private static final String PARENT_DEP_V2_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-parentdep-2.0.0.jar";
- private static final String ROOT_PLUGIN_NAME =
"/resource-upgrade-test-plugin-multi-root-1.0.0.jar";
- private static final String UPGRADE_PROGRESS_PLUGIN_V1_FILENAME =
"/resource-upgrade-test-plugin-progress-test-1.0.0.jar";
- private static final String UPGRADE_PROGRESS_PLUGIN_V2_FILENAME =
"/resource-upgrade-test-plugin-progress-test-2.0.0.jar";
- private static final String UPGRADE_DUPLICATE_PLUGIN_V1_FILENAME =
"/resource-upgrade-test-plugin-duplicate-test-1.0.0.jar";
- private static final String UPGRADE_DUPLICATE_PLUGIN_V2_FILENAME =
"/resource-upgrade-test-plugin-duplicate-test-2.0.0.jar";
-
+ //test names
+ private static final String DUPLICIT_RESOURCE_KEYS_HANDLED_CORRECTLY_TEST =
"DuplicitResourceKeysHandledCorrectly";
+ private static final String
PARENT_RESOURCE_STARTED_UPGRADED_WHEN_CHILD_RESOURCE_BEING_UPGRADED_TEST =
"ParentResourceStartedUpgradedWhenChildResourceBeingUpgraded";
+
+ //plugin names
+ private static final String BASE_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-base-1.0.0.jar";
+ private static final String PARENT_DEP_V1_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-parentdep-1.0.0.jar";
+ private static final String PARENT_DEP_V2_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-parentdep-2.0.0.jar";
+ private static final String ROOT_PLUGIN_NAME =
"classpath:///resource-upgrade-test-plugin-multi-root-1.0.0.jar";
+ private static final String UPGRADE_PROGRESS_PLUGIN_V1_FILENAME =
"classpath:///resource-upgrade-test-plugin-progress-test-1.0.0.jar";
+ private static final String UPGRADE_PROGRESS_PLUGIN_V2_FILENAME =
"classpath:///resource-upgrade-test-plugin-progress-test-2.0.0.jar";
+ private static final String UPGRADE_DUPLICATE_PLUGIN_V1_FILENAME =
"classpath:///resource-upgrade-test-plugin-duplicate-test-1.0.0.jar";
+ private static final String UPGRADE_DUPLICATE_PLUGIN_V2_FILENAME =
"classpath:///resource-upgrade-test-plugin-duplicate-test-2.0.0.jar";
+
private static final ResType TEST_TYPE = new ResType("TestResource",
"test");
private static final ResType PARENT_DEP_TYPE = new
ResType("ParentDependency", "parentdep");
- private static final ResType ROOT_TYPE = new ResType("Root",
"root");
-
- private static final HashMap<String, List<String>> DEPS;
-
- static {
- DEPS = new HashMap<String, List<String>>();
-
- DEPS.put(BASE_PLUGIN_NAME, Collections.<String> emptyList());
- DEPS.put(PARENT_DEP_V1_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME,
ROOT_PLUGIN_NAME));
- DEPS.put(PARENT_DEP_V2_PLUGIN_NAME, DEPS.get(PARENT_DEP_V1_PLUGIN_NAME));
- DEPS.put(ROOT_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME));
- DEPS.put(UPGRADE_PROGRESS_PLUGIN_V1_FILENAME, Arrays.asList(BASE_PLUGIN_NAME,
ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME));
- DEPS.put(UPGRADE_PROGRESS_PLUGIN_V2_FILENAME, Arrays.asList(BASE_PLUGIN_NAME,
ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME));
- DEPS.put(UPGRADE_DUPLICATE_PLUGIN_V1_FILENAME, Arrays.asList(BASE_PLUGIN_NAME,
ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME));
- DEPS.put(UPGRADE_DUPLICATE_PLUGIN_V2_FILENAME, Arrays.asList(BASE_PLUGIN_NAME,
ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME));
- }
+
+ @Test
+ @PluginContainerSetup(plugins = { UPGRADE_PROGRESS_PLUGIN_V1_FILENAME,
BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME,
+ PARENT_DEP_V1_PLUGIN_NAME }, sharedGroup =
PARENT_RESOURCE_STARTED_UPGRADED_WHEN_CHILD_RESOURCE_BEING_UPGRADED_TEST, clearDataDir =
true)
+ public void testParentResourceStartedUpgradedWhenChildResourceBeingUpgraded_V1()
throws Exception {
+ final FakeServerInventory inventory = new FakeServerInventory();
+
setServerSideFake(PARENT_RESOURCE_STARTED_UPGRADED_WHEN_CHILD_RESOURCE_BEING_UPGRADED_TEST,
inventory);
- private Set<String> getAllDepsFor(String... plugins) {
- HashSet<String> deps = new HashSet<String>();
- for (String plugin : plugins) {
- deps.add(plugin);
- deps.addAll(DEPS.get(plugin));
- }
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
- return deps;
- }
-
- @Override
- protected Collection<String> getRequiredPlugins() {
- return Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME,
PARENT_DEP_V1_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME,
- UPGRADE_PROGRESS_PLUGIN_V1_FILENAME, UPGRADE_PROGRESS_PLUGIN_V2_FILENAME,
UPGRADE_DUPLICATE_PLUGIN_V1_FILENAME,
- UPGRADE_DUPLICATE_PLUGIN_V2_FILENAME);
+ startConfiguredPluginContainer();
+
+ //in here we set up the failures that are going to happen when
+ //the v2 plugins are run
+
+ Resource parent = findResourceWithOrdinal(PARENT_DEP_TYPE, 0);
+ assertNotNull(parent, "Failed to find the parent.");
}
- @Test
- public void testParentResourceStartedUpgradedWhenChildResourceBeingUpgraded() throws
Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
-
- executeTestWithPlugins(getAllDepsFor(UPGRADE_PROGRESS_PLUGIN_V1_FILENAME),
- new AbstractTestPayload(true, Collections.<ResType> emptyList()) {
- public void test(Map<ResType, Set<Resource>>
resourceUpgradeTestResources) {
- //in here we set up the failures that are going to happen when
- //the v2 plugins are run
-
- Resource parent = findResourceWithOrdinal(PARENT_DEP_TYPE, 0);
- assertNotNull(parent, "Failed to find the parent.");
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
-
+ @Test(dependsOnMethods =
"testParentResourceStartedUpgradedWhenChildResourceBeingUpgraded_V1")
+ @PluginContainerSetup(plugins = { UPGRADE_PROGRESS_PLUGIN_V2_FILENAME,
BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME,
+ PARENT_DEP_V2_PLUGIN_NAME }, sharedGroup =
PARENT_RESOURCE_STARTED_UPGRADED_WHEN_CHILD_RESOURCE_BEING_UPGRADED_TEST,
clearInventoryDat = false)
+ public void testParentResourceStartedUpgradedWhenChildResourceBeingUpgraded_V2()
throws Exception {
+ final FakeServerInventory inventory = (FakeServerInventory)
getServerSideFake(PARENT_RESOURCE_STARTED_UPGRADED_WHEN_CHILD_RESOURCE_BEING_UPGRADED_TEST);
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
//the upgrade progress plugin is set to check that the parent resource key
//has been upgraded during its upgrade method, so we just need to check here
//that everything got upgraded. If it was not, it'd mean that the the
progress
//plugin failed the upgrade because it didn't see its parent upgraded.
- executeTestWithPlugins(getAllDepsFor(UPGRADE_PROGRESS_PLUGIN_V2_FILENAME),
- new AbstractTestPayload(false, Arrays.asList(TEST_TYPE, PARENT_DEP_TYPE)) {
- public void test(Map<ResType, Set<Resource>>
resourceUpgradeTestResources) {
-
checkResourcesUpgraded(resourceUpgradeTestResources.get(PARENT_DEP_TYPE), 1);
- checkResourcesUpgraded(resourceUpgradeTestResources.get(TEST_TYPE),
2);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
+
+ checkResourcesUpgraded(getTestingResources(inventory, PARENT_DEP_TYPE), 1);
+ checkResourcesUpgraded(getTestingResources(inventory, TEST_TYPE), 2);
}
-
+
@Test
- public void testDuplicitResourceKeysHandledCorrectly() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
-
- executeTestWithPlugins(getAllDepsFor(UPGRADE_DUPLICATE_PLUGIN_V1_FILENAME),
- new AbstractTestPayload(true, Arrays.asList(PARENT_DEP_TYPE, TEST_TYPE)) {
-
- public void test(Map<ResType, Set<Resource>>
resourceUpgradeTestResources) {
- //there's not much to check with the v1 plugins. let's just
check all the
- //resources have been discovered
-
assertEquals(resourceUpgradeTestResources.get(PARENT_DEP_TYPE).size(), 1, "The V1
inventory should have 1 parent.");
- assertEquals(resourceUpgradeTestResources.get(TEST_TYPE).size(), 2,
"The V1 inventory should have 2 test resources.");
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
-
+ @PluginContainerSetup(plugins = { UPGRADE_DUPLICATE_PLUGIN_V1_FILENAME,
BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME,
+ PARENT_DEP_V1_PLUGIN_NAME }, sharedGroup =
DUPLICIT_RESOURCE_KEYS_HANDLED_CORRECTLY_TEST, clearDataDir = true,
numberOfInitialDiscoveries = 2)
+ public void testDuplicitResourceKeysHandledCorrectly_V1() throws Exception {
+ final FakeServerInventory inventory = new FakeServerInventory();
+ setServerSideFake(DUPLICIT_RESOURCE_KEYS_HANDLED_CORRECTLY_TEST, inventory);
+
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
+ //there's not much to check with the v1 plugins. let's just check all the
+ //resources have been discovered
+ assertEquals(getTestingResources(inventory, PARENT_DEP_TYPE).size(), 1,
+ "The V1 inventory should have 1 parent.");
+ assertEquals(getTestingResources(inventory, TEST_TYPE).size(), 2,
+ "The V1 inventory should have 2 test resources.");
+ }
+
+ @Test(dependsOnMethods = "testDuplicitResourceKeysHandledCorrectly_V1")
+ @PluginContainerSetup(plugins = { UPGRADE_DUPLICATE_PLUGIN_V2_FILENAME,
BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME,
+ PARENT_DEP_V2_PLUGIN_NAME }, sharedGroup =
DUPLICIT_RESOURCE_KEYS_HANDLED_CORRECTLY_TEST, clearInventoryDat = false,
numberOfInitialDiscoveries = 2)
+ public void testDuplicitResourceKeysHandledCorrectly_V2() throws Exception {
+ final FakeServerInventory inventory = (FakeServerInventory)
getServerSideFake(DUPLICIT_RESOURCE_KEYS_HANDLED_CORRECTLY_TEST);
+
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
//now the V2 test resource is set to create 2 resources with the same resource
keys.
//the upgrade should therefore fail.
- executeTestWithPlugins(getAllDepsFor(UPGRADE_DUPLICATE_PLUGIN_V2_FILENAME),
- new AbstractTestPayload(false, Arrays.asList(PARENT_DEP_TYPE, TEST_TYPE)) {
- public void test(Map<ResType, Set<Resource>>
resourceUpgradeTestResources) {
-
checkResourcesUpgraded(resourceUpgradeTestResources.get(PARENT_DEP_TYPE), 1);
-
-
checkResourcesNotUpgraded(resourceUpgradeTestResources.get(TEST_TYPE), 2);
-
- for(Resource r : resourceUpgradeTestResources.get(TEST_TYPE)) {
- checkResourceFailedUpgrade(r);
- }
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
- }
+
+ checkResourcesUpgraded(getTestingResources(inventory, PARENT_DEP_TYPE), 1);
+
+ checkResourcesNotUpgraded(getTestingResources(inventory, TEST_TYPE), 2);
+
+ for (Resource r : getTestingResources(inventory, TEST_TYPE)) {
+ checkResourceFailedUpgrade(r);
+ }
+ }
}
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
index e2a8a84..39ae23d 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
@@ -1,24 +1,20 @@
/*
* RHQ Management Platform
- * Copyright (C) 2005-2010 Red Hat, Inc.
+ * Copyright (C) 2005-2011 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License, version 2, as
- * published by the Free Software Foundation, and/or the GNU Lesser
- * General Public License, version 2.1, also as published by the Free
- * Software Foundation.
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License and the GNU Lesser General Public License
- * for more details.
+ * GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * and the GNU Lesser General Public License along with this program;
- * if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.rhq.core.pc.upgrade;
@@ -28,304 +24,320 @@ import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.io.File;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
import java.util.Set;
import org.jmock.Expectations;
-import org.jmock.Mockery;
+import org.testng.annotations.AfterSuite;
import org.testng.annotations.Test;
import org.rhq.core.clientapi.server.discovery.InventoryReport;
import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.pc.PluginContainer;
+import org.rhq.core.pc.ServerServices;
import org.rhq.core.pc.inventory.ResourceContainer;
+import org.rhq.test.pc.PluginContainerSetup;
+import org.rhq.test.pc.PluginContainerTest;
/**
- * Test cases for resource upgrade.
*
+ *
* @author Lukas Krejci
*/
-@Test(sequential = true, invocationCount = 1)
+@Test
public class ResourceUpgradeTest extends ResourceUpgradeTestBase {
- private static final String PLUGIN_V1_FILENAME =
"/resource-upgrade-test-plugin-1.0.0.jar";
- private static final String PLUGIN_V2_FILENAME =
"/resource-upgrade-test-plugin-2.0.0.jar";
- private static final String FAILING_PLUGIN_FILE_NAME =
"/resource-upgrade-test-plugin-3.0.0.jar";
+ private static final String INCLUDE_UNCOMMITTED_RESOURCES_TEST =
"includeUncommittedResources";
+ private static final String UPGRADE_DATA_TEST = "upgradeData";
+ private static final String
INVENTORY_REINITIALIZATION_FROM_SERVER_DURING_UPGRADE_TEST =
"inventoryReinitializationFromServerDuringUpgrade";
+ private static final String SKIP_UPGRADE_WHEN_SERVER_UNAVAILABLE_TEST =
"skipUpgradeWhenServerUnavailable";
+ private static final String UPGRADE_WITH_PLATFORM_DELETED_ON_SERVER_TEST =
"upgradeWithPlatformDeletedOnServer";
+ private static final String UPGRADE_FAILURE_HANDLING =
"upgradeFailureHandling";
+
+ private static final String PLUGIN_V1_FILENAME =
"classpath:///resource-upgrade-test-plugin-1.0.0.jar";
+ private static final String PLUGIN_V2_FILENAME =
"classpath:///resource-upgrade-test-plugin-2.0.0.jar";
+ private static final String FAILING_PLUGIN_FILE_NAME =
"classpath:///resource-upgrade-test-plugin-3.0.0.jar";
private static final String SINGLETON_RESOURCE_TYPE_NAME = "Resource";
private static final String SINGLETON_RESOURCE_TYPE_PLUGIN_NAME =
"ResourceUpgradeTest";
private static final ResType SINGLETON_TYPE = new
ResType(SINGLETON_RESOURCE_TYPE_NAME,
SINGLETON_RESOURCE_TYPE_PLUGIN_NAME);
- private static List<ResType> getMyExpectedTypes() {
- return Arrays.asList(SINGLETON_TYPE);
+ @AfterSuite
+ public void cleanAfterPluginContainers() throws Exception {
+ PluginContainerTest.clearStorage();
}
- protected Collection<String> getRequiredPlugins() {
- return Arrays.asList(PLUGIN_V1_FILENAME, PLUGIN_V2_FILENAME,
FAILING_PLUGIN_FILE_NAME);
+ @Test
+ @PluginContainerSetup(plugins = { PLUGIN_V1_FILENAME }, sharedGroup =
INCLUDE_UNCOMMITTED_RESOURCES_TEST, clearDataDir = true)
+ public void testIncludeUncommittedResources_V1() throws Exception {
+ initialSyncAndDiscovery(INCLUDE_UNCOMMITTED_RESOURCES_TEST,
InventoryStatus.NEW);
}
- @Test
- public void testIncludeUncommittedResources() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
- initialSyncAndDiscovery(InventoryStatus.NEW);
+ @Test(dependsOnMethods = { "testIncludeUncommittedResources_V1" })
+ @PluginContainerSetup(plugins = { PLUGIN_V2_FILENAME }, sharedGroup =
INCLUDE_UNCOMMITTED_RESOURCES_TEST, clearInventoryDat = false)
+ @SuppressWarnings("unchecked")
+ public void testIncludeUncommittedResources_V2() throws Exception {
+ final FakeServerInventory inv = (FakeServerInventory) PluginContainerTest
+ .getServerSideFake(INCLUDE_UNCOMMITTED_RESOURCES_TEST);
+ final ServerServices ss =
PluginContainerTest.getCurrentPluginContainerConfiguration().getServerServices();
- TestPayload testNoChange = new AbstractTestPayload(false, getMyExpectedTypes())
{
- public void test(Map<ResType, Set<Resource>> discoveredResources)
{
- assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1,
- "Expected single test resource but multiple found.");
+ PluginContainerTest.getCurrentMockContext().checking(new Expectations() {
+ {
+ defineDefaultExpectations(inv, this);
- Resource discoveredResource =
discoveredResources.get(SINGLETON_TYPE).iterator().next();
+
allowing(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(inv.mergeInventoryReport(InventoryStatus.COMMITTED));
- assertEquals(discoveredResource.getResourceKey(),
"resource-key-v2");
- assertEquals(discoveredResource.getName(),
"resource-name-v2");
- assertEquals(discoveredResource.getDescription(),
"resource-description-v2");
+
oneOf(ss.getDiscoveryServerService()).upgradeResources(with(any(Set.class)));
+ will(inv.upgradeResources());
}
+ });
- @SuppressWarnings("unchecked")
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
+ PluginContainerTest.startConfiguredPluginContainer();
-
allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
- with(any(InventoryReport.class)));
-
will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
+ Set<Resource> resources = getTestingResources(inv, SINGLETON_TYPE);
-
oneOf(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class)));
- will(getCurrentServerSideInventory().upgradeResources());
- }
- };
- }
- };
+ assertEquals(resources.size(), 1, "Expected single test resource but
multiple found.");
- executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), testNoChange);
+ Resource discoveredResource = resources.iterator().next();
+
+ assertEquals(discoveredResource.getResourceKey(), "resource-key-v2");
+ assertEquals(discoveredResource.getName(), "resource-name-v2");
+ assertEquals(discoveredResource.getDescription(),
"resource-description-v2");
}
@Test
- public void testUpgradeData() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
- upgradeTest(false);
+ @PluginContainerSetup(plugins = { PLUGIN_V1_FILENAME }, sharedGroup =
UPGRADE_DATA_TEST, clearDataDir = true)
+ public void testUpgradeData_V1() throws Exception {
+ initialSyncAndDiscovery(UPGRADE_DATA_TEST, InventoryStatus.COMMITTED);
+ }
+
+ @Test(dependsOnMethods = "testUpgradeData_V1")
+ @PluginContainerSetup(plugins = { PLUGIN_V2_FILENAME }, sharedGroup =
UPGRADE_DATA_TEST, clearInventoryDat = false)
+ public void testUpgradeData_V2() throws Exception {
+ upgradeTest(UPGRADE_DATA_TEST);
}
@Test
- public void testInventoryReinitializationFromServerDuringUpgrade() throws Exception
{
- setCurrentServerSideInventory(new FakeServerInventory());
- upgradeTest(true);
+ @PluginContainerSetup(plugins = { PLUGIN_V1_FILENAME }, sharedGroup =
INVENTORY_REINITIALIZATION_FROM_SERVER_DURING_UPGRADE_TEST, clearDataDir = true)
+ public void testInventoryReinitializationFromServerDuringUpgrade_V1() throws
Exception {
+
initialSyncAndDiscovery(INVENTORY_REINITIALIZATION_FROM_SERVER_DURING_UPGRADE_TEST,
InventoryStatus.COMMITTED);
+ }
+
+ @Test(dependsOnMethods =
"testInventoryReinitializationFromServerDuringUpgrade_V1")
+ @PluginContainerSetup(plugins = { PLUGIN_V2_FILENAME }, sharedGroup =
INVENTORY_REINITIALIZATION_FROM_SERVER_DURING_UPGRADE_TEST, clearInventoryDat = false)
+ public void testInventoryReinitializationFromServerDuringUpgrade_V2() throws
Exception {
+ upgradeTest(INVENTORY_REINITIALIZATION_FROM_SERVER_DURING_UPGRADE_TEST);
}
@Test
- public void testSkipUpgradeWhenServerUnavailable() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
- initialSyncAndDiscovery(InventoryStatus.COMMITTED);
+ @PluginContainerSetup(plugins = { PLUGIN_V1_FILENAME }, sharedGroup =
SKIP_UPGRADE_WHEN_SERVER_UNAVAILABLE_TEST, clearDataDir = true)
+ public void testSkipUpgradeWhenServerUnavailable_V1() throws Exception {
+ initialSyncAndDiscovery(SKIP_UPGRADE_WHEN_SERVER_UNAVAILABLE_TEST,
InventoryStatus.COMMITTED);
+ }
+
+ @Test(dependsOnMethods = "testSkipUpgradeWhenServerUnavailable_V1")
+ @PluginContainerSetup(plugins = { PLUGIN_V2_FILENAME }, sharedGroup =
SKIP_UPGRADE_WHEN_SERVER_UNAVAILABLE_TEST, clearInventoryDat = false)
+ @SuppressWarnings("unchecked")
+ public void testSkipUpgradeWhenServerUnavailable_V2() throws Exception {
+ final FakeServerInventory inv = (FakeServerInventory) PluginContainerTest
+ .getServerSideFake(SKIP_UPGRADE_WHEN_SERVER_UNAVAILABLE_TEST);
+ final ServerServices ss =
PluginContainerTest.getCurrentPluginContainerConfiguration().getServerServices();
- getCurrentServerSideInventory().setFailing(true);
+ inv.setFailing(true);
- TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) {
- public void test(Map<ResType, Set<Resource>> discoveredResources)
{
- assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1,
- "Expected single test resource but multiple found.");
+ PluginContainerTest.getCurrentMockContext().checking(new Expectations() {
+ {
+ defineDefaultExpectations(inv, this);
- Resource discoveredResource =
discoveredResources.get(SINGLETON_TYPE).iterator().next();
+
allowing(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(inv.mergeInventoryReport(InventoryStatus.COMMITTED));
- assertEquals(discoveredResource.getResourceKey(),
"resource-key-v1");
- assertEquals(discoveredResource.getName(),
"resource-name-v1");
- assertEquals(discoveredResource.getDescription(),
"resource-description-v1");
+
never(ss.getDiscoveryServerService()).upgradeResources(with(any(Set.class)));
}
+ });
- @SuppressWarnings("unchecked")
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
+ PluginContainerTest.startConfiguredPluginContainer();
-
allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
- with(any(InventoryReport.class)));
-
will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
+ Set<Resource> discoveredResources = getTestingResources(inv,
SINGLETON_TYPE);
-
never(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class)));
- }
- };
- }
- };
+ assertEquals(discoveredResources.size(), 1, "Expected single test resource
but multiple found.");
+
+ Resource discoveredResource = discoveredResources.iterator().next();
- executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), test);
+ assertEquals(discoveredResource.getResourceKey(), "resource-key-v1");
+ assertEquals(discoveredResource.getName(), "resource-name-v1");
+ assertEquals(discoveredResource.getDescription(),
"resource-description-v1");
}
@Test
- public void testUpgradeWithPlatformDeletedOnServer() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
- initialSyncAndDiscovery(InventoryStatus.COMMITTED);
+ @PluginContainerSetup(plugins = { PLUGIN_V1_FILENAME }, sharedGroup =
UPGRADE_WITH_PLATFORM_DELETED_ON_SERVER_TEST, clearDataDir = true)
+ public void testUpgradeWithPlatformDeletedOnServer_V1() throws Exception {
+ initialSyncAndDiscovery(UPGRADE_WITH_PLATFORM_DELETED_ON_SERVER_TEST,
InventoryStatus.COMMITTED);
+ }
- TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) {
- public void test(Map<ResType, Set<Resource>> discoveredResources)
{
- assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1,
- "Expected single test resource but multiple found.");
+ @Test(dependsOnMethods = "testUpgradeWithPlatformDeletedOnServer_V1")
+ @PluginContainerSetup(plugins = { PLUGIN_V2_FILENAME }, sharedGroup =
UPGRADE_WITH_PLATFORM_DELETED_ON_SERVER_TEST, clearInventoryDat = false)
+ @SuppressWarnings("unchecked")
+ public void testUpgradeWithPlatformDeletedOnServer_V2() throws Exception {
- Resource discoveredResource =
discoveredResources.get(SINGLETON_TYPE).iterator().next();
+ final FakeServerInventory inv = (FakeServerInventory) PluginContainerTest
+ .getServerSideFake(UPGRADE_WITH_PLATFORM_DELETED_ON_SERVER_TEST);
+ final ServerServices ss =
PluginContainerTest.getCurrentPluginContainerConfiguration().getServerServices();
- assertEquals(discoveredResource.getResourceKey(),
"resource-key-v2");
- assertEquals(discoveredResource.getName(),
"resource-name-v2");
- assertEquals(discoveredResource.getDescription(),
"resource-description-v2");
+ PluginContainerTest.getCurrentMockContext().checking(new Expectations() {
+ {
+ defineDefaultExpectations(inv, this);
- ResourceContainer container =
PluginContainer.getInstance().getInventoryManager()
- .getResourceContainer(discoveredResource);
- File dataDir = container.getResourceContext().getDataDirectory();
+ //the first merge will be triggered from within the upgrade process and
we are
+ //going to report null sync.
+
oneOf(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(inv.clearPlatform());
- File marker = new File(dataDir, "upgrade-succeeded");
+ //the rest of the inventory merges are executed by discoveries, so
let's import the
+ //discovered stuff into the server-side inventory.
+
allowing(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(inv.mergeInventoryReport(InventoryStatus.COMMITTED));
- assertFalse(marker.exists(),
- "The upgrade seems to have occured even though there
shouldn't have been a resource to upgrade.");
+
never(ss.getDiscoveryServerService()).upgradeResources(with(any(Set.class)));
}
+ });
- @SuppressWarnings("unchecked")
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
-
- //the first merge will be triggered from within the upgrade
process and we are
- //going to report null sync.
- oneOf(getCurrentDiscoveryServerService())
- .mergeInventoryReport(with(any(InventoryReport.class)));
- will(getCurrentServerSideInventory().clearPlatform());
-
- //the rest of the inventory merges are executed by discoveries,
so let's import the
- //discovered stuff into the server-side inventory.
-
allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
- with(any(InventoryReport.class)));
-
will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
-
-
never(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class)));
- }
- };
- }
- };
+ PluginContainerTest.startConfiguredPluginContainer();
+
+ Set<Resource> discoveredResources = getTestingResources(inv,
SINGLETON_TYPE);
+
+ assertEquals(discoveredResources.size(), 1, "Expected single test resource
but multiple found.");
+
+ Resource discoveredResource = discoveredResources.iterator().next();
- executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), test);
+ assertEquals(discoveredResource.getResourceKey(), "resource-key-v2");
+ assertEquals(discoveredResource.getName(), "resource-name-v2");
+ assertEquals(discoveredResource.getDescription(),
"resource-description-v2");
+
+ ResourceContainer container =
PluginContainer.getInstance().getInventoryManager()
+ .getResourceContainer(discoveredResource);
+ File dataDir = container.getResourceContext().getDataDirectory();
+
+ File marker = new File(dataDir, "upgrade-succeeded");
+
+ assertFalse(marker.exists(),
+ "The upgrade seems to have occured even though there shouldn't have
been a resource to upgrade.");
}
@Test
- public void testUpgradeFailureHandling() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
- initialSyncAndDiscovery(InventoryStatus.COMMITTED);
+ @PluginContainerSetup(plugins = PLUGIN_V1_FILENAME, sharedGroup =
UPGRADE_FAILURE_HANDLING, clearDataDir = true)
+ public void testUpgradeFailureHandling_V1() throws Exception {
+ initialSyncAndDiscovery(UPGRADE_FAILURE_HANDLING, InventoryStatus.COMMITTED);
+ }
- TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) {
- public void test(Map<ResType, Set<Resource>>
resourceUpgradeTestResources) {
- assertEquals(resourceUpgradeTestResources.get(SINGLETON_TYPE).size(), 1,
- "Expected single test resource but multiple found.");
+ @Test(dependsOnMethods = "testUpgradeFailureHandling_V1")
+ @PluginContainerSetup(plugins = FAILING_PLUGIN_FILE_NAME, sharedGroup =
UPGRADE_FAILURE_HANDLING, clearInventoryDat = false)
+ @SuppressWarnings("unchecked")
+ public void testUpgradeFailureHandling_V2() throws Exception {
+ final FakeServerInventory inv = (FakeServerInventory) PluginContainerTest
+ .getServerSideFake(UPGRADE_FAILURE_HANDLING);
+ final ServerServices ss =
PluginContainerTest.getCurrentPluginContainerConfiguration().getServerServices();
- Resource discoveredResource =
resourceUpgradeTestResources.get(SINGLETON_TYPE).iterator().next();
+ PluginContainerTest.getCurrentMockContext().checking(new Expectations() {
+ {
+ defineDefaultExpectations(inv, this);
- assertTrue(discoveredResource.getResourceErrors().size() > 0,
- "There should be upgrade errors persisted on the server
side.");
+
allowing(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(inv.mergeInventoryReport(InventoryStatus.COMMITTED));
- //the discovery of the failed resource mustn't have run
- ResourceContainer container =
PluginContainer.getInstance().getInventoryManager()
- .getResourceContainer(discoveredResource);
- File dataDir = container.getResourceContext().getDataDirectory();
+
oneOf(ss.getDiscoveryServerService()).upgradeResources(with(any(Set.class)));
+ will(inv.upgradeResources());
+ }
+ });
- File marker = new File(dataDir, "failing-discovery-ran");
+ PluginContainerTest.startConfiguredPluginContainer();
- assertFalse(marker.exists(),
- "The discovery of the resource type with a failed upgraded
resource must not be executed but it was.");
- }
+ Set<Resource> resourceUpgradeTestResources = getTestingResources(inv,
SINGLETON_TYPE);
- @SuppressWarnings("unchecked")
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
+ Resource discoveredResource = resourceUpgradeTestResources.iterator().next();
-
allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
- with(any(InventoryReport.class)));
-
will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
+ assertTrue(discoveredResource.getResourceErrors().size() > 0,
+ "There should be upgrade errors persisted on the server side.");
-
oneOf(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class)));
- will(getCurrentServerSideInventory().upgradeResources());
- }
- };
- }
- };
+ //the discovery of the failed resource mustn't have run
+ ResourceContainer container =
PluginContainer.getInstance().getInventoryManager()
+ .getResourceContainer(discoveredResource);
+ File dataDir = container.getResourceContext().getDataDirectory();
+
+ File marker = new File(dataDir, "failing-discovery-ran");
- executeTestWithPlugins(Collections.singleton(FAILING_PLUGIN_FILE_NAME), test);
+ assertFalse(marker.exists(),
+ "The discovery of the resource type with a failed upgraded resource must
not be executed but it was.");
}
- private void initialSyncAndDiscovery(final InventoryStatus requiredInventoryStatus)
throws Exception {
- cleanDataDir();
- executeTestWithPlugins(Collections.singleton(PLUGIN_V1_FILENAME), new
AbstractTestPayload(true,
- getMyExpectedTypes()) {
- public void test(Map<ResType, Set<Resource>> discoveredResources)
{
- assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1,
- "Expected single test resource but multiple found.");
+ private FakeServerInventory initialSyncAndDiscovery(String key, final InventoryStatus
requiredInventoryStatus)
+ throws Exception {
+ final FakeServerInventory inv = new FakeServerInventory();
+ PluginContainerTest.setServerSideFake(key, inv);
+ final ServerServices ss =
PluginContainerTest.getCurrentPluginContainerConfiguration().getServerServices();
- Resource discoveredResource =
discoveredResources.get(SINGLETON_TYPE).iterator().next();
+ PluginContainerTest.getCurrentMockContext().checking(new Expectations() {
+ {
+ defineDefaultExpectations(inv, this);
- assertEquals(discoveredResource.getResourceKey(),
"resource-key-v1");
- assertEquals(discoveredResource.getName(),
"resource-name-v1");
- assertEquals(discoveredResource.getDescription(),
"resource-description-v1");
+
allowing(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(inv.mergeInventoryReport(requiredInventoryStatus));
}
+ });
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
+ PluginContainerTest.startConfiguredPluginContainer();
-
allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
- with(any(InventoryReport.class)));
-
will(getCurrentServerSideInventory().mergeInventoryReport(requiredInventoryStatus));
- }
- };
- }
- });
+ Set<Resource> resources = getTestingResources(inv, SINGLETON_TYPE);
- }
+ assertEquals(resources.size(), 1, "Expected single test resource but
multiple found.");
- private void upgradeTest(boolean clearInventoryDat) throws Exception {
- initialSyncAndDiscovery(InventoryStatus.COMMITTED);
+ Resource discoveredResource = resources.iterator().next();
- executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), new
AbstractTestPayload(clearInventoryDat,
- getMyExpectedTypes()) {
- public void test(Map<ResType, Set<Resource>> discoveredResources)
{
- assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1,
- "Expected single test resource but multiple found.");
+ assertEquals(discoveredResource.getResourceKey(), "resource-key-v1");
+ assertEquals(discoveredResource.getName(), "resource-name-v1");
+ assertEquals(discoveredResource.getDescription(),
"resource-description-v1");
- Resource discoveredResource =
discoveredResources.get(SINGLETON_TYPE).iterator().next();
+ return inv;
+ }
- assertEquals(discoveredResource.getResourceKey(),
"resource-key-v2");
- assertEquals(discoveredResource.getName(),
"resource-name-v2");
- assertEquals(discoveredResource.getDescription(),
"resource-description-v2");
+ @SuppressWarnings("unchecked")
+ private void upgradeTest(String key) throws Exception {
+ final FakeServerInventory serverInventory = (FakeServerInventory)
PluginContainerTest.getServerSideFake(key);
+ final ServerServices ss =
PluginContainerTest.getCurrentPluginContainerConfiguration().getServerServices();
- ResourceContainer container =
PluginContainer.getInstance().getInventoryManager()
- .getResourceContainer(discoveredResource);
- File dataDir = container.getResourceContext().getDataDirectory();
+ PluginContainerTest.getCurrentMockContext().checking(new Expectations() {
+ {
+ defineDefaultExpectations(serverInventory, this);
- File marker = new File(dataDir, "upgrade-succeeded");
+
allowing(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(serverInventory.mergeInventoryReport(InventoryStatus.COMMITTED));
- assertTrue(marker.exists(),
- "The upgrade success marker file wasn't found. This means
the upgrade didn't actually run.");
+
oneOf(ss.getDiscoveryServerService()).upgradeResources(with(any(Set.class)));
+ will(serverInventory.upgradeResources());
}
+ });
- @SuppressWarnings("unchecked")
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
+ PluginContainerTest.startConfiguredPluginContainer();
-
allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
- with(any(InventoryReport.class)));
-
will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
+ Set<Resource> discoveredResources = getTestingResources(serverInventory,
SINGLETON_TYPE);
-
oneOf(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class)));
- will(getCurrentServerSideInventory().upgradeResources());
- }
- };
- }
- });
+ assertEquals(discoveredResources.size(), 1, "Expected single test resource
but multiple found.");
+
+ Resource discoveredResource = discoveredResources.iterator().next();
+
+ assertEquals(discoveredResource.getResourceKey(), "resource-key-v2");
+ assertEquals(discoveredResource.getName(), "resource-name-v2");
+ assertEquals(discoveredResource.getDescription(),
"resource-description-v2");
+
+ ResourceContainer container =
PluginContainer.getInstance().getInventoryManager()
+ .getResourceContainer(discoveredResource);
+ File dataDir = container.getResourceContext().getDataDirectory();
+
+ File marker = new File(dataDir, "upgrade-succeeded");
+
+ assertTrue(marker.exists(),
+ "The upgrade success marker file wasn't found. This means the
upgrade didn't actually run.");
}
}
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java
index e0526a1..3035fef 100644
---
a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java
+++
b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java
@@ -19,398 +19,52 @@
package org.rhq.core.pc.upgrade;
-import static org.testng.Assert.assertTrue;
-import java.io.File;
-import java.io.IOException;
-import java.net.URL;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
import java.util.Set;
-import org.apache.commons.io.FileUtils;
import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.rhq.core.clientapi.server.bundle.BundleServerService;
-import org.rhq.core.clientapi.server.configuration.ConfigurationServerService;
-import org.rhq.core.clientapi.server.content.ContentServerService;
-import org.rhq.core.clientapi.server.core.CoreServerService;
-import org.rhq.core.clientapi.server.discovery.DiscoveryServerService;
-import org.rhq.core.clientapi.server.event.EventServerService;
-import org.rhq.core.clientapi.server.inventory.ResourceFactoryServerService;
-import org.rhq.core.clientapi.server.measurement.MeasurementServerService;
-import org.rhq.core.clientapi.server.operation.OperationServerService;
import org.rhq.core.domain.discovery.AvailabilityReport;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.resource.ResourceType;
import org.rhq.core.pc.PluginContainer;
-import org.rhq.core.pc.PluginContainerConfiguration;
import org.rhq.core.pc.ServerServices;
-import org.rhq.core.pc.inventory.InventoryManager;
-import org.rhq.core.pc.plugin.FileSystemPluginFinder;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
+import org.rhq.test.pc.PluginContainerTest;
/**
*
* @author Lukas Krejci
*/
-public abstract class ResourceUpgradeTestBase {
-
- private static final String PLUGINS_DIR_NAME = "plugins";
- private static final String DATA_DIR_NAME = "data";
- private static final String TMP_DIR_NAME = "tmp";
- private File tmpDir;
- private File pluginDir;
- private File dataDir;
- private BundleServerService currentBundleServerService;
- private ConfigurationServerService currentConfigurationServerService;
- private ContentServerService currentContentServerService;
- private CoreServerService currentCoreServerService;
- private DiscoveryServerService currentDiscoveryServerService;
- private EventServerService currentEventServerService;
- private MeasurementServerService currentMeasurementServerService;
- private OperationServerService currentOperationServerService;
- private ResourceFactoryServerService currentResourceFactoryServerService;
- private FakeServerInventory currentServerSideInventory;
-
- protected static class ResType {
- private String resourceTypeName;
- private String resourceTypePluginName;
-
- public ResType(String resourceTypeName, String resourceTypePluginName) {
- super();
- this.resourceTypeName = resourceTypeName;
- this.resourceTypePluginName = resourceTypePluginName;
- }
-
- public String getResourceTypeName() {
- return resourceTypeName;
- }
-
- public String getResourceTypePluginName() {
- return resourceTypePluginName;
- }
-
- @Override
- public int hashCode() {
- return resourceTypeName.hashCode() * resourceTypePluginName.hashCode();
- }
-
- @Override
- public boolean equals(Object other) {
- if (other == this) {
- return true;
- }
-
- if (!(other instanceof ResType)) {
- return false;
- }
-
- ResType o = (ResType)other;
-
- return resourceTypeName.equals(o.getResourceTypeName()) &&
resourceTypePluginName.equals(o.getResourceTypePluginName());
- }
-
- @Override
- public String toString() {
- return "ResType[name='" + resourceTypeName + "',
plugin='" + resourceTypePluginName + "']";
- }
- }
-
- protected interface TestPayload {
- Expectations getExpectations(Mockery context) throws Exception;
-
- void test(Map<ResType,Set<Resource>> resourceUpgradeTestResources);
-
- boolean isClearInventoryDat();
-
- Set<ResType> getExpectedResourceTypes();
- }
-
- protected static abstract class AbstractTestPayload implements TestPayload {
- private boolean clearInventoryDat;
- private Set<ResType> resourceTypes;
-
- public AbstractTestPayload(boolean clearInventoryDat, Collection<ResType>
resourceTypes) {
- this.clearInventoryDat = clearInventoryDat;
- this.resourceTypes = new HashSet<ResType>(resourceTypes);
- }
-
- public boolean isClearInventoryDat() {
- return clearInventoryDat;
- }
-
- public Set<ResType> getExpectedResourceTypes() {
- return resourceTypes;
- }
- }
-
- @BeforeClass
- public void init() {
- tmpDir = getTmpDirectory();
- pluginDir = new File(tmpDir, PLUGINS_DIR_NAME);
- assertTrue(pluginDir.mkdir(), "Could not create plugin deploy
directory.");
- dataDir = new File(tmpDir, DATA_DIR_NAME);
- assertTrue(dataDir.mkdir(), "Could not create plugin container data
directory.");
- }
-
- @BeforeClass
- public void verifyPluginsExist() {
- for (String plugin : getRequiredPlugins()) {
- verifyPluginExists(plugin);
- }
- }
-
- @AfterClass
- public void undeployPlugins() throws IOException {
- FileUtils.deleteDirectory(tmpDir);
- }
-
- protected abstract Collection<String> getRequiredPlugins();
-
- protected void setCurrentServerSideInventory(FakeServerInventory
currentServerSideInventory) {
- this.currentServerSideInventory = currentServerSideInventory;
- }
-
- protected FakeServerInventory getCurrentServerSideInventory() {
- return currentServerSideInventory;
- }
-
- protected void setCurrentResourceFactoryServerService(
- ResourceFactoryServerService currentResourceFactoryServerService) {
- this.currentResourceFactoryServerService = currentResourceFactoryServerService;
- }
-
- protected ResourceFactoryServerService getCurrentResourceFactoryServerService() {
- return currentResourceFactoryServerService;
- }
-
- protected void setCurrentOperationServerService(OperationServerService
currentOperationServerService) {
- this.currentOperationServerService = currentOperationServerService;
- }
-
- protected OperationServerService getCurrentOperationServerService() {
- return currentOperationServerService;
- }
-
- protected void setCurrentMeasurementServerService(MeasurementServerService
currentMeasurementServerService) {
- this.currentMeasurementServerService = currentMeasurementServerService;
- }
-
- protected MeasurementServerService getCurrentMeasurementServerService() {
- return currentMeasurementServerService;
- }
-
- protected void setCurrentEventServerService(EventServerService
currentEventServerService) {
- this.currentEventServerService = currentEventServerService;
- }
-
- protected EventServerService getCurrentEventServerService() {
- return currentEventServerService;
- }
-
- protected void setCurrentDiscoveryServerService(DiscoveryServerService
currentDiscoveryServerService) {
- this.currentDiscoveryServerService = currentDiscoveryServerService;
- }
-
- protected DiscoveryServerService getCurrentDiscoveryServerService() {
- return currentDiscoveryServerService;
- }
-
- protected void setCurrentCoreServerService(CoreServerService
currentCoreServerService) {
- this.currentCoreServerService = currentCoreServerService;
- }
-
- protected CoreServerService getCurrentCoreServerService() {
- return currentCoreServerService;
- }
-
- protected void setCurrentContentServerService(ContentServerService
currentContentServerService) {
- this.currentContentServerService = currentContentServerService;
- }
-
- protected ContentServerService getCurrentContentServerService() {
- return currentContentServerService;
- }
-
- protected void setCurrentConfigurationServerService(ConfigurationServerService
currentConfigurationServerService) {
- this.currentConfigurationServerService = currentConfigurationServerService;
- }
-
- protected ConfigurationServerService getCurrentConfigurationServerService() {
- return currentConfigurationServerService;
- }
-
- protected void setCurrentBundleServerService(BundleServerService
currentBundleServerService) {
- this.currentBundleServerService = currentBundleServerService;
- }
-
- protected BundleServerService getCurrentBundleServerService() {
- return currentBundleServerService;
- }
-
- protected static File getTmpDirectory() {
- File ret = new File(System.getProperty("java.io.tmpdir"),
"resource-upgrade-test" + System.currentTimeMillis());
-
- while (ret.exists() || !ret.mkdir()) {
- ret = new File(System.getProperty("java.io.tmpdir"),
"resource-upgrade-test" + System.currentTimeMillis());
- }
-
- return ret;
- }
-
- private PluginContainerConfiguration createPluginContainerConfiguration(Mockery
context) throws Exception {
- PluginContainerConfiguration conf = new PluginContainerConfiguration();
-
- conf.setPluginDirectory(new File(tmpDir, PLUGINS_DIR_NAME));
- conf.setDataDirectory(new File(tmpDir, DATA_DIR_NAME));
- conf.setTemporaryDirectory(new File(tmpDir, TMP_DIR_NAME));
- conf.setInsideAgent(true); //pc must think it's inside an agent so that it
persists the inventory between restarts
- conf.setPluginFinder(new FileSystemPluginFinder(conf.getPluginDirectory()));
- conf.setCreateResourceClassloaders(false);
-
- //we're not interested in any scans happening out of our control
- conf.setAvailabilityScanInitialDelay(Long.MAX_VALUE);
- conf.setConfigurationDiscoveryInitialDelay(Long.MAX_VALUE);
- conf.setContentDiscoveryInitialDelay(Long.MAX_VALUE);
- conf.setEventSenderInitialDelay(Long.MAX_VALUE);
- conf.setMeasurementCollectionInitialDelay(Long.MAX_VALUE);
- conf.setServerDiscoveryInitialDelay(Long.MAX_VALUE);
- conf.setServiceDiscoveryInitialDelay(Long.MAX_VALUE);
-
- setCurrentBundleServerService(context.mock(BundleServerService.class));
-
setCurrentConfigurationServerService(context.mock(ConfigurationServerService.class));
- setCurrentContentServerService(context.mock(ContentServerService.class));
- setCurrentCoreServerService(context.mock(CoreServerService.class));
- setCurrentDiscoveryServerService(context.mock(DiscoveryServerService.class));
- setCurrentEventServerService(context.mock(EventServerService.class));
-
setCurrentMeasurementServerService(context.mock(MeasurementServerService.class));
- setCurrentOperationServerService(context.mock(OperationServerService.class));
-
setCurrentResourceFactoryServerService(context.mock(ResourceFactoryServerService.class));
-
- ServerServices serverServices = new ServerServices();
- serverServices.setBundleServerService(getCurrentBundleServerService());
-
serverServices.setConfigurationServerService(getCurrentConfigurationServerService());
- serverServices.setContentServerService(getCurrentContentServerService());
- serverServices.setCoreServerService(getCurrentCoreServerService());
- serverServices.setDiscoveryServerService(getCurrentDiscoveryServerService());
- serverServices.setEventServerService(getCurrentEventServerService());
-
serverServices.setMeasurementServerService(getCurrentMeasurementServerService());
- serverServices.setOperationServerService(getCurrentOperationServerService());
-
serverServices.setResourceFactoryServerService(getCurrentResourceFactoryServerService());
-
- conf.setServerServices(serverServices);
-
- return conf;
- }
-
- /**
- * @param pluginResourcePath
- */
- protected void verifyPluginExists(String pluginResourcePath) {
- URL url = getClass().getResource(pluginResourcePath);
-
- File pluginFile = FileUtils.toFile(url);
-
- assert pluginFile!=null : "pluginFile was null";
- assertTrue(pluginFile.exists(), pluginFile.getAbsoluteFile() + " plugin jar
could not be found.");
- }
-
- private void copyPlugin(String pluginResourcePath, File pluginDirectory) throws
IOException {
- URL pluginUrl = getClass().getResource(pluginResourcePath);
-
- File pluginFile = new File(pluginResourcePath);
- String pluginFileName = pluginFile.getName();
-
- FileUtils.copyURLToFile(pluginUrl, new File(pluginDirectory, pluginFileName));
- }
-
- private Set<Resource> getTestingResources(String resourceTypeName, String
resourceTypePluginName) {
- ResourceType resType =
PluginContainer.getInstance().getPluginManager().getMetadataManager()
- .getType(resourceTypeName, resourceTypePluginName);
-
- return getCurrentServerSideInventory().findResourcesByType(resType);
- }
-
- protected void executeTestWithPlugins(Set<String> pluginResourcePaths,
TestPayload test) throws Exception {
- FileUtils.cleanDirectory(new File(tmpDir, PLUGINS_DIR_NAME));
-
- for (String pluginResourcePath : pluginResourcePaths) {
- copyPlugin(pluginResourcePath, pluginDir);
- }
-
- Mockery context = new Mockery();
-
- PluginContainerConfiguration pcConfig =
createPluginContainerConfiguration(context);
-
- if (test.isClearInventoryDat()) {
- File inventoryDat = new File(pcConfig.getDataDirectory(),
"inventory.dat");
- inventoryDat.delete();
- }
-
- context.checking(test.getExpectations(context));
-
- PluginContainer.getInstance().setConfiguration(pcConfig);
- PluginContainer.getInstance().initialize();
-
- try {
- //give the pc the time to finish resource upgrade
- while (!PluginContainer.getInstance().isStarted()) {
- Thread.sleep(500);
- }
-
- //execute full discovery
- InventoryManager im = PluginContainer.getInstance().getInventoryManager();
- im.executeServerScanImmediately();
-
- //do the service scan a couple of times so that we can commit
- //the resources deep in the type hierarchy
- for(int i = 0; i < 10; ++i) {
- im.executeServiceScanImmediately();
- }
-
- Map<ResType, Set<Resource>> resources = new HashMap<ResType,
Set<Resource>>();
-
- for(ResType type : test.getExpectedResourceTypes()) {
- Set<Resource> rs = getTestingResources(type.getResourceTypeName(),
type.getResourceTypePluginName());
- resources.put(type, rs);
- }
-
- test.test(resources);
-
- context.assertIsSatisfied();
- } finally {
- PluginContainer.getInstance().shutdown();
- }
- }
+public abstract class ResourceUpgradeTestBase extends PluginContainerTest {
@SuppressWarnings("unchecked")
- protected void defineDefaultExpectations(Expectations expectations) {
- expectations.ignoring(getCurrentBundleServerService());
- expectations.ignoring(getCurrentConfigurationServerService());
- expectations.ignoring(getCurrentContentServerService());
- expectations.ignoring(getCurrentCoreServerService());
- expectations.ignoring(getCurrentEventServerService());
- expectations.ignoring(getCurrentMeasurementServerService());
- expectations.ignoring(getCurrentOperationServerService());
- expectations.ignoring(getCurrentResourceFactoryServerService());
+ protected void defineDefaultExpectations(FakeServerInventory inventory, Expectations
expectations) {
+ ServerServices ss = pluginContainerConfiguration.getServerServices();
+
+ expectations.ignoring(ss.getBundleServerService());
+ expectations.ignoring(ss.getConfigurationServerService());
+ expectations.ignoring(ss.getContentServerService());
+ expectations.ignoring(ss.getCoreServerService());
+ expectations.ignoring(ss.getEventServerService());
+ expectations.ignoring(ss.getMeasurementServerService());
+ expectations.ignoring(ss.getOperationServerService());
+ expectations.ignoring(ss.getResourceFactoryServerService());
//just ignore these invocations if we get a availability scan in the PC...
-
expectations.allowing(getCurrentDiscoveryServerService()).mergeAvailabilityReport(
+ expectations.allowing(ss.getDiscoveryServerService()).mergeAvailabilityReport(
expectations.with(Expectations.any(AvailabilityReport.class)));
- expectations.allowing(getCurrentDiscoveryServerService()).getResources(
+ expectations.allowing(ss.getDiscoveryServerService()).getResources(
expectations.with(Expectations.any(Set.class)),
expectations.with(Expectations.any(boolean.class)));
- expectations.will(getCurrentServerSideInventory().getResources());
+ expectations.will(inventory.getResources());
-
expectations.allowing(getCurrentDiscoveryServerService()).postProcessNewlyCommittedResources(
+
expectations.allowing(ss.getDiscoveryServerService()).postProcessNewlyCommittedResources(
expectations.with(Expectations.any(Set.class)));
}
- protected void cleanDataDir() throws IOException {
- FileUtils.cleanDirectory(new File(tmpDir, DATA_DIR_NAME));
+ protected Set<Resource> getTestingResources(FakeServerInventory
serverInventory, ResType type) {
+ ResourceType resType =
PluginContainer.getInstance().getPluginManager().getMetadataManager()
+ .getType(type.getResourceTypeName(), type.getResourceTypePluginName());
+
+ return serverInventory.findResourcesByType(resType);
}
}
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerSetup.java
b/modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerSetup.java
new file mode 100644
index 0000000..a6baff0
--- /dev/null
+++
b/modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerSetup.java
@@ -0,0 +1,118 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2011 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+package org.rhq.test.pc;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import org.rhq.core.pc.ServerServices;
+
+/**
+ * This annotation represents the setup of the plugin container to be
+ * performed before each test.
+ * @author Lukas Krejci
+ */
+(a)Retention(RetentionPolicy.RUNTIME)
+(a)Target({ElementType.METHOD, ElementType.TYPE})
+public @interface PluginContainerSetup {
+
+ /**
+ * The list of plugin URIs that should be loaded into the plugin container.
+ * The "classpath" scheme can be used in the URI to specify that the
plugin
+ * is stored in the classpath of the test being executed. Other schemes are
+ * resolved as usual.
+ * <p>
+ * Examples of URIs:
+ * <ul>
+ * <li> classpath:///test-plugin.jar
+ * <li> file:///some/location/on/the/filesystem.jar
+ * <li>
http://www.rhq-project.org/tests/test-plugin.jar
+ */
+ String[] plugins();
+
+ /**
+ * If specified, the plugin container setups with the same shared group will
+ * be invoked with the same directory layout for storing inventory, data and plugin
+ * files.
+ * <p>
+ * This enables the persistent data to survive among different plugin container
+ * runs which is useful for example to test plugin upgrades. We need to test for
different
+ * things in each plugin container run, we need to deploy different plugins to the
+ * plugin container, yet we usually want the persisted inventory to survive.
+ * <p>
+ * By default each test creates a new directory layout.
+ */
+ String sharedGroup() default "";
+
+ /**
+ * Whether the plugin container should be started and initialized before
+ * the control is handed over to the test method.
+ * <p>
+ * Default is false.
+ */
+ boolean startImmediately() default false;
+
+ /**
+ * If the plugin container is {@link #inAgent()}, it persists the state of
+ * the inventory in a 'inventory.dat' file.
+ * <p>
+ * Because the plugin container test can start up the PC using the same
+ * directories to use (using the {@link #sharedGroup()} grouping), the persisted
+ * inventory can be shared between multiple tests.
+ * <p>
+ * The default value is true.
+ */
+ boolean clearInventoryDat() default true;
+
+ /**
+ * Whether to clear the data directory of the plugin container
+ */
+ boolean clearDataDir() default false;
+
+ /**
+ * The number of server and service discoveries executed before the control
+ * is handed over to the test method. This is useful if you have deep hierarchies
+ * of server resources that only get committed a level at a time.
+ * <p>
+ * If set to 0, no discoveries will be performed.
+ * <p>
+ * The default value is 1.
+ */
+ int numberOfInitialDiscoveries() default 1;
+
+ /**
+ * Should the plugin container be set to think it runs inside an agent?
+ * <p>
+ * The default is true.
+ */
+ boolean inAgent() default true;
+
+ /**
+ * By default the PluginContainerTest
+ * By default the {@link ServerServices} the plugin container will be initialized
with
+ * will contain the mocked out interfaces of the individual services.
+ * <p>
+ * If you need to provide custom implementations, you can tell the setup
+ * to use the instance returned by the method named using this attribute.
+ */
+ String pluginConfigurationProviderMethod() default "";
+}
diff --git
a/modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerTest.java
b/modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerTest.java
new file mode 100644
index 0000000..7e91ede
--- /dev/null
+++
b/modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerTest.java
@@ -0,0 +1,397 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2011 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+package org.rhq.test.pc;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.URI;
+import java.net.URL;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.io.FileUtils;
+import org.jmock.Mockery;
+import org.testng.ITestResult;
+import org.testng.annotations.AfterSuite;
+import org.testng.annotations.Listeners;
+
+import org.rhq.core.clientapi.server.bundle.BundleServerService;
+import org.rhq.core.clientapi.server.configuration.ConfigurationServerService;
+import org.rhq.core.clientapi.server.content.ContentServerService;
+import org.rhq.core.clientapi.server.core.CoreServerService;
+import org.rhq.core.clientapi.server.discovery.DiscoveryServerService;
+import org.rhq.core.clientapi.server.event.EventServerService;
+import org.rhq.core.clientapi.server.inventory.ResourceFactoryServerService;
+import org.rhq.core.clientapi.server.measurement.MeasurementServerService;
+import org.rhq.core.clientapi.server.operation.OperationServerService;
+import org.rhq.core.pc.PluginContainer;
+import org.rhq.core.pc.PluginContainerConfiguration;
+import org.rhq.core.pc.ServerServices;
+import org.rhq.core.pc.inventory.InventoryManager;
+import org.rhq.core.pc.plugin.FileSystemPluginFinder;
+import org.rhq.test.JMockTest;
+
+/**
+ * This class is similar to {@link JMockTest} in that it can be used both
+ * as a base class to your test or as a TestNG {@link Listeners listener}
+ * on your test class.
+ * <p>
+ * This class is used to declaratively setup a plugin container a test wants
+ * to use using the {@link PluginContainerSetup} annotation on a test method or class.
+ *
+ * @author Lukas Krejci
+ */
+public class PluginContainerTest extends JMockTest {
+ private static final File ROOT;
+ private static boolean cleanedUp = false;
+
+ private static final String PLUGINS_DIR_NAME = "plugins";
+
+ private static final String DATA_DIR_NAME = "data";
+ private static final String TMP_DIR_NAME = "tmp";
+
+ private static final ThreadLocal<PluginContainerConfiguration>
STATICALLY_ACCESSIBLE_PLUGIN_CONTAINER_CONFIGURATION = new
ThreadLocal<PluginContainerConfiguration>();
+
+ private static final ThreadLocal<PluginContainerSetup> CURRENT_SETUP = new
ThreadLocal<PluginContainerSetup>();
+
+ private static final Map<String, Object> SERVERSIDE_FAKES =
Collections.synchronizedMap(new HashMap<String, Object>());
+
+ protected PluginContainerConfiguration pluginContainerConfiguration;
+
+ static {
+ File f = new File(System.getProperty("java.io.tmpdir"),
"plugin-container-test-" + System.currentTimeMillis());
+ while (f.exists() || !f.mkdir()) {
+ f = new File(System.getProperty("java.io.tmpdir"),
"plugin-container-test-" + System.currentTimeMillis());
+ }
+
+ ROOT = f;
+ }
+
+ /**
+ * During the tests, one might need to "fake" responses that come to the
plugin container
+ * from external sources, like RHQ server. These are usually mocked out using the
facilities
+ * provided by JMock.
+ * <p>
+ * This method together with {@link #setServerSideFake(String, Object)} provides a
generic
+ * "storage" for tests to share these objects and is only provided as a
convenience to
+ * the test writers. There's nothing that would manadate using it.
+ *
+ * @param name
+ * @return
+ */
+ public static Object getServerSideFake(String name) {
+ return SERVERSIDE_FAKES.get(name);
+ }
+
+ /**
+ * The opposite of {@link #getServerSideFake(String)}.
+ */
+ public static void setServerSideFake(String name, Object object) {
+ SERVERSIDE_FAKES.put(name, object);
+ }
+
+ /**
+ * Returns the {@link PluginContainerConfiguration} as configured using
+ * the {@link PluginContainerSetup} annotation on the current test (or null
+ * if no such thing is configured).
+ * @return
+ */
+ public static PluginContainerConfiguration getCurrentPluginContainerConfiguration()
{
+ return STATICALLY_ACCESSIBLE_PLUGIN_CONTAINER_CONFIGURATION.get();
+ }
+
+ @Override
+ protected void initBeforeTest(Object testObject, Method testMethod) {
+ super.initBeforeTest(testObject, testMethod);
+
+ CURRENT_SETUP.set(getSetup(testMethod));
+
+ if (CURRENT_SETUP.get() != null) {
+ try {
+ initPluginContainerConfiguration(testObject, testMethod);
+ initDirectoryStructure();
+ deployPlugins(testObject,
pluginContainerConfiguration.getPluginDirectory(), CURRENT_SETUP.get());
+
+
PluginContainer.getInstance().setConfiguration(pluginContainerConfiguration);
+
+ if (CURRENT_SETUP.get().clearInventoryDat()) {
+ File inventoryDat = new
File(pluginContainerConfiguration.getDataDirectory(), "inventory.dat");
+ inventoryDat.delete();
+ }
+
+ if (CURRENT_SETUP.get().startImmediately()) {
+ startConfiguredPluginContainer();
+ }
+ } catch (Throwable t) {
+ throw new IllegalStateException("Failed to setup the plugin
container.", t);
+ }
+ }
+ }
+
+ @Override
+ protected void tearDownAfterTest(ITestResult testResult) {
+ try {
+ deletePlugins(pluginContainerConfiguration.getPluginDirectory());
+ } catch (Exception e) {
+ //hmmm
+ } finally {
+ PluginContainer.getInstance().shutdown();
+ super.tearDownAfterTest(testResult);
+ }
+ }
+
+ /**
+ * Starts the plugin container. This method is supposed to be called from tests that
+ * need to start the plugin container manually after it has been configured using
+ * the {@link PluginContainerSetup} annotation.
+ */
+ public static void startConfiguredPluginContainer() {
+
PluginContainer.getInstance().setConfiguration(getCurrentPluginContainerConfiguration());
+
+ PluginContainer.getInstance().initialize();
+
+ try {
+ while (!PluginContainer.getInstance().isStarted()) {
+ Thread.sleep(100);
+ }
+ } catch (InterruptedException e) {
+ throw new IllegalStateException("Thread interrupted while waiting for
plugin container to start.");
+ }
+
+ InventoryManager im = PluginContainer.getInstance().getInventoryManager();
+ for (int i = 0; i < CURRENT_SETUP.get().numberOfInitialDiscoveries(); ++i) {
+ im.executeServerScanImmediately();
+ im.executeServiceScanImmediately();
+ }
+ }
+
+ /**
+ * This method can be called in the after methods of the tests to clear up data
+ * left after the plugin container run.
+ * <p>
+ * This is not done automatically to support sharing the plugin container among
+ * multiple tests to simulate upgrades, etc.
+ *
+ * @throws IOException
+ */
+ public static void clearStorageOfCurrentPluginContainer() throws IOException {
+ File f =
STATICALLY_ACCESSIBLE_PLUGIN_CONTAINER_CONFIGURATION.get().getPluginDirectory();
+ f = f.getParentFile();
+
+ if (f.exists()) {
+ FileUtils.cleanDirectory(f);
+
+ f.delete();
+ }
+ }
+
+ /**
+ * This method clears the storage of all tests made. This is useful in {@link
AfterSuite}
+ * method to clean up after all the tests (annotated with {@link
PluginContainerSetup})
+ * that have been run.
+ *
+ * @throws IOException
+ */
+ public synchronized static void clearStorage() throws IOException {
+ if (!cleanedUp) {
+ FileUtils.cleanDirectory(ROOT);
+ ROOT.delete();
+ cleanedUp = true;
+ }
+ }
+
+ /**
+ * If PluginContainerTest is used as a base class to your tests (and not as a {@link
Listeners listener},
+ * this method is provided to automatically clean up after all the plugin container
tests that ran
+ * in the test suite.
+ * <p>
+ * If you use PluginContainerTest as a listener, you have to call {@link
#clearStorage()} method
+ * on your own.
+ *
+ * @throws IOException
+ */
+ @AfterSuite
+ public void cleanUpAfterPluginContainerTests() throws IOException {
+ clearStorage();
+ }
+
+ /**
+ * This method returns the {@link PluginContainerConfiguration} that will be used in
+ * the current test as was configured by the PluginContainerSetup annotation.
+ * <p>
+ * If your test class inherits from PluginContainerTest, you can override this method
+ * to provide custom configuration.
+ *
+ * @param testObject the object of the current test
+ * @param testMethod the test method currently being executed on the test object
+ * @return
+ */
+ protected PluginContainerConfiguration createPluginConfigurationToUse(Object
testObject, Method testMethod) {
+ PluginContainerSetup setup = CURRENT_SETUP.get();
+
+ if (setup.pluginConfigurationProviderMethod().isEmpty()) {
+ return createDefaultPluginConfiguration(setup, context);
+ } else {
+ String providerName = setup.pluginConfigurationProviderMethod();
+ Class<?> testClass = testMethod.getDeclaringClass();
+ try {
+ Method pluginContainerProvider = testClass.getMethod(providerName,
(Class<?>[]) null);
+
+ if
(!PluginContainerConfiguration.class.isAssignableFrom(pluginContainerProvider.getReturnType()))
{
+ throw new IllegalStateException("The configured
pluginConfigurationProviderMethod '" + providerName + "' on the test
class '" + testClass + "' does not return a
PluginContainerConfiguration.");
+ }
+
+ return (PluginContainerConfiguration)
pluginContainerProvider.invoke(testObject, (Object[]) null);
+ } catch (SecurityException e) {
+ throw new IllegalStateException("The configured
pluginConfigurationProviderMethod '" + providerName + "' could not be
found on the test class '" + testClass + "'.", e);
+ } catch (NoSuchMethodException e) {
+ throw new IllegalStateException("The configured
pluginConfigurationProviderMethod '" + providerName + "' could not be
found on the test class '" + testClass + "'.", e);
+ } catch (IllegalAccessException e) {
+ throw new IllegalStateException("Failed to invoke method '"
+ providerName + "' on test class '" + testClass + "'.",
e);
+ } catch (InvocationTargetException e) {
+ throw new IllegalStateException("Failed to invoke method '"
+ providerName + "' on test class '" + testClass + "'.",
e);
+ }
+ }
+ }
+
+ /**
+ * This method is called after the test to tear down resources associated with the
+ * current plugin container configuration.
+ */
+ protected void tearDownPluginContainerConfiguration() {
+ pluginContainerConfiguration = null;
+ STATICALLY_ACCESSIBLE_PLUGIN_CONTAINER_CONFIGURATION.set(null);
+ }
+
+ private void initPluginContainerConfiguration(Object testObject, Method testMethod)
{
+ pluginContainerConfiguration = createPluginConfigurationToUse(testObject,
testMethod);
+
STATICALLY_ACCESSIBLE_PLUGIN_CONTAINER_CONFIGURATION.set(pluginContainerConfiguration);
+ }
+
+ private static PluginContainerSetup getSetup(Method method) {
+ PluginContainerSetup setup = method.getAnnotation(PluginContainerSetup.class);
+
+ if (setup == null) {
+ setup =
method.getDeclaringClass().getAnnotation(PluginContainerSetup.class);
+ }
+
+ return setup;
+ }
+
+ private void initDirectoryStructure() {
+ File pluginDir = pluginContainerConfiguration.getPluginDirectory();
+ File dataDir = pluginContainerConfiguration.getDataDirectory();
+ File tempDir = pluginContainerConfiguration.getTemporaryDirectory();
+
+ pluginDir.mkdirs();
+ dataDir.mkdirs();
+ tempDir.mkdirs();
+ }
+
+ private static PluginContainerConfiguration
createDefaultPluginConfiguration(PluginContainerSetup setup, Mockery context) {
+ PluginContainerConfiguration conf = new PluginContainerConfiguration();
+
+ File tmpDir = createTemporaryDirectory(setup);
+
+ conf.setPluginDirectory(new File(tmpDir, PLUGINS_DIR_NAME));
+ conf.setDataDirectory(new File(tmpDir, DATA_DIR_NAME));
+ conf.setTemporaryDirectory(new File(tmpDir, TMP_DIR_NAME));
+ conf.setInsideAgent(setup.inAgent());
+ conf.setPluginFinder(new FileSystemPluginFinder(conf.getPluginDirectory()));
+ conf.setCreateResourceClassloaders(false);
+
+ //we're not interested in any scans happening out of our control
+ conf.setAvailabilityScanInitialDelay(Long.MAX_VALUE);
+ conf.setConfigurationDiscoveryInitialDelay(Long.MAX_VALUE);
+ conf.setContentDiscoveryInitialDelay(Long.MAX_VALUE);
+ conf.setEventSenderInitialDelay(Long.MAX_VALUE);
+ conf.setMeasurementCollectionInitialDelay(Long.MAX_VALUE);
+ conf.setServerDiscoveryInitialDelay(Long.MAX_VALUE);
+ conf.setServiceDiscoveryInitialDelay(Long.MAX_VALUE);
+
+ ServerServices serverServices = new ServerServices();
+ serverServices.setBundleServerService(context.mock(BundleServerService.class));
+
serverServices.setConfigurationServerService(context.mock(ConfigurationServerService.class));
+
serverServices.setContentServerService(context.mock(ContentServerService.class));
+ serverServices.setCoreServerService(context.mock(CoreServerService.class));
+
serverServices.setDiscoveryServerService(context.mock(DiscoveryServerService.class));
+ serverServices.setEventServerService(context.mock(EventServerService.class));
+
serverServices.setMeasurementServerService(context.mock(MeasurementServerService.class));
+
serverServices.setOperationServerService(context.mock(OperationServerService.class));
+
serverServices.setResourceFactoryServerService(context.mock(ResourceFactoryServerService.class));
+
+ conf.setServerServices(serverServices);
+
+ return conf;
+ }
+
+ private void deployPlugins(Object testObject, File destination, PluginContainerSetup
setup) throws IOException {
+ for(String plugin : setup.plugins()) {
+ copyPluginToDestination(testObject, plugin, destination);
+ }
+ }
+
+ private void deletePlugins(File deployDirectory) throws IOException {
+ if (deployDirectory.exists()) {
+ FileUtils.cleanDirectory(deployDirectory);
+ }
+ }
+
+ private static File createTemporaryDirectory(PluginContainerSetup setup) {
+ String name = null;
+ boolean mustBeNew = true;
+ if (setup.sharedGroup().length() > 0) {
+ name = setup.sharedGroup();
+ mustBeNew = false;
+ } else {
+ name = Long.toString(System.currentTimeMillis());
+ }
+
+ File ret = new File(ROOT, name);
+
+ while (mustBeNew && (ret.exists() || !ret.mkdir())) {
+ ret = new File(ROOT, Long.toString(System.currentTimeMillis()));
+ }
+
+ return ret;
+ }
+
+ private File copyPluginToDestination(Object testObject, String plugin, File
destination) throws IOException {
+ URI pluginUri = URI.create(plugin);
+ URL pluginUrl = null;
+ if ("classpath".equals(pluginUri.getScheme())) {
+ String path = pluginUri.getPath();
+ pluginUrl = testObject.getClass().getResource(path);
+ } else {
+ pluginUrl = pluginUri.toURL();
+ }
+
+
+ String pluginFileName =
pluginUri.getPath().substring(pluginUri.getPath().lastIndexOf('/') + 1);
+
+ File pluginJar = new File(destination, pluginFileName);
+ FileUtils.copyURLToFile(pluginUrl, pluginJar);
+
+ return pluginJar;
+ }
+}
diff --git a/modules/plugins/pom.xml b/modules/plugins/pom.xml
index f51a2ed..d1863d4 100644
--- a/modules/plugins/pom.xml
+++ b/modules/plugins/pom.xml
@@ -55,6 +55,21 @@
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>${rhq.groupId}</groupId>
+ <artifactId>rhq-core-plugin-container</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>${rhq.groupId}</groupId>
+ <artifactId>test-utils</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+
<!--
TODO: This is a fix for the Javac bug requiring annotations to be available when
compiling dependent classes.
It is fixed in JDK 6.
diff --git a/modules/test-utils/pom.xml b/modules/test-utils/pom.xml
index 89fbc3c..3ed6856 100644
--- a/modules/test-utils/pom.xml
+++ b/modules/test-utils/pom.xml
@@ -75,7 +75,13 @@
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-testng</artifactId>
- <version>3.1</version>
+ <version>3.1</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.testng</groupId>
+ <artifactId>testng</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
diff --git a/modules/test-utils/src/main/java/org/rhq/test/JMockTest.java
b/modules/test-utils/src/main/java/org/rhq/test/JMockTest.java
index f3add4e..2088460 100644
--- a/modules/test-utils/src/main/java/org/rhq/test/JMockTest.java
+++ b/modules/test-utils/src/main/java/org/rhq/test/JMockTest.java
@@ -23,29 +23,145 @@
package org.rhq.test;
+import java.lang.reflect.Method;
+
import org.jmock.Mockery;
import org.testng.IHookCallBack;
import org.testng.IHookable;
+import org.testng.IInvokedMethod;
+import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
+import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Listeners;
-public class JMockTest implements IHookable {
+/**
+ * This class can either be used as a base class for tests using JMock
+ * or it also can be used as a TestNG listener to provide the JMock
+ * context to test classes that need to inherit from another class.
+ * <p>
+ * In the former case, the JMock context is accessible through the {@link #context}
protected
+ * field, while in the latter case (when JMockTest is specified as a {@link Listeners
listener}
+ * of a test class), the JMock context is accessible using the {@link
#getCurrentMockContext()}
+ * static method.
+ *
+ * @author John Sanda
+ * @author Lukas Krejci
+ */
+public class JMockTest implements IHookable, IInvokedMethodListener {
protected Mockery context;
- @BeforeMethod
- public void initContext() {
- context = new Mockery();
+ private static final ThreadLocal<Mockery> STATICALLY_ACCESSIBLE_CONTEXT = new
ThreadLocal<Mockery>();
+
+ private boolean initRan;
+ private boolean tearDownRan;
+
+ /**
+ * @return the JMock context of the current test or null if the calling test class
doesn't have
+ * this class set as a listener or doesn't inherit from this class.
+ */
+ public static Mockery getCurrentMockContext() {
+ return STATICALLY_ACCESSIBLE_CONTEXT.get();
}
- public void run(IHookCallBack iHookCallBack, ITestResult iTestResult) {
+ @BeforeMethod
+ public void initMockContext(Method testMethod) {
+ if (!initRan) {
+ initBeforeTest(this, testMethod);
+ }
+ tearDownRan = false;
+ initRan = true;
+ }
+
+ @AfterMethod
+ public void tearDownMockContext(ITestResult testResult) {
+ if (!tearDownRan) {
+ tearDownAfterTest(testResult);
+ }
+ tearDownRan = true;
+ initRan = false;
+ }
+
+ /**
+ * This method runs {@link #initBeforeTest(ITestResult)}, followed by the actual
test,
+ * followed by {@link #tearDownAfterTest(ITestResult)}.
+ * <p>
+ * If you want to modify the behavior of this method, override the above mentioned
+ * methods.
+ *
+ * @see IHookable#run(IHookCallBack, ITestResult)
+ */
+ public final void run(IHookCallBack iHookCallBack, ITestResult iTestResult) {
iHookCallBack.runTestMethod(iTestResult);
+ }
+
+ /**
+ * Runs {@link #initBeforeTest(ITestResult)}.
+ *
+ * @see IInvokedMethodListener#beforeInvocation(IInvokedMethod, ITestResult)
+ */
+ public final void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
+ if (!initRan) {
+ initBeforeTest(testResult.getInstance(),
testResult.getMethod().getMethod());
+ }
+ initRan = true;
+ tearDownRan = false;
+ }
+
+ /**
+ * Runs {@link #tearDownAfterTest(ITestResult)}.
+ *
+ * @see IInvokedMethodListener#afterInvocation(IInvokedMethod, ITestResult)
+ */
+ public final void afterInvocation(IInvokedMethod method, ITestResult testResult) {
+ if (!tearDownRan) {
+ tearDownAfterTest(testResult);
+ }
+ initRan = false;
+ tearDownRan = true;
+ }
+
+ /**
+ * Does whatever needs done before the test is invoked.
+ * <p>
+ * If you override this method, be sure to call this method
<b>before</b>
+ * your code so that you gain access to the {@link #context}.
+ *
+ * @param testResult
+ */
+ protected void initBeforeTest(Object testObject, Method testMethod) {
+ initContext();
+ }
+
+ /**
+ * Does whatever needs done after the test has been invoked.
+ * <p>
+ * This method calls {@link Mockery#assertIsSatisfied()} and nulls out the {@link
#context}.
+ * <p>
+ * If you override this method, call this implmentation as the last call in your
code.
+ * @param result
+ */
+ protected void tearDownAfterTest(ITestResult result) {
try {
context.assertIsSatisfied();
+ } catch (Throwable t) {
+ result.setStatus(ITestResult.FAILURE);
+ result.setThrowable(t);
+ } finally {
+ tearDownContext();
}
- catch (Throwable t) {
- iTestResult.setStatus(ITestResult.FAILURE);
- iTestResult.setThrowable(t);
- }
+ }
+
+ private void initContext() {
+ context = new Mockery();
+ STATICALLY_ACCESSIBLE_CONTEXT.set(context);
+ }
+
+ private void tearDownContext() {
+ context = null;
+ //null out the static field so that the GC can
+ //collect the no-longer used context.
+ STATICALLY_ACCESSIBLE_CONTEXT.set(null);
}
}