Search in sources :

Example 51 with ProductSubscription

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

the class DevSKUTests method testAutosubscribeAfterChangingDevSkuFacts.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21993", "RHEL7-51855" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.NEGATIVE, 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, alter the dev_sku facts, re-autosubscribe, and verify the initial entitlement was purged", groups = { "Tier1Tests", "blockedByBug-1295452" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testAutosubscribeAfterChangingDevSkuFacts() throws JSONException, Exception {
    if (servertasks.statusStandalone) {
        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).");
    }
    boolean isGuest = Boolean.valueOf(clienttasks.getFactValue("virt.is_guest"));
    // register with force to get a fresh consumer
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, false, null, null, (List<String>) null, null, null, null, true, false, null, null, null, null);
    // find two value SKUs that can be used as a dev_sku
    List<SubscriptionPool> subscriptionPools = clienttasks.getCurrentlyAvailableSubscriptionPools();
    // /*debugTesting*/subscriptionPools = SubscriptionPool.findAllInstancesWithMatchingFieldFromList("productId", "awesomeos-virt-datacenter", subscriptionPools);
    String devSku1 = null, devSku2 = null;
    for (SubscriptionPool subscriptionPool : getRandomList(subscriptionPools)) {
        // Unable to attach subscription for the product 'RH00003': rulefailed.quantity.mismatch.
        if (!subscriptionPool.suggested.equals(Integer.valueOf(1))) {
            boolean invokeWorkaroundWhileBugIsOpen = true;
            // Bug 1463320 - choosing a dev_sku that requires a quantity>1 will fail to auto-attach with error: rulefailed.quantity.mismatch.
            String bugId = "1463320";
            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.info("Excluding subscription '" + subscriptionPool.productId + "' as a dev_sku candidate because its suggested quantity '" + subscriptionPool.suggested + "' is not 1 while bug '" + bugId + "' is open.");
                continue;
            }
        }
        // avoid "Unable to attach subscription for the product 'RH00003': rulefailed.quantity.mismatch." since Bug 1463320 was CLOSED NOTABUG
        if (!subscriptionPool.suggested.equals(Integer.valueOf(1))) {
            log.info("Excluding subscription '" + subscriptionPool.productId + "' as a dev_sku candidate because its suggested quantity '" + subscriptionPool.suggested + "' is not 1 which is NOT indicative of a realistic dev_sku subscription.  Reference https://bugzilla.redhat.com/show_bug.cgi?id=1463320#c1");
            continue;
        }
        // avoid "Unable to attach subscription for the product 'awesomeos-virt-datacenter': rulefailed.physical.only.
        if (isGuest && CandlepinTasks.isPoolProductPhysicalOnly(sm_clientUsername, sm_clientPassword, subscriptionPool.poolId, sm_serverUrl)) {
            log.info("Excluding subscription '" + subscriptionPool.productId + "' as a dev_sku candidate because its physical_only productAttribute is NOT indicative of a realistic dev_sku subscription.");
            continue;
        }
        if (devSku1 == null)
            devSku1 = subscriptionPool.productId;
        if (devSku2 == null && devSku1 != null && devSku1 != subscriptionPool.productId)
            devSku2 = subscriptionPool.productId;
        if (devSku2 != null && devSku1 != null)
            break;
    }
    if (devSku1 == null || devSku2 == null)
        throw new SkipException("Could not find two available SKUs to execute this test.");
    // instrument the system facts to behave as a vagrant image with devSku1
    Map<String, String> factsMap = new HashMap<String, String>();
    factsMap.put("dev_sku", devSku1);
    factsMap.put("dev_platform", "dev_platform_for_" + devSku1);
    clienttasks.createFactsFileWithOverridingValues(factsMap);
    clienttasks.facts(null, true, null, null, null, null);
    // autosubscribe
    clienttasks.subscribe(true, null, null, null, (String) null, null, null, null, null, null, null, null, null);
    // get the autosubscribed entitlement
    List<ProductSubscription> productSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    if (clienttasks.getCurrentProductCertFiles().isEmpty()) {
        // handle case when no products are installed
        Assert.assertEquals(productSubscriptions.size(), 0, "After autosubscribing a system with dev_sku fact '" + devSku1 + "' that has no installed products, no product subscription should be consumed.");
        throw new SkipException("This test requires at least one installed product, otherwise there is no need for a dev SKU entitlement.");
    }
    Assert.assertEquals(productSubscriptions.size(), 1, "After autosubscribing a system with dev_sku fact '" + devSku1 + "', only one product subscription should be consumed.");
    ProductSubscription devSkuProductSubscription1 = productSubscriptions.get(0);
    Assert.assertEquals(devSkuProductSubscription1.productId, devSku1, "The consumed entitlement SKU after autosubscribing a system with dev_sku fact '" + devSku1 + "'.");
    // instrument the system facts to behave as a vagrant image with devSku2
    factsMap.put("dev_sku", devSku2);
    factsMap.put("dev_platform", "dev_platform_for_" + devSku2);
    clienttasks.createFactsFileWithOverridingValues(factsMap);
    clienttasks.facts(null, true, null, null, null, null);
    // which will cause the final assert to fail because the system will have no need to re-autosubscribe to devSku2
    if (clienttasks.getFactValue("system.entitlements_valid").equalsIgnoreCase("valid")) {
        // simply remove the devSkuProductSubscription1 subscription
        clienttasks.unsubscribe_(null, devSkuProductSubscription1.serialNumber, null, null, null, null, null);
    }
    // autosubscribe again
    clienttasks.subscribe(true, null, null, null, (String) null, null, null, null, null, null, null, null, null);
    // get the autosubscribed entitlement
    productSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    // fails prior to the fix for Bug 1295452 - After altering the dev_sku value in the facts file , two CDK subscriptions exists on the machine
    Assert.assertEquals(productSubscriptions.size(), 1, "After autosubscribing a system with dev_sku fact altered to '" + devSku2 + "', only one product subscription should be consumed (the '" + devSku1 + "' entitlement should have been purged)");
    ProductSubscription devSkuProductSubscription2 = productSubscriptions.get(0);
    Assert.assertEquals(devSkuProductSubscription2.productId, devSku2, "The consumed entitlement SKU after autosubscribing a system with dev_sku fact altered to '" + devSku2 + "'.");
}
Also used : HashMap(java.util.HashMap) 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)

Example 52 with ProductSubscription

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

the class DevSKUTests method testDevSku.

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

Example 53 with ProductSubscription

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

the class DevSKUTests method testAutosubscribedDevSkuWithAnUnknownProductInstalled.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21994", "RHEL7-51856" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.NEGATIVE, 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, alter the dev_sku facts, re-autosubscribe, and verify the initial entitlement was purged", groups = { "Tier1Tests", "blockedByBug-1294465", "VerifyAutosubscribedDevSkuWithAnUnknownProductInstalled_Test" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testAutosubscribedDevSkuWithAnUnknownProductInstalled() throws JSONException, Exception {
    // unregister to get rid of current consumer
    clienttasks.unregister(null, null, null, null);
    // verify that an unknown product is installed
    String productId = "88888888";
    Assert.assertNotNull(ProductCert.findFirstInstanceWithMatchingFieldFromList("id", productId, clienttasks.getCurrentProductCerts()), "Unknown product cert id '" + productId + "' is installed.");
    // 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).");
    }
    String expectedMsg = "Unable to find available subscriptions for all your installed products.";
    Assert.assertTrue(result.getStdout().trim().endsWith(expectedMsg), "Register with autosubscribe ends with this message when an unknown product is installed '" + expectedMsg + "'.");
    // get the autosubscribed productSubscription
    List<ProductSubscription> productSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    // failed prior to the fix for Bug 1294465 - Runtime Error null is observed while registering a client (cdk env) with a unknown product cert installed
    Assert.assertEquals(productSubscriptions.size(), 1, "After registering (with autosubscribe) a system with dev_sku fact '" + devSku + "', only one product subscription should be consumed even though an unknown product id '" + productId + "' is installed.");
    ProductSubscription devSkuProductSubscription = productSubscriptions.get(0);
    Assert.assertEquals(devSkuProductSubscription.productId, devSku, "The consumed entitlement SKU after autosubscribing a system with dev_sku fact '" + devSku + "' while an unknown product id '" + productId + "' is installed.");
}
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 54 with ProductSubscription

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

the class ActivationKeyTests method assertProvidedProductsFromPoolAreWithinConsumedProductSubscriptionsUsingQuantity_OLD.

// THIS IS THE ORIGINAL METHOD VALID PRIOR TO THE CHANGE IN list --consumed BEHAVIOR MODIFIED BY BUG 801187
protected void assertProvidedProductsFromPoolAreWithinConsumedProductSubscriptionsUsingQuantity_OLD(JSONObject jsonPool, List<ProductSubscription> consumedProductSubscriptions, Integer addQuantity, boolean assertConsumptionIsLimitedToThisPoolOnly) throws Exception {
    // assert that only the pool's providedProducts (excluding type=MKT products) are consumed (unless it is a ManagementAddOn product - indicated by no providedProducts)
    JSONArray jsonProvidedProducts = jsonPool.getJSONArray("providedProducts");
    // pluck out (remove) the providedProducts that have an attribute type=MKT products
    for (int j = 0; j < jsonProvidedProducts.length(); j++) {
        JSONObject jsonProvidedProduct = (JSONObject) jsonProvidedProducts.get(j);
        JSONObject jsonProduct = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/" + jsonProvidedProduct.getString("productId")));
        JSONArray jsonAttributes = jsonProduct.getJSONArray("attributes");
        for (int k = 0; k < jsonAttributes.length(); k++) {
            JSONObject jsonAttribute = (JSONObject) jsonAttributes.get(k);
            if (jsonAttribute.getString("name").equals("type")) {
                if (jsonAttribute.getString("value").equals("MKT")) {
                    log.info("Found a providedProduct '" + jsonProvidedProduct.getString("productName") + "' from the pool added to the activation key that is actually a Marketing product (type=\"MKT\").  Therefore this provided product will be excluded from the expected consumed ProductSubscriptions assertions that will follow...");
                    jsonProvidedProduct = /*Plucked*/
                    (JSONObject) jsonProvidedProducts.remove(j--);
                    break;
                }
            }
        }
    }
    // List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    if (jsonProvidedProducts.length() > 0) {
        if (assertConsumptionIsLimitedToThisPoolOnly)
            Assert.assertEquals(consumedProductSubscriptions.size(), jsonProvidedProducts.length(), "The number of providedProducts from the pool added to the activation key should match the number of consumed product subscriptions.");
        else
            Assert.assertTrue(consumedProductSubscriptions.size() >= jsonProvidedProducts.length(), "The number of providedProducts from the pool added to the activation key should match (at least) the number of consumed product subscriptions.");
        for (int j = 0; j < jsonProvidedProducts.length(); j++) {
            JSONObject jsonProvidedProduct = (JSONObject) jsonProvidedProducts.get(j);
            // {
            // "created": "2011-08-04T21:39:21.059+0000",
            // "id": "8a90f8c63196bb20013196bc7f6402e7",
            // "productId": "37060",
            // "productName": "Awesome OS Server Bits",
            // "updated": "2011-08-04T21:39:21.059+0000"
            // }
            String providedProductName = jsonProvidedProduct.getString("productName");
            if (assertConsumptionIsLimitedToThisPoolOnly) {
                ProductSubscription consumedProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("productName", providedProductName, consumedProductSubscriptions);
                Assert.assertNotNull(consumedProductSubscription, "Found a consumed product subscription whose productName '" + providedProductName + "' is included in the providedProducts added in the activation key.");
                Assert.assertEquals(consumedProductSubscription.accountNumber.longValue(), jsonPool.getLong("accountNumber"), "The consumed product subscription comes from the same accountNumber as the pool added in the activation key.");
                Assert.assertEquals(consumedProductSubscription.contractNumber.intValue(), jsonPool.getInt("contractNumber"), "The consumed product subscription comes from the same contractNumber as the pool added in the activation key.");
                Assert.assertEquals(consumedProductSubscription.quantityUsed, addQuantity, "The consumed product subscription is using the same quantity as requested by the pool added in the activation key.");
            } else {
                List<ProductSubscription> subsetOfConsumedProductSubscriptions = ProductSubscription.findAllInstancesWithMatchingFieldFromList("productName", providedProductName, consumedProductSubscriptions);
                ProductSubscription consumedProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("contractNumber", jsonPool.getInt("contractNumber"), subsetOfConsumedProductSubscriptions);
                Assert.assertNotNull(consumedProductSubscription, "Found a consumed product subscription whose productName '" + providedProductName + "' AND contract number '" + jsonPool.getInt("contractNumber") + "' is included in the providedProducts added to the activation key.");
                Assert.assertEquals(consumedProductSubscription.accountNumber.longValue(), jsonPool.getLong("accountNumber"), "The consumed product subscription comes from the same accountNumber as the pool added in the activation key.");
                Assert.assertEquals(consumedProductSubscription.contractNumber.intValue(), jsonPool.getInt("contractNumber"), "The consumed product subscription comes from the same contractNumber as the pool added in the activation key.");
                Assert.assertEquals(consumedProductSubscription.quantityUsed, addQuantity, "The consumed product subscription is using the same quantity as requested by the pool added in the activation key.");
            }
        }
    } else {
        // this pool provides a subscription to a Management AddOn product (indicated by no providedProducts)
        if (assertConsumptionIsLimitedToThisPoolOnly)
            Assert.assertEquals(consumedProductSubscriptions.size(), 1, "When a ManagementAddOn product is added to the activation key, then the number of consumed product subscriptions should be one.");
        else
            Assert.assertTrue(consumedProductSubscriptions.size() >= 1, "When a ManagementAddOn product is added to the activation key, then the number of consumed product subscriptions should be (at least) one.");
        if (assertConsumptionIsLimitedToThisPoolOnly) {
            ProductSubscription consumedProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("productName", jsonPool.getString("productName"), consumedProductSubscriptions);
            Assert.assertNotNull(consumedProductSubscription, "Found a consumed product subscription whose productName '" + jsonPool.getString("productName") + "' matches the pool's productName added in the activation key.");
            Assert.assertEquals(consumedProductSubscription.accountNumber.longValue(), jsonPool.getLong("accountNumber"), "The consumed product subscription comes from the same accountNumber as the pool added in the activation key.");
            Assert.assertEquals(consumedProductSubscription.contractNumber.intValue(), jsonPool.getInt("contractNumber"), "The consumed product subscription comes from the same contractNumber as the pool added in the activation key.");
            Assert.assertEquals(consumedProductSubscription.quantityUsed, addQuantity, "The consumed product subscription is using the same quantity as requested by the pool added in the activation key.");
        } else {
            List<ProductSubscription> subsetOfConsumedProductSubscriptions = ProductSubscription.findAllInstancesWithMatchingFieldFromList("productName", jsonPool.getString("productName"), consumedProductSubscriptions);
            ProductSubscription consumedProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("contractNumber", jsonPool.getInt("contractNumber"), subsetOfConsumedProductSubscriptions);
            Assert.assertNotNull(consumedProductSubscription, "Found a consumed product subscription whose productName '" + jsonPool.getString("productName") + "' AND contract number '" + jsonPool.getInt("contractNumber") + "' matches a pool's productName and contractNumber added to the activation key.");
            Assert.assertEquals(consumedProductSubscription.accountNumber.longValue(), jsonPool.getLong("accountNumber"), "The consumed product subscription comes from the same accountNumber as the pool added in the activation key.");
            Assert.assertEquals(consumedProductSubscription.contractNumber.intValue(), jsonPool.getInt("contractNumber"), "The consumed product subscription comes from the same contractNumber as the pool added in the activation key.");
            Assert.assertEquals(consumedProductSubscription.quantityUsed, addQuantity, "The consumed product subscription is using the same quantity as requested by the pool added in the activation key.");
        }
    }
}
Also used : JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) ProductSubscription(rhsm.data.ProductSubscription)

Example 55 with ProductSubscription

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

the class ComplianceTests method testSystemCompliantFactWhenAllProductsSubscribableByMoreThanOneCommonServiceLevel.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21704", "RHEL7-51071" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier1")
@Test(description = "subscription-manager: verify the system.compliant fact is True when all installed products are subscribable by more than one common service level", groups = { "Tier1Tests", "configureProductCertDirForAllProductsSubscribableByMoreThanOneCommonServiceLevel", "cli.tests", "blockedbyBug-859652", "blockedbyBug-1183175" }, dataProvider = "getAllProductsSubscribableByMoreThanOneCommonServiceLevelValuesData", priority = 100, enabled = true)
public // @ImplementsTCMS(id="")
void testSystemCompliantFactWhenAllProductsSubscribableByMoreThanOneCommonServiceLevel(Object bugzilla, String servicelevel) {
    // test register with service level
    clienttasks.unregister_(null, null, null, null);
    // Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance), factValueForSystemNonCompliance,	// THIS ASSERTION IS NO LONGER VALID NOW THAT COMPLIANCE IS CALCULATED ON THE SERVER.  INSTEAD, THE LOCAL COMPLIANCE SHOULD BE TAKEN FROM THE SYSTEM CACHE.  THIS WORK IS CURRENTLY UNDER DEVELOPMENT 3/13/2013.
    // "Before attempting to register with autosubscribe and a common servicelevel to become compliant for all the currently installed products, the system should be non-compliant (see value for fact '"+factNameForSystemCompliance+"').");
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, /*true*/
    null, /*servicelevel*/
    null, null, (String) null, null, null, null, Boolean.TRUE, false, null, null, null, null);
    // to avoid unmapped_guests_only pools
    if (Boolean.valueOf(clienttasks.getFactValue("virt.is_guest")))
        clienttasks.mapSystemAsAGuestOfItself();
    clienttasks.subscribe(true, servicelevel, (List<String>) null, null, null, null, null, null, null, null, null, null, null);
    Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance), factValueForSystemCompliance, "When a system has products installed for which ALL are covered by available subscription pools with a common service level, the system should become compliant (see value for fact '" + factNameForSystemCompliance + "')");
    for (ProductSubscription productSubscription : clienttasks.getCurrentlyConsumedProductSubscriptions()) {
        // catch the special case when autosubscribe grants a subscription with an empty service level in support of 1335371
        if (!servicelevel.equalsIgnoreCase(productSubscription.serviceLevel) && productSubscription.serviceLevel.isEmpty() && SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">", "2.0.2-1")) {
            // commit 9cefb6e23baefcc4ee2e14423f205edd37eecf22	// Bug 1223560 - Service levels on an activation key prevent custom products from attaching at registration if auto-attach enabled (reported by Christine Fouant)
            Assert.assertTrue(productSubscription.serviceLevel.isEmpty(), "After the implementation of Bug 1223560, autosubscribe can potentially grant a product subscription with an empty service level despite specifying a service level preference '" + servicelevel + "'.  In this case, product subscription (" + productSubscription + ") with an empty service level was granted for coverage of the installed product(s).  For justification, review https://bugzilla.redhat.com/show_bug.cgi?id=1335371.");
        } else
            // CASE SENSITIVE ASSERTION Assert.assertEquals(productSubscription.serviceLevel, servicelevel, "When a system has been registered with autosubscribe specifying a common service level, then all consumed product subscriptions must provide that service level.");
            Assert.assertTrue(servicelevel.equalsIgnoreCase(productSubscription.serviceLevel), "When a system has been registered with autosubscribe specifying a common service level '" + servicelevel + "', then this auto consumed product subscription (" + productSubscription + ") must provide case-insensitive match to the requested service level.");
    }
    Assert.assertEquals(clienttasks.getCurrentServiceLevel(), servicelevel, "When a system has been registered with autosubscribe specifying a common service level, then the consumer's service level prefernce should be set to that value.");
    // test autosubscribe (without service level) and assert that the consumed subscriptions provide the same service level as persisted during register
    clienttasks.unsubscribe(true, (BigInteger) null, null, null, null, null, null);
    Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance), factValueForSystemNonCompliance, "Before attempting to autosubscribe with a common servicelevel to become compliant for all the currently installed products, the system should be non-compliant (see value for fact '" + factNameForSystemCompliance + "').");
    clienttasks.subscribe(true, null, (List<String>) null, null, null, null, null, null, null, null, null, null, null);
    Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance), factValueForSystemCompliance, "When a system has products installed for which ALL are covered by available subscription pools with a common service level, the system should become compliant (see value for fact '" + factNameForSystemCompliance + "')");
    for (ProductSubscription productSubscription : clienttasks.getCurrentlyConsumedProductSubscriptions()) {
        if (!servicelevel.equalsIgnoreCase(productSubscription.serviceLevel) && productSubscription.serviceLevel.isEmpty() && SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">", "2.0.2-1")) {
            // commit 9cefb6e23baefcc4ee2e14423f205edd37eecf22	// Bug 1223560 - Service levels on an activation key prevent custom products from attaching at registration if auto-attach enabled (reported by Christine Fouant)
            Assert.assertTrue(productSubscription.serviceLevel.isEmpty(), "After the implementation of Bug 1223560, autosubscribe can potentially grant a product subscription with an empty service level despite specifying a service level preference '" + servicelevel + "'.  In this case, product subscription (" + productSubscription + ") with an empty service level was granted for coverage of the installed product(s).  For justification, review https://bugzilla.redhat.com/show_bug.cgi?id=1335371.");
        } else
            // CASE SENSITIVE ASSERTION Assert.assertEquals(productSubscription.serviceLevel, servicelevel, "When a system has been registered with autosubscribe without specifying a common service level, then all consumed product subscriptions must provide the consumer's service level preference.");
            Assert.assertTrue(servicelevel.equalsIgnoreCase(productSubscription.serviceLevel), "When a system has been registered with autosubscribe without specifying a common service level, then this auto consumed product subscription (" + productSubscription + ") must provide a case-insensitive match to the consumer's service level preference '" + servicelevel + "'.");
    }
}
Also used : ProductSubscription(rhsm.data.ProductSubscription) 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