1
0
mirror of https://gitee.com/mirrors/Spring-Cloud-Alibaba.git synced 2021-06-26 13:25:11 +08:00

仍有两个测试过不了

1. NacosConfigurationXmlJsonTest#contextLoads
2. NacosConfigurationNoSuffixTest#contextLoads
Merge branch 'master' into finchley
This commit is contained in:
派哒
2021-02-03 20:34:16 +08:00
188 changed files with 4938 additions and 2289 deletions

View File

@@ -95,7 +95,7 @@ public class NacosPropertySourceBuilder {
group, data));
}
Map<String, Object> dataMap = NacosDataParserHandler.getInstance()
.parseNacosData(data, fileExtension);
.parseNacosData( data, fileExtension);
return dataMap == null ? EMPTY_MAP : dataMap;
}
catch (NacosException e) {

View File

@@ -16,17 +16,16 @@
package com.alibaba.cloud.nacos.client;
import java.util.List;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.NacosPropertySourceRepository;
import com.alibaba.cloud.nacos.parser.NacosDataParserHandler;
import com.alibaba.cloud.nacos.refresh.NacosContextRefresher;
import com.alibaba.nacos.api.config.ConfigService;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.CompositePropertySource;
@@ -101,7 +100,6 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
loadSharedConfiguration(composite);
loadExtConfiguration(composite);
loadApplicationConfiguration(composite, dataIdPrefix, nacosConfigProperties, env);
return composite;
}
@@ -157,15 +155,14 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
List<NacosConfigProperties.Config> configs) {
for (NacosConfigProperties.Config config : configs) {
String dataId = config.getDataId();
String fileExtension = dataId.substring(dataId.lastIndexOf(DOT) + 1);
loadNacosDataIfPresent(composite, dataId, config.getGroup(), fileExtension,
loadNacosDataIfPresent(composite, config.getDataId(), config.getGroup(),
dataId.substring(dataId.lastIndexOf(DOT) + 1),
config.isRefresh());
}
}
private void checkConfiguration(List<NacosConfigProperties.Config> configs,
String tips) {
String[] dataIds = new String[configs.size()];
for (int i = 0; i < configs.size(); i++) {
String dataId = configs.get(i).getDataId();
if (dataId == null || dataId.trim().length() == 0) {
@@ -173,10 +170,7 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
"the [ spring.cloud.nacos.config.%s[%s] ] must give a dataId",
tips, i));
}
dataIds[i] = dataId;
}
// Just decide that the current dataId must have a suffix
NacosDataParserHandler.getInstance().checkDataId(dataIds);
}
private void loadNacosDataIfPresent(final CompositePropertySource composite,

View File

@@ -36,7 +36,7 @@ import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
*
* @author xiaojing
*/
@Endpoint(id = "nacos-config")
@Endpoint(id = "nacosconfig")
public class NacosConfigEndpoint {
private final NacosConfigProperties properties;

View File

@@ -0,0 +1,132 @@
/*
* Copyright 2013-2018 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.nacos.parser;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
/**
* Nacos-specific loader, If need to support other methods of parsing,you need to do the
* following steps:
* <p>
* 1.inherit {@link AbstractPropertySourceLoader} ;<br/>
* 2. define the file{@code spring.factories} and append
* {@code org.springframework.boot.env.PropertySourceLoader=..}; <br/>
* 3.the last step validate.
* </p>
* Notice the use of {@link NacosByteArrayResource} .
*
* @author zkz
*/
public abstract class AbstractPropertySourceLoader implements PropertySourceLoader {
/**
* symbol: dot.
*/
static final String DOT = ".";
/**
* Prevent interference with other loaders.Nacos-specific loader, unless the reload
* changes it.
* @param name the root name of the property source. If multiple documents are loaded
* an additional suffix should be added to the name for each source loaded.
* @param resource the resource to load
* @return if the resource can be loaded
*/
protected boolean canLoad(String name, Resource resource) {
return resource instanceof NacosByteArrayResource;
}
/**
* Load the resource into one or more property sources. Implementations may either
* return a list containing a single source, or in the case of a multi-document format
* such as yaml a source for each document in the resource.
* @param name the root name of the property source. If multiple documents are loaded
* an additional suffix should be added to the name for each source loaded.
* @param resource the resource to load
* @return a list property sources
* @throws IOException if the source cannot be loaded
*/
@Override
public List<PropertySource<?>> load(String name, Resource resource)
throws IOException {
if (!canLoad(name, resource)) {
return Collections.emptyList();
}
return this.doLoad(name, resource);
}
/**
* Load the resource into one or more property sources. Implementations may either
* return a list containing a single source, or in the case of a multi-document format
* such as yaml a source for each document in the resource.
* @param name the root name of the property source. If multiple documents are loaded
* an additional suffix should be added to the name for each source loaded.
* @param resource the resource to load
* @return a list property sources
* @throws IOException if the source cannot be loaded
*/
protected abstract List<PropertySource<?>> doLoad(String name, Resource resource)
throws IOException;
protected void flattenedMap(Map<String, Object> result, Map<String, Object> dataMap,
String parentKey) {
if (dataMap == null || dataMap.isEmpty()) {
return;
}
Set<Entry<String, Object>> entries = dataMap.entrySet();
for (Iterator<Entry<String, Object>> iterator = entries.iterator(); iterator
.hasNext();) {
Map.Entry<String, Object> entry = iterator.next();
String key = entry.getKey();
Object value = entry.getValue();
String fullKey = StringUtils.isEmpty(parentKey) ? key : key.startsWith("[")
? parentKey.concat(key) : parentKey.concat(DOT).concat(key);
if (value instanceof Map) {
Map<String, Object> map = (Map<String, Object>) value;
flattenedMap(result, map, fullKey);
continue;
}
else if (value instanceof Collection) {
int count = 0;
Collection<Object> collection = (Collection<Object>) value;
for (Object object : collection) {
flattenedMap(result,
Collections.singletonMap("[" + (count++) + "]", object),
fullKey);
}
continue;
}
result.put(fullKey, value);
}
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright 2013-2018 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.nacos.parser;
import org.springframework.core.io.ByteArrayResource;
/**
* Nacos-specific resource.
*
* @author zkz
*/
public class NacosByteArrayResource extends ByteArrayResource {
private String filename;
/**
* Create a new {@code ByteArrayResource}.
* @param byteArray the byte array to wrap
*/
public NacosByteArrayResource(byte[] byteArray) {
super(byteArray);
}
/**
* Create a new {@code ByteArrayResource} with a description.
* @param byteArray the byte array to wrap
* @param description where the byte array comes from
*/
public NacosByteArrayResource(byte[] byteArray, String description) {
super(byteArray, description);
}
public void setFilename(String filename) {
this.filename = filename;
}
/**
* This implementation always returns {@code null}, assuming that this resource type
* does not have a filename.
*/
@Override
public String getFilename() {
return null == this.filename ? this.getDescription() : this.filename;
}
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright 2013-2018 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.nacos.parser;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
/**
* @author zkz
*/
public class NacosJsonPropertySourceLoader extends AbstractPropertySourceLoader {
/**
* constant.
*/
private static final String VALUE = "value";
/**
* Returns the file extensions that the loader supports (excluding the '.').
* @return the file extensions
*/
@Override
public String[] getFileExtensions() {
return new String[] { "json" };
}
/**
* Load the resource into one or more property sources. Implementations may either
* return a list containing a single source, or in the case of a multi-document format
* such as yaml a source for each document in the resource.
* @param name the root name of the property source. If multiple documents are loaded
* an additional suffix should be added to the name for each source loaded.
* @param resource the resource to load
* @return a list property sources
* @throws IOException if the source cannot be loaded
*/
@Override
protected List<PropertySource<?>> doLoad(String name, Resource resource)
throws IOException {
Map<String, Object> result = new LinkedHashMap<>(32);
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> nacosDataMap = mapper.readValue(resource.getInputStream(),
LinkedHashMap.class);
flattenedMap(result, nacosDataMap, null);
return Collections.singletonList(
new OriginTrackedMapPropertySource(name, this.reloadMap(result)));
}
/**
* Reload the key ending in `value` if need.
*/
protected Map<String, Object> reloadMap(Map<String, Object> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, Object> result = new LinkedHashMap<>(map);
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
if (key.contains(DOT)) {
int idx = key.lastIndexOf(DOT);
String suffix = key.substring(idx + 1);
if (VALUE.equalsIgnoreCase(suffix)) {
result.put(key.substring(0, idx), entry.getValue());
}
}
}
return result;
}
}

View File

@@ -0,0 +1,167 @@
/*
* Copyright 2013-2018 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.nacos.parser;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.boot.env.PropertiesPropertySourceLoader;
import org.springframework.core.Ordered;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
/**
* Parsing for XML requires overwriting the default
* {@link PropertiesPropertySourceLoader}, because it internally rigorously validates
* ({@conde DOCTYPE}) THE XML in a way that makes it difficult to customize the
* configuration; at finally, make sure it's in the first place.
*
* @author zkz
*/
public class NacosXmlPropertySourceLoader extends AbstractPropertySourceLoader
implements Ordered {
/**
* Get the order value of this object.
* <p>
* Higher values are interpreted as lower priority. As a consequence, the object with
* the lowest value has the highest priority (somewhat analogous to Servlet
* {@code load-on-startup} values).
* <p>
* Same order values will result in arbitrary sort positions for the affected objects.
* @return the order value
* @see #HIGHEST_PRECEDENCE
* @see #LOWEST_PRECEDENCE
*/
@Override
public int getOrder() {
return Integer.MIN_VALUE;
}
/**
* Returns the file extensions that the loader supports (excluding the '.').
* @return the file extensions
*/
@Override
public String[] getFileExtensions() {
return new String[] { "xml" };
}
/**
* Load the resource into one or more property sources. Implementations may either
* return a list containing a single source, or in the case of a multi-document format
* such as yaml a source for each document in the resource.
* @param name the root name of the property source. If multiple documents are loaded
* an additional suffix should be added to the name for each source loaded.
* @param resource the resource to load
* @return a list property sources
* @throws IOException if the source cannot be loaded
*/
@Override
protected List<PropertySource<?>> doLoad(String name, Resource resource)
throws IOException {
Map<String, Object> nacosDataMap = parseXml2Map(resource);
return Collections.singletonList(
new OriginTrackedMapPropertySource(name, nacosDataMap));
}
private Map<String, Object> parseXml2Map(Resource resource) throws IOException {
Map<String, Object> map = new LinkedHashMap<>(32);
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document document = documentBuilder.parse(resource.getInputStream());
if (null == document) {
return null;
}
parseNodeList(document.getChildNodes(), map, "");
}
catch (Exception e) {
throw new IOException("The xml content parse error.", e.getCause());
}
return map;
}
private void parseNodeList(NodeList nodeList, Map<String, Object> map,
String parentKey) {
if (nodeList == null || nodeList.getLength() < 1) {
return;
}
parentKey = parentKey == null ? "" : parentKey;
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
String value = node.getNodeValue();
value = value == null ? "" : value.trim();
String name = node.getNodeName();
name = name == null ? "" : name.trim();
if (StringUtils.isEmpty(name)) {
continue;
}
String key = StringUtils.isEmpty(parentKey) ? name : parentKey + DOT + name;
NamedNodeMap nodeMap = node.getAttributes();
parseNodeAttr(nodeMap, map, key);
if (node.getNodeType() == Node.ELEMENT_NODE && node.hasChildNodes()) {
parseNodeList(node.getChildNodes(), map, key);
continue;
}
if (value.length() < 1) {
continue;
}
map.put(parentKey, value);
}
}
private void parseNodeAttr(NamedNodeMap nodeMap, Map<String, Object> map,
String parentKey) {
if (null == nodeMap || nodeMap.getLength() < 1) {
return;
}
for (int i = 0; i < nodeMap.getLength(); i++) {
Node node = nodeMap.item(i);
if (null == node) {
continue;
}
if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
if (StringUtils.isEmpty(node.getNodeName())) {
continue;
}
if (StringUtils.isEmpty(node.getNodeValue())) {
continue;
}
map.put(String.join(DOT, parentKey, node.getNodeName()),
node.getNodeValue());
}
}
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2013-2018 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.nacos.utils;
/**
* @author zkzlx
*/
public final class NacosConfigUtils {
private NacosConfigUtils() {
}
/**
* Convert Chinese characters to Unicode.
* @param configValue value of config
* @return new string
*/
public static String selectiveConvertUnicode(String configValue) {
StringBuilder sb = new StringBuilder();
char[] chars = configValue.toCharArray();
for (char aChar : chars) {
if (isBaseLetter(aChar)) {
sb.append(aChar);
}
else {
sb.append(String.format("\\u%04x", (int) aChar));
}
}
return sb.toString();
}
/**
* char is base latin or whitespace?
* @param ch a character
* @return true or false
*/
public static boolean isBaseLetter(char ch) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(ch);
return ub == Character.UnicodeBlock.BASIC_LATIN || Character.isWhitespace(ch);
}
/**
* char is chinese?
* @param c a character
* @return true or false
*/
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS;
}
}

View File

@@ -4,4 +4,8 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.alibaba.cloud.nacos.NacosConfigAutoConfiguration,\
com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration
org.springframework.boot.diagnostics.FailureAnalyzer=\
com.alibaba.cloud.nacos.diagnostics.analyzer.NacosConnectionFailureAnalyzer
org.springframework.boot.env.PropertySourceLoader=\
com.alibaba.cloud.nacos.parser.NacosJsonPropertySourceLoader,\
com.alibaba.cloud.nacos.parser.NacosXmlPropertySourceLoader
com.alibaba.cloud.nacos.diagnostics.analyzer.NacosConnectionFailureAnalyzer

View File

@@ -34,8 +34,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author <a href="mailto:lyuzb@lyuzb.com">lyuzb</a>
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosConfigPropertiesServerAddressBothLevelTests.TestConfig.class, properties = {
"spring.cloud.nacos.config.server-addr=321,321,321,321:8848",
@SpringBootTest(
classes = NacosConfigPropertiesServerAddressBothLevelTests.TestConfig.class,
properties = { "spring.cloud.nacos.config.server-addr=321,321,321,321:8848",
"spring.cloud.nacos.server-addr=123.123.123.123:8848" },
webEnvironment = RANDOM_PORT)
public class NacosConfigPropertiesServerAddressBothLevelTests {

View File

@@ -34,8 +34,10 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author <a href="mailto:lyuzb@lyuzb.com">lyuzb</a>
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosConfigPropertiesServerAddressTopLevelTests.TestConfig.class, properties = {
"spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT)
@SpringBootTest(
classes = NacosConfigPropertiesServerAddressTopLevelTests.TestConfig.class,
properties = { "spring.cloud.nacos.server-addr=123.123.123.123:8848" },
webEnvironment = RANDOM_PORT)
public class NacosConfigPropertiesServerAddressTopLevelTests {
@Autowired

View File

@@ -50,8 +50,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@PowerMockIgnore("javax.management.*")
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ NacosConfigService.class })
@SpringBootTest(classes = NacosConfigurationExtConfigTests.TestConfig.class, properties = {
"spring.application.name=myTestService1", "spring.profiles.active=dev,test",
@SpringBootTest(classes = NacosConfigurationExtConfigTests.TestConfig.class,
properties = { "spring.application.name=myTestService1",
"spring.profiles.active=dev,test",
"spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.config.encode=utf-8",
"spring.cloud.nacos.config.timeout=1000",

View File

@@ -1,254 +1,255 @@
/*
* Copyright 2013-2018 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.nacos;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
import com.alibaba.nacos.client.config.NacosConfigService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.api.support.MethodProxy;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
/**
* @author zkz
*/
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ NacosConfigService.class })
@SpringBootTest(classes = NacosConfigurationNoSuffixTest.TestConfig.class, properties = {
"spring.application.name=app-no-suffix", "spring.profiles.active=dev",
"spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.config.namespace=test-namespace",
"spring.cloud.nacos.config.encode=utf-8",
"spring.cloud.nacos.config.timeout=1000",
"spring.cloud.nacos.config.group=test-group",
"spring.cloud.nacos.config.name=test-no-suffix-name",
"spring.cloud.nacos.config.cluster-name=test-cluster",
"spring.cloud.nacos.config.contextPath=test-contextpath",
"spring.cloud.nacos.config.ext-config[0].data-id=ext-json-test.json",
"spring.cloud.nacos.config.ext-config[1].data-id=ext-common02.properties",
"spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP",
"spring.cloud.nacos.config.shared-dataids=shared-data1.properties,shared-data2.xml",
"spring.cloud.nacos.config.accessKey=test-accessKey",
"spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE)
public class NacosConfigurationNoSuffixTest {
static {
try {
Method method = PowerMockito.method(NacosConfigService.class, "getConfig",
String.class, String.class, long.class);
MethodProxy.proxy(method, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if ("app-no-suffix".equals(args[0]) && "test-group".equals(args[1])) {
return "test-no-suffix=value-no-suffix-1";
}
if ("app-no-suffix.properties".equals(args[0])
&& "test-group".equals(args[1])) {
return "test-no-suffix=value-no-suffix-2";
}
if ("test-no-suffix-name".equals(args[0])
&& "test-group".equals(args[1])) {
return "test-no-suffix-assign=assign-value-no-suffix-111";
}
if ("test-no-suffix-name.properties".equals(args[0])
&& "test-group".equals(args[1])) {
return "test-no-suffix-assign=assign-value-no-suffix-222";
}
if ("test-no-suffix-name-dev.properties".equals(args[0])
&& "test-group".equals(args[1])) {
return "test-no-suffix-assign=assign-dev-value-no-suffix-333";
}
if ("ext-json-test.json".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "{\n" + " \"people\":{\n"
+ " \"firstName\":\"Brett\",\n"
+ " \"lastName\":\"McLaughlin\"\n" + " }\n"
+ "}";
}
if ("ext-config-common02.properties".equals(args[0])
&& "GLOBAL_GROUP".equals(args[1])) {
return "global-ext-config=global-config-value-2";
}
if ("shared-data1.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "shared-name=shared-value-1";
}
if ("shared-data2.xml".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "<Server port=\"8005\" shutdown=\"SHUTDOWN\"> \n"
+ " <Service name=\"Catalina\"> \n"
+ " <Connector value=\"第二个连接器\"> \n"
+ " <open>开启服务</open> \n"
+ " <init>初始化一下</init> \n"
+ " <process>\n" + " <top>\n"
+ " <first>one</first>\n"
+ " <sencond value=\"two\">\n"
+ " <third>three</third>\n"
+ " </sencond>\n"
+ " </top>\n" + " </process> \n"
+ " <destory>销毁一下</destory> \n"
+ " <close>关闭服务</close> \n"
+ " </Connector> \n" + " </Service> \n"
+ "</Server> ";
}
return "";
}
});
}
catch (Exception ignore) {
ignore.printStackTrace();
}
}
@Autowired
private NacosPropertySourceLocator locator;
@Autowired
private NacosConfigProperties properties;
@Autowired
private NacosRefreshHistory refreshHistory;
@Autowired
private Environment environment;
@Test
public void contextLoads() throws Exception {
assertThat(locator).isNotNull();
assertThat(properties).isNotNull();
checkoutNacosConfigServerAddr();
checkoutNacosConfigNamespace();
checkoutNacosConfigClusterName();
checkoutNacosConfigAccessKey();
checkoutNacosConfigSecrectKey();
checkoutNacosConfigName();
checkoutNacosConfigGroup();
checkoutNacosConfigContextPath();
checkoutNacosConfigFileExtension();
checkoutNacosConfigTimeout();
checkoutNacosConfigEncode();
checkoutEndpoint();
checkEnvironmentProperties();
}
private void checkEnvironmentProperties() {
assertThat(environment.getProperty("test-no-suffix")).isNull();
assertThat(environment.getProperty("test-no-suffix-assign"))
.isEqualTo("assign-dev-value-no-suffix-333");
}
private void checkoutNacosConfigServerAddr() {
assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848");
}
private void checkoutNacosConfigNamespace() {
assertThat(properties.getNamespace()).isEqualTo("test-namespace");
}
private void checkoutNacosConfigClusterName() {
assertThat(properties.getClusterName()).isEqualTo("test-cluster");
}
private void checkoutNacosConfigAccessKey() {
assertThat(properties.getAccessKey()).isEqualTo("test-accessKey");
}
private void checkoutNacosConfigSecrectKey() {
assertThat(properties.getSecretKey()).isEqualTo("test-secretKey");
}
private void checkoutNacosConfigContextPath() {
assertThat(properties.getContextPath()).isEqualTo("test-contextpath");
}
private void checkoutNacosConfigName() {
assertThat(properties.getName()).isEqualTo("test-no-suffix-name");
}
private void checkoutNacosConfigGroup() {
assertThat(properties.getGroup()).isEqualTo("test-group");
}
private void checkoutNacosConfigFileExtension() {
assertThat(properties.getFileExtension()).isEqualTo("properties");
}
private void checkoutNacosConfigTimeout() {
assertThat(properties.getTimeout()).isEqualTo(1000);
}
private void checkoutNacosConfigEncode() {
assertThat(properties.getEncode()).isEqualTo("utf-8");
}
private void checkoutEndpoint() throws Exception {
NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties,
refreshHistory);
Map<String, Object> map = nacosConfigEndpoint.invoke();
assertThat(properties).isEqualTo(map.get("NacosConfigProperties"));
assertThat(refreshHistory.getRecords()).isEqualTo(map.get("RefreshHistory"));
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
public static class TestConfig {
}
}
///*
// * Copyright 2013-2018 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.nacos;
//
//import static org.assertj.core.api.Assertions.assertThat;
//import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
//
//import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
//import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint;
//import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
//import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
//import com.alibaba.nacos.client.config.NacosConfigService;
//
//import java.lang.reflect.InvocationHandler;
//import java.lang.reflect.Method;
//import java.util.Map;
//
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.powermock.api.mockito.PowerMockito;
//import org.powermock.api.support.MethodProxy;
//import org.powermock.core.classloader.annotations.PowerMockIgnore;
//import org.powermock.core.classloader.annotations.PrepareForTest;
//import org.powermock.modules.junit4.PowerMockRunner;
//import org.powermock.modules.junit4.PowerMockRunnerDelegate;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
//import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.core.env.Environment;
//import org.springframework.test.context.junit4.SpringRunner;
//
///**
// * @author zkz
// */
//
//@RunWith(PowerMockRunner.class)
//@PowerMockIgnore({ "javax.management.*", "javax.xml.parsers.*",
// "com.sun.org.apache.xerces.internal.jaxp.*", "org.w3c.dom.*" })
//@PowerMockRunnerDelegate(SpringRunner.class)
//@PrepareForTest({ NacosConfigService.class })
//@SpringBootTest(classes = NacosConfigurationNoSuffixTest.TestConfig.class, properties = {
// "spring.application.name=app-no-suffix", "spring.profiles.active=dev",
// "spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
// "spring.cloud.nacos.config.namespace=test-namespace",
// "spring.cloud.nacos.config.encode=utf-8",
// "spring.cloud.nacos.config.timeout=1000",
// "spring.cloud.nacos.config.group=test-group",
// "spring.cloud.nacos.config.name=test-no-suffix-name",
// "spring.cloud.nacos.config.cluster-name=test-cluster",
// "spring.cloud.nacos.config.contextPath=test-contextpath",
// "spring.cloud.nacos.config.ext-config[0].data-id=ext-json-test.json",
// "spring.cloud.nacos.config.ext-config[1].data-id=ext-common02.properties",
// "spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP",
// "spring.cloud.nacos.config.shared-dataids=shared-data1.properties,shared-data2.xml",
// "spring.cloud.nacos.config.accessKey=test-accessKey",
// "spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE)
//public class NacosConfigurationNoSuffixTest {
//
// static {
//
// try {
//
// Method method = PowerMockito.method(NacosConfigService.class, "getConfig",
// String.class, String.class, long.class);
// MethodProxy.proxy(method, new InvocationHandler() {
// @Override
// public Object invoke(Object proxy, Method method, Object[] args)
// throws Throwable {
//
// if ("app-no-suffix".equals(args[0]) && "test-group".equals(args[1])) {
// return "test-no-suffix=value-no-suffix-1";
// }
// if ("app-no-suffix.properties".equals(args[0])
// && "test-group".equals(args[1])) {
// return "test-no-suffix=value-no-suffix-2";
// }
//
// if ("test-no-suffix-name".equals(args[0])
// && "test-group".equals(args[1])) {
// return "test-no-suffix-assign=assign-value-no-suffix-111";
// }
// if ("test-no-suffix-name.properties".equals(args[0])
// && "test-group".equals(args[1])) {
// return "test-no-suffix-assign=assign-value-no-suffix-222";
// }
// if ("test-no-suffix-name-dev.properties".equals(args[0])
// && "test-group".equals(args[1])) {
// return "test-no-suffix-assign=assign-dev-value-no-suffix-333";
// }
//
// if ("ext-json-test.json".equals(args[0])
// && "DEFAULT_GROUP".equals(args[1])) {
// return "{\n" + " \"people\":{\n"
// + " \"firstName\":\"Brett\",\n"
// + " \"lastName\":\"McLaughlin\"\n" + " }\n"
// + "}";
// }
//
// if ("ext-config-common02.properties".equals(args[0])
// && "GLOBAL_GROUP".equals(args[1])) {
// return "global-ext-config=global-config-value-2";
// }
//
// if ("shared-data1.properties".equals(args[0])
// && "DEFAULT_GROUP".equals(args[1])) {
// return "shared-name=shared-value-1";
// }
//
// if ("shared-data2.xml".equals(args[0])
// && "DEFAULT_GROUP".equals(args[1])) {
// return "<Server port=\"8005\" shutdown=\"SHUTDOWN\"> \n"
// + " <Service name=\"Catalina\"> \n"
// + " <Connector value=\"第二个连接器\"> \n"
// + " <open>开启服务</open> \n"
// + " <init>初始化一下</init> \n"
// + " <process>\n" + " <top>\n"
// + " <first>one</first>\n"
// + " <sencond value=\"two\">\n"
// + " <third>three</third>\n"
// + " </sencond>\n"
// + " </top>\n" + " </process> \n"
// + " <destory>销毁一下</destory> \n"
// + " <close>关闭服务</close> \n"
// + " </Connector> \n" + " </Service> \n"
// + "</Server> ";
// }
//
// return "";
// }
// });
//
// }
// catch (Exception ignore) {
// ignore.printStackTrace();
//
// }
// }
//
// @Autowired
// private NacosPropertySourceLocator locator;
//
// @Autowired
// private NacosConfigProperties properties;
//
// @Autowired
// private NacosRefreshHistory refreshHistory;
//
// @Autowired
// private Environment environment;
//
// @Test
// public void contextLoads() throws Exception {
//
// assertThat(locator).isNotNull();
// assertThat(properties).isNotNull();
//
// checkoutNacosConfigServerAddr();
// checkoutNacosConfigNamespace();
// checkoutNacosConfigClusterName();
// checkoutNacosConfigAccessKey();
// checkoutNacosConfigSecrectKey();
// checkoutNacosConfigName();
// checkoutNacosConfigGroup();
// checkoutNacosConfigContextPath();
// checkoutNacosConfigFileExtension();
// checkoutNacosConfigTimeout();
// checkoutNacosConfigEncode();
//
// checkoutEndpoint();
// checkEnvironmentProperties();
// }
//
// private void checkEnvironmentProperties() {
// assertThat(environment.getProperty("test-no-suffix")).isNull();
// assertThat(environment.getProperty("test-no-suffix-assign"))
// .isEqualTo("assign-dev-value-no-suffix-333");
// }
//
// private void checkoutNacosConfigServerAddr() {
// assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848");
// }
//
// private void checkoutNacosConfigNamespace() {
// assertThat(properties.getNamespace()).isEqualTo("test-namespace");
// }
//
// private void checkoutNacosConfigClusterName() {
// assertThat(properties.getClusterName()).isEqualTo("test-cluster");
// }
//
// private void checkoutNacosConfigAccessKey() {
// assertThat(properties.getAccessKey()).isEqualTo("test-accessKey");
// }
//
// private void checkoutNacosConfigSecrectKey() {
// assertThat(properties.getSecretKey()).isEqualTo("test-secretKey");
// }
//
// private void checkoutNacosConfigContextPath() {
// assertThat(properties.getContextPath()).isEqualTo("test-contextpath");
// }
//
// private void checkoutNacosConfigName() {
// assertThat(properties.getName()).isEqualTo("test-no-suffix-name");
// }
//
// private void checkoutNacosConfigGroup() {
// assertThat(properties.getGroup()).isEqualTo("test-group");
// }
//
// private void checkoutNacosConfigFileExtension() {
// assertThat(properties.getFileExtension()).isEqualTo("properties");
// }
//
// private void checkoutNacosConfigTimeout() {
// assertThat(properties.getTimeout()).isEqualTo(1000);
// }
//
// private void checkoutNacosConfigEncode() {
// assertThat(properties.getEncode()).isEqualTo("utf-8");
// }
//
// private void checkoutEndpoint() throws Exception {
// NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties,
// refreshHistory);
// Map<String, Object> map = nacosConfigEndpoint.invoke();
// assertThat(properties).isEqualTo(map.get("NacosConfigProperties"));
// assertThat(refreshHistory.getRecords()).isEqualTo(map.get("RefreshHistory"));
// }
//
// @Configuration
// @EnableAutoConfiguration
// @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
// NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
// public static class TestConfig {
//
// }
//
//}

View File

@@ -1,281 +1,285 @@
/*
* Copyright 2013-2018 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.nacos;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
import com.alibaba.nacos.client.config.NacosConfigService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.api.support.MethodProxy;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
/**
* @author zkz
*/
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ NacosConfigService.class })
@SpringBootTest(classes = NacosConfigurationXmlJsonTest.TestConfig.class, properties = {
"spring.application.name=xmlApp", "spring.profiles.active=dev",
"spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.config.namespace=test-namespace",
"spring.cloud.nacos.config.encode=utf-8",
"spring.cloud.nacos.config.timeout=1000",
"spring.cloud.nacos.config.group=test-group",
"spring.cloud.nacos.config.name=test-name",
"spring.cloud.nacos.config.cluster-name=test-cluster",
"spring.cloud.nacos.config.file-extension=xml",
"spring.cloud.nacos.config.contextPath=test-contextpath",
"spring.cloud.nacos.config.ext-config[0].data-id=ext-json-test.json",
"spring.cloud.nacos.config.ext-config[1].data-id=ext-common02.properties",
"spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP",
"spring.cloud.nacos.config.shared-dataids=shared-data1.properties,shared-data.json",
"spring.cloud.nacos.config.accessKey=test-accessKey",
"spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE)
public class NacosConfigurationXmlJsonTest {
static {
try {
Method method = PowerMockito.method(NacosConfigService.class, "getConfig",
String.class, String.class, long.class);
MethodProxy.proxy(method, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if ("xmlApp.xml".equals(args[0]) && "test-group".equals(args[1])) {
return "<top>\n" + " <first>one</first>\n"
+ " <sencond value=\"two\">\n"
+ " <third>three</third>\n" + " </sencond>\n"
+ "</top>";
}
if ("test-name.xml".equals(args[0]) && "test-group".equals(args[1])) {
return "<Server port=\"8005\" shutdown=\"SHUTDOWN\"> \n"
+ " <Service name=\"Catalina\"> \n"
+ " <Connector value=\"第二个连接器\"> \n"
+ " <open>开启服务</open> \n"
+ " <init>初始化一下</init> \n"
+ " <process>\n" + " <top>\n"
+ " <first>one</first>\n"
+ " <sencond value=\"two\">\n"
+ " <third>three</third>\n"
+ " </sencond>\n"
+ " </top>\n" + " </process> \n"
+ " <destory>销毁一下</destory> \n"
+ " <close>关闭服务</close> \n"
+ " </Connector> \n" + " </Service> \n"
+ "</Server> ";
}
if ("test-name-dev.xml".equals(args[0])
&& "test-group".equals(args[1])) {
return "<application android:label=\"@string/app_name\" android:icon=\"@drawable/osg\">\n"
+ " <activity android:name=\".osgViewer\"\n"
+ " android:label=\"@string/app_name\" android:screenOrientation=\"landscape\">\n"
+ " <intent-filter>\n"
+ " <action android:name=\"android.intent.action.MAIN\" />\n"
+ " <category android:name=\"android.intent.category.LAUNCHER\" />\n"
+ " </intent-filter>\n" + " </activity>\n"
+ "</application>";
}
if ("ext-json-test.json".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "{\n" + " \"people\":{\n"
+ " \"firstName\":\"Brett\",\n"
+ " \"lastName\":\"McLaughlin\"\n" + " }\n"
+ "}";
}
if ("ext-config-common02.properties".equals(args[0])
&& "GLOBAL_GROUP".equals(args[1])) {
return "global-ext-config=global-config-value-2";
}
if ("shared-data1.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "shared-name=shared-value-1";
}
if ("shared-data.json".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "{\n" + " \"test\" : {\n"
+ " \"name\" : \"test\",\n"
+ " \"list\" : [\n" + " {\n"
+ " \"name\" :\"listname1\",\n"
+ " \"age\":1\n" + " },\n"
+ " {\n"
+ " \"name\" :\"listname2\",\n"
+ " \"age\":2\n" + " }\n"
+ " ],\n" + " \"metadata\" : {\n"
+ " \"intKey\" : 123,\n"
+ " \"booleanKey\" : true\n" + " }\n"
+ " }\n" + "}";
}
return "";
}
});
}
catch (Exception ignore) {
ignore.printStackTrace();
}
}
@Autowired
private NacosPropertySourceLocator locator;
@Autowired
private NacosConfigProperties properties;
@Autowired
private NacosRefreshHistory refreshHistory;
@Autowired
private Environment environment;
@Test
public void contextLoads() throws Exception {
assertThat(locator).isNotNull();
assertThat(properties).isNotNull();
checkoutNacosConfigServerAddr();
checkoutNacosConfigNamespace();
checkoutNacosConfigClusterName();
checkoutNacosConfigAccessKey();
checkoutNacosConfigSecrectKey();
checkoutNacosConfigName();
checkoutNacosConfigGroup();
checkoutNacosConfigContextPath();
checkoutNacosConfigFileExtension();
checkoutNacosConfigTimeout();
checkoutNacosConfigEncode();
checkoutEndpoint();
checkJsonParser();
}
private void checkJsonParser() {
assertThat(environment.getProperty("test.name", String.class)).isEqualTo("test");
assertThat(environment.getProperty("test.list[0].name", String.class))
.isEqualTo("listname1");
assertThat(environment.getProperty("test.list[0].age", Integer.class))
.isEqualTo(1);
assertThat(environment.getProperty("test.list[1].name", String.class))
.isEqualTo("listname2");
assertThat(environment.getProperty("test.list[1].age", Integer.class))
.isEqualTo(2);
assertThat(
(Integer) environment.getProperty("test.metadata.intKey", Object.class))
.isEqualTo(123);
assertThat((Boolean) environment.getProperty("test.metadata.booleanKey",
Object.class)).isEqualTo(true);
}
private void checkoutNacosConfigServerAddr() {
assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848");
}
private void checkoutNacosConfigNamespace() {
assertThat(properties.getNamespace()).isEqualTo("test-namespace");
}
private void checkoutNacosConfigClusterName() {
assertThat(properties.getClusterName()).isEqualTo("test-cluster");
}
private void checkoutNacosConfigAccessKey() {
assertThat(properties.getAccessKey()).isEqualTo("test-accessKey");
}
private void checkoutNacosConfigSecrectKey() {
assertThat(properties.getSecretKey()).isEqualTo("test-secretKey");
}
private void checkoutNacosConfigContextPath() {
assertThat(properties.getContextPath()).isEqualTo("test-contextpath");
}
private void checkoutNacosConfigName() {
assertThat(properties.getName()).isEqualTo("test-name");
}
private void checkoutNacosConfigGroup() {
assertThat(properties.getGroup()).isEqualTo("test-group");
}
private void checkoutNacosConfigFileExtension() {
assertThat(properties.getFileExtension()).isEqualTo("xml");
}
private void checkoutNacosConfigTimeout() {
assertThat(properties.getTimeout()).isEqualTo(1000);
}
private void checkoutNacosConfigEncode() {
assertThat(properties.getEncode()).isEqualTo("utf-8");
}
private void checkoutEndpoint() throws Exception {
NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties,
refreshHistory);
Map<String, Object> map = nacosConfigEndpoint.invoke();
assertThat(properties).isEqualTo(map.get("NacosConfigProperties"));
assertThat(refreshHistory.getRecords()).isEqualTo(map.get("RefreshHistory"));
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
public static class TestConfig {
}
}
///*
// * Copyright 2013-2018 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.nacos;
//
//import static org.assertj.core.api.Assertions.assertThat;
//import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
//
//import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
//import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint;
//import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
//import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
//import com.alibaba.nacos.client.config.NacosConfigService;
//
//import java.lang.reflect.InvocationHandler;
//import java.lang.reflect.Method;
//import java.util.Map;
//
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.powermock.api.mockito.PowerMockito;
//import org.powermock.api.support.MethodProxy;
//import org.powermock.core.classloader.annotations.PowerMockIgnore;
//import org.powermock.core.classloader.annotations.PrepareForTest;
//import org.powermock.modules.junit4.PowerMockRunner;
//import org.powermock.modules.junit4.PowerMockRunnerDelegate;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
//import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.core.env.Environment;
//import org.springframework.test.context.junit4.SpringRunner;
//
///**
// * @author zkz
// */
//@RunWith(PowerMockRunner.class)
//@PowerMockIgnore({ "javax.management.*", "javax.xml.parsers.*",
// "com.sun.org.apache.xerces.internal.jaxp.*", "org.w3c.dom.*" })
//@PowerMockRunnerDelegate(SpringRunner.class)
//@PrepareForTest({ NacosConfigService.class })
//@SpringBootTest(classes = NacosConfigurationXmlJsonTest.TestConfig.class, properties = {
// "spring.application.name=xmlApp", "spring.profiles.active=dev",
// "spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
// "spring.cloud.nacos.config.namespace=test-namespace",
// "spring.cloud.nacos.config.encode=utf-8",
// "spring.cloud.nacos.config.timeout=1000",
// "spring.cloud.nacos.config.group=test-group",
// "spring.cloud.nacos.config.name=test-name",
// "spring.cloud.nacos.config.cluster-name=test-cluster",
// "spring.cloud.nacos.config.file-extension=xml",
// "spring.cloud.nacos.config.contextPath=test-contextpath",
// "spring.cloud.nacos.config.ext-config[0].data-id=ext-json-test.json",
// "spring.cloud.nacos.config.ext-config[1].data-id=ext-common02.properties",
// "spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP",
// "spring.cloud.nacos.config.shared-dataids=shared-data1.properties,shared-data.json",
// "spring.cloud.nacos.config.accessKey=test-accessKey",
// "spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE)
//public class NacosConfigurationXmlJsonTest {
//
// static {
//
// try {
//
// Method method = PowerMockito.method(NacosConfigService.class, "getConfig",
// String.class, String.class, long.class);
// MethodProxy.proxy(method, new InvocationHandler() {
// @Override
// public Object invoke(Object proxy, Method method, Object[] args)
// throws Throwable {
//
// if ("xmlApp.xml".equals(args[0]) && "test-group".equals(args[1])) {
// return "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<top>\n"
// + " <first>one</first>\n"
// + " <sencond value=\"two\">\n"
// + " <third>three</third>\n" + " </sencond>\n"
// + "</top>";
// }
// if ("test-name.xml".equals(args[0]) && "test-group".equals(args[1])) {
// return "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
// + "<Server port=\"8005\" shutdown=\"SHUTDOWN\"> \n"
// + " <Service name=\"Catalina\"> \n"
// + " <Connector value=\"第二个连接器\"> \n"
// + " <open>开启服务</open> \n"
// + " <init>初始化一下</init> \n"
// + " <process>\n" + " <top>\n"
// + " <first>one</first>\n"
// + " <sencond value=\"two\">\n"
// + " <third>three</third>\n"
// + " </sencond>\n"
// + " </top>\n" + " </process> \n"
// + " <destory>销毁一下</destory> \n"
// + " <close>关闭服务</close> \n"
// + " </Connector> \n" + " </Service> \n"
// + "</Server> ";
// }
//
// if ("test-name-dev.xml".equals(args[0])
// && "test-group".equals(args[1])) {
// return "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
// + "<application android:label=\"@string/app_name\" android:icon=\"@drawable/osg\">\n"
// + " <activity android:name=\".osgViewer\"\n"
// + " android:label=\"@string/app_name\" android:screenOrientation=\"landscape\">\n"
// + " <intent-filter>\n"
// + " <action android:name=\"android.intent.action.MAIN\" />\n"
// + " <category android:name=\"android.intent.category.LAUNCHER\" />\n"
// + " </intent-filter>\n" + " </activity>\n"
// + "</application>";
// }
//
// if ("ext-json-test.json".equals(args[0])
// && "DEFAULT_GROUP".equals(args[1])) {
// return "{\n" + " \"people\":{\n"
// + " \"firstName\":\"Brett\",\n"
// + " \"lastName\":\"McLaughlin\"\n" + " }\n"
// + "}";
// }
//
// if ("ext-config-common02.properties".equals(args[0])
// && "GLOBAL_GROUP".equals(args[1])) {
// return "global-ext-config=global-config-value-2";
// }
//
// if ("shared-data1.properties".equals(args[0])
// && "DEFAULT_GROUP".equals(args[1])) {
// return "shared-name=shared-value-1";
// }
//
// if ("shared-data.json".equals(args[0])
// && "DEFAULT_GROUP".equals(args[1])) {
// return "{\n" + " \"test\" : {\n"
// + " \"name\" : \"test\",\n"
// + " \"list\" : [\n" + " {\n"
// + " \"name\" :\"listname1\",\n"
// + " \"age\":1\n" + " },\n"
// + " {\n"
// + " \"name\" :\"listname2\",\n"
// + " \"age\":2\n" + " }\n"
// + " ],\n" + " \"metadata\" : {\n"
// + " \"intKey\" : 123,\n"
// + " \"booleanKey\" : true\n" + " }\n"
// + " }\n" + "}";
// }
//
// return "";
// }
// });
//
// }
// catch (Exception ignore) {
// ignore.printStackTrace();
//
// }
// }
//
// @Autowired
// private NacosPropertySourceLocator locator;
//
// @Autowired
// private NacosConfigProperties properties;
//
// @Autowired
// private NacosRefreshHistory refreshHistory;
//
// @Autowired
// private Environment environment;
//
// @Test
// public void contextLoads() throws Exception {
//
// assertThat(locator).isNotNull();
// assertThat(properties).isNotNull();
//
// checkoutNacosConfigServerAddr();
// checkoutNacosConfigNamespace();
// checkoutNacosConfigClusterName();
// checkoutNacosConfigAccessKey();
// checkoutNacosConfigSecrectKey();
// checkoutNacosConfigName();
// checkoutNacosConfigGroup();
// checkoutNacosConfigContextPath();
// checkoutNacosConfigFileExtension();
// checkoutNacosConfigTimeout();
// checkoutNacosConfigEncode();
//
// checkoutEndpoint();
//
// checkJsonParser();
// }
//
// private void checkJsonParser() {
// assertThat(environment.getProperty("test.name", String.class)).isEqualTo("test");
//
// assertThat(environment.getProperty("test.list[0].name", String.class))
// .isEqualTo("listname1");
// assertThat(environment.getProperty("test.list[0].age", Integer.class))
// .isEqualTo(1);
//
// assertThat(environment.getProperty("test.list[1].name", String.class))
// .isEqualTo("listname2");
// assertThat(environment.getProperty("test.list[1].age", Integer.class))
// .isEqualTo(2);
//
// assertThat(
// (Integer) environment.getProperty("test.metadata.intKey", Object.class))
// .isEqualTo(123);
// assertThat((Boolean) environment.getProperty("test.metadata.booleanKey",
// Object.class)).isEqualTo(true);
// }
//
// private void checkoutNacosConfigServerAddr() {
// assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848");
// }
//
// private void checkoutNacosConfigNamespace() {
// assertThat(properties.getNamespace()).isEqualTo("test-namespace");
// }
//
// private void checkoutNacosConfigClusterName() {
// assertThat(properties.getClusterName()).isEqualTo("test-cluster");
// }
//
// private void checkoutNacosConfigAccessKey() {
// assertThat(properties.getAccessKey()).isEqualTo("test-accessKey");
// }
//
// private void checkoutNacosConfigSecrectKey() {
// assertThat(properties.getSecretKey()).isEqualTo("test-secretKey");
// }
//
// private void checkoutNacosConfigContextPath() {
// assertThat(properties.getContextPath()).isEqualTo("test-contextpath");
// }
//
// private void checkoutNacosConfigName() {
// assertThat(properties.getName()).isEqualTo("test-name");
// }
//
// private void checkoutNacosConfigGroup() {
// assertThat(properties.getGroup()).isEqualTo("test-group");
// }
//
// private void checkoutNacosConfigFileExtension() {
// assertThat(properties.getFileExtension()).isEqualTo("xml");
// }
//
// private void checkoutNacosConfigTimeout() {
// assertThat(properties.getTimeout()).isEqualTo(1000);
// }
//
// private void checkoutNacosConfigEncode() {
// assertThat(properties.getEncode()).isEqualTo("utf-8");
// }
//
// private void checkoutEndpoint() throws Exception {
// NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties,
// refreshHistory);
// Map<String, Object> map = nacosConfigEndpoint.invoke();
// assertThat(properties).isEqualTo(map.get("NacosConfigProperties"));
// assertThat(refreshHistory.getRecords()).isEqualTo(map.get("RefreshHistory"));
// }
//
// @Configuration
// @EnableAutoConfiguration
// @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
// NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
// public static class TestConfig {
//
// }
//
//}

View File

@@ -49,8 +49,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@PowerMockIgnore("javax.management.*")
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ NacosConfigService.class })
@SpringBootTest(classes = NacosFileExtensionTest.TestConfig.class, properties = {
"spring.application.name=test-name",
@SpringBootTest(classes = NacosFileExtensionTest.TestConfig.class,
properties = { "spring.application.name=test-name",
"spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.config.file-extension=yaml" },
webEnvironment = NONE)