-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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
feat: Added side-effect-free stubbing framework for SOFABoot applications #1224
Merged
Merged
Changes from 3 commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
b8eedc6
feat: Added side-effect-free stubbing framework for SOFABoot applicat…
e932c0c
perf: Added integration tests
512881d
perf: Adjust file headers
bc58c79
Support sofa service duplicate configurable (#1204)
crazysaltfish c221873
remove SearchStrategy#CURRENT (#1220)
856d0b5
Support compatibility (#1221)
HzjNeverStop 9ae1c4e
update error logs (#1222)
HzjNeverStop 69c1a68
fix pmd
9ece04b
fix pmd
ef62c15
refactor: change package name
5d5432b
perf: remove dependency for lombok
9ab3130
refactor: change module name for smoke tests
469e95d
fix: smoke tests failed
e171417
refactor: Improved sofa test auto-configuration
2ee3d7c
refactor: Improve component scan for smoke tests
74ad7f6
refactor: enforce checkstyle
b4bce1e
refactor: use Guava Preconditions guard consistently
8a585b9
update springboot 3.1.2
ebbe3fc
Merge commit 'refs/pull/1224/head' of https://github.com/sofastack/so…
4a30116
perf: Added condition for SofaTestAutoConfiguration
1972afd
update injector mock
9592a1a
refactor mock
14529ed
add unit tests for injector mock
1b0a070
add integration tests
41e6c38
fix javadoc
0b8750a
Merge remote-tracking branch 'ym/master' into support_mock
cf4f26e
update doc
4e18845
fix ut
7428693
Merge pull request #1 from HzjNeverStop/support_mock
Peng-YM File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
29 changes: 29 additions & 0 deletions
29
...e/test-sofa-boot/src/main/java/com/alipay/sofa/testing/SofaBootTestAutoConfiguration.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one or more | ||
* contributor license agreements. See the NOTICE file distributed with | ||
* this work for additional information regarding copyright ownership. | ||
* The ASF licenses this file to You 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 | ||
* | ||
* http://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.alipay.sofa.testing; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 包名统一修改为 com.alipay.sofa.test,和spring的风格保持一致,用 test 而不是 testing
Peng-YM marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
import org.springframework.context.annotation.ComponentScan; | ||
import org.springframework.context.annotation.Configuration; | ||
|
||
/** | ||
* @author pengym | ||
* @version SofaTestAutoConfiguration.java, v 0.1 2023年08月07日 15:45 pengym | ||
*/ | ||
@Configuration | ||
@ComponentScan(basePackages = "com.alipay.sofa.testing") | ||
Peng-YM marked this conversation as resolved.
Show resolved
Hide resolved
Peng-YM marked this conversation as resolved.
Show resolved
Hide resolved
|
||
public class SofaBootTestAutoConfiguration { | ||
} |
277 changes: 277 additions & 0 deletions
277
...e/test-sofa-boot/src/main/java/com/alipay/sofa/testing/SofaBootTestExecutionListener.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,277 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one or more | ||
* contributor license agreements. See the NOTICE file distributed with | ||
* this work for additional information regarding copyright ownership. | ||
* The ASF licenses this file to You 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 | ||
* | ||
* http://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.alipay.sofa.testing; | ||
|
||
import com.alipay.sofa.boot.log.SofaBootLoggerFactory; | ||
import com.alipay.sofa.runtime.api.aware.ClientFactoryAware; | ||
import com.alipay.sofa.runtime.api.client.ClientFactory; | ||
import com.alipay.sofa.testing.model.definition.MockDefinition; | ||
import com.alipay.sofa.testing.model.definition.StubDefinition; | ||
import com.alipay.sofa.testing.model.stub.Stub; | ||
import com.alipay.sofa.testing.parser.SofaBootTestAnnotationParser; | ||
import com.alipay.sofa.testing.resolver.SofaBootReferenceResolver; | ||
import com.google.common.base.Preconditions; | ||
import org.slf4j.Logger; | ||
import org.springframework.core.Ordered; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.test.context.TestContext; | ||
import org.springframework.test.context.support.AbstractTestExecutionListener; | ||
import org.springframework.util.ReflectionUtils; | ||
|
||
import javax.annotation.Nonnull; | ||
import java.lang.reflect.Field; | ||
import java.util.ArrayList; | ||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.Map.Entry; | ||
import java.util.Set; | ||
|
||
import static java.util.Objects.isNull; | ||
|
||
/** | ||
* @author pengym | ||
* @version SofaBootTestExecutionListener.java, v 0.1 2023年08月07日 15:51 pengym | ||
*/ | ||
@Component | ||
Peng-YM marked this conversation as resolved.
Show resolved
Hide resolved
|
||
public class SofaBootTestExecutionListener extends AbstractTestExecutionListener implements ClientFactoryAware { | ||
private static final Logger LOGGER = SofaBootLoggerFactory | ||
.getLogger(SofaBootTestExecutionListener.class); | ||
private static final String STUBBED_FIELDS = "SOFA_BOOT_STUBBED_FIELDS"; | ||
|
||
private static ClientFactory clientFactory; | ||
|
||
@Override | ||
public int getOrder() { | ||
return Ordered.LOWEST_PRECEDENCE; | ||
} | ||
|
||
@Override | ||
public void prepareTestInstance(@Nonnull TestContext testContext) throws Exception { | ||
info("Executing SofaBootTestExecutionListener#prepareTestInstance ..."); | ||
|
||
// Initialize SofaBootReferenceResolver | ||
SofaBootReferenceResolver.init(testContext, clientFactory); | ||
|
||
// Reset all stubs | ||
StubbedField.resetAll(); | ||
|
||
// Parse annotations | ||
SofaBootTestAnnotationParser parser = new SofaBootTestAnnotationParser(); | ||
Map<StubDefinition, Set<Stub>> definitions = parser.parse(testContext.getTestClass()); | ||
List<StubbedField> stubbedFields = new ArrayList<>(); | ||
|
||
// Register fields to be stubbed | ||
for (Entry<StubDefinition, Set<Stub>> entry : definitions.entrySet()) { | ||
StubDefinition stubDefinition = entry.getKey(); | ||
Class<?> stubClass = stubDefinition.extractClass(); | ||
for (Stub target : entry.getValue()) { | ||
registerStubBeanFields(testContext, stubbedFields, stubDefinition, stubClass, target); | ||
} | ||
registerStubTestField(testContext, stubbedFields, stubDefinition, stubClass); | ||
} | ||
|
||
// Persist | ||
testContext.setAttribute(STUBBED_FIELDS, stubbedFields); | ||
super.prepareTestInstance(testContext); | ||
} | ||
|
||
@SuppressWarnings("unchecked") | ||
@Override | ||
public void beforeTestMethod(@Nonnull TestContext testContext) throws Exception { | ||
info("Executing SofaBootTestExecutionListener#beforeTestMethod ..."); | ||
|
||
ArrayList<StubbedField> stubbedFields = (ArrayList<StubbedField>) testContext.getAttribute(STUBBED_FIELDS); | ||
if (isNull(stubbedFields)) { | ||
return; | ||
} | ||
stubbedFields.forEach(field -> field.doStub(testContext)); | ||
super.beforeTestMethod(testContext); | ||
} | ||
|
||
@SuppressWarnings("unchecked") | ||
@Override | ||
public void afterTestMethod(@Nonnull TestContext testContext) throws Exception { | ||
info("Executing SofaBootTestExecutionListener#afterTestMethod ..."); | ||
|
||
ArrayList<StubbedField> stubbedFields = (ArrayList<StubbedField>) testContext.getAttribute(STUBBED_FIELDS); | ||
if (isNull(stubbedFields)) { | ||
return; | ||
} | ||
stubbedFields.forEach(field -> field.doReset(testContext)); | ||
super.afterTestMethod(testContext); | ||
} | ||
|
||
@SuppressWarnings({"rawtypes"}) | ||
private static void registerStubBeanFields(TestContext testContext, List<StubbedField> stubbedFields, | ||
StubDefinition stubDefinition, Class<?> stubClass, Stub target) { | ||
Set targetBeans = target.resolveTargets(testContext); | ||
for (Object bean : targetBeans) { | ||
if (isNull(bean)) {continue;} | ||
|
||
Field beanField = ReflectionUtils.findField(bean.getClass(), stubDefinition.getFieldName(), stubClass); | ||
|
||
if (beanField == null) { | ||
String stubType = (stubDefinition instanceof MockDefinition) ? "mock" : "spy"; | ||
LOGGER.error( | ||
String.format("No fields can be found in Bean [%s] with type [%s] and name [%s], skipped injecting [%s] instance", | ||
bean.getClass(), stubClass, | ||
stubDefinition.getFieldName(), stubType)); | ||
continue; | ||
} | ||
|
||
beanField.setAccessible(true); | ||
|
||
BeanStubbedField stubField = new BeanStubbedField( | ||
stubDefinition, | ||
beanField, | ||
ReflectionUtils.getField(beanField, bean), | ||
bean); | ||
stubbedFields.add(stubField); | ||
} | ||
} | ||
|
||
private static void registerStubTestField(TestContext testContext, List<StubbedField> stubbedFields, StubDefinition stubDefinition, | ||
Class<?> stubClass) { | ||
Field testField = ReflectionUtils.findField(testContext.getTestClass(), stubDefinition.getBeanName(), stubClass); | ||
Preconditions.checkNotNull(testField, | ||
String.format("Cannot find field in testClass: [%s] with type [%s] and/or name [%s]", testContext.getTestClass(), | ||
stubDefinition.getBeanName(), stubClass)); | ||
testField.setAccessible(true); | ||
|
||
TestStubbedField stubField = new TestStubbedField(stubDefinition, testField); | ||
stubbedFields.add(stubField); | ||
} | ||
|
||
@Override | ||
public void setClientFactory(ClientFactory clientFactory) { | ||
if (clientFactory != null) { | ||
SofaBootTestExecutionListener.clientFactory = clientFactory; | ||
} | ||
} | ||
|
||
private static class StubbedField { | ||
/** | ||
* Cache stubs | ||
*/ | ||
protected static Map<StubDefinition, Object> stubs = new HashMap<>(); | ||
|
||
/** | ||
* Perform the stub operation. The default implementation is empty. | ||
* | ||
* @param context {@link TestContext} | ||
*/ | ||
public void doStub(TestContext context) { | ||
// default implementation | ||
} | ||
|
||
/** | ||
* Reset the stubbed field. The default implementation is empty. | ||
* | ||
* @param context {@link TestContext} | ||
*/ | ||
public void doReset(TestContext context) { | ||
// default implementation | ||
} | ||
|
||
public static void resetAll() { | ||
stubs.clear(); | ||
} | ||
} | ||
|
||
private static class BeanStubbedField extends StubbedField { | ||
/** | ||
* Stub Definition | ||
*/ | ||
private final StubDefinition definition; | ||
/** | ||
* Field to be stubbed | ||
*/ | ||
private final Field field; | ||
/** | ||
* The original value of the stubbed field | ||
*/ | ||
private final Object originalValue; | ||
/** | ||
* The bean to be stubbed | ||
*/ | ||
private final Object bean; | ||
|
||
public BeanStubbedField(StubDefinition definition, Field field, Object originalValue, Object bean) { | ||
this.definition = definition; | ||
this.field = field; | ||
this.originalValue = originalValue; | ||
this.bean = bean; | ||
} | ||
|
||
@Override | ||
public void doStub(TestContext context) { | ||
Object stub = stubs.get(definition); | ||
if (isNull(stub)) { | ||
// Extract the proxied object before creating stubs. This is to ensure that the stubbing does actually work. | ||
Object extracted = SofaBootReferenceResolver.extractProxiedObject(originalValue); | ||
stub = definition.create(extracted); | ||
stubs.put(definition, stub); | ||
} | ||
|
||
ReflectionUtils.setField(field, bean, stub); | ||
|
||
String stubType = (definition instanceof MockDefinition) ? "Mocked" : "Spied"; | ||
info(String.format("%s field [%s] for bean [%s] with value [%s]", stubType, field, bean, stub)); | ||
} | ||
|
||
@Override | ||
public void doReset(TestContext context) { | ||
ReflectionUtils.setField(field, bean, originalValue); | ||
|
||
info(String.format("Reset field [%s] for bean [%s]", field, bean)); | ||
} | ||
} | ||
|
||
private static class TestStubbedField extends StubbedField { | ||
/** | ||
* Stub Definition | ||
*/ | ||
private final StubDefinition definition; | ||
/** | ||
* Field to be stubbed | ||
*/ | ||
private final Field field; | ||
|
||
public TestStubbedField(StubDefinition stubDefinition, Field testField) { | ||
this.definition = stubDefinition; | ||
this.field = testField; | ||
} | ||
|
||
@Override | ||
public void doStub(TestContext context) { | ||
Object stub = stubs.get(definition); | ||
|
||
if (isNull(stub)) { | ||
stub = definition.create(null); | ||
stubs.put(definition, stub); | ||
} | ||
ReflectionUtils.setField(field, context.getTestInstance(), stub); | ||
} | ||
} | ||
|
||
private static void info(String format, Object... args) { | ||
if (LOGGER.isInfoEnabled()) { | ||
LOGGER.info(format, args); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
runtime-sofa-boot 和 isle-sofa-boot 设置 true,test 功能和这两个不强耦合
commons-lang3 依赖移除,替换为 spring 自己的工具类
lombok 依赖移除,框架代码不能依赖动态代码生成,需要直接编写相应代码