Search in sources :

Example 61 with ProductSubscription

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

Example 62 with ProductSubscription

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

the class EventTests method testPoolModifiedAndEntitlementModified.

@// update=true	// uncomment to make TestDefinition changes update Polarion testcases through the polarize testcase importer
TestDefinition(projectID = { Project.RHEL6, Project.RedHatEnterpriseLinux7 }, testCaseID = { "RHEL6-26757", "RHEL7-52091" }, 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: events: Pool Modified and Entitlement Modified is sent over an RSS atom feed.", groups = { "Tier3Tests", "blockedByBug-721141", "PoolModifiedAndEntitlementModified_Test", "blockedByBug-645597", "blockedByBug-1303242", "blockedByBug-1500837", "blockedByBug-1500843" }, dependsOnGroups = { "EntitlementCreated_Test" }, enabled = true)
public // @ImplementsTCMS(id="")
void testPoolModifiedAndEntitlementModified() throws Exception {
    if (server == null)
        throw new SkipException("This test requires an SSH connection to the candlepin server.");
    // get the owner and consumer feeds before we test the firing of a new event
    ConsumerCert consumerCert = clienttasks.getCurrentConsumerCert();
    String ownerKey = CandlepinTasks.getOwnerKeyOfConsumerId(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, consumerCert.consumerid);
    // get the number of subscriptions this owner owns
    // JSONArray jsonSubscriptions = new JSONArray(CandlepinTasks.getResourceUsingRESTfulAPI(serverHostname,serverPort,serverPrefix,clientusername,clientpassword,"/owners/"+ownerKey+"/subscriptions"));
    // find the first pool id of a currently consumed product
    List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    ProductSubscription originalConsumedProductSubscription = consumedProductSubscriptions.get(0);
    testPool = clienttasks.getSubscriptionPoolFromProductSubscription(originalConsumedProductSubscription, sm_clientUsername, sm_clientPassword);
    Calendar originalStartDate = (Calendar) originalConsumedProductSubscription.startDate.clone();
    EntitlementCert originalEntitlementCert = clienttasks.getEntitlementCertCorrespondingToProductSubscription(originalConsumedProductSubscription);
    originalStartDate = (Calendar) originalEntitlementCert.validityNotBefore.clone();
    SyndFeed oldFeed = CandlepinTasks.getSyndFeed(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl);
    SyndFeed oldOwnerFeed = CandlepinTasks.getSyndFeedForOwner(ownerKey, sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl);
    SyndFeed oldConsumerFeed = CandlepinTasks.getSyndFeedForConsumer(/*ownerKey,*/
    consumerCert.consumerid, sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl);
    // fire an modified pool event (and subsequently a modified entitlement event because the pool was modified thereby requiring an entitlement update dropped to the consumer)
    log.info("To fire a modified pool event (and subsequently a modified entitlement event because the pool is already subscribed too), we will modify pool '" + testPool.poolId + "' by subtracting one month from startdate...");
    Calendar newStartDate = (Calendar) originalStartDate.clone();
    newStartDate.add(Calendar.MONTH, -1);
    if (false) {
        // the following block was used prior to candlepin-2.0.0 and replaced by CandlepinTasks.updateSubscriptionAndRefreshPoolsUsingRESTfulAPI which I think will also work for pre candlepin-2.0.0, but is untested.  <== TODO
        updateSubscriptionPoolDatesOnDatabase(testPool, newStartDate, null);
        log.info("Now let's refresh the subscription pools to expose the POOL MODIFIED event...");
        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);
    } else
        /*OLD*/
        CandlepinTasks.updateSubscriptionDatesAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, CandlepinTasks.getSubscriptionIdForPoolId(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, testPool.poolId), newStartDate, null);
    // NEW TODO CandlepinTasks.updateSubscriptionPoolDatesUsingRESTfulAPI(sm_serverAdminUsername,sm_serverAdminPassword,sm_serverUrl, testPool.poolId,newStartDate,null);
    // assert the consumer feed...
    List<String> newEventTitles = new ArrayList<String>();
    // newEventTitles.add("ENTITLEMENT MODIFIED");
    assertTheNewConsumerFeed(ownerKey, consumerCert.consumerid, oldConsumerFeed, newEventTitles);
    // assert the owner feed...
    // //assertTheNewOwnerFeed(ownerKey, oldOwnerFeed, new String[]{"ENTITLEMENT MODIFIED", "POOL MODIFIED"});
    // for (int s=0; s<jsonSubscriptions.length(); s++) newEventTitles.add("POOL MODIFIED");		// NOTE: This is troublesome because the number of POOL MODIFIED events is not this predictable especially when the pool (which is randomly chosen) is a virt pool
    // assertTheNewOwnerFeed(ownerKey, oldOwnerFeed, newEventTitles);
    newEventTitles.add("POOL MODIFIED");
    assertTheNewOwnerFeedContains(ownerKey, oldOwnerFeed, newEventTitles);
    // assert the feed...
    // //assertTheNewFeed(oldFeed, new String[]{"ENTITLEMENT MODIFIED", "POOL MODIFIED"});
    // assertTheNewFeed(oldFeed, newEventTitles);
    assertTheNewFeedContains(oldFeed, newEventTitles);
    log.info("Now let's refresh the client's entitlements to expose the ENTITLEMENT MODIFIED event...");
    clienttasks.refresh(null, null, null, null);
    // COMPLIANCE CREATED events were added to support gutterball
    newEventTitles.add("COMPLIANCE CREATED");
    newEventTitles.add("ENTITLEMENT MODIFIED");
    // assert the feed...
    assertTheNewFeedContains(oldFeed, newEventTitles);
    // assert the owner feed...
    assertTheNewOwnerFeedContains(ownerKey, oldOwnerFeed, newEventTitles);
    // assert the consumer feed...
    newEventTitles.remove("POOL MODIFIED");
    // assertTheNewConsumerFeed(ownerKey, consumerCert.consumerid, oldConsumerFeed, newEventTitles);
    assertTheNewConsumerFeedIgnoringEventTitles(ownerKey, consumerCert.consumerid, oldConsumerFeed, newEventTitles.toArray(new String[] {}), new HashSet<String>() {

        {
            add("COMPLIANCE CREATED");
        }
    });
    // TEMPORARY WORKAROUND FOR BUG
    boolean invokeWorkaroundWhileBugIsOpen = true;
    Calendar now = Calendar.getInstance();
    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 consumed product subscription start date for daylight savings.");
        // 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));
        newStartDate.add(Calendar.MILLISECOND, now.get(Calendar.DST_OFFSET) - newStartDate.get(Calendar.DST_OFFSET));
    }
    // END OF WORKAROUND
    // ProductSubscription newConsumedProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("serialNumber", originalConsumedProductSubscription.serialNumber, clienttasks.getCurrentlyConsumedProductSubscriptions());	// can't do this because the serialNumber changes after the pool and entitlement have been modified
    ProductSubscription newConsumedProductSubscription = ProductSubscription.findFirstInstanceWithMatchingFieldFromList("productId", originalConsumedProductSubscription.productId, clienttasks.getCurrentlyConsumedProductSubscriptions());
    // AN org.xmlpull.v1.XmlPullParserException IS THROWN WHEN THIS FAILS: Assert.assertEquals(newConsumedProductSubscription.startDate, newStartDate, "After modifying pool '"+testPool.poolId+"' by subtracting one month from startdate and refreshing entitlements, the consumed product subscription now reflects the modified field.");
    Assert.assertEquals(ProductSubscription.formatDateString(newConsumedProductSubscription.startDate), ProductSubscription.formatDateString(newStartDate), "After modifying pool '" + testPool.poolId + "' by subtracting one month from startdate and refreshing entitlements, the consumed product subscription now reflects the modified field.");
}
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) SyndFeed(com.sun.syndication.feed.synd.SyndFeed) JSONObject(org.json.JSONObject) SkipException(org.testng.SkipException) ConsumerCert(rhsm.data.ConsumerCert) TestDefinition(com.github.redhatqe.polarize.metadata.TestDefinition) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Example 63 with ProductSubscription

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

the class SubscriptionManagerTasks method unsubscribeFromTheCurrentlyConsumedProductSubscriptionSerialsIndividually.

/**
 * Individually unsubscribe from each of the currently consumed product subscriptions.
 * This will ultimately issue multiple calls to unsubscribe --serial SERIAL for each of the product subscriptions being consumed.
 */
public void unsubscribeFromTheCurrentlyConsumedProductSubscriptionSerialsIndividually() {
    log.info("Unsubscribing from each of the currently consumed product subscription serials one at a time...");
    for (ProductSubscription sub : getCurrentlyConsumedProductSubscriptions()) unsubscribeFromProductSubscription(sub);
    Assert.assertTrue(getCurrentlyConsumedProductSubscriptions().size() == 0, "Currently no product subscriptions are consumed.");
    Assert.assertTrue(getCurrentEntitlementCertFiles().size() == 0, "This machine has no entitlement certificate files.");
}
Also used : ProductSubscription(rhsm.data.ProductSubscription)

Example 64 with ProductSubscription

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

the class SubscriptionManagerTasks method unsubscribeFromTheCurrentlyConsumedProductSubscriptionPoolIdsCollectively.

/**
 * Collectively unsubscribe from all of the currently consumed product subscriptions.
 * This will ultimately issue a single call to unsubscribe --pool POOLID1 --pool POOLID2 --pool POOLID3 for each of the product subscriptions being consumed.
 * @throws Exception
 */
public SSHCommandResult unsubscribeFromTheCurrentlyConsumedProductSubscriptionPoolIdsCollectively() throws Exception {
    log.info("Unsubscribing from all of the currently consumed product subscription poolids in one collective call...");
    List<BigInteger> serials = new ArrayList<BigInteger>();
    List<String> poolIds = new ArrayList<String>();
    // THIS AVOIDS PROBLEMS WHEN MODIFIER ENTITLEMENTS ARE BEING CONSUMED
    for (ProductSubscription productSubscription : getCurrentlyConsumedProductSubscriptions()) {
        EntitlementCert entitlementCert = getEntitlementCertCorrespondingToProductSubscription(productSubscription);
        JSONObject jsonEntitlement = CandlepinTasks.getEntitlementUsingRESTfulAPI(this.currentlyRegisteredUsername, this.currentlyRegisteredPassword, candlepinUrl, entitlementCert.id);
        String poolHref = jsonEntitlement.getJSONObject("pool").getString("href");
        JSONObject jsonPool = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(this.currentlyRegisteredUsername, this.currentlyRegisteredPassword, candlepinUrl, poolHref));
        String poolId = jsonPool.getString("id");
        if (CandlepinTasks.isPoolAModifier(this.currentlyRegisteredUsername, this.currentlyRegisteredPassword, poolId, candlepinUrl)) {
            // serials to entitlements that modify others should be at the front of the list to be removed, otherwise they will get re-issued under a new serial number when the modified entitlement is removed first.
            serials.add(0, productSubscription.serialNumber);
            poolIds.add(0, productSubscription.poolId);
        } else {
            serials.add(productSubscription.serialNumber);
            poolIds.add(productSubscription.poolId);
        }
    }
    // unsubscribe from all poolIds collectively
    SSHCommandResult result = unsubscribe(false, null, poolIds, null, null, null, null);
    Assert.assertTrue(getCurrentlyConsumedProductSubscriptions().size() == 0, "Currently no product subscriptions are consumed.");
    Assert.assertTrue(getCurrentEntitlementCertFiles().size() == 0, "This machine has no entitlement certificate files.");
    return result;
}
Also used : EntitlementCert(rhsm.data.EntitlementCert) JSONObject(org.json.JSONObject) SSHCommandResult(com.redhat.qe.tools.SSHCommandResult) ArrayList(java.util.ArrayList) ProductSubscription(rhsm.data.ProductSubscription) BigInteger(java.math.BigInteger)

Example 65 with ProductSubscription

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

the class ListTests method EnsureListConsumedMatchesProductsListedInTheEntitlementCerts_Test_DEPRECATED.

@Test(description = "subscription-manager: list of consumed entitlements should display consumed product marketing name", groups = { "Tier2Tests" }, dataProvider = "getAllEntitlementCertsData", // this test implementation is no longer valid after the change in format for consumed product subscriptions (from many to one) - see bug 806986
enabled = false)
@Deprecated
@ImplementsNitrateTest(caseId = 48092, fromPlan = 2481)
public void EnsureListConsumedMatchesProductsListedInTheEntitlementCerts_Test_DEPRECATED(EntitlementCert entitlementCert) {
    // assert: The list of consumed products matches the products listed in the entitlement cert
    List<ProductSubscription> productSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
    List<ProductSubscription> productSubscriptionsWithMatchingSerialNumber = ProductSubscription.findAllInstancesWithMatchingFieldFromList("serialNumber", entitlementCert.serialNumber, productSubscriptions);
    // Assert.assertTrue(productSubscriptionsWithMatchingSerialNumber.size()>0, "Found consumed product subscription(s) whose SerialNumber matches this entitlement cert: "+entitlementCert);
    // Assert.assertEquals(productSubscriptionsWithMatchingSerialNumber.size(),entitlementCert.productNamespaces.size(), "Found consumed product subscription(s) for each of the bundleProducts (total of '"+entitlementCert.productNamespaces.size()+"' expected) whose SerialNumber matches this entitlement cert: "+entitlementCert);
    // when there are 0 bundledProducts, we are still consuming 1 ProductSubscription
    int productSubscriptionsWithMatchingSerialNumberSizeExpected = entitlementCert.productNamespaces.size() == 0 ? 1 : entitlementCert.productNamespaces.size();
    Assert.assertEquals(productSubscriptionsWithMatchingSerialNumber.size(), productSubscriptionsWithMatchingSerialNumberSizeExpected, "Found consumed product subscription(s) for each of the bundleProducts (total of '" + productSubscriptionsWithMatchingSerialNumberSizeExpected + "' expected) whose SerialNumber matches this entitlement cert: " + entitlementCert);
    for (ProductNamespace productNamespace : entitlementCert.productNamespaces) {
        List<ProductSubscription> matchingProductSubscriptions = ProductSubscription.findAllInstancesWithMatchingFieldFromList("productName", productNamespace.name, productSubscriptionsWithMatchingSerialNumber);
        Assert.assertEquals(matchingProductSubscriptions.size(), 1, "Found one bundledProduct name '" + productNamespace.name + "' in the list of consumed product subscriptions whose SerialNumber matches this entitlement cert: " + entitlementCert);
        ProductSubscription correspondingProductSubscription = matchingProductSubscriptions.get(0);
        log.info("We are about to assert that this consumed Product Subscription: " + correspondingProductSubscription);
        log.info("...represents this ProductNamespace: " + productNamespace);
        log.info("...corresponding to this OrderNamespace: " + entitlementCert.orderNamespace);
        log.info("...from this EntitlementCert: " + entitlementCert);
        Assert.assertEquals(correspondingProductSubscription.productName, productNamespace.name, "productName from ProductSubscription in list --consumed matches productName from ProductNamespace in EntitlementCert.");
        Assert.assertEquals(correspondingProductSubscription.contractNumber, entitlementCert.orderNamespace.contractNumber, "contractNumber from ProductSubscription in list --consumed matches contractNumber from OrderNamespace in EntitlementCert.");
        Assert.assertEquals(correspondingProductSubscription.accountNumber, entitlementCert.orderNamespace.accountNumber, "accountNumber from ProductSubscription in list --consumed matches accountNumber from OrderNamespace in EntitlementCert.");
        Assert.assertEquals(correspondingProductSubscription.serialNumber, entitlementCert.serialNumber, "serialNumber from ProductSubscription in list --consumed matches serialNumber from EntitlementCert.");
        Calendar now = Calendar.getInstance();
        if (now.after(entitlementCert.orderNamespace.startDate) && now.before(entitlementCert.orderNamespace.endDate)) {
            Assert.assertTrue(correspondingProductSubscription.isActive, "isActive is True when the current time (" + EntitlementCert.formatDateString(now) + ") is between the start/end dates in the EntitlementCert: " + entitlementCert);
        } else {
            Assert.assertFalse(correspondingProductSubscription.isActive, "isActive is False when the current time (" + EntitlementCert.formatDateString(now) + ") is NOT between the start/end dates in the EntitlementCert: " + entitlementCert);
        }
        // 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: startDates and endDates match");
        } else {
            // END OF WORKAROUND
            Assert.assertEquals(ProductSubscription.formatDateString(correspondingProductSubscription.startDate), ProductSubscription.formatDateString(entitlementCert.orderNamespace.startDate), "startDate from ProductSubscription in list --consumed matches startDate from OrderNamespace (" + OrderNamespace.formatDateString(entitlementCert.orderNamespace.startDate) + ") after conversion from GMT in EntitlementCert to local time.");
            Assert.assertEquals(ProductSubscription.formatDateString(correspondingProductSubscription.endDate), ProductSubscription.formatDateString(entitlementCert.orderNamespace.endDate), "endDate from ProductSubscription in list --consumed matches endDate from OrderNamespace (" + OrderNamespace.formatDateString(entitlementCert.orderNamespace.endDate) + ") after conversion from GMT in EntitlementCert to local time.");
        }
    }
}
Also used : Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) ProductSubscription(rhsm.data.ProductSubscription) BugzillaAPIException(com.redhat.qe.auto.bugzilla.BugzillaAPIException) ProductNamespace(rhsm.data.ProductNamespace) Test(org.testng.annotations.Test) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest) ImplementsNitrateTest(com.redhat.qe.auto.tcms.ImplementsNitrateTest)

Aggregations

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