/
TestCaseWriter.kt
368 lines (288 loc) · 12 KB
/
TestCaseWriter.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
package org.evomaster.core.output
import org.evomaster.core.database.DbAction
import org.evomaster.core.output.formatter.OutputFormatter
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.problem.rest.RestCallResult
import org.evomaster.core.problem.rest.RestIndividual
import org.evomaster.core.problem.rest.param.BodyParam
import org.evomaster.core.problem.rest.param.HeaderParam
import org.evomaster.core.search.EvaluatedAction
import org.evomaster.core.search.gene.SqlForeignKeyGene
import org.evomaster.core.search.gene.SqlPrimaryKeyGene
import org.evomaster.core.search.gene.StringGene
class TestCaseWriter {
private var counter = 0
fun convertToCompilableTestCode(
format: OutputFormat,
test: TestCase,
baseUrlOfSut: String)
: Lines {
counter = 0
val lines = Lines()
if (format.isJUnit()) {
lines.add("@Test")
}
when {
format.isJava() -> lines.add("public void ${test.name}() throws Exception {")
format.isKotlin() -> lines.add("fun ${test.name}() {")
}
lines.indent()
if (test.test.individual is RestIndividual) {
if (!test.test.individual.dbInitialization.isEmpty()) {
handleDbInitialization(format, test.test.individual.dbInitialization, lines)
}
}
if (test.hasChainedLocations()) {
lines.addEmpty()
test.test.evaluatedActions()
.map { ea -> ea.action }
.filterIsInstance(RestCallAction::class.java)
.filter { a -> a.locationId != null }
.map { a -> a.locationId }
.distinct()
.forEach { id ->
val name = locationVar(id!!)
when {
format.isJava() -> lines.add("String $name = \"\";")
format.isKotlin() -> lines.add("var $name = \"\"")
}
}
}
test.test.evaluatedActions().forEach { a ->
when (a.action) {
is RestCallAction -> handleRestCall(a, lines, baseUrlOfSut)
else -> throw IllegalStateException("Cannot handle " + a.action.getName())
}
}
lines.deindent()
lines.add("}")
return lines
}
private fun handleDbInitialization(format: OutputFormat, dbInitialization: MutableList<DbAction>, lines: Lines) {
dbInitialization.forEachIndexed { index, dbAction ->
var newInsertIntoLine = ""
if (index == 0) {
when {
format.isJava() -> newInsertIntoLine += "List<InsertionDto> "
format.isKotlin() -> newInsertIntoLine += "val "
}
newInsertIntoLine += "insertions = sql()"
} else {
newInsertIntoLine += ".and()"
}
newInsertIntoLine += ".insertInto(\"${dbAction.table.name}\", ${dbAction.geInsertionId()})"
dbAction.seeGenes().forEach { g ->
if (g.isPrintable()) {
if (g is SqlForeignKeyGene) {
val variableName = g.getVariableName()
val uniqueId = g.uniqueId
newInsertIntoLine += ".r(\"$variableName\", $uniqueId)"
} else if (g is StringGene){
val variableName = g.getVariableName()
val printableValue = g.getValueAsPrintableString()
newInsertIntoLine += ".d(\"$variableName\", $printableValue)"
} else {
val variableName = g.getVariableName()
val printableValue = g.getValueAsPrintableString()
newInsertIntoLine += ".d(\"$variableName\", \"$printableValue\")"
}
}
}
if (index == dbInitialization.size - 1) {
newInsertIntoLine += ".dtos()"
when {
format.isJava() -> newInsertIntoLine += ";"
format.isKotlin() -> {
}
}
}
if (index==1) {
lines.indent()
}
lines.add(newInsertIntoLine)
if (index>0 && index == dbInitialization.size - 1) {
lines.deindent()
}
}
var execInsertionsLine = "controller.execInsertionsIntoDatabase(insertions)"
when {
format.isJava() -> execInsertionsLine += ";"
format.isKotlin() -> {
}
}
lines.add(execInsertionsLine)
}
private fun locationVar(id: String): String {
//TODO make sure name is syntactically valid
//TODO use counters to make them unique
return "location_${id.trim().replace(" ", "_")}"
}
private fun handleRestCall(
evaluatedAction: EvaluatedAction,
lines: Lines,
baseUrlOfSut: String
) {
lines.addEmpty()
val call = evaluatedAction.action as RestCallAction
val res = evaluatedAction.result as RestCallResult
if (res.failedCall()) {
addRestCallInTryCatch(call, lines, res, baseUrlOfSut)
} else {
addRestCallLines(call, lines, res, baseUrlOfSut)
}
}
private fun addRestCallInTryCatch(call: RestCallAction,
lines: Lines,
res: RestCallResult,
baseUrlOfSut: String) {
lines.add("try{")
lines.indent()
addRestCallLines(call, lines, res, baseUrlOfSut)
if (!res.getTimedout()) {
/*
Fail test if exception is not thrown, but not if it was a timeout,
otherwise the test would become flaky
*/
lines.add("fail(\"Expected exception\");")
}
lines.deindent()
lines.add("} catch(Exception e){")
res.getErrorMessage()?.let {
lines.indent()
lines.add("//$it")
lines.deindent()
}
lines.add("}")
}
private fun addRestCallLines(call: RestCallAction,
lines: Lines,
res: RestCallResult,
baseUrlOfSut: String) {
//first handle the first line
handleFirstLine(call, lines, res)
lines.indent(2)
handleHeaders(call, lines)
handleBody(call, lines)
handleVerb(baseUrlOfSut, call, lines)
handleResponse(lines, res)
//finally, handle the last line(s)
handleLastLine(call, res, lines)
}
private fun handleLastLine(call: RestCallAction, res: RestCallResult, lines: Lines) {
if (call.saveLocation && !res.stopping) {
if (!res.getHeuristicsForChainedLocation()) {
lines.add(".extract().header(\"location\");")
lines.addEmpty()
lines.deindent(2)
lines.add("assertTrue(isValidURIorEmpty(${locationVar(call.path.lastElement())}));")
} else {
lines.add(".extract().body().path(\"${res.getResourceIdName()}\").toString();")
lines.addEmpty()
lines.deindent(2)
val baseUri: String = if (call.locationId != null) {
locationVar(call.locationId!!)
} else {
call.path.resolveOnlyPath(call.parameters)
}
lines.add("${locationVar(call.path.lastElement())} = \"$baseUri/\" + id_$counter;")
counter++
}
} else {
lines.append(";")
lines.deindent(2)
}
}
private fun handleFirstLine(call: RestCallAction, lines: Lines, res: RestCallResult) {
lines.addEmpty()
if (call.saveLocation && !res.stopping) {
if (!res.getHeuristicsForChainedLocation()) {
lines.append("${locationVar(call.path.lastElement())} = ")
} else {
lines.append("String id_$counter = ")
}
}
lines.append("given()" + getAcceptHeader())
}
private fun handleVerb(baseUrlOfSut: String, call: RestCallAction, lines: Lines) {
val verb = call.verb.name.toLowerCase()
lines.add(".$verb(")
if (call.locationId != null) {
lines.append("resolveLocation(${locationVar(call.locationId!!)}, $baseUrlOfSut + \"${call.resolvedPath()}\")")
} else {
lines.append("$baseUrlOfSut + ")
if (call.path.numberOfUsableQueryParams(call.parameters) <= 1) {
val uri = call.path.resolve(call.parameters)
lines.append("\"$uri\"")
} else {
//several query parameters. lets have them one per line
val path = call.path.resolveOnlyPath(call.parameters)
val elements = call.path.resolveOnlyQuery(call.parameters)
lines.append("\"$path?\" + ")
lines.indent()
(0..elements.lastIndex - 1).forEach { i -> lines.add("\"${elements[i]}&\" + ") }
lines.add("\"${elements.last()}\"")
lines.deindent()
}
}
lines.append(")")
}
private fun handleResponse(lines: Lines, res: RestCallResult) {
if (!res.failedCall()) {
lines.add(".then()")
lines.add(".statusCode(${res.getStatusCode()})")
//TODO check on body
}
}
private fun handleBody(call: RestCallAction, lines: Lines) {
handleBody(call, lines, true)
}
private fun handleBody(call: RestCallAction, lines: Lines, readable: Boolean) {
call.parameters.find { p -> p is BodyParam }
?.let {
lines.add(".contentType(\"application/json\")")
val body = if (readable) OutputFormatter.JSON_FORMATTER.getFormatted(it.gene.getValueAsPrintableString())
else it.gene.getValueAsPrintableString()
//needed as JSON uses ""
val bodyLines = body.split("\n").map { s ->
"\"" + s.trim().replace("\"", "\\\"") + "\""
}
if (bodyLines.size == 1) {
lines.add(".body(${bodyLines.first()})")
} else {
lines.add(".body(${bodyLines.first()} + ")
lines.indent()
(1..bodyLines.lastIndex - 1).forEach { i ->
lines.add("${bodyLines[i]} + ")
}
lines.add("${bodyLines.last()})")
lines.deindent()
}
}
val form = call.getBodyFormData()
if (!form.isBlank()) {
lines.add(".contentType(\"application/x-www-form-urlencoded\")")
lines.add(".body(\"$form\")")
}
}
private fun handleHeaders(call: RestCallAction, lines: Lines) {
val prechosenAuthHeaders = call.auth.headers.map { it.name }
call.auth.headers.forEach {
lines.add(".header(\"${it.name}\", \"${it.value}\") // ${call.auth.name}")
}
call.parameters.filterIsInstance<HeaderParam>()
.filter { !prechosenAuthHeaders.contains(it.name) }
.forEach {
lines.add(".header(\"${it.name}\", ${it.gene.getValueAsPrintableString()})")
}
}
private fun getAcceptHeader(): String {
/*
* Note: using the type in result body is wrong:
* if you request a JSON but make an error, you might
* get back a text/plain with an explanation
*
* TODO: get the type from the REST call
*/
return ".accept(\"*/*\")"
}
}