PageRenderTime 76ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/Miranda IM - CK Release/Miranda/boost/tools/build/v2/test/BoostBuild.py

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