Saagar Sanghavi | 9949ab7 | 2020-07-20 20:56:40 +0000 | [diff] [blame] | 1 | #!/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 | |
| 6 | import contextlib |
| 7 | import json |
| 8 | import os |
| 9 | import requests |
| 10 | import time |
| 11 | |
| 12 | # Constants describing TestStatus for ResultDB |
| 13 | STATUS_PASS = 'PASS' |
| 14 | STATUS_FAIL = 'FAIL' |
| 15 | STATUS_CRASH = 'CRASH' |
| 16 | STATUS_ABORT = 'ABORT' |
| 17 | STATUS_SKIP = 'SKIP' |
| 18 | |
| 19 | class ResultSinkStatus(object): |
| 20 | def __init__(self): |
| 21 | self.status = STATUS_PASS |
| 22 | |
| 23 | @contextlib.contextmanager |
| 24 | def 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 | ) |