funcguard 0.1.1__py3-none-any.whl → 0.1.4__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.
Potentially problematic release.
This version of funcguard might be problematic. Click here for more details.
- funcguard/__init__.py +11 -2
- funcguard/core.py +8 -1
- funcguard/printer.py +32 -0
- funcguard/tools.py +126 -25
- {funcguard-0.1.1.dist-info → funcguard-0.1.4.dist-info}/METADATA +102 -8
- funcguard-0.1.4.dist-info/RECORD +13 -0
- tests/test_tools.py +17 -8
- funcguard-0.1.1.dist-info/RECORD +0 -12
- {funcguard-0.1.1.dist-info → funcguard-0.1.4.dist-info}/LICENSE +0 -0
- {funcguard-0.1.1.dist-info → funcguard-0.1.4.dist-info}/WHEEL +0 -0
- {funcguard-0.1.1.dist-info → funcguard-0.1.4.dist-info}/top_level.txt +0 -0
funcguard/__init__.py
CHANGED
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
from .core import timeout_handler, retry_function
|
|
2
|
-
from .tools import send_request
|
|
2
|
+
from .tools import send_request, time_log, time_diff
|
|
3
|
+
from .printer import print_block, print_line
|
|
3
4
|
|
|
4
5
|
__author__ = "ruocen"
|
|
5
6
|
|
|
6
7
|
# 暴露主要接口
|
|
7
|
-
__all__ = [
|
|
8
|
+
__all__ = [
|
|
9
|
+
"timeout_handler",
|
|
10
|
+
"retry_function",
|
|
11
|
+
"send_request",
|
|
12
|
+
"time_log",
|
|
13
|
+
"time_diff",
|
|
14
|
+
"print_block",
|
|
15
|
+
"print_line",
|
|
16
|
+
]
|
funcguard/core.py
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
class FuncguardTimeoutError(Exception):
|
|
2
|
+
"""
|
|
3
|
+
funcguard库专用的超时异常类。
|
|
4
|
+
|
|
5
|
+
为了避免与concurrent.futures.TimeoutError和Python内置TimeoutError的命名冲突,
|
|
6
|
+
特定义此异常类来明确表示这是funcguard库抛出的函数执行超时异常。
|
|
7
|
+
这样用户可以清晰地区分异常来源,并进行针对性的异常处理。
|
|
8
|
+
"""
|
|
2
9
|
pass
|
|
3
10
|
|
|
4
11
|
import time
|
|
@@ -55,7 +62,7 @@ def retry_function( func , max_retries = 5 , execute_timeout = 90 , task_name =
|
|
|
55
62
|
result = timeout_handler( func , args = args , kwargs = kwargs , execution_timeout = current_timeout )
|
|
56
63
|
return result # 如果调用成功,则返回结果
|
|
57
64
|
|
|
58
|
-
except
|
|
65
|
+
except Exception as e :
|
|
59
66
|
last_exception = e
|
|
60
67
|
retry_count += 1
|
|
61
68
|
print( e )
|
funcguard/printer.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
# 打印分隔线
|
|
4
|
+
def print_line(separator_char: str = "-", separator_length: int = 40) -> None:
|
|
5
|
+
"""
|
|
6
|
+
打印分隔线,用于分隔不同的打印块
|
|
7
|
+
|
|
8
|
+
:param separator_char: 分隔符字符,默认为'-'
|
|
9
|
+
:param separator_length: 分隔符长度,默认为40
|
|
10
|
+
"""
|
|
11
|
+
separator = separator_char * separator_length
|
|
12
|
+
print(separator)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
# 块打印
|
|
16
|
+
def print_block(title: str, content: Any, separator_char: str = "-", separator_length: int = 40) -> None:
|
|
17
|
+
"""
|
|
18
|
+
使用分隔符打印标题和内容,便于查看
|
|
19
|
+
|
|
20
|
+
:param title: 标题
|
|
21
|
+
:param content: 打印的内容
|
|
22
|
+
:param separator_char: 分隔符字符,默认为'-'
|
|
23
|
+
:param separator_length: 分隔符长度,默认为40
|
|
24
|
+
"""
|
|
25
|
+
print_line(separator_char, separator_length)
|
|
26
|
+
|
|
27
|
+
if title:
|
|
28
|
+
print(f"{title} :")
|
|
29
|
+
print(content)
|
|
30
|
+
|
|
31
|
+
print_line(separator_char, separator_length)
|
|
32
|
+
# print() # 添加一个空行便于阅读
|
funcguard/tools.py
CHANGED
|
@@ -1,13 +1,23 @@
|
|
|
1
1
|
import json
|
|
2
2
|
import requests
|
|
3
|
-
from
|
|
4
|
-
|
|
3
|
+
from datetime import datetime, timezone, timedelta
|
|
4
|
+
from typing import Optional, Dict, Any, Union
|
|
5
|
+
from .core import retry_function
|
|
6
|
+
|
|
5
7
|
|
|
6
8
|
# 发起请求
|
|
7
|
-
def send_request(
|
|
8
|
-
|
|
9
|
+
def send_request(
|
|
10
|
+
method: str,
|
|
11
|
+
url: str,
|
|
12
|
+
headers: Dict[str, str],
|
|
13
|
+
data: Optional[Any] = None,
|
|
14
|
+
return_type: str = "json",
|
|
15
|
+
timeout: int = 60,
|
|
16
|
+
auto_retry: Optional[Dict[str, Any]] = None,
|
|
17
|
+
) -> Union[Dict, str, requests.Response]:
|
|
18
|
+
"""
|
|
9
19
|
发送HTTP请求的通用函数
|
|
10
|
-
|
|
20
|
+
|
|
11
21
|
:param method: HTTP方法(GET, POST等)
|
|
12
22
|
:param url: 请求URL
|
|
13
23
|
:param headers: 请求头
|
|
@@ -17,30 +27,121 @@ def send_request( method , url , headers , data = None , return_type = "json" ,
|
|
|
17
27
|
:param auto_retry: 自动重试配置,格式为:
|
|
18
28
|
{"task_name": "任务名称", "max_retries": 最大重试次数, "execute_timeout": 执行超时时间}
|
|
19
29
|
:return: 请求结果
|
|
20
|
-
|
|
21
|
-
if data is None
|
|
22
|
-
payload = {
|
|
23
|
-
else
|
|
24
|
-
if (isinstance(
|
|
25
|
-
payload = json.dumps(
|
|
26
|
-
else
|
|
30
|
+
"""
|
|
31
|
+
if data is None:
|
|
32
|
+
payload = {}
|
|
33
|
+
else:
|
|
34
|
+
if (isinstance(data, dict) or isinstance(data, list)) and data != {}:
|
|
35
|
+
payload = json.dumps(data, ensure_ascii=False)
|
|
36
|
+
else:
|
|
27
37
|
payload = data
|
|
28
|
-
if auto_retry is None
|
|
29
|
-
response = requests.request(
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
38
|
+
if auto_retry is None:
|
|
39
|
+
response = requests.request(
|
|
40
|
+
method, url, headers=headers, data=payload, timeout=timeout
|
|
41
|
+
)
|
|
42
|
+
else:
|
|
43
|
+
max_retries = auto_retry.get("max_retries", 5)
|
|
44
|
+
execute_timeout = auto_retry.get("execute_timeout", 90)
|
|
45
|
+
task_name = auto_retry.get("task_name", "")
|
|
46
|
+
response = retry_function(
|
|
47
|
+
requests.request,
|
|
48
|
+
max_retries,
|
|
49
|
+
execute_timeout,
|
|
50
|
+
task_name,
|
|
51
|
+
method,
|
|
52
|
+
url,
|
|
53
|
+
headers=headers,
|
|
54
|
+
data=payload,
|
|
55
|
+
timeout=timeout,
|
|
56
|
+
)
|
|
36
57
|
|
|
37
58
|
if response is None:
|
|
38
59
|
raise ValueError("请求返回的响应为None")
|
|
39
|
-
|
|
40
|
-
if return_type == "json"
|
|
60
|
+
|
|
61
|
+
if return_type == "json":
|
|
41
62
|
result = response.json()
|
|
42
|
-
elif return_type == "response"
|
|
63
|
+
elif return_type == "response":
|
|
43
64
|
return response
|
|
44
|
-
else
|
|
65
|
+
else:
|
|
45
66
|
result = response.text
|
|
46
|
-
return result
|
|
67
|
+
return result
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# 打印时间
|
|
71
|
+
def time_log(message, i = 0, max_num = 0, s_time = None) :
|
|
72
|
+
"""
|
|
73
|
+
打印带时间戳的日志信息,支持进度显示和预计完成时间
|
|
74
|
+
|
|
75
|
+
:param message: 日志消息
|
|
76
|
+
:param i: 当前进度(从0开始)
|
|
77
|
+
:param max_num: 总进度数量
|
|
78
|
+
:param s_time: 开始时间,用于计算预计完成时间
|
|
79
|
+
:return: None
|
|
80
|
+
"""
|
|
81
|
+
now = datetime.now( timezone( timedelta( hours = 8 ) ) )
|
|
82
|
+
time_log = "{:02d}:{:02d}:{:02d}".format( now.hour, now.minute, now.second )
|
|
83
|
+
if i < 2 :
|
|
84
|
+
print( time_log + " " + message )
|
|
85
|
+
else :
|
|
86
|
+
if max_num == 0 :
|
|
87
|
+
text = "{}".format( i )
|
|
88
|
+
else :
|
|
89
|
+
text = "{}/{}".format( i, max_num )
|
|
90
|
+
# 检查是否应该显示预计完成时间和剩余时间
|
|
91
|
+
if i % 10 == 0 and s_time is not None and i < max_num :
|
|
92
|
+
duration = now - s_time
|
|
93
|
+
ev_duration = duration / i # 每项平均耗时
|
|
94
|
+
remaining_items = max_num - i
|
|
95
|
+
time_left = ev_duration * remaining_items
|
|
96
|
+
end_time = now + time_left
|
|
97
|
+
end_time_str = end_time.strftime( "%Y-%m-%d %H:%M" )
|
|
98
|
+
remaining_time_str = str( timedelta( seconds = int( time_left.total_seconds() ) ) )
|
|
99
|
+
text = text + "({})etr {}".format( end_time_str, remaining_time_str )
|
|
100
|
+
print( time_log + " " + message + " " + text )
|
|
101
|
+
return
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# 计算持续时间
|
|
105
|
+
def time_diff(s_time = None, max_num = 0, language = "cn") :
|
|
106
|
+
"""
|
|
107
|
+
计算并打印任务执行时间统计信息
|
|
108
|
+
|
|
109
|
+
:param s_time: 开始时间
|
|
110
|
+
:param max_num: 任务数量
|
|
111
|
+
:param language: 语言选择("cn"中文,其他为英文)
|
|
112
|
+
:return: 如果s_time为None则返回当前时间,否则返回None
|
|
113
|
+
"""
|
|
114
|
+
# 获取当前时间并转换为北京时间
|
|
115
|
+
now = datetime.now( timezone( timedelta( hours = 8 ) ) )
|
|
116
|
+
|
|
117
|
+
if s_time is None :
|
|
118
|
+
return now
|
|
119
|
+
|
|
120
|
+
e_time = now
|
|
121
|
+
duration = e_time - s_time
|
|
122
|
+
hours = duration.seconds // 3600
|
|
123
|
+
duration_minutes = (duration.seconds % 3600) // 60
|
|
124
|
+
seconds = duration.seconds % 60
|
|
125
|
+
result = f"{hours:02d}:{duration_minutes:02d}:{seconds:02d}"
|
|
126
|
+
|
|
127
|
+
# 将时间差转化为分钟
|
|
128
|
+
minutes = round( duration.total_seconds() / 60 )
|
|
129
|
+
if max_num == 0 :
|
|
130
|
+
if language == "cn" :
|
|
131
|
+
print( "总耗时:{}".format( result ) )
|
|
132
|
+
else :
|
|
133
|
+
print( "Total time: {}".format( result ) )
|
|
134
|
+
else :
|
|
135
|
+
eve_minutes = round( minutes / max_num, 3 )
|
|
136
|
+
if language == "cn" :
|
|
137
|
+
print( "开始时间:{},结束时间:{}".format( s_time.strftime( "%Y-%m-%d %H:%M" ),
|
|
138
|
+
e_time.strftime( "%Y-%m-%d %H:%M" ) ) )
|
|
139
|
+
print( "总耗时:{},累计:{}分钟,数量;{},平均耗时:{}分钟".format( result, minutes, max_num, eve_minutes ) )
|
|
140
|
+
else :
|
|
141
|
+
print( "Start time:{},End time:{}".format( s_time.strftime( "%Y-%m-%d %H:%M" ),
|
|
142
|
+
e_time.strftime( "%Y-%m-%d %H:%M" ) ) )
|
|
143
|
+
print( "Total time: {},Total minutes: {},Number: {},Average time: {} minutes".format( result, minutes,
|
|
144
|
+
max_num,
|
|
145
|
+
eve_minutes ) )
|
|
146
|
+
|
|
147
|
+
return
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: funcguard
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.4
|
|
4
4
|
Summary: A funcguard for Python.
|
|
5
5
|
Home-page: https://github.com/tinycen/funcguard
|
|
6
6
|
Author: tinycen
|
|
@@ -22,13 +22,11 @@ FuncGuard是一个Python库,提供了函数执行超时控制和重试机制
|
|
|
22
22
|
- 函数执行超时控制
|
|
23
23
|
- 函数执行失败自动重试
|
|
24
24
|
- HTTP请求封装(支持自动重试)
|
|
25
|
+
- 格式化打印工具(分隔线和块打印)
|
|
26
|
+
- 时间日志记录和耗时统计
|
|
25
27
|
|
|
26
28
|
## 安装/升级
|
|
27
29
|
|
|
28
|
-
```bash
|
|
29
|
-
pip install funcguard
|
|
30
|
-
```
|
|
31
|
-
|
|
32
30
|
```bash
|
|
33
31
|
pip install --upgrade funcguard
|
|
34
32
|
```
|
|
@@ -41,7 +39,7 @@ pip install --upgrade funcguard
|
|
|
41
39
|
使用`timeout_handler`函数可以控制函数的执行时间,防止函数运行时间过长:
|
|
42
40
|
|
|
43
41
|
```python
|
|
44
|
-
from funcguard
|
|
42
|
+
from funcguard import timeout_handler
|
|
45
43
|
|
|
46
44
|
def long_running_function():
|
|
47
45
|
# 模拟一个耗时操作
|
|
@@ -62,7 +60,7 @@ except TimeoutError as e:
|
|
|
62
60
|
使用`retry_function`函数可以在函数执行失败时自动重试:
|
|
63
61
|
|
|
64
62
|
```python
|
|
65
|
-
from funcguard
|
|
63
|
+
from funcguard import retry_function
|
|
66
64
|
|
|
67
65
|
def unstable_function():
|
|
68
66
|
# 模拟一个可能失败的操作
|
|
@@ -84,7 +82,7 @@ except Exception as e:
|
|
|
84
82
|
使用`send_request`函数发送HTTP请求,支持自动重试:
|
|
85
83
|
|
|
86
84
|
```python
|
|
87
|
-
from funcguard
|
|
85
|
+
from funcguard import send_request
|
|
88
86
|
|
|
89
87
|
# 不使用重试
|
|
90
88
|
response = send_request(
|
|
@@ -111,6 +109,63 @@ response = send_request(
|
|
|
111
109
|
print(response)
|
|
112
110
|
```
|
|
113
111
|
|
|
112
|
+
### 格式化打印
|
|
113
|
+
|
|
114
|
+
使用`print_line`和`print_block`函数进行格式化打印,便于查看和调试:
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
from funcguard import print_line, print_block
|
|
118
|
+
|
|
119
|
+
# 打印分隔线
|
|
120
|
+
print_line() # 默认使用40个'-'字符
|
|
121
|
+
print_line("*", 30) # 使用30个'*'字符
|
|
122
|
+
|
|
123
|
+
# 打印块内容
|
|
124
|
+
print_block("用户信息", {"name": "张三", "age": 25})
|
|
125
|
+
|
|
126
|
+
# 自定义分隔符
|
|
127
|
+
print_block("配置信息", {"debug": True, "port": 8080}, "=", 50)
|
|
128
|
+
|
|
129
|
+
# 打印复杂内容
|
|
130
|
+
result = {
|
|
131
|
+
"status": "success",
|
|
132
|
+
"data": [1, 2, 3, 4, 5],
|
|
133
|
+
"message": "操作完成"
|
|
134
|
+
}
|
|
135
|
+
print_block("API响应", result)
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### 时间日志记录
|
|
139
|
+
|
|
140
|
+
使用`time_log`和`time_diff`函数记录任务执行时间和统计信息:
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from funcguard import time_log, time_diff
|
|
144
|
+
|
|
145
|
+
# 获取开始时间
|
|
146
|
+
start_time = time_diff()
|
|
147
|
+
|
|
148
|
+
# 记录任务开始
|
|
149
|
+
time_log("开始处理数据", 0, 100, start_time)
|
|
150
|
+
|
|
151
|
+
# 模拟处理过程
|
|
152
|
+
import time
|
|
153
|
+
for i in range(1, 101):
|
|
154
|
+
time.sleep(0.1) # 模拟处理时间
|
|
155
|
+
if i % 20 == 0:
|
|
156
|
+
time_log(f"处理进度", i, 100, start_time) # 显示进度和预计完成时间
|
|
157
|
+
|
|
158
|
+
# 记录任务完成并打印统计信息
|
|
159
|
+
time_log("数据处理完成", 100, 100, start_time)
|
|
160
|
+
time_diff(start_time, 100, "cn") # 中文显示统计信息
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
时间日志功能特点:
|
|
164
|
+
- 自动显示北京时间(UTC+8)
|
|
165
|
+
- 支持进度显示和预计完成时间计算
|
|
166
|
+
- 提供中英文双语统计信息
|
|
167
|
+
- 可显示总耗时、平均耗时等详细统计
|
|
168
|
+
|
|
114
169
|
## API文档
|
|
115
170
|
|
|
116
171
|
### funcguard.core
|
|
@@ -152,6 +207,45 @@ print(response)
|
|
|
152
207
|
- **返回值**: 根据return_type参数返回不同格式的响应数据
|
|
153
208
|
- **异常**: 当请求失败且重试次数用尽后,抛出相应的异常
|
|
154
209
|
|
|
210
|
+
#### time_log(message, i=0, max_num=0, s_time=None)
|
|
211
|
+
|
|
212
|
+
- **参数**:
|
|
213
|
+
- `message`: 日志消息
|
|
214
|
+
- `i`: 当前进度(从0开始),默认为0
|
|
215
|
+
- `max_num`: 总进度数量,默认为0
|
|
216
|
+
- `s_time`: 开始时间,用于计算预计完成时间,默认为None
|
|
217
|
+
- **返回值**: 无
|
|
218
|
+
- **功能**: 打印带时间戳的日志信息,支持进度显示和预计完成时间计算
|
|
219
|
+
|
|
220
|
+
#### time_diff(s_time=None, max_num=0, language="cn")
|
|
221
|
+
|
|
222
|
+
- **参数**:
|
|
223
|
+
- `s_time`: 开始时间,默认为None
|
|
224
|
+
- `max_num`: 任务数量,默认为0
|
|
225
|
+
- `language`: 语言选择("cn"中文,其他为英文),默认为"cn"
|
|
226
|
+
- **返回值**: 如果s_time为None则返回当前时间,否则返回None
|
|
227
|
+
- **功能**: 计算并打印任务执行时间统计信息,支持中英文双语输出
|
|
228
|
+
|
|
229
|
+
### funcguard.printer
|
|
230
|
+
|
|
231
|
+
#### print_line(separator_char: str = "-", separator_length: int = 40) -> None
|
|
232
|
+
|
|
233
|
+
- **参数**:
|
|
234
|
+
- `separator_char`: 分隔符字符,默认为'-'
|
|
235
|
+
- `separator_length`: 分隔符长度,默认为40
|
|
236
|
+
- **返回值**: 无
|
|
237
|
+
- **功能**: 打印分隔线,用于分隔不同的打印块
|
|
238
|
+
|
|
239
|
+
#### print_block(title: str, content: Any, separator_char: str = "-", separator_length: int = 40) -> None
|
|
240
|
+
|
|
241
|
+
- **参数**:
|
|
242
|
+
- `title`: 标题
|
|
243
|
+
- `content`: 打印的内容
|
|
244
|
+
- `separator_char`: 分隔符字符,默认为'-'
|
|
245
|
+
- `separator_length`: 分隔符长度,默认为40
|
|
246
|
+
- **返回值**: 无
|
|
247
|
+
- **功能**: 使用分隔符打印标题和内容,便于查看
|
|
248
|
+
|
|
155
249
|
## 许可证
|
|
156
250
|
|
|
157
251
|
MIT License
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
funcguard/__init__.py,sha256=iyM7STP-KSxUn7PUaBWEQcZus2XskiGTTweI4qjoETE,342
|
|
2
|
+
funcguard/core.py,sha256=-rFRkE-udxM0wxlcv9Qi_yIQBRdVrGgwza-LYQsVRLg,3632
|
|
3
|
+
funcguard/printer.py,sha256=c93x6Z-6a7nnead_Rk_f0Xe23kdVdSj4qaxsuBMKfd0,958
|
|
4
|
+
funcguard/tools.py,sha256=S7t46KurOedvVKCVoFLW_CoDvLSC__lfVLUYBse5ABM,5433
|
|
5
|
+
tests/__init__.py,sha256=VW6FdWdSC_PL3zEtpkRQfUMf6yVD2OfwtSds82jawTs,26
|
|
6
|
+
tests/run_test.py,sha256=-SLdUV7gDifLxuCCAlU8qLxYMx6KpK4cxfG4UYfUIgA,1005
|
|
7
|
+
tests/test_core.py,sha256=aZNbQK4eTnnkCI4c2txYZNTcYIUhSJvII5Dvn0vNJKo,3732
|
|
8
|
+
tests/test_tools.py,sha256=g9dK-WW1s5SIobscRuelufBfPrSgNLZU8d1AJteBpd0,5609
|
|
9
|
+
funcguard-0.1.4.dist-info/LICENSE,sha256=jgOquECfjiXp5xXQ2zuzItDr4XDBLan-bIzIXl1lS4Y,1064
|
|
10
|
+
funcguard-0.1.4.dist-info/METADATA,sha256=ayz3u_YGwUqH3ziy-awhbPMjWgFdPWYCxSQmTZJF-HI,7175
|
|
11
|
+
funcguard-0.1.4.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
|
|
12
|
+
funcguard-0.1.4.dist-info/top_level.txt,sha256=7wL9mWT062DttKNO7Wi1wYWTZilR2AOPRO0rE3gvtB4,16
|
|
13
|
+
funcguard-0.1.4.dist-info/RECORD,,
|
tests/test_tools.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import json
|
|
2
2
|
import unittest
|
|
3
3
|
from unittest.mock import patch, MagicMock
|
|
4
|
+
from typing import Any, Optional, Dict
|
|
4
5
|
import requests
|
|
5
6
|
|
|
6
7
|
from funcguard.tools import send_request
|
|
@@ -9,12 +10,16 @@ from funcguard.tools import send_request
|
|
|
9
10
|
class MockResponse:
|
|
10
11
|
"""模拟requests响应"""
|
|
11
12
|
|
|
12
|
-
|
|
13
|
+
json_data: Dict[str, Any]
|
|
14
|
+
text: str
|
|
15
|
+
status_code: int
|
|
16
|
+
|
|
17
|
+
def __init__(self, json_data: Optional[Dict[str, Any]] = None, text: str = "", status_code: int = 200):
|
|
13
18
|
self.json_data = json_data or {}
|
|
14
19
|
self.text = text
|
|
15
20
|
self.status_code = status_code
|
|
16
21
|
|
|
17
|
-
def json(self):
|
|
22
|
+
def json(self) -> Dict[str, Any]:
|
|
18
23
|
return self.json_data
|
|
19
24
|
|
|
20
25
|
|
|
@@ -97,7 +102,7 @@ class TestSendRequest(unittest.TestCase):
|
|
|
97
102
|
|
|
98
103
|
mock_request.assert_called_once()
|
|
99
104
|
|
|
100
|
-
@patch('funcguard.
|
|
105
|
+
@patch('funcguard.tools.retry_function')
|
|
101
106
|
@patch('requests.request')
|
|
102
107
|
def test_auto_retry_enabled(self, mock_request, mock_retry):
|
|
103
108
|
"""测试启用自动重试"""
|
|
@@ -117,12 +122,16 @@ class TestSendRequest(unittest.TestCase):
|
|
|
117
122
|
}
|
|
118
123
|
)
|
|
119
124
|
|
|
120
|
-
# 验证结果
|
|
121
|
-
if
|
|
122
|
-
# 如果result
|
|
123
|
-
self.assertEqual(result
|
|
125
|
+
# 验证结果 - 使用更安全的方式处理可能的类型差异
|
|
126
|
+
if isinstance(result, dict):
|
|
127
|
+
# 如果result是字典(JSON解析结果)
|
|
128
|
+
self.assertEqual(result, {"success": True})
|
|
129
|
+
elif hasattr(result, 'json_data'):
|
|
130
|
+
# 如果result是MockResponse对象,使用getattr避免类型检查错误
|
|
131
|
+
json_data = getattr(result, 'json_data')
|
|
132
|
+
self.assertEqual(json_data, {"success": True})
|
|
124
133
|
else:
|
|
125
|
-
#
|
|
134
|
+
# 其他情况,直接比较
|
|
126
135
|
self.assertEqual(result, {"success": True})
|
|
127
136
|
mock_retry.assert_called_once()
|
|
128
137
|
|
funcguard-0.1.1.dist-info/RECORD
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
funcguard/__init__.py,sha256=He897o7aWOzpu2RnoRsjYQb5bhEMwC6XhFy0pot7-pA,189
|
|
2
|
-
funcguard/core.py,sha256=41C2bpVTaabK3QHN0vJmnhrKwnT_Ml8mxNitfN5gNdc,3291
|
|
3
|
-
funcguard/tools.py,sha256=UWvMUGj-ga_QbCZp1dJANeZbkyp76ozqbD4CpZkAymo,1807
|
|
4
|
-
tests/__init__.py,sha256=VW6FdWdSC_PL3zEtpkRQfUMf6yVD2OfwtSds82jawTs,26
|
|
5
|
-
tests/run_test.py,sha256=-SLdUV7gDifLxuCCAlU8qLxYMx6KpK4cxfG4UYfUIgA,1005
|
|
6
|
-
tests/test_core.py,sha256=aZNbQK4eTnnkCI4c2txYZNTcYIUhSJvII5Dvn0vNJKo,3732
|
|
7
|
-
tests/test_tools.py,sha256=jBKoam-X3irTynaNg23V_3HgzAHBRvE6S9OyoalLfvI,5170
|
|
8
|
-
funcguard-0.1.1.dist-info/LICENSE,sha256=jgOquECfjiXp5xXQ2zuzItDr4XDBLan-bIzIXl1lS4Y,1064
|
|
9
|
-
funcguard-0.1.1.dist-info/METADATA,sha256=ns_c9tJ_fjnsQjAA3OiKT26cSpDfpqebE8y12608Lu8,4230
|
|
10
|
-
funcguard-0.1.1.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
|
|
11
|
-
funcguard-0.1.1.dist-info/top_level.txt,sha256=7wL9mWT062DttKNO7Wi1wYWTZilR2AOPRO0rE3gvtB4,16
|
|
12
|
-
funcguard-0.1.1.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|