Search in sources :

Example 46 with EntitlementCert

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

the class RHUITests method testDownloadRHUIISOFromFileRepo.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-22305", "RHEL7-55202" }, 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 = "download an expected RHUI iso from an expected file repoUrl", // RHEL-6-RHUI-2-LATEST-Server-x86_64-DVD.iso ERROR 404: Not Found. https://projects.engineering.redhat.com/browse/RCMPROJ-6571
groups = { "Tier1Tests", "blockedByBug-860516", "blockedByBug-894184", "blockedByBug-1427516" }, dependsOnMethods = { "testConsumeRHUISubscriptionProduct" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testDownloadRHUIISOFromFileRepo() {
    if (sm_rhuiDownloadIso.equals(""))
        throw new SkipException("Skipping this test when no value was given for the RHUI Download ISO");
    File downloadedIsoFile = new File("/tmp/" + sm_rhuiDownloadIso);
    RemoteFileTasks.runCommandAndAssert(client, "rm -rf " + downloadedIsoFile, 0);
    // find the repo for the isos
    ContentNamespace contentNamespaceForIso = null;
    for (EntitlementCert entitlementCert : clienttasks.getCurrentEntitlementCerts()) {
        for (ContentNamespace contentNamespace : entitlementCert.contentNamespaces) {
            if (contentNamespace.label.equals(sm_rhuiRepoIdForIsos)) {
                contentNamespaceForIso = contentNamespace;
                break;
            }
        }
    }
    Assert.assertNotNull(contentNamespaceForIso, "Found expected ContentNamespace to repoId '" + sm_rhuiRepoIdForIsos + "' for rhui isos after subscribe to '" + sm_rhuiSubscriptionProductId + "'.");
    String repoUrl = clienttasks.baseurl + contentNamespaceForIso.downloadUrl;
    // assert available repos for "Red Hat Enterprise Linux Server from RHUI" (when not a server, no content should exist)
    List<Repo> repos = clienttasks.getCurrentlySubscribedRepos();
    if (clienttasks.releasever.contains("Server")) {
        Assert.assertMore(repos.size(), 0, "When consuming RHUI Product ID '" + sm_rhuiSubscriptionProductId + "' on a Server '" + clienttasks.releasever + "' system, repo content should be available.");
    } else {
        Assert.assertEquals(repos.size(), 0, "When consuming RHUI Product ID '" + sm_rhuiSubscriptionProductId + "' on a non-Server '" + clienttasks.releasever + "' system, repo content should NOT be available.");
        // RHEL-6.1-RHUI-2.0-LATEST-Server-x86_64-DVD.iso
        throw new SkipException("This system release is '" + clienttasks.releasever + "'.  RHUI ISO '" + sm_rhuiDownloadIso + "' requires Server for downloading.");
    }
    // substitute the yum vars
    // http://www.centos.org/docs/5/html/5.2/Deployment_Guide/s1-yum-useful-variables.html
    // http://www.centos.org/docs/5/html/5.2/Deployment_Guide/s1-yum-useful-variables.html
    String arch = Arrays.asList("i686", "i486", "i386").contains(clienttasks.arch) ? "i386" : clienttasks.arch;
    // RHEL-6.1-RHUI-2.0-LATEST-Server-x86_64-DVD.iso
    if (!sm_rhuiDownloadIso.contains(arch))
        throw new SkipException("When this system's arch (" + arch + ") is substituted into the repoUrl (" + repoUrl + "), it will not find RHUI ISO (" + sm_rhuiDownloadIso + ") for downloading.");
    repoUrl = repoUrl.replaceFirst("\\$releasever", clienttasks.releasever);
    repoUrl = repoUrl.replaceFirst("\\$basearch", arch);
    File entitlementKeyFile = clienttasks.getEntitlementCertKeyFileCorrespondingToEntitlementCertFile(entitlementCertFile);
    // $ wget  --certificate=<Content Certificate>	https://cdn.redhat.com/content/dist/rhel/rhui/server/6/6Server/x86_64/rhui/2.0/iso/RHEL-6.1-RHUI-2.0-LATEST-Server-x86_64-DVD.iso
    // wget --no-check-certificate --certificate=/etc/pki/entitlement/7658526340059785943.pem --private-key=/etc/pki/entitlement/7658526340059785943-key.pem --output-document=/tmp/RHEL-6.1-RHUI-2.0-LATEST-Server-x86_64-DVD.iso -- https://cdn.redhat.com/content/dist/rhel/rhui/server/6/6Server/x86_64/rhui/2.0/iso/RHEL-6.1-RHUI-2.0-LATEST-Server-x86_64-DVD.iso
    RemoteFileTasks.runCommandAndAssert(client, "wget --no-check-certificate --certificate=" + entitlementCertFile + " --private-key=" + entitlementKeyFile + " --output-document=" + downloadedIsoFile + " -- " + repoUrl + "/" + sm_rhuiDownloadIso, 0);
    Assert.assertTrue(RemoteFileTasks.testExists(client, downloadedIsoFile.getPath()), "Expected RHUI Download ISO was downloaded.");
}
Also used : ContentNamespace(rhsm.data.ContentNamespace) EntitlementCert(rhsm.data.EntitlementCert) Repo(rhsm.data.Repo) SkipException(org.testng.SkipException) File(java.io.File) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 47 with EntitlementCert

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

the class InteroperabilityTests method testYumPluginMessageCase0.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-36531", "RHEL7-51304" }, 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 = "Tier2")
@Test(description = "When registered to RHSM (and all subscriptions have expired), the subscription-manager yum plugin should inform that: The subscription for following product(s) has expired: etc.", groups = { "Tier2Tests", "YumPluginMessageCase_Tests", "blockedByBug-818383", "blockedByBug-832119", "blockedByBug-871146", "blockedbyBug-901612", "blockedbyBug-1017354", "blockedByBug-1087620", "blockedByBug-1058380", "blockedByBug-1122772" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testYumPluginMessageCase0() throws JSONException, Exception {
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (List<String>) null, null, null, null, true, false, null, null, null, null);
    // import an expired certificate
    File expiredCertFile = new File(System.getProperty("automation.dir", null) + "/certs/Expiredcert.pem");
    RemoteFileTasks.putFile(client, expiredCertFile.getPath(), "/tmp/Expiredcert.pem", "0644");
    if (clienttasks.isPackageVersion("subscription-manager", "<", "1.17.10-1")) {
        // subscription-manager commit b93e59482563b9e3e972a928233bef7ebf885ea1	// Bug 1251516: Disable import when registered
        clienttasks.importCertificate("/tmp/Expiredcert.pem");
    } else {
        // after fix for bug 1251516, I can no longer use importCertificate while registered; instead we'll simply copy the expired cert to /etc/pki/entitlement ...
        client.runCommandAndWait("cp /tmp/Expiredcert.pem " + clienttasks.getConfFileParameter(clienttasks.rhsmConfFile, "rhsm", "entitlementCertDir"));
    // ... to avoid this usability error:
    // 201608261038:58.987 - FINE: ssh root@jsefler-rhel7.usersys.redhat.com subscription-manager import --certificate=/tmp/Expiredcert.pem
    // 201608261038:59.747 - FINE: Stdout:
    // 201608261038:59.747 - FINE: Stderr: Error: You may not import certificates into a system that is registered to a subscription management service.
    }
    EntitlementCert expiredEntitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(new File("/tmp/Expiredcert.pem"));
    // assert the interoperable registration message (without any current subscriptions)
    SSHCommandResult result = client.runCommandAndWait("yum repolist --disableplugin=rhnplugin --enableplugin=subscription-manager");
    String expectedMsgRHSM = "This system is registered to Red Hat Subscription Management, but is not receiving updates. You can use subscription-manager to assign subscriptions.";
    // subscription-manager commit 5e4b42e1c99472085a44118dd231e7ddd161937a	// https://github.com/candlepin/subscription-manager/pull/1512
    if (clienttasks.isPackageVersion("subscription-manager", ">=", "1.18.4-1"))
        expectedMsgRHSM = "This system is registered with an entitlement server, but is not receiving updates. You can use subscription-manager to assign subscriptions.";
    if (// Bug 901612 - Subscription-manager-s yum plugin prints warning to stdout instead of stderr.	// Bug 901612 was reverted by Bug 1017354
    clienttasks.isPackageVersion("subscription-manager", "<", "1.12.2-1"))
        // Bug 901612 - Subscription-manager-s yum plugin prints warning to stdout instead of stderr.	// Bug 901612 was reverted by Bug 1017354
        Assert.assertTrue(result.getStdout().contains(expectedMsgRHSM), "When registered to RHSM (and all subscriptions have expired), the subscription-manager yum plugin stdout should inform that:\n" + expectedMsgRHSM + "\n");
    else if (// Bug 1058380 was reverted by Bug 1122772
    clienttasks.isPackageVersion("subscription-manager", ">=", "1.12.11-1"))
        // Bug 1058380 was reverted by Bug 1122772
        Assert.assertTrue(result.getStdout().contains(expectedMsgRHSM), "When registered to RHSM (and all subscriptions have expired), the subscription-manager yum plugin stdout should inform that:\n" + expectedMsgRHSM + "\n");
    else
        Assert.assertTrue(!(result.getStdout() + result.getStderr()).contains(expectedMsgRHSM), "When registered to RHSM (and all subscriptions have expired), the subscription-manager yum plugin stdout should NO LONGER inform that:\n" + expectedMsgRHSM + "\nBugzilla https://bugzilla.redhat.com/show_bug.cgi?id=1058380 was used to remove this usability messaging implemented for https://bugzilla.redhat.com/show_bug.cgi?id=818383");
    // assert the expired subscriptions message
    expectedMsgRHSM = "*** WARNING ***\nThe subscription for following product(s) has expired:";
    for (ProductNamespace productNamespace : expiredEntitlementCert.productNamespaces) expectedMsgRHSM += "\n" + "  - " + productNamespace.name;
    expectedMsgRHSM += "\n" + "You no longer have access to the repositories that provide these products.  It is important that you apply an active subscription in order to resume access to security and other critical updates. If you don't have other active subscriptions, you can renew the expired subscription.";
    // Bug 901612 - Subscription-manager-s yum plugin prints warning to stdout instead of stderr.	// Bug 901612 was reverted by Bug 1017354
    Assert.assertTrue(result.getStdout().contains(expectedMsgRHSM), "When registered to RHSM (and all subscriptions have expired), the subscription-manager yum plugin stdout should inform that:\n" + expectedMsgRHSM + "\n");
    // assert the interoperable registration message (with current subscriptions)
    // clienttasks.subscribeToSubscriptionPool(clienttasks.getCurrentlyAvailableSubscriptionPools().get(0));	// will fail with java.lang.AssertionError: The list of consumed products is entitled 'Consumed Subscriptions'. expected:<true> but was:<false>
    clienttasks.subscribe(null, null, clienttasks.getCurrentlyAvailableSubscriptionPools().get(0).poolId, null, null, null, null, null, null, null, null, null, null);
    if (clienttasks.isPackageVersion("subscription-manager", "<", "1.17.10-1")) {
        // subscription-manager commit b93e59482563b9e3e972a928233bef7ebf885ea1	// Bug 1251516: Disable import when registered
        clienttasks.importCertificate("/tmp/Expiredcert.pem");
    } else {
        // after fix for bug 1251516, I can no longer use importCertificate while registered; instead we'll simply copy the expired cert to /etc/pki/entitlement ...
        client.runCommandAndWait("cp /tmp/Expiredcert.pem " + clienttasks.getConfFileParameter(clienttasks.rhsmConfFile, "rhsm", "entitlementCertDir"));
    // ... to avoid this usability error:
    // 201608261038:58.987 - FINE: ssh root@jsefler-rhel7.usersys.redhat.com subscription-manager import --certificate=/tmp/Expiredcert.pem
    // 201608261038:59.747 - FINE: Stdout:
    // 201608261038:59.747 - FINE: Stderr: Error: You may not import certificates into a system that is registered to a subscription management service.
    }
    result = client.runCommandAndWait("yum repolist --disableplugin=rhnplugin --enableplugin=subscription-manager");
    expectedMsgRHSM = "This system is receiving updates from Red Hat Subscription Management.";
    // NOT TRUE ANYMORE Assert.assertTrue(result.getStdout().contains(expectedMsgRHSM), "When registered to RHSM (and some subscriptions have expired), the subscription-manager yum plugin stdout should inform that:\n"+expectedMsgRHSM+"\n");	// Bug 901612 - Subscription-manager-s yum plugin prints warning to stdout instead of stderr.	// Bug 901612 was reverted by Bug 1017354
    // commit 39eadae14eead4bb79978e52d38da2b3e85cba57 1017354: remove msg printed to stderr via yum
    Assert.assertTrue(!(result.getStdout() + result.getStderr()).contains(expectedMsgRHSM), "When registered to RHSM, the subscription-manager yum plugin NO LONGER informs that:\n" + expectedMsgRHSM + "\nFor justification, see https://bugzilla.redhat.com/show_bug.cgi?id=1017354#c12");
    // assert the expired subscriptions message again
    expectedMsgRHSM = "*** WARNING ***\nThe subscription for following product(s) has expired:";
    for (ProductNamespace productNamespace : expiredEntitlementCert.productNamespaces) expectedMsgRHSM += "\n" + "  - " + productNamespace.name;
    expectedMsgRHSM += "\n" + "You no longer have access to the repositories that provide these products.  It is important that you apply an active subscription in order to resume access to security and other critical updates. If you don't have other active subscriptions, you can renew the expired subscription.";
    // Bug 901612 - Subscription-manager-s yum plugin prints warning to stdout instead of stderr.	// Bug 901612 was reverted by Bug 1017354
    Assert.assertTrue(result.getStdout().contains(expectedMsgRHSM), "When registered to RHSM (and some subscriptions have expired), the subscription-manager yum plugin stdout should inform that:\n" + expectedMsgRHSM + "\n");
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) File(java.io.File) ProductNamespace(rhsm.data.ProductNamespace) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 48 with EntitlementCert

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

the class ImportTests method setupEntitlemenCertsForImportBeforeClass.

@BeforeClass(groups = { "setup" }, dependsOnMethods = { "restartCertFrequencyBeforeClass" })
public void setupEntitlemenCertsForImportBeforeClass() throws Exception {
    // register
    // clienttasks.unregister(null,null,null);	// avoid Bug 733525 - [Errno 2] No such file or directory: '/etc/pki/entitlement'
    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);
    // change the entitlementCertDir to a temporary location to store all of the entitlements that will be used for importing
    originalEntitlementCertDir = clienttasks.getConfFileParameter(clienttasks.rhsmConfFile, "entitlementCertDir");
    clienttasks.updateConfFileParameter(clienttasks.rhsmConfFile, "entitlementCertDir", importEntitlementsDir);
    clienttasks.removeAllCerts(false, true, false);
    // create a directory where we can create bundled entitlement/key certificates for import
    RemoteFileTasks.runCommandAndAssert(client, "mkdir -p " + importCertificatesDir, Integer.valueOf(0));
    RemoteFileTasks.runCommandAndAssert(client, "rm -f " + importCertificatesDir + "/*", Integer.valueOf(0));
    // generate a future entitlement for the ImportACertificateForAFutureEntitlement_Test
    List<List<Object>> futureSystemSubscriptionPoolsDataAsListOfLists = new ArrayList<List<Object>>();
    boolean isGuest = Boolean.valueOf(clienttasks.getFactValue("virt.is_guest"));
    for (List<Object> futureSystemSubscriptionPoolsDataList : getAllFutureSystemSubscriptionPoolsDataAsListOfLists()) {
        // filter out...  Pool is restricted when it is temporary and begins in the future:  '8a9087e34c715b2e014c715c44c40be0'
        if (CandlepinTasks.isPoolRestrictedToUnmappedVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, ((SubscriptionPool) futureSystemSubscriptionPoolsDataList.get(0)).poolId))
            continue;
        // filter out...  Pool is restricted to physical systems: '8a9086d3443c043501443c052aec1298'.
        if (CandlepinTasks.isPoolRestrictedToPhysicalSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, ((SubscriptionPool) futureSystemSubscriptionPoolsDataList.get(0)).poolId) && isGuest)
            continue;
        // filter out...  Pool is restricted to virtual systems: '8a90f85734205a010134205ae8d80403'.
        if (CandlepinTasks.isPoolRestrictedToVirtualSystems(sm_clientUsername, sm_clientPassword, sm_serverUrl, ((SubscriptionPool) futureSystemSubscriptionPoolsDataList.get(0)).poolId) && !isGuest)
            continue;
        futureSystemSubscriptionPoolsDataAsListOfLists.add(futureSystemSubscriptionPoolsDataList);
    }
    if (futureSystemSubscriptionPoolsDataAsListOfLists.isEmpty()) {
        log.warning("Could not find a pool to a future system subscription.");
    } else {
        SubscriptionPool futurePool = (SubscriptionPool) getRandomListItem(futureSystemSubscriptionPoolsDataAsListOfLists).get(0);
        // subscribe to the future subscription pool
        SSHCommandResult subscribeResult = clienttasks.subscribe(null, null, futurePool.poolId, null, null, null, null, null, null, null, null, null, null);
        // assert that the granted entitlement cert begins in the future
        Calendar now = new GregorianCalendar();
        now.setTimeInMillis(System.currentTimeMillis());
        EntitlementCert futureEntitlementCert = clienttasks.getEntitlementCertCorrespondingToSubscribedPool(futurePool);
        Assert.assertNotNull(futureEntitlementCert, "Found the newly granted EntitlementCert on the client after subscribing to future subscription pool '" + futurePool.poolId + "'.");
        // TEMPORARY WORKAROUND
        Boolean invokeWorkaroundWhileBugIsOpen = true;
        // Bug 1440180 - Attaching a future pool that will start one year from today changes the supposedly inactive subscription to current subscription
        String bugId = "1440180";
        try {
            if (invokeWorkaroundWhileBugIsOpen && BzChecker.getInstance().isBugOpen(bugId)) {
                log.fine("Invoking workaround for " + BzChecker.getInstance().getBugState(bugId).toString() + " Bugzilla " + bugId + ".  (https://bugzilla.redhat.com/show_bug.cgi?id=" + bugId + ")");
                SubscriptionManagerCLITestScript.addInvokedWorkaround(bugId);
            } else {
                invokeWorkaroundWhileBugIsOpen = false;
            }
        } catch (BugzillaAPIException be) {
        /* ignore exception */
        } catch (RuntimeException re) {
        /* ignore exception */
        }
        if (invokeWorkaroundWhileBugIsOpen) {
            log.warning("Skipping validity and startDate assertions on future entitlement while bug " + bugId + " is open.");
        } else {
            // END OF WORKAROUND
            Assert.assertTrue(futureEntitlementCert.validityNotBefore.after(now), "The newly granted EntitlementCert is not valid until the future.  EntitlementCert: " + futureEntitlementCert);
            Assert.assertTrue(futureEntitlementCert.orderNamespace.startDate.after(now), "The newly granted EntitlementCert's OrderNamespace starts in the future.  OrderNamespace: " + futureEntitlementCert.orderNamespace);
        }
        // remember the futureEntitlementCertFile
        futureEntitlementCertFile = clienttasks.getEntitlementCertFileFromEntitlementCert(futureEntitlementCert);
    }
    // subscribe to all available pools (so as to create valid entitlement cert/key pairs)
    clienttasks.subscribeToTheCurrentlyAvailableSubscriptionPoolsCollectively();
    // assemble a list of entitlements that we can use for import (excluding the future cert)
    entitlementCertFiles = clienttasks.getCurrentEntitlementCertFiles();
    if (futureEntitlementCertFile != null)
        entitlementCertFiles.remove(entitlementCertFiles.indexOf(futureEntitlementCertFile));
    // create a bundled consumer cert/key file for a negative import test
    client.runCommandAndWait("cat " + clienttasks.consumerCertFile() + " " + clienttasks.consumerKeyFile() + " > " + consumerCertFile);
    // restore the entitlementCertDir
    clienttasks.updateConfFileParameter(clienttasks.rhsmConfFile, "entitlementCertDir", originalEntitlementCertDir);
    // unregister client so as to test imports while not registered
    clienttasks.unregister(null, null, null, null);
    // assert that we have some valid entitlement certs for import testing
    if (entitlementCertFiles.size() < 1)
        throw new SkipException("Could not generate valid entitlement certs for these ImportTests.");
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) ArrayList(java.util.ArrayList) GregorianCalendar(java.util.GregorianCalendar) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ArrayList(java.util.ArrayList) List(java.util.List) SkipException(org.testng.SkipException) SubscriptionPool(rhsm.data.SubscriptionPool) BeforeClass(org.testng.annotations.BeforeClass)

Example 49 with EntitlementCert

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

the class ImportTests method testImportAnEntitlementVersion1CertAndKeyFromFile.

// Test methods ***********************************************************************
@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20027", "RHEL7-51043" }, 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 = "subscription-manager: import a valid version 1.0 entitlement cert/key bundle and verify subscriptions are consumed", groups = { "Tier1Tests", "blockedByBug-962520", "blockedByBug-1443693" }, enabled = true)
public // @ImplementsNitrateTest(caseId=)
void testImportAnEntitlementVersion1CertAndKeyFromFile() {
    // assemble a valid bundled cert/key certificate file
    File importEntitlementCertFile = entitlementV1CertFiles.get(randomGenerator.nextInt(entitlementV1CertFiles.size()));
    File importEntitlementKeyFile = clienttasks.getEntitlementCertKeyFileCorrespondingToEntitlementCertFile(importEntitlementCertFile);
    File importCertificateFile = new File(importV1CertificatesDir + File.separator + importEntitlementCertFile.getName());
    client.runCommandAndWait("cat " + importEntitlementCertFile + " " + importEntitlementKeyFile + " > " + importCertificateFile);
    // once imported, what should the entitlement cert file be?
    File expectedEntitlementCertFile = new File(clienttasks.entitlementCertDir + File.separator + importCertificateFile.getName());
    File expectedEntitlementKeyFile = clienttasks.getEntitlementCertKeyFileCorrespondingToEntitlementCertFile(expectedEntitlementCertFile);
    // make sure the expected entitlement files do not exist before our test and that no subscriptions are consumed
    Assert.assertTrue(!RemoteFileTasks.testExists(client, expectedEntitlementCertFile.getPath()), "Before attempting the import, asserting that expected destination for the entitlement cert file does NOT yet exist (" + expectedEntitlementCertFile + ").");
    Assert.assertTrue(!RemoteFileTasks.testExists(client, expectedEntitlementKeyFile.getPath()), "Before attempting the import, asserting that expected destination for the entitlement key file does NOT yet exist (" + expectedEntitlementKeyFile + ").");
    Assert.assertEquals(clienttasks.getCurrentlyConsumedProductSubscriptions().size(), 0, "Should not be consuming any subscriptions before the import.");
    // show the contents of the file about to be imported
    log.info("Following is the contents of the certificate file about to be imported...");
    client.runCommandAndWait("cat " + importCertificateFile);
    // attempt an entitlement cert import from a valid bundled file
    clienttasks.importCertificate(importCertificateFile.getPath());
    // verify that the expectedEntitlementCertFile now exists
    Assert.assertTrue(RemoteFileTasks.testExists(client, expectedEntitlementCertFile.getPath()), "After attempting the import, the expected destination for the entitlement cert file should now exist (" + expectedEntitlementCertFile + ").");
    // verify that the expectedEntitlementKeyFile also exists
    Assert.assertTrue(RemoteFileTasks.testExists(client, expectedEntitlementKeyFile.getPath()), "After attempting the import, the expected destination for the entitlement key file should now exist (" + expectedEntitlementKeyFile + ").");
    // assert that the contents of the imported files match the originals
    log.info("Asserting that the imported entitlement cert file contents match the original...");
    RemoteFileTasks.runCommandAndAssert(client, "diff -w " + expectedEntitlementCertFile + " " + importEntitlementCertFile, 0);
    log.info("Asserting that the imported entitlement key file contents match the original...");
    RemoteFileTasks.runCommandAndAssert(client, "diff -w " + expectedEntitlementKeyFile + " " + importEntitlementKeyFile, 0);
    // finally verify that we are now consuming subscriptions
    Assert.assertTrue(clienttasks.getCurrentlyConsumedProductSubscriptions().size() > 0, "After importing a valid Version 1.0 certificate, we should be consuming subscriptions.");
    // finally verify that imported entitlement is indeed version 1.0
    EntitlementCert importedEntitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(expectedEntitlementCertFile);
    Assert.assertEquals(importedEntitlementCert.version, "1.0", "The version of the imported certificate/key file.");
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) File(java.io.File) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 50 with EntitlementCert

use of rhsm.data.EntitlementCert 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

EntitlementCert (rhsm.data.EntitlementCert)94 Test (org.testng.annotations.Test)63 TestDefinition (com.github.redhatqe.polarize.metadata.TestDefinition)58 SkipException (org.testng.SkipException)39 ArrayList (java.util.ArrayList)38 File (java.io.File)36 ImplementsNitrateTest (com.redhat.qe.auto.tcms.ImplementsNitrateTest)35 SubscriptionPool (rhsm.data.SubscriptionPool)33 SSHCommandResult (com.redhat.qe.tools.SSHCommandResult)30 JSONObject (org.json.JSONObject)29 ContentNamespace (rhsm.data.ContentNamespace)26 ProductCert (rhsm.data.ProductCert)23 BugzillaAPIException (com.redhat.qe.auto.bugzilla.BugzillaAPIException)17 BigInteger (java.math.BigInteger)17 ProductSubscription (rhsm.data.ProductSubscription)17 List (java.util.List)16 Calendar (java.util.Calendar)11 HashMap (java.util.HashMap)11 ProductNamespace (rhsm.data.ProductNamespace)11 HashSet (java.util.HashSet)8