rdb_wrapper.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. import contextlib
  6. import json
  7. import os
  8. import requests
  9. import time
  10. # Constants describing TestStatus for ResultDB
  11. STATUS_PASS = 'PASS'
  12. STATUS_FAIL = 'FAIL'
  13. STATUS_CRASH = 'CRASH'
  14. STATUS_ABORT = 'ABORT'
  15. STATUS_SKIP = 'SKIP'
  16. class ResultSinkStatus(object):
  17. def __init__(self):
  18. self.status = STATUS_PASS
  19. @contextlib.contextmanager
  20. def setup_rdb(function_name, prefix):
  21. """Context Manager function for ResultDB reporting.
  22. Args:
  23. function_name (str): The name of the function we are about to run.
  24. prefix (str): The prefix for the name of the test. The format for this is
  25. presubmit:gerrit_host/folder/to/repo:path/to/file/
  26. for example,
  27. presubmit:chromium-review.googlesource.com/chromium/src/:services/viz/
  28. """
  29. sink = None
  30. if 'LUCI_CONTEXT' in os.environ:
  31. with open(os.environ['LUCI_CONTEXT']) as f:
  32. j = json.load(f)
  33. if 'result_sink' in j:
  34. sink = j['result_sink']
  35. my_status = ResultSinkStatus()
  36. start_time = time.time()
  37. try:
  38. yield my_status
  39. except Exception:
  40. my_status.status = STATUS_FAIL
  41. raise
  42. finally:
  43. end_time = time.time()
  44. elapsed_time = end_time - start_time
  45. if sink != None:
  46. tr = {
  47. 'testId': '{0}:{1}'.format(prefix, function_name),
  48. 'status': my_status.status,
  49. 'expected': (my_status.status == STATUS_PASS),
  50. 'duration': '{:.9f}s'.format(elapsed_time)
  51. }
  52. requests.post(
  53. url='http://{0}/prpc/luci.resultsink.v1.Sink/ReportTestResults'
  54. .format(sink['address']),
  55. headers={
  56. 'Content-Type': 'application/json',
  57. 'Accept': 'application/json',
  58. 'Authorization': 'ResultSink {0}'.format(sink['auth_token'])
  59. },
  60. data=json.dumps({'testResults': [tr]})
  61. )