Python interface automated testing

course address

request

The difference between requests.post() data and json

postdata = {
    
    'jobId': '1',
            'jobType': 'predict',
            'targetClass': 'vm',
            'targetId': 123}
requests.post('http://127.0.0.1:5000/api/getPredictInfo', json=postdata,
                          headers={
    
    'Content-Type': 'application/json'})
或者
requests.post('http://127.0.0.1:5000/api/getPredictInfo', data=json.dunps(postdata))    

Data parameter means form parameter: the default request header is Content-Type: application/x-www-formurlencoded, the format of the request parameter: (k1=v1&k2=v2), and the parameter is a dict of pure key-value pairs, such as:
{key1:value1,key2:value2}
data parameter means text parameter: default request header: text/plain. Parameter: str type
json pass parameter means json pass parameter: default request header: application/json, parameter is dict type
json is Dict type including key-value pairs and lists

File Upload

postdata = {
    
    'midea':open('./test.jpg',"rb")}
requests.post('http://127.0.0.1:5000/api/getPredictInfo', files=postdata)

test with cookie

rep= requests.get()
通过get请求获取到登陆的token,然后登陆测试
headers = {
    
    "Accept":"aplication/json,text/javascript,*/*;q=0.01",
			"X-Requested-With":"XMLHttpRequest"}
rep = requests.post(url,data=data,headers=headers,cookies=rep.cookies)

Complete multiple request tests in the same session

You can replace the above requests.post, requests.getetc. with

requests.session().request("post",xxx)
requests.session().request("get",xxx)

This unified interface requests.postis calledrequests.request()

pytest

1. The module name must start with test_ or _test
2. The test class must start with Test and cannot have an init method
3. The test method must start with test_
4. Pytest has many powerful plugins. pip installInstall

pytest-html generate a simple report
pytest-xdist multi-threaded
pytest-orderding control the execution order of test cases
pytest-rerunfailures failed cases re-run
pytest-base-url base path configuration
allure-pytest generate allure report

Command Line

pytest -vs
pytest -k “add” 执行所有测试用例名中含有“add”的用例
pytest - s 打印测试用例中print语句
pytest -v 增加打印细节
pytest - x 一旦发现失败用例,停止运行
pytest -maxfail=2 当测试遇到两条失败,立刻停止运行
pytest -m “标签名” 给测试用例加标签
pytest -n 多线程(需要安装pytest-xdist)
pytest --reruns=2 失败用例重跑2次
pytest --html='./report.html' 生成简易报告

configuration file

Note:
1. Whether it is the command line or the main function, this configuration file will be automatically read
2. pytest.iniThe file can change the default test case rules of pytest
3. This file is generally placed in the root directory of the project

[pytest]
#配置参数
addopts = ‐vs
#配置测试用例文件夹
testpaths = ./testcases
#配置测试模块的规则
python_files = test_*.py
#配置测试类的规则
python_classes = Test*
#配置测试方法的规则
python_functions = test_*
#配置接口测试的基础路径
base_url = http://127.0.0.1/
#给用例分组
markers =
smoke:冒烟测试
usermanage:用户管理

Smoke and user management need to add a decorator on the use case:

@pytest.mark.smoke
@pytest.mark.usermanage

When executing, you need to use:

-m 分组名 or 分组名

The default execution order of Pytest test cases is from top to bottom.
You can change the execution order of test cases through the following tags@pytest.mark.run(order=1)

Pytest preconditions

before or after all classes, all use cases

def setup_class(self):
	print("在类之前的操作")
	
def teardown_class(self):
	print("在类之后的操作")
	
def setup(self):
	print("在所有用例之前的前置操作")

def teardown(self):
	print("在所有用例之后的后置操作")

Wish to execute before or after some use cases. The complete structure using the Fixture
Fixture decorator is as follows:

@pytest.fixture(scope="作用域",autouser="自动执行",params="数据驱
动",ids="参数别名",name="fixture别名")

scope: Mark the scope of the fixture

  • function: Function level (can be manual or automatic)
  • class: class level (usually automatic)
  • module: module level (usually automatic)
  • package/session:session level (usually automatic): encapsulates framework usage tomorrow.

autouser=TrueAutomatically implement the alias of
paramsthe data-driven
namerepresentation of the fixture. When the alias is used to create an alias, the original name of the fixture will become invalid.

Part of the preceding use cases, the test case directly passes in the function name of the preceding function

import pytest

# 部分测试用例前置
@pytest.fixture()
def conn_database():
    print("连接数据")
    yield
    print("关闭")


class TestALL:

    def test_A(self):
        print("test A")

    def test_B(self,conn_database):
        print("test B")

    def test_C(self):
        print("test C")

if __name__ == '__main__':
    pytest.main(['-vs'])

Optimization
Generally, fixtures will be used together with conftest.py files.

conftest.py是专门用于存放fixture的,是固定名称
conftest.py文件的方法使用时不需要导包
conftest.py文件可以有多个

Put the above conn_database function into the newly created conftest.py file

@pytest.fixture(scope="session",autouse=True)
def claer_yaml():
    YamlUtil().clear_yaml()

claer_yamlThe function is automatically executed and does not need to be passed in as a parameter

generate allure report

1. Download and install
2. pip install allure-pytest
3. addopts = ‐vs --allurdir ./temp# Save path of the generated json file
4. Generate a report through json os.system("allure generate temp -o report")and generate it in the report directory

data driven testing

import pytest
class TestApi:
    @pytest.mark.parametrize("args",["a","b","c"])
    def test_api(self,args):
        print(args)

if __name__ == '__main__':
    pytest.main(['test_2.py'])

postman

interface association

insert image description here
Other interfaces need to use the return value of the above interface, as follows
insert image description here

context switching

insert image description here
insert image description here

Dynamic parameter passing

{ {$timestamp}}Generate a timestamp of the current time
{ {$randomInt}}Generate a random number between 0-1000 (rarely used)
{ {$guid}}Generate a shorthand GUID string


insert image description here
When requesting custom dynamic parameters, pass { {time}}the reference
insert image description here

Business closed loop (add, delete, modify, check)

Use global variables, and then delete, modify and check direct references to global variables
insert image description here

Affirmation

in Pre-request-Scriptthe module
insert image description here

state assertion

insert image description here

business assertion

insert image description here

In the tests tab, global variables cannot be obtained through { {}}, but can only be obtained through the following methods
insert image description here
insert image description here
. The exact same assertion can be used as a global assertion without repeating it in each script
insert image description here
insert image description here

File Upload

insert image description here

batch test

Test multiple scripts at once
insert image description here
insert image description here

File upload batch test interface error

Postman software changes settings
Settings-> General-> Location
1, open Allow reading files outside working drectory
2, copy the file to be uploaded and tested to the default directory (postman will read the file in the default directory)

data driven testing

Generally, when CSV or JSON files
insert image description here
are batch tested, if the returned results are the same, it may be that Paramsthe parameter values ​​​​are written to death before, and it needs to be changed to get
insert image description here
the values ​​​​of variables in the file, and the value data.变量名is not the previous one.global.

Test with request header

Need to use the packet capture tool Telerik Fiddler

insert image description here
Copy it Headersto , delete some addresses, unnecessary information

Cookie Authentication Test

A cookie is a small piece of text information, which is generated when the client requests the server for the first time, and is included in the first request, and returned
to the client, and will be included in the request in the future请求头没有Cookie响应头set-cookie生成Cookie请求头Cookie

postman will automatically save cookies

Postman's Mock Server server

Usage scenario: front-end and back-end are separated, the back-end interface is not completed, but the front-end has been completed, and the front-end business process depends on the back-end interface

insert image description here
It is equivalent to creating a back-end interface by yourself to test the front-end, and you can customize the return information

Interface test encryption and decryption

Encryption and decryption test website
Pre-Script-Request Write code to encrypt documents and set it as a global variable test

Newman

Test cases in postman everywhere, global variables, environment variables, data files
insert image description here
NewMan installation

newman run 接口脚本.json -e 环境变量.json -r html --reporter-html-export test.html

Detailed parameters

RobotFrameWork

Install Robot Framework

pip install robotframework

Install the GUI interface

pip install –i https://pypi.douban.com/simple robotframework-ride

custom keywords

insert image description here
insert image description here
Right-click the newly created file. The
insert image description here
newly created file cannot be used yet, and the resource file must be imported into the suite
insert image description here

common library

Extension library
1) web automation library –Selenium

pip install –i https://pypi.douban.com/simple robotframework- seleniumlibrary

2) API automation library –requests

pip install -i https://pypi.python.org/pypi/robotframework-requests

3) app automatic library

pip install robotframework-AppiumLibrary 

Guess you like

Origin blog.csdn.net/weixin_44831720/article/details/124733774