python
复制代码
from django.test import TestCase, Client
from django.utils import timezone
from datetime import timedelta
from ..models import TicketModify
import json
class TicketModifyTestCase(TestCase):
def setUp(self):
self.client = Client()
self.url = '/api/ticket/modify/'
# 创建测试数据
now = timezone.now()
# 今天的数据
today_str = now.strftime('%Y-%m-%d')
TicketModify.objects.create(
modify_system="System1",
start_time=f"{today_str} 10:00:00",
modify_type="Type1",
modify_result="Success",
modify_model="Model1",
modify_status="Done",
modify_title="Today's Ticket"
)
# 本周的数据(周一)
monday = now - timedelta(days=now.weekday())
monday_str = monday.strftime('%Y-%m-%d')
TicketModify.objects.create(
modify_system="System2",
start_time=f"{monday_str} 09:00:00",
modify_type="Type2",
modify_result="Success",
modify_model="Model2",
modify_status="Done",
modify_title="This Week's Ticket"
)
# 本月的数据(月初)
first_day = now.replace(day=1)
first_day_str = first_day.strftime('%Y-%m-%d')
TicketModify.objects.create(
modify_system="System3",
start_time=f"{first_day_str} 08:00:00",
modify_type="Type3",
modify_result="Success",
modify_model="Model3",
modify_status="Done",
modify_title="This Month's Ticket"
)
# 上个月的数据(用于测试不应返回的数据)
last_month = now.replace(day=1) - timedelta(days=1)
last_month_str = last_month.strftime('%Y-%m-%d')
TicketModify.objects.create(
modify_system="System4",
start_time=f"{last_month_str} 07:00:00",
modify_type="Type4",
modify_result="Success",
modify_model="Model4",
modify_status="Done",
modify_title="Last Month's Ticket"
)
# 创建测试数据
test_data = [
# 今天
{
"start_time": now.strftime('%Y-%m-%d') + " 10:00:00",
"title": "Today's Ticket"
},
# 本周(周一)
{
"start_time": (now - timedelta(days=now.weekday())).strftime('%Y-%m-%d') + " 09:00:00",
"title": "This Week's Ticket"
},
# 本月1号
{
"start_time": now.replace(day=1).strftime('%Y-%m-%d') + " 08:00:00",
"title": "This Month's Ticket"
},
# 今年1月1号
{
"start_time": now.replace(month=1, day=1).strftime('%Y-%m-%d') + " 07:00:00",
"title": "This Year's Ticket"
},
# 去年数据
{
"start_time": (now - timedelta(days=365)).strftime('%Y-%m-%d') + " 06:00:00",
"title": "Last Year's Ticket"
}
]
for data in test_data:
TicketModify.objects.create(
modify_system="TestSystem",
start_time=data['start_time'],
modify_type="TestType",
modify_result="Success",
modify_model="TestModel",
modify_status="Done",
modify_title=data['title']
)
def test_today_action_success(self):
"""测试获取今天的数据"""
data = {'action': 'today'}
response = self.client.get(
self.url,
data=json.dumps(data),
content_type='application/json'
)
self.assertEqual(response.status_code, 200)
result = json.loads(response.content)
self.assertTrue(result['result'])
self.assertEqual(len(result['data']), 1)
self.assertEqual(result['data'][0]['modify_title'], "Today's Ticket")
def test_week_action_success(self):
"""测试获取本周的数据"""
data = {'action': 'week'}
response = self.client.get(
self.url,
data=json.dumps(data),
content_type='application/json'
)
self.assertEqual(response.status_code, 200)
result = json.loads(response.content)
self.assertTrue(result['result'])
# 应该包含今天和本周一的数据
self.assertEqual(len(result['data']), 2)
titles = [item['modify_title'] for item in result['data']]
self.assertIn("Today's Ticket", titles)
self.assertIn("This Week's Ticket", titles)
def test_month_action_success(self):
"""测试获取本月的数据"""
data = {'action': 'month'}
response = self.client.get(
self.url,
data=json.dumps(data),
content_type='application/json'
)
self.assertEqual(response.status_code, 200)
result = json.loads(response.content)
self.assertTrue(result['result'])
# 应该包含今天、本周一和本月1号的数据
self.assertEqual(len(result['data']), 3)
titles = [item['modify_title'] for item in result['data']]
self.assertIn("Today's Ticket", titles)
self.assertIn("This Week's Ticket", titles)
self.assertIn("This Month's Ticket", titles)
def test_year_action_success(self):
"""测试获取本年的数据"""
data = {'action': 'year'}
response = self.client.get(
self.url,
data=json.dumps(data),
content_type='application/json'
)
self.assertEqual(response.status_code, 200)
result = json.loads(response.content)
self.assertTrue(result['result'])
# 应该包含今年所有数据(4条)
self.assertEqual(len(result['data']), 4)
titles = [item['modify_title'] for item in result['data']]
self.assertIn("Today's Ticket", titles)
self.assertIn("This Week's Ticket", titles)
self.assertIn("This Month's Ticket", titles)
self.assertIn("This Year's Ticket", titles)
self.assertNotIn("Last Year's Ticket", titles)
def test_invalid_action(self):
"""测试无效的action参数"""
data = {'action': 'invalid'}
response = self.client.get(
self.url,
data=json.dumps(data),
content_type='application/json'
)
self.assertEqual(response.status_code, 200)
result = json.loads(response.content)
# 无效参数应该返回所有数据(根据你的业务逻辑可能需要调整)
self.assertTrue(result['result'])
self.assertEqual(len(result['data']), 4)
def test_missing_action(self):
"""测试缺少action参数"""
response = self.client.get(
self.url,
content_type='application/json'
)
self.assertEqual(response.status_code, 200)
result = json.loads(response.content)
# 缺少参数应该返回所有数据(根据你的业务逻辑可能需要调整)
self.assertTrue(result['result'])
self.assertEqual(len(result['data']), 4)
def test_empty_action(self):
"""测试空action参数"""
data = {'action': ''}
response = self.client.get(
self.url,
data=json.dumps(data),
content_type='application/json'
)
self.assertEqual(response.status_code, 200)
result = json.loads(response.content)
# 空参数应该返回所有数据(根据你的业务逻辑可能需要调整)
self.assertTrue(result['result'])
self.assertEqual(len(result['data']), 4)
python
复制代码
"""
@api {GET} /api/ticket/modify/ 获取工单变更记录
@apiName GetTicketModify
@apiGroup Ticket
@apiDescription 根据时间范围获取工单变更记录
@apiHeader {String} Content-Type application/json
@apiParam {String} action 时间范围筛选条件 [today|week|month|year]
@apiParamExample {json} 请求示例:
{
"action": "today"
}
@apiSuccess {Boolean} result 请求是否成功
@apiSuccess {Number} code 返回码
@apiSuccess {String} message 返回信息
@apiSuccess {Object[]} data 工单变更记录列表
@apiSuccess {String} data.modify_system 所属业务系统
@apiSuccess {String} data.start_time 实际开始时间
@apiSuccess {String} data.modify_type 变更类型
@apiSuccess {String} data.modify_result 变更结果
@apiSuccess {String} data.modify_model 所属模块
@apiSuccess {String} data.modify_status 工单状态
@apiSuccess {String} data.modify_title 标题
@apiSuccessExample {json} 成功响应:
HTTP/1.1 200 OK
{
"result": true,
"code": 0,
"message": "",
"data": [
{
"modify_system": "业务系统A",
"start_time": "2023-05-20 10:00:00",
"modify_type": "配置变更",
"modify_result": "成功",
"modify_model": "核心模块",
"modify_status": "已完成",
"modify_title": "数据库配置变更"
}
]
}
@apiErrorExample {json} 错误响应:
HTTP/1.1 200 OK
{
"result": false,
"code": 1,
"message": "参数错误",
"data": []
}
"""
@require_GET
@csrf_exempt
@login_exempt
def ticket_modify(request):
try:
# 解析请求数据
request_data = json.loads(request.body) if request.body else {}
action = request_data.get('action', '').lower()
# 获取当前时间
now = timezone.now()
current_year = now.year
# 初始化查询集
queryset = TicketModify.objects.all()
# 根据action参数过滤数据
if action == 'today':
today_str = now.strftime('%Y-%m-%d')
queryset = queryset.filter(start_time__startswith=today_str)
elif action == 'week':
start_of_week = now - timedelta(days=now.weekday())
start_of_week_str = start_of_week.strftime('%Y-%m-%d')
end_of_week = start_of_week + timedelta(days=6)
end_of_week_str = end_of_week.strftime('%Y-%m-%d')
queryset = queryset.filter(start_time__range=(start_of_week_str, end_of_week_str))
elif action == 'month':
first_day = now.replace(day=1)
last_day = now.replace(day=calendar.monthrange(now.year, now.month)[1])
first_day_str = first_day.strftime('%Y-%m-%d')
last_day_str = last_day.strftime('%Y-%m-%d')
queryset = queryset.filter(start_time__range=(first_day_str, last_day_str))
elif action == 'year':
first_day = now.replace(month=1, day=1)
last_day = now.replace(month=12, day=31)
first_day_str = first_day.strftime('%Y-%m-%d')
last_day_str = last_day.strftime('%Y-%m-%d')
queryset = queryset.filter(start_time__range=(first_day_str, last_day_str))
data_list = list(queryset.values(
'modify_system', 'start_time', 'modify_type',
'modify_result', 'modify_model', 'modify_status',
'modify_title'
))
return JsonResponse({
"result": True,
"code": 0,
"message": "",
"data": data_list
})
except Exception as e:
logger.error(f"ticket_modify error: {str(e)}")
return JsonResponse({
"result": False,
"code": 1,
"message": str(e),
"data": []
})