-
Notifications
You must be signed in to change notification settings - Fork 7
/
ci.py
executable file
·1446 lines (1266 loc) · 52.8 KB
/
ci.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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import re
import os
import sys
import time
import urllib
import urllib2
import json
import shutil
import string
import difflib
import logging
import optparse
import tempfile
import fileinput
import traceback
from virttest import common
from virttest import utils_libvirtd, utils_selinux
from virttest import data_dir
from virttest import virsh
from virttest.staging import service
from autotest.client import utils
from virttest.utils_misc import mount, umount
from autotest.client.tools import JUnit_api as api
from autotest.client.shared import error
from datetime import date
class Report():
"""
This is a wrapper of autotest.client.tools.JUnit_api
"""
class testcaseType(api.testcaseType):
def __init__(self, classname=None, name=None, time=None, error=None,
failure=None, skip=None):
api.testcaseType.__init__(self, classname, name, time, error,
failure)
self.skip = skip
self.system_out = None
self.system_err = None
def exportChildren(self, outfile, level, namespace_='',
name_='testcaseType', fromsubclass_=False):
api.testcaseType.exportChildren(
self, outfile, level, namespace_, name_, fromsubclass_)
if self.skip is not None:
self.skip.export(outfile, level, namespace_, name_='skipped')
if self.system_out is not None:
outfile.write(
'<%ssystem-out><![CDATA[%s]]></%ssystem-out>\n' % (
namespace_,
self.system_out,
namespace_))
if self.system_err is not None:
outfile.write(
'<%ssystem-err><![CDATA[%s]]></%ssystem-err>\n' % (
namespace_,
self.system_err,
namespace_))
def hasContent_(self):
if (
self.system_out is not None or
self.system_err is not None or
self.error is not None or
self.failure is not None or
self.skip is not None
):
return True
else:
return False
class failureType(api.failureType):
def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='failureType'):
if self.message is not None and 'message' not in already_processed:
already_processed.append('message')
outfile.write(' message="%s"' % self.message)
if self.type_ is not None and 'type_' not in already_processed:
already_processed.append('type_')
outfile.write(' type="%s"' % self.type_)
class errorType(api.errorType):
def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='errorType'):
if self.message is not None and 'message' not in already_processed:
already_processed.append('message')
outfile.write(' message="%s"' % self.message)
if self.type_ is not None and 'type_' not in already_processed:
already_processed.append('type_')
outfile.write(' type="%s"' % self.type_)
class skipType(api.failureType):
pass
class testsuite(api.testsuite):
def __init__(self, name=None, skips=None):
api.testsuite.__init__(self, name=name)
self.skips = api._cast(int, skips)
def exportAttributes(
self, outfile, level, already_processed,
namespace_='', name_='testsuite'):
api.testsuite.exportAttributes(self,
outfile, level, already_processed,
namespace_, name_)
if self.skips is not None and 'skips' not in already_processed:
already_processed.append('skips')
outfile.write(' skipped="%s"' %
self.gds_format_integer(self.skips,
input_name='skipped'))
def __init__(self, fail_diff=False):
self.ts_dict = {}
self.fail_diff = fail_diff
def save(self, filename):
"""
Save current state of report to files.
"""
testsuites = api.testsuites()
for ts_name in self.ts_dict:
ts = self.ts_dict[ts_name]
testsuites.add_testsuite(ts)
with open(filename, 'w') as fp:
testsuites.export(fp, 0)
def update(self, testname, ts_name, result, log, error_msg, duration):
"""
Insert a new item into report.
"""
def escape_str(inStr):
"""
Escape a string for HTML use.
"""
s1 = (isinstance(inStr, basestring) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&')
s1 = s1.replace('<', '<')
s1 = s1.replace('>', '>')
s1 = s1.replace('"', """)
return s1
if ts_name not in self.ts_dict:
self.ts_dict[ts_name] = self.testsuite(name=ts_name)
ts = self.ts_dict[ts_name]
ts.failures = 0
ts.skips = 0
ts.tests = 0
ts.errors = 0
else:
ts = self.ts_dict[ts_name]
tc = self.testcaseType()
tc.name = testname
tc.time = duration
# Filter non-printable characters in log
log = ''.join(s for s in unicode(log, errors='ignore')
if s in string.printable)
tc.system_out = log
tmp_msg = []
for line in error_msg:
# Filter non-printable characters in error message
line = ''.join(s for s in unicode(line, errors='ignore')
if s in string.printable)
tmp_msg.append(escape_str(line))
error_msg = tmp_msg
if 'FAIL' in result:
error_msg.insert(0, 'Test %s has failed' % testname)
tc.failure = self.failureType(
message=' '.join(error_msg),
type_='Failure')
ts.failures += 1
elif 'TIMEOUT' in result:
error_msg.insert(0, 'Test %s has timed out' % testname)
tc.failure = self.failureType(
message=' '.join(error_msg),
type_='Timeout')
ts.failures += 1
elif 'ERROR' in result or 'INVALID' in result:
error_msg.insert(0, 'Test %s has encountered error' % testname)
tc.error = self.errorType(
message=' '.join(error_msg),
type_='Error')
ts.errors += 1
elif 'SKIP' in result:
error_msg.insert(0, 'Test %s is skipped' % testname)
tc.skip = self.skipType(
message=' '.join(error_msg),
type_='Skip')
ts.skips += 1
elif 'DIFF' in result and self.fail_diff:
error_msg.insert(0, 'Test %s results dirty environment' % testname)
tc.failure = self.failureType(
message=' '.join(error_msg),
type_='DIFF')
ts.failures += 1
ts.add_testcase(tc)
ts.tests += 1
ts.timestamp = date.isoformat(date.today())
class State():
permit_keys = []
permit_re = []
def get_names(self):
raise NotImplementedError('Function get_names not implemented for %s.'
% self.__class__.__name__)
def get_info(self, name):
raise NotImplementedError('Function get_info not implemented for %s.'
% self.__class__.__name__)
def remove(self, name):
raise NotImplementedError('Function remove not implemented for %s.'
% self.__class__.__name__)
def restore(self, name):
raise NotImplementedError('Function restore not implemented for %s.'
% self.__class__.__name__)
def get_state(self):
names = self.get_names()
state = {}
for name in names:
state[name] = self.get_info(name)
return state
def backup(self):
"""
Backup current state
"""
self.backup_state = self.get_state()
def check(self, recover=False):
"""
Check state changes and recover to specified state.
Return a result.
"""
def diff_dict(dict_old, dict_new):
created = set(dict_new) - set(dict_old)
deleted = set(dict_old) - set(dict_new)
shared = set(dict_old) & set(dict_new)
return created, deleted, shared
def lines_permitable(diff, permit_re):
"""
Check whether the diff message is in permitable list of regexs.
"""
diff_lines = set()
for line in diff[2:]:
if re.match(r'^[-+].*', line):
diff_lines.add(line)
for line in diff_lines:
permit = False
for r in permit_re:
if re.match(r, line):
permit = True
break
if not permit:
return False
return True
self.current_state = self.get_state()
diff_msg = []
new_items, del_items, unchanged_items = diff_dict(
self.backup_state, self.current_state)
if new_items:
diff_msg.append('Created %s(s):' % self.name)
for item in new_items:
diff_msg.append(item)
if recover:
try:
self.remove(self.current_state[item])
except Exception, e:
traceback.print_exc()
diff_msg.append('Remove is failed:\n %s' % e)
if del_items:
diff_msg.append('Deleted %s(s):' % self.name)
for item in del_items:
diff_msg.append(item)
if recover:
try:
self.restore(self.backup_state[item])
except Exception, e:
traceback.print_exc()
diff_msg.append('Recover is failed:\n %s' % e)
for item in unchanged_items:
cur = self.current_state[item]
bak = self.backup_state[item]
item_changed = False
new_keys, del_keys, unchanged_keys = diff_dict(bak, cur)
if new_keys:
item_changed = True
diff_msg.append('Created key(s) in %s %s:' % (self.name, item))
for key in new_keys:
diff_msg.append(key)
if del_keys:
for key in del_keys:
if type(key) is str:
if key not in self.permit_keys:
item_changed = True
diff_msg.append('Deleted key(s) in %s %s:' % (self.name, item))
else:
item_changed = True
diff_msg.append('Deleted key(s) in %s %s:' % (self.name, item))
for key in unchanged_keys:
if type(cur[key]) is str:
if key not in self.permit_keys and cur[key] != bak[key]:
item_changed = True
diff_msg.append('%s %s: %s changed: %s -> %s' % (
self.name, item, key, bak[key], cur[key]))
elif type(cur[key]) is list:
diff = difflib.unified_diff(
bak[key], cur[key], lineterm="")
tmp_msg = []
for line in diff:
tmp_msg.append(line)
if tmp_msg and not lines_permitable(tmp_msg,
self.permit_re):
item_changed = True
diff_msg.append('%s %s: "%s" changed:' %
(self.name, item, key))
diff_msg += tmp_msg
else:
diff_msg.append('%s %s: %s: Invalid type %s.' % (
self.name, item, key, type(cur[key])))
if item_changed and recover:
try:
self.restore(self.backup_state[item])
except Exception, e:
traceback.print_exc()
diff_msg.append('Recover is failed:\n %s' % e)
return diff_msg
class DomainState(State):
name = 'domain'
permit_keys = ['id', 'cpu time', 'security label']
def remove(self, name):
dom = name
if dom['state'] != 'shut off':
res = virsh.destroy(dom['name'])
if res.exit_status:
raise Exception(str(res))
if dom['persistent'] == 'yes':
# Make sure the domain is remove anyway
res = virsh.undefine(
dom['name'], options='--snapshots-metadata --managed-save')
if res.exit_status:
raise Exception(str(res))
def restore(self, name):
dom = name
name = dom['name']
doms = self.current_state
if name in doms:
self.remove(doms[name])
domfile = tempfile.NamedTemporaryFile(delete=False)
fname = domfile.name
domfile.writelines(dom['inactive xml'])
domfile.close()
try:
if dom['persistent'] == 'yes':
res = virsh.define(fname)
if res.exit_status:
raise Exception(str(res))
if dom['state'] != 'shut off':
res = virsh.start(name)
if res.exit_status:
raise Exception(str(res))
else:
res = virsh.create(fname)
if res.exit_status:
raise Exception(str(res))
finally:
os.remove(fname)
if dom['autostart'] == 'enable':
res = virsh.autostart(name, '')
if res.exit_status:
raise Exception(str(res))
def get_info(self, name):
infos = {}
for line in virsh.dominfo(name).stdout.strip().splitlines():
key, value = line.split(':', 1)
infos[key.lower()] = value.strip()
infos['inactive xml'] = virsh.dumpxml(
name, extra='--inactive').stdout.splitlines()
return infos
def get_names(self):
return virsh.dom_list(options='--all --name').stdout.splitlines()
class NetworkState(State):
name = 'network'
def remove(self, name):
"""
Remove target network _net_.
:param net: Target net to be removed.
"""
net = name
if net['active'] == 'yes':
res = virsh.net_destroy(net['name'])
if res.exit_status:
raise Exception(str(res))
if net['persistent'] == 'yes':
res = virsh.net_undefine(net['name'])
if res.exit_status:
raise Exception(str(res))
def restore(self, name):
"""
Restore networks from _net_.
:param net: Target net to be restored.
:raise CalledProcessError: when restore failed.
"""
net = name
name = net['name']
nets = self.current_state
if name in nets:
self.remove(nets[name])
netfile = tempfile.NamedTemporaryFile(delete=False)
fname = netfile.name
netfile.writelines(net['inactive xml'])
netfile.close()
try:
if net['persistent'] == 'yes':
res = virsh.net_define(fname)
if res.exit_status:
raise Exception(str(res))
if net['active'] == 'yes':
res = virsh.net_start(name)
if res.exit_status:
res = virsh.net_start(name)
if res.exit_status:
raise Exception(str(res))
else:
res = virsh.net_create(fname)
if res.exit_status:
raise Exception(str(res))
finally:
os.remove(fname)
if net['autostart'] == 'yes':
res = virsh.net_autostart(name)
if res.exit_status:
raise Exception(str(res))
def get_info(self, name):
infos = {}
for line in virsh.net_info(name).stdout.strip().splitlines():
key, value = line.split()
if key.endswith(':'):
key = key[:-1]
infos[key.lower()] = value.strip()
infos['inactive xml'] = virsh.net_dumpxml(
name, '--inactive').stdout.splitlines()
return infos
def get_names(self):
lines = virsh.net_list('--all').stdout.strip().splitlines()[2:]
return [line.split()[0] for line in lines]
class PoolState(State):
name = 'pool'
permit_keys = ['available', 'allocation']
permit_re = [r'^[-+]\s*\<(capacity|allocation|available).*$']
def remove(self, name):
"""
Remove target pool _pool_.
:param pool: Target pool to be removed.
"""
pool = name
if pool['state'] == 'running':
res = virsh.pool_destroy(pool['name'])
if not res:
raise Exception(str(res))
if pool['persistent'] == 'yes':
res = virsh.pool_undefine(pool['name'])
if res.exit_status:
raise Exception(str(res))
def restore(self, name):
pool = name
name = pool['name']
pools = self.current_state
if name in pools:
self.remove(pools[name])
pool_file = tempfile.NamedTemporaryFile(delete=False)
fname = pool_file.name
pool_file.writelines(pool['inactive xml'])
pool_file.close()
try:
if pool['persistent'] == 'yes':
res = virsh.pool_define(fname)
if res.exit_status:
raise Exception(str(res))
if pool['state'] == 'running':
res = virsh.pool_start(name)
if res.exit_status:
raise Exception(str(res))
else:
res = virsh.pool_create(fname)
if res.exit_status:
raise Exception(str(res))
except Exception, e:
raise e
finally:
os.remove(fname)
if pool['autostart'] == 'yes':
res = virsh.pool_autostart(name)
if res.exit_status:
raise Exception(str(res))
def get_info(self, name):
infos = {}
for line in virsh.pool_info(name).stdout.strip().splitlines():
key, value = line.split(':', 1)
infos[key.lower()] = value.strip()
infos['inactive xml'] = virsh.pool_dumpxml(
name, '--inactive').splitlines()
infos['volumes'] = virsh.vol_list(name).stdout.strip().splitlines()[2:]
return infos
def get_names(self):
lines = virsh.pool_list('--all').stdout.strip().splitlines()[2:]
return [line.split()[0] for line in lines]
class SecretState(State):
name = 'secret'
permit_keys = []
permit_re = []
def remove(self, name):
secret = name
res = virsh.secret_undefine(secret['uuid'])
if res.exit_status:
raise Exception(str(res))
def restore(self, name):
uuid = name
cur = self.current_state
bak = self.backup_state
if uuid in cur:
self.remove(name)
secret_file = tempfile.NamedTemporaryFile(delete=False)
fname = secret_file.name
secret_file.writelines(bak[name]['xml'])
secret_file.close()
try:
res = virsh.secret_define(fname)
if res.exit_status:
raise Exception(str(res))
except Exception, e:
raise e
finally:
os.remove(fname)
def get_info(self, name):
infos = {}
infos['uuid'] = name
infos['xml'] = virsh.secret_dumpxml(name).stdout.splitlines()
return infos
def get_names(self):
lines = virsh.secret_list().stdout.strip().splitlines()[2:]
return [line.split()[0] for line in lines]
class MountState(State):
name = 'mount'
permit_keys = []
permit_re = []
info = {}
def remove(self, name):
info = name
# ugly workaround for nfs which unable to umount
#os.system('systemctl restart nfs')
if not umount(info['src'], info['mount_point'], info['fstype'],
verbose=False):
raise Exception("Failed to unmount %s" % info['mount_point'])
def restore(self, name):
info = name
if not mount(info['src'], info['mount_point'], info['fstype'],
info['options'], verbose=False):
raise Exception("Failed to mount %s" % info['mount_point'])
def get_info(self, name):
return self.info[name]
def get_names(self):
"""
Get all mount infomations from /etc/mtab.
:return: A dict using mount point as keys and 6-element dict as value.
"""
lines = file('/etc/mtab').read().splitlines()
names = []
for line in lines:
values = line.split()
if len(values) != 6:
print 'Warning: Error parsing mountpoint: %s' % line
continue
keys = ['src', 'mount_point', 'fstype', 'options', 'dump', 'order']
mount_entry = dict(zip(keys, values))
mount_point = mount_entry['mount_point']
names.append(mount_point)
self.info[mount_point] = mount_entry
return names
class ServiceState(State):
name = 'service'
libvirtd = utils_libvirtd.Libvirtd()
permit_keys = []
permit_re = []
def remove(self, name):
raise Exception('It is meaningless to remove service %s' % name)
def restore(self, name):
info = name
if info['name'] == 'libvirtd':
if info['status'] == 'running':
if not self.libvirtd.start():
raise Exception('Failed to start libvirtd')
elif info['status'] == 'stopped':
if not self.libvirtd.stop():
raise Exception('Failed to stop libvirtd')
else:
raise Exception('Unknown libvirtd status %s' % info['status'])
elif info['name'] == 'selinux':
utils_selinux.set_status(info['status'])
else:
raise Exception('Unknown service %s' % info['name'])
def get_info(self, name):
if name == 'libvirtd':
if self.libvirtd.is_running():
status = 'running'
else:
status = 'stopped'
if name == 'selinux':
status = utils_selinux.get_status()
return {'name': name, 'status': status}
def get_names(self):
return ['libvirtd', 'selinux']
class DirState(State):
name = 'directory'
permit_keys = ['aexpect']
permit_re = []
def remove(self, name):
raise Exception('It is not wise to remove a dir %s' % name)
def restore(self, name):
dirname = name['dir-name']
cur = self.current_state[dirname]
bak = self.backup_state[dirname]
created_files = set(cur) - set(bak)
if created_files:
for fname in created_files:
fpath = os.path.join(name['dir-name'], fname)
if os.path.isfile(fpath):
os.remove(fpath)
elif os.path.isdir(fpath):
shutil.rmtree(fpath)
deleted_files = set(bak) - set(cur)
if deleted_files:
for fname in deleted_files:
fpath = os.path.join(name['dir-name'], fname)
open(fpath, 'a').close()
# TODO: record file/dir info and recover them separately
def get_info(self, name):
infos = {}
infos['dir-name'] = name
for f in os.listdir(name):
infos[f] = f
return infos
def get_names(self):
return ['/tmp',
data_dir.get_tmp_dir(),
os.path.join(data_dir.get_root_dir(), 'shared'),
os.path.join(data_dir.get_data_dir(), 'images'),
'/var/lib/libvirt/images']
class FileState(State):
name = 'file'
permit_keys = []
permit_re = []
def remove(self, name):
raise Exception('It is not wise to remove a system file %s' % name)
def restore(self, name):
file_path = name['file-path']
cur = self.current_state[file_path]
bak = self.backup_state[file_path]
if cur['content'] != bak['content']:
with open(file_path, 'w') as f:
f.write(bak['content'])
def get_info(self, name):
infos = {}
infos['file-path'] = name
with open(name) as f:
infos['content'] = f.read()
return infos
def get_names(self):
return ['/etc/exports',
'/etc/libvirt/libvirtd.conf',
'/etc/libvirt/qemu.conf']
class LibvirtCI():
def parse_args(self):
parser = optparse.OptionParser(
description='Continuouse integration of '
'virt-test libvirt test provider.')
parser.add_option('--list', dest='list', action='store_true',
help='List all the test names')
parser.add_option('--no', dest='no', action='store', default='',
help='Exclude specified tests.')
parser.add_option('--only', dest='only', action='store', default='',
help='Run only for specified tests.')
parser.add_option('--no-check', dest='no_check', action='store_true',
help='Disable checking state changes after each test.')
parser.add_option('--no-recover', dest='no_recover', action='store_true',
help='Disable recover state changes after each test.')
parser.add_option('--connect-uri', dest='connect_uri', action='store',
default='', help='Run tests using specified uri.')
parser.add_option('--additional-vms', dest='add_vms', action='store',
default='', help='Additional VMs for testing')
parser.add_option('--smoke', dest='smoke', action='store_true',
help='Run one test for each script.')
parser.add_option('--slice', dest='slice', action='store',
default='', help='Specify a URL to slice tests.')
parser.add_option('--report', dest='report', action='store',
default='xunit_result.xml',
help='Exclude specified tests.')
parser.add_option('--white', dest='whitelist', action='store',
default='', help='Whitelist file contains '
'specified test cases to run.')
parser.add_option('--black', dest='blacklist', action='store',
default='', help='Blacklist file contains '
'specified test cases to be excluded.')
parser.add_option('--config', dest='config', action='store',
default='', help='Specify a custom Cartesian cfg '
'file')
parser.add_option('--img-url', dest='img_url', action='store',
default='', help='Specify a URL to a custom image '
'file')
parser.add_option('--os-variant', dest='os_variant', action='store',
default='', help='Specify the --os-variant option '
'when doing virt-install.')
parser.add_option('--password', dest='password', action='store',
default='', help='Specify a password for logging '
'into guest')
parser.add_option('--pull-virt-test', dest='virt_test_pull',
action='store', default='',
help='Merge specified virt-test pull requests. '
'Multiple pull requests are separated by ",", '
'example: --pull-virt-test 175,183')
parser.add_option('--pull-libvirt', dest='libvirt_pull',
action='store', default='',
help='Merge specified tp-libvirt pull requests. '
'Multiple pull requests are separated by ",", '
'example: --pull-libvirt 175,183')
parser.add_option('--with-dependence', dest='with_dependence',
action='store_true',
help='Merge virt-test pull requests depend on')
parser.add_option('--no-restore-pull', dest='no_restore_pull',
action='store_true', help='Do not restore repo '
'to branch master after test.')
parser.add_option('--only-change', dest='only_change',
action='store_true', help='Only test tp-libvirt '
'test cases related to changed files.')
parser.add_option('--fail-diff', dest='fail_diff',
action='store_true', help='Report tests who do '
'not clean up environment as a failure')
parser.add_option('--retain-vm', dest='retain_vm',
action='store_true', help='Do not reinstall VM '
'before tests')
parser.add_option('--pre-cmd', dest='pre_cmd',
action='store', help='Run a command line after '
'fetch the source code and before running the test.')
parser.add_option('--post-cmd', dest='post_cmd',
action='store', help='Run a command line after '
'running the test')
parser.add_option('--timeout', dest='timeout',
action='store', default='1200',
help='Maximum run time for one test case')
self.args, self.real_args = parser.parse_args()
def prepare_tests(self, whitelist='whitelist.test',
blacklist='blacklist.test'):
"""
Get all tests to be run.
When a whitelist is given, only tests in whitelist will be run.
When a blacklist is given, tests in blacklist will be excluded.
"""
def read_tests_from_file(file_name):
"""
Read tests from a file
"""
try:
tests = []
with open(file_name) as fp:
for line in fp:
if not line.strip().startswith('#'):
tests.append(line.strip())
return tests
except IOError:
return None
def get_all_tests():
"""
Get all libvirt tests.
"""
if type(self.onlys) == set and not self.onlys:
return []
cmd = './run -t libvirt --list-tests'
if self.args.connect_uri:
cmd += ' --connect-uri %s' % self.args.connect_uri
if self.nos:
cmd += ' --no %s' % ','.join(self.nos)
if self.onlys:
cmd += ' --tests %s' % ','.join(self.onlys)
if self.args.config:
cmd += ' -c %s' % self.args.config
res = utils.run(cmd)
out, err, exitcode = res.stdout, res.stderr, res.exit_status
tests = []
class_names = set()
for line in out.splitlines():
if line:
if line[0].isdigit():
test = re.sub(r'^[0-9]+ (.*) \(requires root\)$',
r'\1', line)
if self.args.smoke:
class_name, _ = self.split_name(test)
if class_name in class_names:
continue
else:
class_names.add(class_name)
tests.append(test)
return tests
def change_to_only(change_list):
"""
Transform the content of a change file to a only set.
"""
onlys = set()
for line in change_list:
filename = line.strip()
res = re.match('libvirt/tests/(cfg|src)/(.*).(cfg|py)',
filename)
if res:
cfg_path = 'libvirt/tests/cfg/%s.cfg' % res.groups()[1]
tp_dir = data_dir.get_test_provider_dir(
'io-github-autotest-libvirt')
cfg_path = os.path.join(tp_dir, cfg_path)
try:
with open(cfg_path) as fcfg:
only = fcfg.readline().strip()
only = only.lstrip('-').rstrip(':').strip()
onlys.add(only)
except:
pass
return onlys
self.nos = set(['io-github-autotest-qemu'])
self.onlys = None
if self.args.only:
self.onlys = set(self.args.only.split(','))
if self.args.slice:
slices = {}
slice_opts = self.args.slice.split(',')
slice_url = slice_opts[0]
slice_opts = slice_opts[1:]
config = urllib2.urlopen(slice_url)
for line in config:
key, val = line.split()
slices[key] = val
for slice_opt in slice_opts:
if slice_opt in slices:
if self.onlys is None:
self.onlys = set(slices[slice_opt].split(','))
else:
self.onlys |= set(slices[slice_opt].split(','))
elif slice_opt == 'other':
for key in slices:
self.nos |= set(slices[key].split(','))
if self.args.no:
self.nos |= set(self.args.no.split(','))
if self.args.only_change:
if self.onlys is not None:
self.onlys &= change_to_only(self.libvirt_file_changed)
else:
self.onlys = change_to_only(self.libvirt_file_changed)
if self.args.whitelist:
tests = read_tests_from_file(whitelist)
else:
tests = get_all_tests()
if self.args.blacklist:
black_tests = read_tests_from_file(blacklist)
tests = [t for t in tests if t not in black_tests]
with open('run.test', 'w') as fp:
for test in tests:
fp.write(test + '\n')
return tests
def split_name(self, name):
"""
Try to return the module name of a test.
"""
if name.startswith('type_specific.io-github-autotest-libvirt'):
name = name.split('.', 2)[2]
if name.split('.')[0] in ['virsh']:
package_name, name = name.split('.', 1)
else:
package_name = ""
names = name.split('.', 1)
if len(names) == 2:
name, test_name = names
else:
name = names[0]
test_name = name
if package_name:
class_name = '.'.join((package_name, name))
else:
class_name = name
return class_name, test_name
def bootstrap(self):
class _Options(object):
pass
from virttest import bootstrap
logging.info('Bootstrapping')
sys.stdout.flush()
base_dir = data_dir.get_data_dir()
if os.path.exists(base_dir):
if os.path.islink(base_dir) or os.path.isfile(base_dir):
os.unlink(base_dir)