-
案例一
-
需求
1, 对登录函数进行测试, 登录函数 定义在 tools.py 中
2, 在 case 目录中书写用例对login 函数进行测试, 使用断言
3, 将 login 函数的测试数据定义在 json 文件中,完成参数化, data 目录中
4, 生成测试报告 report 目录中
tools.py(开发代码)
bash
# 自动化测试函数
def login(username, password):
if username == 'admin' and password == '123456':
return '登录成功'
else:
return '登录失败'
data.test_data.json (data文件夹存放json文件测试数据)
bash
[
{
"desc": "正确的用户名和密码",
"username": "admin",
"password": "123456",
"expect": "登录成功"
},
{
"desc": "错误的用户名",
"username": "root",
"password": "123456",
"expect": "登录失败"
},
{
"desc": "错误的的密码",
"username": "admin",
"password": "123123",
"expect": "登录失败"
},
{
"desc": "错误的用户名和密码",
"username": "root",
"password": "123676",
"expect": "登录失败"
},
{
"desc": "用户名和密码不能为空",
"username": "",
"password": "",
"expect": "登录失败"
}
]
app.py(获取项目完整路径---绝对路径)
bash
import os
BASE_DIR = os.path.dirname(__file__)
if __name__ == '__main__':
print(BASE_DIR)
common.read_data.py(common文件夹放 读取测试数据方法)
bash
import json
from testDemo9.app import BASE_DIR
def build_test_data_1():
with open(BASE_DIR+'/data/test_data.json', 'r', encoding='utf-8') as f:
data_list = json.load(f) # [{},{},{},{}]
new_list = []
for data in data_list: # 字典
username = data.get('username')
password = data.get('password')
expect = data.get('expect')
# c = (username, password, expect)
# new_list.append(tuple(c))
new_list.append((username, password, expect))
return new_list
def build_test_data_2():
with open(BASE_DIR+'/data/test_data.json', 'r', encoding='utf-8') as f:
data_list = json.load(f) # [{},{},{},{}]
new_list = []
for data in data_list: # 字典 中的值都要 使用data.values() 获取,在转换成元组
new_list.append(tuple(data.values()))
return new_list
if __name__ == '__main__':
print(build_test_data_1())
print(build_test_data_2())
case.test_login.py(参数化测试数据脚本)
bash
import unittest
from parameterized import parameterized
from testDemo9.common.read_data import build_test_data_1
from testDemo9.tools import login
class TestLogin(unittest.TestCase):
"""参数化测试数据"""
@parameterized.expand(build_test_data_1)
def test_login(self, username, password, expect):
print(f'username:{username}, password:{password}, expect:{expect}')
self.assertEquals(expect,login(username, password))
login_report.py(套件执行生成测试报告)
bash
from htmltestreport import HTMLTestReport
import unittest
from case.test_login import TestLogin
from app import BASE_DIR
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestLogin))
runner = HTMLTestReport(BASE_DIR+'/report/test_login_report.html', '登录测试用例', '100%通过')
runner.run(suite)