Search in sources :

Example 46 with ProductCert

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

the class HighAvailabilityTests method assertRhelServerBeforeClass.

// Candidates for an automated Test:
// TODO Bug 654442 - pidplugin and rhsmplugin should add to the yum "run with pkgs. list" https://github.com/RedHatQE/rhsm-qe/issues/156
// TODO Bug 705068 - product-id plugin displays "duration" https://github.com/RedHatQE/rhsm-qe/issues/157
// TODO Bug 706265 - product cert is not getting removed after removing all the installed packages from its repo using yum https://github.com/RedHatQE/rhsm-qe/issues/158
// TODO Bug 740773 - product cert lost after installing a pkg from cdn-internal.rcm-test.redhat.com https://github.com/RedHatQE/rhsm-qe/issues/159
/* 
	------------------------------------------------------------
	Notes from alikins
	summary: if you register, and subscribe to say, openshift
	(but not rhel), and install something from openshift, you
	can have your productid deleted as inactive. This doesn't
	seem to be a new behaviour. If you are subscribe to rhel
	(even with no rhel packages installed), you seem to be okay.
	
	The openshift guys have ran into this with 6.3, and I belive 6.4 betas.
	There scenario was:
	
	install rhel
	register
	subscribe to rhel (I belive...)
	subscribe to openshift
	yum install something from openshift
	*boom* rhel product id goes away
	
	MUST WE BE SUBSCRIBED TO RHEL?
	> Testing this, it seems that if rhel is just subscribe to (no packages
	> installed or updated) it seems to be okay.
	>
	> However, I'm not really sure I understand why...
	> Adrian
	>
	>
	
	Our logic is this:
	
	if you have a subscription, and if you have a product id which is not
	backed by a susbcription repo hen we should remove it. I think we need
	to change this logic. Is there a bug open for this? If not, I will.
	-- bk

	----------------------------------------------------------------------
	A couple of thoughts from dgregor regarding bug 859197:

	* A product cert should only be removed when there are no packages left
	on the system that came from the corresponding repo.  So, in the above
	example, as long as there are packages on the system that came from
	anaconda-RedHatEnterpriseLinux-201211201732.x86_64, the product cert
	should stay regardless of whether
	anaconda-RedHatEnterpriseLinux-201211201732.x86_64 is still a defined
	repository.

	* Do we ever associate a product cert with multiple repos?  Let's say I
	install a package from rhel-ha-for-rhel-6-server-beta-rpms and that
	pulls in product cert 83.  I then install a second package from
	rhel-ha-for-rhel-6-server-rpms, which is also mapped to cert 83.  If I
	remove that first package, we still want cert 83 on disk.

	-- Dennis
	HOW TO DETERMINE WHAT REPO A PACKAGE CAME FROM

	# yum history package-info filesystem
	Transaction ID : 1
	Begin time     : Sat Oct 13 19:38:17 2012
	Package        : filesystem-2.4.30-3.el6.x86_64
	State          : Install
	Size           : 0
	Build host     : x86-004.build.bos.redhat.com
	Build time     : Tue Jun 28 10:13:32 2011
	Packager       : Red Hat, Inc. <http://bugzilla.redhat.com/bugzilla>
	Vendor         : Red Hat, Inc.
	License        : Public Domain
	URL            : https://fedorahosted.org/filesystem
	Source RPM     : filesystem-2.4.30-3.el6.src.rpm
	Commit Time    : Tue Jun 28 08:00:00 2011
	Committer      : Ondrej Vasik <ovasik@redhat.com>
	Reason         : user
	>From repo      : anaconda-RedHatEnterpriseLinux-201206132210.x86_64
	Installed by   : System <unset>
	
	
	*/
// Configuration methods ***********************************************************************
@BeforeClass(groups = "setup")
public void assertRhelServerBeforeClass() {
    if (clienttasks == null)
        return;
    if (!clienttasks.releasever.contains("Server")) {
        // "5Server" or "6Server"
        throw new SkipException("High Availability tests are only executable on a RHEL Server.");
    }
    // Skip distributions of RHEL that do not support High Availability
    ProductCert rhelProductCert = clienttasks.getCurrentRhelProductCert();
    if (Arrays.asList(new String[] { "294", /* Red Hat Enterprise Linux Server for ARM */
    "419", /* Red Hat Enterprise Linux for ARM 64 */
    "420", /* Red Hat Enterprise Linux for Power 9 */
    "434", /* Red Hat Enterprise Linux for IBM System z (Structure A) */
    "363", /* Red Hat Enterprise Linux for ARM 64 Beta */
    "362", /* Red Hat Enterprise Linux for Power 9 Beta */
    "433" /* Red Hat Enterprise Linux for IBM System z (Structure A) Beta */
    }).contains(rhelProductCert.productId)) {
        throw new SkipException("High Availability is not offered on '" + rhelProductCert.productName + "'");
    }
    // [root@ibm-js22-vios-02-lp2 ~]# curl -k -u stage_test_2:PASSWORD http://rubyvip.web.stage.ext.phx2.redhat.com:80/clonepin/candlepin/pools/8a99f9843c01ccba013c037a0fa0015a | python -m simplejson/tool
    // "productAttributes": [
    // {
    // "created": "2013-07-22T19:47:22.000+0000",
    // "id": "8a99f98340076c17014007ec04435b89",
    // "name": "arch",
    // "productId": "RH1149049",
    // "updated": "2013-07-22T19:47:22.000+0000",
    // "value": "x86,x86_64,ia64,ppc,ppc64"       <====  NOTE THAT RH1149049 WILL BE AVAILABLE FOR CONSUMPTION ON THESE ARCHES FOR ALL RELEASES OF RHEL (RHEL6 Server ppc64 WILL NOT HAVE ANY CONTENT)
    // },
    // Red Hat Enterprise Linux Server
    serverProductId = "69";
    // Red Hat Enterprise Linux High Availability (for RHEL Server)
    haProductId = "83";
    if (clienttasks.arch.equals("x86_64")) {
        if (clienttasks.redhatReleaseX.equals("5"))
            haPackage1Fetch = "http://download.devel.redhat.com/released/RHEL-5-Server/U7/x86_64/os/Cluster/ipvsadm-1.24-13.el5.x86_64.rpm";
        if (clienttasks.redhatReleaseX.equals("6"))
            haPackage1Fetch = "http://download.devel.redhat.com/released/RHEL-6/6.1/Server/x86_64/os/Packages/ccs-0.16.2-35.el6.x86_64.rpm";
        if (clienttasks.redhatReleaseX.equals("7"))
            haPackage1Fetch = "http://download.devel.redhat.com/released/RHEL-7/7.0/Server/x86_64/os/addons/HighAvailability/omping-0.0.4-6.el7.x86_64.rpm";
        // is usually 69; but could be HTB 230 on RHEL7 or 135 on RHEL6
        serverProductId = rhelProductCert.productId;
    }
    if (clienttasks.arch.startsWith("i")) {
        // i386 i686
        if (clienttasks.redhatReleaseX.equals("5"))
            haPackage1Fetch = "http://download.devel.redhat.com/released/RHEL-5-Server/U7/i386/os/Cluster/ipvsadm-1.24-13.el5.i386.rpm";
        if (clienttasks.redhatReleaseX.equals("6"))
            haPackage1Fetch = "http://download.devel.redhat.com/released/RHEL-6/6.1/Server/i386/os/Packages/ccs-0.16.2-35.el6.i686.rpm";
        // is usually 69;
        serverProductId = rhelProductCert.productId;
    }
    if (clienttasks.arch.equals("ia64")) {
        if (clienttasks.redhatReleaseX.equals("5"))
            haPackage1Fetch = "http://download.devel.redhat.com/released/RHEL-5-Server/U7/ia64/os/Cluster/ipvsadm-1.24-13.el5.ia64.rpm";
    }
    if (clienttasks.arch.startsWith("ppc")) {
        // ppc ppc64
        // Red Hat Enterprise Linux for IBM POWER
        serverProductId = "74";
        if (clienttasks.redhatReleaseX.equals("5"))
            haPackage1Fetch = "http://download.devel.redhat.com/released/RHEL-5-Server/U7/ppc/os/Cluster/ipvsadm-1.24-13.el5.ppc.rpm";
        if (clienttasks.redhatReleaseX.equals("6"))
            throw new SkipException("Although available for consumption, High Availability content is not offered on RHEL6 arch '" + clienttasks.arch + "'.");
        if (clienttasks.redhatReleaseX.equals("7"))
            throw new SkipException("Although available for consumption, High Availability content is not offered on RHEL7 arch '" + clienttasks.arch + "'.");
    }
    if (clienttasks.arch.startsWith("s390")) {
        // s390 s390x
        // Red Hat Enterprise Linux for IBM System z
        serverProductId = "72";
        if (clienttasks.redhatReleaseX.equals("5"))
            throw new SkipException("High Availability is not offered on arch '" + clienttasks.arch + "'.");
        if (clienttasks.redhatReleaseX.equals("6"))
            throw new SkipException("High Availability is not offered on arch '" + clienttasks.arch + "'.");
        if (clienttasks.redhatReleaseX.equals("7")) {
            // Red Hat Enterprise Linux High Availability (for IBM z Systems)
            haProductId = "300";
            haPackage1Fetch = "http://download.devel.redhat.com/released/RHEL-7/7.2/Server/s390x/os/addons/HighAvailability/omping-0.0.4-6.el7.s390x.rpm";
        }
        if (Float.valueOf(clienttasks.redhatReleaseXY) < 7.2)
            throw new SkipException("High Availability is not offered on arch '" + clienttasks.arch + "' release '" + clienttasks.redhatReleaseXY + "'.");
    }
    if (clienttasks.redhatReleaseX.equals("5")) {
        // or  Cluster_Administration-as-IN
        haPackage1 = "ipvsadm";
        // or Cluster_Administration-bn-IN
        haPackage2 = "system-config-cluster";
        haSupportedArches = Arrays.asList("x86_64", "x86", "i386", "i686", "ia64", "ppc", "ppc64");
    }
    if (clienttasks.redhatReleaseX.equals("6")) {
        haPackage1 = "ccs";
        haPackage2 = "cluster-glue-libs";
        haSupportedArches = Arrays.asList("x86_64", "x86", "i386", "i686");
    }
    if (clienttasks.redhatReleaseX.equals("7")) {
        haPackage1 = "omping";
        // 03/2017 started failing due to dependency... Error: Package: resource-agents-3.9.5-82.el7_3.6.x86_64 (rhel-ha-for-rhel-7-server-rpms) Requires: /usr/sbin/mount.cifs
        haPackage2 = "resource-agents";
        haPackage2 = "libqb";
        haSupportedArches = Arrays.asList("x86_64", "s390x");
    }
}
Also used : ProductCert(rhsm.data.ProductCert) SkipException(org.testng.SkipException) BeforeClass(org.testng.annotations.BeforeClass)

Example 47 with ProductCert

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

the class SubscriptionManagerCLITestScript method getSystemSubscriptionPoolProductDataAsListOfLists.

/**
 * @param matchSystemHardware - make sure that atLeastOneProvidedProductSatisfiesArch
 * @param matchSystemSoftware - makes sure that atLeastOneProvidedProductIsInstalled
 * @return
 * @throws Exception
 */
protected List<List<Object>> getSystemSubscriptionPoolProductDataAsListOfLists(boolean matchSystemHardware, boolean matchSystemSoftware) throws Exception {
    JSONObject jsonStatus = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(/*authenticator*/
    null, /*password*/
    null, sm_serverUrl, "/status"));
    List<List<Object>> ll = new ArrayList<List<Object>>();
    if (!isSetupBeforeSuiteComplete)
        return ll;
    List<String> productIdsAddedToSystemSubscriptionPoolProductData = new ArrayList<String>();
    // is this system virtual
    boolean isSystemVirtual = Boolean.valueOf(clienttasks.getFactValue("virt.is_guest"));
    // get the owner key for clientusername, clientpassword
    String consumerId = clienttasks.getCurrentConsumerId();
    if (consumerId == null)
        consumerId = clienttasks.getCurrentConsumerId(clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, Boolean.TRUE, false, null, null, null, null));
    String ownerKey = CandlepinTasks.getOwnerKeyOfConsumerId(sm_clientUsername, sm_clientPassword, sm_serverUrl, consumerId);
    // java.lang.RuntimeException: org.json.JSONException: JSONObject["owner"] not found.
    // ^^^ this will be thrown when the consumerId has been deleted at the server, but the client does not know it.
    Calendar now = new GregorianCalendar();
    now.setTimeInMillis(System.currentTimeMillis());
    // get the currently installed product certs
    List<ProductCert> productCerts = clienttasks.getCurrentProductCerts();
    // process all of the subscriptions/pools belonging to ownerKey...
    // decide whether to loop through the subscription objects or pool objects
    JSONArray jsonSubs;
    if (SubscriptionManagerTasks.isVersion(jsonStatus.getString("version"), ">=", "2.1.1-1")) {
        // candlepin commit 9c448315c843c0a20167236af7591359d895613a Discontinue ambiguous subscription resources in sharing world
        // /pools?add_future=true&include=productId;
        jsonSubs = new JSONArray(CandlepinTasks.getResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/owners/" + ownerKey + "/pools?add_future=true"));
    } else {
        /* 7/10/2015 devel consciously decided to drop @Verify(value = Owner.class, subResource = SubResource.SUBSCRIPTIONS) on this GET method starting with candlepin-2.0.
			 * 7/10/2015 modifying this testware to simply raise the authentication credentials to admin
			jsonSubs = new JSONArray(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername,sm_clientPassword,sm_serverUrl,"/owners/"+ownerKey+"/subscriptions"));
			 */
        jsonSubs = new JSONArray(CandlepinTasks.getResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/owners/" + ownerKey + "/subscriptions"));
        ;
    }
    // loop through all of the jsonSubs
    for (int i = 0; i < jsonSubs.length(); i++) {
        JSONObject jsonSub = (JSONObject) jsonSubs.get(i);
        // skip derived pools
        if (jsonSub.has("subscriptionSubKey") && !jsonSub.isNull("subscriptionSubKey")) {
            // null (custom pools not originating from a subscription)
            if (jsonSub.getString("subscriptionSubKey").toLowerCase().equals("derived")) {
                // master, derived,
                continue;
            }
        }
        // skip future subscriptions that are not valid today (at this time now)
        // "startDate":"2012-02-08T00:00:00.000+0000"
        Calendar startDate = parseISO8601DateString(jsonSub.getString("startDate"), "GMT");
        // "endDate":"2013-02-07T00:00:00.000+0000"
        Calendar endDate = parseISO8601DateString(jsonSub.getString("endDate"), "GMT");
        if (!(startDate.before(now) && endDate.after(now)))
            continue;
        // get the product id name and attributes
        JSONArray jsonProductAttributes;
        String productId;
        String productName;
        if (jsonSub.has("product")) {
            // when jsonSub comes from /owners/{ownerKey}/subscriptions
            productId = jsonSub.getJSONObject("product").getString("id");
            productName = jsonSub.getJSONObject("product").getString("name");
            jsonProductAttributes = jsonSub.getJSONObject("product").getJSONArray("attributes");
        } else {
            // when jsonSub comes from /owners/{ownerKey}/pools
            productId = jsonSub.getString("productId");
            productName = jsonSub.getString("productName");
            jsonProductAttributes = jsonSub.getJSONArray("productAttributes");
        }
        // skip subscriptions that have already been added to SystemSubscriptionPoolProductData
        if (productIdsAddedToSystemSubscriptionPoolProductData.contains(productId))
            continue;
        // process this subscription productId
        // assumed
        boolean productAttributesPassRulesCheck = true;
        String productAttributeSocketsValue = "";
        List<String> productSupportedArches = new ArrayList<String>();
        String productAttributeStackingIdValue = null;
        for (int j = 0; j < jsonProductAttributes.length(); j++) {
            // loop product attributes to find a stacking_id
            if (((JSONObject) jsonProductAttributes.get(j)).getString("name").equals("stacking_id")) {
                productAttributeStackingIdValue = ((JSONObject) jsonProductAttributes.get(j)).getString("value");
                break;
            }
        }
        for (int j = 0; j < jsonProductAttributes.length(); j++) {
            JSONObject jsonProductAttribute = (JSONObject) jsonProductAttributes.get(j);
            String attributeName = jsonProductAttribute.getString("name");
            // String attributeValue = jsonProductAttribute.getString("value");
            String attributeValue = jsonProductAttribute.isNull("value") ? null : jsonProductAttribute.getString("value");
            if (attributeName.equals("arch")) {
                // Note: the arch attribute can be a comma separated list of values
                productSupportedArches.addAll(Arrays.asList(attributeValue.trim().split(" *, *")));
                // Note: x86 is a general arch to cover all 32-bit intel microprocessors
                if (productSupportedArches.contains("x86")) {
                    productSupportedArches.addAll(Arrays.asList("i386", "i486", "i586", "i686"));
                }
                if (!productSupportedArches.contains("ALL") && !productSupportedArches.contains(clienttasks.arch)) {
                    productAttributesPassRulesCheck = false;
                }
            }
            if (attributeName.equals("variant")) {
            // if (!attributeValue.equalsIgnoreCase("ALL") && !attributeValue.equalsIgnoreCase(clienttasks.variant)) {
            // productAttributesPassRulesCheck = false;
            // }
            }
            if (attributeName.equals("type")) {
            }
            if (attributeName.equals("multi-entitlement")) {
            }
            if (attributeName.equals("warning_period")) {
            }
            if (attributeName.equals("version")) {
            // if (!attributeValue.equalsIgnoreCase(clienttasks.version)) {
            // productAttributesPassRulesCheck = false;
            // }
            }
            if (attributeName.equals("requires_consumer_type")) {
                if (!attributeValue.equalsIgnoreCase(ConsumerType.system.toString())) {
                    productAttributesPassRulesCheck = false;
                }
            }
            if (attributeName.equals("stacking_id")) {
            // productAttributeStackingIdValue = attributeValue; // was already searched for above
            }
            if (attributeName.equals("physical_only")) {
                if (attributeValue != null && Boolean.valueOf(attributeValue) && isSystemVirtual) {
                    productAttributesPassRulesCheck = false;
                }
            }
            if (attributeName.equals("virt_only")) {
                if (attributeValue != null && Boolean.valueOf(attributeValue) && !isSystemVirtual) {
                    productAttributesPassRulesCheck = false;
                }
            }
            if (attributeName.equals("sockets")) {
                productAttributeSocketsValue = attributeValue;
                // Because this subscription is stackable, it better not be filtered out from availability based on the system's sockets.
                if (productAttributeStackingIdValue == null) {
                    SOCKETS: {
                        // if the sockets attribute is not numeric (e.g. null or "unlimited"),  then this subscription should be available to this client
                        try {
                            Integer.valueOf(attributeValue);
                        } catch (NumberFormatException e) {
                            // do not mark productAttributesPassRulesCheck = false;
                            log.warning("THE VALIDITY OF SUBSCRIPTION productName='" + productName + "' productId='" + productId + "' IS QUESTIONABLE.  IT HAS A '" + attributeName + "' PRODUCT ATTRIBUTE OF '" + attributeValue + "' WHICH IS NOT NUMERIC.  SIMPLY IGNORING THIS ATTRIBUTE.");
                            break SOCKETS;
                        }
                        // Example: a 1 socket physical or virtual subscription pool should be available for consumption my a 2 socket virt guest
                        if (isSystemVirtual) {
                            // do not mark productAttributesPassRulesCheck = false;
                            break SOCKETS;
                        }
                        // if the sockets attribute is zero, then this subscription should be available to this client
                        if (Integer.valueOf(attributeValue) == 0) {
                        // do not mark productAttributesPassRulesCheck = false;
                        } else // if the socket count on this client exceeds the sockets attribute, then this subscription should NOT be available to this client
                        if (Integer.valueOf(attributeValue) < Integer.valueOf(clienttasks.sockets)) {
                            if (matchSystemHardware)
                                productAttributesPassRulesCheck = false;
                        }
                    }
                }
            }
        }
        if (productAttributesPassRulesCheck) {
            // process this subscription's providedProducts
            // assumed
            Boolean atLeastOneProvidedProductIsInstalled = false;
            // assumed
            Boolean atLeastOneProvidedProductSatisfiesArch = false;
            JSONArray jsonBundledProductData = new JSONArray();
            JSONArray jsonProvidedProducts = (JSONArray) jsonSub.getJSONArray("providedProducts");
            // effectively true when no provided products are installed
            if (jsonProvidedProducts.length() == 0)
                atLeastOneProvidedProductIsInstalled = true;
            // effectively true when no provided products are installed
            if (jsonProvidedProducts.length() == 0)
                atLeastOneProvidedProductSatisfiesArch = true;
            for (int k = 0; k < jsonProvidedProducts.length(); k++) {
                String providedProductId;
                if (((JSONObject) jsonProvidedProducts.get(k)).has("id")) {
                    // when jsonSub comes from /owners/{ownerKey}/subscriptions
                    providedProductId = ((JSONObject) jsonProvidedProducts.get(k)).getString("id");
                } else {
                    // when jsonSub comes from /owners/{ownerKey}/pools
                    providedProductId = ((JSONObject) jsonProvidedProducts.get(k)).getString("productId");
                }
                JSONObject jsonProvidedProduct = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/owners/" + ownerKey + "/products/" + providedProductId));
                String providedProductName = jsonProvidedProduct.getString("name");
                // process this providedProducts attributes
                JSONArray jsonProvidedProductAttributes = jsonProvidedProduct.getJSONArray("attributes");
                // assumed
                boolean providedProductAttributesPassRulesCheck = true;
                for (int l = 0; l < jsonProvidedProductAttributes.length(); l++) {
                    JSONObject jsonProvidedProductAttribute = (JSONObject) jsonProvidedProductAttributes.get(l);
                    String attributeName = jsonProvidedProductAttribute.getString("name");
                    // String attributeValue = jsonProvidedProductAttribute.getString("value");
                    String attributeValue = jsonProvidedProductAttribute.isNull("value") ? null : jsonProvidedProductAttribute.getString("value");
                    /* 6/17/2011 The availability of a Subscription depends only on its attributes and NOT the attributes of its provided products.
						 * You will get ALL of its provided product even if they don't make arch/socket sense.
						 * In this case you could argue that it is not subscription-manager's job to question the meaningfulness of the subscription and its provided products.
						 * For this reason, I am commenting out all the providedProductAttributesPassRulesCheck = false; ... (except "type")
						 */
                    if (attributeName.equals("arch")) {
                        // Note: the arch attribute can be a comma separated list of values
                        List<String> supportedArches = new ArrayList<String>(Arrays.asList(attributeValue.trim().split(" *, *")));
                        // Note: x86 is a general term to cover all 32-bit intel microprocessors
                        if (supportedArches.contains("x86")) {
                            supportedArches.addAll(Arrays.asList("i386", "i486", "i586", "i686"));
                        }
                        if (!productSupportedArches.isEmpty() && !productSupportedArches.containsAll(supportedArches)) {
                            log.warning("THE VALIDITY OF SUBSCRIPTION productName='" + productName + "' productId='" + productId + "' WITH PROVIDED PRODUCT '" + providedProductName + "' IS QUESTIONABLE.  THE PROVIDED PRODUCT '" + providedProductId + "' ARCH ATTRIBUTE '" + attributeValue + "' IS NOT A SUBSET OF THE TOP LEVEL SUBSCRIPTION PRODUCT '" + productId + "' ARCH ATTRIBUTE '" + productSupportedArches + "'.");
                        }
                        if (!supportedArches.contains("ALL") && !supportedArches.contains(clienttasks.arch)) {
                        // providedProductAttributesPassRulesCheck = false;
                        } else {
                            atLeastOneProvidedProductSatisfiesArch = true;
                        }
                    }
                    if (attributeName.equals("variant")) {
                    // if (!attributeValue.equalsIgnoreCase("ALL") && !attributeValue.equalsIgnoreCase(clienttasks.variant)) {
                    // providedProductAttributesPassRulesCheck = false;
                    // }
                    }
                    if (attributeName.equals("type")) {
                        if (attributeValue.equals("MKT")) {
                            // provided products of type "MKT" should not pass the rules check  e.g. providedProductName="Awesome OS Server Bundled"
                            // do not comment out!
                            providedProductAttributesPassRulesCheck = false;
                        }
                    }
                    if (attributeName.equals("version")) {
                    // if (!attributeValue.equalsIgnoreCase(clienttasks.version)) {
                    // providedProductAttributesPassRulesCheck = false;
                    // }
                    }
                    if (attributeName.equals("requires_consumer_type")) {
                        if (!attributeValue.equalsIgnoreCase(ConsumerType.system.toString())) {
                        // providedProductAttributesPassRulesCheck = false;
                        }
                    }
                    if (attributeName.equals("sockets")) {
                    // if (!attributeValue.equals(productAttributeSocketsValue)) {
                    // log.warning("THE VALIDITY OF SUBSCRIPTION productName='"+productName+"' productId='"+productId+"' WITH PROVIDED PRODUCT '"+providedProductName+"' IS QUESTIONABLE.  THE PROVIDED PRODUCT '"+providedProductId+"' SOCKETS ATTRIBUTE '"+attributeValue+"' DOES NOT MATCH THE TOP LEVEL SUBSCRIPTION PRODUCT '"+productId+"' SOCKETS ATTRIBUTE '"+productAttributeSocketsValue+"'.");
                    // }
                    // if (!productAttributeSocketsValue.equals("") && Integer.valueOf(attributeValue) > Integer.valueOf(productAttributeSocketsValue)) {
                    // //providedProductAttributesPassRulesCheck = false;
                    // }
                    }
                }
                if (providedProductAttributesPassRulesCheck) {
                    JSONObject bundledProduct = new JSONObject(String.format("{productName:'%s', productId:'%s'}", providedProductName, providedProductId));
                    jsonBundledProductData.put(bundledProduct);
                }
                // is this provided product already installed
                if (ProductCert.findFirstInstanceWithMatchingFieldFromList("productId", providedProductId, productCerts) != null)
                    atLeastOneProvidedProductIsInstalled = true;
            }
            // String systemProductId, JSONArray bundledProductDataAsJSONArray
            if (matchSystemSoftware && atLeastOneProvidedProductIsInstalled) {
                ll.add(Arrays.asList(new Object[] { productId, jsonBundledProductData }));
                productIdsAddedToSystemSubscriptionPoolProductData.add(productId);
            } else if (matchSystemHardware && atLeastOneProvidedProductSatisfiesArch) {
                ll.add(Arrays.asList(new Object[] { productId, jsonBundledProductData }));
                productIdsAddedToSystemSubscriptionPoolProductData.add(productId);
            } else if (!matchSystemSoftware && !matchSystemHardware) {
                ll.add(Arrays.asList(new Object[] { productId, jsonBundledProductData }));
                productIdsAddedToSystemSubscriptionPoolProductData.add(productId);
            }
        }
    }
    // WARNING: When true, this will fail the testVerifyNormalAvailablePoolsFromSubscriptionsPassTheHardwareRulesCheck
    if (Boolean.valueOf(getProperty("sm.debug.dataProviders.minimize", "false")))
        ll = ll.subList(0, 1);
    return ll;
}
Also used : GregorianCalendar(java.util.GregorianCalendar) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) GregorianCalendar(java.util.GregorianCalendar) JSONArray(org.json.JSONArray) ProductCert(rhsm.data.ProductCert) JSONObject(org.json.JSONObject) List(java.util.List) ArrayList(java.util.ArrayList) JSONObject(org.json.JSONObject)

Example 48 with ProductCert

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

the class HighAvailabilityTests method testProductDatabaseIsInSyncWithInstalledProducts.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20071", "RHEL7-55180" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier1")
@Test(description = "verify product database and installed products are in sync", groups = { "Tier1Tests" }, priority = 12, dependsOnMethods = {}, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testProductDatabaseIsInSyncWithInstalledProducts() throws JSONException {
    // get the installed products and product database map
    List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts();
    Map<String, List<String>> productIdRepoMap = clienttasks.getProductIdToReposMap();
    // List<ProductCert> installedProductCerts = clienttasks.getCurrentProductCerts();	// VALID BEFORE Bugs 1080007 1080012 - [RFE] Include default product certificate in redhat-release
    List<ProductCert> installedProductCerts = clienttasks.getProductCerts(clienttasks.productCertDir);
    // assert that product database and installed products are in sync
    int installedProductCertCount = 0;
    for (ProductCert installedProductCert : installedProductCerts) {
        // skip productCerts from TESTDATA
        if (installedProductCert.file.getName().endsWith("_.pem")) {
            log.info("Skipping assertion that product cert '" + installedProductCert.file + "' (manually installed from generated candlepin TESTDATA) is accounted for in the product database '" + clienttasks.productIdJsonFile + "'.");
            continue;
        }
        // TEMPORARY WORKAROUND
        if (installedProductCert.productId.equals("135") || /* Red Hat Enterprise Linux 6 Server HTB */
        installedProductCert.productId.equals("155")) /* Red Hat Enterprise Linux 6 Workstation HTB */
        {
            List<ProductCert> installedProductDefaultCerts = clienttasks.getProductCerts(clienttasks.productCertDefaultDir);
            if (ProductCert.findFirstInstanceWithMatchingFieldFromList("productId", installedProductCert.productId, installedProductDefaultCerts) != null) {
                boolean invokeWorkaroundWhileBugIsOpen = true;
                // Bug 1318584 - /etc/pki/product-default/*.pem missing in certain variants
                String bugId = "1318584";
                try {
                    if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
                        log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
                        SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
                    } else {
                        invokeWorkaroundWhileBugIsOpen = false;
                    }
                } catch (BugzillaAPIException be) {
                /* ignore exception */
                } catch (RuntimeException re) {
                /* ignore exception */
                }
                if (invokeWorkaroundWhileBugIsOpen) {
                    // only skip when the installed HTB product came from the /etc/pki/product-default location due to bug 1318584
                    log.warning("Skipping assertion that Database '" + clienttasks.productIdJsonFile + "' maps installed product id '" + installedProductCert.productId + "' while bug '" + bugId + "' is open.");
                    continue;
                }
            }
        }
        // END OF WORKAROUND
        installedProductCertCount++;
        Assert.assertTrue(productIdRepoMap.containsKey(installedProductCert.productId), "Database '" + clienttasks.productIdJsonFile + "' contains installed product id: " + installedProductCert.productId);
        log.info("Database '" + clienttasks.productIdJsonFile + "' maps installed product id '" + installedProductCert.productId + "' to repo '" + productIdRepoMap.get(installedProductCert.productId) + "'.");
    }
    for (String productId : productIdRepoMap.keySet()) {
        Assert.assertNotNull(InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", productId, installedProducts), "Database '" + clienttasks.productIdJsonFile + "' product id '" + productId + "' is among the installed products.");
    }
    Assert.assertEquals(productIdRepoMap.keySet().size(), installedProductCertCount, "The product id database size matches the number of installed products (excluding TESTDATA products).");
}
Also used : InstalledProduct(rhsm.data.InstalledProduct) ArrayList(java.util.ArrayList) List(java.util.List) ProductCert(rhsm.data.ProductCert) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 49 with ProductCert

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

the class HighAvailabilityTests method testYumRemoveFirstHighAvailabilityPackageAndAssertInstalledProductCerts.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20079", "RHEL7-55188" }, 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 = "yum remove first High Availability package cman and assert installed products", groups = { "Tier1Tests", "blockedByBug-859197" }, priority = 70, dependsOnMethods = { "testYumInstallFirstHighAvailabilityPackageAndAssertInstalledProductCerts" }, // dependsOnMethods={"testYumRemoveSecondHighAvailabilityPackageAndAssertInstalledProductCerts"},
enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testYumRemoveFirstHighAvailabilityPackageAndAssertInstalledProductCerts() {
    ProductCert haProductCert = ProductCert.findFirstInstanceWithMatchingFieldFromList("productId", haProductId, clienttasks.getCurrentProductCerts());
    // assemble all of the provided tags from the haProductCert
    List<String> haProductCertProvidedTags = Arrays.asList(haProductCert.productNamespace.providedTags.split("\\s*,\\s*"));
    boolean haProductCertProvidesATagStartingWithRhel = false;
    for (String tag : haProductCertProvidedTags) {
        if (tag.toLowerCase().startsWith("rhel")) {
            log.info("Found HA ProductCert tag '" + tag + "' that begins with rhel*.");
            haProductCertProvidesATagStartingWithRhel = true;
        }
    }
    // remove the final package installed from the ha repo
    clienttasks.yumRemovePackage(haPackage1);
    // get the currently installed products
    List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts();
    // verify High Availability product id is uninstalled
    // but it should only be uninstalled if it does not provide an rhel* tags as stated in https://bugzilla.redhat.com/show_bug.cgi?id=859197#c15
    InstalledProduct haInstalledProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", haProductId, installedProducts);
    /* valid before https://bugzilla.redhat.com/show_bug.cgi?id=859197#c15
		if (Integer.valueOf(clienttasks.redhatReleaseX) > 5) Assert.assertNull(haInstalledProduct, "The High Availability product id '"+haProductId+"' should no longer be installed after successful removal of High Availability package '"+haPackage1+"' (because no High Availability packages should be installed).");
		else												 Assert.assertNotNull(haInstalledProduct, "The High Availability product id '"+haProductId+"' should no longer be installed after successful removal of High Availability package '"+haPackage1+"' (because no High Availability packages should be installed); HOWEVER on RHEL5 the productId plugin does NOT remove product certs.  This is a known issue.");
		*/
    if (haProductCertProvidesATagStartingWithRhel) {
        Assert.assertNotNull(haInstalledProduct, "The High Availability product id '" + haProductId + "' should remain installed despite successful removal of the final High Availability package '" + haPackage1 + "' (because the High Availability product cert provides a tag that starts with rhel* even when the last High Availability package installed was removed).");
    } else {
        Assert.assertNull(haInstalledProduct, "The High Availability product id '" + haProductId + "' should no longer be installed after successful removal of High Availability package '" + haPackage1 + "' (because no High Availability packages should be installed AND because none of its provided tags start with rhel*).");
    }
    // verify RHEL product server id 69 remains installed
    InstalledProduct serverInstalledProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", serverProductId, installedProducts);
    Assert.assertNotNull(serverInstalledProduct, "The RHEL Server product id '" + serverProductId + "' should remain installed after successful removal of High Availability package '" + haPackage1 + "'.");
}
Also used : InstalledProduct(rhsm.data.InstalledProduct) ProductCert(rhsm.data.ProductCert) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 50 with ProductCert

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

the class ContentTests method testContentSetsEntitledFromSubscriptionPoolSatisfyTheSystemArch.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20081", "RHEL7-50720" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier1")
@Test(description = "Verify that all content sets granted from a subscription pool satisfy the system arch and subset the provided product's arch", groups = { "Tier1Tests", "blockedByBug-706187", "blockedByBug-975520" }, // "getAvailableSubscriptionPoolsData",
dataProvider = "getAllAvailableSubscriptionPoolsProvidingArchBasedContentData", enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testContentSetsEntitledFromSubscriptionPoolSatisfyTheSystemArch(SubscriptionPool pool) throws JSONException, Exception {
    List<String> providedProductIds = CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId);
    if (providedProductIds.isEmpty())
        throw new SkipException("This test is not applicable for a pool that provides no products.");
    JSONObject jsonStatus = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(/*authenticator*/
    null, /*password*/
    null, sm_serverUrl, "/status"));
    JSONObject jsonPool = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, "/pools/" + pool.poolId));
    // maintain a list of expected content sets
    Set<ContentNamespace> expectedContentNamespaceSet = new HashSet<ContentNamespace>();
    // maintain a list of unexpected content sets
    Set<ContentNamespace> unexpectedContentNamespaceSet = new HashSet<ContentNamespace>();
    for (String providedProductId : providedProductIds) {
        // get the product
        String path = "/products/" + providedProductId;
        // starting with candlepin-2.0.11 /products/<ID> are requested by /owners/<KEY>/products/<ID> OR /products/<UUID>
        if (SubscriptionManagerTasks.isVersion(jsonStatus.getString("version"), ">=", "2.0.11"))
            path = jsonPool.getJSONObject("owner").getString("href") + path;
        JSONObject jsonProduct = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, path));
        // get the product supported arches
        JSONArray jsonProductAttributes = jsonProduct.getJSONArray("attributes");
        List<String> productSupportedArches = new ArrayList<String>();
        for (int j = 0; j < jsonProductAttributes.length(); j++) {
            JSONObject jsonProductAttribute = (JSONObject) jsonProductAttributes.get(j);
            String attributeName = jsonProductAttribute.getString("name");
            String attributeValue = jsonProductAttribute.isNull("value") ? null : jsonProductAttribute.getString("value");
            if (attributeName.equals("arch")) {
                // Note: the arch attribute can be a comma separated list of values
                productSupportedArches.addAll(Arrays.asList(attributeValue.trim().split("\\s*,\\s*")));
                // Note: x86 is a general arch to cover all 32-bit intel microprocessors
                if (productSupportedArches.contains("x86")) {
                    productSupportedArches.addAll(Arrays.asList("i386", "i486", "i586", "i686"));
                }
            }
        }
        // get the provided product contents
        JSONArray jsonProductContents = jsonProduct.getJSONArray("productContent");
        for (int j = 0; j < jsonProductContents.length(); j++) {
            JSONObject jsonProductContent = (JSONObject) jsonProductContents.get(j);
            JSONObject jsonContent = jsonProductContent.getJSONObject("content");
            Map<String, String> certData = new HashMap<String, String>();
            // certData.put("", jsonContent.getString("id"));
            if (jsonContent.has("type") && !jsonContent.isNull("type"))
                certData.put("type", jsonContent.getString("type"));
            if (jsonContent.has("label") && !jsonContent.isNull("label"))
                certData.put("label", jsonContent.getString("label"));
            if (jsonContent.has("name") && !jsonContent.isNull("name"))
                certData.put("name", jsonContent.getString("name"));
            if (jsonContent.has("vendorId") && !jsonContent.isNull("vendorId"))
                certData.put("vendorId", jsonContent.getString("vendor"));
            if (jsonContent.has("downloadUrl") && !jsonContent.isNull("downloadUrl"))
                certData.put("downloadUrl", jsonContent.getString("contentUrl"));
            if (jsonContent.has("requiredTags") && !jsonContent.isNull("requiredTags"))
                certData.put("requiredTags", jsonContent.getString("requiredTags"));
            // certData.put("", jsonContent.getString("releaseVer"));
            if (jsonContent.has("gpgKeyUrl") && !jsonContent.isNull("gpgKeyUrl"))
                certData.put("gpgKeyUrl", jsonContent.getString("gpgUrl"));
            if (jsonContent.has("metadataExpire") && !jsonContent.isNull("metadataExpire"))
                certData.put("metadataExpire", String.valueOf(jsonContent.getInt("metadataExpire")));
            // certData.put("", jsonContent.getString("modifiedProductIds"));
            if (jsonContent.has("arches") && !jsonContent.isNull("arches"))
                certData.put("arches", jsonContent.getString("arches"));
            ContentNamespace contentNamespace = new ContentNamespace(certData);
            // // get modifiedProductIds for each of the productContents
            // JSONArray jsonModifiedProductIds = jsonContent.getJSONArray("modifiedProductIds");
            // for (int k = 0; k < jsonModifiedProductIds.length(); k++) {
            // String modifiedProductId = (String) jsonModifiedProductIds.get(k);
            // }
            // get this content supported arches
            Set<String> contentSupportedArches = new HashSet<String>();
            String jsonContentArches = null;
            if (jsonContent.has("arches") && !jsonContent.isNull("arches") && !jsonContent.getString("arches").isEmpty()) {
                jsonContentArches = jsonContent.getString("arches");
                contentSupportedArches.addAll(Arrays.asList(jsonContentArches.split("\\s*,\\s*")));
                // Note: x86 is a general arch to cover all 32-bit intel microprocessors
                if (contentSupportedArches.contains("x86"))
                    contentSupportedArches.addAll(Arrays.asList("i386", "i486", "i586", "i686"));
                // it contains an arch that matches the system
                if (contentSupportedArches.contains("ALL") || contentSupportedArches.contains("noarch") || contentSupportedArches.contains(clienttasks.arch)) {
                    expectedContentNamespaceSet.add(contentNamespace);
                } else {
                    unexpectedContentNamespaceSet.add(contentNamespace);
                }
            } else {
                // TODO: NOT SURE HOW TOLERANT WE WANT TO BE FOR CONTENT SETS THAT INHERIT FROM THEIR PRODUCTS
                if (productSupportedArches.contains("ALL") || productSupportedArches.contains(clienttasks.arch)) {
                    expectedContentNamespaceSet.add(contentNamespace);
                } else {
                    unexpectedContentNamespaceSet.add(contentNamespace);
                }
            }
        }
    }
    // conflict situation: if a subscription provides more than one product that both provide the same content but whose product's arch differs, then it is possible to have the content in both expectedContentLabels and unexpectedContentLabels; expectedContentLabels wins!
    for (ContentNamespace expectedContentNamespace : expectedContentNamespaceSet) {
        List<ContentNamespace> unexpectedContentNamespaceList = new ArrayList<ContentNamespace>();
        unexpectedContentNamespaceList.addAll(unexpectedContentNamespaceSet);
        ContentNamespace unexpectedContentNamespace = ContentNamespace.findFirstInstanceWithMatchingFieldFromList("label", expectedContentNamespace.label, unexpectedContentNamespaceList);
        if (unexpectedContentNamespace != null) {
            log.warning("Based on multiple products '" + providedProductIds + "' from subscription '" + pool.subscriptionName + "' with conflicting arches, content label '" + expectedContentNamespace.label + "' defined for arches '" + expectedContentNamespace.arches + "' will be provided.");
            unexpectedContentNamespaceSet.remove(unexpectedContentNamespace);
        }
    }
    if (expectedContentNamespaceSet.isEmpty() && unexpectedContentNamespaceSet.isEmpty())
        throw new SkipException("This test is not applicable for a pool whose provided products have no content sets.");
    // avoid throttling RateLimitExceededException from IT-Candlepin
    if (!poolIds.contains(pool.poolId) && CandlepinType.hosted.equals(sm_serverType)) {
        // strategically get a new consumer to avoid 60 repeated API calls from the same consumer
        // re-register as a new consumer
        clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String) null, null, null, null, true, false, null, null, null, null);
    }
    poolIds.add(pool.poolId);
    clienttasks.unsubscribe(true, (BigInteger) null, null, null, null, null, null);
    EntitlementCert entitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(clienttasks.subscribeToSubscriptionPool(pool, /*sm_serverAdminUsername*/
    sm_clientUsername, /*sm_serverAdminPassword*/
    sm_clientPassword, sm_serverUrl));
    // adjust the expectedContentNamespaces for modified product ids that are not installed
    // List<ProductCert> installedProductCerts = clienttasks.getCurrentProductCerts();
    List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    for (String providedProductId : providedProductIds) {
        // get the product
        String path = "/products/" + providedProductId;
        // starting with candlepin-2.0.11 /products/<ID> are requested by /owners/<KEY>/products/<ID> OR /products/<UUID>
        if (SubscriptionManagerTasks.isVersion(jsonStatus.getString("version"), ">=", "2.0.11"))
            path = jsonPool.getJSONObject("owner").getString("href") + path;
        JSONObject jsonProduct = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername, sm_clientPassword, sm_serverUrl, path));
        // get the provided product contents
        JSONArray jsonProductContents = jsonProduct.getJSONArray("productContent");
        for (int j = 0; j < jsonProductContents.length(); j++) {
            JSONObject jsonProductContent = (JSONObject) jsonProductContents.get(j);
            JSONObject jsonContent = jsonProductContent.getJSONObject("content");
            // get modifiedProductIds for each of the productContents
            JSONArray jsonModifiedProductIds = jsonContent.getJSONArray("modifiedProductIds");
            for (int k = 0; k < jsonModifiedProductIds.length(); k++) {
                String modifiedProductId = (String) jsonModifiedProductIds.get(k);
                String contentLabel = jsonContent.getString("label");
                // TODO: I do not believe this should check the installed products or all the current subscriptions' providedProductIds for this modifiedProductId
                // // if modifiedProductId is not installed, then the modifier jsonContent should NOT be among the expectedContentNamespaceSet
                // if (InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productId", modifiedProductId, installedProductCerts)==null) {
                // ContentNamespace contentNamespace = ContentNamespace.findFirstInstanceWithMatchingFieldFromList("label", jsonContent.getString("label"), new ArrayList<ContentNamespace>(expectedContentNamespaceSet));
                // if (contentNamespace!=null) {
                // log.warning("ContentNamespace label '"+contentNamespace.label+"' modifies product id '"+modifiedProductId+"' which is NOT installed and should therefore not be among the entitled content namespaces no matter what its arch ("+contentNamespace.arches+") may be.");
                // unexpectedContentNamespaceSet.add(contentNamespace);
                // expectedContentNamespaceSet.remove(contentNamespace);
                // }
                // }
                // DONE: Implemented the second thought by the following test block
                // if modifiedProductId is not provided by the currently consumed subscriptions, then the modifier jsonContent should NOT be among the expectedContentNamespaceSet
                Set<String> providedProductIdsByCurrentlyConsumedProductSubscriptions = new HashSet<String>();
                for (ProductSubscription productSubscription : consumedProductSubscriptions) {
                    for (String providedProductIdByCurrentlyConsumedProductSubscription : CandlepinTasks.getPoolProvidedProductIds(sm_clientUsername, sm_clientPassword, sm_serverUrl, pool.poolId)) {
                        providedProductIdsByCurrentlyConsumedProductSubscriptions.add(providedProductIdByCurrentlyConsumedProductSubscription);
                    }
                }
                if (!providedProductIdsByCurrentlyConsumedProductSubscriptions.contains(modifiedProductId)) {
                    ContentNamespace contentNamespace = ContentNamespace.findFirstInstanceWithMatchingFieldFromList("label", jsonContent.getString("label"), new ArrayList<ContentNamespace>(expectedContentNamespaceSet));
                    if (contentNamespace != null) {
                        log.warning("ContentNamespace label '" + contentNamespace.label + "' modifies product id '" + modifiedProductId + "' which is NOT provided by the currently consumed subscriptions and should therefore not be among the entitled content namespaces no matter what its arch (" + contentNamespace.arches + ") may be.");
                        unexpectedContentNamespaceSet.add(contentNamespace);
                        expectedContentNamespaceSet.remove(contentNamespace);
                        // to the next contentNamespace/jsonProductContent/jsonContent
                        break;
                    }
                }
            }
        }
    }
    // entitlement asserts
    List<String> actualEntitledContentLabels = new ArrayList<String>();
    for (ContentNamespace contentNamespace : entitlementCert.contentNamespaces) actualEntitledContentLabels.add(contentNamespace.label);
    for (ContentNamespace contentNamespace : expectedContentNamespaceSet) {
        Assert.assertTrue(actualEntitledContentLabels.contains(contentNamespace.label), "As expected, contentNamespace label '" + contentNamespace.label + "' defined for arches '" + contentNamespace.arches + "' requiredTags '" + contentNamespace.requiredTags + "' is included in the entitlement after subscribing to '" + pool.subscriptionName + "' on a '" + clienttasks.arch + "' system.");
    }
    for (ContentNamespace contentNamespace : unexpectedContentNamespaceSet) {
        Assert.assertTrue(!actualEntitledContentLabels.contains(contentNamespace.label), "As expected, contentNamespace label '" + contentNamespace.label + "' defined for arches '" + contentNamespace.arches + "' requiredTags '" + contentNamespace.requiredTags + "' is NOT included in the entitlement after subscribing to '" + pool.subscriptionName + "' on a '" + clienttasks.arch + "' system.");
    }
    // adjust the expectedContentNamespaces for requiredTags that are not provided by the installed productCerts' providedTags before checking the YumRepos
    List<ProductCert> installedProductCerts = clienttasks.getCurrentProductCerts();
    for (ContentNamespace contentNamespace : new HashSet<ContentNamespace>(expectedContentNamespaceSet)) {
        if (!clienttasks.areAllRequiredTagsProvidedByProductCerts(contentNamespace.requiredTags, installedProductCerts)) {
            log.warning("Entitled contentNamespace label '" + contentNamespace.label + "' defined for arches '" + contentNamespace.arches + "' has requiredTags '" + contentNamespace.requiredTags + "' that are NOT provided by the currently installed product certs.  This expected contentNamespace will be moved to the unexpected list when asserting the YumRepos next.");
            unexpectedContentNamespaceSet.add(contentNamespace);
            expectedContentNamespaceSet.remove(contentNamespace);
        }
    }
    // adjust the expectedContentNamespaces for type that does not equal "yum" before checking the YumRepos
    for (ContentNamespace contentNamespace : new HashSet<ContentNamespace>(expectedContentNamespaceSet)) {
        if (!contentNamespace.type.equals("yum")) {
            // "file", "kickstart"
            log.warning("Entitled contentNamespace label '" + contentNamespace.label + "' defined for arches '" + contentNamespace.arches + "' has type '" + contentNamespace.type + "'.  This expected contentNamespace will be moved to the unexpected list when asserting the YumRepos next.");
            unexpectedContentNamespaceSet.add(contentNamespace);
            expectedContentNamespaceSet.remove(contentNamespace);
        }
    }
    // YumRepo asserts
    List<String> actualYumRepoLabels = new ArrayList<String>();
    for (YumRepo yumRepo : clienttasks.getCurrentlySubscribedYumRepos()) actualYumRepoLabels.add(yumRepo.id);
    for (ContentNamespace contentNamespace : expectedContentNamespaceSet) {
        Assert.assertTrue(actualYumRepoLabels.contains(contentNamespace.label), "As expected, yum repo label '" + contentNamespace.label + "' defined for arches '" + contentNamespace.arches + "' requiredTags '" + contentNamespace.requiredTags + "' is included in " + clienttasks.redhatRepoFile + " after subscribing to '" + pool.subscriptionName + "' on a '" + clienttasks.arch + "' system.");
    }
    for (ContentNamespace contentNamespace : unexpectedContentNamespaceSet) {
        Assert.assertTrue(!actualYumRepoLabels.contains(contentNamespace.label), "As expected, yum repo label '" + contentNamespace.label + "' defined for arches '" + contentNamespace.arches + "' requiredTags '" + contentNamespace.requiredTags + "' is NOT included in in " + clienttasks.redhatRepoFile + " after subscribing to '" + pool.subscriptionName + "' on a '" + clienttasks.arch + "' system.");
    }
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) ProductCert(rhsm.data.ProductCert) ContentNamespace(rhsm.data.ContentNamespace) JSONObject(org.json.JSONObject) SkipException(org.testng.SkipException) YumRepo(rhsm.data.YumRepo) HashSet(java.util.HashSet) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Aggregations

ProductCert (rhsm.data.ProductCert)90 Test (org.testng.annotations.Test)60 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)54 SkipException (org.testng.SkipException)44 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)40 ArrayList (java.util.ArrayList)40 File (java.io.File)26 SubscriptionPool (rhsm.data.SubscriptionPool)24 EntitlementCert (rhsm.data.EntitlementCert)23 BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)22 InstalledProduct (rhsm.data.InstalledProduct)21 JSONObject (org.json.JSONObject)19 SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)17 List (java.util.List)16 ContentNamespace (rhsm.data.ContentNamespace)15 HashSet (java.util.HashSet)13 Calendar (java.util.Calendar)7 HashMap (java.util.HashMap)7 BigInteger (java.math.BigInteger)6 JSONArray (org.json.JSONArray)6