|
| 1 | +""" |
| 2 | +HTTP请求头注入模块 |
| 3 | +
|
| 4 | +该模块用于在pytest测试执行过程中,自动向HTTP请求注入测试用例标识信息。 |
| 5 | +支持requests和httplib/http.client两种HTTP库。 |
| 6 | +""" |
| 7 | + |
| 8 | +import threading |
| 9 | +from typing import Optional, Callable, Any, Dict |
| 10 | + |
| 11 | +from loguru import logger |
| 12 | + |
| 13 | + |
| 14 | +# ============ 上下文管理 ============ |
| 15 | +# 用于存储当前测试用例的nodeid |
| 16 | +_test_context = threading.local() |
| 17 | + |
| 18 | +# 原始请求方法引用 |
| 19 | +_original_requests_request: Optional[Callable[..., Any]] = None |
| 20 | +_original_httplib_request: Optional[Callable[..., Any]] = None |
| 21 | + |
| 22 | +# 用于存储判定函数的引用 |
| 23 | +_should_enable_injection_func: Optional[Callable[[], bool]] = None |
| 24 | + |
| 25 | + |
| 26 | +def get_current_test_nodeid() -> Optional[str]: |
| 27 | + """获取当前测试用例的nodeid""" |
| 28 | + return getattr(_test_context, "nodeid", None) |
| 29 | + |
| 30 | + |
| 31 | +def set_current_test_nodeid(nodeid: Optional[str]) -> None: |
| 32 | + """设置当前测试用例的nodeid""" |
| 33 | + _test_context.nodeid = nodeid |
| 34 | + |
| 35 | + |
| 36 | +# ============ Header 注入逻辑 ============ |
| 37 | +def _inject_header_to_dict(headers: Optional[Dict[str, Any]], nodeid: str) -> Dict[str, Any]: |
| 38 | + """ |
| 39 | + 向请求头字典注入X-Testsolar-Testcase |
| 40 | +
|
| 41 | + Args: |
| 42 | + headers: 原始请求头字典 |
| 43 | + nodeid: 测试用例的nodeid |
| 44 | +
|
| 45 | + Returns: |
| 46 | + 注入后的请求头字典 |
| 47 | + """ |
| 48 | + if headers is None: |
| 49 | + headers = {} |
| 50 | + elif not isinstance(headers, dict): |
| 51 | + # 如果headers不是dict,创建新dict |
| 52 | + headers = dict(headers) |
| 53 | + else: |
| 54 | + # 创建副本避免修改原始dict |
| 55 | + headers = headers.copy() |
| 56 | + |
| 57 | + headers["X-Testsolar-Testcase"] = nodeid |
| 58 | + return headers |
| 59 | + |
| 60 | + |
| 61 | +# ============ Monkey Patch 实现 ============ |
| 62 | +def _patch_requests() -> None: |
| 63 | + """Patch requests库的Session.request方法""" |
| 64 | + try: |
| 65 | + import requests # type: ignore[import] |
| 66 | + |
| 67 | + global _original_requests_request |
| 68 | + |
| 69 | + if _original_requests_request is not None: |
| 70 | + # 已经patch过了 |
| 71 | + return |
| 72 | + |
| 73 | + _original_requests_request = requests.Session.request |
| 74 | + |
| 75 | + def _patched_request(self: Any, method: str, url: str, **kwargs: Any) -> Any: |
| 76 | + # 通过判定函数检查是否需要注入 |
| 77 | + if _should_enable_injection_func and _should_enable_injection_func(): |
| 78 | + nodeid = get_current_test_nodeid() |
| 79 | + if nodeid: |
| 80 | + headers = kwargs.get("headers") |
| 81 | + kwargs["headers"] = _inject_header_to_dict(headers, nodeid) |
| 82 | + |
| 83 | + return _original_requests_request(self, method, url, **kwargs) |
| 84 | + |
| 85 | + requests.Session.request = _patched_request |
| 86 | + logger.info("Successfully patched requests.Session.request") |
| 87 | + |
| 88 | + except ImportError: |
| 89 | + logger.debug("requests library not installed, skip patching") |
| 90 | + except Exception as e: |
| 91 | + logger.error(f"Failed to patch requests: {e}") |
| 92 | + |
| 93 | + |
| 94 | +def _patch_httplib() -> None: |
| 95 | + """Patch httplib/http.client的HTTPConnection.request方法""" |
| 96 | + try: |
| 97 | + # Python 2/3 兼容 |
| 98 | + try: |
| 99 | + import http.client as httplib |
| 100 | + except ImportError: |
| 101 | + import httplib # type: ignore |
| 102 | + |
| 103 | + global _original_httplib_request |
| 104 | + |
| 105 | + if _original_httplib_request is not None: |
| 106 | + # 已经patch过了 |
| 107 | + return |
| 108 | + |
| 109 | + _original_httplib_request = httplib.HTTPConnection.request |
| 110 | + |
| 111 | + def _patched_httplib_request( |
| 112 | + self: Any, |
| 113 | + method: str, |
| 114 | + url: str, |
| 115 | + body: Any = None, |
| 116 | + headers: Any = None, |
| 117 | + **kwargs: Any, |
| 118 | + ) -> Any: |
| 119 | + # 通过判定函数检查是否需要注入 |
| 120 | + final_headers: Any = headers |
| 121 | + if _should_enable_injection_func and _should_enable_injection_func(): |
| 122 | + nodeid = get_current_test_nodeid() |
| 123 | + if nodeid: |
| 124 | + # httplib的headers参数默认是{}而不是None |
| 125 | + if final_headers is None: |
| 126 | + final_headers = {"X-Testsolar-Testcase": nodeid} |
| 127 | + else: |
| 128 | + # 创建副本避免修改原始headers |
| 129 | + new_headers = dict(final_headers) |
| 130 | + new_headers["X-Testsolar-Testcase"] = nodeid |
| 131 | + final_headers = new_headers |
| 132 | + |
| 133 | + return _original_httplib_request(self, method, url, body, final_headers, **kwargs) |
| 134 | + |
| 135 | + httplib.HTTPConnection.request = _patched_httplib_request # type: ignore[method-assign] |
| 136 | + logger.info("Successfully patched httplib.HTTPConnection.request") |
| 137 | + |
| 138 | + except ImportError: |
| 139 | + logger.debug("httplib library not available, skip patching") |
| 140 | + except Exception as e: |
| 141 | + logger.error(f"Failed to patch httplib: {e}") |
| 142 | + |
| 143 | + |
| 144 | +# ============ 公共接口 ============ |
| 145 | +def initialize_header_injection(should_enable_func: Callable[[], bool]) -> None: |
| 146 | + """ |
| 147 | + 初始化HTTP请求头注入功能 |
| 148 | +
|
| 149 | + Args: |
| 150 | + should_enable_func: 判定函数,返回bool表示是否启用注入 |
| 151 | + """ |
| 152 | + global _should_enable_injection_func |
| 153 | + _should_enable_injection_func = should_enable_func |
| 154 | + |
| 155 | + logger.info("Initializing API header injection...") |
| 156 | + _patch_requests() |
| 157 | + _patch_httplib() |
0 commit comments