Search in sources :

Example 66 with ImplementsNitrateTest

use of com.redhat.qe.auto.tcms.ImplementsNitrateTest in project rhsm-qe by RedHatQE.

the class MigrationTests method testRhnMigrateClassicToRhsmWithKeepClassicAndLegacyCredentials.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21891", "RHEL7-51747" }, 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 = "Attempt to execute migration tool rhn-migrate-classic-to-rhsm with --keep-classic AND unnecessary classic credentials --legacy-user/--legacy-password (unnecessary because --keep-classic implies that we do NOT want to deregister from classic)", groups = { "Tier3Tests", "blockedByBug-1180273" }, dependsOnMethods = {}, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRhnMigrateClassicToRhsmWithKeepClassicAndLegacyCredentials() {
    // commit 5df7aaaa69a22b9e3f771971f1aa4e58657c8377
    if (clienttasks.isPackageVersion("subscription-manager-migration", "<", "1.14.3"))
        throw new SkipException("This version of subscription-manager does not support 1180273 - [RFE] rhn-migrate-classic-to-rhsm should allow the user to migrate a system without requiring credentials on RHN Classic");
    String options = "--registration-state=keep";
    // commit 6eded942a7d184ef7ed92bbd94225120ee2f2f20
    if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.14.6"))
        options = "--keep";
    if (sm_rhnHostname.equals(""))
        throw new SkipException("This test requires access to RHN Classic or Satellite 5.");
    clienttasks.unregister(null, null, null, null);
    // register to rhn classic
    String rhnSystemId = clienttasks.registerToRhnClassic(sm_rhnUsername, sm_rhnPassword, sm_rhnHostname);
    Assert.assertEquals(clienttasks.identity(null, null, null, null, null, null, null, null).getStdout().trim(), "server type: RHN Classic", "Subscription Manager recognizes that we are registered classically.");
    // subscribe to more RHN Classic channels (just to add a little unnecessary fun)
    List<String> filteredRhnAvailableChildChannels = new ArrayList<String>(rhnAvailableChildChannels);
    // /*debugTesting*/		addRhnClassicChannels(sm_rhnUsername, sm_rhnPassword, Arrays.asList("rhel-x86_64-server-optional-7-beta"));	// only add 1 child channel to avoid "You are subscribed to channels that have conflicting product certificates."
    for (String rhnAvailableChildChannel : rhnAvailableChildChannels) {
        if (rhnAvailableChildChannel.contains("-beta")) {
            filteredRhnAvailableChildChannels.remove(rhnAvailableChildChannel);
        }
    }
    // /*debugTesting*/		addRhnClassicChannels(sm_rhnUsername, sm_rhnPassword, Arrays.asList("rhel-x86_64-server-v2vwin-7-beta-debuginfo"));
    for (String rhnAvailableChildChannel : rhnAvailableChildChannels) {
        if (!channelsToProductCertFilenamesMap.containsKey(rhnAvailableChildChannel)) {
            filteredRhnAvailableChildChannels.remove(rhnAvailableChildChannel);
        }
    }
    // only add 1 child channel to reduce the chance of "You are subscribed to channels that have conflicting product certificates."
    addRhnClassicChannels(sm_rhnUsername, sm_rhnPassword, getRandomSubsetOfList(filteredRhnAvailableChildChannels, /*5*/
    1));
    // attempt to run rhn-migrate-classic-to-rhsm
    // TODO not sure how valid this test is, but it does throw an error.  Maybe I should explicitly call subscription-manager config on the server hostname port prefix
    SSHCommandResult sshCommandResult = executeRhnMigrateClassicToRhsm(options + " " + /*"--destination-url="+originalServerHostname+":"+originalServerPort+originalServerPrefix+" "+*/
    "--legacy-user=" + sm_rhnUsername + " " + "--legacy-password=" + sm_rhnPassword, null, null, sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null);
    // [root@jsefler-os6 ~]# rhn-migrate-classic-to-rhsm --registration-state=keep --legacy-user=qa@redhat.com --legacy-password=REDACTED
    // Unable to connect to certificate server: Invalid credentials..  See /var/log/rhsm/rhsm.log for more details.
    // [root@jsefler-os6 ~]# echo $?
    // 1
    // verify the migration was successful
    // WARNING: asserting this exit code is misleading because it is the exit code from the rhn-migrate-classic-to-rhsm.tcl script which is a wrapper to rhn-migrate-classic-to-rhsm which could exit with a different code
    Assert.assertEquals(sshCommandResult.getExitCode(), Integer.valueOf(0), "ExitCode from call to '" + rhnMigrateTool + "' after attempting to migrate with options '" + options + "'.");
    // verify that we are newly registered to RHSM
    Assert.assertNotNull(clienttasks.getCurrentConsumerCert(), "Confirmed that the system is newly registered with Subscription Manager after migrating from RHN Classic using '" + rhnMigrateTool + "'.");
    // verify that we are still classically registered to RHN
    Assert.assertTrue(clienttasks.isRhnSystemIdRegistered(sm_rhnUsername, sm_rhnPassword, sm_rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is STILL registered on the RHN Classic server (because we passed an option to keep the classic registration).");
    // verify that we were warned with the interoperability message
    Assert.assertTrue(sshCommandResult.getStdout().trim().contains(clienttasks.msg_InteroperabilityWarning), "The expected stdout result from a call to '" + rhnMigrateTool + "' with the option to keep the classic registration should warn the user with the interoperability message: " + clienttasks.msg_InteroperabilityWarning);
    // Now attempt the same migration while supplying the destination credentials on the command line instead of being prompted...
    clienttasks.unregister(null, null, null, null);
    // TODO not sure how valid this test is.  Maybe I should explicitly call subscription-manager config on the server hostname port prefix
    sshCommandResult = executeRhnMigrateClassicToRhsm(options + " " + /*"--destination-url="+originalServerHostname+":"+originalServerPort+originalServerPrefix+" "+*/
    "--legacy-user=" + sm_rhnUsername + " " + "--legacy-password=" + sm_rhnPassword + " " + "--destination-user=" + sm_clientUsername + " " + "--destination-password=" + sm_clientPassword + " " + (sm_clientOrg != null ? "--org=" + sm_clientOrg : ""), /*sm_rhnUsername*/
    null, /*sm_rhnPassword*/
    null, null, null, null, null, null);
    Assert.assertEquals(sshCommandResult.getExitCode(), Integer.valueOf(0), "ExitCode from call to '" + rhnMigrateTool + "' after attempting to use the option to keep the classic registration");
    Assert.assertNotNull(clienttasks.getCurrentConsumerCert(), "Confirmed that the system is newly registered with Subscription Manager after migrating from RHN Classic using '" + rhnMigrateTool + "'.");
    Assert.assertTrue(clienttasks.isRhnSystemIdRegistered(sm_rhnUsername, sm_rhnPassword, sm_rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is STILL registered on the RHN Classic server (because we passed an option to keep the classic registration).");
    Assert.assertTrue(sshCommandResult.getStdout().trim().contains(clienttasks.msg_InteroperabilityWarning), "The expected stdout result from a call to '" + rhnMigrateTool + "' with the option to keep the classic registration should warn the user with the interoperability message: " + clienttasks.msg_InteroperabilityWarning);
}
Also used : SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ArrayList(java.util.ArrayList) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 67 with ImplementsNitrateTest

use of com.redhat.qe.auto.tcms.ImplementsNitrateTest in project rhsm-qe by RedHatQE.

the class MigrationTests method testRhnMigrateClassicToRhsmWithKeepClassic.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21892", "RHEL7-51748" }, 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 = "Attempt to execute migration tool rhn-migrate-classic-to-rhsm with --keep classic which implies that we do not want to deregister from classic which will result in dual interoperability registration.", groups = { "Tier3Tests", "blockedByBug-1180273" }, dependsOnMethods = {}, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRhnMigrateClassicToRhsmWithKeepClassic() {
    // commit 5df7aaaa69a22b9e3f771971f1aa4e58657c8377
    if (clienttasks.isPackageVersion("subscription-manager-migration", "<", "1.14.3"))
        throw new SkipException("This version of subscription-manager does not support 1180273 - [RFE] rhn-migrate-classic-to-rhsm should allow the user to migrate a system without requiring credentials on RHN Classic");
    String options = "--registration-state=keep";
    // commit 6eded942a7d184ef7ed92bbd94225120ee2f2f20
    if (clienttasks.isPackageVersion("subscription-manager-migration", ">=", "1.14.6"))
        options = "--keep";
    if (sm_rhnHostname.equals(""))
        throw new SkipException("This test requires access to RHN Classic or Satellite 5.");
    clienttasks.unregister(null, null, null, null);
    // register to rhn classic
    String rhnSystemId = clienttasks.registerToRhnClassic(sm_rhnUsername, sm_rhnPassword, sm_rhnHostname);
    Assert.assertEquals(clienttasks.identity(null, null, null, null, null, null, null, null).getStdout().trim(), "server type: RHN Classic", "Subscription Manager recognizes that we are registered classically.");
    // subscribe to more RHN Classic channels (just to add a little unnecessary fun)
    List<String> filteredRhnAvailableChildChannels = new ArrayList<String>(rhnAvailableChildChannels);
    // /*debugTesting*/		addRhnClassicChannels(sm_rhnUsername, sm_rhnPassword, Arrays.asList("rhel-x86_64-server-optional-7-beta"));	// only add 1 child channel to avoid "You are subscribed to channels that have conflicting product certificates."
    for (String rhnAvailableChildChannel : rhnAvailableChildChannels) {
        if (rhnAvailableChildChannel.contains("-beta")) {
            filteredRhnAvailableChildChannels.remove(rhnAvailableChildChannel);
        }
    }
    // /*debugTesting*/		addRhnClassicChannels(sm_rhnUsername, sm_rhnPassword, Arrays.asList("rhel-x86_64-server-v2vwin-7-beta-debuginfo"));
    for (String rhnAvailableChildChannel : rhnAvailableChildChannels) {
        if (!channelsToProductCertFilenamesMap.containsKey(rhnAvailableChildChannel)) {
            filteredRhnAvailableChildChannels.remove(rhnAvailableChildChannel);
        }
    }
    // only add 1 child channel to reduce the chance of "You are subscribed to channels that have conflicting product certificates."
    addRhnClassicChannels(sm_rhnUsername, sm_rhnPassword, getRandomSubsetOfList(filteredRhnAvailableChildChannels, /*5*/
    1));
    // attempt to run rhn-migrate-classic-to-rhsm
    SSHCommandResult sshCommandResult = executeRhnMigrateClassicToRhsm(options + " " + "--destination-url=" + originalServerHostname + ":" + originalServerPort + originalServerPrefix, null, null, sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null);
    // [root@jsefler-os6 ~]# rhn-migrate-classic-to-rhsm --registration-state=keep --destination-url=subscription.rhn.stage.redhat.com:443/subscription
    // Destination username: stage_auto_testuser
    // Destination password:
    // 
    // Retrieving existing legacy subscription information...
    // 
    // +-----------------------------------------------------+
    // System is currently subscribed to these legacy channels:
    // +-----------------------------------------------------+
    // rhel-x86_64-server-6
    // 
    // +-----------------------------------------------------+
    // Installing product certificates for these legacy channels:
    // +-----------------------------------------------------+
    // rhel-x86_64-server-6
    // 
    // Product certificates installed successfully to /etc/pki/product.
    // 
    // Attempting to register system to destination server...
    // WARNING
    // 
    // This system has already been registered with Red Hat using RHN Classic.
    // 
    // Your system is being registered again using Red Hat Subscription Management. Red Hat recommends that customers only register once.
    // 
    // To learn how to unregister from either service please consult this Knowledge Base Article: https://access.redhat.com/kb/docs/DOC-45563
    // The system has been registered with ID: 19ff59fe-c824-4acb-bd8b-ef843dd7d149
    // 
    // Installed Product Current Status:
    // Product Name: Red Hat Enterprise Linux Server
    // Status:       Subscribed
    // 
    // System 'jsefler-os6' successfully registered.
    // 
    // [root@jsefler-os6 ~]# echo $?
    // 0
    // verify the migration was successful
    // WARNING: asserting this exit code is misleading because it is the exit code from the rhn-migrate-classic-to-rhsm.tcl script which is a wrapper to rhn-migrate-classic-to-rhsm which could exit with a different code
    Assert.assertEquals(sshCommandResult.getExitCode(), Integer.valueOf(0), "ExitCode from call to '" + rhnMigrateTool + "' after attempting to migrate with options '" + options + "'.");
    // verify that we are newly registered to RHSM
    Assert.assertNotNull(clienttasks.getCurrentConsumerCert(), "Confirmed that the system is newly registered with Subscription Manager after migrating from RHN Classic using '" + rhnMigrateTool + "'.");
    // verify that we are still classically registered to RHN
    Assert.assertTrue(clienttasks.isRhnSystemIdRegistered(sm_rhnUsername, sm_rhnPassword, sm_rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is STILL registered on the RHN Classic server (because we passed an option to keep the classic registration).");
    // verify that we were warned with the interoperability message
    Assert.assertTrue(sshCommandResult.getStdout().trim().contains(clienttasks.msg_InteroperabilityWarning), "The expected stdout result from a call to '" + rhnMigrateTool + "' with the option to keep the classic registration should warn the user with the interoperability message: " + clienttasks.msg_InteroperabilityWarning);
    // Now attempt the same migration while supplying the destination credentials on the command line instead of being prompted...
    clienttasks.unregister(null, null, null, null);
    sshCommandResult = executeRhnMigrateClassicToRhsm(options + " " + "--destination-url=" + originalServerHostname + ":" + originalServerPort + originalServerPrefix + " " + "--destination-user=" + sm_clientUsername + " " + "--destination-password=" + sm_clientPassword + " " + (sm_clientOrg != null ? "--org=" + sm_clientOrg : ""), null, null, null, null, null, null, null);
    Assert.assertEquals(sshCommandResult.getExitCode(), Integer.valueOf(0), "ExitCode from call to '" + rhnMigrateTool + "' after attempting to use the option to keep the classic registration");
    Assert.assertNotNull(clienttasks.getCurrentConsumerCert(), "Confirmed that the system is newly registered with Subscription Manager after migrating from RHN Classic using '" + rhnMigrateTool + "'.");
    Assert.assertTrue(clienttasks.isRhnSystemIdRegistered(sm_rhnUsername, sm_rhnPassword, sm_rhnHostname, rhnSystemId), "Confirmed that rhn systemId '" + rhnSystemId + "' is STILL registered on the RHN Classic server (because we passed an option to keep the classic registration).");
    Assert.assertTrue(sshCommandResult.getStdout().trim().contains(clienttasks.msg_InteroperabilityWarning), "The expected stdout result from a call to '" + rhnMigrateTool + "' with the option to keep the classic registration should warn the user with the interoperability message: " + clienttasks.msg_InteroperabilityWarning);
}
Also used : SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ArrayList(java.util.ArrayList) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 68 with ImplementsNitrateTest

use of com.redhat.qe.auto.tcms.ImplementsNitrateTest in project rhsm-qe by RedHatQE.

the class MigrationTests method testInstallNumMigrateToRhsmWithInvalidInstNumber.

@TestDefinition(projectID = {/*Project.RHEL5*/
}, testCaseID = {})
@Test(description = "Execute migration tool install-num-migrate-to-rhsm with a bad length install-num (expecting 16 chars long)", groups = { "Tier3Tests" }, dependsOnMethods = {}, dataProvider = "InstallNumMigrateToRhsmWithInvalidInstNumberData", enabled = true)
@ImplementsNitrateTest(caseId = 130760)
public void testInstallNumMigrateToRhsmWithInvalidInstNumber(Object bugzilla, String command, Integer expectedExitCode, String expectedStdout, String expectedStderr) {
    if (!clienttasks.redhatReleaseX.equals("5"))
        throw new SkipException("This test is applicable to RHEL5 only.");
    if (clienttasks.isPackageVersion("subscription-manager-migration", ">", "1.11.3-4") && clienttasks.redhatReleaseX.equals("5")) {
        throw new SkipException("Due to bug 1092754, the migration tool '" + installNumTool + "' has been removed from RHEL5.");
    }
    SSHCommandResult result = client.runCommandAndWait(command);
    if (expectedStdout != null)
        Assert.assertEquals(result.getStdout().trim(), expectedStdout, "Stdout from running :" + command);
    if (expectedStderr != null)
        Assert.assertEquals(result.getStderr().trim(), expectedStderr, "Stderr from running :" + command);
    // TEMPORARY WORKAROUND FOR BUG
    String bugId = "783542";
    boolean invokeWorkaroundWhileBugIsOpen = true;
    try {
        if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
        } else {
            invokeWorkaroundWhileBugIsOpen = false;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    String bugPkg = "subscription-manager-migration";
    // RHEL58
    String bugVer = "subscription-manager-migration-0.98";
    try {
        if (clienttasks.installedPackageVersionMap.get(bugPkg).contains(bugVer) && !invokeWorkaroundWhileBugIsOpen) {
            log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + " which has NOT been fixed in this installed version of " + bugVer + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
            SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
            invokeWorkaroundWhileBugIsOpen = true;
        }
    } catch (BugzillaAPIException be) {
    /* ignore exception */
    } catch (RuntimeException re) {
    /* ignore exception */
    }
    if (invokeWorkaroundWhileBugIsOpen) {
        log.warning("Skipping the exitCode assertion from running: " + command);
    } else // END OF WORKAROUND
    if (expectedExitCode != null)
        Assert.assertEquals(result.getExitCode(), expectedExitCode, "ExitCode from running :" + command);
}
Also used : SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SkipException(org.testng.SkipException) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 69 with ImplementsNitrateTest

use of com.redhat.qe.auto.tcms.ImplementsNitrateTest in project rhsm-qe by RedHatQE.

the class MigrationTests method testRhnMigrateClassicToRhsmShouldAutomaticallyEnableYumPluginsWhenAutoEnableIsOn.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-47943", "RHEL7-109986" }, // role= DefTypes.Role.VERIFIES)},
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 = "Verify that the yum plugins for /etc/yum/pluginconf.d/product-id.conf and /etc/yum/pluginconf.d/subscription-manager.conf are automatically enabled by an execution of rhn-migrate-classic-to-rhsm when rhsm.auto_enable_yum_plugins is configured on.", groups = { "Tier3Tests", "blockedByBug-1466453", "testRhnMigrateClassicToRhsmShouldAutomaticallyEnableYumPluginsWhenAutoEnableIsOn" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRhnMigrateClassicToRhsmShouldAutomaticallyEnableYumPluginsWhenAutoEnableIsOn() {
    // this bug is specifically designed to test Bug 1466453 - [RFE] rhn-migrate-classic-to-rhsm should ensure subscription-manager yum plugin is enabled
    if (clienttasks.isPackageVersion("subscription-manager", "<", "1.20.2-1")) {
        // commit 7b2b89c7ba4fbf464dd988e12675b2b763007f2c 	1466453 - [RFE] rhn-migrate-classic-to-rhsm should ensure subscription-manager yum plugin is enabled
        throw new SkipException("This test applies a newer version of subscription-manager that includes an implementation for Bug 1466453 - [RFE] rhn-migrate-classic-to-rhsm should ensure subscription-manager yum plugin is enabled");
    }
    if (sm_rhnHostname.equals(""))
        throw new SkipException("This test requires access to RHN Classic or Satellite 5.");
    clienttasks.unregister(null, null, null, null);
    resetDefaultConfigurationsForYumPluginsAndRhsmAutoEnableYumPlugins();
    // randomly disable one or both /etc/yum/pluginconf.d/product-id.conf and /etc/yum/pluginconf.d/subscription-manager.conf
    if (getRandomBoolean()) {
        clienttasks.updateConfFileParameter(clienttasks.yumPluginConfFileForProductId, "enabled", "0");
        clienttasks.updateConfFileParameter(clienttasks.yumPluginConfFileForSubscriptionManager, "enabled", String.valueOf(getRandInt() % 2));
    } else {
        clienttasks.updateConfFileParameter(clienttasks.yumPluginConfFileForSubscriptionManager, "enabled", "false");
        clienttasks.updateConfFileParameter(clienttasks.yumPluginConfFileForProductId, "enabled", "true");
        // TEMPORARY WORKAROUND
        boolean invokeWorkaroundWhileBugIsOpen = true;
        // Bug 1489917 - disabling yum plugins using "false" (rather than "0") causes traceback: invalid literal for int() with base 10: 'false'
        String bugId = "1489917";
        try {
            if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
                log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
                SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
            } else {
                invokeWorkaroundWhileBugIsOpen = false;
            }
        } catch (BugzillaAPIException be) {
        /* ignore exception */
        } catch (RuntimeException re) {
        /* ignore exception */
        }
        if (invokeWorkaroundWhileBugIsOpen) {
            clienttasks.updateConfFileParameter(clienttasks.yumPluginConfFileForSubscriptionManager, "enabled", "0");
            clienttasks.updateConfFileParameter(clienttasks.yumPluginConfFileForProductId, "enabled", "1");
        }
    // END OF WORKAROUND
    }
    String yumPluginConfFileForProductIdEnabledString = clienttasks.getConfFileParameter(clienttasks.yumPluginConfFileForProductId, "enabled");
    String yumPluginConfFileForSubscriptionManagerEnabledString = clienttasks.getConfFileParameter(clienttasks.yumPluginConfFileForSubscriptionManager, "enabled");
    Boolean yumPluginConfFileForProductIdEnabled = Boolean.valueOf(yumPluginConfFileForProductIdEnabledString);
    Boolean yumPluginConfFileForSubscriptionManagerEnabled = Boolean.valueOf(yumPluginConfFileForSubscriptionManagerEnabledString);
    if (yumPluginConfFileForProductIdEnabledString.equals("1")) {
        yumPluginConfFileForProductIdEnabled = true;
    } else if (yumPluginConfFileForProductIdEnabledString.equals("0")) {
        yumPluginConfFileForProductIdEnabled = false;
    }
    if (yumPluginConfFileForSubscriptionManagerEnabledString.equals("1")) {
        yumPluginConfFileForSubscriptionManagerEnabled = true;
    } else if (yumPluginConfFileForSubscriptionManagerEnabledString.equals("0")) {
        yumPluginConfFileForSubscriptionManagerEnabled = false;
    }
    // register to rhn classic
    String rhnSystemId = clienttasks.registerToRhnClassic(sm_rhnUsername, sm_rhnPassword, sm_rhnHostname);
    // attempt to run rhn-migrate-classic-to-rhsm
    String options = "";
    SSHCommandResult sshCommandResult = executeRhnMigrateClassicToRhsm(options, sm_rhnUsername, sm_rhnPassword, sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null);
    String command = "rhn-migrate-classic-to-rhsm";
    // [root@jsefler-rhel7 ~]# rhn-migrate-classic-to-rhsm --legacy-user=rhsm-client --destination-user=testuser1
    // Legacy password:
    // Destination password:
    // Org: admin
    // 
    // Retrieving existing legacy subscription information...
    // 
    // +-----------------------------------------------------+
    // System is currently subscribed to these legacy channels:
    // +-----------------------------------------------------+
    // rhel-x86_64-server-7
    // 
    // +-----------------------------------------------------+
    // Installing product certificates for these legacy channels:
    // +-----------------------------------------------------+
    // rhel-x86_64-server-7
    // 
    // 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...
    // rhnsd.service is not a native service, redirecting to /sbin/chkconfig.
    // Executing /sbin/chkconfig rhnsd off
    // 
    // Attempting to register system to destination server...
    // WARNING
    // 
    // The yum plugins: /etc/yum/pluginconf.d/subscription-manager.conf were automatically enabled for the benefit of Red Hat Subscription Management. If not desired, use "subscription-manager config --rhsm.auto_enable_yum_plugins=0" to block this behavior.
    // 
    // Registering to: jsefler-candlepin.usersys.redhat.com:8443/candlepin
    // The system has been registered with ID: ed2d6c19-bde5-4e8c-b274-109d8d477723
    // The registered system name is: jsefler-rhel7.usersys.redhat.com
    // Installed Product Current Status:
    // 
    // Product Name: Red Hat Enterprise Linux Server
    // Status:       Not Subscribed
    // 
    // Unable to find available subscriptions for all your installed products.
    // System 'jsefler-rhel7.usersys.redhat.com' successfully registered.
    // 
    // [root@jsefler-rhel7 ~]# echo $?
    // 0
    // verify the migration was successful
    // WARNING: asserting this exit code is misleading because it is the exit code from the rhn-migrate-classic-to-rhsm.tcl script which is a wrapper to rhn-migrate-classic-to-rhsm which could exit with a different code
    Assert.assertEquals(sshCommandResult.getExitCode(), Integer.valueOf(0), "ExitCode from call to '" + rhnMigrateTool + "' after attempting to migrate with options '" + options + "'.");
    // verify that we are newly registered to RHSM
    Assert.assertNotNull(clienttasks.getCurrentConsumerCert(), "Confirmed that the system is newly registered with Subscription Manager after migrating from RHN Classic using '" + rhnMigrateTool + "'.");
    // assert the results contain the expected WARNING message for enabling plugins
    String expectedWarningMsg = "WARNING" + "\n\n" + "The yum plugins: PLUGINS were automatically enabled for the benefit of Red Hat Subscription Management. If not desired, use \"subscription-manager config --rhsm.auto_enable_yum_plugins=0\" to block this behavior.";
    // ensure expectedWarningMsg appears on it's own line
    expectedWarningMsg = "\n" + expectedWarningMsg + "\n";
    if (!yumPluginConfFileForSubscriptionManagerEnabled)
        expectedWarningMsg = expectedWarningMsg.replaceFirst("PLUGINS", clienttasks.yumPluginConfFileForSubscriptionManager + ", PLUGINS");
    if (!yumPluginConfFileForProductIdEnabled)
        expectedWarningMsg = expectedWarningMsg.replaceFirst("PLUGINS", clienttasks.yumPluginConfFileForProductId + ", PLUGINS");
    // strip out my regex substring
    expectedWarningMsg = expectedWarningMsg.replaceFirst(", PLUGINS", "");
    Assert.assertTrue(sshCommandResult.getStdout().contains(expectedWarningMsg), "The stdout from running '" + command + "' contains the expected warning message '" + expectedWarningMsg + "' when at least one yum plugin is disabled and rhsm.auto_enable_yum_plugins is configured on.");
    // assert that both plugins were enabled
    String enabledValue;
    enabledValue = clienttasks.getConfFileParameter(clienttasks.yumPluginConfFileForProductId, "enabled");
    Assert.assertTrue(enabledValue.toLowerCase().matches("1|true"), "Expecting yum config file '" + clienttasks.yumPluginConfFileForProductId + "' to be enabled after running '" + command + "' with rhsm.auto_enable_yum_plugins configured on.  Actual enabled=" + enabledValue);
    enabledValue = clienttasks.getConfFileParameter(clienttasks.yumPluginConfFileForSubscriptionManager, "enabled");
    Assert.assertTrue(enabledValue.toLowerCase().matches("1|true"), "Expecting yum config file '" + clienttasks.yumPluginConfFileForSubscriptionManager + "' to be enabled after running '" + command + "' with rhsm.auto_enable_yum_plugins configured on.  Actual enabled=" + enabledValue);
}
Also used : SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SkipException(org.testng.SkipException) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 70 with ImplementsNitrateTest

use of com.redhat.qe.auto.tcms.ImplementsNitrateTest 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)

Aggregations

ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)267 Test (org.testng.annotations.Test)267 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)244 SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)146 SkipException (org.testng.SkipException)125 SubscriptionPool (rhsm.data.SubscriptionPool)71 ArrayList (java.util.ArrayList)62 BigInteger (java.math.BigInteger)53 BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)42 ProductSubscription (rhsm.data.ProductSubscription)42 File (java.io.File)36 JSONObject (org.json.JSONObject)33 EntitlementCert (rhsm.data.EntitlementCert)32 ProductCert (rhsm.data.ProductCert)32 InstalledProduct (rhsm.data.InstalledProduct)15 ConsumerCert (rhsm.data.ConsumerCert)14 HashMap (java.util.HashMap)11 Calendar (java.util.Calendar)10 List (java.util.List)10 JSONArray (org.json.JSONArray)8