Search in sources :

Example 71 with BugzillaAPIException

use of com.redhat.qe.auto.bugzilla.BugzillaAPIException in project rhsm-qe by RedHatQE.

the class HighAvailabilityTests method testProductDatabaseIsInSyncWithInstalledProducts.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20071", "RHEL7-55180" }, 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 = "verify product database and installed products are in sync", groups = { "Tier1Tests" }, priority = 12, dependsOnMethods = {}, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testProductDatabaseIsInSyncWithInstalledProducts() throws JSONException {
    // get the installed products and product database map
    List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts();
    Map<String, List<String>> productIdRepoMap = clienttasks.getProductIdToReposMap();
    // List<ProductCert> installedProductCerts = clienttasks.getCurrentProductCerts();	// VALID BEFORE Bugs 1080007 1080012 - [RFE] Include default product certificate in redhat-release
    List<ProductCert> installedProductCerts = clienttasks.getProductCerts(clienttasks.productCertDir);
    // assert that product database and installed products are in sync
    int installedProductCertCount = 0;
    for (ProductCert installedProductCert : installedProductCerts) {
        // skip productCerts from TESTDATA
        if (installedProductCert.file.getName().endsWith("_.pem")) {
            log.info("Skipping assertion that product cert '" + installedProductCert.file + "' (manually installed from generated candlepin TESTDATA) is accounted for in the product database '" + clienttasks.productIdJsonFile + "'.");
            continue;
        }
        // TEMPORARY WORKAROUND
        if (installedProductCert.productId.equals("135") || /* Red Hat Enterprise Linux 6 Server HTB */
        installedProductCert.productId.equals("155")) /* Red Hat Enterprise Linux 6 Workstation HTB */
        {
            List<ProductCert> installedProductDefaultCerts = clienttasks.getProductCerts(clienttasks.productCertDefaultDir);
            if (ProductCert.findFirstInstanceWithMatchingFieldFromList("productId", installedProductCert.productId, installedProductDefaultCerts) != null) {
                boolean invokeWorkaroundWhileBugIsOpen = true;
                // Bug 1318584 - /etc/pki/product-default/*.pem missing in certain variants
                String bugId = "1318584";
                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) {
                    // only skip when the installed HTB product came from the /etc/pki/product-default location due to bug 1318584
                    log.warning("Skipping assertion that Database '" + clienttasks.productIdJsonFile + "' maps installed product id '" + installedProductCert.productId + "' while bug '" + bugId + "' is open.");
                    continue;
                }
            }
        }
        // END OF WORKAROUND
        installedProductCertCount++;
        Assert.assertTrue(productIdRepoMap.containsKey(installedProductCert.productId), "Database '" + clienttasks.productIdJsonFile + "' contains installed product id: " + installedProductCert.productId);
        log.info("Database '" + clienttasks.productIdJsonFile + "' maps installed product id '" + installedProductCert.productId + "' to repo '" + productIdRepoMap.get(installedProductCert.productId) + "'.");
    }
    for (String productId : productIdRepoMap.keySet()) {
        Assert.assertNotNull(InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", productId, installedProducts), "Database '" + clienttasks.productIdJsonFile + "' product id '" + productId + "' is among the installed products.");
    }
    Assert.assertEquals(productIdRepoMap.keySet().size(), installedProductCertCount, "The product id database size matches the number of installed products (excluding TESTDATA products).");
}
Also used : InstalledProduct(rhsm.data.InstalledProduct) ArrayList(java.util.ArrayList) List(java.util.List) ProductCert(rhsm.data.ProductCert) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 72 with BugzillaAPIException

use of com.redhat.qe.auto.bugzilla.BugzillaAPIException in project rhsm-qe by RedHatQE.

the class ImportTests method setupEntitlemenCertsForImportBeforeClass.

@BeforeClass(groups = { "setup" }, dependsOnMethods = { "restartCertFrequencyBeforeClass" })
public void setupEntitlemenCertsForImportBeforeClass() throws Exception {
    // register
    // clienttasks.unregister(null,null,null);	// avoid Bug 733525 - [Errno 2] No such file or directory: '/etc/pki/entitlement'
    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);
    // change the entitlementCertDir to a temporary location to store all of the entitlements that will be used for importing
    originalEntitlementCertDir = clienttasks.getConfFileParameter(clienttasks.rhsmConfFile, "entitlementCertDir");
    clienttasks.updateConfFileParameter(clienttasks.rhsmConfFile, "entitlementCertDir", importEntitlementsDir);
    clienttasks.removeAllCerts(false, true, false);
    // create a directory where we can create bundled entitlement/key certificates for import
    RemoteFileTasks.runCommandAndAssert(client, "mkdir -p " + importCertificatesDir, Integer.valueOf(0));
    RemoteFileTasks.runCommandAndAssert(client, "rm -f " + importCertificatesDir + "/*", Integer.valueOf(0));
    // generate a future entitlement for the ImportACertificateForAFutureEntitlement_Test
    List<List<Object>> futureSystemSubscriptionPoolsDataAsListOfLists = new ArrayList<List<Object>>();
    boolean isGuest = Boolean.valueOf(clienttasks.getFactValue("virt.is_guest"));
    for (List<Object> futureSystemSubscriptionPoolsDataList : getAllFutureSystemSubscriptionPoolsDataAsListOfLists()) {
        // filter out...  Pool is restricted when it is temporary and begins in the future:  '8a9087e34c715b2e014c715c44c40be0'
        if (CandlepinTasks.isPoolRestrictedToUnmappedVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, ((SubscriptionPool) futureSystemSubscriptionPoolsDataList.get(0)).poolId))
            continue;
        // filter out...  Pool is restricted to physical systems: '8a9086d3443c043501443c052aec1298'.
        if (CandlepinTasks.isPoolRestrictedToPhysicalSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, ((SubscriptionPool) futureSystemSubscriptionPoolsDataList.get(0)).poolId) && isGuest)
            continue;
        // filter out...  Pool is restricted to virtual systems: '8a90f85734205a010134205ae8d80403'.
        if (CandlepinTasks.isPoolRestrictedToVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, ((SubscriptionPool) futureSystemSubscriptionPoolsDataList.get(0)).poolId) && !isGuest)
            continue;
        futureSystemSubscriptionPoolsDataAsListOfLists.add(futureSystemSubscriptionPoolsDataList);
    }
    if (futureSystemSubscriptionPoolsDataAsListOfLists.isEmpty()) {
        log.warning("Could not find a pool to a future system subscription.");
    } else {
        SubscriptionPool futurePool = (SubscriptionPool) getRandomListItem(futureSystemSubscriptionPoolsDataAsListOfLists).get(0);
        // subscribe to the future subscription pool
        SSHCommandResult subscribeResult = clienttasks.subscribe(null, null, futurePool.poolId, null, null, null, null, null, null, null, null, null, null);
        // assert that the granted entitlement cert begins in the future
        Calendar now = new GregorianCalendar();
        now.setTimeInMillis(System.currentTimeMillis());
        EntitlementCert futureEntitlementCert = clienttasks.getEntitlementCertCorrespondingToSubscribedPool(futurePool);
        Assert.assertNotNull(futureEntitlementCert, "Found the newly granted EntitlementCert on the client after subscribing to future subscription pool '" + futurePool.poolId + "'.");
        // TEMPORARY WORKAROUND
        Boolean invokeWorkaroundWhileBugIsOpen = true;
        // Bug 1440180 - Attaching a future pool that will start one year from today changes the supposedly inactive subscription to current subscription
        String bugId = "1440180";
        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("Skipping validity and startDate assertions on future entitlement while bug " + bugId + " is open.");
        } else {
            // END OF WORKAROUND
            Assert.assertTrue(futureEntitlementCert.validityNotBefore.after(now), "The newly granted EntitlementCert is not valid until the future.  EntitlementCert: " + futureEntitlementCert);
            Assert.assertTrue(futureEntitlementCert.orderNamespace.startDate.after(now), "The newly granted EntitlementCert's OrderNamespace starts in the future.  OrderNamespace: " + futureEntitlementCert.orderNamespace);
        }
        // remember the futureEntitlementCertFile
        futureEntitlementCertFile = clienttasks.getEntitlementCertFileFromEntitlementCert(futureEntitlementCert);
    }
    // subscribe to all available pools (so as to create valid entitlement cert/key pairs)
    clienttasks.subscribeToTheCurrentlyAvailableSubscriptionPoolsCollectively();
    // assemble a list of entitlements that we can use for import (excluding the future cert)
    entitlementCertFiles = clienttasks.getCurrentEntitlementCertFiles();
    if (futureEntitlementCertFile != null)
        entitlementCertFiles.remove(entitlementCertFiles.indexOf(futureEntitlementCertFile));
    // create a bundled consumer cert/key file for a negative import test
    client.runCommandAndWait("cat " + clienttasks.consumerCertFile() + " " + clienttasks.consumerKeyFile() + " > " + consumerCertFile);
    // restore the entitlementCertDir
    clienttasks.updateConfFileParameter(clienttasks.rhsmConfFile, "entitlementCertDir", originalEntitlementCertDir);
    // unregister client so as to test imports while not registered
    clienttasks.unregister(null, null, null, null);
    // assert that we have some valid entitlement certs for import testing
    if (entitlementCertFiles.size() < 1)
        throw new SkipException("Could not generate valid entitlement certs for these ImportTests.");
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) ArrayList(java.util.ArrayList) GregorianCalendar(java.util.GregorianCalendar) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ArrayList(java.util.ArrayList) List(java.util.List) SkipException(org.testng.SkipException) SubscriptionPool(rhsm.data.SubscriptionPool) BeforeClass(org.testng.annotations.BeforeClass)

Example 73 with BugzillaAPIException

use of com.redhat.qe.auto.bugzilla.BugzillaAPIException in project rhsm-qe by RedHatQE.

the class ImportTests method attemptAnEntitlementImportFromAnInvalidFile_Test.

protected void attemptAnEntitlementImportFromAnInvalidFile_Test(File invalidCertificate) {
    // once imported, what should the entitlement cert file be?
    File expectedEntitlementCertFile = new File(clienttasks.entitlementCertDir + "/" + invalidCertificate.getName());
    File expectedEntitlementKeyFile = clienttasks.getEntitlementCertKeyFileCorrespondingToEntitlementCertFile(expectedEntitlementCertFile);
    // make sure the expected entitlement files do not exist before our test
    Assert.assertTrue(!RemoteFileTasks.testExists(client, expectedEntitlementCertFile.getPath()), "Before attempting the import, asserting that expected destination for the entitlement cert file does NOT yet exist (" + expectedEntitlementCertFile + ").");
    Assert.assertTrue(!RemoteFileTasks.testExists(client, expectedEntitlementKeyFile.getPath()), "Before attempting the import, asserting that expected destination for the entitlement key file does NOT yet exist (" + expectedEntitlementKeyFile + ").");
    // show the contents of the file about to be imported
    log.info("Following is the contents of the certificate file about to be imported...");
    client.runCommandAndWait("cat " + invalidCertificate);
    // attempt an entitlement cert import from a file containing only a key (negative test)
    SSHCommandResult importResult = clienttasks.importCertificate_(invalidCertificate.getPath());
    // predict the expected stdout message for this invalidCertificate
    String expectedStdout = String.format("%s is not a valid certificate file. Please use a valid certificate.", invalidCertificate.getName());
    if (clienttasks.isPackageVersion("python-rhsm", ">=", "1.18.5-1")) {
        // python-rhsm commit 214103dcffce29e31858ffee414d79c1b8063970 Reduce usage of m2crypto
        if (!RemoteFileTasks.testExists(client, invalidCertificate.getPath())) {
            expectedStdout = String.format("%s: file not found.", invalidCertificate.getName());
        }
    }
    // TEMPORARY WORKAROUND FOR BUG: https://bugzilla.redhat.com/show_bug.cgi?id=734533 - jsefler 08/30/2011
    String bugId = "734533";
    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 */
    }
    String bugPkg = "subscription-manager-migration";
    // RHEL62
    String bugVer = "subscription-manager-migration-0.96";
    try {
        if (clienttasks.installedPackageVersionMap.get(bugPkg).contains(bugVer) && !invokeWorkaroundWhileBugIsOpen) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + " which has NOT been fixed in this installed version of " + bugVer + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
            invokeWorkaroundWhileBugIsOpen = true;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    // RHEL58
    bugVer = "subscription-manager-migration-0.98";
    try {
        if (clienttasks.installedPackageVersionMap.get(bugPkg).contains(bugVer) && !invokeWorkaroundWhileBugIsOpen) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + " which has NOT been fixed in this installed version of " + bugVer + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
            invokeWorkaroundWhileBugIsOpen = true;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    if (invokeWorkaroundWhileBugIsOpen) {
        Assert.assertEquals(importResult.getExitCode(), Integer.valueOf(0));
        Assert.assertEquals(importResult.getStdout().trim(), expectedStdout);
    } else {
        // END OF WORKAROUND
        // assert the negative results
        Assert.assertEquals(importResult.getExitCode(), Integer.valueOf(1), "The exit code from the import command indicates a failure.");
        // {0} is not a valid certificate file. Please use a valid certificate.
        Assert.assertEquals(importResult.getStdout().trim(), expectedStdout);
    }
    // verify that the expectedEntitlementCertFile does NOT exist
    Assert.assertTrue(!RemoteFileTasks.testExists(client, expectedEntitlementCertFile.getPath()), "After attempting the import, the expected destination for the entitlement cert file should NOT exist (" + expectedEntitlementCertFile + ") since there was no entitlement in the import file.");
    // verify that the expectedEntitlementKeyFile does NOT exist
    Assert.assertTrue(!RemoteFileTasks.testExists(client, expectedEntitlementKeyFile.getPath()), "After attempting the import, the expected destination for the entitlement key file should NOT exist (" + expectedEntitlementKeyFile + ") since there was no key in the import file.");
}
Also used : SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) File(java.io.File)

Example 74 with BugzillaAPIException

use of com.redhat.qe.auto.bugzilla.BugzillaAPIException in project rhsm-qe by RedHatQE.

the class InstanceTests method testQuantityNeededToAchieveSocketCompliance.

// 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-19986", "RHEL7-51020" }, 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 = "test compliance using variations on sockets and system type when subscribing to an Instance-Based subscription", groups = { "Tier1Tests", "QuantityNeededToAchieveSocketCompliance_Test", "blockedByBug-979492" }, dataProvider = "getAvailableInstanceBasedSubscriptionPoolsData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testQuantityNeededToAchieveSocketCompliance(Object bugzilla, Boolean systemIsGuest, Integer systemSockets, SubscriptionPool pool) throws NumberFormatException, JSONException, Exception {
    // avoid throttling RateLimitExceededException from IT-Candlepin
    if (systemSockets.equals(new Integer(1)) && CandlepinType.hosted.equals(sm_serverType)) {
        // strategically get a new consumer to avoid 60 repeated API calls from the same consumer
        // re-register as a new consumer
        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);
    }
    // This dataProvided test was inspired by the following table of scenarios
    // https://engineering.redhat.com/trac/Entitlement/wiki/InstanceBasedDesign#Scenarios
    /*
		+--------------------------------------------------------------------------+
		|                     Quantity needed to Achieve Socket Compliance         |
		|--------------------------------------------------------------------------|
		| Sample Systems |   2010 Pricing Sub  |  2013 Pricing Sub (inst-based)    |
		|                |                     |     instance_multiplier=2         |
		|                |  order quantity=10  |     order quantity=10             |
		|                |  pool quantity=10   |     pool quantity=20              |
		|                |---------------------------------------------------------|
		|                |sockets=2 |sockets=4 | sockets=1 | sockets=2 | sockets=4 | 
		|==========================================================================|
		| Physical       |    1*    |     1*   |     2     |     2*    |    2*     |
		| 1 sockets      |          |          |           |           |           |
		|--------------------------------------------------------------------------|
		| Physical       |    1     |     1*   |     4     |     2     |    2*     |
		| 2 sockets      |          |          |           |           |           |
		|--------------------------------------------------------------------------|
		| Physical       |    4     |     2    |     16    |     8     |    4      |
		| 8 sockets      |          |          |           |           |           |
		|--------------------------------------------------------------------------|
		| Virtual        |    1*    |     1*   |     1     |     1*    |    1*     |
		| 1 sockets      |          |          |           |           |           |
		|--------------------------------------------------------------------------|
		| Virtual        |    1     |     1*   |     1     |     1     |    1*     |
		| 2 sockets      |          |          |           |           |           |
		|--------------------------------------------------------------------------|
		| Virtual        |    4     |     2    |     1     |     1     |    1      |
		| 8 sockets      |          |          |           |           |           |
		+--------------------------------------------------------------------------+
		*/
    // make sure we are unsubscribed from all subscriptions
    clienttasks.unsubscribe(true, (BigInteger) null, null, null, null, null, null);
    // NOTE: can throw a Runtime Error No row with the given identifier exists: [org.candlepin.model.PoolAttribute#8a908790535c4e7201535ce8eb4e18fa] at org.hibernate.UnresolvableObjectException.throwIfNull:64
    // when prior dataProvided test fails thereby skipping the last unsubscribe subProductSubscription.serialNumber in this test
    // get some attributes from the subscription pool
    List<String> poolProvidedProductIds = CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId);
    Integer poolInstanceMultiplier = Integer.valueOf(CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "instance_multiplier"));
    String poolVirtLimit = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "virt_limit");
    String poolSocketsAsString = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "sockets");
    Integer poolSockets = poolSocketsAsString == null ? null : Integer.valueOf(poolSocketsAsString);
    // manipulate a fake value for poolSockets when there is no 'sockets' pool productAttribute
    if (poolSockets == null) {
        // NOTE: Red Hat Enterprise Linux Beta for IBM System z  SKU: RH00071  SubscriptionType: Instance Based  SystemType: Physical  has no "sockets" product attribute
        if (systemIsGuest) {
            // for compliance calculation purposes assume poolSockets is 1 when the pool has no attribute for sockets
            poolSockets = 1;
        } else {
            // for compliance calculation purposes assume poolSockets is systemSockets when the pool has no attribute for sockets
            poolSockets = systemSockets;
        }
        log.warning("There is no 'sockets' productAttribute for Subscription '" + pool.subscriptionName + "' SKU '" + pool.productId + "'.  Assuming a value of '" + poolSockets + "' for compliance calculations.");
    }
    // instrument the system facts from the dataProvider
    Map<String, String> factsMap = new HashMap<String, String>();
    String dmidecodeSystemUuid = client.runCommandAndWait("dmidecode --string=system-uuid").getStdout().trim();
    // ssh root@celeno.idmqe.lab.eng.bos.redhat.com dmidecode --string=system-uuid
    // Stdout:
    // # SMBIOS implementations newer than version 2.8 are not
    // # fully supported by this version of dmidecode.
    // 174DBEBA-F6BA-1BE1-BAF6-E11BBFBFED17
    // Stderr:
    // ExitCode: 0
    // to get rid of comment lines in the dmidecode response
    dmidecodeSystemUuid = dmidecodeSystemUuid.replaceAll("#.*\n", "").toLowerCase().trim();
    factsMap.clear();
    factsMap.put("cpu.cpu_socket(s)", String.valueOf(systemSockets));
    factsMap.put("virt.is_guest", Boolean.toString(systemIsGuest));
    // reset to actual value from dmidecode --string=system-uuid
    factsMap.put("virt.uuid", dmidecodeSystemUuid);
    clienttasks.createFactsFileWithOverridingValues(factsMap);
    // update the facts on the system
    clienttasks.facts(null, true, null, null, null, null);
    // predict the quantity needed to achieve compliance
    // think of this using the old 2010 pricing model and then multiply the answer by the poolInstanceMultiplier
    int expectedQuantityToAchieveCompliance = 1;
    while (expectedQuantityToAchieveCompliance * poolSockets < systemSockets) expectedQuantityToAchieveCompliance++;
    expectedQuantityToAchieveCompliance *= poolInstanceMultiplier;
    // assert the initial unsubscribed installed product status
    List<InstalledProduct> currentlyInstalledProducts = clienttasks.getCurrentlyInstalledProducts();
    List<String> providedProductIdsActuallyInstalled = new ArrayList<String>();
    for (String productId : poolProvidedProductIds) {
        InstalledProduct installedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", productId, currentlyInstalledProducts);
        if (installedProduct != null) {
            providedProductIdsActuallyInstalled.add(installedProduct.productId);
            // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386	covers -> supports
            List<String> expectedStatusDetails = Arrays.asList(new String[] { "Not supported by a valid subscription." });
            if (installedProduct.statusDetails.isEmpty())
                log.warning("Status Details appears empty.  Is your candlepin server older than 0.8.6?");
            Assert.assertEquals(installedProduct.status, "Not Subscribed", "Since we have not yet consumed an instance based entitlement, the status of installed product '" + installedProduct.productName + "' should be this value.");
            Assert.assertEquals(installedProduct.statusDetails, expectedStatusDetails, "Since we have not yet consumed an instance based entitlement, the status details of installed product '" + installedProduct.productName + "' is expected to be: " + expectedStatusDetails);
        }
    }
    // start subscribe testing
    if (systemIsGuest) {
        // virtual systems -----------------------------------------------------------------------------------
        // virtual systems will be allowed to consume 1 entitlement from the instance based pool and be compliant
        // regardless of sockets (this effectively satisfies the "either-or" behavior when a virtual system
        // consumes from the instance based pool - the quantity consumed decrements by one)
        clienttasks.subscribe(false, null, pool.poolId, null, null, "1", null, null, null, null, null, null, null);
        // assert the installed provided products are compliant
        currentlyInstalledProducts = clienttasks.getCurrentlyInstalledProducts();
        for (String productId : poolProvidedProductIds) {
            InstalledProduct installedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", productId, currentlyInstalledProducts);
            if (installedProduct != null) {
                Assert.assertEquals(installedProduct.status, "Subscribed", "After attaching 1 instance-based subscription to a virtual system, installed product '" + installedProduct.productName + "' should be immediately compliant.");
                Assert.assertTrue(installedProduct.statusDetails.isEmpty(), "Status Details for installed product '" + installedProduct.productName + "' should be empty.  Actual=" + installedProduct.statusDetails);
            }
        }
        // now let's unsubscribe from all entitlements and attempt auto-subscribing
        clienttasks.unsubscribe(true, (BigInteger) null, null, null, null, null, null);
        // but first, let's pretend that this virtual system is mapped so that we can avoid unmapped_guests_only pools during auto-subscribe
        factsMap.put("virt.uuid", "avoid-unmapped-guests-only");
        clienttasks.createFactsFileWithOverridingValues(factsMap);
        clienttasks.facts(null, true, null, null, null, null);
        clienttasks.mapSystemAsAGuestOfItself();
        // TEMPORARY WORKAROUND FOR BUG
        String bugId = "964332";
        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) {
            // issue a sacrificial autosubscribe call to get most of the entitlements attached.  If it times out, the post_auto_attach hooks will not get called
            clienttasks.subscribe_(true, null, (String) null, null, null, null, null, null, null, null, null, null, null);
        }
        // END OF WORKAROUND
        // attempt auto-subscribing
        clienttasks.subscribe(true, null, (String) null, null, null, null, null, null, null, null, null, null, null);
        // assert the quantity of consumption
        if (!providedProductIdsActuallyInstalled.isEmpty()) {
        /* These assertions are valid ONLY when this instance-based subscription pool is the ONLY one available that provides for all of the providedProductIdsActuallyInstalled (Not guarantee-able)
				ProductSubscription productSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("productName", pool.subscriptionName, clienttasks.getCurrentlyConsumedProductSubscriptions());
				Assert.assertNotNull(productSubscription, "Found a consumed product subscription to '"+pool.subscriptionName+"' after autosubscribing.");
				Assert.assertEquals(productSubscription.quantityUsed,Integer.valueOf(1),"Autosubscribing a virtual system with instance based products installed should only consume 1 quantity from the instance based pool.");
				*/
        } else
            log.warning("There are no installed product ids '" + poolProvidedProductIds + "' to assert compliance status of instance-based subscription '" + pool.subscriptionName + "'.");
        // assert the installed provided products are compliant after auto-subscribing
        currentlyInstalledProducts = clienttasks.getCurrentlyInstalledProducts();
        for (String productId : poolProvidedProductIds) {
            InstalledProduct installedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", productId, currentlyInstalledProducts);
            if (installedProduct != null) {
                Assert.assertEquals(installedProduct.status, "Subscribed", "After auto-subscribing a virtual system, installed product '" + installedProduct.productName + "' should be immediately compliant.");
                Assert.assertTrue(installedProduct.statusDetails.isEmpty(), "Status Details for installed product '" + installedProduct.productName + "' should be empty.  Actual=" + installedProduct.statusDetails);
            }
        }
    } else {
        // physical systems -----------------------------------------------------------------------------------
        // physical systems must consume entitlements from the instance based pool in quantities that are evenly
        // divisible by the instance_multiplier.  Moreover, sockets matter for compliance.
        // In addition (if host_limited with virt_limit), when a physical system consumes from the instance based
        // pool, a subpool with unlimited quantity available only to the guests on this physical system will be generated.
        // start by attempting to subscribe in quantities that are NOT evenly divisible by the instance_multiplier
        int quantityAttached = 0;
        for (int quantityAttempted = 0; quantityAttempted <= poolInstanceMultiplier + 1; quantityAttempted++) {
            SSHCommandResult sshCommandResult = clienttasks.subscribe_(false, null, pool.poolId, null, null, String.valueOf(quantityAttempted), null, null, null, null, null, null, null);
            // TEMPORARY WORKAROUND FOR BUG: 1183122 - rhsmd/subman dbus traceback on 'attach --pool'
            if (sshCommandResult.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 stdout/stderr/exitCode assertion from the prior subscribe command while bug '" + bugId + "' is open.");
                    if (quantityAttempted % poolInstanceMultiplier == 0)
                        quantityAttached += quantityAttempted;
                    continue;
                }
            }
            if (quantityAttempted == 0) {
                if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.13.8-1")) {
                    // post commit df95529a5edd0be456b3528b74344be283c4d258 bug 1119688
                    Assert.assertEquals(sshCommandResult.getStderr().trim(), "Error: Quantity must be a positive integer.", "The stderr from attempt to attach subscription '" + pool.subscriptionName + "' with quantity '" + quantityAttempted + "' which should be an error.");
                    Assert.assertEquals(sshCommandResult.getStdout().trim(), "", "The stdout from attempt to attach subscription '" + pool.subscriptionName + "' with quantity '" + quantityAttempted + "' which should be an error.");
                    Assert.assertEquals(sshCommandResult.getExitCode(), Integer.valueOf(64), /*EX_USAGE*/
                    "The exit code from attempt to attach subscription '" + pool.subscriptionName + "' with quantity '" + quantityAttempted + "' which should be an error.");
                } else {
                    Assert.assertEquals(sshCommandResult.getStdout().trim(), "Error: Quantity must be a positive integer.", "The stdout from attempt to attach subscription '" + pool.subscriptionName + "' with quantity '" + quantityAttempted + "' which should be an error.");
                    Assert.assertEquals(sshCommandResult.getStderr().trim(), "", "The stderr from attempt to attach subscription '" + pool.subscriptionName + "' with quantity '" + quantityAttempted + "' which should be an error.");
                    Assert.assertEquals(sshCommandResult.getExitCode(), Integer.valueOf(255), "The exit code from attempt to attach subscription '" + pool.subscriptionName + "' with quantity '" + quantityAttempted + "' which should be an error.");
                }
            } else if (quantityAttempted % poolInstanceMultiplier != 0) {
                String expectedStdout = String.format("Subscription '%s' must be attached using a quantity evenly divisible by %s", pool.subscriptionName, poolInstanceMultiplier);
                if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.3.1-1")) {
                    // commit 0d5fefcfa8c1c2485921d2dee6633879b1e06931 Correct incorrect punctuation in user messages
                    expectedStdout = String.format("Subscription \"%s\" must be attached using a quantity evenly divisible by %s", pool.subscriptionName, poolInstanceMultiplier);
                }
                // expected stdout message changed by Bug 1033365 - request to improve unfriendly message: Quantity '1' is not a multiple of instance multiplier '2'
                Assert.assertEquals(sshCommandResult.getStdout().trim(), expectedStdout, "The stdout from attempt to attach subscription '" + pool.subscriptionName + "' with quantity '" + quantityAttempted + "' which is not evenly divisible by the instance_multiplier '" + poolInstanceMultiplier + "'.");
                Assert.assertEquals(sshCommandResult.getStderr().trim(), "", "The stderr from attempt to attach subscription '" + pool.subscriptionName + "' with quantity '" + quantityAttempted + "' which is not evenly divisible by the instance_multiplier '" + poolInstanceMultiplier + "'.");
                Assert.assertEquals(sshCommandResult.getExitCode(), Integer.valueOf(1), /* TODO figure out if this is a bug.  should it be 255?*/
                "The exit code from attempt to attach subscription '" + pool.subscriptionName + "' with quantity '" + quantityAttempted + "' which is not evenly divisible by the instance_multiplier '" + poolInstanceMultiplier + "'.");
            } else {
                Assert.assertEquals(sshCommandResult.getStdout().trim(), String.format("Successfully attached a subscription for: %s", pool.subscriptionName), "The stdout from attempt to attach subscription '" + pool.subscriptionName + "' with quantity '" + quantityAttempted + "' which is evenly divisible by the instance_multiplier '" + poolInstanceMultiplier + "'.");
                Assert.assertEquals(sshCommandResult.getStderr().trim(), "", "The stderr from attempt to attach subscription '" + pool.subscriptionName + "' with quantity '" + quantityAttempted + "' which is evenly divisible by the instance_multiplier '" + poolInstanceMultiplier + "'.");
                Assert.assertEquals(sshCommandResult.getExitCode(), Integer.valueOf(0), "The exit code from attempt to attach subscription '" + pool.subscriptionName + "' with quantity '" + quantityAttempted + "' which is evenly divisible by the instance_multiplier '" + poolInstanceMultiplier + "'.");
                quantityAttached += quantityAttempted;
            }
        }
        // at this point the attempt to attach the instance based subscription should have been successful when the requested quantity was equal to the instance_multiplier
        ProductSubscription productSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("productName", pool.subscriptionName, clienttasks.getCurrentlyConsumedProductSubscriptions());
        Assert.assertNotNull(productSubscription, "Found a consumed product subscription to '" + pool.subscriptionName + "' after manually subscribing.");
        Assert.assertEquals(productSubscription.quantityUsed, Integer.valueOf(poolInstanceMultiplier), "The attached quantity of instance based subscription '" + pool.subscriptionName + "' in the list of consumed product subscriptions.");
        if (poolInstanceMultiplier >= expectedQuantityToAchieveCompliance) {
            // compliant when true
            // 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 + " indicating compliance.");
        } else {
            // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
            List<String> expectedStatusDetails = Arrays.asList(new String[] { String.format("Only supports %s of %s sockets.", (quantityAttached * poolSockets) / poolInstanceMultiplier, systemSockets) });
            if (productSubscription.statusDetails.isEmpty())
                log.warning("Status Details appears empty.  Is your candlepin server older than 0.8.6?");
            Assert.assertEquals(productSubscription.statusDetails, expectedStatusDetails, "Status Details for consumed product subscription '" + productSubscription.productName + "'.  Expected=" + expectedStatusDetails);
        }
        // at this point the installed product id should either be "Subscribed" or "Partially Subscribed" since one of the quantity attempts should have succeeded (when qty was equal to poolInstanceMultiplier), let's assert based on the system's sockets
        currentlyInstalledProducts = clienttasks.getCurrentlyInstalledProducts();
        for (String productId : poolProvidedProductIds) {
            InstalledProduct installedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", productId, currentlyInstalledProducts);
            if (installedProduct != null) {
                if (poolInstanceMultiplier >= expectedQuantityToAchieveCompliance) {
                    // compliant when true
                    Assert.assertEquals(installedProduct.status, "Subscribed", "After manually attaching a quantity of '" + poolInstanceMultiplier + "' subscription '" + pool.subscriptionName + "' covering '" + poolSockets + "' sockets with instance_multiplier '" + poolInstanceMultiplier + "', the status of installed product '" + installedProduct.productName + "' on a physical system with '" + systemSockets + "' cpu_socket(s) should be this.");
                    Assert.assertTrue(installedProduct.statusDetails.isEmpty(), "Status Details for installed product '" + installedProduct.productName + "' should be empty.  Actual=" + installedProduct.statusDetails);
                } else {
                    // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
                    List<String> expectedStatusDetails = Arrays.asList(new String[] { String.format("Only supports %s of %s sockets.", (quantityAttached * poolSockets) / poolInstanceMultiplier, systemSockets) });
                    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", "After manually attaching a quantity of '" + poolInstanceMultiplier + "' subscription '" + pool.subscriptionName + "' covering '" + poolSockets + "' sockets with instance_multiplier '" + poolInstanceMultiplier + "', the status of installed product '" + installedProduct.productName + "' on a physical system with '" + systemSockets + "' cpu_socket(s) should be this.");
                    Assert.assertEquals(installedProduct.statusDetails, expectedStatusDetails, "Status Details for installed product '" + installedProduct.productName + " should be this value: " + expectedStatusDetails);
                }
            }
        }
        // now let's attempt autosubscribing which should complete the stack
        // CAUTION: attempting to autosubscribe to fill a stack of this instance-based pool will work ONLY when this instance-based subscription pool is the ONLY one available that provides for all of the providedProductIdsActuallyInstalled (Not guarantee-able).  However if a second pool with the same stacking_id is consumed, then this assert may work.
        clienttasks.subscribe(true, null, (String) null, null, null, null, null, null, null, null, null, null, null);
        // assert the total quantity of consumption
        if (!providedProductIdsActuallyInstalled.isEmpty()) {
            /* The following algorithm neglects the case when multiple subscriptions by different names provide the installed products providedProductIdsActuallyInstalled.
				List<ProductSubscription> productSubscriptions = ProductSubscription.findAllInstancesWithMatchingFieldFromList("productName", pool.subscriptionName, clienttasks.getCurrentlyConsumedProductSubscriptions());
				Assert.assertTrue(!productSubscriptions.isEmpty(), "Found at least one consumed product subscription to '"+pool.subscriptionName+"' after auto-subscribing.");
				Integer totalQuantityUsed = 0;
				for (ProductSubscription prodSub : productSubscriptions) {
					totalQuantityUsed += prodSub.quantityUsed;
					Assert.assertTrue(prodSub.statusDetails.isEmpty(),"Status Details of auto-attached subscription '"+pool.subscriptionName+"' covering '"+poolSockets+"' sockets with instance_multiplier '"+poolInstanceMultiplier+"' expected to achieve compliance of provided products '"+providedProductIdsActuallyInstalled+"' installed on a physical system with '"+systemSockets+"' cpu_socket(s) should be empty.  Actual="+prodSub.statusDetails);
				}
				Assert.assertEquals(totalQuantityUsed,Integer.valueOf(expectedQuantityToAchieveCompliance),"Quantity of auto-attached subscription '"+pool.subscriptionName+"' covering '"+poolSockets+"' sockets with instance_multiplier '"+poolInstanceMultiplier+"' expected to achieve compliance of provided products '"+providedProductIdsActuallyInstalled+"' installed on a physical system with '"+systemSockets+"' cpu_socket(s) should be this.");
				Re-implementing a new algorithm below to count the number of system sockets covered and then assert that the autosubscribe successfully met coverage without excess over consumption...*/
            // goal
            boolean assertStackedQuantityOfConsumption = true;
            String stackingId = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "stacking_id");
            int numPoolsWithSameStackingId = 0;
            // among the consumed product subscriptions, this is the total stacked accumulation of socket coverage
            float totalSocketsCovered = 0;
            // this is the maximum sockets attribute among the pools that provide for the installed products poolProvidedProductIds
            Integer maxIncrementOfPhysicalSocketCoverage = new Integer(0);
            // List<ProductSubscription> productSubscriptions = new ArrayList<ProductSubscription>();
            for (ProductSubscription prodSub : clienttasks.getCurrentlyConsumedProductSubscriptions()) {
                List<String> thisPoolProvidedProductIds = CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, prodSub.poolId);
                if (doesListOverlapList(thisPoolProvidedProductIds, providedProductIdsActuallyInstalled)) {
                    // deugTesting
                    // if (CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, prodSub.poolId, "instance_multiplier")==null)  { // does not have an "instance_multiplier"
                    // log.warning("Ignoring this consumed product subscription's contribution to compliance (it has no instance_multiplier): "+prodSub);	//  not sure if this is the right choice
                    // continue;
                    // }
                    // the consumed quantity from this pool contributes to the socket coverage for installed products poolProvidedProductIds
                    String thisPoolInstanceMultiplierAsString = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, prodSub.poolId, "instance_multiplier");
                    String thisPoolSocketsAsString = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, prodSub.poolId, "sockets");
                    // catching CAUTION case when autosubscribe grants a secondary entitlement unrelated to the already subscribed instance-based subscription
                    if (thisPoolInstanceMultiplierAsString == null) {
                        assertStackedQuantityOfConsumption = false;
                        // effectively true and a workaround that will prevent a null pointer in the calculations below
                        thisPoolInstanceMultiplierAsString = "1";
                    }
                    // catching CAUTION case when autosubscribe grants a secondary entitlement unrelated to the already subscribed instance-based subscription
                    if (thisPoolSocketsAsString == null) {
                        assertStackedQuantityOfConsumption = false;
                        // effectively true and a workaround that will prevent a null pointer in the calculations below
                        thisPoolSocketsAsString = String.valueOf(systemSockets);
                    }
                    Integer thisPoolInstanceMultiplier = Integer.valueOf(thisPoolInstanceMultiplierAsString);
                    Integer thisPoolSockets = Integer.valueOf(thisPoolSocketsAsString);
                    String thisPoolStackingId = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, prodSub.poolId, "stacking_id");
                    maxIncrementOfPhysicalSocketCoverage = Math.max(maxIncrementOfPhysicalSocketCoverage, thisPoolSockets);
                    float socketsCoveredByThisPool = prodSub.quantityUsed.floatValue() * thisPoolSockets.floatValue() / thisPoolInstanceMultiplier.floatValue();
                    log.info("Attached product subscription '" + prodSub.productName + "' with quantity '" + prodSub.quantityUsed + "' contributes to '" + socketsCoveredByThisPool + "' cpu_socket(s) of coverage.");
                    totalSocketsCovered += socketsCoveredByThisPool;
                    // 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(prodSub.statusDetails, expectedStatusDetails, "Status Details of auto-attached subscription '" + prodSub.productName + "' covering '" + thisPoolSockets + "' sockets with instance_multiplier '" + thisPoolInstanceMultiplier + "' expected to contribute to the full compliance of provided products '" + providedProductIdsActuallyInstalled + "' installed on a physical system with '" + systemSockets + "' cpu_socket(s) should indicate compliance.  Actual=" + prodSub.statusDetails);
                    // catching the CAUTION case when a secondary pool may not provide its own completed socket coverage stack for the installed products.
                    if (!stackingId.equals(thisPoolStackingId)) {
                        log.warning("Cannot assert the attempt to autosubscribe completed the socket stack because it appears that an entitlement from a second pool SKU '" + prodSub.productId + "' was granted that does not share the same stacking_id '" + stackingId + "' as instance-based pool '" + pool.productId + "' '" + pool.subscriptionName + "'.  Consequently, excess entitlement consumption has probably occurred.");
                        assertStackedQuantityOfConsumption = false;
                        // instead, assert that this product subscription provided it's own full stack
                        Assert.assertTrue(systemSockets + maxIncrementOfPhysicalSocketCoverage > socketsCoveredByThisPool && socketsCoveredByThisPool >= systemSockets, "After autosubscribing to complete a stacked quantity of subscriptions providing for installed product ids '" + providedProductIdsActuallyInstalled + "', the total cpu_socket(s) coverage of '" + socketsCoveredByThisPool + "' should minimally satistfy the system's physical socket count of '" + systemSockets + "' cpu_socket(s) within '" + maxIncrementOfPhysicalSocketCoverage + "' sockets of excess coverage (assuming that entitlements from ONLY this product subscription '" + prodSub.productId + "' '" + prodSub.productName + "' contributed to stack '" + thisPoolStackingId + "'.).");
                    } else
                        numPoolsWithSameStackingId++;
                }
            }
            if (assertStackedQuantityOfConsumption)
                Assert.assertTrue(systemSockets + maxIncrementOfPhysicalSocketCoverage > totalSocketsCovered && totalSocketsCovered >= systemSockets, "After autosubscribing to complete a stacked quantity of subscriptions providing for installed product ids '" + providedProductIdsActuallyInstalled + "', the total cpu_socket(s) coverage of '" + totalSocketsCovered + "' should minimally satistfy the system's physical socket count of '" + systemSockets + "' cpu_socket(s) within '" + maxIncrementOfPhysicalSocketCoverage + "' sockets of excess coverage (entitlements from '" + numPoolsWithSameStackingId + "' pools contributed to this stack).");
        } else
            log.warning("There are no installed product ids '" + poolProvidedProductIds + "' to assert compliance status of instance-based subscription '" + pool.subscriptionName + "'.");
        // assert the installed provided products are compliant
        currentlyInstalledProducts = clienttasks.getCurrentlyInstalledProducts();
        for (String productId : poolProvidedProductIds) {
            InstalledProduct installedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", productId, currentlyInstalledProducts);
            if (installedProduct != null) {
                Assert.assertEquals(installedProduct.status, "Subscribed", "After auto-subscribing a physical system, installed product '" + installedProduct.productName + "' should be compliant.");
                Assert.assertTrue(installedProduct.statusDetails.isEmpty(), "Status Details for installed product '" + installedProduct.productName + "' should be empty.  Actual=" + installedProduct.statusDetails);
            }
        }
        // do some more testing when the pool is host limited and virt limited...
        if (CandlepinTasks.isPoolProductHostLimited(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId) && CandlepinTasks.isPoolProductVirtLimited(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId)) {
            // now we can assert that a host_limited subpool was generated from consumption of this physical pool and is only available to guests of this physical system
            // first, let's flip the virt.is_guest to true and assert that the virtual guest subpool is not (yet) available since the virtUuid is not on the host consumer's list of guestIds
            // factsMap.clear(); // do not clear since it will already contain cpu.cpu_socket(s)
            factsMap.put("virt.is_guest", String.valueOf(true));
            clienttasks.createFactsFileWithOverridingValues(factsMap);
            clienttasks.facts(null, true, null, null, null, null);
            List<SubscriptionPool> availableInstanceBasedSubscriptionPools = SubscriptionPool.findAllInstancesWithMatchingFieldFromList("productId", pool.productId, clienttasks.getCurrentlyAllAvailableSubscriptionPools());
            for (SubscriptionPool availableInstanceBasedSubscriptionPool : availableInstanceBasedSubscriptionPools) {
                if (!CandlepinTasks.isPoolRestrictedToUnmappedVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, availableInstanceBasedSubscriptionPool.poolId)) {
                    Assert.assertEquals(availableInstanceBasedSubscriptionPool.machineType, "Physical", "Only physical pools to '" + pool.subscriptionName + "' (poolId=" + availableInstanceBasedSubscriptionPool.poolId + ") should be available to a guest system when its virt_uuid is not on the host's list of guestIds (unless it is an unmapped_guests_only pool).");
                } else {
                    Assert.assertEquals(availableInstanceBasedSubscriptionPool.machineType, "Virtual", "Only unmapped_guests_only virtual pools to '" + pool.subscriptionName + "' (poolId=" + availableInstanceBasedSubscriptionPool.poolId + ") should be available to a guest system when its virt_uuid is not on the host's list of guestIds.");
                }
            }
            // now fake this consumer's facts and guestIds to make it think it is a guest of itself (a trick for testing)
            factsMap.put("virt.uuid", "fake-virt-uuid");
            clienttasks.createFactsFileWithOverridingValues(factsMap);
            clienttasks.facts(null, true, null, null, null, null);
            clienttasks.mapSystemAsAGuestOfItself();
            // now the host_limited subpool for this virtual system should be available
            availableInstanceBasedSubscriptionPools = SubscriptionPool.findAllInstancesWithMatchingFieldFromList("productId", pool.productId, clienttasks.getCurrentlyAvailableSubscriptionPools());
            availableInstanceBasedSubscriptionPools = SubscriptionPool.findAllInstancesWithMatchingFieldFromList("machineType", "Virtual", availableInstanceBasedSubscriptionPools);
            Assert.assertTrue(!availableInstanceBasedSubscriptionPools.isEmpty(), "Host_limited Virtual subpool to instance based subscription '" + pool.subscriptionName + "' is available to its guest.");
            Assert.assertEquals(availableInstanceBasedSubscriptionPools.size(), 1, "Only one host_limited Virtual subpool to instance based subscription '" + pool.subscriptionName + "' is available to its guest.");
            Assert.assertEquals(availableInstanceBasedSubscriptionPools.get(0).quantity, poolVirtLimit, "The quantity of entitlements from the host_limited Virtual subpool to instance based subscription '" + pool.subscriptionName + "' should be equal to the subscription's virt_limit '" + poolVirtLimit + "'.");
            // consume an entitlement from the subPool so that we can test Bug 1000444
            SubscriptionPool subSubscriptionPool = availableInstanceBasedSubscriptionPools.get(0);
            // clienttasks.subscribeToSubscriptionPool(subSubscriptionPool);
            clienttasks.subscribe_(false, null, subSubscriptionPool.poolId, null, null, "1", null, null, null, null, null, null, null);
            ProductSubscription subProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("poolId", subSubscriptionPool.poolId, clienttasks.getCurrentlyConsumedProductSubscriptions());
            // assert Bug 1000444 - Instance based subscription on the guest gets merged with other subscription when a future instance based subscription is added on the host
            // TEMPORARY WORKAROUND
            boolean invokeWorkaroundWhileBugIsOpen = true;
            // Bug 1256926 - Instance Based pool appears to be providing extra products than expected
            String bugId = "1256926";
            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("while bug '" + bugId + "' is open, skipping assertion: The list of provided products from the consumed subpool '" + subProductSubscription.poolId + "' " + subProductSubscription.provides + " should be a superset of the provided products from the consumed hostpool '" + pool.poolId + "' " + pool.provides + ".");
            } else
                // END OF WORKAROUND
                Assert.assertTrue(subProductSubscription.provides.containsAll(pool.provides), /*DELETEME && pool.provides.containsAll(subProductSubscription.provides)*/
                "The list of provided products from the consumed subpool '" + subProductSubscription.poolId + "' " + subProductSubscription.provides + " should be a superset of the provided products from the consumed hostpool '" + pool.poolId + "' " + pool.provides + ".  (Superset because a another pool with the same stacking_id could have been auto consumed earlier in this test that provides additional products that were added to the one-sub-pool-per-stack subpool '" + subProductSubscription.poolId + "'.)");
            clienttasks.unsubscribe_(false, subProductSubscription.serialNumber, null, null, null, null, null);
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) BigInteger(java.math.BigInteger) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) InstalledProduct(rhsm.data.InstalledProduct) SubscriptionPool(rhsm.data.SubscriptionPool) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 75 with BugzillaAPIException

use of com.redhat.qe.auto.bugzilla.BugzillaAPIException in project rhsm-qe by RedHatQE.

the class DataCenterTests method testAvailabilityOfDerivedProductSubpools.

// 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-19987", "RHEL7-33089" }, 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 data center pool, consume it and assert that a pool for the derivedProduct is generated and available only to its guests", groups = { "Tier1Tests", "VerifyAvailabilityOfDerivedProductSubpools_Test" }, dataProvider = "getAvailableDataCenterSubscriptionPoolsData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testAvailabilityOfDerivedProductSubpools(Object bugzilla, /*Boolean systemIsGuest, Integer systemSockets,*/
SubscriptionPool pool) throws NumberFormatException, JSONException, Exception {
    String expectedTemporaryPoolIndicator = " (Temporary)";
    // make sure we are unsubscribed from all subscriptions
    // clienttasks.unsubscribe(true, (BigInteger)null, null, null, null);
    // unsubscribe this way to ensure the newest serial is removed first
    clienttasks.unsubscribeFromTheCurrentlyConsumedSerialsCollectively();
    // get some attributes from the subscription pool
    String poolDerivedProductId = (String) CandlepinTasks.getPoolValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "derivedProductId");
    String poolDerivedProductName = (String) CandlepinTasks.getPoolValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "derivedProductName");
    String poolDerivedProductArch = (String) CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "arch");
    // Note: the arch attribute can be a comma separated list of values
    List<String> poolDerivedProductArches = new ArrayList<String>(Arrays.asList(poolDerivedProductArch.trim().split(" *, *")));
    List<String> poolDerivedProvidedProductIds = CandlepinTasks.getPoolDerivedProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId);
    String poolVirtLimit = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "virt_limit");
    List<String> poolProvidedProductIds = CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId);
    // TEMPORARY WORKAROUND FOR BUG
    if (sm_serverType.equals(CandlepinType.hosted)) {
        // Bug 1214001 - after stage refresh, Virtual Data Center SKUs no longer have a host_limited pool productAttributes
        String bugId = "1214001";
        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) {
            throw new SkipException("Skipping this Virtual Data Center test against SKU '" + pool.productId + "' while bug '" + bugId + "' is open.");
        }
    }
    // TEMPORARY WORKAROUND FOR BUG
    if (sm_serverType.equals(CandlepinType.hosted)) {
        // Bug 1261193 - Datacenter subscriptions in stage candlepin-0.9.51.5-1 should create Temporary pools for their derived products
        String bugId = "1261193";
        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) {
            throw new SkipException("Skipping this Virtual Data Center test against SKU '" + pool.productId + "' while bug '" + bugId + "' is open.");
        }
    }
    // END OF WORKAROUND
    // assert that this virtual data center SKU is host_limited
    Assert.assertTrue(CandlepinTasks.isPoolProductHostLimited(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId), "As a functional requirement for Virtual Data Center SKUs, asserting that the pool's productAttributes contains host_limited=true so that a subscription pool for derivedProductId '" + poolDerivedProductId + "' is available ONLY to mapped virtual guests.");
    // assert that the derivedProductId is different from the host pool's productId
    Assert.assertTrue(!pool.productId.equals(poolDerivedProductId), "The host pool's data center subscription product Id '" + pool.productId + "' should be different than its derived pool's product Id '" + poolDerivedProductId + "'.");
    // NOT NECESSARILY TRUE		// assert that the derivedProductName is different from the host pool's subscription name
    // NOT NECESSARILY TRUE		Assert.assertNotSame(pool.subscriptionName, poolDerivedProductName, "The host pool's data center subscription name '"+pool.subscriptionName+"' should be different than its derived pool's product name '"+poolDerivedProductName+"'.");
    // instrument the system facts to behave as a physical host
    factsMap.put("virt.is_guest", String.valueOf(false));
    clienttasks.createFactsFileWithOverridingValues(factsMap);
    // update facts
    clienttasks.facts(null, true, null, null, null, null);
    // reset a few fake guest ids for this host consumer
    String systemUuid = clienttasks.getCurrentConsumerId();
    // [root@jsefler-5 ~]# curl -k -u testuser1:password --request PUT --data '{"guestIds":["e6f55b91-aae1-44d6-f0db-c8f25ec73ef5","abcd"]}' --header 'accept:application/json' --header 'content-type: application/json' https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/consumers/d2ee0c6e-a57d-4e37-8be3-228a44ca2739
    JSONObject jsonConsumer = CandlepinTasks.setGuestIdsForConsumer(sm_clientUsername, sm_clientPassword, sm_serverUrl, systemUuid, Arrays.asList(new String[] { "abc", "def" }));
    // assert that only Physical pools are available for consumption for this data center sku
    for (SubscriptionPool subscriptionPool : SubscriptionPool.findAllInstancesWithMatchingFieldFromList("productId", pool.productId, clienttasks.getCurrentlyAllAvailableSubscriptionPools())) {
        Assert.assertEquals(subscriptionPool.machineType, "Physical", "Only physical pools to '" + pool.productId + "' should be available to a physical host system.");
    }
    // subscribe the host to the data center pool
    File hostEntitlementFile = clienttasks.subscribeToSubscriptionPool(pool, /*sm_serverAdminUsername*/
    sm_clientUsername, /*sm_serverAdminPassword*/
    sm_clientPassword, sm_serverUrl);
    EntitlementCert hostEntitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(hostEntitlementFile);
    client.runCommandAndWait("rct cat-cert " + hostEntitlementFile);
    // the following general asserts are not true against a production datacenter SKU...
    if (false) {
        // Subscription Name: Red Hat Enterprise Linux for Virtual Datacenters, Premium
        // Provides:          Red Hat Enterprise Linux Atomic Host
        // SKU:               RH00001
        // Contract:          10472273
        // Pool ID:           8a99f98146b4fa9d0146b5d3c0005253
        // Available:         98
        // Suggested:         1
        // Service Level:     Premium
        // Service Type:      L1-L3
        // Subscription Type: Stackable
        // Ends:              12/30/2014
        // System Type:       Physical
        // in general the data center pool will not provide any engineering products
        Assert.assertTrue(poolProvidedProductIds.isEmpty(), "In general, a data center product subscription will not provide any engineering products (productId= '" + pool.productId + "').  Asserting the providedProducts from the subscription is empty...");
        Assert.assertTrue(hostEntitlementCert.productNamespaces.isEmpty(), "In general, a data center product subscription will not provide any engineering products (productId= '" + pool.productId + "').  Asserting the productNamespaces from the granted entitlement are empty...");
        // in general the data center pool will not provide any content
        Assert.assertTrue(hostEntitlementCert.contentNamespaces.isEmpty(), "In general, a data center product subscription will not provide any content sets (productId= '" + pool.productId + "').");
    }
    // assert that the derivedProductId is NOT available to the Physical host system
    List<SubscriptionPool> availablePoolsForDerivedProductId = SubscriptionPool.findAllInstancesWithMatchingFieldFromList("productId", poolDerivedProductId, clienttasks.getCurrentlyAllAvailableSubscriptionPools());
    Assert.assertTrue(availablePoolsForDerivedProductId.isEmpty(), "A subpool for the derivedProductId '" + poolDerivedProductId + "' should NOT be available to the host after (or before) it consumes the data center product subscription.");
    // now we can assert that a host_limited subpool was generated from consumption of this physical pool and is only available to guests of this physical system
    // first, let's flip the virt.is_guest to true and assert that the virtual guest subpool is not (yet) available since the virtUuid is not on the host consumer's list of guestIds
    factsMap.put("virt.is_guest", String.valueOf(true));
    clienttasks.createFactsFileWithOverridingValues(factsMap);
    // update facts
    clienttasks.facts(null, true, null, null, null, null);
    availablePoolsForDerivedProductId = SubscriptionPool.findAllInstancesWithMatchingFieldFromList("productId", poolDerivedProductId, clienttasks.getCurrentlyAllAvailableSubscriptionPools());
    if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, "<", "0.9.45-1")) {
        // this assertion was valid prior to introduction of Temporary pools for unmapped guests
        Assert.assertTrue(availablePoolsForDerivedProductId.isEmpty(), "A subpool for the derivedProductId '" + poolDerivedProductId + "' should NOT be available to a guest system when its virt_uuid is not on the host's list of guestIds.");
    } else {
        // this assertion is valid after the introduction of Temporary pools for unmapped guests
        Assert.assertTrue(!availablePoolsForDerivedProductId.isEmpty(), "Starting with candlepin version 0.9.45-1, a temporary subpool for the derivedProductId '" + poolDerivedProductId + "' should NOW be available to a guest system when its virt_uuid is not on the host's list of guestIds.");
        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
            for (SubscriptionPool subscriptionPool : availablePoolsForDerivedProductId) {
                Assert.assertTrue(subscriptionPool.subscriptionType.endsWith(expectedTemporaryPoolIndicator), "Starting with candlepin version 0.9.47-1, a temporary subpool (indicated by subscription type ending in '" + expectedTemporaryPoolIndicator + "') for the derivedProductId '" + poolDerivedProductId + "' should NOW be available to a guest system when its virt_uuid is not on the host's list of guestIds: " + subscriptionPool);
            }
        }
    }
    // now fake this consumer's facts and guestIds to make it think it is a guest of itself (a trick for testing)
    factsMap.put("virt.uuid", systemUuid);
    clienttasks.createFactsFileWithOverridingValues(factsMap);
    // update facts
    clienttasks.facts(null, true, null, null, null, null);
    // [root@jsefler-5 ~]# curl -k -u testuser1:password --request PUT --data '{"guestIds":["e6f55b91-aae1-44d6-f0db-c8f25ec73ef5","abcd"]}' --header 'accept:application/json' --header 'content-type: application/json' https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/consumers/d2ee0c6e-a57d-4e37-8be3-228a44ca2739
    jsonConsumer = CandlepinTasks.setGuestIdsForConsumer(sm_clientUsername, sm_clientPassword, sm_serverUrl, systemUuid, Arrays.asList(new String[] { "abc", systemUuid, "def" }));
    // now the host_limited subpool to the derivedProductId for this virtual system should be available
    availablePoolsForDerivedProductId = SubscriptionPool.findAllInstancesWithMatchingFieldFromList("productId", poolDerivedProductId, clienttasks.getCurrentlyAllAvailableSubscriptionPools());
    Assert.assertTrue(!availablePoolsForDerivedProductId.isEmpty(), "Host_limited subpool from data center product id '" + pool.productId + "' to derived product id '" + poolDerivedProductId + "' is available to its guest.");
    Assert.assertEquals(availablePoolsForDerivedProductId.size(), 1, "Only one host_limited subpool to derived product id '" + poolDerivedProductId + "' is available to its guest.");
    SubscriptionPool derivedPool = availablePoolsForDerivedProductId.get(0);
    Assert.assertTrue(!derivedPool.subscriptionType.endsWith(expectedTemporaryPoolIndicator), "The host_limited subpool to derived product id '" + poolDerivedProductId + "' available to its guest should NOT indicate that the subscription type '" + derivedPool.subscriptionType + "' is temporary.");
    Assert.assertEquals(derivedPool.subscriptionName, poolDerivedProductName, "Subscription name for the derived product id '" + poolDerivedProductId + "'.");
    Assert.assertEquals(derivedPool.quantity.toLowerCase(), poolVirtLimit, "The quantity of entitlements from the host_limited subpool to derived product subscription '" + poolDerivedProductName + "' should be the same as the host data center subscription's virt_limit '" + poolVirtLimit + "'.");
    // now subscribe to the derived subpool and we'll assert the entitlement values come from the derived product and not the originating data center subscription
    // subscribe the guest to the derived product subscription
    File derivedEntitlementFile = clienttasks.subscribeToSubscriptionPool(derivedPool, /*sm_serverAdminUsername*/
    sm_clientUsername, /*sm_serverAdminPassword*/
    sm_clientPassword, sm_serverUrl);
    EntitlementCert derivedEntitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(derivedEntitlementFile);
    client.runCommandAndWait("rct cat-cert " + derivedEntitlementFile);
    // assert all of the derived provided products are included in the entitlement
    List<String> actualDerivedProvidedProductIds = new ArrayList<String>();
    for (ProductNamespace productNamespace : derivedEntitlementCert.productNamespaces) {
        actualDerivedProvidedProductIds.add(productNamespace.id);
    }
    Assert.assertTrue(actualDerivedProvidedProductIds.containsAll(poolDerivedProvidedProductIds) && poolDerivedProvidedProductIds.containsAll(actualDerivedProvidedProductIds), "The actual product ids " + actualDerivedProvidedProductIds + " provided by an entitlement cert from the derived subpool '" + derivedPool.subscriptionName + "' match the expected derivedProvidedProducts " + poolDerivedProvidedProductIds + " from the data center subscription '" + pool.subscriptionName + "'.");
    // assert the derivedProductAttributes are reflected in the entitlement cert granted from the derived subpool
    // Order:											Order:
    // Name: Awesome OS Server Basic (data center)		Name: Awesome OS Server Basic (dc-virt)
    // Number: order-8675309							Number: order-8675309
    // SKU: awesomeos-server-basic-dc					SKU: awesomeos-server-basic-vdc
    // Contract: 18									Contract: 18
    // Account: 12331131231							Account: 12331131231
    // Service Level: None								Service Level: Full-Service
    // Service Type: Self-Support						Service Type: Drive-Through
    // Quantity: 5										Quantity: 5
    // Quantity Used: 1								Quantity Used: 1
    // Socket Limit: 4									Socket Limit: 2
    // RAM Limit: 										RAM Limit: 2
    // Core Limit: 									Core Limit: 4
    // Virt Limit: 									Virt Limit:
    // Virt Only: False								Virt Only: True
    // Subscription: 									Subscription:
    // Stacking ID: 									Stacking ID:
    // Warning Period: 30								Warning Period: 0
    // Provides Management: False						Provides Management: False
    // Name: Awesome OS Server Basic (data center)		Name: Awesome OS Server Basic (dc-virt)
    Assert.assertEquals(hostEntitlementCert.orderNamespace.productName, pool.subscriptionName, "hostEntitlementCert.orderNamespace.productName should match the data center pool's subscription name");
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.productName, poolDerivedProductName, "derivedEntitlementCert.orderNamespace.productName should match the derivedProductName");
    // Number: order-8675309							Number: order-8675309
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.orderNumber, hostEntitlementCert.orderNamespace.orderNumber, "Order Number from the derived entitlement should match the host entitlement");
    // SKU: awesomeos-server-basic-dc					SKU: awesomeos-server-basic-vdc
    Assert.assertEquals(hostEntitlementCert.orderNamespace.productId, pool.productId, "hostEntitlementCert.orderNamespace.productId should match the data center pool's productId");
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.productId, poolDerivedProductId, "derivedEntitlementCert.orderNamespace.productId should match the derivedProductId");
    // Contract: 18									Contract: 18
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.contractNumber, hostEntitlementCert.orderNamespace.contractNumber, "Contract Number from the derived entitlement should match the host entitlement");
    // Account: 12331131231							Account: 12331131231
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.accountNumber, hostEntitlementCert.orderNamespace.accountNumber, "Account Number from the derived entitlement should match the host entitlement");
    // Service Level: None								Service Level: Full-Service
    Assert.assertEquals(hostEntitlementCert.orderNamespace.supportLevel, pool.serviceLevel, "hostEntitlementCert.orderNamespace.supportLevel should match the data center pool's serviceLevel");
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.supportLevel, CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "support_level"), "derivedEntitlementCert.orderNamespace.supportLevel should match the derivedProductAttribute support_level");
    // Service Type: Self-Support						Service Type: Drive-Through
    Assert.assertEquals(hostEntitlementCert.orderNamespace.supportType, pool.serviceType, "hostEntitlementCert.orderNamespace.supportType should match the data center pool's serviceType");
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.supportType, CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "support_type"), "derivedEntitlementCert.orderNamespace.supportType should match the derivedProductAttribute support_type");
    // Quantity: 5										Quantity: 5
    JSONObject jsonPool = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/pools/" + pool.poolId));
    Assert.assertEquals(hostEntitlementCert.orderNamespace.quantity, String.valueOf(jsonPool.getInt("quantity")), "hostEntitlementCert.orderNamespace.quantity should match the data center subscription pool's total quantity");
    // TEMPORARY WORKAROUND FOR BUG
    String bugId = "983193";
    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) {
        log.warning("Skipping the assertion of quantity while bug '" + bugId + "' is open.");
    } else {
        // END OF WORKAROUND
        if (// Bug 1011961 - rct cat-cert should display "Unlimited" for Quantity instead of "-1";  subscription-manager commit 7554c869608a0276151993d34fee4ddb54185f7a
        clienttasks.isPackageVersion("subscription-manager", "<", "1.10.3-1") && derivedEntitlementCert.orderNamespace.quantity.equals("-1")) // Bug 1011961 - rct cat-cert should display "Unlimited" for Quantity instead of "-1";  subscription-manager commit 7554c869608a0276151993d34fee4ddb54185f7a
        {
            log.warning("The rct cat-cert tool encountered a Quantity of -1 which is fixed in subscription-manager-1.10.3-1.  Skipping assertion.");
        } else
            Assert.assertEquals(derivedEntitlementCert.orderNamespace.quantity, derivedPool.quantity, "derivedEntitlementCert.orderNamespace.quantity should match the derivedPool's quantity");
    }
    // Quantity Used: 1								Quantity Used: 1
    // TODO for derivedEntitlementCert only
    // Socket Limit: 4									Socket Limit: 2
    Assert.assertEquals(hostEntitlementCert.orderNamespace.socketLimit, CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "sockets"), "hostEntitlementCert.orderNamespace.socketLimit should match the data center pool's productAttribute sockets");
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.socketLimit, CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "sockets"), "derivedEntitlementCert.orderNamespace.socketLimit should match the derivedProductAttribute sockets");
    // RAM Limit: 										RAM Limit: 2
    Assert.assertEquals(hostEntitlementCert.orderNamespace.ramLimit, CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "ram"), "hostEntitlementCert.orderNamespace.ramLimit should match the data center pool's productAttribute ram");
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.ramLimit, CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "ram"), "derivedEntitlementCert.orderNamespace.ramLimit should match the derivedProductAttribute ram");
    // Core Limit: 									Core Limit: 4
    Assert.assertEquals(hostEntitlementCert.orderNamespace.coreLimit, CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "cores"), "hostEntitlementCert.orderNamespace.coreLimit should match the data center pool's productAttribute cores");
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.coreLimit, CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "cores"), "derivedEntitlementCert.orderNamespace.coreLimit should match the derivedProductAttribute cores");
    // Virt Limit: 									Virt Limit:
    // TODO ignoring for now based on https://bugzilla.redhat.com/show_bug.cgi?id=983193#c2
    // Virt Only: False								Virt Only: True
    String virtOnly = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "virt_only");
    Assert.assertEquals(hostEntitlementCert.orderNamespace.virtOnly, virtOnly == null ? Boolean.valueOf(false) : Boolean.valueOf(virtOnly), "hostEntitlementCert.orderNamespace.virtOnly should match the data center pool's productAttribute virt_only");
    // CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "virt_only");
    virtOnly = String.valueOf(true);
    /* the derived pool virt_only should ALWAYS be true */
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.virtOnly, virtOnly == null ? Boolean.valueOf(false) : Boolean.valueOf(virtOnly), "derivedEntitlementCert.orderNamespace.virtOnly should match the derivedProductAttribute virt_only");
    // Subscription: 									Subscription:
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.subscriptionNumber, hostEntitlementCert.orderNamespace.subscriptionNumber, "Subscription from the derived entitlement should match the host entitlement");
    // Stacking ID: 									Stacking ID:
    Assert.assertEquals(hostEntitlementCert.orderNamespace.stackingId, CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "stacking_id"), "hostEntitlementCert.orderNamespace.stackingId should match the data center pool's productAttribute stacking_id");
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.stackingId, CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "stacking_id"), "derivedEntitlementCert.orderNamespace.stackingId should match the derivedProductAttribute stacking_id");
    // Warning Period: 30								Warning Period: 0
    String warningPeriod = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "warning_period");
    Assert.assertEquals(hostEntitlementCert.orderNamespace.warningPeriod, warningPeriod == null ? "0" : warningPeriod, "hostEntitlementCert.orderNamespace.warningPeriod should match the data center pool's productAttribute warning_period");
    warningPeriod = CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "warning_period");
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.warningPeriod, warningPeriod == null ? "0" : warningPeriod, "derivedEntitlementCert.orderNamespace.warningPeriod should match the derivedProductAttribute warning_period");
    // Provides Management: False						Provides Management: False
    String providesManagement = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "management_enabled");
    Assert.assertEquals(hostEntitlementCert.orderNamespace.providesManagement, providesManagement == null ? Boolean.valueOf(false) : Boolean.valueOf(providesManagement), "hostEntitlementCert.orderNamespace.providesManagement should match the data center pool's productAttribute management_enabled");
    providesManagement = CandlepinTasks.getPoolDerivedProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "management_enabled");
    Assert.assertEquals(derivedEntitlementCert.orderNamespace.providesManagement, providesManagement == null ? Boolean.valueOf(false) : Boolean.valueOf(providesManagement), "derivedEntitlementCert.orderNamespace.providesManagement should match the derivedProductAttribute management_enabled");
    // for the sake of cleanup and to avoid this candlepin errors, let's unsubscribe from derivedEntitlementCert and then hostEntitlementCert
    // ssh root@jsefler-6server.usersys.redhat.com subscription-manager unregister
    // Stdout: Runtime Error No row with the given identifier exists: [org.candlepin.model.ProvidedProduct#8a90869341e61f7c0141e84e9ade3efd] at org.hibernate.UnresolvableObjectException.throwIfNull:65
    // Stderr:
    // ExitCode: 255
    // 
    // ssh root@jsefler-6server.usersys.redhat.com subscription-manager unsubscribe --all
    // Stdout:
    // Stderr: Runtime Error No row with the given identifier exists: [org.candlepin.model.DerivedProvidedProduct#8a90869341e61f7c0141e84f2b9a3f0e] at org.hibernate.UnresolvableObjectException.throwIfNull:65
    // ExitCode: 255
    clienttasks.unsubscribeFromSerialNumber(derivedEntitlementCert.serialNumber);
    clienttasks.unsubscribeFromSerialNumber(hostEntitlementCert.serialNumber);
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) ArrayList(java.util.ArrayList) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) ProductNamespace(rhsm.data.ProductNamespace) JSONObject(org.json.JSONObject) SkipException(org.testng.SkipException) SubscriptionPool(rhsm.data.SubscriptionPool) File(java.io.File) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Aggregations

BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)134 Test (org.testng.annotations.Test)91 SkipException (org.testng.SkipException)89 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)88 SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)77 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)55 ArrayList (java.util.ArrayList)44 SubscriptionPool (rhsm.data.SubscriptionPool)28 File (java.io.File)23 ProductSubscription (rhsm.data.ProductSubscription)23 ProductCert (rhsm.data.ProductCert)22 JSONObject (org.json.JSONObject)20 EntitlementCert (rhsm.data.EntitlementCert)16 InstalledProduct (rhsm.data.InstalledProduct)14 BigInteger (java.math.BigInteger)13 List (java.util.List)12 ConsumerCert (rhsm.data.ConsumerCert)11 SyndFeed (com.sun.syndication.feed.synd.SyndFeed)10 Calendar (java.util.Calendar)10 HashMap (java.util.HashMap)10