@Test public void testCreatedDevPoolAttributes() { Owner owner = TestUtil.createOwner("o"); List<ProductData> devProdDTOs = new ArrayList<ProductData>(); Product p1 = TestUtil.createProduct("dev-product", "Dev Product"); p1.setAttribute("support_level", "Premium"); p1.setAttribute("expires_after", "47"); Product p2 = TestUtil.createProduct("provided-product1", "Provided Product 1"); Product p3 = TestUtil.createProduct("provided-product2", "Provided Product 2"); devProdDTOs.add(p1.toDTO()); devProdDTOs.add(p2.toDTO()); devProdDTOs.add(p3.toDTO()); Consumer devSystem = TestUtil.createConsumer(owner); devSystem.setFact("dev_sku", p1.getId()); devSystem.addInstalledProduct(new ConsumerInstalledProduct(p2)); devSystem.addInstalledProduct(new ConsumerInstalledProduct(p3)); when(productAdapter.getProductsByIds(eq(owner), any(List.class))).thenReturn(devProdDTOs); this.mockProducts(owner, p1, p2, p3); this.mockProductImport(owner, p1, p2, p3); this.mockContentImport(owner, Collections.<String, Content>emptyMap()); Pool created = entitler.assembleDevPool(devSystem, devSystem.getFact("dev_sku")); Calendar cal = Calendar.getInstance(); cal.setTime(created.getStartDate()); cal.add(Calendar.DAY_OF_YEAR, 47); assertEquals(created.getEndDate(), cal.getTime()); assertEquals("true", created.getAttributeValue(Pool.Attributes.DEVELOPMENT_POOL)); assertEquals(devSystem.getUuid(), created.getAttributeValue(Pool.Attributes.REQUIRES_CONSUMER)); assertEquals(p1.getId(), created.getProductId()); assertEquals(2, created.getProvidedProducts().size()); assertEquals("Premium", created.getProduct().getAttributeValue("support_level")); assertEquals(1L, created.getQuantity().longValue()); }
@Test public void testPhysicalIgnoresFutureConsumed() { // Setup a future pool for the same product: Pool futurePool = TestUtil.createPool(owner, product); futurePool.setStartDate(TestUtil.createDate(2050, 1, 1)); futurePool.setEndDate(TestUtil.createDate(2060, 1, 1)); pool.getProduct().setAttribute("multi-entitlement", "yes"); pool.getProduct().setAttribute("stacking_id", "1"); pool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "1"); futurePool.getProduct().setAttribute("multi-entitlement", "yes"); futurePool.getProduct().setAttribute("stacking_id", "1"); futurePool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "1"); consumer.setFact(SOCKET_FACT, "4"); // Green in future but we have nothing now: Entitlement e = createValidEntitlement(futurePool); e.setQuantity(4); Set<Entitlement> ents = new HashSet<Entitlement>(); ents.add(e); consumer.setEntitlements(ents); SuggestedQuantity suggested = quantityRules.getSuggestedQuantity(pool, consumer, new Date()); assertEquals(new Long(4), suggested.getSuggested()); }
@Test public void testDevPoolCreationAtBindNoFailMissingInstalledProduct() throws Exception { Owner owner = TestUtil.createOwner("o"); List<ProductData> devProdDTOs = new ArrayList<ProductData>(); Product p = TestUtil.createProduct("test-product", "Test Product"); Product ip1 = TestUtil.createProduct("test-product-installed-1", "Installed Test Product 1"); Product ip2 = TestUtil.createProduct("test-product-installed-2", "Installed Test Product 2"); devProdDTOs.add(p.toDTO()); devProdDTOs.add(ip1.toDTO()); Pool activePool = TestUtil.createPool(owner, p); List<Pool> activeList = new ArrayList<Pool>(); activeList.add(activePool); Consumer devSystem = TestUtil.createConsumer(owner); devSystem.setFact("dev_sku", p.getId()); devSystem.addInstalledProduct(new ConsumerInstalledProduct(ip1)); devSystem.addInstalledProduct(new ConsumerInstalledProduct(ip2)); when(config.getBoolean(eq(ConfigProperties.STANDALONE))).thenReturn(false); when(poolCurator.hasActiveEntitlementPools(eq(owner), any(Date.class))).thenReturn(true); when(productAdapter.getProductsByIds(any(Owner.class), any(List.class))) .thenReturn(devProdDTOs); this.mockProducts(owner, p, ip1, ip2); this.mockProductImport(owner, p, ip1, ip2); this.mockContentImport(owner, Collections.<String, Content>emptyMap()); Pool expectedPool = entitler.assembleDevPool(devSystem, p.getId()); when(pm.createPool(any(Pool.class))).thenReturn(expectedPool); AutobindData ad = new AutobindData(devSystem); entitler.bindByProducts(ad); }
@Test public void testFutureSuggested() { consumer.setFact(SOCKET_FACT, "4"); pool.setStartDate(TestUtil.createDate(9000, 1, 1)); pool.setEndDate(TestUtil.createDate(9001, 1, 1)); Pool currentPool = TestUtil.createPool(owner, product); currentPool.setStartDate(TestUtil.createDate(2000, 1, 1)); currentPool.setEndDate(TestUtil.createDate(5000, 1, 1)); currentPool.getProduct().setAttribute("multi-entitlement", "yes"); currentPool.getProduct().setAttribute("stacking_id", "1"); pool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "2"); currentPool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "2"); Entitlement currentEntitlement = TestUtil.createEntitlement(owner, consumer, currentPool, null); currentEntitlement.setQuantity(2); Set<Entitlement> ents = new HashSet<Entitlement>(); ents.add(currentEntitlement); consumer.setEntitlements(ents); SuggestedQuantity suggested = quantityRules.getSuggestedQuantity(currentPool, consumer, TestUtil.createDate(2010, 6, 1)); assertEquals(new Long(0), suggested.getSuggested()); // Make sure current coverage does not affect the future suggested = quantityRules.getSuggestedQuantity(pool, consumer, TestUtil.createDate(9000, 6, 1)); assertEquals(new Long(2), suggested.getSuggested()); }
@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 testDevPoolCreationAtBind() throws Exception { Owner owner = TestUtil.createOwner("o"); List<ProductData> devProdDTOs = new ArrayList<ProductData>(); Product p = TestUtil.createProduct("test-product", "Test Product"); p.setAttribute("support_level", "Premium"); devProdDTOs.add(p.toDTO()); Pool activePool = TestUtil.createPool(owner, p); List<Pool> activeList = new ArrayList<Pool>(); activeList.add(activePool); Pool devPool = mock(Pool.class); Consumer devSystem = TestUtil.createConsumer(owner); devSystem.setFact("dev_sku", p.getId()); when(config.getBoolean(eq(ConfigProperties.STANDALONE))).thenReturn(false); when(poolCurator.hasActiveEntitlementPools(eq(owner), any(Date.class))).thenReturn(true); when(productAdapter.getProductsByIds(eq(owner), any(List.class))).thenReturn(devProdDTOs); this.mockProducts(owner, p); this.mockProductImport(owner, p); this.mockContentImport(owner, Collections.<String, Content>emptyMap()); when(pm.createPool(any(Pool.class))).thenReturn(devPool); when(devPool.getId()).thenReturn("test_pool_id"); AutobindData ad = new AutobindData(devSystem); entitler.bindByProducts(ad); verify(pm).createPool(any(Pool.class)); }
private void setEventData(AbstractHibernateObject entity) { // Be careful to check for null before setting so we don't overwrite anything useful if (entity instanceof Named && ((Named) entity).getName() != null) { event.setTargetName(((Named) entity).getName()); } if (entity instanceof Owned) { Owner entityOwner = ((Owned) entity).getOwner(); if (entityOwner != null && entityOwner.getId() != null) { event.setOwnerId(entityOwner.getId()); } } if (entity instanceof Entitlement) { event.setReferenceType(Event.ReferenceType.POOL); Pool referencedPool = ((Entitlement) entity).getPool(); if (referencedPool != null && referencedPool.getId() != null) { event.setReferenceId(referencedPool.getId()); } } if ((String) entity.getId() != null) { event.setEntityId((String) entity.getId()); if (entity instanceof ConsumerProperty) { Consumer owningConsumer = ((ConsumerProperty) entity).getConsumer(); if (owningConsumer != null && owningConsumer.getId() != null) { event.setConsumerId(owningConsumer.getId()); } } } }
@Test(expected = ExportCreationException.class) public void doNotExportDirtyEntitlements() throws Exception { config.setProperty(ConfigProperties.SYNC_WORK_DIR, "/tmp/"); Consumer consumer = mock(Consumer.class); Entitlement ent = mock(Entitlement.class); Principal principal = mock(Principal.class); IdentityCertificate idcert = new IdentityCertificate(); List<Entitlement> entitlements = new ArrayList<Entitlement>(); entitlements.add(ent); when(pki.getSHA256WithRSAHash(any(InputStream.class))).thenReturn("signature".getBytes()); when(pprov.get()).thenReturn(principal); when(principal.getUsername()).thenReturn("testUser"); when(ec.listByConsumer(consumer)).thenReturn(entitlements); when(ent.getDirty()).thenReturn(true); idcert.setSerial(new CertificateSerial(10L, new Date())); idcert.setKey("euh0876puhapodifbvj094"); idcert.setCert("hpj-08ha-w4gpoknpon*)&^%#"); idcert.setCreated(new Date()); idcert.setUpdated(new Date()); when(consumer.getIdCert()).thenReturn(idcert); KeyPair keyPair = createKeyPair(); when(consumer.getKeyPair()).thenReturn(keyPair); when(pki.getPemEncoded(keyPair.getPrivateKey())).thenReturn("privateKey".getBytes()); when(pki.getPemEncoded(keyPair.getPublicKey())).thenReturn("publicKey".getBytes()); Exporter e = new Exporter( ctc, me, ce, cte, re, ece, ecsa, pe, psa, pce, ec, ee, pki, config, exportRules, pprov); e.getFullExport(consumer); }
/** * Create a tar.gz archive of the exported directory. * * @param exportDir Directory where Candlepin data was exported. * @return File reference to the new archive zip. */ private File makeArchive(Consumer consumer, File tempDir, File exportDir) throws IOException { String exportFileName = exportDir.getName() + ".zip"; log.info("Creating archive of " + exportDir.getAbsolutePath() + " in: " + exportFileName); File archive = createZipArchiveWithDir( tempDir, exportDir, "consumer_export.zip", "Candlepin export for " + consumer.getUuid()); InputStream archiveInputStream = null; try { archiveInputStream = new FileInputStream(archive); File signedArchive = createSignedZipArchive( tempDir, archive, exportFileName, pki.getSHA256WithRSAHash(archiveInputStream), "signed Candlepin export for " + consumer.getUuid()); log.debug("Returning file: " + archive.getAbsolutePath()); return signedArchive; } finally { if (archiveInputStream != null) { try { archiveInputStream.close(); } catch (Exception e) { // nothing to do } } } }
@Test public void testStackOnlyStacksWithSameStackingId() { consumer.setFact(IS_VIRT, "false"); consumer.setFact(SOCKET_FACT, "8"); pool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "2"); pool.setQuantity(10L); Product product1 = TestUtil.createProduct(); Pool pool1 = TestUtil.createPool(owner, product1); Entitlement e = TestUtil.createEntitlement(owner, consumer, pool1, new EntitlementCertificate()); Set<Entitlement> entSet = new HashSet<Entitlement>(); entSet.add(e); pool1.setEntitlements(entSet); pool1.getProduct().setAttribute("multi-entitlement", "yes"); pool1.getProduct().setAttribute("stacking_id", "2"); pool1.getProduct().setAttribute(SOCKET_ATTRIBUTE, "2"); pool1.setQuantity(10L); // Consume 2 subscriptions with another stacking ID Entitlement toAdd = pool1.getEntitlements().iterator().next(); toAdd.setQuantity(2); consumer.addEntitlement(toAdd); // Ensure the 2 attached entitlements do not cause the suggested quantity to change SuggestedQuantity suggested = quantityRules.getSuggestedQuantity(pool, consumer, new Date()); assertEquals(new Long(4), suggested.getSuggested()); }
private Consumer mockConsumer(String[] installedProducts) { Consumer c = new Consumer(); for (String pid : installedProducts) { c.addInstalledProduct(new ConsumerInstalledProduct(pid, pid)); } c.setFact("cpu.cpu_socket(s)", "8"); // 8 socket machine return c; }
@Test public void exportIdentityCertificate() throws Exception { config.setProperty(ConfigProperties.SYNC_WORK_DIR, "/tmp/"); Rules mrules = mock(Rules.class); Consumer consumer = mock(Consumer.class); Principal principal = mock(Principal.class); when(mrules.getRules()).thenReturn("foobar"); when(pki.getSHA256WithRSAHash(any(InputStream.class))).thenReturn("signature".getBytes()); when(rc.getRules()).thenReturn(mrules); when(pprov.get()).thenReturn(principal); when(principal.getUsername()).thenReturn("testUser"); // specific to this test IdentityCertificate idcert = new IdentityCertificate(); idcert.setSerial(new CertificateSerial(10L, new Date())); idcert.setKey("euh0876puhapodifbvj094"); idcert.setCert("hpj-08ha-w4gpoknpon*)&^%#"); idcert.setCreated(new Date()); idcert.setUpdated(new Date()); when(consumer.getIdCert()).thenReturn(idcert); KeyPair keyPair = createKeyPair(); when(consumer.getKeyPair()).thenReturn(keyPair); when(pki.getPemEncoded(keyPair.getPrivateKey())).thenReturn("privateKey".getBytes()); when(pki.getPemEncoded(keyPair.getPublicKey())).thenReturn("publicKey".getBytes()); // FINALLY test this badboy Exporter e = new Exporter( ctc, me, ce, cte, re, ece, ecsa, pe, psa, pce, ec, ee, pki, config, exportRules, pprov, dvc, dve, cdnc, cdne); File export = e.getFullExport(consumer); // VERIFY assertNotNull(export); assertTrue(export.exists()); verifyContent(export, "export/upstream_consumer/10.pem", new VerifyIdentityCert("10.pem")); }
@Test public void testLazyRegenerateForConsumer() { Entitlement e = new Entitlement(); Consumer c = new Consumer(); c.addEntitlement(e); manager.regenerateEntitlementCertificates(c, true); assertTrue(e.getDirty()); verifyZeroInteractions(entCertAdapterMock); }
@Test public void testIsNotVirtWhenFactIsEmpty() { consumer.setFact(IS_VIRT, ""); consumer.setFact(SOCKET_FACT, "4"); pool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "2"); SuggestedQuantity suggested = quantityRules.getSuggestedQuantity(pool, consumer, new Date()); assertEquals(new Long(2), suggested.getSuggested()); }
@Test public void entIsCompliantIfSocketsNotSetOnEntPool() { Consumer c = mock(Consumer.class); when(c.hasFact("cpu.cpu_socket(s)")).thenReturn(true); when(c.getFact("cpu.cpu_socket(s)")).thenReturn("2"); Entitlement ent = mockEntitlement(c, PRODUCT_1); assertTrue(compliance.isEntitlementCompliant(c, ent)); }
@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")); }
private void postBindVirtLimit( PoolHelper postHelper, Entitlement entitlement, Pool pool, Consumer c, Map<String, String> attributes) { log.debug("Running virt_limit post-bind."); if (!c.isManifest() && (config.standalone() || attributes.containsKey("host_limited"))) { String productId = pool.getProductId(); String virtLimit = attributes.get("virt_limit"); if ("unlimited".equals(virtLimit)) { postHelper.createHostRestrictedPool(productId, pool, "unlimited"); } else { int virtQuantity = Integer.parseInt(virtLimit) * entitlement.getQuantity(); if (virtQuantity > 0) { postHelper.createHostRestrictedPool(productId, pool, String.valueOf(virtQuantity)); } } } else { if (!config.standalone() && c.isManifest()) { String virtLimit = attributes.get("virt_limit"); if (!"unlimited".equals(virtLimit)) { // if the bonus pool is not unlimited, then the bonus pool // quantity // needs to be adjusted based on the virt limit int virtQuantity = Integer.parseInt(virtLimit) * entitlement.getQuantity(); if (virtQuantity > 0) { List<Pool> pools = postHelper.lookupBySubscriptionId(pool.getSubscriptionId()); for (int idex = 0; idex < pools.size(); idex++) { Pool derivedPool = pools.get(idex); if (derivedPool.getAttributeValue("pool_derived") != null) { derivedPool = postHelper.updatePoolQuantity(derivedPool, -1 * virtQuantity); } } } } else { // if the bonus pool is unlimited, then the quantity needs // to go to 0 // when the physical pool is exhausted completely by export. // A quantity of 0 will block future binds, whereas -1 does // not. if (pool.getQuantity().equals(pool.getExported())) { // getting all pools matching the sub id. Filtering out // the 'parent'. List<Pool> pools = postHelper.lookupBySubscriptionId(pool.getSubscriptionId()); for (int idex = 0; idex < pools.size(); idex++) { Pool derivedPool = pools.get(idex); if (derivedPool.getAttributeValue("pool_derived") != null) { derivedPool = postHelper.setPoolQuantity(derivedPool, 0); } } } } } } }
@Test public void testVirtUses1IfNoVcpu() { // Ensure that we start this test with no entitlements. consumer.getEntitlements().clear(); consumer.setFact(IS_VIRT, "true"); consumer.setFact(SOCKET_FACT, "4"); consumer.setFact(CORES_FACT, "8"); SuggestedQuantity suggested = quantityRules.getSuggestedQuantity(pool, consumer, new Date()); assertEquals(new Long(1), suggested.getSuggested()); }
@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); }
@Test public void testVirtIgnoresSockets() { // Ensure that we start this test with no entitlements. consumer.getEntitlements().clear(); consumer.setFact(IS_VIRT, "true"); consumer.setFact(SOCKET_FACT, "4"); pool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "2"); SuggestedQuantity suggested = quantityRules.getSuggestedQuantity(pool, consumer, new Date()); assertEquals(new Long(1), suggested.getSuggested()); }
@Test public void entIsNotCompliantWhenSocketsAreNotCovered() { Consumer c = mock(Consumer.class); when(c.hasFact("cpu.cpu_socket(s)")).thenReturn(true); when(c.getFact("cpu.cpu_socket(s)")).thenReturn("8"); Entitlement ent = mockEntitlement(c, PRODUCT_1); ent.getPool().setProductAttribute("sockets", "4", PRODUCT_1); assertFalse(compliance.isEntitlementCompliant(c, ent)); }
@Test public void stackIsCompliant() { Consumer c = mock(Consumer.class); when(c.hasFact("cpu.cpu_socket(s)")).thenReturn(true); when(c.getFact("cpu.cpu_socket(s)")).thenReturn("2"); List<Entitlement> ents = new LinkedList<Entitlement>(); ents.add(mockStackedEntitlement(c, STACK_ID_1, "Awesome Product", PRODUCT_1)); assertTrue(compliance.isStackCompliant(c, STACK_ID_1, ents)); }
@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 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(expected = BadRequestException.class) public void testCreatePersonConsumerWithActivationKey() { Consumer c = mock(Consumer.class); Owner o = mock(Owner.class); ActivationKey ak = mock(ActivationKey.class); NoAuthPrincipal nap = mock(NoAuthPrincipal.class); ActivationKeyCurator akc = mock(ActivationKeyCurator.class); OwnerCurator oc = mock(OwnerCurator.class); ConsumerTypeCurator ctc = mock(ConsumerTypeCurator.class); ConsumerContentOverrideCurator ccoc = mock(ConsumerContentOverrideCurator.class); ConsumerType cType = new ConsumerType(ConsumerTypeEnum.PERSON); when(ak.getId()).thenReturn("testKey"); when(o.getKey()).thenReturn("testOwner"); when(akc.lookupForOwner(eq("testKey"), eq(o))).thenReturn(ak); when(oc.lookupByKey(eq("testOwner"))).thenReturn(o); when(c.getType()).thenReturn(cType); when(c.getName()).thenReturn("testConsumer"); when(ctc.lookupByLabel(eq("person"))).thenReturn(cType); ConsumerResource cr = new ConsumerResource( null, ctc, null, null, null, null, null, i18n, null, null, null, null, null, null, null, oc, akc, null, null, null, null, null, new CandlepinCommonTestConfig(), null, null, null, consumerBindUtil, productCurator, null); cr.create(c, nap, null, "testOwner", "testKey", true); }
@Test public void testInstanceBasedOnPhysicalNotEnoughAvailableUneven() { consumer.setFact(IS_VIRT, "false"); consumer.setFact(SOCKET_FACT, "40"); // lots of ents required pool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "2"); pool.getProduct().setAttribute(INSTANCE_ATTRIBUTE, "2"); pool.setQuantity(3L); SuggestedQuantity suggested = quantityRules.getSuggestedQuantity(pool, consumer, new Date()); assertEquals(new Long(2), suggested.getSuggested()); assertEquals(new Long(2), suggested.getIncrement()); }
/* * Distributors should always get suggested=1, increment=1 */ @Test public void testInstanceBasedOnDistributor() { Consumer dist = TestUtil.createConsumer(owner); dist.getType().setManifest(true); dist.setFact(IS_VIRT, "false"); dist.setFact(SOCKET_FACT, "4"); pool.getProduct().setAttribute(SOCKET_ATTRIBUTE, "2"); pool.getProduct().setAttribute(INSTANCE_ATTRIBUTE, "2"); SuggestedQuantity suggested = quantityRules.getSuggestedQuantity(pool, dist, new Date()); assertEquals(new Long(1), suggested.getSuggested()); assertEquals(new Long(1), suggested.getIncrement()); }
@Test public void testCreatedDevSkuWithNoSla() { Owner owner = TestUtil.createOwner("o"); List<ProductData> devProdDTOs = new ArrayList<ProductData>(); final Product p1 = TestUtil.createProduct("dev-product", "Dev Product"); devProdDTOs.add(p1.toDTO()); Consumer devSystem = TestUtil.createConsumer(owner); devSystem.setFact("dev_sku", p1.getId()); when(productAdapter.getProductsByIds(eq(owner), any(List.class))).thenReturn(devProdDTOs); mockUpdateProduct(p1, owner); this.mockContentImport(owner, Collections.<String, Content>emptyMap()); when(productManager.importProducts(eq(owner), any(Map.class), any(Map.class))) .thenAnswer( new Answer<ImportResult<Product>>() { @Override public ImportResult<Product> answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); Map<String, ProductData> productData = (Map<String, ProductData>) args[1]; ImportResult<Product> importResult = new ImportResult<Product>(); Map<String, Product> output = importResult.getCreatedEntities(); // We need to copy the attributes from the product data to the product to // simulate a proper update. for (ProductData pdata : productData.values()) { if (pdata != null) { if (p1.getId().equals(pdata.getId())) { p1.clearAttributes(); if (pdata.getAttributes() != null) { for (ProductAttributeData attrib : pdata.getAttributes()) { p1.setAttribute(attrib.getName(), attrib.getValue()); } } output.put(p1.getId(), p1); } else { Product product = new Product(pdata.getId(), pdata.getName()); // Do we care about this product? Probably not. output.put(product.getId(), product); } } } return importResult; } }); Pool created = entitler.assembleDevPool(devSystem, devSystem.getFact("dev_sku")); assertEquals(entitler.DEFAULT_DEV_SLA, created.getProduct().getAttributeValue("support_level")); }
@Test(expected = NotFoundException.class) public void testNullPerson() { Consumer c = mock(Consumer.class); Owner o = mock(Owner.class); UserServiceAdapter usa = mock(UserServiceAdapter.class); UserPrincipal up = mock(UserPrincipal.class); OwnerCurator oc = mock(OwnerCurator.class); ConsumerTypeCurator ctc = mock(ConsumerTypeCurator.class); ConsumerType cType = new ConsumerType(ConsumerTypeEnum.PERSON); when(o.getKey()).thenReturn("testOwner"); when(oc.lookupByKey(eq("testOwner"))).thenReturn(o); when(c.getType()).thenReturn(cType); when(c.getName()).thenReturn("testConsumer"); when(ctc.lookupByLabel(eq("person"))).thenReturn(cType); when(up.canAccess(eq(o), eq(SubResource.CONSUMERS), eq(Access.CREATE))).thenReturn(true); // usa.findByLogin() will return null by default no need for a when ConsumerResource cr = new ConsumerResource( null, ctc, null, null, null, null, null, i18n, null, null, null, null, usa, null, null, oc, null, null, null, null, null, null, new CandlepinCommonTestConfig(), null, null, null, consumerBindUtil, productCurator, null); cr.create(c, up, null, "testOwner", null, true); }
@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()); }