-
-
Notifications
You must be signed in to change notification settings - Fork 230
/
Copy pathBoostBuild.py
1391 lines (1180 loc) · 52.7 KB
/
BoostBuild.py
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 2002-2005 Vladimir Prus.
# Copyright 2002-2003 Dave Abrahams.
# Copyright 2006 Rene Ferdinand Rivera Morell.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at
# https://www.bfgroup.xyz/b2/LICENSE.txt)
from __future__ import print_function
import TestCmd
import copy
import fnmatch
import glob
import math
import os
import os.path
import re
import shutil
try:
from StringIO import StringIO
except:
from io import StringIO
import subprocess
import sys
import tempfile
import time
import traceback
import tree
import types
from difflib import ndiff
from xml.sax.saxutils import escape
try:
from functools import reduce
except:
pass
def isstr(data):
return isinstance(data, (type(''), type(u'')))
class TestEnvironmentError(Exception):
pass
annotations = []
def print_annotation(name, value, xml):
"""Writes some named bits of information about the current test run."""
if xml:
print(escape(name) + " {{{")
print(escape(value))
print("}}}")
else:
print(name + " {{{")
print(str(value).encode('utf8'))
print("}}}")
def flush_annotations(xml=0):
global annotations
for ann in annotations:
print_annotation(ann[0], ann[1], xml)
annotations = []
def clear_annotations():
global annotations
annotations = []
defer_annotations = 0
def set_defer_annotations(n):
global defer_annotations
defer_annotations = n
def annotate_stack_trace(tb=None, level=None):
if tb:
trace = TestCmd.caller(traceback.extract_tb(tb), level or 0)
else:
trace = TestCmd.caller(traceback.extract_stack(), level or 1)
annotation("stacktrace", trace)
def annotation(name, value):
"""Records an annotation about the test run."""
annotations.append((name, value))
if not defer_annotations:
flush_annotations()
def get_toolset():
toolset = None
for arg in sys.argv[1:]:
if not arg.startswith("-"):
toolset = arg
if toolset:
return toolset
if sys.platform == "win32":
return "msvc"
if sys.platform == "darwin" or sys.platform.startswith("freebsd") or sys.platform.startswith("openbsd"):
return "clang"
return "gcc"
# Detect the host OS.
if sys.platform == "cygwin":
host_os = "cygwin"
elif sys.platform == "win32":
host_os = "windows"
elif hasattr(os, "uname"):
host_os = os.uname()[0].lower()
def expand_toolset(toolset, target_os):
match = re.match(r'^(clang|intel)(-[\d\.]+|)$', toolset)
if match:
if match.group(1) == "intel" and target_os == "windows":
return match.expand(r'\1-win\2')
elif target_os == "darwin":
return match.expand(r'\1-darwin\2')
else:
return match.expand(r'\1-linux\2')
return toolset
def prepare_prefixes_and_suffixes(toolset, target_os):
ind = toolset.find('-')
if ind == -1:
rtoolset = toolset
else:
rtoolset = toolset[:ind]
prepare_suffix_map(rtoolset, target_os)
prepare_library_prefix(rtoolset, target_os)
def prepare_suffix_map(toolset, target_os):
"""
Set up suffix translation performed by the Boost Build testing framework
to accommodate different toolsets generating targets of the same type using
different filename extensions (suffixes).
"""
global suffixes
suffixes = {}
if target_os == "cygwin":
suffixes[".lib"] = ".a"
suffixes[".obj"] = ".o"
suffixes[".implib"] = ".dll.a"
elif target_os == "windows":
if toolset == "gcc":
# MinGW
suffixes[".lib"] = ".a"
suffixes[".obj"] = ".o"
suffixes[".implib"] = ".dll.a"
else:
# Everything else Windows
suffixes[".implib"] = ".lib"
else:
suffixes[".exe"] = ""
suffixes[".dll"] = ".so"
suffixes[".lib"] = ".a"
suffixes[".obj"] = ".o"
suffixes[".implib"] = ".no_implib_files_on_this_platform"
if target_os == "darwin":
suffixes[".dll"] = ".dylib"
if toolset == "emscripten":
suffixes[".exe"] = ".js" # or .wasm?
suffixes[".dll"] = ".so" # .wasn doesn't work for searched libs
def prepare_library_prefix(toolset, target_os):
"""
Setup whether Boost Build is expected to automatically prepend prefixes
to its built library targets.
"""
global lib_prefix
lib_prefix = "lib"
global dll_prefix
if target_os == "cygwin":
dll_prefix = "cyg"
elif target_os == "windows" and toolset != "gcc":
dll_prefix = None
else:
dll_prefix = "lib"
global implib_prefix
implib_prefix = None
if toolset == "gcc":
implib_prefix = "lib"
def re_remove(sequence, regex):
me = re.compile(regex)
result = list(filter(lambda x: me.match(x), sequence))
if not result:
raise ValueError()
for r in result:
sequence.remove(r)
def glob_remove(sequence, pattern):
result = list(fnmatch.filter(sequence, pattern))
if not result:
raise ValueError()
for r in result:
sequence.remove(r)
class Tester(TestCmd.TestCmd):
"""Main tester class for Boost Build.
Optional arguments:
`arguments` - Arguments passed to the run executable.
`executable` - Name of the executable to invoke.
`match` - Function to use for compating actual and
expected file contents.
`boost_build_path` - Boost build path to be passed to the run
executable.
`translate_suffixes` - Whether to update suffixes on the the file
names passed from the test script so they
match those actually created by the current
toolset. For example, static library files
are specified by using the .lib suffix but
when the "gcc" toolset is used it actually
creates them using the .a suffix.
`pass_toolset` - Whether the test system should pass the
specified toolset to the run executable.
`use_test_config` - Whether the test system should tell the run
executable to read in the test_config.jam
configuration file.
`ignore_toolset_requirements` - Whether the test system should tell the run
executable to ignore toolset requirements.
`workdir` - Absolute directory where the test will be
run from.
`pass_d0` - If set, when tests are not explicitly run
in verbose mode, they are run as silent
(-d0 & --quiet Boost Jam options).
Optional arguments inherited from the base class:
`description` - Test description string displayed in case
of a failed test.
`subdir` - List of subdirectories to automatically
create under the working directory. Each
subdirectory needs to be specified
separately, parent coming before its child.
`verbose` - Flag that may be used to enable more
verbose test system output. Note that it
does not also enable more verbose build
system output like the --verbose command
line option does.
"""
def __init__(self, arguments=None, executable=None,
match=TestCmd.match_exact, boost_build_path=None,
translate_suffixes=True, pass_toolset=True, use_test_config=True,
ignore_toolset_requirements=False, workdir="", pass_d0=False,
**keywords):
if not executable:
executable = os.getenv('B2')
if not executable:
executable = 'b2' if sys.platform not in ['win32', 'cygwin'] else 'b2.exe'
assert arguments.__class__ is not str
self.original_workdir = os.path.dirname(__file__)
if workdir and not os.path.isabs(workdir):
raise ("Parameter workdir <%s> must point to an absolute "
"directory: " % workdir)
self.last_build_timestamp = 0
self.translate_suffixes = translate_suffixes
self.use_test_config = use_test_config
self.set_toolset(get_toolset(), _pass_toolset=pass_toolset)
self.ignore_toolset_requirements = ignore_toolset_requirements
use_default_bjam = "--default-bjam" in sys.argv
if not use_default_bjam:
jam_build_dir = ""
# Find where jam_src is located. Try for the debug version if it is
# lying around.
srcdir = os.path.join(os.path.dirname(__file__), "..", "src")
dirs = [os.path.join(srcdir, "engine", jam_build_dir + ".debug"),
os.path.join(srcdir, "engine", jam_build_dir)]
for d in dirs:
if os.path.exists(d):
jam_build_dir = d
break
else:
print("Cannot find built Boost.Jam")
sys.exit(1)
verbosity = ["-d0", "--quiet"]
if not pass_d0:
verbosity = []
if "--verbose" in sys.argv:
keywords["verbose"] = True
verbosity = ["-d2"]
self.verbosity = verbosity
if boost_build_path is None:
boost_build_path = self.original_workdir + "/.."
program_list = []
if use_default_bjam:
program_list.append(executable)
else:
program_list.append(os.path.join(jam_build_dir, executable))
program_list.append('-sBOOST_BUILD_PATH="' + boost_build_path + '"')
if arguments:
program_list += arguments
TestCmd.TestCmd.__init__(self, program=program_list, match=match,
workdir=workdir, inpath=use_default_bjam, **keywords)
os.chdir(self.workdir)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.cleanup()
def cleanup(self):
try:
TestCmd.TestCmd.cleanup(self)
os.chdir(self.original_workdir)
except AttributeError:
# When this is called during TestCmd.TestCmd.__del__ we can have
# both 'TestCmd' and 'os' unavailable in our scope. Do nothing in
# this case.
pass
def set_toolset(self, toolset, target_os=None, _pass_toolset=True):
self.toolset = _pass_toolset and toolset or "gcc"
if not target_os and self.toolset.startswith("emscripten"):
target_os = "none"
self.target_os = target_os or host_os
self.expanded_toolset = expand_toolset(self.toolset, self.target_os)
self.pass_toolset = _pass_toolset
prepare_prefixes_and_suffixes(self.toolset, self.target_os)
def is_implib_expected(self):
return self.target_os in ["windows", "cygwin"] and not re.match(r'^clang(-linux)?(-[\d.]+)?$', self.toolset)
def is_pdb_expected(self):
return self.toolset == "msvc" or "-win" in self.toolset
#
# Methods that change the working directory's content.
#
def set_tree(self, tree_location):
# It is not possible to remove the current directory.
d = os.getcwd()
os.chdir(os.path.dirname(self.workdir))
shutil.rmtree(self.workdir, ignore_errors=False)
if not os.path.isabs(tree_location):
tree_location = os.path.join(self.original_workdir, tree_location)
shutil.copytree(tree_location, self.workdir)
os.chdir(d)
def make_writable(unused, dir, entries):
for e in entries:
name = os.path.join(dir, e)
os.chmod(name, os.stat(name).st_mode | 0o222)
for root, _, files in os.walk("."):
make_writable(None, root, files)
def write(self, file, content, wait=True):
nfile = self.native_file_name(file)
self.__makedirs(os.path.dirname(nfile), wait)
if not type(content) == bytes:
content = content.encode()
try:
with open(nfile, "wb") as f:
f.write(content)
except Exception as e:
annotation("failure","Could not create file '{}': {}".format(nfile, e))
annotate_stack_trace(level=3)
self.fail_test(1)
self.__ensure_newer_than_last_build(nfile)
def rename(self, src, dst):
src_name = self.native_file_name(src)
dst_name = self.native_file_name(dst)
os.rename(src_name, dst_name)
def copy(self, src, dst):
self.write(dst, self.read(src, binary=True))
def copy_timestamp(self, src, dst):
src_name = self.native_file_name(src)
dst_name = self.native_file_name(dst)
shutil.copystat(src_name, dst_name)
def copy_preserving_timestamp(self, src, dst):
src_name = self.native_file_name(src)
dst_name = self.native_file_name(dst)
shutil.copy2(src_name, dst_name)
def touch(self, names, wait=True):
if isstr(names):
names = [names]
for name in names:
path = self.native_file_name(name)
if wait:
self.__ensure_newer_than_last_build(path)
else:
os.utime(path, None)
def rm(self, names):
if not type(names) == list:
names = [names]
if names == ["."]:
# If we are deleting the entire workspace, there is no need to wait
# for a clock tick.
self.last_build_timestamp = 0
# Avoid attempts to remove the current directory.
os.chdir(self.original_workdir)
for name in names:
n = glob.glob(self.native_file_name(name))
if n: n = n[0]
if not n:
n = self.glob_file(name.replace("$toolset", self.expanded_toolset + "*")
)
if n:
if os.path.isdir(n):
shutil.rmtree(n, ignore_errors=False)
else:
os.unlink(n)
# Create working dir root again in case we removed it.
if not os.path.exists(self.workdir):
os.mkdir(self.workdir)
os.chdir(self.workdir)
def expand_toolset(self, name):
"""
Expands $toolset placeholder in the given file to the name of the
toolset currently being tested.
"""
self.write(name, self.read(name).replace("$toolset", self.expanded_toolset))
def dump_stdio(self):
annotation("STDOUT", self.stdout())
annotation("STDERR", self.stderr())
def run_build_system(self, extra_args=None, subdir="", stdout=None,
stderr="", status=0, match=None, match_filter=None, pass_toolset=None,
use_test_config=None, ignore_toolset_requirements=None,
expected_duration=None, **kw):
assert extra_args.__class__ is not str
if os.path.isabs(subdir):
raise ValueError(
"You must pass a relative directory to subdir <%s>." % subdir)
self.previous_tree, dummy = tree.build_tree(self.workdir)
self.wait_for_time_change_since_last_build()
if match is None:
match = self.match
if pass_toolset is None:
pass_toolset = self.pass_toolset
if use_test_config is None:
use_test_config = self.use_test_config
if ignore_toolset_requirements is None:
ignore_toolset_requirements = self.ignore_toolset_requirements
try:
kw["program"] = []
kw["program"] += self.program
if extra_args:
kw["program"] += extra_args
if not extra_args or not any(a.startswith("-j") for a in extra_args):
kw["program"] += ["-j1"]
if stdout is None and not any(a.startswith("-d") for a in kw["program"]):
kw["program"] += self.verbosity
if pass_toolset:
kw["program"].append("toolset=" + self.toolset)
if use_test_config:
kw["program"].append('--test-config="%s"' % os.path.join(
self.original_workdir, "test-config.jam"))
if ignore_toolset_requirements:
kw["program"].append("--ignore-toolset-requirements")
if "--python" in sys.argv:
# -z disables Python optimization mode.
# this enables type checking (all assert
# and if __debug__ statements).
kw["program"].extend(["--python", "-z"])
if "--stacktrace" in sys.argv:
kw["program"].append("--stacktrace")
kw["chdir"] = subdir
self.last_program_invocation = kw["program"]
build_time_start = time.time()
TestCmd.TestCmd.run(self, **kw)
build_time_finish = time.time()
except:
self.dump_stdio()
raise
old_last_build_timestamp = self.last_build_timestamp
self.tree, self.last_build_timestamp = tree.build_tree(self.workdir)
self.difference = tree.tree_difference(self.previous_tree, self.tree)
if self.difference.empty():
# If nothing has been changed by this build and sufficient time has
# passed since the last build that actually changed something,
# there is no need to wait for touched or newly created files to
# start getting newer timestamps than the currently existing ones.
self.last_build_timestamp = old_last_build_timestamp
self.difference.ignore_directories()
self.unexpected_difference = copy.deepcopy(self.difference)
if (status and self.status) is not None and self.status != status:
expect = ""
if status != 0:
expect = " (expected %d)" % status
annotation("failure", '"%s" returned %d%s' % (kw["program"],
self.status, expect))
annotation("reason", "unexpected status returned by bjam")
self.fail_test(1)
if stdout is not None:
self.do_diff('STDOUT', self.stdout(), stdout, match, match_filter)
# Intel tends to produce some messages to stderr which make tests fail.
intel_workaround = re.compile("^xi(link|lib): executing.*\n", re.M)
actual_stderr = re.sub(intel_workaround, "", self.stderr())
if stderr is not None:
self.do_diff('STDERR', actual_stderr, stderr, match, match_filter)
if expected_duration is not None:
actual_duration = build_time_finish - build_time_start
if actual_duration > expected_duration:
print("Test run lasted %f seconds while it was expected to "
"finish in under %f seconds." % (actual_duration,
expected_duration))
self.fail_test(1, dump_stdio=False)
def do_diff(self, what, actual, expected, matcher, match_filter):
actual_lines = actual.splitlines(keepends=True)
expected_lines = expected.splitlines(keepends=True)
if match_filter is not None:
actual_lines = list(filter(match_filter, actual_lines))
expected_lines = list(filter(match_filter, expected_lines))
match = matcher("".join(actual_lines), "".join(expected_lines))
filtered = " (filtered)"
else:
match = matcher(actual, expected)
filtered = ""
if match:
return
diff = "".join(ndiff(expected_lines, actual_lines))
annotation("Expected {}".format(what), expected)
annotation("Actual {}".format(what), actual)
if what.lower() == "stdout":
annotation("STDERR", self.stderr())
annotation("Difference in {}{}".format(what, filtered), diff)
self.fail_test(True, dump_stdio=False)
def glob_file(self, name):
name = self.adjust_name(name)
result = None
if hasattr(self, "difference"):
for f in (self.difference.added_files +
self.difference.modified_files +
self.difference.touched_files):
if fnmatch.fnmatch(f, name):
result = self.__native_file_name(f)
break
if not result:
result = glob.glob(self.__native_file_name(name))
if result:
result = result[0]
return result
def __read(self, name, binary=False):
try:
openMode = "r"
if binary:
openMode += "b"
elif sys.version_info[0] < 3:
openMode += "U"
f = open(name, openMode)
result = f.read()
f.close()
return result
except Exception as e:
annotation("failure", "Could not open '%s': %s" % (name, e))
annotate_stack_trace(level=3)
self.fail_test(1)
return ""
def read(self, name, binary=False):
name = self.glob_file(name)
return self.__read(name, binary=binary)
def read_and_strip(self, name):
if not self.glob_file(name):
return ""
f = open(self.glob_file(name), "rb")
lines = f.readlines()
f.close()
result = "\n".join(x.decode().rstrip() for x in lines)
if lines and lines[-1][-1] != "\n":
return result + "\n"
return result
def fail_test(self, condition, dump_difference=True, dump_stdio=True,
dump_stack=True):
if not condition:
return
if dump_difference and hasattr(self, "difference"):
f = StringIO()
self.difference.pprint(f)
annotation("changes caused by the last build command",
f.getvalue())
if dump_stdio:
self.dump_stdio()
if "--preserve" in sys.argv:
print()
print("*** Copying the state of working dir into 'failed_test' ***")
print()
path = os.path.join(self.original_workdir, "failed_test")
if os.path.isdir(path):
shutil.rmtree(path, ignore_errors=False)
elif os.path.exists(path):
raise "Path " + path + " already exists and is not a directory"
shutil.copytree(self.workdir, path)
print("The failed command was:")
print(" ".join(self.last_program_invocation))
if dump_stack:
annotate_stack_trace(level=2)
sys.exit(1)
# A number of methods below check expectations with actual difference
# between directory trees before and after a build. All the 'expect*'
# methods require exact names to be passed. All the 'ignore*' methods allow
# wildcards.
# All names can be either a string or a list of strings.
def expect_addition(self, names):
for name in self.adjust_names(names):
try:
glob_remove(self.unexpected_difference.added_files, name)
except:
annotation("failure", "File %s not added as expected" % name)
self.fail_test(1)
def ignore_addition(self, wildcard):
self.__ignore_elements(self.unexpected_difference.added_files,
wildcard)
def expect_removal(self, names):
for name in self.adjust_names(names):
try:
glob_remove(self.unexpected_difference.removed_files, name)
except:
annotation("failure", "File %s not removed as expected" % name)
self.fail_test(1)
def ignore_removal(self, wildcard):
self.__ignore_elements(self.unexpected_difference.removed_files,
wildcard)
def expect_modification(self, names):
for name in self.adjust_names(names):
try:
glob_remove(self.unexpected_difference.modified_files, name)
except:
annotation("failure", "File %s not modified as expected" %
name)
self.fail_test(1)
def ignore_modification(self, wildcard):
self.__ignore_elements(self.unexpected_difference.modified_files,
wildcard)
def expect_touch(self, names):
d = self.unexpected_difference
for name in self.adjust_names(names):
# We need to check both touched and modified files. The reason is
# that:
# (1) Windows binaries such as obj, exe or dll files have slight
# differences even with identical inputs due to Windows PE
# format headers containing an internal timestamp.
# (2) Intel's compiler for Linux has the same behaviour.
filesets = [d.modified_files, d.touched_files]
while filesets:
try:
glob_remove(filesets[-1], name)
break
except ValueError:
filesets.pop()
if not filesets:
annotation("failure", "File %s not touched as expected" % name)
self.fail_test(1)
def ignore_touch(self, wildcard):
self.__ignore_elements(self.unexpected_difference.touched_files,
wildcard)
def ignore(self, wildcard):
self.ignore_addition(wildcard)
self.ignore_removal(wildcard)
self.ignore_modification(wildcard)
self.ignore_touch(wildcard)
def expect_nothing(self, names):
for name in self.adjust_names(names):
if name in self.difference.added_files:
annotation("failure",
"File %s added, but no action was expected" % name)
self.fail_test(1)
if name in self.difference.removed_files:
annotation("failure",
"File %s removed, but no action was expected" % name)
self.fail_test(1)
pass
if name in self.difference.modified_files:
annotation("failure",
"File %s modified, but no action was expected" % name)
self.fail_test(1)
if name in self.difference.touched_files:
annotation("failure",
"File %s touched, but no action was expected" % name)
self.fail_test(1)
def __ignore_junk(self):
# Not totally sure about this change, but I do not see a good
# alternative.
if self.target_os == "windows":
self.ignore("*.ilk") # MSVC incremental linking files.
self.ignore("*.pdb") # MSVC program database files.
self.ignore("*.rsp") # Response files.
self.ignore("*.tds") # Borland debug symbols.
self.ignore("*.manifest") # MSVC DLL manifests.
self.ignore("bin/standalone/msvc/*/msvc-setup.bat")
# emscripten 'exe' is .js which is a laucnher for .wasm file
self.ignore("*.wasm")
# Debug builds of bjam built with gcc produce this profiling data.
self.ignore("gmon.out")
self.ignore("*/gmon.out")
# Boost Build's 'configure' functionality (unfinished at the time)
# produces this file.
self.ignore("bin/config.log")
self.ignore("bin/project-cache.jam")
# Compiled Python files created when running Python based Boost Build.
self.ignore("*.pyc")
# OSX/Darwin files and dirs.
self.ignore("*.dSYM/*")
def expect_nothing_more(self):
self.__ignore_junk()
if not self.unexpected_difference.empty():
annotation("failure", "Unexpected changes found")
output = StringIO()
self.unexpected_difference.pprint(output)
annotation("unexpected changes", output.getvalue())
self.fail_test(1)
def expect_output_lines(self, lines, expected=True):
self.__expect_lines(self.stdout(), lines, expected)
def expect_content_lines(self, filename, line, expected=True):
self.__expect_lines(self.read_and_strip(filename), line, expected)
def expect_content(self, name, content, exact=False):
actual = self.read(name)
content = content.replace("$toolset", self.expanded_toolset + "*")
matched = False
if exact:
matched = fnmatch.fnmatch(actual, content)
else:
def sorted_(z):
z.sort(key=lambda x: x.lower().replace("\\", "/"))
return z
actual_ = list(map(lambda x: sorted_(x.split()), actual.splitlines()))
content_ = list(map(lambda x: sorted_(x.split()), content.splitlines()))
if len(actual_) == len(content_):
matched = map(
lambda x, y: map(lambda n, p: fnmatch.fnmatch(n, p), x, y),
actual_, content_)
matched = reduce(
lambda x, y: x and reduce(
lambda a, b: a and b,
y, True),
matched, True)
if not matched:
print("Expected:\n")
print(content)
print("Got:\n")
print(actual)
self.fail_test(1)
# Internal methods.
def adjust_lib_name(self, name):
global lib_prefix
global dll_prefix
global implib_prefix
result = name
pos = name.rfind(".")
if pos != -1:
suffix = name[pos:]
prefix = {
".lib": lib_prefix,
".dll": dll_prefix,
".implib": implib_prefix,
}.get(suffix)
(head, tail) = os.path.split(name)
if prefix:
tail = prefix + tail
result = os.path.join(head, tail)
# If we want to use this name in a Jamfile, we better convert \ to /,
# as otherwise we would have to quote \.
result = result.replace("\\", "/")
return result
def adjust_suffix(self, name):
if not self.translate_suffixes:
return name
pos = name.rfind(".")
if pos == -1:
return name
suffix = name[pos:]
return name[:pos] + suffixes.get(suffix, suffix)
# Acceps either a string or a list of strings and returns a list of
# strings. Adjusts suffixes on all names.
def adjust_names(self, names):
if isstr(names):
names = [names]
r = map(self.adjust_lib_name, names)
r = map(self.adjust_suffix, r)
r = map(lambda x, t=self.expanded_toolset: x.replace("$toolset", t + "*"), r)
return list(r)
def adjust_name(self, name):
return self.adjust_names(name)[0]
def __native_file_name(self, name):
return os.path.normpath(os.path.join(self.workdir, *name.split("/")))
def native_file_name(self, name):
return self.__native_file_name(self.adjust_name(name))
def wait_for_time_change(self, path, touch):
"""
Wait for newly assigned file system modification timestamps for the
given path to become large enough for the timestamp difference to be
correctly recognized by both this Python based testing framework and
the Boost Jam executable being tested. May optionally touch the given
path to set its modification timestamp to the new value.
"""
self.__wait_for_time_change(path, touch, last_build_time=False)
def wait_for_time_change_since_last_build(self):
"""
Wait for newly assigned file system modification timestamps to
become large enough for the timestamp difference to be
correctly recognized by the Python based testing framework.
Does not care about Jam's timestamp resolution, since we
only need this to detect touched files.
"""
if self.last_build_timestamp:
timestamp_file = "timestamp-3df2f2317e15e4a9"
open(timestamp_file, "wb").close()
self.__wait_for_time_change_impl(timestamp_file,
self.last_build_timestamp,
self.__python_timestamp_resolution(timestamp_file, 0), 0)
os.unlink(timestamp_file)
def __build_timestamp_resolution(self):
"""
Returns the minimum path modification timestamp resolution supported
by the used Boost Jam executable.
"""
dir = tempfile.mkdtemp("bjam_version_info")
try:
jam_script = "timestamp_resolution.jam"
f = open(os.path.join(dir, jam_script), "w")
try:
f.write("EXIT $(JAM_TIMESTAMP_RESOLUTION) : 0 ;")
finally:
f.close()
p = subprocess.Popen([self.program[0], "-d0", "-f%s" % jam_script],
stdout=subprocess.PIPE, cwd=dir, universal_newlines=True)
out, err = p.communicate()
finally:
shutil.rmtree(dir, ignore_errors=False)
if p.returncode != 0:
raise TestEnvironmentError("Unexpected return code (%s) when "
"detecting Boost Jam's minimum supported path modification "
"timestamp resolution version information." % p.returncode)
if err:
raise TestEnvironmentError("Unexpected error output (%s) when "
"detecting Boost Jam's minimum supported path modification "
"timestamp resolution version information." % err)
r = re.match("([0-9]{2}):([0-9]{2}):([0-9]{2}\\.[0-9]{9})$", out)
if not r:
# Older Boost Jam versions did not report their minimum supported
# path modification timestamp resolution and did not actually
# support path modification timestamp resolutions finer than 1
# second.
# TODO: Phase this support out to avoid such fallback code from
# possibly covering up other problems.
return 1
if r.group(1) != "00" or r.group(2) != "00": # hours, minutes
raise TestEnvironmentError("Boost Jam with too coarse minimum "
"supported path modification timestamp resolution (%s:%s:%s)."
% (r.group(1), r.group(2), r.group(3)))
return float(r.group(3)) # seconds.nanoseconds
def __ensure_newer_than_last_build(self, path):
"""
Updates the given path's modification timestamp after waiting for the
newly assigned file system modification timestamp to become large
enough for the timestamp difference between it and the last build
timestamp to be correctly recognized by both this Python based testing
framework and the Boost Jam executable being tested. Does nothing if
there is no 'last build' information available.
"""
if self.last_build_timestamp:
self.__wait_for_time_change(path, touch=True, last_build_time=True)
def __expect_lines(self, data, lines, expected):
"""
Checks whether the given data contains the given lines.
Data may be specified as a single string containing text lines
separated by newline characters.
Lines may be specified in any of the following forms:
* Single string containing text lines separated by newlines - the
given lines are searched for in the given data without any extra
data lines between them.
* Container of strings containing text lines separated by newlines
- the given lines are searched for in the given data with extra
data lines allowed between lines belonging to different strings.
* Container of strings containing text lines separated by newlines
and containers containing strings - the same as above with the
internal containers containing strings being interpreted as if
all their content was joined together into a single string
separated by newlines.
A newline at the end of any multi-line lines string is interpreted as
an expected extra trailig empty line.
"""
# str.splitlines() trims at most one trailing newline while we want the
# trailing newline to indicate that there should be an extra empty line
# at the end.
def splitlines(x):