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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
|
#!/usr/bin/env python3
# Unit test for generate_test_code.py
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
# This file is provided under the Apache License 2.0, or the
# GNU General Public License v2.0 or later.
#
# **********
# Apache License 2.0:
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# **********
#
# **********
# GNU General Public License v2.0 or later:
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# **********
"""
Unit tests for generate_test_code.py
"""
# pylint: disable=wrong-import-order
try:
# Python 2
from StringIO import StringIO
except ImportError:
# Python 3
from io import StringIO
from unittest import TestCase, main as unittest_main
try:
# Python 2
from mock import patch
except ImportError:
# Python 3
from unittest.mock import patch
# pylint: enable=wrong-import-order
from generate_test_code import gen_dependencies, gen_dependencies_one_line
from generate_test_code import gen_function_wrapper, gen_dispatch
from generate_test_code import parse_until_pattern, GeneratorInputError
from generate_test_code import parse_suite_dependencies
from generate_test_code import parse_function_dependencies
from generate_test_code import parse_function_arguments, parse_function_code
from generate_test_code import parse_functions, END_HEADER_REGEX
from generate_test_code import END_SUITE_HELPERS_REGEX, escaped_split
from generate_test_code import parse_test_data, gen_dep_check
from generate_test_code import gen_expression_check, write_dependencies
from generate_test_code import write_parameters, gen_suite_dep_checks
from generate_test_code import gen_from_test_data
class GenDep(TestCase):
"""
Test suite for function gen_dep()
"""
def test_dependencies_list(self):
"""
Test that gen_dep() correctly creates dependencies for given
dependency list.
:return:
"""
dependencies = ['DEP1', 'DEP2']
dep_start, dep_end = gen_dependencies(dependencies)
preprocessor1, preprocessor2 = dep_start.splitlines()
endif1, endif2 = dep_end.splitlines()
self.assertEqual(preprocessor1, '#if defined(DEP1)',
'Preprocessor generated incorrectly')
self.assertEqual(preprocessor2, '#if defined(DEP2)',
'Preprocessor generated incorrectly')
self.assertEqual(endif1, '#endif /* DEP2 */',
'Preprocessor generated incorrectly')
self.assertEqual(endif2, '#endif /* DEP1 */',
'Preprocessor generated incorrectly')
def test_disabled_dependencies_list(self):
"""
Test that gen_dep() correctly creates dependencies for given
dependency list.
:return:
"""
dependencies = ['!DEP1', '!DEP2']
dep_start, dep_end = gen_dependencies(dependencies)
preprocessor1, preprocessor2 = dep_start.splitlines()
endif1, endif2 = dep_end.splitlines()
self.assertEqual(preprocessor1, '#if !defined(DEP1)',
'Preprocessor generated incorrectly')
self.assertEqual(preprocessor2, '#if !defined(DEP2)',
'Preprocessor generated incorrectly')
self.assertEqual(endif1, '#endif /* !DEP2 */',
'Preprocessor generated incorrectly')
self.assertEqual(endif2, '#endif /* !DEP1 */',
'Preprocessor generated incorrectly')
def test_mixed_dependencies_list(self):
"""
Test that gen_dep() correctly creates dependencies for given
dependency list.
:return:
"""
dependencies = ['!DEP1', 'DEP2']
dep_start, dep_end = gen_dependencies(dependencies)
preprocessor1, preprocessor2 = dep_start.splitlines()
endif1, endif2 = dep_end.splitlines()
self.assertEqual(preprocessor1, '#if !defined(DEP1)',
'Preprocessor generated incorrectly')
self.assertEqual(preprocessor2, '#if defined(DEP2)',
'Preprocessor generated incorrectly')
self.assertEqual(endif1, '#endif /* DEP2 */',
'Preprocessor generated incorrectly')
self.assertEqual(endif2, '#endif /* !DEP1 */',
'Preprocessor generated incorrectly')
def test_empty_dependencies_list(self):
"""
Test that gen_dep() correctly creates dependencies for given
dependency list.
:return:
"""
dependencies = []
dep_start, dep_end = gen_dependencies(dependencies)
self.assertEqual(dep_start, '', 'Preprocessor generated incorrectly')
self.assertEqual(dep_end, '', 'Preprocessor generated incorrectly')
def test_large_dependencies_list(self):
"""
Test that gen_dep() correctly creates dependencies for given
dependency list.
:return:
"""
dependencies = []
count = 10
for i in range(count):
dependencies.append('DEP%d' % i)
dep_start, dep_end = gen_dependencies(dependencies)
self.assertEqual(len(dep_start.splitlines()), count,
'Preprocessor generated incorrectly')
self.assertEqual(len(dep_end.splitlines()), count,
'Preprocessor generated incorrectly')
class GenDepOneLine(TestCase):
"""
Test Suite for testing gen_dependencies_one_line()
"""
def test_dependencies_list(self):
"""
Test that gen_dep() correctly creates dependencies for given
dependency list.
:return:
"""
dependencies = ['DEP1', 'DEP2']
dep_str = gen_dependencies_one_line(dependencies)
self.assertEqual(dep_str, '#if defined(DEP1) && defined(DEP2)',
'Preprocessor generated incorrectly')
def test_disabled_dependencies_list(self):
"""
Test that gen_dep() correctly creates dependencies for given
dependency list.
:return:
"""
dependencies = ['!DEP1', '!DEP2']
dep_str = gen_dependencies_one_line(dependencies)
self.assertEqual(dep_str, '#if !defined(DEP1) && !defined(DEP2)',
'Preprocessor generated incorrectly')
def test_mixed_dependencies_list(self):
"""
Test that gen_dep() correctly creates dependencies for given
dependency list.
:return:
"""
dependencies = ['!DEP1', 'DEP2']
dep_str = gen_dependencies_one_line(dependencies)
self.assertEqual(dep_str, '#if !defined(DEP1) && defined(DEP2)',
'Preprocessor generated incorrectly')
def test_empty_dependencies_list(self):
"""
Test that gen_dep() correctly creates dependencies for given
dependency list.
:return:
"""
dependencies = []
dep_str = gen_dependencies_one_line(dependencies)
self.assertEqual(dep_str, '', 'Preprocessor generated incorrectly')
def test_large_dependencies_list(self):
"""
Test that gen_dep() correctly creates dependencies for given
dependency list.
:return:
"""
dependencies = []
count = 10
for i in range(count):
dependencies.append('DEP%d' % i)
dep_str = gen_dependencies_one_line(dependencies)
expected = '#if ' + ' && '.join(['defined(%s)' %
x for x in dependencies])
self.assertEqual(dep_str, expected,
'Preprocessor generated incorrectly')
class GenFunctionWrapper(TestCase):
"""
Test Suite for testing gen_function_wrapper()
"""
def test_params_unpack(self):
"""
Test that params are properly unpacked in the function call.
:return:
"""
code = gen_function_wrapper('test_a', '', ('a', 'b', 'c', 'd'))
expected = '''
void test_a_wrapper( void ** params )
{
test_a( a, b, c, d );
}
'''
self.assertEqual(code, expected)
def test_local(self):
"""
Test that params are properly unpacked in the function call.
:return:
"""
code = gen_function_wrapper('test_a',
'int x = 1;', ('x', 'b', 'c', 'd'))
expected = '''
void test_a_wrapper( void ** params )
{
int x = 1;
test_a( x, b, c, d );
}
'''
self.assertEqual(code, expected)
def test_empty_params(self):
"""
Test that params are properly unpacked in the function call.
:return:
"""
code = gen_function_wrapper('test_a', '', ())
expected = '''
void test_a_wrapper( void ** params )
{
(void)params;
test_a( );
}
'''
self.assertEqual(code, expected)
class GenDispatch(TestCase):
"""
Test suite for testing gen_dispatch()
"""
def test_dispatch(self):
"""
Test that dispatch table entry is generated correctly.
:return:
"""
code = gen_dispatch('test_a', ['DEP1', 'DEP2'])
expected = '''
#if defined(DEP1) && defined(DEP2)
test_a_wrapper,
#else
NULL,
#endif
'''
self.assertEqual(code, expected)
def test_empty_dependencies(self):
"""
Test empty dependency list.
:return:
"""
code = gen_dispatch('test_a', [])
expected = '''
test_a_wrapper,
'''
self.assertEqual(code, expected)
class StringIOWrapper(StringIO):
"""
file like class to mock file object in tests.
"""
def __init__(self, file_name, data, line_no=0):
"""
Init file handle.
:param file_name:
:param data:
:param line_no:
"""
super(StringIOWrapper, self).__init__(data)
self.line_no = line_no
self.name = file_name
def next(self):
"""
Iterator method. This method overrides base class's
next method and extends the next method to count the line
numbers as each line is read.
:return: Line read from file.
"""
parent = super(StringIOWrapper, self)
if getattr(parent, 'next', None):
# Python 2
line = parent.next()
else:
# Python 3
line = parent.__next__()
return line
# Python 3
__next__ = next
def readline(self, length=0):
"""
Wrap the base class readline.
:param length:
:return:
"""
# pylint: disable=unused-argument
line = super(StringIOWrapper, self).readline()
if line is not None:
self.line_no += 1
return line
class ParseUntilPattern(TestCase):
"""
Test Suite for testing parse_until_pattern().
"""
def test_suite_headers(self):
"""
Test that suite headers are parsed correctly.
:return:
"""
data = '''#include "mbedtls/ecp.h"
#define ECP_PF_UNKNOWN -1
/* END_HEADER */
'''
expected = '''#line 1 "test_suite_ut.function"
#include "mbedtls/ecp.h"
#define ECP_PF_UNKNOWN -1
'''
stream = StringIOWrapper('test_suite_ut.function', data, line_no=0)
headers = parse_until_pattern(stream, END_HEADER_REGEX)
self.assertEqual(headers, expected)
def test_line_no(self):
"""
Test that #line is set to correct line no. in source .function file.
:return:
"""
data = '''#include "mbedtls/ecp.h"
#define ECP_PF_UNKNOWN -1
/* END_HEADER */
'''
offset_line_no = 5
expected = '''#line %d "test_suite_ut.function"
#include "mbedtls/ecp.h"
#define ECP_PF_UNKNOWN -1
''' % (offset_line_no + 1)
stream = StringIOWrapper('test_suite_ut.function', data,
offset_line_no)
headers = parse_until_pattern(stream, END_HEADER_REGEX)
self.assertEqual(headers, expected)
def test_no_end_header_comment(self):
"""
Test that InvalidFileFormat is raised when end header comment is
missing.
:return:
"""
data = '''#include "mbedtls/ecp.h"
#define ECP_PF_UNKNOWN -1
'''
stream = StringIOWrapper('test_suite_ut.function', data)
self.assertRaises(GeneratorInputError, parse_until_pattern, stream,
END_HEADER_REGEX)
class ParseSuiteDependencies(TestCase):
"""
Test Suite for testing parse_suite_dependencies().
"""
def test_suite_dependencies(self):
"""
:return:
"""
data = '''
* depends_on:MBEDTLS_ECP_C
* END_DEPENDENCIES
*/
'''
expected = ['MBEDTLS_ECP_C']
stream = StringIOWrapper('test_suite_ut.function', data)
dependencies = parse_suite_dependencies(stream)
self.assertEqual(dependencies, expected)
def test_no_end_dep_comment(self):
"""
Test that InvalidFileFormat is raised when end dep comment is missing.
:return:
"""
data = '''
* depends_on:MBEDTLS_ECP_C
'''
stream = StringIOWrapper('test_suite_ut.function', data)
self.assertRaises(GeneratorInputError, parse_suite_dependencies,
stream)
def test_dependencies_split(self):
"""
Test that InvalidFileFormat is raised when end dep comment is missing.
:return:
"""
data = '''
* depends_on:MBEDTLS_ECP_C:A:B: C : D :F : G: !H
* END_DEPENDENCIES
*/
'''
expected = ['MBEDTLS_ECP_C', 'A', 'B', 'C', 'D', 'F', 'G', '!H']
stream = StringIOWrapper('test_suite_ut.function', data)
dependencies = parse_suite_dependencies(stream)
self.assertEqual(dependencies, expected)
class ParseFuncDependencies(TestCase):
"""
Test Suite for testing parse_function_dependencies()
"""
def test_function_dependencies(self):
"""
Test that parse_function_dependencies() correctly parses function
dependencies.
:return:
"""
line = '/* BEGIN_CASE ' \
'depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */'
expected = ['MBEDTLS_ENTROPY_NV_SEED', 'MBEDTLS_FS_IO']
dependencies = parse_function_dependencies(line)
self.assertEqual(dependencies, expected)
def test_no_dependencies(self):
"""
Test that parse_function_dependencies() correctly parses function
dependencies.
:return:
"""
line = '/* BEGIN_CASE */'
dependencies = parse_function_dependencies(line)
self.assertEqual(dependencies, [])
def test_tolerance(self):
"""
Test that parse_function_dependencies() correctly parses function
dependencies.
:return:
"""
line = '/* BEGIN_CASE depends_on:MBEDTLS_FS_IO: A : !B:C : F*/'
dependencies = parse_function_dependencies(line)
self.assertEqual(dependencies, ['MBEDTLS_FS_IO', 'A', '!B', 'C', 'F'])
class ParseFuncSignature(TestCase):
"""
Test Suite for parse_function_arguments().
"""
def test_int_and_char_params(self):
"""
Test int and char parameters parsing
:return:
"""
line = 'void entropy_threshold( char * a, int b, int result )'
args, local, arg_dispatch = parse_function_arguments(line)
self.assertEqual(args, ['char*', 'int', 'int'])
self.assertEqual(local, '')
self.assertEqual(arg_dispatch, ['(char *) params[0]',
'*( (int *) params[1] )',
'*( (int *) params[2] )'])
def test_hex_params(self):
"""
Test hex parameters parsing
:return:
"""
line = 'void entropy_threshold( char * a, data_t * h, int result )'
args, local, arg_dispatch = parse_function_arguments(line)
self.assertEqual(args, ['char*', 'hex', 'int'])
self.assertEqual(local,
' data_t data1 = {(uint8_t *) params[1], '
'*( (uint32_t *) params[2] )};\n')
self.assertEqual(arg_dispatch, ['(char *) params[0]',
'&data1',
'*( (int *) params[3] )'])
def test_unsupported_arg(self):
"""
Test unsupported arguments (not among int, char * and data_t)
:return:
"""
line = 'void entropy_threshold( char * a, data_t * h, char result )'
self.assertRaises(ValueError, parse_function_arguments, line)
def test_no_params(self):
"""
Test no parameters.
:return:
"""
line = 'void entropy_threshold()'
args, local, arg_dispatch = parse_function_arguments(line)
self.assertEqual(args, [])
self.assertEqual(local, '')
self.assertEqual(arg_dispatch, [])
class ParseFunctionCode(TestCase):
"""
Test suite for testing parse_function_code()
"""
def assert_raises_regex(self, exp, regex, func, *args):
"""
Python 2 & 3 portable wrapper of assertRaisesRegex(p)? function.
:param exp: Exception type expected to be raised by cb.
:param regex: Expected exception message
:param func: callable object under test
:param args: variable positional arguments
"""
parent = super(ParseFunctionCode, self)
# Pylint does not appreciate that the super method called
# conditionally can be available in other Python version
# then that of Pylint.
# Workaround is to call the method via getattr.
# Pylint ignores that the method got via getattr is
# conditionally executed. Method has to be a callable.
# Hence, using a dummy callable for getattr default.
dummy = lambda *x: None
# First Python 3 assertRaisesRegex is checked, since Python 2
# assertRaisesRegexp is also available in Python 3 but is
# marked deprecated.
for name in ('assertRaisesRegex', 'assertRaisesRegexp'):
method = getattr(parent, name, dummy)
if method is not dummy:
method(exp, regex, func, *args)
break
else:
raise AttributeError(" 'ParseFunctionCode' object has no attribute"
" 'assertRaisesRegex' or 'assertRaisesRegexp'"
)
def test_no_function(self):
"""
Test no test function found.
:return:
"""
data = '''
No
test
function
'''
stream = StringIOWrapper('test_suite_ut.function', data)
err_msg = 'file: test_suite_ut.function - Test functions not found!'
self.assert_raises_regex(GeneratorInputError, err_msg,
parse_function_code, stream, [], [])
def test_no_end_case_comment(self):
"""
Test missing end case.
:return:
"""
data = '''
void test_func()
{
}
'''
stream = StringIOWrapper('test_suite_ut.function', data)
err_msg = r'file: test_suite_ut.function - '\
'end case pattern .*? not found!'
self.assert_raises_regex(GeneratorInputError, err_msg,
parse_function_code, stream, [], [])
@patch("generate_test_code.parse_function_arguments")
def test_function_called(self,
parse_function_arguments_mock):
"""
Test parse_function_code()
:return:
"""
parse_function_arguments_mock.return_value = ([], '', [])
data = '''
void test_func()
{
}
'''
stream = StringIOWrapper('test_suite_ut.function', data)
self.assertRaises(GeneratorInputError, parse_function_code,
stream, [], [])
self.assertTrue(parse_function_arguments_mock.called)
parse_function_arguments_mock.assert_called_with('void test_func()\n')
@patch("generate_test_code.gen_dispatch")
@patch("generate_test_code.gen_dependencies")
@patch("generate_test_code.gen_function_wrapper")
@patch("generate_test_code.parse_function_arguments")
def test_return(self, parse_function_arguments_mock,
gen_function_wrapper_mock,
gen_dependencies_mock,
gen_dispatch_mock):
"""
Test generated code.
:return:
"""
parse_function_arguments_mock.return_value = ([], '', [])
gen_function_wrapper_mock.return_value = ''
gen_dependencies_mock.side_effect = gen_dependencies
gen_dispatch_mock.side_effect = gen_dispatch
data = '''
void func()
{
ba ba black sheep
have you any wool
}
/* END_CASE */
'''
stream = StringIOWrapper('test_suite_ut.function', data)
name, arg, code, dispatch_code = parse_function_code(stream, [], [])
self.assertTrue(parse_function_arguments_mock.called)
parse_function_arguments_mock.assert_called_with('void func()\n')
gen_function_wrapper_mock.assert_called_with('test_func', '', [])
self.assertEqual(name, 'test_func')
self.assertEqual(arg, [])
expected = '''#line 1 "test_suite_ut.function"
void test_func()
{
ba ba black sheep
have you any wool
exit:
;
}
'''
self.assertEqual(code, expected)
self.assertEqual(dispatch_code, "\n test_func_wrapper,\n")
@patch("generate_test_code.gen_dispatch")
@patch("generate_test_code.gen_dependencies")
@patch("generate_test_code.gen_function_wrapper")
@patch("generate_test_code.parse_function_arguments")
def test_with_exit_label(self, parse_function_arguments_mock,
gen_function_wrapper_mock,
gen_dependencies_mock,
gen_dispatch_mock):
"""
Test when exit label is present.
:return:
"""
parse_function_arguments_mock.return_value = ([], '', [])
gen_function_wrapper_mock.return_value = ''
gen_dependencies_mock.side_effect = gen_dependencies
gen_dispatch_mock.side_effect = gen_dispatch
data = '''
void func()
{
ba ba black sheep
have you any wool
exit:
yes sir yes sir
3 bags full
}
/* END_CASE */
'''
stream = StringIOWrapper('test_suite_ut.function', data)
_, _, code, _ = parse_function_code(stream, [], [])
expected = '''#line 1 "test_suite_ut.function"
void test_func()
{
ba ba black sheep
have you any wool
exit:
yes sir yes sir
3 bags full
}
'''
self.assertEqual(code, expected)
def test_non_void_function(self):
"""
Test invalid signature (non void).
:return:
"""
data = 'int entropy_threshold( char * a, data_t * h, int result )'
err_msg = 'file: test_suite_ut.function - Test functions not found!'
stream = StringIOWrapper('test_suite_ut.function', data)
self.assert_raises_regex(GeneratorInputError, err_msg,
parse_function_code, stream, [], [])
@patch("generate_test_code.gen_dispatch")
@patch("generate_test_code.gen_dependencies")
@patch("generate_test_code.gen_function_wrapper")
@patch("generate_test_code.parse_function_arguments")
def test_functio_name_on_newline(self, parse_function_arguments_mock,
gen_function_wrapper_mock,
gen_dependencies_mock,
gen_dispatch_mock):
"""
Test when exit label is present.
:return:
"""
parse_function_arguments_mock.return_value = ([], '', [])
gen_function_wrapper_mock.return_value = ''
gen_dependencies_mock.side_effect = gen_dependencies
gen_dispatch_mock.side_effect = gen_dispatch
data = '''
void
func()
{
ba ba black sheep
have you any wool
exit:
yes sir yes sir
3 bags full
}
/* END_CASE */
'''
stream = StringIOWrapper('test_suite_ut.function', data)
_, _, code, _ = parse_function_code(stream, [], [])
expected = '''#line 1 "test_suite_ut.function"
void
test_func()
{
ba ba black sheep
have you any wool
exit:
yes sir yes sir
3 bags full
}
'''
self.assertEqual(code, expected)
class ParseFunction(TestCase):
"""
Test Suite for testing parse_functions()
"""
@patch("generate_test_code.parse_until_pattern")
def test_begin_header(self, parse_until_pattern_mock):
"""
Test that begin header is checked and parse_until_pattern() is called.
:return:
"""
def stop(*_unused):
"""Stop when parse_until_pattern is called."""
raise Exception
parse_until_pattern_mock.side_effect = stop
data = '''/* BEGIN_HEADER */
#include "mbedtls/ecp.h"
#define ECP_PF_UNKNOWN -1
/* END_HEADER */
'''
stream = StringIOWrapper('test_suite_ut.function', data)
self.assertRaises(Exception, parse_functions, stream)
parse_until_pattern_mock.assert_called_with(stream, END_HEADER_REGEX)
self.assertEqual(stream.line_no, 1)
@patch("generate_test_code.parse_until_pattern")
def test_begin_helper(self, parse_until_pattern_mock):
"""
Test that begin helper is checked and parse_until_pattern() is called.
:return:
"""
def stop(*_unused):
"""Stop when parse_until_pattern is called."""
raise Exception
parse_until_pattern_mock.side_effect = stop
data = '''/* BEGIN_SUITE_HELPERS */
void print_hello_world()
{
printf("Hello World!\n");
}
/* END_SUITE_HELPERS */
'''
stream = StringIOWrapper('test_suite_ut.function', data)
self.assertRaises(Exception, parse_functions, stream)
parse_until_pattern_mock.assert_called_with(stream,
END_SUITE_HELPERS_REGEX)
self.assertEqual(stream.line_no, 1)
@patch("generate_test_code.parse_suite_dependencies")
def test_begin_dep(self, parse_suite_dependencies_mock):
"""
Test that begin dep is checked and parse_suite_dependencies() is
called.
:return:
"""
def stop(*_unused):
"""Stop when parse_until_pattern is called."""
raise Exception
parse_suite_dependencies_mock.side_effect = stop
data = '''/* BEGIN_DEPENDENCIES
* depends_on:MBEDTLS_ECP_C
* END_DEPENDENCIES
*/
'''
stream = StringIOWrapper('test_suite_ut.function', data)
self.assertRaises(Exception, parse_functions, stream)
parse_suite_dependencies_mock.assert_called_with(stream)
self.assertEqual(stream.line_no, 1)
@patch("generate_test_code.parse_function_dependencies")
def test_begin_function_dep(self, func_mock):
"""
Test that begin dep is checked and parse_function_dependencies() is
called.
:return:
"""
def stop(*_unused):
"""Stop when parse_until_pattern is called."""
raise Exception
func_mock.side_effect = stop
dependencies_str = '/* BEGIN_CASE ' \
'depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */\n'
data = '''%svoid test_func()
{
}
''' % dependencies_str
stream = StringIOWrapper('test_suite_ut.function', data)
self.assertRaises(Exception, parse_functions, stream)
func_mock.assert_called_with(dependencies_str)
self.assertEqual(stream.line_no, 1)
@patch("generate_test_code.parse_function_code")
@patch("generate_test_code.parse_function_dependencies")
def test_return(self, func_mock1, func_mock2):
"""
Test that begin case is checked and parse_function_code() is called.
:return:
"""
func_mock1.return_value = []
in_func_code = '''void test_func()
{
}
'''
func_dispatch = '''
test_func_wrapper,
'''
func_mock2.return_value = 'test_func', [],\
in_func_code, func_dispatch
dependencies_str = '/* BEGIN_CASE ' \
'depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */\n'
data = '''%svoid test_func()
{
}
''' % dependencies_str
stream = StringIOWrapper('test_suite_ut.function', data)
suite_dependencies, dispatch_code, func_code, func_info = \
parse_functions(stream)
func_mock1.assert_called_with(dependencies_str)
func_mock2.assert_called_with(stream, [], [])
self.assertEqual(stream.line_no, 5)
self.assertEqual(suite_dependencies, [])
expected_dispatch_code = '''/* Function Id: 0 */
test_func_wrapper,
'''
self.assertEqual(dispatch_code, expected_dispatch_code)
self.assertEqual(func_code, in_func_code)
self.assertEqual(func_info, {'test_func': (0, [])})
def test_parsing(self):
"""
Test case parsing.
:return:
"""
data = '''/* BEGIN_HEADER */
#include "mbedtls/ecp.h"
#define ECP_PF_UNKNOWN -1
/* END_HEADER */
/* BEGIN_DEPENDENCIES
* depends_on:MBEDTLS_ECP_C
* END_DEPENDENCIES
*/
/* BEGIN_CASE depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */
void func1()
{
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */
void func2()
{
}
/* END_CASE */
'''
stream = StringIOWrapper('test_suite_ut.function', data)
suite_dependencies, dispatch_code, func_code, func_info = \
parse_functions(stream)
self.assertEqual(stream.line_no, 23)
self.assertEqual(suite_dependencies, ['MBEDTLS_ECP_C'])
expected_dispatch_code = '''/* Function Id: 0 */
#if defined(MBEDTLS_ECP_C) && defined(MBEDTLS_ENTROPY_NV_SEED) && defined(MBEDTLS_FS_IO)
test_func1_wrapper,
#else
NULL,
#endif
/* Function Id: 1 */
#if defined(MBEDTLS_ECP_C) && defined(MBEDTLS_ENTROPY_NV_SEED) && defined(MBEDTLS_FS_IO)
test_func2_wrapper,
#else
NULL,
#endif
'''
self.assertEqual(dispatch_code, expected_dispatch_code)
expected_func_code = '''#if defined(MBEDTLS_ECP_C)
#line 2 "test_suite_ut.function"
#include "mbedtls/ecp.h"
#define ECP_PF_UNKNOWN -1
#if defined(MBEDTLS_ENTROPY_NV_SEED)
#if defined(MBEDTLS_FS_IO)
#line 13 "test_suite_ut.function"
void test_func1()
{
exit:
;
}
void test_func1_wrapper( void ** params )
{
(void)params;
test_func1( );
}
#endif /* MBEDTLS_FS_IO */
#endif /* MBEDTLS_ENTROPY_NV_SEED */
#if defined(MBEDTLS_ENTROPY_NV_SEED)
#if defined(MBEDTLS_FS_IO)
#line 19 "test_suite_ut.function"
void test_func2()
{
exit:
;
}
void test_func2_wrapper( void ** params )
{
(void)params;
test_func2( );
}
#endif /* MBEDTLS_FS_IO */
#endif /* MBEDTLS_ENTROPY_NV_SEED */
#endif /* MBEDTLS_ECP_C */
'''
self.assertEqual(func_code, expected_func_code)
self.assertEqual(func_info, {'test_func1': (0, []),
'test_func2': (1, [])})
def test_same_function_name(self):
"""
Test name conflict.
:return:
"""
data = '''/* BEGIN_HEADER */
#include "mbedtls/ecp.h"
#define ECP_PF_UNKNOWN -1
/* END_HEADER */
/* BEGIN_DEPENDENCIES
* depends_on:MBEDTLS_ECP_C
* END_DEPENDENCIES
*/
/* BEGIN_CASE depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */
void func()
{
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */
void func()
{
}
/* END_CASE */
'''
stream = StringIOWrapper('test_suite_ut.function', data)
self.assertRaises(GeneratorInputError, parse_functions, stream)
class EscapedSplit(TestCase):
"""
Test suite for testing escaped_split().
Note: Since escaped_split() output is used to write back to the
intermediate data file. Any escape characters in the input are
retained in the output.
"""
def test_invalid_input(self):
"""
Test when input split character is not a character.
:return:
"""
self.assertRaises(ValueError, escaped_split, '', 'string')
def test_empty_string(self):
"""
Test empty string input.
:return:
"""
splits = escaped_split('', ':')
self.assertEqual(splits, [])
def test_no_escape(self):
"""
Test with no escape character. The behaviour should be same as
str.split()
:return:
"""
test_str = 'yahoo:google'
splits = escaped_split(test_str, ':')
self.assertEqual(splits, test_str.split(':'))
def test_escaped_input(self):
"""
Test input that has escaped delimiter.
:return:
"""
test_str = r'yahoo\:google:facebook'
splits = escaped_split(test_str, ':')
self.assertEqual(splits, [r'yahoo\:google', 'facebook'])
def test_escaped_escape(self):
"""
Test input that has escaped delimiter.
:return:
"""
test_str = r'yahoo\\:google:facebook'
splits = escaped_split(test_str, ':')
self.assertEqual(splits, [r'yahoo\\', 'google', 'facebook'])
def test_all_at_once(self):
"""
Test input that has escaped delimiter.
:return:
"""
test_str = r'yahoo\\:google:facebook\:instagram\\:bbc\\:wikipedia'
splits = escaped_split(test_str, ':')
self.assertEqual(splits, [r'yahoo\\', r'google',
r'facebook\:instagram\\',
r'bbc\\', r'wikipedia'])
class ParseTestData(TestCase):
"""
Test suite for parse test data.
"""
def test_parser(self):
"""
Test that tests are parsed correctly from data file.
:return:
"""
data = """
Diffie-Hellman full exchange #1
dhm_do_dhm:10:"23":10:"5"
Diffie-Hellman full exchange #2
dhm_do_dhm:10:"93450983094850938450983409623":10:"9345098304850938450983409622"
Diffie-Hellman full exchange #3
dhm_do_dhm:10:"9345098382739712938719287391879381271":10:"9345098792137312973297123912791271"
Diffie-Hellman selftest
dhm_selftest:
"""
stream = StringIOWrapper('test_suite_ut.function', data)
# List of (name, function_name, dependencies, args)
tests = list(parse_test_data(stream))
test1, test2, test3, test4 = tests
self.assertEqual(test1[0], 'Diffie-Hellman full exchange #1')
self.assertEqual(test1[1], 'dhm_do_dhm')
self.assertEqual(test1[2], [])
self.assertEqual(test1[3], ['10', '"23"', '10', '"5"'])
self.assertEqual(test2[0], 'Diffie-Hellman full exchange #2')
self.assertEqual(test2[1], 'dhm_do_dhm')
self.assertEqual(test2[2], [])
self.assertEqual(test2[3], ['10', '"93450983094850938450983409623"',
'10', '"9345098304850938450983409622"'])
self.assertEqual(test3[0], 'Diffie-Hellman full exchange #3')
self.assertEqual(test3[1], 'dhm_do_dhm')
self.assertEqual(test3[2], [])
self.assertEqual(test3[3], ['10',
'"9345098382739712938719287391879381271"',
'10',
'"9345098792137312973297123912791271"'])
self.assertEqual(test4[0], 'Diffie-Hellman selftest')
self.assertEqual(test4[1], 'dhm_selftest')
self.assertEqual(test4[2], [])
self.assertEqual(test4[3], [])
def test_with_dependencies(self):
"""
Test that tests with dependencies are parsed.
:return:
"""
data = """
Diffie-Hellman full exchange #1
depends_on:YAHOO
dhm_do_dhm:10:"23":10:"5"
Diffie-Hellman full exchange #2
dhm_do_dhm:10:"93450983094850938450983409623":10:"9345098304850938450983409622"
"""
stream = StringIOWrapper('test_suite_ut.function', data)
# List of (name, function_name, dependencies, args)
tests = list(parse_test_data(stream))
test1, test2 = tests
self.assertEqual(test1[0], 'Diffie-Hellman full exchange #1')
self.assertEqual(test1[1], 'dhm_do_dhm')
self.assertEqual(test1[2], ['YAHOO'])
self.assertEqual(test1[3], ['10', '"23"', '10', '"5"'])
self.assertEqual(test2[0], 'Diffie-Hellman full exchange #2')
self.assertEqual(test2[1], 'dhm_do_dhm')
self.assertEqual(test2[2], [])
self.assertEqual(test2[3], ['10', '"93450983094850938450983409623"',
'10', '"9345098304850938450983409622"'])
def test_no_args(self):
"""
Test GeneratorInputError is raised when test function name and
args line is missing.
:return:
"""
data = """
Diffie-Hellman full exchange #1
depends_on:YAHOO
Diffie-Hellman full exchange #2
dhm_do_dhm:10:"93450983094850938450983409623":10:"9345098304850938450983409622"
"""
stream = StringIOWrapper('test_suite_ut.function', data)
err = None
try:
for _, _, _, _ in parse_test_data(stream):
pass
except GeneratorInputError as err:
self.assertEqual(type(err), GeneratorInputError)
def test_incomplete_data(self):
"""
Test GeneratorInputError is raised when test function name
and args line is missing.
:return:
"""
data = """
Diffie-Hellman full exchange #1
depends_on:YAHOO
"""
stream = StringIOWrapper('test_suite_ut.function', data)
err = None
try:
for _, _, _, _ in parse_test_data(stream):
pass
except GeneratorInputError as err:
self.assertEqual(type(err), GeneratorInputError)
class GenDepCheck(TestCase):
"""
Test suite for gen_dep_check(). It is assumed this function is
called with valid inputs.
"""
def test_gen_dep_check(self):
"""
Test that dependency check code generated correctly.
:return:
"""
expected = """
case 5:
{
#if defined(YAHOO)
ret = DEPENDENCY_SUPPORTED;
#else
ret = DEPENDENCY_NOT_SUPPORTED;
#endif
}
break;"""
out = gen_dep_check(5, 'YAHOO')
self.assertEqual(out, expected)
def test_not_defined_dependency(self):
"""
Test dependency with !.
:return:
"""
expected = """
case 5:
{
#if !defined(YAHOO)
ret = DEPENDENCY_SUPPORTED;
#else
ret = DEPENDENCY_NOT_SUPPORTED;
#endif
}
break;"""
out = gen_dep_check(5, '!YAHOO')
self.assertEqual(out, expected)
def test_empty_dependency(self):
"""
Test invalid dependency input.
:return:
"""
self.assertRaises(GeneratorInputError, gen_dep_check, 5, '!')
def test_negative_dep_id(self):
"""
Test invalid dependency input.
:return:
"""
self.assertRaises(GeneratorInputError, gen_dep_check, -1, 'YAHOO')
class GenExpCheck(TestCase):
"""
Test suite for gen_expression_check(). It is assumed this function
is called with valid inputs.
"""
def test_gen_exp_check(self):
"""
Test that expression check code generated correctly.
:return:
"""
expected = """
case 5:
{
*out_value = YAHOO;
}
break;"""
out = gen_expression_check(5, 'YAHOO')
self.assertEqual(out, expected)
def test_invalid_expression(self):
"""
Test invalid expression input.
:return:
"""
self.assertRaises(GeneratorInputError, gen_expression_check, 5, '')
def test_negative_exp_id(self):
"""
Test invalid expression id.
:return:
"""
self.assertRaises(GeneratorInputError, gen_expression_check,
-1, 'YAHOO')
class WriteDependencies(TestCase):
"""
Test suite for testing write_dependencies.
"""
def test_no_test_dependencies(self):
"""
Test when test dependencies input is empty.
:return:
"""
stream = StringIOWrapper('test_suite_ut.data', '')
unique_dependencies = []
dep_check_code = write_dependencies(stream, [], unique_dependencies)
self.assertEqual(dep_check_code, '')
self.assertEqual(len(unique_dependencies), 0)
self.assertEqual(stream.getvalue(), '')
def test_unique_dep_ids(self):
"""
:return:
"""
stream = StringIOWrapper('test_suite_ut.data', '')
unique_dependencies = []
dep_check_code = write_dependencies(stream, ['DEP3', 'DEP2', 'DEP1'],
unique_dependencies)
expect_dep_check_code = '''
case 0:
{
#if defined(DEP3)
ret = DEPENDENCY_SUPPORTED;
#else
ret = DEPENDENCY_NOT_SUPPORTED;
#endif
}
break;
case 1:
{
#if defined(DEP2)
ret = DEPENDENCY_SUPPORTED;
#else
ret = DEPENDENCY_NOT_SUPPORTED;
#endif
}
break;
case 2:
{
#if defined(DEP1)
ret = DEPENDENCY_SUPPORTED;
#else
ret = DEPENDENCY_NOT_SUPPORTED;
#endif
}
break;'''
self.assertEqual(dep_check_code, expect_dep_check_code)
self.assertEqual(len(unique_dependencies), 3)
self.assertEqual(stream.getvalue(), 'depends_on:0:1:2\n')
def test_dep_id_repeat(self):
"""
:return:
"""
stream = StringIOWrapper('test_suite_ut.data', '')
unique_dependencies = []
dep_check_code = ''
dep_check_code += write_dependencies(stream, ['DEP3', 'DEP2'],
unique_dependencies)
dep_check_code += write_dependencies(stream, ['DEP2', 'DEP1'],
unique_dependencies)
dep_check_code += write_dependencies(stream, ['DEP1', 'DEP3'],
unique_dependencies)
expect_dep_check_code = '''
case 0:
{
#if defined(DEP3)
ret = DEPENDENCY_SUPPORTED;
#else
ret = DEPENDENCY_NOT_SUPPORTED;
#endif
}
break;
case 1:
{
#if defined(DEP2)
ret = DEPENDENCY_SUPPORTED;
#else
ret = DEPENDENCY_NOT_SUPPORTED;
#endif
}
break;
case 2:
{
#if defined(DEP1)
ret = DEPENDENCY_SUPPORTED;
#else
ret = DEPENDENCY_NOT_SUPPORTED;
#endif
}
break;'''
self.assertEqual(dep_check_code, expect_dep_check_code)
self.assertEqual(len(unique_dependencies), 3)
self.assertEqual(stream.getvalue(),
'depends_on:0:1\ndepends_on:1:2\ndepends_on:2:0\n')
class WriteParams(TestCase):
"""
Test Suite for testing write_parameters().
"""
def test_no_params(self):
"""
Test with empty test_args
:return:
"""
stream = StringIOWrapper('test_suite_ut.data', '')
unique_expressions = []
expression_code = write_parameters(stream, [], [], unique_expressions)
self.assertEqual(len(unique_expressions), 0)
self.assertEqual(expression_code, '')
self.assertEqual(stream.getvalue(), '\n')
def test_no_exp_param(self):
"""
Test when there is no macro or expression in the params.
:return:
"""
stream = StringIOWrapper('test_suite_ut.data', '')
unique_expressions = []
expression_code = write_parameters(stream, ['"Yahoo"', '"abcdef00"',
'0'],
['char*', 'hex', 'int'],
unique_expressions)
self.assertEqual(len(unique_expressions), 0)
self.assertEqual(expression_code, '')
self.assertEqual(stream.getvalue(),
':char*:"Yahoo":hex:"abcdef00":int:0\n')
def test_hex_format_int_param(self):
"""
Test int parameter in hex format.
:return:
"""
stream = StringIOWrapper('test_suite_ut.data', '')
unique_expressions = []
expression_code = write_parameters(stream,
['"Yahoo"', '"abcdef00"', '0xAA'],
['char*', 'hex', 'int'],
unique_expressions)
self.assertEqual(len(unique_expressions), 0)
self.assertEqual(expression_code, '')
self.assertEqual(stream.getvalue(),
':char*:"Yahoo":hex:"abcdef00":int:0xAA\n')
def test_with_exp_param(self):
"""
Test when there is macro or expression in the params.
:return:
"""
stream = StringIOWrapper('test_suite_ut.data', '')
unique_expressions = []
expression_code = write_parameters(stream,
['"Yahoo"', '"abcdef00"', '0',
'MACRO1', 'MACRO2', 'MACRO3'],
['char*', 'hex', 'int',
'int', 'int', 'int'],
unique_expressions)
self.assertEqual(len(unique_expressions), 3)
self.assertEqual(unique_expressions, ['MACRO1', 'MACRO2', 'MACRO3'])
expected_expression_code = '''
case 0:
{
*out_value = MACRO1;
}
break;
case 1:
{
*out_value = MACRO2;
}
break;
case 2:
{
*out_value = MACRO3;
}
break;'''
self.assertEqual(expression_code, expected_expression_code)
self.assertEqual(stream.getvalue(),
':char*:"Yahoo":hex:"abcdef00":int:0:exp:0:exp:1'
':exp:2\n')
def test_with_repeat_calls(self):
"""
Test when write_parameter() is called with same macro or expression.
:return:
"""
stream = StringIOWrapper('test_suite_ut.data', '')
unique_expressions = []
expression_code = ''
expression_code += write_parameters(stream,
['"Yahoo"', 'MACRO1', 'MACRO2'],
['char*', 'int', 'int'],
unique_expressions)
expression_code += write_parameters(stream,
['"abcdef00"', 'MACRO2', 'MACRO3'],
['hex', 'int', 'int'],
unique_expressions)
expression_code += write_parameters(stream,
['0', 'MACRO3', 'MACRO1'],
['int', 'int', 'int'],
unique_expressions)
self.assertEqual(len(unique_expressions), 3)
self.assertEqual(unique_expressions, ['MACRO1', 'MACRO2', 'MACRO3'])
expected_expression_code = '''
case 0:
{
*out_value = MACRO1;
}
break;
case 1:
{
*out_value = MACRO2;
}
break;
case 2:
{
*out_value = MACRO3;
}
break;'''
self.assertEqual(expression_code, expected_expression_code)
expected_data_file = ''':char*:"Yahoo":exp:0:exp:1
:hex:"abcdef00":exp:1:exp:2
:int:0:exp:2:exp:0
'''
self.assertEqual(stream.getvalue(), expected_data_file)
class GenTestSuiteDependenciesChecks(TestCase):
"""
Test suite for testing gen_suite_dep_checks()
"""
def test_empty_suite_dependencies(self):
"""
Test with empty suite_dependencies list.
:return:
"""
dep_check_code, expression_code = \
gen_suite_dep_checks([], 'DEP_CHECK_CODE', 'EXPRESSION_CODE')
self.assertEqual(dep_check_code, 'DEP_CHECK_CODE')
self.assertEqual(expression_code, 'EXPRESSION_CODE')
def test_suite_dependencies(self):
"""
Test with suite_dependencies list.
:return:
"""
dep_check_code, expression_code = \
gen_suite_dep_checks(['SUITE_DEP'], 'DEP_CHECK_CODE',
'EXPRESSION_CODE')
expected_dep_check_code = '''
#if defined(SUITE_DEP)
DEP_CHECK_CODE
#endif
'''
expected_expression_code = '''
#if defined(SUITE_DEP)
EXPRESSION_CODE
#endif
'''
self.assertEqual(dep_check_code, expected_dep_check_code)
self.assertEqual(expression_code, expected_expression_code)
def test_no_dep_no_exp(self):
"""
Test when there are no dependency and expression code.
:return:
"""
dep_check_code, expression_code = gen_suite_dep_checks([], '', '')
self.assertEqual(dep_check_code, '')
self.assertEqual(expression_code, '')
class GenFromTestData(TestCase):
"""
Test suite for gen_from_test_data()
"""
@staticmethod
@patch("generate_test_code.write_dependencies")
@patch("generate_test_code.write_parameters")
@patch("generate_test_code.gen_suite_dep_checks")
def test_intermediate_data_file(func_mock1,
write_parameters_mock,
write_dependencies_mock):
"""
Test that intermediate data file is written with expected data.
:return:
"""
data = '''
My test
depends_on:DEP1
func1:0
'''
data_f = StringIOWrapper('test_suite_ut.data', data)
out_data_f = StringIOWrapper('test_suite_ut.datax', '')
func_info = {'test_func1': (1, ('int',))}
suite_dependencies = []
write_parameters_mock.side_effect = write_parameters
write_dependencies_mock.side_effect = write_dependencies
func_mock1.side_effect = gen_suite_dep_checks
gen_from_test_data(data_f, out_data_f, func_info, suite_dependencies)
write_dependencies_mock.assert_called_with(out_data_f,
['DEP1'], ['DEP1'])
write_parameters_mock.assert_called_with(out_data_f, ['0'],
('int',), [])
expected_dep_check_code = '''
case 0:
{
#if defined(DEP1)
ret = DEPENDENCY_SUPPORTED;
#else
ret = DEPENDENCY_NOT_SUPPORTED;
#endif
}
break;'''
func_mock1.assert_called_with(
suite_dependencies, expected_dep_check_code, '')
def test_function_not_found(self):
"""
Test that AssertError is raised when function info in not found.
:return:
"""
data = '''
My test
depends_on:DEP1
func1:0
'''
data_f = StringIOWrapper('test_suite_ut.data', data)
out_data_f = StringIOWrapper('test_suite_ut.datax', '')
func_info = {'test_func2': (1, ('int',))}
suite_dependencies = []
self.assertRaises(GeneratorInputError, gen_from_test_data,
data_f, out_data_f, func_info, suite_dependencies)
def test_different_func_args(self):
"""
Test that AssertError is raised when no. of parameters and
function args differ.
:return:
"""
data = '''
My test
depends_on:DEP1
func1:0
'''
data_f = StringIOWrapper('test_suite_ut.data', data)
out_data_f = StringIOWrapper('test_suite_ut.datax', '')
func_info = {'test_func2': (1, ('int', 'hex'))}
suite_dependencies = []
self.assertRaises(GeneratorInputError, gen_from_test_data, data_f,
out_data_f, func_info, suite_dependencies)
def test_output(self):
"""
Test that intermediate data file is written with expected data.
:return:
"""
data = '''
My test 1
depends_on:DEP1
func1:0:0xfa:MACRO1:MACRO2
My test 2
depends_on:DEP1:DEP2
func2:"yahoo":88:MACRO1
'''
data_f = StringIOWrapper('test_suite_ut.data', data)
out_data_f = StringIOWrapper('test_suite_ut.datax', '')
func_info = {'test_func1': (0, ('int', 'int', 'int', 'int')),
'test_func2': (1, ('char*', 'int', 'int'))}
suite_dependencies = []
dep_check_code, expression_code = \
gen_from_test_data(data_f, out_data_f, func_info,
suite_dependencies)
expected_dep_check_code = '''
case 0:
{
#if defined(DEP1)
ret = DEPENDENCY_SUPPORTED;
#else
ret = DEPENDENCY_NOT_SUPPORTED;
#endif
}
break;
case 1:
{
#if defined(DEP2)
ret = DEPENDENCY_SUPPORTED;
#else
ret = DEPENDENCY_NOT_SUPPORTED;
#endif
}
break;'''
expected_data = '''My test 1
depends_on:0
0:int:0:int:0xfa:exp:0:exp:1
My test 2
depends_on:0:1
1:char*:"yahoo":int:88:exp:0
'''
expected_expression_code = '''
case 0:
{
*out_value = MACRO1;
}
break;
case 1:
{
*out_value = MACRO2;
}
break;'''
self.assertEqual(dep_check_code, expected_dep_check_code)
self.assertEqual(out_data_f.getvalue(), expected_data)
self.assertEqual(expression_code, expected_expression_code)
if __name__ == '__main__':
unittest_main()
|