pytest的好处:
具有丰富的插件结构
易用性
通过pytest.mark.parametruze进行参数化测试
内置fixture机制
通过login.yaml获取若依的token
url: http://62.234.166.117/prod-api/login
data:
username: admin
password: admin123
header:
Content-Type: application/json
conftest.py 进行fixture调用,保存token
import pytest
import yaml
import yaml_package
import requests
@pytest.fixture (scope="function",autouse= "True")
def pro_post_output():
print("测试用例执行")
yield
print("end of the test process")
@pytest.fixture(scope="session",autouse= "True")
def get_token():
print("获取token")
yaml_data = yaml_package.load_yaml("login.yaml")
url = yaml_data["url"]
json_data = yaml_data["data"]
headers = yaml_data["header"]
result = requests.post(url, json=json_data, headers=headers)
response = result.json()
print(response)
token = response["token"] # 提取 token
print("token:", token)
Authorization = f"Authorization: Bearer {token}"
yaml_package.append_yaml("add.yaml",Authorization,"header")
yield token
print("end of token")
add.yaml进行相应的增加接口调用,这里以用户增加为例,自输入相应的url和请求参数,请求头除了content-type外就是以上的token追加 是Bear {token}形式
测试函数
import pytest
import yaml_package
import requests
#静言可以不用self
class TestAPI:
def test_token(self):
x = 200
assert x == 200
def test_add(self):
yaml_data=yaml_package.load_yaml("add.yaml")
url = yaml_data["url"]
data = yaml_data["data"]
head = yaml_data["header"]
print(head)
result =requests.post(url,json=data,headers=head )
resp=result.json()
print(resp)
assert resp["code"] == 200