@Test
  public void hypervisorCheckInReportsFailureWhenGuestIdUpdateFails() throws Exception {
    Owner owner = new Owner("admin");

    Map<String, List<GuestId>> hostGuestMap = new HashMap<String, List<GuestId>>();
    String expectedHostVirtId = "test-host";
    hostGuestMap.put(expectedHostVirtId, Arrays.asList(new GuestId("GUEST_B")));

    Consumer existing = new Consumer();
    existing.setUuid(expectedHostVirtId);
    existing.addGuestId(new GuestId("GUEST_A"));

    // Force update
    when(consumerCurator.findByUuid(eq(expectedHostVirtId))).thenReturn(existing);

    String expectedMessage = "Forced Exception.";
    RuntimeException exception = new RuntimeException(expectedMessage);
    // Simulate failure  when checking the owner
    when(consumerCurator.getHost(any(String.class))).thenThrow(exception);

    HypervisorCheckInResult result =
        hypervisorResource.hypervisorCheckIn(hostGuestMap, principal, owner.getKey());

    Set<String> failures = result.getFailedUpdate();
    assertEquals(1, failures.size());
    assertEquals(expectedHostVirtId + ": " + expectedMessage, failures.iterator().next());
  }
  @Test
  public void futureHealing() throws Exception {
    Consumer c = mock(Consumer.class);
    Owner o = mock(Owner.class);
    SubscriptionServiceAdapter sa = mock(SubscriptionServiceAdapter.class);
    Entitler e = mock(Entitler.class);
    ConsumerCurator cc = mock(ConsumerCurator.class);
    ConsumerInstalledProduct cip = mock(ConsumerInstalledProduct.class);
    Set<ConsumerInstalledProduct> products = new HashSet<ConsumerInstalledProduct>();
    products.add(cip);

    when(c.getOwner()).thenReturn(o);
    when(cip.getProductId()).thenReturn("product-foo");
    when(sa.hasUnacceptedSubscriptionTerms(eq(o))).thenReturn(false);
    when(cc.verifyAndLookupConsumerWithEntitlements(eq("fakeConsumer"))).thenReturn(c);

    ConsumerResource cr =
        new ConsumerResource(
            cc,
            null,
            null,
            sa,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            e,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            consumerBindUtil,
            productCurator,
            null);
    String dtStr = "2011-09-26T18:10:50.184081+00:00";
    Date dt = ResourceDateParser.parseDateString(dtStr);
    cr.bind("fakeConsumer", null, null, null, null, null, false, dtStr, null, null, null);
    AutobindData data = AutobindData.create(c).on(dt);
    verify(e).bindByProducts(eq(data));
  }
  @Test
  public void testProductNoPool() throws Exception {
    Consumer c = mock(Consumer.class);
    Owner o = mock(Owner.class);
    SubscriptionServiceAdapter sa = mock(SubscriptionServiceAdapter.class);
    Entitler e = mock(Entitler.class);
    ConsumerCurator cc = mock(ConsumerCurator.class);
    String[] prodIds = {"notthere"};

    when(c.getOwner()).thenReturn(o);
    when(sa.hasUnacceptedSubscriptionTerms(eq(o))).thenReturn(false);
    when(cc.verifyAndLookupConsumerWithEntitlements(eq("fakeConsumer"))).thenReturn(c);
    when(e.bindByProducts(any(AutobindData.class))).thenReturn(null);

    ConsumerResource cr =
        new ConsumerResource(
            cc,
            null,
            null,
            sa,
            null,
            null,
            null,
            i18n,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            e,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            consumerBindUtil,
            productCurator,
            null);
    Response r =
        cr.bind("fakeConsumer", null, prodIds, null, null, null, false, null, null, null, null);
    assertEquals(null, r.getEntity());
  }
  @Test
  public void hypervisorCheckInUpdatesGuestIdsWhenHostConsumerExists() throws Exception {
    Owner owner = new Owner("admin");

    Map<String, List<GuestId>> hostGuestMap = new HashMap<String, List<GuestId>>();
    hostGuestMap.put("test-host", Arrays.asList(new GuestId("GUEST_B")));

    Owner o = new Owner();
    o.setId("owner-id");
    Consumer existing = new Consumer();
    existing.setUuid("test-host");
    existing.setOwner(o);
    existing.addGuestId(new GuestId("GUEST_A"));

    when(consumerCurator.findByUuid(eq("test-host"))).thenReturn(existing);

    HypervisorCheckInResult result =
        hypervisorResource.hypervisorCheckIn(hostGuestMap, principal, owner.getKey());
    Set<Consumer> updated = result.getUpdated();
    assertEquals(1, updated.size());

    Consumer c1 = updated.iterator().next();
    assertEquals("test-host", c1.getUuid());
    assertEquals(1, c1.getGuestIds().size());
    assertEquals("GUEST_B", c1.getGuestIds().get(0).getGuestId());
  }
  @Test
  public void hypervisorCheckInCreatesNewConsumer() throws Exception {
    Owner owner = new Owner("admin");

    Map<String, List<GuestId>> hostGuestMap = new HashMap<String, List<GuestId>>();
    hostGuestMap.put("test-host", Arrays.asList(new GuestId("GUEST_A"), new GuestId("GUEST_B")));

    when(consumerCurator.findByUuid(eq("test-host"))).thenReturn(null);
    when(ownerCurator.lookupByKey(eq(owner.getKey()))).thenReturn(owner);
    when(principal.canAccess(eq(owner), eq(Access.ALL))).thenReturn(true);
    when(consumerTypeCurator.lookupByLabel(eq(ConsumerTypeEnum.HYPERVISOR.getLabel())))
        .thenReturn(hypervisorType);
    when(idCertService.generateIdentityCert(any(Consumer.class)))
        .thenReturn(new IdentityCertificate());

    HypervisorCheckInResult result =
        hypervisorResource.hypervisorCheckIn(hostGuestMap, principal, owner.getKey());

    Set<Consumer> created = result.getCreated();
    assertEquals(1, created.size());

    Consumer c1 = created.iterator().next();
    assertEquals("test-host", c1.getUuid());
    assertEquals(2, c1.getGuestIds().size());
    assertEquals("GUEST_A", c1.getGuestIds().get(0).getGuestId());
    assertEquals("GUEST_B", c1.getGuestIds().get(1).getGuestId());
    assertEquals("x86_64", c1.getFact("uname.machine"));
    assertEquals("hypervisor", c1.getType().getLabel());
  }
 @Test
 public void bindByProductsString() throws Exception {
   String[] pids = {"prod1", "prod2", "prod3"};
   when(cc.findByUuid(eq("abcd1234"))).thenReturn(consumer);
   entitler.bindByProducts(pids, "abcd1234", null, null);
   AutobindData data = AutobindData.create(consumer).forProducts(pids);
   verify(pm).entitleByProducts(eq(data));
 }
  @Test
  public void testIdCertGetsRegenerated() throws Exception {
    // using lconsumer simply to avoid hiding consumer. This should
    // get renamed once we refactor this test suite.
    IdentityCertServiceAdapter mockedIdSvc = Mockito.mock(IdentityCertServiceAdapter.class);

    EventSink sink = Mockito.mock(EventSinkImpl.class);

    SubscriptionServiceAdapter ssa = Mockito.mock(SubscriptionServiceAdapter.class);
    ComplianceRules rules = Mockito.mock(ComplianceRules.class);

    Consumer consumer = createConsumer();
    ComplianceStatus status = new ComplianceStatus();
    when(rules.getStatus(any(Consumer.class), any(Date.class), anyBoolean())).thenReturn(status);
    // cert expires today which will trigger regen
    consumer.setIdCert(createIdCert());
    BigInteger origserial = consumer.getIdCert().getSerial().getSerial();

    when(mockedConsumerCurator.verifyAndLookupConsumer(consumer.getUuid())).thenReturn(consumer);
    when(mockedIdSvc.regenerateIdentityCert(consumer)).thenReturn(createIdCert());

    ConsumerResource cr =
        new ConsumerResource(
            mockedConsumerCurator,
            null,
            null,
            ssa,
            null,
            mockedIdSvc,
            null,
            null,
            sink,
            eventFactory,
            null,
            null,
            null,
            null,
            null,
            mockedOwnerCurator,
            null,
            null,
            rules,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            consumerBindUtil,
            productCurator,
            null);
    Consumer c = cr.getConsumer(consumer.getUuid());

    assertFalse(origserial.equals(c.getIdCert().getSerial().getSerial()));
  }
  @Test
  public void testRegenerateIdCerts() throws GeneralSecurityException, IOException {

    // using lconsumer simply to avoid hiding consumer. This should
    // get renamed once we refactor this test suite.
    IdentityCertServiceAdapter mockedIdSvc = Mockito.mock(IdentityCertServiceAdapter.class);

    EventSink sink = Mockito.mock(EventSinkImpl.class);

    Consumer consumer = createConsumer();
    consumer.setIdCert(createIdCert());
    IdentityCertificate ic = consumer.getIdCert();
    assertNotNull(ic);

    when(mockedConsumerCurator.verifyAndLookupConsumer(consumer.getUuid())).thenReturn(consumer);
    when(mockedIdSvc.regenerateIdentityCert(consumer)).thenReturn(createIdCert());

    ConsumerResource cr =
        new ConsumerResource(
            mockedConsumerCurator,
            null,
            null,
            null,
            null,
            mockedIdSvc,
            null,
            null,
            sink,
            eventFactory,
            null,
            null,
            null,
            null,
            null,
            mockedOwnerCurator,
            null,
            null,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            consumerBindUtil,
            productCurator,
            null);

    Consumer fooc = cr.regenerateIdentityCertificates(consumer.getUuid());

    assertNotNull(fooc);
    IdentityCertificate ic1 = fooc.getIdCert();
    assertNotNull(ic1);
    assertFalse(ic.equals(ic1));
  }
  @Test
  public void testGetComplianceStatusList() {
    Consumer c = mock(Consumer.class);
    Consumer c2 = mock(Consumer.class);
    when(c.getUuid()).thenReturn("1");
    when(c2.getUuid()).thenReturn("2");

    List<Consumer> consumers = new ArrayList<Consumer>();
    consumers.add(c);
    consumers.add(c2);

    List<String> uuids = new ArrayList<String>();
    uuids.add("1");
    uuids.add("2");
    when(mockedConsumerCurator.findByUuids(eq(uuids))).thenReturn(consumers);

    ComplianceStatus status = new ComplianceStatus();
    when(mockedComplianceRules.getStatus(any(Consumer.class), any(Date.class))).thenReturn(status);

    ConsumerResource cr =
        new ConsumerResource(
            mockedConsumerCurator,
            null,
            null,
            null,
            null,
            null,
            null,
            i18n,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            mockedComplianceRules,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            consumerBindUtil,
            productCurator,
            null);

    Map<String, ComplianceStatus> results = cr.getComplianceStatusList(uuids);
    assertEquals(2, results.size());
    assertTrue(results.containsKey("1"));
    assertTrue(results.containsKey("2"));
  }
  @Test(expected = NotFoundException.class)
  public void unbindByInvalidSerialShouldFail() {
    Consumer consumer = createConsumer();
    ConsumerCurator consumerCurator = mock(ConsumerCurator.class);
    when(consumerCurator.verifyAndLookupConsumer(eq("fake uuid"))).thenReturn(consumer);

    EntitlementCurator entitlementCurator = mock(EntitlementCurator.class);
    when(entitlementCurator.find(any(Serializable.class))).thenReturn(null);

    ConsumerResource consumerResource =
        new ConsumerResource(
            consumerCurator,
            null,
            null,
            null,
            entitlementCurator,
            null,
            null,
            i18n,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            consumerBindUtil,
            productCurator,
            null);

    consumerResource.unbindBySerial("fake uuid", Long.valueOf(1234L));
  }
Exemple #11
0
 @Test(expected = BadRequestException.class)
 public void nullPool() throws EntitlementRefusedException {
   String poolid = "foo";
   Consumer c = TestUtil.createConsumer(); // keeps me from casting null
   Map<String, Integer> pQs = new HashMap<String, Integer>();
   pQs.put(poolid, 1);
   when(cc.findByUuid(eq(c.getUuid()))).thenReturn(c);
   when(pm.entitleByPools(eq(c), eq(pQs))).thenThrow(new IllegalArgumentException());
   entitler.bindByPoolQuantities(c.getUuid(), pQs);
 }
  /** Basic test. If invalid id is given, should throw {@link NotFoundException} */
  @Test(expected = NotFoundException.class)
  public void unbindByInvalidPoolIdShouldFail() {
    Consumer consumer = createConsumer();
    ConsumerCurator consumerCurator = mock(ConsumerCurator.class);
    when(consumerCurator.verifyAndLookupConsumer(eq("fake-uuid"))).thenReturn(consumer);
    EntitlementCurator entitlementCurator = mock(EntitlementCurator.class);

    when(entitlementCurator.listByConsumerAndPoolId(eq(consumer), any(String.class)))
        .thenReturn(new ArrayList<Entitlement>());

    ConsumerResource consumerResource =
        new ConsumerResource(
            consumerCurator,
            null,
            null,
            null,
            entitlementCurator,
            null,
            null,
            i18n,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            consumerBindUtil,
            productCurator,
            null);
    consumerResource.unbindByPool("fake-uuid", "Run Forest!");
  }
  @Test
  public void testAsyncExport() {
    CdnCurator mockedCdnCurator = mock(CdnCurator.class);
    ManifestManager manifestManager = mock(ManifestManager.class);
    ConsumerResource cr =
        new ConsumerResource(
            mockedConsumerCurator,
            null,
            null,
            null,
            null,
            null,
            null,
            i18n,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            mockedOwnerCurator,
            null,
            null,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            mockedCdnCurator,
            null,
            null,
            productCurator,
            manifestManager);

    List<KeyValueParameter> extParams = new ArrayList<KeyValueParameter>();
    Owner owner = TestUtil.createOwner();
    Consumer consumer =
        TestUtil.createConsumer(new ConsumerType(ConsumerType.ConsumerTypeEnum.CANDLEPIN), owner);
    Cdn cdn = new Cdn("cdn-label", "test", "url");

    when(mockedConsumerCurator.verifyAndLookupConsumer(eq(consumer.getUuid())))
        .thenReturn(consumer);
    when(mockedCdnCurator.lookupByLabel(eq(cdn.getLabel()))).thenReturn(cdn);

    cr.exportDataAsync(null, consumer.getUuid(), cdn.getLabel(), "prefix", cdn.getUrl(), extParams);
    verify(manifestManager)
        .generateManifestAsync(
            eq(consumer.getUuid()),
            eq(cdn.getLabel()),
            eq("prefix"),
            eq(cdn.getUrl()),
            any(Map.class));
  }
 @Test
 public void testFetchAllConsumersForSomeUUIDs() {
   ConsumerResource cr =
       new ConsumerResource(
           mockedConsumerCurator,
           null,
           null,
           null,
           null,
           null,
           null,
           i18n,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           new CandlepinCommonTestConfig(),
           null,
           null,
           null,
           null,
           productCurator,
           null);
   Page<List<Consumer>> page = new Page<List<Consumer>>();
   ArrayList<Consumer> consumers = new ArrayList<Consumer>();
   page.setPageData(consumers);
   when(mockedConsumerCurator.searchOwnerConsumers(
           any(Owner.class),
           anyString(),
           (java.util.Collection<ConsumerType>) any(Collection.class),
           any(List.class),
           any(List.class),
           any(List.class),
           any(List.class),
           any(List.class),
           any(List.class),
           any(PageRequest.class)))
       .thenReturn(page);
   List<String> uuids = new ArrayList<String>();
   uuids.add("swiftuuid");
   List<Consumer> result = cr.list(null, null, null, uuids, null, null, null);
   assertEquals(consumers, result);
 }
  @Test(expected = NotFoundException.class)
  public void testBindByPoolBadConsumerUuid() throws Exception {
    ConsumerCurator consumerCurator = mock(ConsumerCurator.class);
    when(consumerCurator.verifyAndLookupConsumerWithEntitlements(any(String.class)))
        .thenThrow(new NotFoundException(""));
    ConsumerResource consumerResource =
        new ConsumerResource(
            consumerCurator,
            null,
            null,
            null,
            null,
            null,
            null,
            i18n,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            consumerBindUtil,
            productCurator,
            null);

    consumerResource.bind(
        "notarealuuid", "fake pool uuid", null, null, null, null, false, null, null, null, null);
  }
  public void testFetchAllConsumersForOwner() {
    ConsumerResource cr =
        new ConsumerResource(
            mockedConsumerCurator,
            null,
            null,
            null,
            null,
            null,
            null,
            i18n,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            mockedOwnerCurator,
            null,
            null,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            null,
            productCurator,
            null);
    Page<List<Consumer>> page = new Page<List<Consumer>>();
    ArrayList<Consumer> consumers = new ArrayList<Consumer>();
    page.setPageData(consumers);

    when(mockedOwnerCurator.lookupByKey(eq("taylorOwner"))).thenReturn(new Owner());
    when(mockedConsumerCurator.searchOwnerConsumers(
            any(Owner.class),
            anyString(),
            (java.util.Collection<ConsumerType>) any(Collection.class),
            any(List.class),
            any(List.class),
            any(List.class),
            any(List.class),
            any(List.class),
            any(List.class),
            any(PageRequest.class)))
        .thenReturn(page);
    List<Consumer> result = cr.list(null, null, "taylorOwner", null, null, null, null);
    assertEquals(consumers, result);
  }
  /** Basic test. If invalid id is given, should throw {@link NotFoundException} */
  @Test(expected = NotFoundException.class)
  public void testRegenerateEntitlementCertificatesWithInvalidConsumerId() {
    ConsumerCurator consumerCurator = mock(ConsumerCurator.class);
    when(consumerCurator.verifyAndLookupConsumer(any(String.class)))
        .thenThrow(new NotFoundException(""));
    ConsumerResource consumerResource =
        new ConsumerResource(
            consumerCurator,
            null,
            null,
            null,
            null,
            null,
            null,
            i18n,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            consumerBindUtil,
            productCurator,
            null);

    consumerResource.regenerateEntitlementCertificates("xyz", null, true);
  }
  /**
   * Interrogates the request and sets the principal for the request.
   *
   * @throws WebApplicationException when no auths result in a valid principal
   * @throws Failure when there is an unkown failure in the code
   * @return the Server Response
   */
  public ServerResponse preProcess(HttpRequest request, ResourceMethod method)
      throws Failure, WebApplicationException {

    SecurityHole securityHole = AuthUtil.checkForSecurityHoleAnnotation(method.getMethod());

    Principal principal = null;

    if (log.isDebugEnabled()) {
      log.debug("Authentication check for " + request.getUri().getPath());
    }

    // Check for anonymous calls, and let them through
    if (securityHole != null && securityHole.anon()) {
      log.debug("Request is anonymous, adding NoAuth Principal");
      principal = new NoAuthPrincipal();
    } else {
      // This method is not anonymous, so attempt to
      // establish the identity.
      for (AuthProvider provider : providers) {
        principal = provider.getPrincipal(request);

        if (principal != null) {
          break;
        }
      }
    }

    // At this point, there is no provider that has given a valid principal,
    // so we use the NoAuthPrincipal here if it is set.
    if (principal == null) {
      if (securityHole != null && securityHole.noAuth()) {
        log.debug("No auth allowed for resource; setting NoAuth principal");
        principal = new NoAuthPrincipal();
      } else {
        throw new UnauthorizedException("Invalid credentials.");
      }
    }

    // Expose the principal for Resteasy to inject via @Context
    ResteasyProviderFactory.pushContext(Principal.class, principal);

    if (principal instanceof ConsumerPrincipal) {
      // HACK: We need to do this after the principal has been pushed,
      // lest our security settings start getting upset when we try to
      // update a consumer without any roles:
      ConsumerPrincipal p = (ConsumerPrincipal) principal;
      consumerCurator.updateLastCheckin(p.getConsumer());
    }

    return null;
  }
  @Test
  public void testIdCertDoesNotRegenerate() throws Exception {
    SubscriptionServiceAdapter ssa = Mockito.mock(SubscriptionServiceAdapter.class);
    ComplianceRules rules = Mockito.mock(ComplianceRules.class);

    Consumer consumer = createConsumer();
    ComplianceStatus status = new ComplianceStatus();
    when(rules.getStatus(any(Consumer.class), any(Date.class), anyBoolean())).thenReturn(status);
    consumer.setIdCert(createIdCert(TestUtil.createDate(2025, 6, 9)));
    BigInteger origserial = consumer.getIdCert().getSerial().getSerial();

    when(mockedConsumerCurator.verifyAndLookupConsumer(consumer.getUuid())).thenReturn(consumer);

    ConsumerResource cr =
        new ConsumerResource(
            mockedConsumerCurator,
            null,
            null,
            ssa,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            mockedOwnerCurator,
            null,
            null,
            rules,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            consumerBindUtil,
            productCurator,
            null);

    Consumer c = cr.getConsumer(consumer.getUuid());

    assertEquals(origserial, c.getIdCert().getSerial().getSerial());
  }
  @Test
  public void testGetCertSerials() {
    Consumer consumer = createConsumer();
    List<EntitlementCertificate> certificates = createEntitlementCertificates();

    when(mockedEntitlementCertServiceAdapter.listForConsumer(consumer)).thenReturn(certificates);
    when(mockedConsumerCurator.verifyAndLookupConsumer(consumer.getUuid())).thenReturn(consumer);
    when(mockedEntitlementCurator.listByConsumer(consumer))
        .thenReturn(new ArrayList<Entitlement>());

    ConsumerResource consumerResource =
        new ConsumerResource(
            mockedConsumerCurator,
            null,
            null,
            null,
            mockedEntitlementCurator,
            null,
            mockedEntitlementCertServiceAdapter,
            null,
            null,
            null,
            null,
            null,
            null,
            mockedPoolManager,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            consumerBindUtil,
            productCurator,
            null);

    List<CertificateSerialDto> serials =
        consumerResource.getEntitlementCertificateSerials(consumer.getUuid());

    verifyCertificateSerialNumbers(serials);
  }
  @Before
  public void setupTest() {
    this.i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK);
    this.hypervisorType = new ConsumerType(ConsumerTypeEnum.HYPERVISOR);
    this.consumerResource =
        new ConsumerResource(
            this.consumerCurator,
            this.consumerTypeCurator,
            null,
            this.subscriptionService,
            null,
            this.idCertService,
            null,
            this.i18n,
            this.sink,
            this.eventFactory,
            null,
            null,
            this.userService,
            null,
            null,
            null,
            null,
            this.ownerCurator,
            this.activationKeyCurator,
            null,
            this.complianceRules,
            this.deletedConsumerCurator,
            null,
            new CandlepinCommonTestConfig());
    hypervisorResource =
        new HypervisorResource(
            consumerResource, poolManager, consumerCurator, this.deletedConsumerCurator, i18n);

    // Ensure that we get the consumer that was passed in back from the create call.
    when(consumerCurator.create(any(Consumer.class)))
        .thenAnswer(
            new Answer<Object>() {
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                return invocation.getArguments()[0];
              }
            });
    when(complianceRules.getStatus(any(Consumer.class), any(Date.class)))
        .thenReturn(new ComplianceStatus(new Date()));
  }
Exemple #22
0
  @Test
  public void bindByPoolString() throws EntitlementRefusedException {
    String poolid = "pool10";
    Entitlement ent = mock(Entitlement.class);
    List<Entitlement> eList = new ArrayList<Entitlement>();
    eList.add(ent);
    when(cc.findByUuid(eq("abcd1234"))).thenReturn(consumer);

    Map<String, Integer> pQs = new HashMap<String, Integer>();
    pQs.put(poolid, 1);

    when(pm.entitleByPools(eq(consumer), eq(pQs))).thenReturn(eList);

    List<Entitlement> ents = entitler.bindByPoolQuantities("abcd1234", pQs);
    assertNotNull(ents);
    assertEquals(ent, ents.get(0));
  }
  @Test
  public void testNoDryBindWhenAutobindDisabledForOwner() throws Exception {
    Consumer consumer = createConsumer();
    consumer.getOwner().setAutobindDisabled(true);
    when(mockedConsumerCurator.verifyAndLookupConsumer(eq(consumer.getUuid())))
        .thenReturn(consumer);
    ManifestManager manifestManager = mock(ManifestManager.class);
    ConsumerResource consumerResource =
        new ConsumerResource(
            mockedConsumerCurator,
            null,
            null,
            null,
            null,
            null,
            null,
            i18n,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            mockedOwnerCurator,
            null,
            null,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            null,
            productCurator,
            manifestManager);

    try {
      consumerResource.dryBind(consumer.getUuid(), "some-sla");
      fail("Should have thrown a BadRequestException.");
    } catch (BadRequestException e) {
      assertEquals("Owner has autobind disabled.", e.getMessage());
    }
  }
  @Before
  public void createEnforcer() throws Exception {
    MockitoAnnotations.initMocks(this);

    when(config.getInt(eq(ConfigProperties.PRODUCT_CACHE_MAX))).thenReturn(100);
    productCache = new ProductCache(config, productAdapter);

    owner = createOwner();
    ownerCurator.create(owner);

    consumer = TestUtil.createConsumer(owner);
    consumerTypeCurator.create(consumer.getType());
    consumerCurator.create(consumer);

    BufferedReader reader =
        new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream("/rules/test-rules.js")));
    StringBuilder builder = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      builder.append(line + "\n");
    }
    reader.close();

    Rules rules = mock(Rules.class);
    when(rules.getRules()).thenReturn(builder.toString());
    when(rulesCurator.getRules()).thenReturn(rules);
    when(rulesCurator.getUpdated()).thenReturn(TestDateUtil.date(2010, 1, 1));

    JsRunner jsRules = new JsRunnerProvider(rulesCurator).get();

    enforcer =
        new EntitlementRules(
            new DateSourceForTesting(2010, 1, 1),
            jsRules,
            productCache,
            i18n,
            config,
            consumerCurator,
            poolCurator);
  }
  /**
   * Test just verifies that entitler is called only once and it doesn't need any other object to
   * execute.
   */
  @Test
  public void testRegenerateEntitlementCertificateWithValidConsumer() {
    Consumer consumer = createConsumer();

    when(mockedConsumerCurator.verifyAndLookupConsumer(consumer.getUuid())).thenReturn(consumer);

    CandlepinPoolManager mgr = mock(CandlepinPoolManager.class);
    ConsumerResource cr =
        new ConsumerResource(
            mockedConsumerCurator,
            null,
            null,
            mockedSubscriptionServiceAdapter,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            mgr,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            consumerBindUtil,
            productCurator,
            null);
    cr.regenerateEntitlementCertificates(consumer.getUuid(), null, true);
    Mockito.verify(mgr, Mockito.times(1)).regenerateCertificatesOf(eq(consumer), eq(true));
  }
Exemple #26
0
  @Test
  public void testRevokesLapsedUnmappedGuestEntitlementsOnAutoHeal() throws Exception {
    Owner owner1 = new Owner("o1");

    Product product = TestUtil.createProduct();

    Pool p1 = TestUtil.createPool(owner1, product);

    p1.addAttribute(new PoolAttribute("unmapped_guests_only", "true"));

    Date thirtySixHoursAgo = new Date(new Date().getTime() - 36L * 60L * 60L * 1000L);
    Date twelveHoursAgo = new Date(new Date().getTime() - 12L * 60L * 60L * 1000L);

    Consumer c;

    c = TestUtil.createConsumer(owner1);
    c.setCreated(thirtySixHoursAgo);
    c.setFact("virt.uuid", "1");

    Entitlement e1 = TestUtil.createEntitlement(owner1, c, p1, null);
    e1.setEndDateOverride(twelveHoursAgo);
    Set<Entitlement> entitlementSet1 = new HashSet<Entitlement>();
    entitlementSet1.add(e1);

    p1.setEntitlements(entitlementSet1);

    CandlepinQuery cqmock = mock(CandlepinQuery.class);
    when(cqmock.iterator()).thenReturn(Arrays.asList(e1).iterator());
    when(entitlementCurator.findByPoolAttribute(eq(c), eq("unmapped_guests_only"), eq("true")))
        .thenReturn(cqmock);

    String[] pids = {product.getId(), "prod2"};
    when(cc.findByUuid(eq("abcd1234"))).thenReturn(c);
    entitler.bindByProducts(pids, "abcd1234", null, null);
    AutobindData data = AutobindData.create(c).forProducts(pids);
    verify(pm).entitleByProducts(eq(data));
    verify(pm).revokeEntitlement(e1);
  }
 @Test(expected = NotFoundException.class)
 public void testConsumerExistsNo() {
   when(mockedConsumerCurator.doesConsumerExist(any(String.class))).thenReturn(false);
   ConsumerResource cr =
       new ConsumerResource(
           mockedConsumerCurator,
           null,
           null,
           null,
           null,
           null,
           null,
           i18n,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           mockedComplianceRules,
           null,
           null,
           null,
           new CandlepinCommonTestConfig(),
           null,
           null,
           null,
           consumerBindUtil,
           productCurator,
           null);
   cr.consumerExists("uuid");
 }
  @Test
  public void hypervisorCheckInReportsFailuresOnCreateFailure() {
    Owner owner = new Owner("admin");

    Map<String, List<GuestId>> hostGuestMap = new HashMap<String, List<GuestId>>();
    String expectedHostVirtId = "test-host-id";
    hostGuestMap.put(
        expectedHostVirtId, Arrays.asList(new GuestId("GUEST_A"), new GuestId("GUEST_B")));

    // Force create.
    when(consumerCurator.findByUuid(eq(expectedHostVirtId))).thenReturn(null);

    String expectedMessage = "Forced Exception.";
    RuntimeException exception = new RuntimeException(expectedMessage);
    // Simulate failure  when checking the owner
    when(ownerCurator.lookupByKey(eq(owner.getKey()))).thenThrow(exception);

    HypervisorCheckInResult result =
        hypervisorResource.hypervisorCheckIn(hostGuestMap, principal, owner.getKey());

    Set<String> failures = result.getFailedUpdate();
    assertEquals(1, failures.size());
    assertEquals(expectedHostVirtId + ": " + expectedMessage, failures.iterator().next());
  }
 @Test
 public void testConsumerExistsYes() {
   when(mockedConsumerCurator.doesConsumerExist(any(String.class))).thenReturn(true);
   ConsumerResource cr =
       new ConsumerResource(
           mockedConsumerCurator,
           null,
           null,
           null,
           null,
           null,
           null,
           i18n,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           mockedComplianceRules,
           null,
           null,
           null,
           new CandlepinCommonTestConfig(),
           null,
           null,
           null,
           consumerBindUtil,
           productCurator,
           null);
   cr.consumerExists("uuid");
 }
  @SuppressWarnings("unchecked")
  @Test
  public void testBindByPools() throws Exception {
    PoolIdAndQuantity[] pools = new PoolIdAndQuantity[2];
    pools[0] = new PoolIdAndQuantity("first", 1);
    pools[1] = new PoolIdAndQuantity("second", 2);
    ConsumerCurator cc = mock(ConsumerCurator.class);
    SubscriptionServiceAdapter sa = mock(SubscriptionServiceAdapter.class);
    PoolManager pm = mock(PoolManager.class);
    Owner owner = TestUtil.createOwner();
    Consumer consumer = TestUtil.createConsumer(owner);

    when(cc.verifyAndLookupConsumerWithEntitlements(eq("fakeConsumer"))).thenReturn(consumer);
    when(sa.hasUnacceptedSubscriptionTerms(any(Owner.class))).thenReturn(false);

    ConsumerResource cr =
        new ConsumerResource(
            cc,
            null,
            null,
            sa,
            null,
            null,
            null,
            i18n,
            null,
            null,
            null,
            null,
            null,
            pm,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            null,
            new CandlepinCommonTestConfig(),
            null,
            null,
            null,
            consumerBindUtil,
            productCurator,
            null);

    Response rsp =
        cr.bind(
            "fakeConsumer",
            null,
            null,
            null,
            null,
            null,
            true,
            null,
            null,
            pools,
            new TrustedUserPrincipal("TaylorSwift"));

    JobDetail detail = (JobDetail) rsp.getEntity();
    PoolIdAndQuantity[] pQs =
        (PoolIdAndQuantity[]) detail.getJobDataMap().get("pool_and_quantities");
    boolean firstFound = false;
    boolean secondFound = false;
    for (PoolIdAndQuantity pq : pQs) {
      if (pq.getPoolId().contentEquals("first")) {
        firstFound = true;
        assertEquals(1, pq.getQuantity().intValue());
      }
      if (pq.getPoolId().contentEquals("second")) {
        secondFound = true;
        assertEquals(2, pq.getQuantity().intValue());
      }
    }
    assertTrue(firstFound);
    assertTrue(secondFound);
  }