test_utils.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  2. # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
  3. # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
  4. """Utility functions for test code that uses astroid ASTs as input."""
  5. from __future__ import annotations
  6. import contextlib
  7. import functools
  8. import sys
  9. import warnings
  10. from collections.abc import Callable
  11. import pytest
  12. from astroid import manager, nodes, transforms
  13. def require_version(minver: str = "0.0.0", maxver: str = "4.0.0") -> Callable:
  14. """Compare version of python interpreter to the given one and skips the test if older."""
  15. def parse(python_version: str) -> tuple[int, ...]:
  16. try:
  17. return tuple(int(v) for v in python_version.split("."))
  18. except ValueError as e:
  19. msg = f"{python_version} is not a correct version : should be X.Y[.Z]."
  20. raise ValueError(msg) from e
  21. min_version = parse(minver)
  22. max_version = parse(maxver)
  23. def check_require_version(f):
  24. current: tuple[int, int, int] = sys.version_info[:3]
  25. if min_version < current <= max_version:
  26. return f
  27. version: str = ".".join(str(v) for v in sys.version_info)
  28. @functools.wraps(f)
  29. def new_f(*args, **kwargs):
  30. if current <= min_version:
  31. pytest.skip(f"Needs Python > {minver}. Current version is {version}.")
  32. elif current > max_version:
  33. pytest.skip(f"Needs Python <= {maxver}. Current version is {version}.")
  34. return new_f
  35. return check_require_version
  36. def get_name_node(start_from, name, index=0):
  37. return [n for n in start_from.nodes_of_class(nodes.Name) if n.name == name][index]
  38. @contextlib.contextmanager
  39. def enable_warning(warning):
  40. warnings.simplefilter("always", warning)
  41. try:
  42. yield
  43. finally:
  44. # Reset it to default value, so it will take
  45. # into account the values from the -W flag.
  46. warnings.simplefilter("default", warning)
  47. def brainless_manager():
  48. m = manager.AstroidManager()
  49. # avoid caching into the AstroidManager borg since we get problems
  50. # with other tests :
  51. m.__dict__ = {}
  52. m._failed_import_hooks = []
  53. m.astroid_cache = {}
  54. m._mod_file_cache = {}
  55. m._transform = transforms.TransformVisitor()
  56. m.extension_package_whitelist = set()
  57. return m