test_03_teaching_affairs.py 17.9 KB
# -*- coding: utf-8 -*-
# """======================================
# @Software: PyCharm
# @Author  : Shitou ✊
# @Time    : 2022/12/17 22:10
# @FileName: test_03_teaching_affairs.py
# ====================================="""
"""
实习教务管理菜单
"""
import json
import time
import unittest
import os
import requests
from jsonpath import jsonpath
from common.handle_log import HandleLog
from common.handle_path import DataExcel_Path, TeachingAffairs_path, System_path
from common.myddt import ddt, data
from common.handle_excel import Excel
from common.handle_config import conf
from tools.fixture import SelectData
from tools.handle_token import LoginToken
from tools.fixture import RandomPhone, RandomIdentification, RandomEmail


# ==================教师相关的用例==================
@ddt
class Test01Teacher(unittest.TestCase):
    """教师相关"""
    # ---获取添加教师用例
    add_teacher = Excel(os.path.join(TeachingAffairs_path, "test_03_teacher.xlsx"), "add_teacher")
    add_teacher_case = add_teacher.read_excel()

    @classmethod
    def setUpClass(cls):
        """
        用例类执行前执行的函数
        :return:token
        """
        # 获取token
        cls.token = LoginToken.login_token()

        # ---获取添加院系Excel表格
        select_department_excel = Excel(os.path.join(System_path, "test_02_department.xlsx"),
                                        "select_department")
        read_excel = select_department_excel.read_excel_location("C2")
        department_list = SelectData(str(read_excel))
        department_json = department_list.select_list_positive()
        # 获取院系id
        cls.department_id = jsonpath(department_json, "$..id")[-1]

    def setUp(self):
        """单条用例执行前执行的函数"""
        new_time = time.strftime("%Y%m%d_%H:%M:%S")
        # 随机教师名称
        self.teacher_name = "py自动化教师" + new_time

    # ====================================================================
    #                               新增教师
    # ====================================================================
    @data(*add_teacher_case)
    def test_add_teacher_info(self, case):

        """新增教师用例"""
        url = conf.get("url", "url_ip") + case['url']
        # 准备数据
        # ------判断教师姓名
        if "#name#" in case["data"]:
            case["data"] = case["data"].replace("#name#", str(self.teacher_name + "_" + str(case["id"])))
        # ------判断教师姓名
        if "#departmentId#" in case["data"]:
            case["data"] = case["data"].replace("#departmentId#", str(self.department_id))
        # ------判断教师手机号
        if "#phone#" in case["data"]:
            case["data"] = case["data"].replace("#phone#", RandomPhone.random_phone())
        # ------判断教师身份证号
        if "#idNumber#" in case["data"]:
            case["data"] = case["data"].replace("#idNumber#", RandomIdentification().ran_end())
        # ------判断教师邮箱
        if "#email#" in case["data"]:
            case["data"] = case["data"].replace("#email#", RandomEmail.rand_email())
        data = json.loads(case["data"])
        expected = json.loads(case["expected"])
        herders = {}
        herders["Authorization"] = self.token
        # 调用接口
        response = requests.request(url=url, method=case["method"], json=data, headers=herders)
        res = response.json()
        print("用例入参:{}".format(data))
        print("预期结果:", expected)
        print("实际结果:", res)
        # 断言
        try:
            self.assertEqual(expected['msg'], res['msg'])
            self.assertEqual(expected['code'], res['code'])
        except AssertionError as e:
            # 写入Excel
            self.add_teacher.write_excel(row=case["id"] + 1, column=7, value="不通过")
            HandleLog.log.error("用例标题{},不通过".format(case['title']))
            HandleLog.log.exception(e)
            raise e
        else:
            self.add_teacher.write_excel(row=case["id"] + 1, column=7, value="通过")
            # 将创建使用的数据写入到excel表格中
            self.add_teacher.write_excel(row=case["id"] + 1, column=9,
                                         value=case["data"])
            HandleLog.log.info("用例{},执行通过".format(case["title"]))


# ==================班级相关的用例==================
@ddt
class Test02Class(unittest.TestCase):
    """班级相关"""
    add_class = Excel(os.path.join(TeachingAffairs_path, "test_03_class.xlsx"), "add_class")
    add_class_case = add_class.read_excel()

    # ====================================================================
    #                               新增班级
    # ====================================================================
    @classmethod
    def setUpClass(cls):
        """
        用例类执行前执行的函数
        :return:token
        """
        # 获取token
        cls.token = LoginToken.login_token()

        # ---获取添加院系Excel表格
        select_department_excel = Excel(os.path.join(System_path, "test_02_department.xlsx"),
                                        "select_department")
        read_department_excel = select_department_excel.read_excel_location("C2")
        department_list = SelectData(str(read_department_excel))
        department_json = department_list.select_list_positive()
        cls.department_id = jsonpath(department_json, "$..id")[-1]  # 获取院系id
        # 获取查看专业id
        select_specialty_excel = Excel(os.path.join(System_path, "test_02_specialty.xlsx"),
                                       "select_specialty")
        read_specialty_excel = select_specialty_excel.read_excel_location("C2")
        specialty_list = SelectData(str(read_specialty_excel))
        specialty_json = specialty_list.select_list()
        cls.professionalId = jsonpath(specialty_json, "$..id")[0]  # 获取专业id
        # 获取查看教师id
        select_teacher_excel = Excel(os.path.join(TeachingAffairs_path, "test_03_teacher.xlsx"),
                                     "select_teacher")
        read_teacher_excel = select_teacher_excel.read_excel_location("C2")
        teacher_list = SelectData(str(read_teacher_excel))
        teacher_json = teacher_list.select_list()
        cls.teacher_id = jsonpath(teacher_json, "$..id")[0]  # 获取教师id

    def setUp(self):
        """单条用例执行前执行的函数"""
        new_time = time.strftime("%Y%m%d_%H:%M:%S")
        # 随机班级名称
        self.class_name = "py自动化班级" + new_time

    @data(*add_class_case)
    def test_add_class_info(self, case):
        """新增班级用例"""
        url = conf.get("url", "url_ip") + case["url"]
        # 准备数据
        if "#name#" in case["data"]:
            case["data"] = case["data"].replace("#name#", str(self.class_name + "_" + str(case["id"])))
        if "#professionalId#" in case["data"]:
            case["data"] = case["data"].replace("#professionalId#", str(self.professionalId))
        if "#teacherId#" in case["data"]:
            case["data"] = case["data"].replace("#teacherId#", str(self.teacher_id))
        if "#departmentId#" in case["data"]:
            case["data"] = case["data"].replace("#departmentId#", str(self.department_id))
        data = json.loads(case["data"])
        expected = json.loads(case["expected"])
        # 调用接口
        headers = {}
        headers["Authorization"] = self.token
        response = requests.request(url=url, method=case["method"], json=data, headers=headers)
        res = response.json()
        print("用例入参:{}".format(data))
        print("预期结果:", expected)
        print("实际结果:", res)
        # 断言
        try:
            self.assertEqual(expected['msg'], res['msg'])
            self.assertEqual(expected['code'], res['code'])
        except AssertionError as e:
            # 写入Excel
            self.add_class.write_excel(row=case["id"] + 1, column=7, value="不通过")
            HandleLog.log.error("用例标题{},不通过".format(case['title']))
            HandleLog.log.exception(e)
            raise e
        else:
            self.add_class.write_excel(row=case["id"] + 1, column=7, value="通过")
            # 将创建使用的数据写入到excel表格中
            self.add_class.write_excel(row=case["id"] + 1, column=9,
                                       value=case["data"])
            HandleLog.log.info("用例{},执行通过".format(case["title"]))


# ==================实践课程相关的用例==================
@ddt
class Test03Course(unittest.TestCase):
    """时间课程相关"""
    add_course = Excel(os.path.join(TeachingAffairs_path, "test_03_course.xlsx"), "add_course")
    add_course_case = add_course.read_excel()

    # ====================================================================
    #                               新增课程
    # ====================================================================
    @classmethod
    def setUpClass(cls):
        """
        用例类执行前执行的函数
        :return:token
        """
        # 获取token
        cls.token = LoginToken.login_token()

        # ---获取添加院系Excel表格
        select_department_excel = Excel(os.path.join(System_path, "test_02_department.xlsx"),
                                        "select_department")
        read_department_excel = select_department_excel.read_excel_location("C2")
        department_list = SelectData(str(read_department_excel))
        department_json = department_list.select_list_positive()
        cls.department_id = jsonpath(department_json, "$..id")[-1]  # 获取院系id
        # 获取查看专业id
        select_specialty_excel = Excel(os.path.join(System_path, "test_02_specialty.xlsx"),
                                       "select_specialty")
        read_specialty_excel = select_specialty_excel.read_excel_location("C2")
        specialty_list = SelectData(str(read_specialty_excel))
        specialty_json = specialty_list.select_list()
        cls.professionalId = jsonpath(specialty_json, "$..id")[0]  # 获取专业id
        # 获取查看学期id
        select_term_excel = Excel(os.path.join(System_path, "test_02_term.xlsx"),
                                  "select_term")
        read_term_excel = select_term_excel.read_excel_location("C2")
        term_list = SelectData(str(read_term_excel))
        term_json = term_list.select_list()
        cls.termsId = term_json["data"]["records"][0]["terms"][0]["id"]  # 获取学年学期id

    def setUp(self):
        """单条用例执行前执行的函数"""
        new_time = time.strftime("%Y%m%d_%H:%M:%S")
        # 随机班级名称
        self.course_name = "py自动化课程" + new_time

    @data(*add_course_case)
    def test_add_course_info(self, case):
        """新增课程用例"""
        url = conf.get("url", "url_ip") + case["url"]
        # 准备数据
        if "#name#" in case["data"]:
            case["data"] = case["data"].replace("#name#", str(self.course_name + "_" + str(case["id"])))
        if "#departmentId#" in case["data"]:
            case["data"] = case["data"].replace("#departmentId#", str(self.department_id))
        if "#professionalId#" in case["data"]:
            case["data"] = case["data"].replace("#professionalId#", str(self.professionalId))
        if "#termIds#" in case["data"]:
            case["data"] = case["data"].replace("#termIds#", str(self.termsId))

        data = json.loads(case["data"])
        expected = json.loads(case["expected"])
        # 调用接口
        headers = {}
        headers["Authorization"] = self.token
        response = requests.request(url=url, method=case["method"], json=data, headers=headers)
        res = response.json()
        print("用例入参:{}".format(data))
        print("预期结果:", expected)
        print("实际结果:", res)
        # 断言
        try:
            self.assertEqual(expected['msg'], res['msg'])
            self.assertEqual(expected['code'], res['code'])
        except AssertionError as e:
            # 写入Excel
            self.add_course.write_excel(row=case["id"] + 1, column=7, value="不通过")
            HandleLog.log.error("用例标题{},不通过".format(case['title']))
            HandleLog.log.exception(e)
            raise e
        else:
            self.add_course.write_excel(row=case["id"] + 1, column=7, value="通过")
            # 将创建使用的数据写入到excel表格中
            self.add_course.write_excel(row=case["id"] + 1, column=9,
                                        value=case["data"])
            HandleLog.log.info("用例{},执行通过".format(case["title"]))


# ==================学生相关的用例==================
@ddt
class Test04Student(unittest.TestCase):
    """班级相关"""
    add_student = Excel(os.path.join(TeachingAffairs_path, "test_03_student.xlsx"), "add_student")
    add_student_case = add_student.read_excel()

    # ====================================================================
    #                               新增学生
    # ====================================================================
    @classmethod
    def setUpClass(cls):
        """
        用例类执行前执行的函数
        :return:token
        """
        # 获取token
        cls.token = LoginToken.login_token()

        # ---获取添加院系Excel表格
        select_department_excel = Excel(os.path.join(System_path, "test_02_department.xlsx"),
                                        "select_department")
        read_department_excel = select_department_excel.read_excel_location("C2")
        department_list = SelectData(str(read_department_excel))
        department_json = department_list.select_list_positive()
        cls.department_id = jsonpath(department_json, "$..id")[-1]  # 获取院系id
        # ---获取查看专业id
        select_specialty_excel = Excel(os.path.join(System_path, "test_02_specialty.xlsx"),
                                       "select_specialty")
        read_specialty_excel = select_specialty_excel.read_excel_location("C2")
        specialty_list = SelectData(str(read_specialty_excel))
        specialty_json = specialty_list.select_list()
        cls.professionalId = jsonpath(specialty_json, "$..id")[0]  # 获取专业id
        # ---获取查看班级id
        select_class_excel = Excel(os.path.join(TeachingAffairs_path, "test_03_class.xlsx"),
                                   "select_class")
        read_class_excel = select_class_excel.read_excel_location("C2")
        class_list = SelectData(str(read_class_excel))
        class_json = class_list.select_list()
        cls.classId = jsonpath(class_json, "$..id")[0]  # 获取班级id
        # ---获取查看学期id
        select_term_excel = Excel(os.path.join(System_path, "test_02_term.xlsx"),
                                  "select_term")
        read_term_excel = select_term_excel.read_excel_location("C2")
        term_list = SelectData(str(read_term_excel))
        term_json = term_list.select_list()
        cls.termsId = term_json["data"]["records"][0]["terms"][0]["id"]  # 获取学年学期id

    def setUp(self):
        """单条用例执行前执行的函数"""
        new_time = time.strftime("%Y%m%d_%H:%M:%S")
        # 随机学生名称
        self.student_name = "py自动化学生" + new_time
        # 随机学号
        self.student_number = new_time

    @data(*add_student_case)
    def test_add_student_info(self, case):
        """新增课程用例"""
        url = conf.get("url", "url_ip") + case["url"]
        # 准备数据
        if "#name#" in case["data"]:
            case["data"] = case["data"].replace("#name#", str(self.student_name + "_" + str(case["id"])))  # 名称
        if "#number#" in case["data"]:
            case["data"] = case["data"].replace("#number#", str(self.student_number + "_" + str(case["id"])))  # 学号
        if "#phone#" in case["data"]:
            case["data"] = case["data"].replace("#phone#", RandomPhone.random_phone())  # 手机号
        if "#classInfoId#" in case["data"]:
            case["data"] = case["data"].replace("#classInfoId#", str(self.classId))  # 班级id
        if "#idNumber#" in case["data"]:
            case["data"] = case["data"].replace("#idNumber#", RandomIdentification().ran_end())  # 学生身份证号
        if "#other#" in case["data"]:
            case["data"] = case["data"].replace("#other#", RandomPhone.random_phone())  # 其他(备注)
        if "#departmentId#" in case["data"]:
            case["data"] = case["data"].replace("#departmentId#", str(self.department_id))  # 院系id
        if "#professionalId#" in case["data"]:
            case["data"] = case["data"].replace("#professionalId#", str(self.professionalId))  # 专业id

        data = json.loads(case["data"])
        expected = json.loads(case["expected"])
        # 调用接口
        headers = {}
        headers["Authorization"] = self.token
        response = requests.request(url=url, method=case["method"], json=data, headers=headers)
        res = response.json()
        print("用例入参:{}".format(data))
        print("预期结果:", expected)
        print("实际结果:", res)
        # 断言
        try:
            self.assertEqual(expected['msg'], res['msg'])
            self.assertEqual(expected['code'], res['code'])
        except AssertionError as e:
            # 写入Excel
            self.add_student.write_excel(row=case["id"] + 1, column=7, value="不通过")
            HandleLog.log.error("用例标题{},不通过".format(case['title']))
            HandleLog.log.exception(e)
            raise e
        else:
            self.add_student.write_excel(row=case["id"] + 1, column=7, value="通过")
            # 将创建使用的数据写入到excel表格中
            self.add_student.write_excel(row=case["id"] + 1, column=9,
                                         value=case["data"])
            HandleLog.log.info("用例{},执行通过".format(case["title"]))