test_normalizer_issues_files.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """
  2. To easily verify if our normalizer raises the right error codes, just use the
  3. tests of pydocstyle.
  4. """
  5. import difflib
  6. import re
  7. from functools import total_ordering
  8. import parso
  9. from parso.utils import python_bytes_to_unicode
  10. @total_ordering
  11. class WantedIssue(object):
  12. def __init__(self, code, line, column):
  13. self.code = code
  14. self._line = line
  15. self._column = column
  16. def __eq__(self, other):
  17. return self.code == other.code and self.start_pos == other.start_pos
  18. def __lt__(self, other):
  19. return self.start_pos < other.start_pos or self.code < other.code
  20. def __hash__(self):
  21. return hash(str(self.code) + str(self._line) + str(self._column))
  22. @property
  23. def start_pos(self):
  24. return self._line, self._column
  25. def collect_errors(code):
  26. for line_nr, line in enumerate(code.splitlines(), 1):
  27. match = re.match(r'(\s*)#: (.*)$', line)
  28. if match is not None:
  29. codes = match.group(2)
  30. for code in codes.split():
  31. code, _, add_indent = code.partition(':')
  32. column = int(add_indent or len(match.group(1)))
  33. code, _, add_line = code.partition('+')
  34. l = line_nr + 1 + int(add_line or 0)
  35. yield WantedIssue(code[1:], l, column)
  36. def test_normalizer_issue(normalizer_issue_case):
  37. def sort(issues):
  38. issues = sorted(issues, key=lambda i: (i.start_pos, i.code))
  39. return ["(%s, %s): %s" % (i.start_pos[0], i.start_pos[1], i.code)
  40. for i in issues]
  41. with open(normalizer_issue_case.path, 'rb') as f:
  42. code = python_bytes_to_unicode(f.read())
  43. desired = sort(collect_errors(code))
  44. grammar = parso.load_grammar(version=normalizer_issue_case.python_version)
  45. module = grammar.parse(code)
  46. issues = grammar._get_normalizer_issues(module)
  47. actual = sort(issues)
  48. diff = '\n'.join(difflib.ndiff(desired, actual))
  49. # To make the pytest -v diff a bit prettier, stop pytest to rewrite assert
  50. # statements by executing the comparison earlier.
  51. _bool = desired == actual
  52. assert _bool, '\n' + diff