Search in sources :

Example 61 with TestDefinition

use of com.github.redhatqe.polarize.metadata.TestDefinition in project rhsm-qe by RedHatQE.

the class TemporaryPoolTests method testAvailabilityOfUnmappedGuestsOnlySubpool.

// Test methods ***********************************************************************
@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20093", "RHEL7-51735" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier1")
@Test(description = "given an available unmapped_guests_only pool, assert that it is available only to virtual systems whose host consumer has not yet mapped its virt.uuid as a guestId onto the host consumer.  Moreover, assert that once mapped, the pool is no longer available.", groups = { "Tier1Tests" }, dataProvider = "getAvailableUnmappedGuestsOnlySubscriptionPoolsData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testAvailabilityOfUnmappedGuestsOnlySubpool(Object bugzilla, SubscriptionPool unmappedGuestsOnlyPool) throws JSONException, Exception {
    // system facts were overridden in dataProvider with factsMap to fake this system as a guest
    // make sure we are freshly registered (to discard a consumer from a former data provided iteration that has mapped guests)
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, true, false, null, null, null, null);
    // verify the unmapped_guests_only pool is available for consumption
    List<SubscriptionPool> availableSubscriptionPools = clienttasks.getCurrentlyAvailableSubscriptionPools();
    Assert.assertNotNull(SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", unmappedGuestsOnlyPool.poolId, availableSubscriptionPools), "Temporary pool '" + unmappedGuestsOnlyPool.subscriptionName + "' poolId='" + unmappedGuestsOnlyPool.poolId + "' (for virtual systems whose host consumer has not yet reported this system's virt.uuid as a guest) is available for consumption.");
    // verify that it is for Virtual systems
    Assert.assertEquals(unmappedGuestsOnlyPool.machineType, "Virtual", "Temporary pools intended for unmapped guests only should indicate that it is for machine type Virtual.");
    // verify that the Subscription Type indicates it is temporary
    if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "0.9.47-1")) {
        // commit dfd7e68ae83642f77c80590439353a0d66fe2961	// Bug 1201520 - [RFE] Usability suggestions to better identify a temporary (aka 24 hour) entitlement
        String temporarySuffix = " (Temporary)";
        Assert.assertTrue(unmappedGuestsOnlyPool.subscriptionType.endsWith(temporarySuffix), "The Subscription Type for a temporary pool intended for unmapped guests only should end in suffix '" + temporarySuffix + "' (actual='" + unmappedGuestsOnlyPool.subscriptionType + "').");
    }
    // verify that the corresponding Physical pool is also available (when not physical_only)
    String parentPhysicalPoolId = getParentPoolIdCorrespondingToDerivedPoolId(sm_clientUsername, sm_clientPassword, sm_serverUrl, clienttasks.getCurrentlyRegisteredOwnerKey(), unmappedGuestsOnlyPool.poolId);
    Assert.assertNotNull(parentPhysicalPoolId, "Found parent Physical poolId corresponding to temporary unmapped guests only poolId '" + unmappedGuestsOnlyPool.poolId + "'.");
    SubscriptionPool parentPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", parentPhysicalPoolId, availableSubscriptionPools);
    if (CandlepinTasks.isPoolRestrictedToPhysicalSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, parentPhysicalPoolId)) {
        Assert.assertNull(parentPool, "Should NOT found parent pool corresponding to temporary unmapped guests only poolId '" + unmappedGuestsOnlyPool.poolId + "' among available pools since it is Physical only.");
    } else {
        Assert.assertNotNull(parentPool, "Found parent Physical pool corresponding to temporary unmapped guests only poolId '" + unmappedGuestsOnlyPool.poolId + "' among available pools.");
        Assert.assertEquals(parentPool.machineType, "Physical", "The machine type for the parent pool corresponding to temporary unmapped guests only poolId '" + unmappedGuestsOnlyPool.poolId + "'.");
    }
    // simulate the actions of virt-who my mapping the virt.uuid as a guestID onto a host consumer
    clienttasks.mapSystemAsAGuestOfItself();
    // verify that the unmapped_guests_only pool is no longer available
    Assert.assertNull(SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", unmappedGuestsOnlyPool.poolId, clienttasks.getCurrentlyAvailableSubscriptionPools()), "Temporary pool '" + unmappedGuestsOnlyPool.subscriptionName + "' poolId='" + unmappedGuestsOnlyPool.poolId + "' (for virtual systems whose host consumer has not yet reported this system's virt.uuid as a guest) is NO LONGER available for consumption after it's virt.uuid has been mapped to a consumer's guestId list.");
    // assert that we are blocked from attempt to attach the temporary pool
    // 201503191231:11.346 - FINE: ssh root@jsefler-os6.usersys.redhat.com subscription-manager subscribe --pool=8a9087e34c2f214a014c2f22a7d11ad0
    // 201503191231:16.011 - FINE: Stdout: Pool is restricted to unmapped virtual guests: '8a9087e34c2f214a014c2f22a7d11ad0'
    // 201503191231:16.014 - FINE: Stderr:
    // 201503191231:16.016 - FINE: ExitCode: 1
    SSHCommandResult result = clienttasks.subscribe_(null, null, unmappedGuestsOnlyPool.poolId, null, null, null, null, null, null, null, null, null, null);
    String expectedStdout = String.format("Pool is restricted to unmapped virtual guests: '%s'", unmappedGuestsOnlyPool.poolId);
    if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.3.1-1")) {
        // commit 0d5fefcfa8c1c2485921d2dee6633879b1e06931 Correct incorrect punctuation in user messages
        expectedStdout = String.format("Pool is restricted to unmapped virtual guests: \"%s\".", unmappedGuestsOnlyPool.poolId);
    }
    String expectedStderr = "";
    Assert.assertEquals(result.getStdout().trim(), expectedStdout, "Stdout from an attempt to attach a temporary pool to a virtual guest that has already been mapped.");
    Assert.assertEquals(result.getStderr().trim(), expectedStderr, "Stderr from an attempt to attach a temporary pool to a virtual guest that has already been mapped.");
    Assert.assertEquals(result.getExitCode(), Integer.valueOf(1), "Exit code from an attempt to attach a temporary pool to a virtual guest that has already been mapped.");
}
Also used : SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SubscriptionPool(rhsm.data.SubscriptionPool) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 62 with TestDefinition

use of com.github.redhatqe.polarize.metadata.TestDefinition in project rhsm-qe by RedHatQE.

the class TemporaryPoolTests method testAutoHealingOfAnAttachedUnmappedGuestsOnlySubpoolOnceGuestIsMapped.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-22236", "RHEL7-59321" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier1")
@Test(description = "Once a guest is mapped, while consuming a temporary pool entitlement, the entitlement should be removed and the system auto-healed at the next checkin.  Verify it.", groups = { "Tier1Tests", "blockedByBug-1198494" }, dataProvider = "getAvailableUnmappedGuestsOnlySubscriptionPoolsData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testAutoHealingOfAnAttachedUnmappedGuestsOnlySubpoolOnceGuestIsMapped(Object bugzilla, SubscriptionPool unmappedGuestsOnlyPool) throws JSONException, Exception {
    // system facts were overridden in dataProvider with factsMap to fake this system as a guest
    // make sure we are freshly registered (to discard a consumer from a former data provided iteration that has mapped guests)
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, true, null, null, null, null, null);
    // ensure that auto-healing is on
    clienttasks.autoheal(null, true, null, null, null, null, null);
    // attach the unmapped guests only pool
    clienttasks.subscribe_(null, null, unmappedGuestsOnlyPool.poolId, null, null, null, null, null, null, null, null, null, null);
    ProductSubscription consumedUnmappedGuestsOnlyProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("poolId", unmappedGuestsOnlyPool.poolId, clienttasks.getCurrentlyConsumedProductSubscriptions());
    Assert.assertNotNull(consumedUnmappedGuestsOnlyProductSubscription, "Successfully found the consumed product subscription after attaching temporary pool '" + unmappedGuestsOnlyPool.subscriptionName + "' (poolId='" + unmappedGuestsOnlyPool.poolId + "').");
    // map the guest
    clienttasks.mapSystemAsAGuestOfItself();
    // trigger a rhsmcertd checkin (either of these calls are valid - randomly choose)
    // TEMPORARY WORKAROUND FOR BUG
    // Bug 1366301 - Server error attempting a PUT to /subscription/consumers/<UUID>/certificates?lazy_regen=true returned status 404
    String bugId = "1366301";
    boolean invokeWorkaroundWhileBugIsOpen = true;
    try {
        if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
        } else {
            invokeWorkaroundWhileBugIsOpen = false;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    if (invokeWorkaroundWhileBugIsOpen && CandlepinType.hosted.equals(sm_serverType)) {
        log.warning("Skipping a random call to refresh local certificates while bug '" + bugId + "' is open.");
        // no need to pass autoheal option because it is already set true on the consumer
        clienttasks.run_rhsmcertd_worker(null);
    } else // END OF WORKAROUND
    if (getRandomListItem(Arrays.asList(true, false)))
        clienttasks.refresh(null, null, null, null);
    else
        // no need to pass autoheal option because it is already set true on the consumer
        clienttasks.run_rhsmcertd_worker(null);
    // verify that the attached temporary subscription has automatically been removed
    Assert.assertTrue(ProductSubscription.findAllInstancesWithMatchingFieldFromList("poolId", unmappedGuestsOnlyPool.poolId, clienttasks.getCurrentlyConsumedProductSubscriptions()).isEmpty(), "Now that the guest is mapped, the consumed entitlements from the temporary pool '" + unmappedGuestsOnlyPool.subscriptionName + "' (poolId='" + unmappedGuestsOnlyPool.poolId + "') have automatically been removed.");
    // assert that we have been autohealed as well as possible
    List<File> entitlementCertFileAfterMapping = clienttasks.getCurrentEntitlementCertFiles();
    clienttasks.subscribe(true, null, (String) null, null, null, null, null, null, null, null, null, null, null);
    List<File> entitlementCertFileAfterAutosubscribing = clienttasks.getCurrentEntitlementCertFiles();
    Assert.assertTrue(entitlementCertFileAfterMapping.containsAll(entitlementCertFileAfterAutosubscribing) && entitlementCertFileAfterAutosubscribing.containsAll(entitlementCertFileAfterMapping), "When the entitlement certs on the system are identical after a guest has been mapped and auto-healed and an explicit auto-subscribe is attempted, then we are confident that the guest was auto-healed at the instant the guest was mapped.)");
}
Also used : ProductSubscription(rhsm.data.ProductSubscription) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) File(java.io.File) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 63 with TestDefinition

use of com.github.redhatqe.polarize.metadata.TestDefinition in project rhsm-qe by RedHatQE.

the class ActivationKeyTests method testRegisterWithActivationKeyContainingReleaseVer.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21799", "RHEL7-51616" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "create an activation key, add a release to it, and then register with the activation key", groups = { "Tier3Tests", "blockedByBug-1062292" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRegisterWithActivationKeyContainingReleaseVer() throws JSONException, Exception {
    // generate a unique activation key name for this test
    String keyName = String.format("ActivationKey%s_WithReleaseVer", System.currentTimeMillis());
    // choose a releaseVer value
    String releaseVer = "R_1.0";
    // create a JSON object to represent the request body
    Map<String, String> mapActivationKeyRequest = new HashMap<String, String>();
    mapActivationKeyRequest.put("name", keyName);
    mapActivationKeyRequest.put("releaseVer", releaseVer);
    JSONObject jsonActivationKeyRequest = new JSONObject(mapActivationKeyRequest);
    // call the candlepin api to create an activation key
    // [root@jsefler-7 ~]# curl --stderr /dev/null --insecure --user testuser1:password --request POST --data '{"name":"ActivationKey1393948948190_WithReleaseVer","releaseVer":"R_1.0"}' --header 'accept: application/json' --header 'content-type: application/json' https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/owners/admin/activation_keys | python -m simplejson/tool
    JSONObject jsonActivationKey = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/owners/" + sm_clientOrg + "/activation_keys", jsonActivationKeyRequest.toString()));
    // jsonActivationKey = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_serverAdminUsername,sm_serverAdminPassword,sm_serverUrl,"/activation_keys/"+jsonActivationKey.getString("id")));
    // [root@jsefler-7 ~]# curl --stderr /dev/null --insecure --user admin:admin --request GET https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/activation_keys/8a9087e3448960ba01448dd50b1b2c0b | python -m simplejson/tool
    // {
    // "contentOverrides": [],
    // "created": "2014-03-04T16:02:33.371+0000",
    // "id": "8a9087e3448960ba01448dd50b1b2c0b",
    // "name": "ActivationKey1393948948190_WithReleaseVer",
    // "owner": {
    // "displayName": "Admin Owner",
    // "href": "/owners/admin",
    // "id": "8a9087e3448960ba01448960df840001",
    // "key": "admin"
    // },
    // "pools": [],
    // "releaseVer": {
    // "releaseVer": "R_1.0"
    // },
    // "updated": "2014-03-04T16:02:33.371+0000"
    // }
    // register with the activation key
    clienttasks.register(null, null, sm_clientOrg, null, null, null, null, null, null, null, keyName, null, null, null, true, null, null, null, null, null);
    // verify the current release equals the value set in the activation key
    Assert.assertEquals(clienttasks.getCurrentRelease(), releaseVer, "After registering with an activation key containing a releaseVer, the current release is properly set.");
    // POST to /activation_keys/<id>/release to set an updated releaseVer...
    /* NOT ANYMORE... Candlepin Commit d005f2e7f00546ab5c66208225e99d4db105f33e changed this behavior to use PUT /activation_keys/<id>
		releaseVer = "R_2.0";
		mapActivationKeyRequest.clear();
		mapActivationKeyRequest.put("releaseVer", releaseVer);
		jsonActivationKeyRequest = new JSONObject(mapActivationKeyRequest);
		//	[root@jsefler-7 ~]# curl --stderr /dev/null --insecure --user testuser1:password --request POST --data '{"releaseVer":"R_2.0"}' --header 'accept: application/json' --header 'content-type: application/json' https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/activation_keys/8a9087e3448960ba01448df4e5b92cdb/release
		jsonActivationKey = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/activation_keys/"+jsonActivationKey.getString("id")+"/release", jsonActivationKeyRequest.toString()));
		//	[root@jsefler-7 ~]# curl --stderr /dev/null --insecure --user admin:admin --request GET https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/activation_keys/8a9087e3448960ba01448df4e5b92cdb | python -m simplejson/tool
		//	{
		//	    "contentOverrides": [],
		//	    "created": "2014-03-04T16:37:20.953+0000",
		//	    "id": "8a9087e3448960ba01448df4e5b92cdb",
		//	    "name": "ActivationKey1393951040595_WithReleaseVer",
		//	    "owner": {
		//	        "displayName": "Admin Owner",
		//	        "href": "/owners/admin",
		//	        "id": "8a9087e3448960ba01448960df840001",
		//	        "key": "admin"
		//	    },
		//	    "pools": [],
		//	    "releaseVer": {
		//	        "releaseVer": "R_2.0"
		//	    },
		//	    "updated": "2014-03-04T16:37:52.768+0000"
		//	}
		 */
    // PUT to /activation_keys/<id> to set an updated releaseVer...
    releaseVer = "R_2.0";
    mapActivationKeyRequest.clear();
    mapActivationKeyRequest.put("releaseVer", releaseVer);
    jsonActivationKeyRequest = new JSONObject(mapActivationKeyRequest);
    // [root@jsefler-7 ~]# curl --stderr /dev/null --insecure --user testuser1:password --request PUT --data '{"releaseVer":"R_2.0"}' --header 'accept: application/json' --header 'content-type: application/json' https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/activation_keys/8a9087e3452995d301452d14c41e3858 | python -m simplejson/tool
    jsonActivationKey = new JSONObject(CandlepinTasks.putResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/activation_keys/" + jsonActivationKey.getString("id"), jsonActivationKeyRequest));
    // [root@jsefler-7 ~]# curl --stderr /dev/null --insecure --user admin:admin --request GET https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/activation_keys/8a9087e3452995d301452d14c41e3858 | python -m simplejson/tool
    // {
    // "contentOverrides": [],
    // "created": "2014-04-04T14:11:46.846+0000",
    // "id": "8a9087e3452995d301452d14c41e3858",
    // "name": "ActivationKey1396620706731_WithReleaseVer",
    // "owner": {
    // "displayName": "Admin Owner",
    // "href": "/owners/admin",
    // "id": "8a9087e3452995d30145299600ac0004",
    // "key": "admin"
    // },
    // "pools": [],
    // "releaseVer": {
    // "releaseVer": "R_2.0"
    // },
    // "serviceLevel": null,
    // "updated": "2014-04-04T14:12:12.546+0000"
    // }
    // reregister with the same activation key
    clienttasks.register(null, null, sm_clientOrg, null, null, null, null, null, null, null, keyName, null, null, null, true, null, null, null, null, null);
    // verify the current release equals the new value set in the activation key
    Assert.assertEquals(clienttasks.getCurrentRelease(), releaseVer, "After registering with an activation key containing an updated releaseVer, the current release is properly set.");
    // finally, verify that there are no contentOverrides
    if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.10.7-1")) {
        SSHCommandResult listResult = clienttasks.repo_override(true, null, (String) null, (String) null, null, null, null, null, null);
        Assert.assertEquals(listResult.getStdout().trim(), "This system does not have any content overrides applied to it.", "After registering with an activation key containing a releaseVer, but no contentOverrides, this is the subscription-manager repo-override report.");
    }
}
Also used : JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 64 with TestDefinition

use of com.github.redhatqe.polarize.metadata.TestDefinition in project rhsm-qe by RedHatQE.

the class ActivationKeyTests method testRegisterWithSequenceOfMultipleActivationKeys.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21803", "RHEL7-51620" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "create many activation keys with one added pool per key and then register with a sequence of many --activationkey parameters asserting each pool per key gets consumed", groups = { "Tier3Tests", "blockedByBug-878986", "blockedByBug-979492", "blockedByBug-1040101" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRegisterWithSequenceOfMultipleActivationKeys() throws JSONException, Exception {
    // get all of the pools belonging to ownerKey
    JSONArray jsonPools = new JSONArray(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/owners/" + sm_clientOrg + "/pools?listall=true"));
    if (!(jsonPools.length() > 1))
        throw new SkipException("This test requires more than one pool for org '" + sm_clientOrg + "'.");
    jsonPools = clienttasks.workaroundForBug1040101(jsonPools);
    // process each of the pools adding them to an individual activation key
    List<String> activationKeyNames = new ArrayList<String>();
    Integer addQuantity = null;
    JSONArray jsonPoolsAddedToActivationKey = new JSONArray();
    boolean isSystemVirtual = Boolean.valueOf(clienttasks.getFactValue("virt.is_guest"));
    for (int i = 0; i < jsonPools.length(); i++) {
        JSONObject jsonPool = (JSONObject) jsonPools.get(i);
        // for the purpose of this test, skip pools with no available entitlements (consumed>=quantity) (quantity=-1 is unlimited)
        if (jsonPool.getInt("quantity") > 0 && jsonPool.getInt("consumed") >= jsonPool.getInt("quantity"))
            continue;
        // for the purpose of this test, skip non-system pools otherwise the register will fail with "Consumers of this type are not allowed to subscribe to the pool with id '8a90f8c631ab7ccc0131ab7e46ca0619'."
        if (!CandlepinTasks.isPoolProductConsumableByConsumerType(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id"), ConsumerType.system))
            continue;
        // for the purpose of this test, skip physical_only pools when system is virtual otherwise the register will fail with "Pool is restricted to physical systems: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (isSystemVirtual && CandlepinTasks.isPoolRestrictedToPhysicalSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        // for the purpose of this test, skip virt_only pools when system is physical otherwise the register will fail with "Pool is restricted to virtual guests: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (!isSystemVirtual && CandlepinTasks.isPoolRestrictedToVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        /* skipping pools that are not NORMAL is more reliable than this...
			// for the purpose of this test, skip virt_only derived_pool when server is standalone otherwise the register will fail with "Unable to entitle consumer to the pool with id '8a90f85733d86b130133d88c09410e5e'.: virt.guest.host.does.not.match.pool.owner"
			//if (servertasks.statusStandalone) {	// 5/29/2014 removed this check, I can't remember why I originally set it 
			// for the purpose of this test, skip virt_only derived_pool when otherwise the register will fail with "Guest's host does not match owner of pool: '8a908775463fef2301464072ee68496e'."
			if (true) {
				String pool_derived = CandlepinTasks.getPoolAttributeValue(jsonPool, "pool_derived");
				String virt_only = CandlepinTasks.getPoolAttributeValue(jsonPool, "virt_only");
				if (pool_derived!=null && virt_only!=null && Boolean.valueOf(pool_derived) && Boolean.valueOf(virt_only)) {
					continue;
				}
			}
			*/
        // for the purpose of this test, skip pools that are not NORMAL (eg. BONUS, ENTITLEMENT_DERIVED, STACK_DERIVED)
        String poolType = (String) CandlepinTasks.getPoolValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id"), "type");
        if (!poolType.equals("NORMAL"))
            continue;
        // create an activation key
        String activationKeyName = String.format("ActivationKey%sWithPool%sForOrg_%s", System.currentTimeMillis(), jsonPool.getString("id"), sm_clientOrg);
        Map<String, String> mapActivationKeyRequest = new HashMap<String, String>();
        mapActivationKeyRequest.put("name", activationKeyName);
        JSONObject jsonActivationKeyRequest = new JSONObject(mapActivationKeyRequest);
        JSONObject jsonActivationKey = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/owners/" + sm_clientOrg + "/activation_keys", jsonActivationKeyRequest.toString()));
        // add the pool to the activation key
        String path = "/activation_keys/" + jsonActivationKey.getString("id") + "/pools/" + jsonPool.getString("id") + (addQuantity == null ? "" : "?quantity=" + addQuantity);
        JSONObject jsonResult = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, path, null));
        // if (clienttasks.isVersion(servertasks.statusVersion, ">", "0.9.30-1")) the POST now returns the jsonActivationKey and formerly returned the jsonPoolAddedToActivationKey	// candlepin commit 82b9af5dc2c63b58447366e680fcf6f156c6049f
        if (jsonResult.has("displayMessage")) {
            Assert.fail("Failed to add pool '" + jsonPool.getString("productId") + "' '" + jsonPool.getString("id") + "' to activation key '" + jsonActivationKey.getString("id") + "'.  DisplayMessage: " + jsonResult.getString("displayMessage"));
        }
        jsonPoolsAddedToActivationKey.put(jsonPool);
        activationKeyNames.add(activationKeyName);
    }
    if (addQuantity == null)
        addQuantity = 1;
    // register with the activation key specified as a single string
    SSHCommandResult registerResult = clienttasks.register(null, null, sm_clientOrg, null, null, null, null, null, null, null, activationKeyNames, null, null, null, true, null, null, null, null, null);
    // assert that all the pools were consumed
    List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    for (int i = 0; i < jsonPoolsAddedToActivationKey.length(); i++) {
        JSONObject jsonPoolAdded = (JSONObject) jsonPoolsAddedToActivationKey.get(i);
        // assert that the pool's providedProducts (excluding type=MKT products) are consumed (unless it is a ManagementAddOn product - indicated by no providedProducts)
        assertProvidedProductsFromPoolAreWithinConsumedProductSubscriptionsUsingQuantity(jsonPoolAdded, consumedProductSubscriptions, addQuantity, false);
    }
    Assert.assertEquals(clienttasks.getCurrentEntitlementCertFiles().size(), activationKeyNames.size(), "Expecting a new entitlement cert file in '" + clienttasks.entitlementCertDir + "' for each of the single pooled activation keys used during register.");
}
Also used : HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) JSONObject(org.json.JSONObject) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 65 with TestDefinition

use of com.github.redhatqe.polarize.metadata.TestDefinition in project rhsm-qe by RedHatQE.

the class ActivationKeyTests method testMultiClientAttemptToDeadLockOnRegisterWithActivationKeys.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21791", "RHEL7-51608" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.NEGATIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "attempt to register two different consumers with multiple activation keys (in reverse order) containing many subscriptions", groups = { "Tier3Tests", "blockedByBug-1095939" })
public // @ImplementsNitrateTest(caseId=)
void testMultiClientAttemptToDeadLockOnRegisterWithActivationKeys() throws JSONException, Exception {
    if (client2tasks == null)
        throw new SkipException("This multi-client test requires a second client.");
    // register two clients
    String client1ConsumerId = client1tasks.getCurrentConsumerId(client1tasks.register(sm_client1Username, sm_client1Password, sm_client1Org, null, null, null, null, null, null, null, (List<String>) null, null, null, null, true, false, null, null, null, null));
    String client2ConsumerId = client2tasks.getCurrentConsumerId(client2tasks.register(sm_client2Username, sm_client2Password, sm_client2Org, null, null, null, null, null, null, null, (List<String>) null, null, null, null, true, false, null, null, null, null));
    String client1OwnerKey = CandlepinTasks.getOwnerKeyOfConsumerId(sm_client1Username, sm_client1Password, sm_serverUrl, client1ConsumerId);
    String client2OwnerKey = CandlepinTasks.getOwnerKeyOfConsumerId(sm_client2Username, sm_client2Password, sm_serverUrl, client2ConsumerId);
    if (!client1OwnerKey.equals(client2OwnerKey))
        throw new SkipException("This multi-client test requires that both client registerers belong to the same owner. (client1: username=" + sm_client1Username + " ownerkey=" + client1OwnerKey + ") (client2: username=" + sm_client2Username + " ownerkey=" + client2OwnerKey + ")");
    // get all of the pools belonging to ownerKey
    JSONArray jsonPools = new JSONArray(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/owners/" + client1OwnerKey + "/pools?listall=true"));
    if (!(jsonPools.length() > 1))
        throw new SkipException("This test requires more than one pool for org '" + sm_client1Org + "'.");
    jsonPools = clienttasks.workaroundForBug1040101(jsonPools);
    // create two activation key each containing the same pools (added in reverse order)
    long currentTimeMillis = System.currentTimeMillis();
    final String activationKeyName1 = String.format("ActivationKey1_%sWithMultiplePoolsForOrgKey_%s", currentTimeMillis, client1OwnerKey);
    final String activationKeyName2 = String.format("ActivationKey2_%sWithMultiplePoolsForOrgKey_%s", currentTimeMillis, client2OwnerKey);
    Map<String, String> mapActivationKeyRequest1 = new HashMap<String, String>() {

        {
            put("name", activationKeyName1);
        }
    };
    Map<String, String> mapActivationKeyRequest2 = new HashMap<String, String>() {

        {
            put("name", activationKeyName2);
        }
    };
    JSONObject jsonActivationKey1 = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/owners/" + client1OwnerKey + "/activation_keys", new JSONObject(mapActivationKeyRequest1).toString()));
    JSONObject jsonActivationKey2 = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/owners/" + client2OwnerKey + "/activation_keys", new JSONObject(mapActivationKeyRequest2).toString()));
    // process each of the pools to choosing friendly ones to add to the activation keys
    List<String> poolIds = new ArrayList<String>();
    boolean isSystemVirtual = Boolean.valueOf(clienttasks.getFactValue("virt.is_guest"));
    for (int i = 0; i < jsonPools.length(); i++) {
        JSONObject jsonPool = (JSONObject) jsonPools.get(i);
        // for the purpose of this test, skip pools with no available entitlements (consumed>=quantity) (quantity=-1 is unlimited)
        if (jsonPool.getInt("quantity") > 0 && jsonPool.getInt("consumed") >= jsonPool.getInt("quantity"))
            continue;
        // for the purpose of this test, skip pools that do not have at least 4 available entitlements
        if (jsonPool.getInt("quantity") >= 0 && (jsonPool.getInt("quantity") - jsonPool.getInt("consumed")) < 4)
            continue;
        // for the purpose of this test, skip non-system pools otherwise the register will fail with "Consumers of this type are not allowed to subscribe to the pool with id '8a90f8c631ab7ccc0131ab7e46ca0619'."
        if (!CandlepinTasks.isPoolProductConsumableByConsumerType(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id"), ConsumerType.system))
            continue;
        // for the purpose of this test, skip physical_only pools when system is virtual otherwise the register will fail with "Pool is restricted to physical systems: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (isSystemVirtual && CandlepinTasks.isPoolRestrictedToPhysicalSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        // for the purpose of this test, skip virt_only pools when system is physical otherwise the register will fail with "Pool is restricted to virtual guests: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (!isSystemVirtual && CandlepinTasks.isPoolRestrictedToVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        // for the purpose of this test, skip virt_only derived_pool when server is standalone otherwise the register will fail with "Unable to entitle consumer to the pool with id '8a90f85733d86b130133d88c09410e5e'.: virt.guest.host.does.not.match.pool.owner"
        if (servertasks.statusStandalone) {
            String pool_derived = CandlepinTasks.getPoolAttributeValue(jsonPool, "pool_derived");
            String virt_only = CandlepinTasks.getPoolAttributeValue(jsonPool, "virt_only");
            if (pool_derived != null && virt_only != null && Boolean.valueOf(pool_derived) && Boolean.valueOf(virt_only)) {
                continue;
            }
        }
        // for the purpose of this test, skip non-multi-entitlement pools otherwise the multi-activation key register will fail with "This unit has already had the subscription matching pool ID '8a9087e345a9f5f90145b36429073724' attached."
        if (!CandlepinTasks.isPoolProductMultiEntitlement(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        poolIds.add(jsonPool.getString("id"));
    }
    // add each of the pools to jsonActivationKey1
    for (int i = 0; i < poolIds.size(); i++) {
        JSONObject jsonResult1 = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_client1Username, sm_client1Password, sm_serverUrl, "/activation_keys/" + jsonActivationKey1.getString("id") + "/pools/" + poolIds.get(i), /* + (addQuantity==null?"":"?quantity="+addQuantity)*/
        null));
        // if (clienttasks.isVersion(servertasks.statusVersion, ">", "0.9.30-1")) the POST now returns the jsonActivationKey and formerly returned the jsonPoolAddedToActivationKey	// candlepin commit 82b9af5dc2c63b58447366e680fcf6f156c6049f
        if (jsonResult1.has("displayMessage")) {
            Assert.fail("Failed to add pool '" + poolIds.get(i) + "' to activation key '" + jsonActivationKey1.getString("id") + "'.  DisplayMessage: " + jsonResult1.getString("displayMessage"));
        }
    }
    // add each of the pools to jsonActivationKey2 (in reverse order)
    for (int i = poolIds.size() - 1; i >= 0; i--) {
        JSONObject jsonResult2 = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_client2Username, sm_client2Password, sm_serverUrl, "/activation_keys/" + jsonActivationKey2.getString("id") + "/pools/" + poolIds.get(i), /* + (addQuantity==null?"":"?quantity="+addQuantity)*/
        null));
        // if (clienttasks.isVersion(servertasks.statusVersion, ">", "0.9.30-1")) the POST now returns the jsonActivationKey and formerly returned the jsonPoolAddedToActivationKey	// candlepin commit 82b9af5dc2c63b58447366e680fcf6f156c6049f
        if (jsonResult2.has("displayMessage")) {
            Assert.fail("Failed to add pool '" + poolIds.get(i) + "' to activation key '" + jsonActivationKey2.getString("id") + "'.  DisplayMessage: " + jsonResult2.getString("displayMessage"));
        }
    }
    // attempt this test more than once
    for (int attempt = 1; attempt < 5; attempt++) {
        client1tasks.unregister(null, null, null, null);
        client2tasks.unregister(null, null, null, null);
        // register each client simultaneously using the activation keys (one in reverse order of the other)
        log.info("Simultaneously attempting to register with activation keys on '" + client1tasks.hostname + "' and '" + client2tasks.hostname + "'...");
        client1.runCommand(/*AndWait*/
        client1tasks.registerCommand(null, null, client1OwnerKey, null, null, null, null, null, null, null, new ArrayList<String>() {

            {
                add(activationKeyName1);
                add(activationKeyName2);
            }
        }, null, null, null, null, null, null, null, null, null), TestRecords.action());
        client2.runCommand(/*AndWait*/
        client2tasks.registerCommand(null, null, client2OwnerKey, null, null, null, null, null, null, null, new ArrayList<String>() {

            {
                add(activationKeyName2);
                add(activationKeyName1);
            }
        }, null, null, null, null, null, null, null, null, null), TestRecords.action());
        // timeout after 10 min
        client1.waitForWithTimeout(new Long(10 * 60 * 1000));
        // timeout after 10 min
        client2.waitForWithTimeout(new Long(10 * 60 * 1000));
        SSHCommandResult client1Result = client1.getSSHCommandResult();
        SSHCommandResult client2Result = client2.getSSHCommandResult();
        // 201405091623:44.055 - INFO: SSHCommandResult from an attempt to register with activation keys on 'jsefler-7server.usersys.redhat.com':
        // exitCode=255
        // stdout=''
        // stderr='Problem creating unit Consumer [id = 8a9087e345a9f5f90145e2a740c200ad, type = ConsumerType [id=1000, label=system], getName() = jsefler-7server.usersys.redhat.com]'
        // assert the results
        log.info("SSHCommandResult from an attempt to register with activation keys on '" + client1tasks.hostname + "': \n" + client1Result);
        log.info("SSHCommandResult from an attempt to register with activation keys on '" + client2tasks.hostname + "': \n" + client2Result);
        Assert.assertEquals(client1Result.getExitCode(), Integer.valueOf(0), "The exit code from register with activation keys on '" + client1tasks.hostname + "'.");
        // TEMPORARY WORKAROUND FOR BUG: 1183122 - rhsmd/subman dbus traceback on 'attach --pool'
        if (client1Result.getStderr().contains("KeyError: 'product_id'")) {
            boolean invokeWorkaroundWhileBugIsOpen = true;
            String bugId = "1183122";
            try {
                if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
                    log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
                    SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
                } else {
                    invokeWorkaroundWhileBugIsOpen = false;
                }
            } catch (BugzillaAPIException be) {
            /* ignore exception */
            } catch (RuntimeException re) {
            /* ignore exception */
            }
            if (invokeWorkaroundWhileBugIsOpen) {
                log.warning("Encountered bug '" + bugId + "'. Skipping stderr/exitCode assertion from the prior register with activationkey command while bug '" + bugId + "' is open.");
            }
        } else
            // Assert client1Result.getStderr()
            // END OF WORKAROUND
            Assert.assertEquals(client1Result.getStderr(), "", "Stderr from the unsubscribe all on '" + client1tasks.hostname + "'.");
        Assert.assertEquals(client2Result.getExitCode(), Integer.valueOf(0), "The exit code from register with activation keys on '" + client2tasks.hostname + "'.");
        // TEMPORARY WORKAROUND FOR BUG: 1183122 - rhsmd/subman dbus traceback on 'attach --pool'
        if (client2Result.getStderr().contains("KeyError: 'product_id'")) {
            boolean invokeWorkaroundWhileBugIsOpen = true;
            String bugId = "1183122";
            try {
                if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
                    log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
                    SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
                } else {
                    invokeWorkaroundWhileBugIsOpen = false;
                }
            } catch (BugzillaAPIException be) {
            /* ignore exception */
            } catch (RuntimeException re) {
            /* ignore exception */
            }
            if (invokeWorkaroundWhileBugIsOpen) {
                log.warning("Encountered bug '" + bugId + "'. Skipping stderr/exitCode assertion from the prior register with activationkey command while bug '" + bugId + "' is open.");
            }
        } else
            // Assert client2Result.getStderr()
            // END OF WORKAROUND
            Assert.assertEquals(client2Result.getStderr(), "", "Stderr from the unsubscribe all on '" + client2tasks.hostname + "'.");
    }
}
Also used : HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) JSONObject(org.json.JSONObject) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ArrayList(java.util.ArrayList) List(java.util.List) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Aggregations

TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)687 Test (org.testng.annotations.Test)687 SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)401 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)366 SkipException (org.testng.SkipException)328 ArrayList (java.util.ArrayList)144 SubscriptionPool (rhsm.data.SubscriptionPool)137 JSONObject (org.json.JSONObject)95 BigInteger (java.math.BigInteger)90 BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)88 HashMap (java.util.HashMap)78 File (java.io.File)74 ProductSubscription (rhsm.data.ProductSubscription)72 InstalledProduct (rhsm.data.InstalledProduct)66 EntitlementCert (rhsm.data.EntitlementCert)58 ProductCert (rhsm.data.ProductCert)54 YumRepo (rhsm.data.YumRepo)34 Repo (rhsm.data.Repo)26 Calendar (java.util.Calendar)25 List (java.util.List)24