forked from SCons/scons
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestCmdTests.py
More file actions
3347 lines (2823 loc) · 118 KB
/
TestCmdTests.py
File metadata and controls
3347 lines (2823 loc) · 118 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
Unit tests for the TestCmd.py module.
"""
# Copyright 2000-2010 Steven Knight
# This module is free software, and you may redistribute it and/or modify
# it under the same terms as Python itself, so long as this copyright message
# and disclaimer are retained in their original form.
#
# IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
# SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
# THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.
#
# THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
# AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
# SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
__author__ = "Steven Knight <knight at baldmt dot com>"
__revision__ = "TestCmdTests.py 1.3.D001 2010/06/03 12:58:27 knight"
import os
import shutil
import stat
import subprocess
import sys
import tempfile
import time
import unittest
from io import StringIO
from contextlib import closing
from collections import UserList
from subprocess import PIPE
from SCons.Util import to_bytes, to_str
# Strip the current directory so we get the right TestCmd.py module.
sys.path = sys.path[1:]
import TestCmd
def _is_readable(path):
# XXX this doesn't take into account UID, it assumes it's our file
return os.stat(path)[stat.ST_MODE] & stat.S_IREAD
def _is_writable(path):
# XXX this doesn't take into account UID, it assumes it's our file
return os.stat(path)[stat.ST_MODE] & stat.S_IWRITE
def _is_executable(path):
# XXX this doesn't take into account UID, it assumes it's our file
return os.stat(path)[stat.ST_MODE] & stat.S_IEXEC
def _clear_dict(dict, *keys):
for key in keys:
try:
del dict[key]
except KeyError:
pass
class ExitError(Exception):
pass
class TestCmdTestCase(unittest.TestCase):
"""Base class for TestCmd test cases, with fixture and utility methods."""
def setUp(self):
self.orig_cwd = os.getcwd()
def tearDown(self):
os.chdir(self.orig_cwd)
def setup_run_scripts(self):
class T:
pass
t = T()
t.script = 'script'
t.scriptx = 'scriptx.bat'
t.script1 = 'script_1.txt'
t.scriptout = 'scriptout'
t.scripterr = 'scripterr'
fmt = "import os, sys; cwd = os.getcwd(); " + \
"sys.stdout.write('%s: STDOUT: %%s: %%s\\n' %% (cwd, sys.argv[1:])); " + \
"sys.stderr.write('%s: STDERR: %%s: %%s\\n' %% (cwd, sys.argv[1:]))"
fmtout = "import os, sys; cwd = os.getcwd(); " + \
"sys.stdout.write('%s: STDOUT: %%s: %%s\\n' %% (cwd, sys.argv[1:]))"
fmterr = "import os, sys; cwd = os.getcwd(); " + \
"sys.stderr.write('%s: STDERR: %%s: %%s\\n' %% (cwd, sys.argv[1:]))"
text = fmt % (t.script, t.script)
textx = fmt % (t.scriptx, t.scriptx)
if sys.platform == 'win32':
textx = textx.replace('%', '%%')
textx = '@python -c "%s"' % textx + ' %1 %2 %3 %4 %5 %6 %7 %8 %9\n'
else:
textx = '#! /usr/bin/env python\n' + textx + '\n'
text1 = 'A first line to be ignored!\n' + fmt % (t.script1, t.script1)
textout = fmtout % t.scriptout
texterr = fmterr % t.scripterr
run_env = TestCmd.TestCmd(workdir = '')
run_env.subdir('sub dir')
t.run_env = run_env
t.sub_dir = run_env.workpath('sub dir')
t.script_path = run_env.workpath('sub dir', t.script)
t.scriptx_path = run_env.workpath('sub dir', t.scriptx)
t.script1_path = run_env.workpath('sub dir', t.script1)
t.scriptout_path = run_env.workpath('sub dir', t.scriptout)
t.scripterr_path = run_env.workpath('sub dir', t.scripterr)
run_env.write(t.script_path, text)
run_env.write(t.scriptx_path, textx)
run_env.write(t.script1_path, text1)
run_env.write(t.scriptout_path, textout)
run_env.write(t.scripterr_path, texterr)
os.chmod(t.script_path, 0o644) # XXX UNIX-specific
os.chmod(t.scriptx_path, 0o755) # XXX UNIX-specific
os.chmod(t.script1_path, 0o644) # XXX UNIX-specific
os.chmod(t.scriptout_path, 0o644) # XXX UNIX-specific
os.chmod(t.scripterr_path, 0o644) # XXX UNIX-specific
t.orig_cwd = os.getcwd()
t.workdir = run_env.workpath('sub dir')
os.chdir(t.workdir)
return t
def translate_newlines(self, data):
data = data.replace("\r\n", "\n")
return data
def call_python(self, indata, python=None):
if python is None:
python = sys.executable
cp = subprocess.run(python, input=to_bytes(indata), stderr=PIPE, stdout=PIPE)
stdout = self.translate_newlines(to_str(cp.stdout))
stderr = self.translate_newlines(to_str(cp.stderr))
return stdout, stderr, cp.returncode
def popen_python(self, indata, status=0, stdout="", stderr="", python=None):
if python is None:
python = sys.executable
_stdout, _stderr, _status = self.call_python(indata, python)
assert _status == status, (
"status = %s, expected %s\n" % (str(_status), str(status))
+ "STDOUT ===================\n"
+ _stdout
+ "STDERR ===================\n"
+ _stderr
)
assert _stdout == stdout, (
"Expected STDOUT ==========\n"
+ stdout
+ "Actual STDOUT ============\n"
+ _stdout
+ "STDERR ===================\n"
+ _stderr
)
assert _stderr == stderr, (
"Expected STDERR ==========\n"
+ stderr
+ "Actual STDERR ============\n"
+ _stderr
)
def run_match(self, content, *args):
expect = "%s: %s: %s: %s\n" % args
content = self.translate_newlines(to_str(content))
assert content == expect, \
"Expected %s ==========\n" % args[1] + expect + \
"Actual %s ============\n" % args[1] + content
class __init__TestCase(TestCmdTestCase):
def test_init(self):
"""Test init()"""
test = TestCmd.TestCmd()
test = TestCmd.TestCmd(description = 'test')
test = TestCmd.TestCmd(description = 'test', program = 'foo')
test = TestCmd.TestCmd(description = 'test',
program = 'foo',
universal_newlines=None)
class basename_TestCase(TestCmdTestCase):
def test_basename(self):
"""Test basename() [XXX TO BE WRITTEN]"""
assert 1 == 1
class cleanup_TestCase(TestCmdTestCase):
def test_cleanup(self):
"""Test cleanup()"""
test = TestCmd.TestCmd(workdir = '')
wdir = test.workdir
test.write('file1', "Test file #1\n")
test.cleanup()
assert not os.path.exists(wdir)
def test_writable(self):
"""Test cleanup() when the directory isn't writable"""
test = TestCmd.TestCmd(workdir = '')
wdir = test.workdir
test.write('file2', "Test file #2\n")
os.chmod(test.workpath('file2'), 0o400)
os.chmod(wdir, 0o500)
test.cleanup()
assert not os.path.exists(wdir)
def test_shutil(self):
"""Test cleanup() when used with shutil"""
test = TestCmd.TestCmd(workdir = '')
wdir = test.workdir
os.chdir(wdir)
import shutil
save_rmtree = shutil.rmtree
def my_rmtree(dir, ignore_errors=0, wdir=wdir, _rmtree=save_rmtree):
assert os.getcwd() != wdir
return _rmtree(dir, ignore_errors=ignore_errors)
try:
shutil.rmtree = my_rmtree
test.cleanup()
finally:
shutil.rmtree = save_rmtree
def test_atexit(self):
"""Test cleanup when atexit is used"""
self.popen_python("""\
import atexit
import sys
import TestCmd
sys.path = ['%s'] + sys.path
@atexit.register
def cleanup():
print("cleanup()")
result = TestCmd.TestCmd(workdir='')
sys.exit(0)
""" % self.orig_cwd, stdout='cleanup()\n')
class chmod_TestCase(TestCmdTestCase):
def test_chmod(self):
"""Test chmod()"""
test = TestCmd.TestCmd(workdir = '', subdir = 'sub')
wdir_file1 = os.path.join(test.workdir, 'file1')
wdir_sub_file2 = os.path.join(test.workdir, 'sub', 'file2')
with open(wdir_file1, 'w') as f:
f.write("")
with open(wdir_sub_file2, 'w') as f:
f.write("")
if sys.platform == 'win32':
test.chmod(wdir_file1, stat.S_IREAD)
test.chmod(['sub', 'file2'], stat.S_IWRITE)
file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE])
assert file1_mode == 0o444, '0%o' % file1_mode
file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE])
assert file2_mode == 0o666, '0%o' % file2_mode
test.chmod('file1', stat.S_IWRITE)
test.chmod(wdir_sub_file2, stat.S_IREAD)
file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE])
assert file1_mode == 0o666, '0%o' % file1_mode
file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE])
assert file2_mode == 0o444, '0%o' % file2_mode
else:
test.chmod(wdir_file1, 0o700)
test.chmod(['sub', 'file2'], 0o760)
file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE])
assert file1_mode == 0o700, '0%o' % file1_mode
file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE])
assert file2_mode == 0o760, '0%o' % file2_mode
test.chmod('file1', 0o765)
test.chmod(wdir_sub_file2, 0o567)
file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE])
assert file1_mode == 0o765, '0%o' % file1_mode
file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE])
assert file2_mode == 0o567, '0%o' % file2_mode
class combine_TestCase(TestCmdTestCase):
def test_combine(self):
"""Test combining stdout and stderr"""
run_env = TestCmd.TestCmd(workdir = '')
run_env.write('run1', """import sys
sys.stdout.write("run1 STDOUT %s\\n" % sys.argv[1:])
sys.stdout.write("run1 STDOUT second line\\n")
sys.stderr.write("run1 STDERR %s\\n" % sys.argv[1:])
sys.stderr.write("run1 STDERR second line\\n")
sys.stdout.write("run1 STDOUT third line\\n")
sys.stderr.write("run1 STDERR third line\\n")
""")
run_env.write('run2', """import sys
sys.stdout.write("run2 STDOUT %s\\n" % sys.argv[1:])
sys.stdout.write("run2 STDOUT second line\\n")
sys.stderr.write("run2 STDERR %s\\n" % sys.argv[1:])
sys.stderr.write("run2 STDERR second line\\n")
sys.stdout.write("run2 STDOUT third line\\n")
sys.stderr.write("run2 STDERR third line\\n")
""")
cwd = os.getcwd()
os.chdir(run_env.workdir)
# Everything before this prepared our "source directory."
# Now do the real test.
try:
test = TestCmd.TestCmd(interpreter = 'python',
workdir = '',
combine = 1)
output = test.stdout()
if output is not None:
raise IndexError("got unexpected output:\n\t`%s'\n" % output)
# The underlying system subprocess implementations can combine
# stdout and stderr in different orders, so we accomodate both.
test.program_set('run1')
test.run(arguments = 'foo bar')
stdout_lines = """\
run1 STDOUT ['foo', 'bar']
run1 STDOUT second line
run1 STDOUT third line
"""
stderr_lines = """\
run1 STDERR ['foo', 'bar']
run1 STDERR second line
run1 STDERR third line
"""
foo_bar_expect = (stdout_lines + stderr_lines,
stderr_lines + stdout_lines)
test.program_set('run2')
test.run(arguments = 'snafu')
stdout_lines = """\
run2 STDOUT ['snafu']
run2 STDOUT second line
run2 STDOUT third line
"""
stderr_lines = """\
run2 STDERR ['snafu']
run2 STDERR second line
run2 STDERR third line
"""
snafu_expect = (stdout_lines + stderr_lines,
stderr_lines + stdout_lines)
# XXX SHOULD TEST ABSOLUTE NUMBER AS WELL
output = test.stdout()
output = self.translate_newlines(output)
assert output in snafu_expect, output
error = test.stderr()
assert error == '', error
output = test.stdout(run = -1)
output = self.translate_newlines(output)
assert output in foo_bar_expect, output
error = test.stderr(-1)
assert error == '', error
finally:
os.chdir(cwd)
class description_TestCase(TestCmdTestCase):
def test_description(self):
"""Test description()"""
test = TestCmd.TestCmd()
assert test.description is None, 'initialized description?'
test = TestCmd.TestCmd(description = 'test')
assert test.description == 'test', 'uninitialized description'
test.description_set('foo')
assert test.description == 'foo', 'did not set description'
class diff_TestCase(TestCmdTestCase):
def test_diff_re(self):
"""Test diff_re()"""
result = TestCmd.diff_re(["abcde"], ["abcde"])
result = list(result)
assert result == [], result
result = TestCmd.diff_re(["a.*e"], ["abcde"])
result = list(result)
assert result == [], result
result = TestCmd.diff_re(["a.*e"], ["xxx"])
result = list(result)
assert result == ['1c1', "< 'a.*e'", '---', "> 'xxx'"], result
def test_diff_custom_function(self):
"""Test diff() using a custom function"""
self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
def my_diff(a, b):
return [
'*****',
a,
'*****',
b,
'*****',
]
test = TestCmd.TestCmd(diff = my_diff)
test.diff("a\\nb1\\nc\\n", "a\\nb2\\nc\\n", "STDOUT")
sys.exit(0)
""" % self.orig_cwd,
stdout = """\
STDOUT==========================================================================
*****
['a', 'b1', 'c']
*****
['a', 'b2', 'c']
*****
""")
def test_diff_string(self):
self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff = 'diff_re')
test.diff("a\\nb1\\nc\\n", "a\\nb2\\nc\\n", 'STDOUT')
sys.exit(0)
""" % self.orig_cwd,
stdout = """\
STDOUT==========================================================================
2c2
< 'b1'
---
> 'b2'
""")
def test_error(self):
"""Test handling a compilation error in TestCmd.diff_re()"""
script_input = """import sys
sys.path = ['%s'] + sys.path
import TestCmd
assert TestCmd.diff_re([r"a.*(e"], ["abcde"])
sys.exit(0)
""" % self.orig_cwd
stdout, stderr, status = self.call_python(script_input)
assert status == 1, status
expect1 = "Regular expression error in '^a.*(e$': missing )"
expect2 = "Regular expression error in '^a.*(e$': unbalanced parenthesis"
assert (stderr.find(expect1) != -1 or
stderr.find(expect2) != -1), repr(stderr)
def test_simple_diff_static_method(self):
"""Test calling the TestCmd.TestCmd.simple_diff() static method"""
self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
result = TestCmd.TestCmd.simple_diff(['a', 'b', 'c', 'e', 'f1'],
['a', 'c', 'd', 'e', 'f2'])
result = list(result)
expect = ['2d1', '< b', '3a3', '> d', '5c5', '< f1', '---', '> f2']
assert result == expect, result
sys.exit(0)
""" % self.orig_cwd)
def test_context_diff_static_method(self):
"""Test calling the TestCmd.TestCmd.context_diff() static method"""
self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
result = TestCmd.TestCmd.context_diff(['a\\n', 'b\\n', 'c\\n', 'e\\n', 'f1\\n'],
['a\\n', 'c\\n', 'd\\n', 'e\\n', 'f2\\n'])
result = list(result)
expect = [
'*** \\n',
'--- \\n',
'***************\\n',
'*** 1,5 ****\\n',
' a\\n',
'- b\\n',
' c\\n',
' e\\n',
'! f1\\n',
'--- 1,5 ----\\n',
' a\\n',
' c\\n',
'+ d\\n',
' e\\n',
'! f2\\n',
]
assert result == expect, result
sys.exit(0)
""" % self.orig_cwd)
def test_unified_diff_static_method(self):
"""Test calling the TestCmd.TestCmd.unified_diff() static method"""
self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
result = TestCmd.TestCmd.unified_diff(['a\\n', 'b\\n', 'c\\n', 'e\\n', 'f1\\n'],
['a\\n', 'c\\n', 'd\\n', 'e\\n', 'f2\\n'])
result = list(result)
expect = [
'--- \\n',
'+++ \\n',
'@@ -1,5 +1,5 @@\\n',
' a\\n',
'-b\\n',
' c\\n',
'+d\\n',
' e\\n',
'-f1\\n',
'+f2\\n'
]
assert result == expect, result
sys.exit(0)
""" % self.orig_cwd)
def test_diff_re_static_method(self):
"""Test calling the TestCmd.TestCmd.diff_re() static method"""
self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
result = TestCmd.TestCmd.diff_re(['a', 'b', 'c', '.', 'f1'],
['a', 'c', 'd', 'e', 'f2'])
result = list(result)
expect = [
'2c2',
"< 'b'",
'---',
"> 'c'",
'3c3',
"< 'c'",
'---',
"> 'd'",
'5c5',
"< 'f1'",
'---',
"> 'f2'"
]
assert result == expect, result
sys.exit(0)
""" % self.orig_cwd)
class diff_stderr_TestCase(TestCmdTestCase):
def test_diff_stderr_default(self):
"""Test diff_stderr() default behavior"""
self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd()
test.diff_stderr('a\nb1\nc\n', 'a\nb2\nc\n')
sys.exit(0)
""" % self.orig_cwd,
stdout="""\
2c2
< b1
---
> b2
""")
def test_diff_stderr_not_affecting_diff_stdout(self):
"""Test diff_stderr() not affecting diff_stdout() behavior"""
self.popen_python(r"""
import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stderr='diff_re')
print("diff_stderr:")
test.diff_stderr('a\nb.\nc\n', 'a\nbb\nc\n')
print("diff_stdout:")
test.diff_stdout('a\nb.\nc\n', 'a\nbb\nc\n')
sys.exit(0)
""" % self.orig_cwd,
stdout="""\
diff_stderr:
diff_stdout:
2c2
< b.
---
> bb
""")
def test_diff_stderr_custom_function(self):
"""Test diff_stderr() using a custom function"""
self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
def my_diff(a, b):
return ["a:"] + a + ["b:"] + b
test = TestCmd.TestCmd(diff_stderr=my_diff)
test.diff_stderr('abc', 'def')
sys.exit(0)
""" % self.orig_cwd,
stdout="""\
a:
abc
b:
def
""")
def test_diff_stderr_TestCmd_function(self):
"""Test diff_stderr() using a TestCmd function"""
self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stderr = TestCmd.diff_re)
test.diff_stderr('a\n.\n', 'b\nc\n')
sys.exit(0)
""" % self.orig_cwd,
stdout="""\
1c1
< 'a'
---
> 'b'
""")
def test_diff_stderr_static_method(self):
"""Test diff_stderr() using a static method"""
self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stderr=TestCmd.TestCmd.diff_re)
test.diff_stderr('a\n.\n', 'b\nc\n')
sys.exit(0)
""" % self.orig_cwd,
stdout="""\
1c1
< 'a'
---
> 'b'
""")
def test_diff_stderr_string(self):
"""Test diff_stderr() using a string to fetch the diff method"""
self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stderr='diff_re')
test.diff_stderr('a\n.\n', 'b\nc\n')
sys.exit(0)
""" % self.orig_cwd,
stdout="""\
1c1
< 'a'
---
> 'b'
""")
class diff_stdout_TestCase(TestCmdTestCase):
def test_diff_stdout_default(self):
"""Test diff_stdout() default behavior"""
self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd()
test.diff_stdout('a\nb1\nc\n', 'a\nb2\nc\n')
sys.exit(0)
""" % self.orig_cwd,
stdout="""\
2c2
< b1
---
> b2
""")
def test_diff_stdout_not_affecting_diff_stderr(self):
"""Test diff_stdout() not affecting diff_stderr() behavior"""
self.popen_python(r"""
import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stdout='diff_re')
print("diff_stdout:")
test.diff_stdout('a\nb.\nc\n', 'a\nbb\nc\n')
print("diff_stderr:")
test.diff_stderr('a\nb.\nc\n', 'a\nbb\nc\n')
sys.exit(0)
""" % self.orig_cwd,
stdout="""\
diff_stdout:
diff_stderr:
2c2
< b.
---
> bb
""")
def test_diff_stdout_custom_function(self):
"""Test diff_stdout() using a custom function"""
self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
def my_diff(a, b):
return ["a:"] + a + ["b:"] + b
test = TestCmd.TestCmd(diff_stdout=my_diff)
test.diff_stdout('abc', 'def')
sys.exit(0)
""" % self.orig_cwd,
stdout="""\
a:
abc
b:
def
""")
def test_diff_stdout_TestCmd_function(self):
"""Test diff_stdout() using a TestCmd function"""
self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stdout = TestCmd.diff_re)
test.diff_stdout('a\n.\n', 'b\nc\n')
sys.exit(0)
""" % self.orig_cwd,
stdout="""\
1c1
< 'a'
---
> 'b'
""")
def test_diff_stdout_static_method(self):
"""Test diff_stdout() using a static method"""
self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stdout=TestCmd.TestCmd.diff_re)
test.diff_stdout('a\n.\n', 'b\nc\n')
sys.exit(0)
""" % self.orig_cwd,
stdout="""\
1c1
< 'a'
---
> 'b'
""")
def test_diff_stdout_string(self):
"""Test diff_stdout() using a string to fetch the diff method"""
self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stdout='diff_re')
test.diff_stdout('a\n.\n', 'b\nc\n')
sys.exit(0)
""" % self.orig_cwd,
stdout="""\
1c1
< 'a'
---
> 'b'
""")
class exit_TestCase(TestCmdTestCase):
def test_exit(self):
"""Test exit()"""
def _test_it(cwd, tempdir, condition, preserved):
close_true = {'pass_test': 1, 'fail_test': 0, 'no_result': 0}
exit_status = {'pass_test': 0, 'fail_test': 1, 'no_result': 2}
result_string = {'pass_test': "PASSED\n",
'fail_test': "FAILED test at line 5 of <stdin>\n",
'no_result': "NO RESULT for test at line 5 of <stdin>\n"}
global ExitError
input = """import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(workdir = '%s')
test.%s()
""" % (cwd, tempdir, condition)
stdout, stderr, status = self.call_python(input, python="python")
if close_true[condition]:
unexpected = (status != 0)
else:
unexpected = (status == 0)
if unexpected:
msg = "Unexpected exit status from python: %s\n"
raise ExitError(msg % status + stdout + stderr)
if status != exit_status[condition]:
msg = "Expected exit status %d, got %d\n"
raise ExitError(msg % (exit_status[condition], status))
if stderr != result_string[condition]:
msg = "Expected error output:\n%sGot error output:\n%s"
raise ExitError(msg % (result_string[condition], stderr))
if preserved:
if not os.path.exists(tempdir):
msg = "Working directory %s was mistakenly removed\n"
raise ExitError(msg % tempdir + stdout)
else:
if os.path.exists(tempdir):
msg = "Working directory %s was mistakenly preserved\n"
raise ExitError(msg % tempdir + stdout)
run_env = TestCmd.TestCmd(workdir = '')
os.chdir(run_env.workdir)
# Everything before this prepared our "source directory."
# Now do the real test.
try:
cwd = self.orig_cwd
_clear_dict(os.environ, 'PRESERVE', 'PRESERVE_PASS', 'PRESERVE_FAIL', 'PRESERVE_NO_RESULT')
_test_it(cwd, 'dir01', 'pass_test', 0)
_test_it(cwd, 'dir02', 'fail_test', 0)
_test_it(cwd, 'dir03', 'no_result', 0)
os.environ['PRESERVE'] = '1'
_test_it(cwd, 'dir04', 'pass_test', 1)
_test_it(cwd, 'dir05', 'fail_test', 1)
_test_it(cwd, 'dir06', 'no_result', 1)
del os.environ['PRESERVE']
os.environ['PRESERVE_PASS'] = '1'
_test_it(cwd, 'dir07', 'pass_test', 1)
_test_it(cwd, 'dir08', 'fail_test', 0)
_test_it(cwd, 'dir09', 'no_result', 0)
del os.environ['PRESERVE_PASS']
os.environ['PRESERVE_FAIL'] = '1'
_test_it(cwd, 'dir10', 'pass_test', 0)
_test_it(cwd, 'dir11', 'fail_test', 1)
_test_it(cwd, 'dir12', 'no_result', 0)
del os.environ['PRESERVE_FAIL']
os.environ['PRESERVE_NO_RESULT'] = '1'
_test_it(cwd, 'dir13', 'pass_test', 0)
_test_it(cwd, 'dir14', 'fail_test', 0)
_test_it(cwd, 'dir15', 'no_result', 1)
del os.environ['PRESERVE_NO_RESULT']
finally:
_clear_dict(os.environ, 'PRESERVE', 'PRESERVE_PASS', 'PRESERVE_FAIL', 'PRESERVE_NO_RESULT')
class fail_test_TestCase(TestCmdTestCase):
def test_fail_test(self):
"""Test fail_test()"""
run_env = TestCmd.TestCmd(workdir = '')
run_env.write('run', """import sys
sys.stdout.write("run: STDOUT\\n")
sys.stderr.write("run: STDERR\\n")
""")
os.chdir(run_env.workdir)
# Everything before this prepared our "source directory."
# Now do the real test.
self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
TestCmd.fail_test(condition = 1)
""" % self.orig_cwd, status = 1, stderr = "FAILED test at line 4 of <stdin>\n")
self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '')
test.run()
test.fail_test(condition = (test.status == 0))
""" % self.orig_cwd, status = 1, stderr = "FAILED test of %s\n\tat line 6 of <stdin>\n" % run_env.workpath('run'))
self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(program = 'run', interpreter = 'python', description = 'xyzzy', workdir = '')
test.run()
test.fail_test(condition = (test.status == 0))
""" % self.orig_cwd, status = 1, stderr = "FAILED test of %s [xyzzy]\n\tat line 6 of <stdin>\n" % run_env.workpath('run'))
self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '')
test.run()
def xxx():
sys.stderr.write("printed on failure\\n")
test.fail_test(condition = (test.status == 0), function = xxx)
""" % self.orig_cwd, status = 1, stderr = "printed on failure\nFAILED test of %s\n\tat line 8 of <stdin>\n" % run_env.workpath('run'))
self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
def test1(self):
self.run()
self.fail_test(condition = (self.status == 0))
def test2(self):
test1(self)
test2(TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = ''))
""" % self.orig_cwd, status = 1, stderr = "FAILED test of %s\n\tat line 6 of <stdin> (test1)\n\tfrom line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n" % run_env.workpath('run'))
self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
def test1(self):
self.run()
self.fail_test(condition = (self.status == 0), skip = 1)
def test2(self):
test1(self)
test2(TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = ''))
""" % self.orig_cwd, status = 1, stderr = "FAILED test of %s\n\tat line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n" % run_env.workpath('run'))
class interpreter_TestCase(TestCmdTestCase):
def test_interpreter(self):
"""Test interpreter()"""
run_env = TestCmd.TestCmd(workdir = '')
run_env.write('run', """import sys
sys.stdout.write("run: STDOUT\\n")
sys.stderr.write("run: STDERR\\n")
""")
os.chdir(run_env.workdir)
# Everything before this prepared our "source directory."
# Now do the real test.
test = TestCmd.TestCmd(program = 'run', workdir = '')
test.interpreter_set('foo')
assert test.interpreter == 'foo', 'did not set interpreter'
test.interpreter_set('python')
assert test.interpreter == 'python', 'did not set interpreter'
test.run()
class match_TestCase(TestCmdTestCase):
def test_match_default(self):
"""Test match() default behavior"""
test = TestCmd.TestCmd()
assert test.match("abcde\n", "a.*e\n")
assert test.match("12345\nabcde\n", "1\\d+5\na.*e\n")
lines = ["vwxyz\n", "67890\n"]
regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
assert test.match(lines, regexes)
def test_match_custom_function(self):
"""Test match() using a custom function"""
def match_length(lines, matches):
return len(lines) == len(matches)
test = TestCmd.TestCmd(match=match_length)
assert not test.match("123\n", "1\n")
assert test.match("123\n", "111\n")
assert not test.match("123\n123\n", "1\n1\n")
assert test.match("123\n123\n", "111\n111\n")
lines = ["123\n", "123\n"]
regexes = ["1\n", "1\n"]
assert test.match(lines, regexes) # due to equal numbers of lines
def test_match_TestCmd_function(self):
"""Test match() using a TestCmd function"""
test = TestCmd.TestCmd(match = TestCmd.match_exact)
assert not test.match("abcde\n", "a.*e\n")
assert test.match("abcde\n", "abcde\n")
assert not test.match("12345\nabcde\n", "1\\d+5\na.*e\n")
assert test.match("12345\nabcde\n", "12345\nabcde\n")
lines = ["vwxyz\n", "67890\n"]
regexes = [r"v[^a-u]*z\n", r"6[^ ]+0\n"]
assert not test.match(lines, regexes)
assert test.match(lines, lines)
def test_match_static_method(self):
"""Test match() using a static method"""
test = TestCmd.TestCmd(match=TestCmd.TestCmd.match_exact)
assert not test.match("abcde\n", "a.*e\n")
assert test.match("abcde\n", "abcde\n")
assert not test.match("12345\nabcde\n", "1\\d+5\na.*e\n")
assert test.match("12345\nabcde\n", "12345\nabcde\n")
lines = ["vwxyz\n", "67890\n"]
regexes = [r"v[^a-u]*z\n", r"6[^ ]+0\n"]
assert not test.match(lines, regexes)
assert test.match(lines, lines)
def test_match_string(self):
"""Test match() using a string to fetch the match method"""
test = TestCmd.TestCmd(match='match_exact')
assert not test.match("abcde\n", "a.*e\n")
assert test.match("abcde\n", "abcde\n")
assert not test.match("12345\nabcde\n", "1\\d+5\na.*e\n")
assert test.match("12345\nabcde\n", "12345\nabcde\n")
lines = ["vwxyz\n", "67890\n"]
regexes = [r"v[^a-u]*z\n", r"6[^ ]+0\n"]
assert not test.match(lines, regexes)
assert test.match(lines, lines)