五、业务层、数据层、用例层
直接创建:data
目录作为数据层,operations
包作为业务层,testcases
作为用例层。
yml文件读取功能
数据我们采用yaml
格式,封装yaml文件读取功能,在utils
包下创建read_data.py
# utils/read_data.py
import os
import yaml
root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class ReadFileData:
def load_yaml(self, file_path):
try:
data_file_path = os.path.join(root_path, "data", file_path)
with open(data_file_path, encoding='utf-8') as f:
data = yaml.safe_load(f)
except Exception as ex:
print(ex)
else:
return data
data = ReadFileData()
数据层
data
下创建login.yml
文件用于存储登录的用户名和密码
# data/login.yml
login_data:
json:
username: 'admin'
password: '123456'
不要忘记在api
包下新增我们登录接口如下:
# api/login.py
from base.http_client import HttpClient
# 继承HttpClient
class Auth(HttpClient):
# ..此处省略..
def token(self, **kwargs):
return self.post('http://127.0.0.1:5000/user/token', **kwargs)
auth = Auth()
业务层
在operaitons
包下创建auth.py
文件
from api.auth import auth
from utils.read_data import data
# 读取测试数据
data = data.load_yaml('login.yml')
def get_token():
test_case = data['login_data']
# 由于yml文件读取出来是字典形式,可以直接用关键字传参方式调用api层的接口方法
return auth.token(**test_case)
测试用例层
把test_api.py
移动到testcases
下,新增登录测试用例:
# testcases/test_api.py
import pytest
from api.login import auth
from operations.auth import get_token
def test_01():
response = auth.login().json()
assert response.get('success') == 'ok'
# 新增登录测试用例
def test_token():
resp = get_token().json()
assert resp.get('msg') == '登录成功'
if __name__ == '__main__':
pytest.main()
执行用例成功
============================= test session starts =============================
platform win32 -- Python 3.7.1, pytest-6.2.1, py-1.10.0, pluggy-0.13.1
rootdir: D:\study\api-test
plugins: allure-pytest-2.8.31, dependency-0.5.1, forked-1.3.0, ordering-0.6, rerunfailures-9.1.1, xdist-2.2.1collected 2 items
testcases\test_api.py .. [100%]
============================== 2 passed in 0.81s ==============================
至此,我们自动化框架基本完成了,更多功能还需要读者自己去扩展和补充。