Java Code Examples for com.google.common.util.concurrent.MoreExecutors#newDirectExecutorService()

The following examples show how to use com.google.common.util.concurrent.MoreExecutors#newDirectExecutorService() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HostLocationProviderTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    coreService = createMock(CoreService.class);
    expect(coreService.registerApplication(appId.name()))
            .andReturn(appId).anyTimes();
    replay(coreService);

    provider.cfgService = new ComponentConfigAdapter();
    provider.coreService = coreService;

    provider.providerRegistry = hostRegistry;
    provider.topologyService = topoService;
    provider.packetService = packetService;
    provider.deviceService = deviceService;
    provider.hostService = hostService;
    provider.interfaceService = interfaceService;
    provider.registry = registryAdapter;
    provider.netcfgService = netcfgService;
    provider.activate(CTX_FOR_NO_REMOVE);

    provider.deviceEventHandler = MoreExecutors.newDirectExecutorService();
}
 
Example 2
Source File: StateProviderImplTest.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected AbstractDataBrokerTestCustomizer createDataBrokerTestCustomizer() {
    return new ConcurrentDataBrokerTestCustomizer(true) {
        @Override
        public DOMStore createOperationalDatastore() {
            realOperStore = new InMemoryDOMDataStore("OPER", getDataTreeChangeListenerExecutor());
            spiedOperStore = spy(realOperStore);
            getSchemaService().registerSchemaContextListener(spiedOperStore);
            return spiedOperStore;
        }

        @Override
        public ListeningExecutorService getCommitCoordinatorExecutor() {
            return MoreExecutors.newDirectExecutorService();
        }
    };
}
 
Example 3
Source File: DependencyPingerTest.java    From status with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithToggle() throws Exception {
    final AtomicBoolean toggle = new AtomicBoolean(true);
    final ControlledDependency dependency = ControlledDependency.builder().setToggle(new Supplier<Boolean>() {
        @Override
        public Boolean get() {
            return toggle.get();
        }
    }).build();
    dependency.setInError(true);
    final DependencyPinger pinger = new DependencyPinger(MoreExecutors.newDirectExecutorService(), dependency, systemReporter);

    assertEquals(CheckStatus.OUTAGE, pinger.call().getStatus());
    assertEquals(1, dependency.getTimes());

    pinger.run();
    assertEquals(CheckStatus.OUTAGE, pinger.call().getStatus());
    assertEquals(2, dependency.getTimes());

    toggle.set(false);
    pinger.run();
    assertEquals(CheckStatus.OK, pinger.call().getStatus());
    assertEquals(2, dependency.getTimes());
}
 
Example 4
Source File: PluginBootstrapImplTest.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    MockitoAnnotations.initMocks(this);


    pluginLifecycleHandler = new PluginLifecycleHandlerImpl(hiveMQExtensions, MoreExecutors.newDirectExecutorService());
    pluginBootstrap = new PluginBootstrapImpl(pluginLoader, new SystemInformationImpl(), pluginLifecycleHandler,
            hiveMQExtensions, shutdownHooks,authenticators);
}
 
Example 5
Source File: ResourcePoolTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void exceptionOnResourceUsageWithRetireHandling() throws Exception {
  try (Fixture f =
      new Fixture(/* maxResources */ 1, ResourcePool.ResourceUsageErrorPolicy.RETIRE)) {
    ListeningExecutorService executorService = MoreExecutors.newDirectExecutorService();
    List<ListenableFuture<TestResource>> results =
        Stream.of(0, 1, 2)
            .map(
                i ->
                    f.getPool()
                        .scheduleOperationWithResource(
                            r -> {
                              if (i == 1) {
                                throw new TestException();
                              }
                              return r;
                            },
                            executorService))
            .collect(Collectors.toList());

    Futures.successfulAsList(results).get();

    assertThat(f.getCreatedResources().get(), equalTo(f.getMaxResources() + 1));
    // First request gets the first resource (id == 0), second request errors out causing the
    // resource to be retired and the third request gets a new resource (id == 1).
    assertThat(results.get(0).get().getTestResourceId(), equalTo(0));
    assertThat(results.get(2).get().getTestResourceId(), equalTo(1));
    expectedException.expectCause(Matchers.instanceOf(TestException.class));
    results.get(1).get();
  }
}
 
Example 6
Source File: StartMojo.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private ExecutorService getExecutorService() {
    final ExecutorService executorService;
    if (startParallel) {
        executorService = Executors.newCachedThreadPool();
    } else {
        executorService = MoreExecutors.newDirectExecutorService();
    }
    return executorService;
}
 
Example 7
Source File: FlowRuleManagerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    mgr = new FlowRuleManager();
    mgr.store = new SimpleFlowRuleStore();
    injectEventDispatcher(mgr, new TestEventDispatcher());
    mgr.deviceService = new TestDeviceService();
    mgr.mastershipService = new TestMastershipService();
    mgr.coreService = new TestCoreService();
    mgr.operationsService = MoreExecutors.newDirectExecutorService();
    mgr.deviceInstallers = MoreExecutors.newDirectExecutorService();
    mgr.cfgService = new ComponentConfigAdapter();

    ClusterService mockClusterService = createMock(ClusterService.class);
    NodeId nodeId = new NodeId(NODE_ID);
    MockControllerNode mockControllerNode = new MockControllerNode(nodeId);
    expect(mockClusterService.getLocalNode())
            .andReturn(mockControllerNode).anyTimes();
    replay(mockClusterService);
    mgr.clusterService = mockClusterService;

    service = mgr;
    registry = mgr;

    DriverRegistryManager driverRegistry = new DriverRegistryManager();
    driverService = new TestDriverManager(driverRegistry);
    driverRegistry.addDriver(new DefaultDriver("foo", ImmutableList.of(), "", "", "",
                                               ImmutableMap.of(FlowRuleProgrammable.class,
                                                               TestFlowRuleProgrammable.class),
                                               ImmutableMap.of()));

    mgr.activate(null);
    mgr.addListener(listener);
    provider = new TestProvider(PID);
    providerService = this.registry.register(provider);
    appId = new TestApplicationId(0, "FlowRuleManagerTest");
    assertTrue("provider should be registered",
               this.registry.getProviders().contains(provider.id()));
}
 
Example 8
Source File: LldpLinkProviderTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    deviceBlacklist = new HashSet<>();
    portBlacklist = new HashSet<>();
    cfg = new TestSuppressionConfig();
    coreService = createMock(CoreService.class);
    expect(coreService.registerApplication(appId.name()))
            .andReturn(appId).anyTimes();
    replay(coreService);

    provider.cfgService = new ComponentConfigAdapter();
    provider.enabled = false;
    provider.coreService = coreService;
    provider.cfgRegistry = configRegistry;

    provider.deviceService = deviceService;
    provider.linkService = linkService;
    provider.packetService = packetService;
    provider.providerRegistry = linkRegistry;
    provider.masterService = masterService;
    provider.clusterMetadataService = new ClusterMetadataServiceAdapter();

    provider.activate(null);

    provider.eventExecutor = MoreExecutors.newDirectExecutorService();

    providerService = linkRegistry.registeredProvider();
}
 
Example 9
Source File: RemoteConfigComponentTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  context = RuntimeEnvironment.application;
  directExecutor = MoreExecutors.newDirectExecutorService();

  defaultApp = initializeFirebaseApp(context);

  when(mockFirebaseApp.getOptions())
      .thenReturn(new FirebaseOptions.Builder().setApplicationId(APP_ID).build());
  when(mockFirebaseApp.getName()).thenReturn(FirebaseApp.DEFAULT_APP_NAME);
}
 
Example 10
Source File: MQEventHandlerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    coreService = createMock(CoreService.class);
    expect(coreService.registerApplication(appId.name()))
                      .andReturn(appId).anyTimes();
    replay(coreService);
    mqEventHandler.deviceService = deviceService;
    mqEventHandler.packetService = packetService;
    mqEventHandler.eventExecutor = MoreExecutors.newDirectExecutorService();
    linkService.addListener(testLinkListener);
    mqEventHandler.linkService = linkService;
    mqEventHandler.topologyService = service;
    mqEventHandler.activate(context);
}
 
Example 11
Source File: BitfinexExecutedTradesHandlerTest.java    From bitfinex-v2-wss-api-java with Apache License 2.0 5 votes vote down vote up
/**
 * Test the parsing of one executed trade
 *
 * @throws BitfinexClientException
 * @throws InterruptedException
 */
@Test
public void testExecutedTradesUpdateAndNotify() throws BitfinexClientException, InterruptedException {

    final String callbackValue = "[190631057,1518037080162,0.007,8175.9]";
    final JSONArray jsonArray = new JSONArray(callbackValue);

    final BitfinexExecutedTradeSymbol symbol
            = BitfinexSymbols.executedTrades(BitfinexCurrencyPair.of("BTC", "USD"));

    final ExecutorService executorService = MoreExecutors.newDirectExecutorService();
    final BitfinexWebsocketClient bitfinexApiBroker = Mockito.mock(SimpleBitfinexApiBroker.class);
    Mockito.doReturn(new BitfinexApiCallbackRegistry()).when(bitfinexApiBroker).getCallbacks();
    final QuoteManager quoteManager = new QuoteManager(bitfinexApiBroker, executorService);
    Mockito.when(bitfinexApiBroker.getQuoteManager()).thenReturn(quoteManager);

    quoteManager.registerExecutedTradeCallback(symbol, (s, c) -> {
        Assert.assertEquals(symbol, s);
        Assert.assertEquals(190631057L, (long) c.getTradeId());
        Assert.assertEquals(1518037080162L, (long) c.getTimestamp());
        Assert.assertEquals(0.007, c.getAmount().doubleValue(), DELTA);
        Assert.assertEquals(8175.9, c.getPrice().doubleValue(), DELTA);
    });

    final ExecutedTradeHandler handler = new ExecutedTradeHandler(10, symbol);
    handler.handleChannelData("te", jsonArray);
}
 
Example 12
Source File: DexBuilder.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static void produceDexArchive(
    ZipFile in,
    ZipOutputStream out,
    ExecutorService executor,
    boolean convertOnReaderThread,
    Dexing dexing,
    @Nullable Cache<DexingKey, byte[]> dexCache)
    throws InterruptedException, ExecutionException, IOException {
  // If we only have one thread in executor, we give a "direct" executor to the stuffer, which
  // will convert .class files to .dex inline on the same thread that reads the input jar.
  // This is an optimization that makes sure we can start writing the output file below while
  // the stuffer is still working its way through the input.
  DexConversionEnqueuer enqueuer = new DexConversionEnqueuer(in,
      convertOnReaderThread ? MoreExecutors.newDirectExecutorService() : executor,
      new DexConverter(dexing),
      dexCache);
  Future<?> enqueuerTask = executor.submit(enqueuer);
  while (true) {
    // Wait for next future in the queue *and* for that future to finish.  To guarantee
    // deterministic output we just write out the files in the order they appear, which is
    // the same order as in the input zip.
    ZipEntryContent file = enqueuer.getFiles().take().get();
    if (file == null) {
      // "done" marker indicating no more files coming.
      // Make sure enqueuer terminates normally (any wait should be minimal).  This in
      // particular surfaces any exceptions thrown in the enqueuer.
      enqueuerTask.get();
      break;
    }
    out.putNextEntry(file.getEntry());
    out.write(file.getContent());
    out.closeEntry();
  }
}
 
Example 13
Source File: DependencyPingerTest.java    From status with Apache License 2.0 4 votes vote down vote up
@Test
public void testListener() throws Exception {
    final StatusUpdateListener listener = EasyMock.createMock(StatusUpdateListener.class);
    final ControlledDependency dependency = ControlledDependency.build();
    dependency.setInError(true);
    final DependencyPinger pinger = new DependencyPinger(MoreExecutors.newDirectExecutorService(), dependency, systemReporter);
    pinger.addListener(listener);

    final Capture<CheckResult> original = Capture.newInstance();
    final Capture<CheckResult> updated = Capture.newInstance();
    final Capture<CheckResult> checked = Capture.newInstance();
    EasyMock.reset(listener);
    listener.onChecked(EasyMock.same(pinger), EasyMock.capture(checked));
    listener.onChanged(EasyMock.same(pinger), EasyMock.<CheckResult>isNull(), EasyMock.capture(updated));
    listener.onChecked(EasyMock.same(pinger), EasyMock.capture(checked));
    listener.onChanged(EasyMock.same(pinger), EasyMock.capture(original), EasyMock.capture(updated));
    listener.onChecked(EasyMock.same(pinger), EasyMock.capture(checked));
    listener.onChecked(EasyMock.same(pinger), EasyMock.capture(checked));
    listener.onChanged(EasyMock.same(pinger), EasyMock.capture(original), EasyMock.capture(updated));
    EasyMock.replay(listener);

    dependency.setInError(false);
    pinger.run();
    assertEquals(CheckStatus.OK, updated.getValue().getStatus());
    assertEquals(updated.getValue(), checked.getValue());
    original.setValue(null);
    updated.setValue(null);

    dependency.setInError(true);
    pinger.run();
    assertEquals(CheckStatus.OK, original.getValue().getStatus());
    assertEquals(CheckStatus.MINOR, updated.getValue().getStatus());
    assertEquals(ControlledDependency.EXCEPTION, updated.getValue().getThrowable());
    assertEquals(checked.getValue(), updated.getValue());
    original.setValue(null);
    updated.setValue(null);

    pinger.run(); // no change
    assertNull(original.getValue());
    assertNull(updated.getValue());
    assertEquals(CheckStatus.MINOR, checked.getValue().getStatus());

    pinger.run(); // should change
    assertEquals(CheckStatus.MINOR, original.getValue().getStatus());
    assertEquals(CheckStatus.OUTAGE, updated.getValue().getStatus());
    assertEquals(ControlledDependency.EXCEPTION, updated.getValue().getThrowable());
    assertEquals(checked.getValue(), updated.getValue());
    original.setValue(null);
    updated.setValue(null);

    EasyMock.verify(listener);
}
 
Example 14
Source File: AndroidBinaryGraphEnhancerTest.java    From buck with Apache License 2.0 4 votes vote down vote up
private AndroidBinaryGraphEnhancer createGraphEnhancer(TestGraphEnhancerArgs args) {
  ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
  return new AndroidBinaryGraphEnhancer(
      args.getToolchainProvider(),
      TestCellPathResolver.get(projectFilesystem),
      args.getTarget(),
      projectFilesystem,
      TestAndroidPlatformTargetFactory.create(),
      args.getBuildRuleParams(),
      args.getGraphBuilder(),
      AaptMode.AAPT1,
      ImmutableList.of(),
      args.getResourceCompressionMode(),
      FilterResourcesSteps.ResourceFilter.EMPTY_FILTER,
      /* bannedDuplicateResourceTypes */ EnumSet.noneOf(RType.class),
      Optional.empty(),
      Optional.empty(),
      /* locales */ ImmutableSet.of(),
      /* localizedStringFileName */ null,
      Optional.of(FakeSourcePath.of("AndroidManifest.xml")),
      Optional.empty(),
      Optional.empty(),
      PackageType.DEBUG,
      /* cpuFilters */ ImmutableSet.of(),
      /* shouldBuildStringSourceMap */ false,
      /* shouldPreDex */ args.getShouldPredex(),
      args.getDexSplitMode(),
      /* buildRulesToExcludeFromDex */ args.getBuildRulesToExcludeFromDex(),
      /* resourcesToExclude */ ImmutableSet.of(),
      /* nativeLibsToExclude */ ImmutableSet.of(),
      /* nativeLinkablesToExclude */ ImmutableSet.of(),
      /* nativeLibAssetsToExclude */ ImmutableSet.of(),
      /* nativeLinkableAssetsToExclude */ ImmutableSet.of(),
      /* skipCrunchPngs */ false,
      /* includesVectorDrawables */ false,
      /* noAutoVersionResources */ false,
      /* noVersionTransitionsResources */ false,
      /* noAutoAddOverlayResources */ false,
      /* noResourceRemoval */ false,
      DEFAULT_JAVA_CONFIG,
      JavacFactoryHelper.createJavacFactory(DEFAULT_JAVA_CONFIG),
      ANDROID_JAVAC_OPTIONS,
      args.getExopackageMode(),
      /* buildConfigValues */ BuildConfigFields.of(),
      /* buildConfigValuesFiles */ Optional.empty(),
      XzStep.DEFAULT_COMPRESSION_LEVEL,
      args.getTrimResourceIds(),
      /* keepResourcePattern */ Optional.empty(),
      false,
      /* nativeLibraryMergeMap */ Optional.empty(),
      /* nativeLibraryMergeGlue */ Optional.empty(),
      /* nativeLibraryMergeCodeGenerator */ Optional.empty(),
      /* nativeLibraryProguardConfigGenerator */ Optional.empty(),
      Optional.empty(),
      RelinkerMode.DISABLED,
      ImmutableList.of(),
      MoreExecutors.newDirectExecutorService(),
      /* manifestEntries */ ManifestEntries.empty(),
      CxxPlatformUtils.DEFAULT_CONFIG,
      new APKModuleGraph(TargetGraph.EMPTY, args.getTarget(), Optional.empty()),
      new DxConfig(FakeBuckConfig.builder().build()),
      args.getDexTool(),
      Optional.empty(),
      defaultNonPredexedArgs(),
      ImmutableSortedSet::of,
      /* useProtoFormat */ false,
      new NoopAndroidNativeTargetConfigurationMatcher(),
      /* failOnLegacyAapt2Errors */ false,
      false,
      ImmutableSet.of());
}
 
Example 15
Source File: SQLiteArtifactCacheBenchmark.java    From buck with Apache License 2.0 4 votes vote down vote up
@Ignore
@Test
public void testSingleThreaded() {
  executor = MoreExecutors.newDirectExecutorService();
  runAllBenchmarks();
}
 
Example 16
Source File: DexFileMerger.java    From bazel with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static void buildMergedDexFiles(Options options) throws IOException {
  ListeningExecutorService executor;
  checkArgument(!options.inputArchives.isEmpty(), "Need at least one --input");
  checkArgument(
      options.mainDexListFile == null || options.inputArchives.size() == 1,
      "--main-dex-list only supported with exactly one --input, use DexFileSplitter for more");
  if (options.multidexMode.isMultidexAllowed()) {
    executor = createThreadPool();
  } else {
    checkArgument(
        options.mainDexListFile == null,
        "--main-dex-list is only supported with multidex enabled, but mode is: %s",
        options.multidexMode);
    checkArgument(
        !options.minimalMainDex,
        "--minimal-main-dex is only supported with multidex enabled, but mode is: %s",
        options.multidexMode);
    // We'll only ever merge and write one dex file, so multi-threading is pointless.
    executor = MoreExecutors.newDirectExecutorService();
  }

  ImmutableSet<String> classesInMainDex = options.mainDexListFile != null
      ? ImmutableSet.copyOf(Files.readAllLines(options.mainDexListFile, UTF_8))
      : null;
  PrintStream originalStdOut = System.out;
  try (DexFileAggregator out = createDexFileAggregator(options, executor)) {
    if (!options.verbose) {
      // com.android.dx.merge.DexMerger prints status information to System.out that we silence
      // here unless it was explicitly requested.  (It also prints debug info to DxContext.out,
      // which we populate accordingly below.)
      System.setOut(Dexing.nullout);
    }

    LinkedHashSet<String> seen = new LinkedHashSet<>();
    for (Path inputArchive : options.inputArchives) {
      // Simply merge files from inputs in order.  Doing that with a main dex list doesn't work,
      // but we rule out more than one input with a main dex list above.
      try (ZipFile zip = new ZipFile(inputArchive.toFile())) {
        ArrayList<ZipEntry> dexFiles = filesToProcess(zip);
        if (classesInMainDex == null) {
          processDexFiles(zip, dexFiles, seen, out);
        } else {
          // To honor --main_dex_list make two passes:
          // 1. process only the classes listed in the given file
          // 2. process the remaining files
          Predicate<ZipEntry> mainDexFilter =
              ZipEntryPredicates.classFileFilter(classesInMainDex);
          processDexFiles(zip, Iterables.filter(dexFiles, mainDexFilter), seen, out);
          // Fail if main_dex_list is too big, following dx's example
          checkState(out.getDexFilesWritten() == 0, "Too many classes listed in main dex list "
              + "file %s, main dex capacity exceeded", options.mainDexListFile);
          if (options.minimalMainDex) {
            out.flush(); // Start new .dex file if requested
          }
          processDexFiles(
              zip, Iterables.filter(dexFiles, Predicates.not(mainDexFilter)), seen, out);
        }
      }
    }
  } finally {
    // Kill threads in the pool so we don't hang
    MoreExecutors.shutdownAndAwaitTermination(executor, 1, SECONDS);
    System.setOut(originalStdOut);
  }
}
 
Example 17
Source File: ThriftArtifactCacheTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultiContains() throws IOException {
  AtomicReference<BuckCacheResponse> responseRef = new AtomicReference<>();
  HttpService storeClient = new TestHttpService();
  TestHttpService fetchClient =
      new TestHttpService(() -> new InMemoryThriftResponse(responseRef.get()));
  ProjectFilesystem filesystem =
      TestProjectFilesystems.createProjectFilesystem(tempPaths.getRoot());
  ListeningExecutorService service = MoreExecutors.newDirectExecutorService();
  CellPathResolver cellPathResolver = TestCellPathResolver.get(filesystem);
  NetworkCacheArgs networkArgs =
      ImmutableNetworkCacheArgs.builder()
          .setCacheName("default_cache_name")
          .setRepository("default_repository")
          .setCacheReadMode(CacheReadMode.READONLY)
          .setCacheMode(ArtifactCacheMode.thrift_over_http)
          .setScheduleType("default_schedule_type")
          .setTargetConfigurationSerializer(
              TargetConfigurationSerializerForTests.create(cellPathResolver))
          .setUnconfiguredBuildTargetFactory(
              target ->
                  new ParsingUnconfiguredBuildTargetViewFactory()
                      .create(target, cellPathResolver.getCellNameResolver()))
          .setProjectFilesystem(filesystem)
          .setFetchClient(fetchClient)
          .setStoreClient(storeClient)
          .setBuckEventBus(BuckEventBusForTests.newInstance())
          .setHttpWriteExecutorService(service)
          .setHttpFetchExecutorService(service)
          .setErrorTextTemplate("my super error msg")
          .setErrorTextLimit(100)
          .build();

  com.facebook.buck.core.rulekey.RuleKey key0 =
      new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(0));
  com.facebook.buck.core.rulekey.RuleKey key1 =
      new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(1));
  com.facebook.buck.core.rulekey.RuleKey key2 =
      new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(2));
  com.facebook.buck.core.rulekey.RuleKey key3 =
      new com.facebook.buck.core.rulekey.RuleKey(HashCode.fromInt(3));
  ImmutableSet<com.facebook.buck.core.rulekey.RuleKey> ruleKeys =
      ImmutableSet.of(key0, key1, key2, key3);

  BuckCacheMultiContainsResponse multiContainsResponse = new BuckCacheMultiContainsResponse();
  ContainsResult result0 = new ContainsResult().setResultType(DOES_NOT_CONTAIN);
  ContainsResult result1 = new ContainsResult().setResultType(CONTAINS);
  ContainsResult result2 = new ContainsResult().setResultType(UNKNOWN_DUE_TO_TRANSIENT_ERRORS);
  ContainsResult result3 = new ContainsResult().setResultType(CONTAINS);

  multiContainsResponse.addToResults(result0);
  multiContainsResponse.addToResults(result1);
  multiContainsResponse.addToResults(result2);
  multiContainsResponse.addToResults(result3);

  BuckCacheResponse response =
      new BuckCacheResponse()
          .setWasSuccessful(true)
          .setType(BuckCacheRequestType.CONTAINS)
          .setMultiContainsResponse(multiContainsResponse);
  responseRef.set(response);

  try (ThriftArtifactCache cache =
      new ThriftArtifactCache(
          networkArgs,
          "/nice_as_well",
          new BuildId("aabb"),
          1,
          1,
          false,
          "test://",
          "hostname")) {
    AbstractAsynchronousCache.MultiContainsResult result = cache.multiContainsImpl(ruleKeys);
    assertEquals(4, result.getCacheResults().size());
    assertEquals(CacheResultType.MISS, result.getCacheResults().get(key0).getType());
    assertEquals(CacheResultType.CONTAINS, result.getCacheResults().get(key1).getType());
    assertEquals(CacheResultType.ERROR, result.getCacheResults().get(key2).getType());
    assertEquals(CacheResultType.CONTAINS, result.getCacheResults().get(key3).getType());
  }

  assertEquals(1, fetchClient.getCallsCount());
}
 
Example 18
Source File: ParsePipelineTest.java    From buck with Apache License 2.0 4 votes vote down vote up
private Fixture createSynchronousExecutionFixture(String scenario) throws Exception {
  return new Fixture(
      scenario, MoreExecutors.newDirectExecutorService(), SpeculativeParsing.DISABLED);
}
 
Example 19
Source File: DependencyPingerTest.java    From status with Apache License 2.0 4 votes vote down vote up
@Test
public void testWithUrgencyNone() throws Exception {
    final StatusUpdateListener listener = EasyMock.createMock(StatusUpdateListener.class);
    final ControlledDependency dependency = ControlledDependency.builder().setUrgency(Urgency.NONE).build();
    final DependencyPinger pinger = new DependencyPinger(MoreExecutors.newDirectExecutorService(), dependency, systemReporter);
    pinger.addListener(listener);

    final Capture<CheckResult> original = Capture.newInstance();
    final Capture<CheckResult> updated = Capture.newInstance();
    final Capture<CheckResult> checked = Capture.newInstance();
    EasyMock.reset(listener);

    listener.onChecked(EasyMock.same(pinger), EasyMock.capture(checked));
    listener.onChanged(EasyMock.same(pinger), EasyMock.<CheckResult>isNull(), EasyMock.capture(updated));
    listener.onChecked(EasyMock.same(pinger), EasyMock.capture(checked));
    listener.onChanged(EasyMock.same(pinger), EasyMock.capture(original), EasyMock.capture(updated));
    listener.onChecked(EasyMock.same(pinger), EasyMock.capture(checked));
    listener.onChecked(EasyMock.same(pinger), EasyMock.capture(checked));
    listener.onChanged(EasyMock.same(pinger), EasyMock.capture(original), EasyMock.capture(updated));

    EasyMock.replay(listener);

    dependency.setInError(false);
    pinger.run();
    assertEquals(CheckStatus.OK, pinger.call().getStatus());
    assertEquals(CheckStatus.OK, updated.getValue().getStatus());
    assertEquals(checked.getValue(), updated.getValue());

    dependency.setInError(true);
    pinger.run();
    assertEquals(CheckStatus.MINOR, pinger.call().getStatus());
    assertEquals(CheckStatus.OK, original.getValue().getStatus());
    assertEquals(CheckStatus.MINOR, updated.getValue().getStatus());
    assertEquals(checked.getValue(), updated.getValue());

    dependency.setInError(true);
    pinger.run();
    assertEquals(CheckStatus.MINOR, pinger.call().getStatus());
    // no call to listen
    assertEquals(CheckStatus.MINOR, checked.getValue().getStatus());

    dependency.setInError(true);
    pinger.run();
    assertEquals(CheckStatus.OUTAGE, pinger.call().getStatus());
    assertEquals(CheckStatus.MINOR, original.getValue().getStatus());
    assertEquals(CheckStatus.OUTAGE, updated.getValue().getStatus());
    assertEquals(checked.getValue(), updated.getValue());

    EasyMock.verify(listener);
}
 
Example 20
Source File: ThriftScribeLoggerTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
  logger = null;
  executorService = MoreExecutors.newDirectExecutorService();
}