PRESUBMIT_test_mocks.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. # Copyright 2014 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 os
  8. import re
  9. import subprocess
  10. import sys
  11. # TODO(dcheng): It's kind of horrible that this is copy and pasted from
  12. # presubmit_canned_checks.py, but it's far easier than any of the alternatives.
  13. def _ReportErrorFileAndLine(filename, line_num, dummy_line):
  14. """Default error formatter for _FindNewViolationsOfRule."""
  15. return '%s:%s' % (filename, line_num)
  16. class MockCannedChecks(object):
  17. def _FindNewViolationsOfRule(self, callable_rule, input_api,
  18. source_file_filter=None,
  19. error_formatter=_ReportErrorFileAndLine):
  20. """Find all newly introduced violations of a per-line rule (a callable).
  21. Arguments:
  22. callable_rule: a callable taking a file extension and line of input and
  23. returning True if the rule is satisfied and False if there was a
  24. problem.
  25. input_api: object to enumerate the affected files.
  26. source_file_filter: a filter to be passed to the input api.
  27. error_formatter: a callable taking (filename, line_number, line) and
  28. returning a formatted error string.
  29. Returns:
  30. A list of the newly-introduced violations reported by the rule.
  31. """
  32. errors = []
  33. for f in input_api.AffectedFiles(include_deletes=False,
  34. file_filter=source_file_filter):
  35. # For speed, we do two passes, checking first the full file. Shelling out
  36. # to the SCM to determine the changed region can be quite expensive on
  37. # Win32. Assuming that most files will be kept problem-free, we can
  38. # skip the SCM operations most of the time.
  39. extension = str(f.LocalPath()).rsplit('.', 1)[-1]
  40. if all(callable_rule(extension, line) for line in f.NewContents()):
  41. continue # No violation found in full text: can skip considering diff.
  42. for line_num, line in f.ChangedContents():
  43. if not callable_rule(extension, line):
  44. errors.append(error_formatter(f.LocalPath(), line_num, line))
  45. return errors
  46. class MockInputApi(object):
  47. """Mock class for the InputApi class.
  48. This class can be used for unittests for presubmit by initializing the files
  49. attribute as the list of changed files.
  50. """
  51. DEFAULT_FILES_TO_SKIP = ()
  52. def __init__(self):
  53. self.canned_checks = MockCannedChecks()
  54. self.fnmatch = fnmatch
  55. self.json = json
  56. self.re = re
  57. self.os_path = os.path
  58. self.platform = sys.platform
  59. self.python_executable = sys.executable
  60. self.python3_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.change = MockChange([])
  67. self.presubmit_local_path = os.path.dirname(__file__)
  68. self.is_windows = sys.platform == 'win32'
  69. self.no_diffs = False
  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:
  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 RightHandSideLines(self, source_file_filter=None):
  80. affected_files = self.AffectedSourceFiles(source_file_filter)
  81. for af in affected_files:
  82. lines = af.ChangedContents()
  83. for line in lines:
  84. yield (af, line[0], line[1])
  85. def AffectedSourceFiles(self, file_filter=None):
  86. return self.AffectedFiles(file_filter=file_filter)
  87. def FilterSourceFile(self, file,
  88. files_to_check=(), files_to_skip=()):
  89. local_path = file.LocalPath()
  90. found_in_files_to_check = not files_to_check
  91. if files_to_check:
  92. if type(files_to_check) is str:
  93. raise TypeError('files_to_check should be an iterable of strings')
  94. for pattern in files_to_check:
  95. compiled_pattern = re.compile(pattern)
  96. if compiled_pattern.match(local_path):
  97. found_in_files_to_check = True
  98. break
  99. if files_to_skip:
  100. if type(files_to_skip) is str:
  101. raise TypeError('files_to_skip should be an iterable of strings')
  102. for pattern in files_to_skip:
  103. compiled_pattern = re.compile(pattern)
  104. if compiled_pattern.match(local_path):
  105. return False
  106. return found_in_files_to_check
  107. def LocalPaths(self):
  108. return [file.LocalPath() for file in self.files]
  109. def PresubmitLocalPath(self):
  110. return self.presubmit_local_path
  111. def ReadFile(self, filename, mode='rU'):
  112. if hasattr(filename, 'AbsoluteLocalPath'):
  113. filename = filename.AbsoluteLocalPath()
  114. for file_ in self.files:
  115. if file_.LocalPath() == filename:
  116. return '\n'.join(file_.NewContents())
  117. # Otherwise, file is not in our mock API.
  118. raise IOError("No such file or directory: '%s'" % filename)
  119. class MockOutputApi(object):
  120. """Mock class for the OutputApi class.
  121. An instance of this class can be passed to presubmit unittests for outputting
  122. various types of results.
  123. """
  124. class PresubmitResult(object):
  125. def __init__(self, message, items=None, long_text=''):
  126. self.message = message
  127. self.items = items
  128. self.long_text = long_text
  129. def __repr__(self):
  130. return self.message
  131. class PresubmitError(PresubmitResult):
  132. def __init__(self, message, items=None, long_text=''):
  133. MockOutputApi.PresubmitResult.__init__(self, message, items, 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, long_text)
  138. self.type = 'warning'
  139. class PresubmitNotifyResult(PresubmitResult):
  140. def __init__(self, message, items=None, long_text=''):
  141. MockOutputApi.PresubmitResult.__init__(self, message, items, long_text)
  142. self.type = 'notify'
  143. class PresubmitPromptOrNotify(PresubmitResult):
  144. def __init__(self, message, items=None, long_text=''):
  145. MockOutputApi.PresubmitResult.__init__(self, message, items, long_text)
  146. self.type = 'promptOrNotify'
  147. def __init__(self):
  148. self.more_cc = []
  149. def AppendCC(self, more_cc):
  150. self.more_cc.append(more_cc)
  151. class MockFile(object):
  152. """Mock class for the File class.
  153. This class can be used to form the mock list of changed files in
  154. MockInputApi for presubmit unittests.
  155. """
  156. def __init__(self, local_path, new_contents, old_contents=None, action='A',
  157. scm_diff=None):
  158. self._local_path = local_path
  159. self._new_contents = new_contents
  160. self._changed_contents = [(i + 1, l) for i, l in enumerate(new_contents)]
  161. self._action = action
  162. if scm_diff:
  163. self._scm_diff = scm_diff
  164. else:
  165. self._scm_diff = (
  166. "--- /dev/null\n+++ %s\n@@ -0,0 +1,%d @@\n" %
  167. (local_path, len(new_contents)))
  168. for l in new_contents:
  169. self._scm_diff += "+%s\n" % l
  170. self._old_contents = old_contents
  171. def Action(self):
  172. return self._action
  173. def ChangedContents(self):
  174. return self._changed_contents
  175. def NewContents(self):
  176. return self._new_contents
  177. def LocalPath(self):
  178. return self._local_path
  179. def AbsoluteLocalPath(self):
  180. return self._local_path
  181. def GenerateScmDiff(self):
  182. return self._scm_diff
  183. def OldContents(self):
  184. return self._old_contents
  185. def rfind(self, p):
  186. """os.path.basename is called on MockFile so we need an rfind method."""
  187. return self._local_path.rfind(p)
  188. def __getitem__(self, i):
  189. """os.path.basename is called on MockFile so we need a get method."""
  190. return self._local_path[i]
  191. def __len__(self):
  192. """os.path.basename is called on MockFile so we need a len method."""
  193. return len(self._local_path)
  194. def replace(self, altsep, sep):
  195. """os.path.basename is called on MockFile so we need a replace method."""
  196. return self._local_path.replace(altsep, sep)
  197. class MockAffectedFile(MockFile):
  198. def AbsoluteLocalPath(self):
  199. return self._local_path
  200. class MockChange(object):
  201. """Mock class for Change class.
  202. This class can be used in presubmit unittests to mock the query of the
  203. current change.
  204. """
  205. def __init__(self, changed_files):
  206. self._changed_files = changed_files
  207. self.author_email = None
  208. self.footers = defaultdict(list)
  209. def LocalPaths(self):
  210. return self._changed_files
  211. def AffectedFiles(self, include_dirs=False, include_deletes=True,
  212. file_filter=None):
  213. return self._changed_files
  214. def GitFootersFromDescription(self):
  215. return self.footers