Search in sources :

Example 21 with ProductCert

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

the class CertificateTests method testBaseRHELProductCertVersionFromEachCDNReleaseVersion.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20028", "RHEL7-33082" }, 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 base RHEL product certs on the CDN for each release correctly reflect the release version.  For example, this affects users that want use subcription-manager release --set=6.3 to keep yum updates fixed to an older release.", groups = { "Tier1Tests", "VerifyBaseRHELProductCertVersionFromEachCDNReleaseVersion_Test" }, dataProvider = "VerifyBaseRHELProductCertVersionFromEachCDNReleaseVersion_TestData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testBaseRHELProductCertVersionFromEachCDNReleaseVersion(Object blockedByBug, String release, String rhelRepoUrl, File rhelEntitlementCertFile, File caCertFile) {
    if (clienttasks.arch.equals("aarch64") && release.matches("7.0|7.1"))
        throw new SkipException("This test variation for aarch64 against release '" + release + "' is blocked by CLOSED WONTFIX bug 1261163 https://bugzilla.redhat.com/show_bug.cgi?id=1261163");
    File certFile = rhelEntitlementCertFile;
    File keyFile = clienttasks.getEntitlementCertKeyFileCorrespondingToEntitlementCertFile(rhelEntitlementCertFile);
    // determine the exact path to the productid on the CDN
    // Repo URL:  https://cdn.redhat.com/content/dist/rhel/server/6/$releasever/$basearch/os
    // ProductId: https://cdn.redhat.com/content/dist/rhel/server/6/$releasever/$basearch/os/repodata/productid
    String basearch = clienttasks.arch;
    // releng content for these systems is published under arch i386
    if (basearch.equals("i686") || basearch.equals("i586") || basearch.equals("i486"))
        basearch = "i386";
    String rhelRepoUrlToProductId = rhelRepoUrl.replace("$releasever", release).replace("$basearch", basearch) + "/repodata/productid";
    // use the entitlement certificates to get the productid
    File localProductIdFile = new File("/tmp/productid");
    RemoteFileTasks.runCommandAndAssert(client, "wget -nv -O " + localProductIdFile + " --ca-certificate=" + caCertFile + " --certificate-type=PEM --certificate=" + certFile + " --private-key=" + keyFile + " --private-key-type=pem " + rhelRepoUrlToProductId, Integer.valueOf(0), null, "-> \"" + localProductIdFile + "\"");
    // [root@dell-pe650-02 ~]# wget -nv -O /tmp/productid --ca-certificate=/etc/rhsm/ca/redhat-uep.pem --certificate-type=PEM --certificate=/etc/pki/entitlement/19553491962157768.pem --private-key=/etc/pki/entitlement/19553491962157768-key.pem --private-key-type=pem https://cdn.redhat.com/content/dist/rhel/server/6/6.1/x86_64/os/repodata/productid
    // 2015-04-29 11:58:44 URL:https://cdn.redhat.com/content/dist/rhel/server/6/6.1/x86_64/os/repodata/productid [2163/2163] -> "/tmp/productid" [1]
    // [root@dell-pe650-02 ~]# rct cat-cert /tmp/productid | grep -A8 "Product:"
    // Product:
    // ID: 69
    // Name: Red Hat Enterprise Linux 6 Server
    // Version: 6.1
    // Arch: x86_64
    // Tags: rhel-6,rhel-6-server
    // Brand Type:
    // Brand Name:
    // create a ProductCert corresponding to the productid file
    ProductCert productIdCert = clienttasks.getProductCertFromProductCertFile(localProductIdFile);
    log.info("Actual product cert from CDN '" + rhelRepoUrlToProductId + "': " + productIdCert);
    // assert the expected productIdCert release version
    String expectedRelease = release;
    if (!isFloat(expectedRelease)) {
        // happens when release is 6Server
        // in this case of 6Server, the newset release version should be expected (TODO, not sure this is entirely true)
        expectedRelease = getNewestReleaseFromReleases(clienttasks.getCurrentlyAvailableReleases(null, null, null, null));
    }
    Assert.assertEquals(productIdCert.productNamespace.version, expectedRelease, "Version of the productid on the CDN at '" + rhelRepoUrlToProductId + "' that will be installed by the yum product-id plugin after setting the subscription-manager release to '" + release + "'.");
}
Also used : ProductCert(rhsm.data.ProductCert) SkipException(org.testng.SkipException) File(java.io.File) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 22 with ProductCert

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

the class ComplianceTests method getSubscriptionPoolProvidingProductIdOnArchDataAsListOfLists.

protected List<List<Object>> getSubscriptionPoolProvidingProductIdOnArchDataAsListOfLists() throws JSONException, Exception {
    List<List<Object>> ll = new ArrayList<List<Object>>();
    if (!isSetupBeforeSuiteComplete)
        return ll;
    // configureProductCertDirAfterClass(); is not needed since the priority of this test is implied as 0 and run first before the other tests alter the productCertDir
    List<ProductCert> productCerts = clienttasks.getCurrentProductCerts();
    List<String> productIdArchTested = new ArrayList<String>();
    boolean isSystemVirtual = Boolean.valueOf(clienttasks.getFactValue("virt.is_guest"));
    for (List<Object> allAvailableSubscriptionPoolsDataList : getAllAvailableSubscriptionPoolsDataAsListOfLists()) {
        SubscriptionPool availableSubscriptionPool = (SubscriptionPool) allAvailableSubscriptionPoolsDataList.get(0);
        // for the purpose of this test, skip unmapped_guests_only pools when system is virtual otherwise the subscribe will fail with "Pool is restricted to unmapped virtual guests: '8a9087e34bdb9471014bdb9573e60af6'."
        if (isSystemVirtual && CandlepinTasks.isPoolRestrictedToUnmappedVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, availableSubscriptionPool.poolId))
            continue;
        // for the purpose of this test, skip physical_only pools when system is virtual otherwise the subscribe will fail with "Pool is restricted to physical systems: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (isSystemVirtual && CandlepinTasks.isPoolRestrictedToPhysicalSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, availableSubscriptionPool.poolId))
            continue;
        // for the purpose of this test, skip virt_only pools when system is physical otherwise the subscribe will fail with "Pool is restricted to virtual guests: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (!isSystemVirtual && CandlepinTasks.isPoolRestrictedToVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, availableSubscriptionPool.poolId))
            continue;
        List<String> providedProductIds = CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, availableSubscriptionPool.poolId);
        String poolProductArch = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, availableSubscriptionPool.poolId, "arch");
        for (ProductCert productCert : productCerts) {
            if (providedProductIds.contains(productCert.productId)) {
                BlockedByBzBug blockedByBzBug = null;
                // if a row has already been added for this productId+arch combination, skip it since adding it would be redundant testing
                if (productIdArchTested.contains(productCert.productId + poolProductArch))
                    continue;
                // Bug 951633 - installed product with comma separated arch attribute fails to go green
                if (productCert.productNamespace.arch.contains(","))
                    blockedByBzBug = new BlockedByBzBug("951633");
                ll.add(Arrays.asList(new Object[] { blockedByBzBug, availableSubscriptionPool, productCert.productId, poolProductArch }));
                productIdArchTested.add(productCert.productId + poolProductArch);
            }
        }
    }
    return ll;
}
Also used : ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) ProductCert(rhsm.data.ProductCert) SubscriptionPool(rhsm.data.SubscriptionPool) BlockedByBzBug(com.redhat.qe.auto.bugzilla.BlockedByBzBug)

Example 23 with ProductCert

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

the class ComplianceTests method setupProductCertDirsBeforeClass.

@BeforeClass(groups = { "setup" }, dependsOnMethods = { "moveOriginalProductCertDefaultDirFilesBeforeClass" })
public void setupProductCertDirsBeforeClass() throws JSONException, Exception {
    // clean out the productCertDirs
    for (String productCertDir : new String[] { productCertDirForSomeProductsSubscribable, productCertDirForAllProductsSubscribable, productCertDirForNoProductsSubscribable, productCertDirForNoProductsinstalled, productCertDirForAllProductsSubscribableInTheFuture, productCertDirForAllProductsSubscribableByOneCommonServiceLevel, productCertDirForAllProductsSubscribableByMoreThanOneCommonServiceLevel }) {
        RemoteFileTasks.runCommandAndAssert(client, "rm -rf " + productCertDir, 0);
        RemoteFileTasks.runCommandAndAssert(client, "mkdir " + productCertDir, 0);
    }
    // register and subscribe to all available subscriptions
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, true, false, null, null, null, null);
    // to avoid unmapped_guests_only pools
    if (Boolean.valueOf(clienttasks.getFactValue("virt.is_guest")))
        clienttasks.mapSystemAsAGuestOfItself();
    clienttasks.subscribeToTheCurrentlyAvailableSubscriptionPoolsCollectively();
    // get the current certs
    List<EntitlementCert> currentEntitlementCerts = clienttasks.getCurrentEntitlementCerts();
    List<ProductCert> currentProductCerts = clienttasks.getCurrentProductCerts();
    List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts();
    // distribute a copy of the product certs amongst the productCertDirs based on their status
    for (ProductCert productCert : currentProductCerts) {
        InstalledProduct installedProduct = clienttasks.getInstalledProductCorrespondingToProductCert(productCert, installedProducts);
        if (installedProduct.status.equals("Not Subscribed")) {
            // "Not Subscribed" case...
            RemoteFileTasks.runCommandAndAssert(client, "cp " + productCert.file + " " + productCertDirForNoProductsSubscribable, 0);
            RemoteFileTasks.runCommandAndAssert(client, "cp " + productCert.file + " " + productCertDirForSomeProductsSubscribable, 0);
        } else if (installedProduct.status.equals("Subscribed")) {
            // "Subscribed" case...
            RemoteFileTasks.runCommandAndAssert(client, "cp " + productCert.file + " " + productCertDirForAllProductsSubscribable, 0);
            RemoteFileTasks.runCommandAndAssert(client, "cp " + productCert.file + " " + productCertDirForSomeProductsSubscribable, 0);
        } else {
        // TODO "Partially Subscribed" case
        // InstalledProduct installedProduct = clienttasks.getInstalledProductCorrespondingToEntitlementCert(correspondingEntitlementCert);
        }
    }
    // setup for productCertDirForAllProductsSubscribableInTheFuture
    // clienttasks.unsubscribeFromAllOfTheCurrentlyConsumedProductSubscriptions();
    List<File> productCertFilesCopied = new ArrayList<File>();
    futureSystemSubscriptionPools = new ArrayList<SubscriptionPool>();
    for (List<Object> futureSystemSubscriptionPoolsDataRow : getAllFutureSystemSubscriptionPoolsDataAsListOfLists()) {
        SubscriptionPool futureSystemSubscriptionPool = (SubscriptionPool) futureSystemSubscriptionPoolsDataRow.get(0);
        // for (ProductCert productCert : clienttasks.getCurrentProductCertsProvidedBySubscriptionPool(futureSystemSubscriptionPool)) {	// TODO not efficient; testing fix on next line
        for (ProductCert productCert : clienttasks.getProductCertsProvidedBySubscriptionPool(currentProductCerts, futureSystemSubscriptionPool)) {
            if (!productCertFilesCopied.contains(productCert.file)) {
                // RemoteFileTasks.runCommandAndAssert(client, "cp -n "+productCert.file+" "+productCertDirForAllProductsSubscribableInTheFuture, 0);	// RHEL5 does not understand cp -n
                // no clobber copy for both RHEL5 ad RHEL6
                RemoteFileTasks.runCommandAndAssert(client, "if [ ! -e " + productCertDirForAllProductsSubscribableInTheFuture + File.separator + productCert.file.getName() + " ]; then cp " + productCert.file + " " + productCertDirForAllProductsSubscribableInTheFuture + "; fi;", 0);
                productCertFilesCopied.add(productCert.file);
                if (!futureSystemSubscriptionPools.contains(futureSystemSubscriptionPool)) {
                    futureSystemSubscriptionPools.add(futureSystemSubscriptionPool);
                }
            }
        }
    }
    // determine the serviceLevel and all the products that are subscribable by one common service level
    // Map<String,Set<String>> serviceLevelToProductIdsMap = getServiceLevelToProductIdsMapFromEntitlementCerts(clienttasks.getCurrentEntitlementCerts());	// TODO not efficient; testing fix on next line
    Map<String, Set<String>> serviceLevelToProductIdsMap = getServiceLevelToProductIdsMapFromEntitlementCerts(currentEntitlementCerts);
    // /*debugTesting*/ serviceLevelToProductIdsMap.get("Premium").add("17000");
    Map<String, Set<String>> productIdsToServiceLevelsMap = getInvertedMap(serviceLevelToProductIdsMap);
    Set<String> allProductsSubscribableByOneCommonServiceLevelCandidates = productIdsToServiceLevelsMap.keySet();
    boolean allProductsSubscribableByOneCommonServiceLevelDeterminable = true;
    OUT: do {
        String serviceLevelCandidate = getKeyToLongestMap(serviceLevelToProductIdsMap);
        Assert.assertNotNull(serviceLevelCandidate, "If the key to the longest map of serviceLevel to ProductIds is null, then there are probably no subscriptions available.");
        // does this candidate have all candidate products?
        if (serviceLevelToProductIdsMap.get(serviceLevelCandidate).containsAll(allProductsSubscribableByOneCommonServiceLevelCandidates)) {
            // is there another serviceLevel that has all candidate products?
            for (String serviceLevel : serviceLevelToProductIdsMap.keySet()) {
                if (serviceLevel.equals(serviceLevelCandidate))
                    continue;
                if (serviceLevelToProductIdsMap.get(serviceLevel).size() == serviceLevelToProductIdsMap.get(serviceLevelCandidate).size()) {
                    allProductsSubscribableByOneCommonServiceLevelDeterminable = false;
                    break OUT;
                }
            }
            allProductsSubscribableByOneCommonServiceLevelValue = serviceLevelCandidate;
        } else {
            // pluck the first candidate product that is not in the serviceLevelCandidate map of products
            for (String productId : (String[]) allProductsSubscribableByOneCommonServiceLevelCandidates.toArray(new String[] {})) {
                if (!serviceLevelToProductIdsMap.get(serviceLevelCandidate).contains(productId)) {
                    allProductsSubscribableByOneCommonServiceLevelCandidates.remove(productId);
                    for (String serviceLevel : serviceLevelToProductIdsMap.keySet()) {
                        serviceLevelToProductIdsMap.get(serviceLevel).remove(productId);
                    }
                    break;
                }
            }
        }
    } while (allProductsSubscribableByOneCommonServiceLevelValue == null && allProductsSubscribableByOneCommonServiceLevelDeterminable);
    // copy the products to productCertDirForAllProductsSubscribableByOneCommonServiceLevel
    if (allProductsSubscribableByOneCommonServiceLevelDeterminable) {
        // for (ProductCert productCert : clienttasks.getCurrentProductCerts()) {	// TODO not efficient; testing fix on next line
        for (ProductCert productCert : currentProductCerts) {
            if (allProductsSubscribableByOneCommonServiceLevelCandidates.contains(productCert.productId)) {
                RemoteFileTasks.runCommandAndAssert(client, "cp " + productCert.file + " " + productCertDirForAllProductsSubscribableByOneCommonServiceLevel, 0);
            }
        }
    } else {
        log.warning("Cannot determine a set of products where allProductsSubscribableByOneCommonServiceLevel.");
    }
    // determine the serviceLevels and all the products that are subscribable by more than one common service level
    // serviceLevelToProductIdsMap = getServiceLevelToProductIdsMapFromEntitlementCerts(clienttasks.getCurrentEntitlementCerts());	// TODO not efficient; testing fix on next line
    serviceLevelToProductIdsMap = getServiceLevelToProductIdsMapFromEntitlementCerts(currentEntitlementCerts);
    productIdsToServiceLevelsMap = getInvertedMap(serviceLevelToProductIdsMap);
    List<String> allProductsSubscribableByMoreThanOneCommonServiceLevelCandidates = new ArrayList<String>();
    for (String productId : productIdsToServiceLevelsMap.keySet()) {
        if (productIdsToServiceLevelsMap.get(productId).size() > 1)
            allProductsSubscribableByMoreThanOneCommonServiceLevelCandidates.add(productId);
    }
    if (!allProductsSubscribableByMoreThanOneCommonServiceLevelCandidates.isEmpty()) {
        // randomly choose the service levels from the candidates
        // allProductsSubscribableByMoreThanOneCommonServiceLevelValues = Arrays.asList(productIdsToServiceLevelsMap.get(allProductsSubscribableByMoreThanOneCommonServiceLevelCandidates.get(randomGenerator.nextInt(allProductsSubscribableByMoreThanOneCommonServiceLevelCandidates.size()))).toArray(new String[]{}));
        allProductsSubscribableByMoreThanOneCommonServiceLevelValues.addAll(productIdsToServiceLevelsMap.get(allProductsSubscribableByMoreThanOneCommonServiceLevelCandidates.get(randomGenerator.nextInt(allProductsSubscribableByMoreThanOneCommonServiceLevelCandidates.size()))));
        // pluck out the productIds that do not map to all of the values in allProductsSubscribableByMoreThanOneCommonServiceLevelValues
        for (String productId : productIdsToServiceLevelsMap.keySet()) {
            if (!productIdsToServiceLevelsMap.get(productId).containsAll(allProductsSubscribableByMoreThanOneCommonServiceLevelValues)) {
                allProductsSubscribableByMoreThanOneCommonServiceLevelCandidates.remove(productId);
            }
        }
        // for (ProductCert productCert : clienttasks.getCurrentProductCerts()) {	// TODO not efficient; testing fix on next line
        for (ProductCert productCert : currentProductCerts) {
            if (allProductsSubscribableByMoreThanOneCommonServiceLevelCandidates.contains(productCert.productId)) {
                RemoteFileTasks.runCommandAndAssert(client, "cp " + productCert.file + " " + productCertDirForAllProductsSubscribableByMoreThanOneCommonServiceLevel, 0);
            }
        }
    } else {
        log.warning("Cannot determine a set of products where allProductsSubscribableByMoreThanOneCommonServiceLevel.");
    }
    // remember the originally configured productCertDir
    this.originalProductCertDir = clienttasks.productCertDir;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) EntitlementCert(rhsm.data.EntitlementCert) ArrayList(java.util.ArrayList) ProductCert(rhsm.data.ProductCert) InstalledProduct(rhsm.data.InstalledProduct) File(java.io.File) SubscriptionPool(rhsm.data.SubscriptionPool) BeforeClass(org.testng.annotations.BeforeClass)

Example 24 with ProductCert

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

the class ContentIntegrationTests method testInstallAndRemoveUniquePackageFromContentNamespace.

@Test(description = "ensure a unique available package can be installed/removed from the enabled repo ", groups = { "Tier2Tests" }, dependsOnMethods = { "testRegisterAndSubscribe" }, alwaysRun = true, dependsOnGroups = { "VerifyPackagesAreAvailable" }, dataProvider = "getContentNamespaceData", // disabled in favor of various ContentTests which do not depend on the maintenance of dataProvider="getSubscribeData"
enabled = false)
public // @ImplementsNitrateTest(caseId=) //TODO Find a tcms caseId
void testInstallAndRemoveUniquePackageFromContentNamespace(String username, String password, ConsumerType type, String productId, Integer sockets, ContentNamespace contentNamespace) {
    EntitlementCert entitlementCert = recallTheEntitlementCertGrantedAfterSubscribing(username, password, type, productId, sockets);
    // if (!contentNamespace.label.equals("rhel-6-server-beta-debug-rpms")) throw new SkipException("debugging");
    // register
    registerConsumerWhenNotAlreadyRegistered(username, password, type, sockets);
    // subscribe
    if (!currentlySubscribedProductIds.contains(productId)) {
        // try to save some time by not re-subscribing
        clienttasks.subscribeToProductId(productId);
        currentlySubscribedProductIds.add(productId);
    } else {
        log.info("Saving time by assuming that we are already subscribed to productId='" + productId + "'");
    // clienttasks.list_(null,null,null, Boolean.TRUE, null, null, null, null);
    }
    // make sure that the products required for this repo are installed
    /* not needed anymore since this case is already filtered out by the dataProvider
		if (!clienttasks.areAllRequiredTagsInContentNamespaceProvidedByProductCerts(contentNamespace, currentProductCerts)) {
			throw new SkipException("This contentNamespace has requiredTags '"+contentNamespace.requiredTags+"' that were not found amongst all of the currently installed products.  Therefore we cannot install and remove any package from repo '"+contentNamespace.label+"'.");
		}
		*/
    // make sure there is a positive package count provided by this repo
    /* not needed anymore since this case is already filtered out by the dataProvider
		Integer packageCount = clienttasks.getYumRepolistPackageCount(contentNamespace.label+" --enablerepo="+contentNamespace.label);
		if (packageCount==0) {
			throw new SkipException("Cannot install a package from this repo '"+contentNamespace.label+"' since it is not providing any packages.");
		}
		*/
    // find an available package that is uniquely provided by this repo
    String pkg = clienttasks.findUniqueAvailablePackageFromRepo(contentNamespace.label);
    if (pkg == null) {
        throw new SkipException("Could NOT find a unique available package from this repo '" + contentNamespace.label + "' to attempt an install/remove test.");
    }
    // pkg="cairo-spice-debuginfo.x86_64";
    // install the package and assert that it is successfully installed
    // pkgInstalled = true;
    clienttasks.yumInstallPackageFromRepo(pkg, contentNamespace.label, null);
    // 06/09/2011 TODO Would also like to add an assert that the productid.pem file is also installed.
    /* To do this, we need to also include the List of ProductNamepaces from the entitlement cert as another argument to this test,
		 * Then after the yum install, we need to make sure that at least one of the hash values in the list of product ids is
		 * included in the installed products.  If the list of ProductNamespaces from the entitlement cert is one, then this is
		 * a definitive test.  If the list is greater than one, then we don't know for sure if the product hash(s) that is installed is actually the 
		 * right one.  But we do know that if none of the product hashes are installed, then the repo is missing the product ids and this test should fail.
		 * Also note that we should probably make this assertion after removing the package so that we don't over install all the packages in the repo.
		 */
    // 06/10/2011 Mostly Done in the following blocks of code; jsefler
    // determine if at least one of the productids from the productNamespaces was found installed on the client after running yumInstallPackageFromRepo(...)
    // ideally there is only one ProductNamespace in productNamespaces in which case we can definitively know that the correct product cert is installed
    // when there are more than one ProductNamespace in productNamespaces, then we can't say for sure if the product cert installed actually corresponds to the repo under test
    // however if none of the productNamespaces ends up installed, then the yum product-id plugin is not installing the expected product cert
    int numberOfProductNamespacesInstalled = 0;
    ProductCert productCertInstalled = null;
    for (ProductCert productCert : clienttasks.getCurrentProductCerts()) {
        for (ProductNamespace productNamespace : entitlementCert.productNamespaces) {
            if (productNamespace.id.equals(productCert.productId)) {
                numberOfProductNamespacesInstalled++;
                productCertInstalled = productCert;
            }
        }
    }
    // FIXME check if the package was obsolete and its replacement was installed instead
    // if (!obsoletedByPkg.isEmpty()) pkg = obsoletedByPkg;
    // now remove the package
    clienttasks.yumRemovePackage(pkg);
    // Note: I am making this assertion after the yumRemovePackage call to avoid leaving packages installed in case this assert fails.
    if (numberOfProductNamespacesInstalled > 1) {
        log.info("Found product certs installed that match the ProductNamespaces from the entitlement cert that granted the right to install package '" + pkg + "' from repo '" + contentNamespace.label + "'.");
    } else if (numberOfProductNamespacesInstalled == 1) {
        Assert.assertTrue(true, "An installed product cert (productName='" + productCertInstalled.productName + "' productId='" + productCertInstalled.productId + "') corresponding to installed package '" + pkg + "' from repo '" + contentNamespace.label + "' was found after it was installed.");
    } else {
        Assert.fail("After installing package '" + pkg + "' from repo '" + contentNamespace.label + "', there was no product cert installed.  Expected one of the following product certs to get installed via the yum product-id plugin: " + entitlementCert.productNamespaces);
    }
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) ProductCert(rhsm.data.ProductCert) SkipException(org.testng.SkipException) ProductNamespace(rhsm.data.ProductNamespace) Test(org.testng.annotations.Test)

Example 25 with ProductCert

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

the class MigrationTests method InstallNumMigrateToRhsmWithInstNumber.

protected SSHCommandResult InstallNumMigrateToRhsmWithInstNumber(String instNumber) throws JSONException {
    if (!clienttasks.redhatReleaseX.equals("5"))
        throw new SkipException("This test is applicable to RHEL5 only.");
    if (clienttasks.isPackageVersion("subscription-manager-migration", ">", "1.11.3-4") && clienttasks.redhatReleaseX.equals("5")) {
        throw new SkipException("Due to bug 1092754, the migration tool '" + installNumTool + "' has been removed from RHEL5.");
    }
    String command;
    SSHCommandResult result;
    // deleting the currently installed product certs
    clienttasks.removeAllCerts(false, false, true);
    clienttasks.removeAllFacts();
    // get the product cert filenames that we should expect install-num-migrate-to-rhsm to copy
    List<String> expectedMigrationProductCertFilenames = getExpectedMappedProductCertFilenamesCorrespondingToInstnumberUsingInstnumTool(instNumber);
    // test --dryrun --instnumber ................................................
    log.info("Testing with the dryrun option...");
    command = installNumTool + " --dryrun --instnumber=" + instNumber;
    result = RemoteFileTasks.runCommandAndAssert(client, command, 0);
    // assert the dryrun
    for (String expectedMigrationProductCertFilename : expectedMigrationProductCertFilenames) {
        String pemFilename = MigrationDataTests.getPemFileNameFromProductCertFilename(expectedMigrationProductCertFilename);
        // String expectedStdoutString = "Copying "+baseProductsDir+"/"+expectedMigrationProductCertFilename+" to "+clienttasks.productCertDir+"/"+pemFilename;	// valid prior to Bug 853187 - String Update: install-num-migrate-to-rhsm output
        String expectedStdoutString = "Installing " + baseProductsDir + "/" + expectedMigrationProductCertFilename + " to " + clienttasks.productCertDir + "/" + pemFilename;
        Assert.assertTrue(result.getStdout().contains(expectedStdoutString), "The dryrun output from " + installNumTool + " contains the expected message: " + expectedStdoutString);
    }
    int numProductCertFilenamesToBeCopied = 0;
    // for (int fromIndex=0; result.getStdout().indexOf("Copying", fromIndex)>=0&&fromIndex>-1; fromIndex=result.getStdout().indexOf("Copying", fromIndex+1)) numProductCertFilenamesToBeCopied++;	// valid prior to Bug 853187 - String Update: install-num-migrate-to-rhsm output
    for (int fromIndex = 0; result.getStdout().indexOf("Installing", fromIndex) >= 0 && fromIndex > -1; fromIndex = result.getStdout().indexOf("Installing", fromIndex + 1)) numProductCertFilenamesToBeCopied++;
    Assert.assertEquals(numProductCertFilenamesToBeCopied, expectedMigrationProductCertFilenames.size(), "The number of product certs to be copied.");
    Assert.assertEquals(clienttasks.getCurrentlyInstalledProducts().size(), 0, "A dryrun should NOT install any product certs.");
    Map<String, String> factMap = clienttasks.getFacts();
    // Note: this if block help reveal bug 840415 - Install-num migration throws traceback for invalid product cert location.
    if (clienttasks.productCertDir.equals(nonDefaultProductCertDir)) {
        client.runCommandAndWait("rm -rf " + clienttasks.productCertDir);
        Assert.assertTrue(!RemoteFileTasks.testExists(client, clienttasks.productCertDir), "The configured rhsm.productCertDir does not exist.");
    }
    // TEMPORARY WORKAROUND FOR BUG
    String bugId = "783278";
    boolean invokeWorkaroundWhileBugIsOpen = true;
    try {
        if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
        } else {
            invokeWorkaroundWhileBugIsOpen = false;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    String bugPkg = "subscription-manager-migration";
    // RHEL58
    String bugVer = "subscription-manager-migration-0.98";
    try {
        if (clienttasks.installedPackageVersionMap.get(bugPkg).contains(bugVer) && !invokeWorkaroundWhileBugIsOpen) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + " which has NOT been fixed in this installed version of " + bugVer + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
            invokeWorkaroundWhileBugIsOpen = true;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    if (invokeWorkaroundWhileBugIsOpen) {
        log.warning("Skipping the assertion of the fact '" + migrationFromFact + "' fact.");
    } else
        // END OF WORKAROUND
        Assert.assertNull(factMap.get(migrationFromFact), "The migration fact '" + migrationFromFact + "' should NOT be set after running command: " + command);
    Assert.assertNull(factMap.get(migrationSystemIdFact), "The migration fact '" + migrationSystemIdFact + "' should NOT be set after running command: " + command);
    Assert.assertNull(factMap.get(migrationDateFact), "The migration fact '" + migrationDateFact + "' should NOT be set after running command: " + command);
    // test --instnumber ................................................
    log.info("Testing without the dryrun option...");
    command = installNumTool + " --instnumber=" + instNumber;
    result = RemoteFileTasks.runCommandAndAssert(client, command, 0);
    // [root@jsefler-onprem-5server ~]# install-num-migrate-to-rhsm --instnumber 0000000e0017fc01
    // Copying /usr/share/rhsm/product/RHEL-5/Client-Workstation-x86_64-f812997e0eda-71.pem to /etc/pki/product/71.pem
    // Copying /usr/share/rhsm/product/RHEL-5/Client-Client-x86_64-6587edcf1c03-68.pem to /etc/pki/product/68.pem
    List<ProductCert> migratedProductCerts = clienttasks.getCurrentProductCerts();
    Assert.assertEquals(clienttasks.getCurrentlyInstalledProducts().size(), expectedMigrationProductCertFilenames.size(), "The number of productCerts installed after running migration command: " + command);
    for (String expectedMigrationProductCertFilename : expectedMigrationProductCertFilenames) {
        ProductCert expectedMigrationProductCert = clienttasks.getProductCertFromProductCertFile(new File(baseProductsDir + "/" + expectedMigrationProductCertFilename));
        Assert.assertTrue(migratedProductCerts.contains(expectedMigrationProductCert), "The newly installed product certs includes the expected migration productCert: " + expectedMigrationProductCert);
    }
    // [root@jsefler-rhel59 ~]# subscription-manager facts --list | grep migration
    // migration.install_number: 0000000e0017fc01
    // migration.migrated_from: install_number
    // migration.migration_date: 2012-08-08T11:11:15.818782
    factMap = clienttasks.getFacts();
    Assert.assertEquals(factMap.get(migrationFromFact), "install_number", "The migration fact '" + migrationFromFact + "' should be set after running command: " + command);
    Assert.assertNull(factMap.get(migrationSystemIdFact), "The migration fact '" + migrationSystemIdFact + "' should NOT be set after running command: " + command);
    Assert.assertNotNull(factMap.get(migrationDateFact), "The migration fact '" + migrationDateFact + "' should be set after running command: " + command);
    // assert that the migrationDateFact was set within the last few seconds
    // tolerance in seconds
    int tol = 60;
    // NOTE: The .SSS milliseconds was dropped from the date pattern because it was getting confused as seconds from the six digit value in migration.migration_date: 2012-08-08T11:11:15.818782
    Calendar migrationDate = parseDateStringUsingDatePattern(factMap.get(migrationDateFact), "yyyy-MM-dd'T'HH:mm:ss", null);
    // seconds since 1970-01-01 00:00:00 UTC
    long systemTimeInSeconds = Long.valueOf(client.runCommandAndWait("date +%s").getStdout().trim());
    long migratTimeInSeconds = migrationDate.getTimeInMillis() / 1000;
    Assert.assertTrue(systemTimeInSeconds - tol < migratTimeInSeconds && migratTimeInSeconds < systemTimeInSeconds + tol, "The migration date fact '" + factMap.get(migrationDateFact) + "' was set within the last '" + tol + "' seconds.  Actual diff='" + String.valueOf(systemTimeInSeconds - migratTimeInSeconds) + "' seconds.");
    return result;
}
Also used : Calendar(java.util.Calendar) ProductCert(rhsm.data.ProductCert) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SkipException(org.testng.SkipException) File(java.io.File)

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