BatchSourceExecutorTest.java 14.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
/**
 * 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 org.apache.pulsar.functions.source.batch;


import com.google.gson.Gson;
import lombok.Getter;
import org.apache.pulsar.client.api.*;
import org.apache.pulsar.common.io.BatchSourceConfig;
import org.apache.pulsar.functions.api.Record;

import org.apache.pulsar.io.core.BatchPushSource;
import org.apache.pulsar.io.core.BatchSource;
import org.apache.pulsar.io.core.BatchSourceTriggerer;
import org.apache.pulsar.io.core.SourceContext;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CyclicBarrier;
import java.util.function.Consumer;

/**
 * Unit tests for {@link org.apache.pulsar.functions.source.batch.BatchSourceExecutor}
 */
public class BatchSourceExecutorTest {

  public static class TestBatchSource implements BatchSource<String> {
    @Getter
    private static int prepareCount;
    @Getter
    private static int discoverCount;
    @Getter
    private static int recordCount;
57 58
    @Getter
    private static int closeCount;
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    private Record record = Mockito.mock(Record.class);
    public TestBatchSource() { }

    @Override
    public void open(Map<String, Object> config, SourceContext context) throws Exception {
      if (!config.containsKey("foo")) {
        throw new IllegalArgumentException("Bad config passed to TestBatchSource");
      }
    }

    @Override
    public void discover(Consumer<byte[]> taskEater) throws Exception {
      byte[] retval = new byte[10];
      discoverCount++;
      taskEater.accept(retval);
    }

    @Override
    public void prepare(byte[] task) throws Exception {
      prepareCount++;
    }

    @Override
    public Record<String> readNext() throws Exception {
      if (++recordCount % 5 == 0) {
        return null;
      } else {
        return record;
      }
    }

    @Override
    public void close() throws Exception {
92
      closeCount++;
93 94 95 96 97 98 99 100 101 102
    }
  }

  public static class TestBatchPushSource extends BatchPushSource<String> {
    @Getter
    private static int prepareCount;
    @Getter
    private static int discoverCount;
    @Getter
    private static int recordCount;
103 104
    @Getter
    private static int closeCount;
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    private Record record = Mockito.mock(Record.class);
    public TestBatchPushSource() { }

    @Override
    public void open(Map<String, Object> config, SourceContext context) throws Exception {
      if (!config.containsKey("foo")) {
        throw new IllegalArgumentException("Bad config passed to TestBatchPushSource");
      }
    }

    @Override
    public void discover(Consumer<byte[]> taskEater) throws Exception {
      byte[] retval = new byte[10];
      discoverCount++;
      taskEater.accept(retval);
    }

    @Override
    public void prepare(byte[] task) throws Exception {
      prepareCount++;
      for (int i = 0; i < 5; ++i) {
        consume(record);
        ++recordCount;
      }
      consume(null);
    }

    @Override
    public void close() throws Exception {
134
      closeCount++;
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    }
  }

  public static class TestDiscoveryTriggerer implements BatchSourceTriggerer {
    private Consumer<String> trigger;
    private Thread thread;

    public TestDiscoveryTriggerer() { }

    @Override
    public void init(Map<String, Object> config, SourceContext sourceContext) throws Exception {
      if (!config.containsKey("DELAY_MS")) {
        throw new IllegalArgumentException("Bad config passed to TestTriggerer");
      }
    }

    @Override
    public void start(Consumer<String> trigger) {
      this.trigger = trigger;
      thread = new Thread(() -> {
        while(true) {
          try {
            Thread.sleep(100);
            trigger.accept("Triggered");
          } catch (InterruptedException e) {
            break;
          }
        }
      });
      thread.start();
    }

    @Override
    public void stop() {
      if (thread != null) {
        thread.interrupt();
        try {
          thread.join();
        } catch (Exception e) {
        }
      }
    }
  }

  private TestBatchSource testBatchSource;
  private TestBatchPushSource testBatchPushSource;
  private BatchSourceConfig testBatchConfig;
  private Map<String, Object> config;
  private Map<String, Object> pushConfig;
  private BatchSourceExecutor<String> batchSourceExecutor;
  private SourceContext context;
  private ConsumerBuilder consumerBuilder;
  private org.apache.pulsar.client.api.Consumer<byte[]> consumer;
  private TypedMessageBuilder<byte[]> messageBuilder;
  private CyclicBarrier discoveryBarrier;
  private Message<byte[]> discoveredTask;

  private static Map<String, Object> createConfig(String className, BatchSourceConfig batchConfig) {
    Map<String, Object> config = new HashMap<>();
    config.put("foo", "bar");
    config.put(BatchSourceConfig.BATCHSOURCE_CONFIG_KEY, new Gson().toJson(batchConfig));
    config.put(BatchSourceConfig.BATCHSOURCE_CLASSNAME_KEY, className);
    return config;
  }

  private static BatchSourceConfig createBatchSourceConfig() {
    BatchSourceConfig testBatchConfig = new BatchSourceConfig();
    testBatchConfig.setDiscoveryTriggererClassName(TestDiscoveryTriggerer.class.getName());
    Map<String, Object> triggererConfig = new HashMap<>();
    triggererConfig.put("DELAY_MS", 500);
    testBatchConfig.setDiscoveryTriggererConfig(triggererConfig);
    return testBatchConfig;
  }

  @BeforeMethod
  public void setUp() throws Exception {
    testBatchSource = new TestBatchSource();
    testBatchPushSource = new TestBatchPushSource();
    batchSourceExecutor = new BatchSourceExecutor<>();
    testBatchConfig = createBatchSourceConfig();
    config = createConfig(TestBatchSource.class.getName(), testBatchConfig);
    pushConfig = createConfig(TestBatchPushSource.class.getName(), testBatchConfig);
    context = Mockito.mock(SourceContext.class);
    Mockito.doReturn("test-function").when(context).getSourceName();
    Mockito.doReturn("test-namespace").when(context).getNamespace();
    Mockito.doReturn("test-tenant").when(context).getTenant();
    Mockito.doReturn(0).when(context).getInstanceId();
    consumerBuilder = Mockito.mock(ConsumerBuilder.class);
    Mockito.doReturn(consumerBuilder).when(consumerBuilder).subscriptionName(Mockito.any());
    Mockito.doReturn(consumerBuilder).when(consumerBuilder).subscriptionType(Mockito.any());
225
    Mockito.doReturn(consumerBuilder).when(consumerBuilder).properties(Mockito.anyMap());
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    Mockito.doReturn(consumerBuilder).when(consumerBuilder).topic(Mockito.any());
    discoveredTask = Mockito.mock(Message.class);
    consumer = Mockito.mock(org.apache.pulsar.client.api.Consumer.class);
    Mockito.doReturn(discoveredTask).when(consumer).receive();
    Mockito.doReturn(CompletableFuture.completedFuture(consumer)).when(consumerBuilder).subscribeAsync();
    Mockito.doReturn(consumerBuilder).when(context).newConsumerBuilder(Schema.BYTES);
    messageBuilder = Mockito.mock(TypedMessageBuilder.class);
    Mockito.doReturn(messageBuilder).when(messageBuilder).value(Mockito.any());
    Mockito.doReturn(messageBuilder).when(messageBuilder).properties(Mockito.any());
    Mockito.doReturn(messageBuilder).when(context).newOutputMessage(Mockito.anyString(), Mockito.any());

    // Discovery
    discoveryBarrier = new CyclicBarrier(2);
    Mockito.doAnswer(new Answer<MessageId>() {
      @Override public MessageId answer(InvocationOnMock invocation) {
        try {
          discoveryBarrier.await();
        } catch (Exception e) {
          throw new RuntimeException();
        }
        return null;
      }
    }).when(messageBuilder).send();
  }

  @AfterMethod
  public void cleanUp() throws Exception {
    batchSourceExecutor.close();
  }

  @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Batch Configs cannot be found")
  public void testWithoutRightConfig() throws Exception {
    config.clear();
    batchSourceExecutor.open(config, context);
  }

  @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Batch Configs cannot be found")
  public void testPushWithoutRightConfig() throws Exception {
    pushConfig.clear();
    batchSourceExecutor.open(pushConfig, context);
  }

  @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "BatchSourceTriggerer does not implement the correct interface")
  public void testWithoutRightTriggerer() throws Exception {
    testBatchConfig.setDiscoveryTriggererClassName(TestBatchSource.class.getName());
    config.put(BatchSourceConfig.BATCHSOURCE_CONFIG_KEY, new Gson().toJson(testBatchConfig));
    batchSourceExecutor.open(config, context);
  }

  @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "BatchSourceTriggerer does not implement the correct interface")
  public void testPushWithoutRightTriggerer() throws Exception {
    testBatchConfig.setDiscoveryTriggererClassName(TestBatchSource.class.getName());
    pushConfig.put(BatchSourceConfig.BATCHSOURCE_CONFIG_KEY, new Gson().toJson(testBatchConfig));
    batchSourceExecutor.open(pushConfig, context);
  }

  @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Bad config passed to TestTriggerer")
  public void testWithoutRightTriggererConfig() throws Exception {
    Map<String, Object> badConfig = new HashMap<>();
    badConfig.put("something", "else");
    testBatchConfig.setDiscoveryTriggererConfig(badConfig);
    config.put(BatchSourceConfig.BATCHSOURCE_CONFIG_KEY, new Gson().toJson(testBatchConfig));
    batchSourceExecutor.open(config, context);
  }

  @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Bad config passed to TestTriggerer")
  public void testPushWithoutRightTriggererConfig() throws Exception {
    Map<String, Object> badConfig = new HashMap<>();
    badConfig.put("something", "else");
    testBatchConfig.setDiscoveryTriggererConfig(badConfig);
    pushConfig.put(BatchSourceConfig.BATCHSOURCE_CONFIG_KEY, new Gson().toJson(testBatchConfig));
    batchSourceExecutor.open(pushConfig, context);
  }

  @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "BatchSource does not implement the correct interface")
  public void testWithoutRightSource() throws Exception {
    config.put(BatchSourceConfig.BATCHSOURCE_CLASSNAME_KEY, TestDiscoveryTriggerer.class.getName());
    batchSourceExecutor.open(config, context);
  }

  @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "BatchSource does not implement the correct interface")
  public void testPushWithoutRightSource() throws Exception {
    pushConfig.put(BatchSourceConfig.BATCHSOURCE_CLASSNAME_KEY, TestDiscoveryTriggerer.class.getName());
    batchSourceExecutor.open(pushConfig, context);
  }

  @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Bad config passed to TestBatchSource")
  public void testWithoutRightSourceConfig() throws Exception {
    config.remove("foo");
    config.put("something", "else");
    batchSourceExecutor.open(config, context);
  }

  @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Bad config passed to TestBatchPushSource")
  public void testPushWithoutRightSourceConfig() throws Exception {
    pushConfig.remove("foo");
    pushConfig.put("something", "else");
    batchSourceExecutor.open(pushConfig, context);
  }

  @Test
  public void testOpenWithRightSource() throws Exception {
    batchSourceExecutor.open(config, context);
  }

  @Test
  public void testPushOpenWithRightSource() throws Exception {
    batchSourceExecutor.open(pushConfig, context);
  }

  @Test
  public void testLifeCycle() throws Exception {
    batchSourceExecutor.open(config, context);
    Assert.assertTrue(testBatchSource.getDiscoverCount() < 1);
    discoveryBarrier.await();
    Assert.assertTrue(testBatchSource.getDiscoverCount() >= 1);
    Assert.assertTrue(testBatchSource.getDiscoverCount() <= 2);
    for (int i = 0; i < 5; ++i) {
      batchSourceExecutor.read();
    }
    Assert.assertEquals(testBatchSource.getRecordCount(), 6);
    Assert.assertTrue(testBatchSource.getDiscoverCount() >= 1);
    Assert.assertTrue(testBatchSource.getDiscoverCount() <= 2);
    discoveryBarrier.await();
    Assert.assertTrue(testBatchSource.getDiscoverCount() >= 2);
    Assert.assertTrue(testBatchSource.getDiscoverCount() <= 3);
352 353
    batchSourceExecutor.close();
    Assert.assertEquals(testBatchSource.getCloseCount(), 1);
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
  }

  @Test
  public void testPushLifeCycle() throws Exception {
    batchSourceExecutor.open(pushConfig, context);
    Assert.assertTrue(testBatchPushSource.getDiscoverCount() < 1);
    discoveryBarrier.await();
    Assert.assertTrue(testBatchPushSource.getDiscoverCount() >= 1);
    Assert.assertTrue(testBatchPushSource.getDiscoverCount() <= 2);
    for (int i = 0; i < 5; ++i) {
      batchSourceExecutor.read();
    }
    Assert.assertEquals(testBatchPushSource.getRecordCount(), 5);
    Assert.assertTrue(testBatchPushSource.getDiscoverCount() >= 1);
    Assert.assertTrue(testBatchPushSource.getDiscoverCount() <= 2);
    discoveryBarrier.await();
    Assert.assertTrue(testBatchPushSource.getDiscoverCount() >= 2);
    Assert.assertTrue(testBatchPushSource.getDiscoverCount() <= 3);
372 373
    batchSourceExecutor.close();
    Assert.assertEquals(testBatchPushSource.getCloseCount(), 1);
374 375
  }
}