funcguard 0.1.7__py3-none-any.whl → 0.1.8__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 CHANGED
@@ -1,5 +1,6 @@
1
1
  from .core import timeout_handler, retry_function
2
- from .tools import send_request, time_log, time_diff
2
+ from .tools import send_request
3
+ from .time_utils import time_log, time_diff, monitor_execution_time
3
4
  from .printer import print_block, print_line, print_title
4
5
 
5
6
  __author__ = "ruocen"
@@ -11,6 +12,7 @@ __all__ = [
11
12
  "send_request",
12
13
  "time_log",
13
14
  "time_diff",
15
+ "monitor_execution_time",
14
16
  "print_block",
15
17
  "print_line",
16
18
  "print_title",
@@ -0,0 +1,144 @@
1
+ """
2
+ 时间工具模块,提供时间计算、日志记录和执行时间监控功能
3
+ """
4
+ from datetime import datetime, timezone, timedelta
5
+ from typing import Optional, Union
6
+
7
+
8
+ # 打印时间
9
+ def time_log(message, i = 0, max_num = 0, s_time = None, start_from = 0 ) :
10
+ """
11
+ 打印带时间戳的日志信息,支持进度显示和预计完成时间
12
+
13
+ :param message: 日志消息
14
+ :param i: 当前进度
15
+ :param max_num: 总进度数量
16
+ :param s_time: 开始时间,用于计算预计完成时间
17
+ :param start_from: i是否从0开始,0表示从0开始,1表示从1开始
18
+ :return: None
19
+ """
20
+ now = datetime.now( timezone( timedelta( hours = 8 ) ) )
21
+ time_log = "{:02d}:{:02d}:{:02d}".format( now.hour, now.minute, now.second )
22
+ if i < 2 or max_num < 2 :
23
+ print( time_log + " " + message )
24
+
25
+ else :
26
+ # 根据start_from参数计算实际处理的项目数
27
+ process_item = i + 1 if start_from == 0 else i
28
+ text = "{}/{}".format( process_item, max_num )
29
+ # 检查是否应该显示预计完成时间和剩余时间
30
+ if process_item % 10 == 0 and s_time is not None and process_item < max_num :
31
+ duration = now - s_time
32
+ ev_duration = duration / process_item # 每项平均耗时
33
+ remaining_items = max_num - process_item
34
+ time_left = ev_duration * remaining_items
35
+ end_time = now + time_left
36
+ end_time_str = end_time.strftime( "%Y-%m-%d %H:%M" )
37
+ remaining_time_str = str( timedelta( seconds = int( time_left.total_seconds() ) ) )
38
+ text = text + "({})etr {}".format( end_time_str, remaining_time_str )
39
+ print( time_log + " " + message + " " + text )
40
+ return
41
+
42
+
43
+ # 计算持续时间
44
+ def time_diff(s_time = None, max_num = 0, language = "cn", return_duration = 1) :
45
+ """
46
+ 计算并打印任务执行时间统计信息
47
+
48
+ :param s_time: 开始时间
49
+ :param max_num: 任务数量
50
+ :param language: 语言选择("cn"中文,其他为英文)
51
+ :param return_duration:
52
+ 返回模式,默认为1,
53
+ 0,仅返回 total_seconds,不打印信息
54
+ 1,仅打印信息,不返回 total_seconds
55
+ 2,print 信息,并返回 total_seconds
56
+ :return: 如果s_time为None则返回当前时间
57
+ """
58
+ # 获取当前时间并转换为北京时间
59
+ now = datetime.now( timezone( timedelta( hours = 8 ) ) )
60
+
61
+ if s_time is None :
62
+ return now
63
+
64
+ e_time = now
65
+ duration = e_time - s_time
66
+ total_seconds = int(duration.total_seconds())
67
+ if return_duration == 0:
68
+ return total_seconds
69
+
70
+ hours = total_seconds // 3600
71
+ duration_minutes = (total_seconds % 3600) // 60
72
+ seconds = total_seconds % 60
73
+ result = f"{hours:02d}:{duration_minutes:02d}:{seconds:02d}"
74
+
75
+ # 将时间差转化为分钟
76
+ minutes = round( duration.total_seconds() / 60 )
77
+ if max_num == 0 :
78
+ if language == "cn" :
79
+ print( "总耗时:{:02d} : {:02d} : {:02d}".format( hours, duration_minutes, seconds ) )
80
+ else :
81
+ print( "Total time: {:02d} : {:02d} : {:02d}".format( hours, duration_minutes, seconds ) )
82
+ else :
83
+ eve_minutes = round( minutes / max_num, 3 )
84
+ if language == "cn" :
85
+ print( "开始时间:{},结束时间:{}".format( s_time.strftime( "%Y-%m-%d %H:%M" ),
86
+ e_time.strftime( "%Y-%m-%d %H:%M" ) ) )
87
+ print( "总耗时:{},累计:{}分钟,数量;{},平均耗时:{}分钟".format( result, minutes, max_num, eve_minutes ) )
88
+ else :
89
+ print( "Start time:{},End time:{}".format( s_time.strftime( "%Y-%m-%d %H:%M" ),
90
+ e_time.strftime( "%Y-%m-%d %H:%M" ) ) )
91
+ print( "Total time: {},Total minutes: {},Number: {},Average time: {} minutes".format( result, minutes,
92
+ max_num,
93
+ eve_minutes ) )
94
+ if return_duration == 2:
95
+ return total_seconds
96
+ return
97
+
98
+
99
+ # 监控程序的执行时间
100
+ def monitor_execution_time(warning_threshold=None, print_mode=2, func=None, *args, **kwargs):
101
+ """
102
+ 监控函数执行时间,并返回函数的执行结果和执行时间
103
+
104
+ :param warning_threshold: 警告阈值(秒),如果执行耗时超过此值则打印警告
105
+ :param print_mode: 打印模式,支持三种模式:
106
+ 0 - 仅返回total_seconds,不打印任何信息
107
+ 1 - 总是打印执行时间
108
+ 2 - 仅在超时打印警告信息(默认)
109
+ :param func: 要监控的函数
110
+ :param args: 函数的位置参数
111
+ :param kwargs: 函数的关键字参数
112
+ :return:
113
+ print_mode == 0: 函数的执行结果, total_seconds
114
+ print_mode == 1: 函数的执行结果
115
+ print_mode == 2: 函数的执行结果
116
+ """
117
+ s_time = datetime.now( timezone( timedelta( hours = 8 ) ) )
118
+
119
+ if func is None:
120
+ raise ValueError("func is None, func must be a function")
121
+
122
+ # 执行函数并获取结果
123
+ result = func(*args, **kwargs)
124
+
125
+ # 计算执行时间
126
+ if print_mode in [ 0, 2 ] : # print_mode:0 和 2 需要 time_diff 内部不执行 print 但返回 total_seconds 信息
127
+ return_duration = 0
128
+
129
+ elif print_mode == 1 :
130
+ return_duration = 2
131
+
132
+ else:
133
+ raise ValueError("print_mode must be 0, 1 or 2")
134
+
135
+ total_seconds = time_diff(s_time, return_duration=return_duration) # pyright: ignore[reportGeneralTypeIssues]
136
+
137
+ # 根据打印模式决定是否打印耗时信息
138
+ if print_mode == 2 and warning_threshold is not None and total_seconds > warning_threshold:
139
+ print(f"警告: 函数 {func.__name__} 执行耗时 {total_seconds:.2f}秒,超过阈值 {warning_threshold}秒")
140
+
141
+ if print_mode == 0:
142
+ return result, total_seconds
143
+
144
+ return result
funcguard/tools.py CHANGED
@@ -3,6 +3,7 @@ import requests
3
3
  from datetime import datetime, timezone, timedelta
4
4
  from typing import Optional, Dict, Any, Union
5
5
  from .core import retry_function
6
+ from .time_utils import time_log, time_diff, monitor_execution_time
6
7
 
7
8
 
8
9
  # 发起请求
@@ -65,84 +66,3 @@ def send_request(
65
66
  else:
66
67
  result = response.text
67
68
  return result
68
-
69
-
70
- # 打印时间
71
- def time_log(message, i = 0, max_num = 0, s_time = None, start_from = 0 ) :
72
- """
73
- 打印带时间戳的日志信息,支持进度显示和预计完成时间
74
-
75
- :param message: 日志消息
76
- :param i: 当前进度
77
- :param max_num: 总进度数量
78
- :param s_time: 开始时间,用于计算预计完成时间
79
- :param start_from: i是否从0开始,0表示从0开始,1表示从1开始
80
- :return: None
81
- """
82
- now = datetime.now( timezone( timedelta( hours = 8 ) ) )
83
- time_log = "{:02d}:{:02d}:{:02d}".format( now.hour, now.minute, now.second )
84
- if i < 2 or max_num < 2 :
85
- print( time_log + " " + message )
86
-
87
- else :
88
- # 根据start_from参数计算实际处理的项目数
89
- process_item = i + 1 if start_from == 0 else i
90
- text = "{}/{}".format( process_item, max_num )
91
- # 检查是否应该显示预计完成时间和剩余时间
92
- if process_item % 10 == 0 and s_time is not None and process_item < max_num :
93
- duration = now - s_time
94
- ev_duration = duration / process_item # 每项平均耗时
95
- remaining_items = max_num - process_item
96
- time_left = ev_duration * remaining_items
97
- end_time = now + time_left
98
- end_time_str = end_time.strftime( "%Y-%m-%d %H:%M" )
99
- remaining_time_str = str( timedelta( seconds = int( time_left.total_seconds() ) ) )
100
- text = text + "({})etr {}".format( end_time_str, remaining_time_str )
101
- print( time_log + " " + message + " " + text )
102
- return
103
-
104
-
105
- # 计算持续时间
106
- def time_diff(s_time = None, max_num = 0, language = "cn") :
107
- """
108
- 计算并打印任务执行时间统计信息
109
-
110
- :param s_time: 开始时间
111
- :param max_num: 任务数量
112
- :param language: 语言选择("cn"中文,其他为英文)
113
- :return: 如果s_time为None则返回当前时间,否则返回None
114
- """
115
- # 获取当前时间并转换为北京时间
116
- now = datetime.now( timezone( timedelta( hours = 8 ) ) )
117
-
118
- if s_time is None :
119
- return now
120
-
121
- e_time = now
122
- duration = e_time - s_time
123
- hours = duration.seconds // 3600
124
- duration_minutes = (duration.seconds % 3600) // 60
125
- seconds = duration.seconds % 60
126
- result = f"{hours:02d}:{duration_minutes:02d}:{seconds:02d}"
127
-
128
- # 将时间差转化为分钟
129
- minutes = round( duration.total_seconds() / 60 )
130
- if max_num == 0 :
131
- if language == "cn" :
132
- print( "总耗时:{}".format( result ) )
133
- else :
134
- print( "Total time: {}".format( result ) )
135
- else :
136
- eve_minutes = round( minutes / max_num, 3 )
137
- if language == "cn" :
138
- print( "开始时间:{},结束时间:{}".format( s_time.strftime( "%Y-%m-%d %H:%M" ),
139
- e_time.strftime( "%Y-%m-%d %H:%M" ) ) )
140
- print( "总耗时:{},累计:{}分钟,数量;{},平均耗时:{}分钟".format( result, minutes, max_num, eve_minutes ) )
141
- else :
142
- print( "Start time:{},End time:{}".format( s_time.strftime( "%Y-%m-%d %H:%M" ),
143
- e_time.strftime( "%Y-%m-%d %H:%M" ) ) )
144
- print( "Total time: {},Total minutes: {},Number: {},Average time: {} minutes".format( result, minutes,
145
- max_num,
146
- eve_minutes ) )
147
-
148
- return
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: funcguard
3
- Version: 0.1.7
3
+ Version: 0.1.8
4
4
  Summary: FuncGuard是一个Python库,提供函数执行超时控制、重试机制、HTTP请求封装和格式化打印工具。
5
5
  Home-page: https://github.com/tinycen/funcguard
6
6
  Author: tinycen
@@ -24,6 +24,7 @@ FuncGuard是一个Python库,提供了函数执行超时控制和重试机制
24
24
  - HTTP请求封装(支持自动重试)
25
25
  - 格式化打印工具(分隔线和块打印)
26
26
  - 时间日志记录和耗时统计
27
+ - 函数执行时间监控和警告
27
28
 
28
29
  ## 安装/升级
29
30
 
@@ -179,12 +180,49 @@ for i in range(1, 101):
179
180
 
180
181
  ```
181
182
 
183
+ ### 执行时间监控
184
+
185
+ 使用`monitor_execution_time`函数监控函数执行时间:
186
+
187
+ ```python
188
+ from funcguard import monitor_execution_time
189
+
190
+ def some_function():
191
+ # 模拟一个耗时操作
192
+ import time
193
+ time.sleep(2)
194
+ return "操作完成"
195
+
196
+ # 模式1:总是打印执行时间
197
+ result = monitor_execution_time(
198
+ func=some_function,
199
+ print_mode=1
200
+ )
201
+ print(f"结果: {result}")
202
+
203
+ # 模式2:仅在超过阈值时打印警告
204
+ result = monitor_execution_time(
205
+ func=some_function,
206
+ warning_threshold=1.5, # 设置1.5秒的警告阈值
207
+ print_mode=2
208
+ )
209
+ print(f"结果: {result}")
210
+
211
+ # 模式0:不打印任何信息,仅返回结果和执行时间
212
+ result, duration = monitor_execution_time(
213
+ func=some_function,
214
+ print_mode=0
215
+ )
216
+ print(f"结果: {result}, 耗时: {duration}秒")
217
+ ```
218
+
182
219
  时间日志功能特点:
183
220
  - 自动显示北京时间(UTC+8)
184
221
  - 支持进度显示和预计完成时间计算
185
222
  - 提供中英文双语统计信息
186
223
  - 可显示总耗时、平均耗时等详细统计
187
224
  - 支持i从0或从1开始的计数方式
225
+ - 支持函数执行时间监控和警告
188
226
 
189
227
  ## API文档
190
228
 
@@ -227,6 +265,8 @@ for i in range(1, 101):
227
265
  - **返回值**: 根据return_type参数返回不同格式的响应数据
228
266
  - **异常**: 当请求失败且重试次数用尽后,抛出相应的异常
229
267
 
268
+ ### funcguard.time_utils
269
+
230
270
  #### time_log(message, i=0, max_num=0, s_time=None, start_from=0)
231
271
 
232
272
  - **参数**:
@@ -238,15 +278,42 @@ for i in range(1, 101):
238
278
  - **返回值**: 无
239
279
  - **功能**: 打印带时间戳的日志信息,支持进度显示和预计完成时间计算
240
280
 
241
- #### time_diff(s_time=None, max_num=0, language="cn")
281
+ #### time_diff(s_time=None, max_num=0, language="cn", return_duration=1)
242
282
 
243
283
  - **参数**:
244
284
  - `s_time`: 开始时间,默认为None
245
285
  - `max_num`: 任务数量,默认为0
246
286
  - `language`: 语言选择("cn"中文,其他为英文),默认为"cn"
247
- - **返回值**: 如果s_time为None则返回当前时间,否则返回None
287
+ - `return_duration`: 返回模式,默认为1:
288
+ - 0 - 仅返回 total_seconds,不打印信息
289
+ - 1 - 仅打印信息,不返回 total_seconds
290
+ - 2 - 打印信息,并返回 total_seconds
291
+ - **返回值**:
292
+ - 如果s_time为None则返回当前时间
293
+ - 如果return_duration为0或2则返回持续时间(秒)
294
+ - 否则返回None
248
295
  - **功能**: 计算并打印任务执行时间统计信息,支持中英文双语输出
249
296
 
297
+ #### monitor_execution_time(warning_threshold=None, print_mode=2, func=None, *args, **kwargs)
298
+
299
+ - **参数**:
300
+ - `warning_threshold`: 警告阈值(秒),如果执行耗时超过此值则打印警告,默认为None
301
+ - `print_mode`: 打印模式,支持三种模式:
302
+ - 0 - 仅返回total_seconds,不打印任何信息
303
+ - 1 - 总是打印执行时间
304
+ - 2 - 仅在超时打印警告信息(默认)
305
+ - `func`: 要监控的函数
306
+ - `args`: 函数的位置参数
307
+ - `kwargs`: 函数的关键字参数
308
+ - **返回值**:
309
+ - print_mode == 0: 元组 (result, total_seconds) - 函数的执行结果和执行时间(秒)
310
+ - print_mode == 1: 函数的执行结果
311
+ - print_mode == 2: 函数的执行结果
312
+ - **功能**: 监控函数执行时间,并返回函数的执行结果和执行时间
313
+ - **注意**: 该方法内部使用 time_diff 函数,根据 print_mode 自动设置 return_duration 参数
314
+ - print_mode 为 0 或 2 时,设置 return_duration=0( time_diff 仅返回total_seconds,不打印信息)
315
+ - print_mode 为 1 时,设置 return_duration=2( time_diff 打印信息,并返回total_seconds)
316
+
250
317
  ### funcguard.printer
251
318
 
252
319
  #### print_line(separator_char: str = "-", separator_length: int = 40) -> None
@@ -0,0 +1,11 @@
1
+ funcguard/__init__.py,sha256=irZLaE4wDu4bRilk0ySHy7ZTZD0-CGWaogrC7MCKM3k,451
2
+ funcguard/core.py,sha256=-rFRkE-udxM0wxlcv9Qi_yIQBRdVrGgwza-LYQsVRLg,3632
3
+ funcguard/printer.py,sha256=Iig_UO4h5LcL0BqCEEdxiu32h4rUq9GJbmf1pC_hd7o,1462
4
+ funcguard/time_utils.py,sha256=be7l6vMivWAfmLP4V91z9jRUYfnn-T4XrCU21eQkXeo,6139
5
+ funcguard/tools.py,sha256=J25wE1JCRqfDnJn7NJGaS9nepATPxNJT4ko4ITkghQA,2091
6
+ tests/__init__.py,sha256=VW6FdWdSC_PL3zEtpkRQfUMf6yVD2OfwtSds82jawTs,26
7
+ funcguard-0.1.8.dist-info/LICENSE,sha256=jgOquECfjiXp5xXQ2zuzItDr4XDBLan-bIzIXl1lS4Y,1064
8
+ funcguard-0.1.8.dist-info/METADATA,sha256=l7J2kuqmcjPUPnyCDt10leuNvwGJpLrSiMSM3sbxzZc,10658
9
+ funcguard-0.1.8.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
10
+ funcguard-0.1.8.dist-info/top_level.txt,sha256=7wL9mWT062DttKNO7Wi1wYWTZilR2AOPRO0rE3gvtB4,16
11
+ funcguard-0.1.8.dist-info/RECORD,,
@@ -1,13 +0,0 @@
1
- funcguard/__init__.py,sha256=l8GqIAv1jbaq4fLEYsfrfm4Epk8EUoP1BfvwCdwr0Zw,374
2
- funcguard/core.py,sha256=-rFRkE-udxM0wxlcv9Qi_yIQBRdVrGgwza-LYQsVRLg,3632
3
- funcguard/printer.py,sha256=Iig_UO4h5LcL0BqCEEdxiu32h4rUq9GJbmf1pC_hd7o,1462
4
- funcguard/tools.py,sha256=YIrr1qFWEU61R5Plk5UXGAyp9yGJrm28-POhNsttZsg,5623
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.7.dist-info/LICENSE,sha256=jgOquECfjiXp5xXQ2zuzItDr4XDBLan-bIzIXl1lS4Y,1064
10
- funcguard-0.1.7.dist-info/METADATA,sha256=xx4YUVNhJ0F--Cmjm9eUAzxE-LNchoBnuuyeZ0kbw1Y,8304
11
- funcguard-0.1.7.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
12
- funcguard-0.1.7.dist-info/top_level.txt,sha256=7wL9mWT062DttKNO7Wi1wYWTZilR2AOPRO0rE3gvtB4,16
13
- funcguard-0.1.7.dist-info/RECORD,,
tests/run_test.py DELETED
@@ -1,40 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- 测试运行脚本
4
- 运行所有测试用例
5
- """
6
-
7
- import unittest
8
- import sys
9
- import os
10
-
11
- # 添加项目根目录到Python路径
12
- project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
13
- sys.path.insert(0, project_root)
14
-
15
- # 导入测试模块
16
- from tests.test_core import TestTimeoutHandler, TestRetryFunction
17
- from tests.test_tools import TestSendRequest
18
-
19
-
20
- def run_all_tests():
21
- """运行所有测试"""
22
- # 创建测试套件
23
- loader = unittest.TestLoader()
24
- suite = unittest.TestSuite()
25
-
26
- # 添加测试类
27
- suite.addTests(loader.loadTestsFromTestCase(TestTimeoutHandler))
28
- suite.addTests(loader.loadTestsFromTestCase(TestRetryFunction))
29
- suite.addTests(loader.loadTestsFromTestCase(TestSendRequest))
30
-
31
- # 运行测试
32
- runner = unittest.TextTestRunner(verbosity=2)
33
- result = runner.run(suite)
34
-
35
- return result.wasSuccessful()
36
-
37
-
38
- if __name__ == '__main__':
39
- success = run_all_tests()
40
- sys.exit(0 if success else 1)
tests/test_core.py DELETED
@@ -1,109 +0,0 @@
1
- import time
2
- import unittest
3
- from unittest.mock import patch
4
-
5
- from funcguard.core import timeout_handler, retry_function
6
-
7
-
8
- class TestTimeoutHandler(unittest.TestCase):
9
- """测试timeout_handler函数"""
10
-
11
- def test_normal_execution(self):
12
- """测试正常执行的函数"""
13
- def quick_function():
14
- time.sleep(0.1)
15
- return "success"
16
-
17
- result = timeout_handler(quick_function, execution_timeout=2)
18
- self.assertEqual(result, "success")
19
-
20
- def test_timeout_execution(self):
21
- """测试超时的函数"""
22
- def slow_function():
23
- time.sleep(2)
24
- return "should not reach here"
25
-
26
- from funcguard.core import FuncguardTimeoutError
27
- with self.assertRaises(FuncguardTimeoutError) as context:
28
- timeout_handler(slow_function, execution_timeout=1)
29
-
30
- self.assertIn("执行时间超过 1 秒", str(context.exception))
31
-
32
- def test_function_with_args(self):
33
- """测试带参数的函数"""
34
- def add_numbers(a, b):
35
- return a + b
36
-
37
- result = timeout_handler(add_numbers, args=(3, 4), execution_timeout=2)
38
- self.assertEqual(result, 7)
39
-
40
- def test_function_with_kwargs(self):
41
- """测试带关键字参数的函数"""
42
- def greet(name, greeting="Hello"):
43
- return f"{greeting}, {name}!"
44
-
45
- result = timeout_handler(greet, kwargs={"name": "World", "greeting": "Hi"}, execution_timeout=2)
46
- self.assertEqual(result, "Hi, World!")
47
-
48
-
49
- class TestRetryFunction(unittest.TestCase):
50
- """测试retry_function函数"""
51
-
52
- def test_successful_first_try(self):
53
- """测试第一次就成功的函数"""
54
- def always_success():
55
- return "success"
56
-
57
- result = retry_function(always_success, max_retries=2, task_name="test")
58
- self.assertEqual(result, "success")
59
-
60
- def test_retry_until_success(self):
61
- """测试重试后成功的函数"""
62
- attempts = []
63
-
64
- def sometimes_fail():
65
- attempts.append(len(attempts))
66
- if len(attempts) < 2:
67
- raise ValueError("Not yet")
68
- return "finally success"
69
-
70
- result = retry_function(sometimes_fail, max_retries=2, task_name="test")
71
- self.assertEqual(result, "finally success")
72
- self.assertEqual(len(attempts), 2)
73
-
74
- def test_exhaust_all_retries(self):
75
- """测试耗尽所有重试次数"""
76
- def always_fail():
77
- raise RuntimeError("Always fails")
78
-
79
- with self.assertRaises(RuntimeError) as context:
80
- retry_function(always_fail, max_retries=2, task_name="test")
81
-
82
- self.assertEqual(str(context.exception), "Always fails")
83
-
84
- def test_timeout_in_retry(self):
85
- """测试重试中的超时处理"""
86
- def timeout_function():
87
- time.sleep(2)
88
- return "should timeout"
89
-
90
- # retry_function会在重试耗尽后抛出最后的异常
91
- from funcguard.core import FuncguardTimeoutError
92
- with self.assertRaises(FuncguardTimeoutError):
93
- retry_function(timeout_function, max_retries=1, execute_timeout=1, task_name="test")
94
-
95
- @patch('time.sleep')
96
- def test_retry_with_custom_delay(self, mock_sleep):
97
- """测试重试延迟"""
98
- def always_fail():
99
- raise ValueError("test")
100
-
101
- with self.assertRaises(ValueError):
102
- retry_function(always_fail, max_retries=2, task_name="test")
103
-
104
- # 验证sleep被调用了正确的次数
105
- self.assertEqual(mock_sleep.call_count, 1)
106
-
107
-
108
- if __name__ == '__main__':
109
- unittest.main()
tests/test_tools.py DELETED
@@ -1,165 +0,0 @@
1
- import json
2
- import unittest
3
- from unittest.mock import patch, MagicMock
4
- from typing import Any, Optional, Dict
5
- import requests
6
-
7
- from funcguard.tools import send_request
8
-
9
-
10
- class MockResponse:
11
- """模拟requests响应"""
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):
18
- self.json_data = json_data or {}
19
- self.text = text
20
- self.status_code = status_code
21
-
22
- def json(self) -> Dict[str, Any]:
23
- return self.json_data
24
-
25
-
26
- class TestSendRequest(unittest.TestCase):
27
- """测试send_request函数"""
28
-
29
- @patch('requests.request')
30
- def test_get_request_json_response(self, mock_request):
31
- """测试GET请求返回JSON"""
32
- mock_response = MockResponse(json_data={"key": "value"})
33
- mock_request.return_value = mock_response
34
-
35
- result = send_request(
36
- method="GET",
37
- url="https://api.example.com/data",
38
- headers={"Content-Type": "application/json"}
39
- )
40
-
41
- self.assertEqual(result, {"key": "value"})
42
- mock_request.assert_called_once()
43
-
44
- @patch('requests.request')
45
- def test_post_request_with_data(self, mock_request):
46
- """测试POST请求带数据"""
47
- mock_response = MockResponse(json_data={"status": "created"})
48
- mock_request.return_value = mock_response
49
-
50
- result = send_request(
51
- method="POST",
52
- url="https://api.example.com/users",
53
- headers={"Content-Type": "application/json"},
54
- data={"name": "test", "email": "test@example.com"}
55
- )
56
-
57
- self.assertEqual(result, {"status": "created"})
58
- mock_request.assert_called_once()
59
-
60
- @patch('requests.request')
61
- def test_return_response_object(self, mock_request):
62
- """测试返回response对象"""
63
- mock_response = MockResponse(text="raw response")
64
- mock_request.return_value = mock_response
65
-
66
- result = send_request(
67
- method="GET",
68
- url="https://api.example.com/raw",
69
- headers={},
70
- return_type="response"
71
- )
72
-
73
- self.assertEqual(result, mock_response)
74
-
75
- @patch('requests.request')
76
- def test_return_text_response(self, mock_request):
77
- """测试返回文本响应"""
78
- mock_response = MockResponse(text="plain text response")
79
- mock_request.return_value = mock_response
80
-
81
- result = send_request(
82
- method="GET",
83
- url="https://api.example.com/text",
84
- headers={},
85
- return_type="text"
86
- )
87
-
88
- self.assertEqual(result, "plain text response")
89
-
90
- @patch('requests.request')
91
- def test_custom_timeout(self, mock_request):
92
- """测试自定义超时时间"""
93
- mock_response = MockResponse()
94
- mock_request.return_value = mock_response
95
-
96
- send_request(
97
- method="GET",
98
- url="https://api.example.com/data",
99
- headers={},
100
- timeout=30
101
- )
102
-
103
- mock_request.assert_called_once()
104
-
105
- @patch('funcguard.tools.retry_function')
106
- @patch('requests.request')
107
- def test_auto_retry_enabled(self, mock_request, mock_retry):
108
- """测试启用自动重试"""
109
- # 设置retry_function返回一个包含正确json数据的MockResponse对象
110
- mock_response = MockResponse(json_data={"success": True})
111
- mock_retry.return_value = mock_response
112
-
113
- result = send_request(
114
- method="POST",
115
- url="https://api.example.com/data",
116
- headers={"Content-Type": "application/json"},
117
- data={"key": "value"},
118
- auto_retry={
119
- "task_name": "API测试",
120
- "max_retries": 3,
121
- "execute_timeout": 60
122
- }
123
- )
124
-
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})
133
- else:
134
- # 其他情况,直接比较
135
- self.assertEqual(result, {"success": True})
136
- mock_retry.assert_called_once()
137
-
138
- @patch('requests.request')
139
- def test_none_response_raises_error(self, mock_request):
140
- """测试None响应抛出错误"""
141
- mock_request.return_value = None
142
-
143
- with self.assertRaises(ValueError) as context:
144
- send_request("GET", "https://api.example.com/data", {})
145
-
146
- self.assertEqual(str(context.exception), "请求返回的响应为None")
147
-
148
- def test_invalid_return_type(self):
149
- """测试无效的返回类型"""
150
- with patch('requests.request') as mock_request:
151
- mock_response = MockResponse()
152
- mock_request.return_value = mock_response
153
-
154
- # 对于无效的return_type,函数会尝试访问response.text
155
- result = send_request(
156
- method="GET",
157
- url="https://api.example.com/data",
158
- headers={},
159
- return_type="invalid"
160
- )
161
- self.assertEqual(result, "")
162
-
163
-
164
- if __name__ == '__main__':
165
- unittest.main()