PRESUBMIT_test_mocks.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. def CreateMockFileInPath(self, f_list):
  70. self.os_path.exists = lambda x: x in f_list
  71. def AffectedFiles(self, file_filter=None, include_deletes=True):
  72. for file in self.files:
  73. if file_filter and not file_filter(file):
  74. continue
  75. if not include_deletes and file.Action() == 'D':
  76. continue
  77. yield file
  78. def RightHandSideLines(self, source_file_filter=None):
  79. affected_files = self.AffectedSourceFiles(source_file_filter)
  80. for af in affected_files:
  81. lines = af.ChangedContents()
  82. for line in lines:
  83. yield (af, line[0], line[1])
  84. def AffectedSourceFiles(self, file_filter=None):
  85. return self.AffectedFiles(file_filter=file_filter)
  86. def FilterSourceFile(self, file,
  87. files_to_check=(), files_to_skip=()):
  88. local_path = file.LocalPath()
  89. found_in_files_to_check = not files_to_check
  90. if files_to_check:
  91. if type(files_to_check) is str:
  92. raise TypeError('files_to_check should be an iterable of strings')
  93. for pattern in files_to_check:
  94. compiled_pattern = re.compile(pattern)
  95. if compiled_pattern.match(local_path):
  96. found_in_files_to_check = True
  97. break
  98. if files_to_skip:
  99. if type(files_to_skip) is str:
  100. raise TypeError('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.match(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]
  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, long_text)
  133. self.type = 'error'
  134. class PresubmitPromptWarning(PresubmitResult):
  135. def __init__(self, message, items=None, long_text=''):
  136. MockOutputApi.PresubmitResult.__init__(self, message, items, long_text)
  137. self.type = 'warning'
  138. class PresubmitNotifyResult(PresubmitResult):
  139. def __init__(self, message, items=None, long_text=''):
  140. MockOutputApi.PresubmitResult.__init__(self, message, items, long_text)
  141. self.type = 'notify'
  142. class PresubmitPromptOrNotify(PresubmitResult):
  143. def __init__(self, message, items=None, long_text=''):
  144. MockOutputApi.PresubmitResult.__init__(self, message, items, long_text)
  145. self.type = 'promptOrNotify'
  146. def __init__(self):
  147. self.more_cc = []
  148. def AppendCC(self, more_cc):
  149. self.more_cc.append(more_cc)
  150. class MockFile(object):
  151. """Mock class for the File class.
  152. This class can be used to form the mock list of changed files in
  153. MockInputApi for presubmit unittests.
  154. """
  155. def __init__(self, local_path, new_contents, old_contents=None, action='A',
  156. scm_diff=None):
  157. self._local_path = local_path
  158. self._new_contents = new_contents
  159. self._changed_contents = [(i + 1, l) for i, l in enumerate(new_contents)]
  160. self._action = action
  161. if scm_diff:
  162. self._scm_diff = scm_diff
  163. else:
  164. self._scm_diff = (
  165. "--- /dev/null\n+++ %s\n@@ -0,0 +1,%d @@\n" %
  166. (local_path, len(new_contents)))
  167. for l in new_contents:
  168. self._scm_diff += "+%s\n" % l
  169. self._old_contents = old_contents
  170. def Action(self):
  171. return self._action
  172. def ChangedContents(self):
  173. return self._changed_contents
  174. def NewContents(self):
  175. return self._new_contents
  176. def LocalPath(self):
  177. return self._local_path
  178. def AbsoluteLocalPath(self):
  179. return self._local_path
  180. def GenerateScmDiff(self):
  181. return self._scm_diff
  182. def OldContents(self):
  183. return self._old_contents
  184. def rfind(self, p):
  185. """os.path.basename is called on MockFile so we need an rfind method."""
  186. return self._local_path.rfind(p)
  187. def __getitem__(self, i):
  188. """os.path.basename is called on MockFile so we need a get method."""
  189. return self._local_path[i]
  190. def __len__(self):
  191. """os.path.basename is called on MockFile so we need a len method."""
  192. return len(self._local_path)
  193. def replace(self, altsep, sep):
  194. """os.path.basename is called on MockFile so we need a replace method."""
  195. return self._local_path.replace(altsep, sep)
  196. class MockAffectedFile(MockFile):
  197. def AbsoluteLocalPath(self):
  198. return self._local_path
  199. class MockChange(object):
  200. """Mock class for Change class.
  201. This class can be used in presubmit unittests to mock the query of the
  202. current change.
  203. """
  204. def __init__(self, changed_files):
  205. self._changed_files = changed_files
  206. self.footers = defaultdict(list)
  207. def LocalPaths(self):
  208. return self._changed_files
  209. def AffectedFiles(self, include_dirs=False, include_deletes=True,
  210. file_filter=None):
  211. return self._changed_files
  212. def GitFootersFromDescription(self):
  213. return self.footers