Decrypt *args and **kwargs functions in Python

In Python programming, *args and **kwargs are two commonly used function parameter forms. They provide flexibility and extensibility, allowing functions to handle an indefinite number of parameters. This article will explain in detail the concepts and usage of *args and **kwargs as well as sample code in actual interface automation work.

Use of *args

*args is a special parameter that accepts any number of positional parameters.

When defining a function, you can use *args as the parameter name, which will pack the incoming positional parameters into a tuple.

These positional parameters can be accessed inside the function by iterating over the tuple or using indexing.

Sample code:

def print_args(*args):
    for arg in args:
        print(arg)
print_args("Hello", "World", 2022)  # 输出:Hello World 2022

**kwargs usage

**kwargs is a special parameter that accepts any number of keyword arguments.

When defining a function, you can use **kwargs as the parameter name, which will pack the incoming keyword parameters into a dictionary.

These keyword arguments can be accessed via dictionary key-value pairs inside the function.

Sample code:

def print_kwargs(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
print_kwargs(name="Alice", age=25)  # 输出:name: Alice, age: 25

Combination use of *args and **kwargs

*args and **kwargs can be used simultaneously in a function definition, allowing any number of positional and keyword arguments to be accepted.

When a function is called, positional parameters and keyword parameters can be passed at the same time.

Sample code:

def print_args_kwargs(*args, **kwargs):
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(f"{key}: {value}")
print_args_kwargs("Hello", "World", name="Alice", age=25)
# 输出:
# Hello
# World
# name: Alice
# age: 25

In actual interface automation work, *args and **kwargs also have many application scenarios. For example, when writing a general request function, you can use *args and **kwargs to accept parameters from different interfaces to implement flexible requests.

Sample code:

import requests
def send_request(url, method="GET", *args, **kwargs):
    if method == "GET":
        response = requests.get(url, *args, **kwargs)
    elif method == "POST":
        response = requests.post(url, *args, **kwargs)
    else:
        raise ValueError("Unsupported method")
    return response
# 调用send_request函数,发送不同类型的请求
response1 = send_request("https://api.example.com/data", params={"id": 1})
response2 = send_request("https://api.example.com/data", method="POST", json={"name": "Alice"})

When performing automated interface testing, *args and **kwargs can be used in the following areas:

Parameterization when sending a request:

In interface testing, it is often necessary to pass different request parameters, such as request headers, query parameters, request bodies, etc. Use *args and **kwargs to easily achieve dynamic transfer of parameters. For example:

import requests
def send_request(url, method="GET", *args, **kwargs):
    response = requests.request(method, url, *args, **kwargs)
    return response
# 调用send_request函数,发送带有请求头和查询参数的GET请求
response = send_request("https://api.example.com/data", headers={"Authorization": "Bearer xxx"}, params={"page": 1})

Flexibility in assertion results

In interface automated testing, assertions need to be made on the results returned by the interface. Use *args and **kwargs to achieve flexible assertions on the returned results. For example:

def assert_response(response, expected_status_code=200, *args, **kwargs):
    assert response.status_code == expected_status_code, "Invalid status code"
    # 其他断言逻辑...
# 调用assert_response函数,对接口返回结果进行断言
assert_response(response, expected_status_code=200, headers={"Content-Type": "application/json"})

Dynamically generate test data

In interface automation testing, sometimes it is necessary to dynamically generate test data, such as generating random user names, passwords, etc. Use *args and **kwargs to conveniently pass these dynamically generated test data. For example:

def generate_user_data(*args, **kwargs):
    # 生成用户名、密码等测试数据
    username = generate_random_username()
    password = generate_random_password()
    # 其他测试数据生成逻辑...
    return username, password
# 调用generate_user_data函数,获取动态生成的测试数据
username, password = generate_user_data()

Packaging test steps:

In interface automated testing, it is sometimes necessary to encapsulate a series of test steps. Using *args and **kwargs can easily pass different test parameters. For example:

def login_and_assert_response(url, username, password, expected_status_code=200, *args, **kwargs):
    # 登录步骤
    login_response = send_login_request(url, username, password)
    assert_response(login_response, expected_status_code=200)
    # 其他测试步骤...
# 调用login_and_assert_response函数,执行登录并断言响应结果
login_and_assert_response("https://api.example.com/login", username="admin", password="password", expected_status_code=200)

Through the above examples, we can see the flexible use of *args and **kwargs in interface automation testing. They can help us implement functions such as parameterization, flexible assertions, dynamically generated data, and encapsulated test steps, improving the maintainability and scalability of test code.

Finally: The complete software testing video tutorial below has been compiled and uploaded. Friends who need it can get it by themselves [guaranteed 100% free]

Software Testing Interview Document

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 Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.

Guess you like

Origin blog.csdn.net/wx17343624830/article/details/132993131