Pytest uses fixtures to implement token sharing

When students are doing pytest interface automation , they will encounter a scenario where different test cases need a pre- login step. After the login is completed, the token will be obtained and used in the subsequent code. First, let me demonstrate a conventional practice.

First define a login method in conftest, the method returns token

@pytest.fixture(scope="function")
def login():
    header = {
            "Content-Type": "application/json"
    }
    data = {
            "username": "test",
            "password": "test"
    }
    login_info = requests.post(url='http://.../login',json=data).json()
    return login_info['token']

Introduce this method in the test case method, and all tokens used need to use the login method.

def test_user(login):
    token = login # 通过login获取token
    ......
def test_address(login):
    token = login # 通过login获取token
    ......

Through the above method, the requirement of using token for the interface can be solved, but every time this is done, the login interface will be executed first. Is there a way to execute the login interface only once, and the subsequent interfaces will not call the login interface. After Lao Wu's test, it can actually be done.

Idea: The login interface uses the cache. When there is a token, the token is used, and the login interface is not called. If not, the login interface is called, and the token is cached.

Then you need to modify the login method above, add the save_token method, and save the token. Introduce the pickle module to write data.

import pickle
@pytest.fixture(scope="function")
def login():
    ......
    # 增加缓存方法
    save_token(login_info['token'])
    return login_info['token']
 
def save_token(token):
    # login_path为目录中一个存放token的文件路径,自己定义。
    with open(login_path, 'wb') as f:
        pickle.dump(login_info, f)
        f.close()

The above code completes the writing of the token, and when there is no token, the token is written into the file. If there is a token, we don't need to perform the login operation, and directly use the token in the file. At this time, the code needs to be modified. At the beginning of the method, it is judged whether there is a file saving the token, and if so, the token is obtained, and the login operation is no longer performed. Add another method get_login_info to read the content of the file

import pickle
@pytest.fixture(scope="function")
def login():
    if os.path.exists(login_info):
        return get_login_info(login_info)
    else:
        ......
        # 增加缓存方法
        save_token(login_info['token'])
        return login_info['token']
# 增加一个读取文件的方法
def get_login_info():
    with open(login_path, 'rb') as f:
        data = pickle.load(f)
        f.close()
        return data

90% of the above work has been completed, and a finishing touch will be perfect. After each execution of the use case, delete the saved token file, otherwise a token is generated, and the code will not call the login interface if the code judges that the token file exists. Once the token expires, the use case execution will fail.

Define a method in conftest to clean up the token file every time a use case is executed. Note that the level is session level.

@pytest.fixture(scope='session', autouse=True)
def clear_login_file():
    if os.path.exists(login_path):
        logger.info("清理token文件")
        os.remove(login_path)

Guess you like

Origin blog.csdn.net/nhb687095/article/details/131455066