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

feat: Added side-effect-free stubbing framework for SOFABoot applications #1224

Merged
merged 29 commits into from
Aug 25, 2023
Merged
Show file tree
Hide file tree
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…
Aug 8, 2023
e932c0c
perf: Added integration tests
Aug 8, 2023
512881d
perf: Adjust file headers
Aug 8, 2023
bc58c79
Support sofa service duplicate configurable (#1204)
crazysaltfish Jul 26, 2023
c221873
remove SearchStrategy#CURRENT (#1220)
Aug 14, 2023
856d0b5
Support compatibility (#1221)
HzjNeverStop Aug 7, 2023
9ae1c4e
update error logs (#1222)
HzjNeverStop Aug 8, 2023
69c1a68
fix pmd
Aug 14, 2023
9ece04b
fix pmd
Aug 14, 2023
ef62c15
refactor: change package name
Aug 14, 2023
5d5432b
perf: remove dependency for lombok
Aug 14, 2023
9ab3130
refactor: change module name for smoke tests
Aug 14, 2023
469e95d
fix: smoke tests failed
Aug 14, 2023
e171417
refactor: Improved sofa test auto-configuration
Aug 14, 2023
2ee3d7c
refactor: Improve component scan for smoke tests
Aug 14, 2023
74ad7f6
refactor: enforce checkstyle
Aug 14, 2023
b4bce1e
refactor: use Guava Preconditions guard consistently
Aug 14, 2023
8a585b9
update springboot 3.1.2
Aug 14, 2023
ebbe3fc
Merge commit 'refs/pull/1224/head' of https://github.com/sofastack/so…
Aug 14, 2023
4a30116
perf: Added condition for SofaTestAutoConfiguration
Aug 14, 2023
1972afd
update injector mock
Aug 15, 2023
9592a1a
refactor mock
Aug 18, 2023
14529ed
add unit tests for injector mock
Aug 21, 2023
1b0a070
add integration tests
Aug 21, 2023
41e6c38
fix javadoc
Aug 21, 2023
0b8750a
Merge remote-tracking branch 'ym/master' into support_mock
Aug 22, 2023
cf4f26e
update doc
Aug 22, 2023
4e18845
fix ut
Aug 22, 2023
7428693
Merge pull request #1 from HzjNeverStop/support_mock
Peng-YM Aug 25, 2023
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
16 changes: 16 additions & 0 deletions sofa-boot-project/sofa-boot-core/test-sofa-boot/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,22 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
Copy link
Contributor

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 依赖移除,框架代码不能依赖动态代码生成,需要直接编写相应代码

<groupId>com.alipay.sofa</groupId>
<artifactId>runtime-sofa-boot</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>com.alipay.sofa</groupId>
<artifactId>isle-sofa-boot</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
Peng-YM marked this conversation as resolved.
Show resolved Hide resolved
</dependencies>

</project>
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;
Copy link
Contributor

Choose a reason for hiding this comment

The 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 {
}
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);
}
}
}
Loading
Loading