forked from lawbreaker2022/LawBreaker-SourceCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_single_test_case.py
602 lines (572 loc) · 37.9 KB
/
run_single_test_case.py
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
import copy
import os
import select
import shutil
import signal
import sys
import time
import warnings
from pathlib import Path
from threading import Timer
import websockets
import json
import asyncio
from EXtraction import ExtractAll
from GeneticAlgorithm import GAGeneration, EncodedTestCase, DecodedTestCase
from TestCaseRandom import TestCaseRandom
from datetime import datetime
from AssertionExtraction import SingleAssertion
from map import get_map_info
import logging
# logging.basicConfig(level=level, handlers=[stdout_handler, file_handler],format='%(asctime)s, %(levelname)s: %(message)s', datefmt="%Y-%m-%d %H:%M:%S")
# logger = logging.getLogger()
# logger.setLevel(logging.DEBUG)
# logger.addHandler(logging.FileHandler('test.log', 'a'))
# logger.addHandler(logging.StreamHandler(sys.stdout))
min_fitness_list = []
ave_fitness_list = []
def to_json(obj):
return json.dumps(obj, default=lambda o: o.__dict__, indent=4)
async def hello(scenario_msg, single_spec, generation_number=1, population_size=3, directory=None) -> object:
uri = "ws://localhost:8000"
async with websockets.connect(uri, max_size= 300000000, ping_interval=None) as websocket:
scenario_no = len(scenario_msg)
init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
await websocket.send(init_msg)
# for i in range(scenario_no):
# logging.info('iteration: {}'.format(i))
msg = await websocket.recv()
msg = json.loads(msg)
if msg['TYPE'] == 'READY_FOR_NEW_TEST' and msg['DATA']:
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
with open(directory + '/Incompleted.txt', 'a') as f:
f.write('Time: {} \n'.format(dt_string))
with open(directory + '/bugTestCase.txt', 'a') as f:
f.write('Time: {} \n'.format(dt_string))
with open(directory + '/exceptionTestCase.txt', 'a') as f:
f.write('Time: {} \n'.format(dt_string))
with open(directory + '/NoTrace.txt', 'a') as f:
f.write('Time: {} \n'.format(dt_string))
population = []
new_testcases = []
init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
await websocket.send(init_msg)
for i in range(scenario_no):
while True:
msg = await websocket.recv()
msg = json.loads(msg)
if msg['TYPE'] == 'READY_FOR_NEW_TEST':
if msg['DATA']:
logging.info('Running Predefined Test Case: {}'.format(i))
send_msg = {'CMD': "CMD_NEW_TEST", 'DATA': scenario_msg[i]}
await websocket.send(json.dumps(send_msg))
else:
asyncio.sleep(3)
init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
await websocket.send(init_msg)
elif msg['TYPE'] == 'KEEP_SERVER_AND_CLIENT_ALIVE':
send_msg = {'CMD': "KEEP_SERVER_AND_CLIENT_ALIVE", 'DATA': None}
await websocket.send(json.dumps(send_msg))
elif msg['TYPE'] == 'TEST_TERMINATED' or msg['TYPE'] == 'ERROR':
print("Try to reconnect!")
asyncio.sleep(3)
init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
await websocket.send(init_msg)
elif msg['TYPE'] == 'TEST_COMPLETED':
output_trace = msg['DATA']
now = datetime.now()
dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
file = directory + '/data/result' + dt_string + '.json'
with open(file, 'w') as outfile:
json.dump(output_trace, outfile, indent=2)
if not output_trace['destinationReached']:
logging.info("Not reach the destination")
with open(directory + '/Incompleted.txt', 'a') as f:
json.dump(scenario_msg[i], f, indent=2)
f.write('\n')
if len(output_trace['trace']) > 1:
encoded_testcase = EncodedTestCase(output_trace, single_spec)
logging.info(" Fitness Value: {}".format(encoded_testcase.fitness))
del encoded_testcase.trace
if encoded_testcase.fitness <= 0.0:
with open(directory + '/bugTestCase.txt', 'a') as bug_file:
string_index2 = "The detailed fitness values:" + str(encoded_testcase.muti_fitness) + '\n'
bug_file.write(string_index2)
json.dump(output_trace, bug_file, indent=2)
bug_file.write('\n')
population.append(encoded_testcase)
if output_trace["testFailures"]!= []:
with open(directory + '/exceptionTestCase.txt', 'a') as bug_file:
now = datetime.now()
dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
string_index = "Time:" + dt_string + "Generation: " + str(0) + ", Individual: " + str(0) +", Bug: " + str(output_trace["testFailures"]) +'\n'
bug_file.write(string_index)
json.dump(output_trace, bug_file, indent=2)
bug_file.write('\n')
elif len(output_trace['trace']) == 1:
logging.info(
"Is reached: {}, minimal distance: {}".format(output_trace['destinationReached'],
output_trace['minEgoObsDist']))
testcase = TestCaseRandom(output_trace)
testcase.testcase_random(1)
new_testcases.append(testcase.cases[-1])
else:
logging.info("No trace for the test cases")
with open(directory + '/NoTrace.txt', 'a') as f:
json.dump(scenario_msg[i], f, indent=2)
f.write('\n')
testcase = TestCaseRandom(output_trace)
testcase.testcase_random(1)
new_testcases.append(testcase.cases[-1])
init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
await websocket.send(init_msg)
break
# while True:
# msg_valid = await websocket.recv()
# msg_valid = json.loads(msg_valid)
# # print("Received Message: " + msg_valid['TYPE'])
# # if msg_valid['TYPE'] == 'ERROR' or 'TEST_STARTED':
# # print(msg_valid)
# if msg_valid['TYPE'] == 'TEST_TERMINATED' or msg_valid['TYPE'] == 'ERROR':
# print("Try to reconnect!")
# init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
# await websocket.send(init_msg)
# time.sleep(3)
# msg = await websocket.recv()
# msg = json.loads(msg)
# if msg['TYPE'] == 'READY_FOR_NEW_TEST' and msg['DATA']:
# send_msg = {'CMD': "CMD_NEW_TEST", 'DATA': scenario_msg[i]}
# await websocket.send(json.dumps(send_msg))
# continue
# elif msg_valid['TYPE'] == 'TEST_COMPLETED':
# output_trace = msg_valid['DATA']
# now = datetime.now()
# dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
# file = directory + '/data/result' + dt_string + '.json'
# with open(file, 'w') as outfile:
# json.dump(output_trace, outfile, indent=2)
# if not output_trace['destinationReached']:
# logging.info("Not reach the destination")
# with open(directory + '/Incompleted.txt', 'a') as f:
# json.dump(scenario_msg[i], f, indent=2)
# f.write('\n')
# if len(output_trace['trace']) > 1:
# encoded_testcase = EncodedTestCase(output_trace, single_spec)
# logging.info(" Fitness Value: {}".format(encoded_testcase.fitness))
# del encoded_testcase.trace
# if encoded_testcase.fitness < 0.0:
# with open(directory + '/bugTestCase.txt', 'a') as bug_file:
# json.dump(output_trace, bug_file, indent=2)
# bug_file.write('\n')
# population.append(encoded_testcase)
# elif len(output_trace['trace']) == 1:
# logging.info("Is reached: {}, minimal distance: {}".format(output_trace['destinationReached'], output_trace['minEgoObsDist']))
# testcase = TestCaseRandom(output_trace)
# testcase.testcase_random(1)
# new_testcases.append(testcase.cases[-1])
# else:
# logging.info("No trace for the test cases")
# with open(directory + '/NoTrace.txt', 'a') as f:
# json.dump(scenario_msg[i], f, indent=2)
# f.write('\n')
# testcase = TestCaseRandom(output_trace)
# testcase.testcase_random(1)
# new_testcases.append(testcase.cases[-1])
# init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
# await websocket.send(init_msg)
# break
# new_population_obj = ga.GAGeneration(population)
if generation_number:
if len(population):
decoder = DecodedTestCase(population)
new_testcases = decoder.decoding()
if len(new_testcases) < population_size:
testcase = TestCaseRandom(output_trace)
testcase.testcase_random(population_size - scenario_no)
for i2 in range(len(testcase.cases) - 1):
new_testcases.append(testcase.cases[i2 + 1])
with open(directory + '/TestCase.txt', 'w') as outfile:
for i1 in range(len(new_testcases)):
json.dump(new_testcases[i1], outfile, indent=2)
outfile.write('\n')
# Begin GA
for generation in range(generation_number):
generation_fitness = float('inf')
ave_fitness = 0
if len(new_testcases) < population_size:
logging.info('Test case decreases')
population = []
next_new_testcases = []
for j in range(len(new_testcases)):
# deal with each test case
while True:
msg = await websocket.recv()
msg = json.loads(msg)
# print(msg['TYPE'])
if msg['TYPE'] == 'READY_FOR_NEW_TEST':
if msg['DATA']:
logging.info('Running Generation: {}, Individual: {}'.format(generation, j + 1))
send_msg = {'CMD': "CMD_NEW_TEST", 'DATA': new_testcases[j]}
await websocket.send(json.dumps(send_msg))
else:
asyncio.sleep(3)
init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
await websocket.send(init_msg)
elif msg['TYPE'] == 'TEST_TERMINATED' or msg['TYPE'] == 'ERROR':
print(msg)
print("Try to reconnect.")
asyncio.sleep(3)
init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
await websocket.send(init_msg)
elif msg['TYPE'] == 'KEEP_SERVER_AND_CLIENT_ALIVE':
send_msg = {'CMD': "KEEP_SERVER_AND_CLIENT_ALIVE", 'DATA': None}
await websocket.send(json.dumps(send_msg))
elif msg['TYPE'] == 'TEST_COMPLETED':
output_trace = msg['DATA']
now = datetime.now()
dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
file = directory + '/data/result' + dt_string + '.json'
with open(file, 'w') as outfile:
json.dump(output_trace, outfile, indent=2)
logging.info("The number of states in the trace is {}".format(len(output_trace['trace'])))
if not output_trace['destinationReached']:
with open(directory + '/Incompleted.txt', 'a') as f:
json.dump(new_testcases[j], f, indent=2)
f.write('\n')
if len(output_trace['trace']) > 1:
encoded_testcase = EncodedTestCase(output_trace, single_spec)
logging.info(" Fitness Value: {}".format(encoded_testcase.fitness))
ave_fitness += encoded_testcase.fitness
if encoded_testcase.fitness < generation_fitness:
generation_fitness = encoded_testcase.fitness
del encoded_testcase.trace
if encoded_testcase.fitness <= 0.0:
with open(directory + '/bugTestCase.txt', 'a') as bug_file:
now = datetime.now()
dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
string_index = "Time:" + dt_string + "Generation: " + str(generation) + ", Individual: " + str(j+1) + '\n'
bug_file.write(string_index)
string_index2 = "The detailed fitness values:" + str(encoded_testcase.muti_fitness) + '\n'
bug_file.write(string_index2)
json.dump(output_trace, bug_file, indent=2)
bug_file.write('\n')
population.append(encoded_testcase)
if output_trace["testFailures"]!= []:
with open(directory + '/exceptionTestCase.txt', 'a') as bug_file:
now = datetime.now()
dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
string_index = "Time:" + dt_string + "Generation: " + str(generation) + ", Individual: " + str(j+1) +", Bug: " + str(output_trace["testFailures"]) +'\n'
bug_file.write(string_index)
json.dump(output_trace, bug_file, indent=2)
bug_file.write('\n')
elif len(output_trace['trace']) == 1:
logging.info("Only one state. Is reached: {}, minimal distance: {}".format(output_trace['destinationReached'], output_trace['minEgoObsDist']))
testcase = TestCaseRandom(output_trace)
testcase.testcase_random(1)
next_new_testcases.append(testcase.cases[-1])
else:
testcase = TestCaseRandom(output_trace)
testcase.testcase_random(1)
next_new_testcases.append(testcase.cases[-1])
logging.info("No trace for the test cases!")
with open(directory + '/NoTrace.txt', 'a') as f:
now = datetime.now()
dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
f.write("Time: Generation: {}, Individual: {}".format(dt_string, generation, j))
json.dump(new_testcases[j], f, indent=2)
f.write('\n')
init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
await websocket.send(init_msg)
break
# logging.info('Running Generation: {}, Individual: {}'.format(generation, j+1))
# send_msg = {'CMD': "CMD_NEW_TEST", 'DATA': new_testcases[j]}
# await websocket.send(json.dumps(send_msg))
# while True:
# msg_valid = await websocket.recv()
# msg_valid = json.loads(msg_valid)
# # print("Received Message: " + msg_valid['TYPE'])
# # if msg_valid['TYPE'] == 'ERROR' or 'TEST_STARTED':
# # print(msg_valid)
# if msg_valid['TYPE'] == 'TEST_TERMINATED' or msg_valid['TYPE'] == 'ERROR':
# print(msg_valid)
# print("Try to reconnect.")
# time.sleep(3)
# init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
# await websocket.send(init_msg)
# msg = await websocket.recv()
# msg = json.loads(msg)
# if msg['TYPE'] == 'READY_FOR_NEW_TEST' and msg['DATA']:
# send_msg = {'CMD': "CMD_NEW_TEST", 'DATA': new_testcases[j]}
# await websocket.send(json.dumps(send_msg))
# continue
# elif msg_valid['TYPE'] == 'TEST_COMPLETED':
# output_trace = msg_valid['DATA']
# now = datetime.now()
# dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
# file = directory + '/data/result' + dt_string + '.json'
# with open(file, 'w') as outfile:
# json.dump(output_trace, outfile, indent=2)
# logging.info("The number of states in the trace is {}".format(len(output_trace['trace'])))
# if not output_trace['destinationReached']:
# with open(directory + '/Incompleted.txt', 'a') as f:
# json.dump(new_testcases[j], f, indent=2)
# f.write('\n')
# if len(output_trace['trace']) > 1:
# encoded_testcase = EncodedTestCase(output_trace, single_spec)
# logging.info(" Fitness Value: {}".format(encoded_testcase.fitness))
# ave_fitness += encoded_testcase.fitness
# if encoded_testcase.fitness < generation_fitness:
# generation_fitness = encoded_testcase.fitness
# del encoded_testcase.trace
# if encoded_testcase.fitness < 0.0:
# with open(directory + '/bugTestCase.txt', 'a') as bug_file:
# now = datetime.now()
# dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
# string_index = "Time:" + dt_string + "Generation: " + str(generation) + ", Individual: " + str(j+1) + '\n'
# bug_file.write(string_index)
# json.dump(output_trace, bug_file, indent=2)
# bug_file.write('\n')
# population.append(encoded_testcase)
# elif len(output_trace['trace']) == 1:
# logging.info("Only one state. Is reached: {}, minimal distance: {}".format(output_trace['destinationReached'], output_trace['minEgoObsDist']))
# testcase = TestCaseRandom(output_trace)
# testcase.testcase_random(1)
# next_new_testcases.append(testcase.cases[-1])
# else:
# testcase = TestCaseRandom(output_trace)
# testcase.testcase_random(1)
# next_new_testcases.append(testcase.cases[-1])
# logging.info("No trace for the test cases!")
# with open(directory + '/NoTrace.txt', 'a') as f:
# now = datetime.now()
# dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
# f.write("Time: Generation: {}, Individual: {}".format(dt_string, generation, j))
# json.dump(new_testcases[j], f, indent=2)
# f.write('\n')
# break
min_fitness_list.append(generation_fitness)
ave_fitness_list.append(ave_fitness/population_size)
logging.info("The minimal fitness in generation {} is {}.".format(generation, generation_fitness))
logging.info("The average fitness in generation {} is {}.".format(generation, ave_fitness/population_size))
if len(population):
new_population_obj = GAGeneration(population)
new_population = new_population_obj.one_generation()
decoder = DecodedTestCase(new_population)
ga_new_testcases = decoder.decoding()
next_new_testcases.extend(ga_new_testcases)
new_testcases = copy.deepcopy(next_new_testcases)
with open(directory + '/TestCase.txt', 'a') as outfile:
for i in range(len(new_testcases)):
try:
json.dump(new_testcases[i], outfile, indent=2)
outfile.write('\n')
except TypeError:
logging.info("Check the types of test cases")
# The last generation
ave_fitness = 0
generation_fitness = float('inf')
for j in range(len(new_testcases)):
while True:
msg = await websocket.recv()
msg = json.loads(msg)
# print(msg['TYPE'])
if msg['TYPE'] == 'READY_FOR_NEW_TEST':
if msg['DATA']:
logging.info('Running Generation: {}, Individual: {}'.format(generation, j + 1))
send_msg = {'CMD': "CMD_NEW_TEST", 'DATA': new_testcases[j]}
await websocket.send(json.dumps(send_msg))
else:
asyncio.sleep(3)
init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
await websocket.send(init_msg)
elif msg['TYPE'] == 'TEST_TERMINATED' or msg['TYPE'] == 'ERROR':
print(msg)
print("Try to reconnect.")
asyncio.sleep(3)
init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
await websocket.send(init_msg)
elif msg['TYPE'] == 'KEEP_SERVER_AND_CLIENT_ALIVE':
send_msg = {'CMD': "KEEP_SERVER_AND_CLIENT_ALIVE", 'DATA': None}
await websocket.send(json.dumps(send_msg))
elif msg['TYPE'] == 'TEST_COMPLETED':
output_trace = msg['DATA']
now = datetime.now()
dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
file = directory + '/data/result' + dt_string + '.json'
with open(file, 'w') as outfile:
json.dump(output_trace, outfile, indent=2)
logging.info("The number of states in the trace is {}".format(len(output_trace['trace'])))
if not output_trace['destinationReached']:
with open(directory + '/Incompleted.txt', 'a') as f:
json.dump(new_testcases[j], f, indent=2)
f.write('\n')
if len(output_trace['trace']) > 1:
encoded_testcase = EncodedTestCase(output_trace, single_spec)
logging.info(" Fitness Value: {}".format(encoded_testcase.fitness))
ave_fitness += encoded_testcase.fitness
if encoded_testcase.fitness < generation_fitness:
generation_fitness = encoded_testcase.fitness
del encoded_testcase.trace
if encoded_testcase.fitness <= 0.0:
with open(directory + '/bugTestCase.txt', 'a') as bug_file:
now = datetime.now()
dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
string_index = "Time:" + dt_string + "Generation: " + str(
generation) + ", Individual: " + str(j + 1) + '\n'
bug_file.write(string_index)
string_index2 = "The detailed fitness values:" + str(encoded_testcase.muti_fitness) + '\n'
bug_file.write(string_index2)
json.dump(output_trace, bug_file, indent=2)
bug_file.write('\n')
population.append(encoded_testcase)
if output_trace["testFailures"]!= []:
with open(directory + '/exceptionTestCase.txt', 'a') as bug_file:
now = datetime.now()
dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
string_index = "Time:" + dt_string + "Generation: " + str("last") + ", Individual: " + str(j+1) +", Bug: " + str(output_trace["testFailures"]) +'\n'
bug_file.write(string_index)
json.dump(output_trace, bug_file, indent=2)
bug_file.write('\n')
elif len(output_trace['trace']) == 1:
logging.info("Only one state. Is reached: {}, minimal distance: {}".format(
output_trace['destinationReached'], output_trace['minEgoObsDist']))
testcase = TestCaseRandom(output_trace)
testcase.testcase_random(1)
next_new_testcases.append(testcase.cases[-1])
else:
testcase = TestCaseRandom(output_trace)
testcase.testcase_random(1)
next_new_testcases.append(testcase.cases[-1])
logging.info("No trace for the test cases!")
with open(directory + '/NoTrace.txt', 'a') as f:
now = datetime.now()
dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
f.write("Time: Generation: {}, Individual: {}".format(dt_string, generation, j))
json.dump(new_testcases[j], f, indent=2)
f.write('\n')
init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
await websocket.send(init_msg)
break
# logging.info('Generation: {}, Individual: {}'.format(generation + 1, j+1))
# send_msg = {'CMD': "CMD_NEW_TEST", 'DATA': new_testcases[j]}
# await websocket.send(json.dumps(send_msg))
# while True:
# msg_valid = await websocket.recv()
# msg_valid = json.loads(msg_valid)
# # print("Received Message: " + msg_valid['TYPE'])
# # if msg_valid['TYPE'] == 'ERROR' or 'TEST_STARTED':
# # print(msg_valid)
# if msg_valid['TYPE'] == 'TEST_TERMINATED' or msg_valid['TYPE'] == 'ERROR':
# print("Try to reconnect!")
# time.sleep(3)
# init_msg = json.dumps({'CMD': "CMD_READY_FOR_NEW_TEST"})
# await websocket.send(init_msg)
# msg = await websocket.recv()
# msg = json.loads(msg)
# if msg['TYPE'] == 'READY_FOR_NEW_TEST' and msg['DATA']:
# send_msg = {'CMD': "CMD_NEW_TEST", 'DATA': new_testcases[j]}
# await websocket.send(json.dumps(send_msg))
# continue
# elif msg_valid['TYPE'] == 'TEST_COMPLETED':
# output_trace = msg_valid['DATA']
# now = datetime.now()
# dt_string = now.strftime("%d-%m-%Y-%H-%M-%S")
# file = directory + '/data/result' + dt_string + '.json'
# with open(file, 'w') as outfile:
# json.dump(output_trace, outfile, indent=2)
# if not output_trace['destinationReached']:
# with open(directory + '/Incompleted.txt', 'a') as f:
# json.dump(new_testcases[j], f, indent=2)
# f.write('\n')
# if len(output_trace['trace']) > 1:
# encoded_testcase = EncodedTestCase(output_trace, single_spec)
# logging.info(" Fitness Value: {}".format(encoded_testcase.fitness))
# if encoded_testcase.fitness < generation_fitness:
# generation_fitness = encoded_testcase.fitness
# del encoded_testcase.trace
# ave_fitness += encoded_testcase.fitness
# if encoded_testcase.fitness < 0.0:
# with open(directory + '/bugTestCase.txt', 'a') as bug_file:
# string_index = "Generation: " + str(generation + 1) + ", Individual: " + str(j+1) + '\n'
# bug_file.write(string_index)
# json.dump(output_trace, bug_file, indent=2)
# bug_file.write('\n')
# elif len(output_trace['trace']) == 1:
# logging.info("Is reached: {}, minimal distance: {}".format(output_trace['destinationReached'], output_trace['minEgoObsDist']))
# else:
# logging.info("No trace for the test cases!")
# with open(directory + '/NoTrace.txt', 'a') as f:
# json.dump(new_testcases[j], f, indent=2)
# f.write('\n')
# break
min_fitness_list.append(generation_fitness)
ave_fitness_list.append(ave_fitness/population_size)
logging.info("The minimal fitness for the last generation is {}.".format(generation_fitness))
logging.info("The average fitness for the last generation is {}.".format(ave_fitness/population_size))
# logging.info("Minimal fitness: {}".format(min_fitness_list))
# logging.info("Average fitness: {}".format(ave_fitness_list))
def spec_scenario(spec, testcase, generations=0, pop_size=1,file_directory=None):
loop = asyncio.get_event_loop()
scenario_specification = copy.deepcopy(spec)
scenario_testcase = copy.deepcopy(testcase)
msgs = [scenario_testcase]
# scenario_specification = 0
with open(file_directory + '/InitTestCase.txt', 'w') as f:
json.dump(scenario_testcase, f, indent=2)
loop.run_until_complete(
asyncio.gather(hello(msgs, scenario_specification, generation_number=generations, population_size=pop_size, directory=file_directory)))
def test_scenario(direct, item, scenario_spec):
file = direct + item
# file0 = FileStream(file)
with open(file) as json_file:
file0 = json.load(json_file)
log_direct = 'bugs/' + Path(item).stem
if not os.path.exists(log_direct):
os.makedirs(log_direct)
else:
shutil.rmtree(log_direct)
if not os.path.exists(log_direct + '/data'):
os.makedirs(log_direct + '/data')
logging_file = log_direct + '/test.log'
file_handler = logging.FileHandler(logging_file, mode='w')
stdout_handler = logging.StreamHandler(sys.stdout)
logging.basicConfig(level=logging.INFO, handlers=[stdout_handler, file_handler], format='%(asctime)s, %(levelname)s: %(message)s', datefmt="%Y-%m-%d %H:%M:%S")
logging.info("Current Test Case: {}".format(item))
# isGroundTruth = True
# extracted_data = ExtractAll(file, isGroundTruth)
# testcases = extracted_data.Get_TestCastINJsonList()
# all_specifications = extracted_data.Get_Specifications()
# maps = extracted_data.Get_AllMaps()
test_case = file0
scenario_name = test_case['ScenarioName']
# logging.info("Current scenario is {}.\n".format(scenario_name))
try:
specifications_in_scenario = scenario_spec[scenario_name]
current_map = "san_francisco"
ego_init_start = test_case['ego']['start']
map_info = get_map_info(current_map)
if "lane_position" in ego_init_start.keys():
lane_position = ego_init_start['lane_position']
ego_position = map_info.get_position([lane_position['lane'], lane_position['offset']])
else:
ego_position = (ego_init_start['position']['x'], ego_init_start['position']['y'], ego_init_start['position']['z'])
for spec_index in range(len(specifications_in_scenario)):
first_specification = specifications_in_scenario[spec_index]
single_specification = SingleAssertion(first_specification, current_map, ego_position)
# single_spec = SingleAssertion(scenario_spec[scenario_name][0], "san_francisco")
# single_specification = single_spec
spec_scenario(spec=single_specification, testcase=test_case,generations=0, pop_size=2, file_directory=log_direct)
except KeyError:
spec_scenario(spec={}, testcase=test_case)
if __name__ == "__main__":
input_file = 'input-test.txt'
# input_file = 'test_cases/final/intersection2.txt'
# # input_file = 'test_cases/intersection/intersection1.txt'
isGroundTruth = True
extracted_script = ExtractAll(input_file,isGroundTruth)
scenario_spec = extracted_script.Get_Specifications()
# single_spec = SingleAssertion(scenario_spec[scenario_name][0], "san_francisco")
direct = 'rerun_for_videos/'
item = 'test.json'
test_scenario(direct, item, scenario_spec)