hellchin-lib 0.1.0__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.
File without changes
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.1
2
+ Name: hellchin_lib
3
+ Version: 0.1.0
4
+ Summary: A Python library for soft assertions and flexible testing.
5
+ Author: hellchin
6
+ Author-email: your.email@example.com
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ License-File: LICENSE
11
+ Requires-Dist: pytest>=6.0.0
File without changes
@@ -0,0 +1,8 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: __init__.py.py
6
+ Description:
7
+ -------------------------------------------------
8
+ """
@@ -0,0 +1,17 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: __init__.py.py
6
+ Description:
7
+ -------------------------------------------------
8
+ """
9
+
10
+ from .base_soft_assert import SoftAssert
11
+ from .method_assert import MethodAssert
12
+
13
+ # 定义包的统一接口
14
+ __all__ = [
15
+ "SoftAssert",
16
+ "MethodAssert"
17
+ ]
@@ -0,0 +1,100 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: base_soft_assert.py
6
+ Description: 自定义软断言类,支持灵活调用和集成
7
+ -------------------------------------------------
8
+ 1. 提供基础的断言功能,包括记录、检查和报告断言结果。
9
+ 2. 支持单独使用或作为上下文管理器使用。
10
+ """
11
+
12
+ import inspect
13
+
14
+ import pytest
15
+
16
+
17
+ # from apitesting.src.models import Assertion
18
+ # from .logger import logger
19
+
20
+
21
+ class SoftAssert:
22
+ """自定义软断言类,支持灵活调用和集成"""
23
+
24
+ def __init__(self):
25
+ self.results_list = [] # 记录所有断言的结果
26
+ self.has_failures = False # 是否存在失败断言
27
+
28
+ def check(self, condition, assert_name=None, error_message="AssertionError: None"):
29
+ """
30
+ 记录断言结果。
31
+
32
+ :param condition: 表达式或条件,结果应为布尔值
33
+ :param assert_name: 断言名称,默认为None,自动生成
34
+ :param error_message: 如果断言失败时的错误消息
35
+ """
36
+ # 获取调用代码的表达式
37
+ frame = inspect.currentframe().f_back
38
+ code_context = inspect.getframeinfo(frame).code_context
39
+ if code_context:
40
+ expression = code_context[0].strip()
41
+ # print(expression)
42
+ # 提取传入的第一个参数(表达式)
43
+ expression = expression[expression.find("(") + 1: expression.rfind(",", 0)]
44
+ # print(expression)
45
+ else:
46
+ expression = str(condition)
47
+
48
+ # 如果断言名称为None,则使用表达式作为断言名称
49
+ # print(type(assert_name))
50
+ assert_info = assert_name or f"{expression}"
51
+
52
+ # 执行断言
53
+ try:
54
+ assert condition, error_message
55
+ # 记录成功的断言
56
+ self.results_list.append("✅ " + assert_info)
57
+ except AssertionError as ae:
58
+ # 记录失败的断言
59
+ failure_message = "❌ " + ' | '.join([assert_info, error_message])
60
+ self.results_list.append(failure_message)
61
+ self.has_failures = True # 标记存在失败断言
62
+
63
+ def report(self, clear=True):
64
+ """
65
+ 报告所有断言结果。
66
+ "主动调用表示将所有的结果输出"
67
+
68
+ :param clear: 是否清空历史结果,默认清空
69
+ :raises AssertionError: 如果有失败断言
70
+ """
71
+ failure_count = len([r for r in self.results_list if r.startswith("❌")])
72
+ success_count = len([r for r in self.results_list if r.startswith("✅")])
73
+
74
+ # 报告结果
75
+ report_messages = "\n".join([f" [{i + 1}] {msg}" for i, msg in enumerate(self.results_list)])
76
+ if clear:
77
+ self.results_list = [] # 清空结果
78
+
79
+ if self.has_failures:
80
+ # 使用 pytest.fail 避免过多堆栈信息
81
+ 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, # 避免输出多余的堆栈信息
86
+ )
87
+ else:
88
+ print(
89
+ f"Soft assertion summary:\n"
90
+ f"{success_count} success(es):\n"
91
+ f"{report_messages}"
92
+ )
93
+
94
+ def __enter__(self):
95
+ """进入上下文"""
96
+ return self
97
+
98
+ def __exit__(self, exc_type, exc_val, exc_tb):
99
+ """退出上下文时自动报告断言结果"""
100
+ self.report()
@@ -0,0 +1,17 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: logger.py
6
+ Description: 日志配置
7
+ -------------------------------------------------
8
+ """
9
+
10
+ import logging
11
+
12
+ # Configure logging
13
+ logging.basicConfig(
14
+ level=logging.INFO,
15
+ format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
16
+ )
17
+ logger = logging.getLogger("SoftAssert")
@@ -0,0 +1,197 @@
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)
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.1
2
+ Name: hellchin_lib
3
+ Version: 0.1.0
4
+ Summary: A Python library for soft assertions and flexible testing.
5
+ Author: hellchin
6
+ Author-email: your.email@example.com
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ License-File: LICENSE
11
+ Requires-Dist: pytest>=6.0.0
@@ -0,0 +1,17 @@
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
@@ -0,0 +1 @@
1
+ pytest>=6.0.0
@@ -0,0 +1,2 @@
1
+ hellchin_lib
2
+ tests
@@ -0,0 +1,3 @@
1
+ [build-system]
2
+ requires = ["setuptools", "wheel"]
3
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,26 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: setup.py
6
+ Description: 包的元信息
7
+ -------------------------------------------------
8
+ """
9
+ from setuptools import setup, find_packages
10
+
11
+ setup(
12
+ name="hellchin_lib", # 包名
13
+ version="0.1.0", # 版本号
14
+ description="A Python library for soft assertions and flexible testing.", # 描述
15
+ author="hellchin", # 作者
16
+ author_email="your.email@example.com", # 作者邮箱
17
+ packages=find_packages(), # 包列表: 自动查找所有包含__init__.py文件的目录
18
+ install_requires=[
19
+ "pytest>=6.0.0", # 依赖的包
20
+ ],
21
+ classifiers=[ # 分类器列表
22
+ "Programming Language :: Python :: 3",
23
+ "License :: OSI Approved :: MIT License",
24
+ "Operating System :: OS Independent",
25
+ ],
26
+ )
@@ -0,0 +1,8 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: __init__.py.py
6
+ Description:
7
+ -------------------------------------------------
8
+ """
@@ -0,0 +1,8 @@
1
+ # !/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ -------------------------------------------------
5
+ File Name: __init__.py.py
6
+ Description:
7
+ -------------------------------------------------
8
+ """
@@ -0,0 +1,33 @@
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()