Refine search
/** * Verifies that runtime contains expected modules. * * @param runtime a Bootique runtime whose contents we are testing. * @param expectedModules a vararg array of expected module types. */ @SafeVarargs public static void testModulesLoaded(BQRuntime runtime, Class<? extends Module>... expectedModules) { final ModulesMetadata modulesMetadata = runtime.getInstance(ModulesMetadata.class); final List<String> actualModules = modulesMetadata .getModules() .stream() .map(ModuleMetadata::getName) .collect(toList()); final String[] expectedModuleNames = Stream.of(expectedModules) .map(Class::getSimpleName) .toArray(String[]::new); // Using class names for checking module existing - weak. assertThat(actualModules, hasItems(expectedModuleNames)); } }
public void testCanMatchItemWhenCollectionHoldsSuperclass() // Issue 24 { final Set<Number> s = new HashSet<Number>(); s.add(Integer.valueOf(2)); assertThat(s, new IsCollectionContaining<Number>(new IsEqual<Number>(Integer.valueOf(2)))); assertThat(s, IsCollectionContaining.hasItem(Integer.valueOf(2))); }
private void assertEverythingOnEventLoop() { assertThat(threads, hasSize(1)); assertThat(threads.stream().filter(name -> name.startsWith(CPU_LIGHT)).count(), equalTo(1l)); assertThat(threads, not(hasItem(startsWith(IO)))); assertThat(threads, not(hasItem(startsWith(CPU_INTENSIVE)))); assertThat(threads, not(hasItem(startsWith(CUSTOM)))); }
public static void testAllServicesAreAvailable() { Set<String> osgiAvailableClasses = stream(spliterator(OsgiServiceLoader.load(ServiceFactory.class).iterator(), Long.MAX_VALUE, 0), false) .map(f -> f.getClass().getName()) .collect(toSet()); Set<String> jdkAvailableClasses = of(EhcacheActivator.getCoreBundle().getBundles()) .map(b -> b.adapt(BundleWiring.class).getClassLoader()) .flatMap(cl -> stream(spliterator(ServiceLoader.load(ServiceFactory.class, cl).iterator(), Long.MAX_VALUE, 0), false) .map(f -> f.getClass().getName())) .collect(toSet()); assertThat(osgiAvailableClasses, hasItems(jdkAvailableClasses.toArray(new String[0]))); }
/** * Ensures the {@link ClusteringCacheManagerServiceConfigurationParser} is locatable as a * {@link CacheManagerServiceConfigurationParser} instance. */ @Test public void testServiceLocator() throws Exception { assertThat(stream(spliterator(ClassLoading.servicesOfType(CacheManagerServiceConfigurationParser.class).iterator(), Long.MAX_VALUE, 0), false).map(Object::getClass).collect(Collectors.toList()), hasItem(ClusteringCacheManagerServiceConfigurationParser.class)); }
@Test public void testNonClustered() throws Exception { /* * Ensure the cluster provider classes are loadable through the ServiceLoader mechanism. */ assertThat(stream(spliterator(ClassLoading.servicesOfType(ServiceFactory.class).iterator(), Long.MAX_VALUE, 0), false).map(f -> f.getServiceType()).collect(Collectors.toList()), hasItems(ClusteredStore.Provider.class, ClusteringService.class)); CacheConfiguration<String, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder( String.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .offheap(1, MemoryUnit.MB) .build()) .build(); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true); cacheManager.createCache("cache-1", cacheConfiguration); cacheManager.createCache("cache-2", cacheConfiguration); cacheManager.close(); } }
@Test public void testSimpleSamlLoginWithAddShadowUserOnLoginFalse() throws Exception { // Deleting marissa@test.org from simplesamlphp because previous SAML authentications automatically // create a UAA user with the email address as the username. deleteUser(SAML_ORIGIN, testAccounts.getEmail()); IdentityProvider provider = IntegrationTestUtils.createIdentityProvider(SAML_ORIGIN, false, baseUrl, serverRunning); String clientId = "app-addnew-false"+ new RandomValueStringGenerator().generate(); String redirectUri = "http://nosuchhostname:0/nosuchendpoint"; BaseClientDetails client = createClientAndSpecifyProvider(clientId, provider, redirectUri); String firstUrl = "/oauth/authorize?" + "client_id=" + clientId + "&response_type=code" + "&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8"); webDriver.get(baseUrl + firstUrl); webDriver.findElement(By.xpath("//h2[contains(text(), 'Enter your username and password')]")); webDriver.findElement(By.name("username")).clear(); webDriver.findElement(By.name("username")).sendKeys(testAccounts.getUserName()); webDriver.findElement(By.name("password")).sendKeys(testAccounts.getPassword()); webDriver.findElement(By.xpath("//input[@value='Login']")).click(); // We need to verify the last request URL through the performance log because the redirect // URI does not exist. When the webDriver follows the non-existent redirect URI it receives a // connection refused error so webDriver.getCurrentURL() will remain as the SAML IdP URL. List<LogEntry> logEntries = webDriver.manage().logs().get(LogType.PERFORMANCE).getAll(); List<String> logMessages = logEntries.stream().map(logEntry -> logEntry.getMessage()).collect(Collectors.toList()); assertThat(logMessages, hasItem(containsString(redirectUri + "?error=access_denied&error_description=SAML+user+does+not+exist.+You+can+correct+this+by+creating+a+shadow+user+for+the+SAML+user."))); }
@Test public void testFilterAddedFromSourceInApply() { // GIVEN diffSets.add( 42L ); diffSets.add( 44L ); // WHEN Iterator<Long> result = diffSets.apply( asList( 42L, 43L ).iterator() ); // THEN Collection<Long> collectedResult = asCollection( result ); assertEquals( 3, collectedResult.size() ); assertThat( collectedResult, hasItems( 43L, 42L, 44L ) ); } }
@Test public void shouldGetAudience() throws Exception { assertThat(payload, is(notNullValue())); assertThat(payload.getAudience(), is(IsCollectionWithSize.hasSize(1))); assertThat(payload.getAudience(), is(IsCollectionContaining.hasItems("audience"))); }
@Test public void testSerializingIdToken() { String idTokenJsonString = JsonUtils.writeValueAsString(idToken); assertThat(idTokenJsonString, hasJsonPath("acr.values", hasItems("acr1", "acr2"))); assertThat(idTokenJsonString, hasJsonPath("amr", hasItems("amr1", "amr2"))); assertThat(idTokenJsonString, hasJsonPath("sub")); assertThat(idTokenJsonString, hasJsonPath("given_name")); assertThat(idTokenJsonString, hasJsonPath("family_name")); assertThat(idTokenJsonString, hasJsonPath("phone_number")); assertThat(idTokenJsonString, hasJsonPath("user_attributes")); assertThat(idTokenJsonString, hasJsonPath("previous_logon_time", is(1123))); assertThat(idTokenJsonString, hasJsonPath("iat", is(1))); assertThat(idTokenJsonString, hasJsonPath("exp", is(1))); assertThat(idTokenJsonString, hasJsonPath("auth_time", is(1))); assertThat(idTokenJsonString, hasNoJsonPath("authTime")); assertThat(idTokenJsonString, hasJsonPath("scope", hasItem("openid"))); assertThat(idTokenJsonString, hasJsonPath("email_verified", is(true))); assertThat(idTokenJsonString, hasJsonPath("nonce", is("nonce"))); assertThat(idTokenJsonString, hasJsonPath("email", is("email"))); assertThat(idTokenJsonString, hasJsonPath("cid", is("client_id"))); assertThat(idTokenJsonString, hasJsonPath("client_id", is("client_id"))); assertThat(idTokenJsonString, hasJsonPath("user_id", is("sub"))); assertThat(idTokenJsonString, hasJsonPath("grant_type", is("grant_type"))); assertThat(idTokenJsonString, hasJsonPath("user_name", is("username"))); assertThat(idTokenJsonString, hasJsonPath("zid", is("myzid"))); assertThat(idTokenJsonString, hasJsonPath("origin", is("origin"))); assertThat(idTokenJsonString, hasJsonPath("jti", is("some-uuid"))); assertThat(idTokenJsonString, hasJsonPath("rev_sig", is("revSig"))); }
@Test public void shouldGetStringArrayWhenParsingTextNode() throws Exception { Map<String, JsonNode> tree = new HashMap<>(); TextNode textNode = new TextNode("something"); tree.put("key", textNode); List<String> values = deserializer.getStringOrArray(tree, "key"); assertThat(values, is(notNullValue())); assertThat(values, is(IsCollectionWithSize.hasSize(1))); assertThat(values, is(IsCollectionContaining.hasItems("something"))); }
@Test public void create_includesStandardClaims() throws IdTokenCreationException { IdToken idToken = tokenCreator.create(clientId, userId, userAuthenticationData); assertThat(idToken, is(notNullValue())); assertThat(idToken.sub, is(userId)); assertThat(idToken.aud, hasItem(clientId)); assertThat(idToken.iss, is(issuerUrl)); assertThat(idToken.exp, is(expDate)); assertThat(idToken.iat, is(iatDate)); assertThat(idToken.authTime, is(authTime)); assertThat(idToken.amr, hasItems(is("mfa"), is("ext"))); assertThat(idToken.acr, hasItems(is("urn:oasis:names:tc:SAML:2.0:ac:classes:Password"))); assertThat(idToken.azp, is(clientId)); }
assertThat(payload, is(notNullValue())); assertThat(payload.getIssuer(), is("auth0")); assertThat(payload.getSubject(), is("emails")); assertThat(payload.getAudience(), is(IsCollectionContaining.hasItem("users"))); assertThat(payload.getIssuedAt().getTime(), is(10101010L * 1000)); assertThat(payload.getExpiresAt().getTime(), is(11111111L * 1000));
@Test public void testOneCacheConfigWithTemplate() throws Exception { final URL resource = XmlConfigurationTest.class.getResource("/configs/template-cache.xml"); XmlConfiguration xmlConfig = new XmlConfiguration(resource); assertThat(xmlConfig.getServiceCreationConfigurations(), hasSize(0)); assertThat(xmlConfig.getCacheConfigurations().keySet(), hasItem("bar")); assertThat(xmlConfig.getCacheConfigurations().get("bar").getServiceConfigurations(), IsCollectionContaining.hasItem(instanceOf(FooConfiguration.class))); assertThat(xmlConfig.getCacheConfigurations().get("bar").getKeyType(), sameInstance((Class) Number.class)); assertThat(xmlConfig.getCacheConfigurations().get("bar").getValueType(), sameInstance((Class)String.class)); final CacheConfigurationBuilder<String, String> example = xmlConfig.newCacheConfigurationBuilderFromTemplate("example", String.class, String.class, newResourcePoolsBuilder().heap(5, EntryUnit.ENTRIES)); assertThat(example.build().getExpiryPolicy(), equalTo((ExpiryPolicy) ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(30)))); try { xmlConfig.newCacheConfigurationBuilderFromTemplate("example", String.class, Number.class); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("CacheTemplate 'example' declares value type of java.lang.String. Provided: class java.lang.Number")); } try { xmlConfig.newCacheConfigurationBuilderFromTemplate("example", Number.class, String.class); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("CacheTemplate 'example' declares key type of java.lang.String. Provided: class java.lang.Number")); } assertThat(xmlConfig.newCacheConfigurationBuilderFromTemplate("bar", Object.class, Object.class), nullValue()); }
@Test public void testDefaultTypesConfig() throws Exception { URL resource = XmlConfigurationTest.class.getResource("/configs/defaultTypes-cache.xml"); XmlConfiguration xmlConfig = new XmlConfiguration(resource); assertThat(xmlConfig.getCacheConfigurations().keySet(), hasItem("foo")); assertThat(xmlConfig.getCacheConfigurations().get("foo").getKeyType(), sameInstance((Class)Object.class)); assertThat(xmlConfig.getCacheConfigurations().get("foo").getValueType(), sameInstance((Class)Object.class)); assertThat(xmlConfig.getCacheConfigurations().keySet(), hasItem("bar")); assertThat(xmlConfig.getCacheConfigurations().get("bar").getKeyType(), sameInstance((Class)Number.class)); assertThat(xmlConfig.getCacheConfigurations().get("bar").getValueType(), sameInstance((Class)Object.class)); assertThat(xmlConfig.newCacheConfigurationBuilderFromTemplate("example", Object.class, Object.class, heap(10)), notNullValue()); //Allow the key/value to be assignable for xml configuration in case of type definition in template class assertThat(xmlConfig.newCacheConfigurationBuilderFromTemplate("example", Number.class, Object.class, heap(10)), notNullValue()); }
/** * Creates a matcher for {@link Iterable}s that matches when consecutive passes over the * examined {@link Iterable} yield at least one item that is equal to the corresponding * item from the specified <code>items</code>. Whilst matching, each traversal of the * examined {@link Iterable} will stop as soon as a matching item is found. * <p/> * For example: * <pre>assertThat(Arrays.asList("foo", "bar", "baz"), hasItems("baz", "foo"))</pre> * * @param items * the items to compare against the items provided by the examined {@link Iterable} */ public static <T> org.hamcrest.Matcher<java.lang.Iterable<T>> hasItems(T... items) { return org.hamcrest.core.IsCollectionContaining.<T>hasItems(items); }
/** * Creates a matcher for {@link Iterable}s that only matches when a single pass over the * examined {@link Iterable} yields at least one item that is matched by the specified * <code>itemMatcher</code>. Whilst matching, the traversal of the examined {@link Iterable} * will stop as soon as a matching item is found. * <p/> * For example: * <pre>assertThat(Arrays.asList("foo", "bar"), hasItem(startsWith("ba")))</pre> * * @param itemMatcher * the matcher to apply to items provided by the examined {@link Iterable} */ public static <T> org.hamcrest.Matcher<java.lang.Iterable<? super T>> hasItem(org.hamcrest.Matcher<? super T> itemMatcher) { return org.hamcrest.core.IsCollectionContaining.<T>hasItem(itemMatcher); }
@Test public void testGetAll() throws Exception { Store<Number, CharSequence> store = mock(Store.class); when(store.bulkComputeIfAbsent((Set<? extends Number>)argThat(hasItems(1, 2, 3)), any(Function.class))).thenAnswer(invocation -> { Function<Iterable<? extends Number>, Iterable<? extends Map.Entry<? extends Number, ? extends CharSequence>>> function = (Function<Iterable<? extends Number>, Iterable<? extends Map.Entry<? extends Number, ? extends CharSequence>>>) invocation.getArguments()[1]; Set<? extends Number> keys = (Set<? extends Number>) invocation.getArguments()[0]; function.apply(keys); Map<Number, ValueHolder<String>> map = new HashMap<>(); map.put(1, null); map.put(2, null); map.put(3, valueHolder("three")); return map; }); InternalCache<Number, CharSequence> ehcache = getCache(store); ehcache.init(); Map<Number, CharSequence> result = ehcache.getAll(new HashSet<Number>(Arrays.asList(1, 2, 3))); assertThat(result, hasEntry(1, null)); assertThat(result, hasEntry(2, null)); assertThat(result, hasEntry(3, "three")); verify(store).bulkComputeIfAbsent((Set<? extends Number>)argThat(hasItems(1, 2, 3)), any(Function.class)); }