runtests.py 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361
  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. * doesn't 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_TRAVIS = os.getenv('TRAVIS_BUILD_NUMBER', None)
  38. # emperically 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["TRAVIS_BUILD_NUMBER"] = '2' # Mock travis 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 doesn't 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. Don't 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=('sympy/integrals/rubi',),
  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_TRAVIS and timeout is False:
  411. # Travis times out if no activity is seen for 10 minutes.
  412. timeout = 595
  413. fail_on_timeout = True
  414. if ON_TRAVIS:
  415. # pyglet does not work on Travis
  416. blacklist = list(blacklist) + ['sympy/plotting/pygletplot/tests']
  417. blacklist = convert_to_native_paths(blacklist)
  418. r = PyTestReporter(verbose=verbose, tb=tb, colors=colors,
  419. force_colors=force_colors, split=split)
  420. t = SymPyTests(r, kw, post_mortem, seed,
  421. fast_threshold=fast_threshold,
  422. slow_threshold=slow_threshold)
  423. test_files = t.get_test_files('sympy')
  424. not_blacklisted = [f for f in test_files
  425. if not any(b in f for b in blacklist)]
  426. if len(paths) == 0:
  427. matched = not_blacklisted
  428. else:
  429. paths = convert_to_native_paths(paths)
  430. matched = []
  431. for f in not_blacklisted:
  432. basename = os.path.basename(f)
  433. for p in paths:
  434. if p in f or fnmatch(basename, p):
  435. matched.append(f)
  436. break
  437. density = None
  438. if time_balance:
  439. if slow:
  440. density = SPLIT_DENSITY_SLOW
  441. else:
  442. density = SPLIT_DENSITY
  443. if split:
  444. matched = split_list(matched, split, density=density)
  445. t._testfiles.extend(matched)
  446. return int(not t.test(sort=sort, timeout=timeout, slow=slow,
  447. enhance_asserts=enhance_asserts, fail_on_timeout=fail_on_timeout))
  448. def doctest(*paths, subprocess=True, rerun=0, **kwargs):
  449. r"""
  450. Runs doctests in all \*.py files in the SymPy directory which match
  451. any of the given strings in ``paths`` or all tests if paths=[].
  452. Notes:
  453. - Paths can be entered in native system format or in unix,
  454. forward-slash format.
  455. - Files that are on the blacklist can be tested by providing
  456. their path; they are only excluded if no paths are given.
  457. Examples
  458. ========
  459. >>> import sympy
  460. Run all tests:
  461. >>> sympy.doctest() # doctest: +SKIP
  462. Run one file:
  463. >>> sympy.doctest("sympy/core/basic.py") # doctest: +SKIP
  464. >>> sympy.doctest("polynomial.rst") # doctest: +SKIP
  465. Run all tests in sympy/functions/ and some particular file:
  466. >>> sympy.doctest("/functions", "basic.py") # doctest: +SKIP
  467. Run any file having polynomial in its name, doc/src/modules/polynomial.rst,
  468. sympy/functions/special/polynomials.py, and sympy/polys/polynomial.py:
  469. >>> sympy.doctest("polynomial") # doctest: +SKIP
  470. The ``split`` option can be passed to split the test run into parts. The
  471. split currently only splits the test files, though this may change in the
  472. future. ``split`` should be a string of the form 'a/b', which will run
  473. part ``a`` of ``b``. Note that the regular doctests and the Sphinx
  474. doctests are split independently. For instance, to run the first half of
  475. the test suite:
  476. >>> sympy.doctest(split='1/2') # doctest: +SKIP
  477. The ``subprocess`` and ``verbose`` options are the same as with the function
  478. ``test()``. See the docstring of that function for more information.
  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/integrals/rubi/rubi.py",
  512. "sympy/parsing/autolev/_antlr/autolevlexer.py", # generated code
  513. "sympy/parsing/autolev/_antlr/autolevlistener.py", # generated code
  514. "sympy/parsing/autolev/_antlr/autolevparser.py", # generated code
  515. "sympy/parsing/latex/_antlr/latexlexer.py", # generated code
  516. "sympy/parsing/latex/_antlr/latexparser.py", # generated code
  517. "sympy/plotting/pygletplot/__init__.py", # crashes on some systems
  518. "sympy/plotting/pygletplot/plot.py", # crashes on some systems
  519. "sympy/printing/ccode.py", # backwards compatibility shim, importing it breaks the codegen doctests
  520. "sympy/printing/cxxcode.py", # backwards compatibility shim, importing it breaks the codegen doctests
  521. "sympy/printing/fcode.py", # backwards compatibility shim, importing it breaks the codegen doctests
  522. "sympy/testing/randtest.py", # backwards compatibility shim, importing it triggers a deprecation warning
  523. "sympy/this.py", # prints text
  524. ])
  525. # autolev parser tests
  526. num = 12
  527. for i in range (1, num+1):
  528. blacklist.append("sympy/parsing/autolev/test-examples/ruletest" + str(i) + ".py")
  529. blacklist.extend(["sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py",
  530. "sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py",
  531. "sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py",
  532. "sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py"])
  533. if import_module('numpy') is None:
  534. blacklist.extend([
  535. "sympy/plotting/experimental_lambdify.py",
  536. "sympy/plotting/plot_implicit.py",
  537. "examples/advanced/autowrap_integrators.py",
  538. "examples/advanced/autowrap_ufuncify.py",
  539. "examples/intermediate/sample.py",
  540. "examples/intermediate/mplot2d.py",
  541. "examples/intermediate/mplot3d.py",
  542. "doc/src/modules/numeric-computation.rst"
  543. ])
  544. else:
  545. if import_module('matplotlib') is None:
  546. blacklist.extend([
  547. "examples/intermediate/mplot2d.py",
  548. "examples/intermediate/mplot3d.py"
  549. ])
  550. else:
  551. # Use a non-windowed backend, so that the tests work on Travis
  552. import matplotlib
  553. matplotlib.use('Agg')
  554. if ON_TRAVIS or import_module('pyglet') is None:
  555. blacklist.extend(["sympy/plotting/pygletplot"])
  556. if import_module('aesara') is None:
  557. blacklist.extend([
  558. "sympy/printing/aesaracode.py",
  559. "doc/src/modules/numeric-computation.rst",
  560. ])
  561. if import_module('cupy') is None:
  562. blacklist.extend([
  563. "doc/src/modules/numeric-computation.rst",
  564. ])
  565. if import_module('antlr4') is None:
  566. blacklist.extend([
  567. "sympy/parsing/autolev/__init__.py",
  568. "sympy/parsing/latex/_parse_latex_antlr.py",
  569. ])
  570. if import_module('lfortran') is None:
  571. #throws ImportError when lfortran not installed
  572. blacklist.extend([
  573. "sympy/parsing/sym_expr.py",
  574. ])
  575. # disabled because of doctest failures in asmeurer's bot
  576. blacklist.extend([
  577. "sympy/utilities/autowrap.py",
  578. "examples/advanced/autowrap_integrators.py",
  579. "examples/advanced/autowrap_ufuncify.py"
  580. ])
  581. # blacklist these modules until issue 4840 is resolved
  582. blacklist.extend([
  583. "sympy/conftest.py", # Depends on pytest
  584. "sympy/testing/benchmarking.py",
  585. ])
  586. # These are deprecated stubs to be removed:
  587. blacklist.extend([
  588. "sympy/utilities/benchmarking.py",
  589. "sympy/utilities/tmpfiles.py",
  590. "sympy/utilities/pytest.py",
  591. "sympy/utilities/runtests.py",
  592. "sympy/utilities/quality_unicode.py",
  593. "sympy/utilities/randtest.py",
  594. ])
  595. blacklist = convert_to_native_paths(blacklist)
  596. return blacklist
  597. def _doctest(*paths, **kwargs):
  598. """
  599. Internal function that actually runs the doctests.
  600. All keyword arguments from ``doctest()`` are passed to this function
  601. except for ``subprocess``.
  602. Returns 0 if tests passed and 1 if they failed. See the docstrings of
  603. ``doctest()`` and ``test()`` for more information.
  604. """
  605. from sympy.printing.pretty.pretty import pprint_use_unicode
  606. normal = kwargs.get("normal", False)
  607. verbose = kwargs.get("verbose", False)
  608. colors = kwargs.get("colors", True)
  609. force_colors = kwargs.get("force_colors", False)
  610. blacklist = kwargs.get("blacklist", [])
  611. split = kwargs.get('split', None)
  612. blacklist.extend(_get_doctest_blacklist())
  613. # Use a non-windowed backend, so that the tests work on Travis
  614. if import_module('matplotlib') is not None:
  615. import matplotlib
  616. matplotlib.use('Agg')
  617. # Disable warnings for external modules
  618. import sympy.external
  619. sympy.external.importtools.WARN_OLD_VERSION = False
  620. sympy.external.importtools.WARN_NOT_INSTALLED = False
  621. # Disable showing up of plots
  622. from sympy.plotting.plot import unset_show
  623. unset_show()
  624. r = PyTestReporter(verbose, split=split, colors=colors,\
  625. force_colors=force_colors)
  626. t = SymPyDocTests(r, normal)
  627. test_files = t.get_test_files('sympy')
  628. test_files.extend(t.get_test_files('examples', init_only=False))
  629. not_blacklisted = [f for f in test_files
  630. if not any(b in f for b in blacklist)]
  631. if len(paths) == 0:
  632. matched = not_blacklisted
  633. else:
  634. # take only what was requested...but not blacklisted items
  635. # and allow for partial match anywhere or fnmatch of name
  636. paths = convert_to_native_paths(paths)
  637. matched = []
  638. for f in not_blacklisted:
  639. basename = os.path.basename(f)
  640. for p in paths:
  641. if p in f or fnmatch(basename, p):
  642. matched.append(f)
  643. break
  644. if split:
  645. matched = split_list(matched, split)
  646. t._testfiles.extend(matched)
  647. # run the tests and record the result for this *py portion of the tests
  648. if t._testfiles:
  649. failed = not t.test()
  650. else:
  651. failed = False
  652. # N.B.
  653. # --------------------------------------------------------------------
  654. # Here we test *.rst files at or below doc/src. Code from these must
  655. # be self supporting in terms of imports since there is no importing
  656. # of necessary modules by doctest.testfile. If you try to pass *.py
  657. # files through this they might fail because they will lack the needed
  658. # imports and smarter parsing that can be done with source code.
  659. #
  660. test_files = t.get_test_files('doc/src', '*.rst', init_only=False)
  661. test_files.sort()
  662. not_blacklisted = [f for f in test_files
  663. if not any(b in f for b in blacklist)]
  664. if len(paths) == 0:
  665. matched = not_blacklisted
  666. else:
  667. # Take only what was requested as long as it's not on the blacklist.
  668. # Paths were already made native in *py tests so don't repeat here.
  669. # There's no chance of having a *py file slip through since we
  670. # only have *rst files in test_files.
  671. matched = []
  672. for f in not_blacklisted:
  673. basename = os.path.basename(f)
  674. for p in paths:
  675. if p in f or fnmatch(basename, p):
  676. matched.append(f)
  677. break
  678. if split:
  679. matched = split_list(matched, split)
  680. first_report = True
  681. for rst_file in matched:
  682. if not os.path.isfile(rst_file):
  683. continue
  684. old_displayhook = sys.displayhook
  685. try:
  686. use_unicode_prev = setup_pprint()
  687. out = sympytestfile(
  688. rst_file, module_relative=False, encoding='utf-8',
  689. optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE |
  690. pdoctest.IGNORE_EXCEPTION_DETAIL)
  691. finally:
  692. # make sure we return to the original displayhook in case some
  693. # doctest has changed that
  694. sys.displayhook = old_displayhook
  695. # The NO_GLOBAL flag overrides the no_global flag to init_printing
  696. # if True
  697. import sympy.interactive.printing as interactive_printing
  698. interactive_printing.NO_GLOBAL = False
  699. pprint_use_unicode(use_unicode_prev)
  700. rstfailed, tested = out
  701. if tested:
  702. failed = rstfailed or failed
  703. if first_report:
  704. first_report = False
  705. msg = 'rst doctests start'
  706. if not t._testfiles:
  707. r.start(msg=msg)
  708. else:
  709. r.write_center(msg)
  710. print()
  711. # use as the id, everything past the first 'sympy'
  712. file_id = rst_file[rst_file.find('sympy') + len('sympy') + 1:]
  713. print(file_id, end=" ")
  714. # get at least the name out so it is know who is being tested
  715. wid = r.terminal_width - len(file_id) - 1 # update width
  716. test_file = '[%s]' % (tested)
  717. report = '[%s]' % (rstfailed or 'OK')
  718. print(''.join(
  719. [test_file, ' '*(wid - len(test_file) - len(report)), report])
  720. )
  721. # the doctests for *py will have printed this message already if there was
  722. # a failure, so now only print it if there was intervening reporting by
  723. # testing the *rst as evidenced by first_report no longer being True.
  724. if not first_report and failed:
  725. print()
  726. print("DO *NOT* COMMIT!")
  727. return int(failed)
  728. sp = re.compile(r'([0-9]+)/([1-9][0-9]*)')
  729. def split_list(l, split, density=None):
  730. """
  731. Splits a list into part a of b
  732. split should be a string of the form 'a/b'. For instance, '1/3' would give
  733. the split one of three.
  734. If the length of the list is not divisible by the number of splits, the
  735. last split will have more items.
  736. `density` may be specified as a list. If specified,
  737. tests will be balanced so that each split has as equal-as-possible
  738. amount of mass according to `density`.
  739. >>> from sympy.testing.runtests import split_list
  740. >>> a = list(range(10))
  741. >>> split_list(a, '1/3')
  742. [0, 1, 2]
  743. >>> split_list(a, '2/3')
  744. [3, 4, 5]
  745. >>> split_list(a, '3/3')
  746. [6, 7, 8, 9]
  747. """
  748. m = sp.match(split)
  749. if not m:
  750. raise ValueError("split must be a string of the form a/b where a and b are ints")
  751. i, t = map(int, m.groups())
  752. if not density:
  753. return l[(i - 1)*len(l)//t : i*len(l)//t]
  754. # normalize density
  755. tot = sum(density)
  756. density = [x / tot for x in density]
  757. def density_inv(x):
  758. """Interpolate the inverse to the cumulative
  759. distribution function given by density"""
  760. if x <= 0:
  761. return 0
  762. if x >= sum(density):
  763. return 1
  764. # find the first time the cumulative sum surpasses x
  765. # and linearly interpolate
  766. cumm = 0
  767. for i, d in enumerate(density):
  768. cumm += d
  769. if cumm >= x:
  770. break
  771. frac = (d - (cumm - x)) / d
  772. return (i + frac) / len(density)
  773. lower_frac = density_inv((i - 1) / t)
  774. higher_frac = density_inv(i / t)
  775. return l[int(lower_frac*len(l)) : int(higher_frac*len(l))]
  776. from collections import namedtuple
  777. SymPyTestResults = namedtuple('SymPyTestResults', 'failed attempted')
  778. def sympytestfile(filename, module_relative=True, name=None, package=None,
  779. globs=None, verbose=None, report=True, optionflags=0,
  780. extraglobs=None, raise_on_error=False,
  781. parser=pdoctest.DocTestParser(), encoding=None):
  782. """
  783. Test examples in the given file. Return (#failures, #tests).
  784. Optional keyword arg ``module_relative`` specifies how filenames
  785. should be interpreted:
  786. - If ``module_relative`` is True (the default), then ``filename``
  787. specifies a module-relative path. By default, this path is
  788. relative to the calling module's directory; but if the
  789. ``package`` argument is specified, then it is relative to that
  790. package. To ensure os-independence, ``filename`` should use
  791. "/" characters to separate path segments, and should not
  792. be an absolute path (i.e., it may not begin with "/").
  793. - If ``module_relative`` is False, then ``filename`` specifies an
  794. os-specific path. The path may be absolute or relative (to
  795. the current working directory).
  796. Optional keyword arg ``name`` gives the name of the test; by default
  797. use the file's basename.
  798. Optional keyword argument ``package`` is a Python package or the
  799. name of a Python package whose directory should be used as the
  800. base directory for a module relative filename. If no package is
  801. specified, then the calling module's directory is used as the base
  802. directory for module relative filenames. It is an error to
  803. specify ``package`` if ``module_relative`` is False.
  804. Optional keyword arg ``globs`` gives a dict to be used as the globals
  805. when executing examples; by default, use {}. A copy of this dict
  806. is actually used for each docstring, so that each docstring's
  807. examples start with a clean slate.
  808. Optional keyword arg ``extraglobs`` gives a dictionary that should be
  809. merged into the globals that are used to execute examples. By
  810. default, no extra globals are used.
  811. Optional keyword arg ``verbose`` prints lots of stuff if true, prints
  812. only failures if false; by default, it's true iff "-v" is in sys.argv.
  813. Optional keyword arg ``report`` prints a summary at the end when true,
  814. else prints nothing at the end. In verbose mode, the summary is
  815. detailed, else very brief (in fact, empty if all tests passed).
  816. Optional keyword arg ``optionflags`` or's together module constants,
  817. and defaults to 0. Possible values (see the docs for details):
  818. - DONT_ACCEPT_TRUE_FOR_1
  819. - DONT_ACCEPT_BLANKLINE
  820. - NORMALIZE_WHITESPACE
  821. - ELLIPSIS
  822. - SKIP
  823. - IGNORE_EXCEPTION_DETAIL
  824. - REPORT_UDIFF
  825. - REPORT_CDIFF
  826. - REPORT_NDIFF
  827. - REPORT_ONLY_FIRST_FAILURE
  828. Optional keyword arg ``raise_on_error`` raises an exception on the
  829. first unexpected exception or failure. This allows failures to be
  830. post-mortem debugged.
  831. Optional keyword arg ``parser`` specifies a DocTestParser (or
  832. subclass) that should be used to extract tests from the files.
  833. Optional keyword arg ``encoding`` specifies an encoding that should
  834. be used to convert the file to unicode.
  835. Advanced tomfoolery: testmod runs methods of a local instance of
  836. class doctest.Tester, then merges the results into (or creates)
  837. global Tester instance doctest.master. Methods of doctest.master
  838. can be called directly too, if you want to do something unusual.
  839. Passing report=0 to testmod is especially useful then, to delay
  840. displaying a summary. Invoke doctest.master.summarize(verbose)
  841. when you're done fiddling.
  842. """
  843. if package and not module_relative:
  844. raise ValueError("Package may only be specified for module-"
  845. "relative paths.")
  846. # Relativize the path
  847. text, filename = pdoctest._load_testfile(
  848. filename, package, module_relative, encoding)
  849. # If no name was given, then use the file's name.
  850. if name is None:
  851. name = os.path.basename(filename)
  852. # Assemble the globals.
  853. if globs is None:
  854. globs = {}
  855. else:
  856. globs = globs.copy()
  857. if extraglobs is not None:
  858. globs.update(extraglobs)
  859. if '__name__' not in globs:
  860. globs['__name__'] = '__main__'
  861. if raise_on_error:
  862. runner = pdoctest.DebugRunner(verbose=verbose, optionflags=optionflags)
  863. else:
  864. runner = SymPyDocTestRunner(verbose=verbose, optionflags=optionflags)
  865. runner._checker = SymPyOutputChecker()
  866. # Read the file, convert it to a test, and run it.
  867. test = parser.get_doctest(text, globs, name, filename, 0)
  868. runner.run(test)
  869. if report:
  870. runner.summarize()
  871. if pdoctest.master is None:
  872. pdoctest.master = runner
  873. else:
  874. pdoctest.master.merge(runner)
  875. return SymPyTestResults(runner.failures, runner.tries)
  876. class SymPyTests:
  877. def __init__(self, reporter, kw="", post_mortem=False,
  878. seed=None, fast_threshold=None, slow_threshold=None):
  879. self._post_mortem = post_mortem
  880. self._kw = kw
  881. self._count = 0
  882. self._root_dir = get_sympy_dir()
  883. self._reporter = reporter
  884. self._reporter.root_dir(self._root_dir)
  885. self._testfiles = []
  886. self._seed = seed if seed is not None else random.random()
  887. # Defaults in seconds, from human / UX design limits
  888. # http://www.nngroup.com/articles/response-times-3-important-limits/
  889. #
  890. # These defaults are *NOT* set in stone as we are measuring different
  891. # things, so others feel free to come up with a better yardstick :)
  892. if fast_threshold:
  893. self._fast_threshold = float(fast_threshold)
  894. else:
  895. self._fast_threshold = 8
  896. if slow_threshold:
  897. self._slow_threshold = float(slow_threshold)
  898. else:
  899. self._slow_threshold = 10
  900. def test(self, sort=False, timeout=False, slow=False,
  901. enhance_asserts=False, fail_on_timeout=False):
  902. """
  903. Runs the tests returning True if all tests pass, otherwise False.
  904. If sort=False run tests in random order.
  905. """
  906. if sort:
  907. self._testfiles.sort()
  908. elif slow:
  909. pass
  910. else:
  911. random.seed(self._seed)
  912. random.shuffle(self._testfiles)
  913. self._reporter.start(self._seed)
  914. for f in self._testfiles:
  915. try:
  916. self.test_file(f, sort, timeout, slow,
  917. enhance_asserts, fail_on_timeout)
  918. except KeyboardInterrupt:
  919. print(" interrupted by user")
  920. self._reporter.finish()
  921. raise
  922. return self._reporter.finish()
  923. def _enhance_asserts(self, source):
  924. from ast import (NodeTransformer, Compare, Name, Store, Load, Tuple,
  925. Assign, BinOp, Str, Mod, Assert, parse, fix_missing_locations)
  926. ops = {"Eq": '==', "NotEq": '!=', "Lt": '<', "LtE": '<=',
  927. "Gt": '>', "GtE": '>=', "Is": 'is', "IsNot": 'is not',
  928. "In": 'in', "NotIn": 'not in'}
  929. class Transform(NodeTransformer):
  930. def visit_Assert(self, stmt):
  931. if isinstance(stmt.test, Compare):
  932. compare = stmt.test
  933. values = [compare.left] + compare.comparators
  934. names = [ "_%s" % i for i, _ in enumerate(values) ]
  935. names_store = [ Name(n, Store()) for n in names ]
  936. names_load = [ Name(n, Load()) for n in names ]
  937. target = Tuple(names_store, Store())
  938. value = Tuple(values, Load())
  939. assign = Assign([target], value)
  940. new_compare = Compare(names_load[0], compare.ops, names_load[1:])
  941. msg_format = "\n%s " + "\n%s ".join([ ops[op.__class__.__name__] for op in compare.ops ]) + "\n%s"
  942. msg = BinOp(Str(msg_format), Mod(), Tuple(names_load, Load()))
  943. test = Assert(new_compare, msg, lineno=stmt.lineno, col_offset=stmt.col_offset)
  944. return [assign, test]
  945. else:
  946. return stmt
  947. tree = parse(source)
  948. new_tree = Transform().visit(tree)
  949. return fix_missing_locations(new_tree)
  950. def test_file(self, filename, sort=True, timeout=False, slow=False,
  951. enhance_asserts=False, fail_on_timeout=False):
  952. reporter = self._reporter
  953. funcs = []
  954. try:
  955. gl = {'__file__': filename}
  956. try:
  957. open_file = lambda: open(filename, encoding="utf8")
  958. with open_file() as f:
  959. source = f.read()
  960. if self._kw:
  961. for l in source.splitlines():
  962. if l.lstrip().startswith('def '):
  963. if any(l.find(k) != -1 for k in self._kw):
  964. break
  965. else:
  966. return
  967. if enhance_asserts:
  968. try:
  969. source = self._enhance_asserts(source)
  970. except ImportError:
  971. pass
  972. code = compile(source, filename, "exec", flags=0, dont_inherit=True)
  973. exec(code, gl)
  974. except (SystemExit, KeyboardInterrupt):
  975. raise
  976. except ImportError:
  977. reporter.import_error(filename, sys.exc_info())
  978. return
  979. except Exception:
  980. reporter.test_exception(sys.exc_info())
  981. clear_cache()
  982. self._count += 1
  983. random.seed(self._seed)
  984. disabled = gl.get("disabled", False)
  985. if not disabled:
  986. # we need to filter only those functions that begin with 'test_'
  987. # We have to be careful about decorated functions. As long as
  988. # the decorator uses functools.wraps, we can detect it.
  989. funcs = []
  990. for f in gl:
  991. if (f.startswith("test_") and (inspect.isfunction(gl[f])
  992. or inspect.ismethod(gl[f]))):
  993. func = gl[f]
  994. # Handle multiple decorators
  995. while hasattr(func, '__wrapped__'):
  996. func = func.__wrapped__
  997. if inspect.getsourcefile(func) == filename:
  998. funcs.append(gl[f])
  999. if slow:
  1000. funcs = [f for f in funcs if getattr(f, '_slow', False)]
  1001. # Sorting of XFAILed functions isn't fixed yet :-(
  1002. funcs.sort(key=lambda x: inspect.getsourcelines(x)[1])
  1003. i = 0
  1004. while i < len(funcs):
  1005. if inspect.isgeneratorfunction(funcs[i]):
  1006. # some tests can be generators, that return the actual
  1007. # test functions. We unpack it below:
  1008. f = funcs.pop(i)
  1009. for fg in f():
  1010. func = fg[0]
  1011. args = fg[1:]
  1012. fgw = lambda: func(*args)
  1013. funcs.insert(i, fgw)
  1014. i += 1
  1015. else:
  1016. i += 1
  1017. # drop functions that are not selected with the keyword expression:
  1018. funcs = [x for x in funcs if self.matches(x)]
  1019. if not funcs:
  1020. return
  1021. except Exception:
  1022. reporter.entering_filename(filename, len(funcs))
  1023. raise
  1024. reporter.entering_filename(filename, len(funcs))
  1025. if not sort:
  1026. random.shuffle(funcs)
  1027. for f in funcs:
  1028. start = time.time()
  1029. reporter.entering_test(f)
  1030. try:
  1031. if getattr(f, '_slow', False) and not slow:
  1032. raise Skipped("Slow")
  1033. with raise_on_deprecated():
  1034. if timeout:
  1035. self._timeout(f, timeout, fail_on_timeout)
  1036. else:
  1037. random.seed(self._seed)
  1038. f()
  1039. except KeyboardInterrupt:
  1040. if getattr(f, '_slow', False):
  1041. reporter.test_skip("KeyboardInterrupt")
  1042. else:
  1043. raise
  1044. except Exception:
  1045. if timeout:
  1046. signal.alarm(0) # Disable the alarm. It could not be handled before.
  1047. t, v, tr = sys.exc_info()
  1048. if t is AssertionError:
  1049. reporter.test_fail((t, v, tr))
  1050. if self._post_mortem:
  1051. pdb.post_mortem(tr)
  1052. elif t.__name__ == "Skipped":
  1053. reporter.test_skip(v)
  1054. elif t.__name__ == "XFail":
  1055. reporter.test_xfail()
  1056. elif t.__name__ == "XPass":
  1057. reporter.test_xpass(v)
  1058. else:
  1059. reporter.test_exception((t, v, tr))
  1060. if self._post_mortem:
  1061. pdb.post_mortem(tr)
  1062. else:
  1063. reporter.test_pass()
  1064. taken = time.time() - start
  1065. if taken > self._slow_threshold:
  1066. filename = os.path.relpath(filename, reporter._root_dir)
  1067. reporter.slow_test_functions.append(
  1068. (filename + "::" + f.__name__, taken))
  1069. if getattr(f, '_slow', False) and slow:
  1070. if taken < self._fast_threshold:
  1071. filename = os.path.relpath(filename, reporter._root_dir)
  1072. reporter.fast_test_functions.append(
  1073. (filename + "::" + f.__name__, taken))
  1074. reporter.leaving_filename()
  1075. def _timeout(self, function, timeout, fail_on_timeout):
  1076. def callback(x, y):
  1077. signal.alarm(0)
  1078. if fail_on_timeout:
  1079. raise TimeOutError("Timed out after %d seconds" % timeout)
  1080. else:
  1081. raise Skipped("Timeout")
  1082. signal.signal(signal.SIGALRM, callback)
  1083. signal.alarm(timeout) # Set an alarm with a given timeout
  1084. function()
  1085. signal.alarm(0) # Disable the alarm
  1086. def matches(self, x):
  1087. """
  1088. Does the keyword expression self._kw match "x"? Returns True/False.
  1089. Always returns True if self._kw is "".
  1090. """
  1091. if not self._kw:
  1092. return True
  1093. for kw in self._kw:
  1094. if x.__name__.find(kw) != -1:
  1095. return True
  1096. return False
  1097. def get_test_files(self, dir, pat='test_*.py'):
  1098. """
  1099. Returns the list of test_*.py (default) files at or below directory
  1100. ``dir`` relative to the SymPy home directory.
  1101. """
  1102. dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
  1103. g = []
  1104. for path, folders, files in os.walk(dir):
  1105. g.extend([os.path.join(path, f) for f in files if fnmatch(f, pat)])
  1106. return sorted([os.path.normcase(gi) for gi in g])
  1107. class SymPyDocTests:
  1108. def __init__(self, reporter, normal):
  1109. self._count = 0
  1110. self._root_dir = get_sympy_dir()
  1111. self._reporter = reporter
  1112. self._reporter.root_dir(self._root_dir)
  1113. self._normal = normal
  1114. self._testfiles = []
  1115. def test(self):
  1116. """
  1117. Runs the tests and returns True if all tests pass, otherwise False.
  1118. """
  1119. self._reporter.start()
  1120. for f in self._testfiles:
  1121. try:
  1122. self.test_file(f)
  1123. except KeyboardInterrupt:
  1124. print(" interrupted by user")
  1125. self._reporter.finish()
  1126. raise
  1127. return self._reporter.finish()
  1128. def test_file(self, filename):
  1129. clear_cache()
  1130. from io import StringIO
  1131. import sympy.interactive.printing as interactive_printing
  1132. from sympy.printing.pretty.pretty import pprint_use_unicode
  1133. rel_name = filename[len(self._root_dir) + 1:]
  1134. dirname, file = os.path.split(filename)
  1135. module = rel_name.replace(os.sep, '.')[:-3]
  1136. if rel_name.startswith("examples"):
  1137. # Examples files do not have __init__.py files,
  1138. # So we have to temporarily extend sys.path to import them
  1139. sys.path.insert(0, dirname)
  1140. module = file[:-3] # remove ".py"
  1141. try:
  1142. module = pdoctest._normalize_module(module)
  1143. tests = SymPyDocTestFinder().find(module)
  1144. except (SystemExit, KeyboardInterrupt):
  1145. raise
  1146. except ImportError:
  1147. self._reporter.import_error(filename, sys.exc_info())
  1148. return
  1149. finally:
  1150. if rel_name.startswith("examples"):
  1151. del sys.path[0]
  1152. tests = [test for test in tests if len(test.examples) > 0]
  1153. # By default tests are sorted by alphabetical order by function name.
  1154. # We sort by line number so one can edit the file sequentially from
  1155. # bottom to top. However, if there are decorated functions, their line
  1156. # numbers will be too large and for now one must just search for these
  1157. # by text and function name.
  1158. tests.sort(key=lambda x: -x.lineno)
  1159. if not tests:
  1160. return
  1161. self._reporter.entering_filename(filename, len(tests))
  1162. for test in tests:
  1163. assert len(test.examples) != 0
  1164. if self._reporter._verbose:
  1165. self._reporter.write("\n{} ".format(test.name))
  1166. # check if there are external dependencies which need to be met
  1167. if '_doctest_depends_on' in test.globs:
  1168. try:
  1169. self._check_dependencies(**test.globs['_doctest_depends_on'])
  1170. except DependencyError as e:
  1171. self._reporter.test_skip(v=str(e))
  1172. continue
  1173. runner = SymPyDocTestRunner(optionflags=pdoctest.ELLIPSIS |
  1174. pdoctest.NORMALIZE_WHITESPACE |
  1175. pdoctest.IGNORE_EXCEPTION_DETAIL)
  1176. runner._checker = SymPyOutputChecker()
  1177. old = sys.stdout
  1178. new = StringIO()
  1179. sys.stdout = new
  1180. # If the testing is normal, the doctests get importing magic to
  1181. # provide the global namespace. If not normal (the default) then
  1182. # then must run on their own; all imports must be explicit within
  1183. # a function's docstring. Once imported that import will be
  1184. # available to the rest of the tests in a given function's
  1185. # docstring (unless clear_globs=True below).
  1186. if not self._normal:
  1187. test.globs = {}
  1188. # if this is uncommented then all the test would get is what
  1189. # comes by default with a "from sympy import *"
  1190. #exec('from sympy import *') in test.globs
  1191. old_displayhook = sys.displayhook
  1192. use_unicode_prev = setup_pprint()
  1193. try:
  1194. f, t = runner.run(test,
  1195. out=new.write, clear_globs=False)
  1196. except KeyboardInterrupt:
  1197. raise
  1198. finally:
  1199. sys.stdout = old
  1200. if f > 0:
  1201. self._reporter.doctest_fail(test.name, new.getvalue())
  1202. else:
  1203. self._reporter.test_pass()
  1204. sys.displayhook = old_displayhook
  1205. interactive_printing.NO_GLOBAL = False
  1206. pprint_use_unicode(use_unicode_prev)
  1207. self._reporter.leaving_filename()
  1208. def get_test_files(self, dir, pat='*.py', init_only=True):
  1209. r"""
  1210. Returns the list of \*.py files (default) from which docstrings
  1211. will be tested which are at or below directory ``dir``. By default,
  1212. only those that have an __init__.py in their parent directory
  1213. and do not start with ``test_`` will be included.
  1214. """
  1215. def importable(x):
  1216. """
  1217. Checks if given pathname x is an importable module by checking for
  1218. __init__.py file.
  1219. Returns True/False.
  1220. Currently we only test if the __init__.py file exists in the
  1221. directory with the file "x" (in theory we should also test all the
  1222. parent dirs).
  1223. """
  1224. init_py = os.path.join(os.path.dirname(x), "__init__.py")
  1225. return os.path.exists(init_py)
  1226. dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
  1227. g = []
  1228. for path, folders, files in os.walk(dir):
  1229. g.extend([os.path.join(path, f) for f in files
  1230. if not f.startswith('test_') and fnmatch(f, pat)])
  1231. if init_only:
  1232. # skip files that are not importable (i.e. missing __init__.py)
  1233. g = [x for x in g if importable(x)]
  1234. return [os.path.normcase(gi) for gi in g]
  1235. def _check_dependencies(self,
  1236. executables=(),
  1237. modules=(),
  1238. disable_viewers=(),
  1239. python_version=(3, 5)):
  1240. """
  1241. Checks if the dependencies for the test are installed.
  1242. Raises ``DependencyError`` it at least one dependency is not installed.
  1243. """
  1244. for executable in executables:
  1245. if not shutil.which(executable):
  1246. raise DependencyError("Could not find %s" % executable)
  1247. for module in modules:
  1248. if module == 'matplotlib':
  1249. matplotlib = import_module(
  1250. 'matplotlib',
  1251. import_kwargs={'fromlist':
  1252. ['pyplot', 'cm', 'collections']},
  1253. min_module_version='1.0.0', catch=(RuntimeError,))
  1254. if matplotlib is None:
  1255. raise DependencyError("Could not import matplotlib")
  1256. else:
  1257. if not import_module(module):
  1258. raise DependencyError("Could not import %s" % module)
  1259. if disable_viewers:
  1260. tempdir = tempfile.mkdtemp()
  1261. os.environ['PATH'] = '%s:%s' % (tempdir, os.environ['PATH'])
  1262. vw = ('#!/usr/bin/env python3\n'
  1263. 'import sys\n'
  1264. 'if len(sys.argv) <= 1:\n'
  1265. ' exit("wrong number of args")\n')
  1266. for viewer in disable_viewers:
  1267. with open(os.path.join(tempdir, viewer), 'w') as fh:
  1268. fh.write(vw)
  1269. # make the file executable
  1270. os.chmod(os.path.join(tempdir, viewer),
  1271. stat.S_IREAD | stat.S_IWRITE | stat.S_IXUSR)
  1272. if python_version:
  1273. if sys.version_info < python_version:
  1274. raise DependencyError("Requires Python >= " + '.'.join(map(str, python_version)))
  1275. if 'pyglet' in modules:
  1276. # monkey-patch pyglet s.t. it does not open a window during
  1277. # doctesting
  1278. import pyglet
  1279. class DummyWindow:
  1280. def __init__(self, *args, **kwargs):
  1281. self.has_exit = True
  1282. self.width = 600
  1283. self.height = 400
  1284. def set_vsync(self, x):
  1285. pass
  1286. def switch_to(self):
  1287. pass
  1288. def push_handlers(self, x):
  1289. pass
  1290. def close(self):
  1291. pass
  1292. pyglet.window.Window = DummyWindow
  1293. class SymPyDocTestFinder(DocTestFinder):
  1294. """
  1295. A class used to extract the DocTests that are relevant to a given
  1296. object, from its docstring and the docstrings of its contained
  1297. objects. Doctests can currently be extracted from the following
  1298. object types: modules, functions, classes, methods, staticmethods,
  1299. classmethods, and properties.
  1300. Modified from doctest's version to look harder for code that
  1301. appears comes from a different module. For example, the @vectorize
  1302. decorator makes it look like functions come from multidimensional.py
  1303. even though their code exists elsewhere.
  1304. """
  1305. def _find(self, tests, obj, name, module, source_lines, globs, seen):
  1306. """
  1307. Find tests for the given object and any contained objects, and
  1308. add them to ``tests``.
  1309. """
  1310. if self._verbose:
  1311. print('Finding tests in %s' % name)
  1312. # If we've already processed this object, then ignore it.
  1313. if id(obj) in seen:
  1314. return
  1315. seen[id(obj)] = 1
  1316. # Make sure we don't run doctests for classes outside of sympy, such
  1317. # as in numpy or scipy.
  1318. if inspect.isclass(obj):
  1319. if obj.__module__.split('.')[0] != 'sympy':
  1320. return
  1321. # Find a test for this object, and add it to the list of tests.
  1322. test = self._get_test(obj, name, module, globs, source_lines)
  1323. if test is not None:
  1324. tests.append(test)
  1325. if not self._recurse:
  1326. return
  1327. # Look for tests in a module's contained objects.
  1328. if inspect.ismodule(obj):
  1329. for rawname, val in obj.__dict__.items():
  1330. # Recurse to functions & classes.
  1331. if inspect.isfunction(val) or inspect.isclass(val):
  1332. # Make sure we don't run doctests functions or classes
  1333. # from different modules
  1334. if val.__module__ != module.__name__:
  1335. continue
  1336. assert self._from_module(module, val), \
  1337. "%s is not in module %s (rawname %s)" % (val, module, rawname)
  1338. try:
  1339. valname = '%s.%s' % (name, rawname)
  1340. self._find(tests, val, valname, module,
  1341. source_lines, globs, seen)
  1342. except KeyboardInterrupt:
  1343. raise
  1344. # Look for tests in a module's __test__ dictionary.
  1345. for valname, val in getattr(obj, '__test__', {}).items():
  1346. if not isinstance(valname, str):
  1347. raise ValueError("SymPyDocTestFinder.find: __test__ keys "
  1348. "must be strings: %r" %
  1349. (type(valname),))
  1350. if not (inspect.isfunction(val) or inspect.isclass(val) or
  1351. inspect.ismethod(val) or inspect.ismodule(val) or
  1352. isinstance(val, str)):
  1353. raise ValueError("SymPyDocTestFinder.find: __test__ values "
  1354. "must be strings, functions, methods, "
  1355. "classes, or modules: %r" %
  1356. (type(val),))
  1357. valname = '%s.__test__.%s' % (name, valname)
  1358. self._find(tests, val, valname, module, source_lines,
  1359. globs, seen)
  1360. # Look for tests in a class's contained objects.
  1361. if inspect.isclass(obj):
  1362. for valname, val in obj.__dict__.items():
  1363. # Special handling for staticmethod/classmethod.
  1364. if isinstance(val, staticmethod):
  1365. val = getattr(obj, valname)
  1366. if isinstance(val, classmethod):
  1367. val = getattr(obj, valname).__func__
  1368. # Recurse to methods, properties, and nested classes.
  1369. if ((inspect.isfunction(unwrap(val)) or
  1370. inspect.isclass(val) or
  1371. isinstance(val, property)) and
  1372. self._from_module(module, val)):
  1373. # Make sure we don't run doctests functions or classes
  1374. # from different modules
  1375. if isinstance(val, property):
  1376. if hasattr(val.fget, '__module__'):
  1377. if val.fget.__module__ != module.__name__:
  1378. continue
  1379. else:
  1380. if val.__module__ != module.__name__:
  1381. continue
  1382. assert self._from_module(module, val), \
  1383. "%s is not in module %s (valname %s)" % (
  1384. val, module, valname)
  1385. valname = '%s.%s' % (name, valname)
  1386. self._find(tests, val, valname, module, source_lines,
  1387. globs, seen)
  1388. def _get_test(self, obj, name, module, globs, source_lines):
  1389. """
  1390. Return a DocTest for the given object, if it defines a docstring;
  1391. otherwise, return None.
  1392. """
  1393. lineno = None
  1394. # Extract the object's docstring. If it doesn't have one,
  1395. # then return None (no test for this object).
  1396. if isinstance(obj, str):
  1397. # obj is a string in the case for objects in the polys package.
  1398. # Note that source_lines is a binary string (compiled polys
  1399. # modules), which can't be handled by _find_lineno so determine
  1400. # the line number here.
  1401. docstring = obj
  1402. matches = re.findall(r"line \d+", name)
  1403. assert len(matches) == 1, \
  1404. "string '%s' does not contain lineno " % name
  1405. # NOTE: this is not the exact linenumber but its better than no
  1406. # lineno ;)
  1407. lineno = int(matches[0][5:])
  1408. else:
  1409. try:
  1410. if obj.__doc__ is None:
  1411. docstring = ''
  1412. else:
  1413. docstring = obj.__doc__
  1414. if not isinstance(docstring, str):
  1415. docstring = str(docstring)
  1416. except (TypeError, AttributeError):
  1417. docstring = ''
  1418. # Don't bother if the docstring is empty.
  1419. if self._exclude_empty and not docstring:
  1420. return None
  1421. # check that properties have a docstring because _find_lineno
  1422. # assumes it
  1423. if isinstance(obj, property):
  1424. if obj.fget.__doc__ is None:
  1425. return None
  1426. # Find the docstring's location in the file.
  1427. if lineno is None:
  1428. obj = unwrap(obj)
  1429. # handling of properties is not implemented in _find_lineno so do
  1430. # it here
  1431. if hasattr(obj, 'func_closure') and obj.func_closure is not None:
  1432. tobj = obj.func_closure[0].cell_contents
  1433. elif isinstance(obj, property):
  1434. tobj = obj.fget
  1435. else:
  1436. tobj = obj
  1437. lineno = self._find_lineno(tobj, source_lines)
  1438. if lineno is None:
  1439. return None
  1440. # Return a DocTest for this object.
  1441. if module is None:
  1442. filename = None
  1443. else:
  1444. filename = getattr(module, '__file__', module.__name__)
  1445. if filename[-4:] in (".pyc", ".pyo"):
  1446. filename = filename[:-1]
  1447. globs['_doctest_depends_on'] = getattr(obj, '_doctest_depends_on', {})
  1448. return self._parser.get_doctest(docstring, globs, name,
  1449. filename, lineno)
  1450. class SymPyDocTestRunner(DocTestRunner):
  1451. """
  1452. A class used to run DocTest test cases, and accumulate statistics.
  1453. The ``run`` method is used to process a single DocTest case. It
  1454. returns a tuple ``(f, t)``, where ``t`` is the number of test cases
  1455. tried, and ``f`` is the number of test cases that failed.
  1456. Modified from the doctest version to not reset the sys.displayhook (see
  1457. issue 5140).
  1458. See the docstring of the original DocTestRunner for more information.
  1459. """
  1460. def run(self, test, compileflags=None, out=None, clear_globs=True):
  1461. """
  1462. Run the examples in ``test``, and display the results using the
  1463. writer function ``out``.
  1464. The examples are run in the namespace ``test.globs``. If
  1465. ``clear_globs`` is true (the default), then this namespace will
  1466. be cleared after the test runs, to help with garbage
  1467. collection. If you would like to examine the namespace after
  1468. the test completes, then use ``clear_globs=False``.
  1469. ``compileflags`` gives the set of flags that should be used by
  1470. the Python compiler when running the examples. If not
  1471. specified, then it will default to the set of future-import
  1472. flags that apply to ``globs``.
  1473. The output of each example is checked using
  1474. ``SymPyDocTestRunner.check_output``, and the results are
  1475. formatted by the ``SymPyDocTestRunner.report_*`` methods.
  1476. """
  1477. self.test = test
  1478. if compileflags is None:
  1479. compileflags = pdoctest._extract_future_flags(test.globs)
  1480. save_stdout = sys.stdout
  1481. if out is None:
  1482. out = save_stdout.write
  1483. sys.stdout = self._fakeout
  1484. # Patch pdb.set_trace to restore sys.stdout during interactive
  1485. # debugging (so it's not still redirected to self._fakeout).
  1486. # Note that the interactive output will go to *our*
  1487. # save_stdout, even if that's not the real sys.stdout; this
  1488. # allows us to write test cases for the set_trace behavior.
  1489. save_set_trace = pdb.set_trace
  1490. self.debugger = pdoctest._OutputRedirectingPdb(save_stdout)
  1491. self.debugger.reset()
  1492. pdb.set_trace = self.debugger.set_trace
  1493. # Patch linecache.getlines, so we can see the example's source
  1494. # when we're inside the debugger.
  1495. self.save_linecache_getlines = pdoctest.linecache.getlines
  1496. linecache.getlines = self.__patched_linecache_getlines
  1497. # Fail for deprecation warnings
  1498. with raise_on_deprecated():
  1499. try:
  1500. return self.__run(test, compileflags, out)
  1501. finally:
  1502. sys.stdout = save_stdout
  1503. pdb.set_trace = save_set_trace
  1504. linecache.getlines = self.save_linecache_getlines
  1505. if clear_globs:
  1506. test.globs.clear()
  1507. # We have to override the name mangled methods.
  1508. monkeypatched_methods = [
  1509. 'patched_linecache_getlines',
  1510. 'run',
  1511. 'record_outcome'
  1512. ]
  1513. for method in monkeypatched_methods:
  1514. oldname = '_DocTestRunner__' + method
  1515. newname = '_SymPyDocTestRunner__' + method
  1516. setattr(SymPyDocTestRunner, newname, getattr(DocTestRunner, oldname))
  1517. class SymPyOutputChecker(pdoctest.OutputChecker):
  1518. """
  1519. Compared to the OutputChecker from the stdlib our OutputChecker class
  1520. supports numerical comparison of floats occurring in the output of the
  1521. doctest examples
  1522. """
  1523. def __init__(self):
  1524. # NOTE OutputChecker is an old-style class with no __init__ method,
  1525. # so we can't call the base class version of __init__ here
  1526. got_floats = r'(\d+\.\d*|\.\d+)'
  1527. # floats in the 'want' string may contain ellipses
  1528. want_floats = got_floats + r'(\.{3})?'
  1529. front_sep = r'\s|\+|\-|\*|,'
  1530. back_sep = front_sep + r'|j|e'
  1531. fbeg = r'^%s(?=%s|$)' % (got_floats, back_sep)
  1532. fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, got_floats, back_sep)
  1533. self.num_got_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))
  1534. fbeg = r'^%s(?=%s|$)' % (want_floats, back_sep)
  1535. fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, want_floats, back_sep)
  1536. self.num_want_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))
  1537. def check_output(self, want, got, optionflags):
  1538. """
  1539. Return True iff the actual output from an example (`got`)
  1540. matches the expected output (`want`). These strings are
  1541. always considered to match if they are identical; but
  1542. depending on what option flags the test runner is using,
  1543. several non-exact match types are also possible. See the
  1544. documentation for `TestRunner` for more information about
  1545. option flags.
  1546. """
  1547. # Handle the common case first, for efficiency:
  1548. # if they're string-identical, always return true.
  1549. if got == want:
  1550. return True
  1551. # TODO parse integers as well ?
  1552. # Parse floats and compare them. If some of the parsed floats contain
  1553. # ellipses, skip the comparison.
  1554. matches = self.num_got_rgx.finditer(got)
  1555. numbers_got = [match.group(1) for match in matches] # list of strs
  1556. matches = self.num_want_rgx.finditer(want)
  1557. numbers_want = [match.group(1) for match in matches] # list of strs
  1558. if len(numbers_got) != len(numbers_want):
  1559. return False
  1560. if len(numbers_got) > 0:
  1561. nw_ = []
  1562. for ng, nw in zip(numbers_got, numbers_want):
  1563. if '...' in nw:
  1564. nw_.append(ng)
  1565. continue
  1566. else:
  1567. nw_.append(nw)
  1568. if abs(float(ng)-float(nw)) > 1e-5:
  1569. return False
  1570. got = self.num_got_rgx.sub(r'%s', got)
  1571. got = got % tuple(nw_)
  1572. # <BLANKLINE> can be used as a special sequence to signify a
  1573. # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
  1574. if not (optionflags & pdoctest.DONT_ACCEPT_BLANKLINE):
  1575. # Replace <BLANKLINE> in want with a blank line.
  1576. want = re.sub(r'(?m)^%s\s*?$' % re.escape(pdoctest.BLANKLINE_MARKER),
  1577. '', want)
  1578. # If a line in got contains only spaces, then remove the
  1579. # spaces.
  1580. got = re.sub(r'(?m)^\s*?$', '', got)
  1581. if got == want:
  1582. return True
  1583. # This flag causes doctest to ignore any differences in the
  1584. # contents of whitespace strings. Note that this can be used
  1585. # in conjunction with the ELLIPSIS flag.
  1586. if optionflags & pdoctest.NORMALIZE_WHITESPACE:
  1587. got = ' '.join(got.split())
  1588. want = ' '.join(want.split())
  1589. if got == want:
  1590. return True
  1591. # The ELLIPSIS flag says to let the sequence "..." in `want`
  1592. # match any substring in `got`.
  1593. if optionflags & pdoctest.ELLIPSIS:
  1594. if pdoctest._ellipsis_match(want, got):
  1595. return True
  1596. # We didn't find any match; return false.
  1597. return False
  1598. class Reporter:
  1599. """
  1600. Parent class for all reporters.
  1601. """
  1602. pass
  1603. class PyTestReporter(Reporter):
  1604. """
  1605. Py.test like reporter. Should produce output identical to py.test.
  1606. """
  1607. def __init__(self, verbose=False, tb="short", colors=True,
  1608. force_colors=False, split=None):
  1609. self._verbose = verbose
  1610. self._tb_style = tb
  1611. self._colors = colors
  1612. self._force_colors = force_colors
  1613. self._xfailed = 0
  1614. self._xpassed = []
  1615. self._failed = []
  1616. self._failed_doctest = []
  1617. self._passed = 0
  1618. self._skipped = 0
  1619. self._exceptions = []
  1620. self._terminal_width = None
  1621. self._default_width = 80
  1622. self._split = split
  1623. self._active_file = ''
  1624. self._active_f = None
  1625. # TODO: Should these be protected?
  1626. self.slow_test_functions = []
  1627. self.fast_test_functions = []
  1628. # this tracks the x-position of the cursor (useful for positioning
  1629. # things on the screen), without the need for any readline library:
  1630. self._write_pos = 0
  1631. self._line_wrap = False
  1632. def root_dir(self, dir):
  1633. self._root_dir = dir
  1634. @property
  1635. def terminal_width(self):
  1636. if self._terminal_width is not None:
  1637. return self._terminal_width
  1638. def findout_terminal_width():
  1639. if sys.platform == "win32":
  1640. # Windows support is based on:
  1641. #
  1642. # http://code.activestate.com/recipes/
  1643. # 440694-determine-size-of-console-window-on-windows/
  1644. from ctypes import windll, create_string_buffer
  1645. h = windll.kernel32.GetStdHandle(-12)
  1646. csbi = create_string_buffer(22)
  1647. res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
  1648. if res:
  1649. import struct
  1650. (_, _, _, _, _, left, _, right, _, _, _) = \
  1651. struct.unpack("hhhhHhhhhhh", csbi.raw)
  1652. return right - left
  1653. else:
  1654. return self._default_width
  1655. if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty():
  1656. return self._default_width # leave PIPEs alone
  1657. try:
  1658. process = subprocess.Popen(['stty', '-a'],
  1659. stdout=subprocess.PIPE,
  1660. stderr=subprocess.PIPE)
  1661. stdout = process.stdout.read()
  1662. stdout = stdout.decode("utf-8")
  1663. except OSError:
  1664. pass
  1665. else:
  1666. # We support the following output formats from stty:
  1667. #
  1668. # 1) Linux -> columns 80
  1669. # 2) OS X -> 80 columns
  1670. # 3) Solaris -> columns = 80
  1671. re_linux = r"columns\s+(?P<columns>\d+);"
  1672. re_osx = r"(?P<columns>\d+)\s*columns;"
  1673. re_solaris = r"columns\s+=\s+(?P<columns>\d+);"
  1674. for regex in (re_linux, re_osx, re_solaris):
  1675. match = re.search(regex, stdout)
  1676. if match is not None:
  1677. columns = match.group('columns')
  1678. try:
  1679. width = int(columns)
  1680. except ValueError:
  1681. pass
  1682. if width != 0:
  1683. return width
  1684. return self._default_width
  1685. width = findout_terminal_width()
  1686. self._terminal_width = width
  1687. return width
  1688. def write(self, text, color="", align="left", width=None,
  1689. force_colors=False):
  1690. """
  1691. Prints a text on the screen.
  1692. It uses sys.stdout.write(), so no readline library is necessary.
  1693. Parameters
  1694. ==========
  1695. color : choose from the colors below, "" means default color
  1696. align : "left"/"right", "left" is a normal print, "right" is aligned on
  1697. the right-hand side of the screen, filled with spaces if
  1698. necessary
  1699. width : the screen width
  1700. """
  1701. color_templates = (
  1702. ("Black", "0;30"),
  1703. ("Red", "0;31"),
  1704. ("Green", "0;32"),
  1705. ("Brown", "0;33"),
  1706. ("Blue", "0;34"),
  1707. ("Purple", "0;35"),
  1708. ("Cyan", "0;36"),
  1709. ("LightGray", "0;37"),
  1710. ("DarkGray", "1;30"),
  1711. ("LightRed", "1;31"),
  1712. ("LightGreen", "1;32"),
  1713. ("Yellow", "1;33"),
  1714. ("LightBlue", "1;34"),
  1715. ("LightPurple", "1;35"),
  1716. ("LightCyan", "1;36"),
  1717. ("White", "1;37"),
  1718. )
  1719. colors = {}
  1720. for name, value in color_templates:
  1721. colors[name] = value
  1722. c_normal = '\033[0m'
  1723. c_color = '\033[%sm'
  1724. if width is None:
  1725. width = self.terminal_width
  1726. if align == "right":
  1727. if self._write_pos + len(text) > width:
  1728. # we don't fit on the current line, create a new line
  1729. self.write("\n")
  1730. self.write(" "*(width - self._write_pos - len(text)))
  1731. if not self._force_colors and hasattr(sys.stdout, 'isatty') and not \
  1732. sys.stdout.isatty():
  1733. # the stdout is not a terminal, this for example happens if the
  1734. # output is piped to less, e.g. "bin/test | less". In this case,
  1735. # the terminal control sequences would be printed verbatim, so
  1736. # don't use any colors.
  1737. color = ""
  1738. elif sys.platform == "win32":
  1739. # Windows consoles don't support ANSI escape sequences
  1740. color = ""
  1741. elif not self._colors:
  1742. color = ""
  1743. if self._line_wrap:
  1744. if text[0] != "\n":
  1745. sys.stdout.write("\n")
  1746. # Avoid UnicodeEncodeError when printing out test failures
  1747. if IS_WINDOWS:
  1748. text = text.encode('raw_unicode_escape').decode('utf8', 'ignore')
  1749. elif not sys.stdout.encoding.lower().startswith('utf'):
  1750. text = text.encode(sys.stdout.encoding, 'backslashreplace'
  1751. ).decode(sys.stdout.encoding)
  1752. if color == "":
  1753. sys.stdout.write(text)
  1754. else:
  1755. sys.stdout.write("%s%s%s" %
  1756. (c_color % colors[color], text, c_normal))
  1757. sys.stdout.flush()
  1758. l = text.rfind("\n")
  1759. if l == -1:
  1760. self._write_pos += len(text)
  1761. else:
  1762. self._write_pos = len(text) - l - 1
  1763. self._line_wrap = self._write_pos >= width
  1764. self._write_pos %= width
  1765. def write_center(self, text, delim="="):
  1766. width = self.terminal_width
  1767. if text != "":
  1768. text = " %s " % text
  1769. idx = (width - len(text)) // 2
  1770. t = delim*idx + text + delim*(width - idx - len(text))
  1771. self.write(t + "\n")
  1772. def write_exception(self, e, val, tb):
  1773. # remove the first item, as that is always runtests.py
  1774. tb = tb.tb_next
  1775. t = traceback.format_exception(e, val, tb)
  1776. self.write("".join(t))
  1777. def start(self, seed=None, msg="test process starts"):
  1778. self.write_center(msg)
  1779. executable = sys.executable
  1780. v = tuple(sys.version_info)
  1781. python_version = "%s.%s.%s-%s-%s" % v
  1782. implementation = platform.python_implementation()
  1783. if implementation == 'PyPy':
  1784. implementation += " %s.%s.%s-%s-%s" % sys.pypy_version_info
  1785. self.write("executable: %s (%s) [%s]\n" %
  1786. (executable, python_version, implementation))
  1787. from sympy.utilities.misc import ARCH
  1788. self.write("architecture: %s\n" % ARCH)
  1789. from sympy.core.cache import USE_CACHE
  1790. self.write("cache: %s\n" % USE_CACHE)
  1791. version = ''
  1792. if GROUND_TYPES =='gmpy':
  1793. if HAS_GMPY == 1:
  1794. import gmpy
  1795. elif HAS_GMPY == 2:
  1796. import gmpy2 as gmpy
  1797. version = gmpy.version()
  1798. self.write("ground types: %s %s\n" % (GROUND_TYPES, version))
  1799. numpy = import_module('numpy')
  1800. self.write("numpy: %s\n" % (None if not numpy else numpy.__version__))
  1801. if seed is not None:
  1802. self.write("random seed: %d\n" % seed)
  1803. from sympy.utilities.misc import HASH_RANDOMIZATION
  1804. self.write("hash randomization: ")
  1805. hash_seed = os.getenv("PYTHONHASHSEED") or '0'
  1806. if HASH_RANDOMIZATION and (hash_seed == "random" or int(hash_seed)):
  1807. self.write("on (PYTHONHASHSEED=%s)\n" % hash_seed)
  1808. else:
  1809. self.write("off\n")
  1810. if self._split:
  1811. self.write("split: %s\n" % self._split)
  1812. self.write('\n')
  1813. self._t_start = clock()
  1814. def finish(self):
  1815. self._t_end = clock()
  1816. self.write("\n")
  1817. global text, linelen
  1818. text = "tests finished: %d passed, " % self._passed
  1819. linelen = len(text)
  1820. def add_text(mytext):
  1821. global text, linelen
  1822. """Break new text if too long."""
  1823. if linelen + len(mytext) > self.terminal_width:
  1824. text += '\n'
  1825. linelen = 0
  1826. text += mytext
  1827. linelen += len(mytext)
  1828. if len(self._failed) > 0:
  1829. add_text("%d failed, " % len(self._failed))
  1830. if len(self._failed_doctest) > 0:
  1831. add_text("%d failed, " % len(self._failed_doctest))
  1832. if self._skipped > 0:
  1833. add_text("%d skipped, " % self._skipped)
  1834. if self._xfailed > 0:
  1835. add_text("%d expected to fail, " % self._xfailed)
  1836. if len(self._xpassed) > 0:
  1837. add_text("%d expected to fail but passed, " % len(self._xpassed))
  1838. if len(self._exceptions) > 0:
  1839. add_text("%d exceptions, " % len(self._exceptions))
  1840. add_text("in %.2f seconds" % (self._t_end - self._t_start))
  1841. if self.slow_test_functions:
  1842. self.write_center('slowest tests', '_')
  1843. sorted_slow = sorted(self.slow_test_functions, key=lambda r: r[1])
  1844. for slow_func_name, taken in sorted_slow:
  1845. print('%s - Took %.3f seconds' % (slow_func_name, taken))
  1846. if self.fast_test_functions:
  1847. self.write_center('unexpectedly fast tests', '_')
  1848. sorted_fast = sorted(self.fast_test_functions,
  1849. key=lambda r: r[1])
  1850. for fast_func_name, taken in sorted_fast:
  1851. print('%s - Took %.3f seconds' % (fast_func_name, taken))
  1852. if len(self._xpassed) > 0:
  1853. self.write_center("xpassed tests", "_")
  1854. for e in self._xpassed:
  1855. self.write("%s: %s\n" % (e[0], e[1]))
  1856. self.write("\n")
  1857. if self._tb_style != "no" and len(self._exceptions) > 0:
  1858. for e in self._exceptions:
  1859. filename, f, (t, val, tb) = e
  1860. self.write_center("", "_")
  1861. if f is None:
  1862. s = "%s" % filename
  1863. else:
  1864. s = "%s:%s" % (filename, f.__name__)
  1865. self.write_center(s, "_")
  1866. self.write_exception(t, val, tb)
  1867. self.write("\n")
  1868. if self._tb_style != "no" and len(self._failed) > 0:
  1869. for e in self._failed:
  1870. filename, f, (t, val, tb) = e
  1871. self.write_center("", "_")
  1872. self.write_center("%s:%s" % (filename, f.__name__), "_")
  1873. self.write_exception(t, val, tb)
  1874. self.write("\n")
  1875. if self._tb_style != "no" and len(self._failed_doctest) > 0:
  1876. for e in self._failed_doctest:
  1877. filename, msg = e
  1878. self.write_center("", "_")
  1879. self.write_center("%s" % filename, "_")
  1880. self.write(msg)
  1881. self.write("\n")
  1882. self.write_center(text)
  1883. ok = len(self._failed) == 0 and len(self._exceptions) == 0 and \
  1884. len(self._failed_doctest) == 0
  1885. if not ok:
  1886. self.write("DO *NOT* COMMIT!\n")
  1887. return ok
  1888. def entering_filename(self, filename, n):
  1889. rel_name = filename[len(self._root_dir) + 1:]
  1890. self._active_file = rel_name
  1891. self._active_file_error = False
  1892. self.write(rel_name)
  1893. self.write("[%d] " % n)
  1894. def leaving_filename(self):
  1895. self.write(" ")
  1896. if self._active_file_error:
  1897. self.write("[FAIL]", "Red", align="right")
  1898. else:
  1899. self.write("[OK]", "Green", align="right")
  1900. self.write("\n")
  1901. if self._verbose:
  1902. self.write("\n")
  1903. def entering_test(self, f):
  1904. self._active_f = f
  1905. if self._verbose:
  1906. self.write("\n" + f.__name__ + " ")
  1907. def test_xfail(self):
  1908. self._xfailed += 1
  1909. self.write("f", "Green")
  1910. def test_xpass(self, v):
  1911. message = str(v)
  1912. self._xpassed.append((self._active_file, message))
  1913. self.write("X", "Green")
  1914. def test_fail(self, exc_info):
  1915. self._failed.append((self._active_file, self._active_f, exc_info))
  1916. self.write("F", "Red")
  1917. self._active_file_error = True
  1918. def doctest_fail(self, name, error_msg):
  1919. # the first line contains "******", remove it:
  1920. error_msg = "\n".join(error_msg.split("\n")[1:])
  1921. self._failed_doctest.append((name, error_msg))
  1922. self.write("F", "Red")
  1923. self._active_file_error = True
  1924. def test_pass(self, char="."):
  1925. self._passed += 1
  1926. if self._verbose:
  1927. self.write("ok", "Green")
  1928. else:
  1929. self.write(char, "Green")
  1930. def test_skip(self, v=None):
  1931. char = "s"
  1932. self._skipped += 1
  1933. if v is not None:
  1934. message = str(v)
  1935. if message == "KeyboardInterrupt":
  1936. char = "K"
  1937. elif message == "Timeout":
  1938. char = "T"
  1939. elif message == "Slow":
  1940. char = "w"
  1941. if self._verbose:
  1942. if v is not None:
  1943. self.write(message + ' ', "Blue")
  1944. else:
  1945. self.write(" - ", "Blue")
  1946. self.write(char, "Blue")
  1947. def test_exception(self, exc_info):
  1948. self._exceptions.append((self._active_file, self._active_f, exc_info))
  1949. if exc_info[0] is TimeOutError:
  1950. self.write("T", "Red")
  1951. else:
  1952. self.write("E", "Red")
  1953. self._active_file_error = True
  1954. def import_error(self, filename, exc_info):
  1955. self._exceptions.append((filename, None, exc_info))
  1956. rel_name = filename[len(self._root_dir) + 1:]
  1957. self.write(rel_name)
  1958. self.write("[?] Failed to import", "Red")
  1959. self.write(" ")
  1960. self.write("[FAIL]", "Red", align="right")
  1961. self.write("\n")