appium基于PO多设备并发自动化框架部分代码解析

目录

一、common->app_info.py

exec_cmd()解析:

get_app_name()解析:

1. os.walk()解析

2. file.endswith(".apk")

3.get_app_launchable_activity()

unistall_app()解析:

get_all_devices()解析:

二、common -> appium_auto_server.py

os.popen()` 和 `subprocess.popen()区别

三、common -> utils.py

四、common -> base_driver.py

五、test_case ->conftest.py

1. pytest_addoption()解析

2. cmdopt()解析

3. device()解析

eval()用法:

4. pytest_itemcollected()解析

六、main.py


一、common->app_info.py

# _*_coding:utf-8 _*_
# @File    :app_info.py
# @Software  :PyCharm
import logging
import os
from common.all_path import appPath


def exec_cmd(cmd) -> str:
    result = os.popen(cmd).read()
    return result


def get_app_name(file_dir) -> str:
    for root, dirs, files in os.walk(file_dir):
        files = [file for file in files if file.endswith(".apk")]
        if len(files) == 1:
            return files[0]
        else:
            raise FileNotFoundError("{}目录下没有测试包或者存在多个测试包。。".format(file_dir))


def get_app_package_name() -> str:
    cmd = "aapt dump badging {} | findstr package".format(os.path.join(appPath, get_app_name(appPath)))
    result = exec_cmd(cmd)
    if "package" in result:
        package_name = result.strip().split(" ")[1].split('=')[1]
        return package_name
    else:
        raise NameError("未获取到package name。")


def get_app_launchable_activity() -> str:
    cmd = "aapt dump badging {} | findstr launchable".format(os.path.join(appPath, get_app_name(appPath)))
    result = exec_cmd(cmd)
    # logging.info(result)
    # launchable-activity: name='com.zxxk.page.main.LauncherActivity'  label='' icon=''
    if "launchable" in result:
        # launchable_parts = result.strip().split(" ")[2].split('=')
        launchable_parts = result.strip().split(" ")[1].split('=')  # 上面指令运行时,获取不到activity,把[2]改为[1]后可运行
        logging.info(launchable_parts)
        # ['name', "'com.zxxk.page.main.LauncherActivity'"]
        if len(launchable_parts) > 1:
            launchable_activity = launchable_parts[1].replace("label", '')
            return launchable_activity
        else:
            raise NameError("未获取到launchable activity。")
            # print("无法获取可启动活动")
            # return ""
    else:
        raise NameError("未找到可启动活动")
        # print("未找到可启动活动")
        # return ""
    # if "launchable" in result:
    #     launchable_activity = result.strip().split(" ")[2].split('=')[1].replace("label", '')
    #     return launchable_activity
    # else:
    #     raise NameError("未获取到launchable activity。")


def get_devices_version(device: str) -> str:
    if not isinstance(device, str):
        raise Exception("device type is should str..")
    result = exec_cmd("adb -s {} shell getprop ro.build.version.release".format(device))
    result = result.strip()
    if "error" not in result:
        return result
    else:
        raise Exception("获取设备系统版本失败,无法进行正常测试。。")


def get_all_devices() -> list:
    result = exec_cmd('adb devices')
    result = result.strip().split(" ")[3].replace("\n", '').replace("\t", ''). \
        replace("attached", '').split('device')
    result.remove('')
    if len(result) == 0:
        raise Exception("电脑未连接设备信息,无法进行正常测试。。")

    return result


def get_device_infos():
    device_infos = []
    devices = get_all_devices()
    for i in range(len(devices)):
        device_dict = {"platform_version": get_devices_version(devices[i]), "server_port": 4723 + i * 2,
                       "system_port": 8200 + i * 1, "device": devices[i]}
        device_infos.append(device_dict)

    if len(device_infos) < 1:
        raise Exception("当前电脑未连接设备信息。。。")

    return device_infos


def uninstall_app(device_list: list) -> None:
    if not isinstance(device_list, list):
        raise Exception("device_list is should list!")

    for device_info in device_list:
        cmd = 'adb -s 127.0.0.1:{} uninstall "{}"'.format(device_info.get("device").split(':')[-1],
                                                          str(get_app_package_name())).replace("'", '')
        logging.info("开始卸载设备上应用:{}".format(cmd))
        exec_cmd(cmd)

exec_cmd()解析:

# 导入os模块,用于执行系统命令
import os

# 定义一个名为exec_cmd的函数,接受一个参数cmd,返回值类型为str
def exec_cmd(cmd) -> str:
    # 使用os.popen()函数执行传入的命令,并将结果存储在result变量中
    result = os.popen(cmd).read()
    # 返回命令执行的结果
    return result

通过加了logging查看运行结果

def exec_cmd(cmd) -> str:
    result = os.popen(cmd).read()
    logging.info(str(result))
    return result

运行结果:(不同的cmd指令,打印结果不同)

解析: 这段Python代码定义了一个名为exec_cmd的函数,该函数接受一个参数cmd,返回值类型为字符串。函数的主要功能是执行传入的命令,并返回命令执行的结果。

os.popen() 是 Python 中用于执行系统命令的函数。它允许你在 Python 程序中运行外部命令,并获取命令的输出结果。

注意:os.popen() 返回的是一个文件对象,你可以通过调用其 read() 方法来读取命令的输出结果。

get_app_name()解析:

# 定义一个函数get_app_name,接收一个参数file_dir,返回值类型为字符串
def get_app_name(file_dir) -> str:
    # 使用os.walk遍历file_dir目录下的所有文件和文件夹
    for root, dirs, files in os.walk(file_dir):
        # 筛选出所有以".apk"结尾的文件
        files = [file for file in files if file.endswith(".apk")]
        # 如果筛选出的文件只有一个
        if len(files) == 1:
            # 返回该文件名
            return files[0]
        # 如果筛选出的文件有多个或者没有文件
        else:
            # 抛出FileNotFoundError异常,提示用户目录下没有测试包或者存在多个测试包
            raise FileNotFoundError("{}目录下没有测试包或者存在多个测试包。。".format(file_dir))
for root, dirs, files in os.walk(file_dir)

1. os.walk()解析

解释说明: os.walk()是Python标准库中的一个函数,用于遍历目录树。它返回一个生成器,每次迭代都会返回一个三元组,包含当前目录的路径、当前目录下的所有子目录名称和当前目录下的所有文件名称。这个函数非常有用,可以用于批量处理文件和文件夹

示例:

test_000.py

import os

for root, dirs, files in os.walk("."):
    print(f"当前目录:{root}")
    print(f"子目录:{dirs}")
    print(f"文件:{files}")
    print("--------------------")

上述代码会遍历当前目录及其所有子目录,并打印出每个目录的路径、子目录名称和文件名称。

运行结果:

文件目录:

注意事项:
- `os.walk()`函数默认遍历的是当前目录及其所有子目录,可以通过传入不同的路径参数来遍历其他目录。
- 在遍历过程中,需要注意处理可能存在的文件和文件夹权限问题,确保程序能够正常访问和操作这些文件和文件夹。
- 如果需要对文件进行读写操作,可以使用`os.path.join()`函数来拼接路径,以确保在不同操作系统下都能正确工作。

2. file.endswith(".apk")

files = [file for file in files if file.endswith(".apk")]

解释说明:
这段代码是使用列表推导式(List Comprehension)来筛选出以".apk"为后缀的文件名,并将这些文件名存储在名为`files`的列表中

假设有一个包含多个文件名的列表`files`,其中包含了不同类型的文件,例如图片、文档等。我们想要筛选出所有以".apk"为后缀的文件名,可以使用以上代码。

执行完代码后,`files`列表将只包含以".apk"为后缀的文件名。

注意事项:
- 在使用这段代码之前,需要确保变量`files`已经定义并赋值为一个包含文件名的列表。
- `file.endswith(".apk")`是一个字符串方法,用于判断文件名是否以指定的后缀结尾。如果文件名以".apk"结尾,则返回True,否则返回False。
- 列表推导式是一种简洁的创建列表的方式,它通过迭代一个可迭代对象(如列表、元组等),并根据条件对每个元素进行操作,最终生成一个新的列表。

3.get_app_launchable_activity()

使用replace()函数去除这个元素("label", '')

中的 result 及 launchable_parts 打印结果如下:

unistall_app()解析:

def uninstall_app(device_list: list) -> None:
    # 检查输入参数是否为列表类型,如果不是则抛出异常
    if not isinstance(device_list, list):
        raise Exception("device_list is should list!")

    # 遍历设备列表
    for device_info in device_list:
        # 获取设备的IP地址和端口号
        device_ip = device_info.get("device").split(':')[-1]
        # 获取应用的包名
        app_package_name = str(get_app_package_name())
        # 构造卸载命令
        cmd = 'adb -s {} uninstall "{}"'.format(device_ip, app_package_name).replace("'", '')
        # 记录日志
        logging.info("开始卸载设备上应用:{}".format(cmd))
        # 执行卸载命令
        exec_cmd(cmd)

device_ip = device_info.get("device").split(':')[-1]

- 从设备信息中获取键为"device"的值,并使用冒号作为分隔符进行分割。取分割后的最后一个元素作为设备的IP地址,并将其赋值给变量device_ip。


get_all_devices()解析:

common->app_info.py -> get_all_devices()

def get_all_devices() -> list:
    result = exec_cmd('adb devices')
    result = result.strip().split(" ")[3].replace("\n", '').replace("\t", ''). \
        replace("attached", '').split('device')
    result.remove('')
    if len(result) == 0:
        raise Exception("电脑未连接设备信息,无法进行正常测试。。")

    return result

解析:这段Python代码的主要功能是执行一个ADB命令('adb devices'),获取设备列表,然后对结果进行处理。

 这段Python代码的主要功能是对字符串进行处理。首先,它使用strip()函数去除字符串两端的空白字符。然后,它使用split(" ")函数将字符串按空格分割成一个列表。接着,它从这个列表中取出第4个元素(索引为3)。然后,它使用replace()函数去除这个元素的换行符和制表符,以及"attached"这个词。最后,它再次使用split('device')函数将处理后的字符串按'device'分割成一个新的列表。

具体步骤如下:

# 执行ADB命令,获取设备列表
result = exec_cmd('adb devices')

# 去除结果字符串的首尾空格
result = result.strip()

# 将结果字符串按空格分割成一个列表
result = result.split(" ")

# 获取列表中的第四个元素,即设备ID
result = result[3]

# 去除设备ID中的换行符和制表符
result = result.replace("
", '').replace("\t", '')

# 去除设备ID中的"attached"字符串
result = result.replace("attached", '')

# 将设备ID按"device"分割成一个列表
result = result.split('device')

# 去除列表中的空字符串
result.remove('')

1. 使用`exec_cmd('adb devices')`执行ADB命令,获取设备列表。这个函数可能是自定义的,用于执行系统命令并返回结果。
2. 使用`strip()`方法去除结果字符串的首尾空格。
3. 使用`split(" ")`方法将结果字符串按空格分割成一个列表。
4. 使用索引`[3]`获取列表中的第四个元素,即设备ID。
5. 使用`replace(" ", '')`和`replace("\t", '')`方法去除设备ID中的换行符和制表符。
6. 使用`replace("attached", '')`方法去除设备ID中的"attached"字符串。
7. 使用`split('device')`方法将设备ID按"device"分割成一个列表。
8. 使用`remove('')`方法去除列表中的空字符串。


二、common -> appium_auto_server.py

common -> appium_auto_server.py ->open_appium()

def open_appium(cmd, port):
    """
    function : 命令启动appium server
    :param cmd: appium server 启动命令
    :param port: appium server 启动端口
    :return: None
    """
    release_port(port)
    subprocess.Popen(cmd, shell=True, stdout=open(logPath+"/"+str(port)+'.log', "a"), stderr=subprocess.STDOUT)

- 使用subprocess.Popen()函数创建一个子进程,执行cmd命令
- shell=True表示在shell中运行命令,而不是在一个新的进程中运行
- stdout=open(logPath+"/"+str(port)+'.log', "a")表示将子进程的标准输出重定向到一个名为logPath/port.log的文件中,以追加模式打开
- stderr=subprocess.STDOUT表示将子进程的标准错误输出重定向到标准输出流,即与标准输出合并


os.popen()` 和 `subprocess.popen()区别

os.popen()` 和 `subprocess.popen()` 都可以在 Python 中执行系统命令,但它们之间存在一些主要的区别。

首先,`os.popen()` 通过创建管道并 fork 一个子进程来执行命令,返回值是通过标准 I/O 流获取的,这个管道被用于父子进程间的通信。另一方面,`subprocess.popen()` 也创建一个管道和一个子进程来执行命令,但它提供了更多功能,比如能够获取命令的输出和错误信息,而且能够等待命令完成并获取其返回码。

此外,需要注意的是,使用 `os.system()` 函数执行命令时,会直接在控制台打印出命令的执行结果,而结果无法读取保存到文件或变量中。相对地,`os.popen()` 执行后不会在控制台打印输出,而是可以通过调用 `read()` 方法来读取结果。

总的来说,`subprocess.popen()` 在功能上比 `os.popen()` 更加强大和灵活,可以更好地满足复杂程序的需求。然而,如果你只需要简单地执行命令并获取输出结果,那么 `os.popen()` 或许就足够了。


三、common -> utils.py

定义一个函数,用于从给定的数据中提取符合正则表达式路径的内容

# 导入正则表达式模块
import re
# 导入日志记录模块
import logging

# 定义一个函数,用于从给定的数据中提取符合正则表达式路径的内容
def re_extract(data, rePath):
    try:
        # 使用re.findall方法查找符合正则表达式路径的所有内容,并返回结果列表
        return re.findall(rePath, data)
    except Exception as e:
        # 如果发生异常,使用日志记录器记录异常信息,并输出错误提示
        logging.exception("提取执行失败!{}".format(e))
    # 如果发生异常或未找到匹配项,返回None
    return None

四、common -> base_driver.py

common -> base_driver.py ->base_driver()

fp = open(f"{configPath}//caps.yml", encoding='utf-8')


# 使用open函数打开一个文件,参数分别为文件路径和打开模式
# 文件路径由变量configPath指定,并拼接上"//caps.yml"得到完整的文件路径


common -> base_driver.py

# _*_coding:utf-8 _*_
# @File    :base_driver.py
# @Software  :PyCharm
from appium import webdriver
from common.all_path import configPath, appPath
import yaml
import os

from common.app_info import get_devices_version, get_app_name, get_app_launchable_activity, get_app_package_name

from common.appium_auto_server import open_appium


class BaseDriver:

    def __init__(self, device_info):
        self.device_info = device_info
        cmd = "start /b appium -a 127.0.0.1 -p {0} -bp {1}".format(self.device_info["server_port"],
                                                                   self.device_info["server_port"] + 1)
        open_appium(cmd, self.device_info["server_port"])

    def base_driver(self, automationName="appium"):
        fp = open(f"{configPath}//caps.yml", encoding='utf-8')
        # 平台名称、包名、Activity名称、超时时间、是否重置、server_ip、
        desired_caps = yaml.load(fp, Loader=yaml.FullLoader)

        # 设备名称
        desired_caps["deviceName"] = self.device_info['device']

        # 版本信息
        desired_caps["platform_version"] = get_devices_version(desired_caps["deviceName"])

        app_path = os.path.join(appPath, get_app_name(appPath))
        desired_caps['app'] = app_path

        desired_caps['appPackage'] = get_app_package_name()

        desired_caps['appActivity'] = get_app_launchable_activity()

        # udid
        desired_caps["udid"] = self.device_info['device']
        # 系统端口号
        desired_caps["systemPort"] = self.device_info["system_port"]

        if automationName != "appium":
            desired_caps["automationName"] = automationName

        driver = webdriver.Remote(f"http://127.0.0.1:{self.device_info['server_port']}/wd/hub",
                                  desired_capabilities=desired_caps)
        return driver

五、test_case ->conftest.py

通过“在命令行中输入参数,然后用例中接收这个参数,通过判断这个参数的值来做不同的逻辑”来实现。那么我们的需求就变为pytest中如何自定义一个命令行参数呢?这时候我们就需要用到pytest的钩子函数:pytest_addoption

通过conftest.py配置
  新建一个conftest.py文件,然后在conftest.py文件中通过pytest_addoption方法来添加命令行参数,通过定义的fixture来获得参数的值。 

# _*_coding:utf-8 _*_
# @File    :conftest.py
# @Software  :PyCharm

from common.base_driver import BaseDriver
import pytest
import random

from pageViwe.loginPage import LoginPage

driver = None


def pytest_addoption(parser):
    # 注册自定义参数cmdopt到配置对象
    parser.addoption("--cmdopt", action="store", default="device_info", help=None)


@pytest.fixture(scope='session')
def cmdopt(pytestconfig):
    # 两种写法
    # 从配置对象获取cmdopt的值
    return pytestconfig.getoption("--cmdopt")
    # return pytestconfig.option.cmdopt


# 定义公共的fixture
@pytest.fixture(scope='session')
def common_driver(cmdopt):
    global driver
    base_driver = BaseDriver(eval(cmdopt))
    driver = base_driver.base_driver()
    lg = LoginPage(driver)
    yield lg
    driver.close_app()
    driver.quit()


@pytest.fixture
def device(cmdopt):
    yield eval(cmdopt)


def pytest_itemcollected(item):
    item._nodeid = str(random.randint(1, 1000)) + '_' + item . _nodeid

1. pytest_addoption()解析

testcase -> conftest.py ->pytest_addoption()


# 定义一个名为pytest_addoption的函数,该函数接受一个参数parser
def pytest_addoption(parser):
    # 注册自定义参数cmdopt到配置对象
    # 使用parser的addoption方法添加一个命令行选项--cmdopt
    # action="store"表示这个选项的动作是存储,即需要用户提供一个值
    # default="device_info"表示如果没有提供这个选项的值,那么它的默认值是device_info
    parser.addoption("--cmdopt", action="store", default="device_info", help=None)

解析:
通过pytest_addoption方法来添加命令行参数。在函数体中,使用`parser.addoption`方法添加了一个命令行选项`--cmdopt`。这个选项的动作是存储(store),如果没有提供这个选项的值,那么它的默认值是`device_info`。`help=None`表示这个选项没有帮助信息。

parser函数通常用于解析命令行参数。parser函数的主要作用是将输入的命令行参数转换为一个对象,然后可以对这个对象进行进一步的处理和操作。

pytest_addoption用法 动态添加命令行参数 (钩子函数)


2. cmdopt()解析

testcase -> conftest.py -> cmdopt()

代码及注释:


# 定义一个名为cmdopt的函数,接收一个参数pytestconfig
def cmdopt(pytestconfig):
    # 从配置对象获取cmdopt的值
    # 调用pytestconfig对象的getoption方法,传入字符串"--cmdopt"作为参数
    result = pytestconfig.getoption("--cmdopt")
    # 返回getoption方法的结果
    return result

解析:
这段Python代码定义了一个名为`cmdopt`的函数,该函数接收一个参数`pytestconfig`。

函数的主要功能是调用`pytestconfig`对象的`getoption`方法,并传入字符串"--cmdopt"作为参数,然后返回该方法的结果。

pytestconfig.getoption("--cmdopt") 是 pytest-python 库中的一个函数,用于获取命令行选项的值。

参数`pytestconfig` 解释说明:
`pytestconfig` 函数是 pytest 测试框架中的一个内置函数,用于获取当前运行的测试用例的配置信息。它返回一个 `Config` 对象,该对象包含了测试用例的配置信息,如插件、命令行选项等。通过这个函数,我们可以在测试用例中方便地访问这些配置信息。

实例:

python
import pytest

def test_example(pytestconfig):
    # 获取插件列表
    plugins = pytestconfig.getoption("plugins")
    print("插件列表:", plugins)

    # 获取命令行选项
    command_line_options = pytestconfig.getoption("command-line-options")
    print("命令行选项:", command_line_options)

在这个示例中,我们定义了一个名为 `test_example` 的测试函数,并传入了 `pytestconfig` 参数。然后,我们使用 `pytestconfig.getoption()` 方法分别获取了插件列表和命令行选项,并将它们打印出来。

注意事项:
- `pytestconfig` 函数只能在测试函数中使用,不能在普通的 Python 模块或脚本中使用。
- `pytestconfig` 函数返回的 `Config` 对象具有一些常用的属性和方法,如 `getini()`(获取 INI 格式的配置信息)、`getoption()`(获取命令行选项)等。更多详细信息可以参考官方文档:https://docs.pytest.org/en/latest/reference.html#_pytest.main.Config


3. device()解析

def device(cmdopt):
    yield eval(cmdopt)

解释说明: def device(cmdopt): 是一个Python函数定义,函数名为 device,接受一个参数 cmdopt。函数内部使用了生成器(generator)的语法,通过 yield 关键字返回一个值。生成器是一种特殊的迭代器,可以在函数中使用 yield 语句暂停函数的执行,并在下一次调用时从暂停的位置继续执行。

eval()用法:

`eval()` 是 Python 中的一个内置函数,用于计算字符串形式的表达式并返回结果。

基本语法如下:

eval(expression, globals=None, locals=None)

参数说明:
- expression:一个字符串形式的表达式,可以是任何有效的 Python 表达式。
- globals:可选参数,表示全局命名空间(变量),如果提供,则必须是一个字典对象。
- locals:可选参数,表示局部命名空间(变量),如果提供,则可以是任何映射对象。

示例:

# 示例1:计算数学表达式
expression = "1 + 2 * 3"
result = eval(expression)
print(result)  # 输出:7

# 示例2:获取字典中的值
my_dict = {"a": 1, "b": 2}
expression = "my_dict['a'] + my_dict['b']"
result = eval(expression)
print(result)  # 输出:3

# 示例3:使用局部变量
def my_function():
    local_var = "Hello"
    expression = "local_var + ' World'"
    result = eval(expression, {"local_var": local_var})
    return result

print(my_function())  # 输出:Hello World

注意事项:
- `eval()` 函数具有强大的计算能力,但同时也存在安全风险,因为它可以执行任意的 Python 代码。因此,在处理不可信的输入时,应避免使用 `eval()`。
- 如果可能的话,尽量使用更安全的方法来计算表达式,例如使用 `ast.literal_eval()`(只解析字面量表达式)或自定义函数来处理特定类型的表达式

4. pytest_itemcollected()解析

testcase -> conftest.py -> pytest_itemcollected()

def pytest_itemcollected(item):
    item._nodeid = str(random.randint(1, 1000)) + '_' + item . _nodeid

解析:
这段Python代码定义了一个名为`pytest_itemcollected`的函数,该函数接收一个参数`item`。在函数体中,首先生成一个1到1000之间的随机整数,然后将这个随机整数转换为字符串,并与`item._nodeid`进行拼接,最后将结果赋值给`item._nodeid`。

# 导入random模块,用于生成随机数
import random

def pytest_itemcollected(item):
    # 生成一个1到1000之间的随机整数
    random_num = random.randint(1, 1000)
    # 将随机整数转换为字符串
    random_str = str(random_num)
    # 获取item的原始_nodeid属性值
    original_nodeid = item._nodeid
    # 将随机字符串与原始_nodeid进行拼接
    new_nodeid = random_str + '_' + original_nodeid
    # 将新的_nodeid属性值赋给item
    item._nodeid = new_nodeid

六、main.py

# _*_coding:utf-8 _*_
# @File    :main.py
# @Software  :PyCharm
from multiprocessing import Pool

import os
import pytest
from common.app_info import get_device_infos, uninstall_app
from common.appium_auto_server import close_appium


def run_parallel(device_info):
    pytest.main([f"--cmdopt={device_info}",
                 "--alluredir", "outputs/reports/data"])
    os.system("allure generate outputs/reports/data -o outputs/reports/html --clean")


if __name__ == "__main__":
    device_lists = get_device_infos()
    uninstall_app(device_lists)
    with Pool(len(device_lists)) as pool:
        pool.map(run_parallel, device_lists)
        pool.close()
        pool.join()

    close_appium()

使用pytest的主函数来运行测试

pytest.main([f"--cmdopt={device_info}", "--alluredir", "outputs/reports/data"])


-  f"--cmdopt={device_info}" 是一个命令行选项,是用来指定设备信息的
- "--alluredir" 是一个命令行选项,用来指定Allure报告的输出目录
- "outputs/reports/data" 是Allure报告的输出目录
 

代码详解:

# 导入所需模块
from multiprocessing import Pool

# 定义主函数入口
if __name__ == "__main__":
    # 获取设备信息列表
    device_lists = get_device_infos()
    
    # 卸载应用
    uninstall_app(device_lists)
    
    # 使用多进程池并行执行任务
    with Pool(len(device_lists)) as pool:
        # 将设备列表传递给并行执行的函数
        pool.map(run_parallel, device_lists)
        
        # 关闭进程池,不再接受新的任务
        pool.close()
        
        # 等待所有进程完成
        pool.join()

`with Pool(len(device_lists)) as pool`是使用`multiprocessing.Pool`类创建进程池的语法。进程池是一种并行处理的方式,可以同时执行多个任务,提高程序的效率。

`Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None)`

是`multiprocessing.Pool`类的构造函数,其中`processes`参数表示进程池中的进程数量,这里设置为`len(device_lists)`,即设备列表的长度。

在上面的示例中,首先定义了一个`run_parallel`函数,用于处理设备的数据。然后,通过`Pool(len(device_lists))`创建一个进程池,进程数量等于设备列表的长度。

最后,使用`pool.map`方法将设备列表中的每个设备传递给`run_parallel`函数进行处理。 

注意事项:
- `Pool()`构造函数中的其他参数可以根据具体需求进行设置,例如`initializer`参数用于指定进程初始化函数,`initargs`参数用于传递初始化函数的参数等。
- `pool.map()`方法会将可迭代对象(如列表)中的每个元素依次传递给指定的函数进行处理,并返回一个结果列表。如果需要对结果进行进一步处理,可以使用`pool.imap()`方法或自定义回调函数。
- 在使用进程池时,需要注意线程安全问题,避免多个进程同时访问共享资源导致数据竞争或死锁等问题。可以通过加锁机制或其他同步手段来解决这个问题。

注意:这里的进程池pool对象定义一定放在main函数下 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Appium自动化测试中的Page Object模式是一种常用的设计模式,用于将页面元素和操作封装在一个类中,以便于测试脚本的编写和维护。在Appium中,可以使用BasePage类来实现一些公共方法和元素定位的实现。\[3\] 在BasePage类中,通过初始化方法将driver对象传入,并设置了一个隐式等待时间为10秒。然后定义了一些常用的元素定位方法,如by_id、by_xpath、by_class_name和by_uiautomator,这些方法可以根据元素的id、xpath、class name和uiautomator来定位元素。\[3\] 在测试脚本中,可以通过继承BasePage类来创建具体的页面类,然后在页面类中定义具体的页面元素和操作方法。通过这种方式,可以将页面元素和操作进行封装,使测试脚本更加清晰和易于维护。\[3\] 例如,可以创建一个ConversationListPage类,继承自BasePage类,然后在该类中定义一些页面元素和操作方法,如点击某个会话、获取会话列表等。这样,在测试脚本中就可以直接调用ConversationListPage类的方法来进行相应的操作。\[2\] #### 引用[.reference_title] - *1* [Appium自动化测试(五)——PO模式(一):短信案例](https://blog.csdn.net/qq_37089829/article/details/119709665)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Appium PO模式UI自动化测试框架——设计与实践](https://blog.csdn.net/weixin_38306507/article/details/127009364)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值