python - python/pytest Selenium 自动化中的全局变量
问题描述
我正在自动化依赖于其他一些测试的测试。
假设我有测试设置、testA、testB、testC。setUp() 设置启动其他测试所需的服务器或资源。testA、testB、testC 需要等到 setUp 完成,然后才应该并行启动。我的最终目标是并行化测试。我在没有任何并行执行的情况下成功按顺序执行测试,因此 setUp -> testA -> testB -> testC 是它们完成的顺序,但实际上 testA、testB、testC 可以并行运行,因此按顺序运行它们是浪费时间。
这是我的项目的结构:
test_dummy.py
class Values:
can_continue = False ## This holds the boolean value which I am using for other functions to check if they can continue with their test
class SetUp:
def test_dummy_setUp():
## All the code to setUp the environment
##Once above code is done then set the can_continue to true
Values.can_continue = True
class TestA:
def test_methodA():
while Values.can_continue is False:
sleep(10)
## When the can_continue is changed to True by setUp I want it to break out of loop and continue with execution
## Code to be executed
class TestB:
def test_methodB():
while Values.can_continue is False:
sleep(10)
## When the can_continue is changed to True by setUp I want it to break out of loop and continue with execution
## Code to be executed
当我使用 pytest 在并行执行中使用 3 个内核运行 test_dummy 时,为每个类打开 3 个浏览器(我使用 Seleniumbase 并使用 --distload),并且正如预期的那样,setUp 继续创建资源,而其他两个看到 can_continue 最初是 False 他们去睡觉。当 setUp 完成创建资源时,即使在 setUp 中将 can_continue 设置为 True,看起来该更新也没有反映到其他两个方法,并且它们永远处于休眠状态。我可以理解,这可能是因为每个测试类在启动时都创建了一个新对象,并且没有反映更改,或者这可能根本不是正确的方法。我是 Python 新手,现在的范围让我很困惑。
我的最终目标是拥有一个可供所有三个类 SetUp、TestA、TestB 访问的变量,并且任何类所做的更改也必须立即对其他类可见。在 python 中实现这一目标的最佳方法是什么?
谢谢
解决方案
看来您需要使用 pytest 固定装置。在夹具中设置测试,然后将夹具传递给测试。夹具将在测试之前执行。
代码看起来像这样:
@pytest.fixture
def setup():
#setup everything here.
def test_methodA(setup):
## Code to be executed
def test_methodB(setup):
## Code to be executed
编辑:更新了代码以简化它。您不需要添加锁定变量并继续检查它。而且,如果您使用 pytest-xdist 并行化测试,这会很好。我不知道 SeleniumHub 如何并行化测试。
推荐阅读
- python - 将函数应用于基于列的数据帧以及基于索引的其他数据帧
- javascript - 对本机反应的 RTL 支持
- react-native - 在另一个 React-Native 库中使用 React-Native 库
- ios - Swift-可重用的框架在更高版本的 xcode 中不起作用
- python - Python List Comprehensions, sublist row and column
- rest - 添加 RGW 实例时 Ceph 状态 HEALTH_WARN
- javascript - 锚元素上的下载属性在 Firefox 上不起作用
- http - @ 字符在 HTTP 地址路径中是否常见?我们可以在 HTTP 地址路径中使用它吗?
- c++ - “+=”运算符到底是做什么的?
- python - 如果系列的值包含熊猫中的一组特定字符,则替换后续字符