-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
ScriptCachingIntegrationTest.kt
375 lines (311 loc) · 13.2 KB
/
ScriptCachingIntegrationTest.kt
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/*
* Copyright 2018 the original author or authors.
*
* 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 org.gradle.kotlin.dsl.caching
import org.gradle.kotlin.dsl.execution.Program
import org.gradle.kotlin.dsl.execution.ProgramKind.TopLevel
import org.gradle.kotlin.dsl.execution.ProgramParser
import org.gradle.kotlin.dsl.execution.ProgramSource
import org.gradle.kotlin.dsl.execution.ProgramTarget
import org.gradle.kotlin.dsl.fixtures.DeepThought
import org.gradle.kotlin.dsl.fixtures.IsolatedTestKitDir
import org.gradle.kotlin.dsl.fixtures.LeaksFileHandles
import org.gradle.testkit.runner.BuildResult
import org.junit.ClassRule
import org.junit.Test
import java.io.File
@LeaksFileHandles("""
Daemons hold their daemon log file open after the build has finished, debug logging exacerbates this.
This should be revisited once TestKit provides a mechanism to control daemon termination.
""")
class ScriptCachingIntegrationTest : AbstractScriptCachingIntegrationTest() {
companion object {
@Suppress("unused")
@get:ClassRule
@JvmStatic
val isolatedTestKitDir = IsolatedTestKitDir()
}
@Test
fun `same script, target type & classpath`() {
// given: multi-project build with same build files
val sameContent = """println("Same script content on ${'$'}this")"""
withMultiProjectBuild(left = sameContent, right = sameContent).apply {
// when: first use
buildForCacheInspection("help").apply {
compilationTrace(projectRoot) {
assertScriptCompile(settingsFile.stage1)
assertNoScriptCompile(settingsFile.stage2)
assertNoScriptCompile(rootBuildFile.stage1)
assertScriptCompile(rootBuildFile.stage2)
}
// then: single compilation and classloading
compilationCache {
misses(settingsFile, rootBuildFile, leftBuildFile)
hits(rightBuildFile)
}
classLoadingCache {
misses(settingsFile, rootBuildFile, leftBuildFile)
hits(rightBuildFile)
}
}
// when: second use
buildForCacheInspection("help").apply {
compilationTrace(projectRoot) {
assertNoScriptCompile(settingsFile.stage1)
assertNoScriptCompile(settingsFile.stage2)
assertNoScriptCompile(rootBuildFile.stage1)
assertNoScriptCompile(rootBuildFile.stage2)
}
// then: no compilation nor class loading
compilationCache {
hits(leftBuildFile, rootBuildFile, rightBuildFile)
}
classLoadingCache {
hits(leftBuildFile, rootBuildFile, rightBuildFile)
}
}
// when: other daemon
buildWithAnotherDaemon("help").apply {
// then: single class loading only
compilationCache {
hits(leftBuildFile, rootBuildFile, rightBuildFile)
}
classLoadingCache {
misses(rootBuildFile, leftBuildFile)
hits(rightBuildFile)
}
}
}
}
@Test
fun `same script different target type`() {
// given: same init, settings & build files all applying same script
val same = withFile("same.gradle.kts", """println("Same script on ${'$'}this")""")
val sameApply = """apply(from = "same.gradle.kts")"""
val initScriptFile = withFile("same.init.gradle.kts", sameApply)
val initializationFile = cachedInitializationFile(initScriptFile, false, true)
val settingsFile = cachedSettingsFile(withSettings(sameApply), false, true)
val buildFile = cachedBuildFile(withBuildScript(sameApply), true)
val sameOnGradle = cachedGradleScript(same, false, true)
val sameOnSettings = cachedSettingsScript(same, false, true)
val sameOnProject = cachedProjectScript(same, false, true)
// when: first use
buildForCacheInspection("help", "-I", initScriptFile.absolutePath).apply {
// then: compilation and classloading
compilationCache {
misses(initializationFile, settingsFile, buildFile)
misses(sameOnGradle, sameOnSettings, sameOnProject)
}
classLoadingCache {
misses(initializationFile, settingsFile, buildFile)
misses(sameOnGradle, sameOnSettings, sameOnProject)
}
}
// when: second use
buildForCacheInspection("help", "-I", initScriptFile.absolutePath).apply {
// then: no compilation nor class loading
compilationCache {
hits(initializationFile, settingsFile, buildFile)
hits(sameOnGradle, sameOnSettings, sameOnProject)
}
classLoadingCache {
hits(initializationFile, settingsFile, buildFile)
hits(sameOnGradle, sameOnSettings, sameOnProject)
}
}
// when: other daemon
buildWithAnotherDaemon("help", "-I", initScriptFile.absolutePath).apply {
// then: class loading only
compilationCache {
hits(initializationFile, settingsFile, buildFile)
hits(sameOnGradle, sameOnSettings, sameOnProject)
}
classLoadingCache {
misses(initializationFile, settingsFile, buildFile)
misses(sameOnGradle, sameOnSettings, sameOnProject)
}
}
}
@Test
fun `same script & target type different classpath`() {
// given: different classpath
withClassJar("left/fixture.jar")
withClassJar("right/fixture.jar", DeepThought::class.java)
// and: same script & target type
val sameContent = """
buildscript {
dependencies { classpath(files("fixture.jar")) }
}
println("Same content, different classpath on ${'$'}this")
"""
withMultiProjectBuild(left = sameContent, right = sameContent).apply {
// when: first use
buildForCacheInspection("help").apply {
// then: compilation and classloading
compilationCache {
misses(leftBuildFile)
hits(rightBuildFile.stage1) // same buildscript block, target type and classpath
misses(rightBuildFile.stage2) // different classpath
}
classLoadingCache {
misses(leftBuildFile)
hits(rightBuildFile.stage1)
misses(rightBuildFile.stage2)
}
}
// when: second use
buildForCacheInspection("help").apply {
// then: no compilation nor class loading
compilationCache {
hits(leftBuildFile, rightBuildFile)
}
classLoadingCache {
hits(leftBuildFile, rightBuildFile)
}
}
// when: other daemon
buildWithAnotherDaemon("help").apply {
// then: class loading only
compilationCache {
hits(leftBuildFile, rightBuildFile)
}
classLoadingCache {
misses(leftBuildFile)
hits(rightBuildFile.stage1)
misses(rightBuildFile.stage2)
}
}
}
}
@Test
fun `in-memory script class loading cache releases memory of unused entries`() {
// given: buildSrc memory hog
val myTask = withFile("buildSrc/src/main/groovy/MyTask.groovy", """
import org.gradle.api.*
import org.gradle.api.tasks.*
class MyTask extends DefaultTask {
static final byte[] MEMORY_HOG = new byte[64 * 1024 * 1024]
@TaskAction void runAction0() {}
}
""")
val settingsFile = cachedSettingsFile(withSettings(""), false, false)
val buildFile = cachedBuildFile(withBuildScript("""task<MyTask>("myTask")"""), true)
// expect:
for (run in 1..4) {
myTask.writeText(myTask.readText().replace("runAction${run - 1}", "runAction$run"))
buildWithDaemonHeapSize(256, "myTask").apply {
compilationCache {
misses(settingsFile.stage1)
hits(settingsFile.stage2)
misses(buildFile)
}
classLoadingCache {
misses(settingsFile.stage1)
hits(settingsFile.stage2)
misses(buildFile)
}
}
}
}
private
fun withMultiProjectBuild(settings: String = "", root: String = "", left: String = "", right: String = "") =
MultiProjectCachedScripts(
cachedSettingsFile(
withSettings("""
$settings
rootProject.name = "${projectRoot.name}" // distinguish settings files
include("right", "left")
"""),
settings.contains("buildscript {"),
true),
cachedBuildFile(
withBuildScript(root),
hasBody(root)),
cachedBuildFile(
withBuildScriptIn("left", left),
hasBody(left)),
cachedBuildFile(
withBuildScriptIn("right", right),
hasBody(right)))
}
private
fun hasBody(script: String) =
ProgramParser.parse(ProgramSource("script.gradle.kts", script), TopLevel, ProgramTarget.Project).let {
it is Program.Script || it is Program.Staged
}
private
data class MultiProjectCachedScripts(
val settingsFile: CachedScript.WholeFile,
val rootBuildFile: CachedScript.WholeFile,
val leftBuildFile: CachedScript.WholeFile,
val rightBuildFile: CachedScript.WholeFile
)
private
fun BuildResult.classLoadingCache(action: ClassLoadingCache.() -> Unit) =
action(ClassLoadingCache(this))
private
class ClassLoadingCache(val result: BuildResult) {
fun misses(vararg cachedScripts: CachedScript) =
cachedScripts.forEach { assertClassLoads(it, 1) }
fun hits(vararg cachedScripts: CachedScript) =
cachedScripts.forEach { assertClassLoads(it, 0) }
fun assertClassLoads(cachedScript: CachedScript, count: Int) =
when (cachedScript) {
is CachedScript.WholeFile -> cachedScript.stages.forEach { assertClassLoads(it, count) }
is CachedScript.CompilationStage -> assertClassLoads(cachedScript, count)
}
fun assertClassLoads(stage: CachedScript.CompilationStage, count: Int) =
result.assertOccurrenceCountOf("loading", stage, count)
}
internal
fun BuildResult.assertOccurrenceCountOf(actionDisplayName: String, stage: CachedScript.CompilationStage, count: Int) {
val expectedCount = if (stage.enabled) count else 0
val logStatement = "${actionDisplayName.capitalize()} ${stage.templateId} from ${stage.source}"
val observedCount = output.occurrenceCountOf(logStatement)
require(observedCount == expectedCount) {
"Expected $actionDisplayName $expectedCount ${stage.templateId} from ${stage.source}, but got $observedCount\n" +
" Looking for statement: $logStatement\n" +
" Build output was:\n" + output.prependIndent(" ")
}
}
internal
fun String.occurrenceCountOf(string: String) =
split(string).size - 1
internal
fun compilationTrace(projectRoot: File, action: CompileTrace.() -> Unit) {
val file = File(projectRoot, "operation-trace-log.txt")
action(CompileTrace(file.readLines()))
}
internal
class CompileTrace(private val operations: List<String>) {
fun assertScriptCompile(stage: CachedScript.CompilationStage) {
val description = operationDescription(stage)
require(operations.any { it.contains(description) }) {
"Expecting operation `$description`!"
}
}
fun assertNoScriptCompile(stage: CachedScript.CompilationStage) {
val description = operationDescription(stage)
require(!operations.any { it.contains(description) }) {
"Unexpected operation `$description`!"
}
}
private
fun operationDescription(stage: CachedScript.CompilationStage) =
"Compile script ${stage.file.name} (${descriptionOf(stage)})"
private
fun descriptionOf(stage: CachedScript.CompilationStage) =
if (stage.stage == "stage1") "CLASSPATH" else "BODY"
}