@Test(timeout = 2000) public void awaitingForeverReturnsLongMaxValueAsRemainingTime() { final Set<Long> remainingTimes = new HashSet<Long>(); final Set<Long> elapsedTimes = new HashSet<Long>(); with() .conditionEvaluationListener(new ConditionEvaluationListener<Integer>() { public void conditionEvaluated(EvaluatedCondition<Integer> condition) { remainingTimes.add(condition.getRemainingTimeInMS()); elapsedTimes.add(condition.getElapsedTimeInMS()); } }) .forever() .until(new CountDown(10), is(equalTo(5))); assertThat(remainingTimes, everyItem(is(Long.MAX_VALUE))); assertThat(elapsedTimes, everyItem(is(not(Long.MAX_VALUE)))); }
/** * Tests {@link Ehcache#putAll(Map)} for * <ul> * <li>non-empty request map</li> * <li>populated {@code Store} - some keys overlap request</li> * <li>{@link Store#bulkCompute} throws after accessing writer</li> * <li>no {@code CacheLoaderWriter}</li> * </ul> */ @Test public void testPutAllStoreSomeOverlapStoreAccessExceptionAfterNoWriter() throws Exception { final Map<String, String> originalStoreContent = getEntryMap(KEY_SET_A, KEY_SET_B); final FakeStore fakeStore = new FakeStore(originalStoreContent, Collections.singleton("keyA3")); this.store = spy(fakeStore); final Ehcache<String, String> ehcache = this.getEhcache(); final Map<String, String> contentUpdates = getAltEntryMap("new_", fanIn(KEY_SET_A, KEY_SET_C)); ehcache.putAll(contentUpdates); final InOrder ordered = inOrder(this.store, this.resilienceStrategy); ordered.verify(this.store, atLeast(1)).bulkCompute(this.bulkComputeSetCaptor.capture(), getAnyEntryIterableFunction()); assertThat(this.getBulkComputeArgs(), everyItem(isIn(contentUpdates.keySet()))); // ResilienceStrategy invoked; no assertions about Store content ordered.verify(this.resilienceStrategy) .putAllFailure(eq(contentUpdates), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.PutOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutAllOutcome.FAILURE)); assertThat(ehcache.getBulkMethodEntries().get(BulkOps.PUT_ALL).intValue(), is(0)); }
/** * Tests {@link Ehcache#removeAll(Set)} for * <ul> * <li>non-empty request set</li> * <li>populated {@code Store} - some keys overlap request</li> * <li>{@link Store#bulkCompute} throws after accessing writer</li> * <li>no {@code CacheLoaderWriter}</li> * </ul> */ @Test public void testRemoveAllStoreSomeOverlapStoreAccessExceptionAfterNoWriter() throws Exception { final Map<String, String> originalStoreContent = getEntryMap(KEY_SET_A, KEY_SET_B); final FakeStore fakeStore = new FakeStore(originalStoreContent, Collections.singleton("keyA3")); this.store = spy(fakeStore); final Ehcache<String, String> ehcache = this.getEhcache(); final Set<String> contentUpdates = fanIn(KEY_SET_A, KEY_SET_C); ehcache.removeAll(contentUpdates); final InOrder ordered = inOrder(this.store, this.resilienceStrategy); ordered.verify(this.store, atLeast(1)).bulkCompute(this.bulkComputeSetCaptor.capture(), getAnyEntryIterableFunction()); assertThat(this.getBulkComputeArgs(), everyItem(isIn(contentUpdates))); // ResilienceStrategy invoked; no assertions about Store content ordered.verify(this.resilienceStrategy) .removeAllFailure(eq(contentUpdates), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.RemoveOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveAllOutcome.FAILURE)); assertThat(ehcache.getBulkMethodEntries().get(BulkOps.REMOVE_ALL).intValue(), is(0)); }
/** * Tests {@link Ehcache#putAll(Map)} for * <ul> * <li>non-empty request map</li> * <li>populated {@code Store} - some keys overlap request</li> * <li>{@link Store#bulkCompute} throws before accessing writer</li> * <li>no {@code CacheLoaderWriter}</li> * </ul> */ @Test public void testPutAllStoreSomeOverlapStoreAccessExceptionBeforeNoWriter() throws Exception { final Map<String, String> originalStoreContent = getEntryMap(KEY_SET_A, KEY_SET_B); final FakeStore fakeStore = new FakeStore(originalStoreContent); this.store = spy(fakeStore); doThrow(new StoreAccessException("")).when(this.store) .bulkCompute(getAnyStringSet(), getAnyEntryIterableFunction()); final Ehcache<String, String> ehcache = this.getEhcache(); final Map<String, String> contentUpdates = getAltEntryMap("new_", fanIn(KEY_SET_A, KEY_SET_C)); ehcache.putAll(contentUpdates); final InOrder ordered = inOrder(this.store, this.resilienceStrategy); ordered.verify(this.store, atLeast(1)).bulkCompute(this.bulkComputeSetCaptor.capture(), getAnyEntryIterableFunction()); assertThat(this.getBulkComputeArgs(), everyItem(isIn(contentUpdates.keySet()))); // ResilienceStrategy invoked; no assertions about Store content ordered.verify(this.resilienceStrategy) .putAllFailure(eq(contentUpdates), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.PutOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutAllOutcome.FAILURE)); assertThat(ehcache.getBulkMethodEntries().get(BulkOps.PUT_ALL).intValue(), is(0)); }
/** * Test set user code ClassLoader before calling ProcessingTimeCallback. */ @Test public void testSetsUserCodeClassLoaderForTimerThreadFactory() throws Throwable { syncLatch = new OneShotLatch(); try (MockEnvironment mockEnvironment = new MockEnvironmentBuilder() .setUserCodeClassLoader(new TestUserCodeClassLoader()) .build()) { TimeServiceTask timerServiceTask = new TimeServiceTask(mockEnvironment); CompletableFuture<Void> invokeFuture = CompletableFuture.runAsync( () -> { try { timerServiceTask.invoke(); } catch (Exception e) { throw new CompletionException(e); } }, TestingUtils.defaultExecutor()); invokeFuture.get(); assertThat(timerServiceTask.getClassLoaders(), hasSize(greaterThanOrEqualTo(1))); assertThat(timerServiceTask.getClassLoaders(), everyItem(instanceOf(TestUserCodeClassLoader.class))); } }
/** * Ensures that multiple {@code Service} implementations of an interface <i>with</i> the * {@link PluralService} annotation can both be registered. */ @Test public void testPluralRegistration() throws Exception { final ServiceLocator.DependencySet dependencySet = dependencySet(); final AlphaServiceProviderImpl alphaServiceProvider = new AlphaServiceProviderImpl(); final BetaServiceProviderImpl betaServiceProvider = new BetaServiceProviderImpl(); dependencySet.with(alphaServiceProvider); assertThat(dependencySet.providersOf(AlphaServiceProviderImpl.class), everyItem(isOneOf(alphaServiceProvider))); assertThat(dependencySet.providersOf(AlphaServiceProvider.class), everyItem(Matchers.<AlphaServiceProvider>isOneOf(alphaServiceProvider))); assertThat(dependencySet.providersOf(PluralServiceProvider.class), everyItem(Matchers.<PluralServiceProvider>isOneOf(alphaServiceProvider))); dependencySet.with(betaServiceProvider); assertThat(dependencySet.providersOf(BetaServiceProviderImpl.class), everyItem(isOneOf(betaServiceProvider))); assertThat(dependencySet.providersOf(BetaServiceProvider.class), everyItem(Matchers.<BetaServiceProvider>isOneOf(betaServiceProvider))); assertThat(dependencySet.providersOf(PluralServiceProvider.class), everyItem(Matchers.<PluralServiceProvider>isOneOf(alphaServiceProvider, betaServiceProvider))); } }
/** * Tests {@link Ehcache#removeAll(Set)} for * <ul> * <li>non-empty request set</li> * <li>populated {@code Store} - some keys overlap request</li> * <li>{@link Store#bulkCompute} throws before accessing writer</li> * <li>no {@code CacheLoaderWriter}</li> * </ul> */ @Test public void testRemoveAllStoreSomeOverlapStoreAccessExceptionBeforeNoWriter() throws Exception { final Map<String, String> originalStoreContent = getEntryMap(KEY_SET_A, KEY_SET_B); final FakeStore fakeStore = new FakeStore(originalStoreContent); this.store = spy(fakeStore); doThrow(new StoreAccessException("")).when(this.store) .bulkCompute(getAnyStringSet(), getAnyEntryIterableFunction()); final Ehcache<String, String> ehcache = this.getEhcache(); final Set<String> contentUpdates = fanIn(KEY_SET_A, KEY_SET_C); ehcache.removeAll(contentUpdates); final InOrder ordered = inOrder(this.store, this.resilienceStrategy); ordered.verify(this.store, atLeast(1)).bulkCompute(this.bulkComputeSetCaptor.capture(), getAnyEntryIterableFunction()); assertThat(this.getBulkComputeArgs(), everyItem(isIn(contentUpdates))); // ResilienceStrategy invoked; no assertions about Store content ordered.verify(this.resilienceStrategy) .removeAllFailure(eq(contentUpdates), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.RemoveOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveAllOutcome.FAILURE)); assertThat(ehcache.getBulkMethodEntries().get(BulkOps.REMOVE_ALL).intValue(), is(0)); }
@Test public void deserialization_with_user_attributes() throws Exception { String dataWithoutUserAttributes ="{\"principal\":{\"id\":\"user-id\",\"name\":\"username\",\"email\":\"email\",\"origin\":\"uaa\",\"externalId\":null,\"zoneId\":\"uaa\"},\"credentials\":null,\"authorities\":[],\"externalGroups\":[\"something\",\"or\",\"other\",\"something\"],\"details\":null,\"authenticated\":true,\"authenticatedTime\":null,\"name\":\"username\", \"previousLoginSuccessTime\":1485305759347}"; UaaAuthentication authentication = JsonUtils.readValue(dataWithoutUserAttributes, UaaAuthentication.class); assertEquals(3, authentication.getExternalGroups().size()); assertThat(authentication.getExternalGroups(), Matchers.containsInAnyOrder("something", "or", "other")); assertTrue(authentication.isAuthenticated()); MultiValueMap<String,String> userAttributes = new LinkedMultiValueMap<>(); userAttributes.add(COST_CENTER, DENVER_CO); userAttributes.add(MANAGER, JOHN_THE_SLOTH); userAttributes.add(MANAGER, KARI_THE_ANT_EATER); authentication.setUserAttributes(userAttributes); String dataWithUserAttributes = JsonUtils.writeValueAsString(authentication); assertTrue("userAttributes should be part of the JSON", dataWithUserAttributes.contains("userAttributes")); UaaAuthentication authWithUserData = JsonUtils.readValue(dataWithUserAttributes, UaaAuthentication.class); assertNotNull(authWithUserData.getUserAttributes()); assertThat(authWithUserData.getUserAttributes().entrySet(), everyItem(isIn(userAttributes.entrySet()))); assertThat(userAttributes.entrySet(), everyItem(isIn(authWithUserData.getUserAttributes().entrySet()))); assertEquals(3, authentication.getExternalGroups().size()); assertThat(authentication.getExternalGroups(), Matchers.containsInAnyOrder("something", "or", "other")); assertTrue(authentication.isAuthenticated()); assertEquals((Long) 1485305759347L, authentication.getLastLoginSuccessTime()); }
@Test public void testRandomSubsetPick() { LongSortedArraySet singleton = LongUtils.packedSet(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Random rng = new Random(); for (int i = 0; i < 50; i++) { LongSortedSet sample = singleton.randomSubset(rng, 5); assertThat(sample, hasSize(5)); assertThat(sample, everyItem(allOf(greaterThan(0L), lessThan(11L)))); } }
@Test public void testScoreSet() { ItemScorer pred = new ConstantItemScorer(5); Map<Long, Double> v = pred.score(42, LongUtils.packedSet(1, 2, 3, 5, 7)); assertThat(v.keySet(), contains(1L, 2L, 3L, 5L, 7L)); assertThat(v.values(), everyItem(equalTo(5.0))); }
@Test public void testRandomSubsetPickExclude() { LongSortedArraySet singleton = LongUtils.packedSet(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Random rng = new Random(); for (int i = 0; i < 50; i++) { LongSortedSet sample = singleton.randomSubset(rng, 5, LongSets.singleton(7L)); assertThat(sample, hasSize(5)); assertThat(sample, everyItem(allOf(greaterThan(0L), lessThan(11L)))); assertThat(sample, not(hasItem(7L))); } }
@Test public void testRandomSubsetPickMultiExclude() { LongSortedArraySet singleton = LongUtils.packedSet(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); for (int i = 0; i < 50; i++) { LongSortedSet sample = singleton.randomSubset(new Random(), 5, LongUtils.packedSet(1L), LongUtils.packedSet(3L)); assertThat(sample, hasSize(5)); assertThat(sample, everyItem(allOf(greaterThan(0L), lessThan(11L)))); assertThat(sample, not(hasItem(1L))); assertThat(sample, not(hasItem(3L))); } }
@Test public void testScoreDetails() { ItemScorer pred = new ConstantItemScorer(5); ResultMap v = pred.scoreWithDetails(42, LongUtils.packedSet(1, 2, 3, 5, 7)); assertThat(v.keySet(), contains(1L, 2L, 3L, 5L, 7L)); assertThat(v.scoreMap().values(), everyItem(equalTo(5.0))); }
@Test public void shouldCreateTablesConsistentlyWithMultipleCassandraNodes() throws Exception { TableReference table1 = TableReference.createFromFullyQualifiedName("ns.table1"); CassandraKeyValueServiceConfig config = ThreeNodeCassandraCluster.KVS_CONFIG; try { CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT); for (int i = 0; i < THREAD_COUNT; i++) { async(() -> { CassandraKeyValueService keyValueService = CassandraKeyValueServiceImpl.createForTesting(config, Optional.empty()); barrier.await(); keyValueService.createTable(table1, AtlasDbConstants.GENERIC_TABLE_METADATA); return null; }); } } finally { executorService.shutdown(); assertTrue(executorService.awaitTermination(4, TimeUnit.MINUTES)); } CassandraKeyValueService kvs = CassandraKeyValueServiceImpl.createForTesting(config, Optional.empty()); assertThat(kvs.getAllTableNames(), hasItem(table1)); assertThat(new File(CONTAINERS.getLogDirectory()), containsFiles(everyItem(doesNotContainTheColumnFamilyIdMismatchError()))); }
@Test public void testInject() throws RecommenderBuildException { LenskitConfiguration config = new LenskitConfiguration(); config.addComponent(EntityCollectionDAO.create()); config.bind(ItemScorer.class).to(ConstantItemScorer.class); config.set(ConstantItemScorer.Value.class).to(Math.PI); try (LenskitRecommender rec = LenskitRecommenderEngine.build(config).createRecommender()) { ItemScorer scorer = rec.getItemScorer(); assertThat(scorer, notNullValue()); assertThat(scorer, instanceOf(ConstantItemScorer.class)); Map<Long, Double> v = scorer.score(42, LongUtils.packedSet(1, 2, 3, 5, 7)); assertThat(v.keySet(), hasSize(5)); assertThat(v.keySet(), containsInAnyOrder(1L, 2L, 3L, 5L, 7L)); assertThat(v.values(), everyItem(equalTo(Math.PI))); } } }
@Test public void testSampleABunch() { LongSet items = new LongOpenHashSet(); for (int i = 0; i < 25; i++) { items.add(i + 1); } GroupEntitySplitter split = GroupEntitySplitter.disjointSample(3); Long2IntMap splits = split.splitEntities(items, 5, new Random()); assertThat(splits.size(), equalTo(15)); assertThat(splits.keySet(), everyItem(isIn(items))); assertThat(new IntOpenHashSet(splits.values()), containsInAnyOrder(0, 1, 2, 3, 4)); int[] counts = new int[5]; for (int sp: splits.values()) { counts[sp] += 1; } assertThat(new IntArrayList(counts), everyItem(equalTo(3))); }
@Test public void testPartitionABunch() { LongSet items = new LongOpenHashSet(); for (int i = 0; i < 25; i++) { items.add(i + 1); } GroupEntitySplitter split = GroupEntitySplitter.partition(); Long2IntMap splits = split.splitEntities(items, 5, new Random()); assertThat(splits.keySet(), equalTo(items)); assertThat(new IntOpenHashSet(splits.values()), containsInAnyOrder(0, 1, 2, 3, 4)); int[] counts = new int[5]; for (int sp: splits.values()) { counts[sp] += 1; } assertThat(new IntArrayList(counts), everyItem(equalTo(5))); }
@Test public void testRandomMaps() { for (Map<Long,Double> map: someMaps(longs(), doubles())) { Long2DoubleSortedArrayMap vec = Long2DoubleSortedArrayMap.create(map); Set<Long> picked = sets(map.keySet()).next(); Set<Long> extra = sets(longs()).next(); LongSortedSet wanted = LongUtils.setUnion(LongUtils.asLongSet(picked), LongUtils.asLongSet(extra)); Long2DoubleSortedMap sv = vec.subMap(wanted); assertThat(sv.keySet(), everyItem(isIn(wanted))); assertThat(sv.keySet(), containsInAnyOrder(picked.toArray())); assertThat(sv.entrySet(), everyItem(isIn(map.entrySet()))); } }
@Test public void testSampleButICant() { LongSet items = new LongOpenHashSet(); for (int i = 0; i < 25; i++) { items.add(i + 1); } GroupEntitySplitter split = GroupEntitySplitter.disjointSample(10); Long2IntMap splits = split.splitEntities(items, 5, new Random()); assertThat(splits.keySet(), equalTo(items)); assertThat(new IntOpenHashSet(splits.values()), containsInAnyOrder(0, 1, 2, 3, 4)); int[] counts = new int[5]; for (int sp: splits.values()) { counts[sp] += 1; } assertThat(new IntArrayList(counts), everyItem(equalTo(5))); } }