11"""Tests for header_injection module."""
22
33import threading
4+ import urllib .parse
45from typing import Any , Dict , Optional
56from unittest import mock
67
@@ -78,12 +79,12 @@ class TestInjectHeaderToDict:
7879 def test_inject_header_to_none_headers (self ) -> None :
7980 """Test injecting header when headers is None."""
8081 result = _inject_header_to_dict (None , "test::nodeid" )
81- assert result == {"X-Testsolar-Testcase" : "test::nodeid " }
82+ assert result == {"X-Testsolar-Testcase" : "test%3A%3Anodeid " }
8283
8384 def test_inject_header_to_empty_dict (self ) -> None :
8485 """Test injecting header to empty dict."""
8586 result = _inject_header_to_dict ({}, "test::nodeid" )
86- assert result == {"X-Testsolar-Testcase" : "test::nodeid " }
87+ assert result == {"X-Testsolar-Testcase" : "test%3A%3Anodeid " }
8788
8889 def test_inject_header_to_existing_dict (self ) -> None :
8990 """Test injecting header to dict with existing headers."""
@@ -92,11 +93,22 @@ def test_inject_header_to_existing_dict(self) -> None:
9293
9394 assert result == {
9495 "Content-Type" : "application/json" ,
95- "X-Testsolar-Testcase" : "test::nodeid " ,
96+ "X-Testsolar-Testcase" : "test%3A%3Anodeid " ,
9697 }
9798 # Original should not be modified
9899 assert "X-Testsolar-Testcase" not in original
99100
101+ def test_inject_header_encodes_non_ascii_nodeid (self ) -> None :
102+ """含中文等非ASCII字符的nodeid需被percent-encode,避免latin-1编码错误。"""
103+ nodeid = "test_features.py::test_重启运行中实例"
104+ result = _inject_header_to_dict (None , nodeid )
105+
106+ encoded = result ["X-Testsolar-Testcase" ]
107+ # 注入值必须可被latin-1编码(HTTP头部要求),否则抛UnicodeEncodeError
108+ assert isinstance (encoded .encode ("latin-1" ), bytes )
109+ # 接收方unquote可还原原始用例名
110+ assert urllib .parse .unquote (encoded ) == nodeid
111+
100112 def test_inject_header_does_not_modify_original (self ) -> None :
101113 """Test that original headers dict is not modified."""
102114 original : Dict [str , str ] = {"Authorization" : "Bearer token" }
@@ -166,7 +178,7 @@ def test_requests_header_injection(self) -> None:
166178 if mock_send .called :
167179 request = mock_send .call_args [0 ][0 ]
168180 assert "X-Testsolar-Testcase" in request .headers
169- assert request .headers ["X-Testsolar-Testcase" ] == "test_file.py::test_case "
181+ assert request .headers ["X-Testsolar-Testcase" ] == "test_file.py%3A%3Atest_case "
170182
171183 def test_requests_no_injection_when_nodeid_not_set (self ) -> None :
172184 """Test that requests does not inject header when nodeid is not set."""
0 commit comments