Back to Repositories

Testing Sentinel Data Source Converters in Spring Cloud Alibaba

This test suite validates the Sentinel data source converters in Spring Cloud Alibaba, focusing on JSON and XML conversion functionality for flow rules. It ensures proper data transformation and error handling for Sentinel’s rule configuration system.

Test Coverage Overview

The test suite provides comprehensive coverage of Sentinel’s data conversion capabilities:

  • JSON conversion validation for flow rules
  • XML conversion validation for multiple flow rules
  • Empty content handling
  • Error format detection
  • Invalid content validation

Implementation Analysis

The testing approach employs JUnit Jupiter for structured unit testing, with a focus on converter implementations. It utilizes both JsonConverter and XmlConverter classes with ObjectMapper and XmlMapper respectively, validating various aspects of FlowRule conversion and verification.

The tests follow a pattern of setting up converters, providing input data, and asserting expected outcomes using AssertJ assertions.

Technical Details

Testing infrastructure includes:

  • JUnit Jupiter test framework
  • AssertJ for assertions
  • Jackson ObjectMapper for JSON processing
  • Jackson XmlMapper for XML processing
  • Custom FileUtils for test file reading
  • ResourceUtils for classpath resource handling

Best Practices Demonstrated

The test suite exhibits several testing best practices:

  • Isolated test methods for specific functionality
  • Comprehensive error case coverage
  • Clear test method naming
  • Proper exception testing
  • Consistent assertion patterns
  • Resource cleanup handling

alibaba/spring-cloud-alibaba

spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/SentinelConverterTests.java

            
/*
 * 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.datasource;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

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.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.junit.jupiter.api.Test;

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

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

/**
 * @author <a href="mailto:[email protected]">Jim</a>
 */
public class SentinelConverterTests {

	private ObjectMapper objectMapper = new ObjectMapper();

	private XmlMapper xmlMapper = new XmlMapper();

	@Test
	public void testJsonConverter() {
		JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class);
		List<FlowRule> flowRules = (List<FlowRule>) jsonConverter
				.convert(readFileContent("classpath: flowrule.json"));

		assertThat(flowRules.size()).isEqualTo(1);
		assertThat(flowRules.get(0).getResource()).isEqualTo("resource");
		assertThat(flowRules.get(0).getLimitApp()).isEqualTo("default");
		assertThat(String.valueOf(flowRules.get(0).getCount())).isEqualTo("1.0");
		assertThat(flowRules.get(0).getControlBehavior())
				.isEqualTo(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
		assertThat(flowRules.get(0).getStrategy())
				.isEqualTo(RuleConstant.STRATEGY_DIRECT);
		assertThat(flowRules.get(0).getGrade()).isEqualTo(RuleConstant.FLOW_GRADE_QPS);
	}

	@Test
	public void testConverterEmptyContent() {
		JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class);
		List<FlowRule> flowRules = (List<FlowRule>) jsonConverter.convert("");
		assertThat(flowRules.size()).isEqualTo(0);
	}

	@Test
	public void testConverterErrorFormat() {
		assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
			JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class);
			jsonConverter
					.convert(readFileContent("classpath: flowrule-errorformat.json"));
		});
	}

	@Test
	public void testConverterErrorContent() {
		assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> {
			JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class);
			jsonConverter
					.convert(readFileContent("classpath: flowrule-errorcontent.json"));
		});
	}

	@Test
	public void testXmlConverter() {
		XmlConverter jsonConverter = new XmlConverter(xmlMapper, FlowRule.class);
		List<FlowRule> flowRules = (List<FlowRule>) jsonConverter
				.convert(readFileContent("classpath: flowrule.xml"));

		assertThat(flowRules.size()).isEqualTo(2);
		assertThat(flowRules.get(0).getResource()).isEqualTo("resource");
		assertThat(flowRules.get(0).getLimitApp()).isEqualTo("default");
		assertThat(String.valueOf(flowRules.get(0).getCount())).isEqualTo("1.0");
		assertThat(flowRules.get(0).getControlBehavior())
				.isEqualTo(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
		assertThat(flowRules.get(0).getStrategy())
				.isEqualTo(RuleConstant.STRATEGY_DIRECT);
		assertThat(flowRules.get(0).getGrade()).isEqualTo(RuleConstant.FLOW_GRADE_QPS);

		assertThat(flowRules.get(1).getResource()).isEqualTo("test");
		assertThat(flowRules.get(1).getLimitApp()).isEqualTo("default");
		assertThat(String.valueOf(flowRules.get(1).getCount())).isEqualTo("1.0");
		assertThat(flowRules.get(1).getControlBehavior())
				.isEqualTo(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
		assertThat(flowRules.get(1).getStrategy())
				.isEqualTo(RuleConstant.STRATEGY_DIRECT);
		assertThat(flowRules.get(1).getGrade()).isEqualTo(RuleConstant.FLOW_GRADE_QPS);
	}

	private String readFileContent(String file) {
		try {
			return FileUtils.readFileToString(
					ResourceUtils.getFile(StringUtils.trimAllWhitespace(file)),
					Charset.defaultCharset());
		}
		catch (IOException e) {
			return "";
		}
	}

}