org.jetbrains.annotations.TestOnly Java Examples

The following examples show how to use org.jetbrains.annotations.TestOnly. 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: InjectedLanguageManagerImpl.java    From consulo with Apache License 2.0 7 votes vote down vote up
@TestOnly
public static void checkInjectorsAreDisposed(@Nullable Project project) {
  InjectedLanguageManagerImpl cachedManager = project == null ? null : (InjectedLanguageManagerImpl)project.getUserData(INSTANCE_CACHE);
  if (cachedManager == null) return;

  try {
    ClassMapCachingNulls<MultiHostInjector> cached = cachedManager.cachedInjectors;
    if (cached == null) return;
    for (Map.Entry<Class<?>, MultiHostInjector[]> entry : cached.getBackingMap().entrySet()) {
      Class<?> key = entry.getKey();
      if (cachedManager.myInjectorsClone.isEmpty()) return;
      MultiHostInjector[] oldInjectors = cachedManager.myInjectorsClone.get(key);
      for (MultiHostInjector injector : entry.getValue()) {
        if (ArrayUtil.indexOf(oldInjectors, injector) == -1) {
          throw new AssertionError("Injector was not disposed: " + key + " -> " + injector);
        }
      }
    }
  }
  finally {
    cachedManager.myInjectorsClone.clear();
  }
}
 
Example #2
Source File: Alarm.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * wait for all requests to start execution (i.e. their delay elapses and their run() method, well, runs)
 * and then wait for the execution to finish.
 */
@TestOnly
public void waitForAllExecuted(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
  List<Request> requests;
  synchronized (LOCK) {
    requests = new ArrayList<>(myRequests);
  }

  for (Request request : requests) {
    Future<?> future;
    synchronized (LOCK) {
      future = request.myFuture;
    }
    if (future != null) {
      future.get(timeout, unit);
    }
  }
}
 
Example #3
Source File: NonBlockingReadActionImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@TestOnly
private static void waitForTask(@Nonnull CancellablePromise<?> task) {
  int iteration = 0;
  while (!task.isDone() && iteration++ < 60_000) {
    UIUtil.dispatchAllInvocationEvents();
    try {
      task.blockingGet(1, TimeUnit.MILLISECONDS);
      return;
    }
    catch (TimeoutException ignore) {
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  if (!task.isDone()) {
    //noinspection UseOfSystemOutOrSystemErr
    System.err.println(ThreadDumper.dumpThreadsToString());
    throw new AssertionError("Too long async task");
  }
}
 
Example #4
Source File: SoftWrapModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@TestOnly
void validateState() {
  Document document = myEditor.getDocument();
  if (myEditor.getDocument().isInBulkUpdate()) return;
  FoldingModel foldingModel = myEditor.getFoldingModel();
  List<? extends SoftWrap> softWraps = getRegisteredSoftWraps();
  int lastSoftWrapOffset = -1;
  for (SoftWrap wrap : softWraps) {
    int softWrapOffset = wrap.getStart();
    LOG.assertTrue(softWrapOffset > lastSoftWrapOffset, "Soft wraps are not ordered");
    LOG.assertTrue(softWrapOffset < document.getTextLength(), "Soft wrap is after document's end");
    FoldRegion foldRegion = foldingModel.getCollapsedRegionAtOffset(softWrapOffset);
    LOG.assertTrue(foldRegion == null || foldRegion.getStartOffset() == softWrapOffset, "Soft wrap is inside fold region");
    LOG.assertTrue(softWrapOffset != DocumentUtil.getLineEndOffset(softWrapOffset, document) || foldRegion != null, "Soft wrap before line break");
    LOG.assertTrue(softWrapOffset != DocumentUtil.getLineStartOffset(softWrapOffset, document) || foldingModel.isOffsetCollapsed(softWrapOffset - 1), "Soft wrap after line break");
    LOG.assertTrue(!DocumentUtil.isInsideSurrogatePair(document, softWrapOffset), "Soft wrap inside a surrogate pair");
    lastSoftWrapOffset = softWrapOffset;
  }
}
 
Example #5
Source File: UIUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@TestOnly
public static void pump() {
  assert !SwingUtilities.isEventDispatchThread();
  final BlockingQueue<Object> queue = new LinkedBlockingQueue<Object>();
  SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
      queue.offer(queue);
    }
  });
  try {
    queue.take();
  }
  catch (InterruptedException e) {
    getLogger().error(e);
  }
}
 
Example #6
Source File: CompletionProgressIndicator.java    From consulo with Apache License 2.0 6 votes vote down vote up
@TestOnly
public static void cleanupForNextTest() {
  CompletionService completionService = ServiceManager.getService(CompletionService.class);
  if (!(completionService instanceof CompletionServiceImpl)) {
    return;
  }

  CompletionProgressIndicator currentCompletion = CompletionServiceImpl.getCurrentCompletionProgressIndicator();
  if (currentCompletion != null) {
    currentCompletion.finishCompletionProcess(true);
    CompletionServiceImpl.assertPhase(CompletionPhase.NoCompletion.getClass());
  }
  else {
    CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
  }
  StatisticsUpdate.cancelLastCompletionStatisticsUpdate();
}
 
Example #7
Source File: ANRWatchDog.java    From sentry-android with MIT License 6 votes vote down vote up
@TestOnly
ANRWatchDog(
    long timeoutIntervalMillis,
    boolean reportInDebug,
    @NotNull ANRListener listener,
    @NotNull ILogger logger,
    @NotNull IHandler uiHandler,
    final @NotNull Context context) {
  super();
  this.reportInDebug = reportInDebug;
  this.anrListener = listener;
  this.timeoutIntervalMillis = timeoutIntervalMillis;
  this.logger = logger;
  this.uiHandler = uiHandler;
  this.context = context;
}
 
Example #8
Source File: DaemonCodeAnalyzerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
private boolean waitInOtherThread(int millis, boolean canChangeDocument) throws Throwable {
  Disposable disposable = Disposable.newDisposable();
  // last hope protection against PsiModificationTrackerImpl.incCounter() craziness (yes, Kotlin)
  myProject.getMessageBus().connect(disposable).subscribe(PsiModificationTracker.TOPIC, () -> {
    throw new IllegalStateException("You must not perform PSI modifications from inside highlighting");
  });
  if (!canChangeDocument) {
    myProject.getMessageBus().connect(disposable).subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, new DaemonListener() {
      @Override
      public void daemonCancelEventOccurred(@Nonnull String reason) {
        throw new IllegalStateException("You must not cancel daemon inside highlighting test: " + reason);
      }
    });
  }

  try {
    Future<Boolean> future = ApplicationManager.getApplication().executeOnPooledThread(() -> {
      try {
        return myPassExecutorService.waitFor(millis);
      }
      catch (Throwable e) {
        throw new RuntimeException(e);
      }
    });
    return future.get();
  }
  finally {
    Disposer.dispose(disposable);
  }
}
 
Example #9
Source File: AbstractTreeNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated use {@link #toTestString(Queryable.PrintInfo)} instead
 */
@Deprecated
@Nullable
@NonNls
@TestOnly
public String getTestPresentation() {
  if (myName != null) {
    return myName;
  }
  if (getValue() != null) {
    return getValue().toString();
  }
  return null;
}
 
Example #10
Source File: FileStatusMap.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public void assertAllDirtyScopesAreNull(@Nonnull Document document) {
  synchronized (myDocumentToStatusMap) {
    FileStatus status = myDocumentToStatusMap.get(document);
    assert status != null && !status.defensivelyMarked && status.wolfPassFinished && status.allDirtyScopesAreNull() : status;
  }
}
 
Example #11
Source File: SseConnection.java    From habpanelviewer with GNU General Public License v3.0 5 votes vote down vote up
@TestOnly
void disconnect() {
    if (mEventSource != null) {
        mEventSource.close();
        mEventSource = null;
    }

    setStatus(Status.NOT_CONNECTED);
}
 
Example #12
Source File: DocumentCommitThread.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public void clearQueue() {
  synchronized (lock) {
    cancelAll();
    wakeUpQueue();
  }
}
 
Example #13
Source File: FileStructurePopup.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public AsyncPromise<Void> rebuildAndUpdate() {
  AsyncPromise<Void> result = new AsyncPromise<>();
  TreeVisitor visitor = path -> {
    AbstractTreeNode node = TreeUtil.getLastUserObject(AbstractTreeNode.class, path);
    if (node != null) node.update();
    return TreeVisitor.Action.CONTINUE;
  };
  rebuild(false).onProcessed(ignore1 -> myAsyncTreeModel.accept(visitor).onProcessed(ignore2 -> result.setResult(null)));
  return result;
}
 
Example #14
Source File: UndoManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public void dropHistoryInTests() {
  flushMergers();
  LOG.assertTrue(myCommandLevel == 0, myCommandLevel);

  myUndoStacksHolder.clearAllStacksInTests();
  myRedoStacksHolder.clearAllStacksInTests();
}
 
Example #15
Source File: ZipperUpdater.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public void waitForAllExecuted(long timeout, @Nonnull TimeUnit unit) {
  try {
    myAlarm.waitForAllExecuted(timeout, unit);
  }
  catch (InterruptedException | ExecutionException | TimeoutException e) {
    throw new RuntimeException(e);
  }
}
 
Example #16
Source File: CodeInsightTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public static void doInlineRename(VariableInplaceRenameHandler handler, final String newName, Editor editor, PsiElement elementAtCaret) {
  Project project = editor.getProject();
  TemplateManagerImpl templateManager = (TemplateManagerImpl)TemplateManager.getInstance(project);
  try {
    templateManager.setTemplateTesting(true);
    InplaceRefactoring renamer = handler.doRename(elementAtCaret, editor, null);
    if (editor instanceof EditorWindow) {
      editor = ((EditorWindow)editor).getDelegate();
    }
    TemplateState state = TemplateManagerImpl.getTemplateState(editor);
    assert state != null;
    final TextRange range = state.getCurrentVariableRange();
    assert range != null;
    final Editor finalEditor = editor;
    new WriteCommandAction.Simple(project) {
      @Override
      protected void run() throws Throwable {
        finalEditor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), newName);
      }
    }.execute().throwException();

    state = TemplateManagerImpl.getTemplateState(editor);
    assert state != null;
    state.gotoEnd(false);
  }
  finally {
    templateManager.setTemplateTesting(false);
  }
}
 
Example #17
Source File: NonBlockingReadActionImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public static void cancelAllTasks() {
  while (!ourTasks.isEmpty()) {
    for (CancellablePromise<?> task : ourTasks) {
      task.cancel();
    }
    WriteAction.run(() -> {
    }); // let background threads complete
  }
}
 
Example #18
Source File: CtrlMouseHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public boolean isCalculationInProgress() {
  TooltipProvider provider = myTooltipProvider;
  if (provider == null) return false;
  Future<?> progress = provider.myExecutionProgress;
  if (progress == null) return false;
  return !progress.isDone();
}
 
Example #19
Source File: FileContentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public static FileContent createByFile(@Nonnull VirtualFile file) {
  try {
    return new FileContentImpl(file, file.contentsToByteArray());
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #20
Source File: PantsCompileOptionsExecutor.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
@NotNull
@TestOnly
public static PantsCompileOptionsExecutor createMock() {
  return new PantsCompileOptionsExecutor(
    new File("/"),
    new MyPantsCompileOptions("", PantsExecutionSettings.createDefault()),
    true,
    Optional.of(1)
  ) {
  };
}
 
Example #21
Source File: PantsOverrideAction.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
@Override
@TestOnly
public String toString() {
  String activeOverride = pantsActive ? " actively" : "";
  return
    primaryPantsAction.getClass().getSimpleName() + activeOverride +  " overriding " +
    (secondaryIdeaAction == null ? "NullAction" : secondaryIdeaAction.getClass().getSimpleName());
}
 
Example #22
Source File: CommittedChangesCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public void refreshAllCaches() throws IOException, VcsException {
  final Collection<ChangesCacheFile> files = myCachesHolder.getAllCaches();
  for (ChangesCacheFile file : files) {
    if (file.isEmpty()) {
      initCache(file);
    }
    else {
      refreshCache(file);
    }
  }
}
 
Example #23
Source File: DumbServiceImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public void setDumb(boolean dumb) {
  if (dumb) {
    myState.set(State.RUNNING_DUMB_TASKS);
    myPublisher.enteredDumbMode();
  }
  else {
    myState.set(State.WAITING_FOR_FINISH);
    updateFinished();
  }
}
 
Example #24
Source File: ChangeList.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public List<ChangeSet> getChangesInTests() {
  List<ChangeSet> result = new ArrayList<ChangeSet>();
  for (ChangeSet each : iterChanges()) {
    result.add(each);
  }
  return result;
}
 
Example #25
Source File: FileTypeManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public void drainReDetectQueue() {
  try {
    ((BoundedTaskExecutor)reDetectExecutor).waitAllTasksExecuted(1, TimeUnit.MINUTES);
  }
  catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #26
Source File: DesktopCaretModelImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@TestOnly
public void validateState() {
  for (DesktopCaretImpl caret : myCarets) {
    caret.validateState();
  }
}
 
Example #27
Source File: DaemonCodeAnalyzerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@TestOnly
public void mustWaitForSmartMode(final boolean mustWait, @Nonnull Disposable parent) {
  final boolean old = mustWaitForSmartMode;
  mustWaitForSmartMode = mustWait;
  Disposer.register(parent, () -> mustWaitForSmartMode = old);
}
 
Example #28
Source File: SentryClient.java    From sentry-android with MIT License 4 votes vote down vote up
/**
 * Updates the session data based on the event, hint and scope data
 *
 * @param event the SentryEvent
 * @param hint the hint or null
 * @param scope the Scope or null
 */
@TestOnly
void updateSessionData(
    final @NotNull SentryEvent event, final @Nullable Object hint, final @Nullable Scope scope) {
  if (ApplyScopeUtils.shouldApplyScopeData(hint)) {
    if (scope != null) {
      scope.withSession(
          session -> {
            if (session != null) {
              Session.State status = null;
              if (event.isCrashed()) {
                status = Session.State.Crashed;
              }

              boolean crashedOrErrored = false;
              if (Session.State.Crashed == status || event.isErrored()) {
                crashedOrErrored = true;
              }

              String userAgent = null;
              if (event.getRequest() != null && event.getRequest().getHeaders() != null) {
                if (event.getRequest().getHeaders().containsKey("user-agent")) {
                  userAgent = event.getRequest().getHeaders().get("user-agent");
                }
              }

              if (session.update(status, userAgent, crashedOrErrored)) {

                Object sessionHint;

                // if hint is DiskFlushNotification, it means we have an uncaughtException
                // and we can end the session.
                if (hint instanceof DiskFlushNotification) {
                  sessionHint = new SessionEndHint();
                  session.end();
                } else {
                  // otherwise we just cache in the disk but do not flush to the network.
                  sessionHint = new SessionUpdateHint();
                }
                captureSession(session, sessionHint);
              }
            } else {
              options.getLogger().log(SentryLevel.INFO, "Session is null on scope.withSession");
            }
          });
    } else {
      options.getLogger().log(SentryLevel.INFO, "Scope is null on client.captureEvent");
    }
  }
}
 
Example #29
Source File: AllFileTemplatesConfigurable.java    From consulo with Apache License 2.0 4 votes vote down vote up
@TestOnly
FileTemplateConfigurable getEditor() {
  return myEditor;
}
 
Example #30
Source File: PantsResolver.java    From intellij-pants-plugin with Apache License 2.0 4 votes vote down vote up
@TestOnly
public void setProjectInfo(ProjectInfo projectInfo) {
  myProjectInfo = projectInfo;
}