PageRenderTime 51ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/libraries/boost_1_55_0/tools/build/v2/test/BoostBuild.py

https://github.com/eescanaverino/hmailserver
Python | 1317 lines | 1186 code | 41 blank | 90 comment | 52 complexity | 48dfad574a1261bd077f22cda6317fb7 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. # Copyright 2002-2005 Vladimir Prus.
  2. # Copyright 2002-2003 Dave Abrahams.
  3. # Copyright 2006 Rene Rivera.
  4. # Distributed under the Boost Software License, Version 1.0.
  5. # (See accompanying file LICENSE_1_0.txt or copy at
  6. # http://www.boost.org/LICENSE_1_0.txt)
  7. import TestCmd
  8. import copy
  9. import fnmatch
  10. import glob
  11. import math
  12. import os
  13. import os.path
  14. import re
  15. import shutil
  16. import StringIO
  17. import subprocess
  18. import sys
  19. import tempfile
  20. import time
  21. import traceback
  22. import tree
  23. import types
  24. from xml.sax.saxutils import escape
  25. class TestEnvironmentError(Exception):
  26. pass
  27. annotations = []
  28. def print_annotation(name, value, xml):
  29. """Writes some named bits of information about the current test run."""
  30. if xml:
  31. print escape(name) + " {{{"
  32. print escape(value)
  33. print "}}}"
  34. else:
  35. print name + " {{{"
  36. print value
  37. print "}}}"
  38. def flush_annotations(xml=0):
  39. global annotations
  40. for ann in annotations:
  41. print_annotation(ann[0], ann[1], xml)
  42. annotations = []
  43. def clear_annotations():
  44. global annotations
  45. annotations = []
  46. defer_annotations = 0
  47. def set_defer_annotations(n):
  48. global defer_annotations
  49. defer_annotations = n
  50. def annotate_stack_trace(tb=None):
  51. if tb:
  52. trace = TestCmd.caller(traceback.extract_tb(tb), 0)
  53. else:
  54. trace = TestCmd.caller(traceback.extract_stack(), 1)
  55. annotation("stacktrace", trace)
  56. def annotation(name, value):
  57. """Records an annotation about the test run."""
  58. annotations.append((name, value))
  59. if not defer_annotations:
  60. flush_annotations()
  61. def get_toolset():
  62. toolset = None
  63. for arg in sys.argv[1:]:
  64. if not arg.startswith("-"):
  65. toolset = arg
  66. return toolset or "gcc"
  67. # Detect the host OS.
  68. cygwin = hasattr(os, "uname") and os.uname()[0].lower().startswith("cygwin")
  69. windows = cygwin or os.environ.get("OS", "").lower().startswith("windows")
  70. def prepare_prefixes_and_suffixes(toolset):
  71. prepare_suffix_map(toolset)
  72. prepare_library_prefix(toolset)
  73. def prepare_suffix_map(toolset):
  74. """
  75. Set up suffix translation performed by the Boost Build testing framework
  76. to accomodate different toolsets generating targets of the same type using
  77. different filename extensions (suffixes).
  78. """
  79. global suffixes
  80. suffixes = {}
  81. if windows:
  82. if toolset == "gcc":
  83. suffixes[".lib"] = ".a" # mingw static libs use suffix ".a".
  84. suffixes[".obj"] = ".o"
  85. if cygwin:
  86. suffixes[".implib"] = ".lib.a"
  87. else:
  88. suffixes[".implib"] = ".lib"
  89. else:
  90. suffixes[".exe"] = ""
  91. suffixes[".dll"] = ".so"
  92. suffixes[".lib"] = ".a"
  93. suffixes[".obj"] = ".o"
  94. suffixes[".implib"] = ".no_implib_files_on_this_platform"
  95. if hasattr(os, "uname") and os.uname()[0] == "Darwin":
  96. suffixes[".dll"] = ".dylib"
  97. def prepare_library_prefix(toolset):
  98. """
  99. Setup whether Boost Build is expected to automatically prepend prefixes
  100. to its built library targets.
  101. """
  102. global lib_prefix
  103. lib_prefix = "lib"
  104. global dll_prefix
  105. if cygwin:
  106. dll_prefix = "cyg"
  107. elif windows and toolset != "gcc":
  108. dll_prefix = None
  109. else:
  110. dll_prefix = "lib"
  111. def re_remove(sequence, regex):
  112. me = re.compile(regex)
  113. result = filter(lambda x: me.match(x), sequence)
  114. if not result:
  115. raise ValueError()
  116. for r in result:
  117. sequence.remove(r)
  118. def glob_remove(sequence, pattern):
  119. result = fnmatch.filter(sequence, pattern)
  120. if not result:
  121. raise ValueError()
  122. for r in result:
  123. sequence.remove(r)
  124. class Tester(TestCmd.TestCmd):
  125. """Main tester class for Boost Build.
  126. Optional arguments:
  127. `arguments` - Arguments passed to the run executable.
  128. `executable` - Name of the executable to invoke.
  129. `match` - Function to use for compating actual and
  130. expected file contents.
  131. `boost_build_path` - Boost build path to be passed to the run
  132. executable.
  133. `translate_suffixes` - Whether to update suffixes on the the file
  134. names passed from the test script so they
  135. match those actually created by the current
  136. toolset. For example, static library files
  137. are specified by using the .lib suffix but
  138. when the "gcc" toolset is used it actually
  139. creates them using the .a suffix.
  140. `pass_toolset` - Whether the test system should pass the
  141. specified toolset to the run executable.
  142. `use_test_config` - Whether the test system should tell the run
  143. executable to read in the test_config.jam
  144. configuration file.
  145. `ignore_toolset_requirements` - Whether the test system should tell the run
  146. executable to ignore toolset requirements.
  147. `workdir` - Absolute directory where the test will be
  148. run from.
  149. `pass_d0` - If set, when tests are not explicitly run
  150. in verbose mode, they are run as silent
  151. (-d0 & --quiet Boost Jam options).
  152. Optional arguments inherited from the base class:
  153. `description` - Test description string displayed in case
  154. of a failed test.
  155. `subdir` - List of subdirectories to automatically
  156. create under the working directory. Each
  157. subdirectory needs to be specified
  158. separately, parent coming before its child.
  159. `verbose` - Flag that may be used to enable more
  160. verbose test system output. Note that it
  161. does not also enable more verbose build
  162. system output like the --verbose command
  163. line option does.
  164. """
  165. def __init__(self, arguments=None, executable="bjam",
  166. match=TestCmd.match_exact, boost_build_path=None,
  167. translate_suffixes=True, pass_toolset=True, use_test_config=True,
  168. ignore_toolset_requirements=True, workdir="", pass_d0=True,
  169. **keywords):
  170. assert arguments.__class__ is not str
  171. self.original_workdir = os.getcwd()
  172. if workdir and not os.path.isabs(workdir):
  173. raise ("Parameter workdir <%s> must point to an absolute "
  174. "directory: " % workdir)
  175. self.last_build_timestamp = 0
  176. self.translate_suffixes = translate_suffixes
  177. self.use_test_config = use_test_config
  178. self.toolset = get_toolset()
  179. self.pass_toolset = pass_toolset
  180. self.ignore_toolset_requirements = ignore_toolset_requirements
  181. prepare_prefixes_and_suffixes(pass_toolset and self.toolset or "gcc")
  182. use_default_bjam = "--default-bjam" in sys.argv
  183. if not use_default_bjam:
  184. jam_build_dir = ""
  185. if os.name == "nt":
  186. jam_build_dir = "bin.ntx86"
  187. elif (os.name == "posix") and os.__dict__.has_key("uname"):
  188. if os.uname()[0].lower().startswith("cygwin"):
  189. jam_build_dir = "bin.cygwinx86"
  190. if ("TMP" in os.environ and
  191. os.environ["TMP"].find("~") != -1):
  192. print("Setting $TMP to /tmp to get around problem "
  193. "with short path names")
  194. os.environ["TMP"] = "/tmp"
  195. elif os.uname()[0] == "Linux":
  196. cpu = os.uname()[4]
  197. if re.match("i.86", cpu):
  198. jam_build_dir = "bin.linuxx86"
  199. else:
  200. jam_build_dir = "bin.linux" + os.uname()[4]
  201. elif os.uname()[0] == "SunOS":
  202. jam_build_dir = "bin.solaris"
  203. elif os.uname()[0] == "Darwin":
  204. if os.uname()[4] == "i386":
  205. jam_build_dir = "bin.macosxx86"
  206. else:
  207. jam_build_dir = "bin.macosxppc"
  208. elif os.uname()[0] == "AIX":
  209. jam_build_dir = "bin.aix"
  210. elif os.uname()[0] == "IRIX64":
  211. jam_build_dir = "bin.irix"
  212. elif os.uname()[0] == "FreeBSD":
  213. jam_build_dir = "bin.freebsd"
  214. elif os.uname()[0] == "OSF1":
  215. jam_build_dir = "bin.osf"
  216. else:
  217. raise ("Do not know directory where Jam is built for this "
  218. "system: %s/%s" % (os.name, os.uname()[0]))
  219. else:
  220. raise ("Do not know directory where Jam is built for this "
  221. "system: %s" % os.name)
  222. # Find where jam_src is located. Try for the debug version if it is
  223. # lying around.
  224. dirs = [os.path.join("..", "engine", jam_build_dir + ".debug"),
  225. os.path.join("..", "engine", jam_build_dir)]
  226. for d in dirs:
  227. if os.path.exists(d):
  228. jam_build_dir = d
  229. break
  230. else:
  231. print("Cannot find built Boost.Jam")
  232. sys.exit(1)
  233. verbosity = ["-d0", "--quiet"]
  234. if not pass_d0:
  235. verbosity = []
  236. if "--verbose" in sys.argv:
  237. keywords["verbose"] = True
  238. verbosity = ["-d+2"]
  239. if boost_build_path is None:
  240. boost_build_path = self.original_workdir + "/.."
  241. program_list = []
  242. if use_default_bjam:
  243. program_list.append(executable)
  244. else:
  245. program_list.append(os.path.join(jam_build_dir, executable))
  246. program_list.append('-sBOOST_BUILD_PATH="' + boost_build_path + '"')
  247. if verbosity:
  248. program_list += verbosity
  249. if arguments:
  250. program_list += arguments
  251. TestCmd.TestCmd.__init__(self, program=program_list, match=match,
  252. workdir=workdir, inpath=use_default_bjam, **keywords)
  253. os.chdir(self.workdir)
  254. def cleanup(self):
  255. try:
  256. TestCmd.TestCmd.cleanup(self)
  257. os.chdir(self.original_workdir)
  258. except AttributeError:
  259. # When this is called during TestCmd.TestCmd.__del__ we can have
  260. # both 'TestCmd' and 'os' unavailable in our scope. Do nothing in
  261. # this case.
  262. pass
  263. #
  264. # Methods that change the working directory's content.
  265. #
  266. def set_tree(self, tree_location):
  267. # It is not possible to remove the current directory.
  268. d = os.getcwd()
  269. os.chdir(os.path.dirname(self.workdir))
  270. shutil.rmtree(self.workdir, ignore_errors=False)
  271. if not os.path.isabs(tree_location):
  272. tree_location = os.path.join(self.original_workdir, tree_location)
  273. shutil.copytree(tree_location, self.workdir)
  274. os.chdir(d)
  275. def make_writable(unused, dir, entries):
  276. for e in entries:
  277. name = os.path.join(dir, e)
  278. os.chmod(name, os.stat(name).st_mode | 0222)
  279. os.path.walk(".", make_writable, None)
  280. def write(self, file, content, wait=True):
  281. nfile = self.native_file_name(file)
  282. self.__makedirs(os.path.dirname(nfile), wait)
  283. f = open(nfile, "wb")
  284. try:
  285. f.write(content)
  286. finally:
  287. f.close()
  288. self.__ensure_newer_than_last_build(nfile)
  289. def copy(self, src, dst):
  290. try:
  291. self.write(dst, self.read(src, 1))
  292. except:
  293. self.fail_test(1)
  294. def copy_preserving_timestamp(self, src, dst):
  295. src_name = self.native_file_name(src)
  296. dst_name = self.native_file_name(dst)
  297. stats = os.stat(src_name)
  298. self.write(dst, self.read(src, 1))
  299. os.utime(dst_name, (stats.st_atime, stats.st_mtime))
  300. def touch(self, names, wait=True):
  301. if names.__class__ is str:
  302. names = [names]
  303. for name in names:
  304. path = self.native_file_name(name)
  305. if wait:
  306. self.__ensure_newer_than_last_build(path)
  307. else:
  308. os.utime(path, None)
  309. def rm(self, names):
  310. if not type(names) == types.ListType:
  311. names = [names]
  312. if names == ["."]:
  313. # If we are deleting the entire workspace, there is no need to wait
  314. # for a clock tick.
  315. self.last_build_timestamp = 0
  316. # Avoid attempts to remove the current directory.
  317. os.chdir(self.original_workdir)
  318. for name in names:
  319. n = glob.glob(self.native_file_name(name))
  320. if n: n = n[0]
  321. if not n:
  322. n = self.glob_file(name.replace("$toolset", self.toolset + "*")
  323. )
  324. if n:
  325. if os.path.isdir(n):
  326. shutil.rmtree(n, ignore_errors=False)
  327. else:
  328. os.unlink(n)
  329. # Create working dir root again in case we removed it.
  330. if not os.path.exists(self.workdir):
  331. os.mkdir(self.workdir)
  332. os.chdir(self.workdir)
  333. def expand_toolset(self, name):
  334. """
  335. Expands $toolset placeholder in the given file to the name of the
  336. toolset currently being tested.
  337. """
  338. self.write(name, self.read(name).replace("$toolset", self.toolset))
  339. def dump_stdio(self):
  340. annotation("STDOUT", self.stdout())
  341. annotation("STDERR", self.stderr())
  342. def run_build_system(self, extra_args=None, subdir="", stdout=None,
  343. stderr="", status=0, match=None, pass_toolset=None,
  344. use_test_config=None, ignore_toolset_requirements=None,
  345. expected_duration=None, **kw):
  346. assert extra_args.__class__ is not str
  347. if os.path.isabs(subdir):
  348. print("You must pass a relative directory to subdir <%s>." % subdir
  349. )
  350. return
  351. self.previous_tree, dummy = tree.build_tree(self.workdir)
  352. if match is None:
  353. match = self.match
  354. if pass_toolset is None:
  355. pass_toolset = self.pass_toolset
  356. if use_test_config is None:
  357. use_test_config = self.use_test_config
  358. if ignore_toolset_requirements is None:
  359. ignore_toolset_requirements = self.ignore_toolset_requirements
  360. try:
  361. kw["program"] = []
  362. kw["program"] += self.program
  363. if extra_args:
  364. kw["program"] += extra_args
  365. if pass_toolset:
  366. kw["program"].append("toolset=" + self.toolset)
  367. if use_test_config:
  368. kw["program"].append('--test-config="%s"' % os.path.join(
  369. self.original_workdir, "test-config.jam"))
  370. if ignore_toolset_requirements:
  371. kw["program"].append("--ignore-toolset-requirements")
  372. if "--python" in sys.argv:
  373. kw["program"].append("--python")
  374. kw["chdir"] = subdir
  375. self.last_program_invocation = kw["program"]
  376. build_time_start = time.time()
  377. apply(TestCmd.TestCmd.run, [self], kw)
  378. build_time_finish = time.time()
  379. except:
  380. self.dump_stdio()
  381. raise
  382. old_last_build_timestamp = self.last_build_timestamp
  383. self.tree, self.last_build_timestamp = tree.build_tree(self.workdir)
  384. self.difference = tree.tree_difference(self.previous_tree, self.tree)
  385. if self.difference.empty():
  386. # If nothing has been changed by this build and sufficient time has
  387. # passed since the last build that actually changed something,
  388. # there is no need to wait for touched or newly created files to
  389. # start getting newer timestamps than the currently existing ones.
  390. self.last_build_timestamp = old_last_build_timestamp
  391. self.difference.ignore_directories()
  392. self.unexpected_difference = copy.deepcopy(self.difference)
  393. if (status and self.status) is not None and self.status != status:
  394. expect = ""
  395. if status != 0:
  396. expect = " (expected %d)" % status
  397. annotation("failure", '"%s" returned %d%s' % (kw["program"],
  398. self.status, expect))
  399. annotation("reason", "unexpected status returned by bjam")
  400. self.fail_test(1)
  401. if stdout is not None and not match(self.stdout(), stdout):
  402. annotation("failure", "Unexpected stdout")
  403. annotation("Expected STDOUT", stdout)
  404. annotation("Actual STDOUT", self.stdout())
  405. stderr = self.stderr()
  406. if stderr:
  407. annotation("STDERR", stderr)
  408. self.maybe_do_diff(self.stdout(), stdout)
  409. self.fail_test(1, dump_stdio=False)
  410. # Intel tends to produce some messages to stderr which make tests fail.
  411. intel_workaround = re.compile("^xi(link|lib): executing.*\n", re.M)
  412. actual_stderr = re.sub(intel_workaround, "", self.stderr())
  413. if stderr is not None and not match(actual_stderr, stderr):
  414. annotation("failure", "Unexpected stderr")
  415. annotation("Expected STDERR", stderr)
  416. annotation("Actual STDERR", self.stderr())
  417. annotation("STDOUT", self.stdout())
  418. self.maybe_do_diff(actual_stderr, stderr)
  419. self.fail_test(1, dump_stdio=False)
  420. if expected_duration is not None:
  421. actual_duration = build_time_finish - build_time_start
  422. if actual_duration > expected_duration:
  423. print("Test run lasted %f seconds while it was expected to "
  424. "finish in under %f seconds." % (actual_duration,
  425. expected_duration))
  426. self.fail_test(1, dump_stdio=False)
  427. def glob_file(self, name):
  428. result = None
  429. if hasattr(self, "difference"):
  430. for f in (self.difference.added_files +
  431. self.difference.modified_files +
  432. self.difference.touched_files):
  433. if fnmatch.fnmatch(f, name):
  434. result = self.native_file_name(f)
  435. break
  436. if not result:
  437. result = glob.glob(self.native_file_name(name))
  438. if result:
  439. result = result[0]
  440. return result
  441. def read(self, name, binary=False):
  442. try:
  443. if self.toolset:
  444. name = name.replace("$toolset", self.toolset + "*")
  445. name = self.glob_file(name)
  446. openMode = "r"
  447. if binary:
  448. openMode += "b"
  449. else:
  450. openMode += "U"
  451. f = open(name, openMode)
  452. result = f.read()
  453. f.close()
  454. return result
  455. except:
  456. annotation("failure", "Could not open '%s'" % name)
  457. self.fail_test(1)
  458. return ""
  459. def read_and_strip(self, name):
  460. if not self.glob_file(name):
  461. return ""
  462. f = open(self.glob_file(name), "rb")
  463. lines = f.readlines()
  464. f.close()
  465. result = "\n".join(x.rstrip() for x in lines)
  466. if lines and lines[-1][-1] != "\n":
  467. return result + "\n"
  468. return result
  469. def fail_test(self, condition, dump_difference=True, dump_stdio=True,
  470. dump_stack=True):
  471. if not condition:
  472. return
  473. if dump_difference and hasattr(self, "difference"):
  474. f = StringIO.StringIO()
  475. self.difference.pprint(f)
  476. annotation("changes caused by the last build command",
  477. f.getvalue())
  478. if dump_stdio:
  479. self.dump_stdio()
  480. if "--preserve" in sys.argv:
  481. print
  482. print "*** Copying the state of working dir into 'failed_test' ***"
  483. print
  484. path = os.path.join(self.original_workdir, "failed_test")
  485. if os.path.isdir(path):
  486. shutil.rmtree(path, ignore_errors=False)
  487. elif os.path.exists(path):
  488. raise "Path " + path + " already exists and is not a directory"
  489. shutil.copytree(self.workdir, path)
  490. print "The failed command was:"
  491. print " ".join(self.last_program_invocation)
  492. if dump_stack:
  493. annotate_stack_trace()
  494. sys.exit(1)
  495. # A number of methods below check expectations with actual difference
  496. # between directory trees before and after a build. All the 'expect*'
  497. # methods require exact names to be passed. All the 'ignore*' methods allow
  498. # wildcards.
  499. # All names can be either a string or a list of strings.
  500. def expect_addition(self, names):
  501. for name in self.adjust_names(names):
  502. try:
  503. glob_remove(self.unexpected_difference.added_files, name)
  504. except:
  505. annotation("failure", "File %s not added as expected" % name)
  506. self.fail_test(1)
  507. def ignore_addition(self, wildcard):
  508. self.__ignore_elements(self.unexpected_difference.added_files,
  509. wildcard)
  510. def expect_removal(self, names):
  511. for name in self.adjust_names(names):
  512. try:
  513. glob_remove(self.unexpected_difference.removed_files, name)
  514. except:
  515. annotation("failure", "File %s not removed as expected" % name)
  516. self.fail_test(1)
  517. def ignore_removal(self, wildcard):
  518. self.__ignore_elements(self.unexpected_difference.removed_files,
  519. wildcard)
  520. def expect_modification(self, names):
  521. for name in self.adjust_names(names):
  522. try:
  523. glob_remove(self.unexpected_difference.modified_files, name)
  524. except:
  525. annotation("failure", "File %s not modified as expected" %
  526. name)
  527. self.fail_test(1)
  528. def ignore_modification(self, wildcard):
  529. self.__ignore_elements(self.unexpected_difference.modified_files,
  530. wildcard)
  531. def expect_touch(self, names):
  532. d = self.unexpected_difference
  533. for name in self.adjust_names(names):
  534. # We need to check both touched and modified files. The reason is
  535. # that:
  536. # (1) Windows binaries such as obj, exe or dll files have slight
  537. # differences even with identical inputs due to Windows PE
  538. # format headers containing an internal timestamp.
  539. # (2) Intel's compiler for Linux has the same behaviour.
  540. filesets = [d.modified_files, d.touched_files]
  541. while filesets:
  542. try:
  543. glob_remove(filesets[-1], name)
  544. break
  545. except ValueError:
  546. filesets.pop()
  547. if not filesets:
  548. annotation("failure", "File %s not touched as expected" % name)
  549. self.fail_test(1)
  550. def ignore_touch(self, wildcard):
  551. self.__ignore_elements(self.unexpected_difference.touched_files,
  552. wildcard)
  553. def ignore(self, wildcard):
  554. self.ignore_addition(wildcard)
  555. self.ignore_removal(wildcard)
  556. self.ignore_modification(wildcard)
  557. self.ignore_touch(wildcard)
  558. def expect_nothing(self, names):
  559. for name in self.adjust_names(names):
  560. if name in self.difference.added_files:
  561. annotation("failure",
  562. "File %s added, but no action was expected" % name)
  563. self.fail_test(1)
  564. if name in self.difference.removed_files:
  565. annotation("failure",
  566. "File %s removed, but no action was expected" % name)
  567. self.fail_test(1)
  568. pass
  569. if name in self.difference.modified_files:
  570. annotation("failure",
  571. "File %s modified, but no action was expected" % name)
  572. self.fail_test(1)
  573. if name in self.difference.touched_files:
  574. annotation("failure",
  575. "File %s touched, but no action was expected" % name)
  576. self.fail_test(1)
  577. def expect_nothing_more(self):
  578. # Not totally sure about this change, but I do not see a good
  579. # alternative.
  580. if windows:
  581. self.ignore("*.ilk") # MSVC incremental linking files.
  582. self.ignore("*.pdb") # MSVC program database files.
  583. self.ignore("*.rsp") # Response files.
  584. self.ignore("*.tds") # Borland debug symbols.
  585. self.ignore("*.manifest") # MSVC DLL manifests.
  586. # Debug builds of bjam built with gcc produce this profiling data.
  587. self.ignore("gmon.out")
  588. self.ignore("*/gmon.out")
  589. # Boost Build's 'configure' functionality (unfinished at the time)
  590. # produces this file.
  591. self.ignore("bin/config.log")
  592. self.ignore("bin/project-cache.jam")
  593. # Compiled Python files created when running Python based Boost Build.
  594. self.ignore("*.pyc")
  595. if not self.unexpected_difference.empty():
  596. annotation("failure", "Unexpected changes found")
  597. output = StringIO.StringIO()
  598. self.unexpected_difference.pprint(output)
  599. annotation("unexpected changes", output.getvalue())
  600. self.fail_test(1)
  601. def expect_output_lines(self, lines, expected=True):
  602. self.__expect_lines(self.stdout(), lines, expected)
  603. def expect_content_lines(self, filename, line, expected=True):
  604. self.__expect_lines(self.__read_file(filename), line, expected)
  605. def expect_content(self, name, content, exact=False):
  606. actual = self.__read_file(name, exact)
  607. content = content.replace("$toolset", self.toolset + "*")
  608. matched = False
  609. if exact:
  610. matched = fnmatch.fnmatch(actual, content)
  611. else:
  612. def sorted_(x):
  613. x.sort()
  614. return x
  615. actual_ = map(lambda x: sorted_(x.split()), actual.splitlines())
  616. content_ = map(lambda x: sorted_(x.split()), content.splitlines())
  617. if len(actual_) == len(content_):
  618. matched = map(
  619. lambda x, y: map(lambda n, p: fnmatch.fnmatch(n, p), x, y),
  620. actual_, content_)
  621. matched = reduce(
  622. lambda x, y: x and reduce(
  623. lambda a, b: a and b,
  624. y),
  625. matched)
  626. if not matched:
  627. print "Expected:\n"
  628. print content
  629. print "Got:\n"
  630. print actual
  631. self.fail_test(1)
  632. def maybe_do_diff(self, actual, expected):
  633. if os.environ.get("DO_DIFF"):
  634. e = tempfile.mktemp("expected")
  635. a = tempfile.mktemp("actual")
  636. f = open(e, "w")
  637. f.write(expected)
  638. f.close()
  639. f = open(a, "w")
  640. f.write(actual)
  641. f.close()
  642. print("DIFFERENCE")
  643. # Current diff should return 1 to indicate 'different input files'
  644. # but some older diff versions may return 0 and depending on the
  645. # exact Python/OS platform version, os.system() call may gobble up
  646. # the external process's return code and return 0 itself.
  647. if os.system('diff -u "%s" "%s"' % (e, a)) not in [0, 1]:
  648. print('Unable to compute difference: diff -u "%s" "%s"' % (e, a
  649. ))
  650. os.unlink(e)
  651. os.unlink(a)
  652. else:
  653. print("Set environmental variable 'DO_DIFF' to examine the "
  654. "difference.")
  655. # Internal methods.
  656. def adjust_lib_name(self, name):
  657. global lib_prefix
  658. global dll_prefix
  659. result = name
  660. pos = name.rfind(".")
  661. if pos != -1:
  662. suffix = name[pos:]
  663. if suffix == ".lib":
  664. (head, tail) = os.path.split(name)
  665. if lib_prefix:
  666. tail = lib_prefix + tail
  667. result = os.path.join(head, tail)
  668. elif suffix == ".dll":
  669. (head, tail) = os.path.split(name)
  670. if dll_prefix:
  671. tail = dll_prefix + tail
  672. result = os.path.join(head, tail)
  673. # If we want to use this name in a Jamfile, we better convert \ to /,
  674. # as otherwise we would have to quote \.
  675. result = result.replace("\\", "/")
  676. return result
  677. def adjust_suffix(self, name):
  678. if not self.translate_suffixes:
  679. return name
  680. pos = name.rfind(".")
  681. if pos == -1:
  682. return name
  683. suffix = name[pos:]
  684. return name[:pos] + suffixes.get(suffix, suffix)
  685. # Acceps either a string or a list of strings and returns a list of
  686. # strings. Adjusts suffixes on all names.
  687. def adjust_names(self, names):
  688. if names.__class__ is str:
  689. names = [names]
  690. r = map(self.adjust_lib_name, names)
  691. r = map(self.adjust_suffix, r)
  692. r = map(lambda x, t=self.toolset: x.replace("$toolset", t + "*"), r)
  693. return r
  694. def native_file_name(self, name):
  695. name = self.adjust_names(name)[0]
  696. return os.path.normpath(os.path.join(self.workdir, *name.split("/")))
  697. def wait_for_time_change(self, path, touch):
  698. """
  699. Wait for newly assigned file system modification timestamps for the
  700. given path to become large enough for the timestamp difference to be
  701. correctly recognized by both this Python based testing framework and
  702. the Boost Jam executable being tested. May optionally touch the given
  703. path to set its modification timestamp to the new value.
  704. """
  705. self.__wait_for_time_change(path, touch, last_build_time=False)
  706. def __build_timestamp_resolution(self):
  707. """
  708. Returns the minimum path modification timestamp resolution supported
  709. by the used Boost Jam executable.
  710. """
  711. dir = tempfile.mkdtemp("bjam_version_info")
  712. try:
  713. jam_script = "timestamp_resolution.jam"
  714. f = open(os.path.join(dir, jam_script), "w")
  715. try:
  716. f.write("EXIT $(JAM_TIMESTAMP_RESOLUTION) : 0 ;")
  717. finally:
  718. f.close()
  719. p = subprocess.Popen([self.program[0], "-d0", "-f%s" % jam_script],
  720. stdout=subprocess.PIPE, cwd=dir, universal_newlines=True)
  721. out, err = p.communicate()
  722. finally:
  723. shutil.rmtree(dir, ignore_errors=False)
  724. if p.returncode != 0:
  725. raise TestEnvironmentError("Unexpected return code (%s) when "
  726. "detecting Boost Jam's minimum supported path modification "
  727. "timestamp resolution version information." % p.returncode)
  728. if err:
  729. raise TestEnvironmentError("Unexpected error output (%s) when "
  730. "detecting Boost Jam's minimum supported path modification "
  731. "timestamp resolution version information." % err)
  732. r = re.match("([0-9]{2}):([0-9]{2}):([0-9]{2}\\.[0-9]{9})$", out)
  733. if not r:
  734. # Older Boost Jam versions did not report their minimum supported
  735. # path modification timestamp resolution and did not actually
  736. # support path modification timestamp resolutions finer than 1
  737. # second.
  738. # TODO: Phase this support out to avoid such fallback code from
  739. # possibly covering up other problems.
  740. return 1
  741. if r.group(1) != "00" or r.group(2) != "00": # hours, minutes
  742. raise TestEnvironmentError("Boost Jam with too coarse minimum "
  743. "supported path modification timestamp resolution (%s:%s:%s)."
  744. % (r.group(1), r.group(2), r.group(3)))
  745. return float(r.group(3)) # seconds.nanoseconds
  746. def __ensure_newer_than_last_build(self, path):
  747. """
  748. Updates the given path's modification timestamp after waiting for the
  749. newly assigned file system modification timestamp to become large
  750. enough for the timestamp difference between it and the last build
  751. timestamp to be correctly recognized by both this Python based testing
  752. framework and the Boost Jam executable being tested. Does nothing if
  753. there is no 'last build' information available.
  754. """
  755. if self.last_build_timestamp:
  756. self.__wait_for_time_change(path, touch=True, last_build_time=True)
  757. def __expect_lines(self, data, lines, expected):
  758. """
  759. Checks whether the given data contains the given lines.
  760. Data may be specified as a single string containing text lines
  761. separated by newline characters.
  762. Lines may be specified in any of the following forms:
  763. * Single string containing text lines separated by newlines - the
  764. given lines are searched for in the given data without any extra
  765. data lines between them.
  766. * Container of strings containing text lines separated by newlines
  767. - the given lines are searched for in the given data with extra
  768. data lines allowed between lines belonging to different strings.
  769. * Container of strings containing text lines separated by newlines
  770. and containers containing strings - the same as above with the
  771. internal containers containing strings being interpreted as if
  772. all their content was joined together into a single string
  773. separated by newlines.
  774. A newline at the end of any multi-line lines string is interpreted as
  775. an expected extra trailig empty line.
  776. """
  777. # str.splitlines() trims at most one trailing newline while we want the
  778. # trailing newline to indicate that there should be an extra empty line
  779. # at the end.
  780. splitlines = lambda x : (x + "\n").splitlines()
  781. if data is None:
  782. data = []
  783. elif data.__class__ is str:
  784. data = splitlines(data)
  785. if lines.__class__ is str:
  786. lines = [splitlines(lines)]
  787. else:
  788. expanded = []
  789. for x in lines:
  790. if x.__class__ is str:
  791. x = splitlines(x)
  792. expanded.append(x)
  793. lines = expanded
  794. if _contains_lines(data, lines) != bool(expected):
  795. output = []
  796. if expected:
  797. output = ["Did not find expected lines:"]
  798. else:
  799. output = ["Found unexpected lines:"]
  800. first = True
  801. for line_sequence in lines:
  802. if line_sequence:
  803. if first:
  804. first = False
  805. else:
  806. output.append("...")
  807. output.extend(" > " + line for line in line_sequence)
  808. output.append("in output:")
  809. output.extend(" > " + line for line in data)
  810. annotation("failure", "\n".join(output))
  811. self.fail_test(1)
  812. def __ignore_elements(self, list, wildcard):
  813. """Removes in-place 'list' elements matching the given 'wildcard'."""
  814. list[:] = filter(lambda x, w=wildcard: not fnmatch.fnmatch(x, w), list)
  815. def __makedirs(self, path, wait):
  816. """
  817. Creates a folder with the given path, together with any missing
  818. parent folders. If WAIT is set, makes sure any newly created folders
  819. have modification timestamps newer than the ones left behind by the
  820. last build run.
  821. """
  822. try:
  823. if wait:
  824. stack = []
  825. while path and path not in stack and not os.path.isdir(path):
  826. stack.append(path)
  827. path = os.path.dirname(path)
  828. while stack:
  829. path = stack.pop()
  830. os.mkdir(path)
  831. self.__ensure_newer_than_last_build(path)
  832. else:
  833. os.makedirs(path)
  834. except Exception:
  835. pass
  836. def __python_timestamp_resolution(self, path, minimum_resolution):
  837. """
  838. Returns the modification timestamp resolution for the given path
  839. supported by the used Python interpreter/OS/filesystem combination.
  840. Will not check for resolutions less than the given minimum value. Will
  841. change the path's modification timestamp in the process.
  842. Return values:
  843. 0 - nanosecond resolution supported
  844. positive decimal - timestamp resolution in seconds
  845. """
  846. # Note on Python's floating point timestamp support:
  847. # Python interpreter versions prior to Python 2.3 did not support
  848. # floating point timestamps. Versions 2.3 through 3.3 may or may not
  849. # support it depending on the configuration (may be toggled by calling
  850. # os.stat_float_times(True/False) at program startup, disabled by
  851. # default prior to Python 2.5 and enabled by default since). Python 3.3
  852. # deprecated this configuration and 3.4 removed support for it after
  853. # which floating point timestamps are always supported.
  854. ver = sys.version_info[0:2]
  855. python_nanosecond_support = ver >= (3, 4) or (ver >= (2, 3) and
  856. os.stat_float_times())
  857. # Minimal expected floating point difference used to account for
  858. # possible imprecise floating point number representations. We want
  859. # this number to be small (at least smaller than 0.0001) but still
  860. # large enough that we can be sure that increasing a floating point
  861. # value by 2 * eta guarantees the value read back will be increased by
  862. # at least eta.
  863. eta = 0.00005
  864. stats_orig = os.stat(path)
  865. def test_time(diff):
  866. """Returns whether a timestamp difference is detectable."""
  867. os.utime(path, (stats_orig.st_atime, stats_orig.st_mtime + diff))
  868. return os.stat(path).st_mtime > stats_orig.st_mtime + eta
  869. # Test for nanosecond timestamp resolution support.
  870. if not minimum_resolution and python_nanosecond_support:
  871. if test_time(2 * eta):
  872. return 0
  873. # Detect the filesystem timestamp resolution. Note that there is no
  874. # need to make this code 'as fast as possible' as, this function gets
  875. # called before having to sleep until the next detectable modification
  876. # timestamp value and that, since we already know nanosecond resolution
  877. # is not supported, will surely take longer than whatever we do here to
  878. # detect this minimal detectable modification timestamp resolution.
  879. step = 0.1
  880. if not python_nanosecond_support:
  881. # If Python does not support nanosecond timestamp resolution we
  882. # know the minimum possible supported timestamp resolution is 1
  883. # second.
  884. minimum_resolution = max(1, minimum_resolution)
  885. index = max(1, int(minimum_resolution / step))
  886. while step * index < minimum_resolution:
  887. # Floating point number representation errors may cause our
  888. # initially calculated start index to be too small if calculated
  889. # directly.
  890. index += 1
  891. while True:
  892. # Do not simply add up the steps to avoid cumulative floating point
  893. # number representation errors.
  894. next = step * index
  895. if next > 10:
  896. raise TestEnvironmentError("File systems with too coarse "
  897. "modification timestamp resolutions not supported.")
  898. if test_time(next):
  899. return next
  900. index += 1
  901. def __read_file(self, name, exact=False):
  902. name = self.adjust_names(name)[0]
  903. result = ""
  904. try:
  905. if exact:
  906. result = self.read(name)
  907. else:
  908. result = self.read_and_strip(name).replace("\\", "/")
  909. except (IOError, IndexError):
  910. print "Note: could not open file", name
  911. self.fail_test(1)
  912. return result
  913. def __wait_for_time_change(self, path, touch, last_build_time):
  914. """
  915. Wait until a newly assigned file system modification timestamp for
  916. the given path is large enough for the timestamp difference between it
  917. and the last build timestamp or the path's original file system
  918. modification timestamp (depending on the last_build_time flag) to be
  919. correctly recognized by both this Python based testing framework and
  920. the Boost Jam executable being tested. May optionally touch the given
  921. path to set its modification timestamp to the new value.
  922. """
  923. assert self.last_build_timestamp or not last_build_time
  924. stats_orig = os.stat(path)
  925. if last_build_time:
  926. start_time = self.last_build_timestamp
  927. else:
  928. start_time = stats_orig.st_mtime
  929. build_resolution = self.__build_timestamp_resolution()
  930. assert build_resolution >= 0
  931. # Check whether the current timestamp is already new enough.
  932. if stats_orig.st_mtime > start_time and (not build_resolution or
  933. stats_orig.st_mtime >= start_time + build_resolution):
  934. return
  935. resolution = self.__python_timestamp_resolution(path, build_resolution)
  936. assert resolution >= build_resolution
  937. # Implementation notes:
  938. # * Theoretically time.sleep() API might get interrupted too soon
  939. # (never actually encountered).
  940. # * We encountered cases where we sleep just long enough for the
  941. # filesystem's modifiction timestamp to change to the desired value,
  942. # but after waking up, the read timestamp is still just a tiny bit
  943. # too small (encountered on Windows). This is most likely caused by
  944. # imprecise floating point timestamp & sleep interval representation
  945. # used by Python. Note though that we never encountered a case where
  946. # more than one additional tiny sleep() call was needed to remedy
  947. # the situation.
  948. # * We try to wait long enough for the timestamp to change, but do not
  949. # want to waste processing time by waiting too long. The main
  950. # problem is that when we have a coarse resolution, the actual times
  951. # get rounded and we do not know the exact sleep time needed for the
  952. # difference between two such times to pass. E.g. if we have a 1
  953. # second resolution and the original and the current file timestamps
  954. # are both 10 seconds then it could be that the current time is
  955. # 10.99 seconds and that we can wait for just one hundredth of a
  956. # second for the current file timestamp to reach its next value, and
  957. # using a longer sleep interval than that would just be wasting
  958. # time.
  959. while True:
  960. os.utime(path, None)
  961. c = os.stat(path).st_mtime
  962. if resolution:
  963. if c > start_time and (not build_resolution or c >= start_time
  964. + build_resolution):
  965. break
  966. if c <= start_time - resolution:
  967. # Move close to the desired timestamp in one sleep, but not
  968. # close enough for timestamp rounding to potentially cause
  969. # us to wait too long.
  970. if start_time - c > 5:
  971. if last_build_time:
  972. error_message = ("Last build time recorded as "
  973. "being a future event, causing a too long "
  974. "wait period. Something must have played "
  975. "around with the system clock.")
  976. else:
  977. error_message = ("Original path modification "
  978. "timestamp set to far into the future or "
  979. "something must have played around with the "
  980. "system clock, causing a too long wait "
  981. "period.\nPath: '%s'" % path)
  982. raise TestEnvironmentError(message)
  983. _sleep(start_time - c)
  984. else:
  985. # We are close to the desired timestamp so take baby sleeps
  986. # to avoid sleeping too long.
  987. _sleep(max(0.01, resolution / 10))
  988. else:
  989. if c > start_time:
  990. break
  991. _sleep(max(0.01, start_time - c))
  992. if not touch:
  993. os.utime(path, (stats_orig.st_atime, stats_orig.st_mtime))
  994. class List:
  995. def __init__(self, s=""):
  996. elements = []
  997. if s.__class__ is str:
  998. # Have to handle escaped spaces correctly.
  999. elements = s.replace("\ ", "\001").split()
  1000. else:
  1001. elements = s
  1002. self.l = [e.replace("\001", " ") for e in elements]
  1003. def __len__(self):
  1004. return len(self.l)
  1005. def __getitem__(self, key):
  1006. return self.l[key]
  1007. def __setitem__(self, key, value):
  1008. self.l[key] = value
  1009. def __delitem__(self, key):
  1010. del self.l[key]
  1011. def __str__(self):
  1012. return str(self.l)
  1013. def __repr__(self):
  1014. return "%s.List(%r)" % (self.__module__, " ".join(self.l))
  1015. def __mul__(self, other):
  1016. result = List()
  1017. if not isinstance(other, List):
  1018. other = List(other)
  1019. for f in self:
  1020. for s in other:
  1021. result.l.append(f + s)
  1022. return result
  1023. def __rmul__(self, other):
  1024. if not isinstance(other, List):
  1025. other = List(other)
  1026. return List.__mul__(other, self)
  1027. def __add__(self, other):
  1028. result = List()
  1029. result.l = self.l[:] + other.l[:]
  1030. return result
  1031. def _contains_lines(data, lines):
  1032. data_line_count = len(data)
  1033. expected_line_count = reduce(lambda x, y: x + len(y), lines, 0)
  1034. index = 0
  1035. for expected in lines:
  1036. if expected_line_count > data_line_count - index:
  1037. return False
  1038. expected_line_count -= len(expected)
  1039. index = _match_line_sequence(data, index, data_line_count -
  1040. expected_line_count, expected)
  1041. if index < 0:
  1042. return False
  1043. return True
  1044. def _match_line_sequence(data, start, end, lines):
  1045. if not lines:
  1046. return start
  1047. for index in xrange(start, end - len(lines) + 1):
  1048. data_index = index
  1049. for expected in lines:
  1050. if not fnmatch.fnmatch(data[data_index], expected):
  1051. break;
  1052. data_index += 1
  1053. else:
  1054. return data_index
  1055. return -1
  1056. def _sleep(delay):
  1057. if delay > 5:
  1058. raise TestEnvironmentError("Test environment error: sleep period of "
  1059. "more than 5 seconds requested. Most likely caused by a file with "
  1060. "its modification timestamp set to sometime in the future.")
  1061. time.sleep(delay)
  1062. ###############################################################################
  1063. #
  1064. # Initialization.
  1065. #
  1066. ###############################################################################
  1067. # Make os.stat() return file modification times as floats instead of integers
  1068. # to get the best possible file timestamp resolution available. The exact
  1069. # resolution depends on the underlying file system and the Python os.stat()
  1070. # implementation. The better the resolution we achieve, the shorter we need to
  1071. # wait for files we create to start getting new timestamps.
  1072. #
  1073. # Additional notes:
  1074. # * os.stat_float_times() function first introduced in Python 2.3. and
  1075. # suggested for deprecation in Python 3.3.
  1076. # * On Python versions 2.5+ we do not need to do this as there os.stat()
  1077. # returns floating point file modification times by default.
  1078. # * Windows CPython implementations prior to version 2.5 do not support file
  1079. # modification timestamp resolutions of less than 1 second no matter whether
  1080. # these timestamps are returned as integer or floating point values.
  1081. # * Python documentation states that this should be set in a program's
  1082. # __main__ module to avoid affecting other libraries that might not be ready
  1083. # to support floating point timestamps. Since we use no such external
  1084. # libraries, we ignore this warning to make it easier to enable this feature
  1085. # in both our single & multiple-test scripts.
  1086. if (2, 3) <= sys.version_info < (2, 5) and not os.stat_float_times():
  1087. os.stat_float_times(True)
  1088. # Quickie tests. Should use doctest instead.
  1089. if __name__ == "__main__":
  1090. assert str(List("foo bar") * "/baz") == "['foo/baz', 'bar/baz']"
  1091. assert repr("foo/" * List("bar baz")) == "__main__.List('foo/bar foo/baz')"
  1092. assert _contains_lines([], [])
  1093. assert _contains_lines([], [[]])
  1094. assert _contains_lines([], [[], []])
  1095. assert _contains_lines([], [[], [], []])
  1096. assert not _contains_lines([], [[""]])
  1097. assert not _contains_lines([], [["a"]])
  1098. assert _contains_lines([""], [])
  1099. assert _co

Large files files are truncated, but you can click here to view the full file