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 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
|
#!/usr/bin/env python3
# Copyright (c) 2007, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"Unittest for gflags.py module"
__pychecker__ = "no-local" # for unittest
import sys
import os
import shutil
import unittest
# We use the name 'flags' internally in this test, for historical reasons.
# Don't do this yourself! :-) Just do 'import gflags; FLAGS=gflags.FLAGS; etc'
import gflags as flags
FLAGS=flags.FLAGS
# For historic reasons, we use the name module_foo instead of
# test_module_foo, and module_bar instead of test_module_bar.
import test_module_foo as module_foo
import test_module_bar as module_bar
import test_module_baz as module_baz
def Sorted(lst):
"""Equivalent of sorted(), but not dependent on python version."""
sorted_list = lst[:]
sorted_list.sort()
return sorted_list
def MultiLineEqual(expected_help, help):
"""Returns True if expected_help == help. Otherwise returns False
and logs the difference in a human-readable way.
"""
if help == expected_help:
return True
print("Error: FLAGS.MainModuleHelp() didn't return the expected result.")
print("Got:")
print(help)
print("[End of got]")
help_lines = help.split('\n')
expected_help_lines = expected_help.split('\n')
num_help_lines = len(help_lines)
num_expected_help_lines = len(expected_help_lines)
if num_help_lines != num_expected_help_lines:
print("Number of help lines = %d, expected %d" % (
num_help_lines, num_expected_help_lines))
num_to_match = min(num_help_lines, num_expected_help_lines)
for i in range(num_to_match):
if help_lines[i] != expected_help_lines[i]:
print("One discrepancy: Got:")
print(help_lines[i])
print("Expected:")
print(expected_help_lines[i])
break
else:
# If we got here, found no discrepancy, print first new line.
if num_help_lines > num_expected_help_lines:
print("New help line:")
print(help_lines[num_expected_help_lines])
elif num_expected_help_lines > num_help_lines:
print("Missing expected help line:")
print(expected_help_lines[num_help_lines])
else:
print("Bug in this test -- discrepancy detected but not found.")
return False
class _UnitTestClass(unittest.TestCase):
def assertListEqual(self, list1, list2, msg=None):
"""Asserts that, when sorted, list1 and list2 are identical."""
if hasattr(super(_UnitTestClass, self), 'assertListEqual'):
super(_UnitTestClass, self).assertListEqual(Sorted(list1), Sorted(list2))
else:
self.assertEqual(Sorted(list1), Sorted(list2))
def assertMultiLineEqual(self, expected, actual):
"""Could do fancy diffing, but for now, just do a normal compare."""
self.assert_(MultiLineEqual(expected, actual))
def assertRaisesWithRegexpMatch(self, exception, regexp, fn, *args, **kwargs):
try:
fn(*args, **kwargs)
except exception, why:
self.assert_(re.search(regexp, str(why)),
'"%s" does not match "%s"' % (regexp, why))
return
self.fail(exception.__name__ + ' not raised')
class FlagsUnitTest(_UnitTestClass):
"Flags Unit Test"
def setUp(self):
# make sure we are using the old, stupid way of parsing flags.
FLAGS.UseGnuGetOpt(False)
def test_flags(self):
##############################################
# Test normal usage with no (expected) errors.
# Define flags
number_test_framework_flags = len(FLAGS.RegisteredFlags())
repeatHelp = "how many times to repeat (0-5)"
flags.DEFINE_integer("repeat", 4, repeatHelp,
lower_bound=0, short_name='r')
flags.DEFINE_string("name", "Bob", "namehelp")
flags.DEFINE_boolean("debug", 0, "debughelp")
flags.DEFINE_boolean("q", 1, "quiet mode")
flags.DEFINE_boolean("quack", 0, "superstring of 'q'")
flags.DEFINE_boolean("noexec", 1, "boolean flag with no as prefix")
flags.DEFINE_integer("x", 3, "how eXtreme to be")
flags.DEFINE_integer("l", 0x7fffffff00000000L, "how long to be")
flags.DEFINE_list('letters', 'a,b,c', "a list of letters")
flags.DEFINE_list('numbers', [1, 2, 3], "a list of numbers")
flags.DEFINE_enum("kwery", None, ['who', 'what', 'why', 'where', 'when'],
"?")
# Specify number of flags defined above. The short_name defined
# for 'repeat' counts as an extra flag.
number_defined_flags = 11 + 1
self.assertEqual(len(FLAGS.RegisteredFlags()),
number_defined_flags + number_test_framework_flags)
assert FLAGS.repeat == 4, "integer default values not set:" + FLAGS.repeat
assert FLAGS.name == 'Bob', "default values not set:" + FLAGS.name
assert FLAGS.debug == 0, "boolean default values not set:" + FLAGS.debug
assert FLAGS.q == 1, "boolean default values not set:" + FLAGS.q
assert FLAGS.x == 3, "integer default values not set:" + FLAGS.x
assert FLAGS.l == 0x7fffffff00000000L, ("integer default values not set:"
+ FLAGS.l)
assert FLAGS.letters == ['a', 'b', 'c'], ("list default values not set:"
+ FLAGS.letters)
assert FLAGS.numbers == [1, 2, 3], ("list default values not set:"
+ FLAGS.numbers)
assert FLAGS.kwery is None, ("enum default None value not set:"
+ FLAGS.kwery)
flag_values = FLAGS.FlagValuesDict()
assert flag_values['repeat'] == 4
assert flag_values['name'] == 'Bob'
assert flag_values['debug'] == 0
assert flag_values['r'] == 4 # short for of repeat
assert flag_values['q'] == 1
assert flag_values['quack'] == 0
assert flag_values['x'] == 3
assert flag_values['l'] == 0x7fffffff00000000L
assert flag_values['letters'] == ['a', 'b', 'c']
assert flag_values['numbers'] == [1, 2, 3]
assert flag_values['kwery'] is None
# Verify string form of defaults
assert FLAGS['repeat'].default_as_str == "'4'"
assert FLAGS['name'].default_as_str == "'Bob'"
assert FLAGS['debug'].default_as_str == "'false'"
assert FLAGS['q'].default_as_str == "'true'"
assert FLAGS['quack'].default_as_str == "'false'"
assert FLAGS['noexec'].default_as_str == "'true'"
assert FLAGS['x'].default_as_str == "'3'"
assert FLAGS['l'].default_as_str == "'9223372032559808512'"
assert FLAGS['letters'].default_as_str == "'a,b,c'"
assert FLAGS['numbers'].default_as_str == "'1,2,3'"
# Verify that the iterator for flags yields all the keys
keys = list(FLAGS)
keys.sort()
reg_flags = FLAGS.RegisteredFlags()
reg_flags.sort()
self.assertEqual(keys, reg_flags)
# Parse flags
# .. empty command line
argv = ('./program',)
argv = FLAGS(argv)
assert len(argv) == 1, "wrong number of arguments pulled"
assert argv[0]=='./program', "program name not preserved"
# .. non-empty command line
argv = ('./program', '--debug', '--name=Bob', '-q', '--x=8')
argv = FLAGS(argv)
assert len(argv) == 1, "wrong number of arguments pulled"
assert argv[0]=='./program', "program name not preserved"
assert FLAGS['debug'].present == 1
FLAGS['debug'].present = 0 # Reset
assert FLAGS['name'].present == 1
FLAGS['name'].present = 0 # Reset
assert FLAGS['q'].present == 1
FLAGS['q'].present = 0 # Reset
assert FLAGS['x'].present == 1
FLAGS['x'].present = 0 # Reset
# Flags list
self.assertEqual(len(FLAGS.RegisteredFlags()),
number_defined_flags + number_test_framework_flags)
assert 'name' in FLAGS.RegisteredFlags()
assert 'debug' in FLAGS.RegisteredFlags()
assert 'repeat' in FLAGS.RegisteredFlags()
assert 'r' in FLAGS.RegisteredFlags()
assert 'q' in FLAGS.RegisteredFlags()
assert 'quack' in FLAGS.RegisteredFlags()
assert 'x' in FLAGS.RegisteredFlags()
assert 'l' in FLAGS.RegisteredFlags()
assert 'letters' in FLAGS.RegisteredFlags()
assert 'numbers' in FLAGS.RegisteredFlags()
# has_key
assert FLAGS.has_key('name')
assert not FLAGS.has_key('name2')
assert 'name' in FLAGS
assert 'name2' not in FLAGS
# try deleting a flag
del FLAGS.r
self.assertEqual(len(FLAGS.RegisteredFlags()),
number_defined_flags - 1 + number_test_framework_flags)
assert not 'r' in FLAGS.RegisteredFlags()
# .. command line with extra stuff
argv = ('./program', '--debug', '--name=Bob', 'extra')
argv = FLAGS(argv)
assert len(argv) == 2, "wrong number of arguments pulled"
assert argv[0]=='./program', "program name not preserved"
assert argv[1]=='extra', "extra argument not preserved"
assert FLAGS['debug'].present == 1
FLAGS['debug'].present = 0 # Reset
assert FLAGS['name'].present == 1
FLAGS['name'].present = 0 # Reset
# Test reset
argv = ('./program', '--debug')
argv = FLAGS(argv)
assert len(argv) == 1, "wrong number of arguments pulled"
assert argv[0] == './program', "program name not preserved"
assert FLAGS['debug'].present == 1
assert FLAGS['debug'].value
FLAGS.Reset()
assert FLAGS['debug'].present == 0
assert not FLAGS['debug'].value
# Test that reset restores default value when default value is None.
argv = ('./program', '--kwery=who')
argv = FLAGS(argv)
assert len(argv) == 1, "wrong number of arguments pulled"
assert argv[0] == './program', "program name not preserved"
assert FLAGS['kwery'].present == 1
assert FLAGS['kwery'].value == 'who'
FLAGS.Reset()
assert FLAGS['kwery'].present == 0
assert FLAGS['kwery'].value == None
# Test integer argument passing
argv = ('./program', '--x', '0x12345')
argv = FLAGS(argv)
self.assertEquals(FLAGS.x, 0x12345)
self.assertEquals(type(FLAGS.x), int)
argv = ('./program', '--x', '0x1234567890ABCDEF1234567890ABCDEF')
argv = FLAGS(argv)
self.assertEquals(FLAGS.x, 0x1234567890ABCDEF1234567890ABCDEF)
self.assertEquals(type(FLAGS.x), long)
# Treat 0-prefixed parameters as base-10, not base-8
argv = ('./program', '--x', '012345')
argv = FLAGS(argv)
self.assertEquals(FLAGS.x, 12345)
self.assertEquals(type(FLAGS.x), int)
argv = ('./program', '--x', '0123459')
argv = FLAGS(argv)
self.assertEquals(FLAGS.x, 123459)
self.assertEquals(type(FLAGS.x), int)
argv = ('./program', '--x', '0x123efg')
try:
argv = FLAGS(argv)
raise AssertionError("failed to detect invalid hex argument")
except flags.IllegalFlagValue:
pass
argv = ('./program', '--x', '0X123efg')
try:
argv = FLAGS(argv)
raise AssertionError("failed to detect invalid hex argument")
except flags.IllegalFlagValue:
pass
# Test boolean argument parsing
flags.DEFINE_boolean("test0", None, "test boolean parsing")
argv = ('./program', '--notest0')
argv = FLAGS(argv)
assert FLAGS.test0 == 0
flags.DEFINE_boolean("test1", None, "test boolean parsing")
argv = ('./program', '--test1')
argv = FLAGS(argv)
assert FLAGS.test1 == 1
FLAGS.test0 = None
argv = ('./program', '--test0=false')
argv = FLAGS(argv)
assert FLAGS.test0 == 0
FLAGS.test1 = None
argv = ('./program', '--test1=true')
argv = FLAGS(argv)
assert FLAGS.test1 == 1
FLAGS.test0 = None
argv = ('./program', '--test0=0')
argv = FLAGS(argv)
assert FLAGS.test0 == 0
FLAGS.test1 = None
argv = ('./program', '--test1=1')
argv = FLAGS(argv)
assert FLAGS.test1 == 1
# Test booleans that already have 'no' as a prefix
FLAGS.noexec = None
argv = ('./program', '--nonoexec', '--name', 'Bob')
argv = FLAGS(argv)
assert FLAGS.noexec == 0
FLAGS.noexec = None
argv = ('./program', '--name', 'Bob', '--noexec')
argv = FLAGS(argv)
assert FLAGS.noexec == 1
# Test unassigned booleans
flags.DEFINE_boolean("testnone", None, "test boolean parsing")
argv = ('./program',)
argv = FLAGS(argv)
assert FLAGS.testnone == None
# Test get with default
flags.DEFINE_boolean("testget1", None, "test parsing with defaults")
flags.DEFINE_boolean("testget2", None, "test parsing with defaults")
flags.DEFINE_boolean("testget3", None, "test parsing with defaults")
flags.DEFINE_integer("testget4", None, "test parsing with defaults")
argv = ('./program','--testget1','--notestget2')
argv = FLAGS(argv)
assert FLAGS.get('testget1', 'foo') == 1
assert FLAGS.get('testget2', 'foo') == 0
assert FLAGS.get('testget3', 'foo') == 'foo'
assert FLAGS.get('testget4', 'foo') == 'foo'
# test list code
lists = [['hello','moo','boo','1'],
[],]
flags.DEFINE_list('testlist', '', 'test lists parsing')
flags.DEFINE_spaceseplist('testspacelist', '', 'tests space lists parsing')
for name, sep in (('testlist', ','), ('testspacelist', ' '),
('testspacelist', '\n')):
for lst in lists:
argv = ('./program', '--%s=%s' % (name, sep.join(lst)))
argv = FLAGS(argv)
self.assertEquals(getattr(FLAGS, name), lst)
# Test help text
flagsHelp = str(FLAGS)
assert flagsHelp.find("repeat") != -1, "cannot find flag in help"
assert flagsHelp.find(repeatHelp) != -1, "cannot find help string in help"
# Test flag specified twice
argv = ('./program', '--repeat=4', '--repeat=2', '--debug', '--nodebug')
argv = FLAGS(argv)
self.assertEqual(FLAGS.get('repeat', None), 2)
self.assertEqual(FLAGS.get('debug', None), 0)
# Test MultiFlag with single default value
flags.DEFINE_multistring('s_str', 'sing1',
'string option that can occur multiple times',
short_name='s')
self.assertEqual(FLAGS.get('s_str', None), [ 'sing1', ])
# Test MultiFlag with list of default values
multi_string_defs = [ 'def1', 'def2', ]
flags.DEFINE_multistring('m_str', multi_string_defs,
'string option that can occur multiple times',
short_name='m')
self.assertEqual(FLAGS.get('m_str', None), multi_string_defs)
# Test flag specified multiple times with a MultiFlag
argv = ('./program', '--m_str=str1', '-m', 'str2')
argv = FLAGS(argv)
self.assertEqual(FLAGS.get('m_str', None), [ 'str1', 'str2', ])
# Test single-letter flags; should support both single and double dash
argv = ('./program', '-q', '-x8')
argv = FLAGS(argv)
self.assertEqual(FLAGS.get('q', None), 1)
self.assertEqual(FLAGS.get('x', None), 8)
argv = ('./program', '--q', '--x', '9', '--noqu')
argv = FLAGS(argv)
self.assertEqual(FLAGS.get('q', None), 1)
self.assertEqual(FLAGS.get('x', None), 9)
# --noqu should match '--noquack since it's a unique prefix
self.assertEqual(FLAGS.get('quack', None), 0)
argv = ('./program', '--noq', '--x=10', '--qu')
argv = FLAGS(argv)
self.assertEqual(FLAGS.get('q', None), 0)
self.assertEqual(FLAGS.get('x', None), 10)
self.assertEqual(FLAGS.get('quack', None), 1)
####################################
# Test flag serialization code:
oldtestlist = FLAGS.testlist
oldtestspacelist = FLAGS.testspacelist
argv = ('./program',
FLAGS['test0'].Serialize(),
FLAGS['test1'].Serialize(),
FLAGS['testnone'].Serialize(),
FLAGS['s_str'].Serialize())
argv = FLAGS(argv)
self.assertEqual(FLAGS['test0'].Serialize(), '--notest0')
self.assertEqual(FLAGS['test1'].Serialize(), '--test1')
self.assertEqual(FLAGS['testnone'].Serialize(), '')
self.assertEqual(FLAGS['s_str'].Serialize(), '--s_str=sing1')
testlist1 = ['aa', 'bb']
testspacelist1 = ['aa', 'bb', 'cc']
FLAGS.testlist = list(testlist1)
FLAGS.testspacelist = list(testspacelist1)
argv = ('./program',
FLAGS['testlist'].Serialize(),
FLAGS['testspacelist'].Serialize())
argv = FLAGS(argv)
self.assertEqual(FLAGS.testlist, testlist1)
self.assertEqual(FLAGS.testspacelist, testspacelist1)
testlist1 = ['aa some spaces', 'bb']
testspacelist1 = ['aa', 'bb,some,commas,', 'cc']
FLAGS.testlist = list(testlist1)
FLAGS.testspacelist = list(testspacelist1)
argv = ('./program',
FLAGS['testlist'].Serialize(),
FLAGS['testspacelist'].Serialize())
argv = FLAGS(argv)
self.assertEqual(FLAGS.testlist, testlist1)
self.assertEqual(FLAGS.testspacelist, testspacelist1)
FLAGS.testlist = oldtestlist
FLAGS.testspacelist = oldtestspacelist
####################################
# Test flag-update:
def ArgsString():
flagnames = FLAGS.RegisteredFlags()
flagnames.sort()
nonbool_flags = ['--%s %s' % (name, FLAGS.get(name, None))
for name in flagnames
if not isinstance(FLAGS[name], flags.BooleanFlag)]
truebool_flags = ['--%s' % (name)
for name in flagnames
if isinstance(FLAGS[name], flags.BooleanFlag) and
FLAGS.get(name, None)]
falsebool_flags = ['--no%s' % (name)
for name in flagnames
if isinstance(FLAGS[name], flags.BooleanFlag) and
not FLAGS.get(name, None)]
return ' '.join(nonbool_flags + truebool_flags + falsebool_flags)
argv = ('./program', '--repeat=3', '--name=giants', '--nodebug')
FLAGS(argv)
self.assertEqual(FLAGS.get('repeat', None), 3)
self.assertEqual(FLAGS.get('name', None), 'giants')
self.assertEqual(FLAGS.get('debug', None), 0)
self.assertEqual(ArgsString(),
"--kwery None "
"--l 9223372032559808512 "
"--letters ['a', 'b', 'c'] "
"--m ['str1', 'str2'] --m_str ['str1', 'str2'] "
"--name giants "
"--numbers [1, 2, 3] "
"--repeat 3 "
"--s ['sing1'] --s_str ['sing1'] "
"--testget4 None --testlist [] "
"--testspacelist [] --x 10 "
"--noexec --quack "
"--test1 "
"--testget1 --tmod_baz_x --no? --nodebug --nohelp --nohelpshort --nohelpxml "
"--noq --notest0 --notestget2 "
"--notestget3 --notestnone")
argv = ('./program', '--debug', '--m_str=upd1', '-s', 'upd2')
FLAGS(argv)
self.assertEqual(FLAGS.get('repeat', None), 3)
self.assertEqual(FLAGS.get('name', None), 'giants')
self.assertEqual(FLAGS.get('debug', None), 1)
# items appended to existing non-default value lists for --m/--m_str
# new value overwrites default value (not appended to it) for --s/--s_str
self.assertEqual(ArgsString(),
"--kwery None "
"--l 9223372032559808512 "
"--letters ['a', 'b', 'c'] "
"--m ['str1', 'str2', 'upd1'] "
"--m_str ['str1', 'str2', 'upd1'] "
"--name giants "
"--numbers [1, 2, 3] "
"--repeat 3 "
"--s ['upd2'] --s_str ['upd2'] "
"--testget4 None --testlist [] "
"--testspacelist [] --x 10 "
"--debug --noexec --quack "
"--test1 "
"--testget1 --tmod_baz_x --no? --nohelp --nohelpshort --nohelpxml "
"--noq --notest0 --notestget2 "
"--notestget3 --notestnone")
####################################
# Test all kind of error conditions.
# Duplicate flag detection
try:
flags.DEFINE_boolean("run", 0, "runhelp", short_name='q')
raise AssertionError("duplicate flag detection failed")
except flags.DuplicateFlag, e:
pass
# Duplicate short flag detection
try:
flags.DEFINE_boolean("zoom1", 0, "runhelp z1", short_name='z')
flags.DEFINE_boolean("zoom2", 0, "runhelp z2", short_name='z')
raise AssertionError("duplicate short flag detection failed")
except flags.DuplicateFlag, e:
self.assertTrue("The flag 'z' is defined twice. " in e.args[0])
self.assertTrue("First from" in e.args[0])
self.assertTrue(", Second from" in e.args[0])
# Duplicate mixed flag detection
try:
flags.DEFINE_boolean("short1", 0, "runhelp s1", short_name='s')
flags.DEFINE_boolean("s", 0, "runhelp s2")
raise AssertionError("duplicate mixed flag detection failed")
except flags.DuplicateFlag, e:
self.assertTrue("The flag 's' is defined twice. " in e.args[0])
self.assertTrue("First from" in e.args[0])
self.assertTrue(", Second from" in e.args[0])
# Make sure allow_override works
try:
flags.DEFINE_boolean("dup1", 0, "runhelp d11", short_name='u',
allow_override=0)
flag = FLAGS.FlagDict()['dup1']
self.assertEqual(flag.default, 0)
flags.DEFINE_boolean("dup1", 1, "runhelp d12", short_name='u',
allow_override=1)
flag = FLAGS.FlagDict()['dup1']
self.assertEqual(flag.default, 1)
except flags.DuplicateFlag, e:
raise AssertionError("allow_override did not permit a flag duplication")
# Make sure allow_override works
try:
flags.DEFINE_boolean("dup2", 0, "runhelp d21", short_name='u',
allow_override=1)
flag = FLAGS.FlagDict()['dup2']
self.assertEqual(flag.default, 0)
flags.DEFINE_boolean("dup2", 1, "runhelp d22", short_name='u',
allow_override=0)
flag = FLAGS.FlagDict()['dup2']
self.assertEqual(flag.default, 1)
except flags.DuplicateFlag, e:
raise AssertionError("allow_override did not permit a flag duplication")
# Make sure allow_override doesn't work with None default
try:
flags.DEFINE_boolean("dup3", 0, "runhelp d31", short_name='u3',
allow_override=0)
flag = FLAGS.FlagDict()['dup3']
self.assertEqual(flag.default, 0)
flags.DEFINE_boolean("dup3", None, "runhelp d32", short_name='u3',
allow_override=1)
raise AssertionError('Cannot override a flag with a default of None')
except flags.DuplicateFlagCannotPropagateNoneToSwig, e:
pass
# Make sure that when we override, the help string gets updated correctly
flags.DEFINE_boolean("dup3", 0, "runhelp d31", short_name='u',
allow_override=1)
flags.DEFINE_boolean("dup3", 1, "runhelp d32", short_name='u',
allow_override=1)
self.assert_(str(FLAGS).find('runhelp d31') == -1)
self.assert_(str(FLAGS).find('runhelp d32') != -1)
# Make sure AppendFlagValues works
new_flags = flags.FlagValues()
flags.DEFINE_boolean("new1", 0, "runhelp n1", flag_values=new_flags)
flags.DEFINE_boolean("new2", 0, "runhelp n2", flag_values=new_flags)
self.assertEqual(len(new_flags.FlagDict()), 2)
old_len = len(FLAGS.FlagDict())
FLAGS.AppendFlagValues(new_flags)
self.assertEqual(len(FLAGS.FlagDict())-old_len, 2)
self.assertEqual("new1" in FLAGS.FlagDict(), True)
self.assertEqual("new2" in FLAGS.FlagDict(), True)
# Then test that removing those flags works
FLAGS.RemoveFlagValues(new_flags)
self.assertEqual(len(FLAGS.FlagDict()), old_len)
self.assertFalse("new1" in FLAGS.FlagDict())
self.assertFalse("new2" in FLAGS.FlagDict())
# Make sure AppendFlagValues works with flags with shortnames.
new_flags = flags.FlagValues()
flags.DEFINE_boolean("new3", 0, "runhelp n3", flag_values=new_flags)
flags.DEFINE_boolean("new4", 0, "runhelp n4", flag_values=new_flags,
short_name="n4")
self.assertEqual(len(new_flags.FlagDict()), 3)
old_len = len(FLAGS.FlagDict())
FLAGS.AppendFlagValues(new_flags)
self.assertEqual(len(FLAGS.FlagDict())-old_len, 3)
self.assertTrue("new3" in FLAGS.FlagDict())
self.assertTrue("new4" in FLAGS.FlagDict())
self.assertTrue("n4" in FLAGS.FlagDict())
self.assertEqual(FLAGS.FlagDict()['n4'], FLAGS.FlagDict()['new4'])
# Then test removing them
FLAGS.RemoveFlagValues(new_flags)
self.assertEqual(len(FLAGS.FlagDict()), old_len)
self.assertFalse("new3" in FLAGS.FlagDict())
self.assertFalse("new4" in FLAGS.FlagDict())
self.assertFalse("n4" in FLAGS.FlagDict())
# Make sure AppendFlagValues fails on duplicates
flags.DEFINE_boolean("dup4", 0, "runhelp d41")
new_flags = flags.FlagValues()
flags.DEFINE_boolean("dup4", 0, "runhelp d42", flag_values=new_flags)
try:
FLAGS.AppendFlagValues(new_flags)
raise AssertionError("ignore_copy was not set but caused no exception")
except flags.DuplicateFlag, e:
pass
# Integer out of bounds
try:
argv = ('./program', '--repeat=-4')
FLAGS(argv)
raise AssertionError('integer bounds exception not raised:'
+ str(FLAGS.repeat))
except flags.IllegalFlagValue:
pass
# Non-integer
try:
argv = ('./program', '--repeat=2.5')
FLAGS(argv)
raise AssertionError("malformed integer value exception not raised")
except flags.IllegalFlagValue:
pass
# Missing required arugment
try:
argv = ('./program', '--name')
FLAGS(argv)
raise AssertionError("Flag argument required exception not raised")
except flags.FlagsError:
pass
# Non-boolean arguments for boolean
try:
argv = ('./program', '--debug=goofup')
FLAGS(argv)
raise AssertionError("Illegal flag value exception not raised")
except flags.IllegalFlagValue:
pass
try:
argv = ('./program', '--debug=42')
FLAGS(argv)
raise AssertionError("Illegal flag value exception not raised")
except flags.IllegalFlagValue:
pass
# Non-numeric argument for integer flag --repeat
try:
argv = ('./program', '--repeat', 'Bob', 'extra')
FLAGS(argv)
raise AssertionError("Illegal flag value exception not raised")
except flags.IllegalFlagValue:
pass
def test_module_help(self):
"""Test ModuleHelp()."""
helpstr = FLAGS.ModuleHelp(module_baz)
expected_help = "\n" + module_baz.__name__ + ":" + """
--[no]tmod_baz_x: Boolean flag.
(default: 'true')"""
self.assertMultiLineEqual(expected_help, helpstr)
def test_main_module_help(self):
"""Test MainModuleHelp()."""
helpstr = FLAGS.MainModuleHelp()
expected_help = "\n" + sys.argv[0] + ':' + """
--[no]debug: debughelp
(default: 'false')
-u,--[no]dup1: runhelp d12
(default: 'true')
-u,--[no]dup2: runhelp d22
(default: 'true')
-u,--[no]dup3: runhelp d32
(default: 'true')
--[no]dup4: runhelp d41
(default: 'false')
-?,--[no]help: show this help
--[no]helpshort: show usage only for this module
--[no]helpxml: like --help, but generates XML output
--kwery: <who|what|why|where|when>: ?
--l: how long to be
(default: '9223372032559808512')
(an integer)
--letters: a list of letters
(default: 'a,b,c')
(a comma separated list)
-m,--m_str: string option that can occur multiple times;
repeat this option to specify a list of values
(default: "['def1', 'def2']")
--name: namehelp
(default: 'Bob')
--[no]noexec: boolean flag with no as prefix
(default: 'true')
--numbers: a list of numbers
(default: '1,2,3')
(a comma separated list)
--[no]q: quiet mode
(default: 'true')
--[no]quack: superstring of 'q'
(default: 'false')
-r,--repeat: how many times to repeat (0-5)
(default: '4')
(a non-negative integer)
-s,--s_str: string option that can occur multiple times;
repeat this option to specify a list of values
(default: "['sing1']")
--[no]test0: test boolean parsing
--[no]test1: test boolean parsing
--[no]testget1: test parsing with defaults
--[no]testget2: test parsing with defaults
--[no]testget3: test parsing with defaults
--testget4: test parsing with defaults
(an integer)
--testlist: test lists parsing
(default: '')
(a comma separated list)
--[no]testnone: test boolean parsing
--testspacelist: tests space lists parsing
(default: '')
(a whitespace separated list)
--x: how eXtreme to be
(default: '3')
(an integer)
-z,--[no]zoom1: runhelp z1
(default: 'false')"""
self.assertMultiLineEqual(expected_help, helpstr)
class LoadFromFlagFileTest(unittest.TestCase):
"""Testing loading flags from a file and parsing them."""
def setUp(self):
self.flag_values = flags.FlagValues()
# make sure we are using the old, stupid way of parsing flags.
self.flag_values.UseGnuGetOpt(False)
flags.DEFINE_string('UnitTestMessage1', 'Foo!', 'You Add Here.',
flag_values=self.flag_values)
flags.DEFINE_string('UnitTestMessage2', 'Bar!', 'Hello, Sailor!',
flag_values=self.flag_values)
flags.DEFINE_boolean('UnitTestBoolFlag', 0, 'Some Boolean thing',
flag_values=self.flag_values)
flags.DEFINE_integer('UnitTestNumber', 12345, 'Some integer',
lower_bound=0, flag_values=self.flag_values)
flags.DEFINE_list('UnitTestList', "1,2,3", 'Some list',
flag_values=self.flag_values)
self.files_to_delete = []
def tearDown(self):
self._RemoveTestFiles()
def _SetupTestFiles(self):
""" Creates and sets up some dummy flagfile files with bogus flags"""
# Figure out where to create temporary files
tmp_path = '/tmp/flags_unittest'
if os.path.exists(tmp_path):
shutil.rmtree(tmp_path)
os.makedirs(tmp_path)
try:
tmp_flag_file_1 = open((tmp_path + '/UnitTestFile1.tst'), 'w')
tmp_flag_file_2 = open((tmp_path + '/UnitTestFile2.tst'), 'w')
tmp_flag_file_3 = open((tmp_path + '/UnitTestFile3.tst'), 'w')
except IOError, e_msg:
print(e_msg)
print('FAIL\n File Creation problem in Unit Test')
sys.exit(1)
# put some dummy flags in our test files
tmp_flag_file_1.write('#A Fake Comment\n')
tmp_flag_file_1.write('--UnitTestMessage1=tempFile1!\n')
tmp_flag_file_1.write('\n')
tmp_flag_file_1.write('--UnitTestNumber=54321\n')
tmp_flag_file_1.write('--noUnitTestBoolFlag\n')
file_list = [tmp_flag_file_1.name]
# this one includes test file 1
tmp_flag_file_2.write('//A Different Fake Comment\n')
tmp_flag_file_2.write('--flagfile=%s\n' % tmp_flag_file_1.name)
tmp_flag_file_2.write('--UnitTestMessage2=setFromTempFile2\n')
tmp_flag_file_2.write('\t\t\n')
tmp_flag_file_2.write('--UnitTestNumber=6789a\n')
file_list.append(tmp_flag_file_2.name)
# this file points to itself
tmp_flag_file_3.write('--flagfile=%s\n' % tmp_flag_file_3.name)
tmp_flag_file_3.write('--UnitTestMessage1=setFromTempFile3\n')
tmp_flag_file_3.write('#YAFC\n')
tmp_flag_file_3.write('--UnitTestBoolFlag\n')
file_list.append(tmp_flag_file_3.name)
tmp_flag_file_1.close()
tmp_flag_file_2.close()
tmp_flag_file_3.close()
self.files_to_delete = file_list
return file_list # these are just the file names
# end SetupFiles def
def _RemoveTestFiles(self):
"""Closes the files we just created. tempfile deletes them for us """
for file_name in self.files_to_delete:
try:
os.remove(file_name)
except OSError, e_msg:
print('%s\n, Problem deleting test file' % e_msg)
#end RemoveTestFiles def
def _ReadFlagsFromFiles(self, argv, force_gnu):
return argv[:1] + self.flag_values.ReadFlagsFromFiles(argv[1:],
force_gnu=force_gnu)
#### Flagfile Unit Tests ####
def testMethod_flagfiles_1(self):
""" Test trivial case with no flagfile based options. """
fake_cmd_line = 'fooScript --UnitTestBoolFlag'
fake_argv = fake_cmd_line.split(' ')
self.flag_values(fake_argv)
self.assertEqual( self.flag_values.UnitTestBoolFlag, 1)
self.assertEqual( fake_argv, self._ReadFlagsFromFiles(fake_argv, False))
# end testMethodOne
def testMethod_flagfiles_2(self):
"""Tests parsing one file + arguments off simulated argv"""
tmp_files = self._SetupTestFiles()
# specify our temp file on the fake cmd line
fake_cmd_line = 'fooScript --q --flagfile=%s' % tmp_files[0]
fake_argv = fake_cmd_line.split(' ')
# We should see the original cmd line with the file's contents spliced in.
# Note that these will be in REVERSE order from order encountered in file
# This is done so arguements we encounter sooner will have priority.
expected_results = ['fooScript',
'--UnitTestMessage1=tempFile1!',
'--UnitTestNumber=54321',
'--noUnitTestBoolFlag',
'--q']
test_results = self._ReadFlagsFromFiles(fake_argv, False)
self.assertEqual(expected_results, test_results)
# end testTwo def
def testMethod_flagfiles_3(self):
"""Tests parsing nested files + arguments of simulated argv"""
tmp_files = self._SetupTestFiles()
# specify our temp file on the fake cmd line
fake_cmd_line = ('fooScript --UnitTestNumber=77 --flagfile=%s'
% tmp_files[1])
fake_argv = fake_cmd_line.split(' ')
expected_results = ['fooScript',
'--UnitTestMessage1=tempFile1!',
'--UnitTestNumber=54321',
'--noUnitTestBoolFlag',
'--UnitTestMessage2=setFromTempFile2',
'--UnitTestNumber=6789a',
'--UnitTestNumber=77']
test_results = self._ReadFlagsFromFiles(fake_argv, False)
self.assertEqual(expected_results, test_results)
# end testThree def
def testMethod_flagfiles_4(self):
"""Tests parsing self-referential files + arguments of simulated argv.
This test should print a warning to stderr of some sort.
"""
tmp_files = self._SetupTestFiles()
# specify our temp file on the fake cmd line
fake_cmd_line = ('fooScript --flagfile=%s --noUnitTestBoolFlag'
% tmp_files[2])
fake_argv = fake_cmd_line.split(' ')
expected_results = ['fooScript',
'--UnitTestMessage1=setFromTempFile3',
'--UnitTestBoolFlag',
'--noUnitTestBoolFlag' ]
test_results = self._ReadFlagsFromFiles(fake_argv, False)
self.assertEqual(expected_results, test_results)
def testMethod_flagfiles_5(self):
"""Test that --flagfile parsing respects the '--' end-of-options marker."""
tmp_files = self._SetupTestFiles()
# specify our temp file on the fake cmd line
fake_cmd_line = 'fooScript --SomeFlag -- --flagfile=%s' % tmp_files[0]
fake_argv = fake_cmd_line.split(' ')
expected_results = ['fooScript',
'--SomeFlag',
'--',
'--flagfile=%s' % tmp_files[0]]
test_results = self._ReadFlagsFromFiles(fake_argv, False)
self.assertEqual(expected_results, test_results)
def testMethod_flagfiles_6(self):
"""Test that --flagfile parsing stops at non-options (non-GNU behavior)."""
tmp_files = self._SetupTestFiles()
# specify our temp file on the fake cmd line
fake_cmd_line = ('fooScript --SomeFlag some_arg --flagfile=%s'
% tmp_files[0])
fake_argv = fake_cmd_line.split(' ')
expected_results = ['fooScript',
'--SomeFlag',
'some_arg',
'--flagfile=%s' % tmp_files[0]]
test_results = self._ReadFlagsFromFiles(fake_argv, False)
self.assertEqual(expected_results, test_results)
def testMethod_flagfiles_7(self):
"""Test that --flagfile parsing skips over a non-option (GNU behavior)."""
self.flag_values.UseGnuGetOpt()
tmp_files = self._SetupTestFiles()
# specify our temp file on the fake cmd line
fake_cmd_line = ('fooScript --SomeFlag some_arg --flagfile=%s'
% tmp_files[0])
fake_argv = fake_cmd_line.split(' ')
expected_results = ['fooScript',
'--UnitTestMessage1=tempFile1!',
'--UnitTestNumber=54321',
'--noUnitTestBoolFlag',
'--SomeFlag',
'some_arg']
test_results = self._ReadFlagsFromFiles(fake_argv, False)
self.assertEqual(expected_results, test_results)
def testMethod_flagfiles_8(self):
"""Test that --flagfile parsing respects force_gnu=True."""
tmp_files = self._SetupTestFiles()
# specify our temp file on the fake cmd line
fake_cmd_line = ('fooScript --SomeFlag some_arg --flagfile=%s'
% tmp_files[0])
fake_argv = fake_cmd_line.split(' ')
expected_results = ['fooScript',
'--UnitTestMessage1=tempFile1!',
'--UnitTestNumber=54321',
'--noUnitTestBoolFlag',
'--SomeFlag',
'some_arg']
test_results = self._ReadFlagsFromFiles(fake_argv, True)
self.assertEqual(expected_results, test_results)
def test_flagfiles_user_path_expansion(self):
"""Test that user directory referenced paths (ie. ~/foo) are correctly
expanded. This test depends on whatever account's running the unit test
to have read/write access to their own home directory, otherwise it'll
FAIL.
"""
fake_flagfile_item_style_1 = '--flagfile=~/foo.file'
fake_flagfile_item_style_2 = '-flagfile=~/foo.file'
expected_results = os.path.expanduser('~/foo.file')
test_results = self.flag_values.ExtractFilename(fake_flagfile_item_style_1)
self.assertEqual(expected_results, test_results)
test_results = self.flag_values.ExtractFilename(fake_flagfile_item_style_2)
self.assertEqual(expected_results, test_results)
# end testFour def
def test_no_touchy_non_flags(self):
"""
Test that the flags parser does not mutilate arguments which are
not supposed to be flags
"""
fake_argv = ['fooScript', '--UnitTestBoolFlag',
'command', '--command_arg1', '--UnitTestBoom', '--UnitTestB']
argv = self.flag_values(fake_argv)
self.assertEqual(argv, fake_argv[:1] + fake_argv[2:])
def test_parse_flags_after_args_if_using_gnu_getopt(self):
"""
Test that flags given after arguments are parsed if using gnu_getopt.
"""
self.flag_values.UseGnuGetOpt()
fake_argv = ['fooScript', '--UnitTestBoolFlag',
'command', '--UnitTestB']
argv = self.flag_values(fake_argv)
self.assertEqual(argv, ['fooScript', 'command'])
def test_SetDefault(self):
"""
Test changing flag defaults.
"""
# Test that SetDefault changes both the default and the value,
# and that the value is changed when one is given as an option.
self.flag_values['UnitTestMessage1'].SetDefault('New value')
self.assertEqual(self.flag_values.UnitTestMessage1, 'New value')
self.assertEqual(self.flag_values['UnitTestMessage1'].default_as_str,
"'New value'")
self.flag_values([ 'dummyscript', '--UnitTestMessage1=Newer value' ])
self.assertEqual(self.flag_values.UnitTestMessage1, 'Newer value')
# Test that setting the default to None works correctly.
self.flag_values['UnitTestNumber'].SetDefault(None)
self.assertEqual(self.flag_values.UnitTestNumber, None)
self.assertEqual(self.flag_values['UnitTestNumber'].default_as_str, None)
self.flag_values([ 'dummyscript', '--UnitTestNumber=56' ])
self.assertEqual(self.flag_values.UnitTestNumber, 56)
# Test that setting the default to zero works correctly.
self.flag_values['UnitTestNumber'].SetDefault(0)
self.assertEqual(self.flag_values.UnitTestNumber, 0)
self.assertEqual(self.flag_values['UnitTestNumber'].default_as_str, "'0'")
self.flag_values([ 'dummyscript', '--UnitTestNumber=56' ])
self.assertEqual(self.flag_values.UnitTestNumber, 56)
# Test that setting the default to "" works correctly.
self.flag_values['UnitTestMessage1'].SetDefault("")
self.assertEqual(self.flag_values.UnitTestMessage1, "")
self.assertEqual(self.flag_values['UnitTestMessage1'].default_as_str, "''")
self.flag_values([ 'dummyscript', '--UnitTestMessage1=fifty-six' ])
self.assertEqual(self.flag_values.UnitTestMessage1, "fifty-six")
# Test that setting the default to false works correctly.
self.flag_values['UnitTestBoolFlag'].SetDefault(False)
self.assertEqual(self.flag_values.UnitTestBoolFlag, False)
self.assertEqual(self.flag_values['UnitTestBoolFlag'].default_as_str,
"'false'")
self.flag_values([ 'dummyscript', '--UnitTestBoolFlag=true' ])
self.assertEqual(self.flag_values.UnitTestBoolFlag, True)
# Test that setting a list default works correctly.
self.flag_values['UnitTestList'].SetDefault('4,5,6')
self.assertEqual(self.flag_values.UnitTestList, ['4', '5', '6'])
self.assertEqual(self.flag_values['UnitTestList'].default_as_str, "'4,5,6'")
self.flag_values([ 'dummyscript', '--UnitTestList=7,8,9' ])
self.assertEqual(self.flag_values.UnitTestList, ['7', '8', '9'])
# Test that setting invalid defaults raises exceptions
self.assertRaises(flags.IllegalFlagValue,
self.flag_values['UnitTestNumber'].SetDefault, 'oops')
self.assertRaises(flags.IllegalFlagValue,
self.flag_values.SetDefault, 'UnitTestNumber', -1)
class FlagsParsingTest(unittest.TestCase):
"""Testing different aspects of parsing: '-f' vs '--flag', etc."""
def setUp(self):
self.flag_values = flags.FlagValues()
def testMethod_ShortestUniquePrefixes(self):
"""Test FlagValues.ShortestUniquePrefixes"""
flags.DEFINE_string('a', '', '', flag_values=self.flag_values)
flags.DEFINE_string('abc', '', '', flag_values=self.flag_values)
flags.DEFINE_string('common_a_string', '', '', flag_values=self.flag_values)
flags.DEFINE_boolean('common_b_boolean', 0, '',
flag_values=self.flag_values)
flags.DEFINE_boolean('common_c_boolean', 0, '',
flag_values=self.flag_values)
flags.DEFINE_boolean('common', 0, '', flag_values=self.flag_values)
flags.DEFINE_integer('commonly', 0, '', flag_values=self.flag_values)
flags.DEFINE_boolean('zz', 0, '', flag_values=self.flag_values)
flags.DEFINE_integer('nozz', 0, '', flag_values=self.flag_values)
shorter_flags = self.flag_values.ShortestUniquePrefixes(
self.flag_values.FlagDict())
expected_results = {'nocommon_b_boolean': 'nocommon_b',
'common_c_boolean': 'common_c',
'common_b_boolean': 'common_b',
'a': 'a',
'abc': 'ab',
'zz': 'z',
'nozz': 'nozz',
'common_a_string': 'common_a',
'commonly': 'commonl',
'nocommon_c_boolean': 'nocommon_c',
'nocommon': 'nocommon',
'common': 'common'}
for name, shorter in expected_results.iteritems():
self.assertEquals(shorter_flags[name], shorter)
self.flag_values.__delattr__('a')
self.flag_values.__delattr__('abc')
self.flag_values.__delattr__('common_a_string')
self.flag_values.__delattr__('common_b_boolean')
self.flag_values.__delattr__('common_c_boolean')
self.flag_values.__delattr__('common')
self.flag_values.__delattr__('commonly')
self.flag_values.__delattr__('zz')
self.flag_values.__delattr__('nozz')
def test_twodasharg_first(self):
flags.DEFINE_string("twodash_name", "Bob", "namehelp",
flag_values=self.flag_values)
flags.DEFINE_string("twodash_blame", "Rob", "blamehelp",
flag_values=self.flag_values)
argv = ('./program',
'--',
'--twodash_name=Harry')
argv = self.flag_values(argv)
self.assertEqual('Bob', self.flag_values.twodash_name)
self.assertEqual(argv[1], '--twodash_name=Harry')
def test_twodasharg_middle(self):
flags.DEFINE_string("twodash2_name", "Bob", "namehelp",
flag_values=self.flag_values)
flags.DEFINE_string("twodash2_blame", "Rob", "blamehelp",
flag_values=self.flag_values)
argv = ('./program',
'--twodash2_blame=Larry',
'--',
'--twodash2_name=Harry')
argv = self.flag_values(argv)
self.assertEqual('Bob', self.flag_values.twodash2_name)
self.assertEqual('Larry', self.flag_values.twodash2_blame)
self.assertEqual(argv[1], '--twodash2_name=Harry')
def test_onedasharg_first(self):
flags.DEFINE_string("onedash_name", "Bob", "namehelp",
flag_values=self.flag_values)
flags.DEFINE_string("onedash_blame", "Rob", "blamehelp",
flag_values=self.flag_values)
argv = ('./program',
'-',
'--onedash_name=Harry')
argv = self.flag_values(argv)
self.assertEqual(argv[1], '-')
# TODO(csilvers): we should still parse --onedash_name=Harry as a
# flag, but currently we don't (we stop flag processing as soon as
# we see the first non-flag).
# - This requires gnu_getopt from Python 2.3+ see FLAGS.UseGnuGetOpt()
def test_unrecognized_flags(self):
flags.DEFINE_string("name", "Bob", "namehelp", flag_values=self.flag_values)
# Unknown flag --nosuchflag
try:
argv = ('./program', '--nosuchflag', '--name=Bob', 'extra')
self.flag_values(argv)
raise AssertionError("Unknown flag exception not raised")
except flags.UnrecognizedFlag, e:
assert e.flagname == 'nosuchflag'
assert e.flagvalue == '--nosuchflag'
# Unknown flag -w (short option)
try:
argv = ('./program', '-w', '--name=Bob', 'extra')
self.flag_values(argv)
raise AssertionError("Unknown flag exception not raised")
except flags.UnrecognizedFlag, e:
assert e.flagname == 'w'
assert e.flagvalue == '-w'
# Unknown flag --nosuchflagwithparam=foo
try:
argv = ('./program', '--nosuchflagwithparam=foo', '--name=Bob', 'extra')
self.flag_values(argv)
raise AssertionError("Unknown flag exception not raised")
except flags.UnrecognizedFlag, e:
assert e.flagname == 'nosuchflagwithparam'
assert e.flagvalue == '--nosuchflagwithparam=foo'
# Allow unknown flag --nosuchflag if specified with undefok
argv = ('./program', '--nosuchflag', '--name=Bob',
'--undefok=nosuchflag', 'extra')
argv = self.flag_values(argv)
assert len(argv) == 2, "wrong number of arguments pulled"
assert argv[0]=='./program', "program name not preserved"
assert argv[1]=='extra', "extra argument not preserved"
# Allow unknown flag --noboolflag if undefok=boolflag is specified
argv = ('./program', '--noboolflag', '--name=Bob',
'--undefok=boolflag', 'extra')
argv = self.flag_values(argv)
assert len(argv) == 2, "wrong number of arguments pulled"
assert argv[0]=='./program', "program name not preserved"
assert argv[1]=='extra', "extra argument not preserved"
# But not if the flagname is misspelled:
try:
argv = ('./program', '--nosuchflag', '--name=Bob',
'--undefok=nosuchfla', 'extra')
self.flag_values(argv)
raise AssertionError("Unknown flag exception not raised")
except flags.UnrecognizedFlag, e:
assert e.flagname == 'nosuchflag'
try:
argv = ('./program', '--nosuchflag', '--name=Bob',
'--undefok=nosuchflagg', 'extra')
self.flag_values(argv)
raise AssertionError("Unknown flag exception not raised")
except flags.UnrecognizedFlag:
assert e.flagname == 'nosuchflag'
# Allow unknown short flag -w if specified with undefok
argv = ('./program', '-w', '--name=Bob', '--undefok=w', 'extra')
argv = self.flag_values(argv)
assert len(argv) == 2, "wrong number of arguments pulled"
assert argv[0]=='./program', "program name not preserved"
assert argv[1]=='extra', "extra argument not preserved"
# Allow unknown flag --nosuchflagwithparam=foo if specified
# with undefok
argv = ('./program', '--nosuchflagwithparam=foo', '--name=Bob',
'--undefok=nosuchflagwithparam', 'extra')
argv = self.flag_values(argv)
assert len(argv) == 2, "wrong number of arguments pulled"
assert argv[0]=='./program', "program name not preserved"
assert argv[1]=='extra', "extra argument not preserved"
# Even if undefok specifies multiple flags
argv = ('./program', '--nosuchflag', '-w', '--nosuchflagwithparam=foo',
'--name=Bob',
'--undefok=nosuchflag,w,nosuchflagwithparam',
'extra')
argv = self.flag_values(argv)
assert len(argv) == 2, "wrong number of arguments pulled"
assert argv[0]=='./program', "program name not preserved"
assert argv[1]=='extra', "extra argument not preserved"
# However, not if undefok doesn't specify the flag
try:
argv = ('./program', '--nosuchflag', '--name=Bob',
'--undefok=another_such', 'extra')
self.flag_values(argv)
raise AssertionError("Unknown flag exception not raised")
except flags.UnrecognizedFlag, e:
assert e.flagname == 'nosuchflag'
# Make sure --undefok doesn't mask other option errors.
try:
# Provide an option requiring a parameter but not giving it one.
argv = ('./program', '--undefok=name', '--name')
self.flag_values(argv)
raise AssertionError("Missing option parameter exception not raised")
except flags.UnrecognizedFlag:
raise AssertionError("Wrong kind of error exception raised")
except flags.FlagsError:
pass
# Test --undefok <list>
argv = ('./program', '--nosuchflag', '-w', '--nosuchflagwithparam=foo',
'--name=Bob',
'--undefok',
'nosuchflag,w,nosuchflagwithparam',
'extra')
argv = self.flag_values(argv)
assert len(argv) == 2, "wrong number of arguments pulled"
assert argv[0]=='./program', "program name not preserved"
assert argv[1]=='extra', "extra argument not preserved"
class NonGlobalFlagsTest(unittest.TestCase):
def test_nonglobal_flags(self):
"""Test use of non-global FlagValues"""
nonglobal_flags = flags.FlagValues()
flags.DEFINE_string("nonglobal_flag", "Bob", "flaghelp", nonglobal_flags)
argv = ('./program',
'--nonglobal_flag=Mary',
'extra')
argv = nonglobal_flags(argv)
assert len(argv) == 2, "wrong number of arguments pulled"
assert argv[0]=='./program', "program name not preserved"
assert argv[1]=='extra', "extra argument not preserved"
assert nonglobal_flags['nonglobal_flag'].value == 'Mary'
def test_unrecognized_nonglobal_flags(self):
"""Test unrecognized non-global flags"""
nonglobal_flags = flags.FlagValues()
argv = ('./program',
'--nosuchflag')
try:
argv = nonglobal_flags(argv)
raise AssertionError("Unknown flag exception not raised")
except flags.UnrecognizedFlag, e:
assert e.flagname == 'nosuchflag'
pass
argv = ('./program',
'--nosuchflag',
'--undefok=nosuchflag')
argv = nonglobal_flags(argv)
assert len(argv) == 1, "wrong number of arguments pulled"
assert argv[0]=='./program', "program name not preserved"
def test_create_flag_errors(self):
# Since the exception classes are exposed, nothing stops users
# from creating their own instances. This test makes sure that
# people modifying the flags module understand that the external
# mechanisms for creating the exceptions should continue to work.
e = flags.FlagsError()
e = flags.FlagsError("message")
e = flags.DuplicateFlag()
e = flags.DuplicateFlag("message")
e = flags.IllegalFlagValue()
e = flags.IllegalFlagValue("message")
e = flags.UnrecognizedFlag()
e = flags.UnrecognizedFlag("message")
def testFlagValuesDelAttr(self):
"""Checks that del self.flag_values.flag_id works."""
default_value = 'default value for testFlagValuesDelAttr'
# 1. Declare and delete a flag with no short name.
flag_values = flags.FlagValues()
flags.DEFINE_string('delattr_foo', default_value, 'A simple flag.',
flag_values=flag_values)
self.assertEquals(flag_values.delattr_foo, default_value)
flag_obj = flag_values['delattr_foo']
# We also check that _FlagIsRegistered works as expected :)
self.assertTrue(flag_values._FlagIsRegistered(flag_obj))
del flag_values.delattr_foo
self.assertFalse('delattr_foo' in flag_values.FlagDict())
self.assertFalse(flag_values._FlagIsRegistered(flag_obj))
# If the previous del FLAGS.delattr_foo did not work properly, the
# next definition will trigger a redefinition error.
flags.DEFINE_integer('delattr_foo', 3, 'A simple flag.',
flag_values=flag_values)
del flag_values.delattr_foo
self.assertFalse('delattr_foo' in flag_values.RegisteredFlags())
# 2. Declare and delete a flag with a short name.
flags.DEFINE_string('delattr_bar', default_value, 'flag with short name',
short_name='x5', flag_values=flag_values)
flag_obj = flag_values['delattr_bar']
self.assertTrue(flag_values._FlagIsRegistered(flag_obj))
del flag_values.x5
self.assertTrue(flag_values._FlagIsRegistered(flag_obj))
del flag_values.delattr_bar
self.assertFalse(flag_values._FlagIsRegistered(flag_obj))
# 3. Just like 2, but del flag_values.name last
flags.DEFINE_string('delattr_bar', default_value, 'flag with short name',
short_name='x5', flag_values=flag_values)
flag_obj = flag_values['delattr_bar']
self.assertTrue(flag_values._FlagIsRegistered(flag_obj))
del flag_values.delattr_bar
self.assertTrue(flag_values._FlagIsRegistered(flag_obj))
del flag_values.x5
self.assertFalse(flag_values._FlagIsRegistered(flag_obj))
self.assertFalse('delattr_bar' in flag_values.RegisteredFlags())
self.assertFalse('x5' in flag_values.RegisteredFlags())
class KeyFlagsTest(_UnitTestClass):
def setUp(self):
self.flag_values = flags.FlagValues()
def _GetNamesOfDefinedFlags(self, module, flag_values):
"""Returns the list of names of flags defined by a module.
Auxiliary for the testKeyFlags* methods.
Args:
module: A module object or a string module name.
flag_values: A FlagValues object.
Returns:
A list of strings.
"""
return [f.name for f in flag_values._GetFlagsDefinedByModule(module)]
def _GetNamesOfKeyFlags(self, module, flag_values):
"""Returns the list of names of key flags for a module.
Auxiliary for the testKeyFlags* methods.
Args:
module: A module object or a string module name.
flag_values: A FlagValues object.
Returns:
A list of strings.
"""
return [f.name for f in flag_values._GetKeyFlagsForModule(module)]
def _AssertListsHaveSameElements(self, list_1, list_2):
# Checks that two lists have the same elements with the same
# multiplicity, in possibly different order.
list_1 = list(list_1)
list_1.sort()
list_2 = list(list_2)
list_2.sort()
self.assertListEqual(list_1, list_2)
def testKeyFlags(self):
# Before starting any testing, make sure no flags are already
# defined for module_foo and module_bar.
self.assertListEqual(self._GetNamesOfKeyFlags(module_foo, self.flag_values),
[])
self.assertListEqual(self._GetNamesOfKeyFlags(module_bar, self.flag_values),
[])
self.assertListEqual(self._GetNamesOfDefinedFlags(module_foo,
self.flag_values),
[])
self.assertListEqual(self._GetNamesOfDefinedFlags(module_bar,
self.flag_values),
[])
# Defines a few flags in module_foo and module_bar.
module_foo.DefineFlags(flag_values=self.flag_values)
try:
# Part 1. Check that all flags defined by module_foo are key for
# that module, and similarly for module_bar.
for module in [module_foo, module_bar]:
self._AssertListsHaveSameElements(
self.flag_values._GetFlagsDefinedByModule(module),
self.flag_values._GetKeyFlagsForModule(module))
# Also check that each module defined the expected flags.
self._AssertListsHaveSameElements(
self._GetNamesOfDefinedFlags(module, self.flag_values),
module.NamesOfDefinedFlags())
# Part 2. Check that flags.DECLARE_key_flag works fine.
# Declare that some flags from module_bar are key for
# module_foo.
module_foo.DeclareKeyFlags(flag_values=self.flag_values)
# Check that module_foo has the expected list of defined flags.
self._AssertListsHaveSameElements(
self._GetNamesOfDefinedFlags(module_foo, self.flag_values),
module_foo.NamesOfDefinedFlags())
# Check that module_foo has the expected list of key flags.
self._AssertListsHaveSameElements(
self._GetNamesOfKeyFlags(module_foo, self.flag_values),
module_foo.NamesOfDeclaredKeyFlags())
# Part 3. Check that flags.ADOPT_module_key_flags works fine.
# Trigger a call to flags.ADOPT_module_key_flags(module_bar)
# inside module_foo. This should declare a few more key
# flags in module_foo.
module_foo.DeclareExtraKeyFlags(flag_values=self.flag_values)
# Check that module_foo has the expected list of key flags.
self._AssertListsHaveSameElements(
self._GetNamesOfKeyFlags(module_foo, self.flag_values),
module_foo.NamesOfDeclaredKeyFlags() +
module_foo.NamesOfDeclaredExtraKeyFlags())
finally:
module_foo.RemoveFlags(flag_values=self.flag_values)
def testKeyFlagsWithNonDefaultFlagValuesObject(self):
# Check that key flags work even when we use a FlagValues object
# that is not the default flags.self.flag_values object. Otherwise, this
# test is similar to testKeyFlags, but it uses only module_bar.
# The other test module (module_foo) uses only the default values
# for the flag_values keyword arguments. This way, testKeyFlags
# and this method test both the default FlagValues, the explicitly
# specified one, and a mixed usage of the two.
# A brand-new FlagValues object, to use instead of flags.self.flag_values.
fv = flags.FlagValues()
# Before starting any testing, make sure no flags are already
# defined for module_foo and module_bar.
self.assertListEqual(
self._GetNamesOfKeyFlags(module_bar, fv),
[])
self.assertListEqual(
self._GetNamesOfDefinedFlags(module_bar, fv),
[])
module_bar.DefineFlags(flag_values=fv)
# Check that all flags defined by module_bar are key for that
# module, and that module_bar defined the expected flags.
self._AssertListsHaveSameElements(
fv._GetFlagsDefinedByModule(module_bar),
fv._GetKeyFlagsForModule(module_bar))
self._AssertListsHaveSameElements(
self._GetNamesOfDefinedFlags(module_bar, fv),
module_bar.NamesOfDefinedFlags())
# Pick two flags from module_bar, declare them as key for the
# current (i.e., main) module (via flags.DECLARE_key_flag), and
# check that we get the expected effect. The important thing is
# that we always use flags_values=fv (instead of the default
# self.flag_values).
main_module = flags._GetMainModule()
names_of_flags_defined_by_bar = module_bar.NamesOfDefinedFlags()
flag_name_0 = names_of_flags_defined_by_bar[0]
flag_name_2 = names_of_flags_defined_by_bar[2]
flags.DECLARE_key_flag(flag_name_0, flag_values=fv)
self._AssertListsHaveSameElements(
self._GetNamesOfKeyFlags(main_module, fv),
[flag_name_0])
flags.DECLARE_key_flag(flag_name_2, flag_values=fv)
self._AssertListsHaveSameElements(
self._GetNamesOfKeyFlags(main_module, fv),
[flag_name_0, flag_name_2])
# Try with a special (not user-defined) flag too:
flags.DECLARE_key_flag('undefok', flag_values=fv)
self._AssertListsHaveSameElements(
self._GetNamesOfKeyFlags(main_module, fv),
[flag_name_0, flag_name_2, 'undefok'])
flags.ADOPT_module_key_flags(module_bar, fv)
self._AssertListsHaveSameElements(
self._GetNamesOfKeyFlags(main_module, fv),
names_of_flags_defined_by_bar + ['undefok'])
# Adopt key flags from the module google3.pyglib.flags itself.
flags.ADOPT_module_key_flags(flags, flag_values=fv)
self._AssertListsHaveSameElements(
self._GetNamesOfKeyFlags(main_module, fv),
names_of_flags_defined_by_bar + ['flagfile', 'undefok'])
def testMainModuleHelpWithKeyFlags(self):
# Similar to test_main_module_help, but this time we make sure to
# declare some key flags.
# Safety check that the main module does not declare any flags
# at the beginning of this test.
expected_help = ''
self.assertMultiLineEqual(expected_help, self.flag_values.MainModuleHelp())
# Define one flag in this main module and some flags in modules
# a and b. Also declare one flag from module a and one flag
# from module b as key flags for the main module.
flags.DEFINE_integer('main_module_int_fg', 1,
'Integer flag in the main module.',
flag_values=self.flag_values)
try:
main_module_int_fg_help = (
" --main_module_int_fg: Integer flag in the main module.\n"
" (default: '1')\n"
" (an integer)")
expected_help += "\n%s:" % (sys.argv[0])
expected_help += "\n" + main_module_int_fg_help
self.assertMultiLineEqual(expected_help,
self.flag_values.MainModuleHelp())
# The following call should be a no-op: any flag declared by a
# module is automatically key for that module.
flags.DECLARE_key_flag('main_module_int_fg', flag_values=self.flag_values)
self.assertMultiLineEqual(expected_help,
self.flag_values.MainModuleHelp())
# The definition of a few flags in an imported module should not
# change the main module help.
module_foo.DefineFlags(flag_values=self.flag_values)
self.assertMultiLineEqual(expected_help,
self.flag_values.MainModuleHelp())
flags.DECLARE_key_flag('tmod_foo_bool', flag_values=self.flag_values)
tmod_foo_bool_help = (
" --[no]tmod_foo_bool: Boolean flag from module foo.\n"
" (default: 'true')")
expected_help += "\n" + tmod_foo_bool_help
self.assertMultiLineEqual(expected_help,
self.flag_values.MainModuleHelp())
flags.DECLARE_key_flag('tmod_bar_z', flag_values=self.flag_values)
tmod_bar_z_help = (
" --[no]tmod_bar_z: Another boolean flag from module bar.\n"
" (default: 'false')")
# Unfortunately, there is some flag sorting inside
# MainModuleHelp, so we can't keep incrementally extending
# the expected_help string ...
expected_help = ("\n%s:\n%s\n%s\n%s" %
(sys.argv[0],
main_module_int_fg_help,
tmod_bar_z_help,
tmod_foo_bool_help))
self.assertMultiLineEqual(self.flag_values.MainModuleHelp(),
expected_help)
finally:
# At the end, delete all the flag information we created.
self.flag_values.__delattr__('main_module_int_fg')
module_foo.RemoveFlags(flag_values=self.flag_values)
def test_ADOPT_module_key_flags(self):
# Check that ADOPT_module_key_flags raises an exception when
# called with a module name (as opposed to a module object).
self.assertRaises(flags.FlagsError,
flags.ADOPT_module_key_flags,
'google3.pyglib.app')
class GetCallingModuleTest(unittest.TestCase):
"""Test whether we correctly determine the module which defines the flag."""
def test_GetCallingModule(self):
self.assertEqual(flags._GetCallingModule(), sys.argv[0])
self.assertEqual(
module_foo.GetModuleName(),
'test_module_foo')
self.assertEqual(
module_bar.GetModuleName(),
'test_module_bar')
# We execute the following exec statements for their side-effect
# (i.e., not raising an error). They emphasize the case that not
# all code resides in one of the imported modules: Python is a
# really dynamic language, where we can dynamically construct some
# code and execute it.
code = ("import gflags\n"
"module_name = gflags._GetCallingModule()")
exec code
# Next two exec statements executes code with a global environment
# that is different from the global environment of any imported
# module.
exec code in {}
# vars(self) returns a dictionary corresponding to the symbol
# table of the self object. dict(...) makes a distinct copy of
# this dictionary, such that any new symbol definition by the
# exec-ed code (e.g., import flags, module_name = ...) does not
# affect the symbol table of self.
exec code in dict(vars(self))
# Next test is actually more involved: it checks not only that
# _GetCallingModule does not crash inside exec code, it also checks
# that it returns the expected value: the code executed via exec
# code is treated as being executed by the current module. We
# check it twice: first time by executing exec from the main
# module, second time by executing it from module_bar.
global_dict = {}
exec code in global_dict
self.assertEqual(global_dict['module_name'],
sys.argv[0])
global_dict = {}
module_bar.ExecuteCode(code, global_dict)
self.assertEqual(
global_dict['module_name'],
'test_module_bar')
def test_GetCallingModuleWithIteritemsError(self):
# This test checks that _GetCallingModule is using
# sys.modules.items(), instead of .iteritems().
orig_sys_modules = sys.modules
# Mock sys.modules: simulates error produced by importing a module
# in paralel with our iteration over sys.modules.iteritems().
class SysModulesMock(dict):
def __init__(self, original_content):
dict.__init__(self, original_content)
def iteritems(self):
# Any dictionary method is fine, but not .iteritems().
raise RuntimeError('dictionary changed size during iteration')
sys.modules = SysModulesMock(orig_sys_modules)
try:
# _GetCallingModule should still work as expected:
self.assertEqual(flags._GetCallingModule(), sys.argv[0])
self.assertEqual(
module_foo.GetModuleName(),
'test_module_foo')
finally:
sys.modules = orig_sys_modules
class FlagsErrorMessagesTest(unittest.TestCase):
"""Testing special cases for integer and float flags error messages."""
def setUp(self):
# make sure we are using the old, stupid way of parsing flags.
self.flag_values = flags.FlagValues()
self.flag_values.UseGnuGetOpt(False)
def testIntegerErrorText(self):
# Make sure we get proper error text
flags.DEFINE_integer('positive', 4, 'non-negative flag', lower_bound=1,
flag_values=self.flag_values)
flags.DEFINE_integer('non_negative', 4, 'positive flag', lower_bound=0,
flag_values=self.flag_values)
flags.DEFINE_integer('negative', -4, 'negative flag', upper_bound=-1,
flag_values=self.flag_values)
flags.DEFINE_integer('non_positive', -4, 'non-positive flag', upper_bound=0,
flag_values=self.flag_values)
flags.DEFINE_integer('greater', 19, 'greater-than flag', lower_bound=4,
flag_values=self.flag_values)
flags.DEFINE_integer('smaller', -19, 'smaller-than flag', upper_bound=4,
flag_values=self.flag_values)
flags.DEFINE_integer('usual', 4, 'usual flag', lower_bound=0,
upper_bound=10000, flag_values=self.flag_values)
flags.DEFINE_integer('another_usual', 0, 'usual flag', lower_bound=-1,
upper_bound=1, flag_values=self.flag_values)
self._CheckErrorMessage('positive', -4, 'a positive integer')
self._CheckErrorMessage('non_negative', -4, 'a non-negative integer')
self._CheckErrorMessage('negative', 0, 'a negative integer')
self._CheckErrorMessage('non_positive', 4, 'a non-positive integer')
self._CheckErrorMessage('usual', -4, 'an integer in the range [0, 10000]')
self._CheckErrorMessage('another_usual', 4,
'an integer in the range [-1, 1]')
self._CheckErrorMessage('greater', -5, 'integer >= 4')
self._CheckErrorMessage('smaller', 5, 'integer <= 4')
def testFloatErrorText(self):
flags.DEFINE_float('positive', 4, 'non-negative flag', lower_bound=1,
flag_values=self.flag_values)
flags.DEFINE_float('non_negative', 4, 'positive flag', lower_bound=0,
flag_values=self.flag_values)
flags.DEFINE_float('negative', -4, 'negative flag', upper_bound=-1,
flag_values=self.flag_values)
flags.DEFINE_float('non_positive', -4, 'non-positive flag', upper_bound=0,
flag_values=self.flag_values)
flags.DEFINE_float('greater', 19, 'greater-than flag', lower_bound=4,
flag_values=self.flag_values)
flags.DEFINE_float('smaller', -19, 'smaller-than flag', upper_bound=4,
flag_values=self.flag_values)
flags.DEFINE_float('usual', 4, 'usual flag', lower_bound=0,
upper_bound=10000, flag_values=self.flag_values)
flags.DEFINE_float('another_usual', 0, 'usual flag', lower_bound=-1,
upper_bound=1, flag_values=self.flag_values)
self._CheckErrorMessage('positive', 0.5, 'number >= 1')
self._CheckErrorMessage('non_negative', -4.0, 'a non-negative number')
self._CheckErrorMessage('negative', 0.5, 'number <= -1')
self._CheckErrorMessage('non_positive', 4.0, 'a non-positive number')
self._CheckErrorMessage('usual', -4.0, 'a number in the range [0, 10000]')
self._CheckErrorMessage('another_usual', 4.0,
'a number in the range [-1, 1]')
self._CheckErrorMessage('smaller', 5.0, 'number <= 4')
def _CheckErrorMessage(self, flag_name, flag_value, expected_message_suffix):
"""Set a flag to a given value and make sure we get expected message."""
try:
self.flag_values.__setattr__(flag_name, flag_value)
raise AssertionError('Bounds exception not raised!')
except flags.IllegalFlagValue, e:
expected = ('flag --%(name)s=%(value)s: %(value)s is not %(suffix)s' %
{'name': flag_name, 'value': flag_value,
'suffix': expected_message_suffix})
self.assertEquals(str(e), expected)
def main():
unittest.main()
if __name__ == '__main__':
main()
|