Ultra-detailed, Pytest automated test framework token global settings - use in multiple environments (actual combat)


foreword

When doing automated testing, I often encounter a requirement that I only log in once in the global use case, and all subsequent use cases will automatically bring the request header token or cookies.

You can customize the fixture to update the built-in requests_session, and add token to the request header to achieve global login.

1. Global token implementation
In the conftest.py file under the project, log in first and update the request header token

import pytest
from pytest_yaml_yoyo.http_session import HttpSession
import jsonpath
"""
全局仅登录一次,获取token,
在请求头部添加 Authorization: bearer **token** 认证
  也有这种格式 Authorization: Token **token**
内置fixture requests_session
"""


@pytest.fixture(scope="session", autouse=True)
def login_first(requests_session: HttpSession) -> None:
    """全局仅一次登录, 更新session请求头部"""
    # 调用登录方法,获得token
    url = "http://127.0.0.1:8200/api/v1/login"
    body = {
    
    
        "username": "test1",
        "password": "123456"
    }
    r = requests_session.post(url, json=body)
    token = jsonpath.jsonpath(r.json(), '$..token')[0]
    print(f'账号 test1 登录获取到token: {
      
      token}')
    headers = {
    
    
        "Authorization": f"Token {
      
      token}"
    }
    requests_session.headers.update(headers)

Use case content in cases/test_info.yml

test_user_info:
  name: 用户信息
  request:
    url: /api/v1/userinfo
    method: GET
  validate:
    - eq: [$.code, 0]
    - eq: [$.msg, success!]

Only the relative path is written in the use case, and the base_url environment address needs to be configured in pytest.ini

[pytest]

log_cli = true
log_cli_level = info
base_url = http://127.0.0.1:8200

Execute the pytest command to run the use case, and you will see that the token is automatically included in the request header

2023-06-08 11:12:02 [INFO]: 运行用例-> test_user_info
2023-06-08 11:12:02 [INFO]: --------  request info ----------
2023-06-08 11:12:02 [INFO]: yml raw  -->: {
    
    'url': '/api/v1/userinfo', 'method': 'GET'}
2023-06-08 11:12:02 [INFO]: method   -->: GET
2023-06-08 11:12:02 [INFO]: url      -->: /api/v1/userinfo
2023-06-08 11:12:02 [INFO]: headers  -->: {
    
    'User-Agent': 'python-requests/2.31.0', 'Accept-Encoding': 'gzip, deflate', '
Accept': '*/*', 'Connection': 'keep-alive', 'Authorization': 'Token 8846dbad632813f097c577d0ff6aafc4547090f9'}

In this way, you can only log in once globally, and all subsequent use cases will automatically bring the login request header 'Authorization': 'Token ...'.

Although the above method implements a global token, the login token address is hard-coded. If there are multiple environments that need to be switched, and the login accounts of different environments are different, it is necessary to automatically read the environment configuration according to the environment switching. .

2. Multiple sets of environment configuration

Configure different environments in config.py under the project

class Config:
    """每个环境都有一样的公共配置"""
    version = "v1.0"
    appId = 10086


class TestConfig(Config):
    """测试环境"""
    BASE_URL = 'http://127.0.0.1:8200'
    USERNAME = 'test1'
    PASSWORD = '123456'
    BLOG_URL = 'https://www.cnblogs.com'


class UatConfig(Config):
    """联调环境"""
    BASE_URL = 'http://192.168.1.12:8201'
    USERNAME = 'test8'
    PASSWORD = '123456'
    

# 环境关系映射,方便切换多环境配置
env = {
    
    
    "test": TestConfig,
    "uat": UatConfig
}

It is also necessary to configure the environment name in pytest.ini, so that the base_url in pytest.ini does not need to be configured, and can be written all in the configuration in config.py with uppercase BASE_URL

[pytest]

log_cli = true
log_cli_level = info

env = test

Log in first in the conftest.py file under the project, and the modification is as follows

import pytest
from pytest_yaml_yoyo.http_session import HttpSession
import jsonpath
"""
全局仅登录一次,获取token,
在请求头部添加 Authorization: bearer **token** 认证
  也有这种格式 Authorization: Token **token**
内置fixture requests_session
"""


@pytest.fixture(scope="session", autouse=True)
def login_first(requests_session: HttpSession, environ) -> None:
    """全局仅一次登录, 更新session请求头部"""
    # 调用登录方法,获得token
    url = environ.BASE_URL + "/api/v1/login"
    print(url)
    body = {
    
    
        "username": environ.USERNAME,
        "password": environ.PASSWORD
    }
    r = requests_session.post(url, json=body)
    token = jsonpath.jsonpath(r.json(), '$..token')[0]
    print(f'账号 {
      
      environ.USERNAME} 登录获取到token: {
      
      token}')
    headers = {
    
    
        "Authorization": f"Token {
      
      token}"
    }
    requests_session.headers.update(headers)

There are two ways to switch the environment to run.
Method 1: Modify the env value in pytest.ini

[pytest]

env = uat

Method 2: Switch the environment through the command line

pytest --env=uat

In this way, the configuration of the environment can be automatically obtained according to the switching of the environment to generate a token corresponding to the environment.

There is also a simple method, as long as the BASE_URL attribute is added to the environment configuration, you can use requests_session.send_request() to request a relative path

import pytest
from pytest_yaml_yoyo.http_session import HttpSession
import jsonpath
"""
全局仅登录一次,获取token,
在请求头部添加 Authorization: bearer **token** 认证
  也有这种格式 Authorization: Token **token**
内置fixture requests_session
"""


@pytest.fixture(scope="session", autouse=True)
def login_first(requests_session: HttpSession, environ) -> None:
    """全局仅一次登录, 更新session请求头部"""
    # 调用登录方法,获得token
    url = "/api/v1/login"
    body = {
    
    
        "username": environ.USERNAME,
        "password": environ.PASSWORD
    }
    r = requests_session.send_request('post', url, json=body)
    token = jsonpath.jsonpath(r.json(), '$..token')[0]
    print(f'账号 {
      
      environ.USERNAME} 登录获取到token: {
      
      token}')
    headers = {
    
    
        "Authorization": f"Token {
      
      token}"
    }
    requests_session.headers.update(headers)
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)

Only struggle can embrace brilliance; only hard work can pursue dreams; only persistence can overcome difficulties; only positiveness can create miracles; only bravery can change life. Don't give up, go forward to success!

Only through wind and rain can we see the rainbow; only through setbacks can we see success; only through hard work can we reap achievements. Persevering in chasing dreams will eventually shine on the stage of life.

Only persistent struggle can light up the light of hope in the heart, dispel confusion and confusion, and finally achieve a brilliant life. No matter how difficult the road ahead is, go forward bravely, faith and hard work will lead you to the other side of success.

Guess you like

Origin blog.csdn.net/m0_70102063/article/details/131556749