pytest-dsl 0.11.0__py3-none-any.whl → 0.12.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,7 +20,10 @@ from pytest_dsl.core.context import TestContext
20
20
  # 配置日志
21
21
  logger = logging.getLogger(__name__)
22
22
 
23
- def _process_file_reference(reference: Union[str, Dict[str, Any]], allow_vars: bool = True, test_context: TestContext = None) -> Any:
23
+
24
+ def _process_file_reference(reference: Union[str, Dict[str, Any]],
25
+ allow_vars: bool = True,
26
+ test_context: TestContext = None) -> Any:
24
27
  """处理文件引用,加载外部文件内容
25
28
 
26
29
  支持两种语法:
@@ -43,7 +46,8 @@ def _process_file_reference(reference: Union[str, Dict[str, Any]], allow_vars: b
43
46
  if match:
44
47
  file_path = match.group(1).strip()
45
48
  is_template = '_template' in reference[:15] # 检查是否为模板
46
- return _load_file_content(file_path, is_template, 'auto', 'utf-8', test_context)
49
+ return _load_file_content(file_path, is_template, 'auto', 'utf-8',
50
+ test_context)
47
51
 
48
52
  # 处理详细语法
49
53
  elif isinstance(reference, dict) and 'file_ref' in reference:
@@ -51,7 +55,8 @@ def _process_file_reference(reference: Union[str, Dict[str, Any]], allow_vars: b
51
55
 
52
56
  if isinstance(file_ref, str):
53
57
  # 如果file_ref是字符串,使用默认配置
54
- return _load_file_content(file_ref, allow_vars, 'auto', 'utf-8', test_context)
58
+ return _load_file_content(file_ref, allow_vars, 'auto', 'utf-8',
59
+ test_context)
55
60
  elif isinstance(file_ref, dict):
56
61
  # 如果file_ref是字典,使用自定义配置
57
62
  file_path = file_ref.get('path')
@@ -62,14 +67,16 @@ def _process_file_reference(reference: Union[str, Dict[str, Any]], allow_vars: b
62
67
  file_type = file_ref.get('type', 'auto')
63
68
  encoding = file_ref.get('encoding', 'utf-8')
64
69
 
65
- return _load_file_content(file_path, template, file_type, encoding, test_context)
70
+ return _load_file_content(file_path, template, file_type, encoding,
71
+ test_context)
66
72
 
67
73
  # 如果不是文件引用,返回原始值
68
74
  return reference
69
75
 
70
76
 
71
77
  def _load_file_content(file_path: str, is_template: bool = False,
72
- file_type: str = 'auto', encoding: str = 'utf-8', test_context: TestContext = None) -> Any:
78
+ file_type: str = 'auto', encoding: str = 'utf-8',
79
+ test_context: TestContext = None) -> Any:
73
80
  """加载文件内容
74
81
 
75
82
  Args:
@@ -122,7 +129,8 @@ def _load_file_content(file_path: str, is_template: bool = False,
122
129
  return content
123
130
 
124
131
 
125
- def _process_request_config(config: Dict[str, Any], test_context: TestContext = None) -> Dict[str, Any]:
132
+ def _process_request_config(config: Dict[str, Any],
133
+ test_context: TestContext = None) -> Dict[str, Any]:
126
134
  """处理请求配置,检查并处理文件引用
127
135
 
128
136
  Args:
@@ -140,20 +148,24 @@ def _process_request_config(config: Dict[str, Any], test_context: TestContext =
140
148
 
141
149
  # 处理json字段
142
150
  if 'json' in request:
143
- request['json'] = _process_file_reference(request['json'], test_context=test_context)
151
+ request['json'] = _process_file_reference(
152
+ request['json'], test_context=test_context)
144
153
 
145
154
  # 处理data字段
146
155
  if 'data' in request:
147
- request['data'] = _process_file_reference(request['data'], test_context=test_context)
156
+ request['data'] = _process_file_reference(
157
+ request['data'], test_context=test_context)
148
158
 
149
159
  # 处理headers字段
150
160
  if 'headers' in request:
151
- request['headers'] = _process_file_reference(request['headers'], test_context=test_context)
161
+ request['headers'] = _process_file_reference(
162
+ request['headers'], test_context=test_context)
152
163
 
153
164
  return config
154
165
 
155
166
 
156
- def _normalize_retry_config(config, assert_retry_count=None, assert_retry_interval=None):
167
+ def _normalize_retry_config(config, assert_retry_count=None,
168
+ assert_retry_interval=None):
157
169
  """标准化断言重试配置
158
170
 
159
171
  将不同来源的重试配置(命令行参数、retry配置、retry_assertions配置)
@@ -223,14 +235,23 @@ def _normalize_retry_config(config, assert_retry_count=None, assert_retry_interv
223
235
 
224
236
 
225
237
  @keyword_manager.register('HTTP请求', [
226
- {'name': '客户端', 'mapping': 'client', 'description': '客户端名称,对应YAML变量文件中的客户端配置', 'default': 'default'},
227
- {'name': '配置', 'mapping': 'config', 'description': '包含请求、捕获和断言的YAML配置'},
228
- {'name': '会话', 'mapping': 'session', 'description': '会话名称,用于在多个请求间保持会话状态'},
229
- {'name': '保存响应', 'mapping': 'save_response', 'description': '将完整响应保存到指定变量名中'},
230
- {'name': '禁用授权', 'mapping': 'disable_auth', 'description': '禁用客户端配置中的授权机制', 'default': False},
231
- {'name': '模板', 'mapping': 'template', 'description': '使用YAML变量文件中定义的请求模板'},
232
- {'name': '断言重试次数', 'mapping': 'assert_retry_count', 'description': '断言失败时的重试次数', 'default': 0},
233
- {'name': '断言重试间隔', 'mapping': 'assert_retry_interval', 'description': '断言重试间隔时间(秒)', 'default': 1}
238
+ {'name': '客户端', 'mapping': 'client',
239
+ 'description': '客户端名称,对应YAML变量文件中的客户端配置',
240
+ 'default': 'default'},
241
+ {'name': '配置', 'mapping': 'config',
242
+ 'description': '包含请求、捕获和断言的YAML配置'},
243
+ {'name': '会话', 'mapping': 'session',
244
+ 'description': '会话名称,用于在多个请求间保持会话状态'},
245
+ {'name': '保存响应', 'mapping': 'save_response',
246
+ 'description': '将完整响应保存到指定变量名中'},
247
+ {'name': '禁用授权', 'mapping': 'disable_auth',
248
+ 'description': '禁用客户端配置中的授权机制', 'default': False},
249
+ {'name': '模板', 'mapping': 'template',
250
+ 'description': '使用YAML变量文件中定义的请求模板'},
251
+ {'name': '断言重试次数', 'mapping': 'assert_retry_count',
252
+ 'description': '断言失败时的重试次数', 'default': 0},
253
+ {'name': '断言重试间隔', 'mapping': 'assert_retry_interval',
254
+ 'description': '断言重试间隔时间(秒)', 'default': 1}
234
255
  ])
235
256
  def http_request(context, **kwargs):
236
257
  """执行HTTP请求
@@ -260,7 +281,26 @@ def http_request(context, **kwargs):
260
281
  assert_retry_count = kwargs.get('assert_retry_count')
261
282
  assert_retry_interval = kwargs.get('assert_retry_interval')
262
283
 
263
- with allure.step(f"发送HTTP请求 (客户端: {client_name}{', 会话: ' + session_name if session_name else ''})"):
284
+ # 添加调试信息,检查客户端配置是否可用
285
+ print(f"🌐 HTTP请求 - 客户端: {client_name}")
286
+
287
+ # 检查YAML变量中的http_clients配置(现在包含同步的变量)
288
+ http_clients_config = yaml_vars.get_variable("http_clients")
289
+ if http_clients_config:
290
+ print(f"✓ 找到http_clients配置,包含 {len(http_clients_config)} 个客户端")
291
+ if client_name in http_clients_config:
292
+ print(f"✓ 找到客户端 '{client_name}' 的配置")
293
+ client_config = http_clients_config[client_name]
294
+ print(f" - base_url: {client_config.get('base_url', 'N/A')}")
295
+ print(f" - timeout: {client_config.get('timeout', 'N/A')}")
296
+ else:
297
+ print(f"⚠️ 未找到客户端 '{client_name}' 的配置")
298
+ print(f" 可用客户端: {list(http_clients_config.keys())}")
299
+ else:
300
+ print("⚠️ 未找到http_clients配置")
301
+
302
+ with allure.step(f"发送HTTP请求 (客户端: {client_name}"
303
+ f"{', 会话: ' + session_name if session_name else ''})"):
264
304
  # 处理模板
265
305
  if template_name:
266
306
  # 从YAML变量中获取模板
@@ -299,7 +339,8 @@ def http_request(context, **kwargs):
299
339
  raise ValueError(f"无效的YAML配置: {str(e)}")
300
340
 
301
341
  # 统一处理重试配置
302
- retry_config = _normalize_retry_config(config, assert_retry_count, assert_retry_interval)
342
+ retry_config = _normalize_retry_config(config, assert_retry_count,
343
+ assert_retry_interval)
303
344
 
304
345
  # 为了兼容性,将标准化后的重试配置写回到配置中
305
346
  if retry_config['enabled']:
@@ -344,7 +385,8 @@ def http_request(context, **kwargs):
344
385
  if session_name:
345
386
  try:
346
387
  from pytest_dsl.core.http_client import http_client_manager
347
- session_client = http_client_manager.get_session(session_name, client_name)
388
+ session_client = http_client_manager.get_session(
389
+ session_name, client_name)
348
390
  if session_client and session_client._session:
349
391
  session_state = {
350
392
  "cookies": dict(session_client._session.cookies),
@@ -375,7 +417,8 @@ def http_request(context, **kwargs):
375
417
  return {
376
418
  "result": captured_values, # 主要返回值保持兼容
377
419
  "captures": captured_values, # 明确的捕获变量
378
- "session_state": {session_name: session_state} if session_state else {},
420
+ "session_state": ({session_name: session_state}
421
+ if session_state else {}),
379
422
  "response": response_data, # 完整响应(如果需要)
380
423
  "metadata": {
381
424
  "response_time": getattr(response, 'elapsed', None),
@@ -396,7 +439,8 @@ def _deep_merge(dict1, dict2):
396
439
  合并后的字典
397
440
  """
398
441
  for key in dict2:
399
- if key in dict1 and isinstance(dict1[key], dict) and isinstance(dict2[key], dict):
442
+ if (key in dict1 and isinstance(dict1[key], dict) and
443
+ isinstance(dict2[key], dict)):
400
444
  _deep_merge(dict1[key], dict2[key])
401
445
  else:
402
446
  dict1[key] = dict2[key]
@@ -424,7 +468,8 @@ def _process_assertions_with_unified_retry(http_req, retry_config):
424
468
  )
425
469
 
426
470
  # 添加一个特殊的标记到配置中,表示我们只想收集失败的断言而不抛出异常
427
- original_config = http_req.config.copy() if isinstance(http_req.config, dict) else {}
471
+ original_config = (http_req.config.copy()
472
+ if isinstance(http_req.config, dict) else {})
428
473
 
429
474
  # 创建一个临时副本
430
475
  temp_config = original_config.copy()
@@ -442,7 +487,8 @@ def _process_assertions_with_unified_retry(http_req, retry_config):
442
487
  except Exception as collect_err:
443
488
  # 出现意外错误时记录
444
489
  allure.attach(
445
- f"收集失败断言时出错: {type(collect_err).__name__}: {str(collect_err)}",
490
+ f"收集失败断言时出错: {type(collect_err).__name__}: "
491
+ f"{str(collect_err)}",
446
492
  name="断言收集错误",
447
493
  attachment_type=allure.attachment_type.TEXT
448
494
  )
@@ -513,16 +559,18 @@ def _process_assertions_with_unified_retry(http_req, retry_config):
513
559
 
514
560
  # 找出所有断言中最大的重试次数
515
561
  for retryable_assertion in retryable_assertions:
516
- max_retry_count = max(max_retry_count, retryable_assertion.get('retry_count', 3))
562
+ max_retry_count = max(max_retry_count,
563
+ retryable_assertion.get('retry_count', 3))
517
564
 
518
565
  # 进行断言重试
519
- for attempt in range(1, max_retry_count + 1): # 从1开始,因为第0次已经尝试过了
566
+ for attempt in range(1, max_retry_count + 1):
520
567
  # 等待重试间隔
521
568
  with allure.step(f"断言重试 (尝试 {attempt}/{max_retry_count})"):
522
569
  # 确定本次重试的间隔时间(使用每个断言中最长的间隔时间)
523
570
  retry_interval = retry_config['interval']
524
571
  for assertion in retryable_assertions:
525
- retry_interval = max(retry_interval, assertion.get('retry_interval', 1.0))
572
+ retry_interval = max(retry_interval,
573
+ assertion.get('retry_interval', 1.0))
526
574
 
527
575
  allure.attach(
528
576
  f"重试 {len(retryable_assertions)} 个断言\n"
@@ -552,14 +600,21 @@ def _process_assertions_with_unified_retry(http_req, retry_config):
552
600
  # 只重试那些仍在重试范围内的断言
553
601
  try:
554
602
  # 从原始断言配置中提取出需要重试的断言
555
- retry_assertion_indexes = [a['index'] for a in still_retryable_assertions]
556
- retry_assertions = [http_req.config.get('asserts', [])[idx] for idx in retry_assertion_indexes]
603
+ retry_assertion_indexes = [
604
+ a['index'] for a in still_retryable_assertions]
605
+ retry_assertions = [
606
+ http_req.config.get('asserts', [])[idx]
607
+ for idx in retry_assertion_indexes]
557
608
 
558
609
  # 创建索引映射:新索引 -> 原始索引
559
- index_mapping = {new_idx: orig_idx for new_idx, orig_idx in enumerate(retry_assertion_indexes)}
610
+ index_mapping = {
611
+ new_idx: orig_idx for new_idx, orig_idx in
612
+ enumerate(retry_assertion_indexes)}
560
613
 
561
614
  # 只处理需要重试的断言,传递索引映射
562
- results, new_failed_assertions = http_req.process_asserts(specific_asserts=retry_assertions, index_mapping=index_mapping)
615
+ results, new_failed_assertions = http_req.process_asserts(
616
+ specific_asserts=retry_assertions,
617
+ index_mapping=index_mapping)
563
618
 
564
619
  # 如果所有断言都通过了,检查全部断言
565
620
  if not new_failed_assertions:
@@ -607,7 +662,8 @@ def _process_assertions_with_unified_retry(http_req, retry_config):
607
662
  except AssertionError as final_err:
608
663
  # 重新格式化错误消息,添加重试信息
609
664
  enhanced_error = (
610
- f"断言验证失败 (已重试 {max_retry_count} 次):\n\n{str(final_err)}"
665
+ f"断言验证失败 (已重试 {max_retry_count} 次):\n\n"
666
+ f"{str(final_err)}"
611
667
  )
612
668
  allure.attach(
613
669
  enhanced_error,
@@ -617,4 +673,4 @@ def _process_assertions_with_unified_retry(http_req, retry_config):
617
673
  raise AssertionError(enhanced_error) from final_err
618
674
 
619
675
 
620
- # 注意:旧的重试函数已被移除,现在使用统一的重试机制
676
+ # 注意:旧的重试函数已被移除,现在使用统一的重试机制