Search in sources :

Example 71 with ProductSubscription

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

the class MigrationTests method testRhnMigrateClassicToRhsmWithMultipleActivationKeys.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21893", "RHEL7-51749" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "Execute migration tool rhn-migrate-classic-to-rhsm with multiple --activation-key options specified", groups = { "Tier3Tests", "blockedByBug-1154375" }, enabled = true)
@ImplementsNitrateTest(caseId = 130765)
public void testRhnMigrateClassicToRhsmWithMultipleActivationKeys() throws Exception {
    if (clienttasks.isPackageVersion("subscription-manager", "<", "1.14.1-1"))
        throw new SkipException("The --activation-key option was not implemented in this version of subscription-manager.");
    // create valid activation keys
    // randomly choose a valid available pool for this key
    SubscriptionPool pool1 = getRandomListItem(availableSubscriptionPools);
    // choose an activationKey name
    String name1 = String.format("activationKeyForOrg_%s_Pool_%s", clientOrgKey, pool1.productId);
    JSONObject jsonActivationKey1 = CandlepinTasks.createActivationKeyUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, clientOrgKey, name1, Arrays.asList(pool1.poolId), null);
    // randomly choose a valid available pool for this key
    SubscriptionPool pool2 = getRandomListItem(availableSubscriptionPools);
    // choose an activationKey name
    String name2 = String.format("activationKeyForOrg_%s_Pool_%s", clientOrgKey, pool2.productId);
    JSONObject jsonActivationKey2 = CandlepinTasks.createActivationKeyUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, clientOrgKey, name2, Arrays.asList(pool2.poolId), null);
    // register with the activation keys
    if (false) {
        // debugTesting
        clienttasks.register_(null, null, clientOrgKey, null, null, null, null, null, null, null, Arrays.asList(name1, name2), null, null, null, true, null, null, null, null, null);
        clienttasks.unregister_(null, null, null, null);
    }
    // migrate from RHN Classic to RHSM using the activation key
    // TEMPORARY WORKAROUND FOR BUG
    // Bug 1196416 - rhn-migrate-classic-to-rhsm with --activation-key option should not prompt for destination credentials
    String bugId = "1196416";
    boolean invokeWorkaroundWhileBugIsOpen = true;
    try {
        if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
        } else {
            invokeWorkaroundWhileBugIsOpen = false;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    if (invokeWorkaroundWhileBugIsOpen) {
        testRhnMigrateClassicToRhsm(null, sm_rhnUsername, sm_rhnPassword, sm_rhnHostname, new ArrayList<String>(), "--activation-key=" + name1 + " " + "--activation-key=" + name2, sm_rhnUsername, sm_rhnPassword, sm_clientUsername, sm_clientPassword, clientOrgKey, null, null);
    } else
        // call RhnMigrateClassicToRhsm_Test with rhsmUsername=null and rhsmPassword=null
        // END OF WORKAROUND
        testRhnMigrateClassicToRhsm(null, sm_rhnUsername, sm_rhnPassword, sm_rhnHostname, new ArrayList<String>(), "--activation-key=" + name1 + " " + "--activation-key=" + name2 + " " + "--org=" + clientOrgKey, sm_rhnUsername, sm_rhnPassword, null, null, null, null, null);
    // assert that the system is consuming the pools from the activation key.
    List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    Assert.assertNotNull(ProductSubscription.findFirstInstanceWithMatchingFieldFromList("poolId", pool1.poolId, consumedProductSubscriptions), "Found consumed subscription from pool '" + pool1.poolId + "' after migrating with activation keys '" + name1 + "' and '" + name2 + "'.");
    Assert.assertNotNull(ProductSubscription.findFirstInstanceWithMatchingFieldFromList("poolId", pool2.poolId, consumedProductSubscriptions), "Found consumed subscription from pool '" + pool2.poolId + "' after migrating with activation keys '" + name1 + "' and '" + name2 + "'.");
    Assert.assertEquals(consumedProductSubscriptions.size(), 2, "Number of consumed subscriptions after migrating from RHN Classic to RHSM with activation keys '" + name1 + "' and '" + name2 + "'.");
}
Also used : JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) SkipException(org.testng.SkipException) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) SubscriptionPool(rhsm.data.SubscriptionPool) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 72 with ProductSubscription

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

the class StatusTests method testStatusOnFutureDate.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-19967", "RHEL7-33081" }, 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 = "run subscription-manager status ondate (tomorrow and a future date after one of today's entitlements expire)", groups = { "Tier1Tests", "blockedByBug-1500106" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testStatusOnFutureDate() throws JSONException, Exception {
    if (clienttasks.isPackageVersion("subscription-manager", "<", "1.9.2-1"))
        throw new SkipException("Installed package '" + clienttasks.installedPackageVersionMap.get("subscription-manager") + "' does not support status --ondate option.  It was introduced in subscription-manager-1.9.2-1.");
    // register with autosubscribe to establish today's status
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, true, null, null, null, null, null);
    clienttasks.subscribeToTheCurrentlyAvailableSubscriptionPoolsCollectively();
    // make sure at least one installed product was subscribed, otherwise this test is not applicable
    List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts();
    boolean noInstalledProducts = installedProducts.isEmpty();
    boolean areAnyInstalledProductsSubscribable = false;
    for (InstalledProduct installedProduct : installedProducts) {
        if (installedProduct.status.equals("Subscribed") || installedProduct.status.equals("Partially Subscribed")) {
            areAnyInstalledProductsSubscribable = true;
            break;
        }
    }
    // get today's status
    SSHCommandResult statusResultToday = clienttasks.status(null, null, null, null, null);
    Map<String, String> statusMapToday = getProductStatusMapFromStatusResult(statusResultToday);
    // get tomorrow's status
    DateFormat yyyy_MM_dd_DateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar tomorrow = new GregorianCalendar();
    tomorrow.add(Calendar.HOUR, 24);
    String onDateTomorrow = yyyy_MM_dd_DateFormat.format(tomorrow.getTime());
    SSHCommandResult statusResultTomorrow = clienttasks.status(onDateTomorrow, null, null, null, null);
    Map<String, String> statusMapTomorrow = getProductStatusMapFromStatusResult(statusResultTomorrow);
    // assert tomorrow's status is identical to today's (assumes no change in coverage)
    Assert.assertTrue(statusMapTomorrow.equals(statusMapToday), "Asserting the assumption that the status --ondate=tomorrow will be identical to the status ondate=today (default).");
    // now let's find the most future endDate of all current entitlement and assert that the status on the following day is different and Invalid
    List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    if (consumedProductSubscriptions.isEmpty())
        throw new SkipException("The remainder of this test cannot be executed because we expect this system to have at least one consumed entitlement.");
    Calendar future = consumedProductSubscriptions.get(0).startDate;
    for (ProductSubscription productSubscription : consumedProductSubscriptions) if (productSubscription.endDate.after(future))
        future = productSubscription.endDate;
    // add one day
    future.add(Calendar.HOUR, 24);
    String onDateFuture = yyyy_MM_dd_DateFormat.format(future.getTime());
    SSHCommandResult statusResultFuture = clienttasks.status(onDateFuture, null, null, null, null);
    Map<String, String> statusMapFuture = getProductStatusMapFromStatusResult(statusResultFuture);
    // assert future status is NOT identical to today's (assumes entitlements have expired)
    log.info("Status Map ondate=today: " + statusMapToday);
    log.info("Status Map ondate=future: " + statusMapFuture);
    if (areAnyInstalledProductsSubscribable || noInstalledProducts) {
        Assert.assertTrue(!statusMapFuture.equals(statusMapToday), "Asserting that the status --ondate=future (the day after an entitlement expires) will NOT be identical to the status ondate=today (default).");
    } else {
        Assert.assertTrue(statusMapFuture.equals(statusMapToday), "Asserting that the status --ondate=future (the day after an entitlement expires) will be identical to the status ondate=today (default) because none of the subscriptions applied today provide coverage for the products installed today.");
    }
    // assert future status
    if (noInstalledProducts) {
        String expectedStatus = "Overall Status: Current";
        Assert.assertTrue(statusResultFuture.getStdout().contains(expectedStatus), "Expecting '" + expectedStatus + "' onDate '" + onDateFuture + "' which is one day beyond the most future endDate of the currently consumed subscriptions - when there are no installed products.");
    } else {
        String expectedStatus = "Overall Status: Invalid";
        Assert.assertTrue(statusResultFuture.getStdout().contains(expectedStatus), "Expecting '" + expectedStatus + "' onDate '" + onDateFuture + "' which is one day beyond the most future endDate of the currently consumed subscriptions.");
    }
}
Also used : GregorianCalendar(java.util.GregorianCalendar) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) ProductSubscription(rhsm.data.ProductSubscription) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) InstalledProduct(rhsm.data.InstalledProduct) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) SkipException(org.testng.SkipException) SimpleDateFormat(java.text.SimpleDateFormat) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 73 with ProductSubscription

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

the class SubscribeTests method testCandlepinConsumerEntitlementsDryrunWithServiceLevel.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-19983", "RHEL7-51017" }, 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: call the Candlepin API dry_run to get the pools and quantity that would be used to complete an autosubscribe with a valid service level", groups = { "Tier1Tests", "blockedByBug-859652", "blockedByBug-962520" }, dataProvider = "getSubscribeWithAutoAndServiceLevelData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testCandlepinConsumerEntitlementsDryrunWithServiceLevel(Object bugzilla, String serviceLevel) throws JSONException, Exception {
    // Reference: https://engineering.redhat.com/trac/Entitlement/wiki/SlaSubscribe
    // "GET"
    // "url": "/consumers/{consumer_uuid}/entitlements/dry-run?service_level=#{service_level}",
    String consumerId = clienttasks.getCurrentConsumerId();
    // this will remove any prior subscribed modifier entitlements to avoid test logic errors in this test.
    if (firstcalltoCandlepinConsumerEntitlementsDryrunWithServiceLevel_Test) {
        // OR clienttasks.unregister(null,null,null);
        if (consumerId != null)
            clienttasks.unsubscribe(true, (BigInteger) null, null, null, null, null, null);
        firstcalltoCandlepinConsumerEntitlementsDryrunWithServiceLevel_Test = false;
    }
    // store the initial state of the system
    if (consumerId == null)
        consumerId = clienttasks.getCurrentConsumerId(clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, "SubscriptionServiceLevelConsumer", null, null, null, null, (String) null, null, null, null, null, false, null, null, null, null));
    // clienttasks.getCurrentlyRegisteredOwnerKey();
    String orgKey = CandlepinTasks.getOwnerKeyOfConsumerId(sm_clientUsername, sm_clientPassword, sm_serverUrl, consumerId);
    String initialServiceLevel = clienttasks.getCurrentServiceLevel();
    List<EntitlementCert> initialEntitlementCerts = clienttasks.getCurrentEntitlementCerts();
    List<SubscriptionPool> initialAvailableSubscriptionPools = clienttasks.getCurrentlyAvailableSubscriptionPools();
    // get the current exempt service levels
    List<String> exemptServiceLevels = CandlepinTasks.getServiceLevelsForOrgKey(sm_clientUsername, sm_clientPassword, sm_serverUrl, orgKey, true);
    List<String> exemptServiceLevelsInUpperCase = new ArrayList<String>();
    for (String exemptServiceLevel : exemptServiceLevels) exemptServiceLevelsInUpperCase.add(exemptServiceLevel.toUpperCase());
    // call the candlepin API
    // curl --insecure --user testuser1:password --request GET https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/consumers/7033f5c0-c451-4d4c-bf88-c5061dc2c521/entitlements/dry-run?service_level=Premium | python -m simplejson/tool
    // urlEncode is needed to handle whitespace in the serviceLevel
    JSONArray jsonDryrunResults = new JSONArray(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, String.format("/consumers/%s/entitlements/dry-run%s", consumerId, serviceLevel == null ? "" : String.format("?service_level=%s", urlEncode(serviceLevel)))));
    // List<SubscriptionPool> dryrunSubscriptionPools = new ArrayList<SubscriptionPool>();
    for (int i = 0; i < jsonDryrunResults.length(); i++) {
        // jsonDryrunResults is an array of two values per entry: "pool" and "quantity"
        JSONObject jsonPool = ((JSONObject) jsonDryrunResults.get(i)).getJSONObject("pool");
        Integer quantity = ((JSONObject) jsonDryrunResults.get(i)).getInt("quantity");
        // assert that all of the pools proposed provide the requested service level (or a no support_level is now a valid contender based on Bug 1223560 - Service levels on an activation key prevent custom products from attaching at registration if auto-attach enabled)
        String poolId = jsonPool.getString("id");
        String poolProductAttributeSupportLevel = CandlepinTasks.getPoolProductAttributeValue(jsonPool, "support_level");
        SubscriptionPool subscriptionPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", poolId, initialAvailableSubscriptionPools);
        // dryrunSubscriptionPools.add(subscriptionPool);
        if (serviceLevel == null || serviceLevel.isEmpty()) {
            log.info("Without requesting a service-level, pool '" + poolId + "' returned by the dry-run results  has a support_level of '" + poolProductAttributeSupportLevel + "'.");
        } else if (poolProductAttributeSupportLevel == null || poolProductAttributeSupportLevel.isEmpty()) {
            // candlepin commit 9cefb6e23baefcc4ee2e14423f205edd37eecf22
            log.info("Despite the requested service-level '" + serviceLevel + "', pool '" + poolId + "' returned by the dry-run results has a support_level of '" + poolProductAttributeSupportLevel + "'.  (Requested behavior from bug https://bugzilla.redhat.com/show_bug.cgi?id=1223560)");
        } else if (exemptServiceLevelsInUpperCase.contains(poolProductAttributeSupportLevel.toUpperCase())) {
            log.info("Pool '" + poolId + "' returned by the dry-run results provides the exempt support_level '" + poolProductAttributeSupportLevel + "'.");
        } else {
            // CASE SENSITIVE ASSERTION Assert.assertEquals(support_level, serviceLevel,"Pool '"+poolId+"' returned by the dry-run results provides the requested service-level '"+serviceLevel+"'.");
            Assert.assertTrue(serviceLevel.equalsIgnoreCase(poolProductAttributeSupportLevel), "Pool '" + poolId + "' returned by the dry-run results provides a case-insensitive support_level '" + poolProductAttributeSupportLevel + "' match to the requested service-level '" + serviceLevel + "'.");
        }
        Assert.assertNotNull(subscriptionPool, "Pool '" + poolId + "' returned by the dry-run results for service-level '" + serviceLevel + "' was found in the list --available.");
        Assert.assertTrue(quantity <= (subscriptionPool.quantity.equalsIgnoreCase("unlimited") ? quantity + 1 : Integer.valueOf(subscriptionPool.quantity)), "Pool '" + poolId + "' returned by the dry-run results for service-level '" + serviceLevel + "', will supply a quantity (" + quantity + ") that is within the available quantity (" + subscriptionPool.quantity + ").");
    }
    // TODO: This assert is not reliable unless there really is a pool that provides a product that is actually installed.
    // Assert.assertTrue(jsonDryrunResults.length()>0, "Dry-run results for service-level '"+serviceLevel+"' are not empty.");
    // assert the the dry-run did not change the current service level
    Assert.assertEquals(clienttasks.getCurrentServiceLevel(), initialServiceLevel, "The consumer's current service level setting was not affected by the dry-run query with serviceLevel '" + serviceLevel + "'.");
    clienttasks.identity(null, null, true, null, null, null, null, null);
    Assert.assertEquals(clienttasks.getCurrentServiceLevel(), initialServiceLevel, "The consumer's current service level setting was not affected by the dry-run query with serviceLevel '" + serviceLevel + "' even after an identity regeneration.");
    // assert that no new entitlements were actually given
    Assert.assertTrue(clienttasks.getCurrentEntitlementCerts().containsAll(initialEntitlementCerts), "This system's prior entitlements are unchanged after the dry-run.");
    // actually autosubscribe with this service-level
    clienttasks.subscribe(true, serviceLevel, (List<String>) null, (List<String>) null, (List<String>) null, null, null, null, null, null, null, null, null);
    // clienttasks.subscribe(true,"".equals(serviceLevel)?String.format("\"%s\"", serviceLevel):serviceLevel, (List<String>)null, (List<String>)null, (List<String>)null, null, null, null, null, null, null);
    // determine the newly granted entitlement certs
    List<ProductSubscription> currentlyConsumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    List<EntitlementCert> newlyGrantedEntitlementCerts = new ArrayList<EntitlementCert>();
    List<EntitlementCert> currentlyGrantedEntitlementCerts = clienttasks.getCurrentEntitlementCerts();
    for (EntitlementCert entitlementCert : currentlyGrantedEntitlementCerts) {
        if (!initialEntitlementCerts.contains(entitlementCert)) {
            newlyGrantedEntitlementCerts.add(entitlementCert);
            if (serviceLevel == null || serviceLevel.equals("")) {
                log.info("Without specifying a service level preference, the service level provided by the entitlement cert granted after autosubscribe is '" + entitlementCert.orderNamespace.supportLevel + "'.");
            } else if (entitlementCert.orderNamespace.supportLevel == null || entitlementCert.orderNamespace.supportLevel.isEmpty()) {
                // candlepin commit 9cefb6e23baefcc4ee2e14423f205edd37eecf22
                log.info("Despite the requested service-level '" + serviceLevel + "', the entitlement cert granted after autosubscribe has a support_level of '" + entitlementCert.orderNamespace.supportLevel + "'.  (Requested behavior from bug https://bugzilla.redhat.com/show_bug.cgi?id=1223560)");
            } else if (entitlementCert.orderNamespace.supportLevel != null && exemptServiceLevelsInUpperCase.contains(entitlementCert.orderNamespace.supportLevel.toUpperCase())) {
                log.info("After autosubscribe with service level '" + serviceLevel + "', this autosubscribed entitlement provides an exempt service level '" + entitlementCert.orderNamespace.supportLevel + "' from entitled orderNamespace: " + entitlementCert.orderNamespace);
            } else {
                // CASE SENSITIVE ASSERTION Assert.assertEquals(entitlementCert.orderNamespace.supportLevel,serviceLevel,"The service level provided by the entitlement cert granted after autosubscribe matches the requested servicelevel.");
                Assert.assertTrue(serviceLevel.equalsIgnoreCase(entitlementCert.orderNamespace.supportLevel), "Ignoring case, the service level '" + entitlementCert.orderNamespace.supportLevel + "' provided by the entitlement cert granted after autosubscribe matches the requested servicelevel '" + serviceLevel + "'.");
            }
        }
    }
    // [root@jsefler-6 ~]#  curl --stderr /dev/null --insecure --user testuser1:password --request GET https://jsefler-f14-candlepin.usersys.redhat.com:8443/candlepin/consumers/6474c913-4c2f-4283-bcf5-2fc2c44da3ef/entitlements/dry-run?service_level= | python -m simplejson/tool
    if ("".equals(serviceLevel)) {
        // log.warning("When testing dry-run with an empty string for service level, the jsonPools returned should match the service-level that the consumer object already has (unless the service-level granted is exempt).  This is different than calling subscription-manager subscribe --auto --service-level=\"\".");
        log.warning("When testing dry-run with an empty string for service level, the jsonPools returned should match the service-level that the consumer object already has (unless the service-level granted is exempt or null).  This is different than calling subscription-manager subscribe --auto --service-level=\"\".");
        if (!"".equals(initialServiceLevel)) {
            for (int i = 0; i < jsonDryrunResults.length(); i++) {
                // jsonDryrunResults is an array of two values per entry: "pool" and "quantity"
                JSONObject jsonPool = ((JSONObject) jsonDryrunResults.get(i)).getJSONObject("pool");
                Integer quantity = ((JSONObject) jsonDryrunResults.get(i)).getInt("quantity");
                String supportLevelExemptValue = CandlepinTasks.getPoolProductAttributeValue(jsonPool, "support_level_exempt");
                // assert that all of the pools proposed provide the consumer's initial service level
                String poolId = jsonPool.getString("id");
                SubscriptionPool dryrunSubscriptionPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", poolId, initialAvailableSubscriptionPools);
                // check for an exempt service level
                if (supportLevelExemptValue == null || !Boolean.valueOf(supportLevelExemptValue)) {
                    // when the support_level_exempt value is absent or true, then either...
                    if (dryrunSubscriptionPool.serviceLevel == null || dryrunSubscriptionPool.serviceLevel.isEmpty()) {
                        // case 1: the serviceLevel from the pool must be null or "" due to changes from Bug 1223560 candlepin commit 9cefb6e23baefcc4ee2e14423f205edd37eecf22; or...
                        log.info("When dry-run is called with an empty service-level, an entitlement from a pool with no support_level '" + dryrunSubscriptionPool.serviceLevel + "' was granted from the dry-run pool result: " + dryrunSubscriptionPool + ". (Note: This was newly possible by Bug 1223560).");
                    } else {
                        // case 2: the serviceLevel from the pool must match the consumer's initial support_level preference
                        Assert.assertTrue(dryrunSubscriptionPool.serviceLevel.equalsIgnoreCase(initialServiceLevel), "When dry-run is called with an empty service-level, the actual consumer's initially set service-level '" + initialServiceLevel + "' matches the service-level '" + dryrunSubscriptionPool.serviceLevel + "' granted from the dry-run pool result: " + dryrunSubscriptionPool + ". (EXCEPTION: This is not true when the service-level is exempt.)");
                    }
                } else {
                    log.info("An exempt service level '" + dryrunSubscriptionPool.serviceLevel + "' was included in the dry-run pool result: " + dryrunSubscriptionPool);
                }
            }
        }
        log.info("Skipping the remaining assertions in this test when the service-level is empty.");
        return;
    }
    // assert that one entitlement was granted per dry-run pool result
    // Assert.assertEquals(newlyGrantedEntitlementCerts.size(), jsonDryrunResults.length(),"The autosubscribe results granted the same number of entitlements as the dry-run pools returned.");
    /* Update after Bug 1223560: this is not a valid assertion because one of the newly granted entitlement could
		 * actually be a replacement for an original... e.g. a modifier entitlement might deleted and replaced by a new
		 * one since the modifyee was added.  Therefore it is better to assert that the TOTAL new ents was increased by
		 * the dryrun length.
		 */
    Assert.assertEquals(currentlyGrantedEntitlementCerts.size(), jsonDryrunResults.length() + initialEntitlementCerts.size(), "The total number of entitlement after autosubscribe increased by the number of entitlements returned from the dry-run pools.");
    // for (SubscriptionPool dryrunSubscriptionPool : dryrunSubscriptionPools) {
    for (int i = 0; i < jsonDryrunResults.length(); i++) {
        // jsonDryrunResults is an array of two values per entry: "pool" and "quantity"
        JSONObject jsonPool = ((JSONObject) jsonDryrunResults.get(i)).getJSONObject("pool");
        Integer quantity = ((JSONObject) jsonDryrunResults.get(i)).getInt("quantity");
        String poolId = jsonPool.getString("id");
        SubscriptionPool dryrunSubscriptionPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", poolId, initialAvailableSubscriptionPools);
        String supportLevelExemptValue = CandlepinTasks.getPoolProductAttributeValue(jsonPool, "support_level_exempt");
        EntitlementCert entitlementCert = clienttasks.getEntitlementCertCorrespondingToSubscribedPool(dryrunSubscriptionPool);
        if (entitlementCert == null) {
            // can occur when there are multiple available pools that provide coverage for the same installed product
            log.warning("After actually running auto-subscribe, the predicted dry-run pool '" + dryrunSubscriptionPool.poolId + "' was NOT among the attached subscriptions.  This is probably because there is another available pool that also provides the same provided products '" + dryrunSubscriptionPool.provides + "' (at least one of which is installed) which was granted instead of the dry-run pool.");
            // assert that the warning statement is true
            // the follow assertion may expectedly fail when the provided products exceeds one.
            // ProductSubscription consumedProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("provides", dryrunSubscriptionPool.provides, currentlyConsumedProductSubscriptions);	// THIS IS NOT SMART ENOUGH TO COMPARE THE provides List FOR EQUALITY, INSTEAD SEARCH FOR ANOTHER POOL BY THE SAME SKU
            // Assert.assertNotNull(consumedProductSubscription, "Found a consumed Product Subscription that provides the same products corresponding to dry-run pool: "+dryrunSubscriptionPool+"  (IF THIS FAILS, SEE WARNING ABOVE FOR PROBABLE EXPLANATION)");
            ProductSubscription consumedProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("productId", dryrunSubscriptionPool.productId, currentlyConsumedProductSubscriptions);
            Assert.assertNotNull(consumedProductSubscription, "Found a consumed Product Subscription for the same SKU corresponding to dry-run pool: " + dryrunSubscriptionPool + "  (IF THIS FAILS, SEE WARNING ABOVE FOR PROBABLE EXPLANATION)");
            Assert.assertEquals(Integer.valueOf(consumedProductSubscription.quantityUsed), quantity, "The actual entitlement quantityUsed matches the dry-run quantity results for pool :" + dryrunSubscriptionPool);
        } else {
            Assert.assertNotNull(entitlementCert, "Found an entitlement cert corresponding to dry-run pool: " + dryrunSubscriptionPool);
            Assert.assertTrue(newlyGrantedEntitlementCerts.contains(entitlementCert), "This entitlement cert is among the newly granted entitlement from the autosubscribe.");
            Assert.assertEquals(Integer.valueOf(entitlementCert.orderNamespace.quantityUsed), quantity, "The actual entitlement quantityUsed matches the dry-run quantity results for pool :" + dryrunSubscriptionPool);
        }
    }
    // for the sake of variability, let's unsubscribe from a randomly consumed subscription
    unsubscribeRandomly();
// clienttasks.unsubscribeFromAllOfTheCurrentlyConsumedProductSubscriptions();
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) ProductSubscription(rhsm.data.ProductSubscription) BigInteger(java.math.BigInteger) JSONObject(org.json.JSONObject) BigInteger(java.math.BigInteger) SubscriptionPool(rhsm.data.SubscriptionPool) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 74 with ProductSubscription

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

the class SubscribeTests method testSubscribeToSubscriptionPoolProductId.

// 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-19980", "RHEL7-33092" }, 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")
@// ; and assert the subscription pool is not available when it does not match the system hardware.",
Test(// ; and assert the subscription pool is not available when it does not match the system hardware.",
description = "subscription-manager-cli: subscribe consumer to subscription pool product id", dataProvider = "getAllSystemSubscriptionPoolProductData", groups = { "Tier1Tests", "blockedByBug-660713", "blockedByBug-806986", "blockedByBug-878986", "blockedByBug-962520", "blockedByBug-1008647", "blockedByBug-1009600", "blockedByBug-996993" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testSubscribeToSubscriptionPoolProductId(String productId, JSONArray bundledProductDataAsJSONArray) throws Exception {
    // /*debugTesting*/ if (!productId.equals("awesomeos-ul-quantity-virt")) throw new SkipException("debugTesting - Automator should comment out this line.");
    // /*debugTesting*/ if (!productId.equals("awesomeos-onesocketib")) throw new SkipException("debugTesting - Automator should comment out this line.");
    // /*debugTesting*/ if (!productId.equals("awesomeos-virt-4")) throw new SkipException("debugTesting - Automator should comment out this line.");
    // /*debugTesting*/ if (!productId.equals("awesomeos-virt-4")&&!productId.equals("awesomeos-ul-quantity-virt")&&!productId.equals("awesomeos-onesocketib")&&!productId.equals("awesomeos-instancebased")) throw new SkipException("debugTesting - Automator should comment out this line.");
    // /*debugTesting*/ if (!productId.equals("2cores-2ram-multiattr")) throw new SkipException("debugTesting - Automator should comment out this line.");
    // /*debugTesting*/ if (!productId.equals("RH0380468")) throw new SkipException("debugTesting - Automator should comment out this line.");
    // /*debugTesting*/ if (!productId.equals("RH00284")) throw new SkipException("debugTesting - Automator should comment out this line.");
    // /*debugTesting*/ if (!productId.equals("awesomeos-super-hypervisor")) throw new SkipException("debugTesting - Automator should comment out this line.");
    // /*debugTesting*/ if (!productId.equals("MCT3115")) throw new SkipException("debugTesting - Automator should comment out this line.");
    // is this system a virtual guest system or a physical system
    boolean systemIsGuest = Boolean.valueOf(clienttasks.getFactValue("virt.is_guest"));
    // begin test with a fresh register
    clienttasks.unregister(null, null, null, null);
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, null, false, null, null, null, null);
    // assert the subscription pool with the matching productId is available
    // clienttasks.getCurrentlyAvailableSubscriptionPools() is tested at the conclusion of this test
    SubscriptionPool pool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("productId", productId, clienttasks.getCurrentlyAllAvailableSubscriptionPools());
    // special case...
    if (pool == null) {
        // when pool is null, another likely cause is that all of the available subscriptions from the pools are being consumed, let's check...
        for (String poolId : CandlepinTasks.getPoolIdsForProductId(sm_clientUsername, sm_clientPassword, sm_serverUrl, clienttasks.getCurrentlyRegisteredOwnerKey(), productId)) {
            int quantity = (Integer) CandlepinTasks.getPoolValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, poolId, "quantity");
            int consumed = (Integer) CandlepinTasks.getPoolValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, poolId, "consumed");
            if (consumed >= quantity) {
                throw new SkipException("The total quantity '" + quantity + "' of subscriptions from poolId '" + poolId + "' for product '" + productId + "' are being consumed; hence this product subscription is appropriately not available to subscribe.");
            }
        }
    }
    Assert.assertNotNull(pool, "Expected SubscriptionPool with ProductId '" + productId + "' is available for subscribing.");
    // assemble a list of expected bundled product names
    List<String> bundledProductNames = new ArrayList<String>();
    for (int j = 0; j < bundledProductDataAsJSONArray.length(); j++) {
        JSONObject bundledProductAsJSONObject = (JSONObject) bundledProductDataAsJSONArray.get(j);
        String bundledProductId = bundledProductAsJSONObject.getString("productId");
        String bundledProductName = bundledProductAsJSONObject.getString("productName");
        bundledProductNames.add(bundledProductName);
    }
    // TEMPORARY WORKAROUND
    boolean invokeWorkaroundWhileBugIsOpen = true;
    // Bug 1016300 - the "Provides:" field in subscription-manager list --available should exclude "MKT" products.
    String bugId = "1016300";
    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, skip assertion that the actual list of SubscriptionPool provided product names " + pool.provides + " matches the expected list of bundledProductDataNames " + bundledProductNames + ".");
    } else /*if (clienttasks.isPackageVersion("subscription-manager",">=","1.10.3-1"))*/
    if (pool.provides != null) {
        // TEMPORARY WORKAROUND
        invokeWorkaroundWhileBugIsOpen = true;
        // Bug 1394401 - The list of provided products for Temporary Subscriptions is empty
        bugId = "1394401";
        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 && !bundledProductNames.isEmpty() && pool.provides.isEmpty() && pool.subscriptionType.contains("Temporary")) {
            log.warning("While bug '" + bugId + "' is open, skip assertion that the actual list of SubscriptionPool provided product names " + pool.provides + " matches the expected list of bundledProductDataNames " + bundledProductNames + ".");
        } else
            // END OF WORKAROUND
            // assert that the pool's list of Provides matches the list of bundled product names after implementation of Bug 996993 - [RFE] Search for or list matching providedProducts; subscription-manager commit b8738a74c1109975e387fc51105c8ff58eaa8f01
            Assert.assertTrue(bundledProductNames.containsAll(pool.provides) && pool.provides.containsAll(bundledProductNames), "The actual list of SubscriptionPool provided product names " + pool.provides + " matches the expected list of bundledProductDataNames " + bundledProductNames + ".  (If this fails due to provided Product Names changes by Release Engineering, refresh pools for account '" + sm_clientUsername + "' is needed.)");
    }
    List<ProductCert> currentlyInstalledProductCerts = clienttasks.getCurrentProductCerts();
    List<InstalledProduct> currentlyInstalledProducts = clienttasks.getCurrentlyInstalledProducts();
    // assert the installed status of the bundled products
    for (int j = 0; j < bundledProductDataAsJSONArray.length(); j++) {
        JSONObject bundledProductAsJSONObject = (JSONObject) bundledProductDataAsJSONArray.get(j);
        String bundledProductId = bundledProductAsJSONObject.getString("productId");
        // assert the status of the installed products listed
        for (ProductCert productCert : ProductCert.findAllInstancesWithMatchingFieldFromList("productId", bundledProductId, currentlyInstalledProductCerts)) {
            InstalledProduct installedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productName", productCert.productName, currentlyInstalledProducts);
            Assert.assertNotNull(installedProduct, "The status of installed product cert with ProductName '" + productCert.productName + "' is reported in the list of installed products.");
            Assert.assertEquals(installedProduct.status, "Not Subscribed", "Before subscribing to pool for ProductId '" + productId + "', the status of Installed Product '" + productCert.productName + "' is Not Subscribed.");
        }
    }
    // when the Suggested quantity is 0, let's specify a quantity to avoid Stdout: Quantity '1' is not a multiple of instance multiplier '2'
    // adjust quantity for instance_multiplier pools
    String instance_multiplier = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "instance_multiplier");
    String quantity = null;
    /*if (clienttasks.isPackageVersion("subscription-manager",">=","1.10.3-1"))*/
    if (pool.suggested != null) {
        if (pool.suggested < 1 && instance_multiplier != null) {
            quantity = instance_multiplier;
        }
    }
    boolean isPoolRestrictedToUnmappedVirtualSystems = CandlepinTasks.isPoolRestrictedToUnmappedVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId);
    // subscribe to the pool
    File entitlementCertFile = clienttasks.subscribeToSubscriptionPool(pool, quantity, /*sm_serverAdminUsername*/
    sm_clientUsername, /*sm_serverAdminPassword*/
    sm_clientPassword, sm_serverUrl);
    EntitlementCert entitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(entitlementCertFile);
    currentlyInstalledProducts = clienttasks.getCurrentlyInstalledProducts();
    List<ProductSubscription> currentlyConsumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    // after subscribing to a pool, assert that its corresponding productSubscription is found among the currently consumed productSubscriptions
    ProductSubscription consumedProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("productId", pool.productId, currentlyConsumedProductSubscriptions);
    Assert.assertNotNull(consumedProductSubscription, "The consumed ProductSubscription corresponding to the subscribed SubscriptionPool productId '" + pool.productId + "' was found among the list of consumed ProductSubscriptions.");
    // assert that the quantityUsed matches the quantitySuggested after implementation of Bug 1008647 - [RFE] bind requests that do not specify a quantity should automatically use the quantity needed to achieve compliance
    if (quantity != null) {
        Assert.assertEquals(consumedProductSubscription.quantityUsed, Integer.valueOf(quantity), "When the attachment quantity '" + quantity + "' is specified, the quantity used from the consumed product subscription should match.");
    } else {
        /*if (clienttasks.isPackageVersion("subscription-manager",">=","1.10.3-1"))*/
        if (pool.suggested != null) {
            if (pool.suggested > 1) {
                Assert.assertEquals(consumedProductSubscription.quantityUsed, pool.suggested, "When the suggested consumption quantity '" + pool.suggested + "' from the available pool is greater than one, the quantity used from the consumed product subscription should match.");
            } else {
                Assert.assertEquals(consumedProductSubscription.quantityUsed, Integer.valueOf(1), "When the suggested consumption quantity '" + pool.suggested + "' from the available pool is NOT greater than one, the quantity used from the consumed product subscription should be one.");
            }
        }
    }
    /*if (clienttasks.isPackageVersion("subscription-manager",">=","1.10.3-1"))*/
    if (consumedProductSubscription.machineType != null) {
        Assert.assertEquals(consumedProductSubscription.machineType, pool.machineType, "After subscribing from a pool with a machine type '" + pool.machineType + "', the consumed product subscription's machine type should match.");
    }
    // TEMPORARY WORKAROUND
    /*boolean*/
    invokeWorkaroundWhileBugIsOpen = true;
    // Bug 1204311 - Refreshing pools causes unexpected temporary pools for unmapped guests to become available
    bugId = "1204311";
    /*String*/
    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 && isPoolRestrictedToUnmappedVirtualSystems) {
        log.warning("While bug '" + bugId + "' is open and we have subscrbed to a Temporary pool, skip assertion that the consumed productSubscription provides all of the expected bundled product names " + bundledProductNames + " after subscribing to pool: " + pool);
    } else // END OF WORKAROUND
    {
        // TEMPORARY WORKAROUND
        invokeWorkaroundWhileBugIsOpen = true;
        // Bug 1394401 - The list of provided products for Temporary Subscriptions is empty
        bugId = "1394401";
        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 && isPoolRestrictedToUnmappedVirtualSystems) {
            log.warning("While bug '" + bugId + "' is open and we have subscrbed to a Temporary pool, skip assertion that the consumed productSubscription provides all of the expected bundled product names " + bundledProductNames + " after subscribing to pool: " + pool);
        } else
            // END OF WORKAROUND
            // assert that the consumed product subscription provides all the expected bundled products.
            Assert.assertTrue(consumedProductSubscription.provides.containsAll(bundledProductNames) && bundledProductNames.containsAll(consumedProductSubscription.provides), "The consumed productSubscription provides all of the expected bundled product names " + bundledProductNames + " after subscribing to pool: " + pool);
    }
    // assert the dates of the consumed product subscription...
    if (isPoolRestrictedToUnmappedVirtualSystems) {
        // ... assert endDate is 24 hours after the date of registration
        ConsumerCert cert = clienttasks.getCurrentConsumerCert();
        Calendar consumerCertStartDate = cert.validityNotBefore;
        int hours = 24;
        if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.1.0-1")) {
            // commit 0704a73dc0d3bf753351e87ca0b65d85a71acfbe 1450079: virt-who temporary subscription should be 7 days
            hours = 7 * /*days*/
            24;
            log.info("Due to Candlepin RFE Bug 1450079, the vailidity period for temporary subscription pools has increased from one day to one week.");
        }
        if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.0.30-1")) {
            // commit 9302c8f57f37dd5ec3c4020770ac1675a87d99ba 1419576: Pre-date certs to ease clock skew issues
            hours += 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.");
        }
        consumerCertStartDate.add(Calendar.HOUR, hours);
        Assert.assertEquals(ProductSubscription.formatDateString(consumedProductSubscription.endDate), ProductSubscription.formatDateString(consumerCertStartDate), "Consumed productSubscription (from a unmapped_guests_only pool '" + pool.poolId + "') expires '" + hours + "' hours after the time of consumer registration (" + ConsumerCert.formatDateString(clienttasks.getCurrentConsumerCert().validityNotBefore) + ").");
    // TODO Assert the start date after bug 1199670 is resolved
    } else {
        // ... assert endDate matches the originating subscription pool
        Assert.assertEquals(ProductSubscription.formatDateString(consumedProductSubscription.endDate), ProductSubscription.formatDateString(pool.endDate), "Consumed productSubscription expires on the same DAY as the originating subscription pool.");
    // FIXME	Assert.assertTrue(productSubscription.startDate.before(entitlementCert.validityNotBefore), "Consumed ProductSubscription Began before the validityNotBefore date of the new entitlement: "+entitlementCert);
    }
    // assert the expected products are consumed
    for (int j = 0; j < bundledProductDataAsJSONArray.length(); j++) {
        JSONObject bundledProductAsJSONObject = (JSONObject) bundledProductDataAsJSONArray.get(j);
        String bundledProductId = bundledProductAsJSONObject.getString("productId");
        String bundledProductName = bundledProductAsJSONObject.getString("productName");
        bundledProductNames.add(bundledProductName);
        // find the corresponding productNamespace from the entitlementCert
        ProductNamespace productNamespace = null;
        for (ProductNamespace pn : entitlementCert.productNamespaces) {
            if (pn.id.equals(bundledProductId))
                productNamespace = pn;
        }
        // TEMPORARY WORKAROUND
        invokeWorkaroundWhileBugIsOpen = true;
        // Bug 1394401 - The list of provided products for Temporary Subscriptions is empty
        bugId = "1394401";
        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 && !bundledProductNames.isEmpty() && pool.provides.isEmpty() && pool.subscriptionType.contains("Temporary")) {
            log.warning("While bug '" + bugId + "' is open, skip assertion of the consumed entitlement provided products amongst the list of install products.");
        } else // assert the installed status of the corresponding product
        if (entitlementCert.productNamespaces.isEmpty()) {
            log.warning("This product '" + productId + "' (" + bundledProductName + ") does not appear to grant entitlement to any client side content.  This must be a server side management add-on product. Asserting as such...");
            Assert.assertEquals(entitlementCert.contentNamespaces.size(), 0, "When there are no productNamespaces in the entitlementCert, there should not be any contentNamespaces.");
            // when there is no corresponding product, then there better not be an installed product status by the same product name
            Assert.assertNull(InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productName", bundledProductName, currentlyInstalledProducts), "Should not find any installed product status matching a server side management add-on productName: " + bundledProductName);
            // when there is no corresponding product, then there better not be an installed product cert by the same product name
            Assert.assertNull(ProductCert.findFirstInstanceWithMatchingFieldFromList("productName", bundledProductName, currentlyInstalledProductCerts), "Should not find any installed product certs matching a server side management add-on productName: " + bundledProductName);
        } else {
            Assert.assertNotNull(productNamespace, "The new entitlement cert's product namespace corresponding to this expected ProductSubscription with ProductName '" + bundledProductName + "' was found.");
            // assert the status of the installed products listed
            // should be a list of one or empty
            List<ProductCert> productCerts = ProductCert.findAllInstancesWithMatchingFieldFromList("productId", productNamespace.id, currentlyInstalledProductCerts);
            for (ProductCert productCert : productCerts) {
                List<InstalledProduct> installedProducts = InstalledProduct.findAllInstancesWithMatchingFieldFromList("productName", productCert.productName, currentlyInstalledProducts);
                Assert.assertEquals(installedProducts.size(), 1, "The status of installed product '" + productCert.productName + "' should only be reported once in the list of installed products.");
                InstalledProduct installedProduct = installedProducts.get(0);
                // TEMPORARY WORKAROUND FOR BUG
                if (installedProduct.arch.contains(",")) {
                    /*boolean*/
                    invokeWorkaroundWhileBugIsOpen = true;
                    // Bug 951633 - installed product with comma separated arch attribute fails to go green
                    bugId = "951633";
                    /*String*/
                    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("Verification for status of Installed Product name='" + installedProduct.productName + "' with arch='" + installedProduct.arch + "' is blocked by open bugzilla '" + bugId + "'.");
                    }
                }
                // END OF WORKAROUND
                // decide what the status should be...  "Subscribed" or "Partially Subscribed" (SPECIAL CASE WHEN poolProductSocketsAttribute=0  or "null" SHOULD YIELD Subscribed)
                String poolProductSocketsAttribute = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "sockets");
                // introduced by 885785 [RFE] Subscription Manager should alert a user if subscription vcpu limits are lower than system vcpu allocation
                String poolProductVcpuAttribute = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "vcpu");
                String poolProductArchAttribute = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "arch");
                List<String> poolProductArches = new ArrayList<String>();
                if (poolProductArchAttribute != null) {
                    // Note: the arch attribute can be a comma separated list of values
                    poolProductArches.addAll(Arrays.asList(poolProductArchAttribute.trim().split(" *, *")));
                    // Note: x86 is a general arch to cover all 32-bit intel microprocessors
                    if (poolProductArches.contains("x86")) {
                        poolProductArches.addAll(Arrays.asList("i386", "i486", "i586", "i686"));
                    }
                    if (poolProductArches.contains("ALL"))
                        poolProductArches.add(clienttasks.arch);
                }
                // if the sockets attribute is not numeric (e.g. "null"),  then this subscription should be available to this client
                try {
                    Integer.valueOf(poolProductSocketsAttribute);
                } catch (NumberFormatException e) {
                    // do not mark productAttributesPassRulesCheck = false;
                    log.warning("Ecountered a non-numeric value for product sockets attribute sockets on productId='" + productId + "' poolId '" + pool.poolId + "'. SIMPLY IGNORING THIS ATTRIBUTE.");
                    poolProductSocketsAttribute = null;
                }
                // consider the socket/vcpu coverage and assert the installed product's status
                if (isPoolRestrictedToUnmappedVirtualSystems && false) /*since 1200882 was CLOSED NOTABUG, never run the assertion in this if condition*/
                {
                    // TEMPORARY WORKAROUND
                    /*boolean*/
                    invokeWorkaroundWhileBugIsOpen = true;
                    // Bug 1200882 - Wrong installed product status is displayed when a unmapped_guests_only pool is attached
                    bugId = "1200882";
                    /*String*/
                    try {
                        if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
                            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
                            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
                        } else {
                            invokeWorkaroundWhileBugIsOpen = false;
                        }
                    } catch (BugzillaAPIException be) {
                    /* ignore exception */
                    } catch (RuntimeException re) {
                    /* ignore exception */
                    }
                    if (invokeWorkaroundWhileBugIsOpen) {
                        log.warning("Skipping the assertion of the installed product status after subscribing to an unmapped_guests_only pool for ProductId '" + productId + "' while bug '" + bugId + "' is open.");
                    } else
                        // END OF WORKAROUND
                        // for more info, see bugzilla https://bugzilla.redhat.com/show_bug.cgi?id=1197897	// CLOSED NOTABUG
                        Assert.assertEquals(installedProduct.status, "Partially Subscribed", "After subscribing to an unmapped_guests_only pool for ProductId '" + productId + "', the status of Installed Product '" + bundledProductName + "' should be Partially Subscribed regardless of any hardware socket/vcpu coverage or other subscriptions attached.");
                } else if (pool.subscriptionType != null && pool.subscriptionType.equals("Other")) {
                    Assert.fail("Encountered a subscription pool of type '" + pool.subscriptionType + "'.  Do not know how to assert the installedProduct.status after subscribing to pool: " + pool);
                } else if (pool.multiEntitlement == null && pool.subscriptionType != null && pool.subscriptionType.isEmpty()) {
                    log.warning("Encountered a pool with an empty value for subscriptionType (indicative of an older candlepin server): " + pool);
                    log.warning("After subscribing to a pool for ProductId '" + productId + ", skipping assertion of the installed product status for products provided by this pool: " + pool);
                } else if (pool.multiEntitlement != null && !pool.multiEntitlement && /*ADDED AFTER IMPLEMENTATION OF BUG 1008647*/
                !systemIsGuest && /*ADDED AFTER IMPLEMENTATION OF BUG 885785*/
                poolProductSocketsAttribute != null && Integer.valueOf(poolProductSocketsAttribute) < Integer.valueOf(clienttasks.sockets) && Integer.valueOf(poolProductSocketsAttribute) > 0) {
                    Assert.assertEquals(installedProduct.status, "Partially Subscribed", "After subscribing this physical system to a pool for ProductId '" + productId + "' (covers '" + poolProductSocketsAttribute + "' sockets), the status of Installed Product '" + bundledProductName + "' should be Partially Subscribed since a corresponding product cert was found in " + clienttasks.productCertDir + " and the machine's sockets value (" + clienttasks.sockets + ") is greater than what a single subscription from a non-multi-entitlement pool covers.");
                } else if (pool.subscriptionType != null && (pool.subscriptionType.equals("Standard") || pool.subscriptionType.equals("Stackable only with other subscriptions")) && /*ADDED AFTER IMPLEMENTATION OF BUG 1008647 AND 1029968*/
                !systemIsGuest && /*ADDED AFTER IMPLEMENTATION OF BUG 885785*/
                poolProductSocketsAttribute != null && Integer.valueOf(poolProductSocketsAttribute) < Integer.valueOf(clienttasks.sockets) && Integer.valueOf(poolProductSocketsAttribute) > 0) {
                    Assert.assertEquals(installedProduct.status, "Partially Subscribed", "After subscribing this physical system to a pool for ProductId '" + productId + "' (covers '" + poolProductSocketsAttribute + "' sockets), the status of Installed Product '" + bundledProductName + "' should be Partially Subscribed since a corresponding product cert was found in " + clienttasks.productCertDir + " and the machine's sockets value (" + clienttasks.sockets + ") is greater than what a single subscription from a non-multi-entitlement pool covers.");
                } else if (pool.multiEntitlement != null && !pool.multiEntitlement && /*ADDED AFTER IMPLEMENTATION OF BUG 1008647*/
                systemIsGuest && /*ADDED AFTER IMPLEMENTATION OF BUG 885785*/
                poolProductVcpuAttribute != null && Integer.valueOf(poolProductVcpuAttribute) < Integer.valueOf(clienttasks.vcpu) && Integer.valueOf(poolProductVcpuAttribute) > 0) {
                    Assert.assertEquals(installedProduct.status, "Partially Subscribed", "After subscribing this virtual system to a pool for ProductId '" + productId + "' (covers '" + poolProductVcpuAttribute + "' vcpu), the status of Installed Product '" + bundledProductName + "' should be Partially Subscribed since a corresponding product cert was found in " + clienttasks.productCertDir + " and the machine's vcpu value (" + clienttasks.vcpu + ") is greater than what a single subscription from a non-multi-entitlement pool covers.");
                } else if (pool.subscriptionType != null && (pool.subscriptionType.equals("Standard") || pool.subscriptionType.equals("Stackable only with other subscriptions")) && /*ADDED AFTER IMPLEMENTATION OF BUG 1008647 AND 1029968*/
                systemIsGuest && /*ADDED AFTER IMPLEMENTATION OF BUG 885785*/
                poolProductVcpuAttribute != null && Integer.valueOf(poolProductVcpuAttribute) < Integer.valueOf(clienttasks.vcpu) && Integer.valueOf(poolProductVcpuAttribute) > 0) {
                    Assert.assertEquals(installedProduct.status, "Partially Subscribed", "After subscribing this virtual system to a pool for ProductId '" + productId + "' (covers '" + poolProductVcpuAttribute + "' vcpu), the status of Installed Product '" + bundledProductName + "' should be Partially Subscribed since a corresponding product cert was found in " + clienttasks.productCertDir + " and the machine's vcpu value (" + clienttasks.vcpu + ") is greater than what a single subscription from a non-multi-entitlement pool covers.");
                } else if (!poolProductArches.contains(clienttasks.arch)) {
                    log.warning("This case is indicative that a pool refresh may be needed for this owner.");
                    Assert.assertEquals(installedProduct.status, "Partially Subscribed", "After subscribing this system with arch '" + clienttasks.arch + "' to a pool for ProductId '" + productId + "' (that supports '" + poolProductArchAttribute + "' arch), the status of Installed Product '" + bundledProductName + "' should be Partially Subscribed with a reason stating that the system's arch is not supported by this subscription.");
                    // Example Status Details:    Supports architecture x86_64,ppc64,ia64,ppc,x86,s390,s390x but the system is ppc64le.
                    String reason = String.format("Supports architecture %s but the system is %s.", poolProductArchAttribute, clienttasks.arch);
                    Assert.assertTrue(installedProduct.statusDetails.contains(reason), "Installed Product '" + installedProduct.productName + "' Status Details includes '" + reason + "'.");
                } else {
                    Assert.assertEquals(installedProduct.status, "Subscribed", "After subscribing to a pool for ProductId '" + productId + "', the status of Installed Product '" + bundledProductName + "' is Subscribed since a corresponding product cert was found in " + clienttasks.productCertDir + " and the system's sockets/vcpu needs were met.");
                }
                // TEMPORARY WORKAROUND
                /*boolean*/
                invokeWorkaroundWhileBugIsOpen = true;
                // Bug 1199443 - Wrong "End date" in installed list after attaching 24-hour subscription on a unmapped-guest
                bugId = "1199443";
                /*String*/
                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 && isPoolRestrictedToUnmappedVirtualSystems) {
                    log.warning("Skipping the assertion of installed product start-end date range after subscribing to an unmapped_guests_only pool for ProductId '" + productId + "' while bug '" + bugId + "' is open.");
                } else // Assert.assertEquals(InstalledProduct.formatDateString(installedProduct.startDate), ProductSubscription.formatDateString(productSubscription.startDate), "Installed Product '"+bundledProductName+"' starts on the same DAY as the consumed ProductSubscription: "+productSubscription);
                if (installedProduct.status.equals("Subscribed")) {
                    // assert the valid date range on the installed product match the validity period of the product subscription
                    Assert.assertEquals(InstalledProduct.formatDateString(installedProduct.endDate), ProductSubscription.formatDateString(consumedProductSubscription.endDate), "Installed Product '" + bundledProductName + "' expires on the same DAY as the consumed ProductSubscription: " + consumedProductSubscription);
                    Assert.assertEquals(InstalledProduct.formatDateString(installedProduct.startDate), ProductSubscription.formatDateString(consumedProductSubscription.startDate), "Installed Product '" + bundledProductName + "' starts on the same DAY as the consumed ProductSubscription: " + consumedProductSubscription);
                } else {
                    /* valid assertion before Bug 990639 - Update information displayed on My Installed Products tab when product is partially subscribed
						// assert the date range on the installed product is None
						Assert.assertNull(installedProduct.startDate, "Installed Product '"+bundledProductName+"' start date range should be None/null when today's status '"+installedProduct.status+"' is NOT fully Subscribed.");
						Assert.assertNull(installedProduct.endDate, "Installed Product '"+bundledProductName+"' end date range should be None/null when today's status '"+installedProduct.status+"' is NOT fully Subscribed.");
						*/
                    // assert the date range on the installed product is NOT None
                    Assert.assertNotNull(installedProduct.startDate, "Installed Product '" + bundledProductName + "' start date range should NOT be None/null even when today's status '" + installedProduct.status + "' is NOT fully Subscribed.");
                    Assert.assertNotNull(installedProduct.endDate, "Installed Product '" + bundledProductName + "' end date range should NOT be None/null even when today's status '" + installedProduct.status + "' is NOT fully Subscribed.");
                }
            }
            if (productCerts.isEmpty()) {
                Assert.assertNull(InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productName", bundledProductName, currentlyInstalledProducts), "There should NOT be an installed status report for '" + bundledProductName + "' since a corresponding product cert was not found in " + clienttasks.productCertDir);
            }
        }
    }
// TODO I BELIEVE THIS FINAL BLOCK OF TESTING IS INACCURATE - jsefler 5/27/2012
// I THINK IT SHOULD BE CHECKING HARDWARE SOCKETS AND NOT INSTALLED SOFTWARE
/*
		// check if this subscription matches the installed software and then test for availability
		boolean subscriptionProductIdMatchesInstalledSoftware = false;
		for (ContentNamespace contentNamespace : entitlementCert.contentNamespaces) {
			if (clienttasks.areAllRequiredTagsInContentNamespaceProvidedByProductCerts(contentNamespace, currentlyInstalledProductCerts)) {
				subscriptionProductIdMatchesInstalledSoftware=true; break;
			}
		}
		clienttasks.unsubscribeFromSerialNumber(entitlementCert.serialNumber);
		pool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("productId", productId, clienttasks.getCurrentlyAvailableSubscriptionPools());
		if (currentlyInstalledProductCerts.isEmpty()) {
			log.info("A final assertion to verify that SubscriptionPool with ProductId '"+productId+"' is available based on matching installed software is not applicable when the list of installed software is empty.");
		} else {
			if (subscriptionProductIdMatchesInstalledSoftware) {
				Assert.assertNotNull(pool, "Expected SubscriptionPool with ProductId '"+productId+"' matches the installed software and is available for subscribing when listing --available.");
			} else {
				Assert.assertNull(pool, "Expected SubscriptionPool with ProductId '"+productId+"' does NOT match the installed software and is only available for subscribing when listing --all --available.");
			}
		}
		*/
}
Also used : ArrayList(java.util.ArrayList) InstalledProduct(rhsm.data.InstalledProduct) ArrayList(java.util.ArrayList) List(java.util.List) SkipException(org.testng.SkipException) EntitlementCert(rhsm.data.EntitlementCert) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) ProductSubscription(rhsm.data.ProductSubscription) ProductCert(rhsm.data.ProductCert) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) ProductNamespace(rhsm.data.ProductNamespace) BigInteger(java.math.BigInteger) JSONObject(org.json.JSONObject) SubscriptionPool(rhsm.data.SubscriptionPool) File(java.io.File) ConsumerCert(rhsm.data.ConsumerCert) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 75 with ProductSubscription

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

the class SubscribeTests method testSubscribeToASingleEntitlementByProductId_DEPRECATED.

@Test(description = "subscription-manager-cli: subscribe consumer to an entitlement using product ID", groups = { "Tier2Tests", "blockedByBug-584137" }, // old/disabled test from ssalevan
enabled = false)
@Deprecated
public void testSubscribeToASingleEntitlementByProductId_DEPRECATED() {
    clienttasks.unsubscribeFromTheCurrentlyConsumedProductSubscriptionSerialsIndividually();
    SubscriptionPool MCT0696 = new SubscriptionPool("MCT0696", "696");
    MCT0696.addProductID("Red Hat Directory Server");
    clienttasks.subscribeToSubscriptionPoolUsingProductId(MCT0696);
    // this.refreshSubscriptions();
    for (ProductSubscription pid : MCT0696.associatedProductIDs) {
        Assert.assertTrue(clienttasks.getCurrentlyConsumedProductSubscriptions().contains(pid), "ProductID '" + pid.productName + "' consumed from Pool '" + MCT0696.subscriptionName + "'");
    }
}
Also used : ProductSubscription(rhsm.data.ProductSubscription) SubscriptionPool(rhsm.data.SubscriptionPool) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Aggregations

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