说明:以上9篇文章是为自动化框架作准备,接下来开始记录测试用例篇,test case部分
这里简单介绍下test case 的大概框架,具体项目内容需要和实际业务关联
import configparser
import json
import os
import unittest
from TeacherWebsite.common.config_handler import config
from TeacherWebsite.common.excel_handler import ExcelHandler
from TeacherWebsite.common.logger_handler import logger
from TeacherWebsite.common.requests_handler import RequestsHandler
from TeacherWebsite.libs.ddt import ddt, data
from TeacherWebsite.setting.constant import p_path
@ddt
class TestLogin(unittest.TestCase):
# 通过读取配置文件得到cases.xlxs
file_name = config.read('excel', 'file_name')
file_path = os.path.join(p_path.DATA_PATH,file_name)#获取整个路径
#获取sheet_name
sheet_name =config.read('excel', 'login_sheet')
# 读取excel数据(测试数据)
test_data = ExcelHandler(file_path).read(sheet_name)
req = RequestsHandler()
#获取配置文件的url
url = config.read('http','base_url_3')
#获取配置文件的headers
cf = configparser.RawConfigParser()
cf.read('../setting/config.ini')
headers = cf.get('http','headers')
print()
#@classmethod不需要每次进入测试用例数据之前再执行初始化一次
@classmethod
def setUpClass(cls):
cls.req = RequestsHandler()#作为一个类属性,每次都会初始化
cls.logger = logger
@classmethod
def tearDownClass(cls):
pass
def setUp(self): #前置条件,测试用例方法之前自动运行setup里面的程序
pass
def tearDown(self):##后置条件,测试用例方法之后自动运行tearDown里面的程序
pass
#以上都是前置条件前置条件
1、以上是为了前置条件作准备、比如读取测试数据的路径啊,req(接口驱动)的路径之类的,读取配置文件等等、headers读取,这里边因为我的header转义问题,暂时先这么写入,后续可以将headers可以写入Excel文件里边
导入的时候一定要看准导入路径
2、写入接口
@data(*test_data)#一定要加'*'
def test_login(self,test_info):#test_info是接收测试数据
#调用requests模块访问接口
res = self.req.json(test_info['method'],
self.url,
json = test_info['data'],
headers = eval(self.headers))#类属性能通过实例去访问
print(res)
try:
self.assertEqual(json.loads(test_info['expected']),res['msg'])
#json.loads:json 转化为字典,转化就是为了方便对照结果
# JsonDecodeerror 说明你用了一个非法的字符串方式,要用双引号来包装,外边用单引号(在Excel 里边将该字段用双引号阔起来就成,比如"系统繁忙")
#写回excel,静态方法
self.logger.info('断言成功')#日志记录
ExcelHandler.write(self.file_path,
self.sheet_name,
test_info['caseid']+1,
2,
'pass')
except AssertionError as e:
#写入断言失败
self.logger.error('断言失败')#日志记录
ExcelHandler.write(self.file_path,
self.sheet_name,
test_info['caseid'] + 1,
2,
'failed')# 2是表示第二列为了以后测试方便,第二列就写入测试结果用
raise e #抛出异常
#写回Excel 不是必须的,这里是为了灵活展示Excel的操作,因为我们在断言的时候会写入到测试报告里
这里边try 函数是写回的函数,可以不用写在代码里边
读取测试数据的方式最好使用字典
Excelhandler: