brain_nose.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. """Hooks for nose library."""
  5. import re
  6. import textwrap
  7. import astroid.builder
  8. from astroid.brain.helpers import register_module_extender
  9. from astroid.exceptions import InferenceError
  10. from astroid.manager import AstroidManager
  11. _BUILDER = astroid.builder.AstroidBuilder(AstroidManager())
  12. CAPITALS = re.compile("([A-Z])")
  13. def _pep8(name, caps=CAPITALS):
  14. return caps.sub(lambda m: "_" + m.groups()[0].lower(), name)
  15. def _nose_tools_functions():
  16. """Get an iterator of names and bound methods."""
  17. module = _BUILDER.string_build(
  18. textwrap.dedent(
  19. """
  20. import unittest
  21. class Test(unittest.TestCase):
  22. pass
  23. a = Test()
  24. """
  25. )
  26. )
  27. try:
  28. case = next(module["a"].infer())
  29. except (InferenceError, StopIteration):
  30. return
  31. for method in case.methods():
  32. if method.name.startswith("assert") and "_" not in method.name:
  33. pep8_name = _pep8(method.name)
  34. yield pep8_name, astroid.BoundMethod(method, case)
  35. if method.name == "assertEqual":
  36. # nose also exports assert_equals.
  37. yield "assert_equals", astroid.BoundMethod(method, case)
  38. def _nose_tools_transform(node):
  39. for method_name, method in _nose_tools_functions():
  40. node.locals[method_name] = [method]
  41. def _nose_tools_trivial_transform():
  42. """Custom transform for the nose.tools module."""
  43. stub = _BUILDER.string_build("""__all__ = []""")
  44. all_entries = ["ok_", "eq_"]
  45. for pep8_name, method in _nose_tools_functions():
  46. all_entries.append(pep8_name)
  47. stub[pep8_name] = method
  48. # Update the __all__ variable, since nose.tools
  49. # does this manually with .append.
  50. all_assign = stub["__all__"].parent
  51. all_object = astroid.List(all_entries)
  52. all_object.parent = all_assign
  53. all_assign.value = all_object
  54. return stub
  55. register_module_extender(
  56. AstroidManager(), "nose.tools.trivial", _nose_tools_trivial_transform
  57. )
  58. AstroidManager().register_transform(
  59. astroid.Module, _nose_tools_transform, lambda n: n.name == "nose.tools"
  60. )