forked from SCons/scons
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestCmd.py
More file actions
2185 lines (1805 loc) · 70.2 KB
/
TestCmd.py
File metadata and controls
2185 lines (1805 loc) · 70.2 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
# Copyright 2000-2024 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.
#
# Python License: https://docs.python.org/3/license.html#psf-license
"""
A testing framework for commands and scripts.
The TestCmd module provides a framework for portable automated testing
of executable commands and scripts (in any language, not just Python),
especially commands and scripts that require file system interaction.
In addition to running tests and evaluating conditions, the TestCmd
module manages and cleans up one or more temporary workspace
directories, and provides methods for creating files and directories in
those workspace directories from in-line data, here-documents), allowing
tests to be completely self-contained.
A TestCmd environment object is created via the usual invocation:
import TestCmd
test = TestCmd.TestCmd()
There are a bunch of keyword arguments available at instantiation:
test = TestCmd.TestCmd(
description='string',
program='program_or_script_to_test',
interpreter='script_interpreter',
workdir='prefix',
subdir='subdir',
verbose=int, # verbosity level
match=default_match_function,
match_stdout=default_match_stdout_function,
match_stderr=default_match_stderr_function,
diff=default_diff_stderr_function,
diff_stdout=default_diff_stdout_function,
diff_stderr=default_diff_stderr_function,
combine=Boolean,
)
There are a bunch of methods that let you do different things:
test.verbose_set(1)
test.description_set('string')
test.program_set('program_or_script_to_test')
test.interpreter_set('script_interpreter')
test.interpreter_set(['script_interpreter', 'arg'])
test.workdir_set('prefix')
test.workdir_set('')
test.workpath('file')
test.workpath('subdir', 'file')
test.subdir('subdir', ...)
test.rmdir('subdir', ...)
test.write('file', "contents\n")
test.write(['subdir', 'file'], "contents\n")
test.read('file')
test.read(['subdir', 'file'])
test.read('file', mode)
test.read(['subdir', 'file'], mode)
test.writable('dir', 1)
test.writable('dir', None)
test.preserve(condition, ...)
test.cleanup(condition)
test.command_args(
program='program_or_script_to_run',
interpreter='script_interpreter',
arguments='arguments to pass to program',
)
test.run(
program='program_or_script_to_run',
interpreter='script_interpreter',
arguments='arguments to pass to program',
chdir='directory_to_chdir_to',
stdin='input to feed to the program\n',
universal_newlines=True,
)
p = test.start(
program='program_or_script_to_run',
interpreter='script_interpreter',
arguments='arguments to pass to program',
universal_newlines=None,
)
test.finish(self, p)
test.pass_test()
test.pass_test(condition)
test.pass_test(condition, function)
test.fail_test()
test.fail_test(condition)
test.fail_test(condition, function)
test.fail_test(condition, function, skip)
test.fail_test(condition, function, skip, message)
test.no_result()
test.no_result(condition)
test.no_result(condition, function)
test.no_result(condition, function, skip)
test.stdout()
test.stdout(run)
test.stderr()
test.stderr(run)
test.symlink(target, link)
test.banner(string)
test.banner(string, width)
test.diff(actual, expected)
test.diff_stderr(actual, expected)
test.diff_stdout(actual, expected)
test.match(actual, expected)
test.match_stderr(actual, expected)
test.match_stdout(actual, expected)
test.set_match_function(match, stdout, stderr)
test.match_exact("actual 1\nactual 2\n", "expected 1\nexpected 2\n")
test.match_exact(["actual 1\n", "actual 2\n"],
["expected 1\n", "expected 2\n"])
test.match_caseinsensitive("Actual 1\nACTUAL 2\n", "expected 1\nEXPECTED 2\n")
test.match_re("actual 1\nactual 2\n", regex_string)
test.match_re(["actual 1\n", "actual 2\n"], list_of_regexes)
test.match_re_dotall("actual 1\nactual 2\n", regex_string)
test.match_re_dotall(["actual 1\n", "actual 2\n"], list_of_regexes)
test.tempdir()
test.tempdir('temporary-directory')
test.sleep()
test.sleep(seconds)
test.where_is('foo')
test.where_is('foo', 'PATH1:PATH2')
test.where_is('foo', 'PATH1;PATH2', '.suffix3;.suffix4')
test.unlink('file')
test.unlink('subdir', 'file')
The TestCmd module provides pass_test(), fail_test(), and no_result()
unbound functions that report test results for use with the Aegis change
management system. These methods terminate the test immediately,
reporting PASSED, FAILED, or NO RESULT respectively, and exiting with
status 0 (success), 1 or 2 respectively. This allows for a distinction
between an actual failed test and a test that could not be properly
evaluated because of an external condition (such as a full file system
or incorrect permissions).
import TestCmd
TestCmd.pass_test()
TestCmd.pass_test(condition)
TestCmd.pass_test(condition, function)
TestCmd.fail_test()
TestCmd.fail_test(condition)
TestCmd.fail_test(condition, function)
TestCmd.fail_test(condition, function, skip)
TestCmd.fail_test(condition, function, skip, message)
TestCmd.no_result()
TestCmd.no_result(condition)
TestCmd.no_result(condition, function)
TestCmd.no_result(condition, function, skip)
The TestCmd module also provides unbound global functions that handle
matching in the same way as the match_*() methods described above.
import TestCmd
test = TestCmd.TestCmd(match=TestCmd.match_exact)
test = TestCmd.TestCmd(match=TestCmd.match_caseinsensitive)
test = TestCmd.TestCmd(match=TestCmd.match_re)
test = TestCmd.TestCmd(match=TestCmd.match_re_dotall)
These functions are also available as static methods:
import TestCmd
test = TestCmd.TestCmd(match=TestCmd.TestCmd.match_exact)
test = TestCmd.TestCmd(match=TestCmd.TestCmd.match_caseinsensitive)
test = TestCmd.TestCmd(match=TestCmd.TestCmd.match_re)
test = TestCmd.TestCmd(match=TestCmd.TestCmd.match_re_dotall)
These static methods can be accessed by a string naming the method:
import TestCmd
test = TestCmd.TestCmd(match='match_exact')
test = TestCmd.TestCmd(match='match_caseinsensitive')
test = TestCmd.TestCmd(match='match_re')
test = TestCmd.TestCmd(match='match_re_dotall')
The TestCmd module provides unbound global functions that can be used
for the "diff" argument to TestCmd.TestCmd instantiation:
import TestCmd
test = TestCmd.TestCmd(match=TestCmd.match_re, diff=TestCmd.diff_re)
test = TestCmd.TestCmd(diff=TestCmd.simple_diff)
test = TestCmd.TestCmd(diff=TestCmd.context_diff)
test = TestCmd.TestCmd(diff=TestCmd.unified_diff)
These functions are also available as static methods:
import TestCmd
test = TestCmd.TestCmd(match=TestCmd.TestCmd.match_re, diff=TestCmd.TestCmd.diff_re)
test = TestCmd.TestCmd(diff=TestCmd.TestCmd.simple_diff)
test = TestCmd.TestCmd(diff=TestCmd.TestCmd.context_diff)
test = TestCmd.TestCmd(diff=TestCmd.TestCmd.unified_diff)
These static methods can be accessed by a string naming the method:
import TestCmd
test = TestCmd.TestCmd(match='match_re', diff='diff_re')
test = TestCmd.TestCmd(diff='simple_diff')
test = TestCmd.TestCmd(diff='context_diff')
test = TestCmd.TestCmd(diff='unified_diff')
The "diff" argument can also be used with standard difflib functions:
import difflib
test = TestCmd.TestCmd(diff=difflib.context_diff)
test = TestCmd.TestCmd(diff=difflib.unified_diff)
Lastly, the where_is() method also exists in an unbound function
version.
import TestCmd
TestCmd.where_is('foo')
TestCmd.where_is('foo', 'PATH1:PATH2')
TestCmd.where_is('foo', 'PATH1;PATH2', '.suffix3;.suffix4')
"""
from __future__ import annotations
__author__ = "Steven Knight <knight at baldmt dot com>"
__revision__ = "TestCmd.py 1.3.D001 2010/06/03 12:58:27 knight"
__version__ = "1.3"
import atexit
import difflib
import errno
import hashlib
import os
import re
try:
import psutil
except ImportError:
HAVE_PSUTIL = False
else:
HAVE_PSUTIL = True
import shutil
import signal
import stat
import subprocess
import sys
import tempfile
import time
import traceback
from collections import UserList, UserString
from pathlib import Path
from subprocess import PIPE, STDOUT
from typing import Callable
IS_WINDOWS = sys.platform == 'win32'
IS_MACOS = sys.platform == 'darwin'
IS_64_BIT = sys.maxsize > 2**32
IS_PYPY = hasattr(sys, 'pypy_translation_info')
try:
IS_ROOT = os.geteuid() == 0
except AttributeError:
IS_ROOT = False
NEED_HELPER = os.environ.get('SCONS_NO_DIRECT_SCRIPT')
# sentinel for cases where None won't do
_Null = object()
__all__ = [
'diff_re',
'fail_test',
'no_result',
'pass_test',
'match_exact',
'match_caseinsensitive',
'match_re',
'match_re_dotall',
'python',
'_python_',
'TestCmd',
'to_bytes',
'to_str',
]
def is_List(e):
return isinstance(e, (list, UserList))
def to_bytes(s):
if isinstance(s, bytes):
return s
return bytes(s, 'utf-8')
def to_str(s):
if is_String(s):
return s
return str(s, 'utf-8')
def is_String(e):
return isinstance(e, (str, UserString))
testprefix = 'testcmd.'
if os.name in ('posix', 'nt'):
testprefix += f"{os.getpid()}."
re_space = re.compile(r'\s')
def _caller(tblist, skip):
string = ""
arr = []
for file, line, name, text in tblist:
if file[-10:] == "TestCmd.py":
break
arr = [(file, line, name, text)] + arr
atfrom = "at"
for file, line, name, text in arr[skip:]:
if name in ("?", "<module>"):
name = ""
else:
name = f" ({name})"
string = string + ("%s line %d of %s%s\n" % (atfrom, line, file, name))
atfrom = "\tfrom"
return string
def clean_up_ninja_daemon(self, result_type) -> None:
"""
Kill any running scons daemon started by ninja and clean up
Working directory and temp files are removed.
Skipped if this platform doesn't have psutil (e.g. msys2 on Windows)
"""
if not self:
return
for path in Path(self.workdir).rglob('.ninja'):
daemon_dir = Path(tempfile.gettempdir()) / (
f"scons_daemon_{str(hashlib.md5(str(path.resolve()).encode()).hexdigest())}"
)
pidfiles = [daemon_dir / 'pidfile', path / 'scons_daemon_dirty']
for pidfile in pidfiles:
if pidfile.exists():
with open(pidfile) as f:
try:
pid = int(f.read())
os.kill(pid, signal.SIGINT)
except OSError:
pass
while HAVE_PSUTIL:
if pid not in [proc.pid for proc in psutil.process_iter()]:
break
else:
time.sleep(0.1)
if not self._preserve[result_type]:
if daemon_dir.exists():
shutil.rmtree(daemon_dir)
def fail_test(
self=None,
condition: bool = True,
function: Callable | None = None,
skip: int = 0,
message: str = "",
) -> None:
"""Causes a test to exit with a fail.
Reports that the test FAILED and exits with a status of 1, unless
a condition argument is supplied; if so the completion processing
takes place only if the condition is true.
Args:
self: a test class instance. Must be passed in explicitly
by the caller since this is an unbound method.
condition (optional): if false, return to let test continue.
function (optional): function to call before completion processing.
skip (optional): how many lines at the top of the traceback to skip.
message (optional): additional text to include in the fail message.
"""
if not condition:
return
if function is not None:
function()
clean_up_ninja_daemon(self, 'fail_test')
of = ""
desc = ""
sep = " "
if self is not None:
if self.program:
of = f" of {self.program}"
sep = "\n\t"
if self.description:
desc = f" [{self.description}]"
sep = "\n\t"
at = _caller(traceback.extract_stack(), skip)
if message:
msg = f"\t{message}\n"
else:
msg = ""
sys.stderr.write(f"FAILED test{of}{desc}{sep}{at}{msg}")
sys.exit(1)
def no_result(self=None, condition: bool = True, function=None, skip: int = 0) -> None:
"""Causes a test to exit with a no result.
In testing parlance NO RESULT means the test could not be completed
for reasons that imply neither success nor failure - for example a
component needed to run the test could be found. However, at this
point we still have an "outcome", so record the information and exit
with a status code of 2, unless a condition argument is supplied;
if so the completion processing takes place only if the condition is true.
The different exit code and message allows other logic to distinguish
from a fail and decide how to treat NO RESULT tests.
Args:
self: a test class instance. Must be passed in explicitly
by the caller since this is an unbound method.
condition (optional): if false, return to let test continue.
function (optional): function to call before completion processing.
skip (optional): how many lines at the top of the traceback to skip.
"""
if not condition:
return
if function is not None:
function()
clean_up_ninja_daemon(self, 'no_result')
of = ""
desc = ""
sep = " "
if self is not None:
if self.program:
of = f" of {self.program}"
sep = "\n\t"
if self.description:
desc = f" [{self.description}]"
sep = "\n\t"
at = _caller(traceback.extract_stack(), skip)
sys.stderr.write(f"NO RESULT for test{of}{desc}{sep}{at}")
sys.exit(2)
def pass_test(self=None, condition: bool = True, function=None) -> None:
"""Causes a test to exit with a pass.
Reports that the test PASSED and exits with a status of 0, unless
a condition argument is supplied; if so the completion processing
takes place only if the condition is true.
the test passes only if the condition is true.
Args:
self: a test class instance. Must be passed in explicitly
by the caller since this is an unbound method.
condition (optional): if false, return to let test continue.
function (optional): function to call before completion processing.
"""
if not condition:
return
if function is not None:
function()
clean_up_ninja_daemon(self, 'pass_test')
sys.stderr.write("PASSED\n")
sys.exit(0)
def match_exact(lines=None, matches=None, newline=os.sep):
"""Match function using exact match.
:param lines: data lines
:type lines: str or list[str]
:param matches: expected lines to match
:type matches: str or list[str]
:param newline: line separator
:returns: None on failure, 1 on success.
"""
if isinstance(lines, bytes):
newline = to_bytes(newline)
if not is_List(lines):
lines = lines.split(newline)
if not is_List(matches):
matches = matches.split(newline)
if len(lines) != len(matches):
return None
for line, match in zip(lines, matches):
if line != match:
return None
return 1
def match_caseinsensitive(lines=None, matches=None):
"""Match function using case-insensitive matching.
Only a simplistic comparison is done, based on casefolding
the strings. This may still fail but is the suggestion of
the Unicode Standard.
:param lines: data lines
:type lines: str or list[str]
:param matches: expected lines to match
:type matches: str or list[str]
:returns: None on failure, 1 on success.
"""
if not is_List(lines):
lines = lines.split("\n")
if not is_List(matches):
matches = matches.split("\n")
if len(lines) != len(matches):
return None
for line, match in zip(lines, matches):
if line.casefold() != match.casefold():
return None
return 1
def match_re(lines=None, res=None):
"""Match function using line-by-line regular expression match.
:param lines: data lines
:type lines: str or list[str]
:param res: regular expression(s) for matching
:type res: str or list[str]
:returns: None on failure, 1 on success.
"""
if not is_List(lines):
# CRs mess up matching (Windows) so split carefully
lines = re.split('\r?\n', lines)
if not is_List(res):
res = res.split("\n")
if len(lines) != len(res):
print(f"match_re: expected {len(res)} lines, found {len(lines)}")
return None
for i, (line, regex) in enumerate(zip(lines, res)):
s = rf"^{regex}$"
try:
expr = re.compile(s)
except re.error as e:
msg = "Regular expression error in %s: %s"
raise re.error(msg % (repr(s), e.args[0]))
if not expr.search(line):
miss_tmpl = "match_re: mismatch at line {}:\n search re='{}'\n line='{}'"
print(miss_tmpl.format(i, s, line))
return None
return 1
def match_re_dotall(lines=None, res=None):
"""Match function using regular expression match.
Unlike match_re, the arguments are converted to strings (if necessary)
and must match exactly.
:param lines: data lines
:type lines: str or list[str]
:param res: regular expression(s) for matching
:type res: str or list[str]
:returns: a match object on match, else None, like re.match
"""
if not isinstance(lines, str):
lines = "\n".join(lines)
if not isinstance(res, str):
res = "\n".join(res)
s = rf"^{res}$"
try:
expr = re.compile(s, re.DOTALL)
except re.error as e:
msg = "Regular expression error in %s: %s"
raise re.error(msg % (repr(s), e.args[0]))
return expr.match(lines)
def simple_diff(
a,
b,
fromfile: str = '',
tofile: str = '',
fromfiledate: str = '',
tofiledate: str = '',
n: int = 0,
lineterm: str = '',
):
r"""Compare two sequences of lines; generate the delta as a simple diff.
Similar to difflib.context_diff and difflib.unified_diff but
output is like from the "diff" command without arguments. The function
keeps the same signature as the difflib ones so they will be
interchangeable, but except for lineterm, the arguments beyond the
two sequences are ignored in this version. By default, the
diff is not created with trailing newlines, set the lineterm
argument to '\n' to do so.
Example:
>>> print(''.join(simple_diff('one\ntwo\nthree\nfour\n'.splitlines(True),
... 'zero\none\ntree\nfour\n'.splitlines(True), lineterm='\n')))
0a1
> zero
2,3c3
< two
< three
---
> tree
"""
a = [to_str(q) for q in a]
b = [to_str(q) for q in b]
sm = difflib.SequenceMatcher(None, a, b)
def comma(x1, x2):
return str(x2) if x1 + 1 == x2 else f'{x1 + 1},{x2}'
for op, a1, a2, b1, b2 in sm.get_opcodes():
if op == 'delete':
yield f"{comma(a1, a2)}d{b1}{lineterm}"
for l in a[a1:a2]:
yield f"< {l}"
elif op == 'insert':
yield f"{a1}a{comma(b1, b2)}{lineterm}"
for l in b[b1:b2]:
yield f"> {l}"
elif op == 'replace':
yield f"{comma(a1, a2)}c{comma(b1, b2)}{lineterm}"
for l in a[a1:a2]:
yield f"< {l}"
yield f'---{lineterm}'
for l in b[b1:b2]:
yield f"> {l}"
def diff_re(
a,
b,
fromfile: str = '',
tofile: str = '',
fromfiledate: str = '',
tofiledate: str = '',
n: int = 3,
lineterm: str = '\n',
):
"""Compare a and b (lists of strings) where a are regular expressions.
A simple "diff" of two sets of lines when the expected lines
are regular expressions. This is a really dumb thing that
just compares each line in turn, so it doesn't look for
chunks of matching lines and the like--but at least it lets
you know exactly which line first didn't compare correctl...
Raises:
re.error: if a regex fails to compile
"""
result = []
diff = len(a) - len(b)
if diff < 0:
a = a + [''] * (-diff)
elif diff > 0:
b = b + [''] * diff
for i, (aline, bline) in enumerate(zip(a, b)):
s = rf"^{aline}$"
try:
expr = re.compile(s)
except re.error as e:
msg = "Regular expression error in %s: %s"
raise re.error(msg % (repr(s), e.args[0]))
if not expr.search(bline):
result.append(f"{i + 1}c{i + 1}")
result.append(f"< {a[i]!r}")
result.append('---')
result.append(f"> {b[i]!r}")
return result
if os.name == 'posix':
def escape(arg):
"""escape shell special characters"""
slash = '\\'
special = '"$'
arg = arg.replace(slash, slash + slash)
for c in special:
arg = arg.replace(c, slash + c)
if re_space.search(arg):
arg = f"\"{arg}\""
return arg
else:
# Windows does not allow special characters in file names
# anyway, so no need for an escape function, we will just quote
# the arg.
def escape(arg):
if re_space.search(arg):
arg = f"\"{arg}\""
return arg
if os.name == 'java':
python = os.path.join(sys.prefix, 'jython')
else:
python = os.environ.get('python_executable', sys.executable)
_python_ = escape(python)
if sys.platform == 'win32':
default_sleep_seconds = 2
def where_is(file, path=None, pathext=None):
if path is None:
path = os.environ['PATH']
if is_String(path):
path = path.split(os.pathsep)
if pathext is None:
pathext = os.environ['PATHEXT']
if is_String(pathext):
pathext = pathext.split(os.pathsep)
for ext in pathext:
if ext.casefold() == file[-len(ext) :].casefold():
pathext = ['']
break
for dir in path:
f = os.path.join(dir, file)
for ext in pathext:
fext = f + ext
if os.path.isfile(fext):
return fext
return None
else:
def where_is(file, path=None, pathext=None):
if path is None:
path = os.environ['PATH']
if is_String(path):
path = path.split(os.pathsep)
for dir in path:
f = os.path.join(dir, file)
if os.path.isfile(f):
try:
st = os.stat(f)
except OSError:
continue
if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
return f
return None
default_sleep_seconds = 1
# From Josiah Carlson,
# ASPN : Python Cookbook : Module to allow Asynchronous subprocess use on Windows and Posix platforms
# https://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554
if sys.platform == 'win32': # and subprocess.mswindows:
try:
from win32file import ReadFile, WriteFile
from win32pipe import PeekNamedPipe
except ImportError:
# If PyWin32 is not available, try ctypes instead
# XXX These replicate _just_enough_ PyWin32 behaviour for our purposes
import ctypes
from ctypes.wintypes import DWORD
def ReadFile(hFile, bufSize, ol=None):
assert ol is None
lpBuffer = ctypes.create_string_buffer(bufSize)
bytesRead = DWORD()
bErr = ctypes.windll.kernel32.ReadFile(
hFile, lpBuffer, bufSize, ctypes.byref(bytesRead), ol
)
if not bErr:
raise ctypes.WinError()
return (0, ctypes.string_at(lpBuffer, bytesRead.value))
def WriteFile(hFile, data, ol=None):
assert ol is None
bytesWritten = DWORD()
bErr = ctypes.windll.kernel32.WriteFile(
hFile, data, len(data), ctypes.byref(bytesWritten), ol
)
if not bErr:
raise ctypes.WinError()
return (0, bytesWritten.value)
def PeekNamedPipe(hPipe, size):
assert size == 0
bytesAvail = DWORD()
bErr = ctypes.windll.kernel32.PeekNamedPipe(
hPipe, None, size, None, ctypes.byref(bytesAvail), None
)
if not bErr:
raise ctypes.WinError()
return ("", bytesAvail.value, None)
import msvcrt
else:
import select
import fcntl
try:
fcntl.F_GETFL
except AttributeError:
fcntl.F_GETFL = 3
try:
fcntl.F_SETFL
except AttributeError:
fcntl.F_SETFL = 4
class Popen(subprocess.Popen):
def recv(self, maxsize=None):
return self._recv('stdout', maxsize)
def recv_err(self, maxsize=None):
return self._recv('stderr', maxsize)
def send_recv(self, input: str = '', maxsize=None):
return self.send(input), self.recv(maxsize), self.recv_err(maxsize)
def get_conn_maxsize(self, which, maxsize):
if maxsize is None:
maxsize = 1024
elif maxsize < 1:
maxsize = 1
return getattr(self, which), maxsize
def _close(self, which) -> None:
getattr(self, which).close()
setattr(self, which, None)
if sys.platform == 'win32': # and subprocess.mswindows:
def send(self, input):
input = to_bytes(input)
if not self.stdin:
return None
try:
x = msvcrt.get_osfhandle(self.stdin.fileno())
(errCode, written) = WriteFile(x, input)
except ValueError:
return self._close('stdin')
except (subprocess.pywintypes.error, Exception) as why:
if why.args[0] in (109, errno.ESHUTDOWN):
return self._close('stdin')
raise
return written
def _recv(self, which, maxsize):
conn, maxsize = self.get_conn_maxsize(which, maxsize)
if conn is None:
return None
try:
x = msvcrt.get_osfhandle(conn.fileno())
(read, nAvail, nMessage) = PeekNamedPipe(x, 0)
if maxsize < nAvail:
nAvail = maxsize
if nAvail > 0:
(errCode, read) = ReadFile(x, nAvail, None)
except ValueError:
return self._close(which)
except (subprocess.pywintypes.error, Exception) as why:
if why.args[0] in (109, errno.ESHUTDOWN):
return self._close(which)
raise
# if self.universal_newlines:
# read = self._translate_newlines(read)
return read
else:
def send(self, input):
if not self.stdin:
return None
if not select.select([], [self.stdin], [], 0)[1]:
return 0
try:
written = os.write(self.stdin.fileno(), bytearray(input, 'utf-8'))
except OSError as why:
if why.args[0] == errno.EPIPE: # broken pipe
return self._close('stdin')
raise
return written
def _recv(self, which, maxsize):
conn, maxsize = self.get_conn_maxsize(which, maxsize)
if conn is None:
return None
try:
flags = fcntl.fcntl(conn, fcntl.F_GETFL)
except TypeError:
flags = None
else:
if not conn.closed:
fcntl.fcntl(conn, fcntl.F_SETFL, flags | os.O_NONBLOCK)
try:
if not select.select([conn], [], [], 0)[0]:
return ''
r = conn.read(maxsize)
if not r:
return self._close(which)
# if self.universal_newlines: