Learn this Pytest function and easily switch the automated testing environment!

foreword

In the current Internet companies, there are multiple test environments, so when the automation we write wants to run in multiple test environments, how to use it?

What most people think of is probably by modifying the address in our automation code to a different environment.

But at this time, some workload will be added. Every time you run a different environment, you need to modify the address in the configuration file, which is very inconvenient.

Today, the editor introduces a Pytest hook function, which can help us solve this problem easily.

pytest_addoption

pytest_addoption is one of Pytest's hook functions, which is used to add custom options to Pytest and pass these options to test cases.

These options can be set by modifying Pytest's configuration file (pytest.ini) or using command-line arguments.

pytest_addoption This function generally needs to be used in combination with request.config.getoption (obtain command line parameter information) in the built-in function request of pytest fixture.

In the above problem, we can modify the test environment address in the command line parameters, so that the same automation code can be executed in different test environments only through the command line parameters without modifying the configuration file.


def pytest_addoption(parser):
    parser.addoption(
        "--anjing",
        action="store",
        default="dev",
        help="通过'anjing'添加自定义命令行参数名称"
    )

Parameter introduction

Introduction to some parameters commonly used in pytest_addoption:

  • name: Indicates the name of the custom command line parameter, generally used through "-xxx";

  • action: Indicates the basic operation type to be taken when this parameter is encountered in the command line to store the parameter value corresponding to the parameter, and the default is "store";

  • default: Indicates that if the value of the parameter is not passed in the command line, the default value is taken;

  • help: Introduction and description of the function of parameters.

Instructions

Some introductions and uses of pytest_addoption have been introduced. Next, follow the editor to see how to use pytest_addoption to solve our problems.

1. It is necessary to create a pytest_addoption function in the conftest.py file and set the corresponding parameter type.

2. Create a function through pytest.fixture to obtain the corresponding parameter value of the command line.

3. Call the corresponding function name by writing the test case.

4. When the command line is executed, add the corresponding command line parameters.

The editor first lists the writing of pytest_addoption in the conftest.py file:


# conftest.py文件
# coding:utf-8
import pytest

def pytest_addoption(parser):
    parser.addoption(
        "--anjing", action="store", default="anjing", help="将'anjing'添加到pytest的配置参数中"
    )
    parser.addoption(
        "--env", action="store", default="dev", help="env:表示命令行参数内容,不填写默认输出default的值内容"
    )
@pytest.fixture()
def anjing(request):
    return request.config.getoption("--anjing")
    
@pytest.fixture()
def env(request):
    return request.config.getoption("--env")

Then write the corresponding test case according to the content in the conftest.py file:

# coding:utf-8
def test_01(anjing):
    if anjing == 'test':
        print('命令行传参成功!')
    else:
        print('命令行取默认值!')

def test_02(env):
    if env == 'test':
        print('传参成功!')
    else:
        print('传参失败!')


When executed through cmd, the corresponding command line parameter values ​​are added later. Here, the editor adds values ​​to both command line parameters, so what happens if no values ​​are added?


It can be seen from the execution results that when we did not add parameters, the editor here forgot to print the return value. In fact, the default value will actually be output, which is the default we set in the function.

The method we used above is to output in the format of XXX=XXX, here we can also use –xxxx value, input with a space between the parameter and the value, the result is the same.


Case presentation

The above editor introduced how to use it, so how do we use it in the interface project? The editor here uses a simple method to display through the project. Here, the editor changes the default value to the url address of the successful request, and adds the parameter to the wrong url address.


# conftest.py文件
# coding:utf-8
import pytest
def pytest_addoption(parser):
    parser.addoption(
        "--url", 
        action="store", 
        default="http://apis.juhe.cn/simpleWeather/query",
        help="将'anjing'添加到pytest的配置参数中"
    )
    
@pytest.fixture()
def anjing(request):
    return request.config.getoption("--url")

In the conftest.py file, we write the successful address of the default request into the default value, then continue to write the interface request address, and add a command line parameter function.

# test_01.py文件
# coding:utf-8
import requests
def test_01(anjing):
    data = {
        'city': "上海",
        'key': '331eab8f3481f37868378fcdc76cb7cd'
    }
    r = requests.post(anjing, data=data)
    result = r.json()['reason']
    assert result == '查询成功!'

To run the program through cmd, we do not add any command line parameters first, let it request the content of the default parameter value, and find that the test case request is successful.


Next, we simulate the request by randomly following the command line parameters with an incorrect url address. The request cannot be successful here, because the Baidu we requested cannot make the request successfully (mainly simulating the test environment scenario).

Summarize

The editor introduces how to use pytest_addoption to simulate different test environments in a simple way, and how we execute our test cases.

Of course, there are not only so many uses of pytest_addoption, how to use it, you can use it according to your company's content projects.

Thank you for reading, I hope this article is helpful to you.

Finally : In order to give back to the die-hard fans, I have compiled a complete software testing video learning tutorial for you. If you need it, you can get it for free【保证100%免费】

Software Testing Interview Documentation

We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Ali, Tencent, and Byte, and some Byte bosses have given authoritative answers. Finish this set The interview materials believe that everyone can find a satisfactory job.

全部资料获取:

insert image description here

Guess you like

Origin blog.csdn.net/weixin_56331124/article/details/131542912