PageRenderTime 91ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://github.com/ee2/boost-svn
Python | 913 lines | 875 code | 24 blank | 14 comment | 22 complexity | dc1618e100be0584c4b5cb73c6cbf991 MD5 | raw 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 re
  14. import shutil
  15. import string
  16. import StringIO
  17. import sys
  18. import tempfile
  19. import time
  20. import traceback
  21. import tree
  22. import types
  23. from xml.sax.saxutils import escape
  24. annotations = []
  25. def print_annotation(name, value, xml):
  26. """Writes some named bits of information about test run.
  27. """
  28. if xml:
  29. print escape(name) + " {{{"
  30. print escape(value)
  31. print "}}}"
  32. else:
  33. print name + " {{{"
  34. print value
  35. print "}}}"
  36. def flush_annotations(xml=0):
  37. global annotations
  38. for ann in annotations:
  39. print_annotation(ann[0], ann[1], xml)
  40. annotations = []
  41. defer_annotations = 0
  42. def set_defer_annotations(n):
  43. global defer_annotations
  44. defer_annotations = n
  45. def annotation(name, value):
  46. """Records an annotation about the test run.
  47. """
  48. annotations.append((name, value))
  49. if not defer_annotations:
  50. flush_annotations()
  51. def get_toolset():
  52. toolset = None;
  53. for arg in sys.argv[1:]:
  54. if not arg.startswith('-'):
  55. toolset = arg
  56. return toolset or 'gcc'
  57. # Detect the host OS.
  58. windows = False
  59. if os.environ.get('OS', '').lower().startswith('windows') or \
  60. os.__dict__.has_key('uname') and \
  61. os.uname()[0].lower().startswith('cygwin'):
  62. windows = True
  63. suffixes = {}
  64. # Prepare the map of suffixes
  65. def prepare_suffix_map(toolset):
  66. global windows
  67. global suffixes
  68. suffixes = {'.exe': '', '.dll': '.so', '.lib': '.a', '.obj': '.o'}
  69. suffixes['.implib'] = '.no_implib_files_on_this_platform'
  70. if windows:
  71. suffixes = {}
  72. if toolset in ["gcc"]:
  73. suffixes['.lib'] = '.a' # static libs have '.a' suffix with mingw...
  74. suffixes['.obj'] = '.o'
  75. suffixes['.implib'] = '.lib'
  76. if os.__dict__.has_key('uname') and (os.uname()[0] == 'Darwin'):
  77. suffixes['.dll'] = '.dylib'
  78. def re_remove(sequence, regex):
  79. me = re.compile(regex)
  80. result = filter(lambda x: me.match(x), sequence)
  81. if 0 == len(result):
  82. raise ValueError()
  83. for r in result:
  84. sequence.remove(r)
  85. def glob_remove(sequence, pattern):
  86. result = fnmatch.filter(sequence, pattern)
  87. if 0 == len(result):
  88. raise ValueError()
  89. for r in result:
  90. sequence.remove(r)
  91. # Configuration stating whether Boost Build is expected to automatically prepend
  92. # prefixes to built library targets.
  93. lib_prefix = True
  94. dll_prefix = True
  95. if windows:
  96. dll_prefix = False
  97. #
  98. # FIXME: this is copy-pasted from TestSCons.py
  99. # Should be moved to TestCmd.py?
  100. #
  101. if os.name == 'posix':
  102. def _failed(self, status=0):
  103. if self.status is None:
  104. return None
  105. if os.WIFSIGNALED(status):
  106. return None
  107. return _status(self) != status
  108. def _status(self):
  109. if os.WIFEXITED(self.status):
  110. return os.WEXITSTATUS(self.status)
  111. else:
  112. return -1
  113. elif os.name == 'nt':
  114. def _failed(self, status=0):
  115. return not self.status is None and self.status != status
  116. def _status(self):
  117. return self.status
  118. class Tester(TestCmd.TestCmd):
  119. """Main tester class for Boost Build.
  120. Optional arguments:
  121. `arguments` - Arguments passed to the run executable.
  122. `executable` - Name of the executable to invoke.
  123. `match` - Function to use for compating actual and
  124. expected file contents.
  125. `boost_build_path` - Boost build path to be passed to the run
  126. executable.
  127. `translate_suffixes` - Whether to update suffixes on the the file
  128. names passed from the test script so they
  129. match those actually created by the current
  130. toolset. For example, static library files
  131. are specified by using the .lib suffix but
  132. when the 'gcc' toolset is used it actually
  133. creates them using the .a suffix.
  134. `pass_toolset` - Whether the test system should pass the
  135. specified toolset to the run executable.
  136. `use_test_config` - Whether the test system should tell the run
  137. executable to read in the test_config.jam
  138. configuration file.
  139. `ignore_toolset_requirements` - Whether the test system should tell the run
  140. executable to ignore toolset requirements.
  141. `workdir` - indicates an absolute directory where the
  142. test will be run from.
  143. Optional arguments inherited from the base class:
  144. `description` - Test description string displayed in case of
  145. a failed test.
  146. `subdir' - List of subdirectories to automatically
  147. create under the working directory. Each
  148. subdirectory needs to be specified
  149. separately parent coming before its child.
  150. `verbose` - Flag that may be used to enable more verbose
  151. test system output. Note that it does not
  152. also enable more verbose build system
  153. output like the --verbose command line
  154. option does.
  155. """
  156. def __init__(self, arguments="", executable="bjam",
  157. match=TestCmd.match_exact, boost_build_path=None,
  158. translate_suffixes=True, pass_toolset=True, use_test_config=True,
  159. ignore_toolset_requirements=True, workdir="", **keywords):
  160. self.original_workdir = os.getcwd()
  161. if workdir != '' and not os.path.isabs(workdir):
  162. raise "Parameter workdir <"+workdir+"> must point to an absolute directory: "
  163. self.last_build_time_start = 0
  164. self.last_build_time_finish = 0
  165. self.translate_suffixes = translate_suffixes
  166. self.use_test_config = use_test_config
  167. self.toolset = get_toolset()
  168. self.pass_toolset = pass_toolset
  169. self.ignore_toolset_requirements = ignore_toolset_requirements
  170. prepare_suffix_map(pass_toolset and self.toolset or 'gcc')
  171. if not '--default-bjam' in sys.argv:
  172. jam_build_dir = ""
  173. if os.name == 'nt':
  174. jam_build_dir = "bin.ntx86"
  175. elif (os.name == 'posix') and os.__dict__.has_key('uname'):
  176. if os.uname()[0].lower().startswith('cygwin'):
  177. jam_build_dir = "bin.cygwinx86"
  178. if 'TMP' in os.environ and os.environ['TMP'].find('~') != -1:
  179. print 'Setting $TMP to /tmp to get around problem with short path names'
  180. os.environ['TMP'] = '/tmp'
  181. elif os.uname()[0] == 'Linux':
  182. cpu = os.uname()[4]
  183. if re.match("i.86", cpu):
  184. jam_build_dir = "bin.linuxx86";
  185. else:
  186. jam_build_dir = "bin.linux" + os.uname()[4]
  187. elif os.uname()[0] == 'SunOS':
  188. jam_build_dir = "bin.solaris"
  189. elif os.uname()[0] == 'Darwin':
  190. if os.uname()[4] == 'i386':
  191. jam_build_dir = "bin.macosxx86"
  192. else:
  193. jam_build_dir = "bin.macosxppc"
  194. elif os.uname()[0] == "AIX":
  195. jam_build_dir = "bin.aix"
  196. elif os.uname()[0] == "IRIX64":
  197. jam_build_dir = "bin.irix"
  198. elif os.uname()[0] == "FreeBSD":
  199. jam_build_dir = "bin.freebsd"
  200. elif os.uname()[0] == "OSF1":
  201. jam_build_dir = "bin.osf"
  202. else:
  203. raise "Don't know directory where Jam is built for this system: " + os.name + "/" + os.uname()[0]
  204. else:
  205. raise "Don't know directory where Jam is built for this system: " + os.name
  206. # Find where jam_src is located. Try for the debug version if it is
  207. # lying around.
  208. dirs = [os.path.join('../../../jam/src', jam_build_dir + '.debug'),
  209. os.path.join('../../../jam/src', jam_build_dir),
  210. os.path.join('../../jam_src', jam_build_dir + '.debug'),
  211. os.path.join('../../jam_src', jam_build_dir),
  212. os.path.join('../jam_src', jam_build_dir + '.debug'),
  213. os.path.join('../jam_src', jam_build_dir)]
  214. for d in dirs:
  215. if os.path.exists(d):
  216. jam_build_dir = d
  217. break
  218. else:
  219. print "Cannot find built Boost.Jam"
  220. sys.exit(1)
  221. verbosity = ['-d0', '--quiet']
  222. if '--verbose' in sys.argv:
  223. keywords['verbose'] = True
  224. verbosity = ['-d+2']
  225. if boost_build_path is None:
  226. boost_build_path = self.original_workdir
  227. program_list = []
  228. if '--default-bjam' in sys.argv:
  229. program_list.append(executable)
  230. inpath_bjam = True
  231. else:
  232. program_list.append(os.path.join(jam_build_dir, executable))
  233. inpath_bjam = None
  234. program_list.append('-sBOOST_BUILD_PATH="' + boost_build_path + '"')
  235. if verbosity:
  236. program_list += verbosity
  237. if arguments:
  238. program_list += arguments.split(" ")
  239. TestCmd.TestCmd.__init__(
  240. self
  241. , program=program_list
  242. , match=match
  243. , workdir=workdir
  244. , inpath=inpath_bjam
  245. , **keywords)
  246. os.chdir(self.workdir)
  247. def cleanup(self):
  248. try:
  249. TestCmd.TestCmd.cleanup(self)
  250. os.chdir(self.original_workdir)
  251. except AttributeError:
  252. # When this is called during TestCmd.TestCmd.__del__ we can have
  253. # both 'TestCmd' and 'os' unavailable in our scope. Do nothing in
  254. # this case.
  255. pass
  256. #
  257. # Methods that change the working directory's content.
  258. #
  259. def set_tree(self, tree_location):
  260. # It is not possible to remove the current directory.
  261. d = os.getcwd()
  262. os.chdir(os.path.dirname(self.workdir))
  263. shutil.rmtree(self.workdir, ignore_errors=False)
  264. if not os.path.isabs(tree_location):
  265. tree_location = os.path.join(self.original_workdir, tree_location)
  266. shutil.copytree(tree_location, self.workdir)
  267. os.chdir(d)
  268. def make_writable(unused, dir, entries):
  269. for e in entries:
  270. name = os.path.join(dir, e)
  271. os.chmod(name, os.stat(name)[0] | 0222)
  272. os.path.walk(".", make_writable, None)
  273. def write(self, file, content):
  274. self.wait_for_time_change_since_last_build()
  275. nfile = self.native_file_name(file)
  276. try:
  277. os.makedirs(os.path.dirname(nfile))
  278. except Exception, e:
  279. pass
  280. open(nfile, "wb").write(content)
  281. def rename(self, old, new):
  282. try:
  283. os.makedirs(os.path.dirname(new))
  284. except:
  285. pass
  286. try:
  287. os.remove(new)
  288. except:
  289. pass
  290. os.rename(old, new)
  291. self.touch(new);
  292. def copy(self, src, dst):
  293. self.wait_for_time_change_since_last_build()
  294. try:
  295. self.write(dst, self.read(src, 1))
  296. except:
  297. self.fail_test(1)
  298. def copy_preserving_timestamp(self, src, dst):
  299. src_name = self.native_file_name(src)
  300. dst_name = self.native_file_name(dst)
  301. stats = os.stat(src_name)
  302. self.write(dst, self.read(src, 1))
  303. os.utime(dst_name, (stats.st_atime, stats.st_mtime))
  304. def touch(self, names):
  305. self.wait_for_time_change_since_last_build()
  306. for name in self.adjust_names(names):
  307. os.utime(self.native_file_name(name), None)
  308. def rm(self, names):
  309. self.wait_for_time_change_since_last_build()
  310. if not type(names) == types.ListType:
  311. names = [names]
  312. # Avoid attempts to remove the current directory.
  313. os.chdir(self.original_workdir)
  314. for name in names:
  315. n = self.native_file_name(name)
  316. n = glob.glob(n)
  317. if n: n = n[0]
  318. if not n:
  319. n = self.glob_file(string.replace(name, "$toolset", self.toolset+"*"))
  320. if n:
  321. if os.path.isdir(n):
  322. shutil.rmtree(n, ignore_errors=False)
  323. else:
  324. os.unlink(n)
  325. # Create working dir root again in case we removed it.
  326. if not os.path.exists(self.workdir):
  327. os.mkdir(self.workdir)
  328. os.chdir(self.workdir)
  329. def expand_toolset(self, name):
  330. """Expands $toolset in the given file to tested toolset.
  331. """
  332. content = self.read(name)
  333. content = string.replace(content, "$toolset", self.toolset)
  334. self.write(name, content)
  335. def dump_stdio(self):
  336. annotation("STDOUT", self.stdout())
  337. annotation("STDERR", self.stderr())
  338. #
  339. # FIXME: Large portion copied from TestSCons.py, should be moved?
  340. #
  341. def run_build_system(self, extra_args="", subdir="", stdout=None, stderr="",
  342. status=0, match=None, pass_toolset=None, use_test_config=None,
  343. ignore_toolset_requirements=None, expected_duration=None, **kw):
  344. self.last_build_time_start = time.time()
  345. try:
  346. if os.path.isabs(subdir):
  347. if stderr:
  348. print "You must pass a relative directory to subdir <"+subdir+">."
  349. status = 1
  350. return
  351. self.previous_tree = 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.split(" ")
  365. if pass_toolset:
  366. kw['program'].append("toolset=" + self.toolset)
  367. if use_test_config:
  368. kw['program'].append('--test-config="%s"'
  369. % os.path.join(self.original_workdir, "test-config.jam"))
  370. if ignore_toolset_requirements:
  371. kw['program'].append("--ignore-toolset-requirements")
  372. kw['chdir'] = subdir
  373. apply(TestCmd.TestCmd.run, [self], kw)
  374. except:
  375. self.dump_stdio()
  376. raise
  377. finally:
  378. self.last_build_time_finish = time.time()
  379. if (status != None) and _failed(self, status):
  380. expect = ''
  381. if status != 0:
  382. expect = " (expected %d)" % status
  383. annotation("failure", '"%s" returned %d%s'
  384. % (kw['program'], _status(self), expect))
  385. annotation("reason", "error returned by bjam")
  386. self.fail_test(1)
  387. if not (stdout is None) and not match(self.stdout(), stdout):
  388. annotation("failure", "Unexpected stdout")
  389. annotation("Expected STDOUT", stdout)
  390. annotation("Actual STDOUT", self.stdout())
  391. stderr = self.stderr()
  392. if stderr:
  393. annotation("STDERR", stderr)
  394. self.maybe_do_diff(self.stdout(), stdout)
  395. self.fail_test(1, dump_stdio=False)
  396. # Intel tends to produce some messages to stderr which make tests fail.
  397. intel_workaround = re.compile("^xi(link|lib): executing.*\n", re.M)
  398. actual_stderr = re.sub(intel_workaround, "", self.stderr())
  399. if not (stderr is None) and not match(actual_stderr, stderr):
  400. annotation("failure", "Unexpected stderr")
  401. annotation("Expected STDERR", stderr)
  402. annotation("Actual STDERR", self.stderr())
  403. annotation("STDOUT", self.stdout())
  404. self.maybe_do_diff(actual_stderr, stderr)
  405. self.fail_test(1, dump_stdio=False)
  406. if not expected_duration is None:
  407. actual_duration = self.last_build_time_finish - self.last_build_time_start
  408. if (actual_duration > expected_duration):
  409. print "Test run lasted %f seconds while it was expected to " \
  410. "finish in under %f seconds." % (actual_duration,
  411. expected_duration)
  412. self.fail_test(1, dump_stdio=False)
  413. self.tree = tree.build_tree(self.workdir)
  414. self.difference = tree.trees_difference(self.previous_tree, self.tree)
  415. self.difference.ignore_directories()
  416. self.unexpected_difference = copy.deepcopy(self.difference)
  417. def glob_file(self, name):
  418. result = None
  419. if hasattr(self, 'difference'):
  420. for f in self.difference.added_files+self.difference.modified_files+self.difference.touched_files:
  421. if fnmatch.fnmatch(f, name):
  422. result = self.native_file_name(f)
  423. break
  424. if not result:
  425. result = glob.glob(self.native_file_name(name))
  426. if result:
  427. result = result[0]
  428. return result
  429. def read(self, name, binary=False):
  430. try:
  431. if self.toolset:
  432. name = string.replace(name, "$toolset", self.toolset+"*")
  433. name = self.glob_file(name)
  434. openMode = "r"
  435. if binary:
  436. openMode += "b"
  437. else:
  438. openMode += "U"
  439. return open(name, openMode).read()
  440. except:
  441. annotation("failure", "Could not open '%s'" % name)
  442. self.fail_test(1)
  443. return ''
  444. def read_and_strip(self, name):
  445. lines = open(self.glob_file(name), "rb").readlines()
  446. result = string.join(map(string.rstrip, lines), "\n")
  447. if lines and lines[-1][-1] == '\n':
  448. return result + '\n'
  449. else:
  450. return result
  451. def fail_test(self, condition, dump_stdio=True, *args):
  452. if not condition:
  453. return
  454. if hasattr(self, 'difference'):
  455. f = StringIO.StringIO()
  456. self.difference.pprint(f)
  457. annotation("changes caused by the last build command", f.getvalue())
  458. if dump_stdio:
  459. self.dump_stdio()
  460. if '--preserve' in sys.argv:
  461. print
  462. print "*** Copying the state of working dir into 'failed_test' ***"
  463. print
  464. path = os.path.join(self.original_workdir, "failed_test")
  465. if os.path.isdir(path):
  466. shutil.rmtree(path, ignore_errors=False)
  467. elif os.path.exists(path):
  468. raise "Path " + path + " already exists and is not a directory";
  469. shutil.copytree(self.workdir, path)
  470. at = TestCmd.caller(traceback.extract_stack(), 0)
  471. annotation("stacktrace", at)
  472. sys.exit(1)
  473. # A number of methods below check expectations with actual difference
  474. # between directory trees before and after a build. All the 'expect*'
  475. # methods require exact names to be passed. All the 'ignore*' methods allow
  476. # wildcards.
  477. # All names can be lists, which are taken to be directory components.
  478. def expect_addition(self, names):
  479. for name in self.adjust_names(names):
  480. try:
  481. glob_remove(self.unexpected_difference.added_files, name)
  482. except:
  483. annotation("failure", "File %s not added as expected" % name)
  484. self.fail_test(1)
  485. def ignore_addition(self, wildcard):
  486. self.ignore_elements(self.unexpected_difference.added_files, wildcard)
  487. def expect_removal(self, names):
  488. for name in self.adjust_names(names):
  489. try:
  490. glob_remove(self.unexpected_difference.removed_files, name)
  491. except:
  492. annotation("failure", "File %s not removed as expected" % name)
  493. self.fail_test(1)
  494. def ignore_removal(self, wildcard):
  495. self.ignore_elements(self.unexpected_difference.removed_files, wildcard)
  496. def expect_modification(self, names):
  497. for name in self.adjust_names(names):
  498. try:
  499. glob_remove(self.unexpected_difference.modified_files, name)
  500. except:
  501. annotation("failure", "File %s not modified as expected" % name)
  502. self.fail_test(1)
  503. def ignore_modification(self, wildcard):
  504. self.ignore_elements(self.unexpected_difference.modified_files, \
  505. wildcard)
  506. def expect_touch(self, names):
  507. d = self.unexpected_difference
  508. for name in self.adjust_names(names):
  509. # We need to check both touched and modified files. The reason is
  510. # that:
  511. # (1) Windows binaries such as obj, exe or dll files have slight
  512. # differences even with identical inputs due to Windows PE
  513. # format headers containing an internal timestamp.
  514. # (2) Intel's compiler for Linux has the same behaviour.
  515. filesets = [d.modified_files, d.touched_files]
  516. while filesets:
  517. try:
  518. glob_remove(filesets[-1], name)
  519. break
  520. except ValueError:
  521. filesets.pop()
  522. if not filesets:
  523. annotation("failure", "File %s not touched as expected" % name)
  524. self.fail_test(1)
  525. def ignore_touch(self, wildcard):
  526. self.ignore_elements(self.unexpected_difference.touched_files, wildcard)
  527. def ignore(self, wildcard):
  528. self.ignore_elements(self.unexpected_difference.added_files, wildcard)
  529. self.ignore_elements(self.unexpected_difference.removed_files, wildcard)
  530. self.ignore_elements(self.unexpected_difference.modified_files, wildcard)
  531. self.ignore_elements(self.unexpected_difference.touched_files, wildcard)
  532. def expect_nothing(self, names):
  533. for name in self.adjust_names(names):
  534. if name in self.difference.added_files:
  535. annotation("failure",
  536. "File %s added, but no action was expected" % name)
  537. self.fail_test(1)
  538. if name in self.difference.removed_files:
  539. annotation("failure",
  540. "File %s removed, but no action was expected" % name)
  541. self.fail_test(1)
  542. pass
  543. if name in self.difference.modified_files:
  544. annotation("failure",
  545. "File %s modified, but no action was expected" % name)
  546. self.fail_test(1)
  547. if name in self.difference.touched_files:
  548. annotation("failure",
  549. "File %s touched, but no action was expected" % name)
  550. self.fail_test(1)
  551. def expect_nothing_more(self):
  552. # Not totally sure about this change, but I do not see a good
  553. # alternative.
  554. if windows:
  555. self.ignore('*.ilk') # MSVC incremental linking files.
  556. self.ignore('*.pdb') # MSVC program database files.
  557. self.ignore('*.rsp') # Response files.
  558. self.ignore('*.tds') # Borland debug symbols.
  559. self.ignore('*.manifest') # MSVC DLL manifests.
  560. # Debug builds of bjam built with gcc produce this profiling data.
  561. self.ignore('gmon.out')
  562. self.ignore('*/gmon.out')
  563. self.ignore("bin/config.log")
  564. if not self.unexpected_difference.empty():
  565. annotation('failure', 'Unexpected changes found')
  566. output = StringIO.StringIO()
  567. self.unexpected_difference.pprint(output)
  568. annotation("unexpected changes", output.getvalue())
  569. self.fail_test(1)
  570. def __expect_line(self, content, expected, expected_to_exist):
  571. expected = expected.strip()
  572. lines = content.splitlines()
  573. found = False
  574. for line in lines:
  575. line = line.strip()
  576. if fnmatch.fnmatch(line, expected):
  577. found = True
  578. break
  579. if expected_to_exist and not found:
  580. annotation("failure",
  581. "Did not find expected line:\n%s\nin output:\n%s" %
  582. (expected, content))
  583. self.fail_test(1)
  584. if not expected_to_exist and found:
  585. annotation("failure",
  586. "Found an unexpected line:\n%s\nin output:\n%s" %
  587. (expected, content))
  588. self.fail_test(1)
  589. def expect_output_line(self, line, expected_to_exist=True):
  590. self.__expect_line(self.stdout(), line, expected_to_exist)
  591. def expect_content_line(self, name, line, expected_to_exist=True):
  592. content = self.__read_file(name)
  593. self.__expect_line(content, line, expected_to_exist)
  594. def __read_file(self, name, exact=False):
  595. name = self.adjust_names(name)[0]
  596. result = ""
  597. try:
  598. if exact:
  599. result = self.read(name)
  600. else:
  601. result = string.replace(self.read_and_strip(name), "\\", "/")
  602. except (IOError, IndexError):
  603. print "Note: could not open file", name
  604. self.fail_test(1)
  605. return result
  606. def expect_content(self, name, content, exact=False):
  607. actual = self.__read_file(name, exact)
  608. content = string.replace(content, "$toolset", self.toolset+"*")
  609. matched = False
  610. if exact:
  611. matched = fnmatch.fnmatch(actual, content)
  612. else:
  613. def sorted_(x):
  614. x.sort()
  615. return x
  616. actual_ = map(lambda x: sorted_(x.split()), actual.splitlines())
  617. content_ = map(lambda x: sorted_(x.split()), content.splitlines())
  618. if len(actual_) == len(content_):
  619. matched = map(
  620. lambda x, y: map(lambda n, p: fnmatch.fnmatch(n, p), x, y),
  621. actual_, content_)
  622. matched = reduce(
  623. lambda x, y: x and reduce(
  624. lambda a, b: a and b,
  625. y),
  626. matched)
  627. if not matched:
  628. print "Expected:\n"
  629. print content
  630. print "Got:\n"
  631. print actual
  632. self.fail_test(1)
  633. def maybe_do_diff(self, actual, expected):
  634. if os.environ.has_key("DO_DIFF") and os.environ["DO_DIFF"] != '':
  635. e = tempfile.mktemp("expected")
  636. a = tempfile.mktemp("actual")
  637. open(e, "w").write(expected)
  638. open(a, "w").write(actual)
  639. print "DIFFERENCE"
  640. if os.system("diff -u " + e + " " + a):
  641. print "Unable to compute difference: diff -u %s %s" % (e, a)
  642. os.unlink(e)
  643. os.unlink(a)
  644. else:
  645. print "Set environmental variable 'DO_DIFF' to examine difference."
  646. # Helpers.
  647. def mul(self, *arguments):
  648. if len(arguments) == 0:
  649. return None
  650. here = arguments[0]
  651. if type(here) == type(''):
  652. here = [here]
  653. if len(arguments) > 1:
  654. there = apply(self.mul, arguments[1:])
  655. result = []
  656. for i in here:
  657. for j in there:
  658. result.append(i + j)
  659. return result
  660. return here
  661. # Internal methods.
  662. def ignore_elements(self, list, wildcard):
  663. """Removes in-place, element of 'list' that match the given wildcard.
  664. """
  665. list[:] = filter(lambda x, w=wildcard: not fnmatch.fnmatch(x, w), list)
  666. def adjust_lib_name(self, name):
  667. global lib_prefix
  668. result = name
  669. pos = string.rfind(name, ".")
  670. if pos != -1:
  671. suffix = name[pos:]
  672. if suffix == ".lib":
  673. (head, tail) = os.path.split(name)
  674. if lib_prefix:
  675. tail = "lib" + tail
  676. result = os.path.join(head, tail)
  677. elif suffix == ".dll":
  678. (head, tail) = os.path.split(name)
  679. if dll_prefix:
  680. tail = "lib" + tail
  681. result = os.path.join(head, tail)
  682. # If we want to use this name in a Jamfile, we better convert \ to /, as
  683. # otherwise we would have to quote \.
  684. result = string.replace(result, "\\", "/")
  685. return result
  686. def adjust_suffix(self, name):
  687. if not self.translate_suffixes:
  688. return name
  689. pos = string.rfind(name, ".")
  690. if pos != -1:
  691. suffix = name[pos:]
  692. name = name[:pos]
  693. if suffixes.has_key(suffix):
  694. suffix = suffixes[suffix]
  695. else:
  696. suffix = ''
  697. return name + suffix
  698. # Acceps either a string or a list of strings and returns a list of strings.
  699. # Adjusts suffixes on all names.
  700. def adjust_names(self, names):
  701. if type(names) == types.StringType:
  702. names = [names]
  703. r = map(self.adjust_lib_name, names)
  704. r = map(self.adjust_suffix, r)
  705. r = map(lambda x, t=self.toolset: string.replace(x, "$toolset", t+"*"), r)
  706. return r
  707. def native_file_name(self, name):
  708. name = self.adjust_names(name)[0]
  709. elements = string.split(name, "/")
  710. return os.path.normpath(apply(os.path.join, [self.workdir]+elements))
  711. # Wait while time is no longer equal to the time last "run_build_system"
  712. # call finished. Used to avoid subsequent builds treating existing files as
  713. # 'current'.
  714. def wait_for_time_change_since_last_build(self):
  715. while 1:
  716. # In fact, I'm not sure why "+ 2" as opposed to "+ 1" is needed but
  717. # empirically, "+ 1" sometimes causes 'touch' and other functions
  718. # not to bump the file time enough for a rebuild to happen.
  719. if math.floor(time.time()) < math.floor(self.last_build_time_finish) + 2:
  720. time.sleep(0.1)
  721. else:
  722. break
  723. class List:
  724. def __init__(self, s=""):
  725. elements = []
  726. if isinstance(s, type("")):
  727. # Have to handle espaced spaces correctly.
  728. s = string.replace(s, "\ ", '\001')
  729. elements = string.split(s)
  730. else:
  731. elements = s;
  732. self.l = []
  733. for e in elements:
  734. self.l.append(string.replace(e, '\001', ' '))
  735. def __len__(self):
  736. return len(self.l)
  737. def __getitem__(self, key):
  738. return self.l[key]
  739. def __setitem__(self, key, value):
  740. self.l[key] = value
  741. def __delitem__(self, key):
  742. del self.l[key]
  743. def __str__(self):
  744. return str(self.l)
  745. def __repr__(self):
  746. return (self.__module__ + '.List('
  747. + repr(string.join(self.l, ' '))
  748. + ')')
  749. def __mul__(self, other):
  750. result = List()
  751. if not isinstance(other, List):
  752. other = List(other)
  753. for f in self:
  754. for s in other:
  755. result.l.append(f + s)
  756. return result
  757. def __rmul__(self, other):
  758. if not isinstance(other, List):
  759. other = List(other)
  760. return List.__mul__(other, self)
  761. def __add__(self, other):
  762. result = List()
  763. result.l = self.l[:] + other.l[:]
  764. return result
  765. # Quickie tests. Should use doctest instead.
  766. if __name__ == '__main__':
  767. assert str(List("foo bar") * "/baz") == "['foo/baz', 'bar/baz']"
  768. assert repr("foo/" * List("bar baz")) == "__main__.List('foo/bar foo/baz')"
  769. print 'tests passed'