程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Pythons learning record for interface testing Day5 -- an automated testing framework containing token associations for pytest+yaml data-driven +allure reports]

編輯:Python

In the previous study , We have installed all the required plug-ins , Now let's start recording a containing token The whole process of setting up the associated interface automation framework

Our overall structure is as follows :

common: Used to store public classes reports Yes generate report temp It is generated by the test interface json data  , Used to generate reports ( See the previous report generation article for details )testcases Used to store test cases , Others are configuration files , Run the program and pre post

First step ,YAML Encapsulation of data methods

First of all, let's talk about yaml Data reading , write in , Clear and other methods for encapsulation , It belongs to the public method , So we have common Create yaml_util.py The code is as follows

import os
import yaml
# Read
class YamlUtil:
# Read
def read_yaml(self,key):
with open(os.getcwd() + '/extract.yaml', encoding='utf-8', mode='r') as f:
value = yaml.load(f, yaml.FullLoader)
return value[key]
# write in
def write_yaml(self,data):
with open(os.getcwd() + '/extract.yaml', encoding='utf-8', mode='a') as f:
yaml.dump(data, stream=f, allow_unicode=True)
# Empty
def clear_yaml(self):
with open(os.getcwd() + '/extract.yaml', encoding='utf-8', mode='w') as f:
f.truncate()
# Read test cases
def read_testcase(self,yaml_name):
with open(os.getcwd() + '\\testcases\\' + yaml_name, mode='r', encoding='utf-8') as f:
value = yaml.load(f, yaml.FullLoader)
return value

The second step , Encapsulation of interface requests

Still in common Created in request_util.py file , The code is as follows :

import requests
import json
class RequestUtil:
sess= requests.session()
def send_request(self,method,url,datas=None,**kwargs):
method=str(method).lower() # Convert lowercase
res=None
if method=="get":
res=RequestUtil.sess.request(method=method,url=url,params=datas,**kwargs)
elif method=="post":
if datas and isinstance(datas,dict):
datas=json.dumps(datas)
res=RequestUtil.sess.request(method=method, url=url, data=datas, **kwargs)
else:
pass
return res

Here I only encapsulate get and post Two requests , If you want to use other methods , You can join by yourself .

The third step ,yaml Data creation

Create a get_token.yaml file , Use cases used to store our login interface , For example, I :

-
name: Obtain the unified authentication code of the interface token Interface
request:
method: post
url: https://***/jlcloud/api/login
data:
"account": "****"
"password": "014f4041514bc5dcb82845fe5efa3c54"
"project": "DEFAULT"
"teacherLogin": False
"clientId": "1"
"secret": ""
headers:
'Content-Type': 'application/json'
validate: None
-
name: Obtain the unified authentication code of the interface token Interface
request:
method: post
url: https://***/jlcloud/api/login
data:
"account": "***"
"password": "123456"
"project": "DEFAULT"
"teacherLogin": False
"clientId": "1"
"secret": ""
headers:
'Content-Type': 'application/json'
validate: None

yaml Please refer to my previous article on data writing rules ,

The second interface is to obtain user information get request , I create userinfo.yaml To store the use cases of the second interface

-
name: Obtain the unified authentication code of the interface token Interface
request:
method: get
url: https://***/jlcloud/api/login/getUserInfo
data:
{}
headers:
'Content-Type': 'application/json'
validate: None

Step four , Interface test automation

After data preparation , stay testcases Next create a test_login Of py file , Here we are test_login Write code in 、

import pytest
import requests
import json
from common.request_util import RequestUtil
from common.yaml_util import YamlUtil
class TestRequest:
pass
@pytest.mark.parametrize("args_name",YamlUtil().read_testcase('get_token.yaml')) ## Read the of the test case get_token.yaml Parameters and values in the file , Assign a value to a variable args_name
def test_login(self,args_name):
url=args_name['request']['url']
data = args_name['request']['data']
method= args_name['request']['method']
headers=args_name['request']['headers']
res = RequestUtil().send_request(method=method, url=url, datas=data, headers=headers)
print(res.text)
if "data" in res.text:
YamlUtil().write_yaml({"token":res.json()['data']}) # take token Value write yaml file , After execution, the root directory is generated extract.yaml file , The extracted... Can be viewed here token
@pytest.mark.parametrize("userinfo", YamlUtil().read_testcase('userinfo.yaml'))## Read the of the test case userinfo.yaml Parameters and values in the file , Assign a value to a variable userinfo
def test_userinfo(self, userinfo):
token = YamlUtil().read_yaml('token') # Read token Value
url = userinfo['request']['url']+'?token='+token # I am here. url Need to bring token
data = userinfo['request']['data']
method = userinfo['request']['method']
headers = userinfo['request']['headers']
res = RequestUtil().send_request(method=method, url=url, datas=data, headers=headers)
print(res.text)

Step five , Test pre post

Create in the root directory conftest.py, Note that the file name is pytest frame What is written dead cannot be changed , It is often used to deal with the preconditions of test cases . And use fixture Mark up some functions , For example, the operation of connecting to the database 、 Or our kind of token Value change , It needs to be cleared before each run

Here we do it during the test yaml Data clearing

import pytest
from common.yaml_util import YamlUtil
@pytest.fixture(scope="function")
def exe_sql():
print(" Before use case execution ")
yield
print(" After the use case is executed ")
# Execute before all interface requests
@pytest.fixture(scope="session",autouse=True)
def clear_extract():
YamlUtil().clear_yaml()

Step six , function

Create a new directory in the root directory run.py file

import pytest
import os
if __name__ == '__main__': # pytest Operation mode
pytest.main()
os.system("allure generate ./temp -o ./reports --clean") ## Generate test reports 

After operation , The directory will automatically generate temp Of json data , as well as reports Inside index.html file , Open the file to view the report , as follows :

 

Such a simple framework is built , Of course, this is only a very preliminary framework , Many problems cannot be realized with this framework , For example, dynamic parameter problem , The data is too large , I will continue to follow up in the process of learning , You are welcome to give me some advice , Discuss ~


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved