1# Copyright 2013 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
5"""Request Handler to allow test mask updates."""
6
7import webapp2
8import re
9import sys
10import os
11
12from common import constants
13from common import image_tools
14from common import ispy_utils
15
16import gs_bucket
17
18
19class UpdateMaskHandler(webapp2.RequestHandler):
20  """Request handler to allow test mask updates."""
21
22  def post(self):
23    """Accepts post requests.
24
25    This method will accept a post request containing device, site and
26    device_id parameters. This method takes the diff of the run
27    indicated by it's parameters and adds it to the mask of the run's
28    test. It will then delete the run it is applied to and redirect
29    to the device list view.
30    """
31    test_run = self.request.get('test_run')
32    expectation = self.request.get('expectation')
33
34    # Short-circuit if a parameter is missing.
35    if not (test_run and expectation):
36      self.response.headers['Content-Type'] = 'json/application'
37      self.response.write(json.dumps(
38          {'error': '\'test_run\' and \'expectation\' must be '
39                    'supplied to update a mask.'}))
40      return
41    # Otherwise, set up the utilities.
42    self.bucket = gs_bucket.GoogleCloudStorageBucket(constants.BUCKET)
43    self.ispy = ispy_utils.ISpyUtils(self.bucket)
44    # Short-circuit if the failure does not exist.
45    if not self.ispy.FailureExists(test_run, expectation):
46      self.response.headers['Content-Type'] = 'json/application'
47      self.response.write(json.dumps(
48        {'error': 'Could not update mask because failure does not exist.'}))
49      return
50    # Get the failure namedtuple (which also computes the diff).
51    failure = self.ispy.GetFailure(test_run, expectation)
52    # Upload the new mask in place of the original.
53    self.ispy.UpdateImage(
54        ispy_utils.GetExpectationPath(expectation, 'mask.png'),
55        image_tools.ConvertDiffToMask(failure.diff))
56    # Now that there is no diff for the two images, remove the failure.
57    self.ispy.RemoveFailure(test_run, expectation)
58    # Redirect back to the sites list for the test run.
59    self.redirect('/?test_run=%s' % test_run)
60