blob: e075c8983d4fe9df21f95945929e796b1b6527aa [file] [log] [blame]
Saagar Sanghavi9949ab72020-07-20 20:56:40 +00001#!/usr/bin/env vpython
2# Copyright (c) 2020 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6import contextlib
7import json
8import os
9import requests
10import time
11
12# Constants describing TestStatus for ResultDB
13STATUS_PASS = 'PASS'
14STATUS_FAIL = 'FAIL'
15STATUS_CRASH = 'CRASH'
16STATUS_ABORT = 'ABORT'
17STATUS_SKIP = 'SKIP'
18
19class ResultSinkStatus(object):
20 def __init__(self):
21 self.status = STATUS_PASS
22
23@contextlib.contextmanager
Saagar Sanghavi531d9922020-08-10 20:14:01 +000024def setup_rdb(function_name, prefix):
Saagar Sanghavi9949ab72020-07-20 20:56:40 +000025 """Context Manager function for ResultDB reporting.
26
27 Args:
28 function_name (str): The name of the function we are about to run.
Saagar Sanghavi531d9922020-08-10 20:14:01 +000029 prefix (str): The prefix for the name of the test. The format for this is
30 presubmit:gerrit_host/folder/to/repo:path/to/file/
31 for example,
32 presubmit:chromium-review.googlesource.com/chromium/src/:services/viz/
Saagar Sanghavi9949ab72020-07-20 20:56:40 +000033 """
34 sink = None
35 if 'LUCI_CONTEXT' in os.environ:
36 with open(os.environ['LUCI_CONTEXT']) as f:
37 j = json.load(f)
38 if 'result_sink' in j:
39 sink = j['result_sink']
40
41 my_status = ResultSinkStatus()
42 start_time = time.time()
43 try:
44 yield my_status
45 except Exception:
46 my_status.status = STATUS_FAIL
47 raise
48 finally:
49 end_time = time.time()
50 elapsed_time = end_time - start_time
51 if sink != None:
52 tr = {
Saagar Sanghavi531d9922020-08-10 20:14:01 +000053 'testId': '{0}:{1}'.format(prefix, function_name),
Saagar Sanghavi9949ab72020-07-20 20:56:40 +000054 'status': my_status.status,
55 'expected': (my_status.status == STATUS_PASS),
56 'duration': '{:.9f}s'.format(elapsed_time)
57 }
58 requests.post(
59 url='http://{0}/prpc/luci.resultsink.v1.Sink/ReportTestResults'
60 .format(sink['address']),
61 headers={
62 'Content-Type': 'application/json',
63 'Accept': 'application/json',
64 'Authorization': 'ResultSink {0}'.format(sink['auth_token'])
65 },
66 data=json.dumps({'testResults': [tr]})
67 )