Search in sources :

Example 51 with ProductCert

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

the class ContentTests method getYumGroupFromEnabledRepoAndSubscriptionPoolDataAsListOfLists.

protected List<List<Object>> getYumGroupFromEnabledRepoAndSubscriptionPoolDataAsListOfLists() throws JSONException, Exception {
    List<List<Object>> ll = new ArrayList<List<Object>>();
    if (!isSetupBeforeSuiteComplete)
        return ll;
    if (clienttasks == null)
        return ll;
    if (sm_clientUsername == null)
        return ll;
    if (sm_clientPassword == null)
        return ll;
    // get the currently installed product certs to be used when checking for conditional content tagging
    List<ProductCert> currentProductCerts = clienttasks.getCurrentProductCerts();
    // assure we are freshly registered and process all available subscription pools
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, ConsumerType.system, null, null, null, null, null, (String) null, null, null, null, Boolean.TRUE, false, null, null, null, null);
    for (SubscriptionPool pool : clienttasks.getCurrentlyAvailableSubscriptionPools()) {
        // avoid throttling RateLimitExceededException from IT-Candlepin
        if (CandlepinType.hosted.equals(sm_serverType)) {
            // strategically get a new consumer to avoid 60 repeated API calls from the same consumer
            // re-register as a new consumer
            clienttasks.register_(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, ConsumerType.system, null, null, null, null, null, (String) null, null, null, null, Boolean.TRUE, false, null, null, null, null);
        }
        File entitlementCertFile = clienttasks.subscribeToSubscriptionPool_(pool);
        Assert.assertNotNull(entitlementCertFile, "Found the entitlement cert file that was granted after subscribing to pool: " + pool);
        EntitlementCert entitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(entitlementCertFile);
        for (ContentNamespace contentNamespace : entitlementCert.contentNamespaces) {
            if (!contentNamespace.type.equalsIgnoreCase("yum"))
                continue;
            if (contentNamespace.enabled && clienttasks.areAllRequiredTagsInContentNamespaceProvidedByProductCerts(contentNamespace, currentProductCerts)) {
                String repoLabel = contentNamespace.label;
                // find first available group provided by this repo
                String availableGroup = clienttasks.findAnAvailableGroupFromRepo(repoLabel);
                // find first installed group provided by this repo
                String installedGroup = clienttasks.findAnInstalledGroupFromRepo(repoLabel);
                // String availableGroup, String installedGroup, String repoLabel, SubscriptionPool pool
                ll.add(Arrays.asList(new Object[] { availableGroup, installedGroup, repoLabel, pool }));
            }
        }
        clienttasks.unsubscribeFromSerialNumber(clienttasks.getSerialNumberFromEntitlementCertFile(entitlementCertFile));
        // minimize the number of dataProvided rows (useful during automated testcase development)
        if (Boolean.valueOf(getProperty("sm.debug.dataProviders.minimize", "false")) && !ll.isEmpty())
            break;
    }
    return ll;
}
Also used : ContentNamespace(rhsm.data.ContentNamespace) EntitlementCert(rhsm.data.EntitlementCert) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) JSONObject(org.json.JSONObject) ProductCert(rhsm.data.ProductCert) SubscriptionPool(rhsm.data.SubscriptionPool) File(java.io.File)

Example 52 with ProductCert

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

the class ContentTests method testYumRepoListsEnabledContent.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20085", "RHEL7-51099" }, 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 content flag : Default content flag should enable", groups = { "Tier1Tests", "blockedByBug-804227", "blockedByBug-871146", "blockedByBug-924919", "blockedByBug-962520" }, enabled = true)
@ImplementsNitrateTest(caseId = 47578, fromPlan = 2479)
public void testYumRepoListsEnabledContent() throws JSONException, Exception {
    // Original code from ssalevan
    // ArrayList<String> repos = this.getYumRepolist();
    // 
    // for (EntitlementCert cert:clienttasks.getCurrentEntitlementCerts()){
    // if(cert.enabled.contains("1"))
    // Assert.assertTrue(repos.contains(cert.label),
    // "Yum reports enabled content subscribed to repo: " + cert.label);
    // else
    // Assert.assertFalse(repos.contains(cert.label),
    // "Yum reports enabled content subscribed to repo: " + cert.label);
    // }
    List<ProductCert> currentProductCerts = clienttasks.getCurrentProductCerts();
    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);
    if (clienttasks.subscribeToTheCurrentlyAvailableSubscriptionPoolsCollectively().size() <= 0)
        throw new SkipException("No available subscriptions were found.  Therefore we cannot perform this test.");
    List<EntitlementCert> entitlementCerts = clienttasks.getCurrentEntitlementCerts();
    // or maybe we should skip when nothing is consumed
    Assert.assertTrue(!entitlementCerts.isEmpty(), "After subscribing to all available subscription pools, there must be some entitlements.");
    ArrayList<String> repolist = clienttasks.getYumRepolist("enabled");
    for (EntitlementCert entitlementCert : entitlementCerts) {
        for (ContentNamespace contentNamespace : entitlementCert.contentNamespaces) {
            if (!contentNamespace.type.equalsIgnoreCase("yum"))
                continue;
            if (contentNamespace.enabled) {
                if (clienttasks.areAllRequiredTagsInContentNamespaceProvidedByProductCerts(contentNamespace, currentProductCerts)) {
                    Assert.assertTrue(repolist.contains(contentNamespace.label), "Yum repolist enabled includes enabled repo id/label '" + contentNamespace.label + "' after having subscribed to Subscription ProductId '" + entitlementCert.orderNamespace.productId + "'.");
                } else {
                    Assert.assertFalse(repolist.contains(contentNamespace.label), "Yum repolist enabled excludes enabled repo id/label '" + contentNamespace.label + "' after having subscribed to Subscription ProductId '" + entitlementCert.orderNamespace.productId + "' because not all requiredTags (" + contentNamespace.requiredTags + ") in the contentNamespace are provided by the currently installed productCerts.");
                }
            } else {
                Assert.assertFalse(repolist.contains(contentNamespace.label), "Yum repolist enabled excludes disabled repo id/label '" + contentNamespace.label + "' after having subscribed to Subscription ProductId '" + entitlementCert.orderNamespace.productId + "'.");
            }
        }
    }
}
Also used : ContentNamespace(rhsm.data.ContentNamespace) EntitlementCert(rhsm.data.EntitlementCert) ProductCert(rhsm.data.ProductCert) SkipException(org.testng.SkipException) 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 53 with ProductCert

use of rhsm.data.ProductCert 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 54 with ProductCert

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

the class BrandingTests method getEligibleBrandNamesFromCurrentEntitlementCerts.

/**
 * @param entitlementCerts TODO
 * @return the eligible brand names based on the current entitlement certs and the currently installed product certs
 */
Set<String> getEligibleBrandNamesFromCurrentEntitlementCerts() {
    // Rules:
    // - eligible brand names come from the currently entitled productNamespaces and are identified by a brandType = "OS"
    // - the corresponding productId must be among the currently installed product certs to be eligible
    Set<String> eligibleInstalledProductIdSet = new HashSet<String>();
    Set<String> eligibleBrandNamesSet = new HashSet<String>();
    List<String> eligibleBrandNamesList = new ArrayList<String>();
    List<ProductCert> currentProductCerts = clienttasks.getCurrentProductCerts();
    for (EntitlementCert entitlementCert : clienttasks.getCurrentEntitlementCerts()) {
        for (ProductNamespace productNamespace : entitlementCert.productNamespaces) {
            if (ProductCert.findFirstInstanceWithMatchingFieldFromList("productId", productNamespace.id, currentProductCerts) != null) {
                if (productNamespace.brandType != null) {
                    if (productNamespace.brandType.equals("OS")) {
                        /* THE ORIGINAL FLEX BRANDING IMPLEMENTATION DUAL-PURPOSED THE PRODUCT NAME AS THE SOURCE OF THE BRANDING NAME
							eligibleBrandNamesList.add(productNamespace.name);
							eligibleBrandNamesSet.add(productNamespace.name);
							*/
                        eligibleBrandNamesList.add(productNamespace.brandName);
                        eligibleBrandNamesSet.add(productNamespace.brandName);
                        eligibleInstalledProductIdSet.add(productNamespace.id);
                    }
                }
            }
        }
    }
    if (eligibleBrandNamesList.size() > eligibleBrandNamesSet.size()) {
        log.warning("Currently there are multiple entitled OS brand products by the same name " + eligibleBrandNamesList + ".  This can happen when multiple OS subscriptions have been stacked.");
    }
    if (eligibleInstalledProductIdSet.size() > 1) {
        log.warning("Currently there are multiple entitled OS brand product ids installed " + eligibleInstalledProductIdSet + ".  This is likely caused by a RHEL installation or redhat-release bug.  In this case a warning is logged to " + clienttasks.rhsmLogFile + " and no update is made to the branding file '" + brandingFile + "'.");
        // 2017-10-25 13:56:44,700 [DEBUG] subscription-manager:26339:MainThread @certdirectory.py:217 - Installed product IDs: ['68', '69', '71', '76']
        // 2017-10-25 13:56:44,772 [WARNING] subscription-manager:26339:MainThread @rhelentbranding.py:114 - More than one installed product with RHEL brand information is installed
        eligibleBrandNamesSet.clear();
        // TEMPORARY WORKAROUND
        boolean invokeWorkaroundWhileBugIsOpen = true;
        // Bug 1506271 - redhat-release is providing more than 1 variant specific product cert
        String bugId = "1506271";
        try {
            if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
                log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
                SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
            } else {
                invokeWorkaroundWhileBugIsOpen = false;
            }
        } catch (BugzillaAPIException be) {
        /* ignore exception */
        } catch (RuntimeException re) {
        /* ignore exception */
        }
        if (invokeWorkaroundWhileBugIsOpen) {
            throw new SkipException("Skipping this test while bug '" + bugId + "' is open.");
        }
    // END OF WORKAROUND
    }
    return eligibleBrandNamesSet;
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) ArrayList(java.util.ArrayList) ProductCert(rhsm.data.ProductCert) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) ProductNamespace(rhsm.data.ProductNamespace) SkipException(org.testng.SkipException) HashSet(java.util.HashSet)

Example 55 with ProductCert

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

the class CertificateTests method testProductCertStatistics.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-36644", "RHEL7-51455" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier2")
@Test(description = "assert the statistic values reported by the rct stat-cert tool for currently installed product certs", groups = { "Tier2Tests" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testProductCertStatistics() {
    // get all the product certs on the system
    List<ProductCert> productCerts = new ArrayList();
    List<ProductCert> installedProductCerts = clienttasks.getCurrentProductCerts();
    List<ProductCert> migrationProductCerts = clienttasks.getProductCerts("/usr/share/rhsm/product/RHEL-" + clienttasks.redhatReleaseX);
    productCerts.addAll(installedProductCerts);
    productCerts.addAll(migrationProductCerts);
    // loop through all of the current product certs
    if (productCerts.isEmpty())
        throw new SkipException("There are currently no installed product certs to assert statistics.");
    for (ProductCert productCert : productCerts) {
        CertStatistics certStatistics = clienttasks.getCertStatisticsFromCertFile(productCert.file);
        // skip the generated TESTDATA productCerts
        if (productCert.file.toString().endsWith("_.pem"))
            continue;
        // [root@jsefler-6 ~]# rct stat-cert /etc/pki/product/69.pem
        // Type: Product Certificate
        // Version: 1.0
        // DER size: 1553b
        String expectedDerSize = client.runCommandAndWait("openssl x509 -in " + productCert.file.getPath() + " -outform der -out /tmp/cert.der && du -b /tmp/cert.der | cut -f 1").getStdout().trim();
        expectedDerSize += "b";
        Assert.assertEquals(certStatistics.type, "Product Certificate", "rct stat-cert reports this Type.");
        Assert.assertEquals(certStatistics.version, productCert.version, "rct stat-cert reports this Version.");
        Assert.assertEquals(certStatistics.derSize, expectedDerSize, "rct stat-cert reports this DER size.");
        Assert.assertNull(certStatistics.subjectKeyIdSize, "rct stat-cert does NOT report a Subject Key ID size.");
        Assert.assertNull(certStatistics.contentSets, "rct stat-cert does NOT report a number of Content sets.");
    }
}
Also used : ArrayList(java.util.ArrayList) ProductCert(rhsm.data.ProductCert) SkipException(org.testng.SkipException) CertStatistics(rhsm.data.CertStatistics) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Aggregations

ProductCert (rhsm.data.ProductCert)90 Test (org.testng.annotations.Test)60 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)54 SkipException (org.testng.SkipException)44 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)40 ArrayList (java.util.ArrayList)40 File (java.io.File)26 SubscriptionPool (rhsm.data.SubscriptionPool)24 EntitlementCert (rhsm.data.EntitlementCert)23 BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)22 InstalledProduct (rhsm.data.InstalledProduct)21 JSONObject (org.json.JSONObject)19 SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)17 List (java.util.List)16 ContentNamespace (rhsm.data.ContentNamespace)15 HashSet (java.util.HashSet)13 Calendar (java.util.Calendar)7 HashMap (java.util.HashMap)7 BigInteger (java.math.BigInteger)6 JSONArray (org.json.JSONArray)6