Skip to content

Instantly share code, notes, and snippets.

@ryanking
Created September 29, 2021 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanking/cb868651fecf40177209bff57c8f0ac3 to your computer and use it in GitHub Desktop.
Save ryanking/cb868651fecf40177209bff57c8f0ac3 to your computer and use it in GitHub Desktop.
pytest honeycomb tracing
import os
import libhoney
# If buildevents is configured, set up a libhoney client to send spans for each test
writekey = os.environ.get('BUILDEVENT_APIKEY')
if writekey:
libhoney.init(writekey=writekey, dataset="buildevents", debug=True)
libhoney.add_field("service_name", "pytest")
libhoney.add_field("trace.trace_id", os.environ.get("CIRCLE_WORKFLOW_ID"))
libhoney.add_field("trace.parent_id", os.environ.get("BUILDEVENTS_SPAN_ID"))
# https://github.com/honeycombio/buildevents/blob/7df16efbc3ce62932d2e4821c88c6888a2fdcc6d/common.go#L49
libhoney.add_field("branch", os.environ.get("CIRCLE_BRANCH"))
libhoney.add_field("build_num", os.environ.get("CIRCLE_BUILD_NUM"))
libhoney.add_field("build_url", os.environ.get("CIRCLE_BUILD_URL"))
libhoney.add_field("job_name", os.environ.get("CIRCLE_JOB"))
libhoney.add_field("repo", os.environ.get("CIRCLE_REPOSITORY_URL"))
# unused? maybe only for PRs and we don't have data for that yet?
# pr_repo = CIRCLE_PR_REPONAME
# pr_user = CIRCLE_PR_USER
# pr_number = CIRCLE_PR_NUMBER
import time
import libhoney
import pytest
RUNNING_TIMES = {}
def pytest_runtest_logstart(nodeid, location):
RUNNING_TIMES[location] = time.perf_counter()
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
result = outcome.get_result()
if result.when == 'teardown':
now = time.perf_counter()
then = RUNNING_TIMES[item.location]
delta = int((now - then) * 1000)
(filename, line, name) = item.location
ev = libhoney.new_event()
ev.add(
{
"filename": filename,
"line": line,
"name": name,
"outcom": result.outcome,
"duration_ms": delta,
}
)
ev.send()
def pytest_sessionfinish(session, exitstatus):
libhoney.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment