Search in sources :

Example 61 with SSHCommandResult

use of com.redhat.qe.tools.SSHCommandResult in project rhsm-qe by RedHatQE.

the class ActivationKeyTests method testRegisterWithActivationKeyContainingPoolForWhichNotEnoughQuantityRemains.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21796", "RHEL7-51613" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.NEGATIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "create an activation key with a valid quantity and attempt to register with it when not enough entitlements remain", groups = { "Tier3Tests" }, dataProvider = "getAllMultiEntitlementJSONPoolsData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRegisterWithActivationKeyContainingPoolForWhichNotEnoughQuantityRemains(Object blockedByBug, String keyName, JSONObject jsonPool) throws JSONException, Exception {
    // first, figure out how many entitlements remain
    int quantityAvail = jsonPool.getInt("quantity") - jsonPool.getInt("consumed");
    if (quantityAvail < 1)
        throw new SkipException("Cannot do this test until there is an available entitlement for pool '" + jsonPool.getString("id") + "'.");
    // skip this pool when our candlepin is standalone and this is a pool_derived virt_only pool (for which we have not registered our host system)
    if (servertasks.statusStandalone) {
        String pool_derived = CandlepinTasks.getPoolAttributeValue(jsonPool, "pool_derived");
        String virt_only = CandlepinTasks.getPoolAttributeValue(jsonPool, "virt_only");
        if (pool_derived != null && virt_only != null && Boolean.valueOf(pool_derived) && Boolean.valueOf(virt_only)) {
            throw new SkipException("Skipping this virt_only derived_pool '" + jsonPool.getString("id") + "' on a standalone candlepin server since our system's host is not registered.");
        }
    }
    // now consume an entitlement from the pool
    String requires_consumer_type = CandlepinTasks.getPoolProductAttributeValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id"), "requires_consumer_type");
    if (requires_consumer_type != null) {
        if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.20.2-1")) {
            // post commit e0c34a729e9e347ab1e0f4f5fa656c8b20205fdf RFE Bug 1461003: Deprecate --type option on register command
            throw new SkipException("Due to RFE Bug 1461003, subscription-manager can no longer register with --type which prevents registration using an --activationkey for a pool that has attribute \"requires_consumer_type\":\"" + requires_consumer_type + "\"");
        }
    }
    ConsumerType consumerType = requires_consumer_type == null ? null : ConsumerType.valueOf(requires_consumer_type);
    String consumer1Id = clienttasks.getCurrentConsumerId(clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, consumerType, null, null, null, null, null, (String) null, null, null, null, true, null, null, null, null, null));
    SubscriptionPool subscriptionPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", jsonPool.getString("id"), clienttasks.getCurrentlyAllAvailableSubscriptionPools());
    clienttasks.subscribe(null, null, jsonPool.getString("id"), null, null, null, null, null, null, null, null, null, null);
    // remember the consuming consumerId
    // String consumer1Id = clienttasks.getCurrentConsumerId();
    systemConsumerIds.add(consumer1Id);
    // clean the system of all data (will not return the consumed entitlement)
    clienttasks.clean();
    // assert that the current pool recognizes an increment in consumption
    JSONObject jsonCurrentPool = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/pools/" + jsonPool.getString("id")));
    // Assert.assertEquals(jsonCurrentPool.getInt("consumed"),jsonPool.getInt("consumed")+1,"The consumed entitlement from Pool '"+jsonPool.getString("id")+"' has incremented by one to an expected total of '"+(jsonPool.getInt("consumed")+1)+"' consumed.");	// valid before Bug 1008557 and Bug 1008647
    // when subscriptionPool.suggested is zero, subscribe should still attach 1.
    Integer suggested = subscriptionPool.suggested;
    // when subscriptionPool.suggested is zero, subscribe should still attach 1.
    Integer expectedIncrement = suggested > 0 ? suggested : 1;
    Assert.assertEquals(jsonCurrentPool.getInt("consumed"), jsonPool.getInt("consumed") + expectedIncrement, "The consumed entitlement from Pool '" + jsonPool.getString("id") + "' has incremented by the suggested quantity '" + subscriptionPool.suggested + "' to an expected total of '" + (jsonPool.getInt("consumed") + expectedIncrement) + "' consumed (Except when suggested quantity is zero, then subscribe should still attach one entitlement).");
    // finally do the test...
    // create an activation key, add the current pool to the activation key with this valid quantity, and attempt to register with it.
    SSHCommandResult registerResult = testRegisterWithActivationKeyContainingPoolWithQuantity(blockedByBug, keyName, jsonCurrentPool, quantityAvail);
    String expectedStderr = String.format("No entitlements are available from the pool with id '%s'.", jsonCurrentPool.getString("id"));
    // string changed by bug 876758
    expectedStderr = String.format("No subscriptions are available from the pool with id '%s'.", jsonCurrentPool.getString("id"));
    if (!clienttasks.workaroundForBug876764(sm_serverType))
        expectedStderr = String.format("No subscriptions are available from the pool with ID '%s'.", jsonCurrentPool.getString("id"));
    if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.3.1-1")) {
        // commit 0d5fefcfa8c1c2485921d2dee6633879b1e06931 Correct incorrect punctuation in user messages
        expectedStderr = String.format("No subscriptions are available from the pool with ID \"%s\".", jsonCurrentPool.getString("id"));
    }
    if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">", "0.9.30-1")) {
        log.info("Prior to candlepin version 0.9.30-1, the expected feedback was: " + expectedStderr);
        // Follows: candlepin-0.9.30-1	// https://github.com/candlepin/candlepin/commit/bcb4b8fd8ee009e86fc9a1a20b25f19b3dbe6b2a
        expectedStderr = "No activation key was applied successfully.";
    }
    if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.2.0-1")) {
        // candlepin commit 08bcd6829cb4c89f737b8b77cbfdb85600a47933   bug 1440924: Adjust message when activation key registration fails
        log.info("Prior to candlepin version 2.2.0-1 , the expected feedback was: " + expectedStderr);
        expectedStderr = "None of the subscriptions on the activation key were available for attaching.";
    }
    Integer expectedExitCode = new Integer(255);
    // EX_SOFTWARE	// post commit df95529a5edd0be456b3528b74344be283c4d258 bug 1119688
    if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.13.8-1"))
        expectedExitCode = new Integer(70);
    Assert.assertEquals(registerResult.getStderr().trim(), expectedStderr, "Registering a with an activationKey containing a pool for which not enough entitlements remain should fail.");
    Assert.assertEquals(registerResult.getExitCode(), expectedExitCode, "The exitCode from registering with an activationKey containing a pool for which non enough entitlements remain should fail.");
    // make sure there is no consumer cert - register with activation key should be 100% successful - if any one part fails, the whole operation fails
    Assert.assertNull(clienttasks.getCurrentConsumerCert(), "There should be no consumer cert on the system when register with activation key fails.");
}
Also used : JSONObject(org.json.JSONObject) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SkipException(org.testng.SkipException) ConsumerType(rhsm.base.ConsumerType) SubscriptionPool(rhsm.data.SubscriptionPool) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 62 with SSHCommandResult

use of com.redhat.qe.tools.SSHCommandResult in project rhsm-qe by RedHatQE.

the class ActivationKeyTests method testRegisterWithActivationKeyContainingMultiplePools.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21795", "RHEL7-51612" }, 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 = "create an activation key and add many pools to it and then register asserting all the pools get consumed", groups = { "Tier3Tests", "blockedByBug-1040101" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRegisterWithActivationKeyContainingMultiplePools() throws JSONException, Exception {
    // get all of the pools belonging to ownerKey
    JSONArray jsonPools = new JSONArray(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/owners/" + sm_clientOrg + "/pools?listall=true"));
    if (!(jsonPools.length() > 1))
        throw new SkipException("This test requires more than one pool for org '" + sm_clientOrg + "'.");
    jsonPools = clienttasks.workaroundForBug1040101(jsonPools);
    // create an activation key
    String activationKeyName = String.format("ActivationKey%sWithMultiplePoolsForOrg_%s", System.currentTimeMillis(), sm_clientOrg);
    Map<String, String> mapActivationKeyRequest = new HashMap<String, String>();
    mapActivationKeyRequest.put("name", activationKeyName);
    JSONObject jsonActivationKeyRequest = new JSONObject(mapActivationKeyRequest);
    JSONObject jsonActivationKey = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/owners/" + sm_clientOrg + "/activation_keys", jsonActivationKeyRequest.toString()));
    // process each of the pools adding them to the activation key
    Integer addQuantity = null;
    JSONArray jsonPoolsAddedToActivationKey = new JSONArray();
    boolean isSystemVirtual = Boolean.valueOf(clienttasks.getFactValue("virt.is_guest"));
    for (int i = 0; i < jsonPools.length(); i++) {
        JSONObject jsonPool = (JSONObject) jsonPools.get(i);
        // for the purpose of this test, skip pools with no available entitlements (consumed>=quantity) (quantity=-1 is unlimited)
        if (jsonPool.getInt("quantity") > 0 && jsonPool.getInt("consumed") >= jsonPool.getInt("quantity"))
            continue;
        // for the purpose of this test, skip non-system pools otherwise the register will fail with "Consumers of this type are not allowed to subscribe to the pool with id '8a90f8c631ab7ccc0131ab7e46ca0619'."
        if (!CandlepinTasks.isPoolProductConsumableByConsumerType(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id"), ConsumerType.system))
            continue;
        // for the purpose of this test, skip physical_only pools when system is virtual otherwise the register will fail with "Pool is restricted to physical systems: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (isSystemVirtual && CandlepinTasks.isPoolRestrictedToPhysicalSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        // for the purpose of this test, skip virt_only pools when system is physical otherwise the register will fail with "Pool is restricted to virtual guests: '8a9086d344549b0c0144549bf9ae0dd4'."
        if (!isSystemVirtual && CandlepinTasks.isPoolRestrictedToVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id")))
            continue;
        /* skipping pools that are not NORMAL is more reliable than this...
			// for the purpose of this test, skip virt_only derived_pool when server is standalone otherwise the register will fail with "Unable to entitle consumer to the pool with id '8a90f85733d86b130133d88c09410e5e'.: virt.guest.host.does.not.match.pool.owner"
			//if (servertasks.statusStandalone) {	// 5/29/2014 removed this check, I can't remember why I originally set it 
			// for the purpose of this test, skip virt_only derived_pool when otherwise the register will fail with "Guest's host does not match owner of pool: '8a908775463fef2301464072ee68496e'."
			if (true) {
				String pool_derived = CandlepinTasks.getPoolAttributeValue(jsonPool, "pool_derived");
				String virt_only = CandlepinTasks.getPoolAttributeValue(jsonPool, "virt_only");
				if (pool_derived!=null && virt_only!=null && Boolean.valueOf(pool_derived) && Boolean.valueOf(virt_only)) {
					continue;
				}
			}
			*/
        // for the purpose of this test, skip pools that are not NORMAL (eg. BONUS, ENTITLEMENT_DERIVED, STACK_DERIVED)
        String poolType = (String) CandlepinTasks.getPoolValue(sm_clientUsername, sm_clientPassword, sm_serverUrl, jsonPool.getString("id"), "type");
        if (!poolType.equals("NORMAL"))
            continue;
        // add the pool to the activation key
        JSONObject jsonResult = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/activation_keys/" + jsonActivationKey.getString("id") + "/pools/" + jsonPool.getString("id") + (addQuantity == null ? "" : "?quantity=" + addQuantity), null));
        // if (clienttasks.isVersion(servertasks.statusVersion, ">", "0.9.30-1")) the POST now returns the jsonActivationKey and formerly returned the jsonPoolAddedToActivationKey	// candlepin commit 82b9af5dc2c63b58447366e680fcf6f156c6049f
        if (jsonResult.has("displayMessage")) {
            Assert.fail("Failed to add pool '" + jsonPool.getString("productId") + "' '" + jsonPool.getString("id") + "' to activation key '" + jsonActivationKey.getString("id") + "'.  DisplayMessage: " + jsonResult.getString("displayMessage"));
        }
        jsonPoolsAddedToActivationKey.put(jsonPool);
    }
    if (addQuantity == null)
        addQuantity = 1;
    jsonActivationKey = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/activation_keys/" + jsonActivationKey.getString("id")));
    Assert.assertTrue(jsonActivationKey.getJSONArray("pools").length() > 0, "MultiplePools have been added to the activation key: " + jsonActivationKey);
    Assert.assertEquals(jsonActivationKey.getJSONArray("pools").length(), jsonPoolsAddedToActivationKey.length(), "The number of attempted pools added equals the number of pools retrieved from the activation key: " + jsonActivationKey);
    // register with the activation key
    SSHCommandResult registerResult = clienttasks.register(null, null, sm_clientOrg, null, null, null, null, null, null, null, jsonActivationKey.getString("name"), null, null, null, true, null, null, null, null, null);
    // assert that all the pools were consumed
    List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    for (int i = 0; i < jsonPoolsAddedToActivationKey.length(); i++) {
        JSONObject jsonPoolAdded = (JSONObject) jsonPoolsAddedToActivationKey.get(i);
        // assert that the pool's providedProducts (excluding type=MKT products) are consumed (unless it is a ManagementAddOn product - indicated by no providedProducts)
        assertProvidedProductsFromPoolAreWithinConsumedProductSubscriptionsUsingQuantity(jsonPoolAdded, consumedProductSubscriptions, addQuantity, false);
    }
    Assert.assertEquals(clienttasks.getCurrentEntitlementCertFiles().size(), jsonActivationKey.getJSONArray("pools").length(), "Expecting a new entitlement cert file in '" + clienttasks.entitlementCertDir + "' for each of the pools added to the activation key.");
}
Also used : JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) JSONArray(org.json.JSONArray) ProductSubscription(rhsm.data.ProductSubscription) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 63 with SSHCommandResult

use of com.redhat.qe.tools.SSHCommandResult in project rhsm-qe by RedHatQE.

the class ActivationKeyTests method testRegisterWithActivationKeyUsingWrongOrg.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21801", "RHEL7-51618" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.NEGATIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "create an activation key for each org and then attempt to register with the activation key using a different org", groups = { "Tier3Tests" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRegisterWithActivationKeyUsingWrongOrg() throws JSONException, Exception {
    // loop through existing owners and remember the orgs
    JSONArray jsonOwners = new JSONArray(CandlepinTasks.getResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/owners"));
    if (jsonOwners.length() < 2)
        throw new SkipException("This test requires at least two orgs on your candlepin server.");
    List<String> orgs = new ArrayList<String>();
    for (int j = 0; j < jsonOwners.length(); j++) {
        JSONObject jsonOwner = (JSONObject) jsonOwners.get(j);
        // {
        // "contentPrefix": null,
        // "created": "2011-07-01T06:39:58.740+0000",
        // "displayName": "Snow White",
        // "href": "/owners/snowwhite",
        // "id": "8a90f8c630e46c7e0130e46ce114000a",
        // "key": "snowwhite",
        // "parentOwner": null,
        // "updated": "2011-07-01T06:39:58.740+0000",
        // "upstreamUuid": null
        // }
        orgs.add(jsonOwner.getString("key"));
    }
    // now loop through the orgs and create an activation key and attempt to register using a different org
    for (String org : orgs) {
        // generate a unique activationkey name for this org
        String activationKeyName = String.format("ActivationKey%sForOrg_%s", System.currentTimeMillis(), org);
        // create a JSON object to represent the request body
        Map<String, String> mapActivationKeyRequest = new HashMap<String, String>();
        mapActivationKeyRequest.put("name", activationKeyName);
        JSONObject jsonActivationKeyRequest = new JSONObject(mapActivationKeyRequest);
        // call the candlepin api to create an activation key
        JSONObject jsonActivationKeyC = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/owners/" + org + "/activation_keys", jsonActivationKeyRequest.toString()));
        // assert that the creation was successful (does not contain a displayMessage)
        if (jsonActivationKeyC.has("displayMessage")) {
            String displayMessage = jsonActivationKeyC.getString("displayMessage");
            Assert.fail("The creation of an activation key appears to have failed: " + displayMessage);
        }
        Assert.assertTrue(true, "The absense of a displayMessage indicates the activation key creation was probably successful.");
        // now assert that the new activation key is found under /candlepin/activation_keys/<id>
        JSONObject jsonActivationKeyJ = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/activation_keys/" + jsonActivationKeyC.getString("id")));
        // Assert.assertEquals(jsonActivationKeyC.toString(), jsonActivationKeyJ.toString(), "Successfully found newly created activation key among all activation keys under /activation_keys.");
        Assert.assertTrue(areActivationKeysEqual(jsonActivationKeyC, jsonActivationKeyJ), "Successfully found newly created activation key among all activation keys under Candlepin API /activation_keys/<id>." + "\n jsonActivationKeyC='" + jsonActivationKeyC.toString() + "'" + "\n jsonActivationKeyJ='" + jsonActivationKeyJ.toString() + "'");
        // now let's attempt to register with the activation key using a different org
        for (String differentOrg : orgs) {
            if (differentOrg.equals(org))
                continue;
            SSHCommandResult registerResult = clienttasks.register_(null, null, differentOrg, null, null, null, null, null, null, null, activationKeyName, null, null, null, true, null, null, null, null, null);
            // assert the sshCommandResult here
            Integer expectedExitCode = new Integer(255);
            // EX_SOFTWARE	// post commit df95529a5edd0be456b3528b74344be283c4d258 bug 1119688
            if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.13.8-1"))
                expectedExitCode = new Integer(70);
            Assert.assertEquals(registerResult.getExitCode(), expectedExitCode, "The expected exit code from the register attempt with activationKey using the wrong org.");
            // Assert.assertEquals(registerResult.getStdout().trim(), "", "The expected stdout result the register attempt with activationKey using the wrong org.");
            String expectedStderr = "Activation key '" + activationKeyName + "' not found for organization '" + differentOrg + "'.";
            // Follows: candlepin-0.9.30-1	// https://github.com/candlepin/candlepin/commit/bcb4b8fd8ee009e86fc9a1a20b25f19b3dbe6b2a
            if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">", "0.9.30-1"))
                expectedStderr = String.format("None of the activation keys specified exist for this org.");
            Assert.assertEquals(registerResult.getStderr().trim(), expectedStderr, "The expected stderr result from the register attempt with activationKey '" + activationKeyName + "' using the wrong org '" + differentOrg + "'.");
            // make sure there is no consumer cert - register with activation key should be 100% successful - if any one part fails, the whole operation fails
            Assert.assertNull(clienttasks.getCurrentConsumerCert(), "There should be no consumer cert on the system when register with activation key fails.");
        }
    }
}
Also used : JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 64 with SSHCommandResult

use of com.redhat.qe.tools.SSHCommandResult in project rhsm-qe by RedHatQE.

the class BashCompletionTests method testBashCompletion.

// 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-19942", "RHEL7-68140" }, 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 = "when subscription-manager is run with no args, it should default to the help report", groups = { "Tier1Tests" }, dataProvider = "BashCompletionData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testBashCompletion(Object bugzilla, String bashCommand, Set<String> expectedCompletions) {
    // inspired by https://github.com/lacostej/unity3d-bash-completion/blob/master/lib/completion.py
    List<String> program_args = Arrays.asList(bashCommand.split("\\s+"));
    String program = program_args.get(0);
    List<String> args = program_args.subList(1, program_args.size());
    String COMP_LINE = bashCommand;
    String COMP_WORDS = COMP_LINE.trim();
    Integer COMP_CWORD = args.size();
    Integer COMP_POINT = COMP_LINE.length();
    if (COMP_LINE.endsWith(" ")) {
        COMP_WORDS += " ";
        COMP_CWORD += 1;
    }
    // String script = "bash -i -c 'COMP_LINE=\"subscription-manager attach --\" COMP_WORDS=(subscription-manager attach --) COMP_CWORD=2 COMP_POINT=30; $(complete -p subscription-manager | sed \"s/.*-F \\([^ ]*\\) .*/\\1/\") && echo ${COMPREPLY[*]}'";
    String script = String.format("bash -i -c 'COMP_LINE=\"%s\" COMP_WORDS=(%s) COMP_CWORD=%d COMP_POINT=%d; $(complete -p %s | sed \"s/.*-F \\([^ ]*\\) .*/\\1/\") && echo ${COMPREPLY[*]}'", COMP_LINE, COMP_WORDS, COMP_CWORD, COMP_POINT, program);
    SSHCommandResult result = client.runCommandAndWait(script);
    // IGNORE: Stderr:
    // bash: cannot set terminal process group (-1): Invalid argument
    // bash: no job control in this shell
    log.info(result.toString());
    Set<String> actualCompletions = new HashSet<String>(Arrays.asList(result.getStdout().trim().split("\\s+")));
    // assert all of the expectedOptions were found and that no unexpectedOptions were found
    for (String expectedCompletion : expectedCompletions) {
        if (!actualCompletions.contains(expectedCompletion)) {
            log.warning("Was not presented with the expected bash-completion '" + expectedCompletion + "' for command '" + bashCommand + "'.");
        } else {
            Assert.assertTrue(actualCompletions.contains(expectedCompletion), "The expected command '" + bashCommand + "' option '" + expectedCompletion + "' is available.");
        }
    }
    for (String actualCompletion : actualCompletions) {
        if (!expectedCompletions.contains(actualCompletion))
            log.warning("Was presented with an unexpected bash-completion '" + actualCompletion + "' for command '" + bashCommand + "'.");
    }
    // PERMANENT WORKAROUND FOR CLOSED/WONTFIX Bug 1004402 - rhsmd and rhsmcertd-worker does not bash complete its options
    if ((bashCommand.startsWith("/usr/libexec/rhsmcertd-worker ") || bashCommand.startsWith("/usr/libexec/rhsmd ")) && !actualCompletions.containsAll(expectedCompletions)) {
        String bugId = "1004402";
        try {
            if (!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 {
            }
        } catch (BugzillaAPIException be) {
        /* ignore exception */
        } catch (RuntimeException re) {
        /* ignore exception */
        }
        throw new SkipException("Bash completion for '" + bashCommand + "' is broken and bug '" + bugId + "' was CLOSED/WONTFIX.");
    }
    // PERMANENT WORKAROUND
    if ((bashCommand.equals("rct stat-cert -")) && actualCompletions.contains("--no-content") && !expectedCompletions.contains("--no-content")) {
        if (clienttasks.isPackageVersion("subscription-manager", "<", "1.18.2-1")) {
            // commit ac70fc3a50e172030c042bd5f18d78256c56470c // 1374389: rm --no-content from stat-cert completion
            throw new SkipException("Bash completion for '" + bashCommand + "' is broken in this version of subscription-manager '" + clienttasks.installedPackageVersionMap.get("subscription-manager") + "' and was not fixed until subscription-manager-1.18.2-1 by Bug 1374389.");
        }
    }
    // END OF WORKAROUND
    Assert.assertTrue(actualCompletions.containsAll(expectedCompletions), "All of the expected bash-completions for command '" + bashCommand + "' were presented.");
    Assert.assertTrue(expectedCompletions.containsAll(actualCompletions), "All of the presented bash-completions for command '" + bashCommand + "' were expected.");
}
Also used : SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SkipException(org.testng.SkipException) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) HashSet(java.util.HashSet) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 65 with SSHCommandResult

use of com.redhat.qe.tools.SSHCommandResult in project rhsm-qe by RedHatQE.

the class BugzillaTests method testSubscribeWithInvalidFileFromStdin.

/**
 * @author redakkan
 * @throws Exception
 * JSON Exception
 */
@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-47892", "RHEL7-96016" }, linkedWorkItems = { @LinkedItem(// RHSM-REQ : subscription-manager cli attaching and removing subscriptions
workitemId = "RHEL6-28489", project = Project.RHEL6, role = DefTypes.Role.VERIFIES), @LinkedItem(// RHSM-REQ : subscription-manager cli attaching and removing subscriptions
workitemId = "RHEL7-84911", project = Project.RedHatEnterpriseLinux7, 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.NEGATIVE, importance = DefTypes.Importance.LOW, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "subscription-manager: verify subscribe with --file=invalid file from stdin is handled properly", groups = { "Tier3Tests", "blockedByBug-1350402", "testSubscribeWithInvalidFileFromStdin" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testSubscribeWithInvalidFileFromStdin() throws JSONException, Exception {
    // commit 3167333fc3a261de939f4aa0799b4283f2b9f4d2 bug 1159974
    if (clienttasks.isPackageVersion("subscription-manager", "<", "1.13.8-1"))
        throw new SkipException("The attach --file function was not implemented in this version of subscription-manager.");
    // commit cda076cce4ac66d09eba31b64454d2780a6d1312 bug 1350402
    if (clienttasks.isPackageVersion("subscription-manager", "<", "1.20.1-1"))
        throw new SkipException("The currently installed version (" + clienttasks.installedPackageVersionMap.get("subscription-manager") + ") is blocked by bug 1350402 which is fixed in subscription-manager-1.20.1-1 and newer.");
    if (clienttasks.getCurrentlyRegisteredOwnerKey() == null) {
        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);
    } else
        clienttasks.unsubscribe_(true, (BigInteger) null, null, null, null, null, null);
    String InvalidFile = "/tmp/invalid.txt";
    /*About the bug : When stdout/stderr output of subscription-manager is redirected using pipe to some other process ... e.g. subscription-manager list --all --available --pool-only | subscription-manager subscribe --file=/tmp/invalid
        and the second process does not read anything from stdout like in this case, then subscription-manager cannot write the buffer anywhere hence the command was terminated with some errors
        The bug is reproducible only with stdin , hence passing the poolOnlyListCommand to pipe the out put

        [root@ibm-x3250m3-01 ~]# subscription-manager list --all --available --pool-only | subscription-manager subscribe --file=/tmp/invalid
		Error: The file "/tmp/invalid" does not exist or cannot be read.
		close failed in file object destructor:
		sys.excepthook is missing
		lost sys.stderr
        */
    String poolOnlyListCommand = clienttasks.listCommand(true, true, null, null, null, null, null, null, null, true, null, null, null, null);
    String stdinFileSubscribeCommand = clienttasks.subscribeCommand(null, null, (List<String>) null, (List<String>) null, null, null, null, null, InvalidFile, null, null, null, null);
    SSHCommandResult stdinFileSubscribeCommandResult = client.runCommandAndWait(poolOnlyListCommand + "|" + stdinFileSubscribeCommand, (long) (3 * /*min*/
    60 * 1000));
    // Assert the additional error messages no longer appear
    Assert.assertEquals(stdinFileSubscribeCommandResult.getStderr().trim(), "Error: The file \"/tmp/invalid.txt\" does not exist or cannot be read.");
    if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.20.1-1")) {
        // commit 79f86e4c043ee751677131ed4e3cf00affd13087
        Assert.assertEquals(stdinFileSubscribeCommandResult.getExitCode(), Integer.valueOf(65), "Exit Code comparison between the expected result of subscribing using a list of poolids from stdin along with a invalid file.");
    } else {
        Assert.assertEquals(stdinFileSubscribeCommandResult.getExitCode(), Integer.valueOf(64), "Exit Code comparison between the expected result of subscribing using a list of poolids from stdin along with a invalid file.");
    }
}
Also used : SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) BigInteger(java.math.BigInteger) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Aggregations

SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)553 Test (org.testng.annotations.Test)416 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)401 SkipException (org.testng.SkipException)219 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)201 ArrayList (java.util.ArrayList)101 BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)79 BigInteger (java.math.BigInteger)68 File (java.io.File)58 SubscriptionPool (rhsm.data.SubscriptionPool)53 JSONObject (org.json.JSONObject)47 HashMap (java.util.HashMap)42 ProductSubscription (rhsm.data.ProductSubscription)31 EntitlementCert (rhsm.data.EntitlementCert)30 List (java.util.List)21 YumRepo (rhsm.data.YumRepo)18 ProductCert (rhsm.data.ProductCert)17 Repo (rhsm.data.Repo)16 InstalledProduct (rhsm.data.InstalledProduct)15 Calendar (java.util.Calendar)13