b30634beb5a42b067040beb0848e1a1bb1b2b1e1
[idea/community.git] / platform / built-in-server / testSrc / BuiltInServerTestCase.kt
1 package org.jetbrains.ide
2
3 import com.intellij.testFramework.DisposeModulesRule
4 import com.intellij.testFramework.ProjectRule
5 import com.intellij.testFramework.RuleChain
6 import com.intellij.testFramework.TemporaryDirectory
7 import io.netty.handler.codec.http.HttpResponseStatus
8 import org.assertj.core.api.Assertions.assertThat
9 import org.junit.ClassRule
10 import org.junit.Rule
11 import org.junit.rules.Timeout
12 import java.net.HttpURLConnection
13 import java.net.URL
14 import java.util.concurrent.TimeUnit
15
16 internal abstract class BuiltInServerTestCase {
17   companion object {
18     @JvmField
19     @ClassRule val projectRule = ProjectRule()
20   }
21
22   protected val tempDirManager = TemporaryDirectory()
23   protected val manager = TestManager(projectRule, tempDirManager)
24
25   private val ruleChain = RuleChain(
26     tempDirManager,
27     Timeout(60, TimeUnit.SECONDS),
28     manager,
29     DisposeModulesRule(projectRule))
30   @Rule fun getChain() = ruleChain
31
32   protected open val urlPathPrefix = ""
33
34   protected fun doTest(filePath: String? = manager.filePath, additionalCheck: ((connection: HttpURLConnection) -> Unit)? = null) {
35     val serviceUrl = "http://localhost:${BuiltInServerManager.getInstance().port}$urlPathPrefix"
36     var url = serviceUrl + (if (filePath == null) "" else ("/$filePath"))
37     val line = manager.annotation?.line ?: -1
38     if (line != -1) {
39       url += ":$line"
40     }
41     val column = manager.annotation?.column ?: -1
42     if (column != -1) {
43       url += ":$column"
44     }
45
46     val expectedStatus = HttpResponseStatus.valueOf(manager.annotation?.status ?: 200)
47     val connection = testUrl(url, expectedStatus)
48     check(serviceUrl, expectedStatus)
49     additionalCheck?.invoke(connection)
50   }
51
52   protected open fun check(serviceUrl: String, expectedStatus: HttpResponseStatus) {
53   }
54 }
55
56 internal fun testUrl(url: String, expectedStatus: HttpResponseStatus): HttpURLConnection {
57   val connection = URL(url).openConnection() as HttpURLConnection
58   assertThat(HttpResponseStatus.valueOf(connection.responseCode)).isEqualTo(expectedStatus)
59   return connection
60 }