Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add test for spring-cloud-alibaba-sentinel-gateway #3825

Merged
merged 1 commit into from
Aug 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,11 @@
<optional>true</optional>
</dependency>


<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-extension</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.alibaba.cloud.sentinel.gateway;

import org.junit.Assert;
import org.junit.Test;

public class ConfigConstantsTest {
@Test
public void testConfigConstants() {
Assert.assertEquals("11", ConfigConstants.APP_TYPE_SCG_GATEWAY);
Assert.assertEquals("spring.cloud.sentinel.scg", ConfigConstants.GATEWAY_PREFIX);
Assert.assertEquals("response", ConfigConstants.FALLBACK_MSG_RESPONSE);
Assert.assertEquals("redirect", ConfigConstants.FALLBACK_REDIRECT);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.alibaba.cloud.sentinel.gateway;

import org.junit.Assert;
import org.junit.Test;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

public class FallbackPropertiesTest {

/**
* Tests the correct setting and retrieval of fallback properties.
* This test case verifies that the FallbackProperties class correctly sets and retrieves
* various properties for fallback responses, including the response mode, redirect URL,
* response body content, HTTP status code, and content type.
*/
@Test
public void testFallbackProperties() {
FallbackProperties properties = new FallbackProperties()
.setMode("response")
.setRedirect("http://example.com")
.setResponseBody("{'message': 'Fallback response'}")
.setResponseStatus(HttpStatus.TOO_EARLY.value())
.setContentType("application/json");

Assert.assertEquals("response", properties.getMode());
Assert.assertEquals("http://example.com", properties.getRedirect());
Assert.assertEquals("{'message': 'Fallback response'}", properties.getResponseBody());
Assert.assertEquals(HttpStatus.TOO_EARLY.value(), properties.getResponseStatus().intValue());
Assert.assertEquals("application/json", properties.getContentType());
}

/**
* This test method checks the default values of a FallbackProperties object.
* It verifies that certain properties are not set (null) and others have default values.
*/
@Test
public void testDefaultValues() {
FallbackProperties properties = new FallbackProperties();
Assert.assertNull(properties.getMode());
Assert.assertNull(properties.getRedirect());
Assert.assertNull(properties.getResponseBody());
Assert.assertEquals(HttpStatus.TOO_MANY_REQUESTS.value(), properties.getResponseStatus().intValue());
Assert.assertEquals(MediaType.APPLICATION_JSON.toString(), properties.getContentType());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.alibaba.cloud.sentinel.gateway;

import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;
import org.junit.Test;

import org.springframework.boot.SpringApplication;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class GatewayEnvironmentPostProcessorTest {
/**
* Tests the custom property source processing logic.
* This test case verifies whether the custom property source is correctly added during the environment post-processing.
* Specifically, it checks if the configuration property "spring.cloud.sentinel.filter.enabled" is properly added.
*/
@Test
public void testPostProcessEnvironment() {
ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class);
MutablePropertySources propertySources = new MutablePropertySources();
when(environment.getPropertySources()).thenReturn(propertySources);

GatewayEnvironmentPostProcessor postProcessor = new GatewayEnvironmentPostProcessor();
postProcessor.postProcessEnvironment(environment, mock(SpringApplication.class));

PropertySource<?> propertySource = propertySources.get("defaultProperties");
Assert.assertNotNull(propertySource);
Assert.assertNotNull(propertySource.getProperty("spring.cloud.sentinel.filter.enabled"));
}

/**
* Tests the logic of processing an environment that already contains a property source.
* This test case simulates an environment with an existing property source and checks if the post-processor can interact correctly with these property sources.
*/
@Test
public void testPostProcessEnvironmentWithExistingPropertySource() {
ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class);
MutablePropertySources propertySources = new MutablePropertySources();
when(environment.getPropertySources()).thenReturn(propertySources);

Map<String, Object> existingProperties = new HashMap<>();
existingProperties.put("existing.property", "value");
MapPropertySource existingPropertySource = new MapPropertySource("defaultProperties", existingProperties);
propertySources.addFirst(existingPropertySource);

GatewayEnvironmentPostProcessor postProcessor = new GatewayEnvironmentPostProcessor();
postProcessor.postProcessEnvironment(environment, mock(SpringApplication.class));

PropertySource<?> propertySource = propertySources.get("defaultProperties");
Assert.assertNotNull(propertySource);
Assert.assertEquals("value", propertySource.getProperty("existing.property"));
Assert.assertEquals("false", propertySource.getProperty("spring.cloud.sentinel.filter.enabled"));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.alibaba.cloud.sentinel.gateway;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;

import com.alibaba.cloud.commons.io.FileUtils;
import com.alibaba.cloud.sentinel.datasource.converter.JsonConverter;
import com.alibaba.cloud.sentinel.datasource.converter.XmlConverter;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

public class SentinelGatewayAutoConfigurationTest {

private SentinelGatewayAutoConfiguration.SentinelConverterConfiguration.SentinelJsonConfiguration json;
private SentinelGatewayAutoConfiguration.SentinelConverterConfiguration.SentinelXmlConfiguration xml;

/**
* Setup method to initialize test configurations.
*/
@Before
public void setup() {
json = new SentinelGatewayAutoConfiguration.SentinelConverterConfiguration.SentinelJsonConfiguration();
xml = new SentinelGatewayAutoConfiguration.SentinelConverterConfiguration.SentinelXmlConfiguration();
}

/**
* Tests the JSON gateway flow rule converter.
* Reads JSON content from a file, converts it to GatewayFlowRule collection, and validates the result.
*/
@Test
public void testJsonGatewayFlowConverter() {
JsonConverter jsonGatewayFlowConverter = json.jsonGatewayFlowConverter();
Collection<GatewayFlowRule> gatewayFlowRules = jsonGatewayFlowConverter.convert(readFileContent("classpath: gatewayflowrule.json"));
Assert.assertEquals(1, gatewayFlowRules.size());
Assert.assertEquals("test", new ArrayList<>(gatewayFlowRules).get(0).getResource());
}

/**
* Tests the JSON API definition converter.
* Reads JSON content from a file, converts it to ApiDefinition collection, and validates the result.
*/
@Test
public void testJsonApiConverter() {
JsonConverter jsonApiConverter = json.jsonApiConverter();
Collection<ApiDefinition> apiDefinitions = jsonApiConverter.convert(readFileContent("classpath: apidefinition.json"));
Assert.assertEquals(1, apiDefinitions.size());
Assert.assertEquals("test", new ArrayList<>(apiDefinitions).get(0).getApiName());
}

/**
* Tests the XML gateway flow rule converter.
* Reads XML content from a file, converts it to GatewayFlowRule collection, and validates the result.
*/
@Test
public void testXmlGatewayFlowConverter() {
XmlConverter xmlGatewayFlowConverter = xml.xmlGatewayFlowConverter();
Collection<GatewayFlowRule> gatewayFlowRules = xmlGatewayFlowConverter.convert(readFileContent("classpath: gatewayflowrule.xml"));
Assert.assertEquals(1, gatewayFlowRules.size());
Assert.assertEquals("test", new ArrayList<>(gatewayFlowRules).get(0).getResource());
}

/**
* Tests the XML API definition converter.
* Reads XML content from a file, converts it to ApiDefinition collection, and validates the result.
*/
@Test
public void testSentinelXmlConfiguration() {
XmlConverter xmlApiConverter = xml.xmlApiConverter();
Collection<ApiDefinition> apiDefinitions = xmlApiConverter.convert(readFileContent("classpath: apidefinition.xml"));
Assert.assertEquals(1, apiDefinitions.size());
Assert.assertEquals("test", new ArrayList<>(apiDefinitions).get(0).getApiName());
}

/**
* Reads the content of a file.
*
* @param file the classpath location of the file
* @return the content of the file as a string
*/
private String readFileContent(String file) {
try {
return FileUtils.readFileToString(
ResourceUtils.getFile(StringUtils.trimAllWhitespace(file)),
Charset.defaultCharset());
}
catch (IOException e) {
return "";
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Copyright 2013-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.alibaba.cloud.sentinel.gateway.scg;

import com.alibaba.cloud.sentinel.gateway.FallbackProperties;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import org.springframework.core.Ordered;

public class SentinelGatewayPropertiesTest {

private SentinelGatewayProperties properties;

@Before
public void setUp() {
properties = new SentinelGatewayProperties();
}

@Test
public void testDefaultOrder() {
Assert.assertEquals(Ordered.HIGHEST_PRECEDENCE, properties.getOrder().intValue());
}

@Test
public void testSetOrder() {
int newOrder = 100;
properties.setOrder(newOrder);
Assert.assertEquals(newOrder, properties.getOrder().intValue());
}

@Test
public void testFallbackPropertiesInitialization() {
Assert.assertNull(properties.getFallback());
}

@Test
public void testSetFallbackProperties() {
FallbackProperties newFallback = new FallbackProperties();
properties.setFallback(newFallback);
Assert.assertSame(newFallback, properties.getFallback());
}
}
Loading
Loading