Search in sources :

Example 51 with BugzillaAPIException

use of com.redhat.qe.auto.bugzilla.BugzillaAPIException in project rhsm-qe by RedHatQE.

the class MigrationTests method testRhnMigrateClassicToRhsm.

// rhn-migrate-classic-to-rhsm 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-20111", "RHEL7-51115" }, 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 = "Register system using RHN Classic and then Execute migration tool rhn-migrate-classic-to-rhsm with options after adding RHN Channels", groups = { "Tier1Tests", "RhnMigrateClassicToRhsm_Test", "blockedByBug-966745", "blockedByBug-840169", "blockedbyBug-878986", "blockedByBug-1052297", "blockedByBug-1111258", "blockedByBug-1512948", "blockedByBug-1516832" }, dependsOnMethods = {}, dataProvider = "RhnMigrateClassicToRhsmData", enabled = true)
public // @ImplementsNitrateTest(caseId=130764,130762) // TODO some expected yum repo assertions are not yet automated
void testRhnMigrateClassicToRhsm(Object bugzilla, String rhnreg_ksUsername, String rhnreg_ksPassword, String rhnHostname, List<String> rhnChannelsToAdd, String options, String rhnUsername, String rhnPassword, String rhsmUsername, String rhsmPassword, String rhsmOrg, Integer serviceLevelIndex, String serviceLevelExpected) throws JSONException {
    if (sm_rhnHostname.equals(""))
        throw new SkipException("This test requires access to RHN Classic or Satellite 5.");
    if (Integer.valueOf(clienttasks.redhatReleaseX) >= 7 && clienttasks.arch.equals("ppc64le"))
        throw new SkipException("Use of rhn-migrate-classic-to-rhsm is not necessary on RHEL '" + client1tasks.redhatReleaseX + "' arch '" + clienttasks.arch + "' since this product was not released on RHN Classic.");
    if (Integer.valueOf(clienttasks.redhatReleaseX) >= 7 && clienttasks.arch.equals("aarch64"))
        throw new SkipException("Use of rhn-migrate-classic-to-rhsm is not necessary on RHEL '" + client1tasks.redhatReleaseX + "' arch '" + clienttasks.arch + "' since this product was not released on RHN Classic.");
    if (false) {
        // TODO maybe this should go after the unregister and removeAll commands
        // make sure our serverUrl is configured to it's original good value
        restoreOriginallyConfiguredServerUrl();
        // make sure we are NOT registered to RHSM
        clienttasks.unregister(null, null, null, null);
        // deleting the currently installed product certs
        clienttasks.removeAllCerts(false, false, true);
        clienttasks.removeAllFacts();
    } else {
        // TODO: 8/12/2013 Attempting the following logic in response to above TODO
        // make sure we are NOT registered to RHSM (and system is clean from prior test) ignoring errors like:
        // ssh root@cloud-qe-9.idm.lab.bos.redhat.com subscription-manager unregister
        // Stdout: Runtime Error Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [org.candlepin.model.Pool#8a99f9823fc4919b013fc49408a302b7] at org.hibernate.persister.entity.AbstractEntityPersister.check:1,782
        // Stderr:
        // ExitCode: 255
        clienttasks.unregister_(null, null, null, null);
        clienttasks.removeAllCerts(true, true, true);
        clienttasks.removeAllFacts();
        restoreOriginallyConfiguredServerUrl();
    }
    // randomly remove a benign rhn classic package (just to add a little unnecessary fun)
    if (randomGenerator.nextBoolean() && clienttasks.isPackageInstalled("osad"))
        clienttasks.yumRemovePackage("osad");
    if (randomGenerator.nextBoolean() && clienttasks.isPackageInstalled("openscap"))
        clienttasks.yumRemovePackage("openscap");
    // register to RHN Classic
    String rhnSystemId = clienttasks.registerToRhnClassic(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname);
    Assert.assertTrue(clienttasks.isRhnSystemIdRegistered(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is currently registered.");
    // subscribe to more RHN Classic channels
    if (rhnChannelsToAdd.size() > 0)
        addRhnClassicChannels(rhnreg_ksUsername, rhnreg_ksPassword, rhnChannelsToAdd);
    // get a list of the consumed RHN Classic channels
    List<String> rhnChannelsConsumed = clienttasks.getCurrentRhnClassicChannels();
    if (rhnChannelsToAdd.size() > 0)
        Assert.assertTrue(rhnChannelsConsumed.containsAll(rhnChannelsToAdd), "All of the RHN Classic channels added appear to be consumed.");
    // get a map of the productid.js file before we attempt migration
    Map<String, List<String>> productIdRepoMapBeforeMigration = clienttasks.getProductIdToReposMap();
    // get the product cert filenames that we should expect rhn-migrate-classic-to-rhsm to copy (or use the ones supplied to the @Test)
    Set<String> expectedMigrationProductCertFilenames = getExpectedMappedProductCertFilenamesCorrespondingToChannels(rhnChannelsConsumed);
    // screw up the currently configured [server]hostname:port/prefix when the command line options specify a new URL
    if (options.contains("--serverurl") || options.contains("--destination-url")) {
        log.info("Configuring a bad server hostname:port/prefix to test that the specified --serverurl can override it...");
        List<String[]> listOfSectionNameValues = new ArrayList<String[]>();
        if (doesStringContainMatches(options, "(--serverurl|--destination-url)=(https://)?[\\w\\.-]+")) {
            // hostname
            listOfSectionNameValues.add(new String[] { "server", "hostname", "bad-hostname.com" });
        }
        if (doesStringContainMatches(options, "(--serverurl|--destination-url)=(https://)?[\\w\\.-]+:\\d+")) {
            // port
            listOfSectionNameValues.add(new String[] { "server", "port", "000" });
        }
        if (doesStringContainMatches(options, "(--serverurl|--destination-url)=(https://)?[\\w\\.-]+(:\\d+)?/\\w+")) {
            // prefix
            listOfSectionNameValues.add(new String[] { "server", "prefix", "/bad-prefix" });
        }
        clienttasks.config(null, null, true, listOfSectionNameValues);
    }
    // execute rhn-migrate-classic-to-rhsm with options
    SSHCommandResult sshCommandResult = executeRhnMigrateClassicToRhsm(options, rhnUsername, rhnPassword, rhsmUsername, rhsmPassword, rhsmOrg, null, serviceLevelIndex);
    // assert valid usage
    if (sshCommandResult.getStdout().contains("Usage: rhn-migrate-classic-to-rhsms")) {
        Assert.fail("Detected a usage error.");
    }
    // get a map of the productid.js file after we attempt migration
    Map<String, List<String>> productIdRepoMapAfterMigration = clienttasks.getProductIdToReposMap();
    // assert the exit code
    checkForKnownBug881952(sshCommandResult);
    checkForKnownBug1130637(sshCommandResult);
    String expectedMsg;
    if (!getProductCertFilenamesContainingNonUniqueProductIds(expectedMigrationProductCertFilenames).isEmpty()) {
        log.warning("The RHN Classic channels currently consumed map to multiple product certs that share the same product ID " + getProductCertFilenamesContainingNonUniqueProductIds(expectedMigrationProductCertFilenames) + ".  We must abort in this case.  Therefore, the " + rhnMigrateTool + " command should have exited with code 1.");
        // TEMPORARY WORKAROUND FOR BUG
        // Bug 1006985 - rhn-migrate-classic-to-rhsm should abort when it encounters RHN channels that map to different products certs that share the same productId
        String bugId = "1006985";
        boolean invokeWorkaroundWhileBugIsOpen = true;
        try {
            if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
                log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
                SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
            } else {
                invokeWorkaroundWhileBugIsOpen = false;
            }
        } catch (BugzillaAPIException be) {
        /* ignore exception */
        } catch (RuntimeException re) {
        /* ignore exception */
        }
        if (invokeWorkaroundWhileBugIsOpen) {
            throw new SkipException("The remainder of this test is blocked by bug " + bugId + ".  There is no workaround.");
        }
        // END OF WORKAROUND
        // +-----------------------------------------------------+
        // Unable to continue migration!
        // +-----------------------------------------------------+
        // You are subscribed to channels that have conflicting product certificates.
        // The following channels map to product ID 69:
        // rhel-x86_64-rhev-agent-6-server
        // rhel-x86_64-rhev-agent-6-server-beta
        // rhel-x86_64-rhev-agent-6-server-beta-debuginfo
        // rhel-x86_64-rhev-agent-6-server-debuginfo
        // rhel-x86_64-server-6
        // rhel-x86_64-server-6-cf-tools-1
        // rhel-x86_64-server-6-cf-tools-1-beta
        // rhel-x86_64-server-6-cf-tools-1-beta-debuginfo
        // rhel-x86_64-server-6-cf-tools-1-debuginfo
        // Reduce the number of channels per product ID to 1 and run migration again.
        // To remove a channel, use 'rhn-channel --remove --channel=<conflicting_channel>'.
        // TODO Improve the expectedMsg to better assert the list of conflicting channels
        expectedMsg = "Unable to continue migration!";
        Assert.assertTrue(sshCommandResult.getStdout().contains(expectedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + expectedMsg);
        Assert.assertEquals(sshCommandResult.getExitCode(), new Integer(1), "ExitCode from call to '" + rhnMigrateTool + " " + options + "' when currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
        Assert.assertTrue(clienttasks.isRhnSystemRegistered(), "This system is still registered using RHN Classic when currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
        // assert that no product certs have been copied yet
        // OLD		Assert.assertEquals(clienttasks.getCurrentlyInstalledProducts().size(), 0, "No productCerts have been migrated when "+rhnMigrateTool+" aborts because the currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
        Assert.assertEquals(clienttasks.getProductCerts(clienttasks.productCertDir).size(), 0, "No productCerts have been migrated when " + rhnMigrateTool + " aborts because the currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
        // assert that we are not yet registered to RHSM
        Assert.assertNull(clienttasks.getCurrentConsumerCert(), "We should NOT be registered to RHSM when " + rhnMigrateTool + " aborts because the currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
        // assert that we are still registered to RHN
        Assert.assertTrue(clienttasks.isRhnSystemIdRegistered(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is still registered since our migration attempt aborts because the currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
        // assert that the rhnplugin is still enabled
        Assert.assertEquals(clienttasks.getConfFileParameter(clienttasks.yumPluginConfFileForRhn, "enabled"), "1", "The enabled yum plugin configuration for RHN.");
        // assert that productid.js is unchanged
        Assert.assertTrue(productIdRepoMapBeforeMigration.keySet().containsAll(productIdRepoMapAfterMigration.keySet()) && productIdRepoMapAfterMigration.keySet().containsAll(productIdRepoMapBeforeMigration.keySet()), "The '" + clienttasks.productIdJsonFile + "' productIds remain unchanged when " + rhnMigrateTool + " aborts because the currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
        for (String productId : productIdRepoMapBeforeMigration.keySet()) {
            Assert.assertTrue(productIdRepoMapBeforeMigration.get(productId).containsAll(productIdRepoMapAfterMigration.get(productId)) && productIdRepoMapAfterMigration.get(productId).containsAll(productIdRepoMapBeforeMigration.get(productId)), "The '" + clienttasks.productIdJsonFile + "' productIds repos for '" + productId + "' remain unchanged when " + rhnMigrateTool + " aborts because the currently consumed RHN Classic channels map to multiple productCerts sharing the same productId.");
        }
        return;
    } else if (!areAllChannelsMapped(rhnChannelsConsumed) && !options.contains("-f")) /*--force*/
    {
        // when not all of the rhnChannelsConsumed have been mapped to a productCert and no --force has been specified.
        log.warning("Not all of the channels are mapped to a product cert.  Therefore, the " + rhnMigrateTool + " command should have exited with code 1.");
        expectedMsg = "Use --force to ignore these channels and continue the migration.";
        Assert.assertTrue(sshCommandResult.getStdout().contains(expectedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + expectedMsg);
        Assert.assertEquals(sshCommandResult.getExitCode(), new Integer(1), "ExitCode from call to '" + rhnMigrateTool + " " + options + "' when any of the channels are not mapped to a productCert.");
        Assert.assertTrue(clienttasks.isRhnSystemRegistered(), "This system is still registered using RHN Classic when rhn-migrate-classic-to-rhsm requires --force to continue.");
        // assert that no product certs have been copied yet
        Assert.assertEquals(clienttasks.getCurrentlyInstalledProducts().size(), 0, "No productCerts have been migrated when " + rhnMigrateTool + " requires --force to continue.");
        // assert that we are not yet registered to RHSM
        Assert.assertNull(clienttasks.getCurrentConsumerCert(), "We should NOT be registered to RHSM when " + rhnMigrateTool + " requires --force to continue.");
        // assert that we are still registered to RHN
        Assert.assertTrue(clienttasks.isRhnSystemIdRegistered(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is still registered since our migration attempt requires --force to continue.");
        // assert that the rhnplugin is still enabled
        Assert.assertEquals(clienttasks.getConfFileParameter(clienttasks.yumPluginConfFileForRhn, "enabled"), "1", "The enabled yum plugin configuration for RHN.");
        // assert that productid.js is unchanged
        Assert.assertTrue(productIdRepoMapBeforeMigration.keySet().containsAll(productIdRepoMapAfterMigration.keySet()) && productIdRepoMapAfterMigration.keySet().containsAll(productIdRepoMapBeforeMigration.keySet()), "The '" + clienttasks.productIdJsonFile + "' productIds remain unchanged when " + rhnMigrateTool + " requires --force to continue.");
        for (String productId : productIdRepoMapBeforeMigration.keySet()) {
            Assert.assertTrue(productIdRepoMapBeforeMigration.get(productId).containsAll(productIdRepoMapAfterMigration.get(productId)) && productIdRepoMapAfterMigration.get(productId).containsAll(productIdRepoMapBeforeMigration.get(productId)), "The '" + clienttasks.productIdJsonFile + "' productIds repos for '" + productId + "' remain unchanged when " + rhnMigrateTool + " requires --force to continue.");
        }
        return;
    } else if (rhnChannelsConsumed.isEmpty()) {
        log.warning("Modifying expected results when the current RHN Classically registered system is not consuming any RHN channels.");
        String expectedStdout = "Problem encountered getting the list of subscribed channels.  Exiting.";
        // changed by commit c0f8052ec2b5b7b5c736eb626e381aef0e5327e5
        if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.13.1"))
            expectedStdout = "Problem encountered getting the list of subscribed channels.  See /var/log/rhsm/rhsm.log for more details.";
        Assert.assertTrue(sshCommandResult.getStdout().trim().endsWith(expectedStdout), "The expected stdout result from call to '" + rhnMigrateTool + "' when no RHN Classic channels are being consumed: " + expectedStdout);
        // Assert.assertEquals(sshCommandResult.getExitCode(), new Integer(1), "The expected exit code from call to '"+rhnMigrateTool+"' when no RHN Classic channels are being consumed.");		// the exitCode can be altered by the expect script rhn-migrate-classic-to-rhsm.tcl when the final arg slaIndex is non-null; therefore don't bother asserting exitCode; asserting stdout is sufficient
        Assert.assertTrue(clienttasks.isRhnSystemIdRegistered(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is still registered after '" + rhnMigrateTool + "' exits due to: " + expectedStdout);
        // assert that productid.js is unchanged
        Assert.assertTrue(productIdRepoMapBeforeMigration.keySet().containsAll(productIdRepoMapAfterMigration.keySet()) && productIdRepoMapAfterMigration.keySet().containsAll(productIdRepoMapBeforeMigration.keySet()), "The '" + clienttasks.productIdJsonFile + "' productIds remain unchanged when " + rhnMigrateTool + " exits due to: " + expectedStdout);
        for (String productId : productIdRepoMapBeforeMigration.keySet()) {
            Assert.assertTrue(productIdRepoMapBeforeMigration.get(productId).containsAll(productIdRepoMapAfterMigration.get(productId)) && productIdRepoMapAfterMigration.get(productId).containsAll(productIdRepoMapBeforeMigration.get(productId)), "The '" + clienttasks.productIdJsonFile + "' productIds repos for '" + productId + "' remain unchanged when " + rhnMigrateTool + " exits due to: " + expectedStdout);
        }
        return;
    }
    Assert.assertEquals(sshCommandResult.getExitCode(), new Integer(0), "ExitCode from call to '" + rhnMigrateTool + " " + options + "' when all of the channels are mapped.");
    // assert product certificates are copied
    expectedMsg = String.format("Product certificates copied successfully to %s !", clienttasks.productCertDir);
    expectedMsg = String.format("Product certificates copied successfully to %s", clienttasks.productCertDir);
    // Bug 852107 - String Update: rhn-migrate-classic-to-rhsm output
    expectedMsg = String.format("Product certificates installed successfully to %s.", clienttasks.productCertDir);
    Assert.assertTrue(sshCommandResult.getStdout().contains(expectedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + expectedMsg);
    // assert that the expected product certs mapped from the consumed RHN Classic channels are now installed
    // OLD	List<ProductCert> migratedProductCerts = clienttasks.getCurrentProductCerts();
    // OLD	Assert.assertEquals(clienttasks.getCurrentlyInstalledProducts().size(), expectedMigrationProductCertFilenames.size(), "The number of productCerts installed after running "+rhnMigrateTool+" with "+options+".  (If this fails, one of these migration certs may have clobbered the other "+expectedMigrationProductCertFilenames+")");
    List<ProductCert> migratedProductCerts = clienttasks.getProductCerts(clienttasks.productCertDir);
    Assert.assertEquals(migratedProductCerts.size(), expectedMigrationProductCertFilenames.size(), "The number of productCerts in '" + clienttasks.productCertDir + "' after running " + rhnMigrateTool + " with options '" + options + "'.  (If this fails, one of these migration certs may have clobbered the other " + expectedMigrationProductCertFilenames + ")");
    for (String expectedMigrationProductCertFilename : expectedMigrationProductCertFilenames) {
        ProductCert expectedMigrationProductCert = clienttasks.getProductCertFromProductCertFile(new File(baseProductsDir + "/" + expectedMigrationProductCertFilename));
        Assert.assertTrue(migratedProductCerts.contains(expectedMigrationProductCert), "The newly migrated product certs in '" + clienttasks.productCertDir + "' includes the expected migration productCert: " + expectedMigrationProductCert);
    }
    // assert the expected migration.* facts are set
    // [root@ibm-x3620m3-01 ~]# subscription-manager facts --list | grep migration
    Map<String, String> factMap = clienttasks.getFacts();
    if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.13")) {
        // migration.classic_system_id: 1000021964
        // migration.migrated_from: https://sat-56-server.usersys.redhat.com/XMLRPC
        // migration.migration_date: 2015-02-07T18:42:18.744943
        // migration.classic_system_id: 1033298347
        // migration.migrated_from: https://xmlrpc.rhn.code.stage.redhat.com/XMLRPC
        // migration.migration_date: 2015-02-24T19:52:14.685785
        String expectedMigrationFromFact = rhnHostname + "/XMLRPC";
        if (!expectedMigrationFromFact.startsWith("http"))
            expectedMigrationFromFact = "https://xmlrpc." + expectedMigrationFromFact;
        Assert.assertEquals(factMap.get(migrationFromFact), expectedMigrationFromFact, "The migration fact '" + migrationFromFact + "' should be set after running " + rhnMigrateTool + " with " + options + ".");
    } else {
        // migration.classic_system_id: 1023061526
        // migration.migrated_from: rhn_hosted_classic
        // migration.migration_date: 2012-07-13T18:51:44.254543
        Assert.assertEquals(factMap.get(migrationFromFact), "rhn_hosted_classic", "The migration fact '" + migrationFromFact + "' should be set after running " + rhnMigrateTool + " with " + options + ".");
    }
    Assert.assertEquals(factMap.get(migrationSystemIdFact), rhnSystemId, "The migration fact '" + migrationSystemIdFact + "' should be set after running " + rhnMigrateTool + " with " + options + ".");
    Assert.assertNotNull(factMap.get(migrationDateFact), "The migration fact '" + migrationDateFact + "' should be set after running " + rhnMigrateTool + " with " + options + ".");
    // tolerance in seconds to assert that the migration_date facts was set within the last few seconds
    int tol = 300;
    Calendar migrationDate;
    /* 10-23-2015 DELETEME AFTER PROVING THAT migrationDateFactWithGMTOffsetTimeZone WORKS
//		if (client.runCommandAndWait("date +%Z").getStdout().trim().endsWith("DT")) {	// are we currently on daylight summer/savings time?
//			// determined on Mar 9, 2015 (day after Daylight Summer/Savings Time starts), when date +%Z returns EDT, passing passing null for timeZone will correctly pass the migrationDateFact assertion (Note: passing "EDT" will actually screw it up)
//			migrationDate = parseDateStringUsingDatePattern(factMap.get(migrationDateFact), "yyyy-MM-dd'T'HH:mm:ss", null);	// 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
//		} else {
//			migrationDate = parseDateStringUsingDatePattern(factMap.get(migrationDateFact), "yyyy-MM-dd'T'HH:mm:ss", client.runCommandAndWait("date +%Z").getStdout().trim());	// 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
//		}
*/
    // the time zone is absent from the value of the migration.migration_date fact (arguably an RFE bug), let's append the GMTOffsetTimeZone of the client
    // [root@ibm-hs22-04 ~]# subscription-manager facts | grep migration_date
    // migration.migration_date: 2015-10-24T00:01:54.040880
    // [root@ibm-hs22-04 ~]# date -d "2015-10-24T00:01:54.040880" -Iseconds
    // 2015-10-24T00:01:54+0200
    // [root@ibm-hs22-04 ~]# date +%Z
    // CEST
    String migrationDateFactWithGMTOffsetTimeZone = client.runCommandAndWait("date -d \"" + factMap.get(migrationDateFact) + "\" -Iseconds").getStdout().trim();
    String systemTimeZone = client.runCommandAndWait("date +%Z").getStdout().trim();
    String systemTimeZoneHHMM = client.runCommandAndWait("date +%:z").getStdout().trim();
    migrationDate = parseDateStringUsingDatePattern(migrationDateFactWithGMTOffsetTimeZone, "yyyy-MM-dd'T'HH:mm:ssZ", systemTimeZone);
    // seconds since 1970-01-01 00:00:00 UTC (will be the same value no matter what TimeZone the system is in
    long systemTimeInSeconds = Long.valueOf(client.runCommandAndWait("date +%s").getStdout().trim());
    long migratTimeInSeconds = migrationDate.getTimeInMillis() / 1000;
    // workaround on RHEL5 and RHEL6 for coreutils bug
    if (Integer.valueOf(clienttasks.redhatReleaseX) < 7) {
        // bump up the time in seconds by taking 7 hours and subtracting the time zone HH:MM offset)  TODO: determine if this formula works during daylight savings time.
        migratTimeInSeconds += 7 * /*hours*/
        60 * 60 - (Integer.parseInt(systemTimeZoneHHMM.split(":")[0]) * /*hours*/
        60 * 60 + Integer.parseInt(systemTimeZoneHHMM.split(":")[1]) * /*minutes*/
        60);
    }
    Assert.assertTrue(systemTimeInSeconds - tol < migratTimeInSeconds && migratTimeInSeconds < systemTimeInSeconds + tol, "The migration date fact '" + factMap.get(migrationDateFact) + "' was set within the last '" + tol + "' seconds (local system time).  Actual diff='" + String.valueOf(systemTimeInSeconds - migratTimeInSeconds) + "' seconds.");
    // assert we are no longer registered to RHN Classic
    // Two possible results can occur when the rhn-migrate-classic-to-rhsm script attempts to unregister from RHN Classic.  We need to tolerate both cases...
    String successfulUnregisterMsg = "System successfully unregistered from RHN Classic.";
    if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.13"))
        successfulUnregisterMsg = "System successfully unregistered from legacy server.";
    String unsuccessfulUnregisterMsg = "Did not receive a completed unregistration message from RHN Classic for system " + rhnSystemId + "." + "\n" + "Please investigate on the Customer Portal at https://access.redhat.com.";
    if (sshCommandResult.getStdout().contains(successfulUnregisterMsg)) {
        // Case 1: number of subscribed channels is low and all communication completes in a timely fashion.  Here is a snippet from stdout:
        // Preparing to unregister system from RHN Classic ...
        // System successfully unregistered from RHN Classic.
        Assert.assertTrue(sshCommandResult.getStdout().contains(successfulUnregisterMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + successfulUnregisterMsg);
        Assert.assertTrue(!sshCommandResult.getStdout().contains(unsuccessfulUnregisterMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' does NOT contain message: " + unsuccessfulUnregisterMsg);
        Assert.assertTrue(!clienttasks.isRhnSystemRegistered(), "This system is NOT registered using RHN Classic. Therefore this system will no longer communicate with RHN Classic.");
        Assert.assertTrue(!clienttasks.isRhnSystemIdRegistered(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is no longer registered on the RHN Classic server.");
    } else {
        // Case 2: number of subscribed channels is high and communication fails in a timely fashion (see bug 881952).  Here is a snippet from stdout:
        // Preparing to unregister system from RHN Classic ...
        // Did not receive a completed unregistration message from RHN Classic for system 1023722557.
        // Please investigate on the Customer Portal at https://access.redhat.com.
        log.warning("Did not detect expected message '" + successfulUnregisterMsg + "' from " + rhnMigrateTool + " stdout.  Nevertheless, the tool should inform us and continue the migration process.");
        Assert.assertTrue(sshCommandResult.getStdout().contains(unsuccessfulUnregisterMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + unsuccessfulUnregisterMsg);
        Assert.assertTrue(!clienttasks.isRhnSystemRegistered(), "This system is NOT registered using RHN Classic. Therefore this system will no longer communicate with RHN Classic.");
        if (!clienttasks.isRhnSystemIdRegistered(rhnreg_ksUsername, rhnreg_ksPassword, rhnHostname, rhnSystemId)) {
            Assert.assertFalse(false, "Confirmed that rhn systemId '" + rhnSystemId + "' is no longer registered on the RHN Classic server.");
        } else {
            log.warning("The RHN Classic server believes that this system is still registered.  SystemId '" + rhnSystemId + "' should be manually deleted on the Customer Portal.");
        }
    }
    // assert that the legacy services have been stopped (introduced by RFE Bug 1185914
    // Product certificates installed successfully to /etc/pki/product.
    // 
    // Preparing to unregister system from legacy server...
    // System successfully unregistered from legacy server.
    // Stopping and disabling legacy services...
    // osad: unrecognized service
    // osad: unrecognized service
    // TEMPORARY WORKAROUND FOR BUG
    // Bug 1390341 - rhn-migrate-classic-to-rhsm is failing to stop and disable services
    String bugId1 = "1390341";
    // Bug 1432231 - rhn-migrate-classic-to-rhsm is failing to stop and disable services
    String bugId2 = "1432231";
    boolean invokeWorkaroundWhileBug1IsOpen = true;
    boolean invokeWorkaroundWhileBug2IsOpen = true;
    try {
        if (BzChecker.getInstance().isBugOpen(bugId1)) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId1).toString() + " Bugzilla " + bugId1 + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId1 + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId1);
        } else {
            invokeWorkaroundWhileBug1IsOpen = false;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    try {
        if (BzChecker.getInstance().isBugOpen(bugId2)) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId2).toString() + " Bugzilla " + bugId2 + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId2 + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId2);
        } else {
            invokeWorkaroundWhileBug2IsOpen = false;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    if (invokeWorkaroundWhileBug1IsOpen || invokeWorkaroundWhileBug2IsOpen) {
        log.warning("Skipping assertion of stopped and disabled services while bug '" + bugId1 + "' OR '" + bugId2 + "' is open.");
        ;
    } else // END OF WORKAROUND
    if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.18.2-1")) {
        String stoppingServicesMsg = "Stopping and disabling legacy services...";
        Assert.assertTrue(sshCommandResult.getStdout().contains(stoppingServicesMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + stoppingServicesMsg);
        // taken from https://bugzilla.redhat.com/show_bug.cgi?id=1185914#c0
        if (clienttasks.isPackageInstalled("osad")) {
            if (Integer.valueOf(clienttasks.redhatReleaseX) >= 7) {
                // [root@jsefler-rhel7 ~]# systemctl is-enabled osad.service
                // osad.service is not a native service, redirecting to /sbin/chkconfig.
                // Executing /sbin/chkconfig osad --level=5
                // disabled
                // [root@jsefler-rhel7 ~]# echo $?
                // 1
                SSHCommandResult sshSystemctlIsEnabledCommandResult = client.runCommandAndWait("systemctl is-enabled osad.service");
                Assert.assertEquals(sshSystemctlIsEnabledCommandResult.getStdout().trim(), "disabled", "Expected stdout for systemctl is-enabled osad.service");
                Assert.assertEquals(sshSystemctlIsEnabledCommandResult.getExitCode(), Integer.valueOf(1), "Expected exitCode for systemctl is-enabled osad.service");
                // [root@jsefler-rhel7 ~]# systemctl is-active osad.service
                // unknown
                // [root@jsefler-rhel7 ~]# echo $?
                // 3
                SSHCommandResult sshSystemctlIsActiveCommandResult = client.runCommandAndWait("systemctl is-active osad.service");
                Assert.assertEquals(sshSystemctlIsActiveCommandResult.getStdout().trim(), "unknown", "Expected stdout for systemctl is-active osad.service");
                Assert.assertEquals(sshSystemctlIsActiveCommandResult.getExitCode(), Integer.valueOf(3), "Expected exitCode for systemctl is-active osad.service");
            } else {
                // [root@jsefler-rhel6 ~]# service osad status
                // osad is stopped
                // [root@jsefler-rhel6 ~]# echo $?
                // 3
                SSHCommandResult sshServiceCommandResult = client.runCommandAndWait("service osad status");
                Assert.assertEquals(sshServiceCommandResult.getExitCode(), Integer.valueOf(3), "Expected exitCode for service osad status");
                Assert.assertEquals(sshServiceCommandResult.getStdout().trim(), "osad is stopped", "Expected stdout for service osad status");
                // [root@jsefler-rhel6 ~]# chkconfig --list osad
                // osad           	0:off	1:off	2:off	3:off	4:off	5:off	6:off
                SSHCommandResult sshChkconfigCommandResult = client.runCommandAndWait("chkconfig --list osad");
                Assert.assertEquals(sshChkconfigCommandResult.getExitCode(), Integer.valueOf(0), "Expected exitCode for chkconfig --list osad");
                String sshChkconfigRegex = "osad\\s+0:off\\s+1:off\\s+2:off\\s+3:off\\s+4:off\\s+5:off\\s+6:off";
                Assert.assertTrue(sshChkconfigCommandResult.getStdout().trim().matches(sshChkconfigRegex), "Expected stdout for chkconfig --list osad to match regex '" + sshChkconfigRegex + "'.");
            }
        }
        if (clienttasks.isPackageInstalled("rhnsd")) {
            if (Integer.valueOf(clienttasks.redhatReleaseX) >= 7) {
                // [root@jsefler-rhel7 ~]# systemctl is-enabled rhnsd.service
                // rhnsd.service is not a native service, redirecting to /sbin/chkconfig.
                // Executing /sbin/chkconfig rhnsd --level=5
                // disabled
                // [root@jsefler-rhel7 ~]# echo $?
                // 1
                SSHCommandResult sshSystemctlIsEnabledCommandResult = client.runCommandAndWait("systemctl is-enabled rhnsd.service");
                Assert.assertEquals(sshSystemctlIsEnabledCommandResult.getStdout().trim(), "disabled", "Expected stdout for systemctl is-enabled rhnsd.service");
                Assert.assertEquals(sshSystemctlIsEnabledCommandResult.getExitCode(), Integer.valueOf(1), "Expected exitCode for systemctl is-enabled rhnsd.service");
                // [root@jsefler-rhel7 ~]# chkconfig --list rhnsd
                // 
                // Note: This output shows SysV services only and does not include native
                // systemd services. SysV configuration data might be overridden by native
                // systemd configuration.
                // 
                // If you want to list systemd services use 'systemctl list-unit-files'.
                // To see services enabled on particular target use
                // 'systemctl list-dependencies [target]'.
                // 
                // rhnsd          	0:off	1:off	2:off	3:off	4:off	5:off	6:off
                SSHCommandResult sshChkconfigCommandResult = client.runCommandAndWait("chkconfig --list rhnsd");
                Assert.assertEquals(sshChkconfigCommandResult.getExitCode(), Integer.valueOf(0), "Expected exitCode for chkconfig --list rhnsd");
                String sshChkconfigRegex = "rhnsd\\s+0:off\\s+1:off\\s+2:off\\s+3:off\\s+4:off\\s+5:off\\s+6:off";
                Assert.assertTrue(sshChkconfigCommandResult.getStdout().trim().matches(sshChkconfigRegex), "Expected stdout for chkconfig --list rhnsd to match regex '" + sshChkconfigRegex + "'.");
                // [root@jsefler-rhel7 ~]# systemctl is-active rhnsd.service
                // unknown
                // [root@jsefler-rhel7 ~]# echo $?
                // 3
                SSHCommandResult sshSystemctlIsActiveCommandResult = client.runCommandAndWait("systemctl is-active rhnsd.service");
                Assert.assertEquals(sshSystemctlIsActiveCommandResult.getStdout().trim(), "unknown", "Expected stdout for systemctl is-active rhnsd.service");
                Assert.assertEquals(sshSystemctlIsActiveCommandResult.getExitCode(), Integer.valueOf(3), "Expected exitCode for systemctl is-active rhnsd.service");
            } else {
                // [root@jsefler-rhel6 ~]# service rhnsd status
                // [root@jsefler-rhel6 ~]# echo $?
                // 6
                SSHCommandResult sshServiceCommandResult = client.runCommandAndWait("service rhnsd status");
                Assert.assertEquals(sshServiceCommandResult.getExitCode(), Integer.valueOf(6), "Expected exitCode for service rhnsd status - because /etc/init.d/rhnsd is programmed to exit 6 when there is no systemid file");
                Assert.assertEquals(sshServiceCommandResult.getStdout().trim(), "", "Expected stdout for service rhnsd status");
                // [root@jsefler-rhel6 ~]# chkconfig --list rhnsd
                // rhnsd           	0:off	1:off	2:off	3:off	4:off	5:off	6:off
                SSHCommandResult sshChkconfigCommandResult = client.runCommandAndWait("chkconfig --list rhnsd");
                Assert.assertEquals(sshChkconfigCommandResult.getExitCode(), Integer.valueOf(0), "Expected exitCode for chkconfig --list rhnsd");
                String sshChkconfigRegex = "rhnsd\\s+0:off\\s+1:off\\s+2:off\\s+3:off\\s+4:off\\s+5:off\\s+6:off";
                Assert.assertTrue(sshChkconfigCommandResult.getStdout().trim().matches(sshChkconfigRegex), "Expected stdout for chkconfig --list rhnsd to match regex '" + sshChkconfigRegex + "'.");
            }
        }
        // assert that no FAILED nor Usage errors occurred
        // Bug 1390341 - rhn-migrate-classic-to-rhsm is failing to stop and disable services
        Assert.assertTrue(!sshCommandResult.getStdout().contains("FAILED"), "Should not encounter a FAILED message when Stopping and disabling legacy services");
        // Bug 1390341 - rhn-migrate-classic-to-rhsm is failing to stop and disable services
        Assert.assertTrue(!sshCommandResult.getStdout().contains("Usage"), "Should not encounter a Usage error when Stopping and disabling legacy services");
    }
    String removingPackagesMsg = "Removing legacy packages...";
    if (options.contains("--remove-rhn-packages")) {
        Assert.assertTrue(sshCommandResult.getStdout().contains(removingPackagesMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + removingPackagesMsg);
    } else {
        Assert.assertTrue(!sshCommandResult.getStdout().contains(removingPackagesMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' does not contain message: " + removingPackagesMsg);
    }
    // assert that when --serverurl is specified, its hostname:port/prefix are preserved into rhsm.conf
    if (options.contains("--serverurl") || options.contains("--destination-url")) {
        // comparing to original configuration values because these are the ones I am using in the dataProvider
        Assert.assertEquals(clienttasks.getConfFileParameter(clienttasks.rhsmConfFile, "server", "hostname"), originalServerHostname, "The value of the [server]hostname newly configured in " + clienttasks.rhsmConfFile + " was extracted from the --serverurl option specified in rhn-migrated-classic-to-rhsm options '" + options + "'.");
        Assert.assertEquals(clienttasks.getConfFileParameter(clienttasks.rhsmConfFile, "server", "port"), originalServerPort, "The value of the [server]port newly configured in " + clienttasks.rhsmConfFile + " was extracted from the --serverurl option specified in rhn-migrated-classic-to-rhsm options '" + options + "'.");
        Assert.assertEquals(clienttasks.getConfFileParameter(clienttasks.rhsmConfFile, "server", "prefix"), originalServerPrefix, "The value of the [server]prefix newly configured in " + clienttasks.rhsmConfFile + " was extracted from the --serverurl option specified in rhn-migrated-classic-to-rhsm options '" + options + "'.");
    }
    // assert that we are newly registered using rhsm
    clienttasks.identity(null, null, null, null, null, null, null, null);
    Assert.assertNotNull(clienttasks.getCurrentConsumerId(), "The existance of a consumer cert indicates that the system is currently registered using RHSM.");
    expectedMsg = String.format("System '%s' successfully registered to Red Hat Subscription Management.", clienttasks.hostname);
    // changed by commit fad3de89
    if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.13.1"))
        expectedMsg = String.format("System '%s' successfully registered.", clienttasks.hostname);
    // TEMPORARY WORKAROUND FOR BUG
    // Bug 1451003 - subscription-manager identity reports redundant UUID info in the name field
    String bugId = "1451003";
    boolean invokeWorkaroundWhileBugIsOpen = true;
    try {
        if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
        } else {
            invokeWorkaroundWhileBugIsOpen = false;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    if (invokeWorkaroundWhileBugIsOpen) {
        log.warning("Skipping assertion that Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + expectedMsg);
    } else
        // END OF WORKAROUND
        Assert.assertTrue(sshCommandResult.getStdout().contains(expectedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + expectedMsg);
    // assert the the expected service level was set as a preference on the registered consumer
    if (serviceLevelExpected != null) {
        String serviceLevel = clienttasks.getCurrentServiceLevel();
        Assert.assertTrue(serviceLevelExpected.equalsIgnoreCase(serviceLevel), "Regardless of case, the serviceLevel requested during migration (or possibly the org's defaultServiceLevel) was set as the system's service level preference (serviceLevelExpected='" + serviceLevelExpected + "').");
    }
    // assert that when --no-auto is specified, no entitlements were granted during the rhsm registration
    String autosubscribeAttemptedMsg = "Attempting to auto-subscribe to appropriate subscriptions ...";
    // changed by bug 876294
    autosubscribeAttemptedMsg = "Attempting to auto-attach to appropriate subscriptions ...";
    // changed by subscription-manager commit 1fba5696
    autosubscribeAttemptedMsg = "Attempting to auto-attach to appropriate subscriptions...";
    // commit fad3de89779f2217e788b3564ef5dca7f85914fb removed the "Attempting to auto-attach to appropriate subscriptions..." feedback
    if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.13.1"))
        autosubscribeAttemptedMsg = "Installed Product Current Status:";
    String autosubscribeFailedMsg = "Unable to auto-subscribe.  Do your existing subscriptions match the products installed on this system?";
    // changed by bug 876294
    autosubscribeFailedMsg = "Unable to auto-attach.  Do your existing subscriptions match the products installed on this system?";
    // commit fad3de89779f2217e788b3564ef5dca7f85914fb	// matches functionality from bug 864195
    if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.13.1"))
        autosubscribeFailedMsg = "Unable to find available subscriptions for all your installed products.";
    // OLD	if (options.contains("-n")) { // -n, --no-auto   Do not autosubscribe when registering with subscription-manager
    if (options.contains("-n") && !options.contains("--activation-key")) {
        // -n, --no-auto   Do not autosubscribe when registering with subscription-manager
        // assert that autosubscribe was NOT attempted
        Assert.assertTrue(!sshCommandResult.getStdout().contains(autosubscribeAttemptedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' does NOT contain message: " + autosubscribeAttemptedMsg);
        Assert.assertTrue(!sshCommandResult.getStdout().contains(autosubscribeFailedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' does NOT contain message: " + autosubscribeFailedMsg);
        // assert that we are NOT registered using rhsm
        /* THIS ASSERTION IS WRONG! DON'T DO IT!  BUG 849644
			clienttasks.identity_(null, null, null, null, null, null, null);
			Assert.assertNull(clienttasks.getCurrentConsumerCert(),"We should NOT be registered to RHSM after a call to "+rhnMigrateTool+" with options "+options+".");
			*/
        // assert that we are NOT consuming any entitlements
        Assert.assertTrue(clienttasks.getCurrentlyConsumedProductSubscriptions().isEmpty(), "We should NOT be consuming any RHSM entitlements after call to " + rhnMigrateTool + " with options (" + options + ") that indicate no autosubscribe.");
    // OLD	} else {
    }
    if (!options.contains("-n") && !options.contains("--activation-key")) {
        // assert that autosubscribe was attempted
        Assert.assertTrue(sshCommandResult.getStdout().contains(autosubscribeAttemptedMsg), "Stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + autosubscribeAttemptedMsg);
        // assert that the migrated productCert corresponding to the base channel has been autosubscribed by checking the status on the installedProduct
        // FIXME This assertion is wrong when there are no available subscriptions that provide for the migrated product certs' providesTags; however since we register as qa@redhat.com, I think we have access to all base rhel subscriptions
        // FIXME if a service-level is provided that is not available, then this product may NOT be subscribed
        /* DECIDED NOT TO FIXME SINCE THIS ASSERTION IS THE JOB OF DEDICATED AUTOSUBSCRIBE TESTS IN SubscribeTests.java
			InstalledProduct installedProduct = clienttasks.getInstalledProductCorrespondingToProductCert(clienttasks.getProductCertFromProductCertFile(new File(clienttasks.productCertDir+"/"+getPemFileNameFromProductCertFilename(channelsToProductCertFilenamesMap.get(rhnBaseChannel)))));
			Assert.assertEquals(installedProduct.status, "Subscribed","The migrated product cert corresponding to the RHN Classic base channel '"+rhnBaseChannel+"' was autosubscribed: "+installedProduct);
			*/
        // assert that autosubscribe feedback was a success (or not)
        List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
        if (consumedProductSubscriptions.isEmpty()) {
            Assert.assertTrue(sshCommandResult.getStdout().contains(autosubscribeFailedMsg), "Assuming the base RHN channel has been migrated, but no entitlements have been granted, stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + autosubscribeFailedMsg);
        }
        /*else { // 06/15/2015: This else block is wrong since an RHN Channel could have been successfully migrated, but there is no subscription available to cover it.  Replacing it with a call to get the compliance status
				Assert.assertTrue(!sshCommandResult.getStdout().contains(autosubscribeFailedMsg), "When autosubscribe is successful and entitlements have been granted, stdout from call to '"+rhnMigrateTool+" "+options+"' does NOT contain message: "+autosubscribeFailedMsg);				
			} */
        if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.13.8-1")) {
            // post commit 7957b8df95c575e6e8713c2f1a0f8f754e32aed3 bug 1119688
            SSHCommandResult statusResult = clienttasks.status(null, null, null, null, null);
            if (statusResult.getStdout().contains("Overall Status: Invalid")) {
                Assert.assertTrue(sshCommandResult.getStdout().contains(autosubscribeFailedMsg), "Since the subscription-manager overall status appears Invalid, the most likely reason is because at least one of the migrated products could not be auto-subscribed.  Therefore stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + autosubscribeFailedMsg);
            } else {
                // Note: "Overall Status: Insufficient" is possible and likely when the auto-subscribed subscription pool is Temporary
                Assert.assertTrue(!sshCommandResult.getStdout().contains(autosubscribeFailedMsg), "Since the subscription-manager overall status does not appear Invalid (overall status of Current or Insufficient are likely), all of the migrated products should have been auto-subscribed.  Therefore stdout from call to '" + rhnMigrateTool + " " + options + "' does NOT contain message: " + autosubscribeFailedMsg);
            }
        }
        // assert that when no --servicelevel is specified, then no service level preference will be set on the registered consumer
        if (!options.contains("-s ") && !options.contains("--servicelevel") && !options.contains("--service-level") && (serviceLevelExpected == null || serviceLevelExpected.isEmpty())) {
            // assert no service level preference was set
            Assert.assertEquals(clienttasks.getCurrentServiceLevel(), "", "No servicelevel preference should be set on the consumer when no service level was requested.");
        }
        // assert the service levels consumed from autosubscribe match the requested serviceLevel
        if (serviceLevelExpected != null && !serviceLevelExpected.isEmpty()) {
            // when a valid servicelevel was either specified or chosen
            expectedMsg = String.format("Service level set to: %s", serviceLevelExpected);
            Assert.assertTrue(sshCommandResult.getStdout().toUpperCase().contains(expectedMsg.toUpperCase()), "Regardless of service level case, the stdout from call to '" + rhnMigrateTool + " " + options + "' contains message: " + expectedMsg);
            for (ProductSubscription productSubscription : consumedProductSubscriptions) {
                Assert.assertNotNull(productSubscription.serviceLevel, "When migrating from RHN Classic with a specified service level '" + serviceLevelExpected + "', this auto consumed product subscription's service level should not be null: " + productSubscription);
                if (sm_exemptServiceLevelsInUpperCase.contains(productSubscription.serviceLevel.toUpperCase())) {
                    log.info("Exempt service levels: " + sm_exemptServiceLevelsInUpperCase);
                    Assert.assertTrue(sm_exemptServiceLevelsInUpperCase.contains(productSubscription.serviceLevel.toUpperCase()), "This auto consumed product subscription's service level is among the exempt service levels: " + productSubscription);
                } else {
                    Assert.assertTrue(productSubscription.serviceLevel.equalsIgnoreCase(serviceLevelExpected), "When migrating from RHN Classic with a specified service level '" + serviceLevelExpected + "', this auto consumed product subscription's service level should match: " + productSubscription);
                }
            }
        }
    }
    if (options.contains("--activation-key")) {
        // assert that autosubscribe was NOT attempted
        // Assert.assertTrue(!sshCommandResult.getStdout().contains(autosubscribeAttemptedMsg), "Stdout from call to '"+rhnMigrateTool+" "+options+"' does NOT contain message: "+autosubscribeAttemptedMsg);	// not a fair assertion since autosubscribeAttemptedMsg was set to "Installed Product Current Status:"
        // Assert.assertTrue(!sshCommandResult.getStdout().contains(autosubscribeFailedMsg), "Stdout from call to '"+rhnMigrateTool+" "+options+"' does NOT contain message: "+autosubscribeFailedMsg);	// also not a fair assertion since autosubscribeFailedMsg was set to "Unable to find available subscriptions for all your installed products."
        Assert.assertTrue(!sshCommandResult.getStdout().toLowerCase().contains("auto-attach"), "Stdout from an attempt to migrate with options (" + options + ") which include an activation key should make no reference to 'auto-attach'");
        Assert.assertTrue(!sshCommandResult.getStdout().toLowerCase().contains("auto-subscribe"), "Stdout from an attempt to migrate with options (" + options + ") which include an activation key should make no reference to 'auto-subscribe'");
        // assert that we are consuming entitlements, TODO but this is really dependent on the activation key
        Assert.assertTrue(!clienttasks.getCurrentlyConsumedProductSubscriptions().isEmpty(), "We should be consuming some entitlements after a call to " + rhnMigrateTool + " with options (" + options + ").  This assumes the activation key contained one or more pools.");
    // TODO When an activation key is used, all of the consumed subscriptions should have come from the activation key.
    // It would be best to make these assertion in the test that calls this function.
    }
    // assert that the rhnplugin has been disabled
    Assert.assertEquals(clienttasks.getConfFileParameter(clienttasks.yumPluginConfFileForRhn, "enabled"), "0", "The enabled yum plugin configuration for RHN.");
    // assert that productid.js is updated with productid mappings for all of the rhnChannelsConsumed; coverage for Bug 972883 - rhn-migrate-classic-to-rhsm tool neglects to populate /var/lib/rhsm/productid.js
    client.runCommandAndWait("cat " + clienttasks.productIdJsonFile);
    for (String rhnChannelConsumed : rhnChannelsConsumed) {
        if (channelsToProductCertFilenamesMap.containsKey(rhnChannelConsumed)) {
            String productId = MigrationDataTests.getProductIdFromProductCertFilename(channelsToProductCertFilenamesMap.get(rhnChannelConsumed));
            // special case (see RhnMigrateClassicToRhsm_Rhel5ClientDesktopVersusWorkstation_Test)
            if (clienttasks.releasever.equals("5Client")) {
                String productIdForDesktop = "68";
                String productIdForWorkstation = "71";
                if (productId.equals(productIdForDesktop)) {
                    log.info("Encountered a special case for migration of a 5Client system from RHN Classic to RHSM...");
                    log.info("Red Hat Enterprise Linux Desktop (productId=68) corresponds to the base RHN Channel (rhel-ARCH-client-5) for a 5Client system where ARCH=i386,x86_64.");
                    log.info("Red Hat Enterprise Linux Workstation (productId=71) corresponds to child RHN Channel (rhel-ARCH-client-workstation-5) for a 5Client system where ARCH=i386,x86_64.");
                    log.info("After migrating from RHN Classic to RHSM, these two product certs should not be installed at the same time; Workstation should prevail.");
                    if (productIdRepoMapAfterMigration.containsKey(productIdForWorkstation)) {
                        Assert.assertTrue(!productIdRepoMapAfterMigration.containsKey(productId), "The '" + clienttasks.productIdJsonFile + "' database should NOT contain an entry for productId '" + productId + "' which was migrated for consumption of Classic RHN Channel '" + rhnChannelConsumed + "' when Workstation channels for product '" + productIdForWorkstation + "' have also been migrated (Workstation wins).");
                        continue;
                    }
                }
            }
            if (productId.equalsIgnoreCase("none")) {
                Assert.assertTrue(!productIdRepoMapAfterMigration.containsKey(productId), "The '" + clienttasks.productIdJsonFile + "' database does NOT contain an entry for productId '" + productId + "' after migration while consuming Classic RHN Channel '" + rhnChannelConsumed + "'.");
            } else {
                Assert.assertTrue(productIdRepoMapAfterMigration.containsKey(productId), "The '" + clienttasks.productIdJsonFile + "' database contains an entry for productId '" + productId + "' which was migrated for consumption of Classic RHN Channel '" + rhnChannelConsumed + "'.");
                Assert.assertTrue(productIdRepoMapAfterMigration.get(productId).contains(rhnChannelConsumed), "The '" + clienttasks.productIdJsonFile + "' database entry for productId '" + productId + "' contains Classic RHN Channel/Repo '" + rhnChannelConsumed + "'.");
            }
        }
    }
}
Also used : Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) ProductCert(rhsm.data.ProductCert) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ArrayList(java.util.ArrayList) List(java.util.List) 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 52 with BugzillaAPIException

use of com.redhat.qe.auto.bugzilla.BugzillaAPIException in project rhsm-qe by RedHatQE.

the class PluginTests method testPluginsListWithEnabledProductIdRemoveTestPlugin.

// TODO ProductIdRemoveTestPlugin Tests ***************************************************
// CURRENTLY BLOCKED BY BUGZILLA 922882
@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL7-55178" }, 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 = "enable ProductIdRemoveTestPlugin and assert the plugins list reports enablement", groups = { "Tier1Tests", "blockedByBug-922882" }, priority = 710, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testPluginsListWithEnabledProductIdRemoveTestPlugin() {
    // Red Hat Enterprise Linux High Availability (for RHEL Server)
    String haProductId = "83";
    // Red Hat Enterprise Linux High Availability (for IBM z Systems)
    if (clienttasks.arch.startsWith("s390"))
        haProductId = "300";
    // TEMPORARY WORKAROUND FOR BUG
    String bugId = "922882";
    boolean invokeWorkaroundWhileBugIsOpen = true;
    // RFE Bug 922882 was CLOSED NOTABUG and will be re-opened when actually needed.  However, we still need to invoke this workaround to remove the ccs package from the prior test
    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) {
        // remove the HA package that was installed by prior test verifyEnabledProductIdInstallTestPluginHooksAreCalled_Test
        List<String> haPackages = HighAvailabilityTests.getHighAvailabilityPackages(clienttasks.redhatReleaseXY, clienttasks.arch);
        if (!haPackages.isEmpty() && clienttasks.isPackageInstalled(haPackages.get(0))) {
            // yum -y remove ccs
            clienttasks.yumRemovePackage(haPackages.get(0));
        }
        // remove the HA product cert too
        InstalledProduct haInstalledProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", haProductId, clienttasks.getCurrentlyInstalledProducts());
        if (haInstalledProduct != null) {
            ProductCert haInstalledProductCert = ProductCert.findFirstInstanceWithMatchingFieldFromList("productId", haProductId, clienttasks.getCurrentProductCerts());
            log.warning("Manually removing installed High Availability product cert and restoring '" + clienttasks.productIdJsonFile + "' (you are probably running a RHEL5 client)...");
            client.runCommandAndWait("rm -f " + haInstalledProductCert.file.getPath());
            restoreProductIdJsonFileAfterClass();
            haInstalledProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", haProductId, clienttasks.getCurrentlyInstalledProducts());
        }
        Assert.assertNull(haInstalledProduct, "The High Availability product id '" + haProductId + "' should NOT be installed after successful removal of all High Availability packages.");
        throw new SkipException("Skipping test while bug '" + bugId + "' is not implemented.");
    }
    // END OF WORKAROUND
    Assert.fail("This test will be implemented after RFE bug 922882 is implemented.");
}
Also used : InstalledProduct(rhsm.data.InstalledProduct) ProductCert(rhsm.data.ProductCert) SkipException(org.testng.SkipException) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 53 with BugzillaAPIException

use of com.redhat.qe.auto.bugzilla.BugzillaAPIException in project rhsm-qe by RedHatQE.

the class ProxyTests method testRegisterAttemptsToVerifyHonoringNoProxyEnvironmentVariable.

@SuppressWarnings("unused")
@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-22311", "RHEL7-51636" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "subscription-manager : register when no_proxy environment variable matches our hostname regardless of proxy configurations and environment variable (Positive and Negative Variations)", groups = { "Tier3Tests", "blockedByBug-1266608", "blockedByBug-1285010" }, dataProvider = "getRegisterAttemptsToVerifyHonoringNoProxyEnvironmentVariableData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRegisterAttemptsToVerifyHonoringNoProxyEnvironmentVariable(Object blockedByBug, String username, String password, String org, String proxy, String proxyuser, String proxypassword, String proxy_hostnameConfig, String proxy_portConfig, String proxy_userConfig, String proxy_passwordConfig, Integer exitCode, String stdout, String stderr, SSHCommandRunner proxyRunner, String proxyLog, String proxyLogGrepPattern, String noProxyEnvVar, Boolean hostnameMatchesNoProxyEnvVar) {
    if (clienttasks.isPackageVersion("python-rhsm", "<", "1.15.1-1"))
        throw new SkipException("Support for this test does not exist in this version of python-rhsm.  See bugzilla 1266608.");
    String moduleTask = "register";
    String httpProxyEnvVar;
    String proxyLogMarker;
    SSHCommandResult attemptResult;
    // Notes: from http://www.gnu.org/software/emacs/manual/html_node/url/Proxies.html
    // The NO_PROXY environment variable specifies URLs that should be excluded from proxying
    // (on servers that should be contacted directly). This should be a comma-separated list
    // of hostnames, domain names, or a mixture of both. Asterisks can be used as wildcards,
    // but other clients may not support that. Domain names may be indicated by a leading dot.
    // For example:
    // 
    // NO_PROXY="*.aventail.com,home.com,.seanet.com"
    // 
    // says to contact all machines in the ‘aventail.com’ and ‘seanet.com’ domains directly,
    // as well as the machine named ‘home.com’. If NO_PROXY isn’t defined, no_PROXY and no_proxy
    // are also tried, in that order.
    // Notes: from man page for curl
    // ENVIRONMENT
    // The environment variables can be specified in lower case or upper case. The lower case version has precedence. http_proxy is an exception as  it
    // is only available in lower case.
    // 
    // Using an environment variable to set the proxy has the same effect as using the --proxy option.
    // 
    // http_proxy [protocol://]<host>[:port]
    // Sets the proxy server to use for HTTP.
    // 
    // HTTPS_PROXY [protocol://]<host>[:port]
    // Sets the proxy server to use for HTTPS.
    // 
    // [url-protocol]_PROXY [protocol://]<host>[:port]
    // Sets  the  proxy  server  to  use for [url-protocol], where the protocol is a protocol that curl supports and as specified in a URL. FTP,
    // FTPS, POP3, IMAP, SMTP, LDAP etc.
    // 
    // ALL_PROXY [protocol://]<host>[:port]
    // Sets the proxy server to use if no protocol-specific proxy is set.
    // 
    // NO_PROXY <comma-separated list of hosts>
    // list of host names that shouldn't go through any proxy. If set to a asterisk '*' only, it matches all hosts.
    // WARNING: The two docs above do not agree on no_Proxy and the use of *
    // Notes: proxy precedence rules as defined in Sprint Review 68
    // a. proxy values set in the subscription-manager CLI options override all
    // b. proxy values set in the rhsm.conf file override the proxy environment variable
    // c. finally the proxy environment variable applies when no proxy values are set in the CLI options nor rhsm.conf
    // d. if hostname matches no_proxy environment variable, then override c.
    // Notes Update: 2/8/2017 The precedence rules for no_proxy defined above was flawed and was corrected by
    // Bug 1311429 - no_proxy variable ignored when configured in virt-who config file
    // d. if hostname matches no_proxy environment variable, then override all.  DO NOT USE A PROXY.
    // randomly test using one of these valid environment variables
    List<String> validHttpProxyEnvVars = Arrays.asList(new String[] { "HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy" });
    List<String> validHttpNoProxyEnvVars = Arrays.asList(new String[] { "NO_PROXY", "no_proxy" /*,"no_PROXY" not supported by curl*/
    });
    // TEST PART 1:
    // -------------
    // Assert that setting the proxy via environment variables (rhsm.conf and CLI options are void of proxy values)...
    // A: is ignored when hostname matches no_proxy
    // B: is NOT ignored when hostname does not match no_proxy
    // assemble the value of the httpProxyVar
    // HTTPS_PROXY=https://proxyserver
    // HTTPS_PROXY=https://proxyserver:proxyport
    // HTTPS_PROXY=https://username:password@proxyserver:proxyport
    // proxy configurations intended for CLI proxy options take precedence over the proxy configurations intended for rhsm.conf file
    httpProxyEnvVar = validHttpProxyEnvVars.get(randomGenerator.nextInt(validHttpProxyEnvVars.size())) + "=https://";
    if (proxyuser != null)
        httpProxyEnvVar += proxyuser;
    else if (proxy_userConfig != null)
        httpProxyEnvVar += proxy_userConfig;
    if (proxypassword != null)
        httpProxyEnvVar += ":" + proxypassword;
    else if (proxy_passwordConfig != null)
        httpProxyEnvVar += ":" + proxy_passwordConfig;
    if (proxyuser != null || proxy_userConfig != null)
        httpProxyEnvVar += "@";
    if (proxy != null)
        httpProxyEnvVar += proxy;
    else {
        if (proxy_hostnameConfig != null)
            httpProxyEnvVar += proxy_hostnameConfig;
        if (proxy_portConfig != null)
            httpProxyEnvVar += ":" + proxy_portConfig;
    }
    // assemble the value of noProxyEnvVar
    noProxyEnvVar = validHttpNoProxyEnvVars.get(randomGenerator.nextInt(validHttpNoProxyEnvVars.size())) + "=" + noProxyEnvVar;
    // reset the config parameters
    updateConfFileProxyParameters("", "", "", "", "");
    RemoteFileTasks.runCommandAndWait(client, "grep proxy " + clienttasks.rhsmConfFile, TestRecords.action());
    // pad the tail of proxyLog with a message
    proxyLogMarker = System.currentTimeMillis() + " Testing 1 " + moduleTask + " AttemptsToVerifyHonoringNoProxyEnvironmentVariable_Test from " + clienttasks.hostname + "...";
    RemoteFileTasks.markFile(proxyRunner, proxyLog, proxyLogMarker);
    // attempt to register using a non-matching no_proxy environment variable and a proxy server defined by an environment variable (no CLI option nor rhsm.conf [sever] proxy configurations set)
    attemptResult = client.runCommandAndWait(noProxyEnvVar + " " + httpProxyEnvVar + " " + clienttasks.registerCommand(username, password, org, null, null, null, null, null, null, null, (List<String>) null, null, null, null, true, null, null, null, null, null));
    if (hostnameMatchesNoProxyEnvVar) {
        // A: is ignored when hostname matches no_proxy
        Assert.assertEquals(attemptResult.getExitCode(), Integer.valueOf(0), "The exit code from an attempt to " + moduleTask + " using a matching no_proxy environment variable '" + noProxyEnvVar + "'.");
        Assert.assertEquals(attemptResult.getStderr().trim(), "", "The stderr from an attempt to " + moduleTask + " using a matching no_proxy environment variable '" + noProxyEnvVar + "'.");
        if (proxyLogGrepPattern != null) {
            // accounts for multiple tests hitting the same proxy server simultaneously
            String proxyLogResult = RemoteFileTasks.getTailFromMarkedFile(proxyRunner, proxyLog, proxyLogMarker, ipv4_address);
            Assert.assertTrue(proxyLogResult.isEmpty(), "The tail of proxy server log '" + proxyLog + "' following marker '" + proxyLogMarker + "' contains NO connection '" + proxyLogGrepPattern + "' attempts from " + ipv4_address + " to the candlepin server.");
        }
    } else if (exitCode != Integer.valueOf(69)) /* EX_UNAVAILABLE is indicative of a bad proxy; skip Test 1B for negative bad proxy */
    {
        // B: is NOT ignored when hostname does not match no_proxy
        if (exitCode != null)
            Assert.assertEquals(attemptResult.getExitCode(), exitCode, "The exit code from an attempt to " + moduleTask + " using a proxy server defined by an environment variable '" + httpProxyEnvVar + "' that does not match the no_proxy environment variable '" + noProxyEnvVar + "'.");
        if (stdout != null)
            Assert.assertEquals(attemptResult.getStdout().trim(), stdout, "The stdout from an attempt to " + moduleTask + " using a proxy server defined by an environment variable '" + httpProxyEnvVar + "' that does not match the no_proxy environment variable '" + noProxyEnvVar + "'.");
        if (stderr != null)
            Assert.assertEquals(attemptResult.getStderr().trim(), stderr, "The stderr from an attempt to " + moduleTask + " using a proxy server defined by an environment variable '" + httpProxyEnvVar + "' that does not match the no_proxy environment variable '" + noProxyEnvVar + "'.");
        if (proxyLogGrepPattern != null) {
            // accounts for multiple tests hitting the same proxy server simultaneously
            String proxyLogResult = RemoteFileTasks.getTailFromMarkedFile(proxyRunner, proxyLog, proxyLogMarker, ipv4_address);
            Assert.assertTrue(proxyLogResult.contains(proxyLogGrepPattern), "The tail of proxy server log '" + proxyLog + "' following marker '" + proxyLogMarker + "' contains expected connection '" + proxyLogGrepPattern + "' attempts from " + ipv4_address + " to the candlepin server.");
        }
    }
    // -------------
    if (clienttasks.isPackageVersion("python-rhsm", "<", "1.18.3-1")) {
        // pre commit 7b1294aa6bceb6734caa2493c54402537f0773a7 for Bug 1311429 - no_proxy variable ignored when configured in virt-who config file
        // TEST PART 2: now let's assert that setting the proxy via CLI option or rhsm.conf take precedence over the environment variable...
        // A: regardless if hostname matches no_proxy
        // B: regardless if hostname does not matches no_proxy
        // assemble the value of a httpProxyVar that will get overridden
        httpProxyEnvVar = validHttpProxyEnvVars.get(randomGenerator.nextInt(validHttpProxyEnvVars.size())) + "=https://";
        // provided in https://bugzilla.redhat.com/show_bug.cgi?id=1031755#c0	Note: this does not have to be a working proxy to make this a valid test
        httpProxyEnvVar += "proxy.example.com:911";
        // set the config parameters
        updateConfFileProxyParameters(proxy_hostnameConfig, proxy_portConfig, proxy_userConfig, proxy_passwordConfig, "");
        RemoteFileTasks.runCommandAndWait(client, "grep proxy " + clienttasks.rhsmConfFile, TestRecords.action());
        // pad the tail of proxyLog with a message
        proxyLogMarker = System.currentTimeMillis() + " Testing 2 " + moduleTask + " AttemptsToVerifyHonoringNoProxyEnvironmentVariable_Test from " + clienttasks.hostname + "...";
        RemoteFileTasks.markFile(proxyRunner, proxyLog, proxyLogMarker);
        // attempt to register using a proxy server defined by an environment variable (no CLI option nor rhsm.conf [sever] proxy configurations set)
        attemptResult = client.runCommandAndWait(noProxyEnvVar + " " + httpProxyEnvVar + " " + clienttasks.registerCommand(username, password, org, null, null, null, null, null, null, null, (List<String>) null, null, null, null, true, null, proxy, proxyuser, proxypassword, null));
        if (hostnameMatchesNoProxyEnvVar || !hostnameMatchesNoProxyEnvVar) {
            // A: regardless if hostname matches no_proxy	// B: regardless if hostname does not matches no_proxy
            if (exitCode != null)
                Assert.assertEquals(attemptResult.getExitCode(), exitCode, "The exit code from an attempt to " + moduleTask + " using a proxy server to override environment variable '" + httpProxyEnvVar + "'.");
            if (stdout != null)
                Assert.assertEquals(attemptResult.getStdout().trim(), stdout, "The stdout from an attempt to " + moduleTask + " using a proxy server to override environment variable '" + httpProxyEnvVar + "'.");
            if (stderr != null)
                Assert.assertEquals(attemptResult.getStderr().trim(), stderr, "The stderr from an attempt to " + moduleTask + " using a proxy server to override environment variable '" + httpProxyEnvVar + "'.");
            if (proxyLogGrepPattern != null) {
                // accounts for multiple tests hitting the same proxy server simultaneously
                String proxyLogResult = RemoteFileTasks.getTailFromMarkedFile(proxyRunner, proxyLog, proxyLogMarker, ipv4_address);
                Assert.assertTrue(proxyLogResult.contains(proxyLogGrepPattern), "The tail of proxy server log '" + proxyLog + "' following marker '" + proxyLogMarker + "' contains expected connection '" + proxyLogGrepPattern + "' attempts from " + ipv4_address + " to the candlepin server.");
            }
        } else {
            Assert.fail("This line of code should be logically unreachable.");
        }
    } else {
        // post commit 7b1294aa6bceb6734caa2493c54402537f0773a7 for Bug 1311429 - no_proxy variable ignored when configured in virt-who config file
        // TEST PART 2:
        // Assert that setting the no_proxy environment variable is honored when it matches...
        // A: the proxy hostname specified within the rhsm.conf or the proxy hostname specified on the command line
        // do not assemble an environment variable for httpProxyVar - that was covered in Test 1
        httpProxyEnvVar = "";
        // set the config parameters
        updateConfFileProxyParameters(proxy_hostnameConfig, proxy_portConfig, proxy_userConfig, proxy_passwordConfig, "");
        RemoteFileTasks.runCommandAndWait(client, "grep proxy " + clienttasks.rhsmConfFile, TestRecords.action());
        // pad the tail of proxyLog with a message
        proxyLogMarker = System.currentTimeMillis() + " Testing 2 " + moduleTask + " AttemptsToVerifyHonoringNoProxyEnvironmentVariable_Test from " + clienttasks.hostname + "...";
        RemoteFileTasks.markFile(proxyRunner, proxyLog, proxyLogMarker);
        // attempt to register while a no_proxy environment variable that has been defined with a list of proxy servers to ignore
        attemptResult = client.runCommandAndWait(noProxyEnvVar + " " + httpProxyEnvVar + " " + clienttasks.registerCommand(username, password, org, null, null, null, null, null, null, null, (List<String>) null, null, null, null, true, null, proxy, proxyuser, proxypassword, null));
        if (exitCode == Integer.valueOf(69)) {
            // when the proxy is unavailable, subscription-manager now aborts before making any decisions about no_proxy environment variables... Bug 1176219: Error out if bad proxy settings detected
            if (exitCode != null)
                Assert.assertEquals(attemptResult.getExitCode(), exitCode, "The exit code from an attempt to " + moduleTask + " with an unavailable proxy should abort in honor of bug 1176219 regardless of a no_proxy environment variable setting.");
            if (stdout != null)
                Assert.assertEquals(attemptResult.getStdout().trim(), stdout, "The stdout from an attempt to " + moduleTask + " with an unavailable proxy should abort in honor of bug 1176219 regardless of a no_proxy environment variable setting.");
            if (stderr != null)
                Assert.assertEquals(attemptResult.getStderr().trim(), stderr, "The stderr from an attempt to " + moduleTask + " with an unavailable proxy should abort in honor of bug 1176219 regardless of a no_proxy environment variable setting.");
        } else if (hostnameMatchesNoProxyEnvVar) {
            // no_proxy environment variable matches proxy
            Assert.assertEquals(attemptResult.getExitCode(), Integer.valueOf(0), "The exit code from an attempt to " + moduleTask + " using a no_proxy environment variable '" + noProxyEnvVar + "' that matches the hostname to override both the configured and CLI option proxy.");
            Assert.assertEquals(attemptResult.getStderr().trim(), "", "The stderr from an attempt to " + moduleTask + " using a no_proxy environment variable '" + noProxyEnvVar + "' that matches the hostname to override both the configured and CLI option proxy.");
            Assert.assertNotNull(clienttasks.getCurrentConsumerCert(), "The system has succesfully registered a consumer.");
            // assert that no traffic has gone through the proxy logs
            // accounts for multiple tests hitting the same proxy server simultaneously
            String proxyLogResult = RemoteFileTasks.getTailFromMarkedFile(proxyRunner, proxyLog, proxyLogMarker, ipv4_address);
            // TEMPORARY WORKAROUND FOR BUG 1420533 - no_proxy environment variable is ignored by the rhsmd process
            String bugId = "1420533";
            boolean invokeWorkaroundWhileBugIsOpen = true;
            try {
                if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
                    log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
                    SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
                } else {
                    invokeWorkaroundWhileBugIsOpen = false;
                }
            } catch (BugzillaAPIException be) {
            /* ignore exception */
            } catch (RuntimeException re) {
            /* ignore exception */
            }
            if (invokeWorkaroundWhileBugIsOpen) {
                log.warning("Skipping assertion that tail of proxy server log '" + proxyLog + "' contains no attempts from " + ipv4_address + " to the candlepin server while bug '" + bugId + "' is open.");
            } else // PERAMANENT WORKAROUND
            if (true) {
                log.warning("Permanently skipping assertion that tail of proxy server log '" + proxyLog + "' contains no attempts from " + ipv4_address + " to the candlepin server when the NO_PROXY environment variable matches the server.hostname because the solution for bug '" + bugId + "' was to introduce a new server.no_proxy configuration that could be read by the rhsmd process which runs outside the shell that the NO_PROXY environment variable was defined.");
            } else
                // END OF WORKAROUND
                Assert.assertTrue(proxyLogResult.isEmpty(), "The tail of proxy server log '" + proxyLog + "' following marker '" + proxyLogMarker + "' contains no attempts from " + ipv4_address + " to the candlepin server.");
        } else {
            // the proxy does NOT match no_proxy and the no_proxy environment variable should have no effect.  Assert expected results from dataProvider.
            if (exitCode != null)
                Assert.assertEquals(attemptResult.getExitCode(), exitCode, "The exit code from an attempt to " + moduleTask + " when no_proxy environment variable '" + noProxyEnvVar + "' does not match the hostname.");
            if (stdout != null)
                Assert.assertEquals(attemptResult.getStdout().trim(), stdout, "The stdout from an attempt to " + moduleTask + " when no_proxy environment variable '" + noProxyEnvVar + "' does not match the hostname.");
            if (stderr != null)
                Assert.assertEquals(attemptResult.getStderr().trim(), stderr, "The stderr from an attempt to " + moduleTask + " when no_proxy environment variable '" + noProxyEnvVar + "' does not match the hostname.");
            if (proxyLogGrepPattern != null) {
                // accounts for multiple tests hitting the same proxy server simultaneously
                String proxyLogResult = RemoteFileTasks.getTailFromMarkedFile(proxyRunner, proxyLog, proxyLogMarker, ipv4_address);
                Assert.assertTrue(proxyLogResult.contains(proxyLogGrepPattern), "The tail of proxy server log '" + proxyLog + "' following marker '" + proxyLogMarker + "' contains expected connection '" + proxyLogGrepPattern + "' attempts from " + ipv4_address + " to the candlepin server.");
            }
        }
    }
}
Also used : SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ArrayList(java.util.ArrayList) List(java.util.List) SkipException(org.testng.SkipException) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 54 with BugzillaAPIException

use of com.redhat.qe.auto.bugzilla.BugzillaAPIException in project rhsm-qe by RedHatQE.

the class ContentTests method testRhelSubscriptionContentIsAvailable.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20084", "RHEL7-55189" }, 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 all there is at least one available RHEL subscription and that yum content is available for the installed RHEL product cert", groups = { "Tier1Tests", "FipsTests", "blockedByBug-1156638" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRhelSubscriptionContentIsAvailable() throws JSONException, Exception {
    // TEMPORARY WORKAROUND
    if (clienttasks.arch.equals("ppc64le")) {
        boolean invokeWorkaroundWhileBugIsOpen = true;
        // Bug 1156638 - "Red Hat Enterprise Linux for IBM POWER" subscriptions need to provide content for arch "ppc64le"
        String bugId = "1156638";
        try {
            if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
                log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
                SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
            } else {
                invokeWorkaroundWhileBugIsOpen = false;
            }
        } catch (BugzillaAPIException be) {
        /* ignore exception */
        } catch (RuntimeException re) {
        /* ignore exception */
        }
        if (invokeWorkaroundWhileBugIsOpen) {
            throw new SkipException("Skipping this test on arch '" + clienttasks.arch + "' while blocking bug '" + bugId + "' is open.");
        }
    }
    // END OF WORKAROUND
    // get the currently installed RHEL product cert
    ProductCert rhelProductCert = clienttasks.getCurrentRhelProductCert();
    Assert.assertNotNull(rhelProductCert, "Expecting a RHEL Product Cert to be installed.");
    log.info("RHEL product cert installed: " + rhelProductCert);
    // register and make sure autoheal is off
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, true, null, null, null, null, null);
    clienttasks.autoheal(null, null, true, null, null, null, null);
    // verify that NO yum content is available since no entitlements have been granted
    Integer yumRepolistPackageCount = clienttasks.getYumRepolistPackageCount("enabled");
    // added only for debugging a failure
    if (yumRepolistPackageCount > 0)
        clienttasks.list_(null, null, true, null, null, null, null, null, null, null, null, null, null, null);
    Assert.assertEquals(yumRepolistPackageCount, new Integer(0), "Expecting no available packages (actual='" + yumRepolistPackageCount + "') because no RHEL subscription have been explicitly attached.");
    // loop through the available pools looking for those that provide content for this rhelProductCert
    boolean rhelYumContentIsAvailable = true;
    boolean rhelSubscriptionIsAvailable = false;
    for (SubscriptionPool pool : clienttasks.getCurrentlyAvailableSubscriptionPools()) {
        if (CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId).contains(rhelProductCert.productId)) {
            // subscribe
            EntitlementCert rhelEntitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(clienttasks.subscribeToSubscriptionPool(pool, sm_clientUsername, sm_clientPassword, sm_serverUrl));
            // Brand Name:
            if (rhelProductCert.productId.equals("261") && clienttasks.arch.equals("aarch64")) {
                boolean invokeWorkaroundWhileBugIsOpen = true;
                String bugId = "1174966";
                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) {
                    String enablerepo = "rhel-server-for-arm-development-preview-rpms";
                    log.info("Explicitly enabling repo '" + enablerepo + "' to gain access to ARM content.");
                    clienttasks.repos(null, null, null, enablerepo, null, null, null, null, null);
                }
            }
            // WORKAROUND FOR RHEL-ALT-7.5 aarch64
            if (clienttasks.redhatReleaseXY.equals("7.5") && rhelProductCert.productId.equals("433")) {
                // Red Hat Enterprise Linux for IBM System z (Structure A) Beta
                String repo = "rhel-7-for-system-z-a-beta-rpms";
                log.info("WORKAROUND: Enabling beta repo '" + repo + "' for installed product '" + rhelProductCert.productName + "' (" + rhelProductCert.productId + ") because this is the debut release for this product.  No GA content from repo rhel-7-for-system-z-a-rpms is available yet.");
                clienttasks.repos(null, null, null, repo, null, null, null, null, null);
            }
            // END OF WORKAROUND
            // verify that rhel yum content is available
            yumRepolistPackageCount = clienttasks.getYumRepolistPackageCount("enabled");
            if (yumRepolistPackageCount > 0) {
                Assert.assertTrue(yumRepolistPackageCount > 0, "Expecting many available packages (actual='" + yumRepolistPackageCount + "') of enabled repo content because RHEL subscription '" + pool.subscriptionName + "' SKU '" + pool.productId + "' was just attached.");
            } else {
                log.warning("No enabled yum repo content packages are available after attaching RHEL subscription '" + pool.subscriptionName + "'. (This can happen when the RHEL product is brand new and content has not yet been pushed to '" + clienttasks.baseurl + "')");
                rhelYumContentIsAvailable = false;
            }
            // unsubscribe
            clienttasks.unsubscribe(null, rhelEntitlementCert.serialNumber, null, null, null, null, null);
            rhelSubscriptionIsAvailable = true;
            if (rhelYumContentIsAvailable)
                break;
        }
    }
    if (!rhelSubscriptionIsAvailable && sm_serverType.equals(CandlepinType.standalone))
        throw new SkipException("Skipping this test against a standalone Candlepin server that has no RHEL subscriptions available.");
    // TEMPORARY WORKAROUND FOR BUG: https://bugzilla.redhat.com/show_bug.cgi?id=1090058
    if (clienttasks.redhatReleaseX.equals("5") && clienttasks.arch.startsWith("ppc")) {
        boolean invokeWorkaroundWhileBugIsOpen = true;
        String bugId = "1090058";
        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 (!rhelSubscriptionIsAvailable)
                throw new SkipException("skipping this test while bug '" + bugId + "' is open");
        }
    }
    if (!rhelSubscriptionIsAvailable) {
        clienttasks.facts_(true, null, null, null, null, null);
        log.warning("This test is about to fail and may be due to the lack of an available subscription with enough socket/ram/core support to cover this system.  Visually confirm by reviewing the system facts above.");
    }
    Assert.assertTrue(rhelSubscriptionIsAvailable, "Successfully subscribed to at least one available RHEL subscription that provided for our installed RHEL product cert: " + rhelProductCert);
    Assert.assertTrue(rhelYumContentIsAvailable, "All of the RHEL subscriptions subscribed provided at least one enabled yum content package applicable for our installed RHEL product cert: " + rhelProductCert + " (See WARNINGS logged above for failed subscriptions)");
}
Also used : BigInteger(java.math.BigInteger) EntitlementCert(rhsm.data.EntitlementCert) ProductCert(rhsm.data.ProductCert) SkipException(org.testng.SkipException) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) SubscriptionPool(rhsm.data.SubscriptionPool) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 55 with BugzillaAPIException

use of com.redhat.qe.auto.bugzilla.BugzillaAPIException in project rhsm-qe by RedHatQE.

the class DockerTests method testYumRepolistOnRunningDockerImageConsumedFromHostEntitlements.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL7-55539" }, 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 a running container has yum repolist access to appropriate content from the host's entitlement", groups = { "Tier1Tests" }, dependsOnMethods = { "testYumRepolistIsEmptyOnRunningDockerImageWhenHostIsUnregistered" }, dataProvider = "getDockerImageData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testYumRepolistOnRunningDockerImageConsumedFromHostEntitlements(Object bugzilla, String dockerImage) {
    // register the host and autosubscribe
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, true, null, null, (String) null, null, null, null, true, false, null, null, null, null);
    // get a list of the entitled yum repos on the host
    List<String> enabledYumReposOnHost = clienttasks.getYumRepolist("enabled");
    List<EntitlementCert> entitlementCertsOnHost = clienttasks.getCurrentEntitlementCerts();
    Assert.assertTrue(!entitlementCertsOnHost.isEmpty(), "When the host has registered with autosubscribe, we expect to have been granted at least one entitlement.");
    // determine what products are installed on the running docker image
    // [root@bkr-hv03-guest07 ~]# docker run --rm registry.access.redhat.com/rhel7:latest find /etc/pki/product* -name *.pem
    // /etc/pki/product/69.pem
    // /etc/pki/product-default/69.pem
    // SSHCommandResult lsResultOnRunningDockerImage = client.runCommandAndWait("docker run --rm "+dockerImage+" find /etc/pki/product* -name *.pem");	// assumes the productCertDir config within the image is /etc/pki/product
    // assumes the productCertDir config within the image is /etc/pki/product	//  "find /etc/pki/product* -regex .+\.pem"  IS MORE RELIABLE THAN "find /etc/pki/product* -name *.pem"
    SSHCommandResult lsResultOnRunningDockerImage = client.runCommandAndWait("docker run --rm " + dockerImage + " find /etc/pki/product* -regex .+\\.pem");
    List<ProductCert> productCertsOnRunningDockerImage = new ArrayList<ProductCert>();
    for (String productCertFileOnRunningDockerImage : lsResultOnRunningDockerImage.getStdout().trim().split("\n")) {
        SSHCommandResult rctCatCertResultOnRunningDockerImage = RemoteFileTasks.runCommandAndAssert(client, "docker run --rm " + dockerImage + " rct cat-cert " + productCertFileOnRunningDockerImage, 0);
        // 201407071250:40.755 - FINE: ssh root@jsefler-7.usersys.redhat.com docker run --rm docker-registry.usersys.redhat.com/brew/rhel7:latest rct cat-cert /etc/pki/product/69.pem
        // 201407071250:43.954 - FINE: Stdout:
        // 
        // +-------------------------------------------+
        // Product Certificate
        // +-------------------------------------------+
        // 
        // Certificate:
        // Path: /etc/pki/product/69.pem
        // Version: 1.0
        // Serial: 12750047592154746969
        // Start Date: 2014-01-28 18:37:08+00:00
        // End Date: 2034-01-23 18:37:08+00:00
        // 
        // Subject:
        // CN: Red Hat Product ID [eb3b72ca-acb1-4092-9e67-f2915f6444f4]
        // 
        // Issuer:
        // C: US
        // CN: Red Hat Entitlement Product Authority
        // O: Red Hat, Inc.
        // OU: Red Hat Network
        // ST: North Carolina
        // emailAddress: ca-support@redhat.com
        // 
        // Product:
        // ID: 69
        // Name: Red Hat Enterprise Linux Server
        // Version: 7.0
        // Arch: x86_64
        // Tags: rhel-7,rhel-7-server
        // Brand Type:
        // Brand Name:
        productCertsOnRunningDockerImage.add(ProductCert.parse(rctCatCertResultOnRunningDockerImage.getStdout()).get(0));
    }
    // get the product tags installed on the running docker image
    Set<String> providedTagsOnRunningDockerImage = new HashSet<String>();
    for (ProductCert productCertOnRunningDockerImage : productCertsOnRunningDockerImage) {
        if (productCertOnRunningDockerImage.productNamespace.providedTags != null) {
            for (String providedTag : productCertOnRunningDockerImage.productNamespace.providedTags.split("\\s*,\\s*")) {
                providedTagsOnRunningDockerImage.add(providedTag);
            }
        }
    }
    // get the arch on the running docker image
    String archOnRunningDockerImage = RemoteFileTasks.runCommandAndAssert(client, "docker run --rm " + dockerImage + " uname --machine", 0).getStdout().trim();
    // get the yum repolist of enabled repos on the running docker image
    SSHCommandResult enabledYumRepolistResultOnRunningDockerImage = RemoteFileTasks.runCommandAndAssert(client, "docker run --rm " + dockerImage + " yum repolist enabled", 0, "repolist:", null);
    List<String> enabledYumReposOnRunningDockerImage = clienttasks.getYumRepolistFromSSHCommandResult(enabledYumRepolistResultOnRunningDockerImage);
    // TEMPORARY WORKAROUND FOR BUG
    if (clienttasks.redhatReleaseX.equals("7") && clienttasks.variant.equals("Workstation") && enabledYumReposOnRunningDockerImage.isEmpty()) {
        boolean invokeWorkaroundWhileBugIsOpen = true;
        // Bug 1551129 - entitlements from a RHEL7.5 Workstation host fail to flow through to a docker container with docker from latest-EXTRAS-7-RHEL-7
        String bugId = "1551129";
        try {
            if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
                log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
                SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
            } else {
                invokeWorkaroundWhileBugIsOpen = false;
            }
        } catch (BugzillaAPIException be) {
        /* ignore exception */
        } catch (RuntimeException re) {
        /* ignore exception */
        }
        if (invokeWorkaroundWhileBugIsOpen) {
            throw new SkipException("Skipping this test on variant '" + clienttasks.variant + "' while docker bug '" + bugId + "' is open");
        }
    }
    // assert that only the appropriate entitled content sets appear in the yum repolist on the running docker image
    for (EntitlementCert entitlementCertOnHost : entitlementCertsOnHost) {
        for (ContentNamespace contentNamespaceOnHost : entitlementCertOnHost.contentNamespaces) {
            // get the content namespace requiredTags
            Set<String> contentNamespaceRequiredTags = new HashSet<String>();
            if (contentNamespaceOnHost.requiredTags != null) {
                for (String requiredTag : contentNamespaceOnHost.requiredTags.split("\\s*,\\s*")) {
                    if (requiredTag.isEmpty())
                        continue;
                    contentNamespaceRequiredTags.add(requiredTag);
                }
            }
            // get the content namespace arches
            Set<String> contentNamespaceArches = new HashSet<String>();
            if (contentNamespaceOnHost.arches != null) {
                for (String arch : contentNamespaceOnHost.arches.split("\\s*,\\s*")) {
                    if (arch.isEmpty())
                        continue;
                    contentNamespaceArches.add(arch);
                }
            }
            // Note: x86 is a general arch to cover all 32-bit intel microprocessors
            if (contentNamespaceArches.contains("x86")) {
                contentNamespaceArches.addAll(Arrays.asList("i386", "i486", "i586", "i686"));
            }
            // when the content namespace is not of type "yum", it will not appear in either the yum repolist of the host or the running docker image
            if (!contentNamespaceOnHost.type.equals("yum")) {
                Assert.assertTrue(!enabledYumReposOnHost.contains(contentNamespaceOnHost.label), "Entitled content namespace '" + contentNamespaceOnHost.label + "' of type '" + contentNamespaceOnHost.type + "' should never appear on the yum repolist of the host.");
                Assert.assertTrue(!enabledYumReposOnRunningDockerImage.contains(contentNamespaceOnHost.label), "Entitled content namespace '" + contentNamespaceOnHost.label + "' of type '" + contentNamespaceOnHost.type + "' should never appear on the yum repolist of the running docker container.");
                // go to the next content namespace
                continue;
            }
            // when the content namespace is not enabled, it will not appear in either the yum repolist of the host or the running docker image
            if (!contentNamespaceOnHost.enabled) {
                Assert.assertTrue(!enabledYumReposOnHost.contains(contentNamespaceOnHost.label), "Entitled content namespace '" + contentNamespaceOnHost.label + "' is disabled and should NOT appear on the yum repolist of the host because it is disabled by default.");
                Assert.assertTrue(!enabledYumReposOnRunningDockerImage.contains(contentNamespaceOnHost.label), "Entitled content namespace '" + contentNamespaceOnHost.label + "' is disabled and should NOT appear on the yum repolist of the running docker container because it is disabled by default.");
                // go to the next content namespace
                continue;
            }
            // when the content namespace is enabled, it's appearance on the yum repolist of the running docker image depends on the installed product certs on the image.
            if ((contentNamespaceArches.isEmpty() || contentNamespaceArches.contains(archOnRunningDockerImage)) && (contentNamespaceRequiredTags.isEmpty() || providedTagsOnRunningDockerImage.containsAll(contentNamespaceRequiredTags))) {
                Assert.assertTrue(enabledYumReposOnRunningDockerImage.contains(contentNamespaceOnHost.label), "Entitled content namespace '" + contentNamespaceOnHost.label + "' on the host should be enabled in the running docker container because both the docker container arch '" + archOnRunningDockerImage + "' is among the supported content set arches " + contentNamespaceArches + " and the docker container providedTags " + providedTagsOnRunningDockerImage + " provides all the content set required tags " + contentNamespaceRequiredTags + ".");
            } else {
                Assert.assertTrue(!enabledYumReposOnRunningDockerImage.contains(contentNamespaceOnHost.label), "Entitled content namespace '" + contentNamespaceOnHost.label + "' on the host should NOT be enabled in the running docker container because either the docker container arch '" + archOnRunningDockerImage + "' is not among the supported content set arches " + contentNamespaceArches + " or the docker container providedTags " + providedTagsOnRunningDockerImage + " does not provide all the content set required tags " + contentNamespaceRequiredTags + ".");
            }
        }
    }
    // let's test installing a simple package (zsh)
    boolean installedPackage = false;
    if (enabledYumReposOnRunningDockerImage.contains("rhel-6-server-rpms") || enabledYumReposOnRunningDockerImage.contains("rhel-7-server-rpms")) {
        RemoteFileTasks.runCommandAndAssert(client, "docker run --rm " + dockerImage + " yum -y install zsh", 0, "Complete!", null);
        // [root@jsefler-7 ~]# docker run --rm docker-registry.usersys.redhat.com/brew/rhel7:latest yum -y install zsh
        // Loaded plugins: product-id, subscription-manager
        // Resolving Dependencies
        // --> Running transaction check
        // ---> Package zsh.x86_64 0:5.0.2-7.el7 will be installed
        // --> Finished Dependency Resolution
        // 
        // Dependencies Resolved
        // 
        // ================================================================================
        // Package    Arch          Version               Repository                 Size
        // ================================================================================
        // Installing:
        // zsh        x86_64        5.0.2-7.el7           rhel-7-server-rpms        2.4 M
        // 
        // Transaction Summary
        // ================================================================================
        // Install  1 Package
        // 
        // Total download size: 2.4 M
        // Installed size: 5.6 M
        // Downloading packages:
        // warning: /var/cache/yum/x86_64/7Server/rhel-7-server-rpms/packages/zsh-5.0.2-7.el7.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID fd431d51: NOKEY
        // Public key for zsh-5.0.2-7.el7.x86_64.rpm is not installed
        // Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
        // Importing GPG key 0xFD431D51:
        // Userid     : "Red Hat, Inc. (release key 2) <security@redhat.com>"
        // Fingerprint: 567e 347a d004 4ade 55ba 8a5f 199e 2f91 fd43 1d51
        // Package    : redhat-release-server-7.0-1.el7.x86_64 (@koji-override-0/7.0)
        // From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
        // Importing GPG key 0x2FA658E0:
        // Userid     : "Red Hat, Inc. (auxiliary key) <security@redhat.com>"
        // Fingerprint: 43a6 e49c 4a38 f4be 9abf 2a53 4568 9c88 2fa6 58e0
        // Package    : redhat-release-server-7.0-1.el7.x86_64 (@koji-override-0/7.0)
        // From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release
        // Running transaction check
        // Running transaction test
        // Transaction test succeeded
        // Running transaction
        // Installing : zsh-5.0.2-7.el7.x86_64                                       1/1
        // Verifying  : zsh-5.0.2-7.el7.x86_64                                       1/1
        // 
        // Installed:
        // zsh.x86_64 0:5.0.2-7.el7
        // 
        // Complete!
        installedPackage = true;
    }
    if (!installedPackage)
        log.warning("Skipped attempts to install a package since the rhel-(6|7)-server-rpms repo was not entitled.");
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) ArrayList(java.util.ArrayList) ProductCert(rhsm.data.ProductCert) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) ContentNamespace(rhsm.data.ContentNamespace) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SkipException(org.testng.SkipException) HashSet(java.util.HashSet) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Aggregations

BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)134 Test (org.testng.annotations.Test)91 SkipException (org.testng.SkipException)89 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)88 SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)77 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)55 ArrayList (java.util.ArrayList)44 SubscriptionPool (rhsm.data.SubscriptionPool)28 File (java.io.File)23 ProductSubscription (rhsm.data.ProductSubscription)23 ProductCert (rhsm.data.ProductCert)22 JSONObject (org.json.JSONObject)20 EntitlementCert (rhsm.data.EntitlementCert)16 InstalledProduct (rhsm.data.InstalledProduct)14 BigInteger (java.math.BigInteger)13 List (java.util.List)12 ConsumerCert (rhsm.data.ConsumerCert)11 SyndFeed (com.sun.syndication.feed.synd.SyndFeed)10 Calendar (java.util.Calendar)10 HashMap (java.util.HashMap)10