runtests.py 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387
  1. """
  2. This is our testing framework.
  3. Goals:
  4. * it should be compatible with py.test and operate very similarly
  5. (or identically)
  6. * does not require any external dependencies
  7. * preferably all the functionality should be in this file only
  8. * no magic, just import the test file and execute the test functions, that's it
  9. * portable
  10. """
  11. import os
  12. import sys
  13. import platform
  14. import inspect
  15. import traceback
  16. import pdb
  17. import re
  18. import linecache
  19. import time
  20. from fnmatch import fnmatch
  21. from timeit import default_timer as clock
  22. import doctest as pdoctest # avoid clashing with our doctest() function
  23. from doctest import DocTestFinder, DocTestRunner
  24. import random
  25. import subprocess
  26. import shutil
  27. import signal
  28. import stat
  29. import tempfile
  30. import warnings
  31. from contextlib import contextmanager
  32. from inspect import unwrap
  33. from sympy.core.cache import clear_cache
  34. from sympy.external import import_module
  35. from sympy.external.gmpy import GROUND_TYPES, HAS_GMPY
  36. IS_WINDOWS = (os.name == 'nt')
  37. ON_CI = os.getenv('CI', None)
  38. # empirically generated list of the proportion of time spent running
  39. # an even split of tests. This should periodically be regenerated.
  40. # A list of [.6, .1, .3] would mean that if the tests are evenly split
  41. # into '1/3', '2/3', '3/3', the first split would take 60% of the time,
  42. # the second 10% and the third 30%. These lists are normalized to sum
  43. # to 1, so [60, 10, 30] has the same behavior as [6, 1, 3] or [.6, .1, .3].
  44. #
  45. # This list can be generated with the code:
  46. # from time import time
  47. # import sympy
  48. # import os
  49. # os.environ["CI"] = 'true' # Mock CI to get more correct densities
  50. # delays, num_splits = [], 30
  51. # for i in range(1, num_splits + 1):
  52. # tic = time()
  53. # sympy.test(split='{}/{}'.format(i, num_splits), time_balance=False) # Add slow=True for slow tests
  54. # delays.append(time() - tic)
  55. # tot = sum(delays)
  56. # print([round(x / tot, 4) for x in delays])
  57. SPLIT_DENSITY = [
  58. 0.0059, 0.0027, 0.0068, 0.0011, 0.0006,
  59. 0.0058, 0.0047, 0.0046, 0.004, 0.0257,
  60. 0.0017, 0.0026, 0.004, 0.0032, 0.0016,
  61. 0.0015, 0.0004, 0.0011, 0.0016, 0.0014,
  62. 0.0077, 0.0137, 0.0217, 0.0074, 0.0043,
  63. 0.0067, 0.0236, 0.0004, 0.1189, 0.0142,
  64. 0.0234, 0.0003, 0.0003, 0.0047, 0.0006,
  65. 0.0013, 0.0004, 0.0008, 0.0007, 0.0006,
  66. 0.0139, 0.0013, 0.0007, 0.0051, 0.002,
  67. 0.0004, 0.0005, 0.0213, 0.0048, 0.0016,
  68. 0.0012, 0.0014, 0.0024, 0.0015, 0.0004,
  69. 0.0005, 0.0007, 0.011, 0.0062, 0.0015,
  70. 0.0021, 0.0049, 0.0006, 0.0006, 0.0011,
  71. 0.0006, 0.0019, 0.003, 0.0044, 0.0054,
  72. 0.0057, 0.0049, 0.0016, 0.0006, 0.0009,
  73. 0.0006, 0.0012, 0.0006, 0.0149, 0.0532,
  74. 0.0076, 0.0041, 0.0024, 0.0135, 0.0081,
  75. 0.2209, 0.0459, 0.0438, 0.0488, 0.0137,
  76. 0.002, 0.0003, 0.0008, 0.0039, 0.0024,
  77. 0.0005, 0.0004, 0.003, 0.056, 0.0026]
  78. SPLIT_DENSITY_SLOW = [0.0086, 0.0004, 0.0568, 0.0003, 0.0032, 0.0005, 0.0004, 0.0013, 0.0016, 0.0648, 0.0198, 0.1285, 0.098, 0.0005, 0.0064, 0.0003, 0.0004, 0.0026, 0.0007, 0.0051, 0.0089, 0.0024, 0.0033, 0.0057, 0.0005, 0.0003, 0.001, 0.0045, 0.0091, 0.0006, 0.0005, 0.0321, 0.0059, 0.1105, 0.216, 0.1489, 0.0004, 0.0003, 0.0006, 0.0483]
  79. class Skipped(Exception):
  80. pass
  81. class TimeOutError(Exception):
  82. pass
  83. class DependencyError(Exception):
  84. pass
  85. def _indent(s, indent=4):
  86. """
  87. Add the given number of space characters to the beginning of
  88. every non-blank line in ``s``, and return the result.
  89. If the string ``s`` is Unicode, it is encoded using the stdout
  90. encoding and the ``backslashreplace`` error handler.
  91. """
  92. # This regexp matches the start of non-blank lines:
  93. return re.sub('(?m)^(?!$)', indent*' ', s)
  94. pdoctest._indent = _indent # type: ignore
  95. # override reporter to maintain windows and python3
  96. def _report_failure(self, out, test, example, got):
  97. """
  98. Report that the given example failed.
  99. """
  100. s = self._checker.output_difference(example, got, self.optionflags)
  101. s = s.encode('raw_unicode_escape').decode('utf8', 'ignore')
  102. out(self._failure_header(test, example) + s)
  103. if IS_WINDOWS:
  104. DocTestRunner.report_failure = _report_failure # type: ignore
  105. def convert_to_native_paths(lst):
  106. """
  107. Converts a list of '/' separated paths into a list of
  108. native (os.sep separated) paths and converts to lowercase
  109. if the system is case insensitive.
  110. """
  111. newlst = []
  112. for i, rv in enumerate(lst):
  113. rv = os.path.join(*rv.split("/"))
  114. # on windows the slash after the colon is dropped
  115. if sys.platform == "win32":
  116. pos = rv.find(':')
  117. if pos != -1:
  118. if rv[pos + 1] != '\\':
  119. rv = rv[:pos + 1] + '\\' + rv[pos + 1:]
  120. newlst.append(os.path.normcase(rv))
  121. return newlst
  122. def get_sympy_dir():
  123. """
  124. Returns the root SymPy directory and set the global value
  125. indicating whether the system is case sensitive or not.
  126. """
  127. this_file = os.path.abspath(__file__)
  128. sympy_dir = os.path.join(os.path.dirname(this_file), "..", "..")
  129. sympy_dir = os.path.normpath(sympy_dir)
  130. return os.path.normcase(sympy_dir)
  131. def setup_pprint():
  132. from sympy.interactive.printing import init_printing
  133. from sympy.printing.pretty.pretty import pprint_use_unicode
  134. import sympy.interactive.printing as interactive_printing
  135. # force pprint to be in ascii mode in doctests
  136. use_unicode_prev = pprint_use_unicode(False)
  137. # hook our nice, hash-stable strprinter
  138. init_printing(pretty_print=False)
  139. # Prevent init_printing() in doctests from affecting other doctests
  140. interactive_printing.NO_GLOBAL = True
  141. return use_unicode_prev
  142. @contextmanager
  143. def raise_on_deprecated():
  144. """Context manager to make DeprecationWarning raise an error
  145. This is to catch SymPyDeprecationWarning from library code while running
  146. tests and doctests. It is important to use this context manager around
  147. each individual test/doctest in case some tests modify the warning
  148. filters.
  149. """
  150. with warnings.catch_warnings():
  151. warnings.filterwarnings('error', '.*', DeprecationWarning, module='sympy.*')
  152. yield
  153. def run_in_subprocess_with_hash_randomization(
  154. function, function_args=(),
  155. function_kwargs=None, command=sys.executable,
  156. module='sympy.testing.runtests', force=False):
  157. """
  158. Run a function in a Python subprocess with hash randomization enabled.
  159. If hash randomization is not supported by the version of Python given, it
  160. returns False. Otherwise, it returns the exit value of the command. The
  161. function is passed to sys.exit(), so the return value of the function will
  162. be the return value.
  163. The environment variable PYTHONHASHSEED is used to seed Python's hash
  164. randomization. If it is set, this function will return False, because
  165. starting a new subprocess is unnecessary in that case. If it is not set,
  166. one is set at random, and the tests are run. Note that if this
  167. environment variable is set when Python starts, hash randomization is
  168. automatically enabled. To force a subprocess to be created even if
  169. PYTHONHASHSEED is set, pass ``force=True``. This flag will not force a
  170. subprocess in Python versions that do not support hash randomization (see
  171. below), because those versions of Python do not support the ``-R`` flag.
  172. ``function`` should be a string name of a function that is importable from
  173. the module ``module``, like "_test". The default for ``module`` is
  174. "sympy.testing.runtests". ``function_args`` and ``function_kwargs``
  175. should be a repr-able tuple and dict, respectively. The default Python
  176. command is sys.executable, which is the currently running Python command.
  177. This function is necessary because the seed for hash randomization must be
  178. set by the environment variable before Python starts. Hence, in order to
  179. use a predetermined seed for tests, we must start Python in a separate
  180. subprocess.
  181. Hash randomization was added in the minor Python versions 2.6.8, 2.7.3,
  182. 3.1.5, and 3.2.3, and is enabled by default in all Python versions after
  183. and including 3.3.0.
  184. Examples
  185. ========
  186. >>> from sympy.testing.runtests import (
  187. ... run_in_subprocess_with_hash_randomization)
  188. >>> # run the core tests in verbose mode
  189. >>> run_in_subprocess_with_hash_randomization("_test",
  190. ... function_args=("core",),
  191. ... function_kwargs={'verbose': True}) # doctest: +SKIP
  192. # Will return 0 if sys.executable supports hash randomization and tests
  193. # pass, 1 if they fail, and False if it does not support hash
  194. # randomization.
  195. """
  196. cwd = get_sympy_dir()
  197. # Note, we must return False everywhere, not None, as subprocess.call will
  198. # sometimes return None.
  199. # First check if the Python version supports hash randomization
  200. # If it does not have this support, it won't recognize the -R flag
  201. p = subprocess.Popen([command, "-RV"], stdout=subprocess.PIPE,
  202. stderr=subprocess.STDOUT, cwd=cwd)
  203. p.communicate()
  204. if p.returncode != 0:
  205. return False
  206. hash_seed = os.getenv("PYTHONHASHSEED")
  207. if not hash_seed:
  208. os.environ["PYTHONHASHSEED"] = str(random.randrange(2**32))
  209. else:
  210. if not force:
  211. return False
  212. function_kwargs = function_kwargs or {}
  213. # Now run the command
  214. commandstring = ("import sys; from %s import %s;sys.exit(%s(*%s, **%s))" %
  215. (module, function, function, repr(function_args),
  216. repr(function_kwargs)))
  217. try:
  218. p = subprocess.Popen([command, "-R", "-c", commandstring], cwd=cwd)
  219. p.communicate()
  220. except KeyboardInterrupt:
  221. p.wait()
  222. finally:
  223. # Put the environment variable back, so that it reads correctly for
  224. # the current Python process.
  225. if hash_seed is None:
  226. del os.environ["PYTHONHASHSEED"]
  227. else:
  228. os.environ["PYTHONHASHSEED"] = hash_seed
  229. return p.returncode
  230. def run_all_tests(test_args=(), test_kwargs=None,
  231. doctest_args=(), doctest_kwargs=None,
  232. examples_args=(), examples_kwargs=None):
  233. """
  234. Run all tests.
  235. Right now, this runs the regular tests (bin/test), the doctests
  236. (bin/doctest), and the examples (examples/all.py).
  237. This is what ``setup.py test`` uses.
  238. You can pass arguments and keyword arguments to the test functions that
  239. support them (for now, test, doctest, and the examples). See the
  240. docstrings of those functions for a description of the available options.
  241. For example, to run the solvers tests with colors turned off:
  242. >>> from sympy.testing.runtests import run_all_tests
  243. >>> run_all_tests(test_args=("solvers",),
  244. ... test_kwargs={"colors:False"}) # doctest: +SKIP
  245. """
  246. tests_successful = True
  247. test_kwargs = test_kwargs or {}
  248. doctest_kwargs = doctest_kwargs or {}
  249. examples_kwargs = examples_kwargs or {'quiet': True}
  250. try:
  251. # Regular tests
  252. if not test(*test_args, **test_kwargs):
  253. # some regular test fails, so set the tests_successful
  254. # flag to false and continue running the doctests
  255. tests_successful = False
  256. # Doctests
  257. print()
  258. if not doctest(*doctest_args, **doctest_kwargs):
  259. tests_successful = False
  260. # Examples
  261. print()
  262. sys.path.append("examples") # examples/all.py
  263. from all import run_examples # type: ignore
  264. if not run_examples(*examples_args, **examples_kwargs):
  265. tests_successful = False
  266. if tests_successful:
  267. return
  268. else:
  269. # Return nonzero exit code
  270. sys.exit(1)
  271. except KeyboardInterrupt:
  272. print()
  273. print("DO *NOT* COMMIT!")
  274. sys.exit(1)
  275. def test(*paths, subprocess=True, rerun=0, **kwargs):
  276. """
  277. Run tests in the specified test_*.py files.
  278. Tests in a particular test_*.py file are run if any of the given strings
  279. in ``paths`` matches a part of the test file's path. If ``paths=[]``,
  280. tests in all test_*.py files are run.
  281. Notes:
  282. - If sort=False, tests are run in random order (not default).
  283. - Paths can be entered in native system format or in unix,
  284. forward-slash format.
  285. - Files that are on the blacklist can be tested by providing
  286. their path; they are only excluded if no paths are given.
  287. **Explanation of test results**
  288. ====== ===============================================================
  289. Output Meaning
  290. ====== ===============================================================
  291. . passed
  292. F failed
  293. X XPassed (expected to fail but passed)
  294. f XFAILed (expected to fail and indeed failed)
  295. s skipped
  296. w slow
  297. T timeout (e.g., when ``--timeout`` is used)
  298. K KeyboardInterrupt (when running the slow tests with ``--slow``,
  299. you can interrupt one of them without killing the test runner)
  300. ====== ===============================================================
  301. Colors have no additional meaning and are used just to facilitate
  302. interpreting the output.
  303. Examples
  304. ========
  305. >>> import sympy
  306. Run all tests:
  307. >>> sympy.test() # doctest: +SKIP
  308. Run one file:
  309. >>> sympy.test("sympy/core/tests/test_basic.py") # doctest: +SKIP
  310. >>> sympy.test("_basic") # doctest: +SKIP
  311. Run all tests in sympy/functions/ and some particular file:
  312. >>> sympy.test("sympy/core/tests/test_basic.py",
  313. ... "sympy/functions") # doctest: +SKIP
  314. Run all tests in sympy/core and sympy/utilities:
  315. >>> sympy.test("/core", "/util") # doctest: +SKIP
  316. Run specific test from a file:
  317. >>> sympy.test("sympy/core/tests/test_basic.py",
  318. ... kw="test_equality") # doctest: +SKIP
  319. Run specific test from any file:
  320. >>> sympy.test(kw="subs") # doctest: +SKIP
  321. Run the tests with verbose mode on:
  322. >>> sympy.test(verbose=True) # doctest: +SKIP
  323. Do not sort the test output:
  324. >>> sympy.test(sort=False) # doctest: +SKIP
  325. Turn on post-mortem pdb:
  326. >>> sympy.test(pdb=True) # doctest: +SKIP
  327. Turn off colors:
  328. >>> sympy.test(colors=False) # doctest: +SKIP
  329. Force colors, even when the output is not to a terminal (this is useful,
  330. e.g., if you are piping to ``less -r`` and you still want colors)
  331. >>> sympy.test(force_colors=False) # doctest: +SKIP
  332. The traceback verboseness can be set to "short" or "no" (default is
  333. "short")
  334. >>> sympy.test(tb='no') # doctest: +SKIP
  335. The ``split`` option can be passed to split the test run into parts. The
  336. split currently only splits the test files, though this may change in the
  337. future. ``split`` should be a string of the form 'a/b', which will run
  338. part ``a`` of ``b``. For instance, to run the first half of the test suite:
  339. >>> sympy.test(split='1/2') # doctest: +SKIP
  340. The ``time_balance`` option can be passed in conjunction with ``split``.
  341. If ``time_balance=True`` (the default for ``sympy.test``), SymPy will attempt
  342. to split the tests such that each split takes equal time. This heuristic
  343. for balancing is based on pre-recorded test data.
  344. >>> sympy.test(split='1/2', time_balance=True) # doctest: +SKIP
  345. You can disable running the tests in a separate subprocess using
  346. ``subprocess=False``. This is done to support seeding hash randomization,
  347. which is enabled by default in the Python versions where it is supported.
  348. If subprocess=False, hash randomization is enabled/disabled according to
  349. whether it has been enabled or not in the calling Python process.
  350. However, even if it is enabled, the seed cannot be printed unless it is
  351. called from a new Python process.
  352. Hash randomization was added in the minor Python versions 2.6.8, 2.7.3,
  353. 3.1.5, and 3.2.3, and is enabled by default in all Python versions after
  354. and including 3.3.0.
  355. If hash randomization is not supported ``subprocess=False`` is used
  356. automatically.
  357. >>> sympy.test(subprocess=False) # doctest: +SKIP
  358. To set the hash randomization seed, set the environment variable
  359. ``PYTHONHASHSEED`` before running the tests. This can be done from within
  360. Python using
  361. >>> import os
  362. >>> os.environ['PYTHONHASHSEED'] = '42' # doctest: +SKIP
  363. Or from the command line using
  364. $ PYTHONHASHSEED=42 ./bin/test
  365. If the seed is not set, a random seed will be chosen.
  366. Note that to reproduce the same hash values, you must use both the same seed
  367. as well as the same architecture (32-bit vs. 64-bit).
  368. """
  369. # count up from 0, do not print 0
  370. print_counter = lambda i : (print("rerun %d" % (rerun-i))
  371. if rerun-i else None)
  372. if subprocess:
  373. # loop backwards so last i is 0
  374. for i in range(rerun, -1, -1):
  375. print_counter(i)
  376. ret = run_in_subprocess_with_hash_randomization("_test",
  377. function_args=paths, function_kwargs=kwargs)
  378. if ret is False:
  379. break
  380. val = not bool(ret)
  381. # exit on the first failure or if done
  382. if not val or i == 0:
  383. return val
  384. # rerun even if hash randomization is not supported
  385. for i in range(rerun, -1, -1):
  386. print_counter(i)
  387. val = not bool(_test(*paths, **kwargs))
  388. if not val or i == 0:
  389. return val
  390. def _test(*paths,
  391. verbose=False, tb="short", kw=None, pdb=False, colors=True,
  392. force_colors=False, sort=True, seed=None, timeout=False,
  393. fail_on_timeout=False, slow=False, enhance_asserts=False, split=None,
  394. time_balance=True, blacklist=(),
  395. fast_threshold=None, slow_threshold=None):
  396. """
  397. Internal function that actually runs the tests.
  398. All keyword arguments from ``test()`` are passed to this function except for
  399. ``subprocess``.
  400. Returns 0 if tests passed and 1 if they failed. See the docstring of
  401. ``test()`` for more information.
  402. """
  403. kw = kw or ()
  404. # ensure that kw is a tuple
  405. if isinstance(kw, str):
  406. kw = (kw,)
  407. post_mortem = pdb
  408. if seed is None:
  409. seed = random.randrange(100000000)
  410. if ON_CI and timeout is False:
  411. timeout = 595
  412. fail_on_timeout = True
  413. if ON_CI:
  414. blacklist = list(blacklist) + ['sympy/plotting/pygletplot/tests']
  415. blacklist = convert_to_native_paths(blacklist)
  416. r = PyTestReporter(verbose=verbose, tb=tb, colors=colors,
  417. force_colors=force_colors, split=split)
  418. t = SymPyTests(r, kw, post_mortem, seed,
  419. fast_threshold=fast_threshold,
  420. slow_threshold=slow_threshold)
  421. test_files = t.get_test_files('sympy')
  422. not_blacklisted = [f for f in test_files
  423. if not any(b in f for b in blacklist)]
  424. if len(paths) == 0:
  425. matched = not_blacklisted
  426. else:
  427. paths = convert_to_native_paths(paths)
  428. matched = []
  429. for f in not_blacklisted:
  430. basename = os.path.basename(f)
  431. for p in paths:
  432. if p in f or fnmatch(basename, p):
  433. matched.append(f)
  434. break
  435. density = None
  436. if time_balance:
  437. if slow:
  438. density = SPLIT_DENSITY_SLOW
  439. else:
  440. density = SPLIT_DENSITY
  441. if split:
  442. matched = split_list(matched, split, density=density)
  443. t._testfiles.extend(matched)
  444. return int(not t.test(sort=sort, timeout=timeout, slow=slow,
  445. enhance_asserts=enhance_asserts, fail_on_timeout=fail_on_timeout))
  446. def doctest(*paths, subprocess=True, rerun=0, **kwargs):
  447. r"""
  448. Runs doctests in all \*.py files in the SymPy directory which match
  449. any of the given strings in ``paths`` or all tests if paths=[].
  450. Notes:
  451. - Paths can be entered in native system format or in unix,
  452. forward-slash format.
  453. - Files that are on the blacklist can be tested by providing
  454. their path; they are only excluded if no paths are given.
  455. Examples
  456. ========
  457. >>> import sympy
  458. Run all tests:
  459. >>> sympy.doctest() # doctest: +SKIP
  460. Run one file:
  461. >>> sympy.doctest("sympy/core/basic.py") # doctest: +SKIP
  462. >>> sympy.doctest("polynomial.rst") # doctest: +SKIP
  463. Run all tests in sympy/functions/ and some particular file:
  464. >>> sympy.doctest("/functions", "basic.py") # doctest: +SKIP
  465. Run any file having polynomial in its name, doc/src/modules/polynomial.rst,
  466. sympy/functions/special/polynomials.py, and sympy/polys/polynomial.py:
  467. >>> sympy.doctest("polynomial") # doctest: +SKIP
  468. The ``split`` option can be passed to split the test run into parts. The
  469. split currently only splits the test files, though this may change in the
  470. future. ``split`` should be a string of the form 'a/b', which will run
  471. part ``a`` of ``b``. Note that the regular doctests and the Sphinx
  472. doctests are split independently. For instance, to run the first half of
  473. the test suite:
  474. >>> sympy.doctest(split='1/2') # doctest: +SKIP
  475. The ``subprocess`` and ``verbose`` options are the same as with the function
  476. ``test()`` (see the docstring of that function for more information) except
  477. that ``verbose`` may also be set equal to ``2`` in order to print
  478. individual doctest lines, as they are being tested.
  479. """
  480. # count up from 0, do not print 0
  481. print_counter = lambda i : (print("rerun %d" % (rerun-i))
  482. if rerun-i else None)
  483. if subprocess:
  484. # loop backwards so last i is 0
  485. for i in range(rerun, -1, -1):
  486. print_counter(i)
  487. ret = run_in_subprocess_with_hash_randomization("_doctest",
  488. function_args=paths, function_kwargs=kwargs)
  489. if ret is False:
  490. break
  491. val = not bool(ret)
  492. # exit on the first failure or if done
  493. if not val or i == 0:
  494. return val
  495. # rerun even if hash randomization is not supported
  496. for i in range(rerun, -1, -1):
  497. print_counter(i)
  498. val = not bool(_doctest(*paths, **kwargs))
  499. if not val or i == 0:
  500. return val
  501. def _get_doctest_blacklist():
  502. '''Get the default blacklist for the doctests'''
  503. blacklist = []
  504. blacklist.extend([
  505. "doc/src/modules/plotting.rst", # generates live plots
  506. "doc/src/modules/physics/mechanics/autolev_parser.rst",
  507. "sympy/codegen/array_utils.py", # raises deprecation warning
  508. "sympy/core/compatibility.py", # backwards compatibility shim, importing it triggers a deprecation warning
  509. "sympy/core/trace.py", # backwards compatibility shim, importing it triggers a deprecation warning
  510. "sympy/galgebra.py", # no longer part of SymPy
  511. "sympy/parsing/autolev/_antlr/autolevlexer.py", # generated code
  512. "sympy/parsing/autolev/_antlr/autolevlistener.py", # generated code
  513. "sympy/parsing/autolev/_antlr/autolevparser.py", # generated code
  514. "sympy/parsing/latex/_antlr/latexlexer.py", # generated code
  515. "sympy/parsing/latex/_antlr/latexparser.py", # generated code
  516. "sympy/plotting/pygletplot/__init__.py", # crashes on some systems
  517. "sympy/plotting/pygletplot/plot.py", # crashes on some systems
  518. "sympy/printing/ccode.py", # backwards compatibility shim, importing it breaks the codegen doctests
  519. "sympy/printing/cxxcode.py", # backwards compatibility shim, importing it breaks the codegen doctests
  520. "sympy/printing/fcode.py", # backwards compatibility shim, importing it breaks the codegen doctests
  521. "sympy/testing/randtest.py", # backwards compatibility shim, importing it triggers a deprecation warning
  522. "sympy/this.py", # prints text
  523. ])
  524. # autolev parser tests
  525. num = 12
  526. for i in range (1, num+1):
  527. blacklist.append("sympy/parsing/autolev/test-examples/ruletest" + str(i) + ".py")
  528. blacklist.extend(["sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py",
  529. "sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py",
  530. "sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py",
  531. "sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py"])
  532. if import_module('numpy') is None:
  533. blacklist.extend([
  534. "sympy/plotting/experimental_lambdify.py",
  535. "sympy/plotting/plot_implicit.py",
  536. "examples/advanced/autowrap_integrators.py",
  537. "examples/advanced/autowrap_ufuncify.py",
  538. "examples/intermediate/sample.py",
  539. "examples/intermediate/mplot2d.py",
  540. "examples/intermediate/mplot3d.py",
  541. "doc/src/modules/numeric-computation.rst"
  542. ])
  543. else:
  544. if import_module('matplotlib') is None:
  545. blacklist.extend([
  546. "examples/intermediate/mplot2d.py",
  547. "examples/intermediate/mplot3d.py"
  548. ])
  549. else:
  550. # Use a non-windowed backend, so that the tests work on CI
  551. import matplotlib
  552. matplotlib.use('Agg')
  553. if ON_CI or import_module('pyglet') is None:
  554. blacklist.extend(["sympy/plotting/pygletplot"])
  555. if import_module('aesara') is None:
  556. blacklist.extend([
  557. "sympy/printing/aesaracode.py",
  558. "doc/src/modules/numeric-computation.rst",
  559. ])
  560. if import_module('cupy') is None:
  561. blacklist.extend([
  562. "doc/src/modules/numeric-computation.rst",
  563. ])
  564. if import_module('jax') is None:
  565. blacklist.extend([
  566. "doc/src/modules/numeric-computation.rst",
  567. ])
  568. if import_module('antlr4') is None:
  569. blacklist.extend([
  570. "sympy/parsing/autolev/__init__.py",
  571. "sympy/parsing/latex/_parse_latex_antlr.py",
  572. ])
  573. if import_module('lfortran') is None:
  574. #throws ImportError when lfortran not installed
  575. blacklist.extend([
  576. "sympy/parsing/sym_expr.py",
  577. ])
  578. if import_module("scipy") is None:
  579. # throws ModuleNotFoundError when scipy not installed
  580. blacklist.extend([
  581. "doc/src/guides/solving/solve-numerically.md",
  582. "doc/src/guides/solving/solve-ode.md",
  583. ])
  584. if import_module("numpy") is None:
  585. # throws ModuleNotFoundError when numpy not installed
  586. blacklist.extend([
  587. "doc/src/guides/solving/solve-ode.md",
  588. "doc/src/guides/solving/solve-numerically.md",
  589. ])
  590. # disabled because of doctest failures in asmeurer's bot
  591. blacklist.extend([
  592. "sympy/utilities/autowrap.py",
  593. "examples/advanced/autowrap_integrators.py",
  594. "examples/advanced/autowrap_ufuncify.py"
  595. ])
  596. blacklist.extend([
  597. "sympy/conftest.py", # Depends on pytest
  598. ])
  599. # These are deprecated stubs to be removed:
  600. blacklist.extend([
  601. "sympy/utilities/tmpfiles.py",
  602. "sympy/utilities/pytest.py",
  603. "sympy/utilities/runtests.py",
  604. "sympy/utilities/quality_unicode.py",
  605. "sympy/utilities/randtest.py",
  606. ])
  607. blacklist = convert_to_native_paths(blacklist)
  608. return blacklist
  609. def _doctest(*paths, **kwargs):
  610. """
  611. Internal function that actually runs the doctests.
  612. All keyword arguments from ``doctest()`` are passed to this function
  613. except for ``subprocess``.
  614. Returns 0 if tests passed and 1 if they failed. See the docstrings of
  615. ``doctest()`` and ``test()`` for more information.
  616. """
  617. from sympy.printing.pretty.pretty import pprint_use_unicode
  618. normal = kwargs.get("normal", False)
  619. verbose = kwargs.get("verbose", False)
  620. colors = kwargs.get("colors", True)
  621. force_colors = kwargs.get("force_colors", False)
  622. blacklist = kwargs.get("blacklist", [])
  623. split = kwargs.get('split', None)
  624. blacklist.extend(_get_doctest_blacklist())
  625. # Use a non-windowed backend, so that the tests work on CI
  626. if import_module('matplotlib') is not None:
  627. import matplotlib
  628. matplotlib.use('Agg')
  629. # Disable warnings for external modules
  630. import sympy.external
  631. sympy.external.importtools.WARN_OLD_VERSION = False
  632. sympy.external.importtools.WARN_NOT_INSTALLED = False
  633. # Disable showing up of plots
  634. from sympy.plotting.plot import unset_show
  635. unset_show()
  636. r = PyTestReporter(verbose, split=split, colors=colors,\
  637. force_colors=force_colors)
  638. t = SymPyDocTests(r, normal)
  639. test_files = t.get_test_files('sympy')
  640. test_files.extend(t.get_test_files('examples', init_only=False))
  641. not_blacklisted = [f for f in test_files
  642. if not any(b in f for b in blacklist)]
  643. if len(paths) == 0:
  644. matched = not_blacklisted
  645. else:
  646. # take only what was requested...but not blacklisted items
  647. # and allow for partial match anywhere or fnmatch of name
  648. paths = convert_to_native_paths(paths)
  649. matched = []
  650. for f in not_blacklisted:
  651. basename = os.path.basename(f)
  652. for p in paths:
  653. if p in f or fnmatch(basename, p):
  654. matched.append(f)
  655. break
  656. matched.sort()
  657. if split:
  658. matched = split_list(matched, split)
  659. t._testfiles.extend(matched)
  660. # run the tests and record the result for this *py portion of the tests
  661. if t._testfiles:
  662. failed = not t.test()
  663. else:
  664. failed = False
  665. # N.B.
  666. # --------------------------------------------------------------------
  667. # Here we test *.rst and *.md files at or below doc/src. Code from these
  668. # must be self supporting in terms of imports since there is no importing
  669. # of necessary modules by doctest.testfile. If you try to pass *.py files
  670. # through this they might fail because they will lack the needed imports
  671. # and smarter parsing that can be done with source code.
  672. #
  673. test_files_rst = t.get_test_files('doc/src', '*.rst', init_only=False)
  674. test_files_md = t.get_test_files('doc/src', '*.md', init_only=False)
  675. test_files = test_files_rst + test_files_md
  676. test_files.sort()
  677. not_blacklisted = [f for f in test_files
  678. if not any(b in f for b in blacklist)]
  679. if len(paths) == 0:
  680. matched = not_blacklisted
  681. else:
  682. # Take only what was requested as long as it's not on the blacklist.
  683. # Paths were already made native in *py tests so don't repeat here.
  684. # There's no chance of having a *py file slip through since we
  685. # only have *rst files in test_files.
  686. matched = []
  687. for f in not_blacklisted:
  688. basename = os.path.basename(f)
  689. for p in paths:
  690. if p in f or fnmatch(basename, p):
  691. matched.append(f)
  692. break
  693. if split:
  694. matched = split_list(matched, split)
  695. first_report = True
  696. for rst_file in matched:
  697. if not os.path.isfile(rst_file):
  698. continue
  699. old_displayhook = sys.displayhook
  700. try:
  701. use_unicode_prev = setup_pprint()
  702. out = sympytestfile(
  703. rst_file, module_relative=False, encoding='utf-8',
  704. optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE |
  705. pdoctest.IGNORE_EXCEPTION_DETAIL)
  706. finally:
  707. # make sure we return to the original displayhook in case some
  708. # doctest has changed that
  709. sys.displayhook = old_displayhook
  710. # The NO_GLOBAL flag overrides the no_global flag to init_printing
  711. # if True
  712. import sympy.interactive.printing as interactive_printing
  713. interactive_printing.NO_GLOBAL = False
  714. pprint_use_unicode(use_unicode_prev)
  715. rstfailed, tested = out
  716. if tested:
  717. failed = rstfailed or failed
  718. if first_report:
  719. first_report = False
  720. msg = 'rst/md doctests start'
  721. if not t._testfiles:
  722. r.start(msg=msg)
  723. else:
  724. r.write_center(msg)
  725. print()
  726. # use as the id, everything past the first 'sympy'
  727. file_id = rst_file[rst_file.find('sympy') + len('sympy') + 1:]
  728. print(file_id, end=" ")
  729. # get at least the name out so it is know who is being tested
  730. wid = r.terminal_width - len(file_id) - 1 # update width
  731. test_file = '[%s]' % (tested)
  732. report = '[%s]' % (rstfailed or 'OK')
  733. print(''.join(
  734. [test_file, ' '*(wid - len(test_file) - len(report)), report])
  735. )
  736. # the doctests for *py will have printed this message already if there was
  737. # a failure, so now only print it if there was intervening reporting by
  738. # testing the *rst as evidenced by first_report no longer being True.
  739. if not first_report and failed:
  740. print()
  741. print("DO *NOT* COMMIT!")
  742. return int(failed)
  743. sp = re.compile(r'([0-9]+)/([1-9][0-9]*)')
  744. def split_list(l, split, density=None):
  745. """
  746. Splits a list into part a of b
  747. split should be a string of the form 'a/b'. For instance, '1/3' would give
  748. the split one of three.
  749. If the length of the list is not divisible by the number of splits, the
  750. last split will have more items.
  751. `density` may be specified as a list. If specified,
  752. tests will be balanced so that each split has as equal-as-possible
  753. amount of mass according to `density`.
  754. >>> from sympy.testing.runtests import split_list
  755. >>> a = list(range(10))
  756. >>> split_list(a, '1/3')
  757. [0, 1, 2]
  758. >>> split_list(a, '2/3')
  759. [3, 4, 5]
  760. >>> split_list(a, '3/3')
  761. [6, 7, 8, 9]
  762. """
  763. m = sp.match(split)
  764. if not m:
  765. raise ValueError("split must be a string of the form a/b where a and b are ints")
  766. i, t = map(int, m.groups())
  767. if not density:
  768. return l[(i - 1)*len(l)//t : i*len(l)//t]
  769. # normalize density
  770. tot = sum(density)
  771. density = [x / tot for x in density]
  772. def density_inv(x):
  773. """Interpolate the inverse to the cumulative
  774. distribution function given by density"""
  775. if x <= 0:
  776. return 0
  777. if x >= sum(density):
  778. return 1
  779. # find the first time the cumulative sum surpasses x
  780. # and linearly interpolate
  781. cumm = 0
  782. for i, d in enumerate(density):
  783. cumm += d
  784. if cumm >= x:
  785. break
  786. frac = (d - (cumm - x)) / d
  787. return (i + frac) / len(density)
  788. lower_frac = density_inv((i - 1) / t)
  789. higher_frac = density_inv(i / t)
  790. return l[int(lower_frac*len(l)) : int(higher_frac*len(l))]
  791. from collections import namedtuple
  792. SymPyTestResults = namedtuple('SymPyTestResults', 'failed attempted')
  793. def sympytestfile(filename, module_relative=True, name=None, package=None,
  794. globs=None, verbose=None, report=True, optionflags=0,
  795. extraglobs=None, raise_on_error=False,
  796. parser=pdoctest.DocTestParser(), encoding=None):
  797. """
  798. Test examples in the given file. Return (#failures, #tests).
  799. Optional keyword arg ``module_relative`` specifies how filenames
  800. should be interpreted:
  801. - If ``module_relative`` is True (the default), then ``filename``
  802. specifies a module-relative path. By default, this path is
  803. relative to the calling module's directory; but if the
  804. ``package`` argument is specified, then it is relative to that
  805. package. To ensure os-independence, ``filename`` should use
  806. "/" characters to separate path segments, and should not
  807. be an absolute path (i.e., it may not begin with "/").
  808. - If ``module_relative`` is False, then ``filename`` specifies an
  809. os-specific path. The path may be absolute or relative (to
  810. the current working directory).
  811. Optional keyword arg ``name`` gives the name of the test; by default
  812. use the file's basename.
  813. Optional keyword argument ``package`` is a Python package or the
  814. name of a Python package whose directory should be used as the
  815. base directory for a module relative filename. If no package is
  816. specified, then the calling module's directory is used as the base
  817. directory for module relative filenames. It is an error to
  818. specify ``package`` if ``module_relative`` is False.
  819. Optional keyword arg ``globs`` gives a dict to be used as the globals
  820. when executing examples; by default, use {}. A copy of this dict
  821. is actually used for each docstring, so that each docstring's
  822. examples start with a clean slate.
  823. Optional keyword arg ``extraglobs`` gives a dictionary that should be
  824. merged into the globals that are used to execute examples. By
  825. default, no extra globals are used.
  826. Optional keyword arg ``verbose`` prints lots of stuff if true, prints
  827. only failures if false; by default, it's true iff "-v" is in sys.argv.
  828. Optional keyword arg ``report`` prints a summary at the end when true,
  829. else prints nothing at the end. In verbose mode, the summary is
  830. detailed, else very brief (in fact, empty if all tests passed).
  831. Optional keyword arg ``optionflags`` or's together module constants,
  832. and defaults to 0. Possible values (see the docs for details):
  833. - DONT_ACCEPT_TRUE_FOR_1
  834. - DONT_ACCEPT_BLANKLINE
  835. - NORMALIZE_WHITESPACE
  836. - ELLIPSIS
  837. - SKIP
  838. - IGNORE_EXCEPTION_DETAIL
  839. - REPORT_UDIFF
  840. - REPORT_CDIFF
  841. - REPORT_NDIFF
  842. - REPORT_ONLY_FIRST_FAILURE
  843. Optional keyword arg ``raise_on_error`` raises an exception on the
  844. first unexpected exception or failure. This allows failures to be
  845. post-mortem debugged.
  846. Optional keyword arg ``parser`` specifies a DocTestParser (or
  847. subclass) that should be used to extract tests from the files.
  848. Optional keyword arg ``encoding`` specifies an encoding that should
  849. be used to convert the file to unicode.
  850. Advanced tomfoolery: testmod runs methods of a local instance of
  851. class doctest.Tester, then merges the results into (or creates)
  852. global Tester instance doctest.master. Methods of doctest.master
  853. can be called directly too, if you want to do something unusual.
  854. Passing report=0 to testmod is especially useful then, to delay
  855. displaying a summary. Invoke doctest.master.summarize(verbose)
  856. when you're done fiddling.
  857. """
  858. if package and not module_relative:
  859. raise ValueError("Package may only be specified for module-"
  860. "relative paths.")
  861. # Relativize the path
  862. text, filename = pdoctest._load_testfile(
  863. filename, package, module_relative, encoding)
  864. # If no name was given, then use the file's name.
  865. if name is None:
  866. name = os.path.basename(filename)
  867. # Assemble the globals.
  868. if globs is None:
  869. globs = {}
  870. else:
  871. globs = globs.copy()
  872. if extraglobs is not None:
  873. globs.update(extraglobs)
  874. if '__name__' not in globs:
  875. globs['__name__'] = '__main__'
  876. if raise_on_error:
  877. runner = pdoctest.DebugRunner(verbose=verbose, optionflags=optionflags)
  878. else:
  879. runner = SymPyDocTestRunner(verbose=verbose, optionflags=optionflags)
  880. runner._checker = SymPyOutputChecker()
  881. # Read the file, convert it to a test, and run it.
  882. test = parser.get_doctest(text, globs, name, filename, 0)
  883. runner.run(test)
  884. if report:
  885. runner.summarize()
  886. if pdoctest.master is None:
  887. pdoctest.master = runner
  888. else:
  889. pdoctest.master.merge(runner)
  890. return SymPyTestResults(runner.failures, runner.tries)
  891. class SymPyTests:
  892. def __init__(self, reporter, kw="", post_mortem=False,
  893. seed=None, fast_threshold=None, slow_threshold=None):
  894. self._post_mortem = post_mortem
  895. self._kw = kw
  896. self._count = 0
  897. self._root_dir = get_sympy_dir()
  898. self._reporter = reporter
  899. self._reporter.root_dir(self._root_dir)
  900. self._testfiles = []
  901. self._seed = seed if seed is not None else random.random()
  902. # Defaults in seconds, from human / UX design limits
  903. # http://www.nngroup.com/articles/response-times-3-important-limits/
  904. #
  905. # These defaults are *NOT* set in stone as we are measuring different
  906. # things, so others feel free to come up with a better yardstick :)
  907. if fast_threshold:
  908. self._fast_threshold = float(fast_threshold)
  909. else:
  910. self._fast_threshold = 8
  911. if slow_threshold:
  912. self._slow_threshold = float(slow_threshold)
  913. else:
  914. self._slow_threshold = 10
  915. def test(self, sort=False, timeout=False, slow=False,
  916. enhance_asserts=False, fail_on_timeout=False):
  917. """
  918. Runs the tests returning True if all tests pass, otherwise False.
  919. If sort=False run tests in random order.
  920. """
  921. if sort:
  922. self._testfiles.sort()
  923. elif slow:
  924. pass
  925. else:
  926. random.seed(self._seed)
  927. random.shuffle(self._testfiles)
  928. self._reporter.start(self._seed)
  929. for f in self._testfiles:
  930. try:
  931. self.test_file(f, sort, timeout, slow,
  932. enhance_asserts, fail_on_timeout)
  933. except KeyboardInterrupt:
  934. print(" interrupted by user")
  935. self._reporter.finish()
  936. raise
  937. return self._reporter.finish()
  938. def _enhance_asserts(self, source):
  939. from ast import (NodeTransformer, Compare, Name, Store, Load, Tuple,
  940. Assign, BinOp, Str, Mod, Assert, parse, fix_missing_locations)
  941. ops = {"Eq": '==', "NotEq": '!=', "Lt": '<', "LtE": '<=',
  942. "Gt": '>', "GtE": '>=', "Is": 'is', "IsNot": 'is not',
  943. "In": 'in', "NotIn": 'not in'}
  944. class Transform(NodeTransformer):
  945. def visit_Assert(self, stmt):
  946. if isinstance(stmt.test, Compare):
  947. compare = stmt.test
  948. values = [compare.left] + compare.comparators
  949. names = [ "_%s" % i for i, _ in enumerate(values) ]
  950. names_store = [ Name(n, Store()) for n in names ]
  951. names_load = [ Name(n, Load()) for n in names ]
  952. target = Tuple(names_store, Store())
  953. value = Tuple(values, Load())
  954. assign = Assign([target], value)
  955. new_compare = Compare(names_load[0], compare.ops, names_load[1:])
  956. msg_format = "\n%s " + "\n%s ".join([ ops[op.__class__.__name__] for op in compare.ops ]) + "\n%s"
  957. msg = BinOp(Str(msg_format), Mod(), Tuple(names_load, Load()))
  958. test = Assert(new_compare, msg, lineno=stmt.lineno, col_offset=stmt.col_offset)
  959. return [assign, test]
  960. else:
  961. return stmt
  962. tree = parse(source)
  963. new_tree = Transform().visit(tree)
  964. return fix_missing_locations(new_tree)
  965. def test_file(self, filename, sort=True, timeout=False, slow=False,
  966. enhance_asserts=False, fail_on_timeout=False):
  967. reporter = self._reporter
  968. funcs = []
  969. try:
  970. gl = {'__file__': filename}
  971. try:
  972. open_file = lambda: open(filename, encoding="utf8")
  973. with open_file() as f:
  974. source = f.read()
  975. if self._kw:
  976. for l in source.splitlines():
  977. if l.lstrip().startswith('def '):
  978. if any(l.lower().find(k.lower()) != -1 for k in self._kw):
  979. break
  980. else:
  981. return
  982. if enhance_asserts:
  983. try:
  984. source = self._enhance_asserts(source)
  985. except ImportError:
  986. pass
  987. code = compile(source, filename, "exec", flags=0, dont_inherit=True)
  988. exec(code, gl)
  989. except (SystemExit, KeyboardInterrupt):
  990. raise
  991. except ImportError:
  992. reporter.import_error(filename, sys.exc_info())
  993. return
  994. except Exception:
  995. reporter.test_exception(sys.exc_info())
  996. clear_cache()
  997. self._count += 1
  998. random.seed(self._seed)
  999. disabled = gl.get("disabled", False)
  1000. if not disabled:
  1001. # we need to filter only those functions that begin with 'test_'
  1002. # We have to be careful about decorated functions. As long as
  1003. # the decorator uses functools.wraps, we can detect it.
  1004. funcs = []
  1005. for f in gl:
  1006. if (f.startswith("test_") and (inspect.isfunction(gl[f])
  1007. or inspect.ismethod(gl[f]))):
  1008. func = gl[f]
  1009. # Handle multiple decorators
  1010. while hasattr(func, '__wrapped__'):
  1011. func = func.__wrapped__
  1012. if inspect.getsourcefile(func) == filename:
  1013. funcs.append(gl[f])
  1014. if slow:
  1015. funcs = [f for f in funcs if getattr(f, '_slow', False)]
  1016. # Sorting of XFAILed functions isn't fixed yet :-(
  1017. funcs.sort(key=lambda x: inspect.getsourcelines(x)[1])
  1018. i = 0
  1019. while i < len(funcs):
  1020. if inspect.isgeneratorfunction(funcs[i]):
  1021. # some tests can be generators, that return the actual
  1022. # test functions. We unpack it below:
  1023. f = funcs.pop(i)
  1024. for fg in f():
  1025. func = fg[0]
  1026. args = fg[1:]
  1027. fgw = lambda: func(*args)
  1028. funcs.insert(i, fgw)
  1029. i += 1
  1030. else:
  1031. i += 1
  1032. # drop functions that are not selected with the keyword expression:
  1033. funcs = [x for x in funcs if self.matches(x)]
  1034. if not funcs:
  1035. return
  1036. except Exception:
  1037. reporter.entering_filename(filename, len(funcs))
  1038. raise
  1039. reporter.entering_filename(filename, len(funcs))
  1040. if not sort:
  1041. random.shuffle(funcs)
  1042. for f in funcs:
  1043. start = time.time()
  1044. reporter.entering_test(f)
  1045. try:
  1046. if getattr(f, '_slow', False) and not slow:
  1047. raise Skipped("Slow")
  1048. with raise_on_deprecated():
  1049. if timeout:
  1050. self._timeout(f, timeout, fail_on_timeout)
  1051. else:
  1052. random.seed(self._seed)
  1053. f()
  1054. except KeyboardInterrupt:
  1055. if getattr(f, '_slow', False):
  1056. reporter.test_skip("KeyboardInterrupt")
  1057. else:
  1058. raise
  1059. except Exception:
  1060. if timeout:
  1061. signal.alarm(0) # Disable the alarm. It could not be handled before.
  1062. t, v, tr = sys.exc_info()
  1063. if t is AssertionError:
  1064. reporter.test_fail((t, v, tr))
  1065. if self._post_mortem:
  1066. pdb.post_mortem(tr)
  1067. elif t.__name__ == "Skipped":
  1068. reporter.test_skip(v)
  1069. elif t.__name__ == "XFail":
  1070. reporter.test_xfail()
  1071. elif t.__name__ == "XPass":
  1072. reporter.test_xpass(v)
  1073. else:
  1074. reporter.test_exception((t, v, tr))
  1075. if self._post_mortem:
  1076. pdb.post_mortem(tr)
  1077. else:
  1078. reporter.test_pass()
  1079. taken = time.time() - start
  1080. if taken > self._slow_threshold:
  1081. filename = os.path.relpath(filename, reporter._root_dir)
  1082. reporter.slow_test_functions.append(
  1083. (filename + "::" + f.__name__, taken))
  1084. if getattr(f, '_slow', False) and slow:
  1085. if taken < self._fast_threshold:
  1086. filename = os.path.relpath(filename, reporter._root_dir)
  1087. reporter.fast_test_functions.append(
  1088. (filename + "::" + f.__name__, taken))
  1089. reporter.leaving_filename()
  1090. def _timeout(self, function, timeout, fail_on_timeout):
  1091. def callback(x, y):
  1092. signal.alarm(0)
  1093. if fail_on_timeout:
  1094. raise TimeOutError("Timed out after %d seconds" % timeout)
  1095. else:
  1096. raise Skipped("Timeout")
  1097. signal.signal(signal.SIGALRM, callback)
  1098. signal.alarm(timeout) # Set an alarm with a given timeout
  1099. function()
  1100. signal.alarm(0) # Disable the alarm
  1101. def matches(self, x):
  1102. """
  1103. Does the keyword expression self._kw match "x"? Returns True/False.
  1104. Always returns True if self._kw is "".
  1105. """
  1106. if not self._kw:
  1107. return True
  1108. for kw in self._kw:
  1109. if x.__name__.lower().find(kw.lower()) != -1:
  1110. return True
  1111. return False
  1112. def get_test_files(self, dir, pat='test_*.py'):
  1113. """
  1114. Returns the list of test_*.py (default) files at or below directory
  1115. ``dir`` relative to the SymPy home directory.
  1116. """
  1117. dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
  1118. g = []
  1119. for path, folders, files in os.walk(dir):
  1120. g.extend([os.path.join(path, f) for f in files if fnmatch(f, pat)])
  1121. return sorted([os.path.normcase(gi) for gi in g])
  1122. class SymPyDocTests:
  1123. def __init__(self, reporter, normal):
  1124. self._count = 0
  1125. self._root_dir = get_sympy_dir()
  1126. self._reporter = reporter
  1127. self._reporter.root_dir(self._root_dir)
  1128. self._normal = normal
  1129. self._testfiles = []
  1130. def test(self):
  1131. """
  1132. Runs the tests and returns True if all tests pass, otherwise False.
  1133. """
  1134. self._reporter.start()
  1135. for f in self._testfiles:
  1136. try:
  1137. self.test_file(f)
  1138. except KeyboardInterrupt:
  1139. print(" interrupted by user")
  1140. self._reporter.finish()
  1141. raise
  1142. return self._reporter.finish()
  1143. def test_file(self, filename):
  1144. clear_cache()
  1145. from io import StringIO
  1146. import sympy.interactive.printing as interactive_printing
  1147. from sympy.printing.pretty.pretty import pprint_use_unicode
  1148. rel_name = filename[len(self._root_dir) + 1:]
  1149. dirname, file = os.path.split(filename)
  1150. module = rel_name.replace(os.sep, '.')[:-3]
  1151. if rel_name.startswith("examples"):
  1152. # Examples files do not have __init__.py files,
  1153. # So we have to temporarily extend sys.path to import them
  1154. sys.path.insert(0, dirname)
  1155. module = file[:-3] # remove ".py"
  1156. try:
  1157. module = pdoctest._normalize_module(module)
  1158. tests = SymPyDocTestFinder().find(module)
  1159. except (SystemExit, KeyboardInterrupt):
  1160. raise
  1161. except ImportError:
  1162. self._reporter.import_error(filename, sys.exc_info())
  1163. return
  1164. finally:
  1165. if rel_name.startswith("examples"):
  1166. del sys.path[0]
  1167. tests = [test for test in tests if len(test.examples) > 0]
  1168. # By default tests are sorted by alphabetical order by function name.
  1169. # We sort by line number so one can edit the file sequentially from
  1170. # bottom to top. However, if there are decorated functions, their line
  1171. # numbers will be too large and for now one must just search for these
  1172. # by text and function name.
  1173. tests.sort(key=lambda x: -x.lineno)
  1174. if not tests:
  1175. return
  1176. self._reporter.entering_filename(filename, len(tests))
  1177. for test in tests:
  1178. assert len(test.examples) != 0
  1179. if self._reporter._verbose:
  1180. self._reporter.write("\n{} ".format(test.name))
  1181. # check if there are external dependencies which need to be met
  1182. if '_doctest_depends_on' in test.globs:
  1183. try:
  1184. self._check_dependencies(**test.globs['_doctest_depends_on'])
  1185. except DependencyError as e:
  1186. self._reporter.test_skip(v=str(e))
  1187. continue
  1188. runner = SymPyDocTestRunner(verbose=self._reporter._verbose==2,
  1189. optionflags=pdoctest.ELLIPSIS |
  1190. pdoctest.NORMALIZE_WHITESPACE |
  1191. pdoctest.IGNORE_EXCEPTION_DETAIL)
  1192. runner._checker = SymPyOutputChecker()
  1193. old = sys.stdout
  1194. new = old if self._reporter._verbose==2 else StringIO()
  1195. sys.stdout = new
  1196. # If the testing is normal, the doctests get importing magic to
  1197. # provide the global namespace. If not normal (the default) then
  1198. # then must run on their own; all imports must be explicit within
  1199. # a function's docstring. Once imported that import will be
  1200. # available to the rest of the tests in a given function's
  1201. # docstring (unless clear_globs=True below).
  1202. if not self._normal:
  1203. test.globs = {}
  1204. # if this is uncommented then all the test would get is what
  1205. # comes by default with a "from sympy import *"
  1206. #exec('from sympy import *') in test.globs
  1207. old_displayhook = sys.displayhook
  1208. use_unicode_prev = setup_pprint()
  1209. try:
  1210. f, t = runner.run(test,
  1211. out=new.write, clear_globs=False)
  1212. except KeyboardInterrupt:
  1213. raise
  1214. finally:
  1215. sys.stdout = old
  1216. if f > 0:
  1217. self._reporter.doctest_fail(test.name, new.getvalue())
  1218. else:
  1219. self._reporter.test_pass()
  1220. sys.displayhook = old_displayhook
  1221. interactive_printing.NO_GLOBAL = False
  1222. pprint_use_unicode(use_unicode_prev)
  1223. self._reporter.leaving_filename()
  1224. def get_test_files(self, dir, pat='*.py', init_only=True):
  1225. r"""
  1226. Returns the list of \*.py files (default) from which docstrings
  1227. will be tested which are at or below directory ``dir``. By default,
  1228. only those that have an __init__.py in their parent directory
  1229. and do not start with ``test_`` will be included.
  1230. """
  1231. def importable(x):
  1232. """
  1233. Checks if given pathname x is an importable module by checking for
  1234. __init__.py file.
  1235. Returns True/False.
  1236. Currently we only test if the __init__.py file exists in the
  1237. directory with the file "x" (in theory we should also test all the
  1238. parent dirs).
  1239. """
  1240. init_py = os.path.join(os.path.dirname(x), "__init__.py")
  1241. return os.path.exists(init_py)
  1242. dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
  1243. g = []
  1244. for path, folders, files in os.walk(dir):
  1245. g.extend([os.path.join(path, f) for f in files
  1246. if not f.startswith('test_') and fnmatch(f, pat)])
  1247. if init_only:
  1248. # skip files that are not importable (i.e. missing __init__.py)
  1249. g = [x for x in g if importable(x)]
  1250. return [os.path.normcase(gi) for gi in g]
  1251. def _check_dependencies(self,
  1252. executables=(),
  1253. modules=(),
  1254. disable_viewers=(),
  1255. python_version=(3, 5)):
  1256. """
  1257. Checks if the dependencies for the test are installed.
  1258. Raises ``DependencyError`` it at least one dependency is not installed.
  1259. """
  1260. for executable in executables:
  1261. if not shutil.which(executable):
  1262. raise DependencyError("Could not find %s" % executable)
  1263. for module in modules:
  1264. if module == 'matplotlib':
  1265. matplotlib = import_module(
  1266. 'matplotlib',
  1267. import_kwargs={'fromlist':
  1268. ['pyplot', 'cm', 'collections']},
  1269. min_module_version='1.0.0', catch=(RuntimeError,))
  1270. if matplotlib is None:
  1271. raise DependencyError("Could not import matplotlib")
  1272. else:
  1273. if not import_module(module):
  1274. raise DependencyError("Could not import %s" % module)
  1275. if disable_viewers:
  1276. tempdir = tempfile.mkdtemp()
  1277. os.environ['PATH'] = '%s:%s' % (tempdir, os.environ['PATH'])
  1278. vw = ('#!/usr/bin/env python3\n'
  1279. 'import sys\n'
  1280. 'if len(sys.argv) <= 1:\n'
  1281. ' exit("wrong number of args")\n')
  1282. for viewer in disable_viewers:
  1283. with open(os.path.join(tempdir, viewer), 'w') as fh:
  1284. fh.write(vw)
  1285. # make the file executable
  1286. os.chmod(os.path.join(tempdir, viewer),
  1287. stat.S_IREAD | stat.S_IWRITE | stat.S_IXUSR)
  1288. if python_version:
  1289. if sys.version_info < python_version:
  1290. raise DependencyError("Requires Python >= " + '.'.join(map(str, python_version)))
  1291. if 'pyglet' in modules:
  1292. # monkey-patch pyglet s.t. it does not open a window during
  1293. # doctesting
  1294. import pyglet
  1295. class DummyWindow:
  1296. def __init__(self, *args, **kwargs):
  1297. self.has_exit = True
  1298. self.width = 600
  1299. self.height = 400
  1300. def set_vsync(self, x):
  1301. pass
  1302. def switch_to(self):
  1303. pass
  1304. def push_handlers(self, x):
  1305. pass
  1306. def close(self):
  1307. pass
  1308. pyglet.window.Window = DummyWindow
  1309. class SymPyDocTestFinder(DocTestFinder):
  1310. """
  1311. A class used to extract the DocTests that are relevant to a given
  1312. object, from its docstring and the docstrings of its contained
  1313. objects. Doctests can currently be extracted from the following
  1314. object types: modules, functions, classes, methods, staticmethods,
  1315. classmethods, and properties.
  1316. Modified from doctest's version to look harder for code that
  1317. appears comes from a different module. For example, the @vectorize
  1318. decorator makes it look like functions come from multidimensional.py
  1319. even though their code exists elsewhere.
  1320. """
  1321. def _find(self, tests, obj, name, module, source_lines, globs, seen):
  1322. """
  1323. Find tests for the given object and any contained objects, and
  1324. add them to ``tests``.
  1325. """
  1326. if self._verbose:
  1327. print('Finding tests in %s' % name)
  1328. # If we've already processed this object, then ignore it.
  1329. if id(obj) in seen:
  1330. return
  1331. seen[id(obj)] = 1
  1332. # Make sure we don't run doctests for classes outside of sympy, such
  1333. # as in numpy or scipy.
  1334. if inspect.isclass(obj):
  1335. if obj.__module__.split('.')[0] != 'sympy':
  1336. return
  1337. # Find a test for this object, and add it to the list of tests.
  1338. test = self._get_test(obj, name, module, globs, source_lines)
  1339. if test is not None:
  1340. tests.append(test)
  1341. if not self._recurse:
  1342. return
  1343. # Look for tests in a module's contained objects.
  1344. if inspect.ismodule(obj):
  1345. for rawname, val in obj.__dict__.items():
  1346. # Recurse to functions & classes.
  1347. if inspect.isfunction(val) or inspect.isclass(val):
  1348. # Make sure we don't run doctests functions or classes
  1349. # from different modules
  1350. if val.__module__ != module.__name__:
  1351. continue
  1352. assert self._from_module(module, val), \
  1353. "%s is not in module %s (rawname %s)" % (val, module, rawname)
  1354. try:
  1355. valname = '%s.%s' % (name, rawname)
  1356. self._find(tests, val, valname, module,
  1357. source_lines, globs, seen)
  1358. except KeyboardInterrupt:
  1359. raise
  1360. # Look for tests in a module's __test__ dictionary.
  1361. for valname, val in getattr(obj, '__test__', {}).items():
  1362. if not isinstance(valname, str):
  1363. raise ValueError("SymPyDocTestFinder.find: __test__ keys "
  1364. "must be strings: %r" %
  1365. (type(valname),))
  1366. if not (inspect.isfunction(val) or inspect.isclass(val) or
  1367. inspect.ismethod(val) or inspect.ismodule(val) or
  1368. isinstance(val, str)):
  1369. raise ValueError("SymPyDocTestFinder.find: __test__ values "
  1370. "must be strings, functions, methods, "
  1371. "classes, or modules: %r" %
  1372. (type(val),))
  1373. valname = '%s.__test__.%s' % (name, valname)
  1374. self._find(tests, val, valname, module, source_lines,
  1375. globs, seen)
  1376. # Look for tests in a class's contained objects.
  1377. if inspect.isclass(obj):
  1378. for valname, val in obj.__dict__.items():
  1379. # Special handling for staticmethod/classmethod.
  1380. if isinstance(val, staticmethod):
  1381. val = getattr(obj, valname)
  1382. if isinstance(val, classmethod):
  1383. val = getattr(obj, valname).__func__
  1384. # Recurse to methods, properties, and nested classes.
  1385. if ((inspect.isfunction(unwrap(val)) or
  1386. inspect.isclass(val) or
  1387. isinstance(val, property)) and
  1388. self._from_module(module, val)):
  1389. # Make sure we don't run doctests functions or classes
  1390. # from different modules
  1391. if isinstance(val, property):
  1392. if hasattr(val.fget, '__module__'):
  1393. if val.fget.__module__ != module.__name__:
  1394. continue
  1395. else:
  1396. if val.__module__ != module.__name__:
  1397. continue
  1398. assert self._from_module(module, val), \
  1399. "%s is not in module %s (valname %s)" % (
  1400. val, module, valname)
  1401. valname = '%s.%s' % (name, valname)
  1402. self._find(tests, val, valname, module, source_lines,
  1403. globs, seen)
  1404. def _get_test(self, obj, name, module, globs, source_lines):
  1405. """
  1406. Return a DocTest for the given object, if it defines a docstring;
  1407. otherwise, return None.
  1408. """
  1409. lineno = None
  1410. # Extract the object's docstring. If it does not have one,
  1411. # then return None (no test for this object).
  1412. if isinstance(obj, str):
  1413. # obj is a string in the case for objects in the polys package.
  1414. # Note that source_lines is a binary string (compiled polys
  1415. # modules), which can't be handled by _find_lineno so determine
  1416. # the line number here.
  1417. docstring = obj
  1418. matches = re.findall(r"line \d+", name)
  1419. assert len(matches) == 1, \
  1420. "string '%s' does not contain lineno " % name
  1421. # NOTE: this is not the exact linenumber but its better than no
  1422. # lineno ;)
  1423. lineno = int(matches[0][5:])
  1424. else:
  1425. try:
  1426. if obj.__doc__ is None:
  1427. docstring = ''
  1428. else:
  1429. docstring = obj.__doc__
  1430. if not isinstance(docstring, str):
  1431. docstring = str(docstring)
  1432. except (TypeError, AttributeError):
  1433. docstring = ''
  1434. # Don't bother if the docstring is empty.
  1435. if self._exclude_empty and not docstring:
  1436. return None
  1437. # check that properties have a docstring because _find_lineno
  1438. # assumes it
  1439. if isinstance(obj, property):
  1440. if obj.fget.__doc__ is None:
  1441. return None
  1442. # Find the docstring's location in the file.
  1443. if lineno is None:
  1444. obj = unwrap(obj)
  1445. # handling of properties is not implemented in _find_lineno so do
  1446. # it here
  1447. if hasattr(obj, 'func_closure') and obj.func_closure is not None:
  1448. tobj = obj.func_closure[0].cell_contents
  1449. elif isinstance(obj, property):
  1450. tobj = obj.fget
  1451. else:
  1452. tobj = obj
  1453. lineno = self._find_lineno(tobj, source_lines)
  1454. if lineno is None:
  1455. return None
  1456. # Return a DocTest for this object.
  1457. if module is None:
  1458. filename = None
  1459. else:
  1460. filename = getattr(module, '__file__', module.__name__)
  1461. if filename[-4:] in (".pyc", ".pyo"):
  1462. filename = filename[:-1]
  1463. globs['_doctest_depends_on'] = getattr(obj, '_doctest_depends_on', {})
  1464. return self._parser.get_doctest(docstring, globs, name,
  1465. filename, lineno)
  1466. class SymPyDocTestRunner(DocTestRunner):
  1467. """
  1468. A class used to run DocTest test cases, and accumulate statistics.
  1469. The ``run`` method is used to process a single DocTest case. It
  1470. returns a tuple ``(f, t)``, where ``t`` is the number of test cases
  1471. tried, and ``f`` is the number of test cases that failed.
  1472. Modified from the doctest version to not reset the sys.displayhook (see
  1473. issue 5140).
  1474. See the docstring of the original DocTestRunner for more information.
  1475. """
  1476. def run(self, test, compileflags=None, out=None, clear_globs=True):
  1477. """
  1478. Run the examples in ``test``, and display the results using the
  1479. writer function ``out``.
  1480. The examples are run in the namespace ``test.globs``. If
  1481. ``clear_globs`` is true (the default), then this namespace will
  1482. be cleared after the test runs, to help with garbage
  1483. collection. If you would like to examine the namespace after
  1484. the test completes, then use ``clear_globs=False``.
  1485. ``compileflags`` gives the set of flags that should be used by
  1486. the Python compiler when running the examples. If not
  1487. specified, then it will default to the set of future-import
  1488. flags that apply to ``globs``.
  1489. The output of each example is checked using
  1490. ``SymPyDocTestRunner.check_output``, and the results are
  1491. formatted by the ``SymPyDocTestRunner.report_*`` methods.
  1492. """
  1493. self.test = test
  1494. # Remove ``` from the end of example, which may appear in Markdown
  1495. # files
  1496. for example in test.examples:
  1497. example.want = example.want.replace('```\n', '')
  1498. example.exc_msg = example.exc_msg and example.exc_msg.replace('```\n', '')
  1499. if compileflags is None:
  1500. compileflags = pdoctest._extract_future_flags(test.globs)
  1501. save_stdout = sys.stdout
  1502. if out is None:
  1503. out = save_stdout.write
  1504. sys.stdout = self._fakeout
  1505. # Patch pdb.set_trace to restore sys.stdout during interactive
  1506. # debugging (so it's not still redirected to self._fakeout).
  1507. # Note that the interactive output will go to *our*
  1508. # save_stdout, even if that's not the real sys.stdout; this
  1509. # allows us to write test cases for the set_trace behavior.
  1510. save_set_trace = pdb.set_trace
  1511. self.debugger = pdoctest._OutputRedirectingPdb(save_stdout)
  1512. self.debugger.reset()
  1513. pdb.set_trace = self.debugger.set_trace
  1514. # Patch linecache.getlines, so we can see the example's source
  1515. # when we're inside the debugger.
  1516. self.save_linecache_getlines = pdoctest.linecache.getlines
  1517. linecache.getlines = self.__patched_linecache_getlines
  1518. # Fail for deprecation warnings
  1519. with raise_on_deprecated():
  1520. try:
  1521. return self.__run(test, compileflags, out)
  1522. finally:
  1523. sys.stdout = save_stdout
  1524. pdb.set_trace = save_set_trace
  1525. linecache.getlines = self.save_linecache_getlines
  1526. if clear_globs:
  1527. test.globs.clear()
  1528. # We have to override the name mangled methods.
  1529. monkeypatched_methods = [
  1530. 'patched_linecache_getlines',
  1531. 'run',
  1532. 'record_outcome'
  1533. ]
  1534. for method in monkeypatched_methods:
  1535. oldname = '_DocTestRunner__' + method
  1536. newname = '_SymPyDocTestRunner__' + method
  1537. setattr(SymPyDocTestRunner, newname, getattr(DocTestRunner, oldname))
  1538. class SymPyOutputChecker(pdoctest.OutputChecker):
  1539. """
  1540. Compared to the OutputChecker from the stdlib our OutputChecker class
  1541. supports numerical comparison of floats occurring in the output of the
  1542. doctest examples
  1543. """
  1544. def __init__(self):
  1545. # NOTE OutputChecker is an old-style class with no __init__ method,
  1546. # so we can't call the base class version of __init__ here
  1547. got_floats = r'(\d+\.\d*|\.\d+)'
  1548. # floats in the 'want' string may contain ellipses
  1549. want_floats = got_floats + r'(\.{3})?'
  1550. front_sep = r'\s|\+|\-|\*|,'
  1551. back_sep = front_sep + r'|j|e'
  1552. fbeg = r'^%s(?=%s|$)' % (got_floats, back_sep)
  1553. fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, got_floats, back_sep)
  1554. self.num_got_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))
  1555. fbeg = r'^%s(?=%s|$)' % (want_floats, back_sep)
  1556. fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, want_floats, back_sep)
  1557. self.num_want_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))
  1558. def check_output(self, want, got, optionflags):
  1559. """
  1560. Return True iff the actual output from an example (`got`)
  1561. matches the expected output (`want`). These strings are
  1562. always considered to match if they are identical; but
  1563. depending on what option flags the test runner is using,
  1564. several non-exact match types are also possible. See the
  1565. documentation for `TestRunner` for more information about
  1566. option flags.
  1567. """
  1568. # Handle the common case first, for efficiency:
  1569. # if they're string-identical, always return true.
  1570. if got == want:
  1571. return True
  1572. # TODO parse integers as well ?
  1573. # Parse floats and compare them. If some of the parsed floats contain
  1574. # ellipses, skip the comparison.
  1575. matches = self.num_got_rgx.finditer(got)
  1576. numbers_got = [match.group(1) for match in matches] # list of strs
  1577. matches = self.num_want_rgx.finditer(want)
  1578. numbers_want = [match.group(1) for match in matches] # list of strs
  1579. if len(numbers_got) != len(numbers_want):
  1580. return False
  1581. if len(numbers_got) > 0:
  1582. nw_ = []
  1583. for ng, nw in zip(numbers_got, numbers_want):
  1584. if '...' in nw:
  1585. nw_.append(ng)
  1586. continue
  1587. else:
  1588. nw_.append(nw)
  1589. if abs(float(ng)-float(nw)) > 1e-5:
  1590. return False
  1591. got = self.num_got_rgx.sub(r'%s', got)
  1592. got = got % tuple(nw_)
  1593. # <BLANKLINE> can be used as a special sequence to signify a
  1594. # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
  1595. if not (optionflags & pdoctest.DONT_ACCEPT_BLANKLINE):
  1596. # Replace <BLANKLINE> in want with a blank line.
  1597. want = re.sub(r'(?m)^%s\s*?$' % re.escape(pdoctest.BLANKLINE_MARKER),
  1598. '', want)
  1599. # If a line in got contains only spaces, then remove the
  1600. # spaces.
  1601. got = re.sub(r'(?m)^\s*?$', '', got)
  1602. if got == want:
  1603. return True
  1604. # This flag causes doctest to ignore any differences in the
  1605. # contents of whitespace strings. Note that this can be used
  1606. # in conjunction with the ELLIPSIS flag.
  1607. if optionflags & pdoctest.NORMALIZE_WHITESPACE:
  1608. got = ' '.join(got.split())
  1609. want = ' '.join(want.split())
  1610. if got == want:
  1611. return True
  1612. # The ELLIPSIS flag says to let the sequence "..." in `want`
  1613. # match any substring in `got`.
  1614. if optionflags & pdoctest.ELLIPSIS:
  1615. if pdoctest._ellipsis_match(want, got):
  1616. return True
  1617. # We didn't find any match; return false.
  1618. return False
  1619. class Reporter:
  1620. """
  1621. Parent class for all reporters.
  1622. """
  1623. pass
  1624. class PyTestReporter(Reporter):
  1625. """
  1626. Py.test like reporter. Should produce output identical to py.test.
  1627. """
  1628. def __init__(self, verbose=False, tb="short", colors=True,
  1629. force_colors=False, split=None):
  1630. self._verbose = verbose
  1631. self._tb_style = tb
  1632. self._colors = colors
  1633. self._force_colors = force_colors
  1634. self._xfailed = 0
  1635. self._xpassed = []
  1636. self._failed = []
  1637. self._failed_doctest = []
  1638. self._passed = 0
  1639. self._skipped = 0
  1640. self._exceptions = []
  1641. self._terminal_width = None
  1642. self._default_width = 80
  1643. self._split = split
  1644. self._active_file = ''
  1645. self._active_f = None
  1646. # TODO: Should these be protected?
  1647. self.slow_test_functions = []
  1648. self.fast_test_functions = []
  1649. # this tracks the x-position of the cursor (useful for positioning
  1650. # things on the screen), without the need for any readline library:
  1651. self._write_pos = 0
  1652. self._line_wrap = False
  1653. def root_dir(self, dir):
  1654. self._root_dir = dir
  1655. @property
  1656. def terminal_width(self):
  1657. if self._terminal_width is not None:
  1658. return self._terminal_width
  1659. def findout_terminal_width():
  1660. if sys.platform == "win32":
  1661. # Windows support is based on:
  1662. #
  1663. # http://code.activestate.com/recipes/
  1664. # 440694-determine-size-of-console-window-on-windows/
  1665. from ctypes import windll, create_string_buffer
  1666. h = windll.kernel32.GetStdHandle(-12)
  1667. csbi = create_string_buffer(22)
  1668. res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
  1669. if res:
  1670. import struct
  1671. (_, _, _, _, _, left, _, right, _, _, _) = \
  1672. struct.unpack("hhhhHhhhhhh", csbi.raw)
  1673. return right - left
  1674. else:
  1675. return self._default_width
  1676. if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty():
  1677. return self._default_width # leave PIPEs alone
  1678. try:
  1679. process = subprocess.Popen(['stty', '-a'],
  1680. stdout=subprocess.PIPE,
  1681. stderr=subprocess.PIPE)
  1682. stdout, stderr = process.communicate()
  1683. stdout = stdout.decode("utf-8")
  1684. except OSError:
  1685. pass
  1686. else:
  1687. # We support the following output formats from stty:
  1688. #
  1689. # 1) Linux -> columns 80
  1690. # 2) OS X -> 80 columns
  1691. # 3) Solaris -> columns = 80
  1692. re_linux = r"columns\s+(?P<columns>\d+);"
  1693. re_osx = r"(?P<columns>\d+)\s*columns;"
  1694. re_solaris = r"columns\s+=\s+(?P<columns>\d+);"
  1695. for regex in (re_linux, re_osx, re_solaris):
  1696. match = re.search(regex, stdout)
  1697. if match is not None:
  1698. columns = match.group('columns')
  1699. try:
  1700. width = int(columns)
  1701. except ValueError:
  1702. pass
  1703. if width != 0:
  1704. return width
  1705. return self._default_width
  1706. width = findout_terminal_width()
  1707. self._terminal_width = width
  1708. return width
  1709. def write(self, text, color="", align="left", width=None,
  1710. force_colors=False):
  1711. """
  1712. Prints a text on the screen.
  1713. It uses sys.stdout.write(), so no readline library is necessary.
  1714. Parameters
  1715. ==========
  1716. color : choose from the colors below, "" means default color
  1717. align : "left"/"right", "left" is a normal print, "right" is aligned on
  1718. the right-hand side of the screen, filled with spaces if
  1719. necessary
  1720. width : the screen width
  1721. """
  1722. color_templates = (
  1723. ("Black", "0;30"),
  1724. ("Red", "0;31"),
  1725. ("Green", "0;32"),
  1726. ("Brown", "0;33"),
  1727. ("Blue", "0;34"),
  1728. ("Purple", "0;35"),
  1729. ("Cyan", "0;36"),
  1730. ("LightGray", "0;37"),
  1731. ("DarkGray", "1;30"),
  1732. ("LightRed", "1;31"),
  1733. ("LightGreen", "1;32"),
  1734. ("Yellow", "1;33"),
  1735. ("LightBlue", "1;34"),
  1736. ("LightPurple", "1;35"),
  1737. ("LightCyan", "1;36"),
  1738. ("White", "1;37"),
  1739. )
  1740. colors = {}
  1741. for name, value in color_templates:
  1742. colors[name] = value
  1743. c_normal = '\033[0m'
  1744. c_color = '\033[%sm'
  1745. if width is None:
  1746. width = self.terminal_width
  1747. if align == "right":
  1748. if self._write_pos + len(text) > width:
  1749. # we don't fit on the current line, create a new line
  1750. self.write("\n")
  1751. self.write(" "*(width - self._write_pos - len(text)))
  1752. if not self._force_colors and hasattr(sys.stdout, 'isatty') and not \
  1753. sys.stdout.isatty():
  1754. # the stdout is not a terminal, this for example happens if the
  1755. # output is piped to less, e.g. "bin/test | less". In this case,
  1756. # the terminal control sequences would be printed verbatim, so
  1757. # don't use any colors.
  1758. color = ""
  1759. elif sys.platform == "win32":
  1760. # Windows consoles don't support ANSI escape sequences
  1761. color = ""
  1762. elif not self._colors:
  1763. color = ""
  1764. if self._line_wrap:
  1765. if text[0] != "\n":
  1766. sys.stdout.write("\n")
  1767. # Avoid UnicodeEncodeError when printing out test failures
  1768. if IS_WINDOWS:
  1769. text = text.encode('raw_unicode_escape').decode('utf8', 'ignore')
  1770. elif not sys.stdout.encoding.lower().startswith('utf'):
  1771. text = text.encode(sys.stdout.encoding, 'backslashreplace'
  1772. ).decode(sys.stdout.encoding)
  1773. if color == "":
  1774. sys.stdout.write(text)
  1775. else:
  1776. sys.stdout.write("%s%s%s" %
  1777. (c_color % colors[color], text, c_normal))
  1778. sys.stdout.flush()
  1779. l = text.rfind("\n")
  1780. if l == -1:
  1781. self._write_pos += len(text)
  1782. else:
  1783. self._write_pos = len(text) - l - 1
  1784. self._line_wrap = self._write_pos >= width
  1785. self._write_pos %= width
  1786. def write_center(self, text, delim="="):
  1787. width = self.terminal_width
  1788. if text != "":
  1789. text = " %s " % text
  1790. idx = (width - len(text)) // 2
  1791. t = delim*idx + text + delim*(width - idx - len(text))
  1792. self.write(t + "\n")
  1793. def write_exception(self, e, val, tb):
  1794. # remove the first item, as that is always runtests.py
  1795. tb = tb.tb_next
  1796. t = traceback.format_exception(e, val, tb)
  1797. self.write("".join(t))
  1798. def start(self, seed=None, msg="test process starts"):
  1799. self.write_center(msg)
  1800. executable = sys.executable
  1801. v = tuple(sys.version_info)
  1802. python_version = "%s.%s.%s-%s-%s" % v
  1803. implementation = platform.python_implementation()
  1804. if implementation == 'PyPy':
  1805. implementation += " %s.%s.%s-%s-%s" % sys.pypy_version_info
  1806. self.write("executable: %s (%s) [%s]\n" %
  1807. (executable, python_version, implementation))
  1808. from sympy.utilities.misc import ARCH
  1809. self.write("architecture: %s\n" % ARCH)
  1810. from sympy.core.cache import USE_CACHE
  1811. self.write("cache: %s\n" % USE_CACHE)
  1812. version = ''
  1813. if GROUND_TYPES =='gmpy':
  1814. if HAS_GMPY == 1:
  1815. import gmpy
  1816. elif HAS_GMPY == 2:
  1817. import gmpy2 as gmpy
  1818. version = gmpy.version()
  1819. self.write("ground types: %s %s\n" % (GROUND_TYPES, version))
  1820. numpy = import_module('numpy')
  1821. self.write("numpy: %s\n" % (None if not numpy else numpy.__version__))
  1822. if seed is not None:
  1823. self.write("random seed: %d\n" % seed)
  1824. from sympy.utilities.misc import HASH_RANDOMIZATION
  1825. self.write("hash randomization: ")
  1826. hash_seed = os.getenv("PYTHONHASHSEED") or '0'
  1827. if HASH_RANDOMIZATION and (hash_seed == "random" or int(hash_seed)):
  1828. self.write("on (PYTHONHASHSEED=%s)\n" % hash_seed)
  1829. else:
  1830. self.write("off\n")
  1831. if self._split:
  1832. self.write("split: %s\n" % self._split)
  1833. self.write('\n')
  1834. self._t_start = clock()
  1835. def finish(self):
  1836. self._t_end = clock()
  1837. self.write("\n")
  1838. global text, linelen
  1839. text = "tests finished: %d passed, " % self._passed
  1840. linelen = len(text)
  1841. def add_text(mytext):
  1842. global text, linelen
  1843. """Break new text if too long."""
  1844. if linelen + len(mytext) > self.terminal_width:
  1845. text += '\n'
  1846. linelen = 0
  1847. text += mytext
  1848. linelen += len(mytext)
  1849. if len(self._failed) > 0:
  1850. add_text("%d failed, " % len(self._failed))
  1851. if len(self._failed_doctest) > 0:
  1852. add_text("%d failed, " % len(self._failed_doctest))
  1853. if self._skipped > 0:
  1854. add_text("%d skipped, " % self._skipped)
  1855. if self._xfailed > 0:
  1856. add_text("%d expected to fail, " % self._xfailed)
  1857. if len(self._xpassed) > 0:
  1858. add_text("%d expected to fail but passed, " % len(self._xpassed))
  1859. if len(self._exceptions) > 0:
  1860. add_text("%d exceptions, " % len(self._exceptions))
  1861. add_text("in %.2f seconds" % (self._t_end - self._t_start))
  1862. if self.slow_test_functions:
  1863. self.write_center('slowest tests', '_')
  1864. sorted_slow = sorted(self.slow_test_functions, key=lambda r: r[1])
  1865. for slow_func_name, taken in sorted_slow:
  1866. print('%s - Took %.3f seconds' % (slow_func_name, taken))
  1867. if self.fast_test_functions:
  1868. self.write_center('unexpectedly fast tests', '_')
  1869. sorted_fast = sorted(self.fast_test_functions,
  1870. key=lambda r: r[1])
  1871. for fast_func_name, taken in sorted_fast:
  1872. print('%s - Took %.3f seconds' % (fast_func_name, taken))
  1873. if len(self._xpassed) > 0:
  1874. self.write_center("xpassed tests", "_")
  1875. for e in self._xpassed:
  1876. self.write("%s: %s\n" % (e[0], e[1]))
  1877. self.write("\n")
  1878. if self._tb_style != "no" and len(self._exceptions) > 0:
  1879. for e in self._exceptions:
  1880. filename, f, (t, val, tb) = e
  1881. self.write_center("", "_")
  1882. if f is None:
  1883. s = "%s" % filename
  1884. else:
  1885. s = "%s:%s" % (filename, f.__name__)
  1886. self.write_center(s, "_")
  1887. self.write_exception(t, val, tb)
  1888. self.write("\n")
  1889. if self._tb_style != "no" and len(self._failed) > 0:
  1890. for e in self._failed:
  1891. filename, f, (t, val, tb) = e
  1892. self.write_center("", "_")
  1893. self.write_center("%s:%s" % (filename, f.__name__), "_")
  1894. self.write_exception(t, val, tb)
  1895. self.write("\n")
  1896. if self._tb_style != "no" and len(self._failed_doctest) > 0:
  1897. for e in self._failed_doctest:
  1898. filename, msg = e
  1899. self.write_center("", "_")
  1900. self.write_center("%s" % filename, "_")
  1901. self.write(msg)
  1902. self.write("\n")
  1903. self.write_center(text)
  1904. ok = len(self._failed) == 0 and len(self._exceptions) == 0 and \
  1905. len(self._failed_doctest) == 0
  1906. if not ok:
  1907. self.write("DO *NOT* COMMIT!\n")
  1908. return ok
  1909. def entering_filename(self, filename, n):
  1910. rel_name = filename[len(self._root_dir) + 1:]
  1911. self._active_file = rel_name
  1912. self._active_file_error = False
  1913. self.write(rel_name)
  1914. self.write("[%d] " % n)
  1915. def leaving_filename(self):
  1916. self.write(" ")
  1917. if self._active_file_error:
  1918. self.write("[FAIL]", "Red", align="right")
  1919. else:
  1920. self.write("[OK]", "Green", align="right")
  1921. self.write("\n")
  1922. if self._verbose:
  1923. self.write("\n")
  1924. def entering_test(self, f):
  1925. self._active_f = f
  1926. if self._verbose:
  1927. self.write("\n" + f.__name__ + " ")
  1928. def test_xfail(self):
  1929. self._xfailed += 1
  1930. self.write("f", "Green")
  1931. def test_xpass(self, v):
  1932. message = str(v)
  1933. self._xpassed.append((self._active_file, message))
  1934. self.write("X", "Green")
  1935. def test_fail(self, exc_info):
  1936. self._failed.append((self._active_file, self._active_f, exc_info))
  1937. self.write("F", "Red")
  1938. self._active_file_error = True
  1939. def doctest_fail(self, name, error_msg):
  1940. # the first line contains "******", remove it:
  1941. error_msg = "\n".join(error_msg.split("\n")[1:])
  1942. self._failed_doctest.append((name, error_msg))
  1943. self.write("F", "Red")
  1944. self._active_file_error = True
  1945. def test_pass(self, char="."):
  1946. self._passed += 1
  1947. if self._verbose:
  1948. self.write("ok", "Green")
  1949. else:
  1950. self.write(char, "Green")
  1951. def test_skip(self, v=None):
  1952. char = "s"
  1953. self._skipped += 1
  1954. if v is not None:
  1955. message = str(v)
  1956. if message == "KeyboardInterrupt":
  1957. char = "K"
  1958. elif message == "Timeout":
  1959. char = "T"
  1960. elif message == "Slow":
  1961. char = "w"
  1962. if self._verbose:
  1963. if v is not None:
  1964. self.write(message + ' ', "Blue")
  1965. else:
  1966. self.write(" - ", "Blue")
  1967. self.write(char, "Blue")
  1968. def test_exception(self, exc_info):
  1969. self._exceptions.append((self._active_file, self._active_f, exc_info))
  1970. if exc_info[0] is TimeOutError:
  1971. self.write("T", "Red")
  1972. else:
  1973. self.write("E", "Red")
  1974. self._active_file_error = True
  1975. def import_error(self, filename, exc_info):
  1976. self._exceptions.append((filename, None, exc_info))
  1977. rel_name = filename[len(self._root_dir) + 1:]
  1978. self.write(rel_name)
  1979. self.write("[?] Failed to import", "Red")
  1980. self.write(" ")
  1981. self.write("[FAIL]", "Red", align="right")
  1982. self.write("\n")