legacy.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. # -*- coding: utf-8 -*-
  2. """
  3. this is a place where we put datastructures used by legacy apis
  4. we hope ot remove
  5. """
  6. import keyword
  7. import attr
  8. from _pytest.config import UsageError
  9. @attr.s
  10. class MarkMapping(object):
  11. """Provides a local mapping for markers where item access
  12. resolves to True if the marker is present. """
  13. own_mark_names = attr.ib()
  14. @classmethod
  15. def from_item(cls, item):
  16. mark_names = {mark.name for mark in item.iter_markers()}
  17. return cls(mark_names)
  18. def __getitem__(self, name):
  19. return name in self.own_mark_names
  20. class KeywordMapping(object):
  21. """Provides a local mapping for keywords.
  22. Given a list of names, map any substring of one of these names to True.
  23. """
  24. def __init__(self, names):
  25. self._names = names
  26. @classmethod
  27. def from_item(cls, item):
  28. mapped_names = set()
  29. # Add the names of the current item and any parent items
  30. import pytest
  31. for item in item.listchain():
  32. if not isinstance(item, pytest.Instance):
  33. mapped_names.add(item.name)
  34. # Add the names added as extra keywords to current or parent items
  35. mapped_names.update(item.listextrakeywords())
  36. # Add the names attached to the current function through direct assignment
  37. if hasattr(item, "function"):
  38. mapped_names.update(item.function.__dict__)
  39. # add the markers to the keywords as we no longer handle them correctly
  40. mapped_names.update(mark.name for mark in item.iter_markers())
  41. return cls(mapped_names)
  42. def __getitem__(self, subname):
  43. for name in self._names:
  44. if subname in name:
  45. return True
  46. return False
  47. python_keywords_allowed_list = ["or", "and", "not"]
  48. def matchmark(colitem, markexpr):
  49. """Tries to match on any marker names, attached to the given colitem."""
  50. try:
  51. return eval(markexpr, {}, MarkMapping.from_item(colitem))
  52. except SyntaxError as e:
  53. raise SyntaxError(str(e) + "\nMarker expression must be valid Python!")
  54. def matchkeyword(colitem, keywordexpr):
  55. """Tries to match given keyword expression to given collector item.
  56. Will match on the name of colitem, including the names of its parents.
  57. Only matches names of items which are either a :class:`Class` or a
  58. :class:`Function`.
  59. Additionally, matches on names in the 'extra_keyword_matches' set of
  60. any item, as well as names directly assigned to test functions.
  61. """
  62. mapping = KeywordMapping.from_item(colitem)
  63. if " " not in keywordexpr:
  64. # special case to allow for simple "-k pass" and "-k 1.3"
  65. return mapping[keywordexpr]
  66. elif keywordexpr.startswith("not ") and " " not in keywordexpr[4:]:
  67. return not mapping[keywordexpr[4:]]
  68. for kwd in keywordexpr.split():
  69. if keyword.iskeyword(kwd) and kwd not in python_keywords_allowed_list:
  70. raise UsageError(
  71. "Python keyword '{}' not accepted in expressions passed to '-k'".format(
  72. kwd
  73. )
  74. )
  75. try:
  76. return eval(keywordexpr, {}, mapping)
  77. except SyntaxError:
  78. raise UsageError("Wrong expression passed to '-k': {}".format(keywordexpr))