runtests_pytest.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. """Backwards compatible functions for running tests from SymPy using pytest.
  2. SymPy historically had its own testing framework that aimed to:
  3. - be compatible with pytest;
  4. - operate similarly (or identically) to pytest;
  5. - not require any external dependencies;
  6. - have all the functionality in one file only;
  7. - have no magic, just import the test file and execute the test functions; and
  8. - be portable.
  9. To reduce the maintenance burden of developing an independent testing framework
  10. and to leverage the benefits of existing Python testing infrastructure, SymPy
  11. now uses pytest (and various of its plugins) to run the test suite.
  12. To maintain backwards compatibility with the legacy testing interface of SymPy,
  13. which implemented functions that allowed users to run the tests on their
  14. installed version of SymPy, the functions in this module are implemented to
  15. match the existing API while thinly wrapping pytest.
  16. These two key functions are `test` and `doctest`.
  17. """
  18. import functools
  19. import importlib.util
  20. import os
  21. import pathlib
  22. import re
  23. from fnmatch import fnmatch
  24. from typing import List, Optional, Tuple
  25. try:
  26. import pytest
  27. except ImportError:
  28. class NoPytestError(Exception):
  29. """Raise when an internal test helper function is called with pytest."""
  30. class pytest: # type: ignore
  31. """Shadow to support pytest features when pytest can't be imported."""
  32. @staticmethod
  33. def main(*args, **kwargs):
  34. msg = 'pytest must be installed to run tests via this function'
  35. raise NoPytestError(msg)
  36. from sympy.testing.runtests import test as test_sympy
  37. TESTPATHS_DEFAULT = (
  38. pathlib.Path('sympy'),
  39. pathlib.Path('doc', 'src'),
  40. )
  41. BLACKLIST_DEFAULT = (
  42. 'sympy/integrals/rubi/rubi_tests/tests',
  43. )
  44. class PytestPluginManager:
  45. """Module names for pytest plugins used by SymPy."""
  46. PYTEST: str = 'pytest'
  47. RANDOMLY: str = 'pytest_randomly'
  48. SPLIT: str = 'pytest_split'
  49. TIMEOUT: str = 'pytest_timeout'
  50. XDIST: str = 'xdist'
  51. @functools.cached_property
  52. def has_pytest(self) -> bool:
  53. return bool(importlib.util.find_spec(self.PYTEST))
  54. @functools.cached_property
  55. def has_randomly(self) -> bool:
  56. return bool(importlib.util.find_spec(self.RANDOMLY))
  57. @functools.cached_property
  58. def has_split(self) -> bool:
  59. return bool(importlib.util.find_spec(self.SPLIT))
  60. @functools.cached_property
  61. def has_timeout(self) -> bool:
  62. return bool(importlib.util.find_spec(self.TIMEOUT))
  63. @functools.cached_property
  64. def has_xdist(self) -> bool:
  65. return bool(importlib.util.find_spec(self.XDIST))
  66. split_pattern = re.compile(r'([1-9][0-9]*)/([1-9][0-9]*)')
  67. @functools.lru_cache
  68. def sympy_dir() -> pathlib.Path:
  69. """Returns the root SymPy directory."""
  70. return pathlib.Path(__file__).parents[2]
  71. def update_args_with_paths(
  72. paths: List[str],
  73. keywords: Optional[Tuple[str]],
  74. args: List[str],
  75. ) -> List[str]:
  76. """Appends valid paths and flags to the args `list` passed to `pytest.main`.
  77. The are three different types of "path" that a user may pass to the `paths`
  78. positional arguments, all of which need to be handled slightly differently:
  79. 1. Nothing is passed
  80. The paths to the `testpaths` defined in `pytest.ini` need to be appended
  81. to the arguments list.
  82. 2. Full, valid paths are passed
  83. These paths need to be validated but can then be directly appended to
  84. the arguments list.
  85. 3. Partial paths are passed.
  86. The `testpaths` defined in `pytest.ini` need to be recursed and any
  87. matches be appended to the arguments list.
  88. """
  89. def find_paths_matching_partial(partial_paths):
  90. partial_path_file_patterns = []
  91. for partial_path in partial_paths:
  92. if len(partial_path) >= 4:
  93. has_test_prefix = partial_path[:4] == 'test'
  94. has_py_suffix = partial_path[-3:] == '.py'
  95. elif len(partial_path) >= 3:
  96. has_test_prefix = False
  97. has_py_suffix = partial_path[-3:] == '.py'
  98. else:
  99. has_test_prefix = False
  100. has_py_suffix = False
  101. if has_test_prefix and has_py_suffix:
  102. partial_path_file_patterns.append(partial_path)
  103. elif has_test_prefix:
  104. partial_path_file_patterns.append(f'{partial_path}*.py')
  105. elif has_py_suffix:
  106. partial_path_file_patterns.append(f'test*{partial_path}')
  107. else:
  108. partial_path_file_patterns.append(f'test*{partial_path}*.py')
  109. matches = []
  110. for testpath in valid_testpaths_default:
  111. for path, dirs, files in os.walk(testpath, topdown=True):
  112. zipped = zip(partial_paths, partial_path_file_patterns)
  113. for (partial_path, partial_path_file) in zipped:
  114. if fnmatch(path, f'*{partial_path}*'):
  115. matches.append(str(pathlib.Path(path)))
  116. dirs[:] = []
  117. else:
  118. for file in files:
  119. if fnmatch(file, partial_path_file):
  120. matches.append(str(pathlib.Path(path, file)))
  121. return matches
  122. def is_tests_file(filepath: str) -> bool:
  123. path = pathlib.Path(filepath)
  124. if not path.is_file():
  125. return False
  126. if not path.parts[-1].startswith('test_'):
  127. return False
  128. if not path.suffix == '.py':
  129. return False
  130. return True
  131. def find_tests_matching_keywords(keywords, filepath):
  132. matches = []
  133. source = pathlib.Path(filepath).read_text(encoding='utf-8')
  134. for line in source.splitlines():
  135. if line.lstrip().startswith('def '):
  136. for kw in keywords:
  137. if line.lower().find(kw.lower()) != -1:
  138. test_name = line.split(' ')[1].split('(')[0]
  139. full_test_path = filepath + '::' + test_name
  140. matches.append(full_test_path)
  141. return matches
  142. valid_testpaths_default = []
  143. for testpath in TESTPATHS_DEFAULT:
  144. absolute_testpath = pathlib.Path(sympy_dir(), testpath)
  145. if absolute_testpath.exists():
  146. valid_testpaths_default.append(str(absolute_testpath))
  147. candidate_paths = []
  148. if paths:
  149. full_paths = []
  150. partial_paths = []
  151. for path in paths:
  152. if pathlib.Path(path).exists():
  153. full_paths.append(str(pathlib.Path(sympy_dir(), path)))
  154. else:
  155. partial_paths.append(path)
  156. matched_paths = find_paths_matching_partial(partial_paths)
  157. candidate_paths.extend(full_paths)
  158. candidate_paths.extend(matched_paths)
  159. else:
  160. candidate_paths.extend(valid_testpaths_default)
  161. if keywords is not None and keywords != ():
  162. matches = []
  163. for path in candidate_paths:
  164. if is_tests_file(path):
  165. test_matches = find_tests_matching_keywords(keywords, path)
  166. matches.extend(test_matches)
  167. else:
  168. for root, dirnames, filenames in os.walk(path):
  169. for filename in filenames:
  170. absolute_filepath = str(pathlib.Path(root, filename))
  171. if is_tests_file(absolute_filepath):
  172. test_matches = find_tests_matching_keywords(
  173. keywords,
  174. absolute_filepath,
  175. )
  176. matches.extend(test_matches)
  177. args.extend(matches)
  178. else:
  179. args.extend(candidate_paths)
  180. return args
  181. def make_absolute_path(partial_path: str) -> str:
  182. """Convert a partial path to an absolute path.
  183. A path such a `sympy/core` might be needed. However, absolute paths should
  184. be used in the arguments to pytest in all cases as it avoids errors that
  185. arise from nonexistent paths.
  186. This function assumes that partial_paths will be passed in such that they
  187. begin with the explicit `sympy` directory, i.e. `sympy/...`.
  188. """
  189. def is_valid_partial_path(partial_path: str) -> bool:
  190. """Assumption that partial paths are defined from the `sympy` root."""
  191. return pathlib.Path(partial_path).parts[0] == 'sympy'
  192. if not is_valid_partial_path(partial_path):
  193. msg = (
  194. f'Partial path {dir(partial_path)} is invalid, partial paths are '
  195. f'expected to be defined with the `sympy` directory as the root.'
  196. )
  197. raise ValueError(msg)
  198. absolute_path = str(pathlib.Path(sympy_dir(), partial_path))
  199. return absolute_path
  200. def test(*paths, subprocess=True, rerun=0, **kwargs):
  201. """Interface to run tests via pytest compatible with SymPy's test runner.
  202. Explanation
  203. ===========
  204. Note that a `pytest.ExitCode`, which is an `enum`, is returned. This is
  205. different to the legacy SymPy test runner which would return a `bool`. If
  206. all tests successfully pass the `pytest.ExitCode.OK` with value `0` is
  207. returned, whereas the legacy SymPy test runner would return `True`. In any
  208. other scenario, a non-zero `enum` value is returned, whereas the legacy
  209. SymPy test runner would return `False`. Users need to, therefore, be careful
  210. if treating the pytest exit codes as booleans because
  211. `bool(pytest.ExitCode.OK)` evaluates to `False`, the opposite of legacy
  212. behaviour.
  213. Examples
  214. ========
  215. >>> import sympy # doctest: +SKIP
  216. Run one file:
  217. >>> sympy.test('sympy/core/tests/test_basic.py') # doctest: +SKIP
  218. >>> sympy.test('_basic') # doctest: +SKIP
  219. Run all tests in sympy/functions/ and some particular file:
  220. >>> sympy.test("sympy/core/tests/test_basic.py",
  221. ... "sympy/functions") # doctest: +SKIP
  222. Run all tests in sympy/core and sympy/utilities:
  223. >>> sympy.test("/core", "/util") # doctest: +SKIP
  224. Run specific test from a file:
  225. >>> sympy.test("sympy/core/tests/test_basic.py",
  226. ... kw="test_equality") # doctest: +SKIP
  227. Run specific test from any file:
  228. >>> sympy.test(kw="subs") # doctest: +SKIP
  229. Run the tests using the legacy SymPy runner:
  230. >>> sympy.test(use_sympy_runner=True) # doctest: +SKIP
  231. Note that this option is slated for deprecation in the near future and is
  232. only currently provided to ensure users have an alternative option while the
  233. pytest-based runner receives real-world testing.
  234. Parameters
  235. ==========
  236. paths : first n positional arguments of strings
  237. Paths, both partial and absolute, describing which subset(s) of the test
  238. suite are to be run.
  239. subprocess : bool, default is True
  240. Legacy option, is currently ignored.
  241. rerun : int, default is 0
  242. Legacy option, is ignored.
  243. use_sympy_runner : bool or None, default is None
  244. Temporary option to invoke the legacy SymPy test runner instead of
  245. `pytest.main`. Will be removed in the near future.
  246. verbose : bool, default is False
  247. Sets the verbosity of the pytest output. Using `True` will add the
  248. `--verbose` option to the pytest call.
  249. tb : str, 'auto', 'long', 'short', 'line', 'native', or 'no'
  250. Sets the traceback print mode of pytest using the `--tb` option.
  251. kw : str
  252. Only run tests which match the given substring expression. An expression
  253. is a Python evaluatable expression where all names are substring-matched
  254. against test names and their parent classes. Example: -k 'test_method or
  255. test_other' matches all test functions and classes whose name contains
  256. 'test_method' or 'test_other', while -k 'not test_method' matches those
  257. that don't contain 'test_method' in their names. -k 'not test_method and
  258. not test_other' will eliminate the matches. Additionally keywords are
  259. matched to classes and functions containing extra names in their
  260. 'extra_keyword_matches' set, as well as functions which have names
  261. assigned directly to them. The matching is case-insensitive.
  262. pdb : bool, default is False
  263. Start the interactive Python debugger on errors or `KeyboardInterrupt`.
  264. colors : bool, default is True
  265. Color terminal output.
  266. force_colors : bool, default is False
  267. Legacy option, is ignored.
  268. sort : bool, default is True
  269. Run the tests in sorted order. pytest uses a sorted test order by
  270. default. Requires pytest-randomly.
  271. seed : int
  272. Seed to use for random number generation. Requires pytest-randomly.
  273. timeout : int, default is 0
  274. Timeout in seconds before dumping the stacks. 0 means no timeout.
  275. Requires pytest-timeout.
  276. fail_on_timeout : bool, default is False
  277. Legacy option, is currently ignored.
  278. slow : bool, default is False
  279. Run the subset of tests marked as `slow`.
  280. enhance_asserts : bool, default is False
  281. Legacy option, is currently ignored.
  282. split : string in form `<SPLIT>/<GROUPS>` or None, default is None
  283. Used to split the tests up. As an example, if `split='2/3' is used then
  284. only the middle third of tests are run. Requires pytest-split.
  285. time_balance : bool, default is True
  286. Legacy option, is currently ignored.
  287. blacklist : iterable of test paths as strings, default is BLACKLIST_DEFAULT
  288. Blacklisted test paths are ignored using the `--ignore` option. Paths
  289. may be partial or absolute. If partial then they are matched against
  290. all paths in the pytest tests path.
  291. parallel : bool, default is False
  292. Parallelize the test running using pytest-xdist. If `True` then pytest
  293. will automatically detect the number of CPU cores available and use them
  294. all. Requires pytest-xdist.
  295. store_durations : bool, False
  296. Store test durations into the file `.test_durations`. The is used by
  297. `pytest-split` to help determine more even splits when more than one
  298. test group is being used. Requires pytest-split.
  299. """
  300. # NOTE: to be removed alongside SymPy test runner
  301. if kwargs.get('use_sympy_runner', False):
  302. kwargs.pop('parallel', False)
  303. kwargs.pop('store_durations', False)
  304. kwargs.pop('use_sympy_runner', True)
  305. if kwargs.get('slow') is None:
  306. kwargs['slow'] = False
  307. return test_sympy(*paths, subprocess=True, rerun=0, **kwargs)
  308. pytest_plugin_manager = PytestPluginManager()
  309. if not pytest_plugin_manager.has_pytest:
  310. pytest.main()
  311. args = []
  312. if kwargs.get('verbose', False):
  313. args.append('--verbose')
  314. if tb := kwargs.get('tb'):
  315. args.extend(['--tb', tb])
  316. if kwargs.get('pdb'):
  317. args.append('--pdb')
  318. if not kwargs.get('colors', True):
  319. args.extend(['--color', 'no'])
  320. if seed := kwargs.get('seed'):
  321. if not pytest_plugin_manager.has_randomly:
  322. msg = '`pytest-randomly` plugin required to control random seed.'
  323. raise ModuleNotFoundError(msg)
  324. args.extend(['--randomly-seed', str(seed)])
  325. if kwargs.get('sort', True) and pytest_plugin_manager.has_randomly:
  326. args.append('--randomly-dont-reorganize')
  327. elif not kwargs.get('sort', True) and not pytest_plugin_manager.has_randomly:
  328. msg = '`pytest-randomly` plugin required to randomize test order.'
  329. raise ModuleNotFoundError(msg)
  330. if timeout := kwargs.get('timeout', None):
  331. if not pytest_plugin_manager.has_timeout:
  332. msg = '`pytest-timeout` plugin required to apply timeout to tests.'
  333. raise ModuleNotFoundError(msg)
  334. args.extend(['--timeout', str(int(timeout))])
  335. # Skip slow tests by default and always skip tooslow tests
  336. if kwargs.get('slow', False):
  337. args.extend(['-m', 'slow and not tooslow'])
  338. else:
  339. args.extend(['-m', 'not slow and not tooslow'])
  340. if (split := kwargs.get('split')) is not None:
  341. if not pytest_plugin_manager.has_split:
  342. msg = '`pytest-split` plugin required to run tests as groups.'
  343. raise ModuleNotFoundError(msg)
  344. match = split_pattern.match(split)
  345. if not match:
  346. msg = ('split must be a string of the form a/b where a and b are '
  347. 'positive nonzero ints')
  348. raise ValueError(msg)
  349. group, splits = map(str, match.groups())
  350. args.extend(['--group', group, '--splits', splits])
  351. if group > splits:
  352. msg = (f'cannot have a group number {group} with only {splits} '
  353. 'splits')
  354. raise ValueError(msg)
  355. if blacklist := kwargs.get('blacklist', BLACKLIST_DEFAULT):
  356. for path in blacklist:
  357. args.extend(['--ignore', make_absolute_path(path)])
  358. if kwargs.get('parallel', False):
  359. if not pytest_plugin_manager.has_xdist:
  360. msg = '`pytest-xdist` plugin required to run tests in parallel.'
  361. raise ModuleNotFoundError(msg)
  362. args.extend(['-n', 'auto'])
  363. if kwargs.get('store_durations', False):
  364. if not pytest_plugin_manager.has_split:
  365. msg = '`pytest-split` plugin required to store test durations.'
  366. raise ModuleNotFoundError(msg)
  367. args.append('--store-durations')
  368. if (keywords := kwargs.get('kw')) is not None:
  369. keywords = tuple(str(kw) for kw in keywords)
  370. else:
  371. keywords = ()
  372. args = update_args_with_paths(paths, keywords, args)
  373. exit_code = pytest.main(args)
  374. return exit_code
  375. def doctest():
  376. """Interface to run doctests via pytest compatible with SymPy's test runner.
  377. """
  378. raise NotImplementedError