关键字封装
class ApiKeyword:
#get请求
def get(self,url,params=None,**kwargs):
return requests.get(url=url,params=params,**kwargs)
#post请求
def post(self,url,data=None,json=None,**kwargs):
return requests.post(url=url,data=data,json=json,**kwargs)
#获取数据源(从接口返回数据,提取json字符串)
def get_data(self,response,key):
#如果返回数据为字符串,则转换为json
if isinstance(response,str):
reponse = json.loads(response)
value_list = jsonpath.jsonpath(response,key)
return value_list[0]
case执行
def test_login():
ak = ApiKeyword()
url = "http://shop.com/index.php?s=/api/user/login"
public_data = {"application": "app","application_client_type": "weixin"}
data = {"accounts": "admin", "pwd":"123456","type": "username"}
res = ak.post(url,params=public_data,data=data)
text = ak.get_data(res.json(),'$.msg')
assert text == '登录成功','期望结果与实际结果一致'
#使用allure生成报告
if __name__=='__main__':
#-v显示详细信息,-s在控制台输出内容,生成结果放在result下,每次运行前清空这个文件的内容
pytest.main(['-v','./testcase/test_01.py','--alluredir','./result','--clean-alluredir'])
#在终端运行命令,把数据转换成html报告
os.system('allure generate ./result -o ./report_allure --clean')
全局变量可应用夹具做前置处理(写到conftest.py中)
比如:token值等
使用装饰器@pytest.fixture()封装返回需要的值
用例中继承此方法后调用
#夹具方法
@pytest.fixture(scope="session")
def token_fix():
pass
#下单接口调用,下单接口必须传token值
def test_addcart(token_fix):#继承
token = token_fix
pass
logging日志
新建pytest.ini文件(固定名称)
[pytest]
log_cli=true #日志开关
log_level=NOTSET #日志登记,默认debug
log_format = %(asctime)s %(levelname)s %(message)s %(filename)s %(funcName)s %(lineno)d #日期
log_date_format = %Y-%m-%d %H:%M:%S #时间
log_file = ./log.log #存放路径
log_file_level = info #记录日志等级
log_file_format = %(asctime)s %(levelname)s %(message)s %(filename)s %(funcName)s %(lineno)d #记录日期
log_file_date_format = %Y-%m-%d %H:%M:%S #记录时间
使用夹具生成log日志(写到conftest.py文件中)
@pytest.hookimpl(hookwrapper=True,tryfirst=True)
def pytest_runtest_makereport(item, call):
out = yield
res = out.get_result()
if res.when == "call":
logging.info(f"用例ID:{res.nodeid}")
logging.info(f"测试结果:{res.outcome}")
logging.info(f"故障:{res.longrepr}")
logging.info(f"异常:{call.excinfo}")
Logging.info(f"用例耗时:{res.duration}")
logging.info("**************************************")