-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathGenerateTestsCommand.kt
More file actions
166 lines (147 loc) · 6.94 KB
/
GenerateTestsCommand.kt
File metadata and controls
166 lines (147 loc) · 6.94 KB
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
package org.utbot.cli
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.options.check
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.flag
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.required
import com.github.ajalt.clikt.parameters.types.choice
import mu.KotlinLogging
import org.utbot.common.PathUtil.toPath
import org.utbot.common.filterWhen
import org.utbot.engine.Mocker
import org.utbot.framework.UtSettings
import org.utbot.framework.plugin.api.ClassId
import org.utbot.framework.plugin.api.CodegenLanguage
import org.utbot.framework.plugin.api.UtMethodTestSet
import org.utbot.framework.plugin.api.util.UtContext
import org.utbot.framework.plugin.api.util.isAbstract
import org.utbot.framework.plugin.api.util.isSynthetic
import org.utbot.framework.plugin.api.util.withUtContext
import org.utbot.framework.util.isKnownImplicitlyDeclaredMethod
import org.utbot.sarif.SarifReport
import org.utbot.sarif.SourceFindingStrategyDefault
import java.nio.file.Files
import java.nio.file.Paths
import java.time.temporal.ChronoUnit
private val logger = KotlinLogging.logger {}
class GenerateTestsCommand :
GenerateTestsAbstractCommand(name = "generate", help = "Generates tests for the specified class") {
private val targetClassFqn by argument(
help = "Target class fully qualified name"
)
private val output by option("-o", "--output", help = "Specifies output file for a generated test")
.check("Must end with .java or .kt suffix") {
it.endsWith(".java") or it.endsWith(".kt")
}
override val classPath by option(
"-cp", "--classpath",
help = "Specifies the classpath for a class under test"
)
.required()
private val sourceCodeFile by option(
"-s", "--source",
help = "Specifies source code file for a generated test"
)
.check("Must exist and end with .java or .kt suffix") {
(it.endsWith(".java") || it.endsWith(".kt")) && Files.exists(Paths.get(it))
}
private val projectRoot by option(
"--project-root",
help = "Specifies the root of the relative paths in the sarif report that are required to show links correctly"
)
private val sarifReport by option(
"--sarif",
help = "Specifies output file for the static analysis report"
)
.check("Must end with *.sarif suffix") {
it.endsWith(".sarif")
}
override val codegenLanguage by option("-l", "--language", help = "Defines the codegen language")
.choice(
CodegenLanguage.JAVA.toString() to CodegenLanguage.JAVA,
CodegenLanguage.KOTLIN.toString() to CodegenLanguage.KOTLIN
)
.default(CodegenLanguage.defaultItem)
.check("Output file extension must match the test class language") { language ->
output?.let { "." + it.substringAfterLast('.') == language.extension } ?: true
}
private val printToStdOut by option(
"-p",
"--print-test",
help = "Specifies whether a test should be printed out to StdOut"
)
.flag(default = false)
override fun run() {
val started = now()
val workingDirectory = getWorkingDirectory(targetClassFqn)
?: throw Exception("Cannot find the target class in the classpath")
try {
logger.debug { "Generating test for [$targetClassFqn] - started" }
logger.debug { "Classpath to be used: ${newline()} $classPath ${newline()}" }
// utContext is used in `targetMethods`, `generate`, `generateTest`, `generateReport`
withUtContext(UtContext(classLoader)) {
val classIdUnderTest = ClassId(targetClassFqn)
val targetMethods = classIdUnderTest.targetMethods()
.filterWhen(UtSettings.skipTestGenerationForSyntheticAndImplicitlyDeclaredMethods) {
!it.isSynthetic && !it.isKnownImplicitlyDeclaredMethod
}
.filterNot { it.isAbstract }
val testCaseGenerator = initializeGenerator(workingDirectory)
if (targetMethods.isEmpty()) {
throw Exception("Nothing to process. No methods were provided")
}
val testClassName = output?.toPath()?.toFile()?.nameWithoutExtension
?: "${classIdUnderTest.simpleName}Test"
val testSets = generateTestSets(
testCaseGenerator,
targetMethods,
sourceCodeFile?.let(Paths::get),
searchDirectory = workingDirectory,
chosenClassesToMockAlways = (Mocker.defaultSuperClassesToMockAlwaysNames + classesToMockAlways)
.mapTo(mutableSetOf()) { ClassId(it) }
)
val testClassBody = generateTest(classIdUnderTest, testClassName, testSets)
if (printToStdOut) {
logger.info { testClassBody }
}
if (sarifReport != null) {
generateReport(targetClassFqn, testSets, testClassBody)
}
saveToFile(testClassBody, output)
}
} catch (t: Throwable) {
logger.error { "An error has occurred while generating test for snippet $targetClassFqn : $t" }
throw t
} finally {
val duration = ChronoUnit.MILLIS.between(started, now())
logger.debug { "Generating test for [$targetClassFqn] - completed in [$duration] (ms)" }
}
}
private fun generateReport(classFqn: String, testSets: List<UtMethodTestSet>, testClassBody: String) = try {
// reassignments for smart casts
val testsFilePath = output
val projectRootPath = projectRoot
when {
testsFilePath == null -> {
println("The output file is required to generate a report. Please, specify \"--output\" option.")
}
projectRootPath == null -> {
println("The path to the project root is required to generate a report. Please, specify \"--project-root\" option.")
}
sourceCodeFile == null -> {
println("The source file is not found. Please, specify \"--source\" option.")
}
else -> {
val sourceFinding =
SourceFindingStrategyDefault(classFqn, sourceCodeFile!!, testsFilePath, projectRootPath)
val report = SarifReport(testSets, testClassBody, sourceFinding).createReport().toJson()
saveToFile(report, sarifReport)
println("The report was saved to \"$sarifReport\".")
}
}
} catch (t: Throwable) {
logger.error { "An error has occurred while generating sarif report for snippet $targetClassFqn : $t" }
throw t
}
}