Search in sources :

Example 26 with ProductSubscription

use of rhsm.data.ProductSubscription in project rhsm-qe by RedHatQE.

the class SubscriptionManagerTasks method unsubscribeFromTheCurrentlyConsumedProductSubscriptionSerialsCollectively.

/**
 * Collectively unsubscribe from all of the currently consumed product subscriptions.
 * This will ultimately issue a single call to unsubscribe --serial SERIAL1 --serial SERIAL2 --serial SERIAL3 for each of the product subscriptions being consumed.
 * @throws Exception
 */
public SSHCommandResult unsubscribeFromTheCurrentlyConsumedProductSubscriptionSerialsCollectively() throws Exception {
    log.info("Unsubscribing from all of the currently consumed product subscription serials in one collective call...");
    List<BigInteger> serials = new ArrayList<BigInteger>();
    // THIS AVOIDS PROBLEMS WHEN MODIFIER ENTITLEMENTS ARE BEING CONSUMED
    for (ProductSubscription productSubscription : getCurrentlyConsumedProductSubscriptions()) {
        EntitlementCert entitlementCert = getEntitlementCertCorrespondingToProductSubscription(productSubscription);
        JSONObject jsonEntitlement = CandlepinTasks.getEntitlementUsingRESTfulAPI(this.currentlyRegisteredUsername, this.currentlyRegisteredPassword, candlepinUrl, entitlementCert.id);
        String poolHref = jsonEntitlement.getJSONObject("pool").getString("href");
        JSONObject jsonPool = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(this.currentlyRegisteredUsername, this.currentlyRegisteredPassword, candlepinUrl, poolHref));
        String poolId = jsonPool.getString("id");
        if (CandlepinTasks.isPoolAModifier(this.currentlyRegisteredUsername, this.currentlyRegisteredPassword, poolId, candlepinUrl)) {
            // serials to entitlements that modify others should be at the front of the list to be removed, otherwise they will get re-issued under a new serial number when the modified entitlement is removed first.
            serials.add(0, productSubscription.serialNumber);
        } else {
            serials.add(productSubscription.serialNumber);
        }
    }
    // unsubscribe from all serials collectively
    SSHCommandResult result = unsubscribe(false, serials, null, null, null, null, null);
    Assert.assertTrue(getCurrentlyConsumedProductSubscriptions().size() == 0, "Currently no product subscriptions are consumed.");
    Assert.assertTrue(getCurrentEntitlementCertFiles().size() == 0, "This machine has no entitlement certificate files.");
    return result;
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) JSONObject(org.json.JSONObject) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) BigInteger(java.math.BigInteger)

Example 27 with ProductSubscription

use of rhsm.data.ProductSubscription in project rhsm-qe by RedHatQE.

the class ExpirationTests method testEntitlementsAfterSubscriptionExpires.

// 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-36638", "RHEL7-51448" }, 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 = "Tier2")
@Test(description = "subscribe to a pool that will expire soon and assert the entitlements are removed after it expires", groups = { "Tier2Tests", "blockedByBug-655835", "blockedByBug-660713", "blockedByBug-854312", "blockedByBug-907638", "blockedByBug-994266", "blockedByBug-1555582" }, dependsOnGroups = {}, enabled = true)
public void testEntitlementsAfterSubscriptionExpires() throws Exception {
    clienttasks.restart_rhsmcertd(certFrequency, null, true);
    // create a subscription pool that will expire 2 minutes from now
    int endingMinutesFromNow = 2;
    String expiringPoolId = createTestPool(-60 * 24, endingMinutesFromNow);
    // assert the expiring pool is currently available
    SubscriptionPool expiringPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", expiringPoolId, clienttasks.getCurrentlyAllAvailableSubscriptionPools());
    Assert.assertNotNull(expiringPool, "The expiring SubscriptionPool is currently available for subscribing: " + expiringPool);
    // subscribe
    File expiringCertFile = clienttasks.subscribeToSubscriptionPool_(expiringPool);
    /*EntitlementCert*/
    expiringCert = clienttasks.getEntitlementCertFromEntitlementCertFile(expiringCertFile);
    List<ProductSubscription> expiringProductSubscriptions = ProductSubscription.findAllInstancesWithMatchingFieldFromList("serialNumber", expiringCert.serialNumber, clienttasks.getCurrentlyConsumedProductSubscriptions());
    Assert.assertMore(expiringProductSubscriptions.size(), 0, "Found ProductSubscriptions corresponding to the just subscribed SubscriptionPool: " + expiringPool);
    for (ProductSubscription expiringProductSubscription : expiringProductSubscriptions) {
        Assert.assertTrue(expiringProductSubscription.isActive, "Immediately before the consumed subscription '" + expiringProductSubscription.productName + "' is about the expire, the list --consumed should show it as Active.");
    }
    // wait for pool to expire
    // plus a 10 sec buffer; changed to 0 sec - the buffer creates too large of an opportunity for rhsmcertd to run and wipe out the expired cert
    sleep(endingMinutesFromNow * 60 * 1000 + 0 * 1000);
    String rhsmcertdLogMarker = System.currentTimeMillis() + " Testing VerifyEntitlementsAfterSubscriptionExpires_Test...";
    RemoteFileTasks.markFile(client, clienttasks.rhsmcertdLogFile, rhsmcertdLogMarker);
    // /*debugTesting*/sleep(certFrequency*60*1000);	// to delay the assert long enough for rhsmcertd to trigger and delete the expired cert; used to force the code path through the "if (expiredProductSubscription==null)" code block that follows
    // verify that the subscription pool has expired and is therefore not listed in all available; coverage for Bug 655835 - Pools are no longer removed after their expiration date https://github.com/RedHatQE/rhsm-qe/issues/132
    SubscriptionPool expiredPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", expiringPoolId, clienttasks.getCurrentlyAllAvailableSubscriptionPools());
    Assert.assertNull(expiredPool, "Expired Test Pool ID '" + expiringPoolId + "' is no longer available for subscribing.");
    /* The following behavior block of assertions was changed for a few reasons...
		 * 1. Bug 994266 - expired entitlement shows in GUI but not in CLI
		 * 2. We felt that expired entitlements should remain on the system for the system user to acknowledge
		 * 3. The system user can simply acknowledge the expiration by clicking Remove in the GUI tab of "My Subscriptions"
		// verify that the expired product subscriptions are not listed among the consumed
		List <ProductSubscription> currentProductSubscriptions = ProductSubscription.parse(clienttasks.list(null,null,true, null, null, null, null, null, null).getStdout());
		for (ProductSubscription p : expiringProductSubscriptions) {
			Assert.assertTrue(!currentProductSubscriptions.contains(p),"The expired ProductSubscription '"+p+"' no longer appears as consumed.");
		}
		* current behavior is asserted here... */
    // verify that the expired product subscriptions is still listed among the consumed, but inactive
    List<ProductSubscription> currentlyConsumedProductSubscriptions = ProductSubscription.parse(clienttasks.list(null, null, true, null, null, null, null, null, null, null, null, null, null, null).getStdout());
    for (ProductSubscription expiringProductSubscription : expiringProductSubscriptions) {
        ProductSubscription expiredProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("serialNumber", expiringProductSubscription.serialNumber, currentlyConsumedProductSubscriptions);
        // catch a corner case...
        if (expiredProductSubscription == null) {
            // then we were probably too slow and a trigger of rhsmcertd likely deleted the expired cert.
            // Using this if block of code to confirm that assumption and skip the rest of this test
            // desperate attempt to give rhsmcertdLogFile a chance to be updated so rhsmcertdLogTail will not be empty
            sleep(1 * 1000);
            String rhsmcertdLogTail = RemoteFileTasks.getTailFromMarkedFile(client, clienttasks.rhsmcertdLogFile, rhsmcertdLogMarker, null);
            // rhsmcertd:
            // Fri Aug 26 15:42:19 2016 [INFO] (Cert Check) Certificates updated.
            // ---------------------------------------------------------------------------------------------------------
            // rhsm.log:
            // 2016-08-26 15:42:17,819 [DEBUG] rhsmcertd-worker:5398:MainThread @connection.py:573 - Making request: GET /candlepin/consumers/c56bfdb6-ff4c-41b6-84c2-4e0179df3a37/certificates/serials
            // 2016-08-26 15:42:18,016 [DEBUG] rhsmcertd-worker:5398:MainThread @connection.py:602 - Response: status=200, requestUuid=bfd74f37-ef19-4516-8a5f-89d44dc9dc56
            // 2016-08-26 15:42:18,018 [INFO] rhsmcertd-worker:5398:MainThread @entcertlib.py:131 - certs updated:
            // Total updates: 1
            // Found (local) serial# [1826226756700020146L]
            // Expected (UEP) serial# []
            // Added (new)
            // <NONE>
            // Deleted (rogue):
            // [sn:1826226756700020146 (Awesome OS Server Bundled) @ /etc/pki/entitlement/1826226756700020146.pem]
            Assert.assertTrue(rhsmcertdLogTail.trim().endsWith("Certificates updated."), "It appears that the rhsmcertd coincidently triggered too quickly on its frequency of '" + certFrequency + "'min after the entitlement expired causing it to be deleted by the rhsmcertd.");
            throw new SkipException("Skipping the rest of this test since rhsmcertd triggered too closely after the expiration of the entitlement cert for us to do all of our test assertions before rhsmcertd ran.  Hopefully the next test run will complete.");
        }
        Assert.assertNotNull(expiredProductSubscription, "Immediately after the consumed subscription '" + expiringProductSubscription.productName + "' serial '" + expiringProductSubscription.serialNumber + "' expires, it should still be found the list of consumed product subscriptions (assuming that rhsmcertd on certFrequency='" + certFrequency + "'min has not yet triggered before this assert).");
        Assert.assertTrue(!expiredProductSubscription.isActive, "Immediately after the consumed subscription '" + expiringProductSubscription.productName + "' serial '" + expiringProductSubscription.serialNumber + "' expires, the list of consumed product subscriptions should show it as inActive.");
    }
    // verify that the expired entitlement cert file is gone after a trigger of rhsmcertd.certFrequency
    SubscriptionManagerCLITestScript.sleep(certFrequency * 60 * 1000);
    Assert.assertTrue(!RemoteFileTasks.testExists(client, expiringCertFile.getPath()), "The expired entitlement cert file has been cleaned off the system by rhsmcertd");
    // final test in honor of bug 854312 - rhsmcertd removes, then puts, then removes, then puts, then removes, etc... an expired entitlement cert
    // verify that the expired entitlement cert file is still gone after another trigger a rhsmcertd.certFrequency
    SubscriptionManagerCLITestScript.sleep(certFrequency * 60 * 1000);
    Assert.assertTrue(!RemoteFileTasks.testExists(client, expiringCertFile.getPath()), "After another trigger of the cert frequency, the expired entitlement cert file remains cleaned from the system.");
}
Also used : ProductSubscription(rhsm.data.ProductSubscription) SkipException(org.testng.SkipException) SubscriptionPool(rhsm.data.SubscriptionPool) File(java.io.File) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 28 with ProductSubscription

use of rhsm.data.ProductSubscription in project rhsm-qe by RedHatQE.

the class FlexibleBrandingTests method testBrandNameFileCreationWithActivationKeys.

/**
 * @author skallesh
 * @throws Exception
 * @throws JSONException
 */
@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-36694", "RHEL7-51540" }, 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 = "Tier2")
@Test(description = "verify if brandname file is created when registering with an activation key", groups = { "Tier2Tests", "CreationWithTActivationKey" }, enabled = true)
public void testBrandNameFileCreationWithActivationKeys() throws Exception {
    // reset the installed product cert to productCert32060 and reset the brand file
    clienttasks.removeAllCerts(false, false, true);
    RemoteFileTasks.runCommandAndAssert(client, "cp " + productCert32060.file + " " + tmpProductCertDir, Integer.valueOf(0));
    RemoteFileTasks.runCommandAndWait(client, "rm -f " + Brand_Name, TestRecords.action());
    Integer addQuantity = null;
    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);
    if (clienttasks.getFactValue("virt.is_guest").equals("True")) {
        addQuantity = 1;
    } else {
        addQuantity = 2;
    }
    String name = String.format("%s_%s-ActivationKey%s", sm_clientUsername, sm_clientOrg, System.currentTimeMillis());
    Map<String, String> mapActivationKeyRequest = new HashMap<String, String>();
    mapActivationKeyRequest.put("name", name);
    JSONObject jsonActivationKeyRequest = new JSONObject(mapActivationKeyRequest);
    JSONObject jsonActivationKey = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/owners/" + sm_clientOrg + "/activation_keys", jsonActivationKeyRequest.toString()));
    String poolId = null;
    for (SubscriptionPool availList : clienttasks.getCurrentlyAllAvailableSubscriptionPools()) {
        if (availList.subscriptionName.contains("Instance")) {
            poolId = availList.poolId;
        }
    }
    new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/activation_keys/" + jsonActivationKey.getString("id") + "/pools/" + poolId + (addQuantity == null ? "" : "?quantity=" + addQuantity), null));
    clienttasks.register(null, null, sm_clientOrg, null, null, null, null, null, null, null, name, null, null, null, true, null, null, null, null, null);
    List<ProductSubscription> consumed = clienttasks.getCurrentlyConsumedProductSubscriptions();
    String productname = "Branded " + consumed.get(randomGenerator.nextInt(consumed.size())).productName;
    String result = client.runCommandAndWait("cat " + Brand_Name).getStdout();
    Assert.assertEquals(result.trim(), productname.trim());
}
Also used : BigInteger(java.math.BigInteger) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) ProductSubscription(rhsm.data.ProductSubscription) SubscriptionPool(rhsm.data.SubscriptionPool) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 29 with ProductSubscription

use of rhsm.data.ProductSubscription in project rhsm-qe by RedHatQE.

the class ComplianceTests method testComplianceConsidersSystemArch.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20064", "RHEL7-51070" }, 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 = "when a subscription is attached that does not match the system's arch, assert the installed product status is blocked from going green", groups = { "Tier1Tests", "cli.tests", "VerifyComplianceConsidersSystemArch_Test", "blockedByBug-909467" }, dataProvider = "getSubscriptionPoolProvidingProductIdOnArchData", enabled = true)
public // @ImplementsTCMS(id="")
void testComplianceConsidersSystemArch(Object bugzilla, SubscriptionPool pool, String providingProductId, String poolArch) {
    clienttasks.deleteFactsFileWithOverridingValues(fakeArchFactsFilename);
    clienttasks.unsubscribe(true, (BigInteger) null, null, null, null, null, null);
    // OVERKILL InstalledProduct installedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", providingProductId, clienttasks.getCurrentlyInstalledProducts());
    // OVERKILL Assert.assertEquals(installedProduct.status, "Not Subscribed");
    clienttasks.subscribe(null, null, pool.poolId, null, null, null, null, null, null, null, null, null, null);
    ProductSubscription productSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("poolId", pool.poolId, clienttasks.getCurrentlyConsumedProductSubscriptions());
    InstalledProduct installedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", providingProductId, clienttasks.getCurrentlyInstalledProducts());
    // expand the arches that the granted entitlement from this subscription pool covers
    // Note: the arch can be a comma separated list of values
    List<String> poolArches = new ArrayList<String>(Arrays.asList(poolArch.trim().split(" *, *")));
    // Note: x86 is a general term to cover all 32-bit intel microprocessors
    if (poolArches.contains("x86")) {
        poolArches.addAll(Arrays.asList("i386", "i486", "i586", "i686"));
    }
    // expand the ALL alias
    if (poolArches.contains("ALL")) {
        poolArches.addAll(Arrays.asList("i386", "i486", "i586", "i686", "x86_64", "ia64", "ppc64", "s390x"));
    }
    // expand the arches that this installed product is valid on
    // Note: the arch can be a comma separated list of values
    List<String> installedProductArches = new ArrayList<String>(Arrays.asList(installedProduct.arch.trim().split(" *, *")));
    // Note: x86 is a general term to cover all 32-bit intel microprocessors
    if (installedProductArches.contains("x86")) {
        installedProductArches.addAll(Arrays.asList("i386", "i486", "i586", "i686"));
    }
    // expand the ALL alias
    if (installedProductArches.contains("ALL")) {
        installedProductArches.addAll(Arrays.asList("i386", "i486", "i586", "i686", "x86_64", "ia64", "ppc64", "s390x"));
    }
    // assert the statusDetails for the consumed entitlement
    if (poolArches.contains(clienttasks.arch)) {
        // empty
        List<String> expectedStatusDetails = new ArrayList<String>();
        if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.13.13-1")) {
            // commit 252ec4520fb6272b00ae379703cd004f558aac63	// bug 1180400: "Status Details" are now populated on CLI
            // Bug 1180400 - Status datails is blank in list consumed output
            expectedStatusDetails = Arrays.asList(new String[] { "Subscription is current" });
        }
        Assert.assertEquals(productSubscription.statusDetails, expectedStatusDetails, "The statusDetails from the consumed product subscription '" + productSubscription.productName + "' poolId='" + productSubscription.poolId + "' should be " + expectedStatusDetails + " when the system's arch '" + clienttasks.arch + "' is covered by the product subscription arches '" + poolArch.trim() + "'.");
    } else {
        if (productSubscription.statusDetails.isEmpty())
            log.warning("Status Details from the consumed product subscription '" + productSubscription.productName + "' poolId='" + productSubscription.poolId + "' appears empty.  Is your candlepin server older than 0.8.6?");
        // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
        Assert.assertEquals(productSubscription.statusDetails.get(0), /*assumes only one detail*/
        String.format("Supports architecture %s but the system is %s.", poolArch.trim(), clienttasks.arch), "The statusDetails from the consumed product subscription '" + productSubscription.productName + "' poolId='" + productSubscription.poolId + "' when the system's arch '" + clienttasks.arch + "' is NOT covered by the product subscription arches '" + poolArch.trim() + "'.");
    }
    // assert the status and statusDetails for the installed product
    if (poolArches.contains(clienttasks.arch)) {
        // if (CandlepinTasks.isPoolRestrictedToUnmappedVirtualSystems(sm_clientUsername,sm_clientPassword, sm_serverUrl, pool.poolId)) {
        // // handle the system status of when entitled by a unmapped_guests_only pool
        // Assert.assertEquals(installedProduct.status, "Partially Subscribed", "When installed product '"+installedProduct.productName+"' is covered by subscription '"+pool.subscriptionName+"' whose arches '"+poolArch+"' cover the system's arch '"+clienttasks.arch+"', then the installed product can achieve full green compliance.  However, since this pool '"+pool.poolId+"' is restricted to unmapped guests only, then the status is yellow.");
        // Assert.assertEquals(installedProduct.statusDetails.get(0), "Guest has not been reported on any host and is using a temporary unmapped guest subscription.", "The statusDetails for installed product '"+installedProduct.productName+"' productId='"+providingProductId+"' when the system's arch '"+clienttasks.arch+"' is covered by the product subscription arches '"+poolArch.trim()+"' and the entitlement was granted from a unmapped guests only pool '"+pool.poolId+"'. (Note: the installed products arches '"+installedProduct.arch+"' are not considered)");
        // Assert.assertEquals(installedProduct.statusDetails.toArray(new String[]{}), new String[]{"Guest has not been reported on any host and is using a temporary unmapped guest subscription."}, "The statusDetails for installed product '"+installedProduct.productName+"' productId='"+providingProductId+"' when the system's arch '"+clienttasks.arch+"' is covered by the product subscription arches '"+poolArch.trim()+"' and the entitlement was granted from a unmapped guests only pool '"+pool.poolId+"'. (Note: the installed products arches '"+installedProduct.arch+"' are not considered)");
        // } else {
        Assert.assertEquals(installedProduct.status, "Subscribed", "When installed product '" + installedProduct.productName + "' is covered by subscription '" + pool.subscriptionName + "' whose arches '" + poolArch + "' cover the system's arch '" + clienttasks.arch + "', then the installed product can achieve full green compliance.");
        Assert.assertTrue(installedProduct.statusDetails.isEmpty(), "The statusDetails for installed product '" + installedProduct.productName + "' productId='" + providingProductId + "' should be empty when the system's arch '" + clienttasks.arch + "' is covered by the product subscription arches '" + poolArch.trim() + "'. (Note: the installed products arches '" + installedProduct.arch + "' are not considered)");
    // }
    } else {
        if (installedProduct.statusDetails.isEmpty())
            log.warning("Status Details appears empty.  Is your candlepin server older than 0.8.6?");
        Assert.assertEquals(installedProduct.status, "Partially Subscribed", "When installed product '" + installedProduct.productName + "' is covered by subscription '" + pool.subscriptionName + "' whose arches '" + poolArch + "' do NOT cover the system's arch '" + clienttasks.arch + "', then the installed product is limited to yellow compliance.");
        // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
        Assert.assertEquals(installedProduct.statusDetails.get(0), /*assumes only one detail*/
        String.format("Supports architecture %s but the system is %s.", poolArch.trim(), clienttasks.arch), "The statusDetails of the installed product '" + installedProduct.productName + "' when the system's arch '" + clienttasks.arch + "' is NOT covered by the product subscription arches '" + poolArch.trim() + "'.");
    }
    // now let's fake the system's arch fact "uname.machine" forcing it to NOT match the providing productSubscription
    if (productSubscription.statusDetails.isEmpty() && !poolArches.contains("ALL")) {
        String fakeArch = "amd64";
        Map<String, String> factsMap = new HashMap<String, String>();
        factsMap.put("uname.machine", fakeArch);
        clienttasks.createFactsFileWithOverridingValues(fakeArchFactsFilename, factsMap);
        clienttasks.facts(null, true, null, null, null, null);
        productSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("poolId", pool.poolId, clienttasks.getCurrentlyConsumedProductSubscriptions());
        if (productSubscription.statusDetails.isEmpty())
            log.warning("Status Details appears empty.  Is your candlepin server older than 0.8.6?");
        // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
        Assert.assertEquals(productSubscription.statusDetails.get(0), /*assumes only one detail*/
        String.format("Supports architecture %s but the system is %s.", poolArch.trim(), fakeArch), "The statusDetails from the consumed product subscription when the system's arch '" + fakeArch + "' is NOT covered by the product subscription arches '" + poolArch.trim() + "'.");
        installedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", providingProductId, clienttasks.getCurrentlyInstalledProducts());
        if (installedProduct.statusDetails.isEmpty())
            log.warning("Status Details appears empty.  Is your candlepin server older than 0.8.6?");
        // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
        Assert.assertEquals(installedProduct.statusDetails.get(0), /*assumes only one detail*/
        String.format("Supports architecture %s but the system is %s.", poolArch.trim(), fakeArch), "The statusDetails of the installed product '" + installedProduct.productName + "' when the system's arch '" + clienttasks.arch + "' is NOT covered by the product subscription arches '" + poolArch.trim() + "'.");
    }
}
Also used : HashMap(java.util.HashMap) InstalledProduct(rhsm.data.InstalledProduct) ProductSubscription(rhsm.data.ProductSubscription) ArrayList(java.util.ArrayList) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 30 with ProductSubscription

use of rhsm.data.ProductSubscription in project rhsm-qe by RedHatQE.

the class MigrationTests method testRhnMigrateClassicToRhsmWithActivationKey.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20109", "RHEL7-51742" }, 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 = "Execute migration tool rhn-migrate-classic-to-rhsm with a valid activation-key (and a good org)", groups = { "Tier1Tests", "blockedByBug-1154375", "blockedByBug-1512948", "blockedByBug-1516832" }, enabled = true)
@ImplementsNitrateTest(caseId = 130765)
public void testRhnMigrateClassicToRhsmWithActivationKey() throws Exception {
    if (clienttasks.isPackageVersion("subscription-manager", "<", "1.14.1-1"))
        throw new SkipException("The --activation-key option was not implemented in this version of subscription-manager.");
    // create a valid activation key
    // randomly choose a valid available pool for this key
    SubscriptionPool pool = getRandomListItem(availableSubscriptionPools);
    // choose an activationKey name
    String activationKeyName = String.format("activationKeyForOrg_%s_Pool_%s", clientOrgKey, pool.productId);
    JSONObject jsonActivationKey = CandlepinTasks.createActivationKeyUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, clientOrgKey, activationKeyName, Arrays.asList(pool.poolId), null);
    // register with the activation key
    if (false) {
        // debugTesting
        clienttasks.register_(null, null, clientOrgKey, null, null, null, null, null, null, null, activationKeyName, null, null, null, true, null, null, null, null, null);
        clienttasks.unregister_(null, null, null, null);
    }
    // TEMPORARY WORKAROUND FOR BUG
    // Bug 1196416 - rhn-migrate-classic-to-rhsm with --activation-key option should not prompt for destination credentials
    String bugId = "1196416";
    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) {
        testRhnMigrateClassicToRhsm(null, sm_rhnUsername, sm_rhnPassword, sm_rhnHostname, new ArrayList<String>(), "--activation-key=" + activationKeyName + " " + "--org=" + clientOrgKey, sm_rhnUsername, sm_rhnPassword, sm_clientUsername, sm_clientPassword, null, null, null);
    } else
        // call RhnMigrateClassicToRhsm_Test with rhsmUsername=null and rhsmPassword=null
        // END OF WORKAROUND
        // migrate from RHN Classic to RHSM using the activation key
        testRhnMigrateClassicToRhsm(null, sm_rhnUsername, sm_rhnPassword, sm_rhnHostname, new ArrayList<String>(), "--activation-key=" + activationKeyName + " " + "--org=" + clientOrgKey, sm_rhnUsername, sm_rhnPassword, null, null, null, null, null);
    // assert that the system is consuming the pool from the activation key.
    List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    Assert.assertEquals(consumedProductSubscriptions.size(), 1, "Number of consumed subscriptions after migrating from RHN Classic to RHSM with activation key '" + activationKeyName + "'.");
    Assert.assertEquals(consumedProductSubscriptions.get(0).poolId, pool.poolId, "The sole consumed subscription poolId after migrating from RHN Classic to RHSM with activation key '" + activationKeyName + "'.");
}
Also used : JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) SkipException(org.testng.SkipException) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) SubscriptionPool(rhsm.data.SubscriptionPool) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Aggregations

ProductSubscription (rhsm.data.ProductSubscription)90 Test (org.testng.annotations.Test)82 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)72 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)56 SkipException (org.testng.SkipException)46 ArrayList (java.util.ArrayList)41 SubscriptionPool (rhsm.data.SubscriptionPool)38 SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)31 JSONObject (org.json.JSONObject)31 BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)23 HashMap (java.util.HashMap)22 BigInteger (java.math.BigInteger)20 EntitlementCert (rhsm.data.EntitlementCert)17 InstalledProduct (rhsm.data.InstalledProduct)16 Calendar (java.util.Calendar)15 JSONArray (org.json.JSONArray)13 File (java.io.File)10 GregorianCalendar (java.util.GregorianCalendar)10 HashSet (java.util.HashSet)6 ConsumerCert (rhsm.data.ConsumerCert)6