|
| 1 | +"""pytest-trackflaky plugin implementation.""" |
| 2 | + |
| 3 | +import pytest |
| 4 | +import subprocess |
| 5 | +from urllib import request |
| 6 | +import os |
| 7 | +import json |
| 8 | +from time import time |
| 9 | +import unittest |
| 10 | +import threading |
| 11 | + |
| 12 | + |
| 13 | +# Global state for run tracking |
| 14 | +_run_id = None |
| 15 | +_run_id_lock = threading.Lock() |
| 16 | + |
| 17 | + |
| 18 | +class SnowflakeGenerator: |
| 19 | + """ |
| 20 | + Generates Twitter-style Snowflake IDs. |
| 21 | +
|
| 22 | + Format (64 bits): |
| 23 | + - 41 bits: timestamp in milliseconds since custom epoch |
| 24 | + - 10 bits: worker/machine ID |
| 25 | + - 12 bits: sequence number |
| 26 | + """ |
| 27 | + |
| 28 | + # Custom epoch (2024-01-01 00:00:00 UTC in milliseconds) |
| 29 | + EPOCH = 1704067200000 |
| 30 | + |
| 31 | + # Bit allocation |
| 32 | + TIMESTAMP_BITS = 41 |
| 33 | + WORKER_BITS = 10 |
| 34 | + SEQUENCE_BITS = 12 |
| 35 | + |
| 36 | + # Max values |
| 37 | + MAX_WORKER_ID = (1 << WORKER_BITS) - 1 |
| 38 | + MAX_SEQUENCE = (1 << SEQUENCE_BITS) - 1 |
| 39 | + |
| 40 | + # Bit shifts |
| 41 | + TIMESTAMP_SHIFT = WORKER_BITS + SEQUENCE_BITS |
| 42 | + WORKER_SHIFT = SEQUENCE_BITS |
| 43 | + |
| 44 | + def __init__(self, worker_id=None): |
| 45 | + """Initialize the snowflake generator.""" |
| 46 | + if worker_id is None: |
| 47 | + # Try to get worker ID from environment or use process ID |
| 48 | + worker_id = os.getpid() & self.MAX_WORKER_ID |
| 49 | + |
| 50 | + if worker_id > self.MAX_WORKER_ID or worker_id < 0: |
| 51 | + raise ValueError(f"Worker ID must be between 0 and {self.MAX_WORKER_ID}") |
| 52 | + |
| 53 | + self.worker_id = worker_id |
| 54 | + self.sequence = 0 |
| 55 | + self.last_timestamp = -1 |
| 56 | + self.lock = threading.Lock() |
| 57 | + |
| 58 | + def _current_timestamp(self): |
| 59 | + """Get current timestamp in milliseconds since epoch.""" |
| 60 | + return int(time() * 1000) |
| 61 | + |
| 62 | + def generate(self): |
| 63 | + """Generate a new Snowflake ID.""" |
| 64 | + with self.lock: |
| 65 | + timestamp = self._current_timestamp() - self.EPOCH |
| 66 | + |
| 67 | + if timestamp < self.last_timestamp: |
| 68 | + raise Exception("Clock moved backwards. Refusing to generate ID.") |
| 69 | + |
| 70 | + if timestamp == self.last_timestamp: |
| 71 | + self.sequence = (self.sequence + 1) & self.MAX_SEQUENCE |
| 72 | + if self.sequence == 0: |
| 73 | + # Sequence exhausted, wait for next millisecond |
| 74 | + while timestamp <= self.last_timestamp: |
| 75 | + timestamp = self._current_timestamp() - self.EPOCH |
| 76 | + else: |
| 77 | + self.sequence = 0 |
| 78 | + |
| 79 | + self.last_timestamp = timestamp |
| 80 | + |
| 81 | + # Combine all parts |
| 82 | + snowflake_id = ( |
| 83 | + (timestamp << self.TIMESTAMP_SHIFT) | |
| 84 | + (self.worker_id << self.WORKER_SHIFT) | |
| 85 | + self.sequence |
| 86 | + ) |
| 87 | + |
| 88 | + return snowflake_id |
| 89 | + |
| 90 | + |
| 91 | +# Global snowflake generator |
| 92 | +_snowflake_gen = SnowflakeGenerator() |
| 93 | + |
| 94 | + |
| 95 | +def get_git_sha(): |
| 96 | + """Get the current git commit SHA.""" |
| 97 | + try: |
| 98 | + return subprocess.check_output(["git", "rev-parse", "HEAD"]).decode("ASCII").strip() |
| 99 | + except subprocess.CalledProcessError: |
| 100 | + return None |
| 101 | + |
| 102 | + |
| 103 | +def get_git_branch(): |
| 104 | + """Get the current git branch name.""" |
| 105 | + try: |
| 106 | + return ( |
| 107 | + subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]) |
| 108 | + .decode("ASCII") |
| 109 | + .strip() |
| 110 | + ) |
| 111 | + except subprocess.CalledProcessError: |
| 112 | + return None |
| 113 | + |
| 114 | + |
| 115 | +def get_run_id(): |
| 116 | + """Get or generate the run ID for this test session.""" |
| 117 | + global _run_id |
| 118 | + with _run_id_lock: |
| 119 | + if _run_id is None: |
| 120 | + _run_id = _snowflake_gen.generate() |
| 121 | + return _run_id |
| 122 | + |
| 123 | + |
| 124 | +def set_run_id(run_id): |
| 125 | + """Set the run ID (used by workers to inherit from main process).""" |
| 126 | + global _run_id |
| 127 | + with _run_id_lock: |
| 128 | + _run_id = run_id |
| 129 | + |
| 130 | + |
| 131 | +def get_base_result(): |
| 132 | + """Collect base result information from environment and git.""" |
| 133 | + github_sha = get_git_sha() |
| 134 | + github_ref_name = get_git_branch() |
| 135 | + github_run_id = os.environ.get("GITHUB_RUN_ID", None) |
| 136 | + run_number = os.environ.get("GITHUB_RUN_NUMBER", None) |
| 137 | + |
| 138 | + return { |
| 139 | + "run_id": get_run_id(), |
| 140 | + "github_repository": os.environ.get("GITHUB_REPOSITORY", None), |
| 141 | + "github_sha": os.environ.get("GITHUB_SHA", github_sha), |
| 142 | + "github_ref": os.environ.get("GITHUB_REF", None), |
| 143 | + "github_ref_name": github_ref_name, |
| 144 | + "github_run_id": int(github_run_id) if github_run_id else None, |
| 145 | + "github_head_ref": os.environ.get("GITHUB_HEAD_REF", None), |
| 146 | + "github_run_number": int(run_number) if run_number else None, |
| 147 | + "github_base_ref": os.environ.get("GITHUB_BASE_REF", None), |
| 148 | + "github_run_attempt": os.environ.get("GITHUB_RUN_ATTEMPT", None), |
| 149 | + } |
| 150 | + |
| 151 | + |
| 152 | +def pytest_configure(config): |
| 153 | + """Generate a unique run ID when pytest starts.""" |
| 154 | + # Generate the run ID early so it's available for all tests |
| 155 | + get_run_id() |
| 156 | + |
| 157 | + |
| 158 | +def pytest_report_header(config): |
| 159 | + """Add run ID to pytest header.""" |
| 160 | + run_id = get_run_id() |
| 161 | + return f"Run ID: {run_id}" |
| 162 | + |
| 163 | + |
| 164 | +def pytest_configure_node(node): |
| 165 | + """ |
| 166 | + Configure worker nodes to inherit the run ID from the main process. |
| 167 | +
|
| 168 | + This hook is called by pytest-xdist to configure worker nodes. |
| 169 | + """ |
| 170 | + node.workerinput["trackflaky_run_id"] = get_run_id() |
| 171 | + |
| 172 | + |
| 173 | +@pytest.hookimpl(tryfirst=True) |
| 174 | +def pytest_sessionstart(session): |
| 175 | + """ |
| 176 | + Initialize run ID from worker input if this is a worker process. |
| 177 | +
|
| 178 | + This runs on worker nodes to receive the run ID from the main process. |
| 179 | + """ |
| 180 | + if hasattr(session.config, "workerinput"): |
| 181 | + # We're in a worker process |
| 182 | + workerinput = session.config.workerinput |
| 183 | + if "trackflaky_run_id" in workerinput: |
| 184 | + set_run_id(workerinput["trackflaky_run_id"]) |
| 185 | + |
| 186 | + |
| 187 | +@pytest.hookimpl(hookwrapper=True) |
| 188 | +def pytest_pyfunc_call(pyfuncitem): |
| 189 | + """Hook into pytest test execution to track test outcomes.""" |
| 190 | + server = os.environ.get("CI_SERVER_URL", None) |
| 191 | + |
| 192 | + result = get_base_result() |
| 193 | + result["testname"] = pyfuncitem.name |
| 194 | + result["start_time"] = int(time()) |
| 195 | + |
| 196 | + outcome = yield |
| 197 | + |
| 198 | + result["end_time"] = int(time()) |
| 199 | + |
| 200 | + if outcome.excinfo is None: |
| 201 | + result["outcome"] = "success" |
| 202 | + elif outcome.excinfo[0] == unittest.case.SkipTest: |
| 203 | + result["outcome"] = "skip" |
| 204 | + else: |
| 205 | + result["outcome"] = "fail" |
| 206 | + |
| 207 | + print(result) |
| 208 | + |
| 209 | + if not server: |
| 210 | + return |
| 211 | + |
| 212 | + try: |
| 213 | + req = request.Request(f"{server}/hook/test", method="POST") |
| 214 | + req.add_header("Content-Type", "application/json") |
| 215 | + |
| 216 | + request.urlopen( |
| 217 | + req, |
| 218 | + data=json.dumps(result).encode("ASCII"), |
| 219 | + ) |
| 220 | + except ConnectionError as e: |
| 221 | + print(f"Could not report testrun: {e}") |
| 222 | + except Exception as e: |
| 223 | + import warnings |
| 224 | + |
| 225 | + warnings.warn(f"Error reporting testrun: {e}") |
0 commit comments