hellchin-lib 0.1.0__tar.gz → 0.1.2__tar.gz

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.
Files changed (29) hide show
  1. {hellchin_lib-0.1.0 → hellchin_lib-0.1.2}/PKG-INFO +1 -1
  2. hellchin_lib-0.1.2/README.md +65 -0
  3. {hellchin_lib-0.1.0/hellchin_lib/soft_assert → hellchin_lib-0.1.2/_hellchin_lib/assertion}/base_soft_assert.py +49 -18
  4. hellchin_lib-0.1.2/_hellchin_lib/assertion/method_assert.py +441 -0
  5. hellchin_lib-0.1.2/_hellchin_lib/assertion/postman.py +9 -0
  6. hellchin_lib-0.1.2/_hellchin_lib/logger.py +118 -0
  7. hellchin_lib-0.1.2/hellchin_lib/__init__.py +21 -0
  8. {hellchin_lib-0.1.0 → hellchin_lib-0.1.2}/hellchin_lib.egg-info/PKG-INFO +1 -1
  9. hellchin_lib-0.1.2/hellchin_lib.egg-info/SOURCES.txt +22 -0
  10. {hellchin_lib-0.1.0 → hellchin_lib-0.1.2}/hellchin_lib.egg-info/top_level.txt +1 -0
  11. hellchin_lib-0.1.2/pyproject.toml +7 -0
  12. {hellchin_lib-0.1.0 → hellchin_lib-0.1.2}/setup.py +5 -1
  13. hellchin_lib-0.1.2/tests/test_soft_assert/test_demo.py +40 -0
  14. hellchin_lib-0.1.2/tests/test_soft_assert/test_method_assert.py +39 -0
  15. hellchin_lib-0.1.2/tests/test_soft_assert/test_soft_assert.py +18 -0
  16. hellchin_lib-0.1.0/README.md +0 -0
  17. hellchin_lib-0.1.0/hellchin_lib/soft_assert/method_assert.py +0 -197
  18. hellchin_lib-0.1.0/hellchin_lib.egg-info/SOURCES.txt +0 -17
  19. hellchin_lib-0.1.0/pyproject.toml +0 -3
  20. hellchin_lib-0.1.0/tests/test_soft_assert/test_assertions.py +0 -33
  21. {hellchin_lib-0.1.0 → hellchin_lib-0.1.2}/LICENSE +0 -0
  22. {hellchin_lib-0.1.0/hellchin_lib → hellchin_lib-0.1.2/_hellchin_lib}/__init__.py +0 -0
  23. {hellchin_lib-0.1.0/hellchin_lib/soft_assert → hellchin_lib-0.1.2/_hellchin_lib/assertion}/__init__.py +0 -0
  24. {hellchin_lib-0.1.0/hellchin_lib/soft_assert → hellchin_lib-0.1.2/_hellchin_lib/assertion}/logger.py +0 -0
  25. {hellchin_lib-0.1.0 → hellchin_lib-0.1.2}/hellchin_lib.egg-info/dependency_links.txt +0 -0
  26. {hellchin_lib-0.1.0 → hellchin_lib-0.1.2}/hellchin_lib.egg-info/requires.txt +0 -0
  27. {hellchin_lib-0.1.0 → hellchin_lib-0.1.2}/setup.cfg +0 -0
  28. {hellchin_lib-0.1.0 → hellchin_lib-0.1.2}/tests/__init__.py +0 -0
  29. {hellchin_lib-0.1.0 → hellchin_lib-0.1.2}/tests/test_soft_assert/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hellchin_lib
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: A Python library for soft assertions and flexible testing.
5
5
  Author: hellchin
6
6
  Author-email: your.email@example.com
@@ -0,0 +1,65 @@
1
+ # hellchin-lib
2
+
3
+ ## 简介
4
+ 个人开发使用的一些工具包,主要用于自动化测试,目前主要开发断言功能,支持软硬断言。
5
+
6
+ ## 安装
7
+ ```bash
8
+ pip install hellchin-lib
9
+ ```
10
+
11
+ ## 使用方法
12
+
13
+ !!!详细教程有空的时候再进行更新
14
+
15
+ 建议教程如下:
16
+
17
+ 示例代码:
18
+ ```python
19
+ # !/usr/bin/env python
20
+ # -*- coding: utf-8 -*-
21
+ """
22
+ -------------------------------------------------
23
+ File Name: test_demo.py
24
+ Description:
25
+ -------------------------------------------------
26
+ """
27
+
28
+ from hellchin_lib import PostManAssertMethod, MethodAssert
29
+
30
+ pm = PostManAssertMethod()
31
+ pm.response = {
32
+ "a": 1
33
+ }
34
+
35
+ # raise Exception("测试")
36
+ pm_code_test = """
37
+ # pm.expect(1).to.equal(2)
38
+ pm.test("", lambda: pm.expect('1').to.equal(1))
39
+ pm.test("失败断言", lambda: pm.expect(1).to.equal(2))
40
+ pm.test("", lambda: pm.expect(1).to.equal(1))
41
+ pm.test("成功断言", lambda: pm.expect(1).to.equal(1))
42
+ res = pm.response.json()
43
+ pm.test("undefined 测试", lambda: pm.expect(res.b).to.equal(1))
44
+ # pm.expect(res.b).to.equal(1)
45
+ """
46
+
47
+ exec(pm_code_test, {"pm": pm})
48
+
49
+ ma_code_test = """
50
+ method_assert.check(1 == 1)
51
+ method_assert.check(1 == 2)
52
+ method_assert.equal(1, 1)
53
+ method_assert.equal(1, 2)
54
+ method_assert.exists(1)
55
+ method_assert.fail()
56
+ """
57
+
58
+ # exec(ma_code_test, {"method_assert": MethodAssert()})
59
+
60
+ ```
61
+
62
+
63
+ ## 文档链接
64
+
65
+ 更多文档请访问:None
@@ -10,22 +10,22 @@
10
10
  """
11
11
 
12
12
  import inspect
13
+ import weakref
14
+ from typing import Any
13
15
 
14
16
  import pytest
15
17
 
16
18
 
17
- # from apitesting.src.models import Assertion
18
- # from .logger import logger
19
-
20
-
21
19
  class SoftAssert:
22
20
  """自定义软断言类,支持灵活调用和集成"""
23
21
 
24
22
  def __init__(self):
25
23
  self.results_list = [] # 记录所有断言的结果
26
24
  self.has_failures = False # 是否存在失败断言
25
+ self.success_icon = "✅ "
26
+ self.failure_icon = "❌ "
27
27
 
28
- def check(self, condition, assert_name=None, error_message="AssertionError: None"):
28
+ def check(self, condition, assert_name=None, error_message=None):
29
29
  """
30
30
  记录断言结果。
31
31
 
@@ -49,6 +49,8 @@ class SoftAssert:
49
49
  # print(type(assert_name))
50
50
  assert_info = assert_name or f"{expression}"
51
51
 
52
+ error_message = f"AssertionError: {error_message}" if error_message else error_message
53
+
52
54
  # 执行断言
53
55
  try:
54
56
  assert condition, error_message
@@ -56,11 +58,16 @@ class SoftAssert:
56
58
  self.results_list.append("✅ " + assert_info)
57
59
  except AssertionError as ae:
58
60
  # 记录失败的断言
59
- failure_message = "❌ " + ' | '.join([assert_info, error_message])
61
+ if error_message:
62
+ failure_message = self.failure_icon + ' | '.join([assert_info, error_message])
63
+ else:
64
+ failure_message = self.failure_icon + assert_info
60
65
  self.results_list.append(failure_message)
61
66
  self.has_failures = True # 标记存在失败断言
62
67
 
63
- def report(self, clear=True):
68
+ return self.results_list[-1]
69
+
70
+ def result(self, clear=True):
64
71
  """
65
72
  报告所有断言结果。
66
73
  "主动调用表示将所有的结果输出"
@@ -73,23 +80,31 @@ class SoftAssert:
73
80
 
74
81
  # 报告结果
75
82
  report_messages = "\n".join([f" [{i + 1}] {msg}" for i, msg in enumerate(self.results_list)])
83
+
76
84
  if clear:
77
85
  self.results_list = [] # 清空结果
78
86
 
79
- if self.has_failures:
87
+ return (
88
+ f"Soft assertion summary:\n"
89
+ f"""{success_count} success(es){f', {failure_count} failure(s)' if failure_count == 0 else ''}: \n"""
90
+ f"{report_messages}"
91
+ )
92
+
93
+ def fail(self):
94
+ assert_results = self.result()
95
+ # 判断 AssertionError 是否包含在列表字符串中
96
+ contains_assertion_error = "AssertionError" in assert_results
97
+ # 如果断言结果中包含 "AssertionError" 字符串,或者存在失败断言,则抛出异常
98
+ if contains_assertion_error or self.has_failures:
80
99
  # 使用 pytest.fail 避免过多堆栈信息
81
100
  pytest.fail(
82
- f"Soft Assertion Summary:\n"
83
- f"{failure_count} failure(s), {success_count} success(es):\n"
84
- f"{report_messages}",
85
- pytrace=False, # 避免输出多余的堆栈信息
101
+ reason=assert_results,
102
+ # 可选参数,默认为True。
103
+ pytrace=False, # 是否显示完整的 Python 跟踪信息(traceback)。设置为 False 可以隐藏 Python 栈信息,直接显示失败原因。
104
+ # msg="test failed"
86
105
  )
87
106
  else:
88
- print(
89
- f"Soft assertion summary:\n"
90
- f"{success_count} success(es):\n"
91
- f"{report_messages}"
92
- )
107
+ print(assert_results)
93
108
 
94
109
  def __enter__(self):
95
110
  """进入上下文"""
@@ -97,4 +112,20 @@ class SoftAssert:
97
112
 
98
113
  def __exit__(self, exc_type, exc_val, exc_tb):
99
114
  """退出上下文时自动报告断言结果"""
100
- self.report()
115
+ self.result()
116
+
117
+ # def __del__(self):
118
+ # """
119
+ # 析构函数,在对象被销毁时自动报告断言结果,
120
+ # 当对象不再被引用时,Python会自动调用该方法来释放资源
121
+ # 如果不想手动调用fail(), 可以重写del方法,在对象销毁时自动调用fail()方法
122
+ # 注意: 异常无法被外部捕捉,
123
+ # """
124
+ # self.fail()
125
+
126
+
127
+ if __name__ == '__main__':
128
+ expect = SoftAssert()
129
+ expect.check(1 == 1, "1==1")
130
+ expect.check(1 == 2, "1==2")
131
+ expect.check(1 == 3, "1==3")
@@ -0,0 +1,441 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: method_assert.py
6
+ Description: 具体断言逻辑实现
7
+ -------------------------------------------------
8
+
9
+ 继承 SoftAssert 类,扩展出具体的断言方法。
10
+ 如 equal、not_equal、greater_than 等。
11
+ """
12
+
13
+ from typing import Union, Any
14
+
15
+ import requests
16
+ from box import Box
17
+
18
+ from _hellchin_lib.assertion.base_soft_assert import SoftAssert
19
+
20
+
21
+ class AssertMsg:
22
+
23
+ def __init__(self, *args, actual, expected, context):
24
+ self.msg = args[0]
25
+ self.actual = actual
26
+ self.expected = expected
27
+ self.context = context
28
+
29
+ def __call__(self, *args, **kwargs):
30
+ return self.msg # 默认返回第一个参数作为断言信息
31
+
32
+
33
+ class AssertionUndefinedError(AssertionError):
34
+ pass
35
+
36
+
37
+ class Undefined:
38
+ def __repr__(self):
39
+ return "undefined"
40
+
41
+
42
+ # 实例化一个特殊对象
43
+ UNDEFINED = Undefined()
44
+
45
+
46
+ class BaseMethodAssert:
47
+ """
48
+ BaseMethodAssert 类,用于实现具体的断言方法。硬断言方法。
49
+ """
50
+
51
+ def __init__(self, expected_value: Any = None):
52
+ super().__init__()
53
+
54
+ self.IS_UNDEFINED = isinstance(expected_value, Undefined) # 判断是否是未定义的对象
55
+
56
+ self.expected = expected_value
57
+
58
+ @staticmethod
59
+ def _parse_assert_data(assert_data: Union[str, dict]) -> dict:
60
+ """
61
+ 解析断言数据,支持字符串或 pydantic 模型
62
+
63
+ :param assert_data: 可能是字符串表达式或 pydantic 模型
64
+ :return: 解析后的 Assertion 对象
65
+ """
66
+ if isinstance(assert_data, dict): # Assertion
67
+ return assert_data
68
+ elif isinstance(assert_data, str):
69
+ # 解析字符串格式,比如 `$.code > "200"`
70
+ # return self._parse_string_assert(assert_data)
71
+ raise ValueError(f"Unsupported assert_data type: {type(assert_data)}")
72
+ else:
73
+ raise ValueError(f"Unsupported assert_data type: {type(assert_data)}")
74
+
75
+ def _generate_assert_messages(self, success_condition: str, fail_message: str, actual=None, expected=None) -> tuple:
76
+ """
77
+ 生成断言的成功和失败信息。
78
+
79
+ :param success_condition: 成功条件描述
80
+ :param fail_message: 失败消息模板
81
+ :param actual: 实际值
82
+ :param expected: 预期值
83
+ :return: 成功信息和失败信息
84
+ """
85
+
86
+ assert_info_success = success_condition
87
+ fail_message = fail_message.format(actual=repr(actual), expected=repr(expected))
88
+ assert_info_fail = f"{assert_info_success} | AssertionError: {fail_message}"
89
+ assert_raise_msg = AssertMsg(assert_info_fail, actual=actual, expected=expected, context=fail_message)
90
+
91
+ # 如果实际值是未定义的,则抛出 AssertionUndefinedError
92
+ if self.IS_UNDEFINED:
93
+ raise AssertionUndefinedError(assert_raise_msg) # 抛出一个错误对象,具体的错误信息由 assert_raise_msg 提供
94
+
95
+ return assert_info_success, assert_raise_msg
96
+
97
+ def equal(self, actual, /, expected=None, *, assert_name=None, jsonpath: str = None):
98
+ """
99
+ 判断响应相等的逻辑。
100
+ """
101
+
102
+ expected = self.expected or expected
103
+
104
+ if expected is None:
105
+ raise ValueError("Expected value cannot be None.")
106
+
107
+ success_message, fail_message = self._generate_assert_messages(
108
+ assert_name or f"{repr(expected)} == {jsonpath or actual}",
109
+ "expected {expected} to deeply equal {actual} ",
110
+ actual, expected
111
+ )
112
+
113
+ assert actual == expected, fail_message
114
+
115
+ return success_message
116
+
117
+ def not_equal(self, actual, expected=None, assert_name=None, jsonpath: str = None):
118
+ """
119
+ 判断响应不相等的逻辑。
120
+ """
121
+
122
+ expected = self.expected or expected
123
+
124
+ if expected is None:
125
+ raise ValueError("Expected value cannot be None.")
126
+
127
+ success_message, fail_message = self._generate_assert_messages(
128
+ assert_name or f"{repr(expected)} != {jsonpath or actual}",
129
+ "expected {actual} not to deeply equal {expected} ",
130
+ actual, expected
131
+ )
132
+
133
+ assert actual != expected, fail_message
134
+
135
+ return success_message
136
+
137
+ def greater_than(self, actual, expected=None, assert_name=None, jsonpath: str = None):
138
+ """
139
+ 判断响应大于的逻辑。
140
+ """
141
+
142
+ expected = self.expected or expected
143
+
144
+ if expected is None:
145
+ raise ValueError("Expected value cannot be None.")
146
+
147
+ success_message, fail_message = self._generate_assert_messages(
148
+ assert_name or f"{jsonpath or actual} > {repr(expected)}",
149
+ "expected {actual} to be greater than {expected} ",
150
+ actual, expected
151
+ )
152
+
153
+ assert actual > expected, fail_message
154
+
155
+ return success_message
156
+
157
+ def greater_than_or_equal(self, actual, expected=None, *, assert_name=None, jsonpath: str = None) -> None:
158
+ """
159
+ 判断响应值是否大于或等于预期值的逻辑。
160
+ """
161
+
162
+ expected = self.expected or expected
163
+
164
+ if expected is None:
165
+ raise ValueError("Expected value cannot be None.")
166
+
167
+ success_message, fail_message = self._generate_assert_messages(
168
+ assert_name or f"{jsonpath or actual} >= {repr(expected)}",
169
+ "expected {actual} to be greater than or equal to {expected} ",
170
+ actual, expected
171
+ )
172
+
173
+ assert actual >= expected, fail_message
174
+
175
+ return success_message
176
+
177
+ # 执行断言并记录结果
178
+ # self.check(actual >= expected, success_message, fail_message)
179
+
180
+ def greater_than_or_equal_v2(self, actual, expected=None, *, assert_name=None, jsonpath: str = None) -> None:
181
+ """
182
+ 判断响应值是否大于或等于预期值的逻辑。
183
+ """
184
+
185
+ expected = self.expected or expected
186
+
187
+ if expected is None:
188
+ raise ValueError("Expected value cannot be None.")
189
+
190
+ success_message, fail_message = self._generate_assert_messages(
191
+ assert_name or f"{jsonpath or actual} >= {repr(expected)}",
192
+ "expected {actual} to be greater than or equal to {expected} ",
193
+ actual, expected
194
+ )
195
+
196
+ assert actual >= expected, fail_message
197
+
198
+ return success_message
199
+
200
+ # 执行断言并记录结果
201
+ # self.check(actual >= expected, success_message, fail_message)
202
+
203
+ def less_than(self, actual, expected=None, *, assert_name=None, jsonpath: str = None) -> None:
204
+ """
205
+ 判断响应小于的逻辑。
206
+ """
207
+
208
+ expected = self.expected or expected
209
+
210
+ if expected is None:
211
+ raise ValueError("Expected value cannot be None.")
212
+
213
+ success_message, fail_message = self._generate_assert_messages(
214
+ assert_name or f"{jsonpath or actual} < {repr(expected)}",
215
+ "expected {actual} to be less than {expected} ",
216
+ actual, expected
217
+ )
218
+
219
+ assert actual < expected, fail_message
220
+
221
+ return success_message
222
+
223
+ # 执行断言并记录结果
224
+ # self.check(actual < expected, success_message, fail_message)
225
+
226
+ def less_than_or_equal(self, actual, expected=None, *, assert_name=None, jsonpath: str = None) -> None:
227
+ """
228
+ 判断响应小于或等于的逻辑。
229
+ """
230
+
231
+ expected = self.expected or expected
232
+
233
+ if expected is None:
234
+ raise ValueError("Expected value cannot be None.")
235
+
236
+ success_message, fail_message = self._generate_assert_messages(
237
+ assert_name or f"{jsonpath or actual} <= {repr(expected)}",
238
+ "expected {actual} to be less than or equal to {expected} ",
239
+ actual, expected
240
+ )
241
+
242
+ assert actual <= expected, fail_message
243
+
244
+ return success_message
245
+
246
+ @property
247
+ def exists(self):
248
+ """
249
+ 判断 key 是否存在的逻辑。
250
+ self, expected=None, *, assert_name=None, jsonpath: str = None
251
+ """
252
+
253
+ def func(*args, **kwargs):
254
+ print(f"IS_UNDEFINED: {self.IS_UNDEFINED}")
255
+
256
+ expected = self.expected or args[0]
257
+
258
+ desc = kwargs.get("desc", None)
259
+
260
+ if expected is None:
261
+ raise ValueError("Expected value cannot be None.")
262
+
263
+ success_message, fail_message = self._generate_assert_messages(
264
+ desc or f"{expected} exists",
265
+ "expected {expected} to exist",
266
+ expected=expected
267
+ )
268
+
269
+ assert bool(expected), fail_message
270
+
271
+ return success_message
272
+
273
+ return func
274
+
275
+ @property
276
+ def not_exists(self):
277
+ """
278
+ 判断 key 不存在的逻辑。
279
+ """
280
+
281
+ def func(*args, **kwargs) -> str:
282
+ expected = self.expected or args[0]
283
+
284
+ desc = kwargs.get("desc", None)
285
+
286
+ if expected is None:
287
+ raise ValueError("Expected value cannot be None.")
288
+
289
+ success_message, fail_message = self._generate_assert_messages(
290
+ desc or f"{expected} does not exist",
291
+ "expected {expected} to not exist",
292
+ expected=expected
293
+ )
294
+
295
+ assert not bool(expected), fail_message
296
+
297
+ return success_message
298
+
299
+ return func
300
+
301
+
302
+ class Expect:
303
+ """
304
+ Expect 类,用于创建一个 to 属性,该属性包含一个 BaseMethodAssert 对象,
305
+ """
306
+
307
+ def __init__(self, expected_value: Any):
308
+ self.to = BaseMethodAssert(expected_value)
309
+
310
+
311
+ class PostManAssertMethod:
312
+
313
+ def __init__(self):
314
+ # self.expect = Expect # 初始化Expect对象
315
+ self._response = dict() # 初始化响应对象
316
+ self.__success_icon = "✅ "
317
+ self.__failure_icon = "❌ "
318
+ self.test_results_list = [] # 初始化结果列表
319
+
320
+ @staticmethod
321
+ def _format_assert_error(desc: str, error_message: str) -> str:
322
+ """
323
+ 格式化断言错误信息。
324
+ """
325
+ if desc:
326
+ error_message = error_message.split('|')[1]
327
+ return f"❌ {desc} |{error_message}"
328
+ return f"❌ {error_message}"
329
+
330
+ @staticmethod
331
+ def test(desc, test_func=None):
332
+ """
333
+ 测试方法,用于执行测试函数,并打印测试结果。
334
+
335
+ test 方法要对抛出的异常信息做特殊化处理,用来区分硬断言
336
+ :param desc:
337
+ :param test_func:
338
+ :return:
339
+ """
340
+ try:
341
+ assert_result = test_func()
342
+ print(f"✅ {desc if desc else assert_result}")
343
+
344
+ # 自定义异常类,捕捉 expect(参数) 参数为正确传入的情况
345
+ except AssertionUndefinedError as e:
346
+ print(PostManAssertMethod._format_assert_error(desc, e.args[0].msg))
347
+
348
+ except AssertionError as e:
349
+ # 如果断言失败,我们需要处理下断言信息
350
+ print(PostManAssertMethod._format_assert_error(desc, e.args[0].msg))
351
+
352
+ except AttributeError as e:
353
+ print("❌ {desc} | {exception_type}: {exception_msg}".format(
354
+ desc=desc,
355
+ exception_type="AssertionError",
356
+ exception_msg=e.args[0]
357
+ ))
358
+
359
+ except Exception as e:
360
+ print("⚠️ 未处理的异常错误,请检查: {}".format(e))
361
+
362
+ @property
363
+ def response(self):
364
+ """获取响应"""
365
+
366
+ class ResponseProxy:
367
+ def __init__(self, response):
368
+ self._response = response
369
+
370
+ def json(self):
371
+
372
+ # 判断响应类型
373
+ if isinstance(self._response, requests.Response):
374
+ dict_response = self._response.json()
375
+ elif isinstance(self._response, dict):
376
+ dict_response = self._response
377
+ else:
378
+ raise TypeError(f"Invalid response type: {type(self._response)}")
379
+
380
+ return Box(
381
+ dict_response,
382
+ default_box=True, # 是否在访问不存在的键时返回空的 Box 对象
383
+ default_box_attr=UNDEFINED, # 不存在的键返回默认值 undefined
384
+ )
385
+
386
+ def __getattr__(self, item):
387
+ # 代理其他属性和方法到原始 response 对象
388
+ return getattr(self._response, item)
389
+
390
+ return ResponseProxy(self._response)
391
+
392
+ @response.setter
393
+ def response(self, value):
394
+ """设置响应"""
395
+ self._response = value
396
+
397
+ @staticmethod
398
+ def expect(expected_value: Any):
399
+ return Expect(expected_value)
400
+
401
+
402
+ class MethodAssert(SoftAssert):
403
+ def __init__(self, expected_value: Any = None):
404
+ super().__init__()
405
+ self.__base_assert = BaseMethodAssert(expected_value)
406
+ self.expected = expected_value # 期望值
407
+
408
+ def _proxy_method(self, method_name, *args, **kwargs):
409
+ """代理方法,用于调用指定方法并捕获其中的异常"""
410
+ method = getattr(self.__base_assert, method_name)
411
+ try:
412
+ success_result = method(*args, **kwargs)
413
+ self.results_list.append(self.success_icon + success_result)
414
+ except AssertionError as e:
415
+ self.results_list.append(self.failure_icon + e.args[0])
416
+
417
+ def __getattr__(self, name):
418
+ """获取属性时自动调用代理方法"""
419
+ if name.startswith('_'): # 如果方法名以'_'开头,则不进行代理
420
+ pass
421
+ elif hasattr(self.__base_assert, name):
422
+ return lambda *args, **kwargs: self._proxy_method(name, *args, **kwargs)
423
+ else:
424
+ # 如果没有找到指定的方法,则抛出AttributeError异常
425
+ raise AttributeError(f"{type(self).__name__} object has no attribute {name}")
426
+
427
+
428
+ if __name__ == '__main__':
429
+ pm = PostManAssertMethod()
430
+ # pm.expect(1).to.equal(2)
431
+ pm.test("", lambda: pm.expect(1).to.equal(2))
432
+ pm.test("失败断言", lambda: pm.expect(1).to.equal(2))
433
+ pm.test("", lambda: pm.expect(1).to.equal(1))
434
+ pm.test("成功断言", lambda: pm.expect(1).to.equal(1))
435
+
436
+ method_assert = MethodAssert()
437
+ method_assert.check(1 == 1)
438
+ method_assert.check(1 == 2)
439
+ method_assert.equal(1, 1)
440
+ method_assert.equal(1, 2)
441
+ method_assert.fail()
@@ -0,0 +1,9 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: postman.py
6
+ Description:
7
+ -------------------------------------------------
8
+ """
9
+
@@ -0,0 +1,118 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: logger.py
6
+ Description: 基于 loguru 的企业级日志工具
7
+ -------------------------------------------------
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import sys
14
+
15
+ from loguru import logger
16
+ from typing import Optional
17
+
18
+ __all__ = ["LoggerManager"]
19
+
20
+
21
+ class LoggerManager:
22
+ """企业级日志管理器,负责配置日志、清理过期日志、控制台和文件日志的处理"""
23
+
24
+ def __init__(
25
+ self,
26
+ log_path: Optional[str] = None,
27
+ level: str = "DEBUG",
28
+ retention: str = "7 days",
29
+ rotation: str = "00:00",
30
+ format: str = "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level:<8}</level> | <level>{message}</level>",
31
+ compress: str = "zip",
32
+ async_write: bool = True,
33
+ log_size: str = "100 MB",
34
+ error_level: str = "WARNING",
35
+ ):
36
+ """
37
+ 初始化日志管理器,支持灵活配置。
38
+
39
+ :param log_path: 日志保存路径,如果为空使用默认路径
40
+ :param level: 日志记录级别
41
+ :param retention: 日志保留期限
42
+ :param rotation: 日志切割条件
43
+ :param format: 日志输出格式
44
+ :param compress: 日志压缩格式
45
+ :param async_write: 是否启用异步写入日志
46
+ :param log_size: 单个日志文件最大大小
47
+ :param error_level: 错误日志记录级别
48
+ """
49
+
50
+ self.log_path = log_path
51
+ self.level = level
52
+ self.retention = retention
53
+ self.rotation = rotation
54
+ self.format = format
55
+ self.compress = compress
56
+ self.async_write = async_write
57
+ self.log_size = log_size
58
+ self.error_level = error_level
59
+
60
+ def configure(self) -> logger.__class__:
61
+ """
62
+ 配置日志记录器,设置控制台输出和文件输出。
63
+ """
64
+
65
+ # 移除默认的日志配置
66
+ logger.remove()
67
+
68
+ # 控制台输出配置
69
+ logger.add(
70
+ sys.stdout,
71
+ level="DEBUG",
72
+ format="<level>{message}</level>",
73
+ colorize=True,
74
+ enqueue=True,
75
+ )
76
+
77
+ # 如果日志路径不为空,则进行文件输出配置
78
+ if self.log_path:
79
+ # 创建日志目录(如果不存在)
80
+ os.makedirs(self.log_path, exist_ok=True)
81
+
82
+ # 文件输出配置: 记录所有日志
83
+ logger.add(
84
+ os.path.join(self.log_path, '{time:YYYY-MM-DD}/logs.log'),
85
+ level=self.level,
86
+ format=self.format,
87
+ rotation=self.rotation, # 每天 00:00 分进行日志切割
88
+ compression=self.compress, # 压缩格式
89
+ retention=self.retention, # 日志保留期限
90
+ enqueue=self.async_write, # 异步日志写入
91
+ # max_size=self.log_size, # 单个日志文件最大大小
92
+ )
93
+
94
+ # 日志只记录错误及以上:默认仅记录 WARNING 及以上日志
95
+ logger.add(
96
+ os.path.join(self.log_path, '{time:YYYY-MM-DD}/error.log'),
97
+ level=self.error_level,
98
+ format=self.format,
99
+ rotation=self.rotation, # 每天 00:00 分进行日志切割
100
+ compression=self.compress, # 压缩格式
101
+ retention=self.retention, # 日志保留期限
102
+ enqueue=self.async_write, # 异步日志写入
103
+ # max_size=self.log_size, # 单个日志文件最大大小
104
+ )
105
+
106
+ return logger
107
+
108
+
109
+ # 示例
110
+ if __name__ == "__main__":
111
+ # 创建日志记录器实例
112
+ log = LoggerManager().configure()
113
+
114
+ log.debug("This is a debug message")
115
+ log.info("This is an info message")
116
+ log.warning("This is a warning message")
117
+ log.error("This is an error message")
118
+ log.success("This is a success message")
@@ -0,0 +1,21 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: __init__.py.py
6
+ Description:
7
+ -------------------------------------------------
8
+ """
9
+
10
+ from _hellchin_lib.logger import LoggerManager
11
+ from _hellchin_lib.assertion.base_soft_assert import SoftAssert
12
+ from _hellchin_lib.assertion.method_assert import MethodAssert
13
+ from _hellchin_lib.assertion.method_assert import PostManAssertMethod
14
+
15
+ # 对外暴露的模块
16
+ __all__ = [
17
+ 'LoggerManager',
18
+ 'SoftAssert',
19
+ 'MethodAssert',
20
+ 'PostManAssertMethod',
21
+ ]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hellchin_lib
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: A Python library for soft assertions and flexible testing.
5
5
  Author: hellchin
6
6
  Author-email: your.email@example.com
@@ -0,0 +1,22 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ _hellchin_lib/__init__.py
6
+ _hellchin_lib/logger.py
7
+ _hellchin_lib/assertion/__init__.py
8
+ _hellchin_lib/assertion/base_soft_assert.py
9
+ _hellchin_lib/assertion/logger.py
10
+ _hellchin_lib/assertion/method_assert.py
11
+ _hellchin_lib/assertion/postman.py
12
+ hellchin_lib/__init__.py
13
+ hellchin_lib.egg-info/PKG-INFO
14
+ hellchin_lib.egg-info/SOURCES.txt
15
+ hellchin_lib.egg-info/dependency_links.txt
16
+ hellchin_lib.egg-info/requires.txt
17
+ hellchin_lib.egg-info/top_level.txt
18
+ tests/__init__.py
19
+ tests/test_soft_assert/__init__.py
20
+ tests/test_soft_assert/test_demo.py
21
+ tests/test_soft_assert/test_method_assert.py
22
+ tests/test_soft_assert/test_soft_assert.py
@@ -1,2 +1,3 @@
1
+ _hellchin_lib
1
2
  hellchin_lib
2
3
  tests
@@ -0,0 +1,7 @@
1
+ [build-system]
2
+ requires = ["setuptools", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [tool.poetry]
6
+ readme = "README.md"
7
+ changelog = "CHANGELOG.md"
@@ -6,11 +6,13 @@
6
6
  Description: 包的元信息
7
7
  -------------------------------------------------
8
8
  """
9
+ from pathlib import Path
10
+
9
11
  from setuptools import setup, find_packages
10
12
 
11
13
  setup(
12
14
  name="hellchin_lib", # 包名
13
- version="0.1.0", # 版本号
15
+ version="0.1.2", # 版本号
14
16
  description="A Python library for soft assertions and flexible testing.", # 描述
15
17
  author="hellchin", # 作者
16
18
  author_email="your.email@example.com", # 作者邮箱
@@ -23,4 +25,6 @@ setup(
23
25
  "License :: OSI Approved :: MIT License",
24
26
  "Operating System :: OS Independent",
25
27
  ],
28
+ # long_description=(Path("README.md").read_text() + "\n\n" + Path("CHANGELOG.md").read_text()),
29
+ # long_description_content_type="text/markdown",
26
30
  )
@@ -0,0 +1,40 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: test_demo.py
6
+ Description:
7
+ -------------------------------------------------
8
+ """
9
+
10
+ from hellchin_lib import PostManAssertMethod, MethodAssert
11
+
12
+ pm = PostManAssertMethod()
13
+ pm.response = {
14
+ "a": 1
15
+ }
16
+
17
+ # raise Exception("测试")
18
+ pm_code_test = """
19
+ # pm.expect(1).to.equal(2)
20
+ pm.test("", lambda: pm.expect('1').to.equal(1))
21
+ pm.test("失败断言", lambda: pm.expect(1).to.equal(2))
22
+ pm.test("", lambda: pm.expect(1).to.equal(1))
23
+ pm.test("成功断言", lambda: pm.expect(1).to.equal(1))
24
+ res = pm.response.json()
25
+ pm.test("undefined 测试", lambda: pm.expect(res.b).to.equal(1))
26
+ # pm.expect(res.b).to.equal(1)
27
+ """
28
+
29
+ exec(pm_code_test, {"pm": pm})
30
+
31
+ ma_code_test = """
32
+ method_assert.check(1 == 1)
33
+ method_assert.check(1 == 2)
34
+ method_assert.equal(1, 1)
35
+ method_assert.equal(1, 2)
36
+ method_assert.exists(1)
37
+ method_assert.fail()
38
+ """
39
+
40
+ # exec(ma_code_test, {"method_assert": MethodAssert()})
@@ -0,0 +1,39 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: test_method_assert.py
6
+ Description: 测试代码
7
+ -------------------------------------------------
8
+ """
9
+ import unittest
10
+
11
+ import pytest
12
+
13
+ from _hellchin_lib.assertion.method_assert import MethodAssert
14
+
15
+
16
+ class TestMethodAssert:
17
+ def setUp(self) -> None:
18
+ self.expect = MethodAssert()
19
+
20
+ def tearDown(self) -> None:
21
+ pass
22
+
23
+ def test_equal(self):
24
+ expect = MethodAssert()
25
+ expect.equal(1, 1, assert_name="Check if 1 equals 1")
26
+ expect.result()
27
+
28
+ def test_equal_2(self):
29
+ expect = MethodAssert
30
+ expect(1).equal(2)
31
+
32
+ def test_not_equal(self):
33
+ expect = MethodAssert()
34
+ expect.not_equal(1, 1, "Check if 1 does not equal 2")
35
+ expect.result()
36
+
37
+
38
+ if __name__ == '__main__':
39
+ pytest.main()
@@ -0,0 +1,18 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: test_soft_assert.py
6
+ Description:
7
+ -------------------------------------------------
8
+ """
9
+ from _hellchin_lib.assertion import MethodAssert
10
+
11
+
12
+ def test_soft_assert():
13
+ method_assert = MethodAssert()
14
+ # 1. 直接调用方法断言的方法,手动输出断言结果
15
+ method_assert.equal(1, 1, assert_name="test")
16
+ method_assert.not_equal(1, "2", jsonpath="$.a")
17
+ method_assert.check(1 == 3)
18
+ # method_assert.report() # 调用方法断言的report方法,输出断言结果
File without changes
@@ -1,197 +0,0 @@
1
- # !/usr/bin/env python
2
- # -*- coding: utf-8 -*-
3
- """
4
- -------------------------------------------------
5
- File Name: method_assert.py
6
- Description: 具体断言逻辑实现
7
- -------------------------------------------------
8
-
9
- 继承 SoftAssert 类,扩展出具体的断言方法。
10
- 如 equal、not_equal、greater_than 等。
11
- """
12
-
13
- from typing import Union, Any
14
-
15
- # from .logger import logger
16
- from .base_soft_assert import SoftAssert
17
-
18
-
19
- # from apitesting.src.models import Assertion
20
-
21
-
22
- class MethodAssert(SoftAssert):
23
- """类型为json的响应断言,封装各种断言方法"""
24
-
25
- # # 支持的运算符列表,优先匹配长度较长的运算符
26
- # SUPPORTED_OPERATORS = ["not in", "in", ">=", "<=", "!=", "==", ">", "<"]
27
-
28
- # def __init__(self, response_json: dict, assert_data):
29
- # """
30
- # :param response_json: 响应的json数据
31
- # :param assert_data: 断言数据, 可以是字符串或者AssertData对象
32
- # """
33
- # super().__init__() # 初始化 SoftAssert
34
- # self.response_json = response_json
35
- # self.assert_data = self._parse_assert_data(assert_data)
36
- #
37
- # self.actual_value = json_handler.jsonpath_query(self.response_json, self.assert_data.jsonpath)[0]
38
- # self.jsonpath_expression = self.assert_data.jsonpath # 获取断言的jsonpath表达式
39
- # self.assert_name = self.assert_data.name # 获取断言名称
40
- # self.expected_value = self.assert_data.value # 获取断言的预期值
41
-
42
- def _parse_assert_data(self, assert_data: Union[str, dict]) -> dict:
43
- """
44
- 解析断言数据,支持字符串或 pydantic 模型
45
-
46
- :param assert_data: 可能是字符串表达式或 pydantic 模型
47
- :return: 解析后的 Assertion 对象
48
- """
49
- if isinstance(assert_data, dict): # Assertion
50
- return assert_data
51
- elif isinstance(assert_data, str):
52
- # 解析字符串格式,比如 `$.code > "200"`
53
- # return self._parse_string_assert(assert_data)
54
- raise ValueError(f"Unsupported assert_data type: {type(assert_data)}")
55
- else:
56
- raise ValueError(f"Unsupported assert_data type: {type(assert_data)}")
57
-
58
- @staticmethod
59
- def _generate_assert_messages(success_condition: str, fail_message: str, actual, expected) -> tuple:
60
- """
61
- 生成断言的成功和失败信息。
62
-
63
- :param success_condition: 成功条件描述
64
- :param fail_message: 失败消息模板
65
- :param actual: 实际值
66
- :param expected: 预期值
67
- :return: 成功信息和失败信息
68
- """
69
- assert_info_success = success_condition
70
- assert_info_fail = f"AssertionError: {fail_message.format(actual=repr(actual), expected=repr(expected))}"
71
- return assert_info_success, assert_info_fail
72
-
73
- def equal(self, actual, expected, assert_name=None, jsonpath: str = None):
74
- """
75
- 判断响应相等的逻辑。
76
- """
77
-
78
- success_message, fail_message = self._generate_assert_messages(
79
- assert_name or f"{jsonpath or actual} == {repr(expected)}",
80
- "expected {actual} to deeply equal {expected} ",
81
- actual, expected
82
- )
83
-
84
- # 执行断言并记录结果
85
- self.check(actual == expected, success_message, fail_message)
86
-
87
- def not_equal(self, actual, expected, assert_name=None, jsonpath: str = None):
88
- """
89
- 判断响应不相等的逻辑。
90
- """
91
-
92
- success_message, fail_message = self._generate_assert_messages(
93
- assert_name or f"{jsonpath or actual} != {repr(expected)}",
94
- "expected {actual} not to deeply equal {expected} ",
95
- actual, expected
96
- )
97
-
98
- # 执行断言并记录结果
99
- self.check(actual != expected, success_message, fail_message)
100
-
101
- def greater_than(self, actual, expected, assert_name=None, jsonpath: str = None):
102
- """
103
- 判断响应大于的逻辑。
104
- """
105
-
106
- success_message, fail_message = self._generate_assert_messages(
107
- assert_name or f"{jsonpath or actual} > {repr(expected)}",
108
- "expected {actual} to be greater than {expected} ",
109
- actual, expected
110
- )
111
-
112
- # 执行断言并记录结果
113
- self.check(actual > expected, success_message, fail_message)
114
-
115
- def greater_than_or_equal(self, actual, expected, *, assert_name=None, jsonpath: str = None) -> None:
116
- """
117
- 判断响应值是否大于或等于预期值的逻辑。
118
- """
119
-
120
- success_message, fail_message = self._generate_assert_messages(
121
- assert_name or f"{jsonpath or actual} >= {repr(expected)}",
122
- "expected {actual} to be greater than or equal to {expected} ",
123
- actual, expected
124
- )
125
-
126
- # 执行断言并记录结果
127
- self.check(actual >= expected, success_message, fail_message)
128
-
129
- def greater_than_or_equal_v2(self, actual, expected, *, assert_name=None, jsonpath: str = None) -> None:
130
- """
131
- 判断响应值是否大于或等于预期值的逻辑。
132
- """
133
-
134
- success_message, fail_message = self._generate_assert_messages(
135
- assert_name or f"{jsonpath or actual} >= {repr(expected)}",
136
- "expected {actual} to be greater than or equal to {expected} ",
137
- actual, expected
138
- )
139
-
140
- # 执行断言并记录结果
141
- self.check(actual >= expected, success_message, fail_message)
142
-
143
- def less_than(self, actual, expected, *, assert_name=None, jsonpath: str = None) -> None:
144
- """
145
- 判断响应小于的逻辑。
146
- """
147
-
148
- success_message, fail_message = self._generate_assert_messages(
149
- assert_name or f"{jsonpath or actual} < {repr(expected)}",
150
- "expected {actual} to be less than {expected} ",
151
- actual, expected
152
- )
153
-
154
- # 执行断言并记录结果
155
- self.check(actual < expected, success_message, fail_message)
156
-
157
- def less_than_or_equal(self, actual, expected, *, assert_name=None, jsonpath: str = None) -> None:
158
- """
159
- 判断响应小于或等于的逻辑。
160
- """
161
-
162
- success_message, fail_message = self._generate_assert_messages(
163
- assert_name or f"{jsonpath or actual} <= {repr(expected)}",
164
- "expected {actual} to be less than or equal to {expected} ",
165
- actual, expected
166
- )
167
-
168
- # 执行断言并记录结果
169
- self.check(actual <= expected, success_message, fail_message)
170
-
171
- def exists(self, actual, expected, *, assert_name=None, jsonpath: str = None) -> None:
172
- """
173
- 判断 key 是否存在的逻辑。
174
- """
175
-
176
- success_message, fail_message = self._generate_assert_messages(
177
- assert_name or f"{jsonpath or actual} exists",
178
- "expected {actual} to exist",
179
- actual, expected
180
- )
181
-
182
- # 执行断言并记录结果
183
- self.check(actual == expected, success_message, fail_message)
184
-
185
- def not_exists(self, actual, expected, *, assert_name=None, jsonpath: str = None) -> None:
186
- """
187
- 判断 key 不存在的逻辑。
188
- """
189
-
190
- success_message, fail_message = self._generate_assert_messages(
191
- assert_name or f"{jsonpath or actual} not exists",
192
- "expected {actual} to not exist",
193
- actual, expected
194
- )
195
-
196
- # 执行断言并记录结果
197
- self.check(actual != expected, success_message, fail_message)
@@ -1,17 +0,0 @@
1
- LICENSE
2
- README.md
3
- pyproject.toml
4
- setup.py
5
- hellchin_lib/__init__.py
6
- hellchin_lib.egg-info/PKG-INFO
7
- hellchin_lib.egg-info/SOURCES.txt
8
- hellchin_lib.egg-info/dependency_links.txt
9
- hellchin_lib.egg-info/requires.txt
10
- hellchin_lib.egg-info/top_level.txt
11
- hellchin_lib/soft_assert/__init__.py
12
- hellchin_lib/soft_assert/base_soft_assert.py
13
- hellchin_lib/soft_assert/logger.py
14
- hellchin_lib/soft_assert/method_assert.py
15
- tests/__init__.py
16
- tests/test_soft_assert/__init__.py
17
- tests/test_soft_assert/test_assertions.py
@@ -1,3 +0,0 @@
1
- [build-system]
2
- requires = ["setuptools", "wheel"]
3
- build-backend = "setuptools.build_meta"
@@ -1,33 +0,0 @@
1
- # !/usr/bin/env python
2
- # -*- coding: utf-8 -*-
3
- """
4
- -------------------------------------------------
5
- File Name: test_assertions.py
6
- Description: 测试代码
7
- -------------------------------------------------
8
- """
9
-
10
- from hellchin_lib.soft_assert.method_assert import MethodAssert
11
-
12
-
13
- def test_soft_assert_method():
14
- method_assert = MethodAssert()
15
-
16
- with method_assert:
17
- method_assert.equal(1, 1, "Check if 1 equals 1")
18
- method_assert.not_equal(1, 2, "Check if 1 does not equal 2")
19
- method_assert.greater_than(5, 3, "Check if 5 is greater than 3")
20
- # method_assert.equal(1, 2, "This will fail") # 故意失败
21
-
22
-
23
- def test_soft_assert():
24
- method_assert = MethodAssert()
25
- # 1. 直接调用方法断言的方法,手动输出断言结果
26
- method_assert.equal(1, 1, assert_name="test")
27
- method_assert.not_equal(1, "2", jsonpath="$.a")
28
- # method_assert.check(1 == 3)
29
- method_assert.report() # 调用方法断言的report方法,输出断言结果
30
-
31
-
32
- if __name__ == '__main__':
33
- test_soft_assert()
File without changes
File without changes