Commit f429ee6c authored by huangqiang's avatar huangqiang

1期用例全部完成

parent f6439b6f
# Created by pytest automatically.
*.pyc
report/
temp
*.har
*.xml
script/base_api
\ No newline at end of file
script/base_api
debug.py
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/script/ji_yun_ying_pc/statistical_report/.pytest_cache" />
<excludeFolder url="file://$MODULE_DIR$/.pytest_cache" />
<excludeFolder url="file://$MODULE_DIR$/report" />
</content>
<orderEntry type="jdk" jdkName="Python 3.7 (GeekInterfaceTest)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
......
......@@ -27,6 +27,24 @@ def get_time_diff(start, end):
return diff
# 四舍五入保留位数
def public_round(value, num=2):
"""
:num:要保留的位数,默认两位
"""
from decimal import Decimal
rule = "0." + "0" * num
return Decimal(str(value)).quantize(Decimal(rule), rounding="ROUND_HALF_UP")
# 获取两位小数的百分比字符串
def get_two_percentage(num) -> str:
"""
:num:要转换的数字
"""
return "{:.2%}".format(public_round(num, 4))
def get_page_num(page_number, page_size):
try:
page_number = int(page_number) if int(page_number) >= 1 else 1
......
......@@ -4,6 +4,7 @@ from datetime import timedelta
class GetTime:
@staticmethod
def get_current_time():
current_now = datetime.datetime.now()
......@@ -93,6 +94,44 @@ class GetTime:
**GetTime.get_today_before(30)
}
# 获取两个日期之间的所有日期
@staticmethod
def get_every_day(begin_date, end_date):
# 前闭后闭
date_list = []
begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
while begin_date <= end_date:
date_str = begin_date.strftime("%Y-%m-%d")
date_list.append(date_str)
begin_date += datetime.timedelta(days=1)
return date_list
# 获取两个日期之间的日期信息
@staticmethod
def get_week_info(begin_date, end_date):
"""
:return: [{'year': 2022, 'week': 1, 'year_week': '2022_1', 'day': 5, 'date_data': '2022-01-07'}]
"""
week_data = []
for date_data in GetTime.get_every_day(begin_date, end_date):
year, week, day = datetime.date(int(date_data[0:4]), int(date_data[5:7]), int(date_data[8:10])).isocalendar()
week_data.append({
"year_week": f"{year}_{week}",
"day": day,
"date_data": date_data
})
return week_data
@staticmethod
def get_before_date_by_date(date_str, num=1):
"""
:date_str: 日期
:num: 几天前
:return: 返回输入的日期的num天前的日期(如果num为负数,返回num后的日期)
"""
return (datetime.datetime.strptime(date_str, "%Y-%m-%d") - timedelta(days=num)).strftime("%Y-%m-%d")
# 获取当前时间毫秒数
@staticmethod
def get_current_time_millis():
......@@ -101,18 +140,6 @@ class GetTime:
# now = datetime.datetime.now()
# # 今天
# today = now.strftime("%Y-%m-%d %H:%M:%S")
# print("今天")
# print(today)
# # 昨天
# yesterday = now - timedelta(days=1)
# print("昨天")
# print(yesterday)
# # 明天
# tomorrow = now + timedelta(days=1)
# print("明天")
# print(tomorrow)
# 当前季度
# now_quarter = now.month/3 if now.month % 3 == 0 else now.month / 3 + 1
# print("当前季度")
......@@ -162,4 +189,6 @@ if __name__ == "__main__":
# print(GetTime.get_this_month())
# print(GetTime.get_today_before(5))
# print(GetTime.get_today_after(5))
print(GetTime.get_all())
# print(GetTime.get_all())
print(GetTime.get_before_date_by_date("2021-05-01", -2))
pass
\ No newline at end of file
# coding:utf-8
import requests
import json
from common.common_util import replace_string
from json.decoder import JSONDecodeError
from common.common_config import common_config
from urllib3.connectionpool import InsecureRequestWarning
import urllib3
urllib3.disable_warnings(InsecureRequestWarning)
request_data_template = """
${api_name}
${run_method} ${url}${params_str}
${header_str}
${body_str}
"""
class RunMethod:
@staticmethod
def run_request(run_method, url, params=None, body=None, header=None, return_json=True, **kwargs):
host = kwargs.get("host")
config_host = common_config.get("host")
host = host or config_host
api_name = kwargs.get("name")
if not url.startswith("http"):
url = host + url
time_out = kwargs.get("time_out") if kwargs.get("time_out") else 60
if isinstance(body, dict) or isinstance(body, list):
body_str = json.dumps(body, ensure_ascii=False)
body = json.dumps(body, ensure_ascii=False).encode()
else:
body_str = str(body)
try:
host = kwargs.get("host")
config_host = common_config.get("host")
host = host or config_host
api_name = kwargs.get("name")
if not url.startswith("http"):
url = host + url
time_out = kwargs.get("time_out") if kwargs.get("time_out") else 60
if isinstance(body, dict) or isinstance(body, list):
body = json.dumps(body, ensure_ascii=False).encode()
if run_method == 'POST':
res = requests.post(url, data=body, params=params, headers=header, timeout=time_out, verify=False)
elif run_method == 'GET':
......@@ -45,6 +56,28 @@ class RunMethod:
res = {"err_msg": str(e)}
# print(res)
import allure
params_str = ""
if isinstance(params, dict) and params:
params_str = "?"
for k, v in params.items():
params_str = params_str + str(k) + "=" + str(v) + "&"
else:
if params:
params_str = "?" + str(params)
header_str = ""
if isinstance(header, dict):
for k, v in header.items():
header_str = header_str + str(k) + ":" + str(v) + "\r\n"
request_data_dict = {
"api_name": api_name,
"run_method": run_method,
"url": url,
"params_str": params_str,
"header_str": header_str,
"body_str": body_str
}
request_data = replace_string(request_data_template, request_data_dict)
allure.attach(body=request_data, name='请求信息信息', attachment_type=allure.attachment_type.TEXT)
if return_json:
allure.attach(body=json.dumps(res, ensure_ascii=False), name='响应信息', attachment_type=allure.attachment_type.JSON)
else:
......
# print('{:.2%}'.format( round(0.65645 , 4)))
# print(round(0.65635, 2))
# def public_round(value, rule="0.00"):
# from decimal import Decimal
# return Decimal(str(value)).quantize(Decimal(rule), rounding="ROUND_HALF_UP")
def public_round(value, num=2):
from decimal import Decimal
rule = "0." + "0" * num
return Decimal(str(value)).quantize(Decimal(rule), rounding="ROUND_HALF_UP")
# print('{:.2%}'.format( public_round(0.0 / 1 , 4)))
print((1-0) == 1)
\ No newline at end of file
import pika
auth = pika.PlainCredentials('admin', '123456')
connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.32.50', port=5672))
channel = connection.channel()
channel.queue_declare(queue='TEST01')
def callback(ch, method, properties, body):
print(ch)
print(method)
print(properties)
print(" [x] Received %r" % body)
channel.basic_consume(on_message_callback=callback,
queue='TEST01',
auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
\ No newline at end of file
import pika
auth = pika.PlainCredentials("admin", "123456")
connect = pika.BlockingConnection(pika.ConnectionParameters(host="192.168.32.50", port=5672))
channel = connect.channel()
channel.queue_declare(queue='TEST01')
channel.basic_publish(exchange='', routing_key='TEST01', body='Hello World!')
print(" [x] Sent 'Hello World!'")
connect.close()
\ No newline at end of file
......@@ -32,3 +32,6 @@ toml==0.10.2
typing-extensions==3.7.4.3
urllib3==1.26.2
zipp==3.4.0
pika~=1.2.0
pandas~=1.2.4
\ No newline at end of file
......@@ -2,18 +2,64 @@ import pytest
import os
from common.operation_time import GetTime
class RunTest:
def __init__(self, case_path_list, host="https://yf1.jkwljy.com", account_group="A", db_config="yf1", path_dir=None):
path_dir = path_dir or GetTime.get_current_time().get("current_time_num")
print(path_dir)
self.allure_report_xml_path = f"./report/{path_dir}/xml"
self.allure_report_html_path = f"./report/{path_dir}/html"
self.case_path_list = case_path_list
self.host = host
self.account_group = account_group
self.db_config = db_config
def run_test(self):
"""
:case_path_list:用例路径列表
:allure_report_xml_path: 报告的xml路径
:host: 运行的环境
:account_group: 运行的账户组
:db_config: 测试时使用的数据库配置
"""
run_config = [
"-s",
"-q",
*self.case_path_list,
"--alluredir", self.allure_report_xml_path,
"--host", self.host,
"--account", self.account_group,
"--db", self.db_config
]
return pytest.main(run_config)
def collection_case(self):
run_config = [
*self.case_path_list,
"--host", self.host,
"--account", self.account_group,
"--db", self.db_config,
"--collect-only"
]
return pytest.main(run_config)
# 生成allure报告
def generate_allure_report(self, allure_path="/Users/huangqiang/WorkPlace/allure-2.13.8/bin/allure"):
# os模块运行allure命令,来生成html格式的报告(根据刚刚生成的配置信息)
os.system(f"{allure_path} generate {self.allure_report_xml_path} -o {self.allure_report_html_path} --clean")
if __name__ == '__main__':
time_num = GetTime.get_current_time().get("current_time_num")
print(time_num)
report_xml_path = f"./report/{time_num}/xml"
report_html_path = f"./report/{time_num}/html"
run_config = [
"-s", "./script/ji_yun_ying_pc/statistical_report/test_business_statistics.py::TestContinueRate::test_more_search",
"--alluredir", report_xml_path,
"--host", "http://192.168.32.36",
"--account", "A",
"--db", "36"
case_path_list = [
"./script/ji_yun_ying_pc/statistical_report/test_business_statistics.py::TestFullClassRate::test_max_class_type_search"
]
x = pytest.main(run_config)
# os模块运行allure命令,来生成html格式的报告(根据刚刚生成的配置信息)
os.system(f"/Users/huangqiang/WorkPlace/allure-2.13.8/bin/allure generate {report_xml_path} -o {report_html_path} --clean")
host = "https://yf1.jkwljy.com"
account_group = "A"
db_config = "yf1"
run_obj = RunTest(case_path_list, host=host, account_group=account_group, db_config=db_config)
run_obj.run_test()
# run_obj.collection_case()
run_obj.generate_allure_report()
from script.base_api.service_public.targets import targets_setDef_targetId_patch
from script.global_data_config.global_data import GlobalDataConfig
from script.default_header import jyy_header
class TargetSet:
def __init__(self, school_area_id, target_data: dict, target=None):
"""
:target_data: 目标设置的数据all_count,continue_class,expand_class,expand_subject,new_student,boutique为键的字典
字典的值为连个数据的元祖,第一个元素为对应的基础目标,第二个元素为对应的挑战目标,对应的键不存在,对应数据设置为0
:target:目标方案,不传时使用默认目标方案
"""
if target is None:
target = GlobalDataConfig().default_target
all_count = target_data.get("all_count") or (0, 0)
continue_class = target_data.get("continue_class") or (0, 0)
expand_class = target_data.get("expand_class") or (0, 0)
expand_subject = target_data.get("expand_subject") or (0, 0)
new_student = target_data.get("new_student") or (0, 0)
boutique = target_data.get("boutique") or (0, 0)
special_class = target_data.get("special_class") or (0, 0)
self.details = [
{"schoolArea": school_area_id, "type": "ALL_COUNT_TARGET", "target": all_count[0], "category": "PERSONTIME"},
{"schoolArea": school_area_id, "type": "ALL_COUNT_CHALLENGE_TARGET", "target": all_count[1], "category": "PERSONTIME"},
{"schoolArea": school_area_id, "type": "CONTINUE_CLASS_TARGET", "target": continue_class[0], "category": "PERSONTIME"},
{"schoolArea": school_area_id, "type": "CONTINUE_CLASS_CHALLENGE_TARGET", "target": continue_class[0], "category": "PERSONTIME"},
{"schoolArea": school_area_id, "type": "EXPAND_CLASS_TARGET", "target": expand_class[0], "category": "PERSONTIME"},
{"schoolArea": school_area_id, "type": "EXPAND_CLASS_CHALLENGE_TARGET", "target": expand_class[1], "category": "PERSONTIME"},
{"schoolArea": school_area_id, "type": "EXPAND_SUBJECT_TARGET", "target": expand_subject[0], "category": "PERSONTIME"},
{"schoolArea": school_area_id, "type": "EXPAND_SUBJECT_CHALLENGE_TARGET", "target": expand_subject[1], "category": "PERSONTIME"},
{"schoolArea": school_area_id, "type": "NEW_STUDENT_TARGET", "target": new_student[0], "category": "PERSONTIME"},
{"schoolArea": school_area_id, "type": "NEW_STUDENT_CHALLENGE_TARGET", "target": new_student[1], "category": "PERSONTIME"},
{"schoolArea": school_area_id, "type": "BOUTIQUE_TARGET", "target": boutique[0], "category": "PERSONTIME"},
{"schoolArea": school_area_id, "type": "BOUTIQUE_CHALLENGE_TARGET", "target": boutique[1], "category": "PERSONTIME"},
{"schoolArea": school_area_id, "type": "SPECIAL_CLASS_TARGET", "target": special_class[0], "category": "PERSONTIME"},
{"schoolArea": school_area_id, "type": "SPECIAL_CLASS_CHALLENGE_TARGET", "target": special_class[1], "category": "PERSONTIME"}
]
self.endDateStr = target.get("end_time")
self.endTime = f"{target.get('end_time')} 00:00:00"
self.entryGrades = {target.get('entry_grades')}
self.exquisiteDateStr = f"{target.get('exquisite_start_time')} - {target.get('exquisite_end_time')}"
self.exquisiteEndTime = f"{target.get('exquisite_end_time')} 00:00:00"
self.exquisiteStartTime = f"{target.get('exquisite_start_time')} 00:00:00"
self.id = target.get('target_id') or target.get('id')
self.isDefault = target.get('is_default')
self.lastEndDateStr = target.get('last_end_time')
self.lastEndTime = f"{target.get('last_end_time')} 00:00:00"
self.name = target.get("name")
self.orderNum = target.get("order_num")
self.term = target.get("term")
self.year = target.get("year")
def run(self, other_field: dict = {}, header=jyy_header, return_json=True, **kwargs):
body = {**self.__dict__, **other_field}
return targets_setDef_targetId_patch(self.id, body=body, header=header, return_json=return_json, **kwargs)
from script.base_api.service_statistics.statistics import statistics_personTime_post
from script.base_api.service_statistics.statistics import statistics_query_continue_post
from script.base_api.service_statistics.statistics import statistics_refundRate_post
from script.base_api.service_statistics.statistics import statistics_fullClass_rate_post
from script.base_api.service_statistics.statistics import statistics_supplementaryPayment_post
from script.default_header import jyy_header
from common.operation_time import GetTime
# 成都一区的校区ID
cd1_school_area_id = [3104, 3166, 3334, 3335, 3337, 3339, 3340, 3373, 3158, 2371, 2389, 2400,
3069, 3099, 3149, 2397, 2398, 3044, 3054, 3063, 2369, 2385, 2386, 2388,
2399, 2401, 3097, 3137, 3155, 3156, 2416, 3039, 3065, 3167, 2368, 3071]
class PersonTime:
def __init__(self, pageNum=1, pageSize=10, createTime=None, year="2021", term="暑", groups=None, schoolIds=None, refundType="teacherRefund"):
self.pageNum = pageNum
self.pageSize = pageSize
self.createTime = createTime or GetTime.get_today().get("today_date")
self.year = year
self.term = term
self.groups = groups or ["big_area_id", "area_id", "school_area_id"]
self.schoolIds = schoolIds or cd1_school_area_id
self.refundType = refundType
def run(self, other_field: dict = {}, header=jyy_header, return_json=True, **kwargs):
body = {**self.__dict__, **other_field}
return statistics_personTime_post(body=body, header=header, return_json=return_json, **kwargs)
class ContinueRate:
def __init__(self, pageNum=1, pageSize=10, createTime=None, year="2021", term="暑", groups=None, schoolIds=None, refundType="teacherRefund"):
self.pageNum = pageNum
self.pageSize = pageSize
self.createTime = createTime or GetTime.get_today().get("today_date")
self.year = year
self.term = term
self.groups = groups or ["big_area_id", "area_id", "school_area_id"]
self.schoolIds = schoolIds or cd1_school_area_id
self.refundType = refundType
def run(self, other_field: dict = {}, header=jyy_header, return_json=True, **kwargs):
body = {**self.__dict__, **other_field}
return statistics_query_continue_post(body=body, header=header, return_json=return_json, **kwargs)
class RefundRate:
def __init__(self, pageNum=1, pageSize=10, createTime=None, year="2021", term="暑", groups=None, schoolIds=None, refundType="schoolRefund"):
self.pageNum = pageNum
self.pageSize = pageSize
self.createTime = createTime or GetTime.get_today().get("today_date")
self.year = year
self.term = term
self.groups = groups or ["big_area_id", "area_id", "school_area_id"]
self.schoolIds = schoolIds or cd1_school_area_id
self.refundType = refundType
def run(self, other_field: dict = {}, header=jyy_header, return_json=True, **kwargs):
body = {**self.__dict__, **other_field}
return statistics_refundRate_post(body=body, header=header, return_json=return_json, **kwargs)
class FullClassRate:
def __init__(self, pageNum=1, pageSize=10, createTime=None, year="2021", term="暑", groups=None, schoolIds=None, refundType="teacherRefund"):
self.pageNum = pageNum
self.pageSize = pageSize
self.createTime = createTime or GetTime.get_today().get("today_date")
self.year = year
self.term = term
self.groups = groups or ["big_area_id", "area_id", "school_area_id"]
self.schoolIds = schoolIds or cd1_school_area_id
self.refundType = refundType
def run(self, other_field: dict = {}, header=jyy_header, return_json=True, **kwargs):
body = {**self.__dict__, **other_field}
return statistics_fullClass_rate_post(body=body, header=header, return_json=return_json, **kwargs)
class FillRate:
def __init__(self, pageNum=1, pageSize=10, createTime=None, year="2021", term="暑", groups=None, schoolIds=None, refundType="teacherRefund"):
self.pageNum = pageNum
self.pageSize = pageSize
self.createTime = createTime or GetTime.get_today().get("today_date")
self.year = year
self.term = term
self.groups = groups or ["big_area_id", "area_id", "school_area_id"]
self.schoolIds = schoolIds or cd1_school_area_id
self.refundType = refundType
def run(self, other_field: dict = {}, header=jyy_header, return_json=True, **kwargs):
body = {**self.__dict__, **other_field}
return statistics_supplementaryPayment_post(body=body, header=header, return_json=return_json, **kwargs)
......@@ -22,6 +22,60 @@ def pytest_sessionstart(session):
common_config["db_config"] = db_configs.get(session.config.getoption('--db'))
# 获取收集的用例
# def pytest_collection_modifyitems(session, config, items):
# all_test = []
# all_node = set()
# for item in items:
# node_id = item.nodeid
# real_node, method_name = str(node_id).split("[", 1)
# all_node.add(real_node)
# all_node_list = list(all_node)
# for node in all_node_list:
# module_path, class_method_name = str(node).split("::", 1)
# class_path = str(node).rsplit("::", 1)[0]
# package_path, module_name = module_path.rsplit("/", 1)
# package_case = {
# "type": "package",
# "path": package_path,
# "name": package_path.rsplit("/", 1)[-1],
# "parent": None
# }
# all_test.append(package_case)
# module_case = {
# "type": "module",
# "path": module_path,
# "name": module_path.rsplit("/", 1)[-1],
# "parent": package_path
# }
# all_test.append(module_case)
# class_case = {
# "type": "class",
# "path": class_path,
# "name": class_path.split("::", 1)[-1],
# "parent": module_path
# }
# all_test.append(class_case)
# method_case = {
# "type": "method",
# "path": node,
# "name": node.split("::", 2)[-1],
# "parent": class_path
# }
# all_test.append(method_case)
# # 去重
# new_all_test = []
# for x in all_test:
# is_data = [y for y in new_all_test if x.get("name") == y.get("name")
# and x.get("path") == y.get("path")
# and x.get("type") == y.get("type")
# and x.get("parent") == y.get("parent")
# ]
# if not is_data:
# new_all_test.append(x)
# print(new_all_test)
@pytest.fixture(scope='session', autouse=True)
def get_host(pytestconfig):
# 初始化测试环境变量
......
......@@ -66,5 +66,27 @@ accounts = {
"account": "xxxx",
"password": "xxxx"
}
}
},
"线上": {
# 极运营账号
"jyy_account": {
"account": "15360956010",
"password": "hqqwert123456"
},
# 极运营app默认账号
"jyy_app_account": {
"account": "15360956010",
"password": "hqqwert123456"
},
# 家长默认账号
"jz_app_account": {
"account": "xxxx",
"password": "xxxx"
},
# gos微信小程序默认账号
"gos_account": {
"account": "xxxx",
"password": "xxxx"
}
},
}
from common.operation_time import GetTime
from common.connect_db import OperationDb
class GlobalDataConfig:
def __init__(self):
self.year = [2019, 2020, 2021, 2022]
self.grade = ["零年级", "一年级", "二年级", "三年级", "四年级", "五年级", "六年级", "七年级", "八年级", "九年级", "高一", "高二", "高三"]
self.term = ["春", "暑", "秋", "寒"]
# 学段
self.learning_period = ["小低", "小高", "初中", "高中"]
# 小低
self.small_low = ["一年级", "二年级", "三年级"]
# 小高
self.small_high = ["四年级", "五年级", "六年级"]
# 初中
self.junior_high = ["七年级", "八年级", "九年级"]
# 高中
self.high_school = ["高一", "高二", "高三"]
self.subject = ["语文", "英语", "物理", "数学", "化学"]
self.course_type = ["常规班课", "精品定制课", "服务班课", "集训班课", "专题班课"]
self.class_type = {
"常规班课": ["极趣班", "极思班", "极智班", "极客班", "极客A班", "极客蓝队班", "五四极趣班", "五四极思班", "五四极智班", "新生", "人教班", "八人精品", "定制班"],
"精品定制课": ["一对一定制班", "一对三定制班", "一对八定制班", "一对六定制班"],
"服务班课": ["公开课", "辅导课", "讲座"],
"集训班课": ["五年级选修课班", "五四制班", "知识体系复习课班"],
"专题班课": ["专题"]
}
# 常规班课
self.routine_class_type = self.class_type.get("常规班课")
# 精品定制课
self.boutique_class_type = self.class_type.get("精品定制课")
# 服务班课
self.service_class_type = self.class_type.get("服务班课")
# 专题班课
self.special_class_type = self.class_type.get("专题班课")
# 集训班课
self.ji_xun__class_type = self.class_type.get("集训班课")
# 期数
self.phase = [1, 0, 2, 3, 4]
# 价格类型
self.priceType = ["低价", "正价"]
# 学生类型
self.studentType = ["老生", "新生"]
# 测试校区
self.test_school_area = [3074, 3076, 3345, 3047, 3049, 3095, 2383, 3015, 3052]
# 今天日期
self.today_date = GetTime.get_today().get("today_date")
# 30天前的日期
self.before_date_30 = GetTime.get_today_before(30).get("before_date_30")
# 所有目标方案
self.all_target = GlobalDataConfig.get_target()
# 默认目标方案
self.default_target = [x for x in self.all_target if x.get("is_default") == "是"][0]
# 所有大区ID
self.all_big_area_id = GlobalDataConfig.get_department_id(20)
# 所有区域ID
self.all_area_id = GlobalDataConfig.get_department_id(30)
# 所有校区ID
self.all_school_area_id = GlobalDataConfig.get_department_id()
# 获取所有班型
def get_all_class_type(self):
all_class_type = []
for v in self.class_type.values():
all_class_type = [*all_class_type, *v]
return all_class_type
@staticmethod
def get_department_id(department_type=30):
sql = f"""select id from service_user.department where type = {department_type}"""
school_area_datas = OperationDb.query_sql(sql)
school_area_ids = [x[0] for x in school_area_datas]
return school_area_ids
@staticmethod
def get_school_area_id_map():
sql = """select id,name from service_user.department where type = 30"""
school_area_datas = OperationDb.query_sql(sql)
return {x[0]: x[1] for x in school_area_datas}
# 获取所有目标方案
@staticmethod
def get_target():
sql = """
SELECT id,year,term,name,end_time,last_end_time,exquisite_start_time,exquisite_end_time,is_default,entry_grades,order_num
FROM public.target_plan
"""
targets = OperationDb.query_sql(sql)
targets = [
{
"target_id": x[0],
"year": x[1],
"term": x[2],
"name": x[3],
"end_time": str(x[4]),
"last_end_time": str(x[5]),
"exquisite_start_time": str(x[6]),
"exquisite_end_time": str(x[7]),
"is_default": x[8],
"entry_grades": x[9],
"order_num": x[10]
}
for x in targets
]
return targets
# 使用分页总数和每页数量获取分页数据
@staticmethod
def get_page_num_and_size(total, size):
"""
:total:记录条数
:size:每页数量
:return: 返回分页数组,单个元素为元组,0:page_num,1:page_size
"""
num = 0
num_and_size = []
for x in range(0, total, size):
num += 1
num_and_size.append((num, size))
return num_and_size
grade_map = {
"0年级": "零年级",
"1年级": "一年级",
"2年级": "二年级",
"3年级": "三年级",
"4年级": "四年级",
"5年级": "五年级",
"6年级": "六年级",
"7年级": "七年级",
"8年级": "八年级",
"9年级": "九年级",
"高1": "高一",
"高2": "高二",
"高3": "高三"
}
# 年级映射反向
r_grade_map = {
"零年级": "0年级",
"一年级": "1年级",
"二年级": "2年级",
"三年级": "3年级",
"四年级": "4年级",
"五年级": "5年级",
"六年级": "6年级",
"七年级": "7年级",
"八年级": "8年级",
"九年级": "9年级",
"高一": "高1",
"高二": "高2",
"高三": "高3"
}
# 年级数字映射
grade_num_map = {
0: "0年级",
1: "1年级",
2: "2年级",
3: "3年级",
4: "4年级",
5: "5年级",
6: "6年级",
7: "7年级",
8: "8年级",
9: "9年级",
10: "高1",
11: "高2",
12: "高3"
}
# 年级数字映射反向
r_grade_num_map = {
"0年级": 0,
"1年级": 1,
"2年级": 2,
"3年级": 3,
"4年级": 4,
"5年级": 5,
"6年级": 6,
"7年级": 7,
"8年级": 8,
"9年级": 9,
"高1": 10,
"高2": 11,
"高3": 12
}
finance_term_code_map = {
"暑": 1,
"秋": 2,
"寒": 3,
"春": 4,
}
r_finance_term_code_map = {
1: "暑",
2: "秋",
3: "寒",
4: "春",
}
normal_term_code_map = {
"春": 1,
"暑": 2,
"秋": 3,
"寒": 4,
}
r_normal_term_code_map = {
1: "暑",
2: "秋",
3: "寒",
4: "春",
}
......@@ -5,12 +5,16 @@ from script.ji_yun_ying_pc.statistical_report.data_config import global_data
today_date = GetTime.get_today().get("today_date")
person_groups = ["big_area_id", "area_id", "school_area_id", "grade", "subject", "class_type", "course_id"]
continue_groups = ["big_area_id", "area_id", "school_area_id", "grade", "subject", "class_type", "class_teacher", "director_id", "phase"]
refund_groups = ["big_area_id", "area_id", "school_area_id", "grade", "subject", "class_type", "course_id", "class_teacher", "director_id"]
full_class_groups = ["big_area_id", "area_id", "school_area_id", "grade", "subject", "class_type", "phase", "course_id", "class_teacher", "director_id"]
fill_groups = ["big_area_id", "area_id", "school_area_id", "director_id", "class_teacher", "class_type", "subject", "grade"]
search_targets = [x for x in global_data.all_target if x.get("target_id") >= 1000004 and x.get("is_default") == "否"]
# 获取日期筛选数据
def get_date_data(num: int = 10):
def get_date_data(num: int = 5):
date_data_list = [""]
for x in range(num):
date_data_list.append(GetTime.get_today_before(x).get(f"before_date_{x}"))
......@@ -109,5 +113,172 @@ def get_continue_group_search_data(num=10):
continue_more_search_datas = [*get_continue_single_search_data(), *get_continue_group_search_data()]
# 获取续报率不同维度汇总数据
def get_continue_group_data():
continue_group_list_single = [[x] for x in continue_groups]
continue_group_list_group = [random.sample(continue_groups, random.randint(2, len(continue_groups))) for x in range(10)]
return [*continue_group_list_single, *continue_group_list_group, continue_groups]
# 获取退费率更多筛选的单个筛选的数据
def get_refund_single_search_data():
grade_data = [{"grade": [x]} for x in global_data.grade]
subject_data = [{"subject": [x]} for x in global_data.subject]
class_type_data = [{"classType": [x]} for x in global_data.routine_class_type]
return [*grade_data, *subject_data, *class_type_data]
# 获取退费率更多筛选的组合筛选数据
def get_refund_group_search_data(num=10):
"""
:num: 生成数据的数量
:return: 返回随机组合的筛选数据
"""
group_search_data_list = []
for x in range(num):
ran_grade = random.sample(global_data.grade, random.randint(0, len(global_data.grade)))
ran_subject = random.sample(global_data.subject, random.randint(0, len(global_data.subject)))
ran_class_type = random.sample(global_data.routine_class_type, random.randint(0, len(global_data.routine_class_type)))
more_search_data = {}
if ran_subject:
more_search_data["subject"] = ran_subject
if ran_grade:
more_search_data["grade"] = ran_grade
if ran_class_type:
more_search_data["classType"] = ran_class_type
if more_search_data:
group_search_data_list.append(more_search_data)
return group_search_data_list
# 退费率更多筛选数据
refund_more_search_datas = [*get_refund_single_search_data(), *get_refund_group_search_data()]
# 获取退费率不同维度汇总数据
def get_refund_group_data():
refund_group_list_single = [[x] for x in refund_groups]
refund_group_list_group = [random.sample(refund_groups, random.randint(2, len(refund_groups))) for x in range(10)]
return [*refund_group_list_single, *refund_group_list_group, refund_groups]
# 获取满班率更多筛选的单个筛选的数据
def get_full_class_single_search_data():
grade_data = [{"grade": [x]} for x in global_data.grade]
subject_data = [{"subject": [x]} for x in global_data.subject]
class_type_data = [{"classType": [x]} for x in [*global_data.routine_class_type, *global_data.special_class_type]]
phase_data = [{"phase": [x]} for x in global_data.phase]
return [*grade_data, *subject_data, *class_type_data, *phase_data]
# 获取满班率更多筛选的组合筛选数据
def get_full_class_group_search_data(num=10):
"""
:num: 生成数据的数量
:return: 返回随机组合的筛选数据
"""
group_search_data_list = []
for x in range(num):
class_type_temp = [*global_data.routine_class_type, *global_data.special_class_type]
ran_grade = random.sample(global_data.grade, random.randint(0, len(global_data.grade)))
ran_subject = random.sample(global_data.subject, random.randint(0, len(global_data.subject)))
ran_class_type = random.sample(class_type_temp, random.randint(0, len(class_type_temp)))
ran_phase = random.sample(global_data.phase, random.randint(0, len(global_data.phase)))
more_search_data = {}
if ran_subject:
more_search_data["subject"] = ran_subject
if ran_grade:
more_search_data["grade"] = ran_grade
if ran_class_type:
more_search_data["classType"] = ran_class_type
if ran_phase:
more_search_data["phase"] = ran_phase
if more_search_data:
group_search_data_list.append(more_search_data)
return group_search_data_list
# 满班率更多筛选数据
full_class_more_search_datas = [*get_full_class_single_search_data(), *get_full_class_group_search_data()]
# 获取满班率不同维度汇总数据
def get_full_class_group_data():
full_class_group_list_single = [[x] for x in full_class_groups]
full_class_group_list_group = [random.sample(full_class_groups, random.randint(2, len(full_class_groups))) for x in range(10)]
return [*full_class_group_list_single, *full_class_group_list_group, full_class_groups]
# 获取续报率更多筛选的单个筛选的数据
def get_fill_single_search_data():
grade_data = [{"grade": [x]} for x in global_data.grade]
subject_data = [{"subject": [x]} for x in global_data.subject]
class_type_data = [{"classType": [x]} for x in global_data.routine_class_type]
priceType_data = [{"priceType": [x]} for x in global_data.priceType]
studentType_data = [{"studentType": [x]} for x in global_data.studentType]
return [*grade_data, *subject_data, *class_type_data, *priceType_data, *studentType_data]
# 获取续报率更多筛选的组合筛选数据
def get_fill_group_search_data(num=10):
"""
:num: 生成数据的数量
:return: 返回随机组合的筛选数据
"""
group_search_data_list = []
for x in range(num):
ran_grade = random.sample(global_data.grade, random.randint(0, len(global_data.grade)))
ran_subject = random.sample(global_data.subject, random.randint(0, len(global_data.subject)))
ran_class_type = random.sample(global_data.routine_class_type, random.randint(0, len(global_data.routine_class_type)))
ran_priceType = random.sample(global_data.priceType, random.randint(0, len(global_data.priceType)))
ran_studentType = random.sample(global_data.studentType, random.randint(0, len(global_data.studentType)))
more_search_data = {}
if ran_subject:
more_search_data["subject"] = ran_subject
if ran_grade:
more_search_data["grade"] = ran_grade
if ran_class_type:
more_search_data["classType"] = ran_class_type
if ran_priceType:
more_search_data["priceType"] = ran_priceType
if ran_studentType:
more_search_data["studentType"] = ran_studentType
if more_search_data:
group_search_data_list.append(more_search_data)
return group_search_data_list
# 补费率更多筛选数据
fill_more_search_datas = [*get_fill_single_search_data(), *get_fill_group_search_data()]
# 获取补费率不同维度汇总数据
def get_fill_group_data():
fill_group_list_single = [[x] for x in fill_groups]
fill_group_list_group = [random.sample(fill_groups, random.randint(2, len(fill_groups))) for x in range(10)]
return [*fill_group_list_single, *fill_group_list_group, fill_groups]
target_datas = [
{
"all_count": (1000, 2000),
"continue_class": (333, 444),
"expand_class": (111, 222),
"expand_subject": (11, 43),
"new_student": (123, 234),
"boutique": (256, 356),
"special_class": (55, 66)
},
{}
,
{
"all_count": (600, 700),
"continue_class": (33, 44),
"expand_class": (11, 22),
"expand_subject": (77, 88),
"new_student": (99, 100),
"boutique": (5, 6),
"special_class": (1, 2)
},
]
import random
from common.operation_time import GetTime
from common.connect_db import OperationDb
year = [2019, 2020, 2021, 2022]
......@@ -26,6 +27,11 @@ service_class_type = class_type.get("服务班课")
special_class_type = class_type.get("专题班课")
ji_xun__class_type = class_type.get("集训班课")
# 今天日期
today_date = GetTime.get_today().get("today_date")
# 30天前的日期
before_date_30 = GetTime.get_today_before(30).get("before_date_30")
# 获取所有班型
def get_all_class_type():
......@@ -204,4 +210,4 @@ all_big_area_id = get_school_area_id(department_type=20)
# 所有区域ID
all_area_id = get_school_area_id(department_type=40)
# 所有校区ID
al_school_area_id = get_school_area_id()
all_school_area_id = get_school_area_id()
from common.operation_time import GetTime
import pandas as pd
# 获取日期范围筛选数据
def get_date_datas():
date_data_list = []
today_date = GetTime.get_today().get("today_date")
date_data_list.append((today_date, today_date))
for x in range(5, 35, 5):
date_data_list.append((GetTime.get_today_before(x).get(f"before_date_{x}"), today_date))
date_data_list = [GetTime.get_every_day(*x) for x in date_data_list]
return date_data_list
# 日期按按周分组
def get_week_date_group(begin_date, end_date):
week_info_list = GetTime.get_week_info(begin_date, end_date)
year_weeks = set([x.get("year_week") for x in week_info_list])
week_group = []
for year_week in year_weeks:
week_date = [x.get('date_data') for x in week_info_list if x.get("year_week") == year_week]
week_group.append({
"year_week": year_week,
"week_date": week_date
})
from operator import itemgetter
week_group = sorted(week_group, key=itemgetter("year_week"))
return week_group
def set_excel(df, set_dir, sheet_name):
pd.io.formats.excel.header_style = None
writer = pd.ExcelWriter(set_dir, engine='xlsxwriter')
df.to_excel(writer, sheet_name)
# 设置格式
workbook = writer.book
worksheets = writer.sheets
worksheet1 = worksheets[sheet_name]
# 设置特定单元格的宽度
col_format = workbook.add_format({'text_wrap': 1})
worksheet1.set_column("A:N", 30, col_format)
writer.save()
print(get_week_date_group("2021-04-30", "2021-05-10"))
# 查询年份和期段是否精品有课消
ke_xiao_sql = """
SELECT
bs.student_id,
cls.subject,
tp.year,
tp.term,
sum(bs.class_hour_change)
FROM
service_profile.business_statistic bs
LEFT JOIN public.target_plan tp ON bs.create_time BETWEEN tp.exquisite_start_time AND tp.exquisite_end_time
LEFT JOIN service_education.classes cls on bs.class_id = cls.class_id
WHERE
bs.TYPE IN ( 'ATTENDANCE', 'ATTENDANCE_CANCE' )
and bs.student_id = '10193216'
and cls.course_type = '精品定制课'
and tp.year = %s
and tp.term = %s
GROUP BY
bs.student_id,
cls.subject,
HAVING
sum(bs.class_hour_change) < 0
"""
# 查询精品有课消的年份期段
student_ke_xiao_sql = """
SELECT
bs.student_id,
cls.subject,
tp.year,
tp.term,
sum(bs.class_hour_change)
FROM
service_profile.business_statistic bs
LEFT JOIN public.target_plan tp ON bs.create_time BETWEEN tp.exquisite_start_time AND tp.exquisite_end_time
LEFT JOIN service_education.classes cls on bs.class_id = cls.class_id
WHERE
bs.TYPE IN ( 'ATTENDANCE', 'ATTENDANCE_CANCE' )
and bs.student_id = %s
and cls.course_type = '精品定制课'
GROUP BY
bs.student_id,
cls.subject,
tp.year,
tp.term,
HAVING
sum(bs.class_hour_change) < 0
"""
# 查询可补费sql
ke_bu_fei_sql = """
SELECT
tp_tb2.student_id,
tp_tb2.class_id,
tp_tb2.school_area,
tp_tb2.order_no,
tp_tb2.order_detail_id,
tp_tb2.TYPE,
tp_tb2.create_time
FROM
(
SELECT
*
FROM
(
SELECT
bs.student_id,
bs.class_id,
bs.school_area,
bs.order_no,
bs.order_detail_id,
bs.TYPE,
bs.create_time,
ROW_NUMBER ( ) OVER (
PARTITION BY bs.class_id,
bs.order_detail_id
ORDER BY
bs.create_time DESC NULLS LAST
) AS rn
FROM
service_profile.business_statistic bs
WHERE
bs.TYPE NOT IN ( 'ATTENDANCE', 'ATTENDANCE_CANCEL' )
and bs.school_area not in (3074, 3076, 3345, 3047, 3049, 3095, 2383, 3015, 3052)
AND bs.segment = 'UP'
and bs.create_time < '2021-05-01 00:00:00'
) tp_tb
WHERE
tp_tb.rn = 1
AND tp_tb.TYPE IN ( 'ORDER', 'CLASS_CHANGE_IN' )
) tp_tb2
LEFT JOIN service_education.classes cls ON tp_tb2.class_id = cls.class_id
WHERE
cls.course_type = '常规班课'
AND cls.YEAR = 2021
AND cls.term = '春'
ORDER BY
tp_tb2.create_time DESC
"""
fill_rate_sql = """
SELECT
osd.id AS order_segment_detail_id,
up_order_detail.student_id,
up_order.order_no AS up_order_no,
osd.up_order_detail_id,
up_order.status AS up_order_status,
( ARRAY_AGG ( bs.type ORDER BY bs.id DESC ) ) [ 1 ] AS up_now_type,
up_order.pay_time AS up_pay_time,
up_order_detail.class_id AS up_order_class_id,
( ARRAY_AGG ( bs.class_id ORDER BY bs.id DESC ) ) [ 1 ] AS up_now_class_id,
down_order.order_no AS down_order_no,
osd.down_order_detail_id,
down_order.status AS down_order_status,
COALESCE( temp.down_now_type, 'NULL') AS down_now_type,
down_order.pay_time AS down_pay_time,
down_order_detail.class_id AS down_order_class_id,
temp.down_now_class_id,
( ARRAY_AGG ( bs.create_time ORDER BY bs.id DESC ) ) [ 1 ] AS max_create_time
FROM
service_order.order_segment_detail osd
LEFT JOIN service_mall.order_goods up_order_detail ON osd.up_order_detail_id = up_order_detail.id
LEFT JOIN service_mall.order up_order ON up_order_detail.order_id = up_order.id
LEFT JOIN service_mall.order_goods down_order_detail ON osd.down_order_detail_id = down_order_detail.id
LEFT JOIN service_mall.order down_order ON down_order_detail.order_id = down_order.id
LEFT JOIN service_profile.business_statistic bs ON osd.up_order_detail_id = bs.order_detail_id
LEFT JOIN (
SELECT
bs.order_detail_id,
( ARRAY_AGG ( bs.class_id ORDER BY bs.id DESC ) ) [ 1 ] AS down_now_class_id,
( ARRAY_AGG ( bs.type ORDER BY bs.id DESC ) ) [ 1 ] AS down_now_type
FROM
service_order.order_segment_detail osd
LEFT JOIN service_profile.business_statistic bs ON osd.down_order_detail_id = bs.order_detail_id
WHERE
bs.type NOT IN ( 'ATTENDANCE', 'ATTENDANCE_CANCEL')
GROUP BY
bs.order_detail_id
) temp ON temp.order_detail_id = osd.down_order_detail_id
WHERE
osd.up_order_detail_id IS NOT NULL
AND up_order_detail.segment IS NOT NULL
AND bs.type NOT IN ( 'ATTENDANCE', 'ATTENDANCE_CANCEL')
GROUP BY
osd.id,
up_order.id,
up_order_detail.id,
down_order.id,
down_order_detail.id,
temp.down_now_class_id,
temp.down_now_type
"""
from script.ji_yun_ying_pc.system_set.data_config import global_data
school_names = ["金沙", "", "!@#$%^", "'", "德阳"]
area_names = ["金沙", "", "!@#$%^", "'", "德阳"]
finance_years = [2021, 2022]
terms = ["春", "暑", "秋", "寒"]
search_targets = [x for x in global_data.all_target if x.get("target_id") >= 1000004]
def get_year_terms():
year_terms = []
for finance_year in finance_years:
for term in terms:
year_terms.append({
"year": finance_year,
"term": term
})
return year_terms
def get_next_year_term(year, term):
if term == "春":
return year, "暑"
elif term == "暑":
return year, "秋"
elif term == "秋":
return year, "寒"
else:
return int(year) + 1, "春"
def get_open_grade(year, term):
class_list = global_data.get_class_by_year_term(year, term)
keys = list(set([x.get("key") for x in class_list]))
open_grade_list = []
for key in keys:
sub_class_list = [x for x in class_list if x.get("key") == key]
open_grade = list(set([x.get("grade") for x in sub_class_list]))
data = sub_class_list[0]
data.pop("grade")
data.pop("school_area_id")
data.pop("school_area_name")
open_grade = sorted([global_data.r_grade_map.get(x) for x in open_grade])
next_should_continue_grade = [global_data.r_grade_num_map.get(x) for x in open_grade]
data["open_grade"] = open_grade
if term == "春":
next_should_continue_grade = [x + 1 for x in next_should_continue_grade]
data["next_should_continue_grade"] = [global_data.grade_num_map.get(x) for x in next_should_continue_grade]
open_grade_list.append(data)
return open_grade_list
def get_can_continue_grade(year, term):
current_open_grade_list = get_open_grade(year, term)
next_year, next_term = get_next_year_term(year, term)
next_open_grade_list = get_open_grade(next_year, next_term)
for current_open_grade in current_open_grade_list:
next_should_continue_grade = set(current_open_grade.get("next_should_continue_grade"))
key = current_open_grade.get("key")
next_open_grades = [x for x in next_open_grade_list if x.get("key") == key]
if next_open_grades:
next_open_grade = next_open_grades[0]
next_open_grade_data = set(next_open_grade.get("open_grade"))
can_continue_grade = sorted(list(next_should_continue_grade.intersection(next_open_grade_data)))
else:
next_open_grade_data = set()
can_continue_grade = []
current_open_grade["next_open_grades"] = list(next_open_grade_data)
current_open_grade["can_continue_grade"] = can_continue_grade
return current_open_grade_list
import random
import pandas as pd
from common.connect_db import OperationDb
from script.ji_yun_ying_pc.system_set.data_config import query_sql
def set_excel(df_infos, set_dir):
pd.io.formats.excel.header_style = None
writer = pd.ExcelWriter(set_dir, engine='xlsxwriter')
for df_info in df_infos:
df = df_info.get("data")
sheet_name = df_info.get("sheet_name")
df.to_excel(writer, sheet_name, index=False)
# 设置格式
workbook = writer.book
worksheets = writer.sheets
worksheet1 = worksheets[sheet_name]
# 设置特定单元格的宽度
col_format = workbook.add_format({'text_wrap': 1})
worksheet1.set_column("A:N", 30, col_format)
writer.save()
code_term_map = {
"01": "暑",
"02": "秋",
"03": "寒",
"04": "春",
}
term_code_map = {
"暑": "01",
"秋": "02",
"寒": "03",
"春": "04",
}
new_school_phase_num_map = {
"01": 4,
"02": 7,
"03": 6,
"04": 5,
}
def get_school_area_id(department_type=30):
sql = f"""select id from service_user.department where type = {department_type}"""
school_area_datas = OperationDb.query_sql(sql)
school_area_ids = [x[0] for x in school_area_datas]
return school_area_ids
# 所有大区ID
# all_big_area_id = get_school_area_id(department_type=20)
# # 所有区域ID
# all_area_id = get_school_area_id(department_type=40)
# # 所有校区ID
# all_school_area_id = get_school_area_id()
# 获取上期的年份期段code
def get_last_year_code(year_term_code):
year_code = int(year_term_code[0:4])
term_code = int(year_term_code[4:6])
if term_code == 1:
last_year_code = year_code - 1
last_term_code = 7
return str(last_year_code) + "0" + str(last_term_code)
else:
return str(int(year_term_code) - 2)
# 获取年份期段code
def get_year_term_code(year, term):
year_code = str(year)
term_code = str(term_code_map.get(term))
return year_code + term_code
# 获取累计开校期数
def get_new_school_count_phase(current_year_term_code, new_year_term_code):
if current_year_term_code >= new_year_term_code:
current_year_code = int(current_year_term_code[0:4])
current_term_code = int(current_year_term_code[4:6])
new_year_code = int(new_year_term_code[0:4])
new_term_code = int(new_year_term_code[4:6])
year_diff = current_year_code - new_year_code
term_diff = current_term_code - new_term_code
return year_diff * 4 + term_diff + 1
else:
return -1
def get_school_type(count_phase, new_school_phase_num):
if count_phase >= 0:
diff = count_phase - new_school_phase_num
if diff <= 0:
return "新开校"
elif 0 < diff <= 8:
return "成长校"
else:
return "成熟校"
else:
return "未开校"
# 获取全部校年份期段数据
def get_school_year_code():
school_year_code_datas = OperationDb.query_sql(query_sql.school_year_code_sql)
school_year_code_datas = [{
"big_area_id": x[0],
"big_area_name": x[1],
"area_id": x[2],
"area_name": x[3],
"school_area_id": x[4],
"school_area_name": x[5],
"school_area_short_name": x[6],
"school_year": str(x[7]),
"school_term": "0" + str(x[8]),
"school_year_code": str(x[7]) + "0" + str(x[8]),
"new_school_phase_num": new_school_phase_num_map.get("0" + str(x[8]))
} for x in school_year_code_datas]
return school_year_code_datas
all_school_year_code = get_school_year_code()
# 获取所有目标方案
def get_target():
sql = """
SELECT id,year,term,name,end_time,last_end_time,exquisite_start_time,exquisite_end_time,is_default,entry_grades
FROM public.target_plan
"""
targets = OperationDb.query_sql(sql)
targets = [
{
"target_id": x[0],
"year": x[1],
"term": x[2],
"name": x[3],
"end_time": str(x[4]),
"last_end_time": str(x[5]),
"exquisite_start_time": str(x[6]),
"exquisite_end_time": str(x[7]),
"is_default": x[8],
"entry_grades": x[9]
}
for x in targets
]
return targets
# 获取所有班级
def get_class_by_year_term(year, term):
class_infos = OperationDb.query_sql(query_sql.class_query_sql % (year, term))
class_infos = [
{
"big_area_name": x[0],
"area_name": x[1],
"school_area_name": x[2],
"school_area_id": x[3],
"subject": x[4],
"grade": x[5],
"year": x[6],
"term": x[7],
"area_id": x[8],
"key": f"{x[8]}_{x[4]}"
}
for x in class_infos
]
return class_infos
# 所有目标方案
all_target = get_target()
# 默认目标方案
default_target = [x for x in all_target if x.get("is_default") == "是"][0]
# 年级映射
grade_map = {
"0年级": "零年级",
"1年级": "一年级",
"2年级": "二年级",
"3年级": "三年级",
"4年级": "四年级",
"5年级": "五年级",
"6年级": "六年级",
"7年级": "七年级",
"8年级": "八年级",
"9年级": "九年级",
"高1": "高一",
"高2": "高二",
"高3": "高三"
}
# 年级映射反向
r_grade_map = {
"零年级": "0年级",
"一年级": "1年级",
"二年级": "2年级",
"三年级": "3年级",
"四年级": "4年级",
"五年级": "5年级",
"六年级": "6年级",
"七年级": "7年级",
"八年级": "8年级",
"九年级": "9年级",
"高一": "高1",
"高二": "高2",
"高三": "高3"
}
# 年级数字映射
grade_num_map = {
0: "0年级",
1: "1年级",
2: "2年级",
3: "3年级",
4: "4年级",
5: "5年级",
6: "6年级",
7: "7年级",
8: "8年级",
9: "9年级",
10: "高1",
11: "高2",
12: "高3"
}
# 年级数字映射反向
r_grade_num_map = {
"0年级": 0,
"1年级": 1,
"2年级": 2,
"3年级": 3,
"4年级": 4,
"5年级": 5,
"6年级": 6,
"7年级": 7,
"8年级": 8,
"9年级": 9,
"高1": 10,
"高2": 11,
"高3": 12
}
school_year_code_sql = """
SELECT
big_area.id AS big_area_id,
big_area.name AS big_area_name,
area.id AS area_id,
area.name AS area_name,
school_area.id AS school_area_id,
school_area.name AS school_area_name,
school_area.short_name AS school_area_short_name,
open_financial_year,
open_financial_term
FROM
service_user.department school_area
LEFT JOIN service_user.department area ON area.id = school_area.parent_id
LEFT JOIN service_user.department big_area ON area.parent_id = big_area.id
LEFT JOIN service_user.department_school dept_sch ON school_area.id = dept_sch.id
WHERE
big_area.id != 10000
and school_area.id NOT IN ( 3049, 3074, 3076, 3015, 3047, 2383, 3052, 3014, 3073, 3095, 3013 )
and school_area.type = 30
and open_financial_year NOTNULL
ORDER BY open_financial_year, open_financial_term
"""
school_year_code_city_sql = """
SELECT
big_area.id AS big_area_id,
big_area.name AS big_area_name,
area.id AS area_id,
area.name AS area_name,
school_area.id AS school_area_id,
school_area.short_name AS school_area_name ,
province,
province.name AS province_name,
city,
city.name AS city_name,
county,
county.name AS county_name,
longitude,
latitude,
open_financial_year_code
FROM
service_user.department school_area
LEFT JOIN service_user.department area ON area.id = school_area.parent_id
LEFT JOIN service_user.department big_area ON area.parent_id = big_area.id
LEFT JOIN service_user.department_school dept_sch ON school_area.id = dept_sch.id
LEFT JOIN public.administrative_region province ON dept_sch.province = province.id
LEFT JOIN public.administrative_region city ON dept_sch.city = city.id
LEFT JOIN public.administrative_region county ON dept_sch.county = county.id
WHERE
big_area.id != 10000
and school_area.id NOT IN ( 3049, 3074, 3076, 3015, 3047, 2383, 3052, 3014, 3073, 3095, 3013 )
and school_area.type = 30
and open_financial_year_code NOTNULL
ORDER BY open_financial_year_code
"""
class_query_sql = """
SELECT
big_area.name as big_area_name,
d_area.name as area_name,
dept_sch.name as school_area_name,
cls.school_area as chool_area_id,
cls.subject,
cls.grade,
cls.year,
cls.term,
d_area.id as area_id
FROM
service_education.classes cls
LEFT JOIN service_user.department dept_sch ON cls.school_area = dept_sch.id
LEFT JOIN service_user.department d_area ON dept_sch.parent_id = d_area.id
LEFT JOIN service_user.department big_area ON d_area.parent_id = big_area.id
WHERE
cls.status =1 and cls.course_type = '常规班课' and cls.year = %s and cls.term = '%s'
"""
import allure
import pytest
import pandas as pd
import jsonpath
from script.ji_yun_ying_pc.system_set.data_config import basic_parameter_set_data
from script.ji_yun_ying_pc.system_set.data_config import global_data
from script import public_asserts
from script.default_header import jyy_header
def xxx(body, header=jyy_header):
return {}
@allure.epic("测试基础参数设置")
@allure.feature("测试校区类型设置")
class TestSchoolTypeSet:
df_infos = []
@allure.story("测试校区类型设置-校区名称筛选")
@pytest.mark.parametrize("school_name", basic_parameter_set_data.school_names)
def test_school_name_search(self, school_name):
body = {
"pageNum": 1,
"pageSize": 10,
"year": "2022",
"term": "暑",
"school_name": school_name,
}
res = xxx(body=body, header=jyy_header)
# public_asserts.public_assert(res)
@allure.story("测试校区类型设置-财年学期筛选")
@pytest.mark.parametrize("year_term", basic_parameter_set_data.get_year_terms())
def test_year_term_search(self, year_term):
year = year_term.get("year")
term = year_term.get("term")
body = {
"pageNum": 1,
"pageSize": 10,
"year": year,
"term": term,
}
res = xxx(body=body, header=jyy_header)
current_year_code = global_data.get_year_term_code(year, term)
all_school_year_info = []
for x in global_data.get_school_year_code():
count_phase = global_data.get_new_school_count_phase(current_year_code, x.get("school_year_code"))
# x.setdefault("count_phase", count_phase)
# x.setdefault("diff", count_phase-x.get("new_school_phase_num"))
# x.setdefault("school_type", global_data_config.get_school_type(count_phase, x.get("new_school_phase_num")))
x.setdefault("累计开校期数", count_phase)
x.setdefault("差值", count_phase-x.get("new_school_phase_num"))
x.setdefault("校区类型", global_data.get_school_type(count_phase, x.get("new_school_phase_num")))
x.get("school_year_code")
x.setdefault("开校财年", x.get("school_year_code")[0:4])
x.setdefault("开校学期", global_data.code_term_map.get(x.get("school_year_code")[4:6]))
all_school_year_info.append(x)
df = pd.DataFrame(all_school_year_info)
TestSchoolTypeSet.df_infos.append({
"data": df,
"sheet_name": f"{str(year)}{term}({current_year_code})"
})
import time
now = str(int(time.time() * 1000000))
# global_data_config.set_excel(df, f"./temp/校区类型{year}_{term}_{now}.xlsx")
# public_asserts.public_assert(res)
def teardown_class(self):
if TestSchoolTypeSet.df_infos:
import time
now = str(int(time.time() * 1000000))
global_data.set_excel(TestSchoolTypeSet.df_infos, f"./temp/校区类型_{now}.xlsx")
@allure.epic("测试基础参数设置")
@allure.feature("测试区域类型设置")
class TestAreaTypeSet:
df_infos = []
@allure.story("测试校区类型设置-区域名称筛选")
@pytest.mark.parametrize("area_name", basic_parameter_set_data.area_names)
def test_area_name_search(self, area_name):
body = {
"pageNum": 1,
"pageSize": 10,
"year": "2022",
"term": "暑",
"area_name": area_name,
}
res = xxx(body=body, header=jyy_header)
# public_asserts.public_assert(res)
@allure.story("测试区域类型设置-财年学期筛选")
@pytest.mark.parametrize("year_term", basic_parameter_set_data.get_year_terms())
def test_year_term_search(self, year_term):
year = year_term.get("year")
term = year_term.get("term")
body = {
"pageNum": 1,
"pageSize": 10,
"year": year,
"term": term,
}
res = xxx(body=body, header=jyy_header)
current_year_code = global_data.get_year_term_code(year, term)
all_school_year_info = []
for x in global_data.get_school_year_code():
count_phase = global_data.get_new_school_count_phase(current_year_code, x.get("school_year_code"))
x.setdefault("累计开校期数", count_phase)
x.setdefault("差值", count_phase-x.get("new_school_phase_num"))
x.setdefault("校区类型", global_data.get_school_type(count_phase, x.get("new_school_phase_num")))
x.get("school_year_code")
x.setdefault("开校财年", x.get("school_year_code")[0:4])
x.setdefault("开校学期", global_data.code_term_map.get(x.get("school_year_code")[4:6]))
all_school_year_info.append(x)
all_area_ids = list(set([x.get("area_id") for x in all_school_year_info]))
all_area_infos = []
for area_id in all_area_ids:
area_data_list = [x for x in all_school_year_info if x.get("area_id") == area_id]
area_first_school = area_data_list[0]
area_first_school_list = [x for x in area_data_list if x.get("school_year_code") == area_first_school.get("school_year_code")]
all_area_info = {
# "big_area_id": area_first_school.get("big_area_id"),
"big_area_name": area_first_school.get("big_area_name"),
# "area_id": area_first_school.get("area_id"),
"area_name": area_first_school.get("area_name"),
"首校开校财年": area_first_school.get("开校财年"),
"首校开校学期": area_first_school.get("开校学期"),
"首校年份期段编码": area_first_school.get("school_year_code"),
# "school_area_id": "\n".join([str(x.get("school_area_id")) for x in area_first_school_list]),
"school_area_name": "\n".join([x.get("school_area_name") for x in area_first_school_list]),
"首校新开校阶段期数": area_first_school.get("new_school_phase_num"),
"首校累计开校期数": area_first_school.get("累计开校期数"),
"差值": area_first_school.get("差值"),
"区域类型": area_first_school.get("校区类型")
}
all_area_infos.append(all_area_info)
df = pd.DataFrame(all_area_infos)
TestAreaTypeSet.df_infos.append({
"data": df,
"sheet_name": f"{str(year)}{term}({current_year_code})"
})
def teardown_class(self):
if TestAreaTypeSet.df_infos:
import time
now = str(int(time.time() * 1000000))
global_data.set_excel(TestAreaTypeSet.df_infos, f"./temp/区域类型_{now}.xlsx")
@allure.epic("测试基础参数设置")
@allure.feature("测试可续报年级")
class TestCanContinueGrade:
df_infos = []
@allure.story("测试可续报年级-区域名称筛选")
@pytest.mark.parametrize("area_name", basic_parameter_set_data.area_names)
def test_area_name_search(self, area_name):
body = {
"pageNum": 1,
"pageSize": 10,
"year": "2022",
"term": "暑",
"area_name": area_name,
}
res = xxx(body=body, header=jyy_header)
# public_asserts.public_assert(res)
@allure.story("测试可续报年级-目标方案筛选")
@pytest.mark.parametrize("target", basic_parameter_set_data.search_targets)
def test_target_search(self, target):
year = target.get("year")
term = target.get("term")
target_name = target.get("name")
body = {
"pageNum": 1,
"pageSize": 10,
"year": year,
"term": term,
}
res = xxx(body=body, header=jyy_header)
public_asserts.public_assert(res)
# target_can_continue_grade = basic_parameter_set_data.get_can_continue_grade(year, term)
# df = pd.DataFrame(target_can_continue_grade)
# df.insert(0, "目标方案", target_name)
# df.drop(["key"], axis=1, inplace=True)
# df.rename(columns={
# "open_grade": "本期开设年级",
# "next_should_continue_grade": "下期应续报年级",
# "next_open_grades": "下期开设年级",
# "can_continue_grade": "本期续下期可续报年级",
# }, inplace=True)
# TestAreaTypeSet.df_infos.append({
# "data": df,
# "sheet_name": target_name
# })
def teardown_class(self):
if TestAreaTypeSet.df_infos:
import time
now = str(int(time.time() * 1000000))
global_data.set_excel(TestAreaTypeSet.df_infos, f"./temp/可续报年级_{now}.xlsx")
import pytest
import allure
from pytest_assume.plugin import assume
@allure.step("基础断言code,msg")
def public_assert(res_json: dict):
code = res_json.get("code", -100)
msg = res_json.get("msg", "获取失败")
pytest.assume(code == 0)
pytest.assume(msg == "成功")
code = res_json.get("code")
msg = res_json.get("msg")
with assume:
assert code == 0, "code不等于0"
assert msg == "成功", "msg不等于成功"
@allure.step("断言响应的某一列都被输入的内容包含")
......
......@@ -30,4 +30,4 @@ def get_method(url, method):
if __name__ == '__main__':
get_method("/service-statistics/statistics/supplementaryPayment", "post")
get_method("/service-public/targets/1000006", "PATCH")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment