Search in sources :

Example 16 with SubscriptionPool

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

the class SubscriptionManagerTasks method assertNoAvailableSubscriptionPoolsToList.

public void assertNoAvailableSubscriptionPoolsToList(boolean ignoreMuliEntitlementSubscriptionPools, String assertMsg) {
    boolean invokeWorkaroundWhileBugIsOpen = true;
    // TEMPORARY WORKAROUND FOR BUG
    // true;	// Status: CLOSED ERRATA	// Bug 613635 - “connection.UEPConnection instance “ displays while availability check
    invokeWorkaroundWhileBugIsOpen = false;
    try {
        String bugId = "613635";
        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) {
        Assert.assertContainsMatch(listAvailableSubscriptionPools().getStdout(), "^No available subscription pools to list$", assertMsg);
        return;
    }
    // END OF WORKAROUND
    // TEMPORARY WORKAROUND FOR BUG
    // true;	// Status: CLOSED ERRATA	// Bug 622839 - extraneous user hash code appears in stdout after executing list --available
    invokeWorkaroundWhileBugIsOpen = false;
    try {
        String bugId = "622839";
        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) {
        Assert.assertContainsMatch(listAvailableSubscriptionPools().getStdout(), "^No available subscription pools to list$", assertMsg);
        return;
    }
    // END OF WORKAROUND
    // TEMPORARY WORKAROUND FOR BUG
    // true;	// Status: CLOSED DUPLICATE of bug 623481	// Bug 623657 - extraneous self.conn output appears in stdout after executing list --available
    invokeWorkaroundWhileBugIsOpen = false;
    try {
        String bugId = "623657";
        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) {
        Assert.assertContainsMatch(listAvailableSubscriptionPools().getStdout(), "^No available subscription pools to list$", assertMsg);
        return;
    }
    // END OF WORKAROUND
    // determine which available pools are multi-entitlement pools
    List<SubscriptionPool> poolsAvailableExcludingMuliEntitlement = new ArrayList<SubscriptionPool>();
    List<SubscriptionPool> poolsAvailable = getCurrentlyAvailableSubscriptionPools();
    for (SubscriptionPool pool : poolsAvailable) {
        try {
            String authenticator = this.currentlyRegisteredUsername != null ? this.currentlyRegisteredUsername : candlepinAdminUsername;
            String password = this.currentlyRegisteredPassword != null ? this.currentlyRegisteredPassword : candlepinAdminPassword;
            if (!CandlepinTasks.isPoolProductMultiEntitlement(authenticator, password, candlepinUrl, pool.poolId)) {
                poolsAvailableExcludingMuliEntitlement.add(pool);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail(e.getMessage());
        }
    }
    // assert
    if (ignoreMuliEntitlementSubscriptionPools) {
        Assert.assertEquals(poolsAvailableExcludingMuliEntitlement.size(), 0, assertMsg + " (muti-entitlement pools were excluded.)");
    } else {
        Assert.assertEquals(poolsAvailable.size(), 0, assertMsg + " (muti-entitlement pools were excluded.)");
        Assert.assertEquals(listAvailableSubscriptionPools().getStdout().trim(), "No available subscription pools to list", assertMsg);
    }
}
Also used : ArrayList(java.util.ArrayList) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) SubscriptionPool(rhsm.data.SubscriptionPool) SkipException(org.testng.SkipException) JSONException(org.json.JSONException) IOException(java.io.IOException) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException)

Example 17 with SubscriptionPool

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

the class SubscriptionManagerTasks method subscribeToSubscriptionPool.

/**
 * subscribe to the given SubscriptionPool (assumes pool came from the list of available pools)
 * @return the newly installed EntitlementCert file to the newly consumed ProductSubscriptions
 */
public File subscribeToSubscriptionPool(SubscriptionPool pool, String quantity, String authenticator, String password, String serverUrl) {
    List<ProductSubscription> beforeProductSubscriptions = getCurrentlyConsumedProductSubscriptions();
    List<File> beforeEntitlementCertFiles = getCurrentEntitlementCertFiles();
    log.info("Subscribing to subscription pool: " + pool);
    SSHCommandResult sshCommandResult = subscribe(null, null, pool.poolId, null, null, quantity, null, null, null, null, null, null, null);
    // is this pool multi-entitleable?
    /* This information is now in the SubscriptionPool itself
		boolean isPoolMultiEntitlement = false;
		try {
			isPoolMultiEntitlement = CandlepinTasks.isPoolProductMultiEntitlement(this.currentlyRegisteredUsername,this.currentlyRegisteredPassword,SubscriptionManagerBaseTestScript.sm_serverUrl,pool.poolId);
		} catch (Exception e) {
			e.printStackTrace();
			Assert.fail(e.getMessage());
		}
		*/
    // get the pool's product "arch" attribute that this subscription pool supports
    String poolProductAttributeArch = "";
    List<String> poolProductAttributeArches = new ArrayList<String>();
    if (authenticator != null && password != null && serverUrl != null) {
        try {
            poolProductAttributeArch = CandlepinTasks.getPoolProductAttributeValue(authenticator, password, serverUrl, pool.poolId, "arch");
            if (poolProductAttributeArch != null && !poolProductAttributeArch.trim().isEmpty()) {
                // Note: the arch attribute can be a comma separated list of values
                poolProductAttributeArches.addAll(Arrays.asList(poolProductAttributeArch.trim().split(" *, *")));
                // Note: x86 is a general arch to cover all 32-bit intel microprocessors
                if (poolProductAttributeArches.contains("x86"))
                    poolProductAttributeArches.addAll(Arrays.asList("i386", "i486", "i586", "i686"));
            // if (productSupportedArches.contains("ALL")) productSupportedArches.add(arch);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail(e.getMessage());
        }
    }
    // assert that the remaining SubscriptionPools does NOT contain the pool just subscribed to (unless it is multi-entitleable)
    List<SubscriptionPool> afterSubscriptionPools = getCurrentlyAvailableSubscriptionPools();
    if (pool.subscriptionType != null && pool.subscriptionType.equals("Other")) {
        Assert.fail("Encountered a subscription pool of type '" + pool.subscriptionType + "'.  Do not know how to assert the remaining availability of this pool after subscribing to it: " + pool);
    } else if (pool.multiEntitlement == null && pool.subscriptionType != null && pool.subscriptionType.isEmpty()) {
        log.warning("Encountered a pool with an empty value for subscriptionType (indicative of an older candlepin server): " + pool);
        log.warning("Skipping assertion of the pool's expected availability after having subscribed to it.");
    } else if (!pool.quantity.equalsIgnoreCase("unlimited") && Integer.valueOf(pool.quantity) <= 1) {
        Assert.assertTrue(!afterSubscriptionPools.contains(pool), "When the final quantity from the pool was consumed, the remaining available subscription pools no longer contains the just subscribed to pool: " + pool);
    } else if (pool.multiEntitlement != null && !pool.multiEntitlement) {
        Assert.assertTrue(!afterSubscriptionPools.contains(pool), "When the pool is not multi-entitleable, the remaining available subscription pools no longer contains the just subscribed to pool: " + pool);
    } else if (pool.subscriptionType != null && (!pool.subscriptionType.equals("Stackable") && !pool.subscriptionType.equals("Multi-Entitleable") && !pool.subscriptionType.equals("Instance Based") && !pool.subscriptionType.equals("Stackable (Temporary)") && !pool.subscriptionType.equals("Multi-Entitleable (Temporary)") && !pool.subscriptionType.equals("Instance Based (Temporary)"))) {
        // see https://bugzilla.redhat.com/show_bug.cgi?id=1029968#c2
        Assert.assertTrue(!afterSubscriptionPools.contains(pool), "When the pool is not multi-entitleable (not Stackable && not Multi-Entitleable && not Instance Based), the remaining available subscription pools no longer contains the just subscribed to pool: " + pool);
    } else if (!poolProductAttributeArches.isEmpty() && !poolProductAttributeArches.contains("ALL") && !poolProductAttributeArches.contains(arch)) {
        Assert.assertTrue(!afterSubscriptionPools.contains(pool), "When the pools product attribute arch '" + poolProductAttributeArch + "' does not support this system arch '" + arch + "', the remaining available subscription pools should never contain the just subscribed to pool: " + pool);
    } else {
        Assert.assertTrue(afterSubscriptionPools.contains(pool), // TODO fix the assertions for "if this fails"
        "When the pool is multi-entitleable, the remaining available subscription pools still contains the just subscribed to pool: " + pool + " (TODO: if this fails, then we likely attached the final entitlements from the pool)");
    }
    // assert that the remaining SubscriptionPools do NOT contain the same productId just subscribed to
    // log.warning("We will no longer assert that the remaining available pools do not contain the same productId ("+pool.productId+") as the pool that was just subscribed.  Reference: https://bugzilla.redhat.com/show_bug.cgi?id=663455");
    /*
		for (SubscriptionPool afterSubscriptionPool : afterSubscriptionPools) {
			Assert.assertTrue(!afterSubscriptionPool.productId.equals(pool.productId),
					"This remaining available pool "+afterSubscriptionPool+" does NOT contain the same productId ("+pool.productId+") after subscribing to pool: "+pool);
		}
		*/
    // is this a personal subpool?
    String poolProductId = pool.productId;
    boolean isSubpool = false;
    try {
        JSONArray personSubscriptionPoolProductData;
        // personSubscriptionPoolProductData = new JSONArray(System.getProperty("sm.person.subscriptionPoolProductData", "<>").replaceAll("<", "[").replaceAll(">", "]")); // hudson parameters use <> instead of []
        // hudson JSONArray parameters get surrounded with double quotes that need to be stripped
        personSubscriptionPoolProductData = new JSONArray(SubscriptionManagerBaseTestScript.getProperty("sm.person.subscriptionPoolProductData", "[]").replaceFirst("^\"", "").replaceFirst("\"$", "").replaceAll("<", "[").replaceAll(">", "]"));
        for (int j = 0; j < personSubscriptionPoolProductData.length(); j++) {
            JSONObject poolProductDataAsJSONObject = (JSONObject) personSubscriptionPoolProductData.get(j);
            String personProductId = poolProductDataAsJSONObject.getString("personProductId");
            JSONObject subpoolProductDataAsJSONObject = poolProductDataAsJSONObject.getJSONObject("subPoolProductData");
            String systemProductId = subpoolProductDataAsJSONObject.getString("systemProductId");
            if (poolProductId.equals(systemProductId)) {
                // special case when pool's productId is really a personal subpool
                poolProductId = personProductId;
                isSubpool = true;
                break;
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
    // figure out which entitlement cert file has been newly installed into /etc/pki/entitlement after attempting to subscribe to pool
    /* OLD - THIS ALGORITHM BREAKS DOWN WHEN MODIFIER ENTITLEMENTS ARE IN PLAY
		File newCertFile = null;
		List<File> afterEntitlementCertFiles = getCurrentEntitlementCertFiles();
		for (File file : afterEntitlementCertFiles) {
			if (!beforeEntitlementCertFiles.contains(file)) {
				newCertFile = file; break;
			}
		}
		*/
    /* VALID BUT INEFFICIENT
		List<File> afterEntitlementCertFiles = getCurrentEntitlementCertFiles();
		File newCertFile = null;
		Map<BigInteger, SubscriptionPool> map = new HashMap<BigInteger, SubscriptionPool>();
		try {
			map = getCurrentSerialMapToSubscriptionPools(this.currentAuthenticator,this.currentAuthenticatorPassword);
		} catch (Exception e) {
			e.printStackTrace();
			Assert.fail(e.getMessage());
		}
		for (BigInteger serial: map.keySet()) {
			if (map.get(serial).poolId.equals(pool.poolId)) {
				newCertFile = new File(this.entitlementCertDir+"/"+serial+".pem");
				break;
			}
		}
		*/
    // NOTE: this block of code is somewhat duplicated in getEntitlementCertCorrespondingToSubscribedPool(...)
    File newCertFile = null;
    List<File> afterEntitlementCertFiles = getCurrentEntitlementCertFiles("-t");
    if (authenticator != null && password != null && serverUrl != null) {
        for (File entitlementCertFile : afterEntitlementCertFiles) {
            if (!beforeEntitlementCertFiles.contains(entitlementCertFile)) {
                EntitlementCert entitlementCert = getEntitlementCertFromEntitlementCertFile(entitlementCertFile);
                try {
                    // JSONObject jsonEntitlement = CandlepinTasks.getEntitlementUsingRESTfulAPI(authenticator,password,serverUrl,entitlementCert.id);	// is throwing a 500 in stage, but only for qa@redhat.com credentials - I don't know why
                    JSONObject jsonEntitlement = CandlepinTasks.getEntitlementUsingRESTfulAPI(currentlyRegisteredUsername, currentlyRegisteredPassword, serverUrl, entitlementCert.id);
                    JSONObject jsonPool = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(authenticator, password, serverUrl, jsonEntitlement.getJSONObject("pool").getString("href")));
                    if (jsonPool.getString("id").equals(pool.poolId)) {
                        newCertFile = entitlementCertFile;
                        break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Assert.fail(e.getMessage());
                }
            }
        }
    }
    // when the pool is already subscribed to...
    if (sshCommandResult.getStdout().startsWith("This consumer is already subscribed")) {
        // assert that NO new entitlement cert file has been installed in /etc/pki/entitlement
        /*Assert.assertNull(newCertFile,
					"A new entitlement certificate has NOT been installed after attempting to subscribe to an already subscribed to pool: "+pool);
			*/
        Assert.assertEquals(beforeEntitlementCertFiles.size(), afterEntitlementCertFiles.size(), "The existing entitlement certificate count remains unchanged after attempting to subscribe to an already subscribed to pool: " + pool);
        // find the existing entitlement cert file corresponding to the already subscribed pool
        /* ALREADY FOUND USING ALGORITHM ABOVE 
			EntitlementCert entitlementCert = null;
			for (File thisEntitlementCertFile : getCurrentEntitlementCertFiles()) {
				EntitlementCert thisEntitlementCert = getEntitlementCertFromEntitlementCertFile(thisEntitlementCertFile);
				if (thisEntitlementCert.orderNamespace.productId.equals(poolProductId)) {
					entitlementCert = thisEntitlementCert;
					break;
				}
			}
			Assert.assertNotNull(entitlementCert, isSubpool?
					"Found an already existing Entitlement Cert whose personal productId matches the system productId from the subscription pool: "+pool:
					"Found an already existing Entitlement Cert whose productId matches the productId from the subscription pool: "+pool);
			newCertFile = getEntitlementCertFileFromEntitlementCert(entitlementCert); // not really new, just already existing
			*/
        // assert that consumed ProductSubscriptions has NOT changed
        List<ProductSubscription> afterProductSubscriptions = getCurrentlyConsumedProductSubscriptions();
        Assert.assertTrue(afterProductSubscriptions.size() == beforeProductSubscriptions.size() && afterProductSubscriptions.size() > 0, "The list of currently consumed product subscriptions has not changed (from " + beforeProductSubscriptions.size() + " to " + afterProductSubscriptions.size() + ") since the productId of the pool we are trying to subscribe to is already consumed.");
    // when no free entitlements exist...		// No entitlements are available from the pool with id '8a90f8143611c33f013611c4797b0456'.	// No subscriptions are available from the pool with id '8a90f8303c98703a013c98715ca80494'.  Bug 876758
    } else if (sshCommandResult.getStdout().startsWith("No entitlements are available") || sshCommandResult.getStdout().startsWith("No subscriptions are available")) {
        // assert that the depleted pool Quantity is zero
        SubscriptionPool depletedPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", pool.poolId, getCurrentlyAllAvailableSubscriptionPools());
        /* behavior changed on list --all --available  (3/4/2011)
			Assert.assertNotNull(depletedPool,
					"Found the depleted pool amongst --all --available after having consumed all of its available entitlements: ");
			*/
        Assert.assertNull(depletedPool, "Should no longer find the depleted pool amongst --all --available after having consumed all of its available entitlements: ");
        // "Asserting the pool's quantity after having consumed all of its available entitlements is zero.");
        if (authenticator != null && password != null && serverUrl != null) {
            JSONObject jsonPool = null;
            int consumed = 0;
            int quantityAvailable = Integer.valueOf(pool.quantity);
            try {
                jsonPool = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(authenticator, password, serverUrl, "/pools/" + pool.poolId));
                consumed = jsonPool.getInt("consumed");
                quantityAvailable = jsonPool.getInt("quantity");
            } catch (Exception e) {
                e.printStackTrace();
                Assert.fail(e.getMessage());
            }
            Assert.assertEquals(consumed, quantityAvailable, "Asserting the pool's consumed attribute equals it's total quantity after having consumed all of its available entitlements.");
        }
        // assert that NO new entitlement cert file has been installed in /etc/pki/entitlement
        Assert.assertNull(newCertFile, "A new entitlement certificate has NOT been installed after attempting to subscribe to depleted pool: " + depletedPool);
        Assert.assertEquals(beforeEntitlementCertFiles.size(), afterEntitlementCertFiles.size(), "The existing entitlement certificate count remains unchanged after attempting to subscribe to depleted pool: " + depletedPool);
    // otherwise, the pool is NOT already subscribe to...
    } else {
        // assert that only ONE new entitlement cert file has been installed in /etc/pki/entitlement
        // https://bugzilla.redhat.com/show_bug.cgi?id=640338
        Assert.assertTrue(afterEntitlementCertFiles.size() == beforeEntitlementCertFiles.size() + 1, "Only ONE new entitlement certificate has been installed (count was '" + beforeEntitlementCertFiles.size() + "'; is now '" + afterEntitlementCertFiles.size() + "') after subscribing to pool: " + pool);
        if (authenticator != null && password != null && serverUrl != null) {
            // assert the new entitlement cert file has been installed in /etc/pki/entitlement
            Assert.assertNotNull(newCertFile, "A new entitlement certificate has been installed after subscribing to pool: " + pool);
            log.info("The new entitlement certificate file is: " + newCertFile);
            // assert that the productId from the pool matches the entitlement productId
            // TEMPORARY WORKAROUND FOR BUG: https://bugzilla.redhat.com/show_bug.cgi?id=650278 - jsefler 11/05/2010
            // TEMPORARY WORKAROUND FOR BUG: https://bugzilla.redhat.com/show_bug.cgi?id=806986 - jsefler 06/28/2012
            boolean invokeWorkaroundWhileBugIsOpen = true;
            String bugId1 = "650278";
            String bugId2 = "806986";
            try {
                if (invokeWorkaroundWhileBugIsOpen && (BzChecker.getInstance().isBugOpen(bugId1) || BzChecker.getInstance().isBugOpen(bugId2))) {
                    log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId1).toString() + " Bugzilla " + bugId1 + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId1 + ")");
                    SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId1);
                    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 {
                    invokeWorkaroundWhileBugIsOpen = false;
                }
            } catch (BugzillaAPIException be) {
            /* ignore exception */
            } catch (RuntimeException re) {
            /* ignore exception */
            }
            if (invokeWorkaroundWhileBugIsOpen) {
                log.warning("Skipping assert that the productId from the pool matches the entitlement productId");
            } else {
                // END OF WORKAROUND
                EntitlementCert entitlementCert = getEntitlementCertFromEntitlementCertFile(newCertFile);
                File newCertKeyFile = getEntitlementCertKeyFileFromEntitlementCert(entitlementCert);
                Assert.assertEquals(entitlementCert.orderNamespace.productId, poolProductId, isSubpool ? "New EntitlementCert productId '" + entitlementCert.orderNamespace.productId + "' matches originating Personal SubscriptionPool productId '" + poolProductId + "' after subscribing to the subpool." : "New EntitlementCert productId '" + entitlementCert.orderNamespace.productId + "' matches originating SubscriptionPool productId '" + poolProductId + "' after subscribing to the pool.");
                Assert.assertTrue(RemoteFileTasks.testExists(sshCommandRunner, newCertFile.getPath()), "New EntitlementCert file exists after subscribing to SubscriptionPool '" + pool.poolId + "'.");
                Assert.assertTrue(RemoteFileTasks.testExists(sshCommandRunner, newCertKeyFile.getPath()), "New EntitlementCert key file exists after subscribing to SubscriptionPool '" + pool.poolId + "'.");
            }
        }
        // assert that consumed ProductSubscriptions has NOT decreased
        List<ProductSubscription> afterProductSubscriptions = getCurrentlyConsumedProductSubscriptions();
        // this assertion was valid prior to bug Bug 801187 - collapse list of provided products for subscription-manager list --consumed
        // Assert.assertTrue(afterProductSubscriptions.size() >= beforeProductSubscriptions.size() && afterProductSubscriptions.size() > 0,
        // "The list of currently consumed product subscriptions has increased (from "+beforeProductSubscriptions.size()+" to "+afterProductSubscriptions.size()+"), or has remained the same after subscribing (using poolID="+pool.poolId+") to pool: "+pool+"  Note: The list of consumed product subscriptions can remain the same when all the products from this subscription pool are a subset of those from a previously subscribed pool.");
        Assert.assertTrue(afterProductSubscriptions.size() == beforeProductSubscriptions.size() + 1, "The list of currently consumed product subscriptions has increased by 1 (from " + beforeProductSubscriptions.size() + " to " + afterProductSubscriptions.size() + "), after subscribing to pool: " + pool);
    }
    return newCertFile;
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) ProductSubscription(rhsm.data.ProductSubscription) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) SkipException(org.testng.SkipException) JSONException(org.json.JSONException) IOException(java.io.IOException) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) JSONObject(org.json.JSONObject) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) SubscriptionPool(rhsm.data.SubscriptionPool)

Example 18 with SubscriptionPool

use of rhsm.data.SubscriptionPool 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 19 with SubscriptionPool

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

the class BrandingTests method testAttachSubscriptionsForFlexibleBranding.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-19955", "RHEL7-51004" }, 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 = "incrementally attach all available subscriptions and verify tests for Flexible Branding", groups = { "Tier1Tests", "AttachSubscriptionsForFlexibleBranding_Test", "blockedByBug-884290" }, priority = 100, enabled = true)
public void testAttachSubscriptionsForFlexibleBranding() throws JSONException, Exception {
    // register
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (List<String>) null, null, null, null, true, false, null, null, null, null);
    // we will start out by removing the current brand name.
    // before echo to avoid tail -f /var/log/messages | grep brandbot...   systemd: brandbot.service start request repeated too quickly, refusing to start.
    sleep(5000);
    client.runCommandAndWait("rm -f " + brandingFile);
    // choose subscription pools for FlexibleBranded tests from among the available subscription pools
    List<SubscriptionPool> subscriptionPools = clienttasks.getCurrentlyAvailableSubscriptionPools();
    SubscriptionPool brandedSubscriptionPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("productId", brandedSubscriptionProductId, subscriptionPools);
    // randomly reduce the number of subscriptionPools tested
    subscriptionPools = getRandomSubsetOfList(subscriptionPools, 10);
    // include the branded subscription pool for brandedSubscriptionProductId at the head of subscriptionPools
    if (brandedSubscriptionPool != null)
        subscriptionPools.add(0, brandedSubscriptionPool);
    // loop through subscription pools and assert flexible branding tests after attaching each subscription
    boolean flexibleBrandedSubscriptionsFound = false;
    for (SubscriptionPool pool : subscriptionPools) {
        // TODO this should not matter			if (CandlepinTasks.isPoolAModifier(sm_clientUsername, sm_clientPassword, pool.poolId, sm_serverUrl)) continue; // skip modifier pools
        String brandNameBeforeSubscribing = getCurrentBrandName();
        String brandNameStatBeforeSubscribing = getCurrentBrandNameFileStat();
        String prettyNameBeforeSubscribing = getCurrentPrettyName();
        log.info("Currently, the flexible brand name prior to subscribing to pool '" + pool.subscriptionName + "' is '" + brandNameBeforeSubscribing + "'.");
        clienttasks.subscribe(null, null, pool.poolId, null, null, null, null, null, null, null, null, null, null);
        Boolean verifiedSystemsExpectedBrandedNameAfterEvent = verifySystemsExpectedBrandedNameAfterEvent(brandNameBeforeSubscribing, brandNameStatBeforeSubscribing, prettyNameBeforeSubscribing, "subscribing to pool '" + pool.subscriptionName + "'");
        if (verifiedSystemsExpectedBrandedNameAfterEvent == null) {
            // unentitle the system to clear the undefined case of multiple installed OS products
            // clienttasks.unsubscribe_(true, (BigInteger)null, null, null, null);
            testRemoveSubscriptionsForFlexibleBranding();
        } else if (verifiedSystemsExpectedBrandedNameAfterEvent)
            flexibleBrandedSubscriptionsFound = true;
    }
    // throw SkipException when no flexible branding was tested
    if (!flexibleBrandedSubscriptionsFound)
        throw new SkipException("No branding subscriptions were found among the available subscriptions that will brand one of the currently installed OS products.");
}
Also used : SkipException(org.testng.SkipException) SubscriptionPool(rhsm.data.SubscriptionPool) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 20 with SubscriptionPool

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

the class BugzillaTests method testStartEndDateOfSubscription.

/**
 * @author skallesh
 * @throws Exception
 * @throws JSONException
 */
@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21970", "RHEL7-51832" }, 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 End date and start date of the subscription is appropriate one when you attach a future subscription and then  heal after 1 min", groups = { "Tier3Tests", "VerifyStartEndDateOfSubscription", "blockedByBug-994853", "blockedByBug-1440934" }, enabled = true)
public void testStartEndDateOfSubscription() throws Exception {
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, true, null, null, (String) null, null, null, null, true, null, null, null, null, null);
    Map<String, String> factsMap = new HashMap<String, String>();
    factsMap.put("cpu.cpu_socket(s)", String.valueOf(4));
    clienttasks.createFactsFileWithOverridingValues(factsMap);
    // [jsefler] I believe
    clienttasks.facts(null, true, null, null, null, null);
    // facts --update
    // should be called
    // after overriding
    // facts
    clienttasks.autoheal(null, null, true, null, null, null, null);
    for (SubscriptionPool AvailablePools : clienttasks.getCurrentlyAvailableSubscriptionPools()) {
        if (AvailablePools.productId.equals("awesomeos-x86_64")) {
            clienttasks.subscribe(null, null, AvailablePools.poolId, null, null, "1", null, null, null, null, null, null, null);
        }
    }
    InstalledProduct installedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", "100000000000002", clienttasks.getCurrentlyInstalledProducts());
    for (ProductSubscription consumedProductSubscription : clienttasks.getCurrentlyConsumedProductSubscriptions()) {
        if (consumedProductSubscription.provides.contains(installedProduct.productName)) {
            Assert.assertTrue(!installedProduct.startDate.after(consumedProductSubscription.startDate), "Comparing Start Date '" + InstalledProduct.formatDateString(installedProduct.startDate) + "' of Installed Product '" + installedProduct.productName + "' to Start Date '" + InstalledProduct.formatDateString(consumedProductSubscription.startDate) + "' of Consumed Subscription '" + consumedProductSubscription.productName + "'.  (Installed Product startDate should be <= Consumed Subscription startDate)");
        }
    }
    clienttasks.autoheal(null, true, null, null, null, null, null);
    clienttasks.restart_rhsmcertd(null, null, true);
    InstalledProduct installedProductAfterRHSM = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", "100000000000002", clienttasks.getCurrentlyInstalledProducts());
    for (ProductSubscription consumedProductSubscription : clienttasks.getCurrentlyConsumedProductSubscriptions()) {
        if (consumedProductSubscription.provides.contains(installedProductAfterRHSM.productName)) {
            Assert.assertTrue(!installedProductAfterRHSM.startDate.after(consumedProductSubscription.startDate), "Comparing Start Date '" + InstalledProduct.formatDateString(installedProductAfterRHSM.startDate) + "' of Installed Product '" + installedProductAfterRHSM.productName + "' to Start Date '" + InstalledProduct.formatDateString(consumedProductSubscription.startDate) + "' of Consumed Subscription '" + consumedProductSubscription.productName + "'.  (Installed Product startDate should be <= Consumed Subscription startDate)");
            if (!consumedProductSubscription.isActive) {
                Assert.assertEquals(installedProductAfterRHSM.endDate, consumedProductSubscription.endDate);
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) InstalledProduct(rhsm.data.InstalledProduct) ProductSubscription(rhsm.data.ProductSubscription) SubscriptionPool(rhsm.data.SubscriptionPool) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Aggregations

SubscriptionPool (rhsm.data.SubscriptionPool)195 Test (org.testng.annotations.Test)155 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)137 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)112 SkipException (org.testng.SkipException)90 ArrayList (java.util.ArrayList)87 JSONObject (org.json.JSONObject)66 SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)53 ProductSubscription (rhsm.data.ProductSubscription)38 BigInteger (java.math.BigInteger)37 File (java.io.File)34 List (java.util.List)33 EntitlementCert (rhsm.data.EntitlementCert)33 HashMap (java.util.HashMap)32 BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)28 InstalledProduct (rhsm.data.InstalledProduct)25 ProductCert (rhsm.data.ProductCert)24 JSONArray (org.json.JSONArray)22 Calendar (java.util.Calendar)12 GregorianCalendar (java.util.GregorianCalendar)11