Search in sources :

Example 11 with ProductSubscription

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

the class ActivationKeyTests method testRegisterWithSequenceOfMultipleActivationKeys.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21803", "RHEL7-51620" }, 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 many activation keys with one added pool per key and then register with a sequence of many --activationkey parameters asserting each pool per key gets consumed", groups = { "Tier3Tests", "blockedByBug-878986", "blockedByBug-979492", "blockedByBug-1040101" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRegisterWithSequenceOfMultipleActivationKeys() 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);
    // process each of the pools adding them to an individual activation key
    List<String> activationKeyNames = new ArrayList<String>();
    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;
        // create an activation key
        String activationKeyName = String.format("ActivationKey%sWithPool%sForOrg_%s", System.currentTimeMillis(), jsonPool.getString("id"), 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()));
        // add the pool to the activation key
        String path = "/activation_keys/" + jsonActivationKey.getString("id") + "/pools/" + jsonPool.getString("id") + (addQuantity == null ? "" : "?quantity=" + addQuantity);
        JSONObject jsonResult = new JSONObject(CandlepinTasks.postResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, path, 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);
        activationKeyNames.add(activationKeyName);
    }
    if (addQuantity == null)
        addQuantity = 1;
    // register with the activation key specified as a single string
    SSHCommandResult registerResult = clienttasks.register(null, null, sm_clientOrg, null, null, null, null, null, null, null, activationKeyNames, 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(), activationKeyNames.size(), "Expecting a new entitlement cert file in '" + clienttasks.entitlementCertDir + "' for each of the single pooled activation keys used during register.");
}
Also used : HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) JSONObject(org.json.JSONObject) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 12 with ProductSubscription

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

the class ActivationKeyTests method assertProvidedProductsFromPoolAreWithinConsumedProductSubscriptionsUsingQuantity.

protected void assertProvidedProductsFromPoolAreWithinConsumedProductSubscriptionsUsingQuantity(JSONObject jsonPool, List<ProductSubscription> consumedProductSubscriptions, Integer addQuantity, boolean assertConsumptionIsLimitedToThisPoolOnly) throws Exception {
    // assert that only the pool's providedProducts (excluding type=MKT products) are consumed (unless it is a ManagementAddOn product - indicated by no providedProducts)
    JSONArray jsonProvidedProducts = jsonPool.getJSONArray("providedProducts");
    // pluck out (remove) the providedProducts that have an attribute type=MKT products
    for (int j = 0; j < jsonProvidedProducts.length(); j++) {
        JSONObject jsonProvidedProduct = (JSONObject) jsonProvidedProducts.get(j);
        String resourcePath = "/products/" + jsonProvidedProduct.getString("productId");
        // starting with candlepin-2.0.11 /products/<ID> are requested by /owners/<KEY>/products/<ID> OR /products/<UUID>
        if (SubscriptionManagerTasks.isVersion(servertasks.statusVersion, ">=", "2.0.11"))
            resourcePath = jsonPool.getJSONObject("owner").getString("href") + resourcePath;
        JSONObject jsonProduct = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, resourcePath));
        JSONArray jsonAttributes = jsonProduct.getJSONArray("attributes");
        for (int k = 0; k < jsonAttributes.length(); k++) {
            JSONObject jsonAttribute = (JSONObject) jsonAttributes.get(k);
            if (jsonAttribute.getString("name").equals("type")) {
                if (jsonAttribute.getString("value").equals("MKT")) {
                    log.warning("Found a providedProduct '" + jsonProvidedProduct.getString("productName") + "' from the pool added to the activation key that is actually a Marketing product (attribute type=\"MKT\").  Therefore this provided product will be excluded from the expected consumed ProductSubscriptions assertions that will follow...");
                    jsonProvidedProduct = /*Plucked*/
                    (JSONObject) jsonProvidedProducts.remove(j--);
                    break;
                }
            }
        }
    }
    // translate the names of the jsonProvidedProducts into a list of string
    List<String> providedProductNamesFromActivationKeyPool = new ArrayList<String>();
    List<String> providedProductIdsFromActivationKeyPool = new ArrayList<String>();
    for (int j = 0; j < jsonProvidedProducts.length(); j++) {
        JSONObject jsonProvidedProduct = (JSONObject) jsonProvidedProducts.get(j);
        providedProductNamesFromActivationKeyPool.add(jsonProvidedProduct.getString("productName"));
        providedProductIdsFromActivationKeyPool.add(jsonProvidedProduct.getString("productId"));
    }
    if (assertConsumptionIsLimitedToThisPoolOnly) {
        Assert.assertEquals(consumedProductSubscriptions.size(), 1, "Expecting only one consumed product subscription.");
        ProductSubscription consumedProductSubscription = consumedProductSubscriptions.get(0);
        if (jsonPool.has("accountNumber")) {
            Assert.assertEquals(consumedProductSubscription.accountNumber.longValue(), jsonPool.getLong("accountNumber"), "The consumed product subscription comes from the same accountNumber as the pool added in the activation key.");
        } else {
            Assert.assertNull(consumedProductSubscription.accountNumber, "The consumed product subscription has no accountNumber since the pool added in the activation key had no accountNumber.");
        }
        if (jsonPool.has("contractNumber")) {
            Assert.assertEquals(consumedProductSubscription.contractNumber.intValue(), jsonPool.getInt("contractNumber"), "The consumed product subscription comes from the same contractNumber as the pool added in the activation key.");
        } else {
            Assert.assertNull(consumedProductSubscription.contractNumber, "The consumed product subscription has no contractNumber since the pool added in the activation key had no contractNumber.");
        }
        if (addQuantity != null) {
            Assert.assertEquals(consumedProductSubscription.quantityUsed, addQuantity, "The consumed product subscription is using the same quantity as requested by the pool added in the activation key.");
        } else {
            // valid after Bug 1023568 - [RFE] bind requests using activation keys that do not specify a quantity should automatically use the quantity needed to achieve compliance
            Assert.assertTrue(consumedProductSubscription.quantityUsed >= 1, "The actual consumed product subscription quantity of '" + consumedProductSubscription.quantityUsed + "' is >= 1 to achieve compliance since the quantity requested by the pool added in the activation key was null (result of RFE bugzilla 1023568).");
            // if this subscription was stackable, then assert that all of the installed products provided by this subscription are fully subscribed
            if (consumedProductSubscription.subscriptionType.equals("Stackable")) {
                for (InstalledProduct installedProduct : clienttasks.getCurrentlyInstalledProducts()) {
                    if (providedProductIdsFromActivationKeyPool.contains(installedProduct.productId)) {
                        // arch can be defined as a comma seperated string
                        Set<String> installedProductArches = new HashSet<String>(Arrays.asList(installedProduct.arch.split("\\s*,\\s*")));
                        if (installedProductArches.contains("x86")) {
                            installedProductArches.add("i386");
                            installedProductArches.add("i486");
                            installedProductArches.add("i586");
                            installedProductArches.add("i686");
                        }
                        if (installedProductArches.contains(clienttasks.arch) || installedProductArches.contains("ALL")) {
                            Assert.assertEquals(installedProduct.status, "Subscribed", "Installed Product '" + installedProduct.productName + "' provided by pool '" + consumedProductSubscription.productName + "' attached from a Smart ActivationKey (quantity='" + addQuantity + /*null*/
                            "') should be fully compliant.");
                            Assert.assertTrue(installedProduct.statusDetails.isEmpty(), "When Installed Product '" + installedProduct.productName + "' provided by pool '" + consumedProductSubscription.productName + "' attached from a Smart ActivationKey (quantity='" + addQuantity + /*null*/
                            "') is Subscribed, then it's Status Details should be empty.");
                        } else {
                            Assert.assertEquals(installedProduct.status, "Partially Subscribed", "When Installed Product '" + installedProduct.productName + "' provided by pool '" + consumedProductSubscription.productName + "' attached from a Smart ActivationKey (quantity='" + addQuantity + /*null*/
                            "') mismatches the system architecture, then it should be partially compliant.");
                            Assert.assertEquals(installedProduct.statusDetails.get(0), /*assumes only one detail*/
                            String.format("Supports architecture %s but the system is %s.", installedProduct.arch, clienttasks.arch), "When Installed Product '" + installedProduct.productName + "' provided by pool '" + consumedProductSubscription.productName + "' attached from a Smart ActivationKey (quantity='" + addQuantity + /*null*/
                            "') mismatches the system architecture, then the Status Details should state this.");
                        }
                    }
                }
            }
        }
        Assert.assertTrue(consumedProductSubscription.provides.containsAll(providedProductNamesFromActivationKeyPool) && providedProductNamesFromActivationKeyPool.containsAll(consumedProductSubscription.provides), "The consumed product subscription provides all the expected products " + providedProductNamesFromActivationKeyPool + " from the provided products of the pool added in the activation key.");
    } else {
        // after implementation of bug 908671, these three lines are replaced more efficiently by two lines
        // List<ProductSubscription> subsetOfConsumedProductSubscriptions = ProductSubscription.findAllInstancesWithMatchingFieldFromList("accountNumber", new BigInteger(jsonPool.getString("accountNumber")), consumedProductSubscriptions);
        // ProductSubscription consumedProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("contractNumber", new Integer(jsonPool.getString("contractNumber")), subsetOfConsumedProductSubscriptions);
        // Assert.assertNotNull(consumedProductSubscription,"Found a consumed product subscription whose account number '"+jsonPool.getLong("accountNumber")+"' AND contract number '"+jsonPool.getInt("contractNumber")+"' match the pool added to the activation key.");
        ProductSubscription consumedProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("poolId", jsonPool.getString("id"), consumedProductSubscriptions);
        Assert.assertNotNull(consumedProductSubscription, "Found a consumed product subscription that came from pool id '" + jsonPool.getString("id") + "' that was added to the activation key.");
        Assert.assertTrue(consumedProductSubscription.provides.containsAll(providedProductNamesFromActivationKeyPool) && providedProductNamesFromActivationKeyPool.containsAll(consumedProductSubscription.provides), "The consumed product subscription provides all the expected products " + providedProductNamesFromActivationKeyPool + " from the provided products of the pool added in the activation key.");
    }
}
Also used : JSONObject(org.json.JSONObject) InstalledProduct(rhsm.data.InstalledProduct) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) HashSet(java.util.HashSet)

Example 13 with ProductSubscription

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

the class ActivationKeyTests method testRegisterWithListOfCommaSeparatedActivationKeys.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21802", "RHEL7-51619" }, 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 many activation keys with one added pool per key and then register with --activationkey=comma_separated_string_of_keys asserting all the pools get consumed", groups = { "Tier3Tests", "blockedByBug-878986", "blockedByBug-979492", "blockedByBug-1040101" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testRegisterWithListOfCommaSeparatedActivationKeys() 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);
    // process each of the pools adding them to an individual activation key
    List<String> activationKeyNames = new ArrayList<String>();
    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;
        // create an activation key
        String activationKeyName = String.format("ActivationKey%sWithPool%sForOrg_%s", System.currentTimeMillis(), jsonPool.getString("id"), 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()));
        // 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);
        activationKeyNames.add(activationKeyName);
    }
    if (addQuantity == null)
        addQuantity = 1;
    // assemble the comma separated list of activation key names
    String commaSeparatedActivationKeyNames = "";
    for (String activationKeyName : activationKeyNames) commaSeparatedActivationKeyNames += activationKeyName + ",";
    // strip off trailing comma
    commaSeparatedActivationKeyNames = commaSeparatedActivationKeyNames.replaceFirst(",$", "");
    // register with the activation key specified as a single string
    SSHCommandResult registerResult = clienttasks.register(null, null, sm_clientOrg, null, null, null, null, null, null, null, commaSeparatedActivationKeyNames, 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(), activationKeyNames.size(), "Expecting a new entitlement cert file in '" + clienttasks.entitlementCertDir + "' for each of the single pooled activation keys used during register.");
}
Also used : HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) JSONObject(org.json.JSONObject) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 14 with ProductSubscription

use of rhsm.data.ProductSubscription 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 15 with ProductSubscription

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

the class BrandingTests method testRemoveSubscriptionsForFlexibleBranding.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-19956", "RHEL7-51005" }, 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 remove attached subscriptions and verify tests for Flexible Branding", // depend on priority instead of dependsOnMethods={"testAttachSubscriptionsForFlexibleBranding"},
priority = 101, groups = { "Tier1Tests" }, enabled = true)
public void testRemoveSubscriptionsForFlexibleBranding() {
    // loop through all the attached subscriptions and remove them while running tests for branding
    for (ProductSubscription productSubscription : clienttasks.getCurrentlyConsumedProductSubscriptions()) {
        String brandNameBeforeUnsubscribing = getCurrentBrandName();
        String brandNameStatBeforeUnsubscribing = getCurrentBrandNameFileStat();
        String prettyNameBeforeUnsubscribing = getCurrentPrettyName();
        log.info("The flexible brand name prior to unsubscribing from subscription '" + productSubscription.productName + "' is currently '" + brandNameBeforeUnsubscribing + "'.");
        clienttasks.unsubscribe_(null, productSubscription.serialNumber, null, null, null, null, null);
        verifySystemsExpectedBrandedNameAfterEvent(brandNameBeforeUnsubscribing, brandNameStatBeforeUnsubscribing, prettyNameBeforeUnsubscribing, "unsubscribing from '" + productSubscription.productName + "'");
    }
}
Also used : ProductSubscription(rhsm.data.ProductSubscription) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Aggregations

ProductSubscription (rhsm.data.ProductSubscription)90 Test (org.testng.annotations.Test)82 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)72 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)56 SkipException (org.testng.SkipException)46 ArrayList (java.util.ArrayList)41 SubscriptionPool (rhsm.data.SubscriptionPool)38 SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)31 JSONObject (org.json.JSONObject)31 BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)23 HashMap (java.util.HashMap)22 BigInteger (java.math.BigInteger)20 EntitlementCert (rhsm.data.EntitlementCert)17 InstalledProduct (rhsm.data.InstalledProduct)16 Calendar (java.util.Calendar)15 JSONArray (org.json.JSONArray)13 File (java.io.File)10 GregorianCalendar (java.util.GregorianCalendar)10 HashSet (java.util.HashSet)6 ConsumerCert (rhsm.data.ConsumerCert)6