关键字封装及夹具简单使用

本文介绍了如何使用Python的requests库进行API请求封装,包括GET和POST方法,并通过ApiKeyword类实现。同时展示了如何使用pytest进行测试,包括登录测试案例、全局变量的fixture处理、日志记录以及使用allure生成测试报告。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关键字封装

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("**************************************")
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值