The strongest in the whole network, interface automation test-token login association actual combat summary (super detailed)


foreword

When you log in to the company's background management system on the PC or log in to an APP on your mobile phone, you will often find that after the login is successful, the return parameter will contain token, whose value is a long string, and the subsequent request The token needs to be included as a parameter in the header, otherwise it will prompt you to log in first.

What are tokens?

token is generated by the server and is the identity token used by the client for requests. When the first login is successful, the server will generate an encrypted string token containing user information, return it to the client and save it locally, and the subsequent client only needs to bring the token to make a request, without the need to bring the username and password.

The token principle is briefly summarized as follows:
After the user logs in successfully for the first time, the server will generate a token value, which will be saved in the database and returned to the client at the same time;

After the client gets the token value, save it locally;

When the subsequent client sends other requests except login again, it will send the token value stored locally as a parameter to the server together;

After receiving the request from the client, the server will compare the sent token value with the token value stored in the database;
if the two token values ​​are the same, it means that the current user is logged in;
if there is no such token value in the database or If the token value has already taken effect, the user needs to log in again.

token scene processing

A management background system of the company returns a token after logging in, and then needs to add this token in the request header when requesting other interfaces, otherwise it prompts to log in first.

The login interface to request the system is as follows:

import requests
import json

headers = {
    
    "Content-Type": "application/json;charset=utf8"}
url = "http://127.0.0.1:5000/login"
_data = {
    
    
    "username": "刘德华",
    "password": "123456"
}
res = requests.post(url=url, headers=headers, json=_data).text
print(res)

The result is as follows:

{
    
    
  "code": 1000, 
  "msg": "登录成功!", 
  "token": "sh34ljjl08s32730djsh34ljjl08s32730djsh34ljjl08s32730djsh34ljjl08s32730djsh34ljjl08s32730djsh34ljjl08s32730dj"
}

When doing interface automation testing on the project, you need to request the login interface to get the token first, and then request other interfaces. It is feasible to request the login interface once every time other interfaces are requested, but this will not only reduce the efficiency of automation execution, but also waste server resources by requesting login every time.

Two processing ideas:

Idea 1

Before executing the use case, request the login interface first, and store the returned token value in a file (such as a yaml file). Subsequent requests need to use the token value from this file.

For reading and writing of yaml files in python, please refer to my previous article Python reads and writes yaml files (using the PyYAML library).

1. Run the interface automation test framework. When initializing, first request to log in to the interface, obtain the token value, and write it into the specified yaml file.

import requests
import json
import yaml

def get_token():
    '''
    请求登录接口,获取token
    :return:
    '''
    headers = {
    
    "Content-Type": "application/json;charset=utf8"}
    url = "http://127.0.0.1:5000/login"
    _data = {
    
    
        "username": "刘德华",
        "password": "123456"
    }
    res = requests.post(url=url, headers=headers, json=_data).text
    res = json.loads(res)
    token = res["token"]
    return token


def write_yaml(token):
    '''
    写入yaml文件
    :return:
    '''
    t_data = {
    
    
        "token": token
    }
    with open("yaml文件路径", "w", encoding="utf-8") as f:
        yaml.dump(data=t_data,  stream=f, allow_unicode=True)


if __name__ == '__main__':
    token = get_token() # 获取token
    write_yaml(token)   # 将token值写入yaml文件

2. When executing the test case, first read the token value in the yaml file, and add the token to the headers (some also put the token in the request parameter, depending on the specific situation of the tested project), and then send the request.

import requests
import yaml
import pytest
import json

def read_yaml():
    '''
    读yaml文件
    :return:
    '''
    with open('yaml文件路径', 'r', encoding='utf-8') as f:
        result = yaml.load(f.read(), Loader=yaml.FullLoader)
    token = result["token"]
    return token


def test_check_user():
    '''
    查询个人信息(需要先登录系统)
    :return:
    '''
    # 先从yaml文件中读取token
    token = read_yaml()
    # 再将token添加到请求头中
    headers = {
    
    
        "Content-Type": "application/json;charset=utf8",
        "token": token
    }

    url = "http://127.0.0.1:5000/users/3"
    res = requests.get(url=url, headers=headers).text
    # 返回结果为json格式,转换为字典
    res = json.loads(res)
    # 断言code是否为1000
    assert res["code"] == 1000


if __name__ == '__main__':
    pytest.main()

This is just an example, but in the actual framework, we need to encapsulate these functions such as reading and writing of yaml files separately in a certain module for other modules to call, so that the code will be clearer and more concise.

Idea 2

Using the Fixture function in pytest, the scope is set to session, and the token value is returned, and the subsequent test method/function calls the Fixture function.

For the use of Fixture in pytest, please refer to my previous article pytest(6)-Fixture (firmware).

1. First, define a fixture function with the scope of session in conftest, which is used to request the login interface to return token.

import pytest
import requests
import json

@pytest.fixture(scope="session")
def get_token_fixture():
    '''
    作用域为session的fixture函数,返回token
    :return:
    '''
    headers = {
    
    "Content-Type": "application/json;charset=utf8"}
    url = "http://127.0.0.1:5000/login"
    _data = {
    
    
        "username": "刘德华",
        "password": "123456"
    }
    res = requests.post(url=url, headers=headers, json=_data).text
    res = json.loads(res)
    token = res["token"]
    return token

2. Next, the test case calls the Fixture.

def test_check_user(get_token_fixture):
    '''
    查询个人信息(需要先登录系统)
    :return:
    '''
    # 通过Fixture函数g获取et_token_fixture值,即token,再将token添加到请求头中
    headers = {
    
    
        "Content-Type": "application/json;charset=utf8",
        "token": get_token_fixture
    }

    url = "http://127.0.0.1:5000/users/3"
    res = requests.get(url=url, headers=headers).text
    res = json.loads(res)
    print(res)
    print(headers)
    assert res["code"] == 1000


if __name__ == '__main__':
    pytest.main()

The results of executing the test case are as follows:

A1

Compared with Session/Cookies, the use of token is more suitable for systems with a large amount of requests or involving third-party interfaces.

Some project tokens are sent in the request header, while some projects are sent in the request parameters. When doing interface automation, it is necessary to clarify which method is used.

You can choose one of these two ideas when the interface automatically processes tokens. If you use the pytest framework, it is recommended to try idea 2.

The following is the most complete software test engineer learning knowledge architecture system diagram in 2023 that I compiled

1. From entry to mastery of Python programming

Please add a picture description

2. Interface automation project actual combat

Please add a picture description

3. Actual Combat of Web Automation Project

Please add a picture description

4. Actual Combat of App Automation Project

Please add a picture description

5. Resume of first-tier manufacturers

Please add a picture description

6. Test and develop DevOps system

Please add a picture description

7. Commonly used automated testing tools

Please add a picture description

Eight, JMeter performance test

Please add a picture description

9. Summary (little surprise at the end)

Galloping like the wind, unstoppable; shining like the light, dazzling. Struggle is the rhythm of life, and struggle is the soul of dreams. Don't be afraid of difficulties, never give up, interpret tenacity and bravery with actions, and create your own brilliance! Go forward bravely and struggle endlessly!

Embrace challenges and go beyond the limits; let your mind fly and create miracles. The road of struggle may be bitter, but faith and perseverance will create brilliance. Bravely pursue your dream, set sail, and you will write your own magnificent chapter!

Raise the sails and chase the wind of the future. Struggle is not limited to striving for success, but also a journey that gives life infinite possibilities. Believe in your ability, burn your inner passion, and create a brilliant life with sweat and hard work. Embark on a journey and create your own magnificent legend! Struggle unceasingly, dream blossoms!

Guess you like

Origin blog.csdn.net/shuang_waiwai/article/details/132145952