test_04_Internship_preparation.py 6.4 KB
# -*- coding: utf-8 -*-
# ======================================
# @Software: PyCharm
# @Author  : Shitou ✊
# @Time    : 2022/12/29 21:19
# @FileName: test_04_Internship_preparation.py
# ======================================
"""
实习准备模块
"""
import json
import time
import unittest
import os
import requests
from jsonpath import jsonpath
from common.handle_config import conf
from common.handle_excel import Excel
from common.handle_log import HandleLog
from common.handle_path import DataExcel_Path, System_path, TeachingAffairs_path, Internship_path
from common.myddt import ddt, data
from tools.fixture import SelectData
from tools.handle_token import LoginToken


# ==================实习计划相关的用例==================
@ddt
class Test01InternshipPlan(unittest.TestCase):
    add_plan = Excel(os.path.join(Internship_path, "test_04_internship_plan.xlsx"), "add_internship_plan")
    add_plan_case = add_plan.read_excel()

    @classmethod
    def setUpClass(cls):
        # 获取登陆token
        cls.token = LoginToken.login_token()
        # ---获取添加院系id
        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_course_excel = Excel(os.path.join(TeachingAffairs_path, "test_03_course.xlsx"),
                                    "select_course")
        read_course_excel = select_course_excel.read_excel_location("C2")
        course_list = SelectData(str(read_course_excel))
        course_json = course_list.select_list()
        cls.courseId = jsonpath(course_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.teacherId = jsonpath(teacher_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.name = "py自动化计划" + new_time

    # ====================================================================
    #                               新增计划
    # ====================================================================
    @data(*add_plan_case)
    def test_add_plan(self, case):
        """新增计划用例"""
        url = conf.get("url", "url_ip") + case["url"]
        # 准备数据
        if "#name#" in case["data"]:
            case["data"] = case["data"].replace("#name#", str(self.name + "_" + str(case["id"])))  # 名称
        if "#courseId#" in case["data"]:
            case["data"] = case["data"].replace("#courseId#", str(self.courseId))  # 课程
        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
        if "#classInfoId#" in case["data"]:
            case["data"] = case["data"].replace("#classInfoId#", str(self.classId))  # 班级id
        if "#teacherIds#" in case["data"]:
            case["data"] = case["data"].replace("#teacherIds#", str(self.teacherId))  # 教师id
        if "#termId#" in case["data"]:
            case["data"] = case["data"].replace("#termId#", str(self.termsId))  # 学期id

        # 准备数据
        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_plan.write_excel(row=case["id"] + 1, column=7, value="不通过")
            HandleLog.log.error("用例标题{},不通过".format(case['title']))
            HandleLog.log.exception(e)
            raise e
        else:
            self.add_plan.write_excel(row=case["id"] + 1, column=7, value="通过")
            # 将创建使用的数据写入到excel表格中
            self.add_plan.write_excel(row=case["id"] + 1, column=9, value=case["data"])
            HandleLog.log.info("用例{},执行通过".format(case["title"]))