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
|
#!/usr/bin/env python
from cogent.util.unit_test import TestCase, main
from cogent.app.util import Application, CommandLineApplication, \
CommandLineAppResult, ResultPath, ApplicationError, ParameterIterBase,\
ParameterCombinations, cmdline_generator, ApplicationNotFoundError,\
get_tmp_filename, guess_input_handler
from cogent.app.parameters import *
from os import remove,system,mkdir,rmdir,removedirs,getcwd, walk
__author__ = "Greg Caporaso and Sandra Smit"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Greg Caporaso", "Sandra Smit", "Gavin Huttley",
"Rob Knight", "Daniel McDonald"]
__license__ = "GPL"
__version__ = "1.5.3"
__maintainer__ = "Sandra Smit"
__email__ = "sandra.smit@colorado.edu"
__status__ = "Development"
class ParameterCombinationsTests(TestCase):
def setUp(self):
"""Setup for ParameterCombinations tests"""
self.mock_app = ParameterCombinationsApp
self.params = {'-flag1':True,
'--value1':range(0,5),
'-delim':range(0,2),
'-mix1':[None] + range(0,3)}
self.always_on = ['--value1']
self.param_iter = ParameterCombinations(self.mock_app, self.params,
self.always_on)
def test_init_generator(self):
"""Tests generator capabilities"""
all_params = list(self.param_iter)
self.assertEqual(len(all_params), 150)
params = {'-flag1':True,
'--value1':1,
'-delim':['choice1','choice2']}
always_on = ['-flag1','-delim']
param_iter = ParameterCombinations(self.mock_app, params, always_on)
exp = [self.mock_app._parameters.copy(),
self.mock_app._parameters.copy(),
self.mock_app._parameters.copy(),
self.mock_app._parameters.copy()]
# default is on in all these cases
exp[0]['-flag1'].on()
exp[0]['--value1'].on(1)
exp[0]['-delim'].on('choice1')
exp[1]['-flag1'].on()
exp[1]['--value1'].on(1)
exp[1]['-delim'].on('choice2')
exp[2]['-flag1'].on()
exp[2]['--value1'].off()
exp[2]['-delim'].on('choice1')
exp[3]['-flag1'].on()
exp[3]['--value1'].off()
exp[3]['-delim'].on('choice2')
obs = list(param_iter)
self.assertEqual(obs,exp)
def test_reset(self):
"""Resets the iterator"""
first = list(self.param_iter)
self.assertRaises(StopIteration, self.param_iter.next)
self.param_iter.reset()
second = list(self.param_iter)
self.assertEqual(first, second)
class ParameterIterBaseTests(TestCase):
def setUp(self):
"""Setup for ParameterIterBase tests"""
self.mock_app = ParameterCombinationsApp
self.params = {'-flag1':True,
'--value1':range(0,5),
'-delim':range(0,2),
'-mix1':[None] + range(0,3)}
self.always_on = ['--value1']
self.param_base = ParameterIterBase(self.mock_app, self.params,
self.always_on)
def test_init(self):
"""Test constructor"""
exp_params = {'-flag1':[True, False],
'--value1':range(0,5),
'-delim':range(0,2) + [False],
'-mix1':[None,0,1,2] + [False]}
exp_keys = exp_params.keys()
exp_values = exp_params.values()
self.assertEqual(sorted(self.param_base._keys), sorted(exp_keys))
self.assertEqual(sorted(self.param_base._values), sorted(exp_values))
self.params['asdasda'] = 5
self.assertRaises(ValueError, ParameterIterBase, self.mock_app, \
self.params, self.always_on)
self.params.pop('asdasda')
self.always_on.append('asdasd')
self.assertRaises(ValueError, ParameterIterBase, self.mock_app, \
self.params, self.always_on)
def test_make_app_params(self):
"""Returns app parameters with expected values set"""
values = [0,0,True,None]
exp = self.mock_app._parameters.copy()
exp['-flag1'].on()
exp['--value1'].on(0)
exp['-delim'].on(0)
exp['-mix1'].on(None)
obs = self.param_base._make_app_params(values)
self.assertEqual(obs, exp)
state = [4,False,False,False]
exp = self.mock_app._parameters.copy()
exp['-flag1'].off()
exp['--value1'].on(4)
exp['-delim'].off()
exp['-mix1'].off()
obs = self.param_base._make_app_params(values)
self.assertEqual(obs, exp)
class CommandLineGeneratorTests(TestCase):
def setUp(self):
self.abs_path_to_bin = '/bin/path'
self.abs_path_to_cmd = '/cmd/path'
self.abs_path_to_input = '/input/path'
self.abs_path_to_output = '/output/path'
self.abs_path_to_stdout = '/stdout/path'
self.abs_path_to_stderr = '/stderr/path'
self.app = ParameterCombinationsApp
params = {'-flag1':True,
'-delim':['choice1','choice2']}
always_on = ['-delim']
self.mock_app = ParameterCombinationsApp
self.param_iter = ParameterCombinations(self.mock_app,params, always_on)
def test_cmdline_generator_easy(self):
"""Returns parameter combinations commandlines"""
cmdgen = cmdline_generator(self.param_iter,
PathToBin=self.abs_path_to_bin,
PathToCmd=self.abs_path_to_cmd,
PathsToInputs=self.abs_path_to_input,
PathToOutput=self.abs_path_to_output,
PathToStdout=self.abs_path_to_stdout,
PathToStderr=self.abs_path_to_stderr,
UniqueOutputs=False,
InputParam='-input',
OutputParam='-output')
bin = self.abs_path_to_bin
cmd = self.abs_path_to_cmd
inputfile = self.abs_path_to_input
outputfile = self.abs_path_to_output
stdout = self.abs_path_to_stdout
stderr = self.abs_path_to_stderr
exp = [' '.join([bin, cmd, '-default=42', '-delimaaachoice1','-flag1',\
'-input="%s"' % inputfile,'-output="%s"' % outputfile,\
'> "%s"' % stdout, '2> "%s"' % stderr])]
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice1', \
'-input="%s"' % inputfile,'-output="%s"' % outputfile,\
'> "%s"' % stdout, '2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42','-delimaaachoice2', \
'-flag1', '-input="%s"' % inputfile, \
'-output="%s"' % outputfile, '> "%s"' % stdout,\
'2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice2', \
'-input="%s"' % inputfile,'-output="%s"' % outputfile,\
'> "%s"' % stdout, '2> "%s"' % stderr]))
cmdlines = list(cmdgen)
self.assertEqual(cmdlines, exp)
def test_cmdline_generator_hard(self):
"""Returns parameter combinations commandlines. Test stdin/stdout"""
cmdgen = cmdline_generator(self.param_iter,
PathToBin=self.abs_path_to_bin,
PathToCmd=self.abs_path_to_cmd,
PathsToInputs=self.abs_path_to_input,
PathToOutput=self.abs_path_to_output,
PathToStdout=self.abs_path_to_stdout,
PathToStderr=self.abs_path_to_stderr,
UniqueOutputs=True,
InputParam=None,
OutputParam=None)
bin = self.abs_path_to_bin
cmd = self.abs_path_to_cmd
inputfile = self.abs_path_to_input
outputfile = self.abs_path_to_output
stdout = self.abs_path_to_stdout
stderr = self.abs_path_to_stderr
# the extra '' is intentionally added. When stdout is used for actual
# output, the stdout_ param gets set to '' which results in an extra
# space being generated on the cmdline. this should be benign
# across operating systems
exp = [' '.join([bin, cmd, '-default=42', '-delimaaachoice1','-flag1',\
'< "%s"' % inputfile, '> "%s"0' % outputfile, '',\
'2> "%s"' % stderr])]
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice1', \
'< "%s"' % inputfile,'> "%s"1' % outputfile, '',\
'2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42','-delimaaachoice2', \
'-flag1', '< "%s"' % inputfile, \
'> "%s"2' % outputfile, '', '2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice2', \
'< "%s"' % inputfile,'> "%s"3' % outputfile, '',\
'2> "%s"' % stderr]))
cmdlines = list(cmdgen)
self.assertEqual(cmdlines, exp)
def test_cmdline_generator_stdout_stderr_off(self):
"""Returns cmdlines with stdout and stderr disabled"""
cmdgen = cmdline_generator(self.param_iter,
PathToBin=self.abs_path_to_bin,
PathToCmd=self.abs_path_to_cmd,
PathsToInputs=self.abs_path_to_input,
PathToOutput=self.abs_path_to_output,
PathToStdout=None,
PathToStderr=None,
UniqueOutputs=False,
InputParam='-input',
OutputParam='-output')
bin = self.abs_path_to_bin
cmd = self.abs_path_to_cmd
inputfile = self.abs_path_to_input
outputfile = self.abs_path_to_output
stdout = self.abs_path_to_stdout
stderr = self.abs_path_to_stderr
exp = [' '.join([bin, cmd, '-default=42', '-delimaaachoice1','-flag1',\
'-input="%s"' % inputfile,'-output="%s"' % outputfile,\
'',''])]
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice1', \
'-input="%s"' % inputfile,'-output="%s"' % outputfile,\
'','']))
exp.append(' '.join([bin, cmd, '-default=42','-delimaaachoice2', \
'-flag1', '-input="%s"' % inputfile, \
'-output="%s"' % outputfile,'','']))
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice2', \
'-input="%s"' % inputfile,'-output="%s"' % outputfile,\
'','']))
cmdlines = list(cmdgen)
self.assertEqual(cmdlines, exp)
def test_cmdline_generator_multiple_inputs(self):
"""Tests the cmdline_generator for multiple input support"""
paths_to_inputs = ['/some/dir/a','/some/dir/b']
cmdgen = cmdline_generator(self.param_iter,
PathToBin=self.abs_path_to_bin,
PathToCmd=self.abs_path_to_cmd,
PathsToInputs=paths_to_inputs,
PathToOutput=self.abs_path_to_output,
PathToStdout=self.abs_path_to_stdout,
PathToStderr=self.abs_path_to_stderr,
UniqueOutputs=False,
InputParam='-input',
OutputParam='-output')
bin = self.abs_path_to_bin
cmd = self.abs_path_to_cmd
inputfile1 = paths_to_inputs[0]
inputfile2 = paths_to_inputs[1]
outputfile = self.abs_path_to_output
stdout = self.abs_path_to_stdout
stderr = self.abs_path_to_stderr
exp = [' '.join([bin, cmd, '-default=42', '-delimaaachoice1','-flag1',\
'-input="%s"' % inputfile1,'-output="%s"' % outputfile,\
'> "%s"' % stdout, '2> "%s"' % stderr])]
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice1',\
'-flag1', '-input="%s"' % inputfile2,\
'-output="%s"' % outputfile, '> "%s"' % stdout, \
'2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice1', \
'-input="%s"' % inputfile1,'-output="%s"' % outputfile,\
'> "%s"' % stdout, '2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice1', \
'-input="%s"' % inputfile2,'-output="%s"' % outputfile,\
'> "%s"' % stdout, '2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42','-delimaaachoice2', \
'-flag1', '-input="%s"' % inputfile1, \
'-output="%s"' % outputfile, '> "%s"' % stdout,\
'2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42','-delimaaachoice2', \
'-flag1', '-input="%s"' % inputfile2, \
'-output="%s"' % outputfile, '> "%s"' % stdout,\
'2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice2', \
'-input="%s"' % inputfile1,'-output="%s"' % outputfile,\
'> "%s"' % stdout, '2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice2', \
'-input="%s"' % inputfile2,'-output="%s"' % outputfile,\
'> "%s"' % stdout, '2> "%s"' % stderr]))
cmdlines = list(cmdgen)
self.assertEqual(cmdlines, exp)
def test_cmdline_generator_multiple_input_stdin(self):
"""Tests cmdline_generator for multiple inputs over stdin"""
paths_to_inputs = ['/some/dir/a','/some/dir/b']
cmdgen = cmdline_generator(self.param_iter,
PathToBin=self.abs_path_to_bin,
PathToCmd=self.abs_path_to_cmd,
PathsToInputs=paths_to_inputs,
PathToOutput=self.abs_path_to_output,
PathToStdout=self.abs_path_to_stdout,
PathToStderr=self.abs_path_to_stderr,
UniqueOutputs=False,
InputParam=None,
OutputParam='-output')
bin = self.abs_path_to_bin
cmd = self.abs_path_to_cmd
inputfile1 = paths_to_inputs[0]
inputfile2 = paths_to_inputs[1]
outputfile = self.abs_path_to_output
stdout = self.abs_path_to_stdout
stderr = self.abs_path_to_stderr
exp = [' '.join([bin, cmd, '-default=42', '-delimaaachoice1','-flag1',\
'< "%s"' % inputfile1,'-output="%s"' % outputfile,\
'> "%s"' % stdout, '2> "%s"' % stderr])]
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice1',\
'-flag1', '< "%s"' % inputfile2,\
'-output="%s"' % outputfile, '> "%s"' % stdout, \
'2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice1', \
'< "%s"' % inputfile1,'-output="%s"' % outputfile,\
'> "%s"' % stdout, '2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice1', \
'< "%s"' % inputfile2,'-output="%s"' % outputfile,\
'> "%s"' % stdout, '2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42','-delimaaachoice2', \
'-flag1', '< "%s"' % inputfile1, \
'-output="%s"' % outputfile, '> "%s"' % stdout,\
'2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42','-delimaaachoice2', \
'-flag1', '< "%s"' % inputfile2, \
'-output="%s"' % outputfile, '> "%s"' % stdout,\
'2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice2', \
'< "%s"' % inputfile1,'-output="%s"' % outputfile,\
'> "%s"' % stdout, '2> "%s"' % stderr]))
exp.append(' '.join([bin, cmd, '-default=42', '-delimaaachoice2', \
'< "%s"' % inputfile2,'-output="%s"' % outputfile,\
'> "%s"' % stdout, '2> "%s"' % stderr]))
cmdlines = list(cmdgen)
self.assertEqual(cmdlines, exp)
class CommandLineApplicationTests(TestCase):
"""Tests for the CommandLineApplication class"""
def setUp(self):
"""setUp for all CommandLineApplication tests"""
f = open('/tmp/CLAppTester.py','w')
f.write(script)
f.close()
system('chmod 777 /tmp/CLAppTester.py')
# create a copy of the script with a space in the name
f = open('/tmp/CLApp Tester.py','w')
f.write(script)
f.close()
system('chmod 777 "/tmp/CLApp Tester.py"')
self.app_no_params = CLAppTester()
self.app_no_params_no_stderr = CLAppTester(SuppressStderr=True)
self.app_params =CLAppTester({'-F':'p_file.txt'})
self.app_params_space_in_command =\
CLAppTester_space_in_command({'-F':'p_file.txt'})
self.app_params_no_stderr =CLAppTester({'-F':'p_file.txt'},\
SuppressStderr=True)
self.app_params_no_stdout =CLAppTester({'-F':'p_file.txt'},\
SuppressStdout=True)
self.app_params_input_as_file =CLAppTester({'-F':'p_file.txt'},\
InputHandler='_input_as_lines')
self.app_params_WorkingDir =CLAppTester({'-F':'p_file.txt'},\
WorkingDir='/tmp/test')
self.app_params_WorkingDir_w_space =CLAppTester({'-F':'p_file.txt'},\
WorkingDir='/tmp/test space')
self.app_params_TmpDir =CLAppTester({'-F':'p_file.txt'},\
TmpDir='/tmp/tmp2')
self.app_params_TmpDir_w_space =CLAppTester({'-F':'p_file.txt'},\
TmpDir='/tmp/tmp space')
self.data = 42
def test_base_command(self):
"""CLAppTester: BaseCommand correctly composed """
# No parameters on
app = CLAppTester()
self.assertEqual(app.BaseCommand,'cd "/tmp/"; /tmp/CLAppTester.py')
# ValuedParameter on/off
app.Parameters['-F'].on('junk.txt')
self.assertEqual(app.BaseCommand,\
'cd "/tmp/"; /tmp/CLAppTester.py -F "junk.txt"')
app.Parameters['-F'].off()
self.assertEqual(app.BaseCommand,'cd "/tmp/"; /tmp/CLAppTester.py')
# ValuedParameter accessed by synonym turned on/off
app.Parameters['File'].on('junk.txt')
self.assertEqual(app.BaseCommand,\
'cd "/tmp/"; /tmp/CLAppTester.py -F "junk.txt"')
app.Parameters['File'].off()
self.assertEqual(app.BaseCommand,'cd "/tmp/"; /tmp/CLAppTester.py')
# Try multiple parameters, must check for a few different options
# because parameters are printed in arbitrary order
app.Parameters['-F'].on('junk.txt')
app.Parameters['--duh'].on()
self.failUnless(app.BaseCommand ==\
'cd "/tmp/"; /tmp/CLAppTester.py -F "junk.txt" --duh'\
or app.BaseCommand ==\
'cd "/tmp/"; /tmp/CLAppTester.py --duh -F "junk.txt"')
# Space in _command
app = CLAppTester_space_in_command()
self.assertEqual(app.BaseCommand,'cd "/tmp/"; "/tmp/CLApp Tester.py"')
def test_getHelp(self):
"""CLAppTester: getHelp() functions as expected """
app = CLAppTester()
self.assertEqual(app.getHelp(),'Duh')
def test_handle_app_result_build_failure(self):
"""_handle_app_result_build_failure called when CommandLineAppResult() fails
"""
app = CLAppTester_bad_fixed_file()
self.assertRaises(ApplicationError,app)
app = CLAppTester_bad_fixed_file_w_handler()
self.assertEqual(app(),"Called self._handle_app_result_build_failure")
def test_error_on_missing_executable(self):
"""CLAppTester: Useful error message on executable not found
"""
# fake command via self._command
class Blah(CLAppTester):
_command = 'fake_command_jasdlkfsadlkfskladfkladf'
self.assertRaises(ApplicationNotFoundError,Blah)
# real command but bad path via self._command
class Blah(CLAppTester):
_command = '/not/a/real/path/ls'
self.assertRaises(ApplicationNotFoundError,Blah)
# alt _error_on_missing_command function works as expected
class Blah(CLAppTester):
_command = 'ls'
def _error_on_missing_application(self,data):
raise ApplicationNotFoundError
self.assertRaises(ApplicationNotFoundError,Blah)
class Blah(CLAppTester):
_command = 'fake_app_asfasdasdasdasdasd'
def _error_on_missing_application(self,data):
pass
# no error raised
Blah()
def test_no_p_no_d(self):
"""CLAppTester: parameters turned off, no data"""
app = self.app_no_params
#test_init
assert app.Parameters['-F'].isOff()
self.assertEqual(app.InputHandler,'_input_as_string')
assert not app.SuppressStderr
#test_command
self.assertEqual(app.BaseCommand,'cd "/tmp/"; /tmp/CLAppTester.py')
#test_result
result = app()
self.assertEqual(result['StdOut'].read(),'out\n')
self.assertEqual(result['StdErr'].read(),'I am stderr\n')
self.assertEqual(result['ExitStatus'],0)
self.assertEqual(result['fixed_file'].read(),'I am fixed file')
self.assertEqual(result['base_dep_1'].read(),'base dependent 1')
self.assertEqual(result['base_dep_2'].read(),'base dependent 2')
self.assertEqual(result['parameterized_file'],None)
result.cleanUp()
def test_no_p_data_as_str(self):
"""CLAppTester: parameters turned off, data as string"""
app = self.app_no_params
#test_init
assert app.Parameters['-F'].isOff()
self.assertEqual(app.InputHandler,'_input_as_string')
assert not app.SuppressStderr
#test_command
self.assertEqual(app.BaseCommand,'cd "/tmp/"; /tmp/CLAppTester.py')
#test_result
result = app(self.data)
self.assertEqual(result['StdOut'].read(),'out 43\n')
self.assertEqual(result['StdErr'].read(),'I am stderr\n')
self.assertEqual(result['ExitStatus'],0)
self.assertEqual(result['fixed_file'].read(),'I am fixed file')
self.assertEqual(result['base_dep_1'].read(),'base dependent 1')
self.assertEqual(result['base_dep_2'].read(),'base dependent 2')
self.assertEqual(result['parameterized_file'],None)
result.cleanUp()
def test_p_data_as_str_suppress_stderr(self):
"""CLAppTester: parameters turned on, data as string, suppress stderr"""
app = self.app_params_no_stderr
#test_init
assert app.Parameters['-F'].isOn()
self.assertEqual(app.InputHandler,'_input_as_string')
assert app.SuppressStderr
#test_command
self.assertEqual(app.BaseCommand,\
'cd "/tmp/"; /tmp/CLAppTester.py -F "p_file.txt"')
#test_result
result = app(self.data)
self.assertEqual(result['StdOut'].read(),'')
self.assertEqual(result['StdErr'],None)
self.assertEqual(result['ExitStatus'],0)
self.assertEqual(result['fixed_file'].read(),'I am fixed file')
self.assertEqual(result['base_dep_1'].read(),'base dependent 1')
self.assertEqual(result['base_dep_2'].read(),'base dependent 2')
self.assertEqual(result['parameterized_file'].read(),\
'out 43 p_file.txt')
result.cleanUp()
def test_p_data_as_str_suppress_stdout(self):
"""CLAppTester: parameters turned on, data as string, suppress stdout"""
app = self.app_params_no_stdout
#test_init
assert app.Parameters['-F'].isOn()
self.assertEqual(app.InputHandler,'_input_as_string')
assert app.SuppressStdout
#test_command
self.assertEqual(app.BaseCommand,\
'cd "/tmp/"; /tmp/CLAppTester.py -F "p_file.txt"')
#test_result
result = app(self.data)
self.assertEqual(result['StdOut'],None)
self.assertEqual(result['StdErr'].read(),'I am stderr\n')
self.assertEqual(result['ExitStatus'],0)
self.assertEqual(result['fixed_file'].read(),'I am fixed file')
self.assertEqual(result['base_dep_1'].read(),'base dependent 1')
self.assertEqual(result['base_dep_2'].read(),'base dependent 2')
self.assertEqual(result['parameterized_file'].read(),\
'out 43 p_file.txt')
result.cleanUp()
def test_p_no_data(self):
"""CLAppTester: parameters turned on, no data"""
app = self.app_params
#test_init
assert app.Parameters['-F'].isOn()
self.assertEqual(app.InputHandler,'_input_as_string')
assert not app.SuppressStderr
#test_command
self.assertEqual(app.BaseCommand,\
'cd "/tmp/"; /tmp/CLAppTester.py -F "p_file.txt"')
#test_result
result = app()
self.assertEqual(result['StdOut'].read(),'')
self.assertEqual(result['StdErr'].read(),'I am stderr\n')
self.assertEqual(result['ExitStatus'],0)
self.assertEqual(result['fixed_file'].read(),'I am fixed file')
self.assertEqual(result['base_dep_1'].read(),'base dependent 1')
self.assertEqual(result['base_dep_2'].read(),'base dependent 2')
self.assertEqual(result['parameterized_file'].read(),\
'out p_file.txt')
result.cleanUp()
def test_p_space_in_command(self):
"""CLAppTester: parameters turned on, no data, space in command"""
app = self.app_params_space_in_command
#test_init
assert app.Parameters['-F'].isOn()
self.assertEqual(app.InputHandler,'_input_as_string')
assert not app.SuppressStderr
#test_command
self.assertEqual(app.BaseCommand,\
'cd "/tmp/"; "/tmp/CLApp Tester.py" -F "p_file.txt"')
#test_result
result = app()
self.assertEqual(result['StdOut'].read(),'')
self.assertEqual(result['StdErr'].read(),'I am stderr\n')
self.assertEqual(result['ExitStatus'],0)
self.assertEqual(result['fixed_file'].read(),'I am fixed file')
self.assertEqual(result['base_dep_1'].read(),'base dependent 1')
self.assertEqual(result['base_dep_2'].read(),'base dependent 2')
self.assertEqual(result['parameterized_file'].read(),\
'out p_file.txt')
result.cleanUp()
def test_p_data_as_str(self):
"""CLAppTester: parameters turned on, data as str"""
app = self.app_params
#test_init
assert app.Parameters['-F'].isOn()
self.assertEqual(app.InputHandler,'_input_as_string')
assert not app.SuppressStderr
#test_command
self.assertEqual(app.BaseCommand,\
'cd "/tmp/"; /tmp/CLAppTester.py -F "p_file.txt"')
#test_result
result = app(self.data)
self.assertEqual(result['StdOut'].read(),'')
self.assertEqual(result['StdErr'].read(),'I am stderr\n')
self.assertEqual(result['ExitStatus'],0)
self.assertEqual(result['fixed_file'].read(),'I am fixed file')
self.assertEqual(result['base_dep_1'].read(),'base dependent 1')
self.assertEqual(result['base_dep_2'].read(),'base dependent 2')
self.assertEqual(result['parameterized_file'].read(),\
'out 43 p_file.txt')
result.cleanUp()
def test_p_data_as_file(self):
"""CLAppTester: parameters turned on, data as file"""
app = self.app_params_input_as_file
#test_init
assert app.Parameters['-F'].isOn()
self.assertEqual(app.InputHandler,'_input_as_lines')
assert not app.SuppressStderr
#test_command
# we don't test the command in this case, because we don't know what
# the name of the input file is.
#test_result
result = app([self.data])
self.assertEqual(result['StdOut'].read(),'')
self.assertEqual(result['StdErr'].read(),'I am stderr\n')
self.assertEqual(result['ExitStatus'],0)
self.assertEqual(result['fixed_file'].read(),'I am fixed file')
self.assertEqual(result['base_dep_1'].read(),'base dependent 1')
self.assertEqual(result['base_dep_2'].read(),'base dependent 2')
self.assertEqual(result['parameterized_file'].read(),\
'out 43 p_file.txt')
result.cleanUp()
def test_WorkingDir(self):
"""CLAppTester: WorkingDir functions as expected """
system('cp /tmp/CLAppTester.py /tmp/test/CLAppTester.py')
app = self.app_params_WorkingDir
#test_init
assert app.Parameters['-F'].isOn()
self.assertEqual(app.InputHandler,'_input_as_string')
assert not app.SuppressStderr
# WorkingDir is what we expect
self.assertEqual(app.WorkingDir,'/tmp/test/')
#test_command
self.assertEqual(app.BaseCommand,\
'cd "/tmp/test/"; /tmp/CLAppTester.py -F "p_file.txt"')
#test_result
result = app()
self.assertEqual(result['StdOut'].read(),'')
self.assertEqual(result['StdErr'].read(),'I am stderr\n')
self.assertEqual(result['ExitStatus'],0)
self.assertEqual(result['fixed_file'].read(),'I am fixed file')
self.assertEqual(result['base_dep_1'].read(),'base dependent 1')
self.assertEqual(result['base_dep_2'].read(),'base dependent 2')
# Make sure that the parameterized file is in the correct place
self.assertEqual(result['parameterized_file'].name,\
'/tmp/test/p_file.txt')
self.assertEqual(result['parameterized_file'].read(),\
'out p_file.txt')
result.cleanUp()
def test_WorkingDir_w_space(self):
"""CLAppTester: WorkingDir w/ space in path functions as expected """
system('cp /tmp/CLAppTester.py "/tmp/test space/CLAppTester.py"')
app = self.app_params_WorkingDir_w_space
#test_init
assert app.Parameters['-F'].isOn()
self.assertEqual(app.InputHandler,'_input_as_string')
assert not app.SuppressStderr
# WorkingDir is what we expect
self.assertEqual(app.WorkingDir,'/tmp/test space/')
#test_command
self.assertEqual(app.BaseCommand,\
'cd "/tmp/test space/"; /tmp/CLAppTester.py -F "p_file.txt"')
#test_result
result = app()
self.assertEqual(result['StdOut'].read(),'')
self.assertEqual(result['StdErr'].read(),'I am stderr\n')
self.assertEqual(result['ExitStatus'],0)
self.assertEqual(result['fixed_file'].read(),'I am fixed file')
self.assertEqual(result['base_dep_1'].read(),'base dependent 1')
self.assertEqual(result['base_dep_2'].read(),'base dependent 2')
# Make sure that the parameterized file is in the correct place
self.assertEqual(result['parameterized_file'].name,\
'/tmp/test space/p_file.txt')
self.assertEqual(result['parameterized_file'].read(),\
'out p_file.txt')
result.cleanUp()
def test_TmpDir(self):
"""CLAppTester: Alternative TmpDir functions as expected"""
app = self.app_params_TmpDir
#test_init
assert app.Parameters['-F'].isOn()
self.assertEqual(app.InputHandler,'_input_as_string')
assert not app.SuppressStderr
# TmpDir is what we expect
self.assertEqual(app.TmpDir,'/tmp/tmp2')
#test_command
self.assertEqual(app.BaseCommand,\
'cd "/tmp/"; /tmp/CLAppTester.py -F "p_file.txt"')
#test_result
result = app()
self.assertEqual(result['StdOut'].read(),'')
self.assertEqual(result['StdErr'].read(),'I am stderr\n')
self.assertEqual(result['ExitStatus'],0)
self.assertEqual(result['fixed_file'].read(),'I am fixed file')
self.assertEqual(result['base_dep_1'].read(),'base dependent 1')
self.assertEqual(result['base_dep_2'].read(),'base dependent 2')
# Make sure that the parameterized file is in the correct place
self.assertEqual(result['parameterized_file'].name,\
'/tmp/p_file.txt')
self.assertEqual(result['parameterized_file'].read(),\
'out p_file.txt')
result.cleanUp()
def test_TmpDir_w_space(self):
"""CLAppTester: TmpDir functions as expected w space in name"""
app = self.app_params_TmpDir_w_space
#test_init
assert app.Parameters['-F'].isOn()
self.assertEqual(app.InputHandler,'_input_as_string')
assert not app.SuppressStderr
# TmpDir is what we expect
self.assertEqual(app.TmpDir,'/tmp/tmp space')
#test_command
self.assertEqual(app.BaseCommand,\
'cd "/tmp/"; /tmp/CLAppTester.py -F "p_file.txt"')
#test_result
result = app()
self.assertEqual(result['StdOut'].read(),'')
self.assertEqual(result['StdErr'].read(),'I am stderr\n')
self.assertEqual(result['ExitStatus'],0)
self.assertEqual(result['fixed_file'].read(),'I am fixed file')
self.assertEqual(result['base_dep_1'].read(),'base dependent 1')
self.assertEqual(result['base_dep_2'].read(),'base dependent 2')
# Make sure that the parameterized file is in the correct place
self.assertEqual(result['parameterized_file'].name,\
'/tmp/p_file.txt')
self.assertEqual(result['parameterized_file'].read(),\
'out p_file.txt')
result.cleanUp()
def test_input_as_string(self):
"""CLAppTester: _input_as_string functions as expected """
self.assertEqual(self.app_no_params._input_as_string('abcd'),'abcd')
self.assertEqual(self.app_no_params._input_as_string(42),'42')
self.assertEqual(self.app_no_params._input_as_string(None),'None')
self.assertEqual(self.app_no_params._input_as_string([1]),'[1]')
self.assertEqual(self.app_no_params._input_as_string({'a':1}),\
"{'a': 1}")
def test_input_as_lines_from_string(self):
"""CLAppTester: _input_as_lines functions as expected w/ data as str
"""
filename = self.app_no_params._input_as_lines('abcd')
self.assertEqual(filename[0],'/')
f = open(filename)
self.assertEqual(f.readline(),'a\n')
self.assertEqual(f.readline(),'b\n')
self.assertEqual(f.readline(),'c\n')
self.assertEqual(f.readline(),'d')
f.close()
remove(filename)
def test_input_as_lines_from_list(self):
"""CLAppTester: _input_as_lines functions as expected w/ data as list
"""
filename = self.app_no_params._input_as_lines(['line 1',None,3])
self.assertEqual(filename[0],'/')
f = open(filename)
self.assertEqual(f.readline(),'line 1\n')
self.assertEqual(f.readline(),'None\n')
self.assertEqual(f.readline(),'3')
f.close()
remove(filename)
def test_input_as_lines_from_list_w_newlines(self):
"""CLAppTester: _input_as_lines functions w/ data as list w/ newlines
"""
filename = self.app_no_params._input_as_lines(['line 1\n',None,3])
self.assertEqual(filename[0],'/')
f = open(filename)
self.assertEqual(f.readline(),'line 1\n')
self.assertEqual(f.readline(),'None\n')
self.assertEqual(f.readline(),'3')
f.close()
remove(filename)
def test_input_as_multiline_string(self):
"""CLAppTester: _input_as_multiline_string functions as expected
"""
filename = self.app_no_params._input_as_multiline_string(\
'line 1\nNone\n3')
self.assertEqual(filename[0],'/')
f = open(filename)
self.assertEqual(f.readline(),'line 1\n')
self.assertEqual(f.readline(),'None\n')
self.assertEqual(f.readline(),'3')
f.close()
remove(filename)
def test_input_as_lines_from_list_single_entry(self):
"""CLAppTester: _input_as_lines functions as expected w/ 1 element list
"""
filename = self.app_no_params._input_as_lines(['line 1'])
self.assertEqual(filename[0],'/')
f = open(filename)
self.assertEqual(f.readline(),'line 1')
f.close()
remove(filename)
def test_input_as_multiline_string_single_line(self):
"""CLAppTester: _input_as_multiline_string functions w/ single line
"""
# functions as expected with single line string
filename = self.app_no_params._input_as_multiline_string(\
'line 1')
self.assertEqual(filename[0],'/')
f = open(filename)
self.assertEqual(f.readline(),'line 1')
f.close()
remove(filename)
def test_getTmpFilename_non_default(self):
"""TmpFilename handles alt tmp_dir, prefix and suffix properly"""
app = CLAppTester()
obs = app.getTmpFilename(include_class_id=False)
self.assertTrue(obs.startswith('/tmp/tmp'))
self.assertTrue(obs.endswith('.txt'))
obs = app.getTmpFilename(tmp_dir="/tmp/blah",prefix="app_ctl_test",\
suffix='.test',include_class_id=False)
self.assertTrue(obs.startswith('/tmp/blah/app_ctl_test'))
self.assertTrue(obs.endswith('.test'))
def test_getTmpFilename_defaults_to_no_class_id(self):
"""CLAppTester: getTmpFilename doesn't include class id by default
"""
# I want to explicitly test for this so people don't forget to
# set the default to False if they change it for testing purposes
app = CLAppTester()
self.assertFalse(app.getTmpFilename().\
startswith('/tmp/tmpCLAppTester'))
self.assertTrue(app.getTmpFilename(include_class_id=True).\
startswith('/tmp/tmpCLAppTester'))
def test_input_as_path(self):
"""CLAppTester: _input_as_path casts data to FilePath"""
actual = self.app_no_params._input_as_path('test.pdb')
self.assertEqual(actual,'test.pdb')
self.assertEqual(str(actual),'"test.pdb"')
actual = self.app_no_params._input_as_path('te st.pdb')
self.assertEqual(actual,'te st.pdb')
self.assertEqual(str(actual),'"te st.pdb"')
actual = self.app_no_params._input_as_path('./test.pdb')
self.assertEqual(actual,'./test.pdb')
self.assertEqual(str(actual),'"./test.pdb"')
actual = self.app_no_params._input_as_path('/this/is/a/test.pdb')
self.assertEqual(actual,'/this/is/a/test.pdb')
self.assertEqual(str(actual),'"/this/is/a/test.pdb"')
actual = self.app_no_params._input_as_path('/this/i s/a/test.pdb')
self.assertEqual(actual,'/this/i s/a/test.pdb')
self.assertEqual(str(actual),'"/this/i s/a/test.pdb"')
def test_input_as_paths(self):
"""CLAppTester: _input_as_paths casts each input to FilePath """
input = ['test.pdb']
actual = self.app_no_params._input_as_paths(input)
expected = '"test.pdb"'
self.assertEqual(actual,expected)
input = ['test1.pdb','test2.pdb']
actual = self.app_no_params._input_as_paths(input)
expected = '"test1.pdb" "test2.pdb"'
self.assertEqual(actual,expected)
input = ['/path/to/test1.pdb','test2.pdb']
actual = self.app_no_params._input_as_paths(input)
expected = '"/path/to/test1.pdb" "test2.pdb"'
self.assertEqual(actual,expected)
input = ['test1.pdb','/path/to/test2.pdb']
actual = self.app_no_params._input_as_paths(input)
expected = '"test1.pdb" "/path/to/test2.pdb"'
self.assertEqual(actual,expected)
input = ['/path/to/test1.pdb','/path/to/test2.pdb']
actual = self.app_no_params._input_as_paths(input)
expected = '"/path/to/test1.pdb" "/path/to/test2.pdb"'
self.assertEqual(actual,expected)
input = ['/pa th/to/test1.pdb','/path/to/te st2.pdb']
actual = self.app_no_params._input_as_paths(input)
expected = '"/pa th/to/test1.pdb" "/path/to/te st2.pdb"'
self.assertEqual(actual,expected)
def test_absolute(self):
"""CLAppTester: _absolute converts relative paths to absolute paths
"""
absolute = self.app_no_params._absolute
self.assertEqual(absolute('/tmp/test.pdb'),'/tmp/test.pdb')
self.assertEqual(absolute('test.pdb'),'/tmp/test.pdb')
def test_working_dir_setting(self):
"""CLAppTester: WorkingDir is set correctly """
app = CLAppTester_no_working_dir()
self.assertEqual(app.WorkingDir,getcwd()+'/')
def test_error_raised_on_command_None(self):
"""CLAppTester: An error is raises when _command == None """
app = CLAppTester()
app._command = None
self.assertRaises(ApplicationError, app._get_base_command)
def test_rejected_exit_status(self):
"""CLAppTester_reject_exit_status results in useful error """
app = CLAppTester_reject_exit_status()
self.assertRaises(ApplicationError,app)
def test_getTmpFilename(self):
"""TmpFilename should return filename of correct length"""
app = CLAppTester()
obs = app.getTmpFilename(include_class_id=True)
# leaving the strings in this statement so it's clear where the expected
# length comes from
self.assertEqual(len(obs), len(app.TmpDir) + len('/') + app.TmpNameLen \
+ len('tmp') + len('CLAppTester') + len('.txt'))
assert obs.startswith(app.TmpDir)
chars = set(obs[18:])
assert len(chars) > 1
obs = app.getTmpFilename(include_class_id=False)
# leaving the strings in this statement so it's clear where the expected
# length comes from
self.assertEqual(len(obs), len(app.TmpDir) + len('/') + app.TmpNameLen \
+ len('tmp') + len('.txt'))
assert obs.startswith(app.TmpDir)
def test_getTmpFilename_prefix_suffix_result_constructor(self):
"""TmpFilename: result has correct prefix, suffix, type"""
app = CLAppTester()
obs = app.getTmpFilename(prefix='blah',include_class_id=False)
self.assertTrue(obs.startswith('/tmp/blah'))
obs = app.getTmpFilename(suffix='.blah',include_class_id=False)
self.assertTrue(obs.endswith('.blah'))
# Prefix defaults to not include the class name
obs = app.getTmpFilename(include_class_id=False)
self.assertFalse(obs.startswith('/tmp/tmpCLAppTester'))
self.assertTrue(obs.endswith('.txt'))
# including class id functions correctly
obs = app.getTmpFilename(include_class_id=True)
self.assertTrue(obs.startswith('/tmp/tmpCLAppTester'))
self.assertTrue(obs.endswith('.txt'))
# result as FilePath
obs = app.getTmpFilename(result_constructor=FilePath)
self.assertEqual(type(obs),FilePath)
# result as str (must check that result is a str and is not a FilePath
# since a FilePath is a str)
obs = app.getTmpFilename(result_constructor=str)
self.assertEqual(type(obs),str)
self.assertNotEqual(type(obs),FilePath)
class ConvenienceFunctionTests(TestCase):
"""
"""
def setUp(self):
"""
"""
self.tmp_dir = '/tmp'
self.tmp_name_len = 20
def test_guess_input_handler(self):
"""guess_input_handler should correctly identify input"""
gih = guess_input_handler
self.assertEqual(gih('abc.txt'), '_input_as_string')
self.assertEqual(gih('>ab\nTCAG'), '_input_as_multiline_string')
self.assertEqual(gih(['ACC','TGA'], True), '_input_as_seqs')
self.assertEqual(gih(['>a','ACC','>b','TGA']), '_input_as_lines')
self.assertEqual(gih([('a','ACC'),('b','TGA')]),\
'_input_as_seq_id_seq_pairs')
self.assertEqual(gih([]),'_input_as_lines')
def test_get_tmp_filename(self):
"""get_tmp_filename should return filename of correct length
Adapted from the CommandLineApplication tests of the member function
"""
obs = get_tmp_filename()
# leaving the strings in this statement so it's clear where the expected
# length comes from
self.assertEqual(len(obs), len(self.tmp_dir) + len('/') + self.tmp_name_len \
+ len('tmp') + len('.txt'))
self.assertTrue(obs.startswith('/tmp'))
# different results on different calls
self.assertNotEqual(get_tmp_filename(),get_tmp_filename())
obs = get_tmp_filename()
# leaving the strings in this statement so it's clear where the expected
# length comes from
self.assertEqual(len(obs), len(self.tmp_dir) + len('/') + self.tmp_name_len \
+ len('tmp') + len('.txt'))
assert obs.startswith(self.tmp_dir)
def test_get_tmp_filename_prefix_suffix_constructor(self):
"""get_tmp_filename: result has correct prefix, suffix, type
Adapted from the CommandLineApplication tests of the member function
"""
obs = get_tmp_filename(prefix='blah')
self.assertTrue(obs.startswith('/tmp/blah'))
obs = get_tmp_filename(suffix='.blah')
self.assertTrue(obs.endswith('.blah'))
# result as FilePath
obs = get_tmp_filename(result_constructor=FilePath)
self.assertEqual(type(obs),FilePath)
# result as str (must check that result is a str and is not a FilePath
# since a FilePath is a str)
obs = get_tmp_filename(result_constructor=str)
self.assertEqual(type(obs),str)
self.assertNotEqual(type(obs),FilePath)
class RemoveTests(TestCase):
def test_remove(self):
"""This will remove the test script. Not actually a test!"""
for dir, n, fnames in walk('/tmp/test/'):
for f in fnames:
try:
remove(dir + f)
except OSError, e:
pass
remove('/tmp/CLAppTester.py')
remove('/tmp/test space/CLAppTester.py')
remove('/tmp/CLApp Tester.py')
rmdir('/tmp/tmp space')
rmdir('/tmp/test')
rmdir('/tmp/test space')
rmdir('/tmp/tmp2')
rmdir('/tmp/blah')
#=====================END OF TESTS===================================
script = """#!/usr/bin/env python
#This is a test script intended to test the CommandLineApplication
#class and CommandLineAppResult class
from sys import argv, stderr,stdin
from os import isatty
out_file_name = None
input_arg = None
# parse input
try:
if argv[1] == '-F':
out_file_name = argv[2]
except IndexError:
pass
try:
if out_file_name:
input_arg = argv[3]
else:
input_arg = argv[1]
except IndexError:
pass
# Create the output string
out = 'out'
# get input
try:
f = open(str(input_arg))
data = int(f.readline().strip())
except IOError:
try:
data = int(input_arg)
except TypeError:
data = None
if data:
data = str(data + 1)
out = ' '.join([out,data])
# Write base dependent output files
base = 'BASE'
f = open('/tmp/' + base + '.1','w')
f.writelines(['base dependent 1'])
f.close()
f = open('/tmp/' + base + '.2','w')
f.writelines(['base dependent 2'])
f.close()
# If output to file, open the file and write output to it
if out_file_name:
filename = argv[2]
f = open(''.join([out_file_name]),'w')
out = ' '.join([out,out_file_name])
f.writelines(out)
f.close()
else:
print out
#generate some stderr
print >> stderr, 'I am stderr'
# Write the fixed file
f = open('/tmp/fixed.txt','w')
f.writelines(['I am fixed file'])
f.close()
"""
class CLAppTester(CommandLineApplication):
_parameters = {
'-F':ValuedParameter(Prefix='-',Name='F',Delimiter=' ',\
Value=None, Quote="\""),\
'--duh':FlagParameter(Prefix='--',Name='duh')}
_command = '/tmp/CLAppTester.py'
_synonyms = {'File':'-F','file':'-F'}
_working_dir = '/tmp'
def _get_result_paths(self,data):
if self.Parameters['-F'].isOn():
param_path = ''.join([self.WorkingDir,self.Parameters['-F'].Value])
else:
param_path = None
result = {}
result['fixed_file'] = ResultPath(Path='/tmp/fixed.txt')
result['parameterized_file'] = ResultPath(Path=param_path,\
IsWritten=self.Parameters['-F'].isOn())
result['base_dep_1'] = ResultPath(Path=self._build_name(suffix='.1'))
result['base_dep_2'] = ResultPath(Path=self._build_name(suffix='.2'))
return result
def _build_name(self,suffix):
return '/tmp/BASE' + suffix
def getHelp(self):
return """Duh"""
class CLAppTester_no_working_dir(CLAppTester):
_working_dir = None
class CLAppTester_reject_exit_status(CLAppTester):
def _accept_exit_status(self,exit_status):
return False
class CLAppTester_bad_fixed_file(CLAppTester):
def _get_result_paths(self,data):
if self.Parameters['-F'].isOn():
param_path = ''.join([self.WorkingDir,self.Parameters['-F'].Value])
else:
param_path = None
result = {}
result['fixed_file'] = ResultPath(Path='/tmp/fixed.txt')
result['fixed_file_bad'] = ResultPath(Path='/tmp/i_dont_exist.txt')
result['parameterized_file'] = ResultPath(Path=param_path,\
IsWritten=self.Parameters['-F'].isOn())
result['base_dep_1'] = ResultPath(Path=self._build_name(suffix='.1'))
result['base_dep_2'] = ResultPath(Path=self._build_name(suffix='.2'))
return result
class CLAppTester_bad_fixed_file_w_handler(CLAppTester_bad_fixed_file):
def _handle_app_result_build_failure(self,out,err,exit_status,result_paths):
return "Called self._handle_app_result_build_failure"
class CLAppTester_space_in_command(CLAppTester):
_command = '"/tmp/CLApp Tester.py"'
class ParameterCombinationsApp(CommandLineApplication):
"""ParameterCombinations mock application to wrap"""
_command = 'testcmd'
_parameters = {'-flag1':FlagParameter(Prefix='-',Name='flag1'),
'-flag2':FlagParameter(Prefix='-',Name='flag2'),
'--value1':ValuedParameter(Prefix='--',Name='value1'),
'-value2':ValuedParameter(Prefix='-',Name='value2'),
'-mix1':MixedParameter(Prefix='-',Name='mix1'),
'-mix2':MixedParameter(Prefix='-',Name='mix2'),
'-delim':ValuedParameter(Prefix='-',Name='delim',
Delimiter='aaa'),
'-default':ValuedParameter(Prefix='-',Name='default',
Value=42, Delimiter='='),
'-input':ValuedParameter(Prefix='-',Name='input',\
Delimiter='='),
'-output':ValuedParameter(Prefix='-',Name='output',
Delimiter='=')}
if __name__ == '__main__':
main()
|