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

Mockserver #1397

Merged
merged 2 commits into from
Aug 25, 2018
Merged

Mockserver #1397

merged 2 commits into from
Aug 25, 2018

Conversation

weiguang-zz
Copy link
Contributor

@weiguang-zz weiguang-zz commented Aug 23, 2018

apollo的mockserver,基于okhttp提供的mockserver实现。

1. 使用方法

  1. 引入pom依赖
<dependency>
     <artifactId>apollo-mockserver</artifactId>
    <groupId>com.ctrip.framework.apollo</groupId>
    <version>1.1.0-SNAPSHOT</version>
</dependency>

  1. 在test的resources下放置mock的数据,文件名格式约定为 mockdata-{namespace}.properties
    image
  2. 写集成测试类
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
public class SpringIntegrationTest {
  // 启动apollo的mockserver
  @ClassRule
  public static EmbeddedApollo embeddedApollo = new EmbeddedApollo();

  @Test
  @DirtiesContext  // 这个注解很有必要,因为apollo会弄脏应用上下文
  public void testPropertyInject(){
    assertEquals("value1", testBean.key1);
    assertEquals("value2", testBean.key2);
  }

  @Test
  @DirtiesContext
  public void testListenerTriggeredByAdd() throws InterruptedException, ExecutionException, TimeoutException {
    String otherNamespace = "othernamespace";
    embeddedApollo.addOrModifyPropery(otherNamespace,"someKey","someValue");
    ConfigChangeEvent changeEvent = testBean.futureData.get(5000, TimeUnit.MILLISECONDS);
    assertEquals(otherNamespace, changeEvent.getNamespace());
    assertEquals("someValue", changeEvent.getChange("someKey").getNewValue());
  }

  @EnableApolloConfig("application")
  @Configuration
  static class TestConfiguration{
    @Bean
    public TestBean testBean(){
      return new TestBean();
    }
  }

  static class TestBean{
    @Value("${key1:default}")
    String key1;
    @Value("${key2:default}")
    String key2;

    SettableFuture<ConfigChangeEvent> futureData = SettableFuture.create();

    @ApolloConfigChangeListener("othernamespace")
    private void onChange(ConfigChangeEvent changeEvent) {
      futureData.set(changeEvent);
    }
  }

}

2. 实现原理:

    server = new MockWebServer();
    final Dispatcher dispatcher = new Dispatcher() {
      @Override
      public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
        if (request.getPath().startsWith("/services/config")) {
          // 返回mockserver的地址
          return new MockResponse().setResponseCode(200)
              .setBody(mockConfigServiceAddr(listenningUrl));
        } else if (request.getPath().startsWith("/notifications/v2")) {
          // 返回mocked的longpoll数据
          String notifications = request.getRequestUrl().queryParameter("notifications");
          MockResponse response = new MockResponse().setResponseCode(200).setBody(mockLongPollBody(notifications));
          return response;
        } else if (request.getPath().startsWith("/configs")) {
         // 从本地文件读取配置返回
          List<String> pathSegments = request.getRequestUrl().pathSegments();
          String appId = pathSegments.get(1);
          String cluster = pathSegments.get(2);
          String namespace = pathSegments.get(3);
          return new MockResponse().setResponseCode(200)
              .setBody(loadConfigFor(namespace));
        }
        return new MockResponse().setResponseCode(404);
      }
    };

    server.setDispatcher(dispatcher);
    server.start();
    //指定apollo的metaserver地址为localhost
    int port = server.getPort();
    this.listenningUrl = "http://localhost:"+port;

    MockedMetaServerProvider.setAddress(listenningUrl);

    System.setProperty("apollo.longPollingInitialDelayInMills","1");

(cherry picked from commit 9de272b)
@codecov-io
Copy link

Codecov Report

Merging #1397 into master will increase coverage by 7.65%.
The diff coverage is n/a.

Impacted file tree graph

@@             Coverage Diff              @@
##             master    #1397      +/-   ##
============================================
+ Coverage     48.15%   55.81%   +7.65%     
+ Complexity     1781     1038     -743     
============================================
  Files           378      191     -187     
  Lines         10831     5585    -5246     
  Branches       1110      577     -533     
============================================
- Hits           5216     3117    -2099     
+ Misses         5236     2232    -3004     
+ Partials        379      236     -143
Impacted Files Coverage Δ Complexity Δ
...p/framework/apollo/portal/service/ItemService.java
...p/framework/apollo/portal/entity/bo/ReleaseBO.java
...apollo/portal/component/RetryableRestTemplate.java
...ollo/portal/controller/SsoHeartbeatController.java
...o/portal/spi/configuration/EmailConfiguration.java
...al/spi/defaultimpl/DefaultSsoHeartbeatHandler.java
...lo/portal/spi/configuration/AuthConfiguration.java
...o/adminservice/aop/NamespaceAcquireLockAspect.java
...work/apollo/portal/entity/bo/ReleaseHistoryBO.java
...amework/apollo/portal/service/FavoriteService.java
... and 178 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 44a6a7d...bf52eec. Read the comment docs.

@nobodyiam
Copy link
Member

Great! Will take a detailed look soon!

Copy link
Member

@nobodyiam nobodyiam left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@nobodyiam nobodyiam merged commit d762110 into apolloconfig:master Aug 25, 2018
@nobodyiam nobodyiam mentioned this pull request Aug 26, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants