pytest用例管理框架实战(基础篇)

2023-04-12编程技术21823

先安装pip install pytest

pytest用例管理框架

默认规则:

1.py文件必须以test_开头或者_test结尾

2.类名必须以test开头

3.测试用例必须以test_开头

get 请求通过params传递参数

post请求通过json或者data传参

data

数据报文:dict字典类型,请求头:application/x-www-form

以form表单的方式传参   格式:id=3&sn=ed24aw

数据报文:str类型,请求头:text/plain

data只能传简单的只有键值对的dict或者是str格式

json

数据报文:不管是dict还是str类型,application/json

data=json.dumps(data)   序列化,把字典格式的数据转化为字符串的数据

json.loads(data)              反序列化,把str格式转化为字典格式

import requests
class TestSendRequest: #Test开头的类
  token=""         #把token设为全局变量,也称类变量,通过类名来访问TestSendRequest.token
  cks =""
  session = request.session()
  
  def setup(self):
    print("在每个用例之前都执行一次")  
    
  def teardown(self):
    print("在每个用例之后都执行一次")

  def test_login(self):  #Test_开头的测试用例
    url = "……" 
data = { "key":"value" "key":"value" "key":"value" }
rep = session.request("get",url=url,params=data) #传入接口路径和接口参数 #这样去发送请求时就会得到一个response响应
       print(rep.json()) #查看接口文档的响应数据是什么格式 #返回一个token值,是一个键值对 
    TestSendRequest.token =rep.json()['token'] #通过这个键取到这个值

  def test_patch_mecharmId(self,conn_database):    #将函数方法名conn_database传进来
    url = "…… token="+TestSendRequest.token+""
    data = {"SN":"","ID":"32"}
    rep =session.request("post",url=url,json=data) # data=json.dumps(data) 序列化,把字典格式的数据转化为字符串的数据 #post可传URL,data,json等    print(rep.json()) 
    TestSendRequest.cks =rep.cookies

  def test_file_upload(self):
    url ="…… token="+TestSendRequest.token+""
    data = {
      "file":open(r"E:\SHU.png":"rb") #以二进制的形式打开
}
    headeres = {              #有请求头时
      "Accept":"application/json,text/javascript"
      "x-Requested-with":"XMLHttpRequest"
}
    rep =session.request("post",url=url,files=data,headers=headers,cookies=TestSendRequest.cks) #需要cookies鉴权时
    print(rep.json())

运行方式

-v 输出更加详细的运行信息  
-s 输入调试信息
-n 多线程运行
--reruns 数字 失败用例重跑
--html= 报告的路径

实际工作中会使用pytest.ini 的配置文件来配置运行
#新建一个配置文件  当.py文件运行时,会自动读取这个配置文件
[pytest]
addopts = -vs #配置命令
testpaths=./testcases #配置文件路径
python_files = test_*.py #配置文件规则
python_classes = test_*
python_function = test_*
新建一个conftest.py文件,用来实现部分的前置
conftest.py文件是单独存放@pytest.fixture的方法,这些方法不需要导入,直接调用即可
用处是可以在多个.py文件之间共享前置配置
@pytest.fixture(scope="function")      #定义成一个函数
def conn_database(); #把用例名称传到.py文件需要用的的用例即可
  print("连接数据库")
  yield #唤醒
  print("关闭数据库")

@pytest.fixture(scope="session",autouse=True) #将自动清除写进前置文件里面
def clear_yaml():   
  YamlUtil().clear_extract_yaml()

一般会新建一个all.py文件来运行

if _name_=='_main_':   #写个main方法运行
 pytest.main(['-vs']) # -v 输出更加详细的运行信息 -s 输入调试信息

那么怎么做接口的封装呢?

上面的环境变量不过松散,而且每个.py文件都有变量,有着多种关联,建议封装一个读写YAML和写YAML的方法

新建一个extract.yml

再新建一个python package--新建一个公共包--新建yaml_util.py文件

import os
class YamlUtil:
  def read_extract_yaml(self): #读取YAML文件
    with open(os.getcwd()+"/extract.yml",mode='r',encoding='utf-8') as f: #作为文件流
      value = yaml.load(stream=f,Loader=yaml.FullLoader) #通过yaml.load去加载,Loader为加载方式
      return value;
  def read_extract_yaml(self,data):  #写入YAML文件
    with open(os.getcwd()+"/extract.yml",mode='a',encoding='utf-8') as f:
      value = yaml.dump(data=data,stream=f,allow_unicode=True)
      return value;

  def clear_extract_yaml(self):  #清除YAML文件
    with open(os.getcwd()+"/extract.yml",mode='w',encoding='utf-8') as f:
      f.truncate() #直接清除即可
      


import requests
class TestSendRequest: #删除全局变量,将yaml文件写进去
           
  cks =""
  session = request.session()
     def test_login(self):  
    url = "……"
data = { "key":"value" "key":"value" "key":"value" }
rep = session.request("get",url=url,params=data)
print(rep.json()) #下面的yaml文件一般是一个键值对
    YamlUtil().write_extract_yaml({'token':rep.json()['token']}) #把yaml文件写进去,之前是TestSendRequest.token =rep.json()['token']  
  def test_patch_mecharmId(self,conn_database):
    
YamlUtil().write_extract_yaml('token')  #读写yaml的token
    url = "…… token="+token+""     #直接使用token
    data = {"SN":"","ID":"32"}     
    rep =session.request("post",url=url,json=data)    
    print(rep.json()) 
    TestSendRequest.cks =rep.cookies   def test_file_upload(self):
    url ="…… token="+TestSendRequest.token+""
    data = {
      "file":open(r"E:\SHU.png":"rb")
}
    headeres = {
      "Accept":"application/json,text/javascript"
      "x-Requested-with":"XMLHttpRequest"
}
    rep =session.request("post",url=url,files=data,headers=headers,cookies=TestSendRequest.cks)
    print(rep.json())
 

pytest用例管理框架实战(基础篇)的相关教程结束。

本文地址:https://www.ufcn.cn/tutorials/2453308.html

如非特殊说明,本站内容均来自于网友自主分享,概不代表本站观点,如有任何问题我们都将在收到反馈后的第一时间进行处理!