summaryrefslogtreecommitdiff
path: root/platform/platform-tests/testSrc/com/intellij/openapi/project/DumbServiceImplTest.groovy
blob: f7a672bd966fb7ce38a1b61ae72475cdf91b0be8 (plain)
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
57
58
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
92
93
94
95
96
97
98
99
100
101
102
103
104
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
134
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
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.project

import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.util.ProgressIndicatorUtils
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.newvfs.impl.VirtualFileImpl
import com.intellij.psi.impl.PsiManagerImpl
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import com.intellij.testFramework.fixtures.impl.TempDirTestFixtureImpl
import com.intellij.util.ArrayUtil
import com.intellij.util.ConcurrencyUtil
import com.intellij.util.SystemProperties
import com.intellij.util.TimeoutUtil
import com.intellij.util.concurrency.Semaphore
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.indexing.FileBasedIndexImpl
import com.intellij.util.indexing.contentQueue.IndexUpdateRunner
import com.intellij.util.indexing.diagnostic.ProjectIndexingHistoryImpl
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.NotNull
import org.junit.Assert

import java.util.concurrent.CountDownLatch
import java.util.concurrent.Future
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger

/**
 * @author peter
 */
class DumbServiceImplTest extends BasePlatformTestCase {
  @Override
  protected void setUp() throws Exception {
    super.setUp()
    String key = "idea.force.dumb.queue.tasks"
    String prev = System.setProperty(key, "true")
    disposeOnTearDown {
      SystemProperties.setProperty(key, prev)
    }
  }

  void "test no task leak on dispose"() {
    DumbService dumbService = new DumbServiceImpl(project)

    AtomicInteger disposes = new AtomicInteger(0)
    def task1 = new DumbModeTask() {
      @Override
      void performInDumbMode(@NotNull ProgressIndicator indicator) {
        while (!indicator.isCanceled()) {
          Thread.sleep(50)
        }
      }

      @Override
      void dispose() {
        disposes.incrementAndGet()
      }
    }

    def task2 = new DumbModeTask() {
      @Override
      void performInDumbMode(@NotNull ProgressIndicator indicator) {
      }

      @Override
      void dispose() {
        disposes.incrementAndGet()
      }
    }

    dumbService.queueTask(task1)
    dumbService.queueTask(task2)
    Disposer.dispose(dumbService)

    Assert.assertEquals(2, disposes.get())
    Assert.assertTrue(Disposer.isDisposed(task1))
    Assert.assertTrue(Disposer.isDisposed(task2))
  }

  void "test queueTask is async"() {
    def semaphore = new Semaphore(1)
    dumbService.queueTask(new DumbModeTask() {
      @Override
      void performInDumbMode(@NotNull ProgressIndicator indicator) {
        def e = new Exception()
        for (StackTraceElement element : e.stackTrace) {
          if (element.toString().contains(DumbServiceGuiTaskQueue.class.simpleName)) {
            semaphore.up()
            return
          }
        }
        throw new Error("Unexpected stack trace for the DumbModeTask: ", e)
      }
    })

    UIUtil.dispatchAllInvocationEvents()
    assert semaphore.waitFor(1000)
    UIUtil.dispatchAllInvocationEvents()
  }

  void "test runWhenSmart is executed synchronously in smart mode"() {
    int invocations = 0
    dumbService.runWhenSmart { invocations++ }
    assert invocations == 1
  }

  void "test runWhenSmart is executed on EDT without write action"() {
    ApplicationManager.application.assertIsDispatchThread()
    int invocations = 0

    Semaphore semaphore = new Semaphore(1)
    dumbService.queueTask(new DumbModeTask() {
      @Override
      void performInDumbMode(@NotNull ProgressIndicator indicator) {
        assert !ApplicationManager.application.dispatchThread
        edt {
          dumbService.runWhenSmart {
            invocations++
            ApplicationManager.application.assertIsDispatchThread()
            assert !ApplicationManager.application.writeAccessAllowed
          }
        }
        TimeoutUtil.sleep(100)
        semaphore.up()
      }
    })
    assert dumbService.dumb
    assert invocations == 0
    UIUtil.dispatchAllInvocationEvents()
    assert semaphore.waitFor(1000)
    UIUtil.dispatchAllInvocationEvents()
    assert invocations == 1
  }

  private DumbServiceImpl getDumbService() {
    (DumbServiceImpl)DumbService.getInstance(project)
  }

  void "test no deadlocks when indexing JSP modally"() {
    def tempFixture = new TempDirTestFixtureImpl()
    disposeOnTearDown { tempFixture.tearDown() }

    // create externally and carefully refresh, avoiding eager content loading and charset detection
    def dir = new File(tempFixture.tempDirPath + '/jsps')
    dir.mkdirs()
    new File(dir, 'a.jsp').createNewFile()

    def vDir = LocalFileSystem.instance.refreshAndFindFileByIoFile(dir)
    assert vDir != null
    assert vDir.children.length == 1
    def child = vDir.children[0]
    assert child.fileType.name == 'JSP'
    assert !((VirtualFileImpl) child).charsetSet
    assert ((PsiManagerImpl)psiManager).fileManager.getCachedPsiFile(child) == null

    def started = new AtomicBoolean()
    def finished = new AtomicBoolean()

    dumbService.queueTask(new DumbModeTask() {
      @Override
      void performInDumbMode(@NotNull ProgressIndicator indicator) {
        started.set(true)
        assert !ApplicationManager.application.dispatchThread
        try {
          ProgressIndicatorUtils.withTimeout(20_000) {
            def index = FileBasedIndex.getInstance() as FileBasedIndexImpl
            new IndexUpdateRunner(index, ConcurrencyUtil.newSameThreadExecutorService(), 1)
              .indexFiles(project, Collections.singletonList(new IndexUpdateRunner.FileSet(project, "child", [child])),
                          indicator, new ProjectIndexingHistoryImpl(getProject(), "Testing", false))
          }
        }
        catch (ProcessCanceledException e) {
          throw new RuntimeException("Successful indexing expected", e)
        }
        finished.set(true)
      }
    })
    assert !started.get()
    WriteAction.run { dumbService.completeJustSubmittedTasks() }
    assert started.get()
    assert finished.get()
  }

  void testDelayBetweenBecomingSmartAndWaitForSmartReturnMustBeSmall() {
    int N = 100
    int[] delays = new int[N]
    DumbServiceImpl dumbService = getDumbService()
    Future<?> future = null
    for (int i=0; i< N; i++) {
      dumbService.runInDumbMode {
        CountDownLatch waiting = new CountDownLatch(1)
        future = ApplicationManager.getApplication().executeOnPooledThread({
            waiting.countDown()
            dumbService.waitForSmartMode()
          } as Runnable)
        waiting.await()
      }
      long start = System.currentTimeMillis()
      future.get()
      long elapsed = System.currentTimeMillis() - start
      delays[i] = elapsed
    }
    Arrays.sort(delays)
    int avg = ArrayUtil.averageAmongMedians(delays, 3)
    assert avg == 0 : "Seems there's is a significant delay between becoming smart and waitForSmartMode() return. Delays in ms:\n"+Arrays.toString(delays)+"\n"
  }
}