<commit_before>/*
 * Copyright 2018-present Facebook, Inc.
 *
 * Licensed 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.facebook.buck.support.bgtasks;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import com.facebook.buck.core.model.BuildId;
import com.facebook.buck.support.bgtasks.BackgroundTaskManager.Notification;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class AsyncBackgroundTaskManagerTest {

  @Rule public ExpectedException expectedException = ExpectedException.none();

  private AsyncBackgroundTaskManager manager;
  // tests should pass with arbitrary assignments (within reason) to these values
  private static final int NTHREADS = 3;
  private static final int FIRST_COMMAND_TASKS = 5;
  private static final int SECOND_COMMAND_TASKS = 4;
  private static final long TIMEOUT_MILLIS = 1000;

  @After
  public void tearDown() throws InterruptedException {
    manager.shutdown(5, TimeUnit.SECONDS);
  }

  private ImmutableList<BackgroundTask<TestArgs>> generateWaitingTaskList(
      int nTasks,
      Optional<Exception> failure,
      @Nullable CountDownLatch taskBlocker,
      @Nullable CountDownLatch taskWaiter,
      String name) {
    ImmutableList.Builder<BackgroundTask<TestArgs>> taskList = ImmutableList.builder();
    for (int i = 0; i < nTasks; i++) {
      BackgroundTask<TestArgs> task =
          ImmutableBackgroundTask.<TestArgs>builder()
              .setAction(new TestAction())
              .setActionArgs(new TestArgs(failure, taskBlocker, taskWaiter, null))
              .setName(name)
              .build();
      taskList.add(task);
    }
    return taskList.build();
  }

  private ImmutableList<BackgroundTask<TestArgs>> generateNoWaitingTaskList(
      int nTasks, Optional<Exception> failure, String name) {
    return generateWaitingTaskList(nTasks, failure, null, null, name);
  }

  @Test
  public void testNonInterruptException() {
    manager = AsyncBackgroundTaskManager.of(NTHREADS);
    Exception expectedException = new Exception();
    ImmutableList<BackgroundTask<TestArgs>> taskList =
        generateNoWaitingTaskList(1, Optional.of(expectedException), "failureTask");
    ImmutableList<Future<Void>> futures = schedule(taskList);
    manager.notify(Notification.COMMAND_END);

    for (Future<?> f : futures) {
      assertTrue(f.isDone());
      try {
        f.get();
        fail("Expected an Exception from the task");
      } catch (InterruptedException e) {
        fail("Expected an Exception from the task");
      } catch (ExecutionException e) {
        assertSame(expectedException, e.getCause());
      }
    }

    assertEquals(0, manager.getScheduledTasks().size());
  }

  @Test
  public void testTaskInterrupt() throws InterruptedException {
    manager = AsyncBackgroundTaskManager.of(1);
    BackgroundTask<TestArgs> task =
        ImmutableBackgroundTask.<TestArgs>builder()
            .setAction(new TestAction())
            .setActionArgs(new TestArgs(Optional.empty(), new CountDownLatch(1), null, null))
            .setName("interruptTask")
            .build();
    Future<Void> future = schedule(task);
    manager.shutdown(5, TimeUnit.SECONDS);
    manager.notify(Notification.COMMAND_END);
    assertFalse(future.isCancelled());
    assertFalse(future.isDone());
    assertTrue(manager.isShutDown());
  }<commit_msg>Fix Flakey test in AsyncBackgroundTaskTest<commit_after>/*
 * Copyright 2018-present Facebook, Inc.
 *
 * Licensed 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.facebook.buck.support.bgtasks;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import com.facebook.buck.core.model.BuildId;
import com.facebook.buck.support.bgtasks.BackgroundTaskManager.Notification;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.Optional;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class AsyncBackgroundTaskManagerTest {

  @Rule public ExpectedException expectedException = ExpectedException.none();

  private AsyncBackgroundTaskManager manager;
  // tests should pass with arbitrary assignments (within reason) to these values
  private static final int NTHREADS = 3;
  private static final int FIRST_COMMAND_TASKS = 5;
  private static final int SECOND_COMMAND_TASKS = 4;
  private static final long TIMEOUT_MILLIS = 1000;

  @After
  public void tearDown() throws InterruptedException {
    manager.shutdown(5, TimeUnit.SECONDS);
  }

  private ImmutableList<BackgroundTask<TestArgs>> generateWaitingTaskList(
      int nTasks,
      Optional<Exception> failure,
      @Nullable CountDownLatch taskBlocker,
      @Nullable CountDownLatch taskWaiter,
      String name) {
    ImmutableList.Builder<BackgroundTask<TestArgs>> taskList = ImmutableList.builder();
    for (int i = 0; i < nTasks; i++) {
      BackgroundTask<TestArgs> task =
          ImmutableBackgroundTask.<TestArgs>builder()
              .setAction(new TestAction())
              .setActionArgs(new TestArgs(failure, taskBlocker, taskWaiter, null))
              .setName(name)
              .build();
      taskList.add(task);
    }
    return taskList.build();
  }

  private ImmutableList<BackgroundTask<TestArgs>> generateNoWaitingTaskList(
      int nTasks, Optional<Exception> failure, String name) {
    return generateWaitingTaskList(nTasks, failure, null, null, name);
  }

  @Test
  public void testNonInterruptException() {
    manager = AsyncBackgroundTaskManager.of(NTHREADS);
    Exception expectedException = new Exception();
    ImmutableList<BackgroundTask<TestArgs>> taskList =
        generateNoWaitingTaskList(1, Optional.of(expectedException), "failureTask");
    ImmutableList<Future<Void>> futures = schedule(taskList);
    manager.notify(Notification.COMMAND_END);

    for (Future<?> f : futures) {
      try {
        f.get();
        fail("Expected an Exception from the task");
      } catch (InterruptedException e) {
        fail("Expected an Exception from the task");
      } catch (ExecutionException e) {
        assertSame(expectedException, e.getCause());
      }
    }

    assertEquals(0, manager.getScheduledTasks().size());
  }

  @Test
  public void testTaskInterrupt() throws InterruptedException {
    manager = AsyncBackgroundTaskManager.of(1);
    BackgroundTask<TestArgs> task =
        ImmutableBackgroundTask.<TestArgs>builder()
            .setAction(new TestAction())
            .setActionArgs(new TestArgs(Optional.empty(), new CountDownLatch(1), null, null))
            .setName("interruptTask")
            .build();
    Future<Void> future = schedule(task);
    manager.shutdown(5, TimeUnit.SECONDS);
    manager.notify(Notification.COMMAND_END);
    assertFalse(future.isCancelled());
    assertFalse(future.isDone());
    assertTrue(manager.isShutDown());
  }
{'fraction_non_alphanumeric': 0.09692802484196518, 'fraction_numerical': 0.004879671731174449, 'mean_word_length': 4.035175879396985, 'pattern_counts': {'":': 0, '<': 41, '<?xml version=': 0, '>': 39, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5398238', 'n_tokens_mistral': 2495, 'n_tokens_neox': 2446, 'n_words': 647}