mock_drt.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. # Copyright (c) 2012 Google Inc. All rights reserved.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions are
  5. # met:
  6. #
  7. # * Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. # * Redistributions in binary form must reproduce the above
  10. # copyright notice, this list of conditions and the following disclaimer
  11. # in the documentation and/or other materials provided with the
  12. # distribution.
  13. # * Neither the Google name nor the names of its
  14. # contributors may be used to endorse or promote products derived from
  15. # this software without specific prior written permission.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  20. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  22. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  23. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. """
  29. This is an implementation of the Port interface that overrides other
  30. ports and changes the Driver binary to "MockDRT".
  31. The MockDRT objects emulate what a real DRT would do. In particular, they
  32. return the output a real DRT would return for a given test, assuming that
  33. test actually passes (except for reftests, which currently cause the
  34. MockDRT to crash).
  35. """
  36. import base64
  37. import logging
  38. import optparse
  39. import os
  40. import sys
  41. # Since we execute this script directly as part of the unit tests, we need to ensure
  42. # that Tools/Scripts is in sys.path for the next imports to work correctly.
  43. script_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
  44. if script_dir not in sys.path:
  45. sys.path.append(script_dir)
  46. from webkitpy.common.system.systemhost import SystemHost
  47. from webkitpy.port.driver import DriverInput, DriverOutput, DriverProxy
  48. from webkitpy.port.factory import PortFactory
  49. _log = logging.getLogger(__name__)
  50. class MockDRTPort(object):
  51. port_name = 'mock'
  52. @classmethod
  53. def determine_full_port_name(cls, host, options, port_name):
  54. return port_name
  55. def __init__(self, host, port_name, **kwargs):
  56. self.__delegate = PortFactory(host).get(port_name.replace('mock-', ''), **kwargs)
  57. def __getattr__(self, name):
  58. return getattr(self.__delegate, name)
  59. def check_build(self, needs_http):
  60. return True
  61. def check_sys_deps(self, needs_http):
  62. return True
  63. def create_driver(self, worker_number, no_timeout=False):
  64. # The magic of the MockDRTPort is that we create a driver that has a
  65. # cmd_line() method monkey-patched to invoke this script instead of DRT.
  66. return DriverProxy(self, worker_number, self._mocked_driver_maker, pixel_tests=self.get_option('pixel_tests'), no_timeout=no_timeout)
  67. @staticmethod
  68. def _mocked_driver_maker(port, worker_number, pixel_tests, no_timeout=False):
  69. path_to_this_file = port.host.filesystem.abspath(__file__.replace('.pyc', '.py'))
  70. driver = port.__delegate._driver_class()(port, worker_number, pixel_tests, no_timeout)
  71. driver.cmd_line = port._overriding_cmd_line(driver.cmd_line,
  72. port.__delegate._path_to_driver(),
  73. sys.executable,
  74. path_to_this_file,
  75. port.__delegate.name())
  76. return driver
  77. @staticmethod
  78. def _overriding_cmd_line(original_cmd_line, driver_path, python_exe, this_file, port_name):
  79. def new_cmd_line(pixel_tests, per_test_args):
  80. cmd_line = original_cmd_line(pixel_tests, per_test_args)
  81. index = cmd_line.index(driver_path)
  82. cmd_line[index:index + 1] = [python_exe, this_file, '--platform', port_name]
  83. return cmd_line
  84. return new_cmd_line
  85. def start_helper(self):
  86. pass
  87. def start_http_server(self, number_of_servers):
  88. pass
  89. def start_websocket_server(self):
  90. pass
  91. def acquire_http_lock(self):
  92. pass
  93. def stop_helper(self):
  94. pass
  95. def stop_http_server(self):
  96. pass
  97. def stop_websocket_server(self):
  98. pass
  99. def release_http_lock(self):
  100. pass
  101. def show_results_html_file(self, results_filename):
  102. pass
  103. def main(argv, host, stdin, stdout, stderr):
  104. """Run the tests."""
  105. options, args = parse_options(argv)
  106. if options.test_shell:
  107. drt = MockTestShell(options, args, host, stdin, stdout, stderr)
  108. else:
  109. drt = MockDRT(options, args, host, stdin, stdout, stderr)
  110. return drt.run()
  111. def parse_options(argv):
  112. # FIXME: We have to do custom arg parsing instead of using the optparse
  113. # module. First, Chromium and non-Chromium DRTs have a different argument
  114. # syntax. Chromium uses --pixel-tests=<path>, and non-Chromium uses
  115. # --pixel-tests as a boolean flag. Second, we don't want to have to list
  116. # every command line flag DRT accepts, but optparse complains about
  117. # unrecognized flags. At some point it might be good to share a common
  118. # DRT options class between this file and webkit.py and chromium.py
  119. # just to get better type checking.
  120. platform_index = argv.index('--platform')
  121. platform = argv[platform_index + 1]
  122. pixel_tests = False
  123. pixel_path = None
  124. test_shell = '--test-shell' in argv
  125. if test_shell:
  126. for arg in argv:
  127. if arg.startswith('--pixel-tests'):
  128. pixel_tests = True
  129. pixel_path = arg[len('--pixel-tests='):]
  130. else:
  131. pixel_tests = '--pixel-tests' in argv
  132. options = optparse.Values({'test_shell': test_shell, 'platform': platform, 'pixel_tests': pixel_tests, 'pixel_path': pixel_path})
  133. return (options, argv)
  134. class MockDRT(object):
  135. def __init__(self, options, args, host, stdin, stdout, stderr):
  136. self._options = options
  137. self._args = args
  138. self._host = host
  139. self._stdout = stdout
  140. self._stdin = stdin
  141. self._stderr = stderr
  142. port_name = None
  143. if options.platform:
  144. port_name = options.platform
  145. self._port = PortFactory(host).get(port_name=port_name, options=options)
  146. self._driver = self._port.create_driver(0)
  147. def run(self):
  148. while True:
  149. line = self._stdin.readline()
  150. if not line:
  151. return 0
  152. driver_input = self.input_from_line(line)
  153. dirname, basename = self._port.split_test(driver_input.test_name)
  154. is_reftest = (self._port.reference_files(driver_input.test_name) or
  155. self._port.is_reference_html_file(self._port._filesystem, dirname, basename))
  156. output = self.output_for_test(driver_input, is_reftest)
  157. self.write_test_output(driver_input, output, is_reftest)
  158. def input_from_line(self, line):
  159. vals = line.strip().split("'")
  160. if len(vals) == 1:
  161. uri = vals[0]
  162. checksum = None
  163. else:
  164. uri = vals[0]
  165. checksum = vals[1]
  166. if uri.startswith('http://') or uri.startswith('https://'):
  167. test_name = self._driver.uri_to_test(uri)
  168. else:
  169. test_name = self._port.relative_test_filename(uri)
  170. return DriverInput(test_name, 0, checksum, self._options.pixel_tests)
  171. def output_for_test(self, test_input, is_reftest):
  172. port = self._port
  173. actual_text = port.expected_text(test_input.test_name)
  174. actual_audio = port.expected_audio(test_input.test_name)
  175. actual_image = None
  176. actual_checksum = None
  177. if is_reftest:
  178. # Make up some output for reftests.
  179. actual_text = 'reference text\n'
  180. actual_checksum = 'mock-checksum'
  181. actual_image = 'blank'
  182. if test_input.test_name.endswith('-mismatch.html'):
  183. actual_text = 'not reference text\n'
  184. actual_checksum = 'not-mock-checksum'
  185. actual_image = 'not blank'
  186. elif self._options.pixel_tests and test_input.image_hash:
  187. actual_checksum = port.expected_checksum(test_input.test_name)
  188. actual_image = port.expected_image(test_input.test_name)
  189. return DriverOutput(actual_text, actual_image, actual_checksum, actual_audio)
  190. def write_test_output(self, test_input, output, is_reftest):
  191. if output.audio:
  192. self._stdout.write('Content-Type: audio/wav\n')
  193. self._stdout.write('Content-Transfer-Encoding: base64\n')
  194. self._stdout.write(base64.b64encode(output.audio))
  195. else:
  196. self._stdout.write('Content-Type: text/plain\n')
  197. # FIXME: Note that we don't ensure there is a trailing newline!
  198. # This mirrors actual (Mac) DRT behavior but is a bug.
  199. if output.text:
  200. self._stdout.write(output.text)
  201. self._stdout.write('#EOF\n')
  202. if self._options.pixel_tests and output.image_hash:
  203. self._stdout.write('\n')
  204. self._stdout.write('ActualHash: %s\n' % output.image_hash)
  205. self._stdout.write('ExpectedHash: %s\n' % test_input.image_hash)
  206. if output.image_hash != test_input.image_hash:
  207. self._stdout.write('Content-Type: image/png\n')
  208. self._stdout.write('Content-Length: %s\n' % len(output.image))
  209. self._stdout.write(output.image)
  210. self._stdout.write('#EOF\n')
  211. self._stdout.flush()
  212. self._stderr.write('#EOF\n')
  213. self._stderr.flush()
  214. class MockTestShell(MockDRT):
  215. def input_from_line(self, line):
  216. vals = line.strip().split()
  217. if len(vals) == 3:
  218. uri, timeout, checksum = vals
  219. else:
  220. uri, timeout = vals
  221. checksum = None
  222. test_name = self._driver.uri_to_test(uri)
  223. return DriverInput(test_name, timeout, checksum, self._options.pixel_tests)
  224. def output_for_test(self, test_input, is_reftest):
  225. # FIXME: This is a hack to make virtual tests work. Need something more general.
  226. original_test_name = test_input.test_name
  227. if '--enable-accelerated-2d-canvas' in self._args and 'canvas' in test_input.test_name:
  228. test_input.test_name = 'platform/chromium/virtual/gpu/' + test_input.test_name
  229. output = super(MockTestShell, self).output_for_test(test_input, is_reftest)
  230. test_input.test_name = original_test_name
  231. return output
  232. def write_test_output(self, test_input, output, is_reftest):
  233. self._stdout.write("#URL:%s\n" % self._driver.test_to_uri(test_input.test_name))
  234. if self._options.pixel_tests and output.image_hash:
  235. self._stdout.write("#MD5:%s\n" % output.image_hash)
  236. if output.image:
  237. self._host.filesystem.maybe_make_directory(self._host.filesystem.dirname(self._options.pixel_path))
  238. self._host.filesystem.write_binary_file(self._options.pixel_path, output.image)
  239. if output.text:
  240. self._stdout.write(output.text)
  241. if output.text and not output.text.endswith('\n'):
  242. self._stdout.write('\n')
  243. self._stdout.write('#EOF\n')
  244. self._stdout.flush()
  245. if __name__ == '__main__':
  246. # Note that the Mock in MockDRT refers to the fact that it is emulating a
  247. # real DRT, and as such, it needs access to a real SystemHost, not a MockSystemHost.
  248. sys.exit(main(sys.argv[1:], SystemHost(), sys.stdin, sys.stdout, sys.stderr))