Search in sources :

Example 66 with EntitlementCert

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

the class ComplianceTests method testRhsmCompliancedWhenNoProductsAreInstalled.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-20066", "RHEL7-51090" }, 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 = "rhsm-complianced: verify rhsm-complianced -d -s reports a compliant status when no products are installed (and a warning period status when at least one entitlement cert is within its warning period)", groups = { "Tier1Tests", "cli.tests", "blockedbyBug-723336", "blockedByBug-991580", "blockedByBug-1395794" }, // dependsOnMethods={"testSystemCompliantFactWhenNoProductsAreInstalled"},
priority = 610, enabled = true)
public // @ImplementsTCMS(id="")
void testRhsmCompliancedWhenNoProductsAreInstalled() throws JSONException, Exception {
    if (!configureProductCertDirForNoProductsInstalledCompleted)
        throw new SkipException("Unsatisfied dependency configureProductCertDirForNoProductsInstalledCompleted=" + configureProductCertDirForNoProductsInstalledCompleted);
    if (clienttasks.getCurrentlyRegisteredOwnerKey() == null)
        throw new SkipException("Unsatisfied dependency - expected system to already have been registered during a preceding testcase.");
    String command = clienttasks.rhsmComplianceD + " -s -d";
    SSHCommandResult sshCommandResult;
    // verify the rhsmcomplianced status when there are entitlement certs within their warning period
    List<EntitlementCert> entitlementCertsWithinWarningPeriod = clienttasks.getCurrentEntitlementCertsWithinWarningPeriod();
    while (!entitlementCertsWithinWarningPeriod.isEmpty()) {
        // assert the rhsmcomplianced status
        // ssh root@jsefler-onprem-5server.usersys.redhat.com /usr/libexec/rhsmd -s -d
        // Stdout: System has one or more entitlements in their warning period
        // Stderr:
        // ExitCode: 0
        log.info("Asserting RhsmComplianced while at least one of the current entitlement certs is within its warning period...");
        // RemoteFileTasks.runCommandAndAssert(client, command, Integer.valueOf(0), rhsmComplianceDStdoutMessageWhenInsideWarningPeriod, null);
        sshCommandResult = client.runCommandAndWait(command);
        Assert.assertEquals(sshCommandResult.getExitCode(), Integer.valueOf(0), "ExitCode from command '" + command + "'");
        Assert.assertEquals(sshCommandResult.getStdout().trim(), rhsmComplianceDStdoutMessageWhenInsideWarningPeriod, "Stdout from command '" + command + "'");
        Assert.assertEquals(sshCommandResult.getStderr().trim(), "", "Stderr from command '" + command + "'");
        // unsubscribe from the serial
        EntitlementCert entitlementCert = entitlementCertsWithinWarningPeriod.remove(0);
        clienttasks.unsubscribeFromSerialNumber(entitlementCert.serialNumber);
    }
    // verify the stdout message
    log.info("Asserting RhsmComplianced status before unsubscribing from all currently consumed subscriptions...");
    // RemoteFileTasks.runCommandAndAssert(client, command, Integer.valueOf(0), rhsmComplianceDStdoutMessageWhenCompliant, null);
    sshCommandResult = client.runCommandAndWait(command);
    Assert.assertEquals(sshCommandResult.getExitCode(), Integer.valueOf(0), "ExitCode from command '" + command + "'");
    Assert.assertEquals(sshCommandResult.getStdout().trim(), rhsmComplianceDStdoutMessageWhenCompliant, "Stdout from command '" + command + "'");
    Assert.assertEquals(sshCommandResult.getStderr().trim(), "", "Stderr from command '" + command + "'");
    // also assert RhsmComplianced when not consuming any subscriptions
    log.info("Also asserting RhsmComplianced status after unsubscribing from all currently consumed subscriptions...");
    clienttasks.unsubscribeFromAllOfTheCurrentlyConsumedProductSubscriptions();
    // RemoteFileTasks.runCommandAndAssert(client, command, Integer.valueOf(0), rhsmComplianceDStdoutMessageWhenCompliant, null);
    sshCommandResult = client.runCommandAndWait(command);
    Assert.assertEquals(sshCommandResult.getExitCode(), Integer.valueOf(0), "ExitCode from command '" + command + "'");
    Assert.assertEquals(sshCommandResult.getStdout().trim(), rhsmComplianceDStdoutMessageWhenCompliant, "Stdout from command '" + command + "'");
    Assert.assertEquals(sshCommandResult.getStderr().trim(), "", "Stderr from command '" + command + "'");
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 67 with EntitlementCert

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

the class ComplianceTests method testAutoSubscribeAttemptsWhenNotCompliantAndNoProductsAreSubscribable.

@// update=true,	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-21722", "RHEL7-51087" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier1")
@Test(description = "when no installed products are subscribable and system is NOT compliant, auto-subscribing again should try but not get any new entitlements", groups = { "Tier1Tests", "cli.tests", "blockedByBug-723044" }, // dependsOnMethods={"testSystemCompliantFactWhenNoProductsAreSubscribable"},
priority = 520, enabled = true)
public // @ImplementsTCMS(id="")
void testAutoSubscribeAttemptsWhenNotCompliantAndNoProductsAreSubscribable() throws JSONException, Exception {
    if (!configureProductCertDirForNoProductsSubscribableCompleted)
        throw new SkipException("Unsatisfied dependency configureProductCertDirForNoProductsSubscribableCompleted=" + configureProductCertDirForNoProductsSubscribableCompleted);
    if (clienttasks.getCurrentlyRegisteredOwnerKey() == null)
        throw new SkipException("Unsatisfied dependency - expected system to already have been registered during a preceding testcase.");
    List<EntitlementCert> entitlementCertsBefore = clienttasks.getCurrentEntitlementCerts();
    SSHCommandResult result = clienttasks.subscribe(true, null, (List<String>) null, null, null, null, null, null, null, null, null, null, null);
    Assert.assertTrue(!result.getStdout().trim().startsWith(autosubscribeCompliantMessage), "When the system is not compliant, an attempt to auto-subscribe should NOT inform us with this message: " + autosubscribeCompliantMessage);
    List<EntitlementCert> entitlementCertsAfter = clienttasks.getCurrentEntitlementCerts();
    Assert.assertTrue(entitlementCertsBefore.containsAll(entitlementCertsAfter) && entitlementCertsAfter.containsAll(entitlementCertsBefore), "The entitlement certs have not changed after an attempt to autosubscribe a second time.");
    Assert.assertEquals(entitlementCertsBefore.size(), entitlementCertsAfter.size(), "The number of entitlement certs did not change after an attempt to autosubscribe a second time.");
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) SkipException(org.testng.SkipException) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test)

Example 68 with EntitlementCert

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

the class ContentIntegrationTests method getContentNamespaceDataAsListOfLists.

protected List<List<Object>> getContentNamespaceDataAsListOfLists() throws JSONException {
    List<List<Object>> ll = new ArrayList<List<Object>>();
    for (List<Object> row : contentNamespaceData) {
        String username = (String) row.get(0);
        String password = (String) row.get(1);
        ConsumerType type = (ConsumerType) row.get(2);
        String productId = (String) row.get(3);
        Integer sockets = (Integer) row.get(4);
        ContentNamespace contentNamespace = (ContentNamespace) row.get(5);
        EntitlementCert entitlementCert = (EntitlementCert) row.get(6);
        // 
        ll.add(Arrays.asList(new Object[] { username, password, type, productId, sockets, contentNamespace }));
    }
    return ll;
}
Also used : ContentNamespace(rhsm.data.ContentNamespace) EntitlementCert(rhsm.data.EntitlementCert) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) JSONObject(org.json.JSONObject) ConsumerType(rhsm.base.ConsumerType)

Example 69 with EntitlementCert

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

the class BugzillaTests method getVerifyEUSRHELProductCertVersionFromEachCDNReleaseVersion_TestDataAsListOfLists.

protected List<List<Object>> getVerifyEUSRHELProductCertVersionFromEachCDNReleaseVersion_TestDataAsListOfLists() throws JSONException, Exception {
    List<List<Object>> ll = new ArrayList<List<Object>>();
    if (!isSetupBeforeSuiteComplete)
        return ll;
    if (clienttasks == null)
        return ll;
    String eusProductId = null;
    if ((clienttasks.arch.equals("ppc64")) && (clienttasks.variant.equals("Server")))
        eusProductId = "75";
    else if ((clienttasks.arch.equals("x86_64")) && (clienttasks.variant.equals("Server")))
        eusProductId = "70";
    else if ((clienttasks.arch.equals("x86_64")) && clienttasks.variant.equals("ComputeNode"))
        eusProductId = "217";
    else if ((clienttasks.arch.equals("s390x")) && (clienttasks.variant.equals("Server")))
        eusProductId = "73";
    if (eusProductId == null) {
        log.warning("This test does not yet cover variant '" + clienttasks.variant + "' on arch '" + clienttasks.arch + "'.");
        // return no rows and no test will be run
        return ll;
    }
    // unregister
    clienttasks.unregister(null, null, null, null);
    // register
    clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, true, null, null, (String) null, null, null, null, null, null, null, null, null, null);
    // get current product cert and verify that rhelproduct is installed on
    // the system
    ProductCert rhelProductCert = clienttasks.getCurrentRhelProductCert();
    SubscriptionPool pool = null;
    for (SubscriptionPool eusSubscriptionPool : SubscriptionPool.parse(clienttasks.list(null, true, null, null, null, null, null, null, "*Extended*", null, null, null, null, null).getStdout())) {
        if ((CandlepinTasks.getPoolProvidedProductIds(sm_client1Username, sm_client1Password, sm_serverUrl, eusSubscriptionPool.poolId).contains(eusProductId))) {
            // and attach eus subscription
            clienttasks.subscribe(null, null, eusSubscriptionPool.poolId, null, null, null, null, null, null, null, null, null, null);
            pool = eusSubscriptionPool;
            break;
        }
    }
    if (pool == null) {
        log.warning("Could not find an available EUS subscription that covers EUS product '" + eusProductId + "'.");
        // return no rows and no test will be run
        return ll;
    }
    // find the entitlement that provides access to RHEL and EUS
    EntitlementCert eusEntitlementCerts = clienttasks.getEntitlementCertCorrespondingToSubscribedPool(pool);
    if (eusEntitlementCerts == null) {
        return ll;
    }
    // if eus repo is not enabled , enable it
    String rhelRepoUrl = null;
    for (Repo disabledRepo : Repo.parse(clienttasks.repos(null, false, true, (String) null, (String) null, null, null, null, null).getStdout())) {
        String variant = null;
        if (clienttasks.arch.equals("x86_64")) {
            if (clienttasks.variant.equals("ComputeNode"))
                variant = "hpc-node";
            if (clienttasks.variant.equals("Server"))
                variant = "server";
        } else if (clienttasks.arch.equals("ppc64") || (clienttasks.arch.equals("ppc64le"))) {
            variant = "for-power";
        } else if (clienttasks.arch.equals("s390x"))
            variant = "for-system-z";
        // add repos for eus-source rpms and debug rpms
        if ((disabledRepo.repoId.matches("rhel-[0-9]+-" + variant + "-eus-rpms"))) {
            clienttasks.repos(null, null, null, disabledRepo.repoId, (String) null, null, null, null, null);
        }
    }
    for (// if eus repo is enabled then add it to the data provider
    Repo enabledRepo : Repo.parse(clienttasks.repos(null, true, false, (String) null, (String) null, null, null, null, null).getStdout())) {
        if (enabledRepo.enabled) {
            String variant = null;
            if (clienttasks.arch.equals("x86_64")) {
                if (clienttasks.variant.equals("ComputeNode"))
                    variant = "hpc-node";
                if (clienttasks.variant.equals("Server"))
                    variant = "server";
            } else if (clienttasks.arch.equals("ppc64") || (clienttasks.arch.equals("ppc64le"))) {
                variant = "for-power";
            } else if (clienttasks.arch.equals("s390x"))
                variant = "for-system-z";
            if (enabledRepo.repoId.matches("rhel-[0-9]+-" + variant + "-eus-rpms")) {
                rhelRepoUrl = enabledRepo.repoUrl;
            }
        }
    }
    // against ppc64le
    for (String release : clienttasks.getCurrentlyAvailableReleases(null, null, null, null)) {
        // skip the latest releases; e.g. 6Server
        if (!isFloat(release))
            continue;
        List<String> bugIds = new ArrayList<String>();
        if (release.startsWith("6")) {
            if (release.matches("6.4") && clienttasks.variant.equals("Server") && clienttasks.arch.equals("x86_64"))
                // https://bugzilla.redhat.com/show_bug.cgi?id=1357574#c16
                bugIds.add("1357574");
            if (release.matches("6.4") && clienttasks.variant.equals("Server") && clienttasks.arch.equals("i386"))
                // https://bugzilla.redhat.com/show_bug.cgi?id=1357574#c18
                bugIds.add("1357574");
            if (release.matches("6.5") && clienttasks.variant.equals("Server") && clienttasks.arch.equals("i386"))
                // https://bugzilla.redhat.com/show_bug.cgi?id=1357574#c18
                bugIds.add("1357574");
            if (release.matches("6.6") && clienttasks.variant.equals("Server") && clienttasks.arch.equals("i386"))
                // https://bugzilla.redhat.com/show_bug.cgi?id=1357574#c18
                bugIds.add("1357574");
            if (release.matches("6.4") && clienttasks.variant.equals("Server") && clienttasks.arch.equals("s390x"))
                // https://bugzilla.redhat.com/show_bug.cgi?id=1357574#c18
                bugIds.add("1357574");
            if (release.matches("6.5") && clienttasks.variant.equals("Server") && clienttasks.arch.equals("s390x"))
                // https://bugzilla.redhat.com/show_bug.cgi?id=1357574#c18
                bugIds.add("1357574");
            if (release.matches("6.6") && clienttasks.variant.equals("Server") && clienttasks.arch.equals("s390x"))
                // https://bugzilla.redhat.com/show_bug.cgi?id=1357574#c18
                bugIds.add("1357574");
            if (release.matches("6.5") && clienttasks.variant.equals("Server") && clienttasks.arch.equals("ppc64"))
                // https://bugzilla.redhat.com/show_bug.cgi?id=1357574#c19
                bugIds.add("1357574");
            if (release.matches("6.6") && clienttasks.variant.equals("Server") && clienttasks.arch.equals("ppc64"))
                // https://bugzilla.redhat.com/show_bug.cgi?id=1357574#c19
                bugIds.add("1357574");
            if (release.matches("6.7") && clienttasks.variant.equals("Server") && clienttasks.arch.equals("x86_64"))
                bugIds.add("1352162");
        }
        if (release.startsWith("7")) {
            if (// && clienttasks.variant.equals("Server"))
            release.matches("7.1"))
                bugIds.add("1369920");
        }
        BlockedByBzBug blockedByBzBug = new BlockedByBzBug(bugIds.toArray(new String[] {}));
        ll.add(Arrays.asList(new Object[] { blockedByBzBug, release, rhelRepoUrl, eusEntitlementCerts.file }));
    }
    return ll;
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) Repo(rhsm.data.Repo) YumRepo(rhsm.data.YumRepo) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) JSONObject(org.json.JSONObject) ProductCert(rhsm.data.ProductCert) SubscriptionPool(rhsm.data.SubscriptionPool) BlockedByBzBug(com.redhat.qe.auto.bugzilla.BlockedByBzBug)

Example 70 with EntitlementCert

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

the class CRLTests method testChangeToSubscriptionPoolStartEndDatesAndRefreshSubscriptionPools.

// 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-27133", "RHEL7-51947" }, level = DefTypes.Level.COMPONENT, component = "subscription-manager", testtype = @TestType(testtype = DefTypes.TestTypes.FUNCTIONAL, subtype1 = DefTypes.Subtypes.RELIABILITY, subtype2 = DefTypes.Subtypes.EMPTY), posneg = PosNeg.POSITIVE, importance = DefTypes.Importance.HIGH, automation = DefTypes.Automation.AUTOMATED, tags = "Tier3")
@Test(description = "subscription-manager-cli: change subscription pool start/end dates and refresh subscription pools", groups = { "Tier3Tests", "ChangeSubscriptionPoolStartEndDatesAndRefreshSubscriptionPools_Test" }, dependsOnGroups = {}, // dataProvider="getAvailableNonTemporarySubscriptionPoolsData",
dataProvider = "getRandomSubsetOfAvailableNonTemporarySubscriptionPoolsData", enabled = true)
@ImplementsNitrateTest(caseId = 56025)
public void testChangeToSubscriptionPoolStartEndDatesAndRefreshSubscriptionPools(SubscriptionPool originalPool) throws Exception {
    // * the crl list on the server should be poplulated w/ the old entitlement cert serials
    if (servertasks.dbConnection == null)
        throw new SkipException("This testcase requires a connection to the candlepin database.");
    /* https://bugzilla.redhat.com/show_bug.cgi?id=663455#c1 < DUE TO THESE IMPLEMENTED CHANGES, THE FOLLOWING IS NO LONGER APPROPRIATE...
		// Before proceeding with this test, determine if the productId provided by this subscription pool has already been entitled.
		// This will happen when more than one pool has been created under a different contract/serial so as to increase the
		// total quantity of entitlements available to the consumers.
		if (alreadySubscribedProductIdsInChangeSubscriptionPoolStartEndDatesAndRefreshSubscriptionPools_Test.contains(pool.productId)) {
			log.info("Because the productId '"+pool.productId+"' from this pool has already been subscribed to via a previously available pool, it only makes sense to skip this iteration of the test.");
			log.info("However, for the sake of testing, let's attempt to subscribe to it anyway and assert that our subscribe request is blocked with an appropriate message...");
			SSHCommandResult sshCommandResult = clienttasks.subscribe(pool.poolId, null, null, null, null, null, null, null);
			Assert.assertEquals(sshCommandResult.getStdout().trim(),"This consumer is already subscribed to the product matching pool with id '"+pool.poolId+"'.");
			throw new SkipException("Because this consumer is already subscribed to the product ("+pool.productId+") provided by this pool id '"+pool.poolId+".', this pool is unsubscribeable and therefore we must skip this test iteration.");
		}
		*/
    List<ProductSubscription> originalConsumedProducts = clienttasks.getCurrentlyConsumedProductSubscriptions();
    // With the introduction of virt-guest pools, it is possible that a former invocation of this test has changed the validity dates on this pool,
    // therefore, let's re-fetch the SubscriptionPool object that we are about to test.
    SubscriptionPool pool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", originalPool.poolId, clienttasks.getCurrentlyAvailableSubscriptionPools());
    Assert.assertNotNull(pool, "Successfully found the SubscriptionPool with the poolId that we are about to test from list --available.");
    log.info("Subscribe client (already registered as a system under username '" + sm_clientUsername + "') to subscription pool " + pool + "...");
    File entitlementCertFile = clienttasks.subscribeToSubscriptionPool(pool, /*sm_serverAdminUsername*/
    sm_clientUsername, /*sm_serverAdminPassword*/
    sm_clientPassword, sm_serverUrl);
    Assert.assertNotNull(entitlementCertFile, "Our attempt to subscribe resulted in a new entitlement cert on our system.");
    alreadySubscribedProductIdsInChangeSubscriptionPoolStartEndDatesAndRefreshSubscriptionPools_Test.add(pool.productId);
    EntitlementCert entitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(entitlementCertFile);
    log.info("Verify that the currently consumed product subscriptions that came from this subscription pool have the same start and end date as the pool...");
    List<ProductSubscription> originalProducts = ProductSubscription.findAllInstancesWithMatchingFieldFromList("serialNumber", entitlementCert.serialNumber, clienttasks.getCurrentlyConsumedProductSubscriptions());
    Assert.assertFalse(originalProducts.isEmpty(), "After subscribing to a new pool, at least one consumed product subscription matching the entitlement cert's serial number '" + entitlementCert.serialNumber + "' is expected.");
    // TEMPORARY WORKAROUND FOR BUG: https://bugzilla.redhat.com/show_bug.cgi?id=660713 - jsefler 12/12/2010
    Boolean invokeWorkaroundWhileBugIsOpen = true;
    try {
        String bugId = "660713";
        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("The workaround while this bug is open is to skip the assertion that: The original end date for the subscribed product matches the end date of the subscription pool '" + pool.subscriptionName + "' from where it was entitled.");
    } else
        for (ProductSubscription originalProduct : originalProducts) {
            Assert.assertEquals(originalProduct.accountNumber, originalProducts.get(0).accountNumber, "All of the consumed product subscription from this pool '" + pool.poolId + "' should have the same accountNumber.");
            Assert.assertEquals(originalProduct.contractNumber, originalProducts.get(0).contractNumber, "All of the consumed product subscription from this pool '" + pool.poolId + "' should have the same contractNumber.");
            Assert.assertEquals(originalProduct.serialNumber, originalProducts.get(0).serialNumber, "All of the consumed product subscription from this pool '" + pool.poolId + "' should have the same serialNumber.");
            Assert.assertEquals(originalProduct.isActive, originalProducts.get(0).isActive, "All of the consumed product subscription from this pool '" + pool.poolId + "' should have the same active status.");
            Assert.assertTrue(originalProduct.startDate.compareTo(originalProducts.get(0).startDate) == 0, "All of the consumed product subscription from this pool '" + pool.poolId + "' should have the same startDate.");
            Assert.assertTrue(originalProduct.endDate.compareTo(pool.endDate) == 0, "The original end date (" + ProductSubscription.formatDateString(originalProduct.endDate) + ") for the subscribed product '" + originalProduct.productName + "' matches the end date (" + SubscriptionPool.formatDateString(pool.endDate) + ") of the subscription pool '" + pool.subscriptionName + "' from where it was entitled.");
        }
    // new File(clienttasks.entitlementCertDir+"/"+products.get(0).serialNumber+".pem");
    File originalEntitlementCertFile = entitlementCertFile;
    Calendar originalStartDate = (Calendar) originalProducts.get(0).startDate.clone();
    Calendar originalEndDate = (Calendar) originalProducts.get(0).endDate.clone();
    Integer contractNumber = originalProducts.get(0).contractNumber;
    Assert.assertTrue(RemoteFileTasks.testExists(client, originalEntitlementCertFile.getPath()), "Original entitlement cert file '" + originalEntitlementCertFile + "' exists.");
    log.info("Now we will change the start and end date of the subscription pool adding one month to enddate and subtracting one month from startdate...");
    Calendar newStartDate = (Calendar) originalStartDate.clone();
    newStartDate.add(Calendar.MONTH, -1);
    Calendar newEndDate = (Calendar) originalEndDate.clone();
    newEndDate.add(Calendar.MONTH, 1);
    updateSubscriptionPoolDatesOnDatabase(pool, newStartDate, newEndDate);
    // TEMPORARY WORKAROUND FOR BUG
    invokeWorkaroundWhileBugIsOpen = true;
    try {
        String bugId = "883486";
        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("The workaround while this bug is open is to compensate the expected new start/end dates for daylight savings.");
        Calendar now = Calendar.getInstance();
        // adjust the expected entitlement dates for daylight savings time (changed by https://github.com/candlepin/subscription-manager/pull/385)
        // now.get(Calendar.DST_OFFSET) will equal 0 in the winter StandardTime; will equal 1000*60*60 in the summer DaylightSavingsTime (when the local time zone observes DST)
        newStartDate.add(Calendar.MILLISECOND, now.get(Calendar.DST_OFFSET) - newStartDate.get(Calendar.DST_OFFSET));
        newEndDate.add(Calendar.MILLISECOND, now.get(Calendar.DST_OFFSET) - newEndDate.get(Calendar.DST_OFFSET));
    }
    // END OF WORKAROUND
    log.info("Now let's refresh the subscription pools...");
    JSONObject jobDetail = CandlepinTasks.refreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, ownerKey);
    jobDetail = CandlepinTasks.waitForJobDetailStateUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, jobDetail, "FINISHED", 10 * 1000, 3);
    log.info("Refresh to make sure the latest entitlement certs are on the client...");
    // makes sure the new entitlement is downloaded
    clienttasks.refresh(null, null, null, null);
    log.info("The updated certs should now be on the client...");
    log.info("First, let's assert that the original entitlement cert file '" + originalEntitlementCertFile + "' is gone...");
    Assert.assertTrue(!RemoteFileTasks.testExists(client, originalEntitlementCertFile.getPath()), "Original certificate file '" + originalEntitlementCertFile + "' has been removed from the system.");
    log.info("Second, let's assert that the consumed products have been refreshed...");
    // List<ProductSubscription> newProducts = ProductSubscription.findAllInstancesWithMatchingFieldFromList("contractNumber",contractNumber, clienttasks.getCurrentlyConsumedProductSubscriptions());
    // Assert.assertEquals(newProducts.size(), originalProducts.size(),"The number of ProductSubscriptions corresponding to this subscription's original contract number ("+contractNumber+") remains the same.");
    List<ProductSubscription> newProducts = new ArrayList<ProductSubscription>();
    for (ProductSubscription productSubscription : clienttasks.getCurrentlyConsumedProductSubscriptions()) {
        if (!originalConsumedProducts.contains(productSubscription))
            newProducts.add(productSubscription);
    }
    Assert.assertEquals(newProducts.size(), originalProducts.size(), "The number of ProductSubscriptions altered after changing the subscription's start/end dates remains confined to original consumed products.");
    BigInteger newSerialNumber = newProducts.get(0).serialNumber;
    File newCertFile = new File(clienttasks.entitlementCertDir + "/" + newSerialNumber + ".pem");
    Assert.assertNotSame(newCertFile, originalEntitlementCertFile, "The newly granted and refresh entitlement cert file should not be the same as the original cert file.");
    Assert.assertTrue(RemoteFileTasks.testExists(client, newCertFile.getPath()), "New entitlement certificate file '" + newCertFile + "' exists.");
    for (ProductSubscription newProduct : newProducts) {
        Assert.assertEquals(ProductSubscription.formatDateString(newProduct.startDate), ProductSubscription.formatDateString(newStartDate), "Rhsmcertd has updated the entitled startdate from '" + ProductSubscription.formatDateString(originalStartDate) + "' to '" + ProductSubscription.formatDateString(newStartDate) + "' for consumed product '" + newProduct.productName + "' that originated from poolId '" + pool.poolId + "'.");
        Assert.assertEquals(ProductSubscription.formatDateString(newProduct.endDate), ProductSubscription.formatDateString(newEndDate), "Rhsmcertd has updated the entitled enddate from '" + ProductSubscription.formatDateString(originalEndDate) + "' to '" + ProductSubscription.formatDateString(newEndDate) + "' for consumed product '" + newProduct.productName + "' that originated from poolId '" + pool.poolId + "'.");
        log.info("And, let's assert that consumed product entitlement serial has been updated...");
        Assert.assertTrue(!newProduct.serialNumber.equals(originalProducts.get(0).serialNumber) && newProduct.serialNumber.equals(newSerialNumber), "The consumed product entitlement serial has been updated from '" + originalProducts.get(0).serialNumber + "' to '" + newSerialNumber + "' for consumed product '" + newProduct.productName + "' that originated from poolId '" + pool.poolId + "'.");
        log.info("Let's assert that the following consumed product attributes have been left unchanged...");
        Assert.assertEquals(newProduct.accountNumber, originalProducts.get(0).accountNumber, "The consumed product accountNumber remains unchanged for '" + newProduct.productName + "' after its pool (poolId='" + pool.poolId + "') start/end dates have been modified and refreshed.");
        Assert.assertEquals(newProduct.contractNumber, originalProducts.get(0).contractNumber, "The consumed product contractNumber remains unchanged for '" + newProduct.productName + "' after its pool (poolId='" + pool.poolId + "') start/end dates have been modified and refreshed.");
        Assert.assertEquals(newProduct.isActive, originalProducts.get(0).isActive, "The consumed product active status remains unchanged for '" + newProduct.productName + "' after its pool (poolId='" + pool.poolId + "') start/end dates have been modified and refreshed.");
    }
    log.info("Third, let's assert that subscription pool reflects the new end date...");
    clienttasks.unsubscribeFromSerialNumber(newSerialNumber);
    pool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("poolId", pool.poolId, clienttasks.getCurrentlyAvailableSubscriptionPools());
    Assert.assertNotNull(pool, "Successfully found the SubscriptionPool with the poolId that we just unsubscribed from and searched for in list --available.");
    Assert.assertEquals(SubscriptionPool.formatDateString(pool.endDate), SubscriptionPool.formatDateString(newEndDate), "As seen by the client, the enddate of the refreshed pool '" + pool.poolId + "' (" + pool.subscriptionName + ") has been changed from '" + SubscriptionPool.formatDateString(originalEndDate) + "' to '" + SubscriptionPool.formatDateString(newEndDate) + "'.");
    log.info("Forth, in honor of bugzillas 682930, 679617 let's assert that after unsubscribing, the subscription pool's original quantity is restored...");
    Assert.assertEquals(pool.quantity, originalPool.quantity, "Assuming that nobody else has recently subscribed to this pool, the original pool quantity should be restored after updating the subscription's start/end dates and unsubscribing from the poolId '" + pool.poolId + "' (" + pool.subscriptionName + ").");
    log.info("Finally, check the CRL list on the server and verify the original entitlement cert serial is revoked...");
    log.info("Waiting 2 minutes...  (Assuming this is the candlepin.conf value set for pinsetter.org.fedoraproject.candlepin.pinsetter.tasks.CertificateRevocationListTask.schedule)");
    // give the CertificateRevocationListTask.schedule 2 minutes to update the list since that is what was set in setupBeforeSuite()
    sleep(2 * 60 * 1000);
    // NOTE: The refresh schedule should have been set with a call to servertasks.updateConfigFileParameter in the setupBeforeSuite()
    // Set inside /etc/candlepin/candlepin.conf
    // pinsetter.org.fedoraproject.candlepin.pinsetter.tasks.CertificateRevocationListTask.schedule=0 0/2 * * * ?
    // NOTE: if not set, the default is  public static final String DEFAULT_SCHEDULE = "0 0 12 * * ?" Fire at 12pm (noon) every day
    RevokedCert revokedCert = RevokedCert.findFirstInstanceWithMatchingFieldFromList("serialNumber", entitlementCert.serialNumber, servertasks.getCurrentlyRevokedCerts());
    Assert.assertTrue(revokedCert != null, "Original entitlement certificate serial number '" + entitlementCert.serialNumber + "' granted from pool '" + pool.poolId + "' (" + pool.subscriptionName + ") has been added to the Certificate Revocation List (CRL) as: " + revokedCert);
    Assert.assertEquals(revokedCert.reasonCode, "Privilege Withdrawn", "Expanding the certificate start and end dates should revoke the certificated with a reason code of Privilege Withdrawn.");
// just to add some complexity to succeeding dataProvided runs of this test, let's re-subscribe to this pool
// FIXME The following will cause failures for pools that originate from a virtualization aware subscription.  It would be nice to re-subscribe, but first we need to determine if this pool came from a virt-aware subscription and excude it from the resubscribe
// clienttasks.subscribeToSubscriptionPool(pool);
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) Calendar(java.util.Calendar) ProductSubscription(rhsm.data.ProductSubscription) ArrayList(java.util.ArrayList) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) BigInteger(java.math.BigInteger) JSONObject(org.json.JSONObject) BigInteger(java.math.BigInteger) SkipException(org.testng.SkipException) SubscriptionPool(rhsm.data.SubscriptionPool) File(java.io.File) RevokedCert(rhsm.data.RevokedCert) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest) 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