@Test public void getRandomInstance_should_default_to_normal_random_if_desired_algorithm_is_not_available() { Random randomGenerator = TraceAndSpanIdGenerator.getRandomInstance("QuantumDoohickey"); assertThat(randomGenerator).isNotNull(); assertThat(randomGenerator).isNotInstanceOf(SecureRandom.class); }
@Test public void getRandomInstance_should_return_requested_instance_if_available() { // given: all available SecureRandom algorithm providers Provider[] availableProviders = Security.getProviders(); assertThat(availableProviders).isNotNull(); assertThat(availableProviders.length).isGreaterThanOrEqualTo(1); // Ignore some algorithms because they fail on OSX if you're not an admin. // We don't care that *all* algorithms are available at all times on all platforms, just that the code does what it's supposed to do. List<String> excludedAlgorithms = Collections.singletonList("NativePRNGNonBlocking"); Set<String> availableSecureRandomAlgorithms = new HashSet<>(); for (Provider provider : availableProviders) { Set<Provider.Service> services = provider.getServices(); for (Provider.Service service : services) { String type = service.getType(); if ("SecureRandom".equals(type) && !excludedAlgorithms.contains(service.getAlgorithm())) availableSecureRandomAlgorithms.add(service.getAlgorithm()); } } assertThat(availableSecureRandomAlgorithms).isNotEmpty(); for (String algorithm : availableSecureRandomAlgorithms) { // when: we ask getRandomInstance for the algorithm Random randomGenerator = TraceAndSpanIdGenerator.getRandomInstance(algorithm); // then: we get back a valid SecureRandom that uses the requested algorithm assertThat(randomGenerator).isNotNull(); assertThat(randomGenerator).isInstanceOf(SecureRandom.class); //noinspection ConstantConditions assertThat(((SecureRandom)randomGenerator).getAlgorithm()).isEqualTo(algorithm); } }