-
Notifications
You must be signed in to change notification settings - Fork 2
/
spring-Test-Generator.sh
executable file
·536 lines (461 loc) · 18.9 KB
/
spring-Test-Generator.sh
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
#!/bin/bash
dir=springTests
if [ -d "$dir" ]; then
echo -e "\033[1;31mIt seems springTests directory exists in this folder, so we would prefer you to delete it to avoid weird results? y | n"
read dirDelResponse
if [ $dirDelResponse = "y" ]; then rm -rf springTests; else exit 1; fi
fi
mkdir -p ${dir}
if [ -e $1 ]; then
if [[ ! $1 == *.json ]]; then
echo -e "\033[1;31mProvided file type $1 is not json. Please Check"
exit 1
fi
else
echo -e "\033[1;31m $1 File doesn't exists. Please Check"
exit 1
fi
package=$(echo "${content}" | jq -r '.package' $1)
[ $package = "null" ] && {
echo -e "\033[1;31mpackage key is missing from json.
Include the package data of the main file present in project's test directory Exiting..."
exit 1
}
#init Data
if [[ $* == *--initialData* ]]; then
echo "package ${package};
public enum ContentType
{
JSON,TEXT_PLAIN
}" >"${dir}/ContentType.java"
echo "package ${package};
public class ApplicationConfig
{
public static final String OAUTH_CLIENT_ID = \"admin\";
public static final String OAUTH_CLIENT_SECRET = \"admin123\";
public static final String DEFAULT_PASS = \"12345678\";
public static final String DEFAULT_NAME = \"hbbwd@gmail.com\";
}" >>"${dir}/ApplicationConfig.java"
baseTest="package ${package};
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.IOException;
import java.nio.charset.Charset;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.SpringApplication;
import org.springframework.http.MediaType;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;
import ${package}.ContentType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.junit.WireMockClassRule;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = SpringApplication.class)
@Ignore
@ActiveProfiles(\"unittest\")
public abstract class BaseTest {
@Autowired
private WebApplicationContext wac;
protected MockMvc mockMvc;
@ClassRule
public static WireMockClassRule wireMockRule = new WireMockClassRule(8089);
@Rule
public WireMockClassRule instanceRule = wireMockRule;
"
if [[ ! $* == *--no-auth* ]]; then
baseTest+="
@Autowired
private FilterChainProxy springSecurityFilterChain;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
.addFilter(springSecurityFilterChain).build();
}
protected String obtainAccessToken(String username, String password, String clientId, String secret) throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add(\"grant_type\", \"password\");
params.add(\"scope\", \"mobileclient\");
params.add(\"username\", username);
params.add(\"password\", password);
ResultActions result
= mockMvc.perform(post(\"/oauth/token\")
.params(params)
.with(httpBasic(clientId,secret))
.accept(\"application/json;charset=UTF-8\"))
.andExpect(status().isOk())
.andExpect(content().contentType(\"application/json;charset=UTF-8\"));
String resultString = result.andReturn().getResponse().getContentAsString();
JacksonJsonParser jsonParser = new JacksonJsonParser();
return jsonParser.parseMap(resultString).get(\"access_token\").toString();
}
public void executeGetRequest(String url, String accessToken, ContentType contentType,
ResultMatcher... matchers) throws Exception{
MockHttpServletRequestBuilder builder = get(url);
builder.header(\"Authorization\", \"Bearer \" + accessToken);
executeRequest(builder, contentType, null, matchers);
}
public void executePostRequest(String url, String accessToken, ContentType contentType,
byte[] content, ResultMatcher... matchers) throws Exception{
MockHttpServletRequestBuilder builder = post(url);
builder.header(\"Authorization\", \"Bearer \" + accessToken);
executeRequest(builder, contentType, content, matchers);
}
public void executePutRequest(String url, String accessToken, ContentType contentType,
byte[] content, ResultMatcher... matchers) throws Exception{
MockHttpServletRequestBuilder builder = put(url);
builder.header(\"Authorization\", \"Bearer \" + accessToken);
executeRequest(builder, contentType, content, matchers);
}
public void executeDeleteRequest(String url, String accessToken, ContentType contentType,
ResultMatcher... matchers) throws Exception {
MockHttpServletRequestBuilder builder = delete(url);
builder.header(\"Authorization\", \"Bearer \" + accessToken);
executeRequest(builder, contentType, null, matchers);
}"
else
baseTest+="
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
// Custom AccessToken implementation if any, goes here!!
//protected String generateJWTToken() {}
"
fi
baseTest+="
public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
ObjectMapper mapper = new ObjectMapper();
//mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsBytes(object);
}
private void executeRequest(MockHttpServletRequestBuilder builder, ContentType contentType,
byte[] content, ResultMatcher... matchers) throws Exception{
if(contentType == ContentType.JSON){
builder.contentType(new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")));
}
if(content != null){
builder.content(content);
}
ResultActions results = mockMvc.perform(builder);
for(ResultMatcher matcher: matchers){
results.andExpect(matcher);
}
}
public void executeGetRequest(String url, ContentType contentType,
ResultMatcher... matchers) throws Exception{
MockHttpServletRequestBuilder builder = get(url);
executeRequest(builder, contentType, null, matchers);
}
public void executePostRequest(String url, ContentType contentType,
byte[] content, ResultMatcher... matchers) throws Exception{
MockHttpServletRequestBuilder builder = post(url);
executeRequest(builder, contentType, content, matchers);
}
public void executePutRequest(String url, ContentType contentType,
byte[] content, ResultMatcher... matchers) throws Exception{
MockHttpServletRequestBuilder builder = put(url);
executeRequest(builder, contentType, content, matchers);
}
public void executeDeleteRequest(String url, ContentType contentType,
ResultMatcher... matchers) throws Exception {
MockHttpServletRequestBuilder builder = delete(url);
executeRequest(builder, contentType, null, matchers);
}
public void mockRemotePutService(String uri,byte[] bytes,int status) throws IOException
{
stubFor(com.github.tomakehurst.wiremock.client.WireMock.put(urlEqualTo(uri))
.willReturn(aResponse()
.withStatus(status)
.withHeader(\"Content-Type\", \"application/json\").withBody(bytes)));
}
public void mockRemoteDeleteService(String uri,byte[] bytes,int status) throws IOException
{
stubFor(com.github.tomakehurst.wiremock.client.WireMock.delete(urlEqualTo(uri))
.willReturn(aResponse()
.withStatus(status)
.withHeader(\"Content-Type\", \"application/json\").withBody(bytes)));
}
public void mockRemoteGetService(String uri,byte[] bytes,int status) throws IOException
{
stubFor(com.github.tomakehurst.wiremock.client.WireMock.get(urlEqualTo(uri))
.willReturn(aResponse()
.withStatus(status)
.withHeader(\"Content-Type\", \"application/json\").withBody(bytes)));
}
public void mockRemotePostService(String uri,byte[] bytes,int status) throws IOException
{
stubFor(com.github.tomakehurst.wiremock.client.WireMock.post(urlEqualTo(uri))
.willReturn(aResponse()
.withStatus(status)
.withHeader(\"Content-Type\", \"application/json\").withBody(bytes)));
}
}"
echo "$baseTest" >>"${dir}/BaseTest.java"
dir="${dir}/controller"
mkdir -p ${dir}
echo -e "Don't forget to write this down into the application.properties file in the test/resources directory\n
\033[1;32m \tspring.jpa.hibernate.ddl-auto=create
\tspring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_ON_EXIT=FALSE
\tspring.datasource.username=sa
\tspring.datasource.password=sa
\tspring.jpa.database-platform=org.hibernate.dialect.H2Dialect
\tspring.h2.console.enabled=true
\tspring.datasource.driverClassName=org.h2.Driver"
fi
# Line Creator Functions
function headerLine() {
echo " MockHttpServletRequestBuilder builder = $1(\"$2\")$3;
executeRequest(builder, ContentType.JSON, $4, $5);"
}
function requestAuthWithNoBody() {
echo " execute$1Request(\"$2\", token, ContentType.JSON, $3);"
}
function requestWithoutAuthAndBody() {
echo " execute$1Request(\"$2\", ContentType.JSON, $3);"
}
function requestAuth() {
echo " execute$1Request(\"$2\", token, ContentType.JSON, $3, $4);"
}
function requestWithoutAuth() {
echo " execute$1Request(\"$2\", ContentType.JSON, $3, $4);"
}
function requestOfMock() {
echo "wireMockRule.start();
mockRemote$1Service(\"$2\",$3,$4.value());"
}
function convertBashStringToJavaString() {
lines=$1
ITER=$(expr ${#lines[@]} - 1)
for ((i = 0; i < ${#lines[@]}; i++)); do
line=${lines[$i]//\"/\\\"}
if [ $i == 0 ]; then
local formattedJson=" String $2 = \"${line}\\n\" +
"
elif [ $i == $ITER ]; then
formattedJson+=" \"${line}\";"
else
formattedJson+=" \" ${line}\\n\" +
"
fi
done
echo "$formattedJson"
}
#Create file and add basic imports along with
re=0
jq -c '.functions[].fileName' $1 | while read i; do
fileName=$(eval echo $i)
[ $fileName = "null" ] && {
echo -e "\033[1;31mfileName key is missing from json. Exiting..."
exit 1
}
[[ $fileName == *Test ]] && fileName="$fileName" || fileName="${fileName}Test"
touch "${dir}/${fileName}.java"
echo "package ${package}.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import ${package}.ApplicationConfig;
import ${package}.BaseTest;
import ${package}.ContentType;
public class ${fileName} extends BaseTest
{
" >>"${dir}/${fileName}.java"
#Start Adding Tests
ts=0
max_ts=$(jq -r ".functions[${re}].tests | length" $1)
jq -r ".functions[${re}].tests[${ts}]" $1 | while [ "$ts" -lt "$max_ts" ]; do
functionName=$(jq -r ".functions[${re}].tests[${ts}].functionName" $1)
functionName=$(eval echo $functionName)
[ $functionName = "null" ] && {
echo -e "\033[1;31mfunctionName key inside ${fileName} -> tests is missing in json. Exiting..."
exit 1
}
auth=$(jq -r ".functions[${re}].tests[${ts}].auth // false" $1)
if $auth; then
authData=$(jq -r ".functions[${re}].tests[${ts}].authData // \"default\"" $1)
if [ $authData == "default" ]; then
authData="ApplicationConfig.DEFAULT_NAME, ApplicationConfig.DEFAULT_PASS"
else
authData=$(echo \"$authData\" | sed -e 's/;/\",\"/g')
fi
fi
type=$(jq -r ".functions[${re}].tests[${ts}].type" $1)
type=$(eval echo $type | tr '[:lower:]' '[:upper:]')
[ $type = "null" ] && {
echo -e "\033[1;31mtype key inside ${fileName} -> tests is missing in json. Exiting..."
exit 1
}
endpoint=$(jq -r ".functions[${re}].tests[${ts}].endpoint" $1)
[ $endpoint = "null" ] && {
echo -e "\033[1;31mendpoint key inside ${fileName} -> tests is missing in json. Exiting..."
exit 1
}
result=$(jq -r ".functions[${re}].tests[${ts}].result" $1)
result=$(echo $result | cut -d'.' -f2- | sed -r 's/(^|_)([A-Z])/\L\2/g' | sed -E 's/([[:lower:]])|([[:upper:]])/\U\1\L\2/g')
result=$(echo "status().is$result()")
[ $result = "null" ] && {
echo -e "\033[1;31mresult key inside ${fileName} -> tests is missing in json. Exiting..."
exit 1
}
headers=$(jq -r ".functions[${re}].tests[${ts}].headers // false" $1)
enter=$'\n'
tab=$'\t\t\t\t'
if $headers; then
if $auth; then
headerInfo=""
headerInfo+="$enter$tab.header(\"Authorization\", \"Bearer \" + token)"
hs=0
max_hs=$(jq -r ".functions[${re}].tests[${ts}].headersData | length" $1)
while [ "$hs" -lt "$max_hs" ]; do
headerKey=$(jq -r ".functions[${re}].tests[${ts}].headersData[${hs}].key" $1)
headerValue=$(jq -r ".functions[${re}].tests[${ts}].headersData[${hs}].value" $1)
[[ $headerValue == *[{}\(]*[\)] ]] && headerValue=$headerValue || headerValue=\"$headerValue\"
headerInfo+="$enter$tab.header(\"$headerKey\", $headerValue)"
hs=$((hs + 1))
done < <(jq -r ".functions[${re}].tests[${ts}].headersData" $1)
else
hs=0
max_hs=$(jq -r ".functions[${re}].tests[${ts}].headersData | length" $1)
headerInfo=""
while [ "$hs" -lt "$max_hs" ]; do
headerKey=$(jq -r ".functions[${re}].tests[${ts}].headersData[${hs}].key" $1)
headerValue=$(jq -r ".functions[${re}].tests[${ts}].headersData[${hs}].value" $1)
[[ $headerValue == *[{}\(]*[\)] ]] && headerValue=$headerValue || headerValue=\"$headerValue\"
headerInfo+="$enter$tab.header(\"$headerKey\", $headerValue)"
hs=$((hs + 1))
done < <(jq -r ".functions[${re}].tests[${ts}].headersData" $1)
fi
fi
data=$(jq -r ".functions[${re}].tests[${ts}].data // \"\"" $1)
if [ ! -z "$data" ]; then
#After POST line use echo "String data = $data; | " >>
IFS=$'\n' lines=($data)
newdata=$(convertBashStringToJavaString ${lines} data)
else
newdata=" String data = \"\";"
fi
echo " @Test
public void ${functionName}() throws Exception {
" >>"${dir}/${fileName}.java"
if $auth; then
echo " String token = obtainAccessToken($authData,
ApplicationConfig.OAUTH_CLIENT_ID,ApplicationConfig.OAUTH_CLIENT_SECRET);
" >>"${dir}/${fileName}.java"
fi
mockData=$(jq -r ".functions[${re}].tests[${ts}] | has(\"mockData\") // \"\"" $1)
if [[ $mockData == "true" ]]; then
mockType=$(jq -r ".functions[${re}].tests[${ts}].mockData.type // \"$type\"" $1)
mockType=$(echo $mockType | tr '[:upper:]' '[:lower:]' | sed -e "s/\b\(.\)/\u\1/g")
mockUri=$(jq -r ".functions[${re}].tests[${ts}].mockData.uri // \"\"" $1)
[ $mockUri = "null" ] && {
echo -e "\033[1;31muri key inside mockData for ${fileName} -> tests is missing in json. Exiting..."
exit 1
}
mockResponse=$(jq -r ".functions[${re}].tests[${ts}].mockData.response // \"\"" $1)
[ $mockResponse = "null" ] && {
echo -e "\033[1;31mresponse key inside mockData for ${fileName} -> tests is missing in json. Exiting..."
exit 1
}
responseJson=$(jq -r ".functions[${re}].tests[${ts}].mockData.responseJson // \"\"" $1)
if [ ! -z "$responseJson" ]; then
#After POST line use echo "String data = $data; | " >>
IFS=$'\n' lines=($responseJson)
newResponseJson=$(convertBashStringToJavaString ${lines} mockResponseJson)
echo "$newResponseJson
$(requestOfMock $mockType $mockUri "mockResponseJson.getBytes()" $mockResponse)" >>"${dir}/${fileName}.java"
else
echo " $(requestOfMock $mockType $mockUri null $mockResponse)" >>"${dir}/${fileName}.java"
fi
fi
case $type in
GET)
if $headers; then
echo "$(headerLine get $endpoint "$headerInfo" null $result)" >>"${dir}/${fileName}.java"
elif $auth; then
echo "$(requestAuthWithNoBody Get $endpoint $result)" >>"${dir}/${fileName}.java"
else
echo "$(requestWithoutAuthAndBody Get $endpoint $result)" >>"${dir}/${fileName}.java"
fi
;;
POST)
echo "$newdata
" >>"${dir}/${fileName}.java"
if $headers; then
echo "$(headerLine post $endpoint "$headerInfo" "data.getBytes()" $result)" >>"${dir}/${fileName}.java"
elif $auth; then
echo "$(requestAuth Post $endpoint "data.getBytes()" $result)" >>"${dir}/${fileName}.java"
else
echo "$(requestWithoutAuth Post $endpoint "data.getBytes()" $result)" >>"${dir}/${fileName}.java"
fi
;;
PUT)
echo "$newdata
" >>"${dir}/${fileName}.java"
if $headers; then
echo "$(headerLine put $endpoint "$headerInfo" "data.getBytes()" $result)" >>"${dir}/${fileName}.java"
elif $auth; then
echo "$(requestAuth Put $endpoint "data.getBytes()" $result)" >>"${dir}/${fileName}.java"
else
echo "$(requestWithoutAuth Put $endpoint "data.getBytes()" $result)" >>"${dir}/${fileName}.java"
fi
;;
DELETE)
echo "$newdata
" >>"${dir}/${fileName}.java"
if $headers; then
echo "$(headerLine delete $endpoint "$headerInfo" null $result)" >>"${dir}/${fileName}.java"
elif $auth; then
echo "$(requestAuthWithNoBody Delete $endpoint $result)" >>"${dir}/${fileName}.java"
else
echo "$(requestWithoutAuthAndBody Delete $endpoint $result)" >>"${dir}/${fileName}.java"
fi
;;
MULTIPART)
fileType=$(jq -r ".functions[${re}].tests[${ts}].fileType // \"\"" $1)
[ $fileType = "null" ] && {
echo -e "\033[1;31mfileType key inside ${fileName} -> tests is missing in json for multipart Request. Exiting..."
exit 1
}
functionValue=" String fileName = \"sampleDocument.${fileType#*/}\";
MockMultipartFile multipartFile =
new MockMultipartFile(\"zeissDocument\", fileName, \"$fileType\", \"Some bytes\".getBytes());
mockMvc.perform(multipart(\"$endpoint\").file(multipartFile)"
if $headers; then
functionValue+=$headerInfo
fi
functionValue+=")
.andExpect($result);"
echo "$functionValue" >>"${dir}/${fileName}.java"
;;
esac
echo " }" >>"${dir}/${fileName}.java"
ts=$((ts + 1))
done
echo "}" >>"${dir}/${fileName}.java"
re=$((re + 1))
done