-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtest_timezone.py
More file actions
172 lines (138 loc) · 5.71 KB
/
test_timezone.py
File metadata and controls
172 lines (138 loc) · 5.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#!/usr/bin/env python3
"""
测试时区转换功能
"""
import os
import sys
from datetime import datetime, timezone, timedelta
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
def test_timezone_functionality():
"""测试时区功能"""
print("开始测试时区转换功能...")
project_root = os.path.dirname(os.path.abspath(__file__))
os.chdir(project_root)
try:
from video_transcript_api.utils.timeutil import (
parse_timezone_offset,
get_configured_timezone,
format_datetime_with_timezone,
format_datetime_for_display,
)
# 1. 测试时区解析
print("\n步骤1: 测试时区字符串解析...")
test_timezones = [
"UTC+8",
"UTC-5",
"UTC+08:30",
"UTC-05:30",
"UTC",
"utc+8", # 测试大小写不敏感
"UTC+0",
"UTC+12",
"UTC-12",
"INVALID" # 无效格式
]
for tz_str in test_timezones:
result = parse_timezone_offset(tz_str)
if result:
offset = result.utcoffset(datetime.now())
hours = offset.total_seconds() / 3600
print(f" [OK] {tz_str} -> {hours:+.1f}小时偏移")
else:
print(f" [WARN] {tz_str} -> 解析失败")
# 2. 测试配置获取
print("\n步骤2: 测试配置的时区获取...")
configured_tz = get_configured_timezone()
offset = configured_tz.utcoffset(datetime.now())
hours = offset.total_seconds() / 3600
print(f"[OK] 配置的时区偏移: {hours:+.1f}小时")
# 3. 测试时间格式转换
print("\n步骤3: 测试时间格式转换...")
test_times = [
"2025-08-20 12:34:56",
"2025-08-20T12:34:56",
"2025-08-20T12:34:56Z",
"2025-08-20 12:34:56.123456",
datetime.now().strftime("%Y-%m-%d %H:%M:%S")
]
for test_time in test_times:
try:
formatted_time = format_datetime_with_timezone(test_time)
print(f" [OK] {test_time} -> {formatted_time}")
except Exception as e:
print(f" [ERROR] {test_time} -> {e}")
# 4. 测试显示格式
print("\n步骤4: 测试用户显示格式...")
current_utc = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
display_format = format_datetime_for_display(current_utc)
print(f"[OK] 当前UTC时间 {current_utc} -> 显示为: {display_format}")
# 5. 测试不同时区配置
print("\n步骤5: 测试不同时区配置...")
# 临时修改配置测试
from video_transcript_api.utils.logging import load_config
original_config = load_config()
test_timezones_config = ["UTC+0", "UTC-5", "UTC+9", "UTC+05:30"]
for tz in test_timezones_config:
# 模拟不同时区配置
original_config["web"]["timezone"] = tz
# 重新导入模块以获取新配置
import importlib
import video_transcript_api.utils.timeutil.timezone_helper as timezone_helper_module
importlib.reload(timezone_helper_module)
from video_transcript_api.utils.timeutil import (
get_configured_timezone,
format_datetime_for_display,
)
test_time = "2025-08-20 12:00:00"
display_time = format_datetime_for_display(test_time)
print(f" [OK] {tz}: {test_time} UTC -> {display_time}")
# 恢复原始配置
original_config["web"]["timezone"] = "UTC+8"
print("\n[SUCCESS] 时区转换功能测试完成!")
print("功能总结:")
print(" [OK] 时区字符串解析")
print(" [OK] 配置文件时区读取")
print(" [OK] UTC时间转本地时间")
print(" [OK] 用户友好的时间显示格式")
print(" [OK] 多种时区格式支持")
return True
except Exception as e:
print(f"[ERROR] 测试过程中出现异常: {str(e)}")
import traceback
traceback.print_exc()
return False
def test_edge_cases():
"""测试边界情况"""
print("\n测试边界情况...")
try:
from video_transcript_api.utils.timeutil import (
format_datetime_with_timezone,
format_datetime_for_display,
)
edge_cases = [
"", # 空字符串
None, # None值
"invalid", # 无效格式
"2025-13-45 25:61:99", # 无效日期时间
]
for case in edge_cases:
try:
result1 = format_datetime_with_timezone(str(case) if case is not None else "")
result2 = format_datetime_for_display(str(case) if case is not None else "")
print(f" [OK] 边界情况 '{case}' 处理正常")
except Exception as e:
print(f" [WARN] 边界情况 '{case}': {e}")
print("[OK] 边界情况测试完成")
return True
except Exception as e:
print(f"[ERROR] 边界情况测试异常: {e}")
return False
if __name__ == "__main__":
success = test_timezone_functionality()
edge_success = test_edge_cases()
if success and edge_success:
print("\n✅ 所有时区功能测试通过!")
sys.exit(0)
else:
print("\n❌ 部分测试失败")
sys.exit(1)