Search in sources :

Example 81 with EntitlementCert

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

the class ManifestTests method verifyRCTCatManifestWithOptions.

protected void verifyRCTCatManifestWithOptions(File manifestFile, List<String> options) throws Exception {
    // flatten the list of options into a single string for the runCommand
    String optionsAsString = " ";
    if (options != null)
        for (String option : options) optionsAsString += option + " ";
    // execute and assert rct cat-manifest MANIFEST_FILE
    SSHCommandResult catManifestResult = RemoteFileTasks.runCommandAndAssert(client, "rct cat-manifest" + optionsAsString + manifestFile, 0);
    // parse the output from catManifestResult into a Manifest object
    List<Manifest> catManifests = Manifest.parse(catManifestResult.getStdout());
    Assert.assertEquals(catManifests.size(), 1, "Parsed one manifest from '" + manifestFile + "'.");
    Manifest catManifest = catManifests.get(0);
    // create EntitlementCert objects representing the source for all of the entitlements provided by this manifest
    if (manifestFileContentMap.get(manifestFile) == null)
        throw new SkipException("Cannot execute this test until manifest file '" + manifestFile + "' has been successfully dumped.");
    client.runCommandAndWaitWithoutLogging("find " + manifestFileContentMap.get(manifestFile).get(0).getParent() + "/export/entitlement_certificates" + " -regex \"/.+/[0-9]+.pem\" -exec rct cat-cert {} \\;");
    String rawCertificates = client.getStdout();
    List<EntitlementCert> entitlementCerts = EntitlementCert.parse(rawCertificates);
    if (entitlementCerts.isEmpty())
        Assert.fail("Manifest file '" + manifestFile + "' does not provide any entitlements.");
    // loop through the manifest's entitlement certs and assert as much as possible...
    // [root@jsefler-7 test-manifests]# rct cat-manifest manifest_SYS0395_RH0197181.zip
    // 
    // +-------------------------------------------+
    // Manifest
    // +-------------------------------------------+
    String bannerRegex = "\\+-+\\+\\n\\s*Manifest\\s*\\n\\+-+\\+";
    Assert.assertTrue(Pattern.compile(".*" + bannerRegex + ".*", Pattern.DOTALL).matcher(catManifestResult.getStdout()).matches(), "stdout from rct cat-manifest contains a banner matching regex '" + bannerRegex + "'.");
    if (catManifest.server == null) {
        log.warning("Skipping assertion of non-null General and Consumer for what appears to be a manifest from an older candlepin server");
    } else {
        // 
        // General:
        // Server: access.stage.redhat.com/management/distributors/
        // Server Version: 0.7.13.10-1
        // Date Created: 2013-01-21T21:24:16.193+0000
        // Creator: qa@redhat.com
        Assert.assertNotNull(catManifest.server, "General Server value is not null.");
        Assert.assertNotNull(catManifest.serverVersion, "General Server Version value is not null.");
        Assert.assertNotNull(catManifest.dateCreated, "General Date Created value is not null.");
        Assert.assertNotNull(catManifest.creator, "General Creator value is not null.");
        // 
        // Consumer:
        // Name: jsefler
        // UUID: b2837b9a-d2d9-4b41-acd9-34bdcf72af66
        // Type: sam
        Assert.assertNotNull(catManifest.consumerName, "Consumer Name value is not null.");
        Assert.assertNotNull(catManifest.consumerUUID, "Consumer UUID value is not null.");
        String consumerUUIDRegex = "[a-f,0-9,\\-]{36}";
        Assert.assertTrue(Pattern.compile(consumerUUIDRegex).matcher(catManifest.consumerUUID).matches(), "Consumer UUID format matches the expected regex '" + consumerUUIDRegex + "'.");
        Assert.assertNotNull(catManifest.consumerType, "Consumer Type value is not null.");
        // TODO learn why there is a type distinction
        Assert.assertTrue(catManifest.consumerType.equals("sam") || catManifest.consumerType.equals("cloudforms") || catManifest.consumerType.equals("satellite"), "Actual Consumer Type value '" + catManifest.consumerType + "' equals \"sam\" or \"cloudforms' or \"satellite\".");
        // Content Access Mode: entitlement
        if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.19.6-1")) {
            Assert.assertNotNull(catManifest.consumerContentAccessMode, "Consumer Content Access Mode value is not null.");
            Assert.assertTrue(catManifest.consumerContentAccessMode.equals("entitlement") || catManifest.consumerContentAccessMode.equals("org_environment"), "Actual Consumer Content Access Mode value '" + catManifest.consumerContentAccessMode + "' equals \"entitlement\" or \"org_environment\".");
            if (SubscriptionManagerTasks.isVersion(catManifest.serverVersion, "<", "2.0.22-1")) {
                // candlepin commit 18c20d0a1530910d5ca45fecb59f8f7db5e9a04f Golden Ticket
                Assert.assertEquals(catManifest.consumerContentAccessMode, "entitlement", "Since this manifest was created by candlepin version prior to \"2.0.22-1\", the Consumer's Content Access Mode value must be the default value.");
            }
        }
    }
    // /content/beta/rhel/power/5/$releasever/$basearch/highavailability/source/SRPMS
    for (EntitlementCert entitlementCert : entitlementCerts) {
        ManifestSubscription manifestSubscription = ManifestSubscription.findFirstInstanceWithMatchingFieldFromList("certificateFile", entitlementCert.file.toString().replace(manifestFileContentMap.get(manifestFile).get(0).getParent() + File.separator, ""), catManifest.subscriptions);
        if (manifestSubscription == null)
            Assert.fail("Could not find the ManifestSubscription corresponding to Entitlement '" + entitlementCert.file + "'.");
        Assert.assertEquals(manifestSubscription.name, entitlementCert.orderNamespace.productName, "Subscription Name value comes from entitlementCert.orderNamespace.productName");
        Assert.assertEquals(manifestSubscription.quantity, entitlementCert.orderNamespace.quantityUsed, "Subscription Quantity value comes from entitlementCert.orderNamespace.quantityUsed (ASSUMING NO OTHER UPSTREAM CONSUMERS)");
        // TODO assert Created:
        Assert.assertEquals(manifestSubscription.startDate, entitlementCert.validityNotBefore, "Subscription Start Date comes from entitlementCert.validityNotBefore");
        Assert.assertEquals(manifestSubscription.endDate, entitlementCert.validityNotAfter, "Subscription End Date comes from entitlementCert.validityNotAfter");
        Assert.assertEquals(manifestSubscription.supportLevel, entitlementCert.orderNamespace.supportLevel, "Subscription Service Level value comes from entitlementCert.orderNamespace.supportLevel");
        Assert.assertEquals(manifestSubscription.supportType, entitlementCert.orderNamespace.supportType, "Subscription Service Type value comes from entitlementCert.orderNamespace.supportType");
        List<String> actualArchitectures = new ArrayList<String>();
        if (manifestSubscription.architectures != null)
            actualArchitectures.addAll(Arrays.asList(manifestSubscription.architectures.split("\\s*,\\s*")));
        List<String> expectedArchitectures = new ArrayList<String>();
        for (ProductNamespace productNamespace : entitlementCert.productNamespaces) if (productNamespace.arch != null)
            expectedArchitectures.addAll(Arrays.asList(productNamespace.arch.split("\\s*,\\s*")));
        // BAD ASSERT SEE https://bugzilla.redhat.com/show_bug.cgi?id=914799#c3 Assert.assertTrue(actualArchitectures.containsAll(expectedArchitectures)&&expectedArchitectures.containsAll(actualArchitectures), "Subscription Architectures contains the union of providedProduct arches: "+expectedArchitectures);
        Assert.assertEquals(manifestSubscription.productId, entitlementCert.orderNamespace.productId, "Subscription SKU value comes from entitlementCert.orderNamespace.productId");
        Assert.assertEquals(manifestSubscription.contract, entitlementCert.orderNamespace.contractNumber, "Subscription Contract value comes from entitlementCert.orderNamespace.contractNumber");
        Assert.assertEquals(manifestSubscription.subscriptionId, entitlementCert.orderNamespace.orderNumber, "Subscription Order Number value comes from entitlementCert.orderNamespace.orderNumber");
        // TODO assert Entitlement File in json format
        Assert.assertTrue(entitlementCert.file.toString().endsWith(manifestSubscription.certificateFile), "Subscription Certificate File exists");
        Assert.assertEquals(manifestSubscription.certificateVersion, entitlementCert.version, "Subscription Certificate Version value comes from entitlementCert.version");
        List<String> actualProvidedProducts = manifestSubscription.providedProducts;
        List<String> actualDerivedProducts = manifestSubscription.derivedProducts;
        if (false) {
            // This assertion was valid prior to the invention of data center skus that provide no products but do provide derived products to be added to a sub-pool
            List<String> expectedProvidedProducts = new ArrayList<String>();
            for (ProductNamespace productNamespace : entitlementCert.productNamespaces) expectedProvidedProducts.add(String.format("%s: %s", productNamespace.id, productNamespace.name));
            Assert.assertTrue(actualProvidedProducts.containsAll(expectedProvidedProducts) && expectedProvidedProducts.containsAll(actualProvidedProducts), "Manifest Subscription '" + manifestSubscription.name + "' Provided Products " + actualProvidedProducts + " contains all entitlementCert.productNamespaces=>\"id: name\": " + expectedProvidedProducts);
        } else {
            // Instead, let's assume the following assertion is correct... TODO confirm with dev
            // Note: this assertion can only be tested against manifests with data center skus using subscription-manager-1.18.6-1 and higher
            List<String> expectedProducts = new ArrayList<String>();
            for (ProductNamespace productNamespace : entitlementCert.productNamespaces) expectedProducts.add(String.format("%s: %s", productNamespace.id, productNamespace.name));
            if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.18.6-1")) {
                // subscription-manager commit 23c149907852767e51e7ddea8edf506697827203  Bug 1388207 - [RFE] rct cat-manifest command should show derived products
                List<String> actualProvidedAndDerivedProducts = new ArrayList<String>();
                for (String product : actualProvidedProducts) if (!actualProvidedAndDerivedProducts.contains(product))
                    actualProvidedAndDerivedProducts.add(product);
                for (String product : actualDerivedProducts) if (!actualProvidedAndDerivedProducts.contains(product))
                    actualProvidedAndDerivedProducts.add(product);
                Assert.assertTrue(actualProvidedAndDerivedProducts.containsAll(expectedProducts) && expectedProducts.containsAll(actualProvidedAndDerivedProducts), "The union of all Provided Products " + actualProvidedProducts + " and Derived Products " + actualDerivedProducts + " from manifest Subscription '" + manifestSubscription.name + "' contains all entitlementCert.productNamespaces=>\"id: name\": " + expectedProducts);
            } else {
                log.info("Cannot assert that the union of all provided and derived products from manifest Subscription '" + manifestSubscription.name + "' are represented in this entitlementCert.productNamespaces=>\"id: name\": " + expectedProducts + " because RFE Bug 1388207 is not present in this version of subscription-manager.");
                log.info("We can only assert that the provided products from manifest Subscription '" + manifestSubscription.name + "' are a subset of this entitlementCert.productNamespaces=>\"id: name\": " + expectedProducts + " because RFE Bug 1388207 is not present in this version of subscription-manager to account for derived products.");
                Assert.assertTrue(expectedProducts.containsAll(actualProvidedProducts), "The Provided Products " + actualProvidedProducts + " from manifest Subscription '" + manifestSubscription.name + "' are a subset of all entitlementCert.productNamespaces=>\"id: name\": " + expectedProducts);
            }
        }
        List<String> actualContentSets = new ArrayList<String>();
        if (manifestSubscription.contentSets != null)
            actualContentSets.addAll(manifestSubscription.contentSets);
        List<String> expectedContentSets = new ArrayList<String>();
        for (ContentNamespace contentNamespace : entitlementCert.contentNamespaces) expectedContentSets.add(contentNamespace.downloadUrl);
        if (options != null && options.contains("--no-content")) {
            Assert.assertNull(manifestSubscription.contentSets, "The cat-manifest report does not include any Subscription Content Sets when the '--no-content' option is specified.");
        } else {
            Assert.assertTrue(actualContentSets.containsAll(expectedContentSets) && expectedContentSets.containsAll(actualContentSets), "Subscription Content Sets contains all entitlementCert.contentNamespaces=>downloadUrl: (too long to print)");
        }
    }
}
Also used : ContentNamespace(rhsm.data.ContentNamespace) EntitlementCert(rhsm.data.EntitlementCert) ManifestSubscription(rhsm.data.ManifestSubscription) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ArrayList(java.util.ArrayList) SkipException(org.testng.SkipException) Manifest(rhsm.data.Manifest) ProductNamespace(rhsm.data.ProductNamespace)

Example 82 with EntitlementCert

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

the class OstreeTests method testOstreeConfigurationsAreSetAfterSubscribingAndUnsubscribing.

// 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-22238", "RHEL7-51753" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier1")
@Test(description = "Verify that the ostree config and origin files are set after attaching an atomic subscription; attempt an atomic upgrade; unsubscribe and verify ostree config files are unset", groups = { "Tier1Tests", "subscribeAndUnsubscribeTests" }, dataProvider = "getOstreeSubscriptionPools", priority = 10, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testOstreeConfigurationsAreSetAfterSubscribingAndUnsubscribing(Object bugzilla, SubscriptionPool osTreeSubscriptionPool) {
    // this test is designed to be entitled to one subscription at a time.
    clienttasks.unsubscribe_(true, (BigInteger) null, null, null, null, null, null);
    String baseurl = clienttasks.getConfParameter("baseurl");
    String repo_ca_cert = clienttasks.getConfParameter("repo_ca_cert");
    // get a list of the current Product Certs installed on the system
    List<ProductCert> currentProductCerts = clienttasks.getCurrentProductCerts();
    // get a list of the ostree repos from the ostree repo config file before attaching an ostree subscription
    List<OstreeRepo> ostreeReposBefore = getCurrentlyConfiguredOstreeRepos(ostreeRepoConfigFile);
    // get the ostree origin refspec before attaching an ostree subscription
    // UPDATE: After subscription-manager-plugin-ostree-1.18.5-1 RFE Bug 1378495, the ostree origin refspec file is no longer touched
    String ostreeOriginRefspecBefore = ostreeOriginFile == null ? null : clienttasks.getConfFileParameter(ostreeOriginFile.getPath(), "origin", "refspec");
    // also setup an old /ostree/repo/config file to test the migration clean up scenario described in https://bugzilla.redhat.com/show_bug.cgi?id=1152734#c5
    if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.13.9-1")) {
        // post committ 11b377f78dcb06d8dbff5645750791b729e20a0e
        if (!clienttasks.isPackageInstalled("ostree")) {
            client.runCommandAndWait("mkdir -p " + oldOstreeRepoConfigFile.getParent());
            client.runCommandAndWait("echo -e '[core]\nrepo_version=1\nmode=bare\n\n[remote \"REMOTE\"]\nurl=file:///install/ostree\ngpg-verify=false' > " + oldOstreeRepoConfigFile.getPath());
        }
    }
    // attach the subscription that provides ostree content
    File file = clienttasks.subscribeToSubscriptionPool(osTreeSubscriptionPool, sm_clientUsername, sm_clientPassword, sm_serverUrl);
    EntitlementCert entitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(file);
    // get a list of the ostree repos from the ostree repo config file after attaching an ostree subscription
    List<OstreeRepo> ostreeReposAfter = getCurrentlyConfiguredOstreeRepos(ostreeRepoConfigFile);
    // get the ostree origin refspec after attaching an ostree subscription
    // UPDATE: After subscription-manager-plugin-ostree-1.18.5-1 RFE Bug 1378495, the ostree origin refspec file is no longer touched
    String ostreeOriginRefspecAfter = ostreeOriginFile == null ? null : clienttasks.getConfFileParameter(ostreeOriginFile.getPath(), "origin", "refspec");
    // also assert the clean up of remotes from the old /ostree/repo/config file
    if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.13.9-1")) {
        // post committ 11b377f78dcb06d8dbff5645750791b729e20a0e
        if (RemoteFileTasks.testExists(client, oldOstreeRepoConfigFile.getPath())) {
            Assert.assertTrue(getCurrentlyConfiguredOstreeRepos(oldOstreeRepoConfigFile).isEmpty(), "Subscription-manager should have cleaned out the old remotes from '" + oldOstreeRepoConfigFile + "'.");
        }
    }
    // assert that ostree repos have been added for each ostree content namespace
    List<ContentNamespace> osTreeContentNamespaces = ContentNamespace.findAllInstancesWithMatchingFieldFromList("type", "ostree", entitlementCert.contentNamespaces);
    List<ContentNamespace> osTreeContentNamespacesMatchingInstalledProducts = new ArrayList<ContentNamespace>();
    for (ContentNamespace osTreeContentNamespace : osTreeContentNamespaces) {
        log.info("Asserting the following ostree contentNamespace is added to ostree config file '" + ostreeRepoConfigFile + "' : " + osTreeContentNamespace);
        // THIS TAGGING DECISION WAS IMPLEMENTED AS A SOLUTION TO https://bugzilla.redhat.com/show_bug.cgi?id=1153366#c5
        if (clienttasks.areAllRequiredTagsInContentNamespaceProvidedByProductCerts(osTreeContentNamespace, currentProductCerts)) {
            OstreeRepo ostreeRepo = OstreeRepo.findFirstInstanceWithMatchingFieldFromList("remote", osTreeContentNamespace.label, ostreeReposAfter);
            Assert.assertNotNull(ostreeRepo, "Found an OSTree repo configuration in '" + ostreeRepoConfigFile + "' after attaching subscription '" + osTreeSubscriptionPool.subscriptionName + "' originating from entitlement content: " + osTreeContentNamespace);
            Assert.assertEquals(ostreeRepo.url, baseurl + osTreeContentNamespace.downloadUrl, "OSTree repo remote '" + ostreeRepo.remote + "' config for url. (maps to content downloadUrl)");
            Assert.assertEquals(ostreeRepo.gpg_verify, Boolean.valueOf(!osTreeContentNamespace.gpgKeyUrl.replaceFirst("https?://", "").trim().isEmpty()), "OSTree repo remote '" + ostreeRepo.remote + "' config for gpg-verify. (maps to TRUE when content contains gpgKeyUrl)");
            Assert.assertEquals(ostreeRepo.tls_client_cert_path, entitlementCert.file.getPath(), "OSTree repo remote '" + ostreeRepo.remote + "' config for tls-client-cert-path. (maps to path of the entitlement cert)");
            Assert.assertEquals(ostreeRepo.tls_client_key_path, clienttasks.getEntitlementCertKeyFileFromEntitlementCert(entitlementCert).getPath(), "OSTree repo remote '" + ostreeRepo.remote + "' config for tls-client-key-path. (maps to path of the entitlement cert key)");
            Assert.assertEquals(ostreeRepo.tls_ca_path, repo_ca_cert, "OSTree repo remote '" + ostreeRepo.remote + "' config for tls-ca-path. (maps to path of the candlepin CA cert)");
            if (!osTreeContentNamespacesMatchingInstalledProducts.contains(osTreeContentNamespace))
                osTreeContentNamespacesMatchingInstalledProducts.add(osTreeContentNamespace);
        } else {
            OstreeRepo ostreeRepo = OstreeRepo.findFirstInstanceWithMatchingFieldFromList("remote", osTreeContentNamespace.label, ostreeReposAfter);
            Assert.assertNull(ostreeRepo, "Should NOT find an OSTree repo configuration for remote '" + osTreeContentNamespace.label + "' in '" + ostreeRepoConfigFile + "' after attaching subscription '" + osTreeSubscriptionPool.subscriptionName + "' because the Required Tags '" + osTreeContentNamespace.requiredTags + "' from the entitlement content are not found among the current product certs installed.");
        }
    }
    // assert that other ostree repos remain configured
    // TEMPORARY WORKAROUND FOR BUG: 1152734 - Update subman ostree content plugin to use ostree cli for manipulating 'remote' configs
    boolean invokeWorkaroundWhileBugIsOpen = true;
    String bugId = "1152734";
    try {
        if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
        } else {
            invokeWorkaroundWhileBugIsOpen = false;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    if (invokeWorkaroundWhileBugIsOpen) {
        log.warning("Skipping the assertion that other remotes in '" + ostreeRepoConfigFile + "' remain unchanged when attaching an atomic subscription.");
    } else
        // END OF WORKAROUND
        for (OstreeRepo ostreeRepoBefore : ostreeReposBefore) {
            if (ContentNamespace.findFirstInstanceWithMatchingFieldFromList("label", ostreeRepoBefore.remote, osTreeContentNamespaces) == null) {
                OstreeRepo ostreeRepoAfter = OstreeRepo.findFirstInstanceWithMatchingFieldFromList("remote", ostreeRepoBefore.remote, ostreeReposAfter);
                Assert.assertNotNull(ostreeRepoAfter, "OSTree repo configuration in '" + ostreeRepoConfigFile + "' remote '" + ostreeRepoBefore.remote + "' remains configured after attaching subscription '" + osTreeSubscriptionPool.subscriptionName + "' (because it was not among the ostree content sets).");
                Assert.assertEquals(ostreeRepoAfter.url, ostreeRepoBefore.url, "Remote '" + ostreeRepoBefore.remote + "' url");
                Assert.assertEquals(ostreeRepoAfter.gpg_verify, ostreeRepoBefore.gpg_verify, "Remote '" + ostreeRepoBefore.remote + "' gpg-verify");
                Assert.assertEquals(ostreeRepoAfter.tls_client_cert_path, ostreeRepoBefore.tls_client_cert_path, "Remote '" + ostreeRepoBefore.remote + "' tls-client-cert-path");
                Assert.assertEquals(ostreeRepoAfter.tls_client_key_path, ostreeRepoBefore.tls_client_key_path, "Remote '" + ostreeRepoBefore.remote + "' tls-client-key-path");
                Assert.assertEquals(ostreeRepoAfter.tls_ca_path, ostreeRepoBefore.tls_ca_path, "Remote '" + ostreeRepoBefore.remote + "' tls-ca-path");
            }
        }
    /* replacing this with assertion that there is only osTreeContentNamespaceToTest
		// throw a failure on the subscription if there is more than one ostree repo
		// if there is more than one ostree repo, then it is undefined which repo remote to set in the ostree origin file
		Assert.assertEquals(osTreeContentNamespaces.size(), 1, "The number of ostree content sets provided by atomic subscription '"+osTreeSubscriptionPool.subscriptionName+"'.  (Greater than 1 is undefined)");
*/
    // assert that there is only one entitled osTreeContentNamespaceMatchingInstalledProducts
    // TEMPORARY WORKAROUND FOR BUG: 1160771 - Missing provides/requires tags in ostree content sets (not product cert)
    invokeWorkaroundWhileBugIsOpen = true;
    // Status: 	MODIFIED
    invokeWorkaroundWhileBugIsOpen = false;
    bugId = "1160771";
    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) {
        if (osTreeContentNamespacesMatchingInstalledProducts.size() > 1)
            log.warning("Found more than one entitled ostree ContentNamespace whose RequiredTags match the installed productCerts.  Blocked by Jira request https://projects.engineering.redhat.com/browse/APPINFRAT-246");
        log.warning("Skipping the assertion for more than one entitled ostree ContentNamespace whose RequiredTags match the installed productCerts due to open bug '" + bugId + "'.");
    }
    // END OF WORKAROUND
    if (clienttasks.isPackageVersion("subscription-manager-plugin-ostree", "<", "1.13.9-1")) {
        // commit 11b377f78dcb06d8dbff5645750791b729e20a0e
        // Bug 1152734 - Update subman ostree content plugin to use ostree cli for manipulating 'remote' configs
        Assert.fail("This version of subscription-manager-plugin-ostree is blocked by bug 1152734.");
    }
    ContentNamespace osTreeContentNamespaceMatchingInstalledProducts = null;
    if (osTreeContentNamespacesMatchingInstalledProducts.isEmpty()) {
        log.warning("This is probably NOT an atomic system.");
        if (ostreeOriginRefspecBefore != null)
            Assert.assertEquals(ostreeOriginRefspecAfter, ostreeOriginRefspecBefore, "When there are no installed products whose tags match the ostree ContentNamespace tags, then the ostree origin refspec in file '" + ostreeOriginFile + "' should remain unchanged after attaching subscription '" + osTreeSubscriptionPool.subscriptionName + "'.");
    } else {
        Assert.assertEquals(osTreeContentNamespacesMatchingInstalledProducts.size(), 1, "At most there should only be one entitled ostree ContentNamespace that matches the installed product certs.");
        osTreeContentNamespaceMatchingInstalledProducts = osTreeContentNamespacesMatchingInstalledProducts.get(0);
        // UPDATE: After subscription-manager-plugin-ostree-1.18.5-1 RFE Bug 1378495, the ostree origin refspec file is no longer touched
        if (ostreeOriginRefspecAfter != null)
            Assert.assertEquals(ostreeOriginRefspecAfter.split(":")[1], ostreeOriginRefspecBefore.split(":")[1], "The remote path portion of the refspec in the ostree origin file '" + ostreeOriginFile + "' should remain unchanged after attaching atomic subscription '" + osTreeSubscriptionPool.subscriptionName + "'.");
        if (ostreeOriginRefspecAfter != null)
            Assert.assertEquals(ostreeOriginRefspecAfter.split(":")[0], osTreeContentNamespaceMatchingInstalledProducts.label, "The remote label portion of the refspec in the ostree origin file '" + ostreeOriginFile + "' should be updated to the newly entitled ostree content label after attaching atomic subscription '" + osTreeSubscriptionPool.subscriptionName + "'.");
    }
    // attempt to do an atomic upgrade
    String pkg = "rpm-ostree-client";
    if (!clienttasks.isPackageInstalled(pkg)) {
        log.warning("Skipping assertion attempt to do an atomic upgrade after attaching the atomic subscription since package '" + pkg + "' is not installed.");
    } else {
        SSHCommandResult atomicUpgradeResultAfterSubscribe = client.runCommandAndWait("atomic upgrade");
        // -bash-4.2# atomic upgrade
        // Updating from: rhel-atomic-host-beta-ostree:rhel-atomic-host/7/x86_64/standard
        // 
        // Requesting /content/beta/rhel/atomic/7/x86_64/ostree/repo/refs/heads/rhel-atomic-host/7/x86_64/standard
        // Copying /etc changes: 13 modified, 4 removed, 42 added
        // Transaction complete; bootconfig swap: no deployment count change: 0
        // Changed:
        // docker-1.2.0-1.8.el7.x86_64
        // kubernetes-0.4+-0.9.git8e1d416.el7.x86_64
        // tzdata-2014i-1.el7.noarch
        // Updates prepared for next boot; run "systemctl reboot" to start a reboot
        // -bash-4.2#
        String stdoutStartsWith = "Updating from: " + ostreeOriginRefspecBefore;
        String stdoutEndsWith = "Updates prepared for next boot; run \"systemctl reboot\" to start a reboot";
        Assert.assertEquals(atomicUpgradeResultAfterSubscribe.getExitCode(), new Integer(0), "Exitcode after attempting to do an atomic upgrade after attaching an atomic subscription.");
        Assert.assertTrue(atomicUpgradeResultAfterSubscribe.getStdout().trim().startsWith(stdoutStartsWith), "Stdout starts with '" + stdoutStartsWith + "' after attempting to do an atomic upgrade after attaching an atomic subscription.");
        Assert.assertTrue(atomicUpgradeResultAfterSubscribe.getStdout().trim().endsWith(stdoutEndsWith), "Stdout ends with '" + stdoutEndsWith + "' after attempting to do an atomic upgrade after attaching an atomic subscription.");
        Assert.assertEquals(atomicUpgradeResultAfterSubscribe.getStderr().trim(), "", "Exitcode after attempting to do an atomic upgrade after attaching an atomic subscription.");
        // -bash-4.2# atomic status
        // VERSION   ID             OSNAME               REFSPEC
        // 7.0.4     0fc676bdec     rhel-atomic-host     rhel-atomic-host-beta-ostree:rhel-atomic-host/7/x86_64/standard
        // * 7.0.2     9a0dbc159e     rhel-atomic-host     rhel-atomic-host-beta-ostree:rhel-atomic-host/7/x86_64/standard
        // -bash-4.2#
        // This sample output shows that rhel-atomic-host 0fc676bdec... will be booted into on the next restart. The version to be booted on
        // the next restart is printed first.
        // This sample also shows that rhel-atomic-host 9a0dbc159e... is the currently running version. The currently running version is
        // marked with an asterisk (*). This output was created just after the atomic upgrade command was executed, therefore a new
        // version has been staged to be applied at the next restart.
        SSHCommandResult atomicStatusResultAfterSubscribe = client.runCommandAndWait("atomic status | grep -v VERSION");
        Assert.assertTrue(!atomicStatusResultAfterSubscribe.getStdout().trim().split("\n")[0].startsWith("*"), "Stdout from atomic status after doing an atomic upgrade indicates that the upgraded version is listed first and will be booted on the next systemctl reboot.");
        Assert.assertTrue(atomicStatusResultAfterSubscribe.getStdout().trim().split("\n")[1].startsWith("*"), "Stdout from atomic status after doing an atomic upgrade indicates that the currently running version (listed second) is marked with an asterisk (*)");
    }
    // MOVED TO SUBSEQUENT TEST
    // // randomly choose to remove the ostree subscription and assert...
    // if (getRandomBoolean()) {
    // MOVED BACK
    clienttasks.unsubscribe(null, clienttasks.getSerialNumberFromEntitlementCertFile(entitlementCert.file), null, null, null, null, null);
    // after removing the entitlement, assert its corresponding ostree repos are removed
    ostreeReposAfter = getCurrentlyConfiguredOstreeRepos(ostreeRepoConfigFile);
    for (ContentNamespace osTreeContentNamespace : osTreeContentNamespaces) {
        OstreeRepo ostreeRepo = OstreeRepo.findFirstInstanceWithMatchingFieldFromList("remote", osTreeContentNamespace.label, ostreeReposAfter);
        Assert.assertNull(ostreeRepo, "Should no longer find an OSTree repo configuration for remote '" + osTreeContentNamespace.label + "' in '" + ostreeRepoConfigFile + "' after removing subscription '" + osTreeSubscriptionPool.subscriptionName + "'.");
    }
    // TODO: This assertion may be changed by Bug 1193208 - 'atomic host upgrade' gives incorrect error after unregistering with subscription-manager
    if (ostreeOriginFile != null)
        Assert.assertEquals(clienttasks.getConfFileParameter(ostreeOriginFile.getPath(), "origin", "refspec"), ostreeOriginRefspecAfter, "The OSTree origin refspec in '" + ostreeOriginFile + "' should remain unchanged after removing subscription '" + osTreeSubscriptionPool.subscriptionName + "'.");
    // when removing the entitlement, assert that other ostree repos remain configured
    // TEMPORARY WORKAROUND FOR BUG: https://bugzilla.redhat.com/show_bug.cgi?id=1152734
    invokeWorkaroundWhileBugIsOpen = true;
    bugId = "1152734";
    try {
        if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
        } else {
            invokeWorkaroundWhileBugIsOpen = false;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    if (invokeWorkaroundWhileBugIsOpen) {
        log.warning("Skipping the assertion that other remotes in '" + ostreeRepoConfigFile + "' remain unchanged when removing an atomic subscription.");
    } else
        // END OF WORKAROUND
        for (OstreeRepo ostreeRepoBefore : ostreeReposBefore) {
            if (ContentNamespace.findFirstInstanceWithMatchingFieldFromList("label", ostreeRepoBefore.remote, osTreeContentNamespaces) == null) {
                OstreeRepo ostreeRepoAfter = OstreeRepo.findFirstInstanceWithMatchingFieldFromList("remote", ostreeRepoBefore.remote, ostreeReposAfter);
                Assert.assertNotNull(ostreeRepoAfter, "OSTree repo configuration in '" + ostreeRepoConfigFile + "' remote '" + ostreeRepoBefore.remote + "' remains configured after removing subscription '" + osTreeSubscriptionPool.subscriptionName + "' (because it was not among the ostree content sets).");
                Assert.assertEquals(ostreeRepoAfter.url, ostreeRepoBefore.url, "Remote '" + ostreeRepoBefore.remote + "' url");
                Assert.assertEquals(ostreeRepoAfter.gpg_verify, ostreeRepoBefore.gpg_verify, "Remote '" + ostreeRepoBefore.remote + "' gpg-verify");
                Assert.assertEquals(ostreeRepoAfter.tls_client_cert_path, ostreeRepoBefore.tls_client_cert_path, "Remote '" + ostreeRepoBefore.remote + "' tls-client-cert-path");
                Assert.assertEquals(ostreeRepoAfter.tls_client_key_path, ostreeRepoBefore.tls_client_key_path, "Remote '" + ostreeRepoBefore.remote + "' tls-client-key-path");
                Assert.assertEquals(ostreeRepoAfter.tls_ca_path, ostreeRepoBefore.tls_ca_path, "Remote '" + ostreeRepoBefore.remote + "' tls-ca-path");
            }
        }
    // }
    // MOVED BACK
    // attempt to run the atomic upgrade without an entitlement
    // /usr/bin/atomic is provided by rpm-ostree-client-2014.109-2.atomic.el7.x86_64
    pkg = "rpm-ostree-client";
    if (!clienttasks.isPackageInstalled(pkg)) {
        log.warning("Skipping assertion attempt to do an atomic upgrade after removing the atomic subscription since package '" + pkg + "' is not installed.");
    } else {
        SSHCommandResult atomicUpgradeResultAfterUnsubscribe = client.runCommandAndWait("atomic upgrade");
        // -bash-4.2# atomic upgrade
        // Updating from: rhel-atomic-host-beta-ostree:rhel-atomic-host/7/x86_64/standard
        // 
        // 
        // error: No remote 'remote "rhel-atomic-host-beta-ostree"' found in /etc/ostree/remotes.d
        // -bash-4.2#
        // TODO: need to be run on Atomic and updated to make a better assert after the changes from subscription-manager-1.18.5-1 Bug 1378495 - [RFE] Do not change OStree origin refspec
        String stdoutStartsWith = "Updating from: " + ostreeOriginRefspecAfter;
        Assert.assertEquals(atomicUpgradeResultAfterUnsubscribe.getExitCode(), new Integer(1), "Exitcode after attempting to do an atomic upgrade after removing the atomic subscription.");
        Assert.assertTrue(atomicUpgradeResultAfterUnsubscribe.getStdout().trim().startsWith(stdoutStartsWith), "Stdout starts with '" + stdoutStartsWith + "' after attempting to do an atomic upgrade after removing the atomic subscription.");
        Assert.assertEquals(atomicUpgradeResultAfterUnsubscribe.getStderr().trim(), "error: No remote 'remote \"" + osTreeContentNamespaceMatchingInstalledProducts.label + "\"' found in /etc/ostree/remotes.d", "Exitcode after attempting to do an atomic upgrade after removing the atomic subscription.");
    }
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) ArrayList(java.util.ArrayList) ProductCert(rhsm.data.ProductCert) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) BigInteger(java.math.BigInteger) ContentNamespace(rhsm.data.ContentNamespace) OstreeRepo(rhsm.data.OstreeRepo) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) File(java.io.File) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 83 with EntitlementCert

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

the class StackingTests method testStackEachPoolToAchieveAttributeCompliance.

// 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-20011", "RHEL7-51033" }, 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: subscribe to each pool with the same stacking_id to achieve compliance", enabled = true, groups = { "Tier1Tests", "blockedByBug-739671", "blockedByBug-740377", "blockedByBug-861993", "blockedByBug-955142" }, dataProvider = "getAvailableStackableAttributeSubscriptionPoolsData")
public // @ImplementsNitrateTest(caseId=)
void testStackEachPoolToAchieveAttributeCompliance(Object bugzilla, String attribute, boolean systemIsGuest, List<SubscriptionPool> stackableAttributeSubscriptionPools) throws JSONException, Exception {
    // The strategy in this test is to simulate the facts on the systems so that the attribute being tested ("cores","ram",or "sockets", or "vcpu")
    // will achieve full compliance for all of the provided products after attaching a quantity of one entitlement
    // from each pool in the list of stackable subscription pools.  As we incrementally attach from each pool, we will assert
    // a partial compliance until the final subscription is attached which should achieve full compliance.
    // loop through the pools to determine the minimum attribute count for which one
    // of each stackable pool is needed to achieve compliance of the provided products
    // also keep a list of all the provided productIds
    Integer minimumAttributeValue = 0;
    Integer minimumSocketsValue = 0;
    Set<String> productIdsProvidedForByAllStackableSubscriptionPools = new HashSet<String>();
    Map<String, Integer> poolProductAttributeValueMap = new HashMap<String, Integer>();
    for (SubscriptionPool pool : stackableAttributeSubscriptionPools) {
        String attributeValue = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, attribute);
        productIdsProvidedForByAllStackableSubscriptionPools.addAll(CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId));
        minimumAttributeValue += Integer.valueOf(attributeValue);
        poolProductAttributeValueMap.put(pool.poolId, Integer.valueOf(attributeValue));
    }
    // override the system facts setting the attribute count to a value for which all the stackable subscriptions are needed to achieve compliance
    Map<String, String> factsMap = new HashMap<String, String>();
    // force the system to be physical or virtual
    factsMap.put("virt.is_guest", Boolean.valueOf(systemIsGuest).toString());
    factsMap.put("memory.memtotal", "1");
    factsMap.put("cpu.cpu_socket(s)", "1");
    factsMap.put("cpu.core(s)_per_socket", "1");
    if (attribute.equals("ram")) {
        // "memory.memtotal" is stored in Kilobytes; "ram" is specified in Gigabytes; for conversions, see http://www.whatsabyte.com/P1/byteconverter.htm
        factsMap.put("memory.memtotal", String.valueOf(minimumAttributeValue * 1048576));
    }
    if (attribute.equals("sockets")) {
        factsMap.put("cpu.cpu_socket(s)", String.valueOf(minimumAttributeValue));
    }
    if (attribute.equals("cores") || attribute.equals("vcpu")) {
        // vcpu (on a virt system) maps to cores (on a physical system)
        if (Integer.valueOf(minimumAttributeValue) % 2 == 0) {
            // configure facts for an even number of cores
            factsMap.put("cpu.core(s)_per_socket", "2");
            minimumSocketsValue = Integer.valueOf(minimumAttributeValue) / 2;
            factsMap.put("cpu.cpu_socket(s)", String.valueOf(minimumSocketsValue));
        } else {
            // configure facts for an odd number of cores
            factsMap.put("cpu.core(s)_per_socket", "1");
            minimumSocketsValue = Integer.valueOf(minimumAttributeValue);
            factsMap.put("cpu.cpu_socket(s)", String.valueOf(minimumSocketsValue));
        }
    }
    clienttasks.createFactsFileWithOverridingValues(factsMap);
    // register the system which has now been instrumented with facts to test the stack
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (List<String>) null, null, null, null, true, false, null, null, null, null);
    // assert installed product status for all the products that the stacked subscriptions will provide for
    List<InstalledProduct> currentlyInstalledProducts = clienttasks.getCurrentlyInstalledProducts();
    for (String productId : productIdsProvidedForByAllStackableSubscriptionPools) {
        List<InstalledProduct> installedProducts = InstalledProduct.findAllInstancesWithMatchingFieldFromList("productId", productId, currentlyInstalledProducts);
        // this productIdProvidedFor is not installed
        if (installedProducts.isEmpty())
            continue;
        // this should be impossible because the would all share the same /etc/pki/product/<productId>.pem file name
        if (installedProducts.size() > 1)
            Assert.fail("Something is seriously wrong.  Found multiple InstalledProduct " + installedProducts + " with a common productId '" + productId + "'.");
        InstalledProduct installedProduct = installedProducts.get(0);
        // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
        List<String> expectedStatusDetails = Arrays.asList(new String[] { "Not supported by a valid subscription." });
        Assert.assertEquals(installedProduct.status, "Not Subscribed", "Prior to subscribing to any of the stackable subscription pools, Installed product '" + installedProduct.productName + "' which is provided for by the subscription stack should have this status.");
        if (installedProduct.statusDetails.isEmpty())
            log.warning("Status Details appears empty.  Is your candlepin server older than 0.8.6?");
        Assert.assertEquals(installedProduct.statusDetails, expectedStatusDetails, "Prior to subscribing to any of the stackable subscription pools, Installed product '" + installedProduct.productName + "' which is provided for by the subscription stack should have these status details: " + expectedStatusDetails);
    // Assert.assertTrue(isEqualNoOrder(installedProduct.statusDetails,expectedStatusDetails),"Prior to subscribing to any of the stackable subscription pools, Installed product '"+installedProduct.productName+"' which is provided for by the subscription stack should have these status details: "+expectedStatusDetails);
    }
    // incrementally attach one entitlement from each pool in the stack asserting the installed product's status and details along the way
    // the final attachment should achieve full compliance for the provided products in the stack
    int s = 0;
    Integer attributeValueStackedThusFar = 0;
    Integer socketsValueStackedThusFar = 0;
    Integer vcpuValueStackedThusFar = 0;
    Set<String> productIdsProvidedForThusFar = new HashSet<String>();
    for (SubscriptionPool pool : stackableAttributeSubscriptionPools) {
        clienttasks.subscribe(null, null, pool.poolId, null, null, "1", null, null, null, null, null, null, null);
        // add some test coverage for bugs 861993 and 955142
        EntitlementCert entitlementCert = clienttasks.getEntitlementCertCorrespondingToSubscribedPool(pool);
        if (attribute.equals("ram")) {
            Assert.assertEquals(entitlementCert.orderNamespace.ramLimit, poolProductAttributeValueMap.get(pool.poolId).toString(), "rct cat-cert tool reports the expected RAM Limit value in the Order for subscription '" + pool.subscriptionName + "'.");
        }
        if (attribute.equals("sockets")) {
            Assert.assertEquals(entitlementCert.orderNamespace.socketLimit, poolProductAttributeValueMap.get(pool.poolId).toString(), "rct cat-cert tool reports the expected Socket Limit value in the Order for subscription '" + pool.subscriptionName + "'.");
        }
        if (attribute.equals("cores")) {
            Assert.assertEquals(entitlementCert.orderNamespace.coreLimit, poolProductAttributeValueMap.get(pool.poolId).toString(), "rct cat-cert tool reports the expected Core Limit value in the Order for subscription '" + pool.subscriptionName + "'.");
        }
        /* TODO Open a bug to include vcpu in the order repo
			 * Bug 1055617 - [RFE] rct cat-cert should also report the "VCPU Limit" attribute for an Order
			if (attribute.equals("vcpu")) {
				Assert.assertEquals(entitlementCert.orderNamespace.vcpuLimit,poolProductAttributeValueMap.get(pool.poolId).toString(),"rct cat-cert tool reports the expected VCPU Limit value in the Order for subscription '"+pool.subscriptionName+"'.");
			}
			*/
        // keep a running total of how much of the stackable attribute our entitlements have covered thus far
        attributeValueStackedThusFar += poolProductAttributeValueMap.get(pool.poolId);
        // keep a running total of how much socket coverage our stacked entitlements have covered thus far
        String socketsValue = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "sockets");
        if (socketsValue != null) {
            socketsValueStackedThusFar += Integer.valueOf(socketsValue);
        }
        // keep a running total of how much vcpu coverage our stacked entitlements have covered thus far
        String vcpuValue = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "vcpu");
        if (vcpuValue != null) {
            vcpuValueStackedThusFar += Integer.valueOf(vcpuValue);
        }
        // keep a running set of which productIdsProvidedFor have been covered by the subscriptions thus far
        productIdsProvidedForThusFar.addAll(CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId));
        // assert the installed products that have been provided for by the stack of subscriptions thus far are Partially Subscribed
        for (InstalledProduct installedProduct : clienttasks.getCurrentlyInstalledProducts()) {
            if (productIdsProvidedForThusFar.contains(installedProduct.productId)) {
                List<String> expectedStatusDetails = new ArrayList<String>();
                if (attribute.equals("ram") && attributeValueStackedThusFar < minimumAttributeValue) {
                    // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
                    expectedStatusDetails.add(String.format("Only supports %sGB of %sGB of RAM.", attributeValueStackedThusFar, minimumAttributeValue));
                }
                if (attribute.equals("sockets") && !systemIsGuest && attributeValueStackedThusFar < minimumAttributeValue) {
                    // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
                    expectedStatusDetails.add(String.format("Only supports %s of %s sockets.", attributeValueStackedThusFar, minimumAttributeValue));
                }
                if (attribute.equals("cores") && !systemIsGuest && attributeValueStackedThusFar < minimumAttributeValue) {
                    // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
                    expectedStatusDetails.add(String.format("Only supports %s of %s cores.", attributeValueStackedThusFar, minimumAttributeValue));
                }
                if (attribute.equals("vcpu") && systemIsGuest && attributeValueStackedThusFar < minimumAttributeValue) {
                    // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
                    expectedStatusDetails.add(String.format("Only supports %s of %s vCPUs.", attributeValueStackedThusFar, minimumAttributeValue));
                }
                if (attribute.equals("cores") && !systemIsGuest && socketsValueStackedThusFar > 0 && socketsValueStackedThusFar < minimumSocketsValue) {
                    // when a cores stack also includes sockets (on a physical system), we will have more status details
                    // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
                    expectedStatusDetails.add(String.format("Only supports %s of %s sockets.", socketsValueStackedThusFar, minimumSocketsValue));
                }
                if (attribute.equals("cores") && systemIsGuest && vcpuValueStackedThusFar > 0 && vcpuValueStackedThusFar < minimumAttributeValue) {
                    // when a cores stack also includes vcpu (on a virtual system), we will have more status details
                    // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
                    expectedStatusDetails.add(String.format("Only supports %s of %s vCPUs.", vcpuValueStackedThusFar, minimumAttributeValue));
                }
                if (attribute.equals("sockets") && systemIsGuest && vcpuValueStackedThusFar > 0 && vcpuValueStackedThusFar < minimumAttributeValue) {
                    // when a sockets stack also includes vcpu (on a virtual system), we will have more status details
                    // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
                    expectedStatusDetails.add(String.format("Only supports %s of %s vCPUs.", vcpuValueStackedThusFar, minimumAttributeValue));
                }
                if (attribute.equals("vcpu") && !systemIsGuest && socketsValueStackedThusFar > 0 && socketsValueStackedThusFar < minimumSocketsValue) {
                    // when a vcpu stack also includes sockets (on a physical system), we will have more status details
                    // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
                    expectedStatusDetails.add(String.format("Only supports %s of %s sockets.", socketsValueStackedThusFar, minimumSocketsValue));
                }
                if (expectedStatusDetails.isEmpty()) {
                    Assert.assertEquals(installedProduct.status, "Subscribed", "After an incremental attachment of one stackable '" + attribute + "' subscription for '" + pool.subscriptionName + "' poolId=" + pool.poolId + ", Installed product '" + installedProduct.productName + "' which is provided for by the subscription stack should have this status.");
                } else {
                    if (installedProduct.statusDetails.isEmpty())
                        log.warning("Status Details appears empty.  Is your candlepin server older than 0.8.6?");
                    Assert.assertTrue(isEqualNoOrder(installedProduct.statusDetails, expectedStatusDetails), "After an incremental attachment of one stackable '" + attribute + "' subscription for '" + pool.subscriptionName + "' poolId=" + pool.poolId + ", Installed product '" + installedProduct.productName + "' which is provided for by the subscription stack should have status details " + expectedStatusDetails + " (actual= " + installedProduct.statusDetails + ")");
                    Assert.assertEquals(installedProduct.status, "Partially Subscribed", "After an incremental attachment of one stackable '" + attribute + "' subscription for '" + pool.subscriptionName + "' poolId=" + pool.poolId + ", Installed product '" + installedProduct.productName + "' which is provided for by the subscription stack should have this status.");
                }
            } else {
                if (productIdsProvidedForByAllStackableSubscriptionPools.contains(installedProduct.productId)) {
                    // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
                    List<String> expectedStatusDetails = Arrays.asList(new String[] { "Not supported by a valid subscription." });
                    if (installedProduct.statusDetails.isEmpty())
                        log.warning("Status Details appears empty.  Is your candlepin server older than 0.8.6?");
                    Assert.assertEquals(installedProduct.status, "Not Subscribed", "After an incremental attachment of one stackable subscription for '" + pool.subscriptionName + "' poolId=" + pool.poolId + ", Installed product '" + installedProduct.productName + "' which is NOT YET provided for by the subscription stack THUS FAR should have this status.");
                    Assert.assertEquals(installedProduct.statusDetails, expectedStatusDetails, "After an incremental attachment of one stackable subscription for '" + pool.subscriptionName + "' poolId=" + pool.poolId + ", Installed product '" + installedProduct.productName + "' which is NOT YET provided for by the subscription stack THUS FAR should have these status details: " + expectedStatusDetails);
                // Assert.assertTrue(isEqualNoOrder(installedProduct.statusDetails,expectedStatusDetails), "After an incremental attachment of one stackable subscription for '"+pool.subscriptionName+"' poolId="+pool.poolId+", Installed product '"+installedProduct.productName+"' which is NOT YET provided for by the subscription stack THUS FAR should have these status details: "+expectedStatusDetails);
                } else {
                /* These asserts are valid, but not really relevant to this test.  Commented out to reduce noisy logging.
						List<String> expectedStatusDetails = Arrays.asList(new String[]{"Not supported by a valid subscription."}); // Message changed by candlepin commit 43a17952c724374c3fee735642bce52811a1e386 covers -> supports
						Assert.assertEquals(installedProduct.status,"Not Subscribed","After subscribing to stackable subscription for '"+pool.subscriptionName+"' poolId="+pool.poolId+", Installed product '"+installedProduct.productName+"' which is NOT provided for by the subscription stack should have this status.");
						Assert.assertTrue(isEqualNoOrder(installedProduct.statusDetails,expectedStatusDetails), "After subscribing to stackable subscription for '"+pool.subscriptionName+"' poolId="+pool.poolId+", Installed product '"+installedProduct.productName+"' which is NOT provided for by the subscription stack should have these status details: "+expectedStatusDetails);
						*/
                }
            }
        }
    }
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) InstalledProduct(rhsm.data.InstalledProduct) SubscriptionPool(rhsm.data.SubscriptionPool) HashSet(java.util.HashSet) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 84 with EntitlementCert

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

the class SubscribeTests method testOlderClientsAreDeniedEntitlementsToRamAndCoresBasedSubscriptions.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-27121", "RHEL7-51386" }, 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 = "Make sure that older subscription-managers are denied attempts to attach a subscription based on: ram, cores", groups = { "Tier2Tests", "VerifyOlderClientsAreDeniedEntitlementsToRamAndCoresBasedSubscriptions_Test", "blockedByBug-957218" }, dataProvider = "getAllAvailableRamCoresSubscriptionPoolsData", // TODO THIS TEST IS A CANDIDATE FOR DISABLEMENT AFTER IMPLEMENTATION OF BUG 957218
enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testOlderClientsAreDeniedEntitlementsToRamAndCoresBasedSubscriptions(Object bugzilla, SubscriptionPool pool) throws JSONException, Exception {
    if (true) {
        log.warning("Effectively, this test is now obsolete due to RFE Bugzilla https://bugzilla.redhat.com/show_bug.cgi?id=888866 which reversed the original intent of this test.");
        String systemCertificateVersion = clienttasks.getFactValue("system.certificate_version");
        EntitlementCert entitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(clienttasks.subscribeToSubscriptionPool(pool, sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl));
        Assert.assertEquals(entitlementCert.version, "1.0", "RAM and Core based subscriptions are now granted to older subscription-manager clients regardless of version.  See RFE bugzilla https://bugzilla.redhat.com/show_bug.cgi?id=888866");
        Assert.assertNull(entitlementCert.orderNamespace.coreLimit, "Core limit included in an entitlement cert when system.certificate_version is old '" + systemCertificateVersion + "'.");
        Assert.assertNull(entitlementCert.orderNamespace.ramLimit, "RAM limit included in an entitlement cert when system.certificate_version is old '" + systemCertificateVersion + "'.");
        return;
    }
    /*
		The way that this works is that all attributes that are specified on a
		pool are version checked. Here are the current versions:
		ram: 3.1
		cores: 3.2
		sockets: 1.0

		If a pool has a ram attribute, the minimum required version will be 3.1.
		If a pool has a cores attribute, the minimum required version will be 3.2
		if a pool has cores AND ram attributes, the minimum required version
		will be 3.2

		Again, each attribute on the pool will be checked against the above
		versions, and the largest found will be the minimum required version
		that the client must support in order to attach that sub.

		Supported versions do not change based on stacking... it changes when
		the certificate content changes. i.e when the cores attribute was added
		to the cert. It has no relation to what our rules support.

		So both examples above are correct since the system is 1.0. They are
		dealing with RAM subscriptions, so they should be restricted to clients
		supporting certificate versions >= 3.1

		If the test subs were to include cores, it would require 3.2

		Clear as mud!?

		Ping me if you have more questions about this.

		--mstead
		*/
    // [root@jsefler-5 ~]# subscription-manager subscribe --pool=8a90f8313e472bce013e472d22150352
    // The client must support at least v3.1 certificates in order to use subscription: Multi-Attribute (non-stackable) (24 cores, 6 sockets, 8GB RAM). A newer client may be available to address this problem.
    // [root@jsefler-5 ~]#
    String systemCertificateVersion = clienttasks.getFactValue("system.certificate_version");
    SSHCommandResult subscribeResult = clienttasks.subscribe_(null, null, pool.poolId, null, null, null, null, null, null, null, null, null, null);
    Assert.assertEquals(subscribeResult.getExitCode(), new Integer(255), "Exitcode from an attempt to subscribe to '" + pool.subscriptionName + "' when system.certificate_version is old '" + systemCertificateVersion + "'.");
    // CORES-based subscriptions
    if (CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "cores") != null) {
        Assert.assertEquals(subscribeResult.getStderr().trim(), String.format("The client must support at least v%s certificates in order to use subscription: %s. A newer client may be available to address this problem.", "3.2", pool.subscriptionName), "Stderr from an attempt to subscribe to '" + pool.subscriptionName + "' a CORES-based subscription when system.certificate_version is < 3.2");
        Assert.assertEquals(subscribeResult.getStdout().trim(), "", "Stdout from an attempt to subscribe to '" + pool.subscriptionName + "' a CORES-based subscription when system.certificate_version is < 3.2");
        return;
    }
    // RAM-based subscriptions
    if (CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId, "ram") != null) {
        Assert.assertEquals(subscribeResult.getStderr().trim(), String.format("The client must support at least v%s certificates in order to use subscription: %s. A newer client may be available to address this problem.", "3.1", pool.subscriptionName), "Stderr from an attempt to subscribe to '" + pool.subscriptionName + "' a RAM-based subscription when system.certificate_version is < 3.1");
        Assert.assertEquals(subscribeResult.getStdout().trim(), "", "Stdout from an attempt to subscribe to '" + pool.subscriptionName + "' a RAM-based subscription when system.certificate_version is < 3.1");
        return;
    }
    Assert.fail("Do not know how to assert the attempted attachment of '" + pool.subscriptionName + "'.");
}
Also used : BigInteger(java.math.BigInteger) EntitlementCert(rhsm.data.EntitlementCert) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 85 with EntitlementCert

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

the class SubscribeTests method testCandlepinConsumerEntitlementsDryrunWithServiceLevel.

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

Aggregations

EntitlementCert (rhsm.data.EntitlementCert)94 Test (org.testng.annotations.Test)63 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)58 SkipException (org.testng.SkipException)39 ArrayList (java.util.ArrayList)38 File (java.io.File)36 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)35 SubscriptionPool (rhsm.data.SubscriptionPool)33 SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)30 JSONObject (org.json.JSONObject)29 ContentNamespace (rhsm.data.ContentNamespace)26 ProductCert (rhsm.data.ProductCert)23 BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)17 BigInteger (java.math.BigInteger)17 ProductSubscription (rhsm.data.ProductSubscription)17 List (java.util.List)16 Calendar (java.util.Calendar)11 HashMap (java.util.HashMap)11 ProductNamespace (rhsm.data.ProductNamespace)11 HashSet (java.util.HashSet)8