/usr/lib/python3/dist-packages/pyutilib/misc/tests/test_config.py is in python3-pyutilib 5.3.5-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | # _________________________________________________________________________
#
# PyUtilib: A Python utility library.
# Copyright (c) 2008 Sandia Corporation.
# This software is distributed under the BSD License.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
# _________________________________________________________________________
import sys
import os
import os.path
currdir = os.path.dirname(os.path.abspath(__file__))
import pyutilib.th as unittest
import pyutilib.misc.comparison
from pyutilib.misc.config import ConfigValue, ConfigBlock, ConfigList
from six import PY3
try:
import yaml
using_yaml=True
except ImportError:
using_yaml=False
class Test(unittest.TestCase):
def setUp(self):
self.config = config = ConfigBlock(
"Basic configuration for Flushing models", implicit=True )
net = config.declare('network', ConfigBlock())
net.declare( 'epanet file', ConfigValue(
'Net3.inp', str,
'EPANET network inp file',
None ) ).declare_as_argument(dest='epanet')
sc = config.declare('scenario', ConfigBlock(
"Single scenario block", implicit=True, implicit_domain=str ) )
sc.declare( 'scenario file', ConfigValue(
'Net3.tsg', str,
'Scenario generation file, see the TEVASIM documentation',
"""This is the (long) documentation for the 'scenario file'
parameter. It contains multiple lines, and some internal
formatting; like a bulleted list:
- item 1
- item 2
""" ) ).declare_as_argument(group='Scenario definition')
sc.declare( 'merlion', ConfigValue(
False, bool,
'Water quality model',
"""This is the (long) documentation for the 'merlion'
parameter. It contains multiple lines, but no apparent internal
formatting; so the outputter should re-wrap everything.
""" ) ).declare_as_argument(group='Scenario definition')
sc.declare( 'detection', ConfigValue(
# Note use of lambda for an "integer list domain"
[1,2,3], lambda x: list(int(i) for i in x),
'Sensor placement list, epanetID',
None ) )
config.declare('scenarios', ConfigList(
[], sc,
"List of scenario blocks",
None ) )
config.declare('nodes', ConfigList(
[], ConfigValue(0, int, 'Node ID', None),
"List of node IDs",
None ) )
im = config.declare('impact', ConfigBlock())
im.declare( 'metric', ConfigValue(
'MC', str,
'Population or network based impact metric',
None ) )
fl = config.declare( 'flushing', ConfigBlock() )
n = fl.declare( 'flush nodes', ConfigBlock() )
n.declare( 'feasible nodes', ConfigValue(
'ALL', str,
'ALL, NZD, NONE, list or filename',
None ) )
n.declare( 'infeasible nodes', ConfigValue(
'NONE', str,
'ALL, NZD, NONE, list or filename',
None ) )
n.declare( 'max nodes', ConfigValue(
2, int,
'Maximum number of nodes to flush',
None ) )
n.declare( 'rate', ConfigValue(
600, float,
'Flushing rate [gallons/min]',
None ) )
n.declare( 'response time', ConfigValue(
60, float,
'Time [min] between detection and flushing',
None ) )
n.declare( 'duration', ConfigValue(
600, float,
'Time [min] for flushing',
None ) )
v = fl.declare( 'close valves', ConfigBlock() )
v.declare( 'feasible pipes', ConfigValue(
'ALL', str,
'ALL, DIAM min max [inch], NONE, list or filename',
None ) )
v.declare( 'infeasible pipes', ConfigValue(
'NONE', str,
'ALL, DIAM min max [inch], NONE, list or filename',
None ) )
v.declare( 'max pipes', ConfigValue(
2, int,
'Maximum number of pipes to close',
None ) )
v.declare( 'response time', ConfigValue(
60, float,
'Time [min] between detection and closing valves',
None ) )
self._reference = {
'network': {
'epanet file': 'Net3.inp'},
'scenario': {
'detection': [1, 2, 3],
'scenario file': 'Net3.tsg',
'merlion': False},
'scenarios': [],
'nodes': [],
'impact': {
'metric': 'MC'},
'flushing': {
'close valves': {
'infeasible pipes': 'NONE',
'max pipes': 2,
'feasible pipes': 'ALL',
'response time': 60.0},
'flush nodes': {
'feasible nodes': 'ALL',
'max nodes': 2,
'infeasible nodes': 'NONE',
'rate': 600.0,
'duration': 600.0,
'response time': 60.0},
},
}
# Utility method for generating and validating a template description
def _validateTemplate(self, reference_template, **kwds):
test = self.config.generate_yaml_template(**kwds)
width = kwds.get('width', 80)
indent = kwds.get('indent_spacing', 2)
sys.stdout.write(test)
for l in test.splitlines():
self.assertLessEqual(len(l), width)
if l.strip().startswith("#"):
continue
self.assertEqual((len(l)-len(l.lstrip())) % indent, 0)
self.assertEqual(test, reference_template)
def test_template_default(self):
reference_template = """# Basic configuration for Flushing models
network:
epanet file: Net3.inp # EPANET network inp file
scenario: # Single scenario block
scenario file: Net3.tsg # Scenario generation file, see the TEVASIM
# documentation
merlion: false # Water quality model
detection: [1, 2, 3] # Sensor placement list, epanetID
scenarios: [] # List of scenario blocks
nodes: [] # List of node IDs
impact:
metric: MC # Population or network based impact metric
flushing:
flush nodes:
feasible nodes: ALL # ALL, NZD, NONE, list or filename
infeasible nodes: NONE # ALL, NZD, NONE, list or filename
max nodes: 2 # Maximum number of nodes to flush
rate: 600.0 # Flushing rate [gallons/min]
response time: 60.0 # Time [min] between detection and flushing
duration: 600.0 # Time [min] for flushing
close valves:
feasible pipes: ALL # ALL, DIAM min max [inch], NONE, list or filename
infeasible pipes: NONE # ALL, DIAM min max [inch], NONE, list or filename
max pipes: 2 # Maximum number of pipes to close
response time: 60.0 # Time [min] between detection and closing valves
"""
self._validateTemplate(reference_template)
def test_template_3space(self):
reference_template = """# Basic configuration for Flushing models
network:
epanet file: Net3.inp # EPANET network inp file
scenario: # Single scenario block
scenario file: Net3.tsg # Scenario generation file, see the TEVASIM
# documentation
merlion: false # Water quality model
detection: [1, 2, 3] # Sensor placement list, epanetID
scenarios: [] # List of scenario blocks
nodes: [] # List of node IDs
impact:
metric: MC # Population or network based impact metric
flushing:
flush nodes:
feasible nodes: ALL # ALL, NZD, NONE, list or filename
infeasible nodes: NONE # ALL, NZD, NONE, list or filename
max nodes: 2 # Maximum number of nodes to flush
rate: 600.0 # Flushing rate [gallons/min]
response time: 60.0 # Time [min] between detection and flushing
duration: 600.0 # Time [min] for flushing
close valves:
feasible pipes: ALL # ALL, DIAM min max [inch], NONE, list or
# filename
infeasible pipes: NONE # ALL, DIAM min max [inch], NONE, list or
# filename
max pipes: 2 # Maximum number of pipes to close
response time: 60.0 # Time [min] between detection and closing
# valves
"""
self._validateTemplate(reference_template, indent_spacing=3)
def test_template_4space(self):
reference_template = """# Basic configuration for Flushing models
network:
epanet file: Net3.inp # EPANET network inp file
scenario: # Single scenario block
scenario file: Net3.tsg # Scenario generation file, see the TEVASIM
# documentation
merlion: false # Water quality model
detection: [1, 2, 3] # Sensor placement list, epanetID
scenarios: [] # List of scenario blocks
nodes: [] # List of node IDs
impact:
metric: MC # Population or network based impact metric
flushing:
flush nodes:
feasible nodes: ALL # ALL, NZD, NONE, list or filename
infeasible nodes: NONE # ALL, NZD, NONE, list or filename
max nodes: 2 # Maximum number of nodes to flush
rate: 600.0 # Flushing rate [gallons/min]
response time: 60.0 # Time [min] between detection and flushing
duration: 600.0 # Time [min] for flushing
close valves:
feasible pipes: ALL # ALL, DIAM min max [inch], NONE, list or
# filename
infeasible pipes: NONE # ALL, DIAM min max [inch], NONE, list or
# filename
max pipes: 2 # Maximum number of pipes to close
response time: 60.0 # Time [min] between detection and closing
# valves
"""
self._validateTemplate(reference_template, indent_spacing=4)
def test_template_3space_narrow(self):
reference_template = """# Basic configuration for Flushing models
network:
epanet file: Net3.inp # EPANET network inp file
scenario: # Single scenario block
scenario file: Net3.tsg # Scenario generation file, see the TEVASIM
# documentation
merlion: false # Water quality model
detection: [1, 2, 3] # Sensor placement list, epanetID
scenarios: [] # List of scenario blocks
nodes: [] # List of node IDs
impact:
metric: MC # Population or network based impact metric
flushing:
flush nodes:
feasible nodes: ALL # ALL, NZD, NONE, list or filename
infeasible nodes: NONE # ALL, NZD, NONE, list or filename
max nodes: 2 # Maximum number of nodes to flush
rate: 600.0 # Flushing rate [gallons/min]
response time: 60.0 # Time [min] between detection and
# flushing
duration: 600.0 # Time [min] for flushing
close valves:
feasible pipes: ALL # ALL, DIAM min max [inch], NONE, list or
# filename
infeasible pipes: NONE # ALL, DIAM min max [inch], NONE, list or
# filename
max pipes: 2 # Maximum number of pipes to close
response time: 60.0 # Time [min] between detection and closing
# valves
"""
self._validateTemplate(reference_template, indent_spacing=3, width=72)
def test_display_default(self):
reference = """network:
epanet file: Net3.inp
scenario:
scenario file: Net3.tsg
merlion: false
detection: [1, 2, 3]
scenarios: []
nodes: []
impact:
metric: MC
flushing:
flush nodes:
feasible nodes: ALL
infeasible nodes: NONE
max nodes: 2
rate: 600.0
response time: 60.0
duration: 600.0
close valves:
feasible pipes: ALL
infeasible pipes: NONE
max pipes: 2
response time: 60.0
"""
test = self.config.display()
sys.stdout.write(test)
self.assertEqual(test, reference)
def test_display_list(self):
reference = """network:
epanet file: Net3.inp
scenario:
scenario file: Net3.tsg
merlion: false
detection: [1, 2, 3]
scenarios:
-
scenario file: Net3.tsg
merlion: false
detection: [1, 2, 3]
-
scenario file: Net3.tsg
merlion: true
detection: []
nodes: []
impact:
metric: MC
flushing:
flush nodes:
feasible nodes: ALL
infeasible nodes: NONE
max nodes: 2
rate: 600.0
response time: 60.0
duration: 600.0
close valves:
feasible pipes: ALL
infeasible pipes: NONE
max pipes: 2
response time: 60.0
"""
self.config['scenarios'].add()
self.config['scenarios'].add({'merlion':True, 'detection':[]})
test = self.config.display()
sys.stdout.write(test)
self.assertEqual(test, reference)
def test_display_userdata_default(self):
test = self.config.display('userdata')
sys.stdout.write(test)
self.assertEqual(test, "")
def test_display_userdata_list(self):
self.config['scenarios'].add()
test = self.config.display('userdata')
sys.stdout.write(test)
self.assertEqual(test, """scenarios:
-
""")
def test_display_userdata_list_nonDefault(self):
self.config['scenarios'].add()
self.config['scenarios'].add({'merlion':True, 'detection':[]})
test = self.config.display('userdata')
sys.stdout.write(test)
self.assertEqual(test, """scenarios:
-
-
merlion: true
detection: []
""")
def test_display_userdata_block(self):
self.config.add("foo", ConfigValue(0, int,None,None))
self.config.add("bar", ConfigBlock())
test = self.config.display('userdata')
sys.stdout.write(test)
self.assertEqual(test, "")
def test_display_userdata_block_nonDefault(self):
self.config.add("foo", ConfigValue(0, int,None,None))
self.config.add("bar", ConfigBlock(implicit=True)) \
.add("baz", ConfigBlock())
test = self.config.display('userdata')
sys.stdout.write(test)
self.assertEqual(test, "bar:\n")
def test_unusedUserValues_default(self):
test = '\n'.join(x.name(True) for x in self.config.unused_user_values())
sys.stdout.write(test)
self.assertEqual(test, "")
def test_unusedUserValues_scalar(self):
self.config['scenario']['merlion'] = True
test = '\n'.join(x.name(True) for x in self.config.unused_user_values())
sys.stdout.write(test)
self.assertEqual(test, "scenario.merlion")
def test_unusedUserValues_list(self):
self.config['scenarios'].add()
test = '\n'.join(x.name(True) for x in self.config.unused_user_values())
sys.stdout.write(test)
self.assertEqual(test, """scenarios
scenarios[0]""")
def test_unusedUserValues_list_nonDefault(self):
self.config['scenarios'].add()
self.config['scenarios'].add({'merlion':True, 'detection':[]})
test = '\n'.join(x.name(True) for x in self.config.unused_user_values())
sys.stdout.write(test)
self.assertEqual(test, """scenarios
scenarios[0]
scenarios[1]
scenarios[1].merlion
scenarios[1].detection""")
def test_unusedUserValues_list_nonDefault_listAccessed(self):
self.config['scenarios'].add()
self.config['scenarios'].add({'merlion':True, 'detection':[]})
for x in self.config['scenarios']:
pass
test = '\n'.join(x.name(True) for x in self.config.unused_user_values())
sys.stdout.write(test)
self.assertEqual(test, """scenarios[0]
scenarios[1]
scenarios[1].merlion
scenarios[1].detection""")
def test_unusedUserValues_list_nonDefault_itemAccessed(self):
self.config['scenarios'].add()
self.config['scenarios'].add({'merlion':True, 'detection':[]})
self.config['scenarios'][1]['merlion']
test = '\n'.join(x.name(True) for x in self.config.unused_user_values())
sys.stdout.write(test)
self.assertEqual(test, """scenarios[0]
scenarios[1].detection""")
def test_unusedUserValues_topBlock(self):
self.config.add('foo', ConfigBlock())
test = '\n'.join(x.name(True) for x in self.config.unused_user_values())
sys.stdout.write(test)
self.assertEqual(test, "")
def test_unusedUserValues_subBlock(self):
self.config['scenario'].add('foo', ConfigBlock())
test = '\n'.join(x.name(True) for x in self.config.unused_user_values())
sys.stdout.write(test)
self.assertEqual(test, "scenario")
def test_UserValues_default(self):
test = '\n'.join(x.name(True) for x in self.config.user_values())
sys.stdout.write(test)
self.assertEqual(test, "")
def test_UserValues_scalar(self):
self.config['scenario']['merlion'] = True
test = '\n'.join(x.name(True) for x in self.config.user_values())
sys.stdout.write(test)
self.assertEqual(test, "scenario.merlion")
def test_UserValues_list(self):
self.config['scenarios'].add()
test = '\n'.join(x.name(True) for x in self.config.user_values())
sys.stdout.write(test)
self.assertEqual(test, """scenarios
scenarios[0]""")
def test_UserValues_list_nonDefault(self):
self.config['scenarios'].add()
self.config['scenarios'].add({'merlion':True, 'detection':[]})
test = '\n'.join(x.name(True) for x in self.config.user_values())
sys.stdout.write(test)
self.assertEqual(test, """scenarios
scenarios[0]
scenarios[1]
scenarios[1].merlion
scenarios[1].detection""")
def test_UserValues_list_nonDefault_listAccessed(self):
self.config['scenarios'].add()
self.config['scenarios'].add({'merlion':True, 'detection':[]})
for x in self.config['scenarios']:
pass
test = '\n'.join(x.name(True) for x in self.config.user_values())
sys.stdout.write(test)
self.assertEqual(test, """scenarios
scenarios[0]
scenarios[1]
scenarios[1].merlion
scenarios[1].detection""")
def test_UserValues_list_nonDefault_itemAccessed(self):
self.config['scenarios'].add()
self.config['scenarios'].add({'merlion':True, 'detection':[]})
self.config['scenarios'][1]['merlion']
test = '\n'.join(x.name(True) for x in self.config.user_values())
sys.stdout.write(test)
self.assertEqual(test, """scenarios
scenarios[0]
scenarios[1]
scenarios[1].merlion
scenarios[1].detection""")
def test_UserValues_topBlock(self):
self.config.add('foo', ConfigBlock())
test = '\n'.join(x.name(True) for x in self.config.user_values())
sys.stdout.write(test)
self.assertEqual(test, "")
def test_UserValues_subBlock(self):
self.config['scenario'].add('foo', ConfigBlock())
test = '\n'.join(x.name(True) for x in self.config.user_values())
sys.stdout.write(test)
self.assertEqual(test, "scenario")
def test_parseDisplayAndValue_default(self):
if not using_yaml:
self.skipTest("Cannot execute test because PyYAML is not available")
test = self.config.display()
sys.stdout.write(test)
self.assertEqual(yaml.load(test), self.config.value())
def test_parseDisplayAndValue_list(self):
if not using_yaml:
self.skipTest("Cannot execute test because PyYAML is not available")
self.config['scenarios'].add()
self.config['scenarios'].add({'merlion':True, 'detection':[]})
test = self.config.display()
sys.stdout.write(test)
self.assertEqual(yaml.load(test), self.config.value())
def test_parseDisplay_userdata_default(self):
if not using_yaml:
self.skipTest("Cannot execute test because PyYAML is not available")
test = self.config.display('userdata')
sys.stdout.write(test)
self.assertEqual(yaml.load(test), None)
def test_parseDisplay_userdata_list(self):
if not using_yaml:
self.skipTest("Cannot execute test because PyYAML is not available")
self.config['scenarios'].add()
test = self.config.display('userdata')
sys.stdout.write(test)
self.assertEqual(yaml.load(test), {'scenarios': [None]})
def test_parseDisplay_userdata_list_nonDefault(self):
if not using_yaml:
self.skipTest("Cannot execute test because PyYAML is not available")
self.config['scenarios'].add()
self.config['scenarios'].add({'merlion':True, 'detection':[]})
test = self.config.display('userdata')
sys.stdout.write(test)
self.assertEqual( yaml.load(test),
{ 'scenarios':
[ None,
{'merlion':True,'detection':[]}
] } )
def test_parseDisplay_userdata_block(self):
if not using_yaml:
self.skipTest("Cannot execute test because PyYAML is not available")
self.config.add("foo", ConfigValue(0, int,None,None))
self.config.add("bar", ConfigBlock())
test = self.config.display('userdata')
sys.stdout.write(test)
self.assertEqual(yaml.load(test), None)
def test_parseDisplay_userdata_block_nonDefault(self):
if not using_yaml:
self.skipTest("Cannot execute test because PyYAML is not available")
self.config.add("foo", ConfigValue(0, int,None,None))
self.config.add("bar", ConfigBlock(implicit=True)) \
.add("baz", ConfigBlock())
test = self.config.display('userdata')
sys.stdout.write(test)
self.assertEqual(yaml.load(test), {'bar': None})
def test_value_ConfigValue(self):
val = self.config['flushing']['flush nodes']['rate']
self.assertIs(type(val), float)
self.assertEqual(val, 600.0)
def test_value_ConfigList_empty(self):
val = self.config['nodes'].value()
self.assertIs(type(val), list)
self.assertEqual(val, [])
def test_value_ConfigList_simplePopulated(self):
self.config['nodes'].add('1')
self.config['nodes'].add(3)
self.config['nodes'].add()
val = self.config['nodes'].value()
self.assertIs(type(val), list)
self.assertEqual(len(val), 3)
self.assertEqual(val, [1, 3, 0])
def test_value_ConfigList_complexPopulated(self):
self.config['scenarios'].add()
val = self.config['scenarios'].value()
self.assertIs(type(val), list)
self.assertEqual(len(val), 1)
self.assertEqual(val, [{'detection': [1, 2, 3],
'merlion': False,
'scenario file': 'Net3.tsg'}])
def test_name(self):
self.config['scenarios'].add()
self.assertEqual(self.config.name(), "")
self.assertEqual(self.config['scenarios'].name(), "scenarios")
self.assertEqual(self.config['scenarios'][0].name(), "[0]")
self.assertEqual(self.config['scenarios'][0].get('merlion').name(),
"merlion")
def test_name_fullyQualified(self):
self.config['scenarios'].add()
self.assertEqual(self.config.name(True), "")
self.assertEqual(self.config['scenarios'].name(True), "scenarios")
self.assertEqual(self.config['scenarios'][0].name(True),
"scenarios[0]")
self.assertEqual(self.config['scenarios'][0].get('merlion').name(True),
"scenarios[0].merlion")
def test_setValue_scalar(self):
self.config['flushing']['flush nodes']['rate'] = 50
val = self.config['flushing']['flush nodes']['rate']
self.assertIs(type(val), float)
self.assertEqual( val, 50.0 )
def test_setValue_scalar_badDomain(self):
try:
self.config['flushing']['flush nodes']['rate'] = 'a'
except ValueError:
pass
else:
self.fail('expected test to raise ValueError')
val = self.config['flushing']['flush nodes']['rate']
self.assertIs(type(val), float)
self.assertEqual( val, 600.0 )
def test_setValue_scalarList_empty(self):
self.config['scenario']['detection'] = []
val = self.config['scenario']['detection']
self.assertIs(type(val), list)
self.assertEqual( val, [] )
def test_setValue_scalarList_withvalue(self):
self.config['scenario']['detection'] = [6]
val = self.config['scenario']['detection']
self.assertIs(type(val), list)
self.assertEqual( val, [6] )
def test_setValue_scalarList_badDomain(self):
try:
self.config['scenario']['detection'] = 50
except ValueError:
pass
else:
self.fail('expected test to raise ValueError')
val = self.config['scenario']['detection']
self.assertIs(type(val), list)
self.assertEqual( val, [1,2,3] )
def test_setValue_scalarList_badSubDomain(self):
try:
self.config['scenario']['detection'] = [5.5, 'a']
except ValueError:
pass
else:
self.fail('expected test to raise ValueError')
val = self.config['scenario']['detection']
self.assertIs(type(val), list)
self.assertEqual( val, [1,2,3] )
def test_setValue_list_scalardomain_list(self):
self.config['nodes'] = [5, 10]
val = self.config['nodes'].value()
self.assertIs(type(val), list)
self.assertEqual( val, [5, 10] )
def test_setValue_list_scalardomain_scalar(self):
self.config['nodes'] = 10
val = self.config['nodes'].value()
self.assertIs(type(val), list)
self.assertEqual( val, [10] )
def test_setValue_list_badSubDomain(self):
try:
self.config['nodes'] = [5, 'a']
except ValueError:
pass
else:
self.fail('expected test to raise ValueError')
val = self.config['nodes'].value()
self.assertIs(type(val), list)
self.assertEqual( val, [] )
def test_setValue_block_none(self):
ref = self._reference['scenario']
self.config['scenario'] = None
self.assertEqual( ref, self.config['scenario'].value() )
self.config['scenario']['merlion'] = True
ref['merlion'] = True
self.assertEqual( ref, self.config['scenario'].value() )
self.config['scenario'] = None
self.assertEqual( ref, self.config['scenario'].value() )
def test_setValue_block_empty(self):
ref = self._reference['scenario']
self.config['scenario'] = {}
self.assertEqual( ref, self.config['scenario'].value() )
self.config['scenario']['merlion'] = True
ref['merlion'] = True
self.assertEqual( ref, self.config['scenario'].value() )
self.config['scenario'] = {}
self.assertEqual( ref, self.config['scenario'].value() )
def test_setValue_block_simplevalue(self):
_test = {'merlion': True, 'detection': [1]}
ref = self._reference['scenario']
ref.update( _test )
self.config['scenario'] = _test
self.assertEqual( ref, self.config['scenario'].value() )
def test_setItem_block_implicit(self):
ref = self._reference
ref['foo'] = 1
self.config['foo'] = 1
self.assertEqual( ref, self.config.value() )
ref['bar'] = 1
self.config['bar'] = 1
self.assertEqual( ref, self.config.value() )
def test_setItem_block_implicit_domain(self):
ref = self._reference['scenario']
ref['foo'] = '1'
self.config['scenario']['foo'] = 1
self.assertEqual( ref, self.config['scenario'].value() )
ref['bar'] = '1'
self.config['scenario']['bar'] = 1
self.assertEqual( ref, self.config['scenario'].value() )
def test_setValue_block_noImplicit(self):
_test = {'epanet file': 'no_file.inp', 'foo': 1}
try:
self.config['network'] = _test
except ValueError:
pass
except:
raise
else:
self.fail("Expected test to raise ValueError")
self.assertEqual( self._reference, self.config.value() )
def test_setValue_block_implicit(self):
_test = {'scenario':{'merlion': True, 'detection': [1]}, 'foo': 1}
ref = self._reference
ref['scenario'].update( _test['scenario'] )
ref['foo'] = 1
self.config.set_value( _test )
self.assertEqual( ref, self.config.value() )
_test = {'scenario':{'merlion': True, 'detection': [1]}, 'bar': 1}
ref['bar'] = 1
self.config.set_value( _test )
self.assertEqual( ref, self.config.value() )
def test_setValue_block_implicit_domain(self):
_test = {'merlion': True, 'detection': [1], 'foo': 1}
ref = self._reference['scenario']
ref.update( _test )
ref['foo'] = '1'
self.config['scenario'] = _test
self.assertEqual( ref, self.config['scenario'].value() )
_test = {'merlion': True, 'detection': [1], 'bar': '1'}
ref['bar'] = '1'
self.config['scenario'] = _test
self.assertEqual( ref, self.config['scenario'].value() )
def test_setValue_block_badDomain(self):
_test = {'merlion': True, 'detection': ['a'], 'foo': 1, 'a': 1}
try:
self.config['scenario'] = _test
except ValueError:
pass
else:
self.fail('expected test to raise ValueError')
self.assertEqual( self._reference, self.config.value() )
try:
self.config['scenario'] = []
except ValueError:
pass
else:
self.fail('expected test to raise ValueError')
self.assertEqual( self._reference, self.config.value() )
def test_default_function(self):
c = ConfigValue(default=lambda: 10, domain=int)
self.assertEqual(c.value(), 10)
c.set_value(5)
self.assertEqual(c.value(), 5)
c.reset()
self.assertEqual(c.value(), 10)
try:
c = ConfigValue(default=lambda x: 10*x, domain=int)
except TypeError:
pass
else:
self.fail("Expected type error")
try:
c = ConfigValue('a', domain=int)
except ValueError:
pass
else:
self.fail("Expected casting a to int to raise a value error")
def test_getItem_setItem(self):
# a freshly-initialized object should not be accessed
self.assertFalse(self.config._userAccessed)
self.assertFalse(self.config._data['scenario']._userAccessed)
self.assertFalse(self.config._data['scenario']._data['detection']\
._userAccessed)
# Getting a ConfigValue should not access it
self.assertFalse(self.config['scenario'].get('detection')._userAccessed)
#... but should access the parent blocks traversed to get there
self.assertTrue(self.config._userAccessed)
self.assertTrue(self.config._data['scenario']._userAccessed)
self.assertFalse(self.config._data['scenario']._data['detection']\
._userAccessed)
# a freshly-initialized object should not be set
self.assertFalse(self.config._userSet)
self.assertFalse(self.config._data['scenario']._userSet)
self.assertFalse(self.config['scenario']._data['detection']._userSet)
# setting a value should map it to the correct domain
self.assertEqual(self.config['scenario']['detection'], [1,2,3])
self.config['scenario']['detection'] = [ 42.5 ]
self.assertEqual(self.config['scenario']['detection'], [42])
# setting a ConfigValue should mark it as userSet, but NOT any parent blocks
self.assertFalse(self.config._userSet)
self.assertFalse(self.config._data['scenario']._userSet)
self.assertTrue(self.config['scenario'].get('detection')._userSet)
def test_generate_documentation(self):
oFile = os.path.join(currdir,'test_reference.out')
OUTPUT = open(oFile,'w')
test = self.config.generate_documentation()
OUTPUT.write(test)
OUTPUT.close()
print(test)
self.assertFalse(pyutilib.misc.comparison.compare_file(oFile, oFile[:-4]+'.txt')[0])
os.remove(oFile)
def test_block_get(self):
self.assertTrue('scenario' in self.config)
self.assertNotEquals(self.config.get('scenario', 'bogus'), 'bogus')
self.assertFalse('fubar' in self.config)
self.assertEquals(self.config.get('fubar', 'bogus'), 'bogus')
def test_block_keys(self):
ref = ['scenario file','merlion','detection']
# list of keys
keys = self.config['scenario'].keys()
# lists are independent
self.assertFalse( keys is self.config['scenario'].keys() )
if PY3:
self.assertIsNot( type(keys), list )
self.assertEqual( list(keys), ref )
else:
self.assertIs( type(keys), list )
self.assertEqual( keys, ref )
# keys iterator
keyiter = self.config['scenario'].iterkeys()
self.assertIsNot( type(keyiter), list )
self.assertEqual( list(keyiter), ref )
# iterators are independent
self.assertFalse( keyiter is self.config['scenario'].iterkeys() )
# default iterator
keyiter = self.config['scenario'].__iter__()
self.assertIsNot( type(keyiter), list )
self.assertEqual( list(keyiter), ref )
# iterators are independent
self.assertFalse( keyiter is self.config['scenario'].__iter__() )
def test_block_values(self):
ref = ['Net3.tsg', False, [1,2,3]]
# list of values
values = self.config['scenario'].values()
if PY3:
self.assertIsNot( type(values), list )
else:
self.assertIs( type(values), list )
self.assertEqual( list(values), ref )
# lists are independent
self.assertFalse( values is self.config['scenario'].values() )
# values iterator
valueiter = self.config['scenario'].itervalues()
self.assertIsNot( type(valueiter), list )
self.assertEqual( list(valueiter), ref )
# iterators are independent
self.assertFalse( valueiter is self.config['scenario'].itervalues() )
def test_block_items(self):
ref = [ ('scenario file', 'Net3.tsg'),
('merlion',False),
('detection',[1,2,3]) ]
# list of items
items = self.config['scenario'].items()
if PY3:
self.assertIsNot( type(items), list )
else:
self.assertIs( type(items), list )
self.assertEqual( list(items), ref )
# lists are independent
self.assertFalse( items is self.config['scenario'].items() )
# items iterator
itemiter = self.config['scenario'].iteritems()
self.assertIsNot( type(itemiter), list )
self.assertEqual( list(itemiter), ref )
# iterators are independent
self.assertFalse( itemiter is self.config['scenario'].iteritems() )
def test_value(self):
print(self.config.value())
self.assertEqual(self._reference, self.config.value())
def test_list_manipulation(self):
self.assertEqual(len(self.config['scenarios']), 0)
self.config['scenarios'].add()
self.assertEqual(len(self.config['scenarios']), 1)
self.config['scenarios'].add({'merlion':True, 'detection':[]})
self.assertEqual(len(self.config['scenarios']), 2)
test = self.config.display('userdata')
sys.stdout.write(test)
self.assertEqual(test, """scenarios:
-
-
merlion: true
detection: []
""")
self.config['scenarios'][0] = {'merlion':True, 'detection':[]}
self.assertEqual(len(self.config['scenarios']), 2)
test = self.config.display('userdata')
sys.stdout.write(test)
self.assertEqual(test, """scenarios:
-
merlion: true
detection: []
-
merlion: true
detection: []
""")
test = self.config['scenarios'].display()
sys.stdout.write(test)
self.assertEqual(test, """-
scenario file: Net3.tsg
merlion: true
detection: []
-
scenario file: Net3.tsg
merlion: true
detection: []
""")
def test_implicit_entries(self):
config = ConfigBlock()
try:
config['test'] = 5
self.fail("Expected ConfigBlock to throw a ValueError for implicit declarations")
except ValueError:
self.assertEqual(
sys.exc_info()[1].args,
("Key 'test' not defined in Config Block '' and Block disallows implicit entries",) )
config = ConfigBlock(implicit=True)
config['implicit_1'] = 5
config.declare( 'formal', ConfigValue( 42, int ) )
config['implicit_2'] = 5
print(config.display())
self.assertEqual( 3, len(config) )
self.assertEqual( ['implicit_1','formal','implicit_2'],
list(config.iterkeys()) )
config.reset()
self.assertEqual( 1, len(config) )
self.assertEqual( ['formal'],
list(config.iterkeys()) )
def test_argparse_help(self):
try:
import argparse
except ImportError:
self.skipTest("argparse not available")
parser = argparse.ArgumentParser(prog='tester')
self.config.initialize_argparse(parser)
help = parser.format_help()
print(help)
self.assertEqual(
"""usage: tester [-h] [--epanet-file EPANET] [--scenario-file STR] [--merlion]
optional arguments:
-h, --help show this help message and exit
--epanet-file EPANET EPANET network inp file
Scenario definition:
--scenario-file STR Scenario generation file, see the TEVASIM
documentation
--merlion Water quality model
""", help)
def test_argparse_help_implicit_disable(self):
self.config['scenario'].declare('epanet', ConfigValue(
True, bool,
'Use EPANET as the Water quality model',
None) ).declare_as_argument(group='Scenario definition')
try:
import argparse
except ImportError:
self.skipTest("argparse not available")
parser = argparse.ArgumentParser(prog='tester')
self.config.initialize_argparse(parser)
help = parser.format_help()
print(help)
self.assertEqual(
"""usage: tester [-h] [--epanet-file EPANET] [--scenario-file STR] [--merlion]
[--disable-epanet]
optional arguments:
-h, --help show this help message and exit
--epanet-file EPANET EPANET network inp file
Scenario definition:
--scenario-file STR Scenario generation file, see the TEVASIM
documentation
--merlion Water quality model
--disable-epanet [DON'T] Use EPANET as the Water quality model
""", help)
def test_argparse_import(self):
try:
import argparse
except ImportError:
self.skipTest("argparse not available")
parser = argparse.ArgumentParser(prog='tester')
self.config.initialize_argparse(parser)
args = parser.parse_args([])
self.assertEqual(0, len(vars(args)))
leftovers = self.config.import_argparse(args)
self.assertEqual(0, len(vars(args)))
self.assertEqual(
[], [x.name(True) for x in self.config.user_values()] )
args = parser.parse_args(['--merlion'])
self.config.reset()
self.assertFalse(self.config['scenario']['merlion'])
self.assertEqual(1, len(vars(args)))
leftovers = self.config.import_argparse(args)
self.assertEqual(0, len(vars(args)))
self.assertEqual(
['scenario.merlion'],
[x.name(True) for x in self.config.user_values()] )
args = parser.parse_args(['--merlion','--epanet-file','foo'])
self.config.reset()
self.assertFalse(self.config['scenario']['merlion'])
self.assertEqual( 'Net3.inp',
self.config['network']['epanet file'])
self.assertEqual(2, len(vars(args)))
leftovers = self.config.import_argparse(args)
self.assertEqual(1, len(vars(args)))
self.assertEqual(
['network.epanet file','scenario.merlion'],
[x.name(True) for x in self.config.user_values()] )
self.assertTrue(self.config['scenario']['merlion'])
self.assertEqual('foo', self.config['network']['epanet file'])
def test_argparse_subparsers(self):
try:
import argparse
except ImportError:
self.skipTest("argparse not available")
parser = argparse.ArgumentParser(prog='tester')
subp = parser.add_subparsers(title="Subcommands").add_parser('flushing')
# Declare an argument by passing in the name of the subparser
self.config['flushing']['flush nodes'].get('duration').declare_as_argument(
group='flushing')
# Declare an argument by passing in the name of the subparser
# and an implicit group
self.config['flushing']['flush nodes'].get('feasible nodes') \
.declare_as_argument( group=('flushing','Node information') )
# Declare an argument by passing in the subparser and a group name
self.config['flushing']['flush nodes'].get('infeasible nodes') \
.declare_as_argument( group=(subp,'Node information') )
self.config.initialize_argparse(parser)
help = parser.format_help()
print(help)
self.assertEqual(
"""usage: tester [-h] [--epanet-file EPANET] [--scenario-file STR] [--merlion]
{flushing} ...
optional arguments:
-h, --help show this help message and exit
--epanet-file EPANET EPANET network inp file
Subcommands:
{flushing}
Scenario definition:
--scenario-file STR Scenario generation file, see the TEVASIM
documentation
--merlion Water quality model
""", help)
help = subp.format_help()
print(help)
self.assertEqual(
"""usage: tester flushing [-h] [--feasible-nodes STR] [--infeasible-nodes STR]
[--duration FLOAT]
optional arguments:
-h, --help show this help message and exit
--duration FLOAT Time [min] for flushing
Node information:
--feasible-nodes STR ALL, NZD, NONE, list or filename
--infeasible-nodes STR
ALL, NZD, NONE, list or filename
""", help)
def test_getattr_setattr(self):
config = ConfigBlock()
foo = config.declare('foo', ConfigBlock(implicit=True, implicit_domain=int))
foo.declare('explicit_bar', ConfigValue(0, int))
self.assertEqual(1, len(foo))
self.assertEqual(0, foo['explicit_bar'])
self.assertEqual(0, foo.explicit_bar)
foo.explicit_bar = 10
self.assertEqual(1, len(foo))
self.assertEqual(10, foo['explicit_bar'])
self.assertEqual(10, foo.explicit_bar)
foo.implicit_bar = 20
self.assertEqual(2, len(foo))
self.assertEqual(20, foo['implicit bar'])
self.assertEqual(20, foo.implicit_bar)
try:
config.baz = 10
except ValueError:
pass
except:
raise
else:
self.fail("Expected implicit assignment to explicit block to raise ValueError")
try:
a = config.baz
except AttributeError:
pass
except:
raise
else:
self.fail("Expected implicit assignment to explicit block to raise ValueError")
if __name__ == "__main__":
unittest.main()
|