Search in sources :

Example 46 with InstalledProduct

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

the class InstanceBasedTests method testStackingOfInstanceBasedSubscriptions.

/**
 * @author skallesh
 * @throws Exception
 * @throws JSONException
 */
@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-36690", "RHEL7-51535" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier2")
@Test(description = "verify stacking of Instance-Based subscriptions", groups = { "Tier2Tests", "StackingOfInstanceBasedSubscription" }, enabled = true)
public void testStackingOfInstanceBasedSubscriptions() throws JSONException, Exception {
    clienttasks.register_(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, true, null, null, (String) null, null, null, null, true, null, null, null, null, null);
    if (clienttasks.getFactValue("virt.is_guest").equalsIgnoreCase("false")) {
        Integer sockets = 4;
        String poolId = null;
        factsMap.put("cpu.cpu_socket(s)", String.valueOf(sockets));
        clienttasks.createFactsFileWithOverridingValues(factsMap);
        clienttasks.facts(null, true, null, null, null, null);
        for (SubscriptionPool availList : clienttasks.getCurrentlyAllAvailableSubscriptionPools()) {
            if (availList.subscriptionName.contains("Instance Based")) {
                poolId = availList.poolId;
                clienttasks.subscribe(null, null, availList.poolId, null, null, "2", null, null, null, null, null, null, null);
            }
        }
        String messageDetails = "Only covers 2 of " + sockets + " sockets.";
        for (InstalledProduct installed : clienttasks.getCurrentlyInstalledProducts()) {
            if (installed.productId.contains("Instance Server")) {
                Assert.assertEquals(installed.status.trim(), "Partially Subscribed");
                Assert.assertEquals(installed.statusDetails, messageDetails);
            }
        }
        clienttasks.subscribe(null, null, poolId, null, null, "2", null, null, null, null, null, null, null);
        for (InstalledProduct installed : clienttasks.getCurrentlyInstalledProducts()) {
            if (installed.productId.contains("Instance Server")) {
                Assert.assertEquals(installed.status.trim(), "Subscribed");
            }
        }
    }
    if (clienttasks.getFactValue("virt.is_guest").equals("True")) {
        Integer sockets = 4;
        factsMap.put("cpu.cpu_socket(s)", String.valueOf(sockets));
        clienttasks.createFactsFileWithOverridingValues(factsMap);
        clienttasks.facts(null, true, null, null, null, null);
        for (SubscriptionPool availList : clienttasks.getCurrentlyAllAvailableSubscriptionPools()) {
            if (availList.subscriptionName.contains("Instance Based")) {
                clienttasks.subscribe(null, null, availList.poolId, null, null, "1", null, null, null, null, null, null, null);
            }
        }
        for (InstalledProduct installed : clienttasks.getCurrentlyInstalledProducts()) {
            if (installed.productId.contains("Instance Server")) {
                Assert.assertEquals(installed.status.trim(), "Subscribed");
            }
        }
    }
}
Also used : InstalledProduct(rhsm.data.InstalledProduct) SubscriptionPool(rhsm.data.SubscriptionPool) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 47 with InstalledProduct

use of rhsm.data.InstalledProduct 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 48 with InstalledProduct

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

the class DevSKUTests method testDevSku.

// 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-25335", "RHEL7-52092" }, 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 SKU, configure the system with custom facts dev_sku=SKU, register the system with auto-attach and verify several requirements of the attached entitlement", groups = { "Tier1Tests" }, dataProvider = "getDevSkuData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testDevSku(Object bugzilla, String devSku, String devPlatform) throws JSONException, Exception {
    // get the JSON product representation of the devSku
    String resourcePath = "/products/" + devSku;
    String ownerKey = sm_clientOrg;
    if (sm_clientOrg == null)
        ownerKey = clienttasks.getCurrentlyRegisteredOwnerKey();
    if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.0.0"))
        resourcePath = "/owners/" + ownerKey + resourcePath;
    JSONObject jsonDevSkuProduct = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, resourcePath));
    if (jsonDevSkuProduct.has("displayMessage")) {
    // indicative that: // Product with ID 'dev-mkt-product' could not be found.
    }
    // instrument the system facts to behave as a vagrant image
    Map<String, String> factsMap = new HashMap<String, String>();
    factsMap.put("dev_sku", devSku);
    factsMap.put("dev_platform", devPlatform);
    clienttasks.createFactsFileWithOverridingValues(factsMap);
    // mark the rhsm.log file
    String logMarker = System.currentTimeMillis() + " Testing VerifyDevSku_Test...";
    RemoteFileTasks.markFile(client, clienttasks.rhsmLogFile, logMarker);
    // register with auto subscribe and force (to unregister anyone that is already registered)
    SSHCommandResult registerResult = clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, true, null, null, (String) null, null, null, null, true, null, null, null, null, null);
    // get the tail of the marked rhsm.log file
    String logTail = RemoteFileTasks.getTailFromMarkedFile(client, clienttasks.rhsmLogFile, logMarker, null).trim();
    // assert when /etc/candlepin/candlepin.conf candlepin.standalone = true   (FYI: candlepin.standalone=false is synonymous with a hosted candlepin deployment)
    // 2016-01-05 17:02:34,527 [DEBUG] subscription-manager:20144 @connection.py:530 - Making request: POST /candlepin/consumers/21800967-1d20-43a9-9bf3-07c5c7d41f61/entitlements
    // 2016-01-05 17:02:34,802 [DEBUG] subscription-manager:20144 @connection.py:562 - Response: status=403, requestUuid=b88c0d1c-0816-4097-89d5-114020d86af1
    // 2016-01-05 17:02:34,804 [WARNING] subscription-manager:20144 @managercli.py:201 - Error during auto-attach.
    // 2016-01-05 17:02:34,805 [ERROR] subscription-manager:20144 @managercli.py:202 - Development units may only be used on hosted servers and with orgs that have active subscriptions.
    // Traceback (most recent call last):
    // File "/usr/share/rhsm/subscription_manager/managercli.py", line 197, in autosubscribe
    // ents = cp.bind(consumer_uuid)  # new style
    // File "/usr/lib64/python2.6/site-packages/rhsm/connection.py", line 1148, in bind
    // return self.conn.request_post(method)
    // File "/usr/lib64/python2.6/site-packages/rhsm/connection.py", line 657, in request_post
    // return self._request("POST", method, params)
    // File "/usr/lib64/python2.6/site-packages/rhsm/connection.py", line 571, in _request
    // self.validateResponse(result, request_type, handler)
    // File "/usr/lib64/python2.6/site-packages/rhsm/connection.py", line 621, in validateResponse
    // raise RestlibException(response['status'], error_msg, response.get('headers'))
    // RestlibException: Development units may only be used on hosted servers and with orgs that have active subscriptions.
    String expectedStdError = "Development units may only be used on hosted servers and with orgs that have active subscriptions.";
    String expectedLogError = "RestlibException: " + expectedStdError;
    if (servertasks.statusStandalone) {
        Assert.assertEquals(registerResult.getStderr().trim(), expectedStdError, "When attempting to autosubscribe a consumer with a dev_sku fact against a candlepin.standalone=true server, stderr reports '" + expectedStdError + "'.");
        // TEMPORARY WORKAROUND
        boolean invokeWorkaroundWhileBugIsOpen = true;
        // Bug 1493299 - exception handling for a negative dev_sku test is no longer being logged to rhsm.log
        String bugId = "1493299";
        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("Detected that candlepin status standalone=true.  DevSku support is only applicable when /etc/candlepin/candlepin candlepin.standalone=false  (typical of a hosted candlepin server), but skipped assertion that an rhsm.log error is thrown while bug '" + bugId + "' is open.");
        } else
            // END OF WORKAROUND
            Assert.assertTrue(logTail.contains(expectedLogError), "When attempting to autosubscribe a consumer with a dev_sku fact against a candlepin.standalone=true server, an rhsm.log error is thrown stating '" + expectedLogError + "'.");
        throw new SkipException("Detected that candlepin status standalone=true.  DevSku support is only applicable when /etc/candlepin/candlepin candlepin.standalone=false  (typical of a hosted candlepin server).");
    } else {
        Assert.assertTrue(!registerResult.getStderr().trim().contains(expectedStdError), "When attempting to autosubscribe a consumer with a dev_sku fact against a candlepin.standalone=false server, stderr does NOT report '" + expectedStdError + "'.");
        Assert.assertTrue(!logTail.contains(expectedLogError), "When attempting to autosubscribe a consumer with a dev_sku fact against a candlepin.standalone=false server, an rhsm.log error is NOT thrown stating '" + expectedLogError + "'.");
    }
    // RestlibException: SKU product not available to this development unit: 'dev-mkt-product'
    if (jsonDevSkuProduct.has("displayMessage")) {
        expectedStdError = String.format("SKU product not available to this development unit: '%s'", devSku);
        if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.3.1-1")) {
            // commit 0d5fefcfa8c1c2485921d2dee6633879b1e06931 Correct incorrect punctuation in user messages
            expectedStdError = String.format("SKU product not available to this development unit: \"%s\"", devSku);
        }
        expectedLogError = "RestlibException: " + expectedStdError;
        Assert.assertEquals(registerResult.getStderr().trim(), expectedStdError, "When attempting to autosubscribe a consumer with an unknown dev_sku fact against a candlepin.standalone=false server, stderr reports '" + expectedStdError + "'.");
        // TEMPORARY WORKAROUND
        boolean invokeWorkaroundWhileBugIsOpen = true;
        // Bug 1493299 - exception handling for a negative dev_sku test is no longer being logged to rhsm.log
        String bugId = "1493299";
        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("Detected that dev_sku '" + devSku + "' was unknown, but skipped verification that a graceful error was logged to rhsm.log while bug '" + bugId + "' is open.");
        } else
            // END OF WORKAROUND
            Assert.assertTrue(logTail.contains(expectedLogError), "When attempting to autosubscribe a consumer with an unknown dev_sku fact against a candlepin.standalone=false server, an rhsm.log error is thrown stating '" + expectedLogError + "'.");
        throw new SkipException("Detected that dev_sku '" + devSku + "' was unknown.  Verified that a graceful error was logged to rhsm.log.");
    }
    // assert only one entitlement was granted
    List<EntitlementCert> entitlementCerts = clienttasks.getCurrentEntitlementCerts();
    Assert.assertEquals(entitlementCerts.size(), 1, "After registering (with autosubscribe) a system with dev_sku fact '" + devSku + "', only one entitlement should be granted.");
    EntitlementCert devSkuEntitlement = entitlementCerts.get(0);
    ProductSubscription devSkuProductSubscription = clienttasks.getCurrentlyConsumedProductSubscriptions().get(0);
    // assert that all of the known installed products are provided by the consumed entitlement
    List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts();
    List<ProductCert> productCerts = clienttasks.getCurrentProductCerts();
    Set installedProductIds = new HashSet<String>();
    for (InstalledProduct installedProduct : installedProducts) {
        // ignore installed products that are unknown to the candlepin product layer
        resourcePath = "/products/" + installedProduct.productId;
        if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.0.0"))
            resourcePath = "/owners/" + ownerKey + resourcePath;
        JSONObject jsonProduct = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, resourcePath));
        if (jsonProduct.has("displayMessage")) {
            // indicative that: // Product with ID '69' could not be found.
            String expectedDisplayMessage = String.format("Product with UUID '%s' could not be found.", installedProduct.productId);
            if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.0.0")) {
                expectedDisplayMessage = String.format("Product with ID '%s' could not be found.", installedProduct.productId);
            }
            if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.3.1-1")) {
                // commit 0d5fefcfa8c1c2485921d2dee6633879b1e06931 Correct incorrect punctuation in user messages
                expectedDisplayMessage = String.format("Product with ID \"%s\" could not be found.", installedProduct.productId);
            }
            Assert.assertEquals(jsonProduct.getString("displayMessage"), expectedDisplayMessage);
            log.info("Installed Product ID '" + installedProduct.productId + "' (" + installedProduct.productName + ") was not recognized by our candlepin server.  Therefore this product will not be entitled by the devSku.");
        } else {
            installedProductIds.add(installedProduct.productId);
        }
    }
    Set<String> entitledProductIds = new HashSet<String>();
    for (ProductNamespace productNamespace : devSkuEntitlement.productNamespaces) entitledProductIds.add(productNamespace.id);
    Assert.assertTrue(entitledProductIds.containsAll(installedProductIds) && entitledProductIds.size() == installedProductIds.size(), "All (and only) of the currently installed products known by the candlepin product layer are entitled by the devSku entitlement.  (Actual entitled product ids " + entitledProductIds + ")");
    // assert that all of the entitled product names are shown in the provides list of the consumed devSku product subscription
    for (ProductNamespace productNamespace : devSkuEntitlement.productNamespaces) {
        Assert.assertTrue(devSkuProductSubscription.provides.contains(productNamespace.name), "The consumed devSku Product Subscriptions provides installed product name '" + productNamespace.name + "'.");
    }
    // assert that all of the provided product content sets that match this system's arch and installed product tags are available in yum repos
    List<String> yumRepos = clienttasks.getYumRepolist("all");
    for (ContentNamespace contentNamespace : devSkuEntitlement.contentNamespaces) {
        if (contentNamespace.type.equals("yum") && clienttasks.areAllRequiredTagsInContentNamespaceProvidedByProductCerts(contentNamespace, productCerts) && clienttasks.isArchCoveredByArchesInContentNamespace(clienttasks.arch, contentNamespace)) {
            Assert.assertTrue(yumRepos.contains(contentNamespace.label), "Found entitled yum repo '" + contentNamespace.label + "' (" + contentNamespace.name + ") (which matches this system arch and installed product tags) among yum repolist all.");
        } else {
            Assert.assertTrue(!yumRepos.contains(contentNamespace.label), "Did NOT find entitled yum repo '" + contentNamespace.label + "' (" + contentNamespace.name + ") (which does not match this system arch and installed product tags) among yum repolist all.");
        }
    }
    // assert that the entitled service_level defaults to "Self-Service" when not explicitly set by the dev_sku product
    String devSkuServiceLevel = CandlepinTasks.getResourceAttributeValue(jsonDevSkuProduct, "support_level");
    if (devSkuServiceLevel == null) {
        String defaultServiceLevel = "Self-Service";
        Assert.assertEquals(devSkuEntitlement.orderNamespace.supportLevel, defaultServiceLevel, "When no support_level attribute exists on the devSku product, the entitlement's order service level defaults to '" + defaultServiceLevel + "'.");
        Assert.assertEquals(devSkuProductSubscription.serviceLevel, defaultServiceLevel, "When no support_level attribute exists on the devSku product, the entitled consumed product subscription service level defaults to '" + defaultServiceLevel + "'.");
    } else {
        Assert.assertEquals(devSkuEntitlement.orderNamespace.supportLevel, devSkuServiceLevel, "When a support_level attribute was set on the devSku product, the entitlement's order service level matches '" + devSkuServiceLevel + "'.");
        Assert.assertEquals(devSkuProductSubscription.serviceLevel, devSkuServiceLevel, "When a support_level attribute was set on the devSku product, the consumed product subscription service level matches '" + devSkuServiceLevel + "'.");
    }
    // assert that the entitled expires_after defaults to 90 days after the registered consumer data when not explicitly set by the dev_sku product
    ConsumerCert consumerCert = clienttasks.getCurrentConsumerCert();
    Calendar expectedEndDate = Calendar.getInstance();
    expectedEndDate.setTimeInMillis(consumerCert.validityNotBefore.getTimeInMillis());
    if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.0.30-1")) {
        // commit 9302c8f57f37dd5ec3c4020770ac1675a87d99ba 1419576: Pre-date certs to ease clock skew issues
        expectedEndDate.add(Calendar.HOUR, Integer.valueOf(1));
        log.info("Due to Candlepin RFE Bug 1419576, we need to increment the expected expires_after by one hour to account for pre-dating the consumer identity's validityNotBefore date by one hour.");
    }
    String devSkuExpiresAfter = CandlepinTasks.getResourceAttributeValue(jsonDevSkuProduct, "expires_after");
    if (devSkuExpiresAfter == null) {
        // days
        String defaultExpiresAfter = "90";
        // TEMPORARY WORKAROUND
        boolean invokeWorkaroundWhileBugIsOpen = true;
        // Bug 1297863 - to account for daylight savings events, dev_sku (CDK) entitlements should add Calendar.DATE units of expires_after to establish the subscription end date
        String bugId = "1297863";
        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 && clienttasks.redhatReleaseX.equals("6") && clienttasks.isPackageVersion("subscription-manager", ">=", "1.15")) {
            // NOTE: This will be an hour off when the duration crosses the "Fall" back or "Spring" forward daylight saving dates.
            expectedEndDate.add(Calendar.HOUR, Integer.valueOf(defaultExpiresAfter) * 24);
        } else
            // END OF WORKAROUND
            expectedEndDate.add(Calendar.DATE, Integer.valueOf(defaultExpiresAfter));
        // /*debugTesting*/expectedEndDate.add(Calendar.SECOND, 20);	// to force an expected failure
        // Assert.assertEquals(ConsumerCert.formatDateString(devSkuEntitlement.validityNotAfter), ConsumerCert.formatDateString(expectedEndDate), "When no expires_after attribute exists on the devSku product, the entitlement's validityNotAfter date defaults to '"+defaultExpiresAfter+"' days after the date the consumer was registered ("+ConsumerCert.formatDateString(consumerCert.validityNotBefore)+").");
        // java.lang.AssertionError: When no expires_after attribute exists on the devSku product, the entitlement's validityNotAfter date defaults to '90' days after the date the consumer was registered (Jul 6 2016 12:19:18 EDT). expected:<Oct 4 2016 12:19:18 EDT> but was:<Oct 4 2016 12:19:17 EDT>
        // allow for a few seconds of tolerance
        Calendar expectedEndDateUpperTolerance = (Calendar) expectedEndDate.clone();
        expectedEndDateUpperTolerance.add(Calendar.SECOND, +5);
        Calendar expectedEndDateLowerTolerance = (Calendar) expectedEndDate.clone();
        expectedEndDateLowerTolerance.add(Calendar.SECOND, -5);
        Assert.assertTrue(devSkuEntitlement.validityNotAfter.before(expectedEndDateUpperTolerance) && devSkuEntitlement.validityNotAfter.after(expectedEndDateLowerTolerance), "When no expires_after attribute exists on the devSku product, the entitlement's validityNotAfter date defaults to '" + defaultExpiresAfter + "' days after the date the consumer was registered (" + ConsumerCert.formatDateString(consumerCert.validityNotBefore) + "). devSkuEntitlement.validityNotAfter expected: <" + ConsumerCert.formatDateString(expectedEndDate) + "> (withn a few seconds of tolerance of) actual: <" + ConsumerCert.formatDateString(devSkuEntitlement.validityNotAfter) + ">");
    } else {
        // TEMPORARY WORKAROUND
        boolean invokeWorkaroundWhileBugIsOpen = true;
        // Bug 1297863 - to account for daylight savings events, dev_sku (CDK) entitlements should add Calendar.DATE units of expires_after to establish the subscription end date
        String bugId = "1297863";
        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 && clienttasks.redhatReleaseX.equals("6") && clienttasks.isPackageVersion("subscription-manager", ">=", "1.15")) {
            // NOTE: This will be an hour off when the duration crosses the "Fall" back or "Spring" forward daylight saving dates.
            expectedEndDate.add(Calendar.HOUR, Integer.valueOf(devSkuExpiresAfter) * 24);
        } else
            // END OF WORKAROUND
            expectedEndDate.add(Calendar.DATE, Integer.valueOf(devSkuExpiresAfter));
        // /*debugTesting*/expectedEndDate.add(Calendar.SECOND, 20);	// to force an expected failure
        // Assert.assertEquals(ConsumerCert.formatDateString(devSkuEntitlement.validityNotAfter), ConsumerCert.formatDateString(expectedEndDate), "When an expires_after attribute exists on the devSku product, the entitlement's validityNotAfter is '"+devSkuExpiresAfter+"' days after the date the consumer was registered ("+ConsumerCert.formatDateString(consumerCert.validityNotBefore)+").");
        // java.lang.AssertionError: When an expires_after attribute exists on the devSku product, the entitlement's validityNotAfter is '75' days after the date the consumer was registered (Jul 3 2016 21:43:03 EDT). expected:<Sep 16 2016 21:43:03 EDT> but was:<Sep 16 2016 21:43:02 EDT>
        // allow for a few seconds of tolerance
        Calendar expectedEndDateUpperTolerance = (Calendar) expectedEndDate.clone();
        expectedEndDateUpperTolerance.add(Calendar.SECOND, +5);
        Calendar expectedEndDateLowerTolerance = (Calendar) expectedEndDate.clone();
        expectedEndDateLowerTolerance.add(Calendar.SECOND, -5);
        Assert.assertTrue(devSkuEntitlement.validityNotAfter.before(expectedEndDateUpperTolerance) && devSkuEntitlement.validityNotAfter.after(expectedEndDateLowerTolerance), "When an expires_after attribute exists on the devSku product, the entitlement's validityNotAfter is '" + devSkuExpiresAfter + "' days after the date the consumer was registered (" + ConsumerCert.formatDateString(consumerCert.validityNotBefore) + "). devSkuEntitlement.validityNotAfter expected: <" + ConsumerCert.formatDateString(expectedEndDate) + "> (withn a few seconds of tolerance of) actual: <" + ConsumerCert.formatDateString(devSkuEntitlement.validityNotAfter) + ">");
    }
    // assert that the pool consumed exists with quantity 1
    resourcePath = "/pools/" + devSkuProductSubscription.poolId;
    JSONObject jsonDevSkuPool = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, resourcePath));
    Assert.assertEquals(jsonDevSkuPool.getInt("quantity"), 1, "The quantity on pool '" + devSkuProductSubscription.poolId + "' generated for devSku product '" + devSku + "'.");
    // assert that the pool consumed requires_consumer UUID that is currently registered
    // "4a49b1a7-c616-42dd-b96d-62233a4c82b9"
    String devSkuRequiresConsumer = CandlepinTasks.getPoolAttributeValue(jsonDevSkuPool, "requires_consumer");
    Assert.assertEquals(devSkuRequiresConsumer, consumerCert.consumerid, "The requires_consumer attribute on pool '" + devSkuProductSubscription.poolId + "' generated for devSku product '" + devSku + "'.");
    // assert that the pool generated has attribute dev_pool: true
    // "true" or "false"
    String devSkuDevPool = CandlepinTasks.getPoolAttributeValue(jsonDevSkuPool, "dev_pool");
    Assert.assertEquals(Boolean.valueOf(devSkuDevPool), Boolean.TRUE, "The dev_pool attribute on pool '" + devSkuProductSubscription.poolId + "' generated for devSku product '" + devSku + "'.");
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) EntitlementCert(rhsm.data.EntitlementCert) HashMap(java.util.HashMap) Calendar(java.util.Calendar) ProductSubscription(rhsm.data.ProductSubscription) ProductCert(rhsm.data.ProductCert) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) ProductNamespace(rhsm.data.ProductNamespace) ContentNamespace(rhsm.data.ContentNamespace) JSONObject(org.json.JSONObject) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) InstalledProduct(rhsm.data.InstalledProduct) SkipException(org.testng.SkipException) ConsumerCert(rhsm.data.ConsumerCert) HashSet(java.util.HashSet) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 49 with InstalledProduct

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

the class ComplianceTests method verifyListInstalledIsCachedWhenServerGoesOffline.

protected void verifyListInstalledIsCachedWhenServerGoesOffline() {
    List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts();
    clienttasks.config(null, null, true, new String[] { "server", "hostname", "offline-" + serverHostname });
    Integer expectedIdentityExitCode = new Integer(255);
    // EX_SOFTWARE	// post commit df95529a5edd0be456b3528b74344be283c4d258 bug 1119688
    if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.13.8-1"))
        expectedIdentityExitCode = new Integer(70);
    Assert.assertEquals(clienttasks.identity_(null, null, null, null, null, null, null, null).getExitCode(), expectedIdentityExitCode, "Identity fails when system is offline");
    List<InstalledProduct> installedProductsCached = clienttasks.getCurrentlyInstalledProducts();
    for (InstalledProduct installedProduct : installedProductsCached) {
        Assert.assertTrue(!installedProduct.status.equalsIgnoreCase("Unknown"), "Installed product '" + installedProduct.productName + "' status '" + installedProduct.status + "' should NOT be Unknown when server is offline.");
    }
    Assert.assertTrue(installedProductsCached.containsAll(installedProducts) && installedProducts.containsAll(installedProductsCached), "Installed product list should remain cached when server is offline.");
}
Also used : BigInteger(java.math.BigInteger) InstalledProduct(rhsm.data.InstalledProduct)

Example 50 with InstalledProduct

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

the class ComplianceTests method testSystemCompliantFactWhenAllProductsAreSubscribableInTheFuture.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21725", "RHEL7-33103" }, 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 = "subscription-manager: verify the system.compliant fact remains False when all installed products are subscribable in the future", groups = { "Tier1Tests", "configureProductCertDirForAllProductsSubscribableInTheFuture", "cli.tests", "blockedbyBug-737553", "blockedbyBug-649068", "blockedbyBug-1183175", "blockedbyBug-1440180" }, priority = 800, enabled = true)
public // @ImplementsTCMS(id="")
void testSystemCompliantFactWhenAllProductsAreSubscribableInTheFuture() throws JSONException, Exception {
    List<ProductCert> currentProductCerts = clienttasks.getCurrentProductCerts();
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, Boolean.TRUE, false, null, null, null, null);
    // to avoid unmapped_guests_only pools
    if (Boolean.valueOf(clienttasks.getFactValue("virt.is_guest")))
        clienttasks.mapSystemAsAGuestOfItself();
    // initial assertions
    Assert.assertFalse(clienttasks.getCurrentlyInstalledProducts().isEmpty(), "Products are currently installed for which the compliance of ALL are covered by future available subscription pools.");
    Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance), factValueForSystemNonCompliance, "Before attempting to subscribe to any future subscription, the system should be non-compliant (see value for fact '" + factNameForSystemCompliance + "').");
    // incrementally subscribe to each future subscription pool and assert the corresponding installed product's status
    Set<String> productIdsProvidedByFutureSubscriptionsThatFailedToAttach = new HashSet<String>();
    for (SubscriptionPool futureSystemSubscriptionPool : futureSystemSubscriptionPools) {
        // subscribe without asserting results (not necessary)
        File entitlementCertFile = clienttasks.subscribeToSubscriptionPool_(futureSystemSubscriptionPool);
        // WARNING: Pool is restricted to unmapped virtual guests: '2c90af964cba07a6014cba0b1ab80e24'
        if (entitlementCertFile == null) {
            log.warning("Encountered a problem trying to attach future subscription '" + futureSystemSubscriptionPool.subscriptionName + "'.  Look for two preceeding WARNING messages.  Skipping assertion of installed product status.");
            // FIXME need to account for this problem in the assertions that follow this block especially if this failed futureSystemSubscriptionPool is the only one that provides one of the installed products.
            // 8/26/2015 ATTEMPTING TO FIXME WITH productIdsProvidedByFutureSubscriptionsThatFailedToAttach
            productIdsProvidedByFutureSubscriptionsThatFailedToAttach.addAll(CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, futureSystemSubscriptionPool.poolId));
            continue;
        }
        // assert that the Status of the installed product is "Future Subscription"
        List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts();
        // for (ProductCert productCert : clienttasks.getCurrentProductCertsProvidedBySubscriptionPool(futureSystemSubscriptionPool)) {	// TODO not efficient; testing fix on next line
        for (ProductCert productCert : clienttasks.getProductCertsProvidedBySubscriptionPool(currentProductCerts, futureSystemSubscriptionPool)) {
            InstalledProduct installedProduct = clienttasks.getInstalledProductCorrespondingToProductCert(productCert, installedProducts);
            Assert.assertEquals(installedProduct.status, "Future Subscription", "Status of the installed product '" + productCert.productName + "' after subscribing to future subscription pool: " + futureSystemSubscriptionPool);
        // TODO assert the installedProduct start/end dates
        }
    }
    // simply assert that we actually did subscribe every installed product to a future subscription pool
    for (InstalledProduct installedProduct : clienttasks.getCurrentlyInstalledProducts()) {
        // 8/26/2015 ATTEMPTING TO FIXME AS SUGGESTED IN THE COMMENT LINE ABOVE
        if (!installedProduct.status.equals("Future Subscription") && productIdsProvidedByFutureSubscriptionsThatFailedToAttach.contains(installedProduct.productId)) {
            log.warning("Employing a workaround by removing installed product '" + installedProduct.productName + "' since we encountered a problem when attempting to attach a future subscription that provided for this installed product.");
            client.runCommandAndWait("rm -f " + ProductCert.findFirstInstanceWithMatchingFieldFromList("productId", installedProduct.productId, currentProductCerts).file);
            continue;
        }
        Assert.assertEquals(installedProduct.status, "Future Subscription", "Status of every installed product should be a Future Subscription after subscribing all installed products to a future pool.  This Installed Product: " + installedProduct);
    }
    // finally assert that the overall system is non-compliant
    Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance), factValueForSystemNonCompliance, "When a system has products installed for which ALL are covered by future available subscription pools, the system should remain non-compliant (see value for fact '" + factNameForSystemCompliance + "') after having subscribed to every available subscription pool.");
}
Also used : InstalledProduct(rhsm.data.InstalledProduct) ProductCert(rhsm.data.ProductCert) SubscriptionPool(rhsm.data.SubscriptionPool) File(java.io.File) HashSet(java.util.HashSet) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Aggregations

InstalledProduct (rhsm.data.InstalledProduct)77 Test (org.testng.annotations.Test)71 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)66 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)33 SkipException (org.testng.SkipException)27 SubscriptionPool (rhsm.data.SubscriptionPool)25 ArrayList (java.util.ArrayList)22 ProductCert (rhsm.data.ProductCert)21 ProductSubscription (rhsm.data.ProductSubscription)16 SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)15 BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)14 HashMap (java.util.HashMap)13 BigInteger (java.math.BigInteger)12 JSONObject (org.json.JSONObject)10 File (java.io.File)9 Calendar (java.util.Calendar)7 HashSet (java.util.HashSet)7 EntitlementCert (rhsm.data.EntitlementCert)6 GregorianCalendar (java.util.GregorianCalendar)5 JSONArray (org.json.JSONArray)5