presubmit_canned_checks_test_mocks.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. # Copyright 2021 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. from collections import defaultdict
  5. import fnmatch
  6. import json
  7. import logging
  8. import os
  9. import re
  10. import subprocess
  11. import sys
  12. from presubmit_canned_checks import _ReportErrorFileAndLine
  13. class MockCannedChecks(object):
  14. def _FindNewViolationsOfRule(self,
  15. callable_rule,
  16. input_api,
  17. source_file_filter=None,
  18. error_formatter=_ReportErrorFileAndLine):
  19. """Find all newly introduced violations of a per-line rule (a callable).
  20. Arguments:
  21. callable_rule: a callable taking a file extension and line of input
  22. and returning True if the rule is satisfied and False if there
  23. was a problem.
  24. input_api: object to enumerate the affected files.
  25. source_file_filter: a filter to be passed to the input api.
  26. error_formatter: a callable taking (filename, line_number, line)
  27. and returning a formatted error string.
  28. Returns:
  29. A list of the newly-introduced violations reported by the rule.
  30. """
  31. errors = []
  32. for f in input_api.AffectedFiles(include_deletes=False,
  33. file_filter=source_file_filter):
  34. # For speed, we do two passes, checking first the full file.
  35. # Shelling out to the SCM to determine the changed region can be
  36. # quite expensive on Win32. Assuming that most files will be kept
  37. # problem-free, we can skip the SCM operations most of the time.
  38. extension = str(f.LocalPath()).rsplit('.', 1)[-1]
  39. if all(callable_rule(extension, line) for line in f.NewContents()):
  40. # No violation found in full text: can skip considering diff.
  41. continue
  42. for line_num, line in f.ChangedContents():
  43. if not callable_rule(extension, line):
  44. errors.append(error_formatter(f.LocalPath(), line_num,
  45. line))
  46. return errors
  47. class MockInputApi(object):
  48. """Mock class for the InputApi class.
  49. This class can be used for unittests for presubmit by initializing the files
  50. attribute as the list of changed files.
  51. """
  52. DEFAULT_FILES_TO_SKIP = ()
  53. def __init__(self):
  54. self.canned_checks = MockCannedChecks()
  55. self.fnmatch = fnmatch
  56. self.json = json
  57. self.re = re
  58. self.os_path = os.path
  59. self.platform = sys.platform
  60. self.python_executable = sys.executable
  61. self.platform = sys.platform
  62. self.subprocess = subprocess
  63. self.sys = sys
  64. self.files = []
  65. self.is_committing = False
  66. self.no_diffs = False
  67. self.change = MockChange([])
  68. self.presubmit_local_path = os.path.dirname(__file__)
  69. self.logging = logging.getLogger('PRESUBMIT')
  70. def CreateMockFileInPath(self, f_list):
  71. self.os_path.exists = lambda x: x in f_list
  72. def AffectedFiles(self, file_filter=None, include_deletes=True):
  73. for file in self.files: # pylint: disable=redefined-builtin
  74. if file_filter and not file_filter(file):
  75. continue
  76. if not include_deletes and file.Action() == 'D':
  77. continue
  78. yield file
  79. def AffectedSourceFiles(self, file_filter=None):
  80. return self.AffectedFiles(file_filter=file_filter)
  81. def FilterSourceFile(
  82. self,
  83. file, # pylint: disable=redefined-builtin
  84. files_to_check=(),
  85. files_to_skip=()):
  86. local_path = file.LocalPath()
  87. found_in_files_to_check = not files_to_check
  88. if files_to_check:
  89. if isinstance(files_to_check, str):
  90. raise TypeError(
  91. 'files_to_check should be an iterable of strings')
  92. for pattern in files_to_check:
  93. compiled_pattern = re.compile(pattern)
  94. if compiled_pattern.search(local_path):
  95. found_in_files_to_check = True
  96. break
  97. if files_to_skip:
  98. if isinstance(files_to_skip, str):
  99. raise TypeError(
  100. 'files_to_skip should be an iterable of strings')
  101. for pattern in files_to_skip:
  102. compiled_pattern = re.compile(pattern)
  103. if compiled_pattern.search(local_path):
  104. return False
  105. return found_in_files_to_check
  106. def LocalPaths(self):
  107. return [file.LocalPath() for file in self.files] # pylint: disable=redefined-builtin
  108. def PresubmitLocalPath(self):
  109. return self.presubmit_local_path
  110. def ReadFile(self, filename, mode='rU'):
  111. if hasattr(filename, 'AbsoluteLocalPath'):
  112. filename = filename.AbsoluteLocalPath()
  113. for file_ in self.files:
  114. if file_.LocalPath() == filename:
  115. return '\n'.join(file_.NewContents())
  116. # Otherwise, file is not in our mock API.
  117. raise IOError("No such file or directory: '%s'" % filename)
  118. class MockOutputApi(object):
  119. """Mock class for the OutputApi class.
  120. An instance of this class can be passed to presubmit unittests for outputing
  121. various types of results.
  122. """
  123. class PresubmitResult(object):
  124. def __init__(self, message, items=None, long_text=''):
  125. self.message = message
  126. self.items = items
  127. self.long_text = long_text
  128. def __repr__(self):
  129. return self.message
  130. class PresubmitError(PresubmitResult):
  131. def __init__(self, message, items=None, long_text=''):
  132. MockOutputApi.PresubmitResult.__init__(self, message, items,
  133. long_text)
  134. self.type = 'error'
  135. class PresubmitPromptWarning(PresubmitResult):
  136. def __init__(self, message, items=None, long_text=''):
  137. MockOutputApi.PresubmitResult.__init__(self, message, items,
  138. long_text)
  139. self.type = 'warning'
  140. class PresubmitNotifyResult(PresubmitResult):
  141. def __init__(self, message, items=None, long_text=''):
  142. MockOutputApi.PresubmitResult.__init__(self, message, items,
  143. long_text)
  144. self.type = 'notify'
  145. class PresubmitPromptOrNotify(PresubmitResult):
  146. def __init__(self, message, items=None, long_text=''):
  147. MockOutputApi.PresubmitResult.__init__(self, message, items,
  148. long_text)
  149. self.type = 'promptOrNotify'
  150. def __init__(self):
  151. self.more_cc = []
  152. def AppendCC(self, more_cc):
  153. self.more_cc.extend(more_cc)
  154. class MockFile(object):
  155. """Mock class for the File class.
  156. This class can be used to form the mock list of changed files in
  157. MockInputApi for presubmit unittests.
  158. """
  159. def __init__(self,
  160. local_path,
  161. new_contents,
  162. old_contents=None,
  163. action='A',
  164. scm_diff=None):
  165. self._local_path = local_path
  166. self._new_contents = new_contents
  167. self._changed_contents = [(i + 1, l)
  168. for i, l in enumerate(new_contents)]
  169. self._action = action
  170. if scm_diff:
  171. self._scm_diff = scm_diff
  172. else:
  173. self._scm_diff = ("--- /dev/null\n+++ %s\n@@ -0,0 +1,%d @@\n" %
  174. (local_path, len(new_contents)))
  175. for l in new_contents:
  176. self._scm_diff += "+%s\n" % l
  177. self._old_contents = old_contents
  178. def Action(self):
  179. return self._action
  180. def ChangedContents(self):
  181. return self._changed_contents
  182. def NewContents(self):
  183. return self._new_contents
  184. def LocalPath(self):
  185. return self._local_path
  186. def AbsoluteLocalPath(self):
  187. return self._local_path
  188. def GenerateScmDiff(self):
  189. return self._scm_diff
  190. def OldContents(self):
  191. return self._old_contents
  192. def rfind(self, p):
  193. """os.path.basename is used on MockFile so we need an rfind method."""
  194. return self._local_path.rfind(p)
  195. def __getitem__(self, i):
  196. """os.path.basename is used on MockFile so we need a get method."""
  197. return self._local_path[i]
  198. def __len__(self):
  199. """os.path.basename is used on MockFile so we need a len method."""
  200. return len(self._local_path)
  201. def replace(self, altsep, sep):
  202. """os.path.basename is used on MockFile so we need a replace method."""
  203. return self._local_path.replace(altsep, sep)
  204. class MockAffectedFile(MockFile):
  205. def AbsoluteLocalPath(self):
  206. return self._local_path
  207. class MockChange(object):
  208. """Mock class for Change class.
  209. This class can be used in presubmit unittests to mock the query of the
  210. current change.
  211. """
  212. def __init__(self, changed_files, description='', issue=0):
  213. self._changed_files = changed_files
  214. self.footers = defaultdict(list)
  215. self._description = description
  216. self.issue = issue
  217. def LocalPaths(self):
  218. return self._changed_files
  219. def AffectedFiles(self,
  220. include_dirs=False,
  221. include_deletes=True,
  222. file_filter=None):
  223. return self._changed_files
  224. def GitFootersFromDescription(self):
  225. return self.footers
  226. def DescriptionText(self):
  227. return self._description