BoostBuild.py 52 KB

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