Search in sources :

Example 46 with ProductSubscription

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

the class InstanceBasedTests method testAutoSubscribingInstanceBasedSubscriptions.

/**
 * @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-36687", "RHEL7-51532" }, 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 auto subscribing of Instance-Based subscriptions", groups = { "Tier2Tests", "AutoSubscribingInstanceBasedSubscription" }, enabled = true)
public void testAutoSubscribingInstanceBasedSubscriptions() throws JSONException, Exception {
    clienttasks.register_(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, false, null, null, (String) null, null, null, null, true, null, null, null, null, null);
    // to avoid unmapped_guests_only pools
    if (Boolean.valueOf(clienttasks.getFactValue("virt.is_guest")))
        clienttasks.mapSystemAsAGuestOfItself();
    clienttasks.subscribe_(true, null, (String) null, null, null, null, null, null, null, null, null, null, null);
    if (clienttasks.getFactValue("virt.is_guest").equalsIgnoreCase("false")) {
        Integer sockets = 4;
        factsMap.put("cpu.cpu_socket(s)", String.valueOf(sockets));
        clienttasks.createFactsFileWithOverridingValues(factsMap);
        clienttasks.facts(null, true, null, null, null, null);
        clienttasks.subscribe(true, null, (String) null, null, null, null, null, null, null, null, null, null, null);
        for (InstalledProduct installed : clienttasks.getCurrentlyInstalledProducts()) {
            if (installed.productName.contains("Instance Server")) {
                Assert.assertEquals(installed.status.trim(), "Subscribed");
            }
        }
        for (ProductSubscription consumed : clienttasks.getCurrentlyConsumedProductSubscriptions()) {
            if (consumed.productName.contains("Instance Based")) {
                String SocketsCount = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, consumed.poolId, "sockets");
                sockets = sockets / Integer.parseInt(SocketsCount);
                Assert.assertEquals(consumed.quantityUsed, sockets);
            }
        }
    }
    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);
        clienttasks.subscribe(true, null, (String) null, null, null, null, null, null, null, null, null, null, null);
        for (InstalledProduct installed : clienttasks.getCurrentlyInstalledProducts()) {
            if (installed.productName.contains("Instance Server")) {
                Assert.assertEquals(installed.status.trim(), "Subscribed");
            }
        }
        for (ProductSubscription consumed : clienttasks.getCurrentlyConsumedProductSubscriptions()) {
            if (consumed.productName.contains("Instance Based")) {
                Integer quantity = 1;
                Assert.assertEquals(consumed.quantityUsed, quantity);
            }
        }
    }
}
Also used : InstalledProduct(rhsm.data.InstalledProduct) ProductSubscription(rhsm.data.ProductSubscription) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 47 with ProductSubscription

use of rhsm.data.ProductSubscription 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 ProductSubscription

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

the class ContentTests method testContentSetsEntitledFromSubscriptionPoolSatisfyTheSystemArch.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20081", "RHEL7-50720" }, 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 that all content sets granted from a subscription pool satisfy the system arch and subset the provided product's arch", groups = { "Tier1Tests", "blockedByBug-706187", "blockedByBug-975520" }, // "getAvailableSubscriptionPoolsData",
dataProvider = "getAllAvailableSubscriptionPoolsProvidingArchBasedContentData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testContentSetsEntitledFromSubscriptionPoolSatisfyTheSystemArch(SubscriptionPool pool) throws JSONException, Exception {
    List<String> providedProductIds = CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId);
    if (providedProductIds.isEmpty())
        throw new SkipException("This test is not applicable for a pool that provides no products.");
    JSONObject jsonStatus = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(/*authenticator*/
    null, /*password*/
    null, sm_serverUrl, "/status"));
    JSONObject jsonPool = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/pools/" + pool.poolId));
    // maintain a list of expected content sets
    Set<ContentNamespace> expectedContentNamespaceSet = new HashSet<ContentNamespace>();
    // maintain a list of unexpected content sets
    Set<ContentNamespace> unexpectedContentNamespaceSet = new HashSet<ContentNamespace>();
    for (String providedProductId : providedProductIds) {
        // get the product
        String path = "/products/" + providedProductId;
        // starting with candlepin-2.0.11 /products/<ID> are requested by /owners/<KEY>/products/<ID> OR /products/<UUID>
        if (SubscriptionManagerTasks.isVersion(jsonStatus.getString("version"), ">=", "2.0.11"))
            path = jsonPool.getJSONObject("owner").getString("href") + path;
        JSONObject jsonProduct = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, path));
        // get the product supported arches
        JSONArray jsonProductAttributes = jsonProduct.getJSONArray("attributes");
        List<String> productSupportedArches = new ArrayList<String>();
        for (int j = 0; j < jsonProductAttributes.length(); j++) {
            JSONObject jsonProductAttribute = (JSONObject) jsonProductAttributes.get(j);
            String attributeName = jsonProductAttribute.getString("name");
            String attributeValue = jsonProductAttribute.isNull("value") ? null : jsonProductAttribute.getString("value");
            if (attributeName.equals("arch")) {
                // Note: the arch attribute can be a comma separated list of values
                productSupportedArches.addAll(Arrays.asList(attributeValue.trim().split("\\s*,\\s*")));
                // Note: x86 is a general arch to cover all 32-bit intel microprocessors
                if (productSupportedArches.contains("x86")) {
                    productSupportedArches.addAll(Arrays.asList("i386", "i486", "i586", "i686"));
                }
            }
        }
        // get the provided product contents
        JSONArray jsonProductContents = jsonProduct.getJSONArray("productContent");
        for (int j = 0; j < jsonProductContents.length(); j++) {
            JSONObject jsonProductContent = (JSONObject) jsonProductContents.get(j);
            JSONObject jsonContent = jsonProductContent.getJSONObject("content");
            Map<String, String> certData = new HashMap<String, String>();
            // certData.put("", jsonContent.getString("id"));
            if (jsonContent.has("type") && !jsonContent.isNull("type"))
                certData.put("type", jsonContent.getString("type"));
            if (jsonContent.has("label") && !jsonContent.isNull("label"))
                certData.put("label", jsonContent.getString("label"));
            if (jsonContent.has("name") && !jsonContent.isNull("name"))
                certData.put("name", jsonContent.getString("name"));
            if (jsonContent.has("vendorId") && !jsonContent.isNull("vendorId"))
                certData.put("vendorId", jsonContent.getString("vendor"));
            if (jsonContent.has("downloadUrl") && !jsonContent.isNull("downloadUrl"))
                certData.put("downloadUrl", jsonContent.getString("contentUrl"));
            if (jsonContent.has("requiredTags") && !jsonContent.isNull("requiredTags"))
                certData.put("requiredTags", jsonContent.getString("requiredTags"));
            // certData.put("", jsonContent.getString("releaseVer"));
            if (jsonContent.has("gpgKeyUrl") && !jsonContent.isNull("gpgKeyUrl"))
                certData.put("gpgKeyUrl", jsonContent.getString("gpgUrl"));
            if (jsonContent.has("metadataExpire") && !jsonContent.isNull("metadataExpire"))
                certData.put("metadataExpire", String.valueOf(jsonContent.getInt("metadataExpire")));
            // certData.put("", jsonContent.getString("modifiedProductIds"));
            if (jsonContent.has("arches") && !jsonContent.isNull("arches"))
                certData.put("arches", jsonContent.getString("arches"));
            ContentNamespace contentNamespace = new ContentNamespace(certData);
            // // get modifiedProductIds for each of the productContents
            // JSONArray jsonModifiedProductIds = jsonContent.getJSONArray("modifiedProductIds");
            // for (int k = 0; k < jsonModifiedProductIds.length(); k++) {
            // String modifiedProductId = (String) jsonModifiedProductIds.get(k);
            // }
            // get this content supported arches
            Set<String> contentSupportedArches = new HashSet<String>();
            String jsonContentArches = null;
            if (jsonContent.has("arches") && !jsonContent.isNull("arches") && !jsonContent.getString("arches").isEmpty()) {
                jsonContentArches = jsonContent.getString("arches");
                contentSupportedArches.addAll(Arrays.asList(jsonContentArches.split("\\s*,\\s*")));
                // Note: x86 is a general arch to cover all 32-bit intel microprocessors
                if (contentSupportedArches.contains("x86"))
                    contentSupportedArches.addAll(Arrays.asList("i386", "i486", "i586", "i686"));
                // it contains an arch that matches the system
                if (contentSupportedArches.contains("ALL") || contentSupportedArches.contains("noarch") || contentSupportedArches.contains(clienttasks.arch)) {
                    expectedContentNamespaceSet.add(contentNamespace);
                } else {
                    unexpectedContentNamespaceSet.add(contentNamespace);
                }
            } else {
                // TODO: NOT SURE HOW TOLERANT WE WANT TO BE FOR CONTENT SETS THAT INHERIT FROM THEIR PRODUCTS
                if (productSupportedArches.contains("ALL") || productSupportedArches.contains(clienttasks.arch)) {
                    expectedContentNamespaceSet.add(contentNamespace);
                } else {
                    unexpectedContentNamespaceSet.add(contentNamespace);
                }
            }
        }
    }
    // conflict situation: if a subscription provides more than one product that both provide the same content but whose product's arch differs, then it is possible to have the content in both expectedContentLabels and unexpectedContentLabels; expectedContentLabels wins!
    for (ContentNamespace expectedContentNamespace : expectedContentNamespaceSet) {
        List<ContentNamespace> unexpectedContentNamespaceList = new ArrayList<ContentNamespace>();
        unexpectedContentNamespaceList.addAll(unexpectedContentNamespaceSet);
        ContentNamespace unexpectedContentNamespace = ContentNamespace.findFirstInstanceWithMatchingFieldFromList("label", expectedContentNamespace.label, unexpectedContentNamespaceList);
        if (unexpectedContentNamespace != null) {
            log.warning("Based on multiple products '" + providedProductIds + "' from subscription '" + pool.subscriptionName + "' with conflicting arches, content label '" + expectedContentNamespace.label + "' defined for arches '" + expectedContentNamespace.arches + "' will be provided.");
            unexpectedContentNamespaceSet.remove(unexpectedContentNamespace);
        }
    }
    if (expectedContentNamespaceSet.isEmpty() && unexpectedContentNamespaceSet.isEmpty())
        throw new SkipException("This test is not applicable for a pool whose provided products have no content sets.");
    // avoid throttling RateLimitExceededException from IT-Candlepin
    if (!poolIds.contains(pool.poolId) && 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);
    }
    poolIds.add(pool.poolId);
    clienttasks.unsubscribe(true, (BigInteger) null, null, null, null, null, null);
    EntitlementCert entitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(clienttasks.subscribeToSubscriptionPool(pool, /*sm_serverAdminUsername*/
    sm_clientUsername, /*sm_serverAdminPassword*/
    sm_clientPassword, sm_serverUrl));
    // adjust the expectedContentNamespaces for modified product ids that are not installed
    // List<ProductCert> installedProductCerts = clienttasks.getCurrentProductCerts();
    List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    for (String providedProductId : providedProductIds) {
        // get the product
        String path = "/products/" + providedProductId;
        // starting with candlepin-2.0.11 /products/<ID> are requested by /owners/<KEY>/products/<ID> OR /products/<UUID>
        if (SubscriptionManagerTasks.isVersion(jsonStatus.getString("version"), ">=", "2.0.11"))
            path = jsonPool.getJSONObject("owner").getString("href") + path;
        JSONObject jsonProduct = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, path));
        // get the provided product contents
        JSONArray jsonProductContents = jsonProduct.getJSONArray("productContent");
        for (int j = 0; j < jsonProductContents.length(); j++) {
            JSONObject jsonProductContent = (JSONObject) jsonProductContents.get(j);
            JSONObject jsonContent = jsonProductContent.getJSONObject("content");
            // get modifiedProductIds for each of the productContents
            JSONArray jsonModifiedProductIds = jsonContent.getJSONArray("modifiedProductIds");
            for (int k = 0; k < jsonModifiedProductIds.length(); k++) {
                String modifiedProductId = (String) jsonModifiedProductIds.get(k);
                String contentLabel = jsonContent.getString("label");
                // TODO: I do not believe this should check the installed products or all the current subscriptions' providedProductIds for this modifiedProductId
                // // if modifiedProductId is not installed, then the modifier jsonContent should NOT be among the expectedContentNamespaceSet
                // if (InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", modifiedProductId, installedProductCerts)==null) {
                // ContentNamespace contentNamespace = ContentNamespace.findFirstInstanceWithMatchingFieldFromList("label", jsonContent.getString("label"), new ArrayList<ContentNamespace>(expectedContentNamespaceSet));
                // if (contentNamespace!=null) {
                // log.warning("ContentNamespace label '"+contentNamespace.label+"' modifies product id '"+modifiedProductId+"' which is NOT installed and should therefore not be among the entitled content namespaces no matter what its arch ("+contentNamespace.arches+") may be.");
                // unexpectedContentNamespaceSet.add(contentNamespace);
                // expectedContentNamespaceSet.remove(contentNamespace);
                // }
                // }
                // DONE: Implemented the second thought by the following test block
                // if modifiedProductId is not provided by the currently consumed subscriptions, then the modifier jsonContent should NOT be among the expectedContentNamespaceSet
                Set<String> providedProductIdsByCurrentlyConsumedProductSubscriptions = new HashSet<String>();
                for (ProductSubscription productSubscription : consumedProductSubscriptions) {
                    for (String providedProductIdByCurrentlyConsumedProductSubscription : CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId)) {
                        providedProductIdsByCurrentlyConsumedProductSubscriptions.add(providedProductIdByCurrentlyConsumedProductSubscription);
                    }
                }
                if (!providedProductIdsByCurrentlyConsumedProductSubscriptions.contains(modifiedProductId)) {
                    ContentNamespace contentNamespace = ContentNamespace.findFirstInstanceWithMatchingFieldFromList("label", jsonContent.getString("label"), new ArrayList<ContentNamespace>(expectedContentNamespaceSet));
                    if (contentNamespace != null) {
                        log.warning("ContentNamespace label '" + contentNamespace.label + "' modifies product id '" + modifiedProductId + "' which is NOT provided by the currently consumed subscriptions and should therefore not be among the entitled content namespaces no matter what its arch (" + contentNamespace.arches + ") may be.");
                        unexpectedContentNamespaceSet.add(contentNamespace);
                        expectedContentNamespaceSet.remove(contentNamespace);
                        // to the next contentNamespace/jsonProductContent/jsonContent
                        break;
                    }
                }
            }
        }
    }
    // entitlement asserts
    List<String> actualEntitledContentLabels = new ArrayList<String>();
    for (ContentNamespace contentNamespace : entitlementCert.contentNamespaces) actualEntitledContentLabels.add(contentNamespace.label);
    for (ContentNamespace contentNamespace : expectedContentNamespaceSet) {
        Assert.assertTrue(actualEntitledContentLabels.contains(contentNamespace.label), "As expected, contentNamespace label '" + contentNamespace.label + "' defined for arches '" + contentNamespace.arches + "' requiredTags '" + contentNamespace.requiredTags + "' is included in the entitlement after subscribing to '" + pool.subscriptionName + "' on a '" + clienttasks.arch + "' system.");
    }
    for (ContentNamespace contentNamespace : unexpectedContentNamespaceSet) {
        Assert.assertTrue(!actualEntitledContentLabels.contains(contentNamespace.label), "As expected, contentNamespace label '" + contentNamespace.label + "' defined for arches '" + contentNamespace.arches + "' requiredTags '" + contentNamespace.requiredTags + "' is NOT included in the entitlement after subscribing to '" + pool.subscriptionName + "' on a '" + clienttasks.arch + "' system.");
    }
    // adjust the expectedContentNamespaces for requiredTags that are not provided by the installed productCerts' providedTags before checking the YumRepos
    List<ProductCert> installedProductCerts = clienttasks.getCurrentProductCerts();
    for (ContentNamespace contentNamespace : new HashSet<ContentNamespace>(expectedContentNamespaceSet)) {
        if (!clienttasks.areAllRequiredTagsProvidedByProductCerts(contentNamespace.requiredTags, installedProductCerts)) {
            log.warning("Entitled contentNamespace label '" + contentNamespace.label + "' defined for arches '" + contentNamespace.arches + "' has requiredTags '" + contentNamespace.requiredTags + "' that are NOT provided by the currently installed product certs.  This expected contentNamespace will be moved to the unexpected list when asserting the YumRepos next.");
            unexpectedContentNamespaceSet.add(contentNamespace);
            expectedContentNamespaceSet.remove(contentNamespace);
        }
    }
    // adjust the expectedContentNamespaces for type that does not equal "yum" before checking the YumRepos
    for (ContentNamespace contentNamespace : new HashSet<ContentNamespace>(expectedContentNamespaceSet)) {
        if (!contentNamespace.type.equals("yum")) {
            // "file", "kickstart"
            log.warning("Entitled contentNamespace label '" + contentNamespace.label + "' defined for arches '" + contentNamespace.arches + "' has type '" + contentNamespace.type + "'.  This expected contentNamespace will be moved to the unexpected list when asserting the YumRepos next.");
            unexpectedContentNamespaceSet.add(contentNamespace);
            expectedContentNamespaceSet.remove(contentNamespace);
        }
    }
    // YumRepo asserts
    List<String> actualYumRepoLabels = new ArrayList<String>();
    for (YumRepo yumRepo : clienttasks.getCurrentlySubscribedYumRepos()) actualYumRepoLabels.add(yumRepo.id);
    for (ContentNamespace contentNamespace : expectedContentNamespaceSet) {
        Assert.assertTrue(actualYumRepoLabels.contains(contentNamespace.label), "As expected, yum repo label '" + contentNamespace.label + "' defined for arches '" + contentNamespace.arches + "' requiredTags '" + contentNamespace.requiredTags + "' is included in " + clienttasks.redhatRepoFile + " after subscribing to '" + pool.subscriptionName + "' on a '" + clienttasks.arch + "' system.");
    }
    for (ContentNamespace contentNamespace : unexpectedContentNamespaceSet) {
        Assert.assertTrue(!actualYumRepoLabels.contains(contentNamespace.label), "As expected, yum repo label '" + contentNamespace.label + "' defined for arches '" + contentNamespace.arches + "' requiredTags '" + contentNamespace.requiredTags + "' is NOT included in in " + clienttasks.redhatRepoFile + " after subscribing to '" + pool.subscriptionName + "' on a '" + clienttasks.arch + "' system.");
    }
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) ProductCert(rhsm.data.ProductCert) ContentNamespace(rhsm.data.ContentNamespace) JSONObject(org.json.JSONObject) SkipException(org.testng.SkipException) YumRepo(rhsm.data.YumRepo) HashSet(java.util.HashSet) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 49 with ProductSubscription

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

the class DevSKUTests method testDevSkuEntitlementCanBeRemovedAndReAttached.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20116", "RHEL7-51857" }, 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 = "configure the system with custom facts for a dev_sku, register the system with auto-subscribe verify the attached entitlement can be removed and re-autoattached", groups = { "Tier1Tests" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testDevSkuEntitlementCanBeRemovedAndReAttached() throws JSONException, Exception {
    // get a valid dev_sku to test with
    List<Object> l = getRandomValidDevSkuData();
    String devSku = (String) l.get(1);
    String devPlatform = (String) l.get(2);
    // 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);
    // register with autosubscribe and force (to unregister anyone that is already registered)
    SSHCommandResult result = 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 (servertasks.statusStandalone) {
        Assert.assertEquals(result.getStderr().trim(), "Development units may only be used on hosted servers and with orgs that have active subscriptions.", "Expected stderr when /etc/candlepin/candlepin candlepin.standalone=true  (typical of Satellite deployment).");
        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).");
    }
    // get the autosubscribed productSubscription
    List<ProductSubscription> productSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    Assert.assertEquals(productSubscriptions.size(), 1, "After registering (with autosubscribe) a system with dev_sku fact '" + devSku + "', only one product subscription should be consumed.");
    ProductSubscription devSkuProductSubscription1 = productSubscriptions.get(0);
    // remove it
    clienttasks.unsubscribe(null, devSkuProductSubscription1.serialNumber, null, null, null, null, null);
    // verify that the pool from which the devSku was entitled is no longer consumable after having removed the devSku entitlement
    result = clienttasks.subscribe_(null, null, devSkuProductSubscription1.poolId, null, null, null, null, null, null, null, null, null, null);
    String expectedStdout = String.format("Pool with id %s could not be found.", devSkuProductSubscription1.poolId);
    Assert.assertEquals(result.getStdout().trim(), expectedStdout, "After removing a devSku entitlement, its pool should no longer be consumable.");
    // re-autosubscribe
    clienttasks.subscribe(true, null, null, null, (String) null, null, null, null, null, null, null, null, null);
    // get the re-autosubscribed entitlement
    productSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    Assert.assertEquals(productSubscriptions.size(), 1, "After re-autosubscribing a system with dev_sku fact '" + devSku + "', only one product subscription should be consumed.");
    ProductSubscription devSkuProductSubscription2 = productSubscriptions.get(0);
    // assert the re-autosubscribes product subscriptions match (except for pool id and serial since the pool must go when removed)
    Assert.assertEquals(ProductSubscription.formatDateString(devSkuProductSubscription2.endDate), ProductSubscription.formatDateString(devSkuProductSubscription1.endDate), "A dev_sku enabled system that has been re-autosubscribed is granted another product subscription with the same end date.");
    Assert.assertEquals(devSkuProductSubscription2.serviceLevel, devSkuProductSubscription1.serviceLevel, "A dev_sku enabled system that has been re-autosubscribed is granted another product subscription with the same service level.");
    Assert.assertEquals(devSkuProductSubscription2.quantityUsed, devSkuProductSubscription1.quantityUsed, "A dev_sku enabled system that has been re-autosubscribed is granted another product subscription with the quantity used.");
    Assert.assertTrue(devSkuProductSubscription2.provides.containsAll(devSkuProductSubscription1.provides) && devSkuProductSubscription1.provides.containsAll(devSkuProductSubscription2.provides), "A dev_sku enabled system that has been re-autosubscribed is granted another product subscription that provides the same products." + "  devSkuProductSubscription1.provides=" + devSkuProductSubscription1.provides + "  devSkuProductSubscription2.provides=" + devSkuProductSubscription2.provides);
    Assert.assertTrue(!devSkuProductSubscription2.poolId.equals(devSkuProductSubscription1.poolId), "A dev_sku enabled system that has been re-autosubscribed is granted another product subscription from a different pool id.");
    Assert.assertTrue(!devSkuProductSubscription2.serialNumber.equals(devSkuProductSubscription1.serialNumber), "A dev_sku enabled system that has been re-autosubscribed is granted another product subscription with a different serial.");
}
Also used : HashMap(java.util.HashMap) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ProductSubscription(rhsm.data.ProductSubscription) JSONObject(org.json.JSONObject) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 50 with ProductSubscription

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

the class DevSKUTests method testManualSubscribesWhileConsumingDevSkuEntitlement.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-26779", "RHEL7-51858" }, 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 = "configure the system with custom facts for a dev_sku, register the system with auto-subscribe and verify that a cost-based subscription can be manually attached without affecting the devSku entitlement", groups = { "Tier1Tests", "blockedByBug-1298577" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testManualSubscribesWhileConsumingDevSkuEntitlement() throws JSONException, Exception {
    // get a valid dev_sku to test with
    List<Object> l = getRandomValidDevSkuData();
    String devSku = (String) l.get(1);
    String devPlatform = (String) l.get(2);
    // /*debugTesting*/devSku = "dev-sku-product";devPlatform = "dev-platform";
    // 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);
    // register with autosubscribe and force (to unregister anyone that is already registered)
    SSHCommandResult result = 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 (servertasks.statusStandalone) {
        Assert.assertEquals(result.getStderr().trim(), "Development units may only be used on hosted servers and with orgs that have active subscriptions.", "Expected stderr when /etc/candlepin/candlepin candlepin.standalone=true  (typical of Satellite deployment).");
        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).");
    }
    // get the autosubscribed productSubscription
    List<ProductSubscription> productSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    Assert.assertEquals(productSubscriptions.size(), 1, "After registering (with autosubscribe) a system with dev_sku fact '" + devSku + "', only one product subscription should be consumed.");
    ProductSubscription devSkuProductSubscription1 = productSubscriptions.get(0);
    List<String> devSkuProductSubscriptionProvidedProductModifiedIds = new ArrayList<String>(CandlepinTasks.getPoolProvidedProductModifiedIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, devSkuProductSubscription1.poolId));
    // manually subscribe to any available pool and test
    List<SubscriptionPool> availableSubscriptionPools = clienttasks.getCurrentlyAvailableSubscriptionPools();
    for (SubscriptionPool subscriptionPool : getRandomSubsetOfList(availableSubscriptionPools, 3)) {
        // /*debugTesting*/ subscriptionPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("subscriptionName", "Awesome OS with up to 4 virtual guests", availableSubscriptionPools); // causes: 1 local certificate has been deleted.
        // manually subscribe to the available cost-based subscription
        clienttasks.subscribe(null, null, subscriptionPool.poolId, null, null, null, null, null, null, null, null, null, null);
        // assert that the consumed subscriptions still includes the consumed devSkuProductSubscription
        productSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
        ProductSubscription devSkuProductSubscription2 = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("poolId", devSkuProductSubscription1.poolId, productSubscriptions);
        Assert.assertNotNull(devSkuProductSubscription2, "After manually attaching a cost-based subscription, an entitlement for devSku '" + devSku + "' from pool id '" + devSkuProductSubscription1.poolId + "' is still being consumed.");
        // Assert.assertEquals(devSkuProductSubscription2.serialNumber, devSkuProductSubscription1.serialNumber, "After manually attaching a cost-based subscription, the same serial number from an entitlement for devSku '"+devSku+"' from pool id '"+devSkuProductSubscription1.poolId+"' is still being consumed.");
        // The prior assert on equal serial numbers fails when the devSkuProductSubscription1 provides a modifier product that modifies a provided product in subscriptionPool
        // Instead let's determine if devSkuProductSubscription1 does indeed provide modifier products that are modified by products provided by subscriptionPool...
        List<String> subscriptionPoolProvidedProductIds = CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, subscriptionPool.poolId);
        if (!doesListOverlapList(subscriptionPoolProvidedProductIds, devSkuProductSubscriptionProvidedProductModifiedIds)) {
            Assert.assertEquals(devSkuProductSubscription2.serialNumber, devSkuProductSubscription1.serialNumber, "After manually attaching a cost-based subscription, the same serial number from an entitlement for devSku '" + devSku + "' from pool id '" + devSkuProductSubscription1.poolId + "' is still being consumed (because the cost-based subscription does not provide any of the products " + devSkuProductSubscriptionProvidedProductModifiedIds + " that are modified by the provided modifier products of the devSku.");
        } else
            // save for the next loop's serial assert
            devSkuProductSubscription1.serialNumber = devSkuProductSubscription2.serialNumber;
    }
}
Also used : HashMap(java.util.HashMap) ProductSubscription(rhsm.data.ProductSubscription) ArrayList(java.util.ArrayList) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) JSONObject(org.json.JSONObject) SkipException(org.testng.SkipException) SubscriptionPool(rhsm.data.SubscriptionPool) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Aggregations

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