blob: 302ec5e01d2a035422d8bcc63abe425a670758f1 [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
24def setup_rdb(function_name, rel_path):
25 """Context Manager function for ResultDB reporting.
26
27 Args:
28 function_name (str): The name of the function we are about to run.
29 rel_path (str): The relative path from the root of the repository to the
30 directory defining the check being executed.
31 """
32 sink = None
33 if 'LUCI_CONTEXT' in os.environ:
34 with open(os.environ['LUCI_CONTEXT']) as f:
35 j = json.load(f)
36 if 'result_sink' in j:
37 sink = j['result_sink']
38
39 my_status = ResultSinkStatus()
40 start_time = time.time()
41 try:
42 yield my_status
43 except Exception:
44 my_status.status = STATUS_FAIL
45 raise
46 finally:
47 end_time = time.time()
48 elapsed_time = end_time - start_time
49 if sink != None:
50 tr = {
51 'testId': '{0}/:{1}'.format(rel_path, function_name),
52 'status': my_status.status,
53 'expected': (my_status.status == STATUS_PASS),
54 'duration': '{:.9f}s'.format(elapsed_time)
55 }
56 requests.post(
57 url='http://{0}/prpc/luci.resultsink.v1.Sink/ReportTestResults'
58 .format(sink['address']),
59 headers={
60 'Content-Type': 'application/json',
61 'Accept': 'application/json',
62 'Authorization': 'ResultSink {0}'.format(sink['auth_token'])
63 },
64 data=json.dumps({'testResults': [tr]})
65 )