org.springframework.mock.env.MockEnvironment

Here are the examples of the java api org.springframework.mock.env.MockEnvironment taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

165 Examples 7

19 View Source File : ReactiveMongoClientFactoryTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link ReactiveMongoClientFactory}.
 *
 * @author Mark Paluch
 * @author Stephane Nicoll
 */
public clreplaced ReactiveMongoClientFactoryTests {

    private MockEnvironment environment = new MockEnvironment();

    @Test
    public void portCanBeCustomized() {
        MongoProperties properties = new MongoProperties();
        properties.setPort(12345);
        MongoClient client = createMongoClient(properties);
        List<ServerAddress> allAddresses = extractServerAddresses(client);
        replacedertThat(allAddresses).hreplacedize(1);
        replacedertServerAddress(allAddresses.get(0), "localhost", 12345);
    }

    @Test
    public void hostCanBeCustomized() {
        MongoProperties properties = new MongoProperties();
        properties.setHost("mongo.example.com");
        MongoClient client = createMongoClient(properties);
        List<ServerAddress> allAddresses = extractServerAddresses(client);
        replacedertThat(allAddresses).hreplacedize(1);
        replacedertServerAddress(allAddresses.get(0), "mongo.example.com", 27017);
    }

    @Test
    public void credentialsCanBeCustomized() {
        MongoProperties properties = new MongoProperties();
        properties.setUsername("user");
        properties.setPreplacedword("secret".toCharArray());
        MongoClient client = createMongoClient(properties);
        replacedertMongoCredential(extractMongoCredentials(client), "user", "secret", "test");
    }

    @Test
    public void databaseCanBeCustomized() {
        MongoProperties properties = new MongoProperties();
        properties.setDatabase("foo");
        properties.setUsername("user");
        properties.setPreplacedword("secret".toCharArray());
        MongoClient client = createMongoClient(properties);
        replacedertMongoCredential(extractMongoCredentials(client), "user", "secret", "foo");
    }

    @Test
    public void authenticationDatabaseCanBeCustomized() {
        MongoProperties properties = new MongoProperties();
        properties.setAuthenticationDatabase("foo");
        properties.setUsername("user");
        properties.setPreplacedword("secret".toCharArray());
        MongoClient client = createMongoClient(properties);
        replacedertMongoCredential(extractMongoCredentials(client), "user", "secret", "foo");
    }

    @Test
    public void uriCanBeCustomized() {
        MongoProperties properties = new MongoProperties();
        properties.setUri("mongodb://user:[email protected]:12345," + "mongo2.example.com:23456/test");
        MongoClient client = createMongoClient(properties);
        List<ServerAddress> allAddresses = extractServerAddresses(client);
        replacedertThat(allAddresses).hreplacedize(2);
        replacedertServerAddress(allAddresses.get(0), "mongo1.example.com", 12345);
        replacedertServerAddress(allAddresses.get(1), "mongo2.example.com", 23456);
        MongoCredential credential = extractMongoCredentials(client);
        replacedertMongoCredential(credential, "user", "secret", "test");
    }

    @Test
    public void retryWritesIsPropagatedFromUri() {
        MongoProperties properties = new MongoProperties();
        properties.setUri("mongodb://localhost/test?retryWrites=true");
        MongoClient client = createMongoClient(properties);
        replacedertThat(getSettings(client).getRetryWrites()).isTrue();
    }

    @Test
    public void uriCannotBeSetWithCredentials() {
        MongoProperties properties = new MongoProperties();
        properties.setUri("mongodb://127.0.0.1:1234/mydb");
        properties.setUsername("user");
        properties.setPreplacedword("secret".toCharArray());
        replacedertThatIllegalStateException().isThrownBy(() -> createMongoClient(properties)).withMessageContaining("Invalid mongo configuration, " + "either uri or host/port/credentials must be specified");
    }

    @Test
    public void uriCannotBeSetWithHostPort() {
        MongoProperties properties = new MongoProperties();
        properties.setUri("mongodb://127.0.0.1:1234/mydb");
        properties.setHost("localhost");
        properties.setPort(4567);
        replacedertThatIllegalStateException().isThrownBy(() -> createMongoClient(properties)).withMessageContaining("Invalid mongo configuration, " + "either uri or host/port/credentials must be specified");
    }

    @Test
    public void uriIsIgnoredInEmbeddedMode() {
        MongoProperties properties = new MongoProperties();
        properties.setUri("mongodb://mongo.example.com:1234/mydb");
        this.environment.setProperty("local.mongo.port", "4000");
        MongoClient client = createMongoClient(properties, this.environment);
        List<ServerAddress> allAddresses = extractServerAddresses(client);
        replacedertThat(allAddresses).hreplacedize(1);
        replacedertServerAddress(allAddresses.get(0), "localhost", 4000);
    }

    @Test
    public void customizerIsInvoked() {
        MongoProperties properties = new MongoProperties();
        MongoClientSettingsBuilderCustomizer customizer = mock(MongoClientSettingsBuilderCustomizer.clreplaced);
        createMongoClient(properties, this.environment, customizer);
        verify(customizer).customize(any(MongoClientSettings.Builder.clreplaced));
    }

    @Test
    public void customizerIsInvokedWhenHostIsSet() {
        MongoProperties properties = new MongoProperties();
        properties.setHost("localhost");
        MongoClientSettingsBuilderCustomizer customizer = mock(MongoClientSettingsBuilderCustomizer.clreplaced);
        createMongoClient(properties, this.environment, customizer);
        verify(customizer).customize(any(MongoClientSettings.Builder.clreplaced));
    }

    @Test
    public void customizerIsInvokedForEmbeddedMongo() {
        MongoProperties properties = new MongoProperties();
        this.environment.setProperty("local.mongo.port", "27017");
        MongoClientSettingsBuilderCustomizer customizer = mock(MongoClientSettingsBuilderCustomizer.clreplaced);
        createMongoClient(properties, this.environment, customizer);
        verify(customizer).customize(any(MongoClientSettings.Builder.clreplaced));
    }

    private MongoClient createMongoClient(MongoProperties properties) {
        return createMongoClient(properties, this.environment);
    }

    private MongoClient createMongoClient(MongoProperties properties, Environment environment, MongoClientSettingsBuilderCustomizer... customizers) {
        return new ReactiveMongoClientFactory(properties, environment, Arrays.asList(customizers)).createMongoClient(null);
    }

    private List<ServerAddress> extractServerAddresses(MongoClient client) {
        MongoClientSettings settings = getSettings(client);
        ClusterSettings clusterSettings = settings.getClusterSettings();
        return clusterSettings.getHosts();
    }

    private MongoCredential extractMongoCredentials(MongoClient client) {
        return getSettings(client).getCredential();
    }

    @SuppressWarnings("deprecation")
    private MongoClientSettings getSettings(MongoClient client) {
        return (MongoClientSettings) ReflectionTestUtils.getField(client.getSettings(), "wrapped");
    }

    private void replacedertServerAddress(ServerAddress serverAddress, String expectedHost, int expectedPort) {
        replacedertThat(serverAddress.getHost()).isEqualTo(expectedHost);
        replacedertThat(serverAddress.getPort()).isEqualTo(expectedPort);
    }

    private void replacedertMongoCredential(MongoCredential credentials, String expectedUsername, String expectedPreplacedword, String expectedSource) {
        replacedertThat(credentials.getUserName()).isEqualTo(expectedUsername);
        replacedertThat(credentials.getPreplacedword()).isEqualTo(expectedPreplacedword.toCharArray());
        replacedertThat(credentials.getSource()).isEqualTo(expectedSource);
    }
}

19 View Source File : MongoClientFactoryTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link MongoClientFactory}.
 *
 * @author Phillip Webb
 * @author Andy Wilkinson
 * @author Stephane Nicoll
 * @author Mark Paluch
 */
public clreplaced MongoClientFactoryTests {

    private MockEnvironment environment = new MockEnvironment();

    @Test
    public void portCanBeCustomized() {
        MongoProperties properties = new MongoProperties();
        properties.setPort(12345);
        MongoClient client = createMongoClient(properties);
        List<ServerAddress> allAddresses = extractServerAddresses(client);
        replacedertThat(allAddresses).hreplacedize(1);
        replacedertServerAddress(allAddresses.get(0), "localhost", 12345);
    }

    @Test
    public void hostCanBeCustomized() {
        MongoProperties properties = new MongoProperties();
        properties.setHost("mongo.example.com");
        MongoClient client = createMongoClient(properties);
        List<ServerAddress> allAddresses = extractServerAddresses(client);
        replacedertThat(allAddresses).hreplacedize(1);
        replacedertServerAddress(allAddresses.get(0), "mongo.example.com", 27017);
    }

    @Test
    public void credentialsCanBeCustomized() {
        MongoProperties properties = new MongoProperties();
        properties.setUsername("user");
        properties.setPreplacedword("secret".toCharArray());
        MongoClient client = createMongoClient(properties);
        replacedertMongoCredential(client.getCredentialsList().get(0), "user", "secret", "test");
    }

    @Test
    public void databaseCanBeCustomized() {
        MongoProperties properties = new MongoProperties();
        properties.setDatabase("foo");
        properties.setUsername("user");
        properties.setPreplacedword("secret".toCharArray());
        MongoClient client = createMongoClient(properties);
        replacedertMongoCredential(client.getCredentialsList().get(0), "user", "secret", "foo");
    }

    @Test
    public void authenticationDatabaseCanBeCustomized() {
        MongoProperties properties = new MongoProperties();
        properties.setAuthenticationDatabase("foo");
        properties.setUsername("user");
        properties.setPreplacedword("secret".toCharArray());
        MongoClient client = createMongoClient(properties);
        replacedertMongoCredential(client.getCredentialsList().get(0), "user", "secret", "foo");
    }

    @Test
    public void uriCanBeCustomized() {
        MongoProperties properties = new MongoProperties();
        properties.setUri("mongodb://user:[email protected]:12345," + "mongo2.example.com:23456/test");
        MongoClient client = createMongoClient(properties);
        List<ServerAddress> allAddresses = extractServerAddresses(client);
        replacedertThat(allAddresses).hreplacedize(2);
        replacedertServerAddress(allAddresses.get(0), "mongo1.example.com", 12345);
        replacedertServerAddress(allAddresses.get(1), "mongo2.example.com", 23456);
        List<MongoCredential> credentialsList = client.getCredentialsList();
        replacedertThat(credentialsList).hreplacedize(1);
        replacedertMongoCredential(credentialsList.get(0), "user", "secret", "test");
    }

    @Test
    public void uriIsIgnoredInEmbeddedMode() {
        MongoProperties properties = new MongoProperties();
        properties.setUri("mongodb://mongo.example.com:1234/mydb");
        this.environment.setProperty("local.mongo.port", "4000");
        MongoClient client = createMongoClient(properties, this.environment);
        List<ServerAddress> allAddresses = extractServerAddresses(client);
        replacedertThat(allAddresses).hreplacedize(1);
        replacedertServerAddress(allAddresses.get(0), "localhost", 4000);
    }

    private MongoClient createMongoClient(MongoProperties properties) {
        return createMongoClient(properties, null);
    }

    private MongoClient createMongoClient(MongoProperties properties, Environment environment) {
        return new MongoClientFactory(properties, environment).createMongoClient(null);
    }

    private List<ServerAddress> extractServerAddresses(MongoClient client) {
        Cluster cluster = (Cluster) ReflectionTestUtils.getField(ReflectionTestUtils.getField(client, "delegate"), "cluster");
        ClusterSettings clusterSettings = (ClusterSettings) ReflectionTestUtils.getField(cluster, "settings");
        return clusterSettings.getHosts();
    }

    private void replacedertServerAddress(ServerAddress serverAddress, String expectedHost, int expectedPort) {
        replacedertThat(serverAddress.getHost()).isEqualTo(expectedHost);
        replacedertThat(serverAddress.getPort()).isEqualTo(expectedPort);
    }

    private void replacedertMongoCredential(MongoCredential credentials, String expectedUsername, String expectedPreplacedword, String expectedSource) {
        replacedertThat(credentials.getUserName()).isEqualTo(expectedUsername);
        replacedertThat(credentials.getPreplacedword()).isEqualTo(expectedPreplacedword.toCharArray());
        replacedertThat(credentials.getSource()).isEqualTo(expectedSource);
    }

    @Configuration
    @EnableConfigurationProperties(MongoProperties.clreplaced)
    static clreplaced Config {
    }
}

/**
 * Tests for {@link InvalidConfigurationPropertyValueFailurereplacedyzer}.
 *
 * @author Stephane Nicoll
 */
public clreplaced InvalidConfigurationPropertyValueFailurereplacedyzerTests {

    private final MockEnvironment environment = new MockEnvironment();

    @Test
    public void replacedysisWithNullEnvironment() {
        InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException("test.property", "invalid", "This is not valid.");
        Failurereplacedysis replacedysis = new InvalidConfigurationPropertyValueFailurereplacedyzer().replacedyze(failure);
        replacedertThat(replacedysis).isNull();
    }

    @Test
    public void replacedysisWithKnownProperty() {
        MapPropertySource source = new MapPropertySource("test", Collections.singletonMap("test.property", "invalid"));
        this.environment.getPropertySources().addFirst(OriginCapablePropertySource.get(source));
        InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException("test.property", "invalid", "This is not valid.");
        Failurereplacedysis replacedysis = performreplacedysis(failure);
        replacedertCommonParts(failure, replacedysis);
        replacedertThat(replacedysis.getAction()).contains("Review the value of the property with the provided reason.");
        replacedertThat(replacedysis.getDescription()).contains("Validation failed for the following reason").contains("This is not valid.").doesNotContain("Additionally, this property is also set");
    }

    @Test
    public void replacedysisWithKnownPropertyAndNoReason() {
        MapPropertySource source = new MapPropertySource("test", Collections.singletonMap("test.property", "invalid"));
        this.environment.getPropertySources().addFirst(OriginCapablePropertySource.get(source));
        InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException("test.property", "invalid", null);
        Failurereplacedysis replacedysis = performreplacedysis(failure);
        replacedertThat(replacedysis.getAction()).contains("Review the value of the property.");
        replacedertThat(replacedysis.getDescription()).contains("No reason was provided.").doesNotContain("Additionally, this property is also set");
    }

    @Test
    public void replacedysisWithKnownPropertyAndOtherCandidates() {
        MapPropertySource source = new MapPropertySource("test", Collections.singletonMap("test.property", "invalid"));
        MapPropertySource additional = new MapPropertySource("additional", Collections.singletonMap("test.property", "valid"));
        MapPropertySource another = new MapPropertySource("another", Collections.singletonMap("test.property", "test"));
        this.environment.getPropertySources().addFirst(OriginCapablePropertySource.get(source));
        this.environment.getPropertySources().addLast(additional);
        this.environment.getPropertySources().addLast(OriginCapablePropertySource.get(another));
        InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException("test.property", "invalid", "This is not valid.");
        Failurereplacedysis replacedysis = performreplacedysis(failure);
        replacedertCommonParts(failure, replacedysis);
        replacedertThat(replacedysis.getAction()).contains("Review the value of the property with the provided reason.");
        replacedertThat(replacedysis.getDescription()).contains("Additionally, this property is also set in the following " + "property sources:").contains("In 'additional' with the value 'valid'").contains("In 'another' with the value 'test' (originating from 'TestOrigin test.property')");
    }

    @Test
    public void replacedysisWithUnknownKey() {
        InvalidConfigurationPropertyValueException failure = new InvalidConfigurationPropertyValueException("test.key.not.defined", "invalid", "This is not valid.");
        replacedertThat(performreplacedysis(failure)).isNull();
    }

    private void replacedertCommonParts(InvalidConfigurationPropertyValueException failure, Failurereplacedysis replacedysis) {
        replacedertThat(replacedysis.getDescription()).contains("test.property").contains("invalid").contains("TestOrigin test.property");
        replacedertThat(replacedysis.getCause()).isSameAs(failure);
    }

    private Failurereplacedysis performreplacedysis(InvalidConfigurationPropertyValueException failure) {
        InvalidConfigurationPropertyValueFailurereplacedyzer replacedyzer = new InvalidConfigurationPropertyValueFailurereplacedyzer();
        replacedyzer.setEnvironment(this.environment);
        return replacedyzer.replacedyze(failure);
    }

    static clreplaced OriginCapablePropertySource<T> extends EnumerablePropertySource<T> implements OriginLookup<String> {

        private final EnumerablePropertySource<T> propertySource;

        OriginCapablePropertySource(EnumerablePropertySource<T> propertySource) {
            super(propertySource.getName(), propertySource.getSource());
            this.propertySource = propertySource;
        }

        @Override
        public Object getProperty(String name) {
            return this.propertySource.getProperty(name);
        }

        @Override
        public String[] getPropertyNames() {
            return this.propertySource.getPropertyNames();
        }

        @Override
        public Origin getOrigin(String name) {
            return new Origin() {

                @Override
                public String toString() {
                    return "TestOrigin " + name;
                }
            };
        }

        static <T> OriginCapablePropertySource<T> get(EnumerablePropertySource<T> propertySource) {
            return new OriginCapablePropertySource<>(propertySource);
        }
    }
}

19 View Source File : SystemInputTests.java
License : Apache License 2.0
Project Creator : spring-io

/**
 * Tests for {@link SystemInput}.
 *
 * @author Phillip Webb
 * @author Madhura Bhave
 */
clreplaced SystemInputTests {

    private MockEnvironment environment;

    @BeforeEach
    void setUp() {
        this.environment = new MockEnvironment();
    }

    @Test
    void readWhenNoDataTimesout() {
        SystemInput input = new SystemInput(this.environment, new MockSystemStreams(""), new ObjectMapper(), 10);
        replacedertThatIllegalStateException().isThrownBy(() -> input.read(String[].clreplaced)).withMessage("Timeout waiting for input");
    }

    @Test
    void readDeserializesJson() throws Exception {
        SystemInput input = new SystemInput(this.environment, new MockSystemStreams("[\"foo\",\"bar\"]"), new ObjectMapper());
        String[] result = input.read(String[].clreplaced);
        replacedertThat(result).containsExactly("foo", "bar");
    }

    @Test
    void readResolvesPlaceholders() throws Exception {
        this.environment.setProperty("bar", "hello-world");
        SystemInput input = new SystemInput(this.environment, new MockSystemStreams("[\"foo\",\"${bar}\"]"), new ObjectMapper());
        String[] result = input.read(String[].clreplaced);
        replacedertThat(result).containsExactly("foo", "hello-world");
    }
}

19 View Source File : LiveBeansViewTests.java
License : Apache License 2.0
Project Creator : SourceHot

/**
 * Tests for {@link LiveBeansView}
 *
 * @author Stephane Nicoll
 * @author Sam Brannen
 */
clreplaced LiveBeansViewTests {

    private final MockEnvironment environment = new MockEnvironment();

    @Test
    void registerIgnoredIfPropertyIsNotSet(TestInfo testInfo) throws MalformedObjectNameException {
        ConfigurableApplicationContext context = createApplicationContext("app");
        replacedertThat(searchLiveBeansViewMeans(testInfo).size()).isEqualTo(0);
        LiveBeansView.registerApplicationContext(context);
        replacedertThat(searchLiveBeansViewMeans(testInfo).size()).isEqualTo(0);
        LiveBeansView.unregisterApplicationContext(context);
    }

    @Test
    void registerUnregisterSingleContext(TestInfo testInfo) throws MalformedObjectNameException {
        this.environment.setProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME, testInfo.getTestMethod().get().getName());
        ConfigurableApplicationContext context = createApplicationContext("app");
        replacedertThat(searchLiveBeansViewMeans(testInfo).size()).isEqualTo(0);
        LiveBeansView.registerApplicationContext(context);
        replacedertSingleLiveBeansViewMbean(testInfo, "app");
        LiveBeansView.unregisterApplicationContext(context);
        replacedertThat(searchLiveBeansViewMeans(testInfo).size()).isEqualTo(0);
    }

    @Test
    void registerUnregisterSeveralContexts(TestInfo testInfo) throws MalformedObjectNameException {
        this.environment.setProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME, testInfo.getTestMethod().get().getName());
        ConfigurableApplicationContext context = createApplicationContext("app");
        ConfigurableApplicationContext childContext = createApplicationContext("child");
        replacedertThat(searchLiveBeansViewMeans(testInfo).size()).isEqualTo(0);
        LiveBeansView.registerApplicationContext(context);
        replacedertSingleLiveBeansViewMbean(testInfo, "app");
        LiveBeansView.registerApplicationContext(childContext);
        // Only one MBean
        replacedertThat(searchLiveBeansViewMeans(testInfo).size()).isEqualTo(1);
        LiveBeansView.unregisterApplicationContext(childContext);
        // Root context removes it
        replacedertSingleLiveBeansViewMbean(testInfo, "app");
        LiveBeansView.unregisterApplicationContext(context);
        replacedertThat(searchLiveBeansViewMeans(testInfo).size()).isEqualTo(0);
    }

    @Test
    void registerUnregisterSeveralContextsDifferentOrder(TestInfo testInfo) throws MalformedObjectNameException {
        this.environment.setProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME, testInfo.getTestMethod().get().getName());
        ConfigurableApplicationContext context = createApplicationContext("app");
        ConfigurableApplicationContext childContext = createApplicationContext("child");
        replacedertThat(searchLiveBeansViewMeans(testInfo).size()).isEqualTo(0);
        LiveBeansView.registerApplicationContext(context);
        replacedertSingleLiveBeansViewMbean(testInfo, "app");
        LiveBeansView.registerApplicationContext(childContext);
        // Only one MBean
        replacedertSingleLiveBeansViewMbean(testInfo, "app");
        LiveBeansView.unregisterApplicationContext(context);
        LiveBeansView.unregisterApplicationContext(childContext);
        replacedertThat(searchLiveBeansViewMeans(testInfo).size()).isEqualTo(0);
    }

    private ConfigurableApplicationContext createApplicationContext(String applicationName) {
        ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.clreplaced);
        given(context.getEnvironment()).willReturn(this.environment);
        given(context.getApplicationName()).willReturn(applicationName);
        return context;
    }

    private void replacedertSingleLiveBeansViewMbean(TestInfo testInfo, String applicationName) throws MalformedObjectNameException {
        Set<ObjectName> objectNames = searchLiveBeansViewMeans(testInfo);
        replacedertThat(objectNames.size()).isEqualTo(1);
        replacedertThat(objectNames.iterator().next().getCanonicalName()).as("Wrong MBean name").isEqualTo(String.format("%s:application=%s", testInfo.getTestMethod().get().getName(), applicationName));
    }

    private Set<ObjectName> searchLiveBeansViewMeans(TestInfo testInfo) throws MalformedObjectNameException {
        String objectName = String.format("%s:*,%s=*", testInfo.getTestMethod().get().getName(), LiveBeansView.MBEAN_APPLICATION_KEY);
        return ManagementFactory.getPlatformMBeanServer().queryNames(new ObjectName(objectName), null);
    }
}

19 View Source File : SpringProxyInvocationHandlerTest.java
License : Apache License 2.0
Project Creator : Netflix

public clreplaced SpringProxyInvocationHandlerTest {

    private final MockEnvironment environment = new MockEnvironment();

    private SomeConfiguration configuration;

    @Before
    public void setUp() {
        environment.setProperty("annotationPrefix.intWithNoDefault", "11");
        this.configuration = Archaius2Ext.newConfiguration(SomeConfiguration.clreplaced, environment);
    }

    @Test
    public void testInt() {
        replacedertThat(configuration.getInt()).isEqualTo(1);
        environment.setProperty("annotationPrefix.int", "123");
        replacedertThat(configuration.getInt()).isEqualTo(123);
        replacedertThat(configuration.getIntWithNoDefault()).isEqualTo(11);
    }

    @Test
    public void testLong() {
        replacedertThat(configuration.getLong()).isEqualTo(2L);
        environment.setProperty("annotationPrefix.long", "123");
        replacedertThat(configuration.getLong()).isEqualTo(123);
    }

    @Test
    public void testDouble() {
        replacedertThat(configuration.getDouble()).isEqualTo(3.3D);
        environment.setProperty("annotationPrefix.double", "4.4");
        replacedertThat(configuration.getDouble()).isEqualTo(4.4);
    }

    @Test
    public void testFloat() {
        replacedertThat(configuration.getFloat()).isEqualTo(4.5F);
        environment.setProperty("annotationPrefix.float", "5.5");
        replacedertThat(configuration.getFloat()).isEqualTo(5.5F);
    }

    @Test
    public void testBoolean() {
        replacedertThat(configuration.getBoolean()).isTrue();
        environment.setProperty("annotationPrefix.boolean", "false");
        replacedertThat(configuration.getBoolean()).isFalse();
    }

    @Test
    public void testList() {
        replacedertThat(configuration.getList()).containsExactly("a", "b", "c");
        environment.setProperty("annotationPrefix.list", "A,B,C");
        replacedertThat(configuration.getList()).containsExactly("A", "B", "C");
    }

    @Test
    public void testEmptyList() {
        replacedertThat(configuration.getEmptyList()).isEmpty();
    }

    @Test
    public void testSet() {
        replacedertThat(configuration.getSet()).containsExactly("d", "e", "f");
        environment.setProperty("annotationPrefix.set", "D,E,F");
        replacedertThat(configuration.getSet()).containsExactly("D", "E", "F");
    }

    @Test
    public void testEmptySet() {
        replacedertThat(configuration.getEmptySet()).isEmpty();
    }

    @Test
    public void testNullValue() {
        replacedertThat(configuration.getInteger()).isNull();
        environment.setProperty("annotationPrefix.integer", "1");
        replacedertThat(configuration.getInteger()).isEqualTo(1);
    }

    @Test(expected = IllegalArgumentException.clreplaced)
    public void testCreateFailsOnPropertiesWithoutValue() {
        Archaius2Ext.newConfiguration(SomeConfiguration.clreplaced, new MockEnvironment());
    }

    @Test
    public void testCustomPrefix() {
        environment.setProperty("customPrefix.intWithNoDefault", "456");
        SomeConfiguration configuration = Archaius2Ext.newConfiguration(SomeConfiguration.clreplaced, "customPrefix", environment);
        replacedertThat(configuration.getIntWithNoDefault()).isEqualTo(456);
    }

    @Test
    public void testDefaultMethods() {
        replacedertThat(configuration.getNumber(false)).isEqualTo(1);
        replacedertThat(configuration.getNumber(true)).isEqualTo(2);
    }

    @Test
    public void testToString() {
        String[] expectedParts = { "float=4.5", "boolean=true", "double=3.3", "intWithNoDefault=11", "list=[a, b, c]", "set=[d, e, f]", "int=1", "long=2" };
        String actual = configuration.toString();
        for (String part : expectedParts) {
            replacedertThat(actual).contains(part);
        }
    }

    @Configuration(prefix = "annotationPrefix")
    private interface SomeConfiguration {

        @DefaultValue("1")
        int getInt();

        Integer getInteger();

        int getIntWithNoDefault();

        @DefaultValue("2")
        long getLong();

        @DefaultValue("3.3")
        double getDouble();

        @DefaultValue("4.5")
        double getFloat();

        @DefaultValue("true")
        boolean getBoolean();

        @DefaultValue("a,b,c")
        List<String> getList();

        List<String> getEmptyList();

        @DefaultValue("d,e,f")
        List<String> getSet();

        Set<String> getEmptySet();

        default long getNumber(boolean returnLong) {
            return returnLong ? getLong() : getInt();
        }
    }
}

19 View Source File : SpringConfigTest.java
License : Apache License 2.0
Project Creator : Netflix

public clreplaced SpringConfigTest {

    private final MockEnvironment environment = new MockEnvironment();

    @Test
    public void testGetProperty() {
        environment.setProperty("number", "123");
        SpringConfig config = new SpringConfig(null, environment);
        replacedertThat(config.getString("number")).isEqualTo("123");
        replacedertThat(config.getLong("number")).isEqualTo(123L);
    }

    @Test
    public void testPrefixedView() {
        environment.setProperty("myPrefix.number", "123");
        SpringConfig config = new SpringConfig("myPrefix", environment);
        replacedertThat(config.getString("number")).isEqualTo("123");
        replacedertThat(config.getLong("number")).isEqualTo(123L);
    }

    @Test
    public void testUpdates() {
        environment.setProperty("number", "123");
        SpringConfig config = new SpringConfig(null, environment);
        replacedertThat(config.getString("number")).isEqualTo("123");
        replacedertThat(config.getLong("number")).isEqualTo(123L);
        environment.setProperty("number", "456");
        replacedertThat(config.getString("number")).isEqualTo("456");
        replacedertThat(config.getLong("number")).isEqualTo(456L);
    }
}

19 View Source File : PrefetchingQueueListenerParserTest.java
License : MIT License
Project Creator : JaidenAshmore

clreplaced PrefetchingQueueListenerParserTest {

    MockEnvironment mockEnvironment;

    PrefetchingQueueListenerParser parser;

    @BeforeEach
    void setUp() {
        mockEnvironment = new MockEnvironment();
        parser = new PrefetchingQueueListenerParser(mockEnvironment);
    }

    @Test
    void minimalAnnotation() throws Exception {
        // arrange
        final PrefetchingQueueListener annotation = PrefetchingQueueListenerParserTest.clreplaced.getMethod("method").getAnnotation(PrefetchingQueueListener.clreplaced);
        // act
        final PrefetchingMessageListenerContainerProperties properties = parser.parse(annotation);
        // replacedert
        replacedertThat(properties.concurrencyLevel()).isEqualTo(5);
        replacedertThat(properties.desiredMinPrefetchedMessages()).isEqualTo(1);
        replacedertThat(properties.maxPrefetchedMessages()).isEqualTo(10);
        replacedertThat(properties.messageVisibilityTimeout()).isEqualTo(Duration.ofSeconds(30));
        replacedertThat(properties.processAnyExtraRetrievedMessagesOnShutdown()).isTrue();
        replacedertThat(properties.interruptThreadsProcessingMessagesOnShutdown()).isFalse();
    }

    @Test
    void primitiveValues() throws Exception {
        // arrange
        final PrefetchingQueueListener annotation = PrefetchingQueueListenerParserTest.clreplaced.getMethod("methodWithPrimitives").getAnnotation(PrefetchingQueueListener.clreplaced);
        // act
        final PrefetchingMessageListenerContainerProperties properties = parser.parse(annotation);
        // replacedert
        replacedertThat(properties.concurrencyLevel()).isEqualTo(7);
        replacedertThat(properties.desiredMinPrefetchedMessages()).isEqualTo(8);
        replacedertThat(properties.maxPrefetchedMessages()).isEqualTo(15);
        replacedertThat(properties.messageVisibilityTimeout()).isEqualTo(Duration.ofSeconds(16));
        replacedertThat(properties.processAnyExtraRetrievedMessagesOnShutdown()).isFalse();
        replacedertThat(properties.interruptThreadsProcessingMessagesOnShutdown()).isTrue();
    }

    @Test
    void stringFieldsWithRawValues() throws Exception {
        // arrange
        final PrefetchingQueueListener annotation = PrefetchingQueueListenerParserTest.clreplaced.getMethod("stringMethod").getAnnotation(PrefetchingQueueListener.clreplaced);
        // act
        final PrefetchingMessageListenerContainerProperties properties = parser.parse(annotation);
        // replacedert
        replacedertThat(properties.concurrencyLevel()).isEqualTo(10);
        replacedertThat(properties.desiredMinPrefetchedMessages()).isEqualTo(6);
        replacedertThat(properties.maxPrefetchedMessages()).isEqualTo(12);
        replacedertThat(properties.messageVisibilityTimeout()).isEqualTo(Duration.ofSeconds(15));
    }

    @Test
    void stringFieldsWithReplacements() throws Exception {
        // arrange
        mockEnvironment.withProperty("queue.concurrencyLevel", "2").withProperty("queue.desiredMinPrefetchedMessages", "3").withProperty("queue.maxPrefetchedMessages", "15").withProperty("queue.messageVisibilityInSeconds", "5");
        final PrefetchingQueueListener annotation = PrefetchingQueueListenerParserTest.clreplaced.getMethod("stringMethodWithReplacements").getAnnotation(PrefetchingQueueListener.clreplaced);
        // act
        final PrefetchingMessageListenerContainerProperties properties = parser.parse(annotation);
        // replacedert
        replacedertThat(properties.concurrencyLevel()).isEqualTo(2);
        replacedertThat(properties.desiredMinPrefetchedMessages()).isEqualTo(3);
        replacedertThat(properties.maxPrefetchedMessages()).isEqualTo(15);
        replacedertThat(properties.messageVisibilityTimeout()).isEqualTo(Duration.ofSeconds(5));
    }

    @PrefetchingQueueListener("queueName")
    public void method() {
    }

    @PrefetchingQueueListener(value = "queueName", concurrencyLevel = 7, desiredMinPrefetchedMessages = 8, maxPrefetchedMessages = 15, messageVisibilityTimeoutInSeconds = 16, interruptThreadsProcessingMessagesOnShutdown = true, processAnyExtraRetrievedMessagesOnShutdown = false)
    public void methodWithPrimitives() {
    }

    @PrefetchingQueueListener(value = "queueName", concurrencyLevelString = "10", desiredMinPrefetchedMessagesString = "6", maxPrefetchedMessagesString = "12", messageVisibilityTimeoutInSecondsString = "15")
    public void stringMethod() {
    }

    @PrefetchingQueueListener(value = "queueName", concurrencyLevelString = "${queue.concurrencyLevel}", desiredMinPrefetchedMessagesString = "${queue.desiredMinPrefetchedMessages}", maxPrefetchedMessagesString = "${queue.maxPrefetchedMessages}", messageVisibilityTimeoutInSecondsString = "${queue.messageVisibilityInSeconds}")
    public void stringMethodWithReplacements() {
    }
}

19 View Source File : FifoQueueListenerParserTest.java
License : MIT License
Project Creator : JaidenAshmore

clreplaced FifoQueueListenerParserTest {

    MockEnvironment mockEnvironment;

    FifoQueueListenerParser parser;

    @BeforeEach
    void setUp() {
        mockEnvironment = new MockEnvironment();
        parser = new FifoQueueListenerParser(mockEnvironment);
    }

    @Test
    void minimalAnnotation() throws Exception {
        // arrange
        final FifoQueueListener annotation = FifoQueueListenerParserTest.clreplaced.getMethod("method").getAnnotation(FifoQueueListener.clreplaced);
        // act
        final FifoMessageListenerContainerProperties properties = parser.parse(annotation);
        // replacedert
        replacedertThat(properties.concurrencyLevel()).isEqualTo(5);
        replacedertThat(properties.maximumMessagesInMessageGroup()).isEqualTo(2);
        replacedertThat(properties.maximumCachedMessageGroups()).isEqualTo(15);
        replacedertThat(properties.messageVisibilityTimeout()).isNull();
        replacedertThat(properties.tryAndProcessAnyExtraRetrievedMessagesOnShutdown()).isFalse();
        replacedertThat(properties.interruptThreadsProcessingMessagesOnShutdown()).isFalse();
    }

    @Test
    void primitiveValues() throws Exception {
        // arrange
        final FifoQueueListener annotation = FifoQueueListenerParserTest.clreplaced.getMethod("methodWithPrimitives").getAnnotation(FifoQueueListener.clreplaced);
        // act
        final FifoMessageListenerContainerProperties properties = parser.parse(annotation);
        // replacedert
        replacedertThat(properties.concurrencyLevel()).isEqualTo(7);
        replacedertThat(properties.maximumMessagesInMessageGroup()).isEqualTo(8);
        replacedertThat(properties.maximumCachedMessageGroups()).isEqualTo(10);
        replacedertThat(properties.messageVisibilityTimeout()).isEqualTo(Duration.ofSeconds(16));
        replacedertThat(properties.tryAndProcessAnyExtraRetrievedMessagesOnShutdown()).isTrue();
        replacedertThat(properties.interruptThreadsProcessingMessagesOnShutdown()).isTrue();
    }

    @Test
    void stringFieldsWithRawValues() throws Exception {
        // arrange
        final FifoQueueListener annotation = FifoQueueListenerParserTest.clreplaced.getMethod("stringMethod").getAnnotation(FifoQueueListener.clreplaced);
        // act
        final FifoMessageListenerContainerProperties properties = parser.parse(annotation);
        // replacedert
        replacedertThat(properties.concurrencyLevel()).isEqualTo(10);
        replacedertThat(properties.maximumMessagesInMessageGroup()).isEqualTo(6);
        replacedertThat(properties.maximumCachedMessageGroups()).isEqualTo(12);
        replacedertThat(properties.messageVisibilityTimeout()).isEqualTo(Duration.ofSeconds(15));
    }

    @Test
    void stringFieldsWithReplacements() throws Exception {
        // arrange
        mockEnvironment.withProperty("queue.concurrencyLevel", "2").withProperty("queue.maximumMessagesInMessageGroup", "3").withProperty("queue.maximumCachedMessageGroups", "15").withProperty("queue.messageVisibilityInSeconds", "5");
        final FifoQueueListener annotation = FifoQueueListenerParserTest.clreplaced.getMethod("stringMethodWithReplacements").getAnnotation(FifoQueueListener.clreplaced);
        // act
        final FifoMessageListenerContainerProperties properties = parser.parse(annotation);
        // replacedert
        replacedertThat(properties.concurrencyLevel()).isEqualTo(2);
        replacedertThat(properties.maximumMessagesInMessageGroup()).isEqualTo(3);
        replacedertThat(properties.maximumCachedMessageGroups()).isEqualTo(15);
        replacedertThat(properties.messageVisibilityTimeout()).isEqualTo(Duration.ofSeconds(5));
    }

    @FifoQueueListener("queueName")
    public void method() {
    }

    @FifoQueueListener(value = "queueName", concurrencyLevel = 7, maximumMessagesInMessageGroup = 8, maximumCachedMessageGroups = 10, messageVisibilityTimeoutInSeconds = 16, interruptThreadsProcessingMessagesOnShutdown = true, tryAndProcessAnyExtraRetrievedMessagesOnShutdown = true)
    public void methodWithPrimitives() {
    }

    @FifoQueueListener(value = "queueName", concurrencyLevelString = "10", maximumMessagesInMessageGroupString = "6", maximumCachedMessageGroupsString = "12", messageVisibilityTimeoutInSecondsString = "15")
    public void stringMethod() {
    }

    @FifoQueueListener(value = "queueName", concurrencyLevelString = "${queue.concurrencyLevel}", maximumMessagesInMessageGroupString = "${queue.maximumMessagesInMessageGroup}", maximumCachedMessageGroupsString = "${queue.maximumCachedMessageGroups}", messageVisibilityTimeoutInSecondsString = "${queue.messageVisibilityInSeconds}")
    public void stringMethodWithReplacements() {
    }
}

19 View Source File : QueueListenerParserTest.java
License : MIT License
Project Creator : JaidenAshmore

clreplaced QueueListenerParserTest {

    MockEnvironment mockEnvironment;

    QueueListenerParser parser;

    @BeforeEach
    void setUp() {
        mockEnvironment = new MockEnvironment();
        parser = new QueueListenerParser(mockEnvironment);
    }

    @Test
    void minimalAnnotation() throws Exception {
        // arrange
        final QueueListener annotation = QueueListenerParserTest.clreplaced.getMethod("method").getAnnotation(QueueListener.clreplaced);
        // act
        final BatchingMessageListenerContainerProperties properties = parser.parse(annotation);
        // replacedert
        replacedertThat(properties.concurrencyLevel()).isEqualTo(5);
        replacedertThat(properties.batchSize()).isEqualTo(5);
        replacedertThat(properties.getBatchingPeriod()).isEqualTo(Duration.ofSeconds(2));
        replacedertThat(properties.messageVisibilityTimeout()).isEqualTo(Duration.ofSeconds(30));
        replacedertThat(properties.processAnyExtraRetrievedMessagesOnShutdown()).isTrue();
        replacedertThat(properties.interruptThreadsProcessingMessagesOnShutdown()).isFalse();
    }

    @Test
    void primitiveValues() throws Exception {
        // arrange
        final QueueListener annotation = QueueListenerParserTest.clreplaced.getMethod("methodWithPrimitives").getAnnotation(QueueListener.clreplaced);
        // act
        final BatchingMessageListenerContainerProperties properties = parser.parse(annotation);
        // replacedert
        replacedertThat(properties.concurrencyLevel()).isEqualTo(7);
        replacedertThat(properties.batchSize()).isEqualTo(8);
        replacedertThat(properties.getBatchingPeriod()).isEqualTo(Duration.ofMillis(1500));
        replacedertThat(properties.messageVisibilityTimeout()).isEqualTo(Duration.ofSeconds(16));
        replacedertThat(properties.processAnyExtraRetrievedMessagesOnShutdown()).isFalse();
        replacedertThat(properties.interruptThreadsProcessingMessagesOnShutdown()).isTrue();
    }

    @Test
    void stringFieldsWithRawValues() throws Exception {
        // arrange
        final QueueListener annotation = QueueListenerParserTest.clreplaced.getMethod("stringMethod").getAnnotation(QueueListener.clreplaced);
        // act
        final BatchingMessageListenerContainerProperties properties = parser.parse(annotation);
        // replacedert
        replacedertThat(properties.concurrencyLevel()).isEqualTo(10);
        replacedertThat(properties.batchSize()).isEqualTo(6);
        replacedertThat(properties.getBatchingPeriod()).isEqualTo(Duration.ofSeconds(1));
        replacedertThat(properties.messageVisibilityTimeout()).isEqualTo(Duration.ofSeconds(15));
        replacedertThat(properties.processAnyExtraRetrievedMessagesOnShutdown()).isTrue();
        replacedertThat(properties.interruptThreadsProcessingMessagesOnShutdown()).isFalse();
    }

    @Test
    void stringFieldsWithReplacements() throws Exception {
        // arrange
        mockEnvironment.withProperty("queue.concurrencyLevel", "2").withProperty("queue.batchSize", "3").withProperty("queue.batchingPeriodInMs", "500").withProperty("queue.messageVisibilityInSeconds", "5");
        final QueueListener annotation = QueueListenerParserTest.clreplaced.getMethod("stringMethodWithReplacements").getAnnotation(QueueListener.clreplaced);
        // act
        final BatchingMessageListenerContainerProperties properties = parser.parse(annotation);
        // replacedert
        replacedertThat(properties.concurrencyLevel()).isEqualTo(2);
        replacedertThat(properties.batchSize()).isEqualTo(3);
        replacedertThat(properties.getBatchingPeriod()).isEqualTo(Duration.ofMillis(500));
        replacedertThat(properties.messageVisibilityTimeout()).isEqualTo(Duration.ofSeconds(5));
        replacedertThat(properties.processAnyExtraRetrievedMessagesOnShutdown()).isTrue();
        replacedertThat(properties.interruptThreadsProcessingMessagesOnShutdown()).isFalse();
    }

    @QueueListener("queueName")
    public void method() {
    }

    @QueueListener(value = "queueName", concurrencyLevel = 7, batchSize = 8, batchingPeriodInMs = 1500, messageVisibilityTimeoutInSeconds = 16, interruptThreadsProcessingMessagesOnShutdown = true, processAnyExtraRetrievedMessagesOnShutdown = false)
    public void methodWithPrimitives() {
    }

    @QueueListener(value = "queueName", concurrencyLevelString = "10", batchSizeString = "6", batchingPeriodInMsString = "1000", messageVisibilityTimeoutInSecondsString = "15")
    public void stringMethod() {
    }

    @QueueListener(value = "queueName", concurrencyLevelString = "${queue.concurrencyLevel}", batchSizeString = "${queue.batchSize}", batchingPeriodInMsString = "${queue.batchingPeriodInMs}", messageVisibilityTimeoutInSecondsString = "${queue.messageVisibilityInSeconds}")
    public void stringMethodWithReplacements() {
    }
}

19 View Source File : DubboTransportedMethodMetadataResolverTest.java
License : Apache License 2.0
Project Creator : alibaba

/**
 * {@link DubboTransportedMethodMetadataResolver} Test.
 *
 * @author <a href="mailto:[email protected]">Mercy</a>
 */
public clreplaced DubboTransportedMethodMetadataResolverTest {

    private DubboTransportedMethodMetadataResolver resolver;

    private MockEnvironment environment;

    @Before
    public void init() {
        environment = new MockEnvironment();
        resolver = new DubboTransportedMethodMetadataResolver(environment, new SpringMvcContract());
    }

    @Test
    public void testResolve() {
        Set<DubboTransportedMethodMetadata> metadataSet = resolver.resolveDubboTransportedMethodMetadataSet(TestDefaultService.clreplaced);
        replacedert.replacedertEquals(1, metadataSet.size());
    }

    @DubboTransported
    interface TestDefaultService {

        String test(String message);
    }
}

19 View Source File : DataSourcePoolPropertiesTest.java
License : Apache License 2.0
Project Creator : alibaba

public clreplaced DataSourcePoolPropertiesTest {

    private static final String JDBC_URL = "jdbc:derby://127.0.0.1:3306/nacos_devtest?characterEncoding=utf8&serverTimezone=UTC";

    private static final String JDBC_DRIVER_CLreplaced_NAME = "org.apache.derby.jdbc.EmbeddedDriver";

    private static final String PreplacedWORD = "nacos";

    private static final String USERNAME = "nacos_devtest";

    private static final Long CONNECTION_TIMEOUT = 10000L;

    private static final Integer MAX_POOL_SIZE = 50;

    private MockEnvironment environment;

    @Before
    public void setUp() throws Exception {
        environment = new MockEnvironment();
        environment.setProperty("db.user", USERNAME);
        environment.setProperty("db.preplacedword", PreplacedWORD);
        environment.setProperty("db.pool.config.connectionTimeout", CONNECTION_TIMEOUT.toString());
        environment.setProperty("db.pool.config.maximumPoolSize", MAX_POOL_SIZE.toString());
    }

    @Test
    public void testBuild() {
        DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(environment);
        poolProperties.setJdbcUrl(JDBC_URL);
        poolProperties.setDriverClreplacedName(JDBC_DRIVER_CLreplaced_NAME);
        poolProperties.setUsername(USERNAME);
        poolProperties.setPreplacedword(PreplacedWORD);
        HikariDataSource actual = poolProperties.getDataSource();
        replacedertEquals(JDBC_URL, actual.getJdbcUrl());
        replacedertEquals(JDBC_DRIVER_CLreplaced_NAME, actual.getDriverClreplacedName());
        replacedertEquals(USERNAME, actual.getUsername());
        replacedertEquals(PreplacedWORD, actual.getPreplacedword());
        replacedertEquals(CONNECTION_TIMEOUT.longValue(), actual.getConnectionTimeout());
        replacedertEquals(DataSourcePoolProperties.DEFAULT_VALIDATION_TIMEOUT, actual.getValidationTimeout());
        replacedertEquals(MAX_POOL_SIZE.intValue(), actual.getMaximumPoolSize());
        replacedertEquals(DataSourcePoolProperties.DEFAULT_MINIMUM_IDLE, actual.getMinimumIdle());
    }
}

18 View Source File : ZonkyPostgresDatabaseProviderTest.java
License : Apache License 2.0
Project Creator : zonkyio

@Test
public void providersWithDefaultConfigurationShouldEquals() {
    MockEnvironment environment = new MockEnvironment();
    ZonkyPostgresDatabaseProvider provider1 = new ZonkyPostgresDatabaseProvider(environment, databaseCustomizers);
    ZonkyPostgresDatabaseProvider provider2 = new ZonkyPostgresDatabaseProvider(environment, databaseCustomizers);
    replacedertThat(provider1).isEqualTo(provider2);
}

18 View Source File : YandexPostgresDatabaseProviderTest.java
License : Apache License 2.0
Project Creator : zonkyio

@Test
public void providersWithDefaultConfigurationShouldEquals() {
    MockEnvironment environment = new MockEnvironment();
    YandexPostgresDatabaseProvider provider1 = new YandexPostgresDatabaseProvider(environment);
    YandexPostgresDatabaseProvider provider2 = new YandexPostgresDatabaseProvider(environment);
    replacedertThat(provider1).isEqualTo(provider2);
}

18 View Source File : OpenTablePostgresDatabaseProviderTest.java
License : Apache License 2.0
Project Creator : zonkyio

@Test
public void providersWithDefaultConfigurationShouldEquals() {
    MockEnvironment environment = new MockEnvironment();
    OpenTablePostgresDatabaseProvider provider1 = new OpenTablePostgresDatabaseProvider(environment, databaseCustomizers);
    OpenTablePostgresDatabaseProvider provider2 = new OpenTablePostgresDatabaseProvider(environment, databaseCustomizers);
    replacedertThat(provider1).isEqualTo(provider2);
}

18 View Source File : DockerPostgresDatabaseProviderTest.java
License : Apache License 2.0
Project Creator : zonkyio

@Test
public void providersWithDefaultConfigurationShouldEquals() {
    MockEnvironment environment = new MockEnvironment();
    DockerPostgresDatabaseProvider provider1 = new DockerPostgresDatabaseProvider(environment, containerCustomizers);
    DockerPostgresDatabaseProvider provider2 = new DockerPostgresDatabaseProvider(environment, containerCustomizers);
    replacedertThat(provider1).isEqualTo(provider2);
}

/**
 * Tests for {@link SpringBootTestRandomPortEnvironmentPostProcessor}.
 *
 * @author Madhura Bhave
 * @author Andy Wilkinson
 */
public clreplaced SpringBootTestRandomPortEnvironmentPostProcessorTests {

    private SpringBootTestRandomPortEnvironmentPostProcessor postProcessor = new SpringBootTestRandomPortEnvironmentPostProcessor();

    private MockEnvironment environment;

    private MutablePropertySources propertySources;

    @Before
    public void setup() {
        this.environment = new MockEnvironment();
        this.propertySources = this.environment.getPropertySources();
    }

    @Test
    public void postProcessWhenServerAndManagementPortIsZeroInTestPropertySource() {
        addTestPropertySource("0", "0");
        this.postProcessor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.getProperty("server.port")).isEqualTo("0");
        replacedertThat(this.environment.getProperty("management.server.port")).isEqualTo("0");
    }

    @Test
    public void postProcessWhenTestServerAndTestManagementPortAreNonZero() {
        addTestPropertySource("8080", "8081");
        this.environment.setProperty("server.port", "8080");
        this.environment.setProperty("management.server.port", "8081");
        this.postProcessor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.getProperty("server.port")).isEqualTo("8080");
        replacedertThat(this.environment.getProperty("management.server.port")).isEqualTo("8081");
    }

    @Test
    public void postProcessWhenTestServerPortIsZeroAndTestManagementPortIsNotNull() {
        addTestPropertySource("0", "8080");
        this.postProcessor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.getProperty("server.port")).isEqualTo("0");
        replacedertThat(this.environment.getProperty("management.server.port")).isEqualTo("8080");
    }

    @Test
    public void postProcessWhenTestServerPortIsZeroAndManagementPortIsNull() {
        addTestPropertySource("0", null);
        this.postProcessor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.getProperty("server.port")).isEqualTo("0");
        replacedertThat(this.environment.getProperty("management.server.port")).isNull();
    }

    @Test
    public void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndSameInProduction() {
        addTestPropertySource("0", null);
        Map<String, Object> other = new HashMap<>();
        other.put("server.port", "8081");
        other.put("management.server.port", "8081");
        MapPropertySource otherSource = new MapPropertySource("other", other);
        this.propertySources.addLast(otherSource);
        this.postProcessor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.getProperty("server.port")).isEqualTo("0");
        replacedertThat(this.environment.getProperty("management.server.port")).isEqualTo("");
    }

    @Test
    public void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndDefaultSameInProduction() {
        // mgmt port is 8080 which means it's on the same port as main server since that
        // is null in app properties
        addTestPropertySource("0", null);
        this.propertySources.addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8080")));
        this.postProcessor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.getProperty("server.port")).isEqualTo("0");
        replacedertThat(this.environment.getProperty("management.server.port")).isEqualTo("");
    }

    @Test
    public void postProcessWhenTestServerPortIsZeroAndManagementPortIsNotNullAndDifferentInProduction() {
        addTestPropertySource("0", null);
        this.propertySources.addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "8081")));
        this.postProcessor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.getProperty("server.port")).isEqualTo("0");
        replacedertThat(this.environment.getProperty("management.server.port")).isEqualTo("0");
    }

    @Test
    public void postProcessWhenTestServerPortIsZeroAndManagementPortMinusOne() {
        addTestPropertySource("0", null);
        this.propertySources.addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", "-1")));
        this.postProcessor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.getProperty("server.port")).isEqualTo("0");
        replacedertThat(this.environment.getProperty("management.server.port")).isEqualTo("-1");
    }

    @Test
    public void postProcessWhenTestServerPortIsZeroAndManagementPortIsAnInteger() {
        addTestPropertySource("0", null);
        this.propertySources.addLast(new MapPropertySource("other", Collections.singletonMap("management.server.port", 8081)));
        this.postProcessor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.getProperty("server.port")).isEqualTo("0");
        replacedertThat(this.environment.getProperty("management.server.port")).isEqualTo("0");
    }

    private void addTestPropertySource(String serverPort, String managementPort) {
        Map<String, Object> source = new HashMap<>();
        source.put("server.port", serverPort);
        source.put("management.server.port", managementPort);
        MapPropertySource inlineTestSource = new MapPropertySource(TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME, source);
        this.propertySources.addFirst(inlineTestSource);
    }
}

18 View Source File : LocalHostWebConnectionHtmlUnitDriverTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void getWhenUrlIsRelativeAndNoPortWillUseLocalhost8080() throws Exception {
    MockEnvironment environment = new MockEnvironment();
    LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(environment);
    driver.get("/test");
    verify(this.webClient).getPage(any(WebWindow.clreplaced), requestToUrl(new URL("http://localhost:8080/test")));
}

18 View Source File : LocalHostUriTemplateHandlerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void getRootUriUsesCustomScheme() {
    MockEnvironment environment = new MockEnvironment();
    LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment, "https");
    replacedertThat(handler.getRootUri()).isEqualTo("https://localhost:8080");
}

18 View Source File : LocalHostUriTemplateHandlerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void getRootUriWhenLocalServerPortMissingShouldUsePort8080() {
    MockEnvironment environment = new MockEnvironment();
    LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment);
    replacedertThat(handler.getRootUri()).isEqualTo("http://localhost:8080");
}

18 View Source File : TomcatServletWebServerFactoryCustomizerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link TomcatServletWebServerFactoryCustomizer}.
 *
 * @author Phillip Webb
 */
public clreplaced TomcatServletWebServerFactoryCustomizerTests {

    private TomcatServletWebServerFactoryCustomizer customizer;

    private MockEnvironment environment;

    private ServerProperties serverProperties;

    @Before
    public void setup() {
        this.environment = new MockEnvironment();
        this.serverProperties = new ServerProperties();
        ConfigurationPropertySources.attach(this.environment);
        this.customizer = new TomcatServletWebServerFactoryCustomizer(this.serverProperties);
    }

    @Test
    public void customTldSkip() {
        bind("server.tomcat.additional-tld-skip-patterns=foo.jar,bar.jar");
        testCustomTldSkip("foo.jar", "bar.jar");
    }

    @Test
    public void customTldSkipAsList() {
        bind("server.tomcat.additional-tld-skip-patterns[0]=biz.jar", "server.tomcat.additional-tld-skip-patterns[1]=bah.jar");
        testCustomTldSkip("biz.jar", "bah.jar");
    }

    private void testCustomTldSkip(String... expectedJars) {
        TomcatServletWebServerFactory factory = customizeAndGetFactory();
        replacedertThat(factory.getTldSkipPatterns()).contains(expectedJars);
        replacedertThat(factory.getTldSkipPatterns()).contains("junit-*.jar", "spring-boot-*.jar");
    }

    @Test
    public void redirectContextRootCanBeConfigured() {
        bind("server.tomcat.redirect-context-root=false");
        ServerProperties.Tomcat tomcat = this.serverProperties.getTomcat();
        replacedertThat(tomcat.getRedirectContextRoot()).isFalse();
        TomcatWebServer server = customizeAndGetServer();
        Context context = (Context) server.getTomcat().getHost().findChildren()[0];
        replacedertThat(context.getMapperContextRootRedirectEnabled()).isFalse();
    }

    @Test
    public void useRelativeRedirectsCanBeConfigured() {
        bind("server.tomcat.use-relative-redirects=true");
        replacedertThat(this.serverProperties.getTomcat().getUseRelativeRedirects()).isTrue();
        TomcatWebServer server = customizeAndGetServer();
        Context context = (Context) server.getTomcat().getHost().findChildren()[0];
        replacedertThat(context.getUseRelativeRedirects()).isTrue();
    }

    private void bind(String... inlinedProperties) {
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, inlinedProperties);
        new Binder(ConfigurationPropertySources.get(this.environment)).bind("server", Bindable.ofInstance(this.serverProperties));
    }

    private TomcatWebServer customizeAndGetServer() {
        TomcatServletWebServerFactory factory = customizeAndGetFactory();
        return (TomcatWebServer) factory.getWebServer();
    }

    private TomcatServletWebServerFactory customizeAndGetFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0);
        this.customizer.customize(factory);
        return factory;
    }
}

18 View Source File : JspTemplateAvailabilityProviderTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link JspTemplateAvailabilityProvider}.
 *
 * @author Yunkun Huang
 */
public clreplaced JspTemplateAvailabilityProviderTests {

    private final JspTemplateAvailabilityProvider provider = new JspTemplateAvailabilityProvider();

    private final ResourceLoader resourceLoader = new DefaultResourceLoader();

    private final MockEnvironment environment = new MockEnvironment();

    @Test
    public void availabilityOfTemplateThatDoesNotExist() {
        replacedertThat(isTemplateAvailable("whatever")).isFalse();
    }

    @Test
    public void availabilityOfTemplateWithCustomPrefix() {
        this.environment.setProperty("spring.mvc.view.prefix", "clreplacedpath:/custom-templates/");
        replacedertThat(isTemplateAvailable("custom.jsp")).isTrue();
    }

    @Test
    public void availabilityOfTemplateWithCustomSuffix() {
        this.environment.setProperty("spring.mvc.view.prefix", "clreplacedpath:/custom-templates/");
        this.environment.setProperty("spring.mvc.view.suffix", ".jsp");
        replacedertThat(isTemplateAvailable("suffixed")).isTrue();
    }

    private boolean isTemplateAvailable(String view) {
        return this.provider.isTemplateAvailable(view, this.environment, getClreplaced().getClreplacedLoader(), this.resourceLoader);
    }
}

18 View Source File : UndertowWebServerFactoryCustomizerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link UndertowWebServerFactoryCustomizer}.
 *
 * @author Brian Clozel
 * @author Phillip Webb
 */
public clreplaced UndertowWebServerFactoryCustomizerTests {

    private MockEnvironment environment;

    private ServerProperties serverProperties;

    private UndertowWebServerFactoryCustomizer customizer;

    @Before
    public void setup() {
        this.environment = new MockEnvironment();
        this.serverProperties = new ServerProperties();
        ConfigurationPropertySources.attach(this.environment);
        this.customizer = new UndertowWebServerFactoryCustomizer(this.environment, this.serverProperties);
    }

    @Test
    public void customizeUndertowAccessLog() {
        bind("server.undertow.accesslog.enabled=true", "server.undertow.accesslog.pattern=foo", "server.undertow.accesslog.prefix=test_log", "server.undertow.accesslog.suffix=txt", "server.undertow.accesslog.dir=test-logs", "server.undertow.accesslog.rotate=false");
        ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.clreplaced);
        this.customizer.customize(factory);
        verify(factory).setAccessLogEnabled(true);
        verify(factory).setAccessLogPattern("foo");
        verify(factory).setAccessLogPrefix("test_log");
        verify(factory).setAccessLogSuffix("txt");
        verify(factory).setAccessLogDirectory(new File("test-logs"));
        verify(factory).setAccessLogRotate(false);
    }

    @Test
    public void deduceUseForwardHeaders() {
        this.environment.setProperty("DYNO", "-");
        ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.clreplaced);
        this.customizer.customize(factory);
        verify(factory).setUseForwardHeaders(true);
    }

    @Test
    public void defaultUseForwardHeaders() {
        ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.clreplaced);
        this.customizer.customize(factory);
        verify(factory).setUseForwardHeaders(false);
    }

    @Test
    public void setUseForwardHeaders() {
        this.serverProperties.setUseForwardHeaders(true);
        ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.clreplaced);
        this.customizer.customize(factory);
        verify(factory).setUseForwardHeaders(true);
    }

    @Test
    public void customizeMaxHttpHeaderSize() {
        bind("server.max-http-header-size=2048");
        Builder builder = Undertow.builder();
        ConfigurableUndertowWebServerFactory factory = mockFactory(builder);
        this.customizer.customize(factory);
        OptionMap map = ((OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions")).getMap();
        replacedertThat(map.get(UndertowOptions.MAX_HEADER_SIZE).intValue()).isEqualTo(2048);
    }

    @Test
    public void customMaxHttpHeaderSizeIgnoredIfNegative() {
        bind("server.max-http-header-size=-1");
        Builder builder = Undertow.builder();
        ConfigurableUndertowWebServerFactory factory = mockFactory(builder);
        this.customizer.customize(factory);
        OptionMap map = ((OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions")).getMap();
        replacedertThat(map.contains(UndertowOptions.MAX_HEADER_SIZE)).isFalse();
    }

    @Test
    public void customMaxHttpHeaderSizeIgnoredIfZero() {
        bind("server.max-http-header-size=0");
        Builder builder = Undertow.builder();
        ConfigurableUndertowWebServerFactory factory = mockFactory(builder);
        this.customizer.customize(factory);
        OptionMap map = ((OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions")).getMap();
        replacedertThat(map.contains(UndertowOptions.MAX_HEADER_SIZE)).isFalse();
    }

    private ConfigurableUndertowWebServerFactory mockFactory(Builder builder) {
        ConfigurableUndertowWebServerFactory factory = mock(ConfigurableUndertowWebServerFactory.clreplaced);
        willAnswer((invocation) -> {
            Object argument = invocation.getArgument(0);
            Arrays.stream((argument instanceof UndertowBuilderCustomizer) ? new UndertowBuilderCustomizer[] { (UndertowBuilderCustomizer) argument } : (UndertowBuilderCustomizer[]) argument).forEach((customizer) -> customizer.customize(builder));
            return null;
        }).given(factory).addBuilderCustomizers(any());
        return factory;
    }

    private void bind(String... inlinedProperties) {
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, inlinedProperties);
        new Binder(ConfigurationPropertySources.get(this.environment)).bind("server", Bindable.ofInstance(this.serverProperties));
    }
}

18 View Source File : TomcatWebServerFactoryCustomizerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link TomcatWebServerFactoryCustomizer}
 *
 * @author Brian Clozel
 * @author Phillip Webb
 * @author Rob Tompkins
 * @author Artsiom Yudovin
 * @author Stephane Nicoll
 */
public clreplaced TomcatWebServerFactoryCustomizerTests {

    private MockEnvironment environment;

    private ServerProperties serverProperties;

    private TomcatWebServerFactoryCustomizer customizer;

    @Before
    public void setup() {
        this.environment = new MockEnvironment();
        this.serverProperties = new ServerProperties();
        ConfigurationPropertySources.attach(this.environment);
        this.customizer = new TomcatWebServerFactoryCustomizer(this.environment, this.serverProperties);
    }

    @Test
    public void defaultsAreConsistent() {
        customizeAndRunServer((server) -> replacedertThat(((AbstractHttp11Protocol<?>) server.getTomcat().getConnector().getProtocolHandler()).getMaxSwallowSize()).isEqualTo(this.serverProperties.getTomcat().getMaxSwallowSize().toBytes()));
    }

    @Test
    public void customAcceptCount() {
        bind("server.tomcat.accept-count=10");
        customizeAndRunServer((server) -> replacedertThat(((AbstractProtocol<?>) server.getTomcat().getConnector().getProtocolHandler()).getAcceptCount()).isEqualTo(10));
    }

    @Test
    public void customBackgroundProcessorDelay() {
        bind("server.tomcat.background-processor-delay=5");
        TomcatWebServer server = customizeAndGetServer();
        replacedertThat(server.getTomcat().getEngine().getBackgroundProcessorDelay()).isEqualTo(5);
    }

    @Test
    public void customDisableMaxHttpPostSize() {
        bind("server.tomcat.max-http-post-size=-1");
        customizeAndRunServer((server) -> replacedertThat(server.getTomcat().getConnector().getMaxPostSize()).isEqualTo(-1));
    }

    @Test
    public void customMaxConnections() {
        bind("server.tomcat.max-connections=5");
        customizeAndRunServer((server) -> replacedertThat(((AbstractProtocol<?>) server.getTomcat().getConnector().getProtocolHandler()).getMaxConnections()).isEqualTo(5));
    }

    @Test
    public void customMaxHttpPostSize() {
        bind("server.tomcat.max-http-post-size=10000");
        customizeAndRunServer((server) -> replacedertThat(server.getTomcat().getConnector().getMaxPostSize()).isEqualTo(10000));
    }

    @Test
    public void customMaxHttpHeaderSize() {
        bind("server.max-http-header-size=1KB");
        customizeAndRunServer((server) -> replacedertThat(((AbstractHttp11Protocol<?>) server.getTomcat().getConnector().getProtocolHandler()).getMaxHttpHeaderSize()).isEqualTo(DataSize.ofKilobytes(1).toBytes()));
    }

    @Test
    public void customMaxHttpHeaderSizeIgnoredIfNegative() {
        bind("server.max-http-header-size=-1");
        customizeAndRunServer((server) -> replacedertThat(((AbstractHttp11Protocol<?>) server.getTomcat().getConnector().getProtocolHandler()).getMaxHttpHeaderSize()).isEqualTo(DataSize.ofKilobytes(8).toBytes()));
    }

    @Test
    public void customMaxHttpHeaderSizeIgnoredIfZero() {
        bind("server.max-http-header-size=0");
        customizeAndRunServer((server) -> replacedertThat(((AbstractHttp11Protocol<?>) server.getTomcat().getConnector().getProtocolHandler()).getMaxHttpHeaderSize()).isEqualTo(DataSize.ofKilobytes(8).toBytes()));
    }

    @Test
    @Deprecated
    public void customMaxHttpHeaderSizeWithDeprecatedProperty() {
        bind("server.max-http-header-size=4KB", "server.tomcat.max-http-header-size=1024");
        customizeAndRunServer((server) -> replacedertThat(((AbstractHttp11Protocol<?>) server.getTomcat().getConnector().getProtocolHandler()).getMaxHttpHeaderSize()).isEqualTo(DataSize.ofKilobytes(1).toBytes()));
    }

    @Test
    public void customMaxSwallowSize() {
        bind("server.tomcat.max-swallow-size=10MB");
        customizeAndRunServer((server) -> replacedertThat(((AbstractHttp11Protocol<?>) server.getTomcat().getConnector().getProtocolHandler()).getMaxSwallowSize()).isEqualTo(DataSize.ofMegabytes(10).toBytes()));
    }

    @Test
    public void customRemoteIpValve() {
        bind("server.tomcat.remote-ip-header=x-my-remote-ip-header", "server.tomcat.protocol-header=x-my-protocol-header", "server.tomcat.internal-proxies=192.168.0.1", "server.tomcat.port-header=x-my-forward-port", "server.tomcat.protocol-header-https-value=On");
        TomcatServletWebServerFactory factory = customizeAndGetFactory();
        replacedertThat(factory.getEngineValves()).hreplacedize(1);
        Valve valve = factory.getEngineValves().iterator().next();
        replacedertThat(valve).isInstanceOf(RemoteIpValve.clreplaced);
        RemoteIpValve remoteIpValve = (RemoteIpValve) valve;
        replacedertThat(remoteIpValve.getProtocolHeader()).isEqualTo("x-my-protocol-header");
        replacedertThat(remoteIpValve.getProtocolHeaderHttpsValue()).isEqualTo("On");
        replacedertThat(remoteIpValve.getRemoteIpHeader()).isEqualTo("x-my-remote-ip-header");
        replacedertThat(remoteIpValve.getPortHeader()).isEqualTo("x-my-forward-port");
        replacedertThat(remoteIpValve.getInternalProxies()).isEqualTo("192.168.0.1");
    }

    @SuppressWarnings("unchecked")
    @Test
    public void customStaticResourceAllowCaching() {
        bind("server.tomcat.resource.allow-caching=false");
        customizeAndRunServer((server) -> {
            Mapper mapper = server.getTomcat().getService().getMapper();
            Object contextObjectToContextVersionMap = ReflectionTestUtils.getField(mapper, "contextObjectToContextVersionMap");
            Object tomcatEmbeddedContext = ((Map<Context, Object>) contextObjectToContextVersionMap).values().toArray()[0];
            replacedertThat(((StandardRoot) ReflectionTestUtils.getField(tomcatEmbeddedContext, "resources")).isCachingAllowed()).isFalse();
        });
    }

    @Test
    public void customStaticResourceCacheTtl() {
        bind("server.tomcat.resource.cache-ttl=10000");
        customizeAndRunServer((server) -> {
            Tomcat tomcat = server.getTomcat();
            Context context = (Context) tomcat.getHost().findChildren()[0];
            replacedertThat(context.getResources().getCacheTtl()).isEqualTo(10000L);
        });
    }

    @Test
    public void deduceUseForwardHeaders() {
        this.environment.setProperty("DYNO", "-");
        testRemoteIpValveConfigured();
    }

    @Test
    public void defaultRemoteIpValve() {
        // Since 1.1.7 you need to specify at least the protocol
        bind("server.tomcat.protocol-header=X-Forwarded-Proto", "server.tomcat.remote-ip-header=X-Forwarded-For");
        testRemoteIpValveConfigured();
    }

    @Test
    public void setUseForwardHeaders() {
        // Since 1.3.0 no need to explicitly set header names if use-forward-header=true
        this.serverProperties.setUseForwardHeaders(true);
        testRemoteIpValveConfigured();
    }

    private void testRemoteIpValveConfigured() {
        TomcatServletWebServerFactory factory = customizeAndGetFactory();
        replacedertThat(factory.getEngineValves()).hreplacedize(1);
        Valve valve = factory.getEngineValves().iterator().next();
        replacedertThat(valve).isInstanceOf(RemoteIpValve.clreplaced);
        RemoteIpValve remoteIpValve = (RemoteIpValve) valve;
        replacedertThat(remoteIpValve.getProtocolHeader()).isEqualTo("X-Forwarded-Proto");
        replacedertThat(remoteIpValve.getProtocolHeaderHttpsValue()).isEqualTo("https");
        replacedertThat(remoteIpValve.getRemoteIpHeader()).isEqualTo("X-Forwarded-For");
        String expectedInternalProxies = // 10/8
        "10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" + // 192.168/16
        "192\\.168\\.\\d{1,3}\\.\\d{1,3}|" + // 169.254/16
        "169\\.254\\.\\d{1,3}\\.\\d{1,3}|" + // 127/8
        "127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" + // 172.16/12
        "172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" + "172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" + // 
        "172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}|" + "0:0:0:0:0:0:0:1|::1";
        replacedertThat(remoteIpValve.getInternalProxies()).isEqualTo(expectedInternalProxies);
    }

    @Test
    public void defaultBackgroundProcessorDelay() {
        TomcatWebServer server = customizeAndGetServer();
        replacedertThat(server.getTomcat().getEngine().getBackgroundProcessorDelay()).isEqualTo(10);
    }

    @Test
    public void disableRemoteIpValve() {
        bind("server.tomcat.remote-ip-header=", "server.tomcat.protocol-header=");
        TomcatServletWebServerFactory factory = customizeAndGetFactory();
        replacedertThat(factory.getEngineValves()).isEmpty();
    }

    @Test
    public void errorReportValveIsConfiguredToNotReportStackTraces() {
        TomcatWebServer server = customizeAndGetServer();
        Valve[] valves = server.getTomcat().getHost().getPipeline().getValves();
        replacedertThat(valves).hasAtLeastOneElementOfType(ErrorReportValve.clreplaced);
        for (Valve valve : valves) {
            if (valve instanceof ErrorReportValve) {
                ErrorReportValve errorReportValve = (ErrorReportValve) valve;
                replacedertThat(errorReportValve.isShowReport()).isFalse();
                replacedertThat(errorReportValve.isShowServerInfo()).isFalse();
            }
        }
    }

    @Test
    public void testCustomizeMinSpareThreads() {
        bind("server.tomcat.min-spare-threads=10");
        replacedertThat(this.serverProperties.getTomcat().getMinSpareThreads()).isEqualTo(10);
    }

    @Test
    public void accessLogBufferingCanBeDisabled() {
        bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.buffered=false");
        TomcatServletWebServerFactory factory = customizeAndGetFactory();
        replacedertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).isBuffered()).isFalse();
    }

    @Test
    public void accessLogCanBeEnabled() {
        bind("server.tomcat.accesslog.enabled=true");
        TomcatServletWebServerFactory factory = customizeAndGetFactory();
        replacedertThat(factory.getEngineValves()).hreplacedize(1);
        replacedertThat(factory.getEngineValves()).first().isInstanceOf(AccessLogValve.clreplaced);
    }

    @Test
    public void accessLogFileDateFormatByDefault() {
        bind("server.tomcat.accesslog.enabled=true");
        TomcatServletWebServerFactory factory = customizeAndGetFactory();
        replacedertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getFileDateFormat()).isEqualTo(".yyyy-MM-dd");
    }

    @Test
    public void accessLogFileDateFormatCanBeRedefined() {
        bind("server.tomcat.accesslog.enabled=true", "server.tomcat.accesslog.file-date-format=yyyy-MM-dd.HH");
        TomcatServletWebServerFactory factory = customizeAndGetFactory();
        replacedertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).getFileDateFormat()).isEqualTo("yyyy-MM-dd.HH");
    }

    @Test
    public void accessLogIsBufferedByDefault() {
        bind("server.tomcat.accesslog.enabled=true");
        TomcatServletWebServerFactory factory = customizeAndGetFactory();
        replacedertThat(((AccessLogValve) factory.getEngineValves().iterator().next()).isBuffered()).isTrue();
    }

    @Test
    public void accessLogIsDisabledByDefault() {
        TomcatServletWebServerFactory factory = customizeAndGetFactory();
        replacedertThat(factory.getEngineValves()).isEmpty();
    }

    private void bind(String... inlinedProperties) {
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, inlinedProperties);
        new Binder(ConfigurationPropertySources.get(this.environment)).bind("server", Bindable.ofInstance(this.serverProperties));
    }

    private void customizeAndRunServer(Consumer<TomcatWebServer> consumer) {
        TomcatWebServer server = customizeAndGetServer();
        server.start();
        try {
            consumer.accept(server);
        } finally {
            server.stop();
        }
    }

    private TomcatWebServer customizeAndGetServer() {
        TomcatServletWebServerFactory factory = customizeAndGetFactory();
        return (TomcatWebServer) factory.getWebServer();
    }

    private TomcatServletWebServerFactory customizeAndGetFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0);
        this.customizer.customize(factory);
        return factory;
    }
}

18 View Source File : NettyWebServerFactoryCustomizerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link NettyWebServerFactoryCustomizer}.
 *
 * @author Brian Clozel
 */
public clreplaced NettyWebServerFactoryCustomizerTests {

    private MockEnvironment environment;

    private ServerProperties serverProperties;

    private NettyWebServerFactoryCustomizer customizer;

    @Before
    public void setup() {
        this.environment = new MockEnvironment();
        this.serverProperties = new ServerProperties();
        ConfigurationPropertySources.attach(this.environment);
        this.customizer = new NettyWebServerFactoryCustomizer(this.environment, this.serverProperties);
    }

    @Test
    public void deduceUseForwardHeaders() {
        this.environment.setProperty("DYNO", "-");
        NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.clreplaced);
        this.customizer.customize(factory);
        verify(factory).setUseForwardHeaders(true);
    }

    @Test
    public void defaultUseForwardHeaders() {
        NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.clreplaced);
        this.customizer.customize(factory);
        verify(factory).setUseForwardHeaders(false);
    }

    @Test
    public void setUseForwardHeaders() {
        this.serverProperties.setUseForwardHeaders(true);
        NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.clreplaced);
        this.customizer.customize(factory);
        verify(factory).setUseForwardHeaders(true);
    }
}

18 View Source File : JettyWebServerFactoryCustomizerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link JettyWebServerFactoryCustomizer}.
 *
 * @author Brian Clozel
 * @author Phillip Webb
 */
public clreplaced JettyWebServerFactoryCustomizerTests {

    private MockEnvironment environment;

    private ServerProperties serverProperties;

    private JettyWebServerFactoryCustomizer customizer;

    @Before
    public void setup() {
        this.environment = new MockEnvironment();
        this.serverProperties = new ServerProperties();
        ConfigurationPropertySources.attach(this.environment);
        this.customizer = new JettyWebServerFactoryCustomizer(this.environment, this.serverProperties);
    }

    @Test
    public void deduceUseForwardHeaders() {
        this.environment.setProperty("DYNO", "-");
        ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.clreplaced);
        this.customizer.customize(factory);
        verify(factory).setUseForwardHeaders(true);
    }

    @Test
    public void defaultUseForwardHeaders() {
        ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.clreplaced);
        this.customizer.customize(factory);
        verify(factory).setUseForwardHeaders(false);
    }

    @Test
    public void accessLogCanBeCustomized() throws IOException {
        File logFile = File.createTempFile("jetty_log", ".log");
        String timezone = TimeZone.getDefault().getID();
        bind("server.jetty.accesslog.enabled=true", "server.jetty.accesslog.filename=" + logFile.getAbsolutePath().replace("\\", "\\\\"), "server.jetty.accesslog.file-date-format=yyyy-MM-dd", "server.jetty.accesslog.retention-period=42", "server.jetty.accesslog.append=true", "server.jetty.accesslog.extended-format=true", "server.jetty.accesslog.date-format=HH:mm:ss", "server.jetty.accesslog.locale=en_BE", "server.jetty.accesslog.time-zone=" + timezone, "server.jetty.accesslog.log-cookies=true", "server.jetty.accesslog.log-server=true", "server.jetty.accesslog.log-latency=true");
        JettyWebServer server = customizeAndGetServer();
        NCSARequestLog requestLog = getNCSARequestLog(server);
        replacedertThat(requestLog.getFilename()).isEqualTo(logFile.getAbsolutePath());
        replacedertThat(requestLog.getFilenameDateFormat()).isEqualTo("yyyy-MM-dd");
        replacedertThat(requestLog.getRetainDays()).isEqualTo(42);
        replacedertThat(requestLog.isAppend()).isTrue();
        replacedertThat(requestLog.isExtended()).isTrue();
        replacedertThat(requestLog.getLogDateFormat()).isEqualTo("HH:mm:ss");
        replacedertThat(requestLog.getLogLocale()).isEqualTo(new Locale("en", "BE"));
        replacedertThat(requestLog.getLogTimeZone()).isEqualTo(timezone);
        replacedertThat(requestLog.getLogCookies()).isTrue();
        replacedertThat(requestLog.getLogServer()).isTrue();
        replacedertThat(requestLog.getLogLatency()).isTrue();
    }

    @Test
    public void accessLogCanBeEnabled() {
        bind("server.jetty.accesslog.enabled=true");
        JettyWebServer server = customizeAndGetServer();
        NCSARequestLog requestLog = getNCSARequestLog(server);
        replacedertThat(requestLog.getFilename()).isNull();
        replacedertThat(requestLog.isAppend()).isFalse();
        replacedertThat(requestLog.isExtended()).isFalse();
        replacedertThat(requestLog.getLogCookies()).isFalse();
        replacedertThat(requestLog.getLogServer()).isFalse();
        replacedertThat(requestLog.getLogLatency()).isFalse();
    }

    private NCSARequestLog getNCSARequestLog(JettyWebServer server) {
        RequestLog requestLog = server.getServer().getRequestLog();
        replacedertThat(requestLog).isInstanceOf(NCSARequestLog.clreplaced);
        return (NCSARequestLog) requestLog;
    }

    @Test
    public void setUseForwardHeaders() {
        this.serverProperties.setUseForwardHeaders(true);
        ConfigurableJettyWebServerFactory factory = mock(ConfigurableJettyWebServerFactory.clreplaced);
        this.customizer.customize(factory);
        verify(factory).setUseForwardHeaders(true);
    }

    @Test
    public void customizeMaxHttpHeaderSize() {
        bind("server.max-http-header-size=2048");
        JettyWebServer server = customizeAndGetServer();
        List<Integer> requestHeaderSizes = getRequestHeaderSizes(server);
        replacedertThat(requestHeaderSizes).containsOnly(2048);
    }

    @Test
    public void customMaxHttpHeaderSizeIgnoredIfNegative() {
        bind("server.max-http-header-size=-1");
        JettyWebServer server = customizeAndGetServer();
        List<Integer> requestHeaderSizes = getRequestHeaderSizes(server);
        replacedertThat(requestHeaderSizes).containsOnly(8192);
    }

    @Test
    public void customMaxHttpHeaderSizeIgnoredIfZero() {
        bind("server.max-http-header-size=0");
        JettyWebServer server = customizeAndGetServer();
        List<Integer> requestHeaderSizes = getRequestHeaderSizes(server);
        replacedertThat(requestHeaderSizes).containsOnly(8192);
    }

    private List<Integer> getRequestHeaderSizes(JettyWebServer server) {
        List<Integer> requestHeaderSizes = new ArrayList<>();
        Connector[] connectors = (Connector[]) ReflectionTestUtils.getField(server, "connectors");
        for (Connector connector : connectors) {
            connector.getConnectionFactories().stream().filter((factory) -> factory instanceof ConnectionFactory).forEach((cf) -> {
                ConnectionFactory factory = (ConnectionFactory) cf;
                HttpConfiguration configuration = factory.getHttpConfiguration();
                requestHeaderSizes.add(configuration.getRequestHeaderSize());
            });
        }
        return requestHeaderSizes;
    }

    private void bind(String... inlinedProperties) {
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, inlinedProperties);
        new Binder(ConfigurationPropertySources.get(this.environment)).bind("server", Bindable.ofInstance(this.serverProperties));
    }

    private JettyWebServer customizeAndGetServer() {
        JettyServletWebServerFactory factory = customizeAndGetFactory();
        return (JettyWebServer) factory.getWebServer();
    }

    private JettyServletWebServerFactory customizeAndGetFactory() {
        JettyServletWebServerFactory factory = new JettyServletWebServerFactory(0);
        this.customizer.customize(factory);
        return factory;
    }
}

18 View Source File : DefaultEndpointObjectNameFactoryTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link DefaultEndpointObjectNameFactory}.
 *
 * @author Stephane Nicoll
 */
public clreplaced DefaultEndpointObjectNameFactoryTests {

    private final MockEnvironment environment = new MockEnvironment();

    private final JmxEndpointProperties properties = new JmxEndpointProperties(this.environment);

    private final MBeanServer mBeanServer = mock(MBeanServer.clreplaced);

    private String contextId;

    @Test
    public void generateObjectName() {
        ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test")));
        replacedertThat(objectName.toString()).isEqualTo("org.springframework.boot:type=Endpoint,name=Test");
    }

    @Test
    public void generateObjectNameWithCapitalizedId() {
        ObjectName objectName = generateObjectName(endpoint(EndpointId.of("testEndpoint")));
        replacedertThat(objectName.toString()).isEqualTo("org.springframework.boot:type=Endpoint,name=TestEndpoint");
    }

    @Test
    public void generateObjectNameWithCustomDomain() {
        this.properties.setDomain("com.example.acme");
        ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test")));
        replacedertThat(objectName.toString()).isEqualTo("com.example.acme:type=Endpoint,name=Test");
    }

    @Test
    public void generateObjectNameWithUniqueNames() {
        this.environment.setProperty("spring.jmx.unique-names", "true");
        replacedertUniqueObjectName();
    }

    @Test
    @Deprecated
    public void generateObjectNameWithUniqueNamesDeprecatedProperty() {
        this.properties.setUniqueNames(true);
        replacedertUniqueObjectName();
    }

    private void replacedertUniqueObjectName() {
        ExposableJmxEndpoint endpoint = endpoint(EndpointId.of("test"));
        String id = ObjectUtils.getIdenreplacedyHexString(endpoint);
        ObjectName objectName = generateObjectName(endpoint);
        replacedertThat(objectName.toString()).isEqualTo("org.springframework.boot:type=Endpoint,name=Test,idenreplacedy=" + id);
    }

    @Test
    @Deprecated
    public void generateObjectNameWithUniqueNamesDeprecatedPropertyMismatchMainProperty() {
        this.environment.setProperty("spring.jmx.unique-names", "false");
        this.properties.setUniqueNames(true);
        replacedertThatIllegalArgumentException().isThrownBy(() -> generateObjectName(endpoint(EndpointId.of("test")))).withMessageContaining("spring.jmx.unique-names").withMessageContaining("management.endpoints.jmx.unique-names");
    }

    @Test
    public void generateObjectNameWithStaticNames() {
        this.properties.getStaticNames().setProperty("counter", "42");
        this.properties.getStaticNames().setProperty("foo", "bar");
        ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test")));
        replacedertThat(objectName.getKeyProperty("counter")).isEqualTo("42");
        replacedertThat(objectName.getKeyProperty("foo")).isEqualTo("bar");
        replacedertThat(objectName.toString()).startsWith("org.springframework.boot:type=Endpoint,name=Test,");
    }

    @Test
    public void generateObjectNameWithDuplicate() throws MalformedObjectNameException {
        this.contextId = "testContext";
        given(this.mBeanServer.queryNames(new ObjectName("org.springframework.boot:type=Endpoint,name=Test,*"), null)).willReturn(Collections.singleton(new ObjectName("org.springframework.boot:type=Endpoint,name=Test")));
        ObjectName objectName = generateObjectName(endpoint(EndpointId.of("test")));
        replacedertThat(objectName.toString()).isEqualTo("org.springframework.boot:type=Endpoint,name=Test,context=testContext");
    }

    private ObjectName generateObjectName(ExposableJmxEndpoint endpoint) {
        try {
            return new DefaultEndpointObjectNameFactory(this.properties, this.environment, this.mBeanServer, this.contextId).getObjectName(endpoint);
        } catch (MalformedObjectNameException ex) {
            throw new replacedertionError("Invalid object name", ex);
        }
    }

    private ExposableJmxEndpoint endpoint(EndpointId id) {
        ExposableJmxEndpoint endpoint = mock(ExposableJmxEndpoint.clreplaced);
        given(endpoint.getEndpointId()).willReturn(id);
        return endpoint;
    }
}

18 View Source File : ExposeExcludePropertyEndpointFilterTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

private void setupFilter(String include, String exclude) {
    MockEnvironment environment = new MockEnvironment();
    environment.setProperty("foo.include", include);
    environment.setProperty("foo.exclude", exclude);
    this.filter = new ExposeExcludePropertyEndpointFilter<>(TestExposableWebEndpoint.clreplaced, environment, "foo", "def");
}

18 View Source File : EndpointIdTimeToLivePropertyFunctionTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link EndpointIdTimeToLivePropertyFunction}.
 *
 * @author Stephane Nicoll
 * @author Phillip Webb
 */
public clreplaced EndpointIdTimeToLivePropertyFunctionTests {

    private final MockEnvironment environment = new MockEnvironment();

    private final Function<EndpointId, Long> timeToLive = new EndpointIdTimeToLivePropertyFunction(this.environment);

    @Test
    public void defaultConfiguration() {
        Long result = this.timeToLive.apply(EndpointId.of("test"));
        replacedertThat(result).isNull();
    }

    @Test
    public void userConfiguration() {
        this.environment.setProperty("management.endpoint.another-test.cache.time-to-live", "500");
        Long result = this.timeToLive.apply(EndpointId.of("anotherTest"));
        replacedertThat(result).isEqualTo(500L);
    }

    @Test
    public void mixedCaseUserConfiguration() {
    }
}

18 View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : tillias

/**
 * Unit tests for the {@link WebConfigurer} clreplaced.
 */
public clreplaced WebConfigurerTest {

    private WebConfigurer webConfigurer;

    private MockServletContext servletContext;

    private MockEnvironment env;

    private JHipsterProperties props;

    @BeforeEach
    public void setup() {
        servletContext = spy(new MockServletContext());
        doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
        doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
        env = new MockEnvironment();
        props = new JHipsterProperties();
        webConfigurer = new WebConfigurer(env, props);
    }

    @Test
    public void testStartUpProdServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        webConfigurer.onStartup(servletContext);
        verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
    }

    @Test
    public void testStartUpDevServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
        webConfigurer.onStartup(servletContext);
        verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
    }

    @Test
    public void testCustomizeServletContainer() {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
        webConfigurer.customize(container);
        replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
        replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
        replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
        if (container.getDoreplacedentRoot() != null) {
            replacedertThat(container.getDoreplacedentRoot()).isEqualTo(new File("target/clreplacedes/static/"));
        }
    }

    @Test
    public void testCorsFilterOnApiPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
    }

    @Test
    public void testCorsFilterOnOtherPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated() throws Exception {
        props.getCors().setAllowedOrigins(null);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated2() throws Exception {
        props.getCors().setAllowedOrigins(new ArrayList<>());
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }
}

18 View Source File : OnEnabledComponentTests.java
License : Apache License 2.0
Project Creator : spring-cloud

clreplaced OnEnabledComponentTests {

    private OnEnabledComponent<Object> onEnabledComponent;

    private MockEnvironment environment;

    private ConditionContext conditionContext;

    @BeforeEach
    void setUp() {
        this.onEnabledComponent = createOnEnabledComponent("test-clreplaced");
        this.environment = new MockEnvironment();
        this.conditionContext = mock(ConditionContext.clreplaced);
    }

    @Test
    public void shouldMatchComponent() {
        when(conditionContext.getEnvironment()).thenReturn(environment);
        ConditionOutcome outcome = onEnabledComponent.getMatchOutcome(conditionContext, mockMetaData(EnabledComponent.clreplaced));
        replacedertThat(outcome.isMatch()).isTrue();
    }

    @Test
    public void shouldNotMatchDisabledComponent() {
        String componentName = "disabled-component";
        this.onEnabledComponent = createOnEnabledComponent(componentName);
        when(conditionContext.getEnvironment()).thenReturn(environment);
        environment.setProperty("spring.cloud.gateway." + componentName + ".enabled", "false");
        ConditionOutcome outcome = onEnabledComponent.getMatchOutcome(conditionContext, mockMetaData(DisabledComponent.clreplaced));
        replacedertThat(outcome.isMatch()).isFalse();
        replacedertThat(outcome.getMessage()).contains("DisabledComponent").contains("bean is not available");
    }

    private AnnotatedTypeMetadata mockMetaData(Clreplaced<?> value) {
        AnnotatedTypeMetadata metadata = mock(AnnotatedTypeMetadata.clreplaced);
        when(metadata.getAnnotationAttributes(eq(ConditionalOnEnabledFilter.clreplaced.getName()))).thenReturn(Collections.singletonMap("value", value));
        return metadata;
    }

    private OnEnabledComponent<Object> createOnEnabledComponent(String componentName) {
        return new OnEnabledComponent<Object>() {

            @Override
            protected String normalizeComponentName(Clreplaced<?> componentClreplaced) {
                return componentName;
            }

            @Override
            protected Clreplaced<?> annotationClreplaced() {
                return ConditionalOnEnabledFilter.clreplaced;
            }

            @Override
            protected Clreplaced<?> defaultValueClreplaced() {
                return Object.clreplaced;
            }
        };
    }

    protected static clreplaced EnabledComponent {
    }

    protected static clreplaced DisabledComponent {
    }
}

18 View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing

/**
 * Unit tests for the {@link WebConfigurer} clreplaced.
 */
public clreplaced WebConfigurerTest {

    private WebConfigurer webConfigurer;

    private MockServletContext servletContext;

    private MockEnvironment env;

    private JHipsterProperties props;

    @BeforeEach
    public void setup() {
        servletContext = spy(new MockServletContext());
        doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
        doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
        env = new MockEnvironment();
        props = new JHipsterProperties();
        webConfigurer = new WebConfigurer(env, props);
    }

    @Test
    public void testStartUpProdServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        webConfigurer.onStartup(servletContext);
        verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
        verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
    }

    @Test
    public void testStartUpDevServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
        webConfigurer.onStartup(servletContext);
        verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
        verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
    }

    @Test
    public void testCustomizeServletContainer() {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
        webConfigurer.customize(container);
        replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
        replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
        replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
        if (container.getDoreplacedentRoot() != null) {
            replacedertThat(container.getDoreplacedentRoot()).isEqualTo(new File("build/resources/main/static/"));
        }
    }

    @Test
    public void testCorsFilterOnApiPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
    }

    @Test
    public void testCorsFilterOnOtherPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated() throws Exception {
        props.getCors().setAllowedOrigins(null);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated2() throws Exception {
        props.getCors().setAllowedOrigins(new ArrayList<>());
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }
}

18 View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing

/**
 * Unit tests for the {@link WebConfigurer} clreplaced.
 */
public clreplaced WebConfigurerTest {

    private WebConfigurer webConfigurer;

    private MockServletContext servletContext;

    private MockEnvironment env;

    private JHipsterProperties props;

    @BeforeEach
    public void setup() {
        servletContext = spy(new MockServletContext());
        doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
        doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
        env = new MockEnvironment();
        props = new JHipsterProperties();
        webConfigurer = new WebConfigurer(env, props);
    }

    @Test
    public void testStartUpProdServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        webConfigurer.onStartup(servletContext);
        verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
        verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
    }

    @Test
    public void testStartUpDevServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
        webConfigurer.onStartup(servletContext);
        verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
        verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
    }

    @Test
    public void testCustomizeServletContainer() {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
        webConfigurer.customize(container);
        replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
        replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
        replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
        if (container.getDoreplacedentRoot() != null) {
            replacedertThat(container.getDoreplacedentRoot()).isEqualTo(new File("target/clreplacedes/static/"));
        }
    }

    @Test
    public void testCorsFilterOnApiPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
    }

    @Test
    public void testCorsFilterOnOtherPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated() throws Exception {
        props.getCors().setAllowedOrigins(null);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated2() throws Exception {
        props.getCors().setAllowedOrigins(new ArrayList<>());
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }
}

18 View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing

/**
 * Unit tests for the {@link WebConfigurer} clreplaced.
 */
public clreplaced WebConfigurerTest {

    private WebConfigurer webConfigurer;

    private MockServletContext servletContext;

    private MockEnvironment env;

    private JHipsterProperties props;

    @BeforeEach
    public void setup() {
        servletContext = spy(new MockServletContext());
        doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
        doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
        env = new MockEnvironment();
        props = new JHipsterProperties();
        webConfigurer = new WebConfigurer(env, props);
    }

    @Test
    public void testStartUpProdServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        webConfigurer.onStartup(servletContext);
    }

    @Test
    public void testStartUpDevServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
        webConfigurer.onStartup(servletContext);
    }

    @Test
    public void testCorsFilterOnApiPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
    }

    @Test
    public void testCorsFilterOnOtherPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated() throws Exception {
        props.getCors().setAllowedOrigins(null);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated2() throws Exception {
        props.getCors().setAllowedOrigins(new ArrayList<>());
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }
}

18 View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing

/**
 * Unit tests for the {@link WebConfigurer} clreplaced.
 */
public clreplaced WebConfigurerTest {

    private WebConfigurer webConfigurer;

    private MockServletContext servletContext;

    private MockEnvironment env;

    private JHipsterProperties props;

    @BeforeEach
    public void setup() {
        servletContext = spy(new MockServletContext());
        doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
        doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
        env = new MockEnvironment();
        props = new JHipsterProperties();
        webConfigurer = new WebConfigurer(env, props);
    }

    @Test
    public void testStartUpProdServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        webConfigurer.onStartup(servletContext);
        verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
    }

    @Test
    public void testStartUpDevServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
        webConfigurer.onStartup(servletContext);
        verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
    }

    @Test
    public void testCorsFilterOnApiPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
    }

    @Test
    public void testCorsFilterOnOtherPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated() throws Exception {
        props.getCors().setAllowedOrigins(null);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated2() throws Exception {
        props.getCors().setAllowedOrigins(new ArrayList<>());
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }
}

18 View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : otto-de

/**
 * Unit tests for the WebConfigurer clreplaced.
 *
 * @see WebConfigurer
 */
public clreplaced WebConfigurerTest {

    private WebConfigurer webConfigurer;

    private MockServletContext servletContext;

    private MockEnvironment env;

    private JHipsterProperties props;

    @Before
    public void setup() {
        servletContext = spy(new MockServletContext());
        doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
        doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
        env = new MockEnvironment();
        props = new JHipsterProperties();
        webConfigurer = new WebConfigurer(env, props);
    }

    @Test
    public void testStartUpProdServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        webConfigurer.onStartup(servletContext);
        verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
    }

    @Test
    public void testStartUpDevServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
        webConfigurer.onStartup(servletContext);
        verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
    }

    @Test
    public void testCustomizeServletContainer() {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
        webConfigurer.customize(container);
        replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
        replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
        replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
        if (container.getDoreplacedentRoot() != null) {
            replacedertThat(container.getDoreplacedentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("build/www"));
        }
        Builder builder = Undertow.builder();
        container.getBuilderCustomizers().forEach(c -> c.customize(builder));
        OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
        replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
    }

    @Test
    public void testUndertowHttp2Enabled() {
        props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
        UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
        webConfigurer.customize(container);
        Builder builder = Undertow.builder();
        container.getBuilderCustomizers().forEach(c -> c.customize(builder));
        OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
        replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
    }

    @Test
    public void testCorsFilterOnApiPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
    }

    @Test
    public void testCorsFilterOnOtherPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated() throws Exception {
        props.getCors().setAllowedOrigins(null);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated2() throws Exception {
        props.getCors().setAllowedOrigins(new ArrayList<>());
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }
}

18 View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : OpenArchitex

/**
 * Unit tests for the {@link WebConfigurer} clreplaced.
 */
public clreplaced WebConfigurerTest {

    private WebConfigurer webConfigurer;

    private MockServletContext servletContext;

    private MockEnvironment env;

    private JHipsterProperties props;

    @BeforeEach
    public void setup() {
        servletContext = spy(new MockServletContext());
        doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
        doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
        env = new MockEnvironment();
        props = new JHipsterProperties();
        webConfigurer = new WebConfigurer(env, props);
    }

    @Test
    public void testStartUpProdServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        webConfigurer.onStartup(servletContext);
        verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
    }

    @Test
    public void testStartUpDevServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
        webConfigurer.onStartup(servletContext);
        verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
    }

    @Test
    public void testCustomizeServletContainer() {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
        webConfigurer.customize(container);
        replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
        replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
        replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
        if (container.getDoreplacedentRoot() != null) {
            replacedertThat(container.getDoreplacedentRoot()).isEqualTo(new File("target/clreplacedes/static/"));
        }
    }

    @Test
    public void testCorsFilterOnApiPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
    }

    @Test
    public void testCorsFilterOnOtherPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated() throws Exception {
        props.getCors().setAllowedOrigins(null);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated2() throws Exception {
        props.getCors().setAllowedOrigins(new ArrayList<>());
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }
}

18 View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : oktadeveloper

/**
 * Unit tests for the WebConfigurer clreplaced.
 *
 * @see WebConfigurer
 */
public clreplaced WebConfigurerTest {

    private WebConfigurer webConfigurer;

    private MockServletContext servletContext;

    private MockEnvironment env;

    private JHipsterProperties props;

    @Before
    public void setup() {
        servletContext = spy(new MockServletContext());
        doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
        doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
        env = new MockEnvironment();
        props = new JHipsterProperties();
        webConfigurer = new WebConfigurer(env, props);
    }

    @Test
    public void testStartUpProdServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        webConfigurer.onStartup(servletContext);
        verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
        verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
    }

    @Test
    public void testStartUpDevServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
        webConfigurer.onStartup(servletContext);
        verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
        verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
    }

    @Test
    public void testCustomizeServletContainer() {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
        webConfigurer.customize(container);
        replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
        replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
        replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
        if (container.getDoreplacedentRoot() != null) {
            replacedertThat(container.getDoreplacedentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("build/www"));
        }
        Builder builder = Undertow.builder();
        container.getBuilderCustomizers().forEach(c -> c.customize(builder));
        OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
        replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
    }

    @Test
    public void testUndertowHttp2Enabled() {
        props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
        UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
        webConfigurer.customize(container);
        Builder builder = Undertow.builder();
        container.getBuilderCustomizers().forEach(c -> c.customize(builder));
        OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
        replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
    }

    @Test
    public void testCorsFilterOnApiPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
    }

    @Test
    public void testCorsFilterOnOtherPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated() throws Exception {
        props.getCors().setAllowedOrigins(null);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated2() throws Exception {
        props.getCors().setAllowedOrigins(new ArrayList<>());
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }
}

18 View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : oktadeveloper

/**
 * Unit tests for the {@link WebConfigurer} clreplaced.
 */
public clreplaced WebConfigurerTest {

    private WebConfigurer webConfigurer;

    private MockServletContext servletContext;

    private MockEnvironment env;

    private JHipsterProperties props;

    @BeforeEach
    public void setup() {
        servletContext = spy(new MockServletContext());
        doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
        doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
        env = new MockEnvironment();
        props = new JHipsterProperties();
        webConfigurer = new WebConfigurer(env, props);
    }

    @Test
    public void testStartUpProdServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        webConfigurer.onStartup(servletContext);
    }

    @Test
    public void testStartUpDevServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
        webConfigurer.onStartup(servletContext);
    }

    @Test
    public void testCustomizeServletContainer() {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
        webConfigurer.customize(container);
        replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
        replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
        replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
    }

    @Test
    public void testCorsFilterOnApiPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
    }

    @Test
    public void testCorsFilterOnOtherPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated() throws Exception {
        props.getCors().setAllowedOrigins(null);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated2() throws Exception {
        props.getCors().setAllowedOrigins(new ArrayList<>());
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }
}

18 View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : oktadeveloper

/**
 * Unit tests for the {@link WebConfigurer} clreplaced.
 */
public clreplaced WebConfigurerTest {

    private WebConfigurer webConfigurer;

    private MockServletContext servletContext;

    private MockEnvironment env;

    private JHipsterProperties props;

    @BeforeEach
    public void setup() {
        servletContext = spy(new MockServletContext());
        doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
        doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
        env = new MockEnvironment();
        props = new JHipsterProperties();
        webConfigurer = new WebConfigurer(env, props);
    }

    @Test
    public void testStartUpProdServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        webConfigurer.onStartup(servletContext);
        verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
    }

    @Test
    public void testStartUpDevServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
        webConfigurer.onStartup(servletContext);
        verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
    }

    @Test
    public void testCustomizeServletContainer() {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
        webConfigurer.customize(container);
        replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
        replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
        replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
    }

    @Test
    public void testCorsFilterOnApiPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
    }

    @Test
    public void testCorsFilterOnOtherPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated() throws Exception {
        props.getCors().setAllowedOrigins(null);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    public void testCorsFilterDeactivated2() throws Exception {
        props.getCors().setAllowedOrigins(new ArrayList<>());
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }
}

18 View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : jhipster

/**
 * Unit tests for the {@link WebConfigurer} clreplaced.
 */
clreplaced WebConfigurerTest {

    private WebConfigurer webConfigurer;

    private MockServletContext servletContext;

    private MockEnvironment env;

    private JHipsterProperties props;

    @BeforeEach
    public void setup() {
        servletContext = spy(new MockServletContext());
        doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
        doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
        env = new MockEnvironment();
        props = new JHipsterProperties();
        webConfigurer = new WebConfigurer(env, props);
    }

    @Test
    void testStartUpProdServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        webConfigurer.onStartup(servletContext);
        verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
    }

    @Test
    void testStartUpDevServletContext() throws ServletException {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
        webConfigurer.onStartup(servletContext);
        verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
    }

    @Test
    void testCustomizeServletContainer() {
        env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
        UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
        webConfigurer.customize(container);
        replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
        replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
        replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
        if (container.getDoreplacedentRoot() != null) {
            replacedertThat(container.getDoreplacedentRoot()).isEqualTo(new File("target/clreplacedes/static/"));
        }
    }

    @Test
    void testCorsFilterOnApiPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
    }

    @Test
    void testCorsFilterOnOtherPath() throws Exception {
        props.getCors().setAllowedOrigins(Collections.singletonList("*"));
        props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        props.getCors().setAllowedHeaders(Collections.singletonList("*"));
        props.getCors().setMaxAge(1800L);
        props.getCors().setAllowCredentials(true);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    void testCorsFilterDeactivated() throws Exception {
        props.getCors().setAllowedOrigins(null);
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }

    @Test
    void testCorsFilterDeactivated2() throws Exception {
        props.getCors().setAllowedOrigins(new ArrayList<>());
        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
        mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
    }
}

18 View Source File : AwsSecretsManagerPropertySourceLocatorTest.java
License : Apache License 2.0
Project Creator : awspring

/**
 * Unit test for {@link AwsSecretsManagerPropertySourceLocator}.
 *
 * @author Anthony Foulfoin
 * @author Matej Nedic
 * @author Maciej Walkowiak.
 */
clreplaced AwsSecretsManagerPropertySourceLocatorTest {

    private AWSSecretsManager smClient = mock(AWSSecretsManager.clreplaced);

    private MockEnvironment env = new MockEnvironment();

    @Test
    void locate_nameSpecifiedInConstructor_returnsPropertySourceWithSpecifiedName() {
        GetSecretValueResult secretValueResult = new GetSecretValueResult();
        secretValueResult.setSecretString("{\"key1\": \"value1\", \"key2\": \"value2\"}");
        when(smClient.getSecretValue(any(GetSecretValueRequest.clreplaced))).thenReturn(secretValueResult);
        AwsSecretsManagerProperties properties = new AwsSecretsManagerProperties();
        AwsSecretsManagerPropertySourceLocator locator = new AwsSecretsManagerPropertySourceLocator("my-name", smClient, properties);
        PropertySource propertySource = locator.locate(env);
        replacedertThat(propertySource.getName()).isEqualTo("my-name");
    }

    @Test
    void locate_nameNotSpecifiedInConstructor_returnsPropertySourceWithDefaultName() {
        GetSecretValueResult secretValueResult = new GetSecretValueResult();
        secretValueResult.setSecretString("{\"key1\": \"value1\", \"key2\": \"value2\"}");
        when(smClient.getSecretValue(any(GetSecretValueRequest.clreplaced))).thenReturn(secretValueResult);
        AwsSecretsManagerProperties properties = new AwsSecretsManagerProperties();
        AwsSecretsManagerPropertySourceLocator locator = new AwsSecretsManagerPropertySourceLocator(smClient, properties);
        PropertySource propertySource = locator.locate(env);
        replacedertThat(propertySource.getName()).isEqualTo("aws-secrets-manager");
    }

    @Test
    void contextExpectedToHave2Elements() {
        AwsSecretsManagerProperties properties = new AwsSecretsManagerPropertiesBuilder().withDefaultContext("application").withName("application").build();
        GetSecretValueResult secretValueResult = new GetSecretValueResult();
        secretValueResult.setSecretString("{\"key1\": \"value1\", \"key2\": \"value2\"}");
        when(smClient.getSecretValue(any(GetSecretValueRequest.clreplaced))).thenReturn(secretValueResult);
        AwsSecretsManagerPropertySourceLocator locator = new AwsSecretsManagerPropertySourceLocator(smClient, properties);
        env.setActiveProfiles("test");
        locator.locate(env);
        replacedertThat(locator.getContexts()).hreplacedize(2);
    }

    @Test
    void contextExpectedToHave4Elements() {
        AwsSecretsManagerProperties properties = new AwsSecretsManagerPropertiesBuilder().withDefaultContext("application").withName("messaging-service").build();
        GetSecretValueResult secretValueResult = new GetSecretValueResult();
        secretValueResult.setSecretString("{\"key1\": \"value1\", \"key2\": \"value2\"}");
        when(smClient.getSecretValue(any(GetSecretValueRequest.clreplaced))).thenReturn(secretValueResult);
        AwsSecretsManagerPropertySourceLocator locator = new AwsSecretsManagerPropertySourceLocator(smClient, properties);
        env.setActiveProfiles("test");
        locator.locate(env);
        replacedertThat(locator.getContexts()).hreplacedize(4);
    }

    @Test
    void contextSpecificOrderExpected() {
        AwsSecretsManagerProperties properties = new AwsSecretsManagerPropertiesBuilder().withDefaultContext("application").withName("messaging-service").build();
        GetSecretValueResult secretValueResult = new GetSecretValueResult();
        secretValueResult.setSecretString("{\"key1\": \"value1\", \"key2\": \"value2\"}");
        when(smClient.getSecretValue(any(GetSecretValueRequest.clreplaced))).thenReturn(secretValueResult);
        AwsSecretsManagerPropertySourceLocator locator = new AwsSecretsManagerPropertySourceLocator(smClient, properties);
        env.setActiveProfiles("test");
        locator.locate(env);
        List<String> contextToBeTested = new ArrayList<>(locator.getContexts());
        replacedertThat(contextToBeTested.get(0)).isEqualTo("/secret/messaging-service_test");
        replacedertThat(contextToBeTested.get(1)).isEqualTo("/secret/messaging-service");
        replacedertThat(contextToBeTested.get(2)).isEqualTo("/secret/application_test");
        replacedertThat(contextToBeTested.get(3)).isEqualTo("/secret/application");
    }

    @Test
    void whenFailFastIsTrueAndSecretDoesNotExistThrowsException() {
        AwsSecretsManagerProperties properties = new AwsSecretsManagerProperties();
        properties.setFailFast(true);
        when(smClient.getSecretValue(any(GetSecretValueRequest.clreplaced))).thenThrow(ResourceNotFoundException.clreplaced);
        AwsSecretsManagerPropertySourceLocator locator = new AwsSecretsManagerPropertySourceLocator(smClient, properties);
        replacedertThatThrownBy(() -> locator.locate(env)).isInstanceOf(AwsSecretsManagerPropertySourceNotFoundException.clreplaced);
    }

    @Test
    void whenFailFastIsFalseAndSecretDoesNotExistReturnsEmptyPropertySource() {
        AwsSecretsManagerProperties properties = new AwsSecretsManagerProperties();
        properties.setFailFast(false);
        when(smClient.getSecretValue(any(GetSecretValueRequest.clreplaced))).thenThrow(ResourceNotFoundException.clreplaced);
        AwsSecretsManagerPropertySourceLocator locator = new AwsSecretsManagerPropertySourceLocator(smClient, properties);
        CompositePropertySource result = (CompositePropertySource) locator.locate(env);
        replacedertThat(result.getPropertySources()).isEmpty();
    }

    private final static clreplaced AwsSecretsManagerPropertiesBuilder {

        private final AwsSecretsManagerProperties properties = new AwsSecretsManagerProperties();

        private AwsSecretsManagerPropertiesBuilder() {
        }

        public AwsSecretsManagerPropertiesBuilder withDefaultContext(String defaultContext) {
            this.properties.setDefaultContext(defaultContext);
            return this;
        }

        public AwsSecretsManagerPropertiesBuilder withName(String name) {
            this.properties.setName(name);
            return this;
        }

        public AwsSecretsManagerProperties build() {
            return this.properties;
        }
    }
}

18 View Source File : AwsParamStorePropertySourceLocatorTest.java
License : Apache License 2.0
Project Creator : awspring

/**
 * Unit test for {@link AwsParamStorePropertySourceLocator}.
 *
 * @author Matej Nedic
 * @author Eddú Meléndez
 */
clreplaced AwsParamStorePropertySourceLocatorTest {

    private AWSSimpleSystemsManagement ssmClient = mock(AWSSimpleSystemsManagement.clreplaced);

    private MockEnvironment env = new MockEnvironment();

    @Test
    void contextExpectedToHave2Elements() {
        AwsParamStoreProperties properties = new AwsParamStoreProperties();
        properties.setPrefix("application");
        properties.setName("application");
        GetParametersByPathResult firstResult = getFirstResult();
        GetParametersByPathResult nextResult = getNextResult();
        when(this.ssmClient.getParametersByPath(any(GetParametersByPathRequest.clreplaced))).thenReturn(firstResult, nextResult);
        AwsParamStorePropertySourceLocator locator = new AwsParamStorePropertySourceLocator(this.ssmClient, properties);
        this.env.setActiveProfiles("test");
        locator.locate(this.env);
        replacedertThat(locator.getContexts()).hreplacedize(2);
    }

    @Test
    void contextExpectedToHave4Elements() {
        AwsParamStoreProperties properties = new AwsParamStoreProperties();
        properties.setPrefix("application");
        properties.setName("messaging-service");
        GetParametersByPathResult firstResult = getFirstResult();
        GetParametersByPathResult nextResult = getNextResult();
        when(this.ssmClient.getParametersByPath(any(GetParametersByPathRequest.clreplaced))).thenReturn(firstResult, nextResult);
        AwsParamStorePropertySourceLocator locator = new AwsParamStorePropertySourceLocator(this.ssmClient, properties);
        this.env.setActiveProfiles("test");
        locator.locate(this.env);
        replacedertThat(locator.getContexts()).hreplacedize(4);
    }

    @Test
    void contextSpecificOrderExpected() {
        AwsParamStoreProperties properties = new AwsParamStoreProperties();
        properties.setPrefix("application");
        properties.setName("messaging-service");
        GetParametersByPathResult firstResult = getFirstResult();
        GetParametersByPathResult nextResult = getNextResult();
        when(this.ssmClient.getParametersByPath(any(GetParametersByPathRequest.clreplaced))).thenReturn(firstResult, nextResult);
        AwsParamStorePropertySourceLocator locator = new AwsParamStorePropertySourceLocator(this.ssmClient, properties);
        this.env.setActiveProfiles("test");
        locator.locate(this.env);
        List<String> contextToBeTested = new ArrayList<>(locator.getContexts());
        replacedertThat(contextToBeTested.get(0)).isEqualTo("application/messaging-service_test/");
        replacedertThat(contextToBeTested.get(1)).isEqualTo("application/messaging-service/");
        replacedertThat(contextToBeTested.get(2)).isEqualTo("application/application_test/");
        replacedertThat(contextToBeTested.get(3)).isEqualTo("application/application/");
    }

    @Test
    void whenFailFastIsTrueAndParameterDoesNotExistThrowsException() {
        AwsParamStoreProperties properties = new AwsParamStoreProperties();
        properties.setFailFast(true);
        AwsParamStorePropertySourceLocator locator = new AwsParamStorePropertySourceLocator(this.ssmClient, properties);
        replacedertThatThrownBy(() -> locator.locate(this.env)).isInstanceOf(AwsParameterPropertySourceNotFoundException.clreplaced);
    }

    @Test
    void whenFailFastIsFalseAndParameterDoesNotExistReturnsEmptyPropertySource() {
        AwsParamStoreProperties properties = new AwsParamStoreProperties();
        properties.setFailFast(false);
        AwsParamStorePropertySourceLocator locator = new AwsParamStorePropertySourceLocator(this.ssmClient, properties);
        CompositePropertySource result = (CompositePropertySource) locator.locate(this.env);
        replacedertThat(result.getPropertySources()).isEmpty();
    }

    private static GetParametersByPathResult getNextResult() {
        return new GetParametersByPathResult().withParameters(new Parameter().withName("/config/myservice/key3").withValue("value3"), new Parameter().withName("/config/myservice/key4").withValue("value4"));
    }

    private static GetParametersByPathResult getFirstResult() {
        return new GetParametersByPathResult().withParameters(new Parameter().withName("/config/myservice/key3").withValue("value3"), new Parameter().withName("/config/myservice/key4").withValue("value4"));
    }
}

18 View Source File : ExternalDataSourcePropertiesTest.java
License : Apache License 2.0
Project Creator : alibaba

@Test(expected = IllegalArgumentException.clreplaced)
public void externalDatasourceFailureWithLarkInfo() {
    MockEnvironment environment = new MockEnvironment();
    new ExternalDataSourceProperties().build(environment, null);
}

17 View Source File : ZonkyPostgresDatabaseProviderTest.java
License : Apache License 2.0
Project Creator : zonkyio

@Test
public void providersWithSameConfigurationShouldEquals() {
    MockEnvironment environment = new MockEnvironment();
    environment.setProperty("zonky.test.database.postgres.zonky-provider.preparer-isolation", "database");
    environment.setProperty("zonky.test.database.postgres.initdb.properties.xxx", "xxx-value");
    environment.setProperty("zonky.test.database.postgres.server.properties.yyy", "yyy-value");
    environment.setProperty("zonky.test.database.postgres.client.properties.zzz", "zzz-value");
    ZonkyPostgresDatabaseProvider provider1 = new ZonkyPostgresDatabaseProvider(environment, databaseCustomizers);
    ZonkyPostgresDatabaseProvider provider2 = new ZonkyPostgresDatabaseProvider(environment, databaseCustomizers);
    replacedertThat(provider1).isEqualTo(provider2);
}

17 View Source File : YandexPostgresDatabaseProviderTest.java
License : Apache License 2.0
Project Creator : zonkyio

@Test
public void providersWithSameConfigurationShouldEquals() {
    MockEnvironment environment = new MockEnvironment();
    environment.setProperty("zonky.test.database.postgres.yandex-provider.postgres-version", "postgres-version");
    environment.setProperty("zonky.test.database.postgres.initdb.properties.xxx", "xxx-value");
    environment.setProperty("zonky.test.database.postgres.server.properties.yyy", "yyy-value");
    environment.setProperty("zonky.test.database.postgres.client.properties.zzz", "zzz-value");
    YandexPostgresDatabaseProvider provider1 = new YandexPostgresDatabaseProvider(environment);
    YandexPostgresDatabaseProvider provider2 = new YandexPostgresDatabaseProvider(environment);
    replacedertThat(provider1).isEqualTo(provider2);
}

17 View Source File : OpenTablePostgresDatabaseProviderTest.java
License : Apache License 2.0
Project Creator : zonkyio

@Test
public void providersWithSameConfigurationShouldEquals() {
    MockEnvironment environment = new MockEnvironment();
    environment.setProperty("zonky.test.database.postgres.initdb.properties.xxx", "xxx-value");
    environment.setProperty("zonky.test.database.postgres.server.properties.yyy", "yyy-value");
    environment.setProperty("zonky.test.database.postgres.client.properties.zzz", "zzz-value");
    OpenTablePostgresDatabaseProvider provider1 = new OpenTablePostgresDatabaseProvider(environment, databaseCustomizers);
    OpenTablePostgresDatabaseProvider provider2 = new OpenTablePostgresDatabaseProvider(environment, databaseCustomizers);
    replacedertThat(provider1).isEqualTo(provider2);
}

17 View Source File : DockerPostgresDatabaseProviderTest.java
License : Apache License 2.0
Project Creator : zonkyio

@Test
public void providersWithSameConfigurationShouldEquals() {
    MockEnvironment environment = new MockEnvironment();
    environment.setProperty("zonky.test.database.postgres.docker.image", "test-image");
    environment.setProperty("zonky.test.database.postgres.docker.tmpfs.options", "mount-options");
    environment.setProperty("zonky.test.database.postgres.docker.tmpfs.enabled", "true");
    environment.setProperty("zonky.test.database.postgres.initdb.properties.xxx", "xxx-value");
    environment.setProperty("zonky.test.database.postgres.server.properties.yyy", "yyy-value");
    environment.setProperty("zonky.test.database.postgres.client.properties.zzz", "zzz-value");
    DockerPostgresDatabaseProvider provider1 = new DockerPostgresDatabaseProvider(environment, containerCustomizers);
    DockerPostgresDatabaseProvider provider2 = new DockerPostgresDatabaseProvider(environment, containerCustomizers);
    replacedertThat(provider1).isEqualTo(provider2);
}

17 View Source File : LocalHostWebConnectionHtmlUnitDriverTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void getWhenUrlIsRelativeAndHasPortWillUseLocalhostPort() throws Exception {
    MockEnvironment environment = new MockEnvironment();
    environment.setProperty("local.server.port", "8181");
    LocalHostWebConnectionHtmlUnitDriver driver = new TestLocalHostWebConnectionHtmlUnitDriver(environment);
    driver.get("/test");
    verify(this.webClient).getPage(any(WebWindow.clreplaced), requestToUrl(new URL("http://localhost:8181/test")));
}

17 View Source File : LocalHostUriTemplateHandlerTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void getRootUriShouldUseContextPath() {
    MockEnvironment environment = new MockEnvironment();
    environment.setProperty("server.servlet.context-path", "/foo");
    LocalHostUriTemplateHandler handler = new LocalHostUriTemplateHandler(environment);
    replacedertThat(handler.getRootUri()).isEqualTo("http://localhost:8080/foo");
}

See More Examples