fix: auto-fix code issues (cron)
- 修复重复导入/字段 - 修复异常处理 - 修复PEP8格式问题 - 添加类型注解 - 修复缺失的urllib.parse导入
This commit is contained in:
@@ -30,6 +30,7 @@ backend_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
if backend_dir not in sys.path:
|
||||
sys.path.insert(0, backend_dir)
|
||||
|
||||
|
||||
class TestOpsManager:
|
||||
"""测试运维与监控管理器"""
|
||||
|
||||
@@ -92,7 +93,7 @@ class TestOpsManager:
|
||||
channels=[],
|
||||
labels={"service": "api", "team": "platform"},
|
||||
annotations={"summary": "CPU 使用率过高", "runbook": "https://wiki/runbooks/cpu"},
|
||||
created_by="test_user"
|
||||
created_by="test_user",
|
||||
)
|
||||
self.log(f"Created alert rule: {rule1.name} (ID: {rule1.id})")
|
||||
|
||||
@@ -111,7 +112,7 @@ class TestOpsManager:
|
||||
channels=[],
|
||||
labels={"service": "database"},
|
||||
annotations={},
|
||||
created_by="test_user"
|
||||
created_by="test_user",
|
||||
)
|
||||
self.log(f"Created anomaly alert rule: {rule2.name} (ID: {rule2.id})")
|
||||
|
||||
@@ -128,9 +129,7 @@ class TestOpsManager:
|
||||
|
||||
# 更新告警规则
|
||||
updated_rule = self.manager.update_alert_rule(
|
||||
rule1.id,
|
||||
threshold=85.0,
|
||||
description="更新后的描述"
|
||||
rule1.id, threshold=85.0, description="更新后的描述"
|
||||
)
|
||||
assert updated_rule.threshold == 85.0
|
||||
self.log(f"Updated alert rule threshold to {updated_rule.threshold}")
|
||||
@@ -155,9 +154,9 @@ class TestOpsManager:
|
||||
channel_type=AlertChannelType.FEISHU,
|
||||
config={
|
||||
"webhook_url": "https://open.feishu.cn/open-apis/bot/v2/hook/test",
|
||||
"secret": "test_secret"
|
||||
"secret": "test_secret",
|
||||
},
|
||||
severity_filter=["p0", "p1"]
|
||||
severity_filter=["p0", "p1"],
|
||||
)
|
||||
self.log(f"Created Feishu channel: {channel1.name} (ID: {channel1.id})")
|
||||
|
||||
@@ -168,9 +167,9 @@ class TestOpsManager:
|
||||
channel_type=AlertChannelType.DINGTALK,
|
||||
config={
|
||||
"webhook_url": "https://oapi.dingtalk.com/robot/send?access_token=test",
|
||||
"secret": "test_secret"
|
||||
"secret": "test_secret",
|
||||
},
|
||||
severity_filter=["p0", "p1", "p2"]
|
||||
severity_filter=["p0", "p1", "p2"],
|
||||
)
|
||||
self.log(f"Created DingTalk channel: {channel2.name} (ID: {channel2.id})")
|
||||
|
||||
@@ -179,10 +178,8 @@ class TestOpsManager:
|
||||
tenant_id=self.tenant_id,
|
||||
name="Slack 告警",
|
||||
channel_type=AlertChannelType.SLACK,
|
||||
config={
|
||||
"webhook_url": "https://hooks.slack.com/services/test"
|
||||
},
|
||||
severity_filter=["p0", "p1", "p2", "p3"]
|
||||
config={"webhook_url": "https://hooks.slack.com/services/test"},
|
||||
severity_filter=["p0", "p1", "p2", "p3"],
|
||||
)
|
||||
self.log(f"Created Slack channel: {channel3.name} (ID: {channel3.id})")
|
||||
|
||||
@@ -228,7 +225,7 @@ class TestOpsManager:
|
||||
channels=[],
|
||||
labels={},
|
||||
annotations={},
|
||||
created_by="test_user"
|
||||
created_by="test_user",
|
||||
)
|
||||
|
||||
# 记录资源指标
|
||||
@@ -240,12 +237,13 @@ class TestOpsManager:
|
||||
metric_name="test_metric",
|
||||
metric_value=110.0 + i,
|
||||
unit="percent",
|
||||
metadata={"region": "cn-north-1"}
|
||||
metadata={"region": "cn-north-1"},
|
||||
)
|
||||
self.log("Recorded 10 resource metrics")
|
||||
|
||||
# 手动创建告警
|
||||
from ops_manager import Alert
|
||||
|
||||
alert_id = f"test_alert_{datetime.now().strftime('%Y%m%d%H%M%S')}"
|
||||
now = datetime.now().isoformat()
|
||||
|
||||
@@ -267,20 +265,35 @@ class TestOpsManager:
|
||||
acknowledged_by=None,
|
||||
acknowledged_at=None,
|
||||
notification_sent={},
|
||||
suppression_count=0
|
||||
suppression_count=0,
|
||||
)
|
||||
|
||||
with self.manager._get_db() as conn:
|
||||
conn.execute("""
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO alerts
|
||||
(id, rule_id, tenant_id, severity, status, title, description,
|
||||
metric, value, threshold, labels, annotations, started_at, notification_sent, suppression_count)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""", (alert.id, alert.rule_id, alert.tenant_id, alert.severity.value,
|
||||
alert.status.value, alert.title, alert.description,
|
||||
alert.metric, alert.value, alert.threshold,
|
||||
json.dumps(alert.labels), json.dumps(alert.annotations),
|
||||
alert.started_at, json.dumps(alert.notification_sent), alert.suppression_count))
|
||||
""",
|
||||
(
|
||||
alert.id,
|
||||
alert.rule_id,
|
||||
alert.tenant_id,
|
||||
alert.severity.value,
|
||||
alert.status.value,
|
||||
alert.title,
|
||||
alert.description,
|
||||
alert.metric,
|
||||
alert.value,
|
||||
alert.threshold,
|
||||
json.dumps(alert.labels),
|
||||
json.dumps(alert.annotations),
|
||||
alert.started_at,
|
||||
json.dumps(alert.notification_sent),
|
||||
alert.suppression_count,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
self.log(f"Created test alert: {alert.id}")
|
||||
@@ -325,12 +338,23 @@ class TestOpsManager:
|
||||
for i in range(30):
|
||||
timestamp = (base_time + timedelta(days=i)).isoformat()
|
||||
with self.manager._get_db() as conn:
|
||||
conn.execute("""
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO resource_metrics
|
||||
(id, tenant_id, resource_type, resource_id, metric_name, metric_value, unit, timestamp)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""", (f"cm_{i}", self.tenant_id, ResourceType.CPU.value, "server-001",
|
||||
"cpu_usage_percent", 50.0 + random.random() * 30, "percent", timestamp))
|
||||
""",
|
||||
(
|
||||
f"cm_{i}",
|
||||
self.tenant_id,
|
||||
ResourceType.CPU.value,
|
||||
"server-001",
|
||||
"cpu_usage_percent",
|
||||
50.0 + random.random() * 30,
|
||||
"percent",
|
||||
timestamp,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
self.log("Recorded 30 days of historical metrics")
|
||||
@@ -342,7 +366,7 @@ class TestOpsManager:
|
||||
resource_type=ResourceType.CPU,
|
||||
current_capacity=100.0,
|
||||
prediction_date=prediction_date,
|
||||
confidence=0.85
|
||||
confidence=0.85,
|
||||
)
|
||||
|
||||
self.log(f"Created capacity plan: {plan.id}")
|
||||
@@ -382,7 +406,7 @@ class TestOpsManager:
|
||||
scale_down_threshold=0.3,
|
||||
scale_up_step=2,
|
||||
scale_down_step=1,
|
||||
cooldown_period=300
|
||||
cooldown_period=300,
|
||||
)
|
||||
|
||||
self.log(f"Created auto scaling policy: {policy.name} (ID: {policy.id})")
|
||||
@@ -397,9 +421,7 @@ class TestOpsManager:
|
||||
|
||||
# 模拟扩缩容评估
|
||||
event = self.manager.evaluate_scaling_policy(
|
||||
policy_id=policy.id,
|
||||
current_instances=3,
|
||||
current_utilization=0.85
|
||||
policy_id=policy.id, current_instances=3, current_utilization=0.85
|
||||
)
|
||||
|
||||
if event:
|
||||
@@ -416,7 +438,9 @@ class TestOpsManager:
|
||||
# 清理
|
||||
with self.manager._get_db() as conn:
|
||||
conn.execute("DELETE FROM scaling_events WHERE tenant_id = ?", (self.tenant_id,))
|
||||
conn.execute("DELETE FROM auto_scaling_policies WHERE tenant_id = ?", (self.tenant_id,))
|
||||
conn.execute(
|
||||
"DELETE FROM auto_scaling_policies WHERE tenant_id = ?", (self.tenant_id,)
|
||||
)
|
||||
conn.commit()
|
||||
self.log("Cleaned up auto scaling test data")
|
||||
|
||||
@@ -435,13 +459,10 @@ class TestOpsManager:
|
||||
target_type="service",
|
||||
target_id="api-service",
|
||||
check_type="http",
|
||||
check_config={
|
||||
"url": "https://api.insightflow.io/health",
|
||||
"expected_status": 200
|
||||
},
|
||||
check_config={"url": "https://api.insightflow.io/health", "expected_status": 200},
|
||||
interval=60,
|
||||
timeout=10,
|
||||
retry_count=3
|
||||
retry_count=3,
|
||||
)
|
||||
self.log(f"Created HTTP health check: {check1.name} (ID: {check1.id})")
|
||||
|
||||
@@ -452,13 +473,10 @@ class TestOpsManager:
|
||||
target_type="database",
|
||||
target_id="postgres-001",
|
||||
check_type="tcp",
|
||||
check_config={
|
||||
"host": "db.insightflow.io",
|
||||
"port": 5432
|
||||
},
|
||||
check_config={"host": "db.insightflow.io", "port": 5432},
|
||||
interval=30,
|
||||
timeout=5,
|
||||
retry_count=2
|
||||
retry_count=2,
|
||||
)
|
||||
self.log(f"Created TCP health check: {check2.name} (ID: {check2.id})")
|
||||
|
||||
@@ -498,7 +516,7 @@ class TestOpsManager:
|
||||
failover_trigger="health_check_failed",
|
||||
auto_failover=False,
|
||||
failover_timeout=300,
|
||||
health_check_id=None
|
||||
health_check_id=None,
|
||||
)
|
||||
|
||||
self.log(f"Created failover config: {config.name} (ID: {config.id})")
|
||||
@@ -512,8 +530,7 @@ class TestOpsManager:
|
||||
|
||||
# 发起故障转移
|
||||
event = self.manager.initiate_failover(
|
||||
config_id=config.id,
|
||||
reason="Primary region health check failed"
|
||||
config_id=config.id, reason="Primary region health check failed"
|
||||
)
|
||||
|
||||
if event:
|
||||
@@ -557,7 +574,7 @@ class TestOpsManager:
|
||||
retention_days=30,
|
||||
encryption_enabled=True,
|
||||
compression_enabled=True,
|
||||
storage_location="s3://insightflow-backups/"
|
||||
storage_location="s3://insightflow-backups/",
|
||||
)
|
||||
|
||||
self.log(f"Created backup job: {job.name} (ID: {job.id})")
|
||||
@@ -613,7 +630,7 @@ class TestOpsManager:
|
||||
avg_utilization=0.08,
|
||||
idle_time_percent=0.85,
|
||||
report_date=report_date,
|
||||
recommendations=["Consider downsizing this resource"]
|
||||
recommendations=["Consider downsizing this resource"],
|
||||
)
|
||||
|
||||
self.log("Recorded 5 resource utilization records")
|
||||
@@ -621,9 +638,7 @@ class TestOpsManager:
|
||||
# 生成成本报告
|
||||
now = datetime.now()
|
||||
report = self.manager.generate_cost_report(
|
||||
tenant_id=self.tenant_id,
|
||||
year=now.year,
|
||||
month=now.month
|
||||
tenant_id=self.tenant_id, year=now.year, month=now.month
|
||||
)
|
||||
|
||||
self.log(f"Generated cost report: {report.id}")
|
||||
@@ -639,9 +654,10 @@ class TestOpsManager:
|
||||
idle_list = self.manager.get_idle_resources(self.tenant_id)
|
||||
for resource in idle_list:
|
||||
self.log(
|
||||
f" Idle resource: {
|
||||
resource.resource_name} (est. cost: {
|
||||
resource.estimated_monthly_cost}/month)")
|
||||
f" Idle resource: {resource.resource_name} (est. cost: {
|
||||
resource.estimated_monthly_cost
|
||||
}/month)"
|
||||
)
|
||||
|
||||
# 生成成本优化建议
|
||||
suggestions = self.manager.generate_cost_optimization_suggestions(self.tenant_id)
|
||||
@@ -649,7 +665,9 @@ class TestOpsManager:
|
||||
|
||||
for suggestion in suggestions:
|
||||
self.log(f" Suggestion: {suggestion.title}")
|
||||
self.log(f" Potential savings: {suggestion.potential_savings} {suggestion.currency}")
|
||||
self.log(
|
||||
f" Potential savings: {suggestion.potential_savings} {suggestion.currency}"
|
||||
)
|
||||
self.log(f" Confidence: {suggestion.confidence}")
|
||||
self.log(f" Difficulty: {suggestion.difficulty}")
|
||||
|
||||
@@ -667,9 +685,14 @@ class TestOpsManager:
|
||||
|
||||
# 清理
|
||||
with self.manager._get_db() as conn:
|
||||
conn.execute("DELETE FROM cost_optimization_suggestions WHERE tenant_id = ?", (self.tenant_id,))
|
||||
conn.execute(
|
||||
"DELETE FROM cost_optimization_suggestions WHERE tenant_id = ?",
|
||||
(self.tenant_id,),
|
||||
)
|
||||
conn.execute("DELETE FROM idle_resources WHERE tenant_id = ?", (self.tenant_id,))
|
||||
conn.execute("DELETE FROM resource_utilizations WHERE tenant_id = ?", (self.tenant_id,))
|
||||
conn.execute(
|
||||
"DELETE FROM resource_utilizations WHERE tenant_id = ?", (self.tenant_id,)
|
||||
)
|
||||
conn.execute("DELETE FROM cost_reports WHERE tenant_id = ?", (self.tenant_id,))
|
||||
conn.commit()
|
||||
self.log("Cleaned up cost optimization test data")
|
||||
@@ -699,10 +722,12 @@ class TestOpsManager:
|
||||
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
test = TestOpsManager()
|
||||
test.run_all_tests()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user