test_02_system_management.py 10.5 KB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2022/12/8 23:53
# @Author  : Shitou
# @FileName: test_02_department.xlsx.py
# @Software: PyCharm

"""
系统管理菜单用例
"""
import json
import os
import unittest
import requests
import time
from common import myddt
from common.handle_excel import Excel
from common.handle_log import HandleLog
from common.handle_path import DataExcel_Path
from common.handle_config import conf
from tools.handle_token import LoginToken
from tools.fixture import SystemManagement
from jsonpath import jsonpath

# 系统管理相关的用例目录
System_path = os.path.join(DataExcel_Path, "system")


# ==================院系相关的用例==================
@myddt.ddt
class Test01Department(unittest.TestCase):
    """院系"""
    # 新增院系用例
    open_add_excel = Excel(os.path.join(System_path, "test_02_department.xlsx"), "add_department")
    test_add_case = open_add_excel.read_excel()

    # 查看院系用例
    open_select_excel = Excel(os.path.join(System_path, "test_02_department.xlsx"), "select_department")
    test_select_case = open_select_excel.read_excel()

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

    def setUp(self):
        """单条用例执行前执行的函数"""
        new_time = time.strftime("%Y%m%d_%H:%M:%S")
        # 随机院系名称
        self.department_name = "py自动化院系" + new_time
        # 随机院系代码
        self.department_code = "py_code" + new_time

    # ====================================================================
    #                               新增院系
    # ====================================================================
    @myddt.data(*test_add_case)
    def test_add_department(self, case):
        """新增院系"""
        url = conf.get("url", "url_ip") + case['url']
        # 准备数据
        # -----写入数据
        if "#department#" in case["data"]:
            case["data"] = case["data"].replace("#department#", self.department_name + "_" + str(case["id"]))
        if "#department_code#" in case["data"]:
            case["data"] = case["data"].replace("#department_code#", self.department_code + "_" + str(case["id"]))
        data = json.loads(case['data'])
        # -----预期结果
        expected = json.loads(case['expected'])
        # 调用接口
        # 请求头
        headers = {}
        headers["Authorization"] = self.token
        response = requests.request(method=case["method"], url=url, 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.open_add_excel.write_excel(row=case["id"] + 1, column=7, value="不通过")
            HandleLog.log.error("用例标题{},不通过".format(case['title']))
            HandleLog.log.exception(e)
            raise e
        else:
            self.open_add_excel.write_excel(row=case["id"] + 1, column=7, value="通过")
            # 将创建使用的数据写入到excel表格中
            self.open_add_excel.write_excel(row=case["id"] + 1, column=9,
                                            value=case["data"])
            HandleLog.log.info("用例{},执行通过".format(case["title"]))

    # ====================================================================
    #                               查看院系
    # ====================================================================
    @myddt.data(*test_select_case)
    def test_select_department(self, select_case):
        """查看院系"""
        url = conf.get("url", "url_ip") + select_case['url']
        # 准备数据
        # -----写入数据
        data = json.loads(select_case['data'])
        # -----预期结果
        expected = json.loads(select_case['expected'])
        # 调用接口
        # 请求头
        headers = {}
        headers["Authorization"] = self.token
        response = requests.request(method=select_case['method'], url=url, 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.select_excel.write_excel(row=select_case["id"] + 1, column=7, value="不通过")
            HandleLog.log.error("用例标题{},不通过".format(select_case['title']))
            HandleLog.log.exception(e)
            raise e
        else:
            self.open_select_excel.write_excel(row=select_case["id"] + 1, column=7, value="通过")
            # 将创建使用的数据写入到excel表格中
            self.open_select_excel.write_excel(row=select_case["id"] + 1, column=9,
                                               value=select_case["data"])
            HandleLog.log.info("用例{},执行通过".format(select_case["title"]))


# ==================专业相关的用例==================
@myddt.ddt
class Test02Specialty(unittest.TestCase):
    """专业相关的用例"""
    open_speciality_excel = Excel(os.path.join(System_path, "test_03_specialty.xlsx"), "add_specialty")
    test_data = open_speciality_excel.read_excel()

    @classmethod
    def setUpClass(cls):
        """
        :return: token
        """
        # 获取token
        cls.token = LoginToken.login_token()

    def setUp(self):
        """单条用例执行前执行的函数"""
        new_time = time.strftime("%H:%M:%S")
        # 随机专业名称
        self.specialty_name = "py专业" + new_time
        # 随机专业代码
        self.specialty_code = "py_code" + new_time

    # ====================================================================
    #                               新增专业
    # ====================================================================
    @myddt.data(*test_data)
    def test_add_specialty(self, case):
        """新增专业"""
        # 准备数据
        # --写入数据
        # 获取院系id
        department_list = SystemManagement.department_list()
        department_id = jsonpath(department_list, "$..id")[0]
        if "#specialty_name#" in case["data"]:
            case["data"] = case["data"].replace("#specialty_name#", self.specialty_name + "_" + str(case["id"]))
        if "#specialty_code#" in case["data"]:
            case["data"] = case["data"].replace("#specialty_code#", self.specialty_code + "_" + str(case["id"]))

        if "#departmentId#" in case["data"]:
            case["data"] = case["data"].replace("#departmentId#", department_id)
        data = json.loads(case["data"])
        # --预期结果
        expected = json.loads(case["expected"])
        # 调用接口
        url = conf.get("url", "url_ip") + case["url"]

        headers = {}
        headers["Authorization"] = self.token
        req = requests.request(method=case["method"], url=url, json=data, headers=headers)
        res = req.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:
            self.open_speciality_excel.write_excel(row=case["id"] + 1, column=7, value="不通过")
            HandleLog.log.error("用例标题{},不通过".format(case['title']))
            HandleLog.log.exception(e)
            raise e
        else:
            self.open_speciality_excel.write_excel(row=case["id"] + 1, column=7, value="通过")
            HandleLog.log.info("用例{},执行通过".format(case["title"]))


# ==================校历(学年学期)相关的用例========2022 12.15
@myddt.ddt
class Test03Year(unittest.TestCase):
    """校历(学年学期)相关的用例"""
    open_year_excel = Excel(os.path.join(System_path, "test_04_term.xlsx"), "add_term")
    test_data = open_year_excel.read_excel()

    @classmethod
    def setUpClass(cls):
        """
        :return: token
        """
        # 获取token
        cls.token = LoginToken.login_token()

    def setUp(self):
        """单条用例执行前执行的函数"""
        new_time = time.strftime("%H:%M:%S")
        # 随机学年名称
        self.year_name = "py学年" + new_time
        # 随机学年备注
        self.year_comment = "py_comment备注" + new_time

    # ====================================================================
    #                               新增学年学期
    # ====================================================================
    @myddt.data(*test_data)
    def test_add_year(self, case):
        """新增学年学期"""
        # 准备数据
        # --写入数据
        if "#year#" in case["data"]:
            case["data"] = case["data"].replace("#year#", self.year_name + "_" + str(case["id"]))
        if "#remark#" in case["data"]:
            case["data"] = case["data"].replace("#remark#", self.year_comment + "_" + str(case["id"]))
        data = json.loads(case["data"])
        # --预期结果
        expected = json.loads(case["expected"])
        # 调用接口
        url = conf.get("url", "url_ip") + case["url"]

        headers = {}
        headers["Authorization"] = self.token
        req = requests.request(method=case["method"], url=url, json=data, headers=headers)
        res = req.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:
            self.open_year_excel.write_excel(row=case["id"] + 1, column=7, value="不通过")
            HandleLog.log.error("用例标题{},不通过".format(case['title']))
            HandleLog.log.exception(e)
            raise e
        else:
            self.open_year_excel.write_excel(row=case["id"] + 1, column=7, value="通过")
            HandleLog.log.info("用例{},执行通过".format(case["title"]))