-
Notifications
You must be signed in to change notification settings - Fork 27
/
cb-replay
executable file
·1444 lines (1151 loc) · 42.7 KB
/
cb-replay
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
"""
CB POV / Poll communication verification tool
Copyright (C) 2014 - Brian Caswell <bmc@lungetech.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
This tool allows for deterministic communication to a CGC Challenge Binary
using a communication spec [0] defined in XML. Results are logged in the TAP
format [1].
0 - file:///usr/share/cgc-docs/replay.dtd
1 - http://testanything.org/
"""
import os
import argparse
import multiprocessing
import signal
import re
import socket
import struct
import time
import zipfile
import defusedxml.ElementTree as ET
class RegexMatch(object):
""" Simple wrapper for handling regexes in Throw.
Attributes:
group: which re group to use when extracting data
regex: The compiled re to be evaluated
"""
def __init__(self, regex, group=None):
if group is None:
group = 0
self.regex = regex
self.group = group
def match(self, data):
"""
Match the compiled regular expression
Arguments:
data: Data to match
Returns:
Result of the re.match call
Raises
None
"""
return self.regex.match(data)
class _ValueStr(str):
""" Wrapper class, used to specify the string is meant to be a 'key' in the
Throw.values key/value store."""
pass
class TimeoutException(Exception):
""" Exception to be used by Timeout(), to allow catching of timeout
exceptions """
pass
class TestFailure(Exception):
""" Exception to be used by Throw(), to allow catching of test failures """
pass
class Timeout(object):
""" Timeout - A class to use within 'with' for timing out a block via
exceptions and alarm."""
def __init__(self, seconds):
self.seconds = seconds
@staticmethod
def cb_handle_timeout(signum, frame):
""" SIGALRM signal handler callback """
raise TimeoutException("timed out")
def __enter__(self):
if self.seconds:
signal.signal(signal.SIGALRM, self.cb_handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, exit_type, exit_value, traceback):
if self.seconds:
signal.alarm(0)
class Throw(object):
"""Throw - Perform the interactions with a CB
This class implements the basic methods to interact with a CB, verifying
the interaction works as expected.
Usage:
a = Throw((source_ip, source_port), (target_ip, target_port), POV,
timeout, should_debug, negotiate)
a.run()
Attributes:
source: touple of host and port for the outbound connection
target: touple of host and port for the CB
count: Number of actions performed
debug: Is debugging enabled
failed: Number of actions that did not work as expected
passed: Number of actions that did worked as expected
pov: POV, as defined by POV()
sock: TCP Socket to the CB
timeout: connection timeout
values: Variable dictionary
logs: all of the output from the interactions
max_send: maxmimum amount of data to send per request
negotiate: Should the CB negotiation process happen
"""
def __init__(self, source, target, pov, timeout, debug, max_send, negotiate):
self.source = source
self.target = target
self.count = 0
self.failed = 0
self.passed = 0
self.pov = pov
self.debug = debug
self.sock = None
self.timeout = timeout
self.values = {}
self.logs = []
self.max_send = max_send
self._read_buffer = ''
self.negotiate = negotiate
def is_ok(self, expected, result, message):
""" Verifies 'expected' is equal to 'result', logging results in TAP
format
Args:
expected: Expected value
result: Action value
message: String describing the action being evaluated
Returns:
legnth: If the 'expected' result is a string, returns the length of
the string, otherwise 0
Raises:
None
"""
if isinstance(expected, _ValueStr):
message += ' (expanded from %s)' % repr(expected)
if expected not in self.values:
message += ' value not provided'
self.log_fail(message)
return 0
expected = self.values[expected]
if isinstance(expected, str):
if result.startswith(expected):
self.log_ok(message)
return len(expected)
else:
if result == expected:
self.log_ok(message)
return 0
if self.debug:
self.log('expected: %s' % repr(expected))
self.log('result: %s' % repr(result))
self.log_fail(message)
return 0
def is_not(self, expected, result, message):
""" Verifies 'expected' is not equal to 'result', logging results in
TAP format
Args:
expected: Expected value
result: Action value
message: String describing the action being evaluated
Returns:
legnth: If the 'expected' result is a string, returns the length of
the string, otherwise 0
Raises:
None
"""
if isinstance(expected, _ValueStr):
message += ' (expanded from %s)' % repr(expected)
if expected not in self.values:
message += ' value not provided'
self.log_fail(message)
return 0
expected = self.values[expected]
if isinstance(expected, str):
if not result.startswith(expected):
self.log_ok(message)
return len(expected)
else:
if result != expected:
self.log_ok(message)
return 0
if self.debug:
self.log('these are expected to be different:')
self.log('expected: %s' % repr(expected))
self.log('result: %s' % repr(result))
self.log_fail(message)
return 0
def log_ok(self, message):
""" Log a test that passed in the TAP format
Args:
message: String describing the action that 'passed'
Returns:
None
Raises:
None
"""
self.passed += 1
self.count += 1
self.logs.append("ok %d - %s" % (self.count, message))
def log_fail(self, message):
""" Log a test that failed in the TAP format
Args:
message: String describing the action that 'passed'
Returns:
None
Raises:
None
"""
self.failed += 1
self.count += 1
self.logs.append("not ok %d - %s" % (self.count, message))
raise TestFailure('failed: %s' % message)
def log(self, message):
""" Log diagnostic information in the TAP format
Args:
message: String being logged
Returns:
None
Raises:
None
"""
self.logs.append("# %s" % message)
def sleep(self, value):
""" Sleep a specified amount
Args:
value: Amount of time to sleep, specified in miliseconds
Returns:
None
Raises:
None
"""
time.sleep(value)
self.log_ok("slept %f" % value)
def declare(self, values):
""" Declare variables for use within the current CB communication
iteration
Args:
values: Dictionary of key/value pair values to be set
Returns:
None
Raises:
None
"""
self.values.update(values)
set_values = [repr(x) for x in values.keys()]
self.log_ok("set values: %s" % ', '.join(set_values))
def _perform_match(self, match, data, invert=False):
""" Validate the data read from the CB is as expected
Args:
match: Pre-parsed expression to validate the data from the CB
data: Data read from the CB
Returns:
None
Raises:
None
"""
offset = 0
for item in match:
if isinstance(item, str):
if invert:
offset += self.is_not(item, data[offset:],
'match: not string')
else:
offset += self.is_ok(item, data[offset:], 'match: string')
elif hasattr(item, 'match'):
match = item.match(data[offset:])
if match:
if invert:
if self.debug:
self.log('pattern: %s' % repr(item.pattern))
self.log('data: %s' % repr(data[offset:]))
self.log_fail('match: not pcre')
else:
self.log_ok('match: pcre')
offset += match.end()
else:
if invert:
self.log_ok('match: not pcre')
else:
if self.debug:
self.log('pattern: %s' % repr(item.pattern))
self.log('data: %s' % repr(data[offset:]))
self.log_fail('match: pcre')
else:
raise Exception('unknown match type: %s' % repr(item))
def _perform_expr(self, expr, key, data):
""" Extract a value from the value read from the CB using 'slice' or
'pcre'
Args:
expr: Pre-parsed expression to extract the value
key: Key to store the value in the instance iteration
data: Data read from the CB
Returns:
None
Raises:
None
"""
value = None
# self.log('PERFORMING EXPR (%s): %s' % (key, repr(expr)))
# self.log('DATA: %s' % repr(data))
if isinstance(expr, slice):
value = data[expr]
elif isinstance(expr, RegexMatch):
match = expr.match(data)
if match:
try:
value = match.group(expr.group)
except IndexError:
self.log_fail('match group unavailable')
else:
self.log_fail('match failed')
else:
self.log_fail('unknown expr type: %s' % repr(expr))
if value is not None:
self.values[key] = value
if self.debug:
self.log('set %s to %s' % (key, value.encode('hex')))
self.log_ok('set %s' % (key))
def _read_len(self, read_len):
"""
Read a specified size, but only ever get 4096 bytes from the socket
"""
if len(self._read_buffer) >= read_len:
data = self._read_buffer[:read_len]
self._read_buffer = self._read_buffer[read_len:]
return data
data = [self._read_buffer]
data_len = len(self._read_buffer)
while data_len < read_len:
left = read_len - data_len
data_read = self.sock.recv(max(4096, left))
if len(data_read) == 0:
self.log_fail('recv failed. (%s so far)' % repr(data))
self._read_buffer = ''.join(data)
return ''
data.append(data_read)
data_len += len(data_read)
data = ''.join(data)
self._read_buffer = data[read_len:]
return data[:read_len]
def _read_delim(self, delim):
"""
Read until a delimiter is found, but only ever get 4096 bytes from the
socket
"""
while delim not in self._read_buffer:
data_read = self.sock.recv(4096)
if len(data_read) == 0:
self.log_fail('recv failed. No data returned.')
return ''
self._read_buffer += data_read
depth = self._read_buffer.index(delim) + len(delim)
data = self._read_buffer[:depth]
self._read_buffer = self._read_buffer[depth:]
return data
def read(self, read_args):
""" Read data from the CB, validating the results
Args:
read_args: Dictionary of arguments
Returns:
None
Raises:
Exception: if 'expr' argument is provided and 'assign' is not
"""
data = ''
try:
if 'length' in read_args:
data = self._read_len(read_args['length'])
self.is_ok(read_args['length'], len(data), 'read length')
elif 'delim' in read_args:
data = self._read_delim(read_args['delim'])
except socket.error as err:
self.log_fail('recv failed: %s' % str(err))
if 'echo' in read_args and self.debug:
assert read_args['echo'] in ['yes', 'no', 'ascii']
if 'yes' == read_args['echo']:
self.log('received %s' % data.encode('hex'))
elif 'ascii' == read_args['echo']:
self.log('received %s' % repr(data))
if 'match' in read_args:
self._perform_match(read_args['match']['values'], data,
read_args['match']['invert'])
if 'expr' in read_args:
assert 'assign' in read_args
self._perform_expr(read_args['expr'], read_args['assign'], data)
def _send_all(self, data, max_send=None):
total_sent = 0
while total_sent < len(data):
if max_send is not None:
sent = self.sock.send(data[total_sent:total_sent+max_send])
# allow the kernel a chance to forward the data
time.sleep(0.00001)
else:
sent = self.sock.send(data[total_sent:])
if sent == 0:
return total_sent
total_sent += sent
return total_sent
def write(self, args):
""" Write data to the CB
Args:
args: Dictionary of arguments
Returns:
None
Raises:
None
"""
data = []
for value in args['value']:
if isinstance(value, _ValueStr):
if value not in self.values:
self.log_fail('write failed: %s not available' % value)
return
data.append(self.values[value])
else:
data.append(value)
to_send = ''.join(data)
if self.debug:
if args['echo'] == 'yes':
self.log('writing: %s' % to_send.encode('hex'))
elif args['echo'] == 'ascii':
self.log('writing: %s' % repr(to_send))
try:
sent = self._send_all(to_send, self.max_send)
if sent != len(to_send):
self.log_fail('write failed. wrote %d of %d bytes' %
(sent, len(to_send)))
return
else:
self.log_ok('write: sent %d bytes' % sent)
except socket.error:
self.log_fail('write failed')
def _encode(self, records):
"""
record is a list of records in the format (type, data)
Current wire format:
RECORD_COUNT (DWORD)
record_0_type (DWORD)
record_0_len (DWORD)
record_0_data (record_0_len bytes)
record_N_type (DWORD)
record_N_len (DWORD)
record_N_data (record_N_len bytes)
"""
packed = []
for record_type, data in records:
packed.append(struct.pack('<LL', record_type, len(data)) + data)
result = struct.pack('<L', len(packed)) + ''.join(packed)
return result
def cb_negotiate(self):
""" Prior to starting the POV comms, setup the seeds with the CB server
Args:
None
Returns:
None
Raises:
None
"""
if not self.negotiate:
return 0
seed = self.pov.seed
if seed is None:
print "# No seed specified, using random seed"
seed = os.urandom(48)
print "# negotiating seed as %s" % seed.encode('hex')
request_seed = (1, seed)
request = [request_seed]
encoded = self._encode(request)
sent = self._send_all(encoded)
if sent != len(encoded):
self.log_fail('negotiate failed. expected to send %d, sent %d' % (len(encoded), sent))
return -1
response_packed = self._read_len(4)
response = struct.unpack('<L', response_packed)[0]
if response != 1:
return -1
return 0
def run(self):
""" Iteratively execute each of the actions within the POV
Args:
None
Returns:
None
Raises:
AssertionError: if a POV action is not in the pre-defined methods
"""
self.log('%s - %s' % (self.pov.name, self.pov.filename))
methods = {
'sleep': self.sleep,
'declare': self.declare,
'read': self.read,
'write': self.write,
}
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
struct.pack('ii', 1, 5))
self.sock.bind(self.source)
try:
self.sock.connect(self.target)
except socket.error as err:
self.log_fail('connection error: %s' % repr(err))
return
# = socket.create_connection(self.target)
self.log('connected to %s' % repr(self.target))
if self.cb_negotiate() != 0:
self.log_fail('negotiation failed')
return
for method, arguments in self.pov:
assert method in methods, "%s not in methods" % method
try:
methods[method](arguments)
except TestFailure:
self.log('stopping due to failure')
return
def dump(self):
""" Log information for the current POV iteraction
Args:
None
Returns:
None
Raises:
None
"""
if len(self.values) and self.debug:
self.log("variables at end of interaction: ")
for key in self.values:
self.log("%s : %s" % (repr(key), repr(self.values[key])))
self.log('tests passed: %d' % self.passed)
self.log('tests failed: %d' % self.failed)
class POV(object):
"""POV - Parse a POV xml file
This class implements a parser for the CGC POV/Poll format defined in
replay.dtd.
Usage:
p = POV()
p.parse(filename)
p.dump()
Attributes:
name: Name of the CB
filename: Filename of the CB definition
_steps: List of iteractions of a CB
_variables: List of variables used during CB interaction
"""
def __init__(self, seed=None):
self.filename = None
self.name = None
self._steps = []
self._variables = []
self.seed = seed
def __iter__(self):
""" Iterate over iteractions in a POV
Args:
None
Returns:
None
Raises:
None
"""
for step in self._steps:
yield step
def mutate_seed(self):
self.seed = ''.join(chr(ord(a) ^ 255) for a in self.seed)
@staticmethod
def compile_hex_match(data):
""" Convert a string of hex values to their ascii value, skipping
whitespace
Args:
data: Hex string
Returns:
None
Raises:
None
"""
for i in [' ', '\n', '\r', '\t']:
data = data.replace(i, '')
return data.decode('hex')
@staticmethod
def compile_pcre(data):
""" Compile a PCRE regular express for later use
Args:
data: String to be compiled
Returns:
None
Raises:
None
"""
pattern = re.compile(data, re.DOTALL)
return RegexMatch(pattern)
@staticmethod
def compile_slice(data):
""" Parse a slice XML element, into simplified Python slice format
(<digits>:<digits>).
Args:
data: XML element defining a slice
Returns:
None
Raises:
AssertionError: If the tag text is not empty
AssertionError: If the tag name is not 'slice'
"""
assert data.tag == 'slice'
assert data.text is None
begin = int(POV.get_attribute(data, 'begin', '0'))
end = POV.get_attribute(data, 'end', None)
if end is not None:
end = int(end)
return slice(begin, end)
@staticmethod
def compile_string_match(data):
""" Parse a string into an 'asciic' format, for easy use. Allows for
\\r, \\n, \\t, \\\\, and hex values specified via C Style \\x notation.
Args:
data: String to be parsed into a 'asciic' supported value.
Returns:
None
Raises:
AssertionError: if either of two characters following '\\x' are not
hexidecimal values
Exception: if the escaped value is not one of the supported escaped
strings (See above)
"""
# \\, \r, \n, \t \x(HEX)(HEX)
data = str(data) # no unicode support
state = 0
out = []
chars = {'n': '\n', 'r': '\r', 't': '\t', '\\': '\\'}
hex_chars = '0123456789abcdef'
hex_tmp = ''
for val in data:
if state == 0:
if val != '\\':
out.append(val)
continue
state = 1
elif state == 1:
if val in chars:
out.append(chars[val])
state = 0
continue
elif val == 'x':
state = 2
else:
raise Exception('invalid asciic string (%s)' % repr(data))
elif state == 2:
assert val.lower() in hex_chars
hex_tmp = val
state = 3
else:
assert val.lower() in hex_chars
hex_tmp += val
out.append(hex_tmp.decode('hex'))
hex_tmp = ''
state = 0
return ''.join(out)
@staticmethod
def compile_string(data_type, data):
""" Converts a string from a specified format into the converted into
an optimized form for later use
Args:
data_type: Which 'compiler' to use
data: String to be 'compiled'
Returns:
None
Raises:
None
"""
funcs = {
'pcre': POV.compile_pcre,
'asciic': POV.compile_string_match,
'hex': POV.compile_hex_match,
}
return funcs[data_type](data)
@staticmethod
def get_child(data, name):
""" Retrieve the specified 'BeautifulSoup' child from the current
element
Args:
data: Current element that should be searched
name: Name of child element to be returned
Returns:
child: BeautifulSoup element
Raises:
AssertionError: if a child with the specified name is not contained
in the specified element
"""
child = data.findChild(name)
assert child is not None
return child
@staticmethod
def get_attribute(data, name, default=None, allowed=None):
""" Return the named attribute from the current element.
Args:
data: Element to read the named attribute
name: Name of attribute
default: Optional default value to be returne if the attribute is
not provided
allowed: Optional list of allowed values
Returns:
None
Raises:
AssertionError: if the value is not in the specified allowed values
"""
value = default
if name in data.attrib:
value = data.attrib[name]
if allowed is not None:
assert value in allowed
return value
def add_variable(self, name):
""" Add a variable the POV interaction
This allows for insurance of runtime access of initialized variables
during parse time.
Args:
name: Name of variable
Returns:
None
Raises:
None
"""
if name not in self._variables:
self._variables.append(name)
def has_variable(self, name):
""" Verify a variable has been defined
Args:
name: Name of variable
Returns:
None
Raises:
None
"""
return name in self._variables
def add_step(self, step_type, data):
""" Add a step to the POV iteraction sequence
Args:
step_type: Type of interaction
data: Data for the interaction
Returns:
None
Raises:
AssertionError: if the step_type is not one of the pre-defined
types
"""
assert step_type in ['declare', 'sleep', 'read', 'write']
self._steps.append((step_type, data))
def parse_delay(self, data):
""" Parse a 'delay' interaction XML element
Args:
data: XML Element defining the 'delay' iteraction
Returns:
None
Raises:
AssertionError: if there is not only one child in the 'delay'
element
"""
self.add_step('sleep', float(data.text) / 1000)
def parse_decl(self, data):
""" Parse a 'decl' interaction XML element
Args:
data: XML Element defining the 'decl' iteraction
Returns:
None
Raises:
AssertionError: If there is not two children in the 'decl' element
AssertionError: If the 'var' child element is not defined
AssertionError: If the 'var' child element does not have only one
child
AssertionError: If the 'value' child element is not defined
AssertionError: If the 'value' child element does not have only one
child
"""
assert len(data) == 2
assert data[0].tag == 'var'
key = data[0].text
values = []
assert data[1].tag == 'value'
assert len(data[1]) > 0
for item in data[1]:
values.append(self.parse_data(item))
value = ''.join(values)
self.add_variable(key)
self.add_step('declare', {key: value})
def parse_assign(self, data):
""" Parse an 'assign' XML element
Args:
data: XML Element defining the 'assign' iteraction
Returns: