Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize token Associated Login of python+pytest Interface Automation

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, I would like to share with you the relevant knowledge of python+pytest interface automation token association login. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's learn about it.

When you log in to the company's backend management system on the PC or log in to an APP on the mobile phone, you will often find that the token is included in the return parameters after the login is successful, and its value is a long string. The token is required as a parameter in the request header for subsequent requests, otherwise you will be prompted to log in first.

This is actually the third way of state or session persistence, token.

one。 What is token?

The token is generated by the server and is the identity token used by the client to request. When the login is successful for the first time, the server generates an encrypted string token containing user information, which is returned to the client and saved locally. The subsequent client only needs to bring token to make the request, without the need for user name and password.

The principles of token are briefly summarized as follows:

After the user logs in successfully for the first time, the server generates a token value, saves it in the database, and returns it to the client.

After the client gets the token value, save it locally

When the subsequent client sends a request other than login, it will send the token value saved locally as a parameter to the server.

After receiving the request from the client, the server compares the sent token value with the token value stored in the database.

If the two token values are the same, the current user is logged in

If the token value is not in the database or is already in effect, the user needs to log in again.

two。 Token scene processing

When a company manages a backend system, return token after login, and then add this token to the request header when you go to request other APIs. Otherwise, please log in first.

The login interface for requesting the system is as follows:

Import requestsimport jsonheaders = {"Content-Type": "application/json;charset=utf8"} url= "http://127.0.0.1:5000/login"_data = {" username ":" Andy Lau "," password ":" 123456 "} res = requests.post (url=url, headers=headers, json=_data) .textprint (res)

The results are as follows:

{

"code": 1000

"msg": "Login successful!"

"token": "sh44ljjl08s32730djsh44ljjl08s32730djsh44ljjl08s32730djsh44ljjl08s32730djsh44ljjl08s32730djsh44ljjl08s32730dj"

}

When doing interface automation testing on a sampled project, you need to request the login interface to get the token, and then request other interfaces. It is feasible to request a login interface each time you request another interface, but it not only reduces the efficiency of automation, but also wastes server resources every time you request a login.

Here are two ways to deal with it. 1. Idea one

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

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

1. Run the interface automation test framework. When initializing, request the login interface, get the token value, and write it to the specified yaml file.

Import requestsimport jsonimport yamldef get_token ():''request login API to get token: return: headers = {"Content-Type": "application/json" Charset=utf8 "} url=" http://127.0.0.1:5000/login" _ data = {"username": "Andy Lau", "password": "123456"} res = requests.post (url=url, headers=headers) Json=_data) .text res = json.loads (res) token = res ["token"] return tokendef write_yaml (token): write yaml file t_data = {"token": token with open ("yaml file path", "w", encoding= "utf-8") as f: yaml.dump (data=t_data, stream=f) Allow_unicode=True) if _ _ name__ = ='_ main__': token = get_token () # get token write_yaml (token) # write the token value to the yaml file

2. When executing the test case, read the token value in the yaml file and add token to the headers (or put token in the request parameters, depending on the specific circumstances of the project being tested), and then send the request.

Import requestsimport yamlimport pytestimport jsondef read_yaml ():''read yaml file: return: with open (' yaml file path', 'ringing, encoding='utf-8') as f: result = yaml.load (f.read () Loader=yaml.FullLoader) token = result ["token"] return tokendef test_check_user (): query personal information (you need to log in to the system first) # read token token = read_yaml () from the yaml file first # then add token to the request header 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 # returns the result in json format, which is converted to the dictionary res = json.loads (res) # to assert whether code is 1000 assert res ["code"] = = 1000if _ _ name__ = ='_ main__': pytest.main ()

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

two。 Idea two

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.

Please refer to my previous article pytest (6)-Fixture (firmware) for the use of Fixture in pytest.

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

Import pytestimport requestsimport json@pytest.fixture (scope= "session") def get_token_fixture (): 'the fixture function whose scope is session, and returns token: return:' 'headers = {"Content-Type": "application/json" Charset=utf8 "} url=" http://127.0.0.1:5000/login" _ data = {"username": "Andy Lau", "password": "123456"} res = requests.post (url=url, headers=headers, json=_data). Text res = json.loads (res) token = res ["token"] return token

2, and then the test case calls the Fixture.

Def test_check_user (get_token_fixture):''to query personal information (you need to log in to the system first): return:''# get the et_token_ fixture value, namely token, through the Fixture function g, and then add token to the request header 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"] = = 1000if _ _ name__ = ='_ main__': pytest.main ()

The results of executing the test case are as follows:

These are all the contents of the article "how to implement token Association Login for python+pytest Interface Automation". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 239

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report