用pytest写一个多线程执行selenium的用例
时间: 2023-10-21 22:03:45 浏览: 46
当使用 pytest 运行多线程的 Selenium 用例时,可以使用 `pytest-xdist` 插件来实现。下面是一个示例代码:
首先,确保已经安装了 `pytest` 和 `pytest-xdist` 插件:
```
pip install pytest pytest-xdist
```
然后,创建一个名为 `test_selenium.py` 的文件,编写多线程执行 Selenium 用例的代码:
```python
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
# 使用 pytest 的参数化装饰器,定义多个测试数据
@pytest.mark.parametrize("username, password", [("user1", "pass1"), ("user2", "pass2")])
def test_login(username, password):
# 创建 WebDriver 对象
driver = webdriver.Chrome()
# 执行登录操作
driver.get("https://example.com/login")
driver.find_element(By.ID, "username").send_keys(username)
driver.find_element(By.ID, "password").send_keys(password)
driver.find_element(By.ID, "login-button").click()
# 断言登录成功
assert "Welcome" in driver.page_source
# 关闭浏览器窗口
driver.quit()
# 使用 pytest 的并发插件,指定线程数为2
@pytest.mark.parametrize("n", [2])
def test_concurrent(n):
pytest.xdist.plugin.pytest_configure(config=None)
pytest.xdist.plugin.__dict__["workerinput"] = lambda: iter(range(n))
```
在上述代码中,`test_login` 函数使用 `@pytest.mark.parametrize` 装饰器定义了多个测试数据,每个数据代表一个线程执行的用例。在每个用例中,使用 Selenium 进行登录操作,并断言登录成功。
`test_concurrent` 函数使用 `@pytest.mark.parametrize` 装饰器定义了线程数为 2,这里可以根据需要设置多个线程数。
最后,通过运行以下命令来执行多线程的 Selenium 用例:
```
pytest -n 2 test_selenium.py
```
其中 `-n 2` 表示使用 2 个线程来执行用例。你可以根据需要设置不同的线程数。
注意:多线程执行 Selenium 用例时,需要注意每个线程使用独立的 WebDriver 对象,并在每个用例执行完毕后关闭 WebDriver 对象,以免资源泄露。